local-commander-agent 0.3.51 → 0.3.52

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
@@ -3240,7 +3240,7 @@ var require_stream = __commonJS({
3240
3240
  };
3241
3241
  duplex._final = function(callback) {
3242
3242
  if (ws.readyState === ws.CONNECTING) {
3243
- ws.once("open", function open14() {
3243
+ ws.once("open", function open15() {
3244
3244
  duplex._final(callback);
3245
3245
  });
3246
3246
  return;
@@ -3261,7 +3261,7 @@ var require_stream = __commonJS({
3261
3261
  };
3262
3262
  duplex._write = function(chunk, encoding, callback) {
3263
3263
  if (ws.readyState === ws.CONNECTING) {
3264
- ws.once("open", function open14() {
3264
+ ws.once("open", function open15() {
3265
3265
  duplex._write(chunk, encoding, callback);
3266
3266
  });
3267
3267
  return;
@@ -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, path31) {
4545
- if (!path31)
4544
+ function getElementAtPath(obj, path32) {
4545
+ if (!path32)
4546
4546
  return obj;
4547
- return path31.reduce((acc, key) => acc?.[key], obj);
4547
+ return path32.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(path31, issues) {
4887
+ function prefixIssues(path32, issues) {
4888
4888
  return issues.map((iss) => {
4889
4889
  var _a3;
4890
4890
  (_a3 = iss).path ?? (_a3.path = []);
4891
- iss.path.unshift(path31);
4891
+ iss.path.unshift(path32);
4892
4892
  return iss;
4893
4893
  });
4894
4894
  }
@@ -4939,14 +4939,14 @@ function codePointLength(str) {
4939
4939
  const units2 = str.length;
4940
4940
  if (!highSurrogate.test(str))
4941
4941
  return units2;
4942
- let count3 = units2;
4942
+ let count4 = units2;
4943
4943
  for (let i = 0; i < units2 - 1; i++) {
4944
4944
  if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
4945
- count3--;
4945
+ count4--;
4946
4946
  i++;
4947
4947
  }
4948
4948
  }
4949
- return count3;
4949
+ return count4;
4950
4950
  }
4951
4951
  function getLengthableOrigin(input2) {
4952
4952
  if (Array.isArray(input2))
@@ -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, path31 = []) => {
5341
+ const processError = (error63, path32 = []) => {
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 }, [...path31, ...issue2.path]));
5344
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
5345
5345
  } else if (issue2.code === "invalid_key") {
5346
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5346
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5347
5347
  } else if (issue2.code === "invalid_element") {
5348
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5348
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5349
5349
  } else {
5350
- const fullpath = [...path31, ...issue2.path];
5350
+ const fullpath = [...path32, ...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, path31 = []) => {
5389
+ const processError = (error63, path32 = []) => {
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 }, [...path31, ...issue2.path]));
5393
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
5394
5394
  } else if (issue2.code === "invalid_key") {
5395
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5395
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5396
5396
  } else if (issue2.code === "invalid_element") {
5397
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5397
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5398
5398
  } else {
5399
- const fullpath = [...path31, ...issue2.path];
5399
+ const fullpath = [...path32, ...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 path31 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5439
- for (const seg of path31) {
5438
+ const path32 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5439
+ for (const seg of path32) {
5440
5440
  if (typeof seg === "number")
5441
5441
  segs.push(`[${seg}]`);
5442
5442
  else if (typeof seg === "symbol")
@@ -8551,9 +8551,9 @@ function partPattern(schema) {
8551
8551
  return own2;
8552
8552
  }
8553
8553
  if (def.options) {
8554
- const sources = def.options.map(partPattern);
8555
- if (sources.every(Boolean))
8556
- return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`;
8554
+ const sources2 = def.options.map(partPattern);
8555
+ if (sources2.every(Boolean))
8556
+ return `^(${sources2.map((s) => cleanRegex(s)).join("|")})$`;
8557
8557
  }
8558
8558
  return leafPattern(schema);
8559
8559
  }
@@ -9301,8 +9301,8 @@ function az_default() {
9301
9301
  }
9302
9302
 
9303
9303
  // ../../node_modules/zod/v4/locales/be.js
9304
- function getBelarusianPlural(count3, one, few, many) {
9305
- const absCount = Math.abs(count3);
9304
+ function getBelarusianPlural(count4, one, few, many) {
9305
+ const absCount = Math.abs(count4);
9306
9306
  const lastDigit = absCount % 10;
9307
9307
  const lastTwoDigits = absCount % 100;
9308
9308
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -11949,8 +11949,8 @@ function hu_default() {
11949
11949
  }
11950
11950
 
11951
11951
  // ../../node_modules/zod/v4/locales/hy.js
11952
- function getArmenianPlural(count3, one, many) {
11953
- return Math.abs(count3) === 1 ? one : many;
11952
+ function getArmenianPlural(count4, one, many) {
11953
+ return Math.abs(count4) === 1 ? one : many;
11954
11954
  }
11955
11955
  function withDefiniteArticle(word) {
11956
11956
  if (!word)
@@ -14688,8 +14688,8 @@ function ro_default() {
14688
14688
  }
14689
14689
 
14690
14690
  // ../../node_modules/zod/v4/locales/ru.js
14691
- function getRussianPlural(count3, one, few, many) {
14692
- const absCount = Math.abs(count3);
14691
+ function getRussianPlural(count4, one, few, many) {
14692
+ const absCount = Math.abs(count4);
14693
14693
  const lastDigit = absCount % 10;
14694
14694
  const lastTwoDigits = absCount % 100;
14695
14695
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -19288,8 +19288,8 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) {
19288
19288
  }
19289
19289
 
19290
19290
  // ../../node_modules/zod/v4/core/to-json-schema.js
19291
- function assignProps(target, ...sources) {
19292
- for (const source of sources) {
19291
+ function assignProps(target, ...sources2) {
19292
+ for (const source of sources2) {
19293
19293
  for (const key of Reflect.ownKeys(source)) {
19294
19294
  if (Object.prototype.propertyIsEnumerable.call(source, key)) {
19295
19295
  assignProp(target, key, source[key]);
@@ -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 path31 = ref.slice(1).split("/").filter(Boolean);
22542
- if (path31.length === 0) {
22541
+ const path32 = ref.slice(1).split("/").filter(Boolean);
22542
+ if (path32.length === 0) {
22543
22543
  return ctx.rootSchema;
22544
22544
  }
22545
22545
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
22546
- if (path31[0] === defsKey) {
22547
- const key = path31[1] === void 0 ? void 0 : decodeJSONPointerSegment(path31[1]);
22546
+ if (path32[0] === defsKey) {
22547
+ const key = path32[1] === void 0 ? void 0 : decodeJSONPointerSegment(path32[1]);
22548
22548
  if (!key || !ctx.defs[key]) {
22549
22549
  throw new Error(`Reference not found: ${ref}`);
22550
22550
  }
@@ -24580,7 +24580,7 @@ var RelayBridge = class _RelayBridge {
24580
24580
  const upstream = netConnect({ host, port });
24581
24581
  this.tunnels.add(socket);
24582
24582
  this.tunnels.add(upstream);
24583
- let open14 = false;
24583
+ let open15 = false;
24584
24584
  const cleanup = () => {
24585
24585
  this.tunnels.delete(socket);
24586
24586
  this.tunnels.delete(upstream);
@@ -24588,13 +24588,13 @@ var RelayBridge = class _RelayBridge {
24588
24588
  upstream.destroy();
24589
24589
  };
24590
24590
  const timer = setTimeout(() => {
24591
- if (!open14) {
24591
+ if (!open15) {
24592
24592
  refuse("504 Gateway Timeout");
24593
24593
  cleanup();
24594
24594
  }
24595
24595
  }, CONNECT_TIMEOUT_MS);
24596
24596
  upstream.once("connect", () => {
24597
- open14 = true;
24597
+ open15 = true;
24598
24598
  clearTimeout(timer);
24599
24599
  socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
24600
24600
  if (head.length) upstream.write(head);
@@ -24603,7 +24603,7 @@ var RelayBridge = class _RelayBridge {
24603
24603
  });
24604
24604
  upstream.on("error", () => {
24605
24605
  clearTimeout(timer);
24606
- if (!open14) refuse("502 Bad Gateway");
24606
+ if (!open15) refuse("502 Bad Gateway");
24607
24607
  cleanup();
24608
24608
  });
24609
24609
  socket.on("error", cleanup);
@@ -24624,7 +24624,7 @@ var RelayBridge = class _RelayBridge {
24624
24624
  const remote = (0, import_stream.default)(ws, { allowHalfOpen: false });
24625
24625
  this.tunnels.add(socket);
24626
24626
  this.tunnels.add(remote);
24627
- let reply = Buffer.alloc(0), open14 = false;
24627
+ let reply = Buffer.alloc(0), open15 = false;
24628
24628
  const cleanup = () => {
24629
24629
  this.tunnels.delete(socket);
24630
24630
  this.tunnels.delete(remote);
@@ -24632,7 +24632,7 @@ var RelayBridge = class _RelayBridge {
24632
24632
  remote.destroy();
24633
24633
  };
24634
24634
  const timer = setTimeout(() => {
24635
- if (!open14) {
24635
+ if (!open15) {
24636
24636
  refuse("504 Gateway Timeout");
24637
24637
  cleanup();
24638
24638
  }
@@ -24654,7 +24654,7 @@ var RelayBridge = class _RelayBridge {
24654
24654
  cleanup();
24655
24655
  return;
24656
24656
  }
24657
- open14 = true;
24657
+ open15 = true;
24658
24658
  socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
24659
24659
  const rest = reply.subarray(end + 4);
24660
24660
  if (rest.length) socket.write(rest);
@@ -24671,7 +24671,7 @@ Proxy-Authorization: Basic ${Buffer.from("lc:" + route.token).toString("base64")
24671
24671
  remote.on("data", onReply);
24672
24672
  });
24673
24673
  remote.on("error", () => {
24674
- if (!open14) refuse("502 Bad Gateway");
24674
+ if (!open15) refuse("502 Bad Gateway");
24675
24675
  cleanup();
24676
24676
  });
24677
24677
  socket.on("error", cleanup);
@@ -25037,19 +25037,19 @@ import path2 from "node:path";
25037
25037
  import { spawn, spawnSync } from "node:child_process";
25038
25038
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
25039
25039
  var Receipt = external_exports.object({ version: external_exports.literal(1), deviceId: external_exports.string().uuid(), tenantId: external_exports.string().uuid(), accountId: external_exports.string().uuid(), bundleId: external_exports.string().regex(/^[a-f0-9]{64}$/) }).strict();
25040
- function networkPath(stateDirectory, name2) {
25041
- return path2.join(path2.dirname(stateDirectory), "Network", name2);
25040
+ function networkPath(stateDirectory2, name2) {
25041
+ return path2.join(path2.dirname(stateDirectory2), "Network", name2);
25042
25042
  }
25043
- async function networkDirectory(stateDirectory) {
25044
- const directory = path2.dirname(networkPath(stateDirectory, "x"));
25043
+ async function networkDirectory(stateDirectory2) {
25044
+ const directory = path2.dirname(networkPath(stateDirectory2, "x"));
25045
25045
  await fs.mkdir(directory, { recursive: true, mode: 448 });
25046
25046
  const stat2 = await fs.lstat(directory);
25047
25047
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw Error("NETWORK_DIRECTORY_INVALID");
25048
25048
  return directory;
25049
25049
  }
25050
- async function networkPrepared(stateDirectory, identity) {
25050
+ async function networkPrepared(stateDirectory2, identity) {
25051
25051
  try {
25052
- const file3 = networkPath(stateDirectory, "network-prepared.json"), stat2 = await fs.lstat(file3);
25052
+ const file3 = networkPath(stateDirectory2, "network-prepared.json"), stat2 = await fs.lstat(file3);
25053
25053
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > 1024) return false;
25054
25054
  const receipt = Receipt.parse(JSON.parse(await fs.readFile(file3, "utf8"))), e = identity.enrollment;
25055
25055
  return !!e && receipt.deviceId === e.deviceId && receipt.tenantId === e.tenantId && receipt.accountId === e.accountId;
@@ -25087,9 +25087,9 @@ async function payload(binaryDirectory) {
25087
25087
  throw error62;
25088
25088
  }
25089
25089
  }
25090
- async function installedNetworkHelper(stateDirectory) {
25090
+ async function installedNetworkHelper(stateDirectory2) {
25091
25091
  try {
25092
- const receipt = Receipt.parse(JSON.parse(await fs.readFile(networkPath(stateDirectory, "network-prepared.json"), "utf8")));
25092
+ const receipt = Receipt.parse(JSON.parse(await fs.readFile(networkPath(stateDirectory2, "network-prepared.json"), "utf8")));
25093
25093
  const programFiles = process.env.ProgramW6432 ?? process.env.ProgramFiles ?? "C:\\Program Files";
25094
25094
  const helper = path2.join(programFiles, "LocalCommander", "Network", receipt.bundleId, "NetworkService.exe"), stat2 = await fs.lstat(helper);
25095
25095
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > 4 * 1024 * 1024 || (await fs.realpath(helper)).toLowerCase() !== path2.resolve(helper).toLowerCase()) return null;
@@ -25118,13 +25118,13 @@ async function elevated(helper, command, requestPath, directory) {
25118
25118
  await fs.rm(scriptPath, { force: true });
25119
25119
  }
25120
25120
  }
25121
- async function setupNetwork(binaryDirectory, stateDirectory, identity) {
25121
+ async function setupNetwork(binaryDirectory, stateDirectory2, identity) {
25122
25122
  const bundle = await payload(binaryDirectory);
25123
25123
  if (!bundle) return "not_packaged";
25124
25124
  const e = identity.enrollment;
25125
25125
  if (!e?.accountId) throw Error("NETWORK_ACCOUNT_BINDING_REQUIRED");
25126
25126
  const request = { ownerSid: windowsSid(), tenantId: e.tenantId, accountId: e.accountId, deviceId: e.deviceId, keyFingerprint: identity.fingerprint };
25127
- const directory = await networkDirectory(stateDirectory);
25127
+ const directory = await networkDirectory(stateDirectory2);
25128
25128
  const requestPath = path2.join(directory, "network-setup-" + randomUUID2() + ".json");
25129
25129
  await fs.writeFile(requestPath, JSON.stringify(request), { flag: "wx", mode: 384 });
25130
25130
  try {
@@ -25143,14 +25143,14 @@ async function setupNetwork(binaryDirectory, stateDirectory, identity) {
25143
25143
  await fs.rm(requestPath, { force: true });
25144
25144
  }
25145
25145
  }
25146
- async function removeNetwork(binaryDirectory, stateDirectory, identity) {
25146
+ async function removeNetwork(binaryDirectory, stateDirectory2, identity) {
25147
25147
  const e = identity.enrollment;
25148
- if (!e || !await networkPrepared(stateDirectory, identity)) return;
25148
+ if (!e || !await networkPrepared(stateDirectory2, identity)) return;
25149
25149
  await localNetworkControl(e.deviceId, "off");
25150
- const helper = (await payload(binaryDirectory))?.helper ?? await installedNetworkHelper(stateDirectory);
25150
+ const helper = (await payload(binaryDirectory))?.helper ?? await installedNetworkHelper(stateDirectory2);
25151
25151
  if (!helper) throw Error("NETWORK_REMOVAL_PACKAGE_REQUIRED");
25152
- await elevated(helper, "uninstall", void 0, await networkDirectory(stateDirectory));
25153
- await fs.rm(networkPath(stateDirectory, "network-prepared.json"), { force: true });
25152
+ await elevated(helper, "uninstall", void 0, await networkDirectory(stateDirectory2));
25153
+ await fs.rm(networkPath(stateDirectory2, "network-prepared.json"), { force: true });
25154
25154
  }
25155
25155
  async function openNetworkPanel(binaryDirectory, identity) {
25156
25156
  const bundle = await payload(binaryDirectory), e = identity.enrollment;
@@ -25164,8 +25164,8 @@ async function openNetworkPanel(binaryDirectory, identity) {
25164
25164
  }
25165
25165
 
25166
25166
  // agent/src/main.ts
25167
- import path30 from "node:path";
25168
- import os8 from "node:os";
25167
+ import path31 from "node:path";
25168
+ import os9 from "node:os";
25169
25169
 
25170
25170
  // agent/src/posix-store.ts
25171
25171
  import { constants } from "node:fs";
@@ -25584,7 +25584,7 @@ async function acquirePosixJournalGuard(directory, helper) {
25584
25584
  }
25585
25585
 
25586
25586
  // agent/src/main.ts
25587
- import { mkdir as mkdir15, open as open13, readFile as readFile13, realpath as realpath10, rm as rm11 } from "node:fs/promises";
25587
+ import { mkdir as mkdir16, open as open14, readFile as readFile14, realpath as realpath10, rm as rm12 } from "node:fs/promises";
25588
25588
  import { fileURLToPath } from "node:url";
25589
25589
 
25590
25590
  // packages/operations/src/crypto.ts
@@ -27140,7 +27140,7 @@ var NativeJournal = class _NativeJournal {
27140
27140
  * still alive; otherwise, including every entry from an older agent, it stays EXECUTION_UNKNOWN (#194). */
27141
27141
  recoverAfterRestart(liveness) {
27142
27142
  return this.enqueue(async () => {
27143
- let count3 = 0;
27143
+ let count4 = 0;
27144
27144
  const interrupted = [...this.entries.values()].filter((e) => ["accepted", "running"].includes(e.state));
27145
27145
  const pids = [...new Set(interrupted.flatMap((e) => e.supervisors ?? []))];
27146
27146
  const linuxSupervisors = interrupted.flatMap((e) => e.linuxSupervisors ?? []), darwinSupervisors = interrupted.flatMap((e) => e.darwinSupervisors ?? []);
@@ -27173,9 +27173,9 @@ var NativeJournal = class _NativeJournal {
27173
27173
  } });
27174
27174
  }
27175
27175
  await this.persist(e);
27176
- count3++;
27176
+ count4++;
27177
27177
  }
27178
- return count3;
27178
+ return count4;
27179
27179
  });
27180
27180
  }
27181
27181
  eligibleForPruning(entry, cutoff) {
@@ -27183,20 +27183,20 @@ var NativeJournal = class _NativeJournal {
27183
27183
  }
27184
27184
  admissionAvailable() {
27185
27185
  if (this.closed || this.lock.guard && !this.lock.guard.active) return false;
27186
- let count3 = this.entries.size, bytes3 = this.totalBytes;
27187
- if (count3 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27186
+ let count4 = this.entries.size, bytes3 = this.totalBytes;
27187
+ if (count4 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27188
27188
  const cutoff = this.now().getTime() - this.options.retentionMs;
27189
27189
  for (const entry of this.entries.values()) {
27190
27190
  if (!this.eligibleForPruning(entry, cutoff)) continue;
27191
- count3--;
27191
+ count4--;
27192
27192
  bytes3 -= this.sizes.get(entry.executionId);
27193
- if (count3 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27193
+ if (count4 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27194
27194
  }
27195
27195
  return false;
27196
27196
  }
27197
27197
  // Called only inside the serialized queue; enqueueing prune here would deadlock.
27198
27198
  async pruneEligible() {
27199
- let count3 = 0;
27199
+ let count4 = 0;
27200
27200
  const cutoff = this.now().getTime() - this.options.retentionMs;
27201
27201
  for (const e of [...this.entries.values()]) {
27202
27202
  if (!this.eligibleForPruning(e, cutoff)) continue;
@@ -27206,9 +27206,9 @@ var NativeJournal = class _NativeJournal {
27206
27206
  this.entries.delete(e.executionId);
27207
27207
  this.sizes.delete(e.executionId);
27208
27208
  this.digests.delete(e.executionId);
27209
- count3++;
27209
+ count4++;
27210
27210
  }
27211
- return count3;
27211
+ return count4;
27212
27212
  }
27213
27213
  prune() {
27214
27214
  return this.enqueue(() => this.pruneEligible());
@@ -29546,11 +29546,11 @@ async function portalScreenshot(socket, uid, token, signal) {
29546
29546
  signal.addEventListener("abort", abort, { once: true });
29547
29547
  connection.on("error", fail7);
29548
29548
  connection.on("close", () => fail7(Error("CLOSED")));
29549
- const call = (destination, path31, iface, member, signature = "", body = () => {
29549
+ const call = (destination, path32, iface, member, signature = "", body = () => {
29550
29550
  }) => new Promise((done, failed) => {
29551
29551
  const payload2 = new Writer();
29552
29552
  body(payload2);
29553
- const header = new Writer(), fields = [[1, "o", path31], [2, "s", iface], [3, "s", member], [6, "s", destination]];
29553
+ const header = new Writer(), fields = [[1, "o", path32], [2, "s", iface], [3, "s", member], [6, "s", destination]];
29554
29554
  if (signature) fields.push([8, "g", signature]);
29555
29555
  header.byte(108);
29556
29556
  header.byte(1);
@@ -29733,8 +29733,8 @@ function downscale(image, edge) {
29733
29733
  sums[x * 3 + 2] = sums[x * 3 + 2] + image.rgb[i + 2];
29734
29734
  }
29735
29735
  for (let x = 0; x < width; x++) {
29736
- const count3 = (ys[y + 1] - ys[y]) * (xs[x + 1] - xs[x]);
29737
- for (let c = 0; c < 3; c++) rgb[(y * width + x) * 3 + c] = Math.round(sums[x * 3 + c] / count3);
29736
+ const count4 = (ys[y + 1] - ys[y]) * (xs[x + 1] - xs[x]);
29737
+ for (let c = 0; c < 3; c++) rgb[(y * width + x) * 3 + c] = Math.round(sums[x * 3 + c] / count4);
29738
29738
  }
29739
29739
  }
29740
29740
  return { width, height, rgb };
@@ -30210,8 +30210,8 @@ var HUFFMAN = [
30210
30210
  var CODES = HUFFMAN.map(([, counts, values]) => {
30211
30211
  const table2 = [];
30212
30212
  let code = 0, at = 0;
30213
- counts.forEach((count3, index) => {
30214
- for (let i = 0; i < count3; i++) table2[values[at++]] = [code++, index + 1];
30213
+ counts.forEach((count4, index) => {
30214
+ for (let i = 0; i < count4; i++) table2[values[at++]] = [code++, index + 1];
30215
30215
  code <<= 1;
30216
30216
  });
30217
30217
  return table2;
@@ -31081,16 +31081,16 @@ var NativeTools = class {
31081
31081
  if (value) selectedHeaders[name2] = value.slice(0, 2048);
31082
31082
  }
31083
31083
  const reader = response.body?.getReader(), chunks = [];
31084
- let count3 = 0, truncated = false;
31084
+ let count4 = 0, truncated = false;
31085
31085
  try {
31086
31086
  if (reader) for (; ; ) {
31087
31087
  const part = await reader.read();
31088
31088
  if (part.done) break;
31089
31089
  const b = Buffer.from(part.value);
31090
- const take = Math.min(b.length, 1e5 - count3);
31090
+ const take = Math.min(b.length, 1e5 - count4);
31091
31091
  chunks.push(b.subarray(0, take));
31092
- count3 += take;
31093
- if (take !== b.length || count3 >= 1e5) {
31092
+ count4 += take;
31093
+ if (take !== b.length || count4 >= 1e5) {
31094
31094
  truncated = true;
31095
31095
  break;
31096
31096
  }
@@ -31644,11 +31644,11 @@ function parseNodeTapShadow(input2) {
31644
31644
  return passThrough(input2, "unrecognized_record", true, notices);
31645
31645
  }
31646
31646
  if (line === "") continue;
31647
- const count3 = SUMMARY_COUNT.exec(line);
31648
- if (count3) {
31649
- const key = count3[1];
31647
+ const count4 = SUMMARY_COUNT.exec(line);
31648
+ if (count4) {
31649
+ const key = count4[1];
31650
31650
  if (counts.has(key)) return passThrough(input2, "summary_inconsistent", true, notices);
31651
- counts.set(key, Number(count3[2]));
31651
+ counts.set(key, Number(count4[2]));
31652
31652
  continue;
31653
31653
  }
31654
31654
  const summaryDuration = SUMMARY_DURATION.exec(line);
@@ -31762,11 +31762,11 @@ function parseNodeTapFailureShadow(input2) {
31762
31762
  let durationMs = null;
31763
31763
  for (const line of lines.slice(index + 1)) {
31764
31764
  if (!line) continue;
31765
- const count3 = SUMMARY_COUNT.exec(line);
31766
- if (count3) {
31767
- const key = count3[1];
31765
+ const count4 = SUMMARY_COUNT.exec(line);
31766
+ if (count4) {
31767
+ const key = count4[1];
31768
31768
  if (counts.has(key)) return fallback("summary_inconsistent");
31769
- counts.set(key, Number(count3[2]));
31769
+ counts.set(key, Number(count4[2]));
31770
31770
  } else {
31771
31771
  const duration3 = SUMMARY_DURATION.exec(line);
31772
31772
  if (duration3) {
@@ -36575,9 +36575,9 @@ var rev2026Codec = {
36575
36575
  });
36576
36576
  const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3);
36577
36577
  if (!parsed.success) for (const issue2 of parsed.error.issues) {
36578
- const path31 = issue2.path.map(String);
36579
- const key = path31.length > 0 ? path31.join(".") : "_meta";
36580
- if (path31.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
36578
+ const path32 = issue2.path.map(String);
36579
+ const key = path32.length > 0 ? path32.join(".") : "_meta";
36580
+ if (path32.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
36581
36581
  issues.push({
36582
36582
  key,
36583
36583
  problem: issue2.message
@@ -36879,29 +36879,29 @@ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
36879
36879
  function scanXMcpHeaderDeclarations(inputSchema) {
36880
36880
  const declarations = [];
36881
36881
  const seenLower = /* @__PURE__ */ new Map();
36882
- const visit2 = (node2, path31, reachable) => {
36882
+ const visit2 = (node2, path32, reachable) => {
36883
36883
  if (node2 === null || typeof node2 !== "object") return void 0;
36884
36884
  const schema = node2;
36885
36885
  if (X_MCP_HEADER_KEY in schema) {
36886
- if (!reachable || path31.length === 0) return `${pathName(path31)}: 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)`;
36886
+ if (!reachable || path32.length === 0) return `${pathName(path32)}: 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)`;
36887
36887
  const raw = schema[X_MCP_HEADER_KEY];
36888
- if (typeof raw !== "string" || raw.length === 0) return `${pathName(path31)}: x-mcp-header MUST be a non-empty string`;
36889
- if (!RFC9110_TOKEN.test(raw)) return `${pathName(path31)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
36888
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path32)}: x-mcp-header MUST be a non-empty string`;
36889
+ if (!RFC9110_TOKEN.test(raw)) return `${pathName(path32)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
36890
36890
  const type = typeof schema.type === "string" ? schema.type : void 0;
36891
- if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path31)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
36891
+ if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path32)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
36892
36892
  const lower = raw.toLowerCase();
36893
36893
  const prior = seenLower.get(lower);
36894
36894
  if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
36895
36895
  seenLower.set(lower, raw);
36896
36896
  declarations.push({
36897
- path: path31,
36897
+ path: path32,
36898
36898
  headerName: raw,
36899
36899
  type
36900
36900
  });
36901
36901
  }
36902
36902
  const properties = schema.properties;
36903
36903
  if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
36904
- const fault$1 = visit2(child, [...path31, key], reachable);
36904
+ const fault$1 = visit2(child, [...path32, key], reachable);
36905
36905
  if (fault$1 !== void 0) return fault$1;
36906
36906
  }
36907
36907
  for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
@@ -36909,7 +36909,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
36909
36909
  if (sub === void 0) continue;
36910
36910
  const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
36911
36911
  for (const branch of branches) {
36912
- const fault$1 = visit2(branch, [...path31, `<${k}>`], false);
36912
+ const fault$1 = visit2(branch, [...path32, `<${k}>`], false);
36913
36913
  if (fault$1 !== void 0) return fault$1;
36914
36914
  }
36915
36915
  }
@@ -36949,8 +36949,8 @@ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
36949
36949
  "$defs",
36950
36950
  "definitions"
36951
36951
  ]);
36952
- function pathName(path31) {
36953
- return path31.length === 0 ? "<root>" : path31.join(".");
36952
+ function pathName(path32) {
36953
+ return path32.length === 0 ? "<root>" : path32.join(".");
36954
36954
  }
36955
36955
  var HEADER_MISMATCH_ERROR_CODE = -32020;
36956
36956
  var INBOUND_VALIDATION_LADDER = [
@@ -37200,7 +37200,7 @@ var PROPERTY_KEYS_BY_TYPE = {
37200
37200
  array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])
37201
37201
  };
37202
37202
  var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options);
37203
- function walkProperty(node2, path31, vendor, unsupported) {
37203
+ function walkProperty(node2, path32, vendor, unsupported) {
37204
37204
  if (!isJsonObject(node2)) return node2;
37205
37205
  const allowedKeys = typeof node2.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node2.type) ? PROPERTY_KEYS_BY_TYPE[node2.type] : void 0;
37206
37206
  if (allowedKeys === void 0) return node2;
@@ -37208,8 +37208,8 @@ function walkProperty(node2, path31, vendor, unsupported) {
37208
37208
  for (const [key, value] of Object.entries(node2)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value;
37209
37209
  else if (key === "pattern" && node2.type === "string" && typeof node2.format === "string") {
37210
37210
  if (!SUPPORTED_STRING_FORMATS.has(node2.format)) pruned[key] = value;
37211
- else if (typeof value !== "string" || !isLibraryFormatPattern(node2.format, value, vendor)) unsupported.push(`${path31}.${key}`);
37212
- } else unsupported.push(`${path31}.${key}`);
37211
+ else if (typeof value !== "string" || !isLibraryFormatPattern(node2.format, value, vendor)) unsupported.push(`${path32}.${key}`);
37212
+ } else unsupported.push(`${path32}.${key}`);
37213
37213
  return pruned;
37214
37214
  }
37215
37215
  function walkRequestedSchema(converted, vendor) {
@@ -37226,11 +37226,11 @@ function describeUnsupportedProperties(pruned, fallback) {
37226
37226
  const offenders = Object.entries(pruned.properties).filter(([, node2]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node2).success).map(([name2]) => `properties.${name2}`);
37227
37227
  return offenders.length > 0 ? offenders.join(", ") : fallback;
37228
37228
  }
37229
- function findDroppedConstraintPaths(original, parsed, path31 = "") {
37230
- if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path31}[${index}]`));
37229
+ function findDroppedConstraintPaths(original, parsed, path32 = "") {
37230
+ if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path32}[${index}]`));
37231
37231
  if (!isJsonObject(original) || !isJsonObject(parsed)) return [];
37232
37232
  return Object.entries(original).flatMap(([key, value]) => {
37233
- const childPath = path31 ? `${path31}.${key}` : key;
37233
+ const childPath = path32 ? `${path32}.${key}` : key;
37234
37234
  if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];
37235
37235
  return findDroppedConstraintPaths(value, parsed[key], childPath);
37236
37236
  });
@@ -40460,15 +40460,15 @@ var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
40460
40460
  return false;
40461
40461
  }
40462
40462
  function countKeys(schema) {
40463
- let count3 = 0;
40463
+ let count4 = 0;
40464
40464
  for (const key in schema) {
40465
40465
  if (key === "$ref") return Infinity;
40466
- count3++;
40466
+ count4++;
40467
40467
  if (SIMPLE_INLINED.has(key)) continue;
40468
- if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count3 += countKeys(sch));
40469
- if (count3 === Infinity) return Infinity;
40468
+ if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count4 += countKeys(sch));
40469
+ if (count4 === Infinity) return Infinity;
40470
40470
  }
40471
- return count3;
40471
+ return count4;
40472
40472
  }
40473
40473
  function getFullPath(resolver, id2 = "", normalize) {
40474
40474
  if (normalize !== false) id2 = normalizeId(id2);
@@ -41306,8 +41306,8 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
41306
41306
  for (let i = 0; i < str.length; i++) if (str[i] === token) ind++;
41307
41307
  return ind;
41308
41308
  }
41309
- function removeDotSegments(path31) {
41310
- let input2 = path31;
41309
+ function removeDotSegments(path32) {
41310
+ let input2 = path32;
41311
41311
  const output2 = [];
41312
41312
  let nextSlash = -1;
41313
41313
  let len = 0;
@@ -41460,8 +41460,8 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
41460
41460
  wsComponent.secure = void 0;
41461
41461
  }
41462
41462
  if (wsComponent.resourceName) {
41463
- const [path31, query] = wsComponent.resourceName.split("?");
41464
- wsComponent.path = path31 && path31 !== "/" ? path31 : void 0;
41463
+ const [path32, query] = wsComponent.resourceName.split("?");
41464
+ wsComponent.path = path32 && path32 !== "/" ? path32 : void 0;
41465
41465
  wsComponent.query = query;
41466
41466
  wsComponent.resourceName = void 0;
41467
41467
  }
@@ -43068,8 +43068,8 @@ var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => {
43068
43068
  cxt.result(valid, () => cxt.reset());
43069
43069
  function validateItemsWithCount() {
43070
43070
  const schValid = gen.name("_valid");
43071
- const count3 = gen.let("count", 0);
43072
- validateItems(schValid, () => gen.if(schValid, () => checkLimits(count3)));
43071
+ const count4 = gen.let("count", 0);
43072
+ validateItems(schValid, () => gen.if(schValid, () => checkLimits(count4)));
43073
43073
  }
43074
43074
  function validateItems(_valid, block) {
43075
43075
  gen.forRange("i", 0, len, (i) => {
@@ -43082,13 +43082,13 @@ var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => {
43082
43082
  block();
43083
43083
  });
43084
43084
  }
43085
- function checkLimits(count3) {
43086
- gen.code((0, codegen_1._)`${count3}++`);
43087
- if (max === void 0) gen.if((0, codegen_1._)`${count3} >= ${min}`, () => gen.assign(valid, true).break());
43085
+ function checkLimits(count4) {
43086
+ gen.code((0, codegen_1._)`${count4}++`);
43087
+ if (max === void 0) gen.if((0, codegen_1._)`${count4} >= ${min}`, () => gen.assign(valid, true).break());
43088
43088
  else {
43089
- gen.if((0, codegen_1._)`${count3} > ${max}`, () => gen.assign(valid, false).break());
43089
+ gen.if((0, codegen_1._)`${count4} > ${max}`, () => gen.assign(valid, false).break());
43090
43090
  if (min === 1) gen.assign(valid, true);
43091
- else gen.if((0, codegen_1._)`${count3} >= ${min}`, () => gen.assign(valid, true));
43091
+ else gen.if((0, codegen_1._)`${count4} >= ${min}`, () => gen.assign(valid, true));
43092
43092
  }
43093
43093
  }
43094
43094
  }
@@ -47263,6 +47263,42 @@ var NativeIncidentProducer = class {
47263
47263
  }
47264
47264
  };
47265
47265
 
47266
+ // packages/contracts/src/token-usage-protocol.ts
47267
+ var TOKEN_USAGE_CAPABILITY = "tokenUsageV1";
47268
+ var uuid20 = external_exports.string().uuid().toLowerCase();
47269
+ var epoch3 = external_exports.string().refine((v) => /^[1-9]\d{0,18}$/.test(v) && BigInt(v) <= 9223372036854775807n);
47270
+ var tokens = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
47271
+ var TokenUsageClientSchema = external_exports.enum(["claude-code", "codex"]);
47272
+ var TOKEN_USAGE_MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,79}$/;
47273
+ var TokenUsageRowSchema = external_exports.object({
47274
+ day: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((v) => Number.isFinite(Date.parse(v + "T00:00:00Z"))),
47275
+ client: TokenUsageClientSchema,
47276
+ model: external_exports.string().regex(TOKEN_USAGE_MODEL),
47277
+ requests: tokens,
47278
+ inputTokens: tokens,
47279
+ cachedInputTokens: tokens,
47280
+ cacheWriteTokens: tokens,
47281
+ outputTokens: tokens,
47282
+ reasoningTokens: tokens.nullable()
47283
+ }).strict().refine((row) => row.cachedInputTokens + row.cacheWriteTokens <= row.inputTokens && (row.reasoningTokens === null || row.reasoningTokens <= row.outputTokens), "Subset exceeds total");
47284
+ var TokenUsageBatchSchema = external_exports.object({
47285
+ type: external_exports.literal("tokenUsageBatch"),
47286
+ protocolVersion: external_exports.literal(1),
47287
+ batchId: uuid20,
47288
+ connectionEpoch: epoch3,
47289
+ /** Random per agent state; a new state counts only usage after it started, so states never overlap. */
47290
+ stateId: uuid20,
47291
+ rows: external_exports.array(TokenUsageRowSchema).min(1).max(64)
47292
+ }).strict().refine((batch) => new Set(batch.rows.map((r) => `${r.day}|${r.client}|${r.model}`)).size === batch.rows.length, "Duplicate rows");
47293
+ var TokenUsageBatchResultSchema = external_exports.enum(["accepted", "invalid", "stale", "disabled", "retry", "busy"]);
47294
+ var TokenUsageBatchAckSchema = external_exports.object({
47295
+ type: external_exports.literal("tokenUsageBatchAck"),
47296
+ protocolVersion: external_exports.literal(1),
47297
+ batchId: uuid20.optional(),
47298
+ result: TokenUsageBatchResultSchema
47299
+ }).strict();
47300
+ var TokenUsageStateSchema = external_exports.object({ type: external_exports.literal("tokenUsageState"), protocolVersion: external_exports.literal(1), connectionEpoch: epoch3, enabled: external_exports.boolean() }).strict();
47301
+
47266
47302
  // agent/src/relay-client.ts
47267
47303
  var RelayClientError = class extends Error {
47268
47304
  constructor(code) {
@@ -47298,7 +47334,7 @@ function relayUrlFromEnrollment(enrollment) {
47298
47334
  url2.pathname = "/api/agent/relay";
47299
47335
  return url2.toString();
47300
47336
  }
47301
- function uuid20(value, code) {
47337
+ function uuid21(value, code) {
47302
47338
  if (typeof value !== "string" || !UUID2.test(value)) fail5(code);
47303
47339
  return value.toLowerCase();
47304
47340
  }
@@ -47306,7 +47342,7 @@ function protocol(value, expected) {
47306
47342
  if (value !== expected) fail5("RELAY_PROTOCOL_INVALID");
47307
47343
  return expected;
47308
47344
  }
47309
- function epoch3(value) {
47345
+ function epoch4(value) {
47310
47346
  if (typeof value !== "string" || !EPOCH.test(value) || BigInt(value) > 9223372036854775807n) fail5("RELAY_EPOCH_INVALID");
47311
47347
  return value;
47312
47348
  }
@@ -47428,11 +47464,11 @@ function sendJson(socket, value, maxBytes) {
47428
47464
  function validateChallenge(frame, expectedProtocol) {
47429
47465
  if (frame.type !== "challenge") fail5("RELAY_HANDSHAKE_INVALID");
47430
47466
  protocol(frame.protocolVersion, expectedProtocol);
47431
- uuid20(frame.gatewayId, "RELAY_HANDSHAKE_INVALID");
47467
+ uuid21(frame.gatewayId, "RELAY_HANDSHAKE_INVALID");
47432
47468
  if (typeof frame.nonce !== "string" || frame.nonce.length < 32 || frame.nonce.length > 512 || /[\u0000-\u001f\u007f]/u.test(frame.nonce)) fail5("RELAY_HANDSHAKE_INVALID");
47433
47469
  if (typeof frame.expiresAt !== "string" || !Number.isFinite(Date.parse(frame.expiresAt)) || Date.parse(frame.expiresAt) <= Date.now()) fail5("RELAY_HANDSHAKE_INVALID");
47434
47470
  return {
47435
- challengeId: uuid20(frame.challengeId, "RELAY_HANDSHAKE_INVALID"),
47471
+ challengeId: uuid21(frame.challengeId, "RELAY_HANDSHAKE_INVALID"),
47436
47472
  nonce: frame.nonce,
47437
47473
  // Older servers offer no capabilities and verify only the v1 proof.
47438
47474
  machineIdentity: Array.isArray(frame.capabilities) && frame.capabilities.includes(MACHINE_IDENTITY_CAPABILITY)
@@ -47441,27 +47477,27 @@ function validateChallenge(frame, expectedProtocol) {
47441
47477
  function validateReady(frame, enrollment, expectedProtocol) {
47442
47478
  if (frame.type !== "connected") fail5("RELAY_HANDSHAKE_INVALID");
47443
47479
  protocol(frame.protocolVersion, expectedProtocol);
47444
- if (uuid20(frame.tenantId, "RELAY_HANDSHAKE_INVALID") !== enrollment.tenantId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47445
- if (uuid20(frame.deviceId, "RELAY_HANDSHAKE_INVALID") !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47480
+ if (uuid21(frame.tenantId, "RELAY_HANDSHAKE_INVALID") !== enrollment.tenantId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47481
+ if (uuid21(frame.deviceId, "RELAY_HANDSHAKE_INVALID") !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47446
47482
  const terminalMetrics2 = Array.isArray(frame.capabilities) && frame.capabilities.includes(TERMINAL_METRICS_CAPABILITY);
47447
- return { connectionEpoch: epoch3(frame.connectionEpoch), terminalMetrics: terminalMetrics2 };
47483
+ return { connectionEpoch: epoch4(frame.connectionEpoch), terminalMetrics: terminalMetrics2 };
47448
47484
  }
47449
47485
  function validateRequest(frame, enrollment, expectedProtocol, connectionEpoch) {
47450
47486
  if (frame.type !== "relayFrame") fail5("RELAY_REQUEST_INVALID");
47451
47487
  protocol(frame.protocolVersion, expectedProtocol);
47452
- const tenantId = uuid20(frame.tenantId, "RELAY_REQUEST_INVALID");
47453
- const deviceId = uuid20(frame.deviceId, "RELAY_REQUEST_INVALID");
47488
+ const tenantId = uuid21(frame.tenantId, "RELAY_REQUEST_INVALID");
47489
+ const deviceId = uuid21(frame.deviceId, "RELAY_REQUEST_INVALID");
47454
47490
  if (tenantId !== enrollment.tenantId.toLowerCase() || deviceId !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47455
- if (epoch3(frame.connectionEpoch) !== connectionEpoch) fail5("RELAY_EPOCH_MISMATCH");
47491
+ if (epoch4(frame.connectionEpoch) !== connectionEpoch) fail5("RELAY_EPOCH_MISMATCH");
47456
47492
  const kind = frame.kind;
47457
47493
  if (typeof kind !== "string" || !REQUEST_KINDS.has(kind)) fail5("RELAY_REQUEST_INVALID");
47458
47494
  return {
47459
- requestId: uuid20(frame.requestId, "RELAY_REQUEST_INVALID"),
47495
+ requestId: uuid21(frame.requestId, "RELAY_REQUEST_INVALID"),
47460
47496
  tenantId,
47461
47497
  deviceId,
47462
47498
  connectionEpoch,
47463
- operationId: uuid20(frame.operationId, "RELAY_REQUEST_INVALID"),
47464
- executionId: uuid20(frame.executionId, "RELAY_REQUEST_INVALID"),
47499
+ operationId: uuid21(frame.operationId, "RELAY_REQUEST_INVALID"),
47500
+ executionId: uuid21(frame.executionId, "RELAY_REQUEST_INVALID"),
47465
47501
  kind,
47466
47502
  payload: frame.payload,
47467
47503
  deadlineAt: isoDate(frame.deadlineAt),
@@ -47503,8 +47539,8 @@ async function connectOnce(options) {
47503
47539
  const identity = await options.store.load();
47504
47540
  if (!identity || !identity.enrollment) fail5("ENROLLMENT_MISSING");
47505
47541
  const enrollment = identity.enrollment;
47506
- const tenantId = uuid20(enrollment.tenantId, "ENROLLMENT_INVALID");
47507
- const deviceId = uuid20(enrollment.deviceId, "ENROLLMENT_INVALID");
47542
+ const tenantId = uuid21(enrollment.tenantId, "ENROLLMENT_INVALID");
47543
+ const deviceId = uuid21(enrollment.deviceId, "ENROLLMENT_INVALID");
47508
47544
  const url2 = relayUrlFromEnrollment(enrollment);
47509
47545
  const socket = new wrapper_default(url2, [], {
47510
47546
  followRedirects: false,
@@ -47523,7 +47559,8 @@ async function connectOnce(options) {
47523
47559
  guardIdentity: true,
47524
47560
  ...options.aiConnectivity ? { aiConnectivity: true } : {},
47525
47561
  ...options.onHeldLeases ? { heldLeases: true } : {},
47526
- ...options.onFullLogChoice ? { fullLogNotice: true } : {}
47562
+ ...options.onFullLogChoice ? { fullLogNotice: true } : {},
47563
+ ...options.onTokenUsageState ? { tokenUsage: true } : {}
47527
47564
  }, maxFrameBytes);
47528
47565
  const challenge = validateChallenge(await waitForMessage(socket, maxFrameBytes, connectTimeoutMs, "RELAY_HANDSHAKE_TIMEOUT"), protocolVersion2);
47529
47566
  const machine = challenge.machineIdentity ? options.machineIdentity?.(deviceId) ?? null : null;
@@ -47550,6 +47587,7 @@ async function connectOnce(options) {
47550
47587
  const { connectionEpoch, terminalMetrics: terminalMetrics2 } = validateReady(readyFrame, enrollment, protocolVersion2);
47551
47588
  const rejectionResults = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(REJECTION_RESULT_CAPABILITY);
47552
47589
  const incidents = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes("incidentBatchV1");
47590
+ const tokenUsage = !!options.onTokenUsageState && Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(TOKEN_USAGE_CAPABILITY);
47553
47591
  const monitorHeartbeat = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes("monitorHeartbeatV1") && typeof readyFrame.heartbeatMs === "number" && Number.isInteger(readyFrame.heartbeatMs) && readyFrame.heartbeatMs >= 1e3 && readyFrame.heartbeatMs <= 6e4 ? readyFrame.heartbeatMs : void 0;
47554
47592
  const nativeStatus = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(NATIVE_STATUS_CAPABILITY) && options.status;
47555
47593
  const accessModes = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(WORKSPACE_ACCESS_MODE_CAPABILITY);
@@ -47637,6 +47675,26 @@ async function connectOnce(options) {
47637
47675
  }
47638
47676
  return;
47639
47677
  }
47678
+ if (frame.type === "tokenUsageState") {
47679
+ const state = TokenUsageStateSchema.safeParse(frame);
47680
+ if (tokenUsage && state.success && state.data.connectionEpoch === connectionEpoch) {
47681
+ try {
47682
+ options.onTokenUsageState?.(state.data.enabled);
47683
+ } catch {
47684
+ }
47685
+ }
47686
+ return;
47687
+ }
47688
+ if (frame.type === "tokenUsageBatchAck") {
47689
+ const ack = TokenUsageBatchAckSchema.safeParse(frame);
47690
+ if (tokenUsage && ack.success) {
47691
+ try {
47692
+ options.onTokenUsageAck?.(ack.data.batchId, ack.data.result);
47693
+ } catch {
47694
+ }
47695
+ }
47696
+ return;
47697
+ }
47640
47698
  if (frame.type === "aiConnectivityRevoked") {
47641
47699
  if (connectivity && frame.protocolVersion === 1 && frame.connectionEpoch === connectionEpoch) notifyConnectivityRevoked();
47642
47700
  return;
@@ -47767,6 +47825,15 @@ async function connectOnce(options) {
47767
47825
  return false;
47768
47826
  }
47769
47827
  } } : {},
47828
+ ...tokenUsage ? { sendTokenUsageBatch: (batch) => {
47829
+ try {
47830
+ if (socket.readyState !== wrapper_default.OPEN) return false;
47831
+ sendJson(socket, TokenUsageBatchSchema.parse({ type: "tokenUsageBatch", protocolVersion: 1, batchId: batch.batchId, connectionEpoch, stateId: batch.stateId, rows: batch.rows }), Math.min(maxFrameBytes, 32768));
47832
+ return true;
47833
+ } catch {
47834
+ return false;
47835
+ }
47836
+ } } : {},
47770
47837
  sendTerminal: (binding2, state, resultCode, metrics) => {
47771
47838
  if (state === "rejected" && !rejectionResults) return Promise.reject(new RelayClientError("RELAY_RESULT_UNSUPPORTED"));
47772
47839
  if (pendingTerminal.size >= 64) return Promise.reject(new RelayClientError("RELAY_PENDING_LIMIT"));
@@ -47985,10 +48052,10 @@ function canonicalOrigin2(value) {
47985
48052
  fail6("ORIGIN_INVALID");
47986
48053
  }
47987
48054
  }
47988
- function endpoint(origin, path31) {
47989
- return origin + path31;
48055
+ function endpoint(origin, path32) {
48056
+ return origin + path32;
47990
48057
  }
47991
- function uuid21(value, code) {
48058
+ function uuid22(value, code) {
47992
48059
  if (typeof value !== "string" || !UUID3.test(value)) fail6(code);
47993
48060
  return value.toLowerCase();
47994
48061
  }
@@ -48108,7 +48175,7 @@ var PairingClient = class {
48108
48175
  publicKey: identity.publicKeyPem,
48109
48176
  agentVersion: this.version
48110
48177
  }));
48111
- const pairingId = uuid21(response.pairingId, "PAIRING_RESPONSE_INVALID");
48178
+ const pairingId = uuid22(response.pairingId, "PAIRING_RESPONSE_INVALID");
48112
48179
  const expiresAt = parseDate(response.expiresAt, "PAIRING_RESPONSE_INVALID");
48113
48180
  const now = this.nowMs();
48114
48181
  if (expiresAt.getTime() <= now || expiresAt.getTime() - now > 30 * 6e4) fail6("PAIRING_RESPONSE_INVALID");
@@ -48142,7 +48209,7 @@ var PairingClient = class {
48142
48209
  }
48143
48210
  async completeOnce(beginResult, approved, displayNameValue) {
48144
48211
  const pairing = this.validateBeginResult(beginResult);
48145
- const tenantId = uuid21(approved.tenantId, "PAIRING_RESPONSE_INVALID");
48212
+ const tenantId = uuid22(approved.tenantId, "PAIRING_RESPONSE_INVALID");
48146
48213
  const email3 = accountEmail(approved.accountEmail);
48147
48214
  const name2 = displayName(displayNameValue);
48148
48215
  const identity = await this.currentIdentity();
@@ -48156,15 +48223,15 @@ var PairingClient = class {
48156
48223
  displayName: name2,
48157
48224
  agentVersion: this.version
48158
48225
  }));
48159
- const completedTenant = uuid21(response.tenantId, "PAIRING_RESPONSE_INVALID");
48226
+ const completedTenant = uuid22(response.tenantId, "PAIRING_RESPONSE_INVALID");
48160
48227
  if (completedTenant !== tenantId) fail6("PAIRING_RESPONSE_INVALID");
48161
- const deviceId = uuid21(response.deviceId, "PAIRING_RESPONSE_INVALID");
48228
+ const deviceId = uuid22(response.deviceId, "PAIRING_RESPONSE_INVALID");
48162
48229
  const enrollment = {
48163
48230
  tenantId,
48164
48231
  deviceId,
48165
48232
  serverOrigin: this.origin,
48166
48233
  accountEmail: email3,
48167
- ...response.accountId !== void 0 ? { accountId: uuid21(response.accountId, "PAIRING_RESPONSE_INVALID") } : {}
48234
+ ...response.accountId !== void 0 ? { accountId: uuid22(response.accountId, "PAIRING_RESPONSE_INVALID") } : {}
48168
48235
  };
48169
48236
  await this.store.saveEnrollment(enrollment);
48170
48237
  return { ...enrollment };
@@ -48178,7 +48245,7 @@ var PairingClient = class {
48178
48245
  state: response.state,
48179
48246
  expiresAt: parseDate(response.expiresAt, "PAIRING_RESPONSE_INVALID")
48180
48247
  };
48181
- if (response.tenantId !== void 0) result2.tenantId = uuid21(response.tenantId, "PAIRING_RESPONSE_INVALID");
48248
+ if (response.tenantId !== void 0) result2.tenantId = uuid22(response.tenantId, "PAIRING_RESPONSE_INVALID");
48182
48249
  if (response.accountEmail !== void 0) result2.accountEmail = accountEmail(response.accountEmail);
48183
48250
  return result2;
48184
48251
  }
@@ -48190,10 +48257,10 @@ var PairingClient = class {
48190
48257
  }
48191
48258
  validateBeginResult(value) {
48192
48259
  return {
48193
- pairingId: uuid21(value.pairingId, "PAIRING_INVALID"),
48260
+ pairingId: uuid22(value.pairingId, "PAIRING_INVALID"),
48194
48261
  pairingSecret: pairingSecret(value.pairingSecret),
48195
48262
  confirmationCode: confirmationCode(value.confirmationCode),
48196
- approvalUrl: approvalUrl(value.approvalUrl, this.origin, uuid21(value.pairingId, "PAIRING_INVALID")),
48263
+ approvalUrl: approvalUrl(value.approvalUrl, this.origin, uuid22(value.pairingId, "PAIRING_INVALID")),
48197
48264
  expiresAt: value.expiresAt instanceof Date ? new Date(value.expiresAt.getTime()) : parseDate(value.expiresAt, "PAIRING_INVALID"),
48198
48265
  keyFingerprint: fingerprint2(value.keyFingerprint)
48199
48266
  };
@@ -48724,9 +48791,9 @@ function commandSummary2(tool) {
48724
48791
  return { name: name2, command };
48725
48792
  }
48726
48793
  var ProductionMonitor = class {
48727
- constructor(directory, stateDirectory, agentVersion3) {
48794
+ constructor(directory, stateDirectory2, agentVersion3) {
48728
48795
  this.agentVersion = agentVersion3;
48729
- const key = createHash17("sha256").update(path23.resolve(stateDirectory).toLowerCase()).digest("hex");
48796
+ const key = createHash17("sha256").update(path23.resolve(stateDirectory2).toLowerCase()).digest("hex");
48730
48797
  this.file = path23.join(directory, key + ".json");
48731
48798
  this.transportFile = path23.join(directory, key + ".transport");
48732
48799
  }
@@ -49080,6 +49147,342 @@ var FullLogNotice = class {
49080
49147
  }
49081
49148
  };
49082
49149
 
49150
+ // agent/src/token-usage.ts
49151
+ import { randomUUID as randomUUID14 } from "node:crypto";
49152
+ import { lstat as lstat12, mkdir as mkdir11, open as open10, readdir as readdir6, readFile as readFile11, rename as rename8, rm as rm10, writeFile as writeFile5 } from "node:fs/promises";
49153
+ import os8 from "node:os";
49154
+ import path25 from "node:path";
49155
+ var KEEP_DAYS = 35;
49156
+ var MAX_FILES = 1e4;
49157
+ var MAX_SCAN_BYTES = 256 * 1024 * 1024;
49158
+ var CHUNK_BYTES = 4 * 1024 * 1024;
49159
+ var MAX_ROWS = 64;
49160
+ var DAY_MS = 864e5;
49161
+ function tokenUsageRoots(env = process.env) {
49162
+ const home = os8.homedir();
49163
+ const absolute2 = (value, fallback) => value && path25.isAbsolute(value) ? value : fallback;
49164
+ return { claude: absolute2(env.CLAUDE_CONFIG_DIR, path25.join(home, ".claude")), codex: absolute2(env.CODEX_HOME, path25.join(home, ".codex")) };
49165
+ }
49166
+ var stateDirectory = (directory) => path25.join(directory, "optimization");
49167
+ var stateFile = (directory) => path25.join(stateDirectory(directory), "token-usage.json");
49168
+ var utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
49169
+ var count2 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
49170
+ var modelName = (value) => typeof value === "string" && TOKEN_USAGE_MODEL.test(value) ? value : "unknown";
49171
+ async function sources(roots, since) {
49172
+ const found = [];
49173
+ const entries = async (dir) => {
49174
+ try {
49175
+ return await readdir6(dir, { withFileTypes: true });
49176
+ } catch {
49177
+ return [];
49178
+ }
49179
+ };
49180
+ const add = async (client, file3) => {
49181
+ if (found.length >= MAX_FILES) return;
49182
+ try {
49183
+ const info = await lstat12(file3);
49184
+ if (info.isFile() && info.mtimeMs >= since) found.push({ client, file: file3 });
49185
+ } catch {
49186
+ }
49187
+ };
49188
+ const projects = path25.join(roots.claude, "projects");
49189
+ for (const project of await entries(projects)) {
49190
+ if (!project.isDirectory()) continue;
49191
+ for (const entry of await entries(path25.join(projects, project.name))) {
49192
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) await add("claude-code", path25.join(projects, project.name, entry.name));
49193
+ else if (entry.isDirectory()) {
49194
+ const subagents = path25.join(projects, project.name, entry.name, "subagents");
49195
+ for (const agent of await entries(subagents)) if (agent.isFile() && agent.name.endsWith(".jsonl")) await add("claude-code", path25.join(subagents, agent.name));
49196
+ }
49197
+ }
49198
+ }
49199
+ const sessions = path25.join(roots.codex, "sessions"), first = utcDay(since - DAY_MS);
49200
+ for (const year of await entries(sessions)) {
49201
+ if (!year.isDirectory() || !/^\d{4}$/.test(year.name) || year.name < first.slice(0, 4)) continue;
49202
+ for (const month of await entries(path25.join(sessions, year.name))) {
49203
+ if (!month.isDirectory() || !/^\d{2}$/.test(month.name) || `${year.name}-${month.name}` < first.slice(0, 7)) continue;
49204
+ for (const day of await entries(path25.join(sessions, year.name, month.name))) {
49205
+ if (!day.isDirectory() || !/^\d{2}$/.test(day.name) || `${year.name}-${month.name}-${day.name}` < first) continue;
49206
+ const folder = path25.join(sessions, year.name, month.name, day.name);
49207
+ for (const file3 of await entries(folder)) if (file3.isFile() && file3.name.endsWith(".jsonl")) await add("codex", path25.join(folder, file3.name));
49208
+ }
49209
+ }
49210
+ }
49211
+ return found;
49212
+ }
49213
+ function usageFromLine(client, line, file3) {
49214
+ if (client === "claude-code" ? !line.includes('"usage"') : !line.includes('"token_count"') && !line.includes('"turn_context"')) return null;
49215
+ let value;
49216
+ try {
49217
+ value = JSON.parse(line);
49218
+ } catch {
49219
+ return null;
49220
+ }
49221
+ const at = typeof value?.timestamp === "string" ? Date.parse(value.timestamp) : NaN;
49222
+ if (client === "claude-code") {
49223
+ const message2 = value?.type === "assistant" ? value.message : void 0, usage = message2?.usage;
49224
+ if (!usage || typeof message2.id !== "string" || message2.model === "<synthetic>") return null;
49225
+ if (message2.id === file3.lastMessageId) return null;
49226
+ file3.lastMessageId = message2.id.slice(0, 128);
49227
+ const input3 = count2(usage.input_tokens), cacheWrite2 = count2(usage.cache_creation_input_tokens ?? 0), cached3 = count2(usage.cache_read_input_tokens ?? 0), output3 = count2(usage.output_tokens);
49228
+ if (input3 === null || cacheWrite2 === null || cached3 === null || output3 === null || !Number.isFinite(at)) return null;
49229
+ return { at, model: modelName(message2.model), input: input3 + cacheWrite2 + cached3, cached: cached3, cacheWrite: cacheWrite2, output: output3, reasoning: null };
49230
+ }
49231
+ if (value?.type === "turn_context") {
49232
+ file3.model = modelName(value.payload?.model);
49233
+ return null;
49234
+ }
49235
+ const info = value?.type === "event_msg" && value.payload?.type === "token_count" ? value.payload.info : void 0;
49236
+ const total = count2(info?.total_token_usage?.total_tokens), last = info?.last_token_usage;
49237
+ if (total === null || !last || total === file3.lastTotal) return null;
49238
+ file3.lastTotal = total;
49239
+ const input2 = count2(last.input_tokens), cached2 = count2(last.cached_input_tokens ?? 0), cacheWrite = count2(last.cache_write_input_tokens ?? 0), output2 = count2(last.output_tokens), reasoning = count2(last.reasoning_output_tokens ?? 0);
49240
+ if (input2 === null || cached2 === null || cacheWrite === null || output2 === null || reasoning === null || !Number.isFinite(at)) return null;
49241
+ if (cached2 + cacheWrite > input2 || reasoning > output2) return null;
49242
+ return { at, model: file3.model ?? "unknown", input: input2, cached: cached2, cacheWrite, output: output2, reasoning };
49243
+ }
49244
+ async function readNew(source, file3, size, budget, countFrom, add) {
49245
+ if (size < file3.offset) Object.assign(file3, { offset: 0, lastMessageId: void 0, lastTotal: void 0, skipping: false });
49246
+ let read = 0;
49247
+ const handle = await open10(source.file, "r");
49248
+ try {
49249
+ while (file3.offset < size && read < budget) {
49250
+ const length = Math.min(CHUNK_BYTES, size - file3.offset);
49251
+ const buffer = Buffer.alloc(length);
49252
+ const { bytesRead } = await handle.read(buffer, 0, length, file3.offset);
49253
+ if (bytesRead <= 0) break;
49254
+ read += bytesRead;
49255
+ const end = buffer.lastIndexOf(10, bytesRead - 1);
49256
+ if (end < 0) {
49257
+ if (bytesRead < CHUNK_BYTES) break;
49258
+ file3.offset += bytesRead;
49259
+ file3.skipping = true;
49260
+ continue;
49261
+ }
49262
+ let start = 0;
49263
+ if (file3.skipping) {
49264
+ start = buffer.indexOf(10) + 1;
49265
+ file3.skipping = false;
49266
+ }
49267
+ for (const line of buffer.toString("utf8", start, end).split("\n")) {
49268
+ const usage = usageFromLine(source.client, line, file3);
49269
+ if (usage && usage.at >= countFrom) add(source.client, usage);
49270
+ }
49271
+ file3.offset += end + 1;
49272
+ }
49273
+ } finally {
49274
+ await handle.close();
49275
+ }
49276
+ return read;
49277
+ }
49278
+ var TokenUsageReporter = class {
49279
+ constructor(directory, enrollment, options = {}) {
49280
+ this.directory = directory;
49281
+ this.enrollment = enrollment;
49282
+ this.options = options;
49283
+ }
49284
+ directory;
49285
+ enrollment;
49286
+ options;
49287
+ saved;
49288
+ send;
49289
+ enabled = false;
49290
+ wanted = false;
49291
+ timer;
49292
+ running;
49293
+ inFlight;
49294
+ closed = false;
49295
+ failed = false;
49296
+ /** The state frame can arrive before the connection is handed over, so both feed one decision. */
49297
+ connected(send) {
49298
+ this.send = send;
49299
+ this.apply();
49300
+ }
49301
+ disconnected() {
49302
+ this.send = void 0;
49303
+ this.wanted = false;
49304
+ this.apply();
49305
+ if (this.inFlight) {
49306
+ clearTimeout(this.inFlight.timer);
49307
+ this.inFlight = void 0;
49308
+ }
49309
+ }
49310
+ close() {
49311
+ this.closed = true;
49312
+ this.disconnected();
49313
+ }
49314
+ /** The server's choice for this computer, sent after connect and on every change. */
49315
+ state(enabled) {
49316
+ this.wanted = enabled;
49317
+ this.apply();
49318
+ if (!enabled) void this.exclusive(async () => {
49319
+ const saved2 = await this.load();
49320
+ if (!saved2.paused) {
49321
+ saved2.paused = true;
49322
+ await this.persist();
49323
+ }
49324
+ }).catch(() => {
49325
+ });
49326
+ }
49327
+ apply() {
49328
+ const on = this.wanted && !!this.send && !this.closed;
49329
+ if (on && !this.enabled) {
49330
+ this.enabled = true;
49331
+ this.schedule(this.options.firstDelayMs ?? 6e4);
49332
+ } else if (!on && this.enabled) {
49333
+ this.enabled = false;
49334
+ clearTimeout(this.timer);
49335
+ this.timer = void 0;
49336
+ }
49337
+ }
49338
+ ack(batchId, result2) {
49339
+ const flight = this.inFlight;
49340
+ if (!flight || batchId !== flight.batchId) return;
49341
+ clearTimeout(flight.timer);
49342
+ this.inFlight = void 0;
49343
+ if (result2 === "disabled") {
49344
+ this.state(false);
49345
+ return;
49346
+ }
49347
+ if (result2 !== "accepted" && result2 !== "invalid") return;
49348
+ void this.exclusive(async () => {
49349
+ const saved2 = await this.load();
49350
+ for (const [key, version2] of Object.entries(flight.versions)) if (saved2.dirty[key] === version2) delete saved2.dirty[key];
49351
+ await this.persist();
49352
+ if (result2 === "accepted") this.flush();
49353
+ });
49354
+ }
49355
+ /** One scan and report now; used by the timer and by manual checks. */
49356
+ async scanOnce() {
49357
+ await this.exclusive(async () => {
49358
+ const saved2 = await this.load(), now = this.now();
49359
+ if (saved2.paused) {
49360
+ saved2.countFrom = new Date(now).toISOString();
49361
+ saved2.files = {};
49362
+ saved2.baseline = true;
49363
+ delete saved2.paused;
49364
+ }
49365
+ const countFrom = Date.parse(saved2.countFrom);
49366
+ const since = Math.max(countFrom, now - KEEP_DAYS * DAY_MS);
49367
+ let budget = MAX_SCAN_BYTES;
49368
+ const seen = /* @__PURE__ */ new Set();
49369
+ const baseline = saved2.baseline === true;
49370
+ for (const source of await sources(this.roots(), since - DAY_MS)) {
49371
+ if (budget <= 0) break;
49372
+ seen.add(source.file);
49373
+ let info;
49374
+ try {
49375
+ info = await lstat12(source.file);
49376
+ } catch {
49377
+ continue;
49378
+ }
49379
+ const file3 = saved2.files[source.file] ??= { offset: baseline ? info.size : 0, mtimeMs: 0 };
49380
+ file3.mtimeMs = info.mtimeMs;
49381
+ if (info.size === file3.offset) continue;
49382
+ try {
49383
+ budget -= await readNew(source, file3, info.size, budget, countFrom, (client, usage) => this.add(saved2, client, usage));
49384
+ } catch {
49385
+ }
49386
+ }
49387
+ if (baseline) delete saved2.baseline;
49388
+ for (const [name2, file3] of Object.entries(saved2.files)) if (!seen.has(name2) && file3.mtimeMs < now - KEEP_DAYS * DAY_MS) delete saved2.files[name2];
49389
+ const oldest = utcDay(now - KEEP_DAYS * DAY_MS);
49390
+ for (const key of Object.keys(saved2.totals)) if (key.slice(0, 10) < oldest) {
49391
+ delete saved2.totals[key];
49392
+ delete saved2.dirty[key];
49393
+ }
49394
+ await this.persist();
49395
+ });
49396
+ this.flush();
49397
+ }
49398
+ add(saved2, client, usage) {
49399
+ const key = `${utcDay(usage.at)}|${client}|${usage.model}`;
49400
+ const row = saved2.totals[key] ??= { requests: 0, inputTokens: 0, cachedInputTokens: 0, cacheWriteTokens: 0, outputTokens: 0, reasoningTokens: client === "codex" ? 0 : null };
49401
+ row.requests++;
49402
+ row.inputTokens += usage.input;
49403
+ row.cachedInputTokens += usage.cached;
49404
+ row.cacheWriteTokens += usage.cacheWrite;
49405
+ row.outputTokens += usage.output;
49406
+ if (row.reasoningTokens !== null && usage.reasoning !== null) row.reasoningTokens += usage.reasoning;
49407
+ saved2.dirty[key] = (saved2.dirty[key] ?? 0) + 1;
49408
+ }
49409
+ flush() {
49410
+ const saved2 = this.saved, send = this.send;
49411
+ if (!saved2 || !send || !this.enabled || this.inFlight) return;
49412
+ const keys = Object.keys(saved2.dirty).filter((key) => saved2.totals[key]).sort().slice(0, MAX_ROWS);
49413
+ if (!keys.length) return;
49414
+ const rows = keys.map((key) => {
49415
+ const [day, client, model] = key.split("|");
49416
+ return { day, client, model, ...saved2.totals[key] };
49417
+ });
49418
+ const batchId = randomUUID14(), versions = Object.fromEntries(keys.map((key) => [key, saved2.dirty[key]]));
49419
+ let sent = false;
49420
+ try {
49421
+ sent = send({ batchId, stateId: saved2.stateId, rows });
49422
+ } catch {
49423
+ }
49424
+ if (sent) this.inFlight = { batchId, versions, timer: setTimeout(() => {
49425
+ if (this.inFlight?.batchId === batchId) this.inFlight = void 0;
49426
+ }, 3e4).unref() };
49427
+ }
49428
+ schedule(delay4) {
49429
+ clearTimeout(this.timer);
49430
+ this.timer = setTimeout(() => {
49431
+ if (!this.enabled) return;
49432
+ void this.scanOnce().catch(() => {
49433
+ if (!this.failed) {
49434
+ this.failed = true;
49435
+ process.stderr.write("TOKEN_USAGE_SCAN_FAILED\n");
49436
+ }
49437
+ }).finally(() => {
49438
+ if (this.enabled) this.schedule(this.options.intervalMs ?? 36e5);
49439
+ });
49440
+ }, delay4);
49441
+ this.timer.unref();
49442
+ }
49443
+ exclusive(task) {
49444
+ const next = (this.running ?? Promise.resolve()).then(task, task);
49445
+ this.running = next.catch(() => {
49446
+ });
49447
+ return next;
49448
+ }
49449
+ now() {
49450
+ return (this.options.now ?? Date.now)();
49451
+ }
49452
+ roots() {
49453
+ return this.options.roots ?? tokenUsageRoots();
49454
+ }
49455
+ async load() {
49456
+ if (this.saved) return this.saved;
49457
+ let value;
49458
+ try {
49459
+ const info = await lstat12(stateFile(this.directory));
49460
+ if (info.isFile() && !info.isSymbolicLink() && info.size <= 16 * 1024 * 1024) {
49461
+ const parsed = JSON.parse(await readFile11(stateFile(this.directory), "utf8"));
49462
+ if (parsed.version === 1 && parsed.tenantId === this.enrollment.tenantId && parsed.deviceId === this.enrollment.deviceId && typeof parsed.stateId === "string" && Number.isFinite(Date.parse(parsed.countFrom)) && parsed.files && parsed.totals && parsed.dirty) value = parsed;
49463
+ }
49464
+ } catch {
49465
+ }
49466
+ return this.saved = value ?? { version: 1, ...this.enrollment, stateId: randomUUID14(), countFrom: new Date(this.now()).toISOString(), files: {}, totals: {}, dirty: {}, baseline: true };
49467
+ }
49468
+ async persist() {
49469
+ if (!this.saved) return;
49470
+ await mkdir11(stateDirectory(this.directory), { mode: 448 }).catch((error62) => {
49471
+ if (error62.code !== "EEXIST") throw error62;
49472
+ });
49473
+ const parent = await lstat12(stateDirectory(this.directory));
49474
+ if (!parent.isDirectory() || parent.isSymbolicLink()) throw Error("TOKEN_USAGE_DIRECTORY_INVALID");
49475
+ const temporary = stateFile(this.directory) + "." + randomUUID14() + ".tmp";
49476
+ try {
49477
+ await writeFile5(temporary, JSON.stringify(this.saved), { flag: "wx", mode: 384 });
49478
+ await rename8(temporary, stateFile(this.directory));
49479
+ } finally {
49480
+ await rm10(temporary, { force: true }).catch(() => {
49481
+ });
49482
+ }
49483
+ }
49484
+ };
49485
+
49083
49486
  // agent/src/native-event-buffer.ts
49084
49487
  import { createHash as createHash18 } from "node:crypto";
49085
49488
  function nativeFingerprint(code, executionId = "") {
@@ -49362,7 +49765,7 @@ var NativeEventSupervisor = class {
49362
49765
  };
49363
49766
 
49364
49767
  // agent/src/native-fabric-observer.ts
49365
- 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;
49768
+ var uuid23 = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
49366
49769
  var NativeFabricObserver = class {
49367
49770
  constructor(supervisor, source) {
49368
49771
  this.supervisor = supervisor;
@@ -49384,7 +49787,7 @@ var NativeFabricObserver = class {
49384
49787
  unsubscribe;
49385
49788
  connected(authenticatedDeviceId) {
49386
49789
  this.disconnected();
49387
- if (uuid22.test(authenticatedDeviceId)) this.deviceId = authenticatedDeviceId.toLowerCase();
49790
+ if (uuid23.test(authenticatedDeviceId)) this.deviceId = authenticatedDeviceId.toLowerCase();
49388
49791
  this.activity();
49389
49792
  }
49390
49793
  disconnected() {
@@ -49419,17 +49822,17 @@ var NativeFabricObserver = class {
49419
49822
  void Promise.resolve().then(() => this.source.mailbox.snapshot()).then((state) => {
49420
49823
  if (this.closed || expired || generation !== this.generation) return;
49421
49824
  if (state.workers.length > 64 || state.assignments.length > 256 || state.messages.length > 1024) throw Error("FABRIC_BOUND_INVALID");
49422
- const workers = new Set(state.workers.filter((w) => w.device?.deviceId.toLowerCase() === deviceId && uuid22.test(w.workerId)).map((w) => w.workerId));
49825
+ const workers = new Set(state.workers.filter((w) => w.device?.deviceId.toLowerCase() === deviceId && uuid23.test(w.workerId)).map((w) => w.workerId));
49423
49826
  const assignments = new Map(state.assignments.filter((a) => workers.has(a.workerId)).map((a) => [a.assignmentId, a]));
49424
49827
  const refs = /* @__PURE__ */ new Map();
49425
49828
  for (const a of assignments.values()) {
49426
49829
  const id2 = a.execution?.executionId;
49427
- if (!id2 || !uuid22.test(id2)) continue;
49830
+ if (!id2 || !uuid23.test(id2)) continue;
49428
49831
  if (refs.has(id2.toLowerCase())) throw Error("FABRIC_EXECUTION_CONFLICT");
49429
49832
  refs.set(id2.toLowerCase(), {
49430
49833
  executionId: id2.toLowerCase(),
49431
49834
  workerId: a.workerId.toLowerCase(),
49432
- ...uuid22.test(a.taskId) ? { taskId: a.taskId.toLowerCase() } : {}
49835
+ ...uuid23.test(a.taskId) ? { taskId: a.taskId.toLowerCase() } : {}
49433
49836
  });
49434
49837
  }
49435
49838
  this.referencesByExecution.clear();
@@ -49481,27 +49884,27 @@ var NativeFabricObserver = class {
49481
49884
  };
49482
49885
 
49483
49886
  // agent/src/native-fabric-startup.ts
49484
- import { lstat as lstat13, mkdir as mkdir13, open as open11, readFile as readFile11 } from "node:fs/promises";
49485
- import path27 from "node:path";
49887
+ import { lstat as lstat14, mkdir as mkdir14, open as open12, readFile as readFile12 } from "node:fs/promises";
49888
+ import path28 from "node:path";
49486
49889
 
49487
49890
  // src/agent-fabric-service.ts
49488
- import { lstat as lstat12, mkdir as mkdir12, realpath as realpath9 } from "node:fs/promises";
49891
+ import { lstat as lstat13, mkdir as mkdir13, realpath as realpath9 } from "node:fs/promises";
49489
49892
  import { watch } from "node:fs";
49490
- import path26 from "node:path";
49893
+ import path27 from "node:path";
49491
49894
 
49492
49895
  // src/agent-runtime-identity.ts
49493
- import { createHash as createHash19, randomBytes as randomBytes8, randomUUID as randomUUID15, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
49896
+ import { createHash as createHash19, randomBytes as randomBytes8, randomUUID as randomUUID16, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
49494
49897
 
49495
49898
  // src/agent-fabric-state.ts
49496
- import { randomUUID as randomUUID14 } from "node:crypto";
49497
- import { mkdir as mkdir11, open as open10, rename as rename8, unlink as unlink3 } from "node:fs/promises";
49498
- import path25 from "node:path";
49899
+ import { randomUUID as randomUUID15 } from "node:crypto";
49900
+ import { mkdir as mkdir12, open as open11, rename as rename9, unlink as unlink3 } from "node:fs/promises";
49901
+ import path26 from "node:path";
49499
49902
  var queues = /* @__PURE__ */ new Map();
49500
49903
  var FabricStateFile = class {
49501
49904
  constructor(file3, maxBytes, parse4) {
49502
49905
  this.maxBytes = maxBytes;
49503
49906
  this.parse = parse4;
49504
- this.file = path25.resolve(file3);
49907
+ this.file = path26.resolve(file3);
49505
49908
  }
49506
49909
  maxBytes;
49507
49910
  parse;
@@ -49519,7 +49922,7 @@ var FabricStateFile = class {
49519
49922
  return result2;
49520
49923
  }
49521
49924
  async load() {
49522
- const handle = await open10(this.file, "r");
49925
+ const handle = await open11(this.file, "r");
49523
49926
  try {
49524
49927
  const info = await handle.stat();
49525
49928
  if (!info.isFile() || info.size > this.maxBytes) throw Error("FABRIC_STATE_LIMIT");
@@ -49545,10 +49948,10 @@ var FabricStateFile = class {
49545
49948
  }
49546
49949
  update(fn, create) {
49547
49950
  return this.serial(async () => {
49548
- if (create) await mkdir11(path25.dirname(this.file), { recursive: true });
49951
+ if (create) await mkdir12(path26.dirname(this.file), { recursive: true });
49549
49952
  const lockPath = this.file + ".lock";
49550
- const token = randomUUID14();
49551
- const lock = await open10(lockPath, "wx", 384).catch((error62) => {
49953
+ const token = randomUUID15();
49954
+ const lock = await open11(lockPath, "wx", 384).catch((error62) => {
49552
49955
  if (error62.code === "EEXIST") throw Error("FABRIC_STATE_BUSY");
49553
49956
  throw error62;
49554
49957
  });
@@ -49566,7 +49969,7 @@ var FabricStateFile = class {
49566
49969
  const encoded = JSON.stringify(this.parse(state));
49567
49970
  if (Buffer.byteLength(encoded) > this.maxBytes) throw Error("FABRIC_STATE_LIMIT");
49568
49971
  const temporary = this.file + "." + token + ".tmp";
49569
- const handle = await open10(temporary, "wx", 384);
49972
+ const handle = await open11(temporary, "wx", 384);
49570
49973
  try {
49571
49974
  try {
49572
49975
  await handle.writeFile(encoded, "utf8");
@@ -49574,7 +49977,7 @@ var FabricStateFile = class {
49574
49977
  } finally {
49575
49978
  await handle.close();
49576
49979
  }
49577
- await rename8(temporary, this.file);
49980
+ await rename9(temporary, this.file);
49578
49981
  } finally {
49579
49982
  await unlink3(temporary).catch((error62) => {
49580
49983
  if (error62.code !== "ENOENT") throw error62;
@@ -49583,7 +49986,7 @@ var FabricStateFile = class {
49583
49986
  return result2;
49584
49987
  } finally {
49585
49988
  await lock.close();
49586
- const current2 = await open10(lockPath, "r");
49989
+ const current2 = await open11(lockPath, "r");
49587
49990
  try {
49588
49991
  if ((await current2.stat()).size > 1024 || JSON.parse(await current2.readFile("utf8")).token !== token)
49589
49992
  throw Error("FABRIC_STATE_LOCK_CHANGED");
@@ -49643,7 +50046,7 @@ var AgentRuntimeIdentityStore = class {
49643
50046
  issue() {
49644
50047
  return this.serial((state) => {
49645
50048
  if (state.bindings.length >= MAX_BINDINGS) throw Error("RUNTIME_IDENTITY_LIMIT");
49646
- const runtimeId = "rt-" + randomUUID15();
50049
+ const runtimeId = "rt-" + randomUUID16();
49647
50050
  const runtimeKey = randomBytes8(32).toString("base64url");
49648
50051
  const now = this.now();
49649
50052
  state.bindings.push({ runtimeId, keyHash: encodedDigest(runtimeKey), createdAt: now, lastUsedAt: now, revoked: false });
@@ -49676,10 +50079,10 @@ var AgentRuntimeIdentityStore = class {
49676
50079
  };
49677
50080
 
49678
50081
  // src/agent-fabric-mailbox.ts
49679
- import { randomUUID as randomUUID17 } from "node:crypto";
50082
+ import { randomUUID as randomUUID18 } from "node:crypto";
49680
50083
 
49681
50084
  // src/agent-fabric-timeline.ts
49682
- import { randomUUID as randomUUID16 } from "node:crypto";
50085
+ import { randomUUID as randomUUID17 } from "node:crypto";
49683
50086
  import { performance as performance2 } from "node:perf_hooks";
49684
50087
  var FabricId = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/);
49685
50088
  var FabricUtc = external_exports.string().datetime({ precision: 3 }).refine((value) => new Date(value).toISOString() === value);
@@ -49688,7 +50091,7 @@ var FabricStampSchema = external_exports.strictObject({
49688
50091
  clockId: FabricId,
49689
50092
  monotonicMs: external_exports.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER)
49690
50093
  });
49691
- var processClockId = "clock-" + randomUUID16();
50094
+ var processClockId = "clock-" + randomUUID17();
49692
50095
  function createFabricClock() {
49693
50096
  return () => ({ atUtc: (/* @__PURE__ */ new Date()).toISOString(), clockId: processClockId, monotonicMs: performance2.now() });
49694
50097
  }
@@ -49945,7 +50348,7 @@ var AgentWorkerMailbox = class {
49945
50348
  const now = this.clock().atUtc;
49946
50349
  const worker = {
49947
50350
  ...registration,
49948
- workerId: randomUUID17(),
50351
+ workerId: randomUUID18(),
49949
50352
  controllerId: this.controllerId,
49950
50353
  runtimeId: null,
49951
50354
  attribution: WorkerAttributionSchema.parse({}),
@@ -49979,7 +50382,7 @@ var AgentWorkerMailbox = class {
49979
50382
  if (state.messages.length >= MAX_MESSAGES) throw Error("FABRIC_MESSAGE_LIMIT");
49980
50383
  const now = this.clock();
49981
50384
  const message2 = {
49982
- messageId: randomUUID17(),
50385
+ messageId: randomUUID18(),
49983
50386
  key: request.key,
49984
50387
  assignmentId: assignment.assignmentId,
49985
50388
  direction,
@@ -50009,7 +50412,7 @@ var AgentWorkerMailbox = class {
50009
50412
  const now = this.clock().atUtc;
50010
50413
  const assignment = {
50011
50414
  ...request,
50012
- assignmentId: randomUUID17(),
50415
+ assignmentId: randomUUID18(),
50013
50416
  phase: "assigned",
50014
50417
  createdAt: now,
50015
50418
  updatedAt: now,
@@ -50189,9 +50592,9 @@ var WorkerRequest = external_exports.discriminatedUnion("operation", [
50189
50592
  var AgentFabricService = class _AgentFabricService {
50190
50593
  constructor(directory, controllerId) {
50191
50594
  this.directory = directory;
50192
- this.identities = new AgentRuntimeIdentityStore(path26.join(directory, "identities.json"));
50595
+ this.identities = new AgentRuntimeIdentityStore(path27.join(directory, "identities.json"));
50193
50596
  this.mailbox = new AgentWorkerMailbox(
50194
- path26.join(directory, "mailbox.json"),
50597
+ path27.join(directory, "mailbox.json"),
50195
50598
  controllerId,
50196
50599
  this.identities,
50197
50600
  void 0,
@@ -50206,21 +50609,21 @@ var AgentFabricService = class _AgentFabricService {
50206
50609
  closed = false;
50207
50610
  static async open(directory, controllerId, device = null, initialize = true) {
50208
50611
  const expected = Binding.parse({ version: 1, controllerId, device, initialized: false });
50209
- const absolute2 = path26.resolve(directory);
50210
- for (let current2 = absolute2; ; current2 = path26.dirname(current2)) {
50612
+ const absolute2 = path27.resolve(directory);
50613
+ for (let current2 = absolute2; ; current2 = path27.dirname(current2)) {
50211
50614
  try {
50212
- if ((await lstat12(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50615
+ if ((await lstat13(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50213
50616
  } catch (error62) {
50214
50617
  if (error62.code !== "ENOENT") throw error62;
50215
50618
  }
50216
- if (path26.dirname(current2) === current2) break;
50619
+ if (path27.dirname(current2) === current2) break;
50217
50620
  }
50218
- if (initialize) await mkdir12(absolute2, { recursive: true, mode: 448 });
50219
- if (!(await lstat12(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
50621
+ if (initialize) await mkdir13(absolute2, { recursive: true, mode: 448 });
50622
+ if (!(await lstat13(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
50220
50623
  throw Error("FABRIC_DIRECTORY_INVALID");
50221
50624
  const present = /* @__PURE__ */ new Set();
50222
50625
  for (const name2 of ["binding.json", "mailbox.json", "identities.json"]) {
50223
- const file3 = await lstat12(path26.join(absolute2, name2)).catch((error62) => {
50626
+ const file3 = await lstat13(path27.join(absolute2, name2)).catch((error62) => {
50224
50627
  if (error62.code === "ENOENT") return null;
50225
50628
  throw error62;
50226
50629
  });
@@ -50228,7 +50631,7 @@ var AgentFabricService = class _AgentFabricService {
50228
50631
  if (file3) present.add(name2);
50229
50632
  }
50230
50633
  if (!present.has("binding.json") && present.size) throw Error("FABRIC_BINDING_MISSING");
50231
- const binding2 = new FabricStateFile(path26.join(absolute2, "binding.json"), 2048, (value) => Binding.parse(value));
50634
+ const binding2 = new FabricStateFile(path27.join(absolute2, "binding.json"), 2048, (value) => Binding.parse(value));
50232
50635
  const service2 = new _AgentFabricService(absolute2, controllerId);
50233
50636
  await binding2.update(async (state) => {
50234
50637
  if (state.controllerId !== expected.controllerId || JSON.stringify(state.device) !== JSON.stringify(expected.device))
@@ -50243,7 +50646,7 @@ var AgentFabricService = class _AgentFabricService {
50243
50646
  state.initialized = true;
50244
50647
  }
50245
50648
  const snapshot2 = await service2.mailbox.snapshot();
50246
- if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat12(path26.join(absolute2, "identities.json"));
50649
+ if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat13(path27.join(absolute2, "identities.json"));
50247
50650
  }, initialize ? () => expected : void 0);
50248
50651
  return service2;
50249
50652
  }
@@ -50327,26 +50730,26 @@ var OwnerRequest = external_exports.discriminatedUnion("operation", [
50327
50730
  })
50328
50731
  ]);
50329
50732
  var Delivery = external_exports.strictObject({ capability: external_exports.string().regex(/^[A-Za-z0-9+/]+={0,2}$/).max(4096), request: external_exports.unknown() });
50330
- async function openNativeFabric(stateDirectory, enrollment, box, initialize = true) {
50733
+ async function openNativeFabric(stateDirectory2, enrollment, box, initialize = true) {
50331
50734
  const controllerId = "device-" + external_exports.string().uuid().parse(enrollment.deviceId).toLowerCase();
50332
50735
  const tenantId = external_exports.string().uuid().parse(enrollment.tenantId).toLowerCase();
50333
- const parent = path27.join(stateDirectory, ".local-commander"), marker = path27.join(parent, "fabric-established.json");
50736
+ const parent = path28.join(stateDirectory2, ".local-commander"), marker = path28.join(parent, "fabric-established.json");
50334
50737
  try {
50335
- await mkdir13(parent, { mode: 448 });
50738
+ await mkdir14(parent, { mode: 448 });
50336
50739
  } catch (error62) {
50337
50740
  if (error62.code !== "EEXIST") throw error62;
50338
50741
  }
50339
- const parentInfo = await lstat13(parent);
50742
+ const parentInfo = await lstat14(parent);
50340
50743
  if (!parentInfo.isDirectory() || parentInfo.isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50341
50744
  const expected = JSON.stringify({ version: 1, controllerId, tenantId });
50342
50745
  let fresh = false;
50343
50746
  try {
50344
- const info = await lstat13(marker);
50345
- if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile11(marker, "utf8") !== expected)
50747
+ const info = await lstat14(marker);
50748
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile12(marker, "utf8") !== expected)
50346
50749
  throw Error("FABRIC_BINDING_CHANGED");
50347
50750
  } catch (error62) {
50348
50751
  if (error62.code !== "ENOENT" || !initialize) throw error62;
50349
- const file3 = await open11(marker, "wx", 384);
50752
+ const file3 = await open12(marker, "wx", 384);
50350
50753
  try {
50351
50754
  await file3.writeFile(expected);
50352
50755
  await file3.datasync();
@@ -50356,22 +50759,22 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
50356
50759
  fresh = true;
50357
50760
  }
50358
50761
  const service2 = await AgentFabricService.open(
50359
- path27.join(stateDirectory, ".local-commander", "fabric"),
50762
+ path28.join(stateDirectory2, ".local-commander", "fabric"),
50360
50763
  controllerId,
50361
50764
  { deviceId: enrollment.deviceId.toLowerCase(), enrollmentEvidenceRef: "enrollment-" + tenantId },
50362
50765
  fresh
50363
50766
  );
50364
50767
  const purpose = "native-fabric:" + tenantId + ":" + controllerId;
50365
- const credentialFile = (workerId) => path27.join(service2.directory, external_exports.string().uuid().parse(workerId) + ".capability");
50768
+ const credentialFile = (workerId) => path28.join(service2.directory, external_exports.string().uuid().parse(workerId) + ".capability");
50366
50769
  const decode4 = (value) => {
50367
50770
  const credential = Credential.parse(JSON.parse(box.open(Buffer.from(value, "base64"), purpose).toString("utf8")));
50368
50771
  if (credential.controllerId !== controllerId) throw Error("FABRIC_WORKER_DENIED");
50369
50772
  return credential;
50370
50773
  };
50371
50774
  async function capability(workerId) {
50372
- const file3 = credentialFile(workerId), info = await lstat13(file3);
50775
+ const file3 = credentialFile(workerId), info = await lstat14(file3);
50373
50776
  if (!info.isFile() || info.isSymbolicLink() || info.size > 4096) throw Error("FABRIC_CREDENTIAL_UNKNOWN");
50374
- const encoded = await readFile11(file3, "utf8");
50777
+ const encoded = await readFile12(file3, "utf8");
50375
50778
  if (decode4(encoded).workerId !== workerId) throw Error("FABRIC_WORKER_DENIED");
50376
50779
  return encoded;
50377
50780
  }
@@ -50404,7 +50807,7 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
50404
50807
  } else {
50405
50808
  const credential = await service2.identities.issue();
50406
50809
  const encoded = box.seal(Buffer.from(JSON.stringify({ ...credential, workerId: worker.workerId, controllerId })), purpose).toString("base64");
50407
- const file3 = await open11(credentialFile(worker.workerId), "wx", 384);
50810
+ const file3 = await open12(credentialFile(worker.workerId), "wx", 384);
50408
50811
  try {
50409
50812
  await file3.writeFile(encoded);
50410
50813
  await file3.datasync();
@@ -50463,7 +50866,7 @@ async function readFabricRequest(input2 = process.stdin) {
50463
50866
 
50464
50867
  // agent/src/supervisor-liveness.ts
50465
50868
  import { spawn as spawn6 } from "node:child_process";
50466
- import path28 from "node:path";
50869
+ import path29 from "node:path";
50467
50870
  import { setTimeout as delay3 } from "node:timers/promises";
50468
50871
  var ROW = /^"([^"]+)","(\d{1,10})"/;
50469
50872
  function parseTasklist(output2, image) {
@@ -50478,7 +50881,7 @@ function parseTasklist(output2, image) {
50478
50881
  }
50479
50882
  function listProcesses(image, timeoutMs2 = 5e3) {
50480
50883
  if (process.platform !== "win32" || !/^[A-Za-z0-9._-]{1,64}\.exe$/i.test(image)) return Promise.resolve(null);
50481
- const tasklist = path28.join(process.env.SystemRoot || "C:\\Windows", "System32", "tasklist.exe");
50884
+ const tasklist = path29.join(process.env.SystemRoot || "C:\\Windows", "System32", "tasklist.exe");
50482
50885
  return new Promise((resolve) => {
50483
50886
  let output2 = "", settled = false;
50484
50887
  const finish = (value) => {
@@ -50507,8 +50910,8 @@ function listProcesses(image, timeoutMs2 = 5e3) {
50507
50910
  }
50508
50911
  function supervisorLiveness(helperPath, options = {}) {
50509
50912
  if (process.platform === "linux" && !options.list) return linuxSupervisorLiveness;
50510
- if (process.platform === "darwin" && !options.list) return (pids, _linux, darwin) => darwinSupervisorLiveness(path28.join(path28.dirname(helperPath), "posix-host"), pids, darwin);
50511
- const image = path28.basename(helperPath), waitMs = options.waitMs ?? 1e4, pollMs = options.pollMs ?? 500, list = options.list ?? listProcesses;
50913
+ if (process.platform === "darwin" && !options.list) return (pids, _linux, darwin) => darwinSupervisorLiveness(path29.join(path29.dirname(helperPath), "posix-host"), pids, darwin);
50914
+ const image = path29.basename(helperPath), waitMs = options.waitMs ?? 1e4, pollMs = options.pollMs ?? 500, list = options.list ?? listProcesses;
50512
50915
  return async (pids) => {
50513
50916
  const deadline = Date.now() + waitMs;
50514
50917
  for (; ; ) {
@@ -50523,8 +50926,8 @@ function supervisorLiveness(helperPath, options = {}) {
50523
50926
 
50524
50927
  // agent/src/content-audit.ts
50525
50928
  import { createReadStream } from "node:fs";
50526
- import { appendFile, lstat as lstat14, mkdir as mkdir14, open as open12, readdir as readdir6, readFile as readFile12, rename as rename9, rm as rm10, writeFile as writeFile5 } from "node:fs/promises";
50527
- import path29 from "node:path";
50929
+ import { appendFile, lstat as lstat15, mkdir as mkdir15, open as open13, readdir as readdir7, readFile as readFile13, rename as rename10, rm as rm11, writeFile as writeFile6 } from "node:fs/promises";
50930
+ import path30 from "node:path";
50528
50931
  import { performance as performance3 } from "node:perf_hooks";
50529
50932
  import { createInterface as createInterface2 } from "node:readline";
50530
50933
  import { randomBytes as randomBytes10 } from "node:crypto";
@@ -50691,19 +51094,19 @@ var AUDIT_MAX_BYTES = 512 * 1024 * 1024;
50691
51094
  var MAX_PENDING = 64;
50692
51095
  var FILE = /^(full|metrics)-(\d{4}-\d{2}-\d{2})\.jsonl$/;
50693
51096
  var PAUSED_FILE = "paused.json";
50694
- var DAY_MS = 864e5;
51097
+ var DAY_MS2 = 864e5;
50695
51098
  function contentAuditDirectory(stateDir) {
50696
- return path29.join(path29.dirname(path29.resolve(stateDir)), "Audit");
51099
+ return path30.join(path30.dirname(path30.resolve(stateDir)), "Audit");
50697
51100
  }
50698
51101
  async function plainDirectory(dir) {
50699
- await mkdir14(dir, { recursive: true, mode: 448 });
50700
- const info = await lstat14(dir);
51102
+ await mkdir15(dir, { recursive: true, mode: 448 });
51103
+ const info = await lstat15(dir);
50701
51104
  if (info.isSymbolicLink() || !info.isDirectory()) throw Error("AUDIT_DIRECTORY_INVALID");
50702
51105
  }
50703
51106
  async function auditFiles(dir) {
50704
51107
  let names;
50705
51108
  try {
50706
- names = await readdir6(dir);
51109
+ names = await readdir7(dir);
50707
51110
  } catch (error62) {
50708
51111
  if (error62.code === "ENOENT") return [];
50709
51112
  throw error62;
@@ -50712,7 +51115,7 @@ async function auditFiles(dir) {
50712
51115
  for (const name2 of names) {
50713
51116
  const match = FILE.exec(name2);
50714
51117
  if (!match) continue;
50715
- const info = await lstat14(path29.join(dir, name2));
51118
+ const info = await lstat15(path30.join(dir, name2));
50716
51119
  if (info.isFile()) files.push({ name: name2, kind: match[1], day: match[2], bytes: info.size });
50717
51120
  }
50718
51121
  return files.sort((a, b) => a.name.localeCompare(b.name));
@@ -50720,10 +51123,10 @@ async function auditFiles(dir) {
50720
51123
  async function writeJsonAtomic(file3, value) {
50721
51124
  const temp = `${file3}.${randomBytes10(6).toString("hex")}.tmp`;
50722
51125
  try {
50723
- await writeFile5(temp, JSON.stringify(value) + "\n", { flag: "wx", mode: 384 });
50724
- await rename9(temp, file3);
51126
+ await writeFile6(temp, JSON.stringify(value) + "\n", { flag: "wx", mode: 384 });
51127
+ await rename10(temp, file3);
50725
51128
  } finally {
50726
- await rm10(temp, { force: true }).catch(() => {
51129
+ await rm11(temp, { force: true }).catch(() => {
50727
51130
  });
50728
51131
  }
50729
51132
  }
@@ -50750,7 +51153,7 @@ var ContentAudit = class _ContentAudit {
50750
51153
  skipped = 0;
50751
51154
  closed = false;
50752
51155
  static async open(options) {
50753
- const dir = path29.resolve(options.directory);
51156
+ const dir = path30.resolve(options.directory);
50754
51157
  await plainDirectory(dir);
50755
51158
  const audit = new _ContentAudit(
50756
51159
  dir,
@@ -50759,7 +51162,7 @@ var ContentAudit = class _ContentAudit {
50759
51162
  { retentionDays: options.retentionDays ?? AUDIT_RETENTION_DAYS, maxBytes: options.maxBytes ?? AUDIT_MAX_BYTES },
50760
51163
  options.now ?? (() => /* @__PURE__ */ new Date())
50761
51164
  );
50762
- await rm10(path29.join(dir, PAUSED_FILE), { force: true });
51165
+ await rm11(path30.join(dir, PAUSED_FILE), { force: true });
50763
51166
  await audit.rollover(audit.now());
50764
51167
  if (audit.usedBytes >= audit.limits.maxBytes) await audit.pause("QUOTA_EXCEEDED");
50765
51168
  return audit;
@@ -50829,17 +51232,17 @@ var ContentAudit = class _ContentAudit {
50829
51232
  await this.pause("QUOTA_EXCEEDED");
50830
51233
  return;
50831
51234
  }
50832
- await appendFile(path29.join(this.dir, `full-${day}.jsonl`), line, { mode: 384 });
50833
- await appendFile(path29.join(this.dir, `metrics-${day}.jsonl`), metrics, { mode: 384 });
51235
+ await appendFile(path30.join(this.dir, `full-${day}.jsonl`), line, { mode: 384 });
51236
+ await appendFile(path30.join(this.dir, `metrics-${day}.jsonl`), metrics, { mode: 384 });
50834
51237
  this.usedBytes += bytes3;
50835
51238
  }
50836
51239
  /** Daily retention runs on the first write of a new day; no timer or background scan. */
50837
51240
  async rollover(at) {
50838
51241
  this.day = at.toISOString().slice(0, 10);
50839
- const cutoff = new Date(at.getTime() - this.limits.retentionDays * DAY_MS).toISOString().slice(0, 10);
51242
+ const cutoff = new Date(at.getTime() - this.limits.retentionDays * DAY_MS2).toISOString().slice(0, 10);
50840
51243
  let used = 0;
50841
51244
  for (const file3 of await auditFiles(this.dir)) {
50842
- if (file3.day <= cutoff) await rm10(path29.join(this.dir, file3.name), { force: true });
51245
+ if (file3.day <= cutoff) await rm11(path30.join(this.dir, file3.name), { force: true });
50843
51246
  else used += file3.bytes;
50844
51247
  }
50845
51248
  this.usedBytes = used;
@@ -50847,7 +51250,7 @@ var ContentAudit = class _ContentAudit {
50847
51250
  async pause(reason) {
50848
51251
  if (this.paused) return;
50849
51252
  this.paused = reason;
50850
- await writeJsonAtomic(path29.join(this.dir, PAUSED_FILE), { reason, at: this.now().toISOString() });
51253
+ await writeJsonAtomic(path30.join(this.dir, PAUSED_FILE), { reason, at: this.now().toISOString() });
50851
51254
  }
50852
51255
  };
50853
51256
  function percentiles(values) {
@@ -50867,15 +51270,15 @@ async function* jsonLines(file3) {
50867
51270
  }
50868
51271
  }
50869
51272
  }
50870
- var count2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
51273
+ var count3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
50871
51274
  async function summarizeContentAudit(directory, key) {
50872
- const dir = path29.resolve(directory);
51275
+ const dir = path30.resolve(directory);
50873
51276
  const files = await auditFiles(dir);
50874
51277
  const days = /* @__PURE__ */ new Map();
50875
51278
  const sizes = [];
50876
51279
  const timings = [];
50877
51280
  for (const file3 of files.filter((f) => f.kind === "metrics")) {
50878
- for await (const line of jsonLines(path29.join(dir, file3.name))) {
51281
+ for await (const line of jsonLines(path30.join(dir, file3.name))) {
50879
51282
  let day = days.get(file3.day);
50880
51283
  if (!day) {
50881
51284
  day = { day: file3.day, records: 0, failed: 0, rawBytes: 0, sanitizedBytes: 0, compressedBytes: 0, envelopeBytes: 0 };
@@ -50883,19 +51286,19 @@ async function summarizeContentAudit(directory, key) {
50883
51286
  }
50884
51287
  day.records += 1;
50885
51288
  if (line.resultCode !== "SUCCESS") day.failed += 1;
50886
- day.rawBytes += count2(line.rawBytes);
50887
- day.sanitizedBytes += count2(line.sanitizedBytes);
50888
- day.compressedBytes += count2(line.compressedBytes);
50889
- day.envelopeBytes += count2(line.envelopeBytes);
51289
+ day.rawBytes += count3(line.rawBytes);
51290
+ day.sanitizedBytes += count3(line.sanitizedBytes);
51291
+ day.compressedBytes += count3(line.compressedBytes);
51292
+ day.envelopeBytes += count3(line.envelopeBytes);
50890
51293
  if (sizes.length < 1e5) {
50891
- sizes.push(count2(line.envelopeBytes));
50892
- timings.push(count2(line.encryptMs));
51294
+ sizes.push(count3(line.envelopeBytes));
51295
+ timings.push(count3(line.encryptMs));
50893
51296
  }
50894
51297
  }
50895
51298
  }
50896
51299
  let paused = null;
50897
51300
  try {
50898
- const value = JSON.parse(await readFile12(path29.join(dir, PAUSED_FILE), "utf8"));
51301
+ const value = JSON.parse(await readFile13(path30.join(dir, PAUSED_FILE), "utf8"));
50899
51302
  if (typeof value.reason === "string" && typeof value.at === "string") paused = { reason: value.reason.slice(0, 40), at: value.at.slice(0, 40) };
50900
51303
  } catch {
50901
51304
  }
@@ -50903,7 +51306,7 @@ async function summarizeContentAudit(directory, key) {
50903
51306
  const newest = files.filter((f) => f.kind === "full").at(-1);
50904
51307
  if (key && newest) {
50905
51308
  const tail = [];
50906
- for await (const line of jsonLines(path29.join(dir, newest.name))) {
51309
+ for await (const line of jsonLines(path30.join(dir, newest.name))) {
50907
51310
  tail.push(line);
50908
51311
  if (tail.length > 5) tail.shift();
50909
51312
  }
@@ -50937,10 +51340,10 @@ async function summarizeContentAudit(directory, key) {
50937
51340
  };
50938
51341
  }
50939
51342
  async function restoreContentAudit(input2, output2, key) {
50940
- const handle = await open12(path29.resolve(output2), "wx", 384);
51343
+ const handle = await open13(path30.resolve(output2), "wx", 384);
50941
51344
  let records = 0, failed = 0;
50942
51345
  try {
50943
- for await (const line of jsonLines(path29.resolve(input2))) {
51346
+ for await (const line of jsonLines(path30.resolve(input2))) {
50944
51347
  try {
50945
51348
  await handle.appendFile(JSON.stringify(decryptAuditRecord(line, key)) + "\n");
50946
51349
  records += 1;
@@ -50955,7 +51358,7 @@ async function restoreContentAudit(input2, output2, key) {
50955
51358
  }
50956
51359
 
50957
51360
  // agent/src/main.ts
50958
- var AGENT_VERSION2 = true ? "0.3.51" : "0.3.2";
51361
+ var AGENT_VERSION2 = true ? "0.3.52" : "0.3.2";
50959
51362
  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" : "";
50960
51363
  var AI_CONNECTION_SHIPPED = false;
50961
51364
  var QUARANTINE_RETRY_MS = 6e4;
@@ -50969,11 +51372,11 @@ function processAlive(pid) {
50969
51372
  }
50970
51373
  }
50971
51374
  async function claimAgentProcess(stateDir, runtimeDir, version2) {
50972
- await mkdir15(stateDir, { recursive: true });
50973
- const file3 = path30.join(stateDir, "agent-process.json");
51375
+ await mkdir16(stateDir, { recursive: true });
51376
+ const file3 = path31.join(stateDir, "agent-process.json");
50974
51377
  for (let attempt = 0; attempt < 2; attempt += 1) {
50975
51378
  try {
50976
- const handle = await open13(file3, "wx", 384);
51379
+ const handle = await open14(file3, "wx", 384);
50977
51380
  try {
50978
51381
  await handle.writeFile(JSON.stringify({ pid: process.pid, runtimeDir, version: version2, startedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", "utf8");
50979
51382
  } finally {
@@ -50981,8 +51384,8 @@ async function claimAgentProcess(stateDir, runtimeDir, version2) {
50981
51384
  }
50982
51385
  return async () => {
50983
51386
  try {
50984
- const current2 = JSON.parse(await readFile13(file3, "utf8"));
50985
- if (current2.pid === process.pid) await rm11(file3, { force: true });
51387
+ const current2 = JSON.parse(await readFile14(file3, "utf8"));
51388
+ if (current2.pid === process.pid) await rm12(file3, { force: true });
50986
51389
  } catch {
50987
51390
  }
50988
51391
  };
@@ -50990,12 +51393,12 @@ async function claimAgentProcess(stateDir, runtimeDir, version2) {
50990
51393
  if (!error62 || typeof error62 !== "object" || !("code" in error62) || error62.code !== "EEXIST") throw error62;
50991
51394
  let stale = true;
50992
51395
  try {
50993
- const current2 = JSON.parse(await readFile13(file3, "utf8"));
51396
+ const current2 = JSON.parse(await readFile14(file3, "utf8"));
50994
51397
  stale = typeof current2.pid !== "number" || !processAlive(current2.pid);
50995
51398
  } catch {
50996
51399
  }
50997
51400
  if (!stale) throw Error("AGENT_ALREADY_RUNNING");
50998
- await rm11(file3, { force: true });
51401
+ await rm12(file3, { force: true });
50999
51402
  }
51000
51403
  }
51001
51404
  throw Error("AGENT_ALREADY_RUNNING");
@@ -51119,6 +51522,7 @@ async function runAgent(options) {
51119
51522
  status: () => runtime.status(),
51120
51523
  onIncidentAck: (ack) => incidentProducer.ack(ack),
51121
51524
  onFullLogChoice: options.onFullLogChoice,
51525
+ ...options.tokenUsage ? { onTokenUsageState: (enabled) => options.tokenUsage.state(enabled), onTokenUsageAck: (batchId, result2) => options.tokenUsage.ack(batchId, result2) } : {},
51122
51526
  // After bridge.connected, like requests: the journal has recorded this connection first.
51123
51527
  onHeldLeases: (bindings) => {
51124
51528
  void readyPromise.then(() => bridge.heldLeases(bindings)).catch(() => {
@@ -51152,6 +51556,7 @@ async function runAgent(options) {
51152
51556
  await options.journal.prune();
51153
51557
  connection.reportStatus?.();
51154
51558
  incidentProducer.connected(connection.sendIncidentBatch);
51559
+ options.tokenUsage?.connected(connection.sendTokenUsageBatch);
51155
51560
  supervisor.observe({ kind: "connected" });
51156
51561
  monitor(() => options.monitor?.setConnection("connected", connection));
51157
51562
  if (options.monitor && !connection.monitorFreshnessMs) {
@@ -51207,6 +51612,7 @@ async function runAgent(options) {
51207
51612
  clearInterval(legacyMonitorTimer);
51208
51613
  legacyMonitorTimer = void 0;
51209
51614
  incidentProducer.disconnected();
51615
+ options.tokenUsage?.disconnected();
51210
51616
  if (!options.signal.aborted) supervisor.observe({ kind: "disconnected" });
51211
51617
  monitor(() => options.monitor?.setConnection("disconnected"));
51212
51618
  try {
@@ -51227,6 +51633,7 @@ async function runAgent(options) {
51227
51633
  } finally {
51228
51634
  fabric?.close();
51229
51635
  incidentProducer.close();
51636
+ options.tokenUsage?.close();
51230
51637
  supervisor.close();
51231
51638
  await options.journal.close();
51232
51639
  }
@@ -51253,10 +51660,10 @@ async function openContentAudit(store, stateDir) {
51253
51660
  async function main() {
51254
51661
  if (!["win32", "linux", "darwin"].includes(process.platform)) throw Error("PLATFORM_UNSUPPORTED");
51255
51662
  const appData = process.env.LC_AGENT_DATA_DIR ?? (process.platform === "win32" ? process.env.LOCALAPPDATA : posixDataHome());
51256
- if (!appData || !path30.isAbsolute(appData)) throw Error("APP_DATA_MISSING");
51257
- const stateDir = process.env.LC_AGENT_STATE_DIR ?? path30.join(appData, "LocalCommander", "Agent");
51258
- const binaryDir = path30.dirname(process.platform === "win32" ? process.execPath : await realpath10(process.execPath));
51259
- const ownerBridgePath = process.env.LC_OWNER_BRIDGE ?? path30.join(binaryDir, process.platform === "win32" ? "OwnerBridge.exe" : "owner-store");
51663
+ if (!appData || !path31.isAbsolute(appData)) throw Error("APP_DATA_MISSING");
51664
+ const stateDir = process.env.LC_AGENT_STATE_DIR ?? path31.join(appData, "LocalCommander", "Agent");
51665
+ const binaryDir = path31.dirname(process.platform === "win32" ? process.execPath : await realpath10(process.execPath));
51666
+ const ownerBridgePath = process.env.LC_OWNER_BRIDGE ?? path31.join(binaryDir, process.platform === "win32" ? "OwnerBridge.exe" : "owner-store");
51260
51667
  const store = await WindowsPrivateStore.open(stateDir, ownerBridgePath);
51261
51668
  const command = process.argv[2] ?? "run";
51262
51669
  if (process.platform !== "win32" && (command.startsWith("guard-") || command.startsWith("network-"))) throw Error("FEATURE_PLATFORM_UNSUPPORTED");
@@ -51266,7 +51673,7 @@ async function main() {
51266
51673
  const pairing = new PairingClient(store, { controlPlaneOrigin: origin, agentVersion: AGENT_VERSION2 });
51267
51674
  const begun = await pairing.begin();
51268
51675
  process.stdout.write(JSON.stringify({ approvalUrl: begun.approvalUrl, confirmationCode: begun.confirmationCode, expiresAt: begun.expiresAt.toISOString() }) + "\n");
51269
- await pairing.waitAndComplete(begun, os8.hostname().slice(0, 120));
51676
+ await pairing.waitAndComplete(begun, os9.hostname().slice(0, 120));
51270
51677
  process.stdout.write("DEVICE_PAIRED\n");
51271
51678
  return;
51272
51679
  }
@@ -51352,7 +51759,7 @@ async function main() {
51352
51759
  }
51353
51760
  if (command === "efficiency-report") {
51354
51761
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
51355
- const ledger = await OptimizationLedger.open(path30.join(stateDir, "optimization"));
51762
+ const ledger = await OptimizationLedger.open(path31.join(stateDir, "optimization"));
51356
51763
  try {
51357
51764
  process.stdout.write(JSON.stringify(await ledger.report(), null, 2) + "\n");
51358
51765
  } finally {
@@ -51362,7 +51769,7 @@ async function main() {
51362
51769
  }
51363
51770
  if (command === "guard-configure") {
51364
51771
  if (args.length !== 1) throw Error("AGENT_COMMAND_INVALID");
51365
- const filename = await (await import("node:fs/promises")).realpath(path30.resolve(args[0]));
51772
+ const filename = await (await import("node:fs/promises")).realpath(path31.resolve(args[0]));
51366
51773
  const input2 = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await readWindowsFile(ownerBridgePath, filename, 2e5)));
51367
51774
  if (!input2 || typeof input2 !== "object" || Object.keys(input2).sort().join(",") !== "compact,settings") throw Error("GUARD_CONFIGURATION_INVALID");
51368
51775
  await store.configureGuard(input2.settings, input2.compact);
@@ -51381,7 +51788,7 @@ async function main() {
51381
51788
  }
51382
51789
  if (command === "guard-evidence") {
51383
51790
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
51384
- const journal = await NativeJournal.open(path30.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51791
+ const journal = await NativeJournal.open(path31.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51385
51792
  try {
51386
51793
  process.stdout.write(JSON.stringify(await journal.guardEvidence()) + "\n");
51387
51794
  } finally {
@@ -51393,7 +51800,7 @@ async function main() {
51393
51800
  if (args.length !== (command === "guard-export" ? 0 : 1)) throw Error("AGENT_COMMAND_INVALID");
51394
51801
  const identity = await store.load();
51395
51802
  if (!identity?.enrollment) throw Error("ENROLLMENT_MISSING");
51396
- const journal = await NativeJournal.open(path30.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51803
+ const journal = await NativeJournal.open(path31.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51397
51804
  try {
51398
51805
  const { tenantId, deviceId } = identity.enrollment;
51399
51806
  const records = (await journal.guardEvidence()).filter((record2) => record2.tenantId === tenantId && record2.deviceId === deviceId);
@@ -51471,27 +51878,27 @@ async function main() {
51471
51878
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
51472
51879
  if (!(await store.load())?.enrollment) throw Error("ENROLLMENT_MISSING");
51473
51880
  const releaseProcess = await claimAgentProcess(stateDir, binaryDir, AGENT_VERSION2);
51474
- const monitor = new ProductionMonitor(path30.join(appData, "LocalCommander", "Monitor"), stateDir, AGENT_VERSION2);
51881
+ const monitor = new ProductionMonitor(path31.join(appData, "LocalCommander", "Monitor"), stateDir, AGENT_VERSION2);
51475
51882
  const publishMonitor = () => monitor.flush().catch(() => {
51476
51883
  process.stderr.write("MONITOR_WRITE_FAILED\n");
51477
51884
  });
51478
51885
  await publishMonitor();
51479
51886
  try {
51480
51887
  const journal = await NativeJournal.open(
51481
- path30.join(stateDir, "journal"),
51888
+ path31.join(stateDir, "journal"),
51482
51889
  new SecretBox({ "1": await store.loadDataKey() }),
51483
- process.platform === "win32" ? {} : { lockHelper: path30.join(binaryDir, "posix-host") }
51890
+ process.platform === "win32" ? {} : { lockHelper: path31.join(binaryDir, "posix-host") }
51484
51891
  );
51485
51892
  const ledgerLoss = () => {
51486
51893
  process.stderr.write("OPTIMIZATION_TELEMETRY_INCOMPLETE\n");
51487
51894
  };
51488
51895
  const efficiencyLedger = await new OptionalWork(ledgerLoss, 1e3, 1).run(
51489
- () => OptimizationLedger.open(path30.join(stateDir, "optimization")),
51896
+ () => OptimizationLedger.open(path31.join(stateDir, "optimization")),
51490
51897
  void 0,
51491
51898
  (ledger) => ledger.close()
51492
51899
  );
51493
51900
  try {
51494
- const helperPath = process.env.LC_JOB_HOST ?? path30.join(binaryDir, process.platform === "win32" ? "JobHost.exe" : "job-host.mjs");
51901
+ const helperPath = process.env.LC_JOB_HOST ?? path31.join(binaryDir, process.platform === "win32" ? "JobHost.exe" : "job-host.mjs");
51495
51902
  const tools = new NativeTools({ stateDirectory: stateDir, helperPath, ownerBridgePath, programs: await store.loadPrograms() });
51496
51903
  const stop = new AbortController();
51497
51904
  process.once("SIGINT", () => stop.abort());
@@ -51504,6 +51911,7 @@ async function main() {
51504
51911
  });
51505
51912
  };
51506
51913
  onFullLogChoice(null);
51914
+ const tokenUsage = process.env.LC_TOKEN_USAGE === "off" ? void 0 : new TokenUsageReporter(stateDir, enrollment);
51507
51915
  const fabric = await openNativeFabric(stateDir, enrollment, new SecretBox({ "1": await store.loadDataKey() })).catch(() => {
51508
51916
  process.stderr.write("FABRIC_STARTUP_FAILED\n");
51509
51917
  return void 0;
@@ -51533,6 +51941,7 @@ async function main() {
51533
51941
  efficiencyLedger,
51534
51942
  monitor,
51535
51943
  onFullLogChoice,
51944
+ ...tokenUsage ? { tokenUsage } : {},
51536
51945
  localDirect: { key: localDirectKey(await store.loadDataKey()), directory: localDirectDirectory(appData) },
51537
51946
  supervisorLiveness: supervisorLiveness(helperPath),
51538
51947
  ...proxyMode ? { proxyMode: { providers: proxyMode.providers, publicKeyPem: NETWORK_PUBLIC_KEY, endpoint: proxyEndpoint, onState: onProxyState } } : {},
@@ -51569,7 +51978,7 @@ async function main() {
51569
51978
  await releaseProcess();
51570
51979
  }
51571
51980
  }
51572
- var entrypoint = process.argv[1] && (process.platform === "win32" ? path30.resolve(process.argv[1]) : await realpath10(process.argv[1]).catch(() => null));
51981
+ var entrypoint = process.argv[1] && (process.platform === "win32" ? path31.resolve(process.argv[1]) : await realpath10(process.argv[1]).catch(() => null));
51573
51982
  if (entrypoint === fileURLToPath(import.meta.url)) {
51574
51983
  void main().catch((error62) => {
51575
51984
  const code = error62 instanceof Error && /^[A-Z0-9_]{1,64}$/.test(error62.message) ? error62.message : "AGENT_START_FAILED";