local-commander-agent 0.3.42 → 0.3.44

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
@@ -4541,10 +4541,10 @@ function mergeDefs(...defs) {
4541
4541
  function cloneDef(schema) {
4542
4542
  return mergeDefs(schema._zod.def);
4543
4543
  }
4544
- function getElementAtPath(obj, path28) {
4545
- if (!path28)
4544
+ function getElementAtPath(obj, path29) {
4545
+ if (!path29)
4546
4546
  return obj;
4547
- return path28.reduce((acc, key) => acc?.[key], obj);
4547
+ return path29.reduce((acc, key) => acc?.[key], obj);
4548
4548
  }
4549
4549
  function promiseAllObject(promisesObj) {
4550
4550
  const keys = Object.keys(promisesObj);
@@ -4884,11 +4884,11 @@ function explicitlyAborted(x, startIndex = 0) {
4884
4884
  }
4885
4885
  return false;
4886
4886
  }
4887
- function prefixIssues(path28, issues) {
4887
+ function prefixIssues(path29, issues) {
4888
4888
  return issues.map((iss) => {
4889
4889
  var _a3;
4890
4890
  (_a3 = iss).path ?? (_a3.path = []);
4891
- iss.path.unshift(path28);
4891
+ iss.path.unshift(path29);
4892
4892
  return iss;
4893
4893
  });
4894
4894
  }
@@ -5338,16 +5338,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
5338
5338
  }
5339
5339
  function formatError(error62, mapper = (issue2) => issue2.message) {
5340
5340
  const fieldErrors = { _errors: [] };
5341
- const processError = (error63, path28 = []) => {
5341
+ const processError = (error63, path29 = []) => {
5342
5342
  for (const issue2 of error63.issues) {
5343
5343
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5344
- issue2.errors.map((issues) => processError({ issues }, [...path28, ...issue2.path]));
5344
+ issue2.errors.map((issues) => processError({ issues }, [...path29, ...issue2.path]));
5345
5345
  } else if (issue2.code === "invalid_key") {
5346
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
5346
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
5347
5347
  } else if (issue2.code === "invalid_element") {
5348
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
5348
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
5349
5349
  } else {
5350
- const fullpath = [...path28, ...issue2.path];
5350
+ const fullpath = [...path29, ...issue2.path];
5351
5351
  if (fullpath.length === 0) {
5352
5352
  fieldErrors._errors.push(mapper(issue2));
5353
5353
  } else {
@@ -5386,17 +5386,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
5386
5386
  }
5387
5387
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
5388
5388
  const result2 = { errors: [] };
5389
- const processError = (error63, path28 = []) => {
5389
+ const processError = (error63, path29 = []) => {
5390
5390
  var _a3;
5391
5391
  for (const issue2 of error63.issues) {
5392
5392
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5393
- issue2.errors.map((issues) => processError({ issues }, [...path28, ...issue2.path]));
5393
+ issue2.errors.map((issues) => processError({ issues }, [...path29, ...issue2.path]));
5394
5394
  } else if (issue2.code === "invalid_key") {
5395
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
5395
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
5396
5396
  } else if (issue2.code === "invalid_element") {
5397
- processError({ issues: issue2.issues }, [...path28, ...issue2.path]);
5397
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
5398
5398
  } else {
5399
- const fullpath = [...path28, ...issue2.path];
5399
+ const fullpath = [...path29, ...issue2.path];
5400
5400
  if (fullpath.length === 0) {
5401
5401
  result2.errors.push(mapper(issue2));
5402
5402
  continue;
@@ -5435,8 +5435,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
5435
5435
  }
5436
5436
  function toDotPath(_path) {
5437
5437
  const segs = [];
5438
- const path28 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5439
- for (const seg of path28) {
5438
+ const path29 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5439
+ for (const seg of path29) {
5440
5440
  if (typeof seg === "number")
5441
5441
  segs.push(`[${seg}]`);
5442
5442
  else if (typeof seg === "symbol")
@@ -16905,9 +16905,9 @@ function codePointLengthVar(doc, ctx, accessor, inDoubt) {
16905
16905
  doc.write(`const ${v} = typeof ${accessor} === "string" && ${inDoubt} ? ${cpLen}(${accessor}) : ${accessor}.length;`);
16906
16906
  return v;
16907
16907
  }
16908
- function numericOperand(value, label) {
16908
+ function numericOperand(value, label2) {
16909
16909
  if (typeof value !== "number" || !Number.isFinite(value)) {
16910
- throw new ZodCompileUnsupportedError(`${label} bound of type ${typeof value}`);
16910
+ throw new ZodCompileUnsupportedError(`${label2} bound of type ${typeof value}`);
16911
16911
  }
16912
16912
  return `${value}`;
16913
16913
  }
@@ -22538,13 +22538,13 @@ function resolveRef(ref, ctx) {
22538
22538
  if (!ref.startsWith("#")) {
22539
22539
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
22540
22540
  }
22541
- const path28 = ref.slice(1).split("/").filter(Boolean);
22542
- if (path28.length === 0) {
22541
+ const path29 = ref.slice(1).split("/").filter(Boolean);
22542
+ if (path29.length === 0) {
22543
22543
  return ctx.rootSchema;
22544
22544
  }
22545
22545
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
22546
- if (path28[0] === defsKey) {
22547
- const key = path28[1] === void 0 ? void 0 : decodeJSONPointerSegment(path28[1]);
22546
+ if (path29[0] === defsKey) {
22547
+ const key = path29[1] === void 0 ? void 0 : decodeJSONPointerSegment(path29[1]);
22548
22548
  if (!key || !ctx.defs[key]) {
22549
22549
  throw new Error(`Reference not found: ${ref}`);
22550
22550
  }
@@ -23934,9 +23934,9 @@ function encode4(input2) {
23934
23934
  }
23935
23935
 
23936
23936
  // ../../node_modules/jose/dist/webapi/lib/validate.js
23937
- function assertUint8Array(input2, label) {
23937
+ function assertUint8Array(input2, label2) {
23938
23938
  if (!(input2 instanceof Uint8Array))
23939
- throw new TypeError(`${label} must be an instance of Uint8Array`);
23939
+ throw new TypeError(`${label2} must be an instance of Uint8Array`);
23940
23940
  }
23941
23941
  function isObject2(input2) {
23942
23942
  if (typeof input2 != "object" || input2 === null || Object.prototype.toString.call(input2) !== "[object Object]")
@@ -23959,18 +23959,18 @@ function assertNotSet(value, name2) {
23959
23959
  if (value !== void 0)
23960
23960
  throw new TypeError(`${name2} can only be called once`);
23961
23961
  }
23962
- function decodeBase64url(value, label, ErrorClass) {
23962
+ function decodeBase64url(value, label2, ErrorClass) {
23963
23963
  try {
23964
23964
  return decode3(value);
23965
23965
  } catch {
23966
- throw new ErrorClass(`Failed to base64url decode the ${label}`);
23966
+ throw new ErrorClass(`Failed to base64url decode the ${label2}`);
23967
23967
  }
23968
23968
  }
23969
- function encodeBase64url(value, label, ErrorClass) {
23969
+ function encodeBase64url(value, label2, ErrorClass) {
23970
23970
  try {
23971
23971
  return encode3(value);
23972
23972
  } catch {
23973
- throw new ErrorClass(`The ${label} is not a valid base64url string`);
23973
+ throw new ErrorClass(`The ${label2} is not a valid base64url string`);
23974
23974
  }
23975
23975
  }
23976
23976
  function parseJoseHeader(b64, ErrorClass, message2) {
@@ -24323,9 +24323,9 @@ function secs(str) {
24323
24323
  const value = parseFloat(matched[2]), numericDate2 = Math.round(value * multipliers[matched[3][0].toLowerCase()]);
24324
24324
  return Number.isFinite(numericDate2) || invalidDuration(), matched[1] === "-" || matched[4] === "ago" ? -numericDate2 : numericDate2;
24325
24325
  }
24326
- function validateInput(label, input2) {
24326
+ function validateInput(label2, input2) {
24327
24327
  if (!Number.isFinite(input2))
24328
- throw new TypeError(`Invalid ${label} input`);
24328
+ throw new TypeError(`Invalid ${label2} input`);
24329
24329
  return input2;
24330
24330
  }
24331
24331
  var normalizeTyp = (value) => {
@@ -25164,7 +25164,7 @@ async function openNetworkPanel(binaryDirectory, identity) {
25164
25164
  }
25165
25165
 
25166
25166
  // agent/src/main.ts
25167
- import path27 from "node:path";
25167
+ import path28 from "node:path";
25168
25168
  import os7 from "node:os";
25169
25169
 
25170
25170
  // agent/src/posix-store.ts
@@ -25583,7 +25583,7 @@ async function acquirePosixJournalGuard(directory, helper) {
25583
25583
  }
25584
25584
 
25585
25585
  // agent/src/main.ts
25586
- import { mkdir as mkdir14, open as open13, readFile as readFile10, realpath as realpath10, rm as rm9 } from "node:fs/promises";
25586
+ import { mkdir as mkdir14, open as open13, readFile as readFile11, realpath as realpath10, rm as rm9 } from "node:fs/promises";
25587
25587
  import { fileURLToPath } from "node:url";
25588
25588
 
25589
25589
  // packages/operations/src/crypto.ts
@@ -25629,8 +25629,129 @@ var SecretBox = class {
25629
25629
 
25630
25630
  // agent/src/journal.ts
25631
25631
  import { constants as constants2 } from "node:fs";
25632
- import { lstat as lstat2, mkdir as mkdir3, open as open3, readdir as readdir2, readFile as readFile2, realpath as realpath2, rename, rm as rm2 } from "node:fs/promises";
25633
- import path5 from "node:path";
25632
+
25633
+ // agent/src/linux-containment.ts
25634
+ import { execFile } from "node:child_process";
25635
+ import { readFile as readFile2, statfs } from "node:fs/promises";
25636
+ import path4 from "node:path";
25637
+ import { promisify } from "node:util";
25638
+ import { setTimeout as delay } from "node:timers/promises";
25639
+ var uuid5 = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
25640
+ var unitName = new RegExp("^lc-command-" + uuid5 + "\\.service$");
25641
+ var bootId = new RegExp("^" + uuid5 + "$");
25642
+ function validLinuxContainment(value) {
25643
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
25644
+ const v = value;
25645
+ return Object.keys(v).length === 5 && Number.isInteger(v.uid) && v.uid > 0 && v.uid <= 4294967295 && typeof v.unit === "string" && unitName.test(v.unit) && typeof v.bootId === "string" && bootId.test(v.bootId) && typeof v.invocationId === "string" && /^[0-9a-f]{32}$/.test(v.invocationId) && !/^0+$/.test(v.invocationId) && typeof v.cgroup === "string" && v.cgroup.length <= 2048 && !v.cgroup.includes("\0") && v.cgroup.startsWith("/user.slice/user-" + v.uid + ".slice/user@" + v.uid + ".service/") && path4.posix.normalize(v.cgroup) === v.cgroup && path4.posix.basename(v.cgroup) === v.unit;
25646
+ }
25647
+ var exec = promisify(execFile);
25648
+ async function linuxSupervisorLiveness(pids, records = []) {
25649
+ if (process.platform !== "linux" || !process.getuid?.() || process.getuid() !== process.geteuid?.()) return null;
25650
+ const remaining = new Set(pids), uid = process.getuid(), deadline = Date.now() + 1e4;
25651
+ const env = buildChildEnvironment(process.env);
25652
+ env.XDG_RUNTIME_DIR = "/run/user/" + uid;
25653
+ env.DBUS_SESSION_BUS_ADDRESS = "unix:path=" + env.XDG_RUNTIME_DIR + "/bus";
25654
+ try {
25655
+ if ((await statfs("/sys/fs/cgroup")).type !== 1667723888) return null;
25656
+ const boot = (await readFile2("/proc/sys/kernel/random/boot_id", "utf8")).trim();
25657
+ const control = (unit, args) => exec(
25658
+ "/usr/bin/systemctl",
25659
+ ["--user", "--no-ask-password", ...args, unit],
25660
+ { env, timeout: Math.max(1, Math.min(2e3, deadline - Date.now())), maxBuffer: 8192, encoding: "utf8", windowsHide: true }
25661
+ );
25662
+ const show = async (unit) => {
25663
+ const properties = ["Id", "LoadState", "ActiveState", "ControlGroup", "InvocationID", "Transient", "Restart", "KillMode"];
25664
+ const result2 = await control(unit, ["show", ...properties.map((p) => "--property=" + p)]).catch((e) => {
25665
+ if (e.code !== 4 || typeof e.stdout !== "string") throw e;
25666
+ return { stdout: e.stdout };
25667
+ });
25668
+ const fields = {};
25669
+ for (const line of result2.stdout.trim().split("\n")) {
25670
+ const at = line.indexOf("="), key = line.slice(0, at);
25671
+ if (at < 1 || !properties.includes(key) || key in fields) throw Error("LINUX_CONTAINMENT_INVALID");
25672
+ fields[key] = line.slice(at + 1);
25673
+ }
25674
+ if (fields.Id !== unit || !fields.LoadState || !fields.ActiveState) throw Error("LINUX_CONTAINMENT_INVALID");
25675
+ return fields;
25676
+ };
25677
+ for (const pid of remaining) {
25678
+ if (Date.now() >= deadline) break;
25679
+ const matches2 = records.filter((r) => r.pid === pid);
25680
+ if (matches2.length !== 1) continue;
25681
+ const proof2 = matches2[0].containment;
25682
+ if (!validLinuxContainment(proof2) || proof2.uid !== uid || proof2.bootId !== boot) continue;
25683
+ try {
25684
+ let stopped2 = false;
25685
+ while (Date.now() < deadline) {
25686
+ const fields = await show(proof2.unit);
25687
+ const absent2 = fields.LoadState === "not-found" && fields.ActiveState === "inactive" && !fields.ControlGroup && !fields.InvocationID;
25688
+ if (!absent2 && (fields.LoadState !== "loaded" || fields.ControlGroup !== proof2.cgroup || fields.InvocationID !== proof2.invocationId || fields.Transient !== "yes" || fields.Restart !== "no" || fields.KillMode !== "control-group")) break;
25689
+ if (absent2 || fields.ActiveState === "inactive" || fields.ActiveState === "failed") {
25690
+ const empty = await readFile2("/sys/fs/cgroup" + proof2.cgroup + "/cgroup.events", "utf8").then((text3) => /(?:^|\n)populated 0(?:\n|$)/.test(text3), (e) => e.code === "ENOENT");
25691
+ if (empty) remaining.delete(pid);
25692
+ break;
25693
+ }
25694
+ if (!stopped2) {
25695
+ await control(proof2.unit, ["stop"]).catch(() => {
25696
+ });
25697
+ stopped2 = true;
25698
+ } else await delay(50);
25699
+ }
25700
+ } catch {
25701
+ }
25702
+ }
25703
+ return remaining;
25704
+ } catch {
25705
+ return null;
25706
+ }
25707
+ }
25708
+
25709
+ // agent/src/darwin-containment.ts
25710
+ import { execFile as execFile2 } from "node:child_process";
25711
+ import { promisify as promisify2 } from "node:util";
25712
+ var label = /^app\.localcmd\.command\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
25713
+ var bootSession = /^[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}$/;
25714
+ function validDarwinContainment(value) {
25715
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
25716
+ const v = value;
25717
+ return Object.keys(v).length === 4 && Number.isInteger(v.uid) && v.uid > 0 && v.uid <= 4294967295 && typeof v.label === "string" && label.test(v.label) && typeof v.bootSession === "string" && bootSession.test(v.bootSession) && typeof v.coalition === "string" && /^[1-9][0-9]{0,17}$/.test(v.coalition) && v.coalition !== "1";
25718
+ }
25719
+ var exec2 = promisify2(execFile2);
25720
+ async function darwinSupervisorLiveness(helper, pids, records = []) {
25721
+ if (process.platform !== "darwin" || !process.getuid?.() || process.getuid() !== process.geteuid?.()) return null;
25722
+ const remaining = new Set(pids), uid = process.getuid(), deadline = Date.now() + 1e4, env = buildChildEnvironment(process.env);
25723
+ const run = (file2, args) => exec2(
25724
+ file2,
25725
+ args,
25726
+ { env, timeout: Math.max(1, Math.min(7e3, deadline - Date.now())), maxBuffer: 8192, encoding: "utf8", windowsHide: true }
25727
+ );
25728
+ try {
25729
+ const boot = (await run("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"])).stdout.trim();
25730
+ if (!bootSession.test(boot)) return null;
25731
+ for (const pid of remaining) {
25732
+ if (Date.now() >= deadline) break;
25733
+ const matches2 = records.filter((r) => r.pid === pid);
25734
+ if (matches2.length !== 1) continue;
25735
+ const proof2 = matches2[0].containment;
25736
+ if (!validDarwinContainment(proof2) || proof2.uid !== uid || proof2.bootSession !== boot) continue;
25737
+ try {
25738
+ await run(helper, ["--reap", proof2.coalition]);
25739
+ if ((await run(helper, ["--count", proof2.coalition])).stdout.trim() !== "0") continue;
25740
+ await run("/bin/launchctl", ["bootout", "gui/" + uid + "/" + proof2.label]).catch(() => {
25741
+ });
25742
+ remaining.delete(pid);
25743
+ } catch {
25744
+ }
25745
+ }
25746
+ return remaining;
25747
+ } catch {
25748
+ return null;
25749
+ }
25750
+ }
25751
+
25752
+ // agent/src/journal.ts
25753
+ import { lstat as lstat2, mkdir as mkdir3, open as open3, readdir as readdir2, readFile as readFile3, realpath as realpath2, rename, rm as rm2 } from "node:fs/promises";
25754
+ import path6 from "node:path";
25634
25755
  import { createHash as createHash7, randomBytes as randomBytes4, randomUUID as randomUUID4 } from "node:crypto";
25635
25756
 
25636
25757
  // src/output-buffer.ts
@@ -25864,7 +25985,7 @@ import { createHash as createHash6, createPublicKey as createPublicKey3, KeyObje
25864
25985
 
25865
25986
  // packages/contracts/src/agent-policy.ts
25866
25987
  var agentPolicyProtocolVersion = 1;
25867
- var uuid5 = external_exports.string().uuid().toLowerCase();
25988
+ var uuid8 = external_exports.string().uuid().toLowerCase();
25868
25989
  var utcDateTime = external_exports.iso.datetime({ offset: false }).refine(
25869
25990
  (value) => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/.test(value),
25870
25991
  "Expected UTC timestamp with seconds"
@@ -26009,11 +26130,11 @@ var AdapterActionInputSchema = external_exports.object({
26009
26130
  });
26010
26131
  var TrustedActionBindingSchema = external_exports.object({
26011
26132
  bindingSource: external_exports.enum(["server", "endpoint-attestation"]),
26012
- tenantId: uuid5,
26013
- accountId: uuid5,
26014
- grantId: uuid5.optional(),
26015
- deviceId: uuid5.optional(),
26016
- executionSessionId: uuid5.optional(),
26133
+ tenantId: uuid8,
26134
+ accountId: uuid8,
26135
+ grantId: uuid8.optional(),
26136
+ deviceId: uuid8.optional(),
26137
+ executionSessionId: uuid8.optional(),
26017
26138
  authenticatedAt: utcDateTime,
26018
26139
  expiresAt: utcDateTime
26019
26140
  }).strict().refine((value) => Date.parse(value.authenticatedAt) < Date.parse(value.expiresAt), {
@@ -26022,7 +26143,7 @@ var TrustedActionBindingSchema = external_exports.object({
26022
26143
  });
26023
26144
  var BoundActionRequestSchema = external_exports.object({
26024
26145
  protocolVersion: external_exports.literal(agentPolicyProtocolVersion),
26025
- requestId: uuid5,
26146
+ requestId: uuid8,
26026
26147
  input: AdapterActionInputSchema,
26027
26148
  binding: TrustedActionBindingSchema
26028
26149
  }).strict().superRefine((value, ctx) => {
@@ -26056,8 +26177,8 @@ var TransformSpecSchema = external_exports.object({
26056
26177
  }).strict();
26057
26178
  var PolicyDecisionSchema = external_exports.object({
26058
26179
  protocolVersion: external_exports.literal(agentPolicyProtocolVersion),
26059
- decisionId: uuid5,
26060
- requestId: uuid5,
26180
+ decisionId: uuid8,
26181
+ requestId: uuid8,
26061
26182
  policyId: slug,
26062
26183
  policyVersion: external_exports.string().trim().min(1).max(64),
26063
26184
  decidedAt: utcDateTime,
@@ -26090,15 +26211,15 @@ var ContentEvidenceSchema = external_exports.discriminatedUnion("mode", [
26090
26211
  external_exports.object({ mode: external_exports.literal("none") }).strict(),
26091
26212
  external_exports.object({
26092
26213
  mode: external_exports.literal("encrypted-opt-in"),
26093
- objectId: uuid5,
26214
+ objectId: uuid8,
26094
26215
  keyFingerprint: sha256
26095
26216
  }).strict()
26096
26217
  ]);
26097
26218
  var ActionEvidenceSchema = external_exports.object({
26098
26219
  protocolVersion: external_exports.literal(agentPolicyProtocolVersion),
26099
- evidenceId: uuid5,
26100
- requestId: uuid5,
26101
- decisionId: uuid5,
26220
+ evidenceId: uuid8,
26221
+ requestId: uuid8,
26222
+ decisionId: uuid8,
26102
26223
  occurredAt: utcDateTime,
26103
26224
  mediation: external_exports.enum(["mediated", "observed-only", "unknown"]),
26104
26225
  phase: external_exports.enum(["request", "decision", "dispatch", "result"]),
@@ -26122,7 +26243,7 @@ function projectRelativePath(value) {
26122
26243
  if (normalized.split("/").some((part) => !part || part === "." || part === ".." || /[. ]$/u.test(part) || /^(?:con|prn|aux|nul|clock\$|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu.test(part))) throw new TypeError("Invalid relativePath");
26123
26244
  return normalized;
26124
26245
  }
26125
- var uuid8 = external_exports.string().uuid().toLowerCase();
26246
+ var uuid9 = external_exports.string().uuid().toLowerCase();
26126
26247
  var hash2 = external_exports.string().regex(/^[a-f0-9]{64}$/);
26127
26248
  var ProjectRelativePathSchema = external_exports.string().transform((value, ctx) => {
26128
26249
  try {
@@ -26133,8 +26254,8 @@ var ProjectRelativePathSchema = external_exports.string().transform((value, ctx)
26133
26254
  }
26134
26255
  });
26135
26256
  var ProjectTargetBindingSchema = external_exports.object({
26136
- projectId: uuid8,
26137
- targetId: uuid8,
26257
+ projectId: uuid9,
26258
+ targetId: uuid9,
26138
26259
  environment: external_exports.enum(["dev", "staging", "prod"]),
26139
26260
  relativePath: ProjectRelativePathSchema,
26140
26261
  repositoryFingerprint: hash2,
@@ -26167,7 +26288,7 @@ function repositoryFingerprint(remote) {
26167
26288
  var protocolVersion = 1;
26168
26289
  var MAX_FILE_WRITE_BYTES = 1024 * 1024;
26169
26290
  var MAX_RELAY_FRAME_BYTES = 8 * 1024 * 1024;
26170
- var uuid9 = external_exports.string().uuid().toLowerCase();
26291
+ var uuid10 = external_exports.string().uuid().toLowerCase();
26171
26292
  var nonEmpty = external_exports.string().trim().min(1);
26172
26293
  var utcDateTime2 = external_exports.iso.datetime({ offset: false }).refine((value) => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/.test(value), "Expected UTC timestamp with seconds");
26173
26294
  var units = external_exports.number().int().min(0).max(1e9);
@@ -26223,27 +26344,27 @@ var ErrorCodeSchema = external_exports.enum([
26223
26344
  var LedgerEventKindSchema = external_exports.enum(["reserve", "charge", "release", "credit"]);
26224
26345
  var TrustedPrincipalSchema = external_exports.object({
26225
26346
  protocolVersion: external_exports.literal(protocolVersion),
26226
- accountId: uuid9,
26227
- tenantId: uuid9,
26228
- grantId: uuid9,
26347
+ accountId: uuid10,
26348
+ tenantId: uuid10,
26349
+ grantId: uuid10,
26229
26350
  scopes: external_exports.array(PermissionScopeSchema).min(1).max(32),
26230
26351
  authenticatedAt: utcDateTime2,
26231
26352
  expiresAt: utcDateTime2
26232
26353
  }).strict().refine((value) => Date.parse(value.authenticatedAt) < Date.parse(value.expiresAt), { path: ["expiresAt"], message: "Expiry must follow authentication" });
26233
26354
  var ExecutionSessionSchema = external_exports.object({
26234
26355
  protocolVersion: external_exports.literal(protocolVersion),
26235
- executionSessionId: uuid9,
26236
- tenantId: uuid9,
26237
- grantId: uuid9,
26238
- deviceId: uuid9,
26239
- workspaceGrantId: uuid9.optional(),
26356
+ executionSessionId: uuid10,
26357
+ tenantId: uuid10,
26358
+ grantId: uuid10,
26359
+ deviceId: uuid10,
26360
+ workspaceGrantId: uuid10.optional(),
26240
26361
  policyVersion: external_exports.string().trim().min(1).max(64),
26241
26362
  openedAt: utcDateTime2,
26242
26363
  expiresAt: utcDateTime2,
26243
26364
  state: external_exports.enum(["open", "closing", "closed", "expired"])
26244
26365
  }).strict().refine((value) => Date.parse(value.openedAt) < Date.parse(value.expiresAt), { path: ["expiresAt"], message: "Expiry must follow session creation" });
26245
26366
  var ChildCommandSchema = external_exports.object({
26246
- childExecutionId: uuid9,
26367
+ childExecutionId: uuid10,
26247
26368
  executable: nonEmpty.max(260),
26248
26369
  argv: external_exports.array(external_exports.string().max(8192)).max(128).default([]),
26249
26370
  cwd: external_exports.string().trim().min(1).max(2048).optional(),
@@ -26251,8 +26372,8 @@ var ChildCommandSchema = external_exports.object({
26251
26372
  }).strict();
26252
26373
  var ClientCommandRequestSchema = external_exports.object({
26253
26374
  protocolVersion: external_exports.literal(protocolVersion),
26254
- executionSessionId: uuid9,
26255
- operationId: uuid9,
26375
+ executionSessionId: uuid10,
26376
+ operationId: uuid10,
26256
26377
  idempotencyKey: external_exports.string().trim().min(8).max(128),
26257
26378
  children: external_exports.array(ChildCommandSchema).min(2).max(32)
26258
26379
  }).strict().superRefine((value, ctx) => {
@@ -26266,25 +26387,25 @@ var ClientCommandRequestSchema = external_exports.object({
26266
26387
  });
26267
26388
  var ControlOperationSchema = external_exports.object({
26268
26389
  protocolVersion: external_exports.literal(protocolVersion),
26269
- executionSessionId: uuid9,
26270
- operationId: uuid9,
26390
+ executionSessionId: uuid10,
26391
+ operationId: uuid10,
26271
26392
  kind: external_exports.enum(["status", "output", "cancel"]),
26272
26393
  cursor: external_exports.string().trim().min(1).max(512).optional()
26273
26394
  }).strict();
26274
26395
  var LedgerEventSchema = external_exports.object({
26275
26396
  protocolVersion: external_exports.literal(protocolVersion),
26276
- tenantId: uuid9,
26277
- executionId: uuid9,
26397
+ tenantId: uuid10,
26398
+ executionId: uuid10,
26278
26399
  eventKind: LedgerEventKindSchema,
26279
26400
  units: external_exports.literal(1),
26280
26401
  periodStartUtc: utcDateTime2,
26281
26402
  periodEndUtc: utcDateTime2,
26282
26403
  occurredAt: utcDateTime2,
26283
- adjustmentId: uuid9.optional()
26404
+ adjustmentId: uuid10.optional()
26284
26405
  }).strict().refine(validUsagePeriod, { path: ["periodEndUtc"], message: "Expected one UTC calendar month" }).refine((value) => value.eventKind !== "credit" || value.adjustmentId !== void 0, { path: ["adjustmentId"], message: "Credit requires a unique adjustment ID" });
26285
26406
  var UsageCountersSchema = external_exports.object({
26286
26407
  protocolVersion: external_exports.literal(protocolVersion),
26287
- tenantId: uuid9,
26408
+ tenantId: uuid10,
26288
26409
  periodStartUtc: utcDateTime2,
26289
26410
  periodEndUtc: utcDateTime2,
26290
26411
  limitUnits: units,
@@ -26302,7 +26423,7 @@ var OperationErrorSchema = external_exports.object({
26302
26423
  }).strict();
26303
26424
 
26304
26425
  // packages/contracts/src/device-protocol.ts
26305
- var uuid10 = external_exports.string().uuid().toLowerCase();
26426
+ var uuid11 = external_exports.string().uuid().toLowerCase();
26306
26427
  var hash3 = external_exports.string().regex(/^[a-f0-9]{64}$/);
26307
26428
  var epoch2 = external_exports.string().regex(/^[1-9]\d{0,18}$/).refine((v) => BigInt(v) <= 9223372036854775807n);
26308
26429
  var text = external_exports.string().max(32767).refine((v) => !v.includes("\0"));
@@ -26310,19 +26431,19 @@ var timestamp = external_exports.iso.datetime({ offset: false });
26310
26431
  var EfficiencyProfileSchema = external_exports.object({
26311
26432
  model: external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/+-]{0,79}$/)
26312
26433
  }).strict();
26313
- var path4 = text.min(1);
26434
+ var path5 = text.min(1);
26314
26435
  var ToolCallSchema = external_exports.discriminatedUnion("name", [
26315
26436
  external_exports.object({ name: external_exports.literal("project_identity"), args: external_exports.object({ path: ProjectRelativePathSchema }).strict() }).strict(),
26316
- external_exports.object({ name: external_exports.literal("fs_list"), args: external_exports.object({ path: path4.optional(), recursive: external_exports.boolean().default(false), maxDepth: external_exports.number().int().min(0).max(8).default(3), maxEntries: external_exports.number().int().min(1).max(1e3).default(200) }).strict() }).strict(),
26317
- external_exports.object({ name: external_exports.literal("fs_read"), args: external_exports.object({ path: path4, startLine: external_exports.number().int().min(1).max(1e6).optional(), endLine: external_exports.number().int().min(1).max(1e6).optional() }).strict() }).strict(),
26318
- external_exports.object({ name: external_exports.literal("fs_search"), args: external_exports.object({ path: path4.optional(), query: external_exports.string().min(1).max(1e3), caseSensitive: external_exports.boolean().default(false), maxResults: external_exports.number().int().min(1).max(300).default(100) }).strict() }).strict(),
26319
- external_exports.object({ name: external_exports.literal("fs_write"), args: external_exports.object({ path: path4, content: external_exports.string().max(MAX_FILE_WRITE_BYTES).refine((value) => Buffer.byteLength(value, "utf8") <= MAX_FILE_WRITE_BYTES, "fs_write content exceeds 1 MiB UTF-8"), overwrite: external_exports.boolean().default(false), expectedSha256: hash3.optional() }).strict() }).strict(),
26320
- external_exports.object({ name: external_exports.literal("fs_replace"), args: external_exports.object({ path: path4, oldText: external_exports.string().min(1).max(6e4), newText: external_exports.string().max(6e4), replaceAll: external_exports.boolean().default(false), expectedSha256: hash3.optional() }).strict() }).strict(),
26321
- external_exports.object({ name: external_exports.literal("git_status"), args: external_exports.object({ path: path4.optional() }).strict() }).strict(),
26322
- external_exports.object({ name: external_exports.literal("git_diff"), args: external_exports.object({ path: path4.optional(), file: path4.optional(), staged: external_exports.boolean().default(false) }).strict() }).strict(),
26323
- external_exports.object({ name: external_exports.literal("git_log"), args: external_exports.object({ path: path4.optional(), limit: external_exports.number().int().min(1).max(50).default(15) }).strict() }).strict(),
26324
- external_exports.object({ name: external_exports.literal("project_snapshot"), args: external_exports.object({ path: path4.optional(), startup: external_exports.boolean().optional(), taskId: external_exports.string().regex(/^[A-Za-z0-9_-]{1,100}$/).optional() }).strict() }).strict(),
26325
- external_exports.object({ name: external_exports.literal("command_run"), args: external_exports.object({ command: external_exports.string().min(1).max(260).refine((v) => !/[\r\n\0]/.test(v)), args: external_exports.array(external_exports.string().max(8192).refine((v) => !v.includes("\0"))).max(128).default([]), cwd: path4.optional(), timeoutMs: external_exports.number().int().min(100).max(864e5).default(6e4) }).strict() }).strict(),
26437
+ external_exports.object({ name: external_exports.literal("fs_list"), args: external_exports.object({ path: path5.optional(), recursive: external_exports.boolean().default(false), maxDepth: external_exports.number().int().min(0).max(8).default(3), maxEntries: external_exports.number().int().min(1).max(1e3).default(200) }).strict() }).strict(),
26438
+ external_exports.object({ name: external_exports.literal("fs_read"), args: external_exports.object({ path: path5, startLine: external_exports.number().int().min(1).max(1e6).optional(), endLine: external_exports.number().int().min(1).max(1e6).optional() }).strict() }).strict(),
26439
+ external_exports.object({ name: external_exports.literal("fs_search"), args: external_exports.object({ path: path5.optional(), query: external_exports.string().min(1).max(1e3), caseSensitive: external_exports.boolean().default(false), maxResults: external_exports.number().int().min(1).max(300).default(100) }).strict() }).strict(),
26440
+ external_exports.object({ name: external_exports.literal("fs_write"), args: external_exports.object({ path: path5, content: external_exports.string().max(MAX_FILE_WRITE_BYTES).refine((value) => Buffer.byteLength(value, "utf8") <= MAX_FILE_WRITE_BYTES, "fs_write content exceeds 1 MiB UTF-8"), overwrite: external_exports.boolean().default(false), expectedSha256: hash3.optional() }).strict() }).strict(),
26441
+ external_exports.object({ name: external_exports.literal("fs_replace"), args: external_exports.object({ path: path5, oldText: external_exports.string().min(1).max(6e4), newText: external_exports.string().max(6e4), replaceAll: external_exports.boolean().default(false), expectedSha256: hash3.optional() }).strict() }).strict(),
26442
+ external_exports.object({ name: external_exports.literal("git_status"), args: external_exports.object({ path: path5.optional() }).strict() }).strict(),
26443
+ external_exports.object({ name: external_exports.literal("git_diff"), args: external_exports.object({ path: path5.optional(), file: path5.optional(), staged: external_exports.boolean().default(false) }).strict() }).strict(),
26444
+ external_exports.object({ name: external_exports.literal("git_log"), args: external_exports.object({ path: path5.optional(), limit: external_exports.number().int().min(1).max(50).default(15) }).strict() }).strict(),
26445
+ external_exports.object({ name: external_exports.literal("project_snapshot"), args: external_exports.object({ path: path5.optional(), startup: external_exports.boolean().optional(), taskId: external_exports.string().regex(/^[A-Za-z0-9_-]{1,100}$/).optional() }).strict() }).strict(),
26446
+ external_exports.object({ name: external_exports.literal("command_run"), args: external_exports.object({ command: external_exports.string().min(1).max(260).refine((v) => !/[\r\n\0]/.test(v)), args: external_exports.array(external_exports.string().max(8192).refine((v) => !v.includes("\0"))).max(128).default([]), cwd: path5.optional(), timeoutMs: external_exports.number().int().min(100).max(864e5).default(6e4) }).strict() }).strict(),
26326
26447
  external_exports.object({ name: external_exports.literal("localhost_request"), args: external_exports.object({ url: external_exports.string().url().max(2048), method: external_exports.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]).default("GET"), headers: external_exports.record(external_exports.string().max(128), external_exports.string().max(2048)).optional(), body: external_exports.string().max(6e4).optional() }).strict() }).strict()
26327
26448
  ]);
26328
26449
  function scopeForTool(call) {
@@ -26330,29 +26451,29 @@ function scopeForTool(call) {
26330
26451
  if (call.name === "localhost_request") return "localhost:access";
26331
26452
  return call.name === "fs_write" || call.name === "fs_replace" ? "files:write" : "files:read";
26332
26453
  }
26333
- var ExecutionBindingSchema = external_exports.object({ tenantId: uuid10, accountId: uuid10.optional(), deviceId: uuid10, grantId: uuid10, sessionId: uuid10, operationId: uuid10, executionId: uuid10, connectionEpoch: epoch2, workspaceGrantId: uuid10, policyVersion: external_exports.number().int().min(1).max(2147483647), payloadHash: hash3, deadlineAt: timestamp, projectTarget: ProjectTargetBindingSchema.optional() }).strict();
26454
+ var ExecutionBindingSchema = external_exports.object({ tenantId: uuid11, accountId: uuid11.optional(), deviceId: uuid11, grantId: uuid11, sessionId: uuid11, operationId: uuid11, executionId: uuid11, connectionEpoch: epoch2, workspaceGrantId: uuid11, policyVersion: external_exports.number().int().min(1).max(2147483647), payloadHash: hash3, deadlineAt: timestamp, projectTarget: ProjectTargetBindingSchema.optional() }).strict();
26334
26455
  var EfficiencyNoticeSchema = external_exports.object({ message: external_exports.string().min(1).max(160), estimatedSavedTokens: external_exports.number().int().min(1).max(1e12), savedBytes: external_exports.number().int().min(1).max(1e12), sessionCalls: external_exports.number().int().min(20).max(1e9) }).strict();
26335
26456
  var ResultSchema = external_exports.object({ exitCode: external_exports.number().int().min(-2147483648).max(4294967295).nullable(), timedOut: external_exports.boolean(), cancelled: external_exports.boolean(), treeTerminated: external_exports.boolean(), stdout: external_exports.string().max(196608), stderr: external_exports.string().max(196608), stdoutTruncated: external_exports.boolean(), stderrTruncated: external_exports.boolean(), resultCode: external_exports.string().regex(/^[A-Z0-9_]{1,40}$/), efficiencyNotice: EfficiencyNoticeSchema.optional() }).strict();
26336
26457
  var ServerFrameSchema = external_exports.discriminatedUnion("type", [
26337
- external_exports.object({ type: external_exports.literal("hello"), version: external_exports.literal(1), tenantId: uuid10, deviceId: uuid10, connectionEpoch: epoch2, serverTime: timestamp }).strict(),
26458
+ external_exports.object({ type: external_exports.literal("hello"), version: external_exports.literal(1), tenantId: uuid11, deviceId: uuid11, connectionEpoch: epoch2, serverTime: timestamp }).strict(),
26338
26459
  external_exports.object({ type: external_exports.literal("prepare"), version: external_exports.literal(1), binding: ExecutionBindingSchema, tool: ToolCallSchema }).strict(),
26339
26460
  external_exports.object({ type: external_exports.literal("execute"), version: external_exports.literal(1), binding: ExecutionBindingSchema }).strict(),
26340
- external_exports.object({ type: external_exports.literal("control"), version: external_exports.literal(1), requestId: uuid10, binding: ExecutionBindingSchema, action: external_exports.enum(["status", "output", "cancel"]) }).strict(),
26461
+ external_exports.object({ type: external_exports.literal("control"), version: external_exports.literal(1), requestId: uuid11, binding: ExecutionBindingSchema, action: external_exports.enum(["status", "output", "cancel"]) }).strict(),
26341
26462
  external_exports.object({ type: external_exports.literal("heartbeat_ack"), version: external_exports.literal(1), connectionEpoch: epoch2, leaseExpiresAt: timestamp }).strict(),
26342
- external_exports.object({ type: external_exports.literal("workspace_ack"), version: external_exports.literal(1), requestId: uuid10, workspaceGrantId: uuid10, accepted: external_exports.boolean(), code: external_exports.string().max(64).optional() }).strict(),
26463
+ 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(),
26343
26464
  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()
26344
26465
  ]);
26345
26466
  var ClientFrameSchema = external_exports.discriminatedUnion("type", [
26346
26467
  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(),
26347
26468
  external_exports.object({ type: external_exports.literal("heartbeat"), version: external_exports.literal(1), connectionEpoch: epoch2 }).strict(),
26348
- external_exports.object({ type: external_exports.literal("workspace_grant"), version: external_exports.literal(1), requestId: uuid10, workspaceGrantId: uuid10, rootHash: hash3, displayName: external_exports.string().min(1).max(120), policyVersion: external_exports.number().int().min(1).max(2147483647) }).strict(),
26349
- external_exports.object({ type: external_exports.literal("workspace_revoke"), version: external_exports.literal(1), requestId: uuid10, workspaceGrantId: uuid10 }).strict(),
26469
+ 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(),
26470
+ external_exports.object({ type: external_exports.literal("workspace_revoke"), version: external_exports.literal(1), requestId: uuid11, workspaceGrantId: uuid11 }).strict(),
26350
26471
  external_exports.object({ type: external_exports.literal("prepared"), version: external_exports.literal(1), binding: ExecutionBindingSchema }).strict(),
26351
26472
  external_exports.object({ type: external_exports.literal("accepted"), version: external_exports.literal(1), binding: ExecutionBindingSchema }).strict(),
26352
26473
  external_exports.object({ type: external_exports.literal("running"), version: external_exports.literal(1), binding: ExecutionBindingSchema, pid: external_exports.number().int().positive().optional() }).strict(),
26353
26474
  external_exports.object({ type: external_exports.literal("result"), version: external_exports.literal(1), binding: ExecutionBindingSchema, result: ResultSchema }).strict(),
26354
26475
  external_exports.object({ type: external_exports.literal("not_accepted"), version: external_exports.literal(1), binding: ExecutionBindingSchema, code: external_exports.string().regex(/^[A-Z0-9_]{1,40}$/), provedNotStarted: external_exports.boolean() }).strict(),
26355
- external_exports.object({ type: external_exports.literal("control_result"), version: external_exports.literal(1), requestId: uuid10, binding: ExecutionBindingSchema, state: external_exports.enum(["prepared", "accepted", "running", "finished", "failed", "cancelled", "rejected", "unknown", "missing"]), result: ResultSchema.optional() }).strict()
26476
+ external_exports.object({ type: external_exports.literal("control_result"), version: external_exports.literal(1), requestId: uuid11, binding: ExecutionBindingSchema, state: external_exports.enum(["prepared", "accepted", "running", "finished", "failed", "cancelled", "rejected", "unknown", "missing"]), result: ResultSchema.optional() }).strict()
26356
26477
  ]);
26357
26478
  var TerminalMetricsSchema = external_exports.object({ stdoutBytes: external_exports.number().int().min(0).max(4194304), stderrBytes: external_exports.number().int().min(0).max(4194304), outputTruncated: external_exports.boolean() }).strict();
26358
26479
  var TERMINAL_METRICS_CAPABILITY = "terminalMetrics";
@@ -26362,8 +26483,8 @@ var NATIVE_CAPACITY_CAPABILITY = "nativeCapacity";
26362
26483
  var NativeCapacitySchema = external_exports.object({ type: external_exports.literal("nativeCapacity"), protocolVersion: external_exports.literal(1), connectionEpoch: epoch2, safeSlots: external_exports.number().int().min(1).max(32), agentVersion: external_exports.string().regex(/^[A-Za-z0-9._+-]{1,64}$/) }).strict();
26363
26484
  var NATIVE_STATUS_CAPABILITY = "nativeStatusV1";
26364
26485
  var NativeStatusSchema = NativeCapacitySchema.extend({ type: external_exports.literal("nativeStatus"), active: external_exports.number().int().min(0).max(32), queued: external_exports.number().int().min(0).max(256), paused: external_exports.boolean() }).strict().refine((v) => v.active <= v.safeSlots);
26365
- var TerminalEventSchema = external_exports.object({ type: external_exports.literal("executionResult"), protocolVersion: external_exports.literal(1), requestId: uuid10, tenantId: uuid10, deviceId: uuid10, connectionEpoch: epoch2, binding: ExecutionBindingSchema, state: external_exports.enum(["finished", "failed", "cancelled", "unknown", "rejected"]), resultCode: external_exports.string().regex(/^[A-Z0-9_]{1,40}$/), metrics: TerminalMetricsSchema.optional() }).strict();
26366
- var TerminalEventAckSchema = external_exports.object({ type: external_exports.literal("executionResultAck"), protocolVersion: external_exports.literal(1), requestId: uuid10, ok: external_exports.boolean() }).strict();
26486
+ var TerminalEventSchema = external_exports.object({ type: external_exports.literal("executionResult"), protocolVersion: external_exports.literal(1), requestId: uuid11, tenantId: uuid11, deviceId: uuid11, connectionEpoch: epoch2, binding: ExecutionBindingSchema, state: external_exports.enum(["finished", "failed", "cancelled", "unknown", "rejected"]), resultCode: external_exports.string().regex(/^[A-Z0-9_]{1,40}$/), metrics: TerminalMetricsSchema.optional() }).strict();
26487
+ var TerminalEventAckSchema = external_exports.object({ type: external_exports.literal("executionResultAck"), protocolVersion: external_exports.literal(1), requestId: uuid11, ok: external_exports.boolean() }).strict();
26367
26488
  function canonicalJson(value) {
26368
26489
  function canonical2(v) {
26369
26490
  if (Array.isArray(v)) return v.map(canonical2);
@@ -26396,16 +26517,16 @@ var guardAdapter = AdapterDescriptorSchema.parse({
26396
26517
  detectsNativeBypass: false
26397
26518
  }
26398
26519
  });
26399
- var uuid11 = external_exports.string().uuid().toLowerCase();
26520
+ var uuid12 = external_exports.string().uuid().toLowerCase();
26400
26521
  var GuardSettingsSchema = external_exports.object({
26401
26522
  policyId: external_exports.string().regex(/^[a-z][a-z0-9._-]{0,63}$/),
26402
26523
  keys: external_exports.array(external_exports.object({ keyId: external_exports.string().regex(/^[a-z][a-z0-9._-]{0,63}$/), publicKeyPem: external_exports.string().max(1024) }).strict()).min(1).max(8),
26403
26524
  environment: EnvironmentContextSchema
26404
26525
  }).strict();
26405
26526
  var GuardConfigurationSchema = GuardSettingsSchema.extend({
26406
- tenantId: uuid11,
26407
- deviceId: uuid11,
26408
- ownerAccountId: uuid11,
26527
+ tenantId: uuid12,
26528
+ deviceId: uuid12,
26529
+ ownerAccountId: uuid12,
26409
26530
  ownerSid: external_exports.string().regex(/^S-1-(?:[0-9]+-)+[0-9]+$/).max(184)
26410
26531
  }).strict();
26411
26532
  function guardHash(value) {
@@ -26486,14 +26607,14 @@ var GuardEventSchema = external_exports.object({
26486
26607
  previousHash: hash4,
26487
26608
  hash: hash4
26488
26609
  }).strict();
26489
- var uuid12 = external_exports.string().uuid().toLowerCase();
26610
+ var uuid13 = external_exports.string().uuid().toLowerCase();
26490
26611
  var GuardEvidenceRecordSchema = external_exports.object({
26491
- tenantId: uuid12,
26492
- deviceId: uuid12,
26493
- accountId: uuid12.optional(),
26494
- sessionId: uuid12,
26495
- operationId: uuid12,
26496
- executionId: uuid12,
26612
+ tenantId: uuid13,
26613
+ deviceId: uuid13,
26614
+ accountId: uuid13.optional(),
26615
+ sessionId: uuid13,
26616
+ operationId: uuid13,
26617
+ executionId: uuid13,
26497
26618
  state: external_exports.enum(["prepared", "accepted", "running", "finished", "failed", "cancelled", "rejected", "unknown"]),
26498
26619
  events: external_exports.array(GuardEventSchema).min(1).max(12)
26499
26620
  }).strict();
@@ -26512,8 +26633,8 @@ function appendGuardEvent(events, input2) {
26512
26633
  }
26513
26634
  var ExportSchema = external_exports.object({
26514
26635
  formatVersion: external_exports.literal(1),
26515
- tenantId: uuid12,
26516
- deviceId: uuid12,
26636
+ tenantId: uuid13,
26637
+ deviceId: uuid13,
26517
26638
  records: external_exports.array(GuardEvidenceRecordSchema).max(1e3)
26518
26639
  }).strict();
26519
26640
  var HeaderSchema = external_exports.object({ alg: external_exports.literal("EdDSA"), typ: external_exports.literal("lc-guard-evidence+jws"), kid: hash4 }).strict();
@@ -26560,7 +26681,7 @@ var MAX_SUPERVISORS = 8;
26560
26681
  function validPid(value) {
26561
26682
  return Number.isSafeInteger(value) && value > 0 && value <= 4294967295;
26562
26683
  }
26563
- var uuid13 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
26684
+ var uuid14 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
26564
26685
  var hash5 = /^[0-9a-f]{64}$/;
26565
26686
  var bindingKeys = ["executionId", "operationId", "sessionId", "tenantId", "grantId", "deviceId", "connectionEpoch", "payloadHash", "deadlineAt", "workspaceGrantId", "policyVersion", "accountId", "projectTarget"];
26566
26687
  var terminal = /* @__PURE__ */ new Set(["finished", "failed", "cancelled", "rejected"]);
@@ -26580,11 +26701,11 @@ function canonicalTime(value) {
26580
26701
  }
26581
26702
  function validateInput2(value) {
26582
26703
  if (!value || typeof value !== "object" || Object.keys(value).some((k) => !bindingKeys.includes(k))) throw failure2("JOURNAL_INPUT_INVALID");
26583
- for (const name2 of bindingKeys.slice(0, 6)) if (typeof value[name2] !== "string" || !uuid13.test(value[name2])) throw failure2("JOURNAL_INPUT_INVALID");
26584
- if (value.accountId !== void 0 && !uuid13.test(value.accountId)) throw failure2("JOURNAL_INPUT_INVALID");
26704
+ for (const name2 of bindingKeys.slice(0, 6)) if (typeof value[name2] !== "string" || !uuid14.test(value[name2])) throw failure2("JOURNAL_INPUT_INVALID");
26705
+ if (value.accountId !== void 0 && !uuid14.test(value.accountId)) throw failure2("JOURNAL_INPUT_INVALID");
26585
26706
  if (value.projectTarget !== void 0 && !ProjectTargetBindingSchema.safeParse(value.projectTarget).success) throw failure2("JOURNAL_INPUT_INVALID");
26586
26707
  if (typeof value.connectionEpoch !== "string" || !/^[1-9]\d{0,18}$/.test(value.connectionEpoch) || BigInt(value.connectionEpoch) > 9223372036854775807n || typeof value.payloadHash !== "string" || !hash5.test(value.payloadHash) || !canonicalTime(value.deadlineAt)) throw failure2("JOURNAL_INPUT_INVALID");
26587
- if (value.workspaceGrantId === void 0 !== (value.policyVersion === void 0) || value.workspaceGrantId !== void 0 && (!uuid13.test(value.workspaceGrantId) || !Number.isInteger(value.policyVersion) || value.policyVersion < 1 || value.policyVersion > 2147483647)) throw failure2("JOURNAL_INPUT_INVALID");
26708
+ if (value.workspaceGrantId === void 0 !== (value.policyVersion === void 0) || value.workspaceGrantId !== void 0 && (!uuid14.test(value.workspaceGrantId) || !Number.isInteger(value.policyVersion) || value.policyVersion < 1 || value.policyVersion > 2147483647)) throw failure2("JOURNAL_INPUT_INVALID");
26588
26709
  }
26589
26710
  function clone2(value) {
26590
26711
  return structuredClone(value);
@@ -26607,7 +26728,7 @@ function boundedResult(value) {
26607
26728
  }
26608
26729
  }
26609
26730
  async function safeDirectory(directory) {
26610
- const absolute2 = path5.resolve(directory);
26731
+ const absolute2 = path6.resolve(directory);
26611
26732
  let current2 = absolute2;
26612
26733
  for (; ; ) {
26613
26734
  try {
@@ -26615,7 +26736,7 @@ async function safeDirectory(directory) {
26615
26736
  } catch (e) {
26616
26737
  if (e.code !== "ENOENT") throw e;
26617
26738
  }
26618
- const parent = path5.dirname(current2);
26739
+ const parent = path6.dirname(current2);
26619
26740
  if (parent === current2) break;
26620
26741
  current2 = parent;
26621
26742
  }
@@ -26645,7 +26766,7 @@ var NativeJournal = class _NativeJournal {
26645
26766
  static async open(directory, box, options = {}) {
26646
26767
  const maxEntries = options.maxEntries ?? 2e3, maxBytes = options.maxBytes ?? 64 * 1048576, retentionMs = options.retentionMs ?? 864e5;
26647
26768
  if (!Number.isInteger(maxEntries) || maxEntries < 1 || maxEntries > 1e4 || !Number.isInteger(maxBytes) || maxBytes < 1024 || maxBytes > 64 * 1048576 || !Number.isInteger(retentionMs) || retentionMs < 0 || retentionMs > 30 * 864e5) throw failure2("JOURNAL_LIMIT_INVALID");
26648
- const dir = await safeDirectory(directory), lockPath = path5.join(dir, "journal.lock"), nonce2 = randomBytes4(16).toString("hex");
26769
+ const dir = await safeDirectory(directory), lockPath = path6.join(dir, "journal.lock"), nonce2 = randomBytes4(16).toString("hex");
26649
26770
  const guard = options.lockHelper ? await acquirePosixJournalGuard(dir, options.lockHelper) : void 0;
26650
26771
  let file2;
26651
26772
  try {
@@ -26665,7 +26786,7 @@ var NativeJournal = class _NativeJournal {
26665
26786
  await file2.close().catch(() => {
26666
26787
  });
26667
26788
  try {
26668
- const value = JSON.parse(await readFile2(lockPath, "utf8"));
26789
+ const value = JSON.parse(await readFile3(lockPath, "utf8"));
26669
26790
  if (value.nonce === nonce2) await rm2(lockPath);
26670
26791
  } catch {
26671
26792
  }
@@ -26687,10 +26808,10 @@ var NativeJournal = class _NativeJournal {
26687
26808
  return next;
26688
26809
  }
26689
26810
  file(id2) {
26690
- return path5.join(this.dir, id2 + ".entry");
26811
+ return path6.join(this.dir, id2 + ".entry");
26691
26812
  }
26692
26813
  need(id2) {
26693
- if (!uuid13.test(id2)) throw failure2("JOURNAL_INPUT_INVALID");
26814
+ if (!uuid14.test(id2)) throw failure2("JOURNAL_INPUT_INVALID");
26694
26815
  const e = this.entries.get(id2);
26695
26816
  if (!e) throw failure2("EXECUTION_UNKNOWN");
26696
26817
  return clone2(e);
@@ -26713,7 +26834,7 @@ var NativeJournal = class _NativeJournal {
26713
26834
  for (const name2 of names) {
26714
26835
  if (!name2.endsWith(".entry")) continue;
26715
26836
  const id2 = name2.slice(0, -6);
26716
- if (!uuid13.test(id2)) throw failure2("JOURNAL_CORRUPT");
26837
+ if (!uuid14.test(id2)) throw failure2("JOURNAL_CORRUPT");
26717
26838
  const envelope = await this.readOwned(id2);
26718
26839
  this.totalBytes += envelope.length;
26719
26840
  if (this.totalBytes > this.options.maxBytes || this.entries.size >= this.options.maxEntries) throw failure2("JOURNAL_CAPACITY_EXCEEDED");
@@ -26727,6 +26848,8 @@ var NativeJournal = class _NativeJournal {
26727
26848
  if (entry.resultCode !== void 0 && (typeof entry.resultCode !== "string" || !/^[A-Z0-9_]{1,40}$/.test(entry.resultCode))) throw Error();
26728
26849
  if (entry.reportedAt !== void 0 && (!entry.resultCode || !canonicalTime(entry.reportedAt))) throw Error();
26729
26850
  if (entry.supervisors !== void 0 && (!Array.isArray(entry.supervisors) || entry.supervisors.length > MAX_SUPERVISORS || !entry.supervisors.every(validPid))) throw Error();
26851
+ if (entry.linuxSupervisors !== void 0 && (!Array.isArray(entry.linuxSupervisors) || entry.linuxSupervisors.length > MAX_SUPERVISORS || new Set(entry.linuxSupervisors.map((s) => s?.pid)).size !== entry.linuxSupervisors.length || !entry.linuxSupervisors.every((s) => s && Object.keys(s).length === 2 && validPid(s.pid) && entry.supervisors?.includes(s.pid) && validLinuxContainment(s.containment)))) throw Error();
26852
+ if (entry.darwinSupervisors !== void 0 && (!Array.isArray(entry.darwinSupervisors) || entry.darwinSupervisors.length > MAX_SUPERVISORS || new Set(entry.darwinSupervisors.map((s) => s?.pid)).size !== entry.darwinSupervisors.length || !entry.darwinSupervisors.every((s) => s && Object.keys(s).length === 2 && validPid(s.pid) && entry.supervisors?.includes(s.pid) && !entry.linuxSupervisors?.some((l) => l.pid === s.pid) && validDarwinContainment(s.containment)))) throw Error();
26730
26853
  if (entry.guardEvents) {
26731
26854
  verifyGuardEvidence(entry.guardEvents);
26732
26855
  if (entry.guardEvents.some((record2) => record2.event.requestId !== id2)) throw Error();
@@ -26758,7 +26881,7 @@ var NativeJournal = class _NativeJournal {
26758
26881
  if (plaintext.length > 262144) throw failure2("JOURNAL_ENTRY_TOO_LARGE");
26759
26882
  const envelope = this.box.seal(plaintext, "execution:" + entry.executionId), oldSize = this.sizes.get(entry.executionId) ?? 0;
26760
26883
  if (this.totalBytes + envelope.length > this.options.maxBytes) throw failure2("JOURNAL_CAPACITY_EXCEEDED");
26761
- const temporary = path5.join(this.dir, entry.executionId + "." + this.lock.nonce + "." + randomBytes4(8).toString("hex") + ".tmp");
26884
+ const temporary = path6.join(this.dir, entry.executionId + "." + this.lock.nonce + "." + randomBytes4(8).toString("hex") + ".tmp");
26762
26885
  const handle = await open3(temporary, constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY, 384);
26763
26886
  try {
26764
26887
  await handle.writeFile(envelope);
@@ -26826,13 +26949,20 @@ var NativeJournal = class _NativeJournal {
26826
26949
  });
26827
26950
  }
26828
26951
  /** Durably records a JobHost pid before that JobHost receives its request; a failure must stop the launch. */
26829
- supervisor(id2, pid) {
26952
+ supervisor(id2, pid, containment) {
26830
26953
  return this.enqueue(async () => {
26831
26954
  const e = this.need(id2);
26832
26955
  if (!validPid(pid)) throw failure2("JOURNAL_INPUT_INVALID");
26833
26956
  if (e.state !== "running" || !e.supervisors) throw failure2("JOURNAL_STATE_INVALID");
26834
- if (e.supervisors.length >= MAX_SUPERVISORS) throw failure2("JOURNAL_SUPERVISOR_LIMIT");
26835
- e.supervisors.push(pid);
26957
+ if (containment !== void 0) {
26958
+ const linux = validLinuxContainment(containment), darwin = !linux && validDarwinContainment(containment);
26959
+ 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");
26960
+ if (linux) (e.linuxSupervisors ??= []).push({ pid, containment: clone2(containment) });
26961
+ else (e.darwinSupervisors ??= []).push({ pid, containment: clone2(containment) });
26962
+ } else {
26963
+ if (e.supervisors.length >= MAX_SUPERVISORS) throw failure2("JOURNAL_SUPERVISOR_LIMIT");
26964
+ e.supervisors.push(pid);
26965
+ }
26836
26966
  e.updatedAt = this.now().toISOString();
26837
26967
  await this.persist(e);
26838
26968
  });
@@ -26875,7 +27005,7 @@ var NativeJournal = class _NativeJournal {
26875
27005
  }
26876
27006
  get(id2) {
26877
27007
  return this.enqueue(async () => {
26878
- if (!uuid13.test(id2)) throw failure2("JOURNAL_INPUT_INVALID");
27008
+ if (!uuid14.test(id2)) throw failure2("JOURNAL_INPUT_INVALID");
26879
27009
  const e = this.entries.get(id2);
26880
27010
  return e ? clone2(e) : null;
26881
27011
  });
@@ -26933,11 +27063,13 @@ var NativeJournal = class _NativeJournal {
26933
27063
  recoverAfterRestart(liveness) {
26934
27064
  return this.enqueue(async () => {
26935
27065
  let count3 = 0;
26936
- const pids = [...new Set([...this.entries.values()].filter((e) => ["accepted", "running"].includes(e.state)).flatMap((e) => e.supervisors ?? []))];
27066
+ const interrupted = [...this.entries.values()].filter((e) => ["accepted", "running"].includes(e.state));
27067
+ const pids = [...new Set(interrupted.flatMap((e) => e.supervisors ?? []))];
27068
+ const linuxSupervisors = interrupted.flatMap((e) => e.linuxSupervisors ?? []), darwinSupervisors = interrupted.flatMap((e) => e.darwinSupervisors ?? []);
26937
27069
  let live = /* @__PURE__ */ new Set();
26938
27070
  if (pids.length) {
26939
27071
  try {
26940
- live = liveness ? await liveness(pids) : null;
27072
+ live = liveness ? await liveness(pids, linuxSupervisors, darwinSupervisors) : null;
26941
27073
  } catch {
26942
27074
  live = null;
26943
27075
  }
@@ -27010,7 +27142,7 @@ var NativeJournal = class _NativeJournal {
27010
27142
  try {
27011
27143
  const st = await lstat2(this.lock.path);
27012
27144
  if (!st.isFile() || st.isSymbolicLink() || st.size > 1024) throw failure2("JOURNAL_LOCK_LOST");
27013
- const value = JSON.parse(await readFile2(this.lock.path, "utf8"));
27145
+ const value = JSON.parse(await readFile3(this.lock.path, "utf8"));
27014
27146
  if (value.nonce !== this.lock.nonce) throw failure2("JOURNAL_LOCK_LOST");
27015
27147
  await this.lock.file.close();
27016
27148
  await rm2(this.lock.path);
@@ -27031,25 +27163,25 @@ import { constants as constants4 } from "node:fs";
27031
27163
  import { openSync, closeSync } from "node:fs";
27032
27164
  import { isatty, ReadStream, WriteStream } from "node:tty";
27033
27165
  import { createInterface } from "node:readline/promises";
27034
- import path7 from "node:path";
27166
+ import path8 from "node:path";
27035
27167
 
27036
27168
  // agent/src/owner-permissions.ts
27037
27169
  import { createHash as createHash8 } from "node:crypto";
27038
27170
  import { constants as constants3 } from "node:fs";
27039
27171
  import { access, lstat as lstat3, realpath as realpath3 } from "node:fs/promises";
27040
- import path6 from "node:path";
27041
- var uuid14 = external_exports.string().uuid().toLowerCase();
27172
+ import path7 from "node:path";
27173
+ var uuid15 = external_exports.string().uuid().toLowerCase();
27042
27174
  var name = external_exports.string().regex(/^[a-zA-Z0-9_.-]{1,64}$/).toLowerCase();
27043
27175
  var changeSchema = external_exports.discriminatedUnion("kind", [
27044
- external_exports.object({ workspaceGrantId: uuid14, kind: external_exports.literal("write"), enabled: external_exports.boolean() }).strict(),
27045
- external_exports.object({ workspaceGrantId: uuid14, kind: external_exports.literal("localhost"), enabled: external_exports.boolean(), port: external_exports.number().int().min(1).max(65535) }).strict(),
27046
- external_exports.object({ workspaceGrantId: uuid14, kind: external_exports.literal("command"), enabled: external_exports.boolean(), name, executable: external_exports.string().min(1).max(4096).optional() }).strict()
27176
+ external_exports.object({ workspaceGrantId: uuid15, kind: external_exports.literal("write"), enabled: external_exports.boolean() }).strict(),
27177
+ external_exports.object({ workspaceGrantId: uuid15, kind: external_exports.literal("localhost"), enabled: external_exports.boolean(), port: external_exports.number().int().min(1).max(65535) }).strict(),
27178
+ external_exports.object({ workspaceGrantId: uuid15, kind: external_exports.literal("command"), enabled: external_exports.boolean(), name, executable: external_exports.string().min(1).max(4096).optional() }).strict()
27047
27179
  ]);
27048
27180
  var PERMISSION_HISTORY_LIMIT = 64;
27049
27181
  var PermissionHistorySchema = external_exports.array(external_exports.object({
27050
- id: uuid14,
27182
+ id: uuid15,
27051
27183
  changedAt: external_exports.string().datetime(),
27052
- workspaceGrantId: uuid14,
27184
+ workspaceGrantId: uuid15,
27053
27185
  kind: external_exports.enum(["write", "command", "localhost"]),
27054
27186
  enabled: external_exports.boolean(),
27055
27187
  resourceHash: external_exports.string().regex(/^[a-f0-9]{64}$/),
@@ -27111,10 +27243,10 @@ async function planPermissionChange(current2, programs, input2) {
27111
27243
  let executableIdentity = null;
27112
27244
  if (change.enabled) {
27113
27245
  const executable = change.executable;
27114
- if (!path6.isAbsolute(executable) || process.platform === "win32" && path6.extname(executable).toLowerCase() !== ".exe" || /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/u.test(executable)) invalid2();
27246
+ if (!path7.isAbsolute(executable) || process.platform === "win32" && path7.extname(executable).toLowerCase() !== ".exe" || /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/u.test(executable)) invalid2();
27115
27247
  const stat2 = await lstat3(executable).catch(() => invalid2());
27116
27248
  const canonical2 = await realpath3(executable).catch(() => invalid2());
27117
- if (!stat2.isFile() || stat2.isSymbolicLink() || !equalPath(path6.resolve(executable), canonical2)) invalid2();
27249
+ if (!stat2.isFile() || stat2.isSymbolicLink() || !equalPath(path7.resolve(executable), canonical2)) invalid2();
27118
27250
  if (process.platform !== "win32") await access(canonical2, constants3.X_OK).catch(() => invalid2());
27119
27251
  if (Object.hasOwn(nextPrograms, change.name) && !equalPath(nextPrograms[change.name], canonical2)) invalid2("COMMAND_CONFLICT");
27120
27252
  nextPrograms[change.name] = canonical2;
@@ -27192,17 +27324,17 @@ async function choosePosixFolder() {
27192
27324
  return terminal2(async (ask) => {
27193
27325
  const folder = await ask("Local Commander: enter the absolute folder to allow reading and writing files (empty cancels): ");
27194
27326
  if (!folder) return null;
27195
- if (!path7.isAbsolute(folder) || folder.length > 4096 || /[\u0000-\u001f]/.test(folder)) throw Error("WORKSPACE_INVALID");
27327
+ if (!path8.isAbsolute(folder) || folder.length > 4096 || /[\u0000-\u001f]/.test(folder)) throw Error("WORKSPACE_INVALID");
27196
27328
  return await ask("Read/write folder: " + permissionLabel(folder) + "\nType APPROVE to accept: ") === "APPROVE" ? folder : null;
27197
27329
  }, 12e4);
27198
27330
  }
27199
27331
  async function choosePosixAccess() {
27200
27332
  return terminal2(async (ask) => {
27201
- if (process.platform === "darwin") await ask("This experimental macOS runtime supports files and localhost. Command execution and Git are unavailable pending process-cleanup qualification. Press Enter to review access: ");
27333
+ if (process.platform === "darwin") await ask("Local Commander runs each command as its own launchd job and stops that job's processes when the command ends; work handed to other services is not stopped. Press Enter to review access: ");
27202
27334
  const choice = await ask("Local Commander access\n1. One folder: read and write files\n2. Full Access: account capabilities across this computer, including commands and localhost\nEnter 1 or 2 (empty cancels): ");
27203
27335
  if (choice !== "1" && choice !== "2") return null;
27204
27336
  const folder = choice === "2" ? "/" : await ask("Absolute folder path: ");
27205
- if (!path7.isAbsolute(folder) || folder.length > 4096 || /[\u0000-\u001f]/.test(folder)) throw Error("WORKSPACE_INVALID");
27337
+ if (!path8.isAbsolute(folder) || folder.length > 4096 || /[\u0000-\u001f]/.test(folder)) throw Error("WORKSPACE_INVALID");
27206
27338
  const summary = choice === "2" ? "Full Access allows programs to use your account's capabilities across this computer. This is not an OS sandbox." : "Allow reading and writing files in " + permissionLabel(folder) + ".";
27207
27339
  if (await ask(summary + "\nThis replaces the previous folder/command/localhost selection and persists until revoked.\nType APPROVE to accept: ") !== "APPROVE") return null;
27208
27340
  return { mode: choice === "2" ? "all-drives" : "folders", paths: [folder] };
@@ -27210,14 +27342,14 @@ async function choosePosixAccess() {
27210
27342
  }
27211
27343
 
27212
27344
  // agent/src/private-store.ts
27213
- import { lstat as lstat4, open as open4, readFile as readFile3, readdir as readdir3, realpath as realpath4, rename as rename2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
27214
- import path9 from "node:path";
27345
+ import { lstat as lstat4, open as open4, readFile as readFile4, readdir as readdir3, realpath as realpath4, rename as rename2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
27346
+ import path10 from "node:path";
27215
27347
  import os2 from "node:os";
27216
27348
  import { createHash as createHash12, createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey4, generateKeyPairSync, randomBytes as randomBytes5, randomUUID as randomUUID6 } from "node:crypto";
27217
27349
  import { spawn as spawn3 } from "node:child_process";
27218
27350
 
27219
27351
  // agent/src/access-selection.ts
27220
- import path8 from "node:path";
27352
+ import path9 from "node:path";
27221
27353
  function parseAccessSelection(value, platform = process.platform) {
27222
27354
  const fail7 = () => {
27223
27355
  throw Error("ACCESS_SELECTION_INVALID");
@@ -27231,7 +27363,7 @@ function parseAccessSelection(value, platform = process.platform) {
27231
27363
  }
27232
27364
  if (input2.mode !== "folders" && input2.mode !== "all-drives") return fail7();
27233
27365
  if (input2.paths.length < 1 || input2.paths.length > (input2.mode === "folders" ? 1 : 26)) return fail7();
27234
- const paths = platform === "win32" ? path8.win32 : path8.posix;
27366
+ const paths = platform === "win32" ? path9.win32 : path9.posix;
27235
27367
  const key = (value2) => platform === "win32" ? paths.normalize(value2).toLowerCase() : paths.normalize(value2);
27236
27368
  const roots = [];
27237
27369
  for (const candidate of input2.paths) {
@@ -27250,7 +27382,7 @@ import { createHash as createHash10, KeyObject as KeyObject2 } from "node:crypto
27250
27382
  // packages/policy/src/evaluator.ts
27251
27383
  import { createHash as createHash9 } from "node:crypto";
27252
27384
  import { isDeepStrictEqual } from "node:util";
27253
- var uuid15 = external_exports.string().uuid().toLowerCase();
27385
+ var uuid16 = external_exports.string().uuid().toLowerCase();
27254
27386
  var slug2 = external_exports.string().regex(/^[a-z][a-z0-9._-]{0,63}$/);
27255
27387
  var utc = external_exports.iso.datetime({ offset: false });
27256
27388
  var risk = external_exports.enum(["low", "moderate", "high", "critical"]);
@@ -27275,7 +27407,7 @@ var PolicyRuleSchema = external_exports.object({
27275
27407
  }
27276
27408
  });
27277
27409
  var PolicySnapshotSchema = external_exports.object({
27278
- tenantId: uuid15,
27410
+ tenantId: uuid16,
27279
27411
  policyId: slug2,
27280
27412
  policyVersion: external_exports.string().trim().min(1).max(64),
27281
27413
  issuedAt: utc,
@@ -27389,14 +27521,14 @@ async function verifySignedPolicyBundle(candidate, authority, checkpointInput, n
27389
27521
 
27390
27522
  // packages/policy/src/approvals.ts
27391
27523
  import { createHash as createHash11, randomUUID as randomUUID5 } from "node:crypto";
27392
- var uuid16 = TrustedActionBindingSchema.shape.tenantId;
27524
+ var uuid17 = TrustedActionBindingSchema.shape.tenantId;
27393
27525
  var utc3 = TrustedActionBindingSchema.shape.expiresAt;
27394
27526
  var digest3 = ResourceRefSchema.shape.locatorFingerprint;
27395
27527
  var requirement = PolicyDecisionSchema.shape.approval.unwrap();
27396
27528
  var ApprovalActionSchema = external_exports.object({ request: BoundActionRequestSchema, payloadHash: digest3 }).strict();
27397
27529
  var ApprovalAuthoritySchema = external_exports.object({
27398
- tenantId: uuid16,
27399
- accountId: uuid16,
27530
+ tenantId: uuid17,
27531
+ accountId: uuid17,
27400
27532
  approvalClass: requirement.shape.approvalClass,
27401
27533
  authenticatedAt: utc3,
27402
27534
  expiresAt: utc3
@@ -27408,11 +27540,11 @@ var ContextSchema = external_exports.object({
27408
27540
  policyExpiresAt: utc3
27409
27541
  }).strict();
27410
27542
  var GrantSchema = external_exports.object({
27411
- approvalId: uuid16,
27412
- requestId: uuid16,
27413
- decisionId: uuid16,
27543
+ approvalId: uuid17,
27544
+ requestId: uuid17,
27545
+ decisionId: uuid17,
27414
27546
  bindingHash: digest3,
27415
- approverAccountId: uuid16,
27547
+ approverAccountId: uuid17,
27416
27548
  approvalClass: requirement.shape.approvalClass,
27417
27549
  scope: requirement.shape.scope,
27418
27550
  issuedAt: utc3,
@@ -27421,8 +27553,8 @@ var GrantSchema = external_exports.object({
27421
27553
  uses: external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
27422
27554
  }).strict().refine((value) => Date.parse(value.issuedAt) < Date.parse(value.expiresAt) && (value.scope === "once" ? value.uses === (value.state === "consumed" ? 1 : 0) : value.state !== "consumed"));
27423
27555
  var ApprovalLedgerSchema = external_exports.object({
27424
- tenantId: uuid16,
27425
- deviceId: uuid16,
27556
+ tenantId: uuid17,
27557
+ deviceId: uuid17,
27426
27558
  lastChangedAt: utc3,
27427
27559
  grants: external_exports.array(GrantSchema).max(128)
27428
27560
  }).strict().refine((value) => new Set(value.grants.map((grant) => grant.approvalId)).size === value.grants.length && new Set(value.grants.map((grant) => grant.requestId)).size === value.grants.length && value.grants.every((grant) => Date.parse(grant.issuedAt) <= Date.parse(value.lastChangedAt)));
@@ -27499,7 +27631,7 @@ function issueApproval(ledgerInput, context, authorityInput, now, expiresAt) {
27499
27631
  }
27500
27632
  function consumeApproval(ledgerInput, context, approvalId, now) {
27501
27633
  try {
27502
- const ledger = current(ledgerInput, now), bound = binding(ledger, context, now), id2 = uuid16.parse(approvalId);
27634
+ const ledger = current(ledgerInput, now), bound = binding(ledger, context, now), id2 = uuid17.parse(approvalId);
27503
27635
  const grant = ledger.grants.find((candidate) => candidate.approvalId === id2);
27504
27636
  if (!grant || grant.state !== "active" || grant.bindingHash !== bound.bindingHash || grant.uses === Number.MAX_SAFE_INTEGER || Date.parse(now) < Date.parse(grant.issuedAt) || grant.scope === "once" && (grant.requestId !== bound.request.requestId || grant.decisionId !== bound.decision.decisionId)) throw Error();
27505
27637
  const consumed = { ...grant, uses: grant.uses + 1, state: grant.scope === "once" ? "consumed" : "active" };
@@ -27510,7 +27642,7 @@ function consumeApproval(ledgerInput, context, approvalId, now) {
27510
27642
  }
27511
27643
  function revokeApproval(ledgerInput, approvalId, now) {
27512
27644
  try {
27513
- const ledger = current(ledgerInput, now), id2 = uuid16.parse(approvalId);
27645
+ const ledger = current(ledgerInput, now), id2 = uuid17.parse(approvalId);
27514
27646
  return { ...ledger, grants: ledger.grants.map((grant) => grant.approvalId === id2 && grant.state === "active" ? { ...grant, state: "revoked" } : grant) };
27515
27647
  } catch {
27516
27648
  throw Error("APPROVAL_INVALID");
@@ -27526,11 +27658,11 @@ function fail2(code) {
27526
27658
  return Object.assign(new Error(code), { code });
27527
27659
  }
27528
27660
  function equalPath2(a, b) {
27529
- return process.platform === "win32" ? path9.resolve(a).toLowerCase() === path9.resolve(b).toLowerCase() : path9.resolve(a) === path9.resolve(b);
27661
+ return process.platform === "win32" ? path10.resolve(a).toLowerCase() === path10.resolve(b).toLowerCase() : path10.resolve(a) === path10.resolve(b);
27530
27662
  }
27531
27663
  function under(child, parent) {
27532
- const rel = path9.relative(parent, child);
27533
- return rel !== "" && !rel.startsWith("..") && !path9.isAbsolute(rel);
27664
+ const rel = path10.relative(parent, child);
27665
+ return rel !== "" && !rel.startsWith("..") && !path10.isAbsolute(rel);
27534
27666
  }
27535
27667
  function canonicalPublicKey(value) {
27536
27668
  try {
@@ -27613,8 +27745,8 @@ function validateState(value) {
27613
27745
  const programs = value.programs ?? {};
27614
27746
  const pendingWorkspaceRevokes = value.pendingWorkspaceRevokes ?? [];
27615
27747
  if (!Array.isArray(pendingWorkspaceRevokes) || pendingWorkspaceRevokes.length > 32 || pendingWorkspaceRevokes.some((id2) => typeof id2 !== "string" || !UUID.test(id2) || id2 !== id2.toLowerCase()) || new Set(pendingWorkspaceRevokes).size !== pendingWorkspaceRevokes.length) throw fail2("STATE_CORRUPT");
27616
- if (!programs || typeof programs !== "object" || Array.isArray(programs) || Object.keys(programs).length > 32 || Object.entries(programs).some(([name2, executable]) => !/^[a-z0-9_.-]{1,64}$/.test(name2) || typeof executable !== "string" || !path9.isAbsolute(executable) || executable.length > 4096 || /[\u0000-\u001f]/.test(executable))) throw fail2("STATE_CORRUPT");
27617
- if (!Array.isArray(workspaces) || workspaces.length > 32 || workspaces.some((w) => !w || !UUID.test(w.workspaceGrantId) || typeof w.root !== "string" || !path9.isAbsolute(w.root) || w.root.length > 4096 || /[\u0000-\u001f]/.test(w.root) || !/^[a-f0-9]{64}$/.test(w.rootHash) || typeof w.displayName !== "string" || !w.displayName || w.displayName.length > 120 || w.policyVersion !== 1 || !w.permissions || w.permissions.readFiles !== true || typeof w.permissions.writeFiles !== "boolean" || typeof w.permissions.executeCommands !== "boolean" || typeof w.permissions.localhost !== "boolean" || !Array.isArray(w.allowedCommands) || w.allowedCommands.length > 32 || w.allowedCommands.some((name2) => typeof name2 !== "string" || !Object.hasOwn(programs, name2)) || new Set(w.allowedCommands).size !== w.allowedCommands.length || w.permissions.executeCommands !== (w.fullAccess === true || w.allowedCommands.length > 0) || !Array.isArray(w.localhostPorts) || w.localhostPorts.length > 32 || w.localhostPorts.some((port) => !Number.isInteger(port) || port < 1 || port > 65535) || new Set(w.localhostPorts).size !== w.localhostPorts.length || w.permissions.localhost !== (w.fullAccess === true || w.localhostPorts.length > 0))) throw fail2("STATE_CORRUPT");
27748
+ if (!programs || typeof programs !== "object" || Array.isArray(programs) || Object.keys(programs).length > 32 || Object.entries(programs).some(([name2, executable]) => !/^[a-z0-9_.-]{1,64}$/.test(name2) || typeof executable !== "string" || !path10.isAbsolute(executable) || executable.length > 4096 || /[\u0000-\u001f]/.test(executable))) throw fail2("STATE_CORRUPT");
27749
+ if (!Array.isArray(workspaces) || workspaces.length > 32 || workspaces.some((w) => !w || !UUID.test(w.workspaceGrantId) || typeof w.root !== "string" || !path10.isAbsolute(w.root) || w.root.length > 4096 || /[\u0000-\u001f]/.test(w.root) || !/^[a-f0-9]{64}$/.test(w.rootHash) || typeof w.displayName !== "string" || !w.displayName || w.displayName.length > 120 || w.policyVersion !== 1 || !w.permissions || w.permissions.readFiles !== true || typeof w.permissions.writeFiles !== "boolean" || typeof w.permissions.executeCommands !== "boolean" || typeof w.permissions.localhost !== "boolean" || !Array.isArray(w.allowedCommands) || w.allowedCommands.length > 32 || w.allowedCommands.some((name2) => typeof name2 !== "string" || !Object.hasOwn(programs, name2)) || new Set(w.allowedCommands).size !== w.allowedCommands.length || w.permissions.executeCommands !== (w.fullAccess === true || w.allowedCommands.length > 0) || !Array.isArray(w.localhostPorts) || w.localhostPorts.length > 32 || w.localhostPorts.some((port) => !Number.isInteger(port) || port < 1 || port > 65535) || new Set(w.localhostPorts).size !== w.localhostPorts.length || w.permissions.localhost !== (w.fullAccess === true || w.localhostPorts.length > 0))) throw fail2("STATE_CORRUPT");
27618
27750
  const audit = value.audit === void 0 ? void 0 : validateAudit(value.audit);
27619
27751
  if (new Set(workspaces.map((w) => w.workspaceGrantId)).size !== workspaces.length || new Set(workspaces.map((w) => w.rootHash)).size !== workspaces.length) throw fail2("STATE_CORRUPT");
27620
27752
  if (workspaces.some((w) => pendingWorkspaceRevokes.includes(w.workspaceGrantId))) throw fail2("STATE_CORRUPT");
@@ -27624,9 +27756,9 @@ function validateState(value) {
27624
27756
  return { version: 1, publicKeyPem: value.publicKeyPem, privateKeyPem: value.privateKeyPem, fingerprint: value.fingerprint, dataKey: value.dataKey, ...enrollment ? { enrollment } : {}, workspaces, programs, pendingWorkspaceRevokes, ...value.permissionHistory ? { permissionHistory: permissionHistory.data } : {}, ...policyBundle ? { policyBundle } : {}, ...approvals?.success ? { approvals: approvals.data } : {}, ...value.guardRequired ? { guardRequired: true } : {}, ...guard ? { guard } : {}, ...audit ? { audit } : {} };
27625
27757
  }
27626
27758
  async function noSymlinkChain(target) {
27627
- if (!path9.isAbsolute(target)) throw fail2("STORE_DIRECTORY_INVALID");
27628
- const absolute2 = path9.resolve(target);
27629
- if (absolute2 === path9.parse(absolute2).root) throw fail2("STORE_DIRECTORY_INVALID");
27759
+ if (!path10.isAbsolute(target)) throw fail2("STORE_DIRECTORY_INVALID");
27760
+ const absolute2 = path10.resolve(target);
27761
+ if (absolute2 === path10.parse(absolute2).root) throw fail2("STORE_DIRECTORY_INVALID");
27630
27762
  const missing = [];
27631
27763
  let cursor = absolute2;
27632
27764
  for (; ; ) {
@@ -27637,7 +27769,7 @@ async function noSymlinkChain(target) {
27637
27769
  } catch (error62) {
27638
27770
  if (error62.code !== "ENOENT") throw error62;
27639
27771
  missing.push(cursor);
27640
- const parent = path9.dirname(cursor);
27772
+ const parent = path10.dirname(cursor);
27641
27773
  if (parent === cursor) throw fail2("STORE_DIRECTORY_INVALID");
27642
27774
  cursor = parent;
27643
27775
  }
@@ -27647,15 +27779,15 @@ async function noSymlinkChain(target) {
27647
27779
  return absolute2;
27648
27780
  }
27649
27781
  function allowedDirectory(absolute2) {
27650
- const localAppData = process.env.LOCALAPPDATA || path9.join(os2.homedir(), "AppData", "Local");
27651
- const appRoot = path9.resolve(localAppData, "LocalCommander");
27652
- const tempRoot = path9.resolve(os2.tmpdir());
27782
+ const localAppData = process.env.LOCALAPPDATA || path10.join(os2.homedir(), "AppData", "Local");
27783
+ const appRoot = path10.resolve(localAppData, "LocalCommander");
27784
+ const tempRoot = path10.resolve(os2.tmpdir());
27653
27785
  if (under(absolute2, appRoot)) return;
27654
- if (under(absolute2, tempRoot) && /^lc-private-[A-Za-z0-9_.-]+$/i.test(path9.basename(absolute2))) return;
27786
+ if (under(absolute2, tempRoot) && /^lc-private-[A-Za-z0-9_.-]+$/i.test(path10.basename(absolute2))) return;
27655
27787
  throw fail2("STORE_DIRECTORY_POLICY");
27656
27788
  }
27657
27789
  async function canonicalBridge(value) {
27658
- if (typeof value !== "string" || !path9.isAbsolute(value) || path9.extname(value).toLowerCase() !== ".exe") throw fail2("BRIDGE_INVALID");
27790
+ if (typeof value !== "string" || !path10.isAbsolute(value) || path10.extname(value).toLowerCase() !== ".exe") throw fail2("BRIDGE_INVALID");
27659
27791
  const stat2 = await lstat4(value).catch(() => {
27660
27792
  throw fail2("BRIDGE_INVALID");
27661
27793
  });
@@ -27699,28 +27831,28 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
27699
27831
  const memoryFile = (name2) => name2 === "host-memory.json" || /^host-memory\.json\.[1-9][0-9]{0,9}\.tmp$/.test(name2);
27700
27832
  if (names.some((name2) => !approved.has(name2) && !memoryFile(name2))) throw fail2("STORE_DIRECTORY_UNKNOWN");
27701
27833
  for (const name2 of names.filter(memoryFile)) {
27702
- const stat2 = await lstat4(path9.join(absolute2, name2));
27834
+ const stat2 = await lstat4(path10.join(absolute2, name2));
27703
27835
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > 32768) throw fail2("STORE_DIRECTORY_INVALID");
27704
27836
  }
27705
27837
  for (const name2 of ["agent-process.json", "optimization", ".local-commander"]) {
27706
27838
  if (!names.includes(name2)) continue;
27707
- const filename = path9.join(absolute2, name2), stat2 = await lstat4(filename);
27839
+ const filename = path10.join(absolute2, name2), stat2 = await lstat4(filename);
27708
27840
  if (stat2.isSymbolicLink() || (name2 !== "agent-process.json" ? !stat2.isDirectory() : !stat2.isFile() || stat2.size < 1 || stat2.size > 8192)) throw fail2("STORE_DIRECTORY_INVALID");
27709
27841
  if (name2 === "agent-process.json") {
27710
27842
  let value;
27711
27843
  try {
27712
- value = JSON.parse(await readFile3(filename, "utf8"));
27844
+ value = JSON.parse(await readFile4(filename, "utf8"));
27713
27845
  } catch {
27714
27846
  throw fail2("STORE_DIRECTORY_INVALID");
27715
27847
  }
27716
- if (!value || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.runtimeDir !== "string" || !path9.isAbsolute(value.runtimeDir) || value.runtimeDir.length > 4096 || /[\u0000-\u001f]/.test(value.runtimeDir) || typeof value.version !== "string" || !/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.version) || typeof value.startedAt !== "string" || !Number.isFinite(Date.parse(value.startedAt))) throw fail2("STORE_DIRECTORY_INVALID");
27848
+ if (!value || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.runtimeDir !== "string" || !path10.isAbsolute(value.runtimeDir) || value.runtimeDir.length > 4096 || /[\u0000-\u001f]/.test(value.runtimeDir) || typeof value.version !== "string" || !/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.version) || typeof value.startedAt !== "string" || !Number.isFinite(Date.parse(value.startedAt))) throw fail2("STORE_DIRECTORY_INVALID");
27717
27849
  }
27718
27850
  }
27719
27851
  const posix = process.platform !== "win32" ? await PosixProtection.open(absolute2, bridge) : void 0;
27720
27852
  if (!posix) await _WindowsPrivateStore.invoke(bridge, "init-directory", { path: absolute2 }, 5e3, false);
27721
27853
  const canonical2 = await realpath4(absolute2);
27722
27854
  if (!equalPath2(absolute2, canonical2) || (await lstat4(canonical2)).isSymbolicLink()) throw fail2("STORE_DIRECTORY_INVALID");
27723
- const markerPath = path9.join(canonical2, MARKER);
27855
+ const markerPath = path10.join(canonical2, MARKER);
27724
27856
  try {
27725
27857
  await writeFile2(markerPath, "LocalCommander private state\n", { flag: "wx", mode: 384 });
27726
27858
  } catch (error62) {
@@ -27738,10 +27870,10 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
27738
27870
  return result2;
27739
27871
  }
27740
27872
  statePath() {
27741
- return path9.join(this.dir, "owner-state.dat");
27873
+ return path10.join(this.dir, "owner-state.dat");
27742
27874
  }
27743
27875
  lockPath() {
27744
- return path9.join(this.dir, "owner-state.lock");
27876
+ return path10.join(this.dir, "owner-state.lock");
27745
27877
  }
27746
27878
  static invoke(bridge, arg, body, timeoutMs2, interactive, signal) {
27747
27879
  return new Promise((resolve, reject) => {
@@ -27832,7 +27964,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
27832
27964
  await handle.close().catch(() => {
27833
27965
  });
27834
27966
  try {
27835
- const current2 = await readFile3(this.lockPath(), "utf8");
27967
+ const current2 = await readFile4(this.lockPath(), "utf8");
27836
27968
  if (current2 === nonce2) await rm3(this.lockPath());
27837
27969
  } catch {
27838
27970
  }
@@ -27854,7 +27986,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
27854
27986
  try {
27855
27987
  const stat2 = await lstat4(this.statePath());
27856
27988
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size < 1 || stat2.size > MAX_STATE_BYTES * 4) throw fail2("STATE_CORRUPT");
27857
- const encrypted = this.posix ? await privateRead(this.statePath(), MAX_STATE_BYTES * 4) : await readFile3(this.statePath());
27989
+ const encrypted = this.posix ? await privateRead(this.statePath(), MAX_STATE_BYTES * 4) : await readFile4(this.statePath());
27858
27990
  const plaintext = await this.unprotect(encrypted);
27859
27991
  if (plaintext.length > MAX_STATE_BYTES) throw fail2("STATE_CORRUPT");
27860
27992
  return validateState(JSON.parse(plaintext.toString("utf8")));
@@ -27868,7 +28000,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
27868
28000
  try {
27869
28001
  const stat2 = await lstat4(this.statePath());
27870
28002
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > MAX_STATE_BYTES * 4) throw fail2("STATE_CORRUPT");
27871
- return createHash12("sha256").update(this.posix ? await privateRead(this.statePath(), MAX_STATE_BYTES * 4) : await readFile3(this.statePath())).digest("hex");
28003
+ return createHash12("sha256").update(this.posix ? await privateRead(this.statePath(), MAX_STATE_BYTES * 4) : await readFile4(this.statePath())).digest("hex");
27872
28004
  } catch (error62) {
27873
28005
  if (error62.code === "ENOENT") return null;
27874
28006
  throw error62;
@@ -27879,7 +28011,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
27879
28011
  const plaintext = Buffer.from(JSON.stringify(validateState(state)), "utf8");
27880
28012
  if (plaintext.length > MAX_STATE_BYTES) throw fail2("STATE_TOO_LARGE");
27881
28013
  const encrypted = await this.protect(plaintext);
27882
- const temp = path9.join(this.dir, "owner-state." + randomBytes5(8).toString("hex") + ".tmp");
28014
+ const temp = path10.join(this.dir, "owner-state." + randomBytes5(8).toString("hex") + ".tmp");
27883
28015
  const handle = await open4(temp, constants4.O_CREAT | constants4.O_EXCL | constants4.O_WRONLY, 384);
27884
28016
  let closed = false;
27885
28017
  try {
@@ -28238,11 +28370,14 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28238
28370
  }
28239
28371
  /** Replace scope only after an explicit local dialog; updates never call this implicitly. */
28240
28372
  async configureAccess() {
28373
+ let account = "";
28241
28374
  const expected = await this.run(() => this.withLock(async () => {
28242
- if (!(await this.readState())?.enrollment) throw fail2("ENROLLMENT_REQUIRED");
28375
+ const enrollment = (await this.readState())?.enrollment;
28376
+ if (!enrollment) throw fail2("ENROLLMENT_REQUIRED");
28377
+ account = enrollment.accountEmail;
28243
28378
  return this.rawHash();
28244
28379
  }));
28245
- const decision = await this.chooseAccess();
28380
+ const decision = await this.chooseAccess(account);
28246
28381
  if (decision === null) return null;
28247
28382
  const selected = parseAccessSelection(decision);
28248
28383
  if (!selected) return null;
@@ -28251,7 +28386,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28251
28386
  const stat2 = await lstat4(chosen);
28252
28387
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw fail2("WORKSPACE_INVALID");
28253
28388
  const root = await realpath4(chosen);
28254
- const isDrive = equalPath2(root, path9.parse(root).root);
28389
+ const isDrive = equalPath2(root, path10.parse(root).root);
28255
28390
  if (!equalPath2(root, chosen) || (selected.mode === "all-drives" ? !isDrive : isDrive) || equalPath2(root, this.dir) || under(root, this.dir) || selected.mode === "folders" && under(this.dir, root)) throw fail2("WORKSPACE_INVALID");
28256
28391
  roots.push(root);
28257
28392
  }
@@ -28266,7 +28401,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28266
28401
  workspaceGrantId: existing?.workspaceGrantId ?? randomUUID6(),
28267
28402
  root,
28268
28403
  rootHash,
28269
- displayName: (path9.basename(root) || root).slice(0, 120),
28404
+ displayName: (path10.basename(root) || root).slice(0, 120),
28270
28405
  policyVersion: 1,
28271
28406
  ...selected.mode === "all-drives" ? { fullAccess: true } : {},
28272
28407
  permissions: { readFiles: true, writeFiles: true, executeCommands: selected.mode === "all-drives", localhost: selected.mode === "all-drives" },
@@ -28285,9 +28420,9 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28285
28420
  return structuredClone(workspaces);
28286
28421
  }));
28287
28422
  }
28288
- chooseAccess() {
28423
+ chooseAccess(account) {
28289
28424
  if (this.posix) return this.run(() => choosePosixAccess());
28290
- return this.run(async () => parseAccessSelection(await _WindowsPrivateStore.invoke(this.bridge, "choose-access", {}, 24e4, true)));
28425
+ return this.run(async () => parseAccessSelection(await _WindowsPrivateStore.invoke(this.bridge, "choose-access", { data: Buffer.from(account, "utf8").toString("base64") }, 24e4, true)));
28291
28426
  }
28292
28427
  loadPermissionHistory() {
28293
28428
  return this.run(async () => structuredClone((await this.readState())?.permissionHistory ?? []));
@@ -28298,7 +28433,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28298
28433
  const stat2 = await lstat4(chosen);
28299
28434
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw fail2("WORKSPACE_INVALID");
28300
28435
  const root = await realpath4(chosen);
28301
- if (!equalPath2(root, chosen) || equalPath2(root, path9.parse(root).root) || equalPath2(root, this.dir) || under(this.dir, root)) throw fail2("WORKSPACE_INVALID");
28436
+ if (!equalPath2(root, chosen) || equalPath2(root, path10.parse(root).root) || equalPath2(root, this.dir) || under(this.dir, root)) throw fail2("WORKSPACE_INVALID");
28302
28437
  const rootHash = createHash12("sha256").update(process.platform === "win32" ? root.toLowerCase() : root).digest("hex");
28303
28438
  return this.run(() => this.withLock(async () => {
28304
28439
  const state = await this.readState();
@@ -28307,7 +28442,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28307
28442
  if (existing) return existing;
28308
28443
  if ((state.workspaces?.length ?? 0) >= 32) throw fail2("WORKSPACE_LIMIT");
28309
28444
  const before = await this.rawHash();
28310
- const workspace2 = { workspaceGrantId: randomUUID6(), root, rootHash, displayName: path9.basename(root).slice(0, 120), policyVersion: 1, permissions: { readFiles: true, writeFiles: true, executeCommands: false, localhost: false }, allowedCommands: [], localhostPorts: [] };
28445
+ const workspace2 = { workspaceGrantId: randomUUID6(), root, rootHash, displayName: path10.basename(root).slice(0, 120), policyVersion: 1, permissions: { readFiles: true, writeFiles: true, executeCommands: false, localhost: false }, allowedCommands: [], localhostPorts: [] };
28311
28446
  state.workspaces = [...state.workspaces ?? [], workspace2];
28312
28447
  await this.writeState(state, before);
28313
28448
  return workspace2;
@@ -28318,7 +28453,7 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28318
28453
  return this.run(async () => {
28319
28454
  const result2 = await _WindowsPrivateStore.invoke(this.bridge, "choose-folder", {}, 12e4, true);
28320
28455
  if (result2.path === null) return null;
28321
- if (typeof result2.path !== "string" || !path9.isAbsolute(result2.path) || result2.path.length > 4096 || /[\u0000-\u001f]/.test(result2.path)) throw fail2("BRIDGE_OUTPUT_INVALID");
28456
+ if (typeof result2.path !== "string" || !path10.isAbsolute(result2.path) || result2.path.length > 4096 || /[\u0000-\u001f]/.test(result2.path)) throw fail2("BRIDGE_OUTPUT_INVALID");
28322
28457
  return result2.path;
28323
28458
  });
28324
28459
  }
@@ -28326,10 +28461,10 @@ var WindowsPrivateStore = class _WindowsPrivateStore {
28326
28461
 
28327
28462
  // src/host-memory.ts
28328
28463
  import os3 from "node:os";
28329
- import path11 from "node:path";
28464
+ import path12 from "node:path";
28330
28465
  import { createHash as createHash13 } from "node:crypto";
28331
28466
  import { accessSync, constants as constants5, statSync as statSync2 } from "node:fs";
28332
- import { lstat as lstat5, readFile as readFile4, mkdir as mkdir5, open as open5, rename as rename3, rm as rm4 } from "node:fs/promises";
28467
+ import { lstat as lstat5, readFile as readFile5, mkdir as mkdir5, open as open5, rename as rename3, rm as rm4 } from "node:fs/promises";
28333
28468
 
28334
28469
  // packages/agent-cli/bin/monitor-context.mjs
28335
28470
  var AGENT_NAMES = Object.freeze([
@@ -28513,7 +28648,7 @@ function commandPreview(tool, meta3 = {}) {
28513
28648
 
28514
28649
  // src/process.ts
28515
28650
  import { statSync } from "node:fs";
28516
- import path10 from "node:path";
28651
+ import path11 from "node:path";
28517
28652
  var WINDOWS_LAUNCH_EXTENSIONS = [".com", ".exe", ".bat", ".cmd"];
28518
28653
  function envValue(env, name2) {
28519
28654
  const key = Object.keys(env).find((k) => k.toUpperCase() === name2.toUpperCase());
@@ -28523,9 +28658,9 @@ function resolveWindowsLauncher(commandName, env = process.env) {
28523
28658
  const extensions = (envValue(env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD").split(";").map((ext) => ext.trim().toLowerCase()).filter((ext) => WINDOWS_LAUNCH_EXTENSIONS.includes(ext));
28524
28659
  for (const entry of (envValue(env, "PATH") ?? "").split(";")) {
28525
28660
  const dir = entry.trim().replace(/^"(.*)"$/, "$1");
28526
- if (!path10.win32.isAbsolute(dir)) continue;
28661
+ if (!path11.win32.isAbsolute(dir)) continue;
28527
28662
  for (const ext of extensions) {
28528
- const file2 = path10.win32.join(dir, commandName + ext);
28663
+ const file2 = path11.win32.join(dir, commandName + ext);
28529
28664
  try {
28530
28665
  if (statSync(file2).isFile()) return { file: file2, shell: ext === ".bat" || ext === ".cmd" };
28531
28666
  } catch {
@@ -28566,7 +28701,7 @@ var HostMemory = class {
28566
28701
  try {
28567
28702
  const stat2 = await lstat5(this.file);
28568
28703
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > 32768) throw Error("HOST_MEMORY_INVALID");
28569
- const data = State.parse(JSON.parse(await readFile4(this.file, "utf8")));
28704
+ const data = State.parse(JSON.parse(await readFile5(this.file, "utf8")));
28570
28705
  if (data.platform === process.platform) this.entries = data.entries.filter((e) => e.at <= Date.now() && Date.now() - e.at < 30 * 864e5);
28571
28706
  } catch (error62) {
28572
28707
  if (error62.code !== "ENOENT") this.errors++;
@@ -28580,16 +28715,16 @@ var HostMemory = class {
28580
28715
  if (this.programs) {
28581
28716
  try {
28582
28717
  const executable = this.programs[command];
28583
- available = !!executable && path11.isAbsolute(executable) && statSync2(executable).isFile();
28718
+ available = !!executable && path12.isAbsolute(executable) && statSync2(executable).isFile();
28584
28719
  } catch {
28585
28720
  available = false;
28586
28721
  }
28587
28722
  }
28588
28723
  if (!this.programs && !available && process.platform === "win32") available = !!resolveWindowsLauncher(command);
28589
- else if (!this.programs && !available) available = (process.env.PATH ?? "").split(path11.delimiter).some((dir) => {
28590
- if (!path11.isAbsolute(dir)) return false;
28724
+ else if (!this.programs && !available) available = (process.env.PATH ?? "").split(path12.delimiter).some((dir) => {
28725
+ if (!path12.isAbsolute(dir)) return false;
28591
28726
  try {
28592
- const file2 = path11.join(dir, command);
28727
+ const file2 = path12.join(dir, command);
28593
28728
  accessSync(file2, constants5.X_OK);
28594
28729
  return statSync2(file2).isFile();
28595
28730
  } catch {
@@ -28647,7 +28782,7 @@ var HostMemory = class {
28647
28782
  this.entries = this.entries.slice(-32);
28648
28783
  const encoded = JSON.stringify({ version: 1, platform: process.platform, entries: this.entries }) + "\n";
28649
28784
  this.writing = this.writing.then(async () => {
28650
- const directory2 = path11.dirname(this.file), temp = this.file + "." + process.pid + ".tmp";
28785
+ const directory2 = path12.dirname(this.file), temp = this.file + "." + process.pid + ".tmp";
28651
28786
  await mkdir5(directory2, { recursive: true, mode: 448 });
28652
28787
  const stat2 = await lstat5(directory2);
28653
28788
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw Error("HOST_MEMORY_DIRECTORY_INVALID");
@@ -28671,12 +28806,12 @@ var HostMemory = class {
28671
28806
  // agent/src/tools.ts
28672
28807
  import { constants as constants7 } from "node:fs";
28673
28808
  import { lstat as lstat7, open as open6, readdir as readdir4, realpath as realpath7, rename as rename4, rm as rm5 } from "node:fs/promises";
28674
- import path16 from "node:path";
28809
+ import path17 from "node:path";
28675
28810
  import { createHash as createHash14, randomUUID as randomUUID7 } from "node:crypto";
28676
28811
 
28677
28812
  // src/guard.ts
28678
28813
  import { lstat as lstat6, realpath as realpath5 } from "node:fs/promises";
28679
- import path12 from "node:path";
28814
+ import path13 from "node:path";
28680
28815
  var SENSITIVE_NAMES = /* @__PURE__ */ new Set([
28681
28816
  ".npmrc",
28682
28817
  ".pypirc",
@@ -28713,12 +28848,12 @@ function comparePath(value) {
28713
28848
  return process.platform === "win32" ? value.toLowerCase() : value;
28714
28849
  }
28715
28850
  function isInside(root, candidate) {
28716
- const relative = path12.relative(root, candidate);
28717
- return relative === "" || !path12.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path12.sep}`);
28851
+ const relative = path13.relative(root, candidate);
28852
+ return relative === "" || !path13.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path13.sep}`);
28718
28853
  }
28719
28854
  function splitPathSegments(filePath) {
28720
- const parsed = path12.parse(path12.resolve(filePath));
28721
- return path12.relative(parsed.root, path12.resolve(filePath)).split(path12.sep).filter((segment) => segment.length > 0);
28855
+ const parsed = path13.parse(path13.resolve(filePath));
28856
+ return path13.relative(parsed.root, path13.resolve(filePath)).split(path13.sep).filter((segment) => segment.length > 0);
28722
28857
  }
28723
28858
  function isProtectedAuditFile(base) {
28724
28859
  return base === ".local-commander-audit.jsonl" || base.startsWith(".local-commander-audit.jsonl.");
@@ -28733,24 +28868,24 @@ function looksProtected(filePath) {
28733
28868
  return false;
28734
28869
  }
28735
28870
  function looksSensitive(filePath) {
28736
- const base = path12.basename(filePath).toLowerCase();
28871
+ const base = path13.basename(filePath).toLowerCase();
28737
28872
  if (base === ".env" || base.startsWith(".env.") && base !== ".env.example") return true;
28738
28873
  if (SENSITIVE_NAMES.has(base)) return true;
28739
- if (SENSITIVE_EXTENSIONS.has(path12.extname(base))) return true;
28874
+ if (SENSITIVE_EXTENSIONS.has(path13.extname(base))) return true;
28740
28875
  const segments = splitPathSegments(filePath).map((segment) => segment.toLowerCase());
28741
28876
  if (segments.slice(0, -1).some((segment) => SENSITIVE_DIRECTORIES.has(segment))) return true;
28742
28877
  const parent = segments.at(-2);
28743
28878
  return SENSITIVE_IN_DIRECTORY.some(([directory, name2]) => directory === parent && name2 === base);
28744
28879
  }
28745
28880
  async function canonicalizePossiblyMissing(inputPath, base) {
28746
- const absolute2 = path12.isAbsolute(inputPath) ? path12.resolve(inputPath) : path12.resolve(base, inputPath);
28747
- const parsed = path12.parse(absolute2);
28881
+ const absolute2 = path13.isAbsolute(inputPath) ? path13.resolve(inputPath) : path13.resolve(base, inputPath);
28882
+ const parsed = path13.parse(absolute2);
28748
28883
  let current2 = absolute2;
28749
28884
  const missing = [];
28750
28885
  while (current2 !== parsed.root) {
28751
28886
  try {
28752
28887
  const resolved = await realpath5(current2);
28753
- return path12.join(resolved, ...missing.reverse());
28888
+ return path13.join(resolved, ...missing.reverse());
28754
28889
  } catch (error62) {
28755
28890
  if (error62.code !== "ENOENT") throw error62;
28756
28891
  let exists = false;
@@ -28761,12 +28896,12 @@ async function canonicalizePossiblyMissing(inputPath, base) {
28761
28896
  if (statError.code !== "ENOENT") throw statError;
28762
28897
  }
28763
28898
  if (exists) throw error62;
28764
- missing.push(path12.basename(current2));
28765
- current2 = path12.dirname(current2);
28899
+ missing.push(path13.basename(current2));
28900
+ current2 = path13.dirname(current2);
28766
28901
  }
28767
28902
  }
28768
28903
  const root = await realpath5(parsed.root);
28769
- return path12.join(root, ...missing.reverse());
28904
+ return path13.join(root, ...missing.reverse());
28770
28905
  }
28771
28906
  var PathGuard = class _PathGuard {
28772
28907
  constructor(roots, allowSensitiveFiles, protectedPaths) {
@@ -28782,7 +28917,7 @@ var PathGuard = class _PathGuard {
28782
28917
  for (const root of roots) {
28783
28918
  let resolved;
28784
28919
  try {
28785
- resolved = await realpath5(path12.resolve(root));
28920
+ resolved = await realpath5(path13.resolve(root));
28786
28921
  } catch {
28787
28922
  throw new Error(`Configured root does not exist: ${root}`);
28788
28923
  }
@@ -28795,8 +28930,8 @@ var PathGuard = class _PathGuard {
28795
28930
  if (canonical2.length === 0) throw new Error("At least one allowed root is required");
28796
28931
  const protectedPaths = [];
28797
28932
  for (const protectedPath of options.protectedPaths ?? []) {
28798
- const base = path12.isAbsolute(protectedPath) ? path12.parse(path12.resolve(protectedPath)).root : canonical2[0];
28799
- const absolute2 = path12.resolve(base, protectedPath);
28933
+ const base = path13.isAbsolute(protectedPath) ? path13.parse(path13.resolve(protectedPath)).root : canonical2[0];
28934
+ const absolute2 = path13.resolve(base, protectedPath);
28800
28935
  if (!protectedPaths.some((existing) => comparePath(existing) === comparePath(absolute2))) protectedPaths.push(absolute2);
28801
28936
  const resolved = await canonicalizePossiblyMissing(protectedPath, base);
28802
28937
  if (!protectedPaths.some((existing) => comparePath(existing) === comparePath(resolved))) {
@@ -28812,7 +28947,7 @@ var PathGuard = class _PathGuard {
28812
28947
  }
28813
28948
  assertNotProtected(candidate) {
28814
28949
  if (looksProtected(candidate)) {
28815
- throw new Error(`Local Commander protected state is blocked: ${path12.basename(candidate)}`);
28950
+ throw new Error(`Local Commander protected state is blocked: ${path13.basename(candidate)}`);
28816
28951
  }
28817
28952
  const normalizedCandidate = comparePath(candidate);
28818
28953
  for (const protectedPath of this.protectedPaths) {
@@ -28825,13 +28960,13 @@ var PathGuard = class _PathGuard {
28825
28960
  this.assertNotProtected(filePath);
28826
28961
  if (!this.allowSensitiveFiles && looksSensitive(filePath)) {
28827
28962
  throw new Error(
28828
- `Sensitive file access is blocked by default: ${path12.basename(filePath)}. Enable files.allowSensitiveFiles only if you really need it.`
28963
+ `Sensitive file access is blocked by default: ${path13.basename(filePath)}. Enable files.allowSensitiveFiles only if you really need it.`
28829
28964
  );
28830
28965
  }
28831
28966
  }
28832
28967
  async resolveExisting(inputPath, cwd) {
28833
28968
  const base = cwd ? await this.resolveExisting(cwd) : this.roots[0];
28834
- const candidate = path12.isAbsolute(inputPath) ? path12.resolve(inputPath) : path12.resolve(base, inputPath);
28969
+ const candidate = path13.isAbsolute(inputPath) ? path13.resolve(inputPath) : path13.resolve(base, inputPath);
28835
28970
  this.assertNotProtected(candidate);
28836
28971
  const resolved = await realpath5(candidate);
28837
28972
  this.assertWithinRoots(resolved);
@@ -28846,7 +28981,7 @@ var PathGuard = class _PathGuard {
28846
28981
  }
28847
28982
  async resolveForWrite(inputPath, cwd) {
28848
28983
  const base = cwd ? await this.resolveDirectory(cwd) : this.roots[0];
28849
- const candidate = path12.isAbsolute(inputPath) ? path12.resolve(inputPath) : path12.resolve(base, inputPath);
28984
+ const candidate = path13.isAbsolute(inputPath) ? path13.resolve(inputPath) : path13.resolve(base, inputPath);
28850
28985
  this.assertNotProtected(candidate);
28851
28986
  let existing;
28852
28987
  try {
@@ -28868,11 +29003,11 @@ var PathGuard = class _PathGuard {
28868
29003
  this.assertSafeFile(existing);
28869
29004
  return existing;
28870
29005
  }
28871
- const parent = await realpath5(path12.dirname(candidate));
29006
+ const parent = await realpath5(path13.dirname(candidate));
28872
29007
  this.assertWithinRoots(parent);
28873
29008
  this.assertNotProtected(parent);
28874
29009
  this.assertSafeFile(candidate);
28875
- const target = path12.join(parent, path12.basename(candidate));
29010
+ const target = path13.join(parent, path13.basename(candidate));
28876
29011
  this.assertSafeFile(target);
28877
29012
  return target;
28878
29013
  }
@@ -28882,8 +29017,8 @@ var PathGuard = class _PathGuard {
28882
29017
  };
28883
29018
 
28884
29019
  // src/windows-file-read.ts
28885
- import { execFile } from "node:child_process";
28886
- import path13 from "node:path";
29020
+ import { execFile as execFile3 } from "node:child_process";
29021
+ import path14 from "node:path";
28887
29022
  function readWindowsFile(bridge, file2, maxBytes, signal) {
28888
29023
  return invokeRead(bridge, file2, maxBytes, false, signal);
28889
29024
  }
@@ -28899,13 +29034,52 @@ async function readWindowsFilePrefix(bridge, file2, maxBytes, signal) {
28899
29034
  throw new Error("FILE_READ_FAILED");
28900
29035
  }
28901
29036
  }
29037
+ function readWindowsFiles(bridge, files, maxBytes, maxTotalBytes, signal) {
29038
+ const input2 = JSON.stringify({ paths: files });
29039
+ if (process.platform !== "win32" || !path14.isAbsolute(bridge) || files.length < 1 || files.length > 64 || files.some((file2) => !path14.isAbsolute(file2)) || Buffer.byteLength(input2) > 3e5 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576 || !Number.isSafeInteger(maxTotalBytes) || maxTotalBytes < 1 || maxTotalBytes > 16777216) {
29040
+ return Promise.reject(new Error("FILE_READ_ARGUMENT_INVALID"));
29041
+ }
29042
+ if (signal?.aborted) return Promise.reject(new Error("CANCELLED"));
29043
+ return new Promise((resolve, reject) => {
29044
+ const child = execFile3(bridge, ["read-files", String(maxBytes), String(maxTotalBytes)], {
29045
+ encoding: "buffer",
29046
+ timeout: 3e4,
29047
+ maxBuffer: Math.ceil(maxTotalBytes / 3) * 4 + files.length * 64 + 512,
29048
+ windowsHide: true,
29049
+ shell: false,
29050
+ env: buildChildEnvironment(process.env, "win32"),
29051
+ signal
29052
+ }, (error62, stdout) => {
29053
+ if (error62) return reject(new Error(signal?.aborted ? "CANCELLED" : "FILE_READ_FAILED"));
29054
+ try {
29055
+ const lines = stdout.toString("utf8").split("\n");
29056
+ if (lines.pop() !== "" || lines.length !== files.length) throw Error();
29057
+ let total = 0;
29058
+ resolve(lines.map((line) => {
29059
+ const value = JSON.parse(line);
29060
+ if (!value || Object.keys(value).length !== 1) throw Error();
29061
+ if (/^(ENOENT|FILE_CHANGED|FILE_UNSUPPORTED_OR_TOO_LARGE|PATH_INVALID|ACCESS_DENIED|IO_FAILED)$/.test(value.error)) return { code: value.error };
29062
+ if (typeof value.data !== "string") throw Error();
29063
+ const data = Buffer.from(value.data, "base64");
29064
+ if (data.toString("base64") !== value.data || data.length > maxBytes || (total += data.length) > maxTotalBytes) throw Error();
29065
+ return { data };
29066
+ }));
29067
+ } catch {
29068
+ reject(new Error("FILE_READ_FAILED"));
29069
+ }
29070
+ });
29071
+ child.stdin.on("error", () => {
29072
+ });
29073
+ child.stdin.end(input2);
29074
+ });
29075
+ }
28902
29076
  function invokeRead(bridge, file2, maxBytes, prefix, signal) {
28903
- if (process.platform !== "win32" || !path13.isAbsolute(bridge) || !path13.isAbsolute(file2) || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > (prefix ? 16777216 : 1048576)) {
29077
+ if (process.platform !== "win32" || !path14.isAbsolute(bridge) || !path14.isAbsolute(file2) || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > (prefix ? 16777216 : 1048576)) {
28904
29078
  return Promise.reject(new Error("FILE_READ_ARGUMENT_INVALID"));
28905
29079
  }
28906
29080
  if (signal?.aborted) return Promise.reject(new Error("CANCELLED"));
28907
29081
  return new Promise((resolve, reject) => {
28908
- const child = execFile(bridge, prefix ? ["read-prefix", String(maxBytes)] : ["read-file"], {
29082
+ const child = execFile3(bridge, prefix ? ["read-prefix", String(maxBytes)] : ["read-file"], {
28909
29083
  encoding: "buffer",
28910
29084
  timeout: 1e4,
28911
29085
  maxBuffer: prefix ? Math.ceil(maxBytes / 3) * 4 + 512 : 1048576,
@@ -28930,10 +29104,10 @@ function invokeRead(bridge, file2, maxBytes, prefix, signal) {
28930
29104
  // agent/src/posix-platform.ts
28931
29105
  import { constants as constants6 } from "node:fs";
28932
29106
  import { access as access2, realpath as realpath6, stat } from "node:fs/promises";
28933
- import path14 from "node:path";
29107
+ import path15 from "node:path";
28934
29108
  async function resolvePosixExecutable(command, searchPath = process.env.PATH ?? "") {
28935
29109
  if (!command || /[\u0000-\u001f]/.test(command)) return null;
28936
- const candidates = path14.posix.isAbsolute(command) ? [command] : /^[\w.-]+$/.test(command) ? searchPath.split(":").filter((directory) => path14.posix.isAbsolute(directory)).map((directory) => path14.posix.join(directory, command)) : [];
29110
+ const candidates = path15.posix.isAbsolute(command) ? [command] : /^[\w.-]+$/.test(command) ? searchPath.split(":").filter((directory) => path15.posix.isAbsolute(directory)).map((directory) => path15.posix.join(directory, command)) : [];
28937
29111
  for (const candidate of candidates) {
28938
29112
  try {
28939
29113
  const canonical2 = await realpath6(candidate);
@@ -28949,12 +29123,12 @@ async function resolvePosixExecutable(command, searchPath = process.env.PATH ??
28949
29123
 
28950
29124
  // agent/src/job-supervisor.ts
28951
29125
  import { spawn as spawn4 } from "node:child_process";
28952
- import path15 from "node:path";
29126
+ import path16 from "node:path";
28953
29127
  function absolute(value) {
28954
- return typeof value === "string" && value.length > 0 && value.length < 32767 && !value.includes("\0") && path15.isAbsolute(value) && path15.resolve(value) === value;
29128
+ return typeof value === "string" && value.length > 0 && value.length < 32767 && !value.includes("\0") && path16.isAbsolute(value) && path16.resolve(value) === value;
28955
29129
  }
28956
29130
  async function runSupervised(helper, request, options = {}) {
28957
- if (process.platform !== "win32" && process.platform !== "linux") throw Error("SUPERVISOR_PLATFORM_UNSUPPORTED");
29131
+ if (process.platform !== "win32" && process.platform !== "linux" && process.platform !== "darwin") throw Error("SUPERVISOR_PLATFORM_UNSUPPORTED");
28958
29132
  if (!absolute(helper) || !absolute(request.executable) || !absolute(request.cwd)) throw new TypeError("INVALID_SUPERVISOR_PATH");
28959
29133
  const args = request.args ?? [], timeoutMs2 = request.timeoutMs ?? 6e4, maxProcesses = request.maxProcesses ?? 16, maxBytes = options.maxOutputBytes ?? 98304;
28960
29134
  if (!Array.isArray(args) || args.length > 128 || args.some((v) => typeof v !== "string" || v.length > 8192 || v.includes("\0"))) throw new TypeError("INVALID_SUPERVISOR_ARGS");
@@ -28966,8 +29140,9 @@ async function runSupervised(helper, request, options = {}) {
28966
29140
  const stdout = new Utf8OutputTailBuffer(maxBytes, options.encoding), stderr = new Utf8OutputTailBuffer(maxBytes, options.encoding);
28967
29141
  let pid = null, outcome = null;
28968
29142
  let buffer = "", failure6 = null, closed = false, cancelSent = false;
29143
+ let containmentReceived = false, containmentSaved = process.platform === "win32";
28969
29144
  let killTimer, hardTimer;
28970
- const child = spawn4(process.platform === "linux" ? process.execPath : helper, process.platform === "linux" ? [helper] : [], { cwd: path15.dirname(helper), stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: false, env: buildChildEnvironment(process.env) });
29145
+ const child = spawn4(process.platform === "win32" ? helper : process.execPath, process.platform === "win32" ? [] : [helper], { cwd: path16.dirname(helper), stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: false, env: buildChildEnvironment(process.env) });
28971
29146
  const cancel = () => {
28972
29147
  if (closed || cancelSent) return;
28973
29148
  cancelSent = true;
@@ -29005,7 +29180,20 @@ async function runSupervised(helper, request, options = {}) {
29005
29180
  try {
29006
29181
  const m = JSON.parse(line);
29007
29182
  if (!m || typeof m !== "object" || Array.isArray(m) || outcome) throw Error();
29008
- if (m.type === "started") {
29183
+ if (m.type === "containment") {
29184
+ const containment = m.containment;
29185
+ const valid = (value) => process.platform === "linux" ? validLinuxContainment(value) : process.platform === "darwin" && validDarwinContainment(value);
29186
+ if (!valid(containment) || containmentReceived || pid !== null || child.pid === void 0 || containment.uid !== process.getuid?.()) throw Error();
29187
+ containmentReceived = true;
29188
+ Promise.resolve().then(() => options.onSupervisor?.(child.pid, containment)).then(() => {
29189
+ if (failure6 || closed || cancelSent) return;
29190
+ containmentSaved = true;
29191
+ child.stdin.write("continue\n", (error62) => {
29192
+ if (error62) fail7("SUPERVISOR_CONTROL_CLOSED");
29193
+ });
29194
+ }, () => fail7("SUPERVISOR_START_FAILED"));
29195
+ } else if (m.type === "started") {
29196
+ if (!containmentSaved) throw Error();
29009
29197
  if (pid !== null || !Number.isSafeInteger(m.pid) || m.pid <= 0) throw Error();
29010
29198
  pid = m.pid;
29011
29199
  options.onStarted?.(pid);
@@ -29147,24 +29335,33 @@ function encodeText(text3, encoding) {
29147
29335
  const bytes3 = Buffer.from("\uFEFF" + text3.replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g, "\uFFFD"), "utf16le");
29148
29336
  return encoding === "utf16be" ? bytes3.swap16() : bytes3;
29149
29337
  }
29150
- var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29338
+ var delay2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29151
29339
  var NativeTools = class {
29152
29340
  constructor(options) {
29153
29341
  this.options = options;
29154
29342
  this.options = structuredClone(options);
29155
- this.memory = new HostMemory(path16.join(options.stateDirectory, "host-memory.json"), Object.keys(options.programs), Object.fromEntries(Object.entries(options.programs).map(([name2, program]) => [name2, program.executable])));
29343
+ this.memory = new HostMemory(path17.join(options.stateDirectory, "host-memory.json"), Object.keys(options.programs), Object.fromEntries(Object.entries(options.programs).map(([name2, program]) => [name2, program.executable])));
29156
29344
  }
29157
29345
  options;
29158
29346
  memory;
29159
29347
  async readFile(file2, maxBytes, signal) {
29160
29348
  try {
29161
- return await readBoundedFile(file2, maxBytes, this.options.ownerBridgePath ?? path16.join(path16.dirname(this.options.helperPath), "OwnerBridge.exe"), signal);
29349
+ return await readBoundedFile(file2, maxBytes, this.options.ownerBridgePath ?? path17.join(path17.dirname(this.options.helperPath), "OwnerBridge.exe"), signal);
29162
29350
  } catch (error62) {
29163
29351
  if (error62.code === "ENOENT") throw error62;
29164
29352
  if (error62 instanceof Error && /^[A-Z_]{1,40}$/.test(error62.message)) fail3(error62.message);
29165
29353
  throw error62;
29166
29354
  }
29167
29355
  }
29356
+ /** Windows only: up to 64 files of at most 1 MiB in one bridge process, each with its own result. */
29357
+ async readFiles(files, maxTotalBytes, signal) {
29358
+ try {
29359
+ return await readWindowsFiles(this.options.ownerBridgePath ?? path17.join(path17.dirname(this.options.helperPath), "OwnerBridge.exe"), files, 1048576, maxTotalBytes, signal);
29360
+ } catch (error62) {
29361
+ if (error62 instanceof Error && /^[A-Z_]{1,40}$/.test(error62.message)) fail3(error62.message);
29362
+ throw error62;
29363
+ }
29364
+ }
29168
29365
  async prepare(workspace2, candidate, selection) {
29169
29366
  let prepared;
29170
29367
  try {
@@ -29176,14 +29373,14 @@ var NativeTools = class {
29176
29373
  const proof2 = JSON.parse((await identity.run(AbortSignal.timeout(15e3))).stdout);
29177
29374
  if (!proof2.repositoryFingerprint) fail3("PROJECT_IDENTITY_UNKNOWN");
29178
29375
  if (proof2.repositoryFingerprint !== target.repositoryFingerprint) fail3("PROJECT_IDENTITY_MISMATCH");
29179
- projectRoot = path16.resolve(workspace2.root, target.relativePath);
29376
+ projectRoot = path17.resolve(workspace2.root, target.relativePath);
29180
29377
  const common = identity.claims.find((claim2) => claim2.namespace === "git")?.path;
29181
29378
  if (common) workspace2 = { ...workspace2, gitCommonDir: common };
29182
29379
  }
29183
29380
  prepared = await this.prepareTool(workspace2, candidate, projectRoot);
29184
29381
  } catch (error62) {
29185
29382
  const parsed = ToolCallSchema.safeParse(candidate);
29186
- if (parsed.success && parsed.data.name === "command_run") await this.memory.record({ ...parsed.data.args, cwd: path16.resolve(workspace2.root, parsed.data.args.cwd ?? ".") }, void 0, error62).catch(() => {
29383
+ if (parsed.success && parsed.data.name === "command_run") await this.memory.record({ ...parsed.data.args, cwd: path17.resolve(workspace2.root, parsed.data.args.cwd ?? ".") }, void 0, error62).catch(() => {
29187
29384
  });
29188
29385
  throw error62;
29189
29386
  }
@@ -29203,17 +29400,17 @@ var NativeTools = class {
29203
29400
  try {
29204
29401
  const canonical2 = await realpath7(workspace2.root);
29205
29402
  if (!equalPath3(canonical2, workspace2.root) || hash6(process.platform === "win32" ? canonical2.toLowerCase() : canonical2) !== workspace2.rootHash) fail3("WORKSPACE_CHANGED");
29206
- const runtimeDirectory = path16.dirname(this.options.helperPath);
29403
+ const runtimeDirectory = path17.dirname(this.options.helperPath);
29207
29404
  const protectedPaths = [
29208
29405
  this.options.stateDirectory,
29209
29406
  this.options.helperPath,
29210
- ...["agent.mjs", "node.exe", "OwnerBridge.exe", "LocalCommanderAgent.exe", "node", "owner-store", "posix-host", "job-host.mjs", "lifecycle.mjs", "manifest.json"].map((name2) => path16.join(runtimeDirectory, name2))
29407
+ ...["agent.mjs", "node.exe", "OwnerBridge.exe", "LocalCommanderAgent.exe", "node", "owner-store", "posix-host", "job-host.mjs", "lifecycle.mjs", "manifest.json"].map((name2) => path17.join(runtimeDirectory, name2))
29211
29408
  ];
29212
29409
  if (this.options.ownerBridgePath) protectedPaths.push(this.options.ownerBridgePath);
29213
- if (process.platform === "win32" && process.env.LOCALAPPDATA && path16.isAbsolute(process.env.LOCALAPPDATA)) {
29214
- protectedPaths.push(path16.join(process.env.LOCALAPPDATA, "LocalCommander"));
29410
+ if (process.platform === "win32" && process.env.LOCALAPPDATA && path17.isAbsolute(process.env.LOCALAPPDATA)) {
29411
+ protectedPaths.push(path17.join(process.env.LOCALAPPDATA, "LocalCommander"));
29215
29412
  }
29216
- if (process.platform !== "win32") protectedPaths.push(path16.join(process.env.LC_AGENT_DATA_DIR || posixDataHome(), "LocalCommander"));
29413
+ if (process.platform !== "win32") protectedPaths.push(path17.join(process.env.LC_AGENT_DATA_DIR || posixDataHome(), "LocalCommander"));
29217
29414
  guard = await PathGuard.create([canonical2], false, { protectedPaths });
29218
29415
  if (projectRoot) {
29219
29416
  const selected = await guard.resolveDirectory(projectRoot);
@@ -29302,7 +29499,7 @@ var NativeTools = class {
29302
29499
  }
29303
29500
  if (taken === first - 1 && first <= end) fail3("OUTPUT_LIMIT_EXCEEDED");
29304
29501
  const remaining = lines.length - (lines.length > 1 && lines.at(-1) === "" ? 1 : 0);
29305
- return result({ path: path16.relative(workspace2.root, filename), sha256: hash6(bytes3), startLine: first, endLine: Math.min(taken === first - 1 ? last : taken, lines.length), totalLines: lines.length, content: lines.slice(first - 1, taken).join("\n"), truncated: taken < remaining });
29502
+ return result({ path: path17.relative(workspace2.root, filename), sha256: hash6(bytes3), startLine: first, endLine: Math.min(taken === first - 1 ? last : taken, lines.length), totalLines: lines.length, content: lines.slice(first - 1, taken).join("\n"), truncated: taken < remaining });
29306
29503
  } };
29307
29504
  }
29308
29505
  if (call.name === "fs_write" || call.name === "fs_replace") {
@@ -29345,7 +29542,7 @@ var NativeTools = class {
29345
29542
  bytes3 = encodeText(pieces.join(newText), original.encoding);
29346
29543
  }
29347
29544
  if (bytes3.length > MAX_FILE_WRITE_BYTES) fail3("FILE_WRITE_LIMIT");
29348
- const temp = path16.join(path16.dirname(target), ".lc-write-" + randomUUID7() + ".tmp");
29545
+ const temp = path17.join(path17.dirname(target), ".lc-write-" + randomUUID7() + ".tmp");
29349
29546
  const handle = await open6(temp, constants7.O_CREAT | constants7.O_EXCL | constants7.O_WRONLY, 384);
29350
29547
  try {
29351
29548
  await handle.writeFile(bytes3);
@@ -29363,7 +29560,7 @@ var NativeTools = class {
29363
29560
  } catch (error62) {
29364
29561
  if (process.platform !== "win32" || !["EPERM", "EBUSY", "EACCES"].includes(error62.code ?? "")) throw error62;
29365
29562
  if (attempt === 4) fail3((await lstat7(target)).mode & 128 ? "FILE_IN_USE" : "FILE_READ_ONLY");
29366
- await delay(50 << attempt);
29563
+ await delay2(50 << attempt);
29367
29564
  stopped(signal);
29368
29565
  }
29369
29566
  }
@@ -29380,11 +29577,11 @@ var NativeTools = class {
29380
29577
  await rm5(temp);
29381
29578
  break;
29382
29579
  } catch {
29383
- await delay(100);
29580
+ await delay2(100);
29384
29581
  }
29385
29582
  }
29386
29583
  }
29387
- return result({ path: path16.relative(workspace2.root, target), bytes: bytes3.length, sha256: hash6(bytes3), ...call.name === "fs_replace" ? { replacements } : {} });
29584
+ return result({ path: path17.relative(workspace2.root, target), bytes: bytes3.length, sha256: hash6(bytes3), ...call.name === "fs_replace" ? { replacements } : {} });
29388
29585
  } catch (e) {
29389
29586
  await handle.close().catch(() => {
29390
29587
  });
@@ -29400,34 +29597,80 @@ var NativeTools = class {
29400
29597
  const listing = await this.list(guard, base, 8, 1e3, signal), matches2 = [];
29401
29598
  const query = call.args.caseSensitive ? call.args.query : call.args.query.toLowerCase();
29402
29599
  let scanned = 0, scannedBytes = 0, room = RESULT_ITEMS_BUDGET, incomplete = false;
29600
+ const done = () => matches2.length >= call.args.maxResults || scanned >= 300 || room < 0;
29601
+ const skipped = (error62) => {
29602
+ if (error62 instanceof NativeToolError && ["FILE_READ_FAILED", "CANCELLED"].includes(error62.code)) throw error62;
29603
+ if (error62 instanceof NativeToolError && error62.code === "FILE_UNSUPPORTED_OR_TOO_LARGE") incomplete = true;
29604
+ };
29605
+ const searchFile = (filename, bytes3) => {
29606
+ scannedBytes += bytes3.length;
29607
+ const lines = decodeText(bytes3).text.split(/\r?\n/);
29608
+ scanned++;
29609
+ for (let i = 0; i < lines.length && matches2.length < call.args.maxResults; i++) if ((call.args.caseSensitive ? lines[i] : lines[i].toLowerCase()).includes(query)) {
29610
+ const match = { path: path17.relative(workspace2.root, filename), line: i + 1, text: lines[i].slice(0, 500) };
29611
+ if ((room -= Buffer.byteLength(JSON.stringify(match)) + 1) < 0) {
29612
+ incomplete = true;
29613
+ break;
29614
+ }
29615
+ matches2.push(match);
29616
+ }
29617
+ };
29618
+ const batched = process.platform === "win32", pending = [];
29619
+ let pendingBytes = 0, pendingInput = 0;
29620
+ const flush = async () => {
29621
+ if (!pending.length) return;
29622
+ const files = pending.splice(0);
29623
+ pendingBytes = 0;
29624
+ pendingInput = 0;
29625
+ const results2 = await this.readFiles(files, Math.max(1, 16777216 - scannedBytes), signal);
29626
+ for (let i = 0; i < files.length && !done(); i++) {
29627
+ const read = results2[i];
29628
+ if ("code" in read) {
29629
+ if (read.code === "FILE_UNSUPPORTED_OR_TOO_LARGE") incomplete = true;
29630
+ continue;
29631
+ }
29632
+ try {
29633
+ searchFile(files[i], read.data);
29634
+ } catch (error62) {
29635
+ skipped(error62);
29636
+ }
29637
+ }
29638
+ };
29403
29639
  for (const entry of listing.entries) {
29404
29640
  if (entry.type !== "file") continue;
29405
29641
  stopped(signal);
29406
- if (matches2.length >= call.args.maxResults || scanned >= 300 || room < 0) break;
29407
- if ((entry.size ?? 0) > 1048576 || scannedBytes + (entry.size ?? 0) > 16777216) {
29642
+ if (done()) break;
29643
+ const size = entry.size ?? 0;
29644
+ if (pending.length && size <= 1048576 && scannedBytes + pendingBytes + size > 16777216) {
29645
+ await flush();
29646
+ if (done()) break;
29647
+ }
29648
+ if (size > 1048576 || scannedBytes + pendingBytes + size > 16777216) {
29408
29649
  incomplete = true;
29409
29650
  continue;
29410
29651
  }
29411
29652
  try {
29412
- const filename = await guard.resolveExisting(path16.join(base, entry.path));
29653
+ const filename = await guard.resolveExisting(path17.join(base, entry.path));
29413
29654
  guard.assertSafeFile(filename);
29414
- const bytes3 = await this.readFile(filename, 1048576, signal);
29415
- scannedBytes += bytes3.length;
29416
- const lines = decodeText(bytes3).text.split(/\r?\n/);
29417
- scanned++;
29418
- for (let i = 0; i < lines.length && matches2.length < call.args.maxResults; i++) if ((call.args.caseSensitive ? lines[i] : lines[i].toLowerCase()).includes(query)) {
29419
- const match = { path: path16.relative(workspace2.root, filename), line: i + 1, text: lines[i].slice(0, 500) };
29420
- if ((room -= Buffer.byteLength(JSON.stringify(match)) + 1) < 0) {
29421
- incomplete = true;
29422
- break;
29423
- }
29424
- matches2.push(match);
29655
+ if (!batched) {
29656
+ searchFile(filename, await this.readFile(filename, 1048576, signal));
29657
+ continue;
29425
29658
  }
29659
+ const input2 = Buffer.byteLength(JSON.stringify(filename)) + 1;
29660
+ if (pending.length && pendingInput + input2 > 25e4) await flush();
29661
+ pending.push(filename);
29662
+ pendingBytes += size;
29663
+ pendingInput += input2;
29426
29664
  } catch (error62) {
29427
- if (error62 instanceof NativeToolError && ["FILE_READ_FAILED", "CANCELLED"].includes(error62.code)) throw error62;
29428
- if (error62 instanceof NativeToolError && error62.code === "FILE_UNSUPPORTED_OR_TOO_LARGE") incomplete = true;
29665
+ skipped(error62);
29666
+ continue;
29667
+ }
29668
+ if (pending.length >= Math.min(64, 300 - scanned) || pendingBytes >= 4194304) {
29669
+ await flush();
29670
+ if (done()) break;
29429
29671
  }
29430
29672
  }
29673
+ if (!done()) await flush();
29431
29674
  return result({ matches: matches2, scannedFiles: scanned, truncated: listing.truncated || incomplete || matches2.length >= call.args.maxResults || scanned >= 300 });
29432
29675
  } };
29433
29676
  }
@@ -29473,7 +29716,7 @@ var NativeTools = class {
29473
29716
  } };
29474
29717
  }
29475
29718
  if (call.name === "command_run") {
29476
- if (process.platform !== "win32" && process.platform !== "linux") fail3("COMMAND_NOT_ALLOWED");
29719
+ if (!["win32", "linux", "darwin"].includes(process.platform)) fail3("COMMAND_NOT_ALLOWED");
29477
29720
  const cwd2 = await resolve(call.args.cwd, true), program = await this.resolveProgram(call.args.command, workspace2, call.args.args);
29478
29721
  const claims2 = writeClaim(cwd2);
29479
29722
  return { call, claims: claims2, execution: { ...program, cwd: cwd2 }, run: async (signal, onStarted, onOutput, onSupervisor) => {
@@ -29501,9 +29744,9 @@ var NativeTools = class {
29501
29744
  else if (call.name === "git_diff") {
29502
29745
  argv = ["diff", "--no-ext-diff", "--no-textconv", ...call.args.staged ? ["--cached"] : []];
29503
29746
  if (call.args.file) {
29504
- const file2 = await resolve(path16.resolve(cwd, call.args.file));
29505
- const relative = path16.relative(cwd, file2);
29506
- if (relative.startsWith(".." + path16.sep) || relative === ".." || path16.isAbsolute(relative)) fail3("PATH_NOT_ALLOWED");
29747
+ const file2 = await resolve(path17.resolve(cwd, call.args.file));
29748
+ const relative = path17.relative(cwd, file2);
29749
+ if (relative.startsWith(".." + path17.sep) || relative === ".." || path17.isAbsolute(relative)) fail3("PATH_NOT_ALLOWED");
29507
29750
  argv.push("--", relative);
29508
29751
  } else argv.push("--stat");
29509
29752
  } else fail3("TOOL_MISSING");
@@ -29514,7 +29757,7 @@ var NativeTools = class {
29514
29757
  const listing = await this.list(guard, cwd, 1, call.args.startup ? 20 : 150, signal);
29515
29758
  let packageInfo = null;
29516
29759
  try {
29517
- const name2 = await guard.resolveExisting(path16.join(cwd, "package.json"));
29760
+ const name2 = await guard.resolveExisting(path17.join(cwd, "package.json"));
29518
29761
  guard.assertSafeFile(name2);
29519
29762
  const value = JSON.parse(utf8(await this.readFile(name2, 64e3, signal)));
29520
29763
  packageInfo = { name: typeof value.name === "string" ? value.name : null, version: typeof value.version === "string" ? value.version : null, scripts: value.scripts && typeof value.scripts === "object" ? Object.keys(value.scripts).slice(0, 100) : [] };
@@ -29534,7 +29777,7 @@ var NativeTools = class {
29534
29777
  }
29535
29778
  const contextFile = async (relative, limit, optional2 = false) => {
29536
29779
  try {
29537
- const file2 = await guard.resolveExisting(path16.join(primary, relative));
29780
+ const file2 = await guard.resolveExisting(path17.join(primary, relative));
29538
29781
  guard.assertSafeFile(file2);
29539
29782
  return utf8(await this.readFile(file2, limit, signal));
29540
29783
  } catch (error62) {
@@ -29567,17 +29810,17 @@ var NativeTools = class {
29567
29810
  } };
29568
29811
  }
29569
29812
  async resolveProgram(name2, workspace2, args) {
29570
- const entry = Object.entries(this.options.programs).find(([key, value]) => equalPath3(key, name2) || path16.isAbsolute(name2) && equalPath3(value.executable, path16.resolve(name2)));
29813
+ const entry = Object.entries(this.options.programs).find(([key, value]) => equalPath3(key, name2) || path17.isAbsolute(name2) && equalPath3(value.executable, path17.resolve(name2)));
29571
29814
  if (workspace2.fullAccess) {
29572
- const commandKey = (value) => process.platform === "win32" ? path16.basename(value).toLowerCase().replace(/\.(exe|com|cmd|bat)$/i, "") : path16.basename(value);
29815
+ const commandKey = (value) => process.platform === "win32" ? path17.basename(value).toLowerCase().replace(/\.(exe|com|cmd|bat)$/i, "") : path17.basename(value);
29573
29816
  const denied = new Set((workspace2.deniedCommands ?? []).map(commandKey));
29574
29817
  if (denied.has(commandKey(name2)) || entry && denied.has(commandKey(entry[0]))) fail3("COMMAND_NOT_ALLOWED");
29575
- const extension2 = path16.extname(name2).toLowerCase();
29576
- const candidate = entry?.[1].executable ?? (process.platform !== "win32" ? await resolvePosixExecutable(name2) : path16.isAbsolute(name2) ? name2 : /^[\w.-]+$/.test(name2) ? resolveWindowsLauncher(
29818
+ const extension2 = path17.extname(name2).toLowerCase();
29819
+ const candidate = entry?.[1].executable ?? (process.platform !== "win32" ? await resolvePosixExecutable(name2) : path17.isAbsolute(name2) ? name2 : /^[\w.-]+$/.test(name2) ? resolveWindowsLauncher(
29577
29820
  commandKey(name2),
29578
29821
  [".exe", ".com", ".cmd", ".bat"].includes(extension2) ? { ...process.env, PATHEXT: extension2 } : process.env
29579
29822
  )?.file : void 0);
29580
- if (!candidate || !path16.isAbsolute(candidate)) fail3("COMMAND_NOT_FOUND");
29823
+ if (!candidate || !path17.isAbsolute(candidate)) fail3("COMMAND_NOT_FOUND");
29581
29824
  const executable = await realpath7(candidate).catch(() => fail3("COMMAND_NOT_FOUND"));
29582
29825
  if (!(await lstat7(executable)).isFile()) fail3("COMMAND_NOT_FOUND");
29583
29826
  if (denied.has(commandKey(executable))) fail3("COMMAND_NOT_ALLOWED");
@@ -29592,7 +29835,7 @@ var NativeTools = class {
29592
29835
  if (/\.(cmd|bat)$/i.test(executable)) {
29593
29836
  if ([executable, ...args].some((value) => /[&|<>^%!"\r\n]/.test(value))) fail3("INVALID_SCRIPT_ARGUMENTS");
29594
29837
  const literal2 = (value) => "'" + value.replaceAll("'", "''") + "'";
29595
- const shell = path16.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
29838
+ const shell = path17.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
29596
29839
  if (denied.has("powershell") || denied.has("cmd")) fail3("COMMAND_NOT_ALLOWED");
29597
29840
  const script = "& " + literal2(executable) + " @(" + args.map(literal2).join(",") + "); exit $LASTEXITCODE";
29598
29841
  return { executable: shell, args: ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")] };
@@ -29600,7 +29843,7 @@ var NativeTools = class {
29600
29843
  if (!/\.(exe|com)$/i.test(executable)) fail3("COMMAND_NOT_ALLOWED");
29601
29844
  return { executable, args: [...entry?.[1].prefixArgs ?? [], ...args] };
29602
29845
  }
29603
- if (!entry || !workspace2.allowedCommands.some((v) => equalPath3(v, entry[0])) || !path16.isAbsolute(entry[1].executable)) fail3("COMMAND_NOT_ALLOWED");
29846
+ if (!entry || !workspace2.allowedCommands.some((v) => equalPath3(v, entry[0])) || !path17.isAbsolute(entry[1].executable)) fail3("COMMAND_NOT_ALLOWED");
29604
29847
  return { executable: entry[1].executable, args: [...entry[1].prefixArgs ?? [], ...args] };
29605
29848
  }
29606
29849
  async memoryContext(workspace2) {
@@ -29613,11 +29856,11 @@ var NativeTools = class {
29613
29856
  })) } };
29614
29857
  }
29615
29858
  async gitExecution(cwd, args) {
29616
- if (process.platform !== "win32" && process.platform !== "linux") fail3("COMMAND_NOT_ALLOWED");
29859
+ if (!["win32", "linux", "darwin"].includes(process.platform)) fail3("COMMAND_NOT_ALLOWED");
29617
29860
  const configured = this.options.programs.git;
29618
- const candidates = configured ? [configured.executable] : process.platform === "win32" ? [[process.env.ProgramFiles, "Git"], [process.env["ProgramFiles(x86)"], "Git"], [process.env.LOCALAPPDATA, "Programs/Git"]].filter(([root]) => root && path16.isAbsolute(root)).map(([root, suffix]) => path16.join(root, suffix, "cmd", "git.exe")) : ["/usr/bin/git", "/usr/local/bin/git", "/opt/homebrew/bin/git"];
29861
+ const candidates = configured ? [configured.executable] : process.platform === "win32" ? [[process.env.ProgramFiles, "Git"], [process.env["ProgramFiles(x86)"], "Git"], [process.env.LOCALAPPDATA, "Programs/Git"]].filter(([root]) => root && path17.isAbsolute(root)).map(([root, suffix]) => path17.join(root, suffix, "cmd", "git.exe")) : ["/usr/bin/git", "/usr/local/bin/git", "/opt/homebrew/bin/git"];
29619
29862
  for (const source of candidates) {
29620
- if (!path16.isAbsolute(source)) continue;
29863
+ if (!path17.isAbsolute(source)) continue;
29621
29864
  const candidate = process.platform === "win32" ? source : await resolvePosixExecutable(source);
29622
29865
  if (!candidate) continue;
29623
29866
  try {
@@ -29651,7 +29894,7 @@ var NativeTools = class {
29651
29894
  break;
29652
29895
  }
29653
29896
  if (item.isSymbolicLink() || excluded.has(item.name.toLowerCase())) continue;
29654
- const candidate = path16.join(current2.path, item.name);
29897
+ const candidate = path17.join(current2.path, item.name);
29655
29898
  let resolved;
29656
29899
  try {
29657
29900
  resolved = await guard.resolveExisting(candidate);
@@ -29661,11 +29904,11 @@ var NativeTools = class {
29661
29904
  }
29662
29905
  if (!equalPath3(candidate, resolved)) continue;
29663
29906
  if (item.isDirectory()) {
29664
- entries.push({ path: path16.relative(root, resolved), type: "directory" });
29907
+ entries.push({ path: path17.relative(root, resolved), type: "directory" });
29665
29908
  if (current2.level < depth) queue.push({ path: resolved, level: current2.level + 1 });
29666
29909
  } else if (item.isFile()) {
29667
29910
  const stat2 = await lstat7(resolved).catch(() => null);
29668
- if (stat2) entries.push({ path: path16.relative(root, resolved), type: "file", size: stat2.size });
29911
+ if (stat2) entries.push({ path: path17.relative(root, resolved), type: "file", size: stat2.size });
29669
29912
  }
29670
29913
  }
29671
29914
  if (truncated) break;
@@ -29675,7 +29918,7 @@ var NativeTools = class {
29675
29918
  async gitCommonDir(cwd, workspace2, guard) {
29676
29919
  let directory = cwd;
29677
29920
  while (guard.isWithin(directory, workspace2.root)) {
29678
- const dotGit = path16.join(directory, ".git");
29921
+ const dotGit = path17.join(directory, ".git");
29679
29922
  try {
29680
29923
  const stat2 = await lstat7(dotGit);
29681
29924
  if (stat2.isSymbolicLink()) fail3("GIT_METADATA_CHANGED");
@@ -29684,14 +29927,14 @@ var NativeTools = class {
29684
29927
  else {
29685
29928
  const content = utf8(await this.readFile(dotGit, 4096)).trim();
29686
29929
  if (!content.startsWith("gitdir: ")) fail3("GIT_METADATA_CHANGED");
29687
- gitDir = await realpath7(path16.resolve(directory, content.slice(8)));
29930
+ gitDir = await realpath7(path17.resolve(directory, content.slice(8)));
29688
29931
  }
29689
29932
  if (guard.isWithin(gitDir, this.options.stateDirectory) || !guard.isWithin(gitDir, workspace2.root) && (!workspace2.gitCommonDir || !guard.isWithin(gitDir, workspace2.gitCommonDir))) fail3("GIT_COMMON_DIRECTORY_NOT_APPROVED");
29690
29933
  let common = gitDir;
29691
29934
  try {
29692
- const content = utf8(await this.readFile(path16.join(gitDir, "commondir"), 4096)).trim();
29935
+ const content = utf8(await this.readFile(path17.join(gitDir, "commondir"), 4096)).trim();
29693
29936
  if (!content) fail3("GIT_METADATA_CHANGED");
29694
- common = await realpath7(path16.resolve(gitDir, content));
29937
+ common = await realpath7(path17.resolve(gitDir, content));
29695
29938
  } catch (e) {
29696
29939
  if (e.code !== "ENOENT") throw e;
29697
29940
  }
@@ -29702,22 +29945,22 @@ var NativeTools = class {
29702
29945
  if (e.code !== "ENOENT") throw e;
29703
29946
  }
29704
29947
  if (equalPath3(directory, workspace2.root)) break;
29705
- directory = path16.dirname(directory);
29948
+ directory = path17.dirname(directory);
29706
29949
  }
29707
29950
  return null;
29708
29951
  }
29709
29952
  };
29710
29953
 
29711
29954
  // agent/src/scheduler.ts
29712
- import path17 from "node:path";
29955
+ import path18 from "node:path";
29713
29956
  import os4 from "node:os";
29714
29957
  function canonical(value) {
29715
- const p = path17.resolve(value);
29958
+ const p = path18.resolve(value);
29716
29959
  return process.platform === "win32" ? p.toLowerCase() : p;
29717
29960
  }
29718
29961
  function ancestor(a, b) {
29719
- const relative = path17.relative(a, b);
29720
- return relative === "" || !path17.isAbsolute(relative) && relative !== ".." && !relative.startsWith(".." + path17.sep);
29962
+ const relative = path18.relative(a, b);
29963
+ return relative === "" || !path18.isAbsolute(relative) && relative !== ".." && !relative.startsWith(".." + path18.sep);
29721
29964
  }
29722
29965
  function claimsConflict(a, b) {
29723
29966
  return a.some((x) => b.some((y) => (x.namespace ?? "filesystem") === (y.namespace ?? "filesystem") && (x.mode === "write" || y.mode === "write") && (ancestor(x.path, y.path) || ancestor(y.path, x.path))));
@@ -29746,7 +29989,7 @@ var NativeScheduler = class {
29746
29989
  schedule(id2, claims, deadlineAt, run, signal) {
29747
29990
  if (!this.accepting) return Promise.reject(Error("AGENT_PAUSED"));
29748
29991
  if (!id2 || id2.length > 100 || this.active.has(id2) || this.waiting.some((j) => j.id === id2)) return Promise.reject(Error("DUPLICATE_SCHEDULED_EXECUTION"));
29749
- if (!Array.isArray(claims) || !claims.length || claims.length > 32 || claims.some((c) => !c || !path17.isAbsolute(c.path) || !["read", "write"].includes(c.mode))) return Promise.reject(Error("INVALID_RESOURCE_CLAIM"));
29992
+ if (!Array.isArray(claims) || !claims.length || claims.length > 32 || claims.some((c) => !c || !path18.isAbsolute(c.path) || !["read", "write"].includes(c.mode))) return Promise.reject(Error("INVALID_RESOURCE_CLAIM"));
29750
29993
  const deadline = deadlineAt.getTime();
29751
29994
  if (!Number.isFinite(deadline) || deadline <= Date.now()) return Promise.reject(Error("ADMISSION_DEADLINE_EXPIRED"));
29752
29995
  if (signal?.aborted) return Promise.reject(Error("CANCELLED_BEFORE_ACCEPTANCE"));
@@ -30253,17 +30496,17 @@ function unshapedResultTelemetry(result2) {
30253
30496
 
30254
30497
  // packages/optimization/src/live-telemetry.ts
30255
30498
  var LIVE_EFFICIENCY_EVENT_VERSION = 1;
30256
- var uuid17 = external_exports.string().uuid().toLowerCase();
30499
+ var uuid18 = external_exports.string().uuid().toLowerCase();
30257
30500
  var bytes2 = external_exports.number().int().min(0).max(1e9);
30258
30501
  var utc4 = external_exports.iso.datetime({ offset: false });
30259
30502
  var LiveEfficiencyEventSchema = external_exports.object({
30260
30503
  version: external_exports.literal(LIVE_EFFICIENCY_EVENT_VERSION),
30261
30504
  occurredAt: utc4,
30262
- tenantId: uuid17,
30263
- accountId: uuid17.nullable(),
30264
- sessionId: uuid17,
30265
- operationId: uuid17,
30266
- executionId: uuid17,
30505
+ tenantId: uuid18,
30506
+ accountId: uuid18.nullable(),
30507
+ sessionId: uuid18,
30508
+ operationId: uuid18,
30509
+ executionId: uuid18,
30267
30510
  toolName: external_exports.string().trim().min(1).max(120),
30268
30511
  outcome: external_exports.enum(["success", "failed", "timed_out", "cancelled", "unknown"]),
30269
30512
  parserId: external_exports.string().trim().min(1).max(120).nullable(),
@@ -30647,7 +30890,7 @@ var NativeRuntime = class {
30647
30890
  this.send({ type: "running", version: 1, binding: binding2, pid });
30648
30891
  }, (stream, bytes3) => {
30649
30892
  (stream === "stdout" ? context.stdout : context.stderr).append(bytes3);
30650
- }, (pid) => this.options.journal.supervisor(binding2.executionId, pid));
30893
+ }, (pid, containment) => this.options.journal.supervisor(binding2.executionId, pid, containment));
30651
30894
  const checked = ResultSchema.parse(output2);
30652
30895
  const { resultCode, ...journalOutput } = checked;
30653
30896
  if (context.guardPermit) await this.options.guard.result(context.guardPermit, checked);
@@ -30858,9 +31101,9 @@ var NativeRelayBridge = class {
30858
31101
 
30859
31102
  // agent/src/local-direct.ts
30860
31103
  import net from "node:net";
30861
- import path18 from "node:path";
31104
+ import path19 from "node:path";
30862
31105
  import { createHmac as createHmac2, hkdfSync, randomBytes as randomBytes6, randomUUID as randomUUID8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
30863
- import { mkdir as mkdir7, readFile as readFile6, rename as rename5, rm as rm6, writeFile as writeFile3 } from "node:fs/promises";
31106
+ import { mkdir as mkdir7, readFile as readFile7, rename as rename5, rm as rm6, writeFile as writeFile3 } from "node:fs/promises";
30864
31107
  var LocalDirectError = class extends Error {
30865
31108
  constructor(code) {
30866
31109
  super(code);
@@ -30878,11 +31121,11 @@ var ADMISSION_MS = 6e4;
30878
31121
  var MAX_IN_FLIGHT = 16;
30879
31122
  var MAX_CONNECTIONS = 32;
30880
31123
  function localDirectDirectory(appData) {
30881
- return path18.join(appData, "LocalCommander", "LocalMcp");
31124
+ return path19.join(appData, "LocalCommander", "LocalMcp");
30882
31125
  }
30883
31126
  async function localDirectEnabled(directory) {
30884
31127
  try {
30885
- return JSON.parse(await readFile6(path18.join(directory, "settings.json"), "utf8"))?.enabled === true;
31128
+ return JSON.parse(await readFile7(path19.join(directory, "settings.json"), "utf8"))?.enabled === true;
30886
31129
  } catch {
30887
31130
  return false;
30888
31131
  }
@@ -30955,7 +31198,7 @@ var Lines = class {
30955
31198
  async function readEndpoint(directory) {
30956
31199
  let value;
30957
31200
  try {
30958
- value = JSON.parse(await readFile6(path18.join(directory, "endpoint.json"), "utf8"));
31201
+ value = JSON.parse(await readFile7(path19.join(directory, "endpoint.json"), "utf8"));
30959
31202
  } catch {
30960
31203
  fail4("LOCAL_AGENT_NOT_RUNNING");
30961
31204
  }
@@ -30972,7 +31215,7 @@ var LocalDirectServer = class _LocalDirectServer {
30972
31215
  sockets = /* @__PURE__ */ new Set();
30973
31216
  /** Listens only while the owner has enabled direct local access; null otherwise. */
30974
31217
  static async start(options) {
30975
- const endpointFile = path18.join(options.directory, "endpoint.json");
31218
+ const endpointFile = path19.join(options.directory, "endpoint.json");
30976
31219
  if (!await localDirectEnabled(options.directory)) {
30977
31220
  await rm6(endpointFile, { force: true }).catch(() => {
30978
31221
  });
@@ -31000,7 +31243,7 @@ var LocalDirectServer = class _LocalDirectServer {
31000
31243
  for (const socket of this.sockets) socket.destroy();
31001
31244
  await new Promise((resolve) => this.server.close(() => resolve()));
31002
31245
  try {
31003
- if ((await readEndpoint(this.options.directory)).pid === process.pid) await rm6(path18.join(this.options.directory, "endpoint.json"), { force: true });
31246
+ if ((await readEndpoint(this.options.directory)).pid === process.pid) await rm6(path19.join(this.options.directory, "endpoint.json"), { force: true });
31004
31247
  } catch {
31005
31248
  }
31006
31249
  }
@@ -34855,9 +35098,9 @@ var rev2026Codec = {
34855
35098
  });
34856
35099
  const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3);
34857
35100
  if (!parsed.success) for (const issue2 of parsed.error.issues) {
34858
- const path28 = issue2.path.map(String);
34859
- const key = path28.length > 0 ? path28.join(".") : "_meta";
34860
- if (path28.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
35101
+ const path29 = issue2.path.map(String);
35102
+ const key = path29.length > 0 ? path29.join(".") : "_meta";
35103
+ if (path29.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
34861
35104
  issues.push({
34862
35105
  key,
34863
35106
  problem: issue2.message
@@ -35159,29 +35402,29 @@ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
35159
35402
  function scanXMcpHeaderDeclarations(inputSchema) {
35160
35403
  const declarations = [];
35161
35404
  const seenLower = /* @__PURE__ */ new Map();
35162
- const visit2 = (node2, path28, reachable) => {
35405
+ const visit2 = (node2, path29, reachable) => {
35163
35406
  if (node2 === null || typeof node2 !== "object") return void 0;
35164
35407
  const schema = node2;
35165
35408
  if (X_MCP_HEADER_KEY in schema) {
35166
- if (!reachable || path28.length === 0) return `${pathName(path28)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
35409
+ if (!reachable || path29.length === 0) return `${pathName(path29)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
35167
35410
  const raw = schema[X_MCP_HEADER_KEY];
35168
- if (typeof raw !== "string" || raw.length === 0) return `${pathName(path28)}: x-mcp-header MUST be a non-empty string`;
35169
- if (!RFC9110_TOKEN.test(raw)) return `${pathName(path28)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
35411
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path29)}: x-mcp-header MUST be a non-empty string`;
35412
+ if (!RFC9110_TOKEN.test(raw)) return `${pathName(path29)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
35170
35413
  const type = typeof schema.type === "string" ? schema.type : void 0;
35171
- if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path28)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
35414
+ if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path29)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
35172
35415
  const lower = raw.toLowerCase();
35173
35416
  const prior = seenLower.get(lower);
35174
35417
  if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
35175
35418
  seenLower.set(lower, raw);
35176
35419
  declarations.push({
35177
- path: path28,
35420
+ path: path29,
35178
35421
  headerName: raw,
35179
35422
  type
35180
35423
  });
35181
35424
  }
35182
35425
  const properties = schema.properties;
35183
35426
  if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
35184
- const fault$1 = visit2(child, [...path28, key], reachable);
35427
+ const fault$1 = visit2(child, [...path29, key], reachable);
35185
35428
  if (fault$1 !== void 0) return fault$1;
35186
35429
  }
35187
35430
  for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
@@ -35189,7 +35432,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
35189
35432
  if (sub === void 0) continue;
35190
35433
  const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
35191
35434
  for (const branch of branches) {
35192
- const fault$1 = visit2(branch, [...path28, `<${k}>`], false);
35435
+ const fault$1 = visit2(branch, [...path29, `<${k}>`], false);
35193
35436
  if (fault$1 !== void 0) return fault$1;
35194
35437
  }
35195
35438
  }
@@ -35229,8 +35472,8 @@ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
35229
35472
  "$defs",
35230
35473
  "definitions"
35231
35474
  ]);
35232
- function pathName(path28) {
35233
- return path28.length === 0 ? "<root>" : path28.join(".");
35475
+ function pathName(path29) {
35476
+ return path29.length === 0 ? "<root>" : path29.join(".");
35234
35477
  }
35235
35478
  var HEADER_MISMATCH_ERROR_CODE = -32020;
35236
35479
  var INBOUND_VALIDATION_LADDER = [
@@ -35480,7 +35723,7 @@ var PROPERTY_KEYS_BY_TYPE = {
35480
35723
  array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])
35481
35724
  };
35482
35725
  var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options);
35483
- function walkProperty(node2, path28, vendor, unsupported) {
35726
+ function walkProperty(node2, path29, vendor, unsupported) {
35484
35727
  if (!isJsonObject(node2)) return node2;
35485
35728
  const allowedKeys = typeof node2.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node2.type) ? PROPERTY_KEYS_BY_TYPE[node2.type] : void 0;
35486
35729
  if (allowedKeys === void 0) return node2;
@@ -35488,8 +35731,8 @@ function walkProperty(node2, path28, vendor, unsupported) {
35488
35731
  for (const [key, value] of Object.entries(node2)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value;
35489
35732
  else if (key === "pattern" && node2.type === "string" && typeof node2.format === "string") {
35490
35733
  if (!SUPPORTED_STRING_FORMATS.has(node2.format)) pruned[key] = value;
35491
- else if (typeof value !== "string" || !isLibraryFormatPattern(node2.format, value, vendor)) unsupported.push(`${path28}.${key}`);
35492
- } else unsupported.push(`${path28}.${key}`);
35734
+ else if (typeof value !== "string" || !isLibraryFormatPattern(node2.format, value, vendor)) unsupported.push(`${path29}.${key}`);
35735
+ } else unsupported.push(`${path29}.${key}`);
35493
35736
  return pruned;
35494
35737
  }
35495
35738
  function walkRequestedSchema(converted, vendor) {
@@ -35506,11 +35749,11 @@ function describeUnsupportedProperties(pruned, fallback) {
35506
35749
  const offenders = Object.entries(pruned.properties).filter(([, node2]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node2).success).map(([name2]) => `properties.${name2}`);
35507
35750
  return offenders.length > 0 ? offenders.join(", ") : fallback;
35508
35751
  }
35509
- function findDroppedConstraintPaths(original, parsed, path28 = "") {
35510
- if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path28}[${index}]`));
35752
+ function findDroppedConstraintPaths(original, parsed, path29 = "") {
35753
+ if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path29}[${index}]`));
35511
35754
  if (!isJsonObject(original) || !isJsonObject(parsed)) return [];
35512
35755
  return Object.entries(original).flatMap(([key, value]) => {
35513
- const childPath = path28 ? `${path28}.${key}` : key;
35756
+ const childPath = path29 ? `${path29}.${key}` : key;
35514
35757
  if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];
35515
35758
  return findDroppedConstraintPaths(value, parsed[key], childPath);
35516
35759
  });
@@ -37221,9 +37464,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37221
37464
  }
37222
37465
  };
37223
37466
  var Label = class extends Node {
37224
- constructor(label) {
37467
+ constructor(label2) {
37225
37468
  super();
37226
- this.label = label;
37469
+ this.label = label2;
37227
37470
  this.names = {};
37228
37471
  }
37229
37472
  render({ _n }) {
@@ -37231,9 +37474,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37231
37474
  }
37232
37475
  };
37233
37476
  var Break = class extends Node {
37234
- constructor(label) {
37477
+ constructor(label2) {
37235
37478
  super();
37236
- this.label = label;
37479
+ this.label = label2;
37237
37480
  this.names = {};
37238
37481
  }
37239
37482
  render({ _n }) {
@@ -37598,11 +37841,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => {
37598
37841
  endFor() {
37599
37842
  return this._endBlockNode(For);
37600
37843
  }
37601
- label(label) {
37602
- return this._leafNode(new Label(label));
37844
+ label(label2) {
37845
+ return this._leafNode(new Label(label2));
37603
37846
  }
37604
- break(label) {
37605
- return this._leafNode(new Break(label));
37847
+ break(label2) {
37848
+ return this._leafNode(new Break(label2));
37606
37849
  }
37607
37850
  return(value) {
37608
37851
  const node2 = new Return();
@@ -39586,8 +39829,8 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
39586
39829
  for (let i = 0; i < str.length; i++) if (str[i] === token) ind++;
39587
39830
  return ind;
39588
39831
  }
39589
- function removeDotSegments(path28) {
39590
- let input2 = path28;
39832
+ function removeDotSegments(path29) {
39833
+ let input2 = path29;
39591
39834
  const output2 = [];
39592
39835
  let nextSlash = -1;
39593
39836
  let len = 0;
@@ -39740,8 +39983,8 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
39740
39983
  wsComponent.secure = void 0;
39741
39984
  }
39742
39985
  if (wsComponent.resourceName) {
39743
- const [path28, query] = wsComponent.resourceName.split("?");
39744
- wsComponent.path = path28 && path28 !== "/" ? path28 : void 0;
39986
+ const [path29, query] = wsComponent.resourceName.split("?");
39987
+ wsComponent.path = path29 && path29 !== "/" ? path29 : void 0;
39745
39988
  wsComponent.query = query;
39746
39989
  wsComponent.resourceName = void 0;
39747
39990
  }
@@ -45382,10 +45625,10 @@ import { createHash as createHash15, createPrivateKey as createPrivateKey3, rand
45382
45625
 
45383
45626
  // agent/src/native-incident-producer.ts
45384
45627
  import { randomUUID as randomUUID9 } from "node:crypto";
45385
- var uuid18 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
45628
+ var uuid19 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
45386
45629
  var results = /* @__PURE__ */ new Set(["accepted", "duplicate", "invalid", "stale", "unconfirmed", "capacity", "retry", "disabled", "busy"]);
45387
45630
  function nativeIncidentAck(candidate) {
45388
- if (candidate.type !== "incidentBatchAck" || candidate.protocolVersion !== 1 || Object.keys(candidate).some((key) => !["type", "protocolVersion", "batchId", "result"].includes(key)) || typeof candidate.result !== "string" || !results.has(candidate.result) || candidate.batchId !== void 0 && (typeof candidate.batchId !== "string" || !uuid18.test(candidate.batchId))) return;
45631
+ if (candidate.type !== "incidentBatchAck" || candidate.protocolVersion !== 1 || Object.keys(candidate).some((key) => !["type", "protocolVersion", "batchId", "result"].includes(key)) || typeof candidate.result !== "string" || !results.has(candidate.result) || candidate.batchId !== void 0 && (typeof candidate.batchId !== "string" || !uuid19.test(candidate.batchId))) return;
45389
45632
  return { result: candidate.result, ...candidate.batchId ? { batchId: String(candidate.batchId).toLowerCase() } : {} };
45390
45633
  }
45391
45634
  var NativeIncidentProducer = class {
@@ -45451,12 +45694,12 @@ var NativeIncidentProducer = class {
45451
45694
  classify(event, occurrences) {
45452
45695
  const incident = event.incident;
45453
45696
  if (!incident) return;
45454
- const executionId = incident.executionId && uuid18.test(incident.executionId) ? incident.executionId.toLowerCase() : void 0;
45697
+ const executionId = incident.executionId && uuid19.test(incident.executionId) ? incident.executionId.toLowerCase() : void 0;
45455
45698
  let refs = {};
45456
45699
  try {
45457
45700
  const confirmed = executionId && this.references?.(executionId);
45458
- if (confirmed && confirmed.executionId === executionId && uuid18.test(confirmed.workerId)) {
45459
- refs = { workerId: confirmed.workerId.toLowerCase(), ...confirmed.taskId && uuid18.test(confirmed.taskId) ? { taskId: confirmed.taskId.toLowerCase() } : {} };
45701
+ if (confirmed && confirmed.executionId === executionId && uuid19.test(confirmed.workerId)) {
45702
+ refs = { workerId: confirmed.workerId.toLowerCase(), ...confirmed.taskId && uuid19.test(confirmed.taskId) ? { taskId: confirmed.taskId.toLowerCase() } : {} };
45460
45703
  }
45461
45704
  } catch {
45462
45705
  }
@@ -45569,7 +45812,7 @@ function relayUrlFromEnrollment(enrollment) {
45569
45812
  url2.pathname = "/api/agent/relay";
45570
45813
  return url2.toString();
45571
45814
  }
45572
- function uuid19(value, code) {
45815
+ function uuid20(value, code) {
45573
45816
  if (typeof value !== "string" || !UUID2.test(value)) fail5(code);
45574
45817
  return value.toLowerCase();
45575
45818
  }
@@ -45699,11 +45942,11 @@ function sendJson(socket, value, maxBytes) {
45699
45942
  function validateChallenge(frame, expectedProtocol) {
45700
45943
  if (frame.type !== "challenge") fail5("RELAY_HANDSHAKE_INVALID");
45701
45944
  protocol(frame.protocolVersion, expectedProtocol);
45702
- uuid19(frame.gatewayId, "RELAY_HANDSHAKE_INVALID");
45945
+ uuid20(frame.gatewayId, "RELAY_HANDSHAKE_INVALID");
45703
45946
  if (typeof frame.nonce !== "string" || frame.nonce.length < 32 || frame.nonce.length > 512 || /[\u0000-\u001f\u007f]/u.test(frame.nonce)) fail5("RELAY_HANDSHAKE_INVALID");
45704
45947
  if (typeof frame.expiresAt !== "string" || !Number.isFinite(Date.parse(frame.expiresAt)) || Date.parse(frame.expiresAt) <= Date.now()) fail5("RELAY_HANDSHAKE_INVALID");
45705
45948
  return {
45706
- challengeId: uuid19(frame.challengeId, "RELAY_HANDSHAKE_INVALID"),
45949
+ challengeId: uuid20(frame.challengeId, "RELAY_HANDSHAKE_INVALID"),
45707
45950
  nonce: frame.nonce,
45708
45951
  // Older servers offer no capabilities and verify only the v1 proof.
45709
45952
  machineIdentity: Array.isArray(frame.capabilities) && frame.capabilities.includes(MACHINE_IDENTITY_CAPABILITY)
@@ -45712,27 +45955,27 @@ function validateChallenge(frame, expectedProtocol) {
45712
45955
  function validateReady(frame, enrollment, expectedProtocol) {
45713
45956
  if (frame.type !== "connected") fail5("RELAY_HANDSHAKE_INVALID");
45714
45957
  protocol(frame.protocolVersion, expectedProtocol);
45715
- if (uuid19(frame.tenantId, "RELAY_HANDSHAKE_INVALID") !== enrollment.tenantId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
45716
- if (uuid19(frame.deviceId, "RELAY_HANDSHAKE_INVALID") !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
45958
+ if (uuid20(frame.tenantId, "RELAY_HANDSHAKE_INVALID") !== enrollment.tenantId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
45959
+ if (uuid20(frame.deviceId, "RELAY_HANDSHAKE_INVALID") !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
45717
45960
  const terminalMetrics2 = Array.isArray(frame.capabilities) && frame.capabilities.includes(TERMINAL_METRICS_CAPABILITY);
45718
45961
  return { connectionEpoch: epoch3(frame.connectionEpoch), terminalMetrics: terminalMetrics2 };
45719
45962
  }
45720
45963
  function validateRequest(frame, enrollment, expectedProtocol, connectionEpoch) {
45721
45964
  if (frame.type !== "relayFrame") fail5("RELAY_REQUEST_INVALID");
45722
45965
  protocol(frame.protocolVersion, expectedProtocol);
45723
- const tenantId = uuid19(frame.tenantId, "RELAY_REQUEST_INVALID");
45724
- const deviceId = uuid19(frame.deviceId, "RELAY_REQUEST_INVALID");
45966
+ const tenantId = uuid20(frame.tenantId, "RELAY_REQUEST_INVALID");
45967
+ const deviceId = uuid20(frame.deviceId, "RELAY_REQUEST_INVALID");
45725
45968
  if (tenantId !== enrollment.tenantId.toLowerCase() || deviceId !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
45726
45969
  if (epoch3(frame.connectionEpoch) !== connectionEpoch) fail5("RELAY_EPOCH_MISMATCH");
45727
45970
  const kind = frame.kind;
45728
45971
  if (typeof kind !== "string" || !REQUEST_KINDS.has(kind)) fail5("RELAY_REQUEST_INVALID");
45729
45972
  return {
45730
- requestId: uuid19(frame.requestId, "RELAY_REQUEST_INVALID"),
45973
+ requestId: uuid20(frame.requestId, "RELAY_REQUEST_INVALID"),
45731
45974
  tenantId,
45732
45975
  deviceId,
45733
45976
  connectionEpoch,
45734
- operationId: uuid19(frame.operationId, "RELAY_REQUEST_INVALID"),
45735
- executionId: uuid19(frame.executionId, "RELAY_REQUEST_INVALID"),
45977
+ operationId: uuid20(frame.operationId, "RELAY_REQUEST_INVALID"),
45978
+ executionId: uuid20(frame.executionId, "RELAY_REQUEST_INVALID"),
45736
45979
  kind,
45737
45980
  payload: frame.payload,
45738
45981
  deadlineAt: isoDate(frame.deadlineAt),
@@ -45774,8 +46017,8 @@ async function connectOnce(options) {
45774
46017
  const identity = await options.store.load();
45775
46018
  if (!identity || !identity.enrollment) fail5("ENROLLMENT_MISSING");
45776
46019
  const enrollment = identity.enrollment;
45777
- const tenantId = uuid19(enrollment.tenantId, "ENROLLMENT_INVALID");
45778
- const deviceId = uuid19(enrollment.deviceId, "ENROLLMENT_INVALID");
46020
+ const tenantId = uuid20(enrollment.tenantId, "ENROLLMENT_INVALID");
46021
+ const deviceId = uuid20(enrollment.deviceId, "ENROLLMENT_INVALID");
45779
46022
  const url2 = relayUrlFromEnrollment(enrollment);
45780
46023
  const socket = new wrapper_default(url2, [], {
45781
46024
  followRedirects: false,
@@ -46074,7 +46317,7 @@ import { createHash as createHash16 } from "node:crypto";
46074
46317
  import os5 from "node:os";
46075
46318
  import { open as open7 } from "node:fs/promises";
46076
46319
  import { constants as constants8 } from "node:fs";
46077
- import path19 from "node:path";
46320
+ import path20 from "node:path";
46078
46321
  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;
46079
46322
  async function readMachineGuid(timeoutMs2 = 5e3) {
46080
46323
  if (process.platform === "linux") {
@@ -46095,7 +46338,7 @@ async function readMachineGuid(timeoutMs2 = 5e3) {
46095
46338
  }
46096
46339
  }
46097
46340
  if (!["win32", "darwin"].includes(process.platform)) return null;
46098
- const reg = process.platform === "darwin" ? "/usr/sbin/ioreg" : path19.join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
46341
+ const reg = process.platform === "darwin" ? "/usr/sbin/ioreg" : path20.join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
46099
46342
  const args = process.platform === "darwin" ? ["-rd1", "-c", "IOPlatformExpertDevice"] : ["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid", "/reg:64"];
46100
46343
  const pattern = process.platform === "darwin" ? /"IOPlatformUUID"\s*=\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})"/ : MACHINE_GUID;
46101
46344
  return new Promise((resolve) => {
@@ -46165,10 +46408,10 @@ function canonicalOrigin2(value) {
46165
46408
  fail6("ORIGIN_INVALID");
46166
46409
  }
46167
46410
  }
46168
- function endpoint(origin, path28) {
46169
- return origin + path28;
46411
+ function endpoint(origin, path29) {
46412
+ return origin + path29;
46170
46413
  }
46171
- function uuid20(value, code) {
46414
+ function uuid21(value, code) {
46172
46415
  if (typeof value !== "string" || !UUID3.test(value)) fail6(code);
46173
46416
  return value.toLowerCase();
46174
46417
  }
@@ -46288,7 +46531,7 @@ var PairingClient = class {
46288
46531
  publicKey: identity.publicKeyPem,
46289
46532
  agentVersion: this.version
46290
46533
  }));
46291
- const pairingId = uuid20(response.pairingId, "PAIRING_RESPONSE_INVALID");
46534
+ const pairingId = uuid21(response.pairingId, "PAIRING_RESPONSE_INVALID");
46292
46535
  const expiresAt = parseDate(response.expiresAt, "PAIRING_RESPONSE_INVALID");
46293
46536
  const now = this.nowMs();
46294
46537
  if (expiresAt.getTime() <= now || expiresAt.getTime() - now > 30 * 6e4) fail6("PAIRING_RESPONSE_INVALID");
@@ -46322,7 +46565,7 @@ var PairingClient = class {
46322
46565
  }
46323
46566
  async completeOnce(beginResult, approved, displayNameValue) {
46324
46567
  const pairing = this.validateBeginResult(beginResult);
46325
- const tenantId = uuid20(approved.tenantId, "PAIRING_RESPONSE_INVALID");
46568
+ const tenantId = uuid21(approved.tenantId, "PAIRING_RESPONSE_INVALID");
46326
46569
  const email3 = accountEmail(approved.accountEmail);
46327
46570
  const name2 = displayName(displayNameValue);
46328
46571
  const identity = await this.currentIdentity();
@@ -46336,15 +46579,15 @@ var PairingClient = class {
46336
46579
  displayName: name2,
46337
46580
  agentVersion: this.version
46338
46581
  }));
46339
- const completedTenant = uuid20(response.tenantId, "PAIRING_RESPONSE_INVALID");
46582
+ const completedTenant = uuid21(response.tenantId, "PAIRING_RESPONSE_INVALID");
46340
46583
  if (completedTenant !== tenantId) fail6("PAIRING_RESPONSE_INVALID");
46341
- const deviceId = uuid20(response.deviceId, "PAIRING_RESPONSE_INVALID");
46584
+ const deviceId = uuid21(response.deviceId, "PAIRING_RESPONSE_INVALID");
46342
46585
  const enrollment = {
46343
46586
  tenantId,
46344
46587
  deviceId,
46345
46588
  serverOrigin: this.origin,
46346
46589
  accountEmail: email3,
46347
- ...response.accountId !== void 0 ? { accountId: uuid20(response.accountId, "PAIRING_RESPONSE_INVALID") } : {}
46590
+ ...response.accountId !== void 0 ? { accountId: uuid21(response.accountId, "PAIRING_RESPONSE_INVALID") } : {}
46348
46591
  };
46349
46592
  await this.store.saveEnrollment(enrollment);
46350
46593
  return { ...enrollment };
@@ -46358,7 +46601,7 @@ var PairingClient = class {
46358
46601
  state: response.state,
46359
46602
  expiresAt: parseDate(response.expiresAt, "PAIRING_RESPONSE_INVALID")
46360
46603
  };
46361
- if (response.tenantId !== void 0) result2.tenantId = uuid20(response.tenantId, "PAIRING_RESPONSE_INVALID");
46604
+ if (response.tenantId !== void 0) result2.tenantId = uuid21(response.tenantId, "PAIRING_RESPONSE_INVALID");
46362
46605
  if (response.accountEmail !== void 0) result2.accountEmail = accountEmail(response.accountEmail);
46363
46606
  return result2;
46364
46607
  }
@@ -46370,10 +46613,10 @@ var PairingClient = class {
46370
46613
  }
46371
46614
  validateBeginResult(value) {
46372
46615
  return {
46373
- pairingId: uuid20(value.pairingId, "PAIRING_INVALID"),
46616
+ pairingId: uuid21(value.pairingId, "PAIRING_INVALID"),
46374
46617
  pairingSecret: pairingSecret(value.pairingSecret),
46375
46618
  confirmationCode: confirmationCode(value.confirmationCode),
46376
- approvalUrl: approvalUrl(value.approvalUrl, this.origin, uuid20(value.pairingId, "PAIRING_INVALID")),
46619
+ approvalUrl: approvalUrl(value.approvalUrl, this.origin, uuid21(value.pairingId, "PAIRING_INVALID")),
46377
46620
  expiresAt: value.expiresAt instanceof Date ? new Date(value.expiresAt.getTime()) : parseDate(value.expiresAt, "PAIRING_INVALID"),
46378
46621
  keyFingerprint: fingerprint2(value.keyFingerprint)
46379
46622
  };
@@ -46668,15 +46911,15 @@ async function deliverGuardEvidence(target, packet, options = {}) {
46668
46911
 
46669
46912
  // agent/src/optimization-ledger.ts
46670
46913
  import { constants as constants9 } from "node:fs";
46671
- import { lstat as lstat8, mkdir as mkdir8, open as open8, readFile as readFile7, realpath as realpath8 } from "node:fs/promises";
46672
- import path20 from "node:path";
46914
+ import { lstat as lstat8, mkdir as mkdir8, open as open8, readFile as readFile8, realpath as realpath8 } from "node:fs/promises";
46915
+ import path21 from "node:path";
46673
46916
  var MAX_LEDGER_BYTES = 64 * 1024 * 1024;
46674
46917
  var MAX_NOTICE_LEDGER_BYTES = 8 * 1024 * 1024;
46675
46918
  function failure5(code) {
46676
46919
  return Object.assign(new Error(code), { code });
46677
46920
  }
46678
46921
  async function safeDirectory2(directory) {
46679
- const absolute2 = path20.resolve(directory);
46922
+ const absolute2 = path21.resolve(directory);
46680
46923
  let current2 = absolute2;
46681
46924
  for (; ; ) {
46682
46925
  try {
@@ -46684,7 +46927,7 @@ async function safeDirectory2(directory) {
46684
46927
  } catch (error62) {
46685
46928
  if (error62.code !== "ENOENT") throw error62;
46686
46929
  }
46687
- const parent = path20.dirname(current2);
46930
+ const parent = path21.dirname(current2);
46688
46931
  if (parent === current2) break;
46689
46932
  current2 = parent;
46690
46933
  }
@@ -46719,15 +46962,15 @@ var OptimizationLedger = class _OptimizationLedger {
46719
46962
  closed = false;
46720
46963
  static async open(directory) {
46721
46964
  const dir = await safeDirectory2(directory);
46722
- const filename = path20.join(dir, "live-efficiency.v1.jsonl");
46723
- const noticesFilename = path20.join(dir, "live-efficiency-notices.v1.jsonl");
46965
+ const filename = path21.join(dir, "live-efficiency.v1.jsonl");
46966
+ const noticesFilename = path21.join(dir, "live-efficiency-notices.v1.jsonl");
46724
46967
  let existing = "";
46725
46968
  try {
46726
46969
  const stat2 = await lstat8(filename);
46727
46970
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > MAX_LEDGER_BYTES) {
46728
46971
  throw failure5("OPTIMIZATION_LEDGER_INVALID");
46729
46972
  }
46730
- existing = await readFile7(filename, "utf8");
46973
+ existing = await readFile8(filename, "utf8");
46731
46974
  } catch (error62) {
46732
46975
  if (error62.code !== "ENOENT") throw error62;
46733
46976
  }
@@ -46741,7 +46984,7 @@ var OptimizationLedger = class _OptimizationLedger {
46741
46984
  try {
46742
46985
  const noticeStat = await lstat8(noticesFilename);
46743
46986
  if (!noticeStat.isFile() || noticeStat.isSymbolicLink() || noticeStat.size > MAX_NOTICE_LEDGER_BYTES) throw failure5("OPTIMIZATION_NOTICE_LEDGER_INVALID");
46744
- const notices = await readFile7(noticesFilename, "utf8");
46987
+ const notices = await readFile8(noticesFilename, "utf8");
46745
46988
  for (const line of notices.split("\n")) {
46746
46989
  if (!line) continue;
46747
46990
  const parsed = JSON.parse(line);
@@ -46870,7 +47113,7 @@ var OptimizationLedger = class _OptimizationLedger {
46870
47113
  // agent/src/monitor.ts
46871
47114
  import { createHash as createHash17, randomUUID as randomUUID12 } from "node:crypto";
46872
47115
  import { lstat as lstat9, mkdir as mkdir9, open as open9, rename as rename6, rm as rm7 } from "node:fs/promises";
46873
- import path21 from "node:path";
47116
+ import path22 from "node:path";
46874
47117
  import os6 from "node:os";
46875
47118
 
46876
47119
  // packages/agent-cli/bin/monitor-savings.mjs
@@ -46893,7 +47136,7 @@ function lifetimeSavingsView(raw) {
46893
47136
  // agent/src/monitor.ts
46894
47137
  function commandSummary2(tool) {
46895
47138
  if (tool.name !== "command_run") return { name: tool.name, command: tool.name };
46896
- const candidate = path21.win32.basename(tool.args.command).replace(/\.(exe|cmd|bat|com)$/i, "").toLowerCase();
47139
+ const candidate = path22.win32.basename(tool.args.command).replace(/\.(exe|cmd|bat|com)$/i, "").toLowerCase();
46897
47140
  const name2 = ["node", "npm", "npx", "git", "rg", "powershell", "pwsh", "cmd", "tsc", "python", "dotnet"].includes(candidate) ? candidate : "command";
46898
47141
  let command = name2;
46899
47142
  if (name2 === "node" && tool.args.args.includes("--test") && !tool.args.args.some((arg) => ["-e", "--eval", "-p", "--print"].includes(arg))) command += " --test";
@@ -46906,9 +47149,9 @@ function commandSummary2(tool) {
46906
47149
  var ProductionMonitor = class {
46907
47150
  constructor(directory, stateDirectory, agentVersion3) {
46908
47151
  this.agentVersion = agentVersion3;
46909
- const key = createHash17("sha256").update(path21.resolve(stateDirectory).toLowerCase()).digest("hex");
46910
- this.file = path21.join(directory, key + ".json");
46911
- this.transportFile = path21.join(directory, key + ".transport");
47152
+ const key = createHash17("sha256").update(path22.resolve(stateDirectory).toLowerCase()).digest("hex");
47153
+ this.file = path22.join(directory, key + ".json");
47154
+ this.transportFile = path22.join(directory, key + ".transport");
46912
47155
  }
46913
47156
  agentVersion;
46914
47157
  instanceId = randomUUID12();
@@ -47100,7 +47343,7 @@ var ProductionMonitor = class {
47100
47343
  schemaVersion: 1,
47101
47344
  instanceId: this.instanceId,
47102
47345
  pid: process.pid,
47103
- savingsSourceId: path21.basename(this.file, ".json"),
47346
+ savingsSourceId: path22.basename(this.file, ".json"),
47104
47347
  lifetimeSavings: this.lifetimeSavings && { ...this.lifetimeSavings },
47105
47348
  computer: this.computer,
47106
47349
  processName: "lc-agent",
@@ -47134,7 +47377,7 @@ var ProductionMonitor = class {
47134
47377
  return this.writing;
47135
47378
  }
47136
47379
  async write(file2, contents) {
47137
- const directory = path21.dirname(file2);
47380
+ const directory = path22.dirname(file2);
47138
47381
  await mkdir9(directory, { recursive: true, mode: 448 });
47139
47382
  const stat2 = await lstat9(directory);
47140
47383
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw Error("MONITOR_DIRECTORY_INVALID");
@@ -47440,7 +47683,7 @@ var NativeEventSupervisor = class {
47440
47683
  };
47441
47684
 
47442
47685
  // agent/src/native-fabric-observer.ts
47443
- var uuid21 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
47686
+ var uuid22 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
47444
47687
  var NativeFabricObserver = class {
47445
47688
  constructor(supervisor, source) {
47446
47689
  this.supervisor = supervisor;
@@ -47462,7 +47705,7 @@ var NativeFabricObserver = class {
47462
47705
  unsubscribe;
47463
47706
  connected(authenticatedDeviceId) {
47464
47707
  this.disconnected();
47465
- if (uuid21.test(authenticatedDeviceId)) this.deviceId = authenticatedDeviceId.toLowerCase();
47708
+ if (uuid22.test(authenticatedDeviceId)) this.deviceId = authenticatedDeviceId.toLowerCase();
47466
47709
  this.activity();
47467
47710
  }
47468
47711
  disconnected() {
@@ -47497,17 +47740,17 @@ var NativeFabricObserver = class {
47497
47740
  void Promise.resolve().then(() => this.source.mailbox.snapshot()).then((state) => {
47498
47741
  if (this.closed || expired || generation !== this.generation) return;
47499
47742
  if (state.workers.length > 64 || state.assignments.length > 256 || state.messages.length > 1024) throw Error("FABRIC_BOUND_INVALID");
47500
- const workers = new Set(state.workers.filter((w) => w.device?.deviceId.toLowerCase() === deviceId && uuid21.test(w.workerId)).map((w) => w.workerId));
47743
+ const workers = new Set(state.workers.filter((w) => w.device?.deviceId.toLowerCase() === deviceId && uuid22.test(w.workerId)).map((w) => w.workerId));
47501
47744
  const assignments = new Map(state.assignments.filter((a) => workers.has(a.workerId)).map((a) => [a.assignmentId, a]));
47502
47745
  const refs = /* @__PURE__ */ new Map();
47503
47746
  for (const a of assignments.values()) {
47504
47747
  const id2 = a.execution?.executionId;
47505
- if (!id2 || !uuid21.test(id2)) continue;
47748
+ if (!id2 || !uuid22.test(id2)) continue;
47506
47749
  if (refs.has(id2.toLowerCase())) throw Error("FABRIC_EXECUTION_CONFLICT");
47507
47750
  refs.set(id2.toLowerCase(), {
47508
47751
  executionId: id2.toLowerCase(),
47509
47752
  workerId: a.workerId.toLowerCase(),
47510
- ...uuid21.test(a.taskId) ? { taskId: a.taskId.toLowerCase() } : {}
47753
+ ...uuid22.test(a.taskId) ? { taskId: a.taskId.toLowerCase() } : {}
47511
47754
  });
47512
47755
  }
47513
47756
  this.referencesByExecution.clear();
@@ -47559,13 +47802,13 @@ var NativeFabricObserver = class {
47559
47802
  };
47560
47803
 
47561
47804
  // agent/src/native-fabric-startup.ts
47562
- import { lstat as lstat11, mkdir as mkdir12, open as open11, readFile as readFile8 } from "node:fs/promises";
47563
- import path24 from "node:path";
47805
+ import { lstat as lstat11, mkdir as mkdir12, open as open11, readFile as readFile9 } from "node:fs/promises";
47806
+ import path25 from "node:path";
47564
47807
 
47565
47808
  // src/agent-fabric-service.ts
47566
47809
  import { lstat as lstat10, mkdir as mkdir11, realpath as realpath9 } from "node:fs/promises";
47567
47810
  import { watch } from "node:fs";
47568
- import path23 from "node:path";
47811
+ import path24 from "node:path";
47569
47812
 
47570
47813
  // src/agent-runtime-identity.ts
47571
47814
  import { createHash as createHash19, randomBytes as randomBytes7, randomUUID as randomUUID14, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
@@ -47573,13 +47816,13 @@ import { createHash as createHash19, randomBytes as randomBytes7, randomUUID as
47573
47816
  // src/agent-fabric-state.ts
47574
47817
  import { randomUUID as randomUUID13 } from "node:crypto";
47575
47818
  import { mkdir as mkdir10, open as open10, rename as rename7, unlink as unlink2 } from "node:fs/promises";
47576
- import path22 from "node:path";
47819
+ import path23 from "node:path";
47577
47820
  var queues = /* @__PURE__ */ new Map();
47578
47821
  var FabricStateFile = class {
47579
47822
  constructor(file2, maxBytes, parse3) {
47580
47823
  this.maxBytes = maxBytes;
47581
47824
  this.parse = parse3;
47582
- this.file = path22.resolve(file2);
47825
+ this.file = path23.resolve(file2);
47583
47826
  }
47584
47827
  maxBytes;
47585
47828
  parse;
@@ -47623,7 +47866,7 @@ var FabricStateFile = class {
47623
47866
  }
47624
47867
  update(fn, create) {
47625
47868
  return this.serial(async () => {
47626
- if (create) await mkdir10(path22.dirname(this.file), { recursive: true });
47869
+ if (create) await mkdir10(path23.dirname(this.file), { recursive: true });
47627
47870
  const lockPath = this.file + ".lock";
47628
47871
  const token = randomUUID13();
47629
47872
  const lock = await open10(lockPath, "wx", 384).catch((error62) => {
@@ -48267,9 +48510,9 @@ var WorkerRequest = external_exports.discriminatedUnion("operation", [
48267
48510
  var AgentFabricService = class _AgentFabricService {
48268
48511
  constructor(directory, controllerId) {
48269
48512
  this.directory = directory;
48270
- this.identities = new AgentRuntimeIdentityStore(path23.join(directory, "identities.json"));
48513
+ this.identities = new AgentRuntimeIdentityStore(path24.join(directory, "identities.json"));
48271
48514
  this.mailbox = new AgentWorkerMailbox(
48272
- path23.join(directory, "mailbox.json"),
48515
+ path24.join(directory, "mailbox.json"),
48273
48516
  controllerId,
48274
48517
  this.identities,
48275
48518
  void 0,
@@ -48284,21 +48527,21 @@ var AgentFabricService = class _AgentFabricService {
48284
48527
  closed = false;
48285
48528
  static async open(directory, controllerId, device = null, initialize = true) {
48286
48529
  const expected = Binding.parse({ version: 1, controllerId, device, initialized: false });
48287
- const absolute2 = path23.resolve(directory);
48288
- for (let current2 = absolute2; ; current2 = path23.dirname(current2)) {
48530
+ const absolute2 = path24.resolve(directory);
48531
+ for (let current2 = absolute2; ; current2 = path24.dirname(current2)) {
48289
48532
  try {
48290
48533
  if ((await lstat10(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
48291
48534
  } catch (error62) {
48292
48535
  if (error62.code !== "ENOENT") throw error62;
48293
48536
  }
48294
- if (path23.dirname(current2) === current2) break;
48537
+ if (path24.dirname(current2) === current2) break;
48295
48538
  }
48296
48539
  if (initialize) await mkdir11(absolute2, { recursive: true, mode: 448 });
48297
48540
  if (!(await lstat10(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
48298
48541
  throw Error("FABRIC_DIRECTORY_INVALID");
48299
48542
  const present = /* @__PURE__ */ new Set();
48300
48543
  for (const name2 of ["binding.json", "mailbox.json", "identities.json"]) {
48301
- const file2 = await lstat10(path23.join(absolute2, name2)).catch((error62) => {
48544
+ const file2 = await lstat10(path24.join(absolute2, name2)).catch((error62) => {
48302
48545
  if (error62.code === "ENOENT") return null;
48303
48546
  throw error62;
48304
48547
  });
@@ -48306,7 +48549,7 @@ var AgentFabricService = class _AgentFabricService {
48306
48549
  if (file2) present.add(name2);
48307
48550
  }
48308
48551
  if (!present.has("binding.json") && present.size) throw Error("FABRIC_BINDING_MISSING");
48309
- const binding2 = new FabricStateFile(path23.join(absolute2, "binding.json"), 2048, (value) => Binding.parse(value));
48552
+ const binding2 = new FabricStateFile(path24.join(absolute2, "binding.json"), 2048, (value) => Binding.parse(value));
48310
48553
  const service2 = new _AgentFabricService(absolute2, controllerId);
48311
48554
  await binding2.update(async (state) => {
48312
48555
  if (state.controllerId !== expected.controllerId || JSON.stringify(state.device) !== JSON.stringify(expected.device))
@@ -48321,7 +48564,7 @@ var AgentFabricService = class _AgentFabricService {
48321
48564
  state.initialized = true;
48322
48565
  }
48323
48566
  const snapshot2 = await service2.mailbox.snapshot();
48324
- if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat10(path23.join(absolute2, "identities.json"));
48567
+ if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat10(path24.join(absolute2, "identities.json"));
48325
48568
  }, initialize ? () => expected : void 0);
48326
48569
  return service2;
48327
48570
  }
@@ -48408,7 +48651,7 @@ var Delivery = external_exports.strictObject({ capability: external_exports.stri
48408
48651
  async function openNativeFabric(stateDirectory, enrollment, box, initialize = true) {
48409
48652
  const controllerId = "device-" + external_exports.string().uuid().parse(enrollment.deviceId).toLowerCase();
48410
48653
  const tenantId = external_exports.string().uuid().parse(enrollment.tenantId).toLowerCase();
48411
- const parent = path24.join(stateDirectory, ".local-commander"), marker = path24.join(parent, "fabric-established.json");
48654
+ const parent = path25.join(stateDirectory, ".local-commander"), marker = path25.join(parent, "fabric-established.json");
48412
48655
  try {
48413
48656
  await mkdir12(parent, { mode: 448 });
48414
48657
  } catch (error62) {
@@ -48420,7 +48663,7 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
48420
48663
  let fresh = false;
48421
48664
  try {
48422
48665
  const info = await lstat11(marker);
48423
- if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile8(marker, "utf8") !== expected)
48666
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile9(marker, "utf8") !== expected)
48424
48667
  throw Error("FABRIC_BINDING_CHANGED");
48425
48668
  } catch (error62) {
48426
48669
  if (error62.code !== "ENOENT" || !initialize) throw error62;
@@ -48434,13 +48677,13 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
48434
48677
  fresh = true;
48435
48678
  }
48436
48679
  const service2 = await AgentFabricService.open(
48437
- path24.join(stateDirectory, ".local-commander", "fabric"),
48680
+ path25.join(stateDirectory, ".local-commander", "fabric"),
48438
48681
  controllerId,
48439
48682
  { deviceId: enrollment.deviceId.toLowerCase(), enrollmentEvidenceRef: "enrollment-" + tenantId },
48440
48683
  fresh
48441
48684
  );
48442
48685
  const purpose = "native-fabric:" + tenantId + ":" + controllerId;
48443
- const credentialFile = (workerId) => path24.join(service2.directory, external_exports.string().uuid().parse(workerId) + ".capability");
48686
+ const credentialFile = (workerId) => path25.join(service2.directory, external_exports.string().uuid().parse(workerId) + ".capability");
48444
48687
  const decode4 = (value) => {
48445
48688
  const credential = Credential.parse(JSON.parse(box.open(Buffer.from(value, "base64"), purpose).toString("utf8")));
48446
48689
  if (credential.controllerId !== controllerId) throw Error("FABRIC_WORKER_DENIED");
@@ -48449,7 +48692,7 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
48449
48692
  async function capability(workerId) {
48450
48693
  const file2 = credentialFile(workerId), info = await lstat11(file2);
48451
48694
  if (!info.isFile() || info.isSymbolicLink() || info.size > 4096) throw Error("FABRIC_CREDENTIAL_UNKNOWN");
48452
- const encoded = await readFile8(file2, "utf8");
48695
+ const encoded = await readFile9(file2, "utf8");
48453
48696
  if (decode4(encoded).workerId !== workerId) throw Error("FABRIC_WORKER_DENIED");
48454
48697
  return encoded;
48455
48698
  }
@@ -48541,8 +48784,8 @@ async function readFabricRequest(input2 = process.stdin) {
48541
48784
 
48542
48785
  // agent/src/supervisor-liveness.ts
48543
48786
  import { spawn as spawn6 } from "node:child_process";
48544
- import path25 from "node:path";
48545
- import { setTimeout as delay2 } from "node:timers/promises";
48787
+ import path26 from "node:path";
48788
+ import { setTimeout as delay3 } from "node:timers/promises";
48546
48789
  var ROW = /^"([^"]+)","(\d{1,10})"/;
48547
48790
  function parseTasklist(output2, image) {
48548
48791
  const pids = /* @__PURE__ */ new Set();
@@ -48556,7 +48799,7 @@ function parseTasklist(output2, image) {
48556
48799
  }
48557
48800
  function listProcesses(image, timeoutMs2 = 5e3) {
48558
48801
  if (process.platform !== "win32" || !/^[A-Za-z0-9._-]{1,64}\.exe$/i.test(image)) return Promise.resolve(null);
48559
- const tasklist = path25.join(process.env.SystemRoot || "C:\\Windows", "System32", "tasklist.exe");
48802
+ const tasklist = path26.join(process.env.SystemRoot || "C:\\Windows", "System32", "tasklist.exe");
48560
48803
  return new Promise((resolve) => {
48561
48804
  let output2 = "", settled = false;
48562
48805
  const finish = (value) => {
@@ -48584,7 +48827,9 @@ function listProcesses(image, timeoutMs2 = 5e3) {
48584
48827
  });
48585
48828
  }
48586
48829
  function supervisorLiveness(helperPath, options = {}) {
48587
- const image = path25.basename(helperPath), waitMs = options.waitMs ?? 1e4, pollMs = options.pollMs ?? 500, list = options.list ?? listProcesses;
48830
+ if (process.platform === "linux" && !options.list) return linuxSupervisorLiveness;
48831
+ if (process.platform === "darwin" && !options.list) return (pids, _linux, darwin) => darwinSupervisorLiveness(path26.join(path26.dirname(helperPath), "posix-host"), pids, darwin);
48832
+ const image = path26.basename(helperPath), waitMs = options.waitMs ?? 1e4, pollMs = options.pollMs ?? 500, list = options.list ?? listProcesses;
48588
48833
  return async (pids) => {
48589
48834
  const deadline = Date.now() + waitMs;
48590
48835
  for (; ; ) {
@@ -48592,24 +48837,24 @@ function supervisorLiveness(helperPath, options = {}) {
48592
48837
  if (!running) return null;
48593
48838
  const live = new Set(pids.filter((pid) => running.has(pid)));
48594
48839
  if (!live.size || Date.now() >= deadline) return live;
48595
- await delay2(pollMs);
48840
+ await delay3(pollMs);
48596
48841
  }
48597
48842
  };
48598
48843
  }
48599
48844
 
48600
48845
  // agent/src/content-audit.ts
48601
48846
  import { createReadStream } from "node:fs";
48602
- import { appendFile, lstat as lstat12, mkdir as mkdir13, open as open12, readdir as readdir5, readFile as readFile9, rename as rename8, rm as rm8, writeFile as writeFile4 } from "node:fs/promises";
48603
- import path26 from "node:path";
48847
+ import { appendFile, lstat as lstat12, mkdir as mkdir13, open as open12, readdir as readdir5, readFile as readFile10, rename as rename8, rm as rm8, writeFile as writeFile4 } from "node:fs/promises";
48848
+ import path27 from "node:path";
48604
48849
  import { performance as performance3 } from "node:perf_hooks";
48605
48850
  import { createInterface as createInterface2 } from "node:readline";
48606
48851
  import { randomBytes as randomBytes9 } from "node:crypto";
48607
48852
 
48608
48853
  // src/audit-crypto.ts
48609
48854
  import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, createHash as createHash20, randomBytes as randomBytes8 } from "node:crypto";
48610
- import { promisify } from "node:util";
48855
+ import { promisify as promisify3 } from "node:util";
48611
48856
  import { gunzipSync, gzip, gzipSync } from "node:zlib";
48612
- var gzipAsync = promisify(gzip);
48857
+ var gzipAsync = promisify3(gzip);
48613
48858
  var AUDIT_ENCRYPTION_ALGORITHM = "A256GCM";
48614
48859
  var AUDIT_COMPRESSION = "gzip";
48615
48860
  var AUDIT_RECOVERY_KEY_PREFIX = "lca1_";
@@ -48769,7 +49014,7 @@ var FILE = /^(full|metrics)-(\d{4}-\d{2}-\d{2})\.jsonl$/;
48769
49014
  var PAUSED_FILE = "paused.json";
48770
49015
  var DAY_MS = 864e5;
48771
49016
  function contentAuditDirectory(stateDir) {
48772
- return path26.join(path26.dirname(path26.resolve(stateDir)), "Audit");
49017
+ return path27.join(path27.dirname(path27.resolve(stateDir)), "Audit");
48773
49018
  }
48774
49019
  async function plainDirectory(dir) {
48775
49020
  await mkdir13(dir, { recursive: true, mode: 448 });
@@ -48788,7 +49033,7 @@ async function auditFiles(dir) {
48788
49033
  for (const name2 of names) {
48789
49034
  const match = FILE.exec(name2);
48790
49035
  if (!match) continue;
48791
- const info = await lstat12(path26.join(dir, name2));
49036
+ const info = await lstat12(path27.join(dir, name2));
48792
49037
  if (info.isFile()) files.push({ name: name2, kind: match[1], day: match[2], bytes: info.size });
48793
49038
  }
48794
49039
  return files.sort((a, b) => a.name.localeCompare(b.name));
@@ -48826,7 +49071,7 @@ var ContentAudit = class _ContentAudit {
48826
49071
  skipped = 0;
48827
49072
  closed = false;
48828
49073
  static async open(options) {
48829
- const dir = path26.resolve(options.directory);
49074
+ const dir = path27.resolve(options.directory);
48830
49075
  await plainDirectory(dir);
48831
49076
  const audit = new _ContentAudit(
48832
49077
  dir,
@@ -48835,7 +49080,7 @@ var ContentAudit = class _ContentAudit {
48835
49080
  { retentionDays: options.retentionDays ?? AUDIT_RETENTION_DAYS, maxBytes: options.maxBytes ?? AUDIT_MAX_BYTES },
48836
49081
  options.now ?? (() => /* @__PURE__ */ new Date())
48837
49082
  );
48838
- await rm8(path26.join(dir, PAUSED_FILE), { force: true });
49083
+ await rm8(path27.join(dir, PAUSED_FILE), { force: true });
48839
49084
  await audit.rollover(audit.now());
48840
49085
  if (audit.usedBytes >= audit.limits.maxBytes) await audit.pause("QUOTA_EXCEEDED");
48841
49086
  return audit;
@@ -48905,8 +49150,8 @@ var ContentAudit = class _ContentAudit {
48905
49150
  await this.pause("QUOTA_EXCEEDED");
48906
49151
  return;
48907
49152
  }
48908
- await appendFile(path26.join(this.dir, `full-${day}.jsonl`), line, { mode: 384 });
48909
- await appendFile(path26.join(this.dir, `metrics-${day}.jsonl`), metrics, { mode: 384 });
49153
+ await appendFile(path27.join(this.dir, `full-${day}.jsonl`), line, { mode: 384 });
49154
+ await appendFile(path27.join(this.dir, `metrics-${day}.jsonl`), metrics, { mode: 384 });
48910
49155
  this.usedBytes += bytes3;
48911
49156
  }
48912
49157
  /** Daily retention runs on the first write of a new day; no timer or background scan. */
@@ -48915,7 +49160,7 @@ var ContentAudit = class _ContentAudit {
48915
49160
  const cutoff = new Date(at.getTime() - this.limits.retentionDays * DAY_MS).toISOString().slice(0, 10);
48916
49161
  let used = 0;
48917
49162
  for (const file2 of await auditFiles(this.dir)) {
48918
- if (file2.day <= cutoff) await rm8(path26.join(this.dir, file2.name), { force: true });
49163
+ if (file2.day <= cutoff) await rm8(path27.join(this.dir, file2.name), { force: true });
48919
49164
  else used += file2.bytes;
48920
49165
  }
48921
49166
  this.usedBytes = used;
@@ -48923,7 +49168,7 @@ var ContentAudit = class _ContentAudit {
48923
49168
  async pause(reason) {
48924
49169
  if (this.paused) return;
48925
49170
  this.paused = reason;
48926
- await writeJsonAtomic(path26.join(this.dir, PAUSED_FILE), { reason, at: this.now().toISOString() });
49171
+ await writeJsonAtomic(path27.join(this.dir, PAUSED_FILE), { reason, at: this.now().toISOString() });
48927
49172
  }
48928
49173
  };
48929
49174
  function percentiles(values) {
@@ -48945,13 +49190,13 @@ async function* jsonLines(file2) {
48945
49190
  }
48946
49191
  var count2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
48947
49192
  async function summarizeContentAudit(directory, key) {
48948
- const dir = path26.resolve(directory);
49193
+ const dir = path27.resolve(directory);
48949
49194
  const files = await auditFiles(dir);
48950
49195
  const days = /* @__PURE__ */ new Map();
48951
49196
  const sizes = [];
48952
49197
  const timings = [];
48953
49198
  for (const file2 of files.filter((f) => f.kind === "metrics")) {
48954
- for await (const line of jsonLines(path26.join(dir, file2.name))) {
49199
+ for await (const line of jsonLines(path27.join(dir, file2.name))) {
48955
49200
  let day = days.get(file2.day);
48956
49201
  if (!day) {
48957
49202
  day = { day: file2.day, records: 0, failed: 0, rawBytes: 0, sanitizedBytes: 0, compressedBytes: 0, envelopeBytes: 0 };
@@ -48971,7 +49216,7 @@ async function summarizeContentAudit(directory, key) {
48971
49216
  }
48972
49217
  let paused = null;
48973
49218
  try {
48974
- const value = JSON.parse(await readFile9(path26.join(dir, PAUSED_FILE), "utf8"));
49219
+ const value = JSON.parse(await readFile10(path27.join(dir, PAUSED_FILE), "utf8"));
48975
49220
  if (typeof value.reason === "string" && typeof value.at === "string") paused = { reason: value.reason.slice(0, 40), at: value.at.slice(0, 40) };
48976
49221
  } catch {
48977
49222
  }
@@ -48979,7 +49224,7 @@ async function summarizeContentAudit(directory, key) {
48979
49224
  const newest = files.filter((f) => f.kind === "full").at(-1);
48980
49225
  if (key && newest) {
48981
49226
  const tail = [];
48982
- for await (const line of jsonLines(path26.join(dir, newest.name))) {
49227
+ for await (const line of jsonLines(path27.join(dir, newest.name))) {
48983
49228
  tail.push(line);
48984
49229
  if (tail.length > 5) tail.shift();
48985
49230
  }
@@ -49013,10 +49258,10 @@ async function summarizeContentAudit(directory, key) {
49013
49258
  };
49014
49259
  }
49015
49260
  async function restoreContentAudit(input2, output2, key) {
49016
- const handle = await open12(path26.resolve(output2), "wx", 384);
49261
+ const handle = await open12(path27.resolve(output2), "wx", 384);
49017
49262
  let records = 0, failed = 0;
49018
49263
  try {
49019
- for await (const line of jsonLines(path26.resolve(input2))) {
49264
+ for await (const line of jsonLines(path27.resolve(input2))) {
49020
49265
  try {
49021
49266
  await handle.appendFile(JSON.stringify(decryptAuditRecord(line, key)) + "\n");
49022
49267
  records += 1;
@@ -49031,7 +49276,7 @@ async function restoreContentAudit(input2, output2, key) {
49031
49276
  }
49032
49277
 
49033
49278
  // agent/src/main.ts
49034
- var AGENT_VERSION2 = true ? "0.3.42" : "0.3.2";
49279
+ var AGENT_VERSION2 = true ? "0.3.44" : "0.3.2";
49035
49280
  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" : "";
49036
49281
  var AI_CONNECTION_SHIPPED = false;
49037
49282
  function processAlive(pid) {
@@ -49045,7 +49290,7 @@ function processAlive(pid) {
49045
49290
  }
49046
49291
  async function claimAgentProcess(stateDir, runtimeDir, version2) {
49047
49292
  await mkdir14(stateDir, { recursive: true });
49048
- const file2 = path27.join(stateDir, "agent-process.json");
49293
+ const file2 = path28.join(stateDir, "agent-process.json");
49049
49294
  for (let attempt = 0; attempt < 2; attempt += 1) {
49050
49295
  try {
49051
49296
  const handle = await open13(file2, "wx", 384);
@@ -49056,7 +49301,7 @@ async function claimAgentProcess(stateDir, runtimeDir, version2) {
49056
49301
  }
49057
49302
  return async () => {
49058
49303
  try {
49059
- const current2 = JSON.parse(await readFile10(file2, "utf8"));
49304
+ const current2 = JSON.parse(await readFile11(file2, "utf8"));
49060
49305
  if (current2.pid === process.pid) await rm9(file2, { force: true });
49061
49306
  } catch {
49062
49307
  }
@@ -49065,7 +49310,7 @@ async function claimAgentProcess(stateDir, runtimeDir, version2) {
49065
49310
  if (!error62 || typeof error62 !== "object" || !("code" in error62) || error62.code !== "EEXIST") throw error62;
49066
49311
  let stale = true;
49067
49312
  try {
49068
- const current2 = JSON.parse(await readFile10(file2, "utf8"));
49313
+ const current2 = JSON.parse(await readFile11(file2, "utf8"));
49069
49314
  stale = typeof current2.pid !== "number" || !processAlive(current2.pid);
49070
49315
  } catch {
49071
49316
  }
@@ -49088,7 +49333,7 @@ function aborted2(signal, ms) {
49088
49333
  });
49089
49334
  }
49090
49335
  async function runAgent(options) {
49091
- const delay3 = options.reconnectDelayMs ?? 2e3;
49336
+ const delay4 = options.reconnectDelayMs ?? 2e3;
49092
49337
  const monitor = (update) => {
49093
49338
  try {
49094
49339
  update();
@@ -49098,7 +49343,7 @@ async function runAgent(options) {
49098
49343
  }
49099
49344
  };
49100
49345
  try {
49101
- if (!Number.isInteger(delay3) || delay3 < 0 || delay3 > 3e4) throw Error("RECONNECT_DELAY_INVALID");
49346
+ if (!Number.isInteger(delay4) || delay4 < 0 || delay4 > 3e4) throw Error("RECONNECT_DELAY_INVALID");
49102
49347
  const identity = await options.store.load();
49103
49348
  if (!identity?.enrollment) throw Error("ENROLLMENT_MISSING");
49104
49349
  const origin = identity.enrollment.serverOrigin;
@@ -49278,7 +49523,7 @@ async function runAgent(options) {
49278
49523
  await bridge.disconnected();
49279
49524
  connection = null;
49280
49525
  }
49281
- if (!options.signal.aborted) await aborted2(options.signal, delay3);
49526
+ if (!options.signal.aborted) await aborted2(options.signal, delay4);
49282
49527
  }
49283
49528
  } finally {
49284
49529
  try {
@@ -49314,10 +49559,10 @@ async function openContentAudit(store, stateDir) {
49314
49559
  async function main() {
49315
49560
  if (!["win32", "linux", "darwin"].includes(process.platform)) throw Error("PLATFORM_UNSUPPORTED");
49316
49561
  const appData = process.env.LC_AGENT_DATA_DIR ?? (process.platform === "win32" ? process.env.LOCALAPPDATA : posixDataHome());
49317
- if (!appData || !path27.isAbsolute(appData)) throw Error("APP_DATA_MISSING");
49318
- const stateDir = process.env.LC_AGENT_STATE_DIR ?? path27.join(appData, "LocalCommander", "Agent");
49319
- const binaryDir = path27.dirname(process.platform === "win32" ? process.execPath : await realpath10(process.execPath));
49320
- const ownerBridgePath = process.env.LC_OWNER_BRIDGE ?? path27.join(binaryDir, process.platform === "win32" ? "OwnerBridge.exe" : "owner-store");
49562
+ if (!appData || !path28.isAbsolute(appData)) throw Error("APP_DATA_MISSING");
49563
+ const stateDir = process.env.LC_AGENT_STATE_DIR ?? path28.join(appData, "LocalCommander", "Agent");
49564
+ const binaryDir = path28.dirname(process.platform === "win32" ? process.execPath : await realpath10(process.execPath));
49565
+ const ownerBridgePath = process.env.LC_OWNER_BRIDGE ?? path28.join(binaryDir, process.platform === "win32" ? "OwnerBridge.exe" : "owner-store");
49321
49566
  const store = await WindowsPrivateStore.open(stateDir, ownerBridgePath);
49322
49567
  const command = process.argv[2] ?? "run";
49323
49568
  if (process.platform !== "win32" && (command.startsWith("guard-") || command.startsWith("network-"))) throw Error("FEATURE_PLATFORM_UNSUPPORTED");
@@ -49412,7 +49657,7 @@ async function main() {
49412
49657
  }
49413
49658
  if (command === "efficiency-report") {
49414
49659
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
49415
- const ledger = await OptimizationLedger.open(path27.join(stateDir, "optimization"));
49660
+ const ledger = await OptimizationLedger.open(path28.join(stateDir, "optimization"));
49416
49661
  try {
49417
49662
  process.stdout.write(JSON.stringify(await ledger.report(), null, 2) + "\n");
49418
49663
  } finally {
@@ -49422,7 +49667,7 @@ async function main() {
49422
49667
  }
49423
49668
  if (command === "guard-configure") {
49424
49669
  if (args.length !== 1) throw Error("AGENT_COMMAND_INVALID");
49425
- const filename = await (await import("node:fs/promises")).realpath(path27.resolve(args[0]));
49670
+ const filename = await (await import("node:fs/promises")).realpath(path28.resolve(args[0]));
49426
49671
  const input2 = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await readWindowsFile(ownerBridgePath, filename, 2e5)));
49427
49672
  if (!input2 || typeof input2 !== "object" || Object.keys(input2).sort().join(",") !== "compact,settings") throw Error("GUARD_CONFIGURATION_INVALID");
49428
49673
  await store.configureGuard(input2.settings, input2.compact);
@@ -49441,7 +49686,7 @@ async function main() {
49441
49686
  }
49442
49687
  if (command === "guard-evidence") {
49443
49688
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
49444
- const journal = await NativeJournal.open(path27.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
49689
+ const journal = await NativeJournal.open(path28.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
49445
49690
  try {
49446
49691
  process.stdout.write(JSON.stringify(await journal.guardEvidence()) + "\n");
49447
49692
  } finally {
@@ -49453,7 +49698,7 @@ async function main() {
49453
49698
  if (args.length !== (command === "guard-export" ? 0 : 1)) throw Error("AGENT_COMMAND_INVALID");
49454
49699
  const identity = await store.load();
49455
49700
  if (!identity?.enrollment) throw Error("ENROLLMENT_MISSING");
49456
- const journal = await NativeJournal.open(path27.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
49701
+ const journal = await NativeJournal.open(path28.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
49457
49702
  try {
49458
49703
  const { tenantId, deviceId } = identity.enrollment;
49459
49704
  const records = (await journal.guardEvidence()).filter((record2) => record2.tenantId === tenantId && record2.deviceId === deviceId);
@@ -49531,27 +49776,27 @@ async function main() {
49531
49776
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
49532
49777
  if (!(await store.load())?.enrollment) throw Error("ENROLLMENT_MISSING");
49533
49778
  const releaseProcess = await claimAgentProcess(stateDir, binaryDir, AGENT_VERSION2);
49534
- const monitor = new ProductionMonitor(path27.join(appData, "LocalCommander", "Monitor"), stateDir, AGENT_VERSION2);
49779
+ const monitor = new ProductionMonitor(path28.join(appData, "LocalCommander", "Monitor"), stateDir, AGENT_VERSION2);
49535
49780
  const publishMonitor = () => monitor.flush().catch(() => {
49536
49781
  process.stderr.write("MONITOR_WRITE_FAILED\n");
49537
49782
  });
49538
49783
  await publishMonitor();
49539
49784
  try {
49540
49785
  const journal = await NativeJournal.open(
49541
- path27.join(stateDir, "journal"),
49786
+ path28.join(stateDir, "journal"),
49542
49787
  new SecretBox({ "1": await store.loadDataKey() }),
49543
- process.platform === "win32" ? {} : { lockHelper: path27.join(binaryDir, "posix-host") }
49788
+ process.platform === "win32" ? {} : { lockHelper: path28.join(binaryDir, "posix-host") }
49544
49789
  );
49545
49790
  const ledgerLoss = () => {
49546
49791
  process.stderr.write("OPTIMIZATION_TELEMETRY_INCOMPLETE\n");
49547
49792
  };
49548
49793
  const efficiencyLedger = await new OptionalWork(ledgerLoss, 1e3, 1).run(
49549
- () => OptimizationLedger.open(path27.join(stateDir, "optimization")),
49794
+ () => OptimizationLedger.open(path28.join(stateDir, "optimization")),
49550
49795
  void 0,
49551
49796
  (ledger) => ledger.close()
49552
49797
  );
49553
49798
  try {
49554
- const helperPath = process.env.LC_JOB_HOST ?? path27.join(binaryDir, process.platform === "win32" ? "JobHost.exe" : "job-host.mjs");
49799
+ const helperPath = process.env.LC_JOB_HOST ?? path28.join(binaryDir, process.platform === "win32" ? "JobHost.exe" : "job-host.mjs");
49555
49800
  const tools = new NativeTools({ stateDirectory: stateDir, helperPath, ownerBridgePath, programs: await store.loadPrograms() });
49556
49801
  const stop = new AbortController();
49557
49802
  process.once("SIGINT", () => stop.abort());
@@ -49622,7 +49867,7 @@ async function main() {
49622
49867
  await releaseProcess();
49623
49868
  }
49624
49869
  }
49625
- var entrypoint = process.argv[1] && (process.platform === "win32" ? path27.resolve(process.argv[1]) : await realpath10(process.argv[1]).catch(() => null));
49870
+ var entrypoint = process.argv[1] && (process.platform === "win32" ? path28.resolve(process.argv[1]) : await realpath10(process.argv[1]).catch(() => null));
49626
49871
  if (entrypoint === fileURLToPath(import.meta.url)) {
49627
49872
  void main().catch((error62) => {
49628
49873
  const code = error62 instanceof Error && /^[A-Z0-9_]{1,64}$/.test(error62.message) ? error62.message : "AGENT_START_FAILED";