local-commander-agent-linux-x64 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
@@ -3253,7 +3253,7 @@ var require_stream = __commonJS({
3253
3253
  };
3254
3254
  duplex._final = function(callback) {
3255
3255
  if (ws.readyState === ws.CONNECTING) {
3256
- ws.once("open", function open14() {
3256
+ ws.once("open", function open15() {
3257
3257
  duplex._final(callback);
3258
3258
  });
3259
3259
  return;
@@ -3274,7 +3274,7 @@ var require_stream = __commonJS({
3274
3274
  };
3275
3275
  duplex._write = function(chunk, encoding, callback) {
3276
3276
  if (ws.readyState === ws.CONNECTING) {
3277
- ws.once("open", function open14() {
3277
+ ws.once("open", function open15() {
3278
3278
  duplex._write(chunk, encoding, callback);
3279
3279
  });
3280
3280
  return;
@@ -4554,10 +4554,10 @@ function mergeDefs(...defs) {
4554
4554
  function cloneDef(schema) {
4555
4555
  return mergeDefs(schema._zod.def);
4556
4556
  }
4557
- function getElementAtPath(obj, path31) {
4558
- if (!path31)
4557
+ function getElementAtPath(obj, path32) {
4558
+ if (!path32)
4559
4559
  return obj;
4560
- return path31.reduce((acc, key) => acc?.[key], obj);
4560
+ return path32.reduce((acc, key) => acc?.[key], obj);
4561
4561
  }
4562
4562
  function promiseAllObject(promisesObj) {
4563
4563
  const keys = Object.keys(promisesObj);
@@ -4897,11 +4897,11 @@ function explicitlyAborted(x, startIndex = 0) {
4897
4897
  }
4898
4898
  return false;
4899
4899
  }
4900
- function prefixIssues(path31, issues) {
4900
+ function prefixIssues(path32, issues) {
4901
4901
  return issues.map((iss) => {
4902
4902
  var _a3;
4903
4903
  (_a3 = iss).path ?? (_a3.path = []);
4904
- iss.path.unshift(path31);
4904
+ iss.path.unshift(path32);
4905
4905
  return iss;
4906
4906
  });
4907
4907
  }
@@ -4952,14 +4952,14 @@ function codePointLength(str) {
4952
4952
  const units2 = str.length;
4953
4953
  if (!highSurrogate.test(str))
4954
4954
  return units2;
4955
- let count3 = units2;
4955
+ let count4 = units2;
4956
4956
  for (let i = 0; i < units2 - 1; i++) {
4957
4957
  if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
4958
- count3--;
4958
+ count4--;
4959
4959
  i++;
4960
4960
  }
4961
4961
  }
4962
- return count3;
4962
+ return count4;
4963
4963
  }
4964
4964
  function getLengthableOrigin(input2) {
4965
4965
  if (Array.isArray(input2))
@@ -5351,16 +5351,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
5351
5351
  }
5352
5352
  function formatError(error62, mapper = (issue2) => issue2.message) {
5353
5353
  const fieldErrors = { _errors: [] };
5354
- const processError = (error63, path31 = []) => {
5354
+ const processError = (error63, path32 = []) => {
5355
5355
  for (const issue2 of error63.issues) {
5356
5356
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5357
- issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
5357
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
5358
5358
  } else if (issue2.code === "invalid_key") {
5359
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5359
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5360
5360
  } else if (issue2.code === "invalid_element") {
5361
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5361
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5362
5362
  } else {
5363
- const fullpath = [...path31, ...issue2.path];
5363
+ const fullpath = [...path32, ...issue2.path];
5364
5364
  if (fullpath.length === 0) {
5365
5365
  fieldErrors._errors.push(mapper(issue2));
5366
5366
  } else {
@@ -5399,17 +5399,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
5399
5399
  }
5400
5400
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
5401
5401
  const result2 = { errors: [] };
5402
- const processError = (error63, path31 = []) => {
5402
+ const processError = (error63, path32 = []) => {
5403
5403
  var _a3;
5404
5404
  for (const issue2 of error63.issues) {
5405
5405
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5406
- issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
5406
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
5407
5407
  } else if (issue2.code === "invalid_key") {
5408
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5408
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5409
5409
  } else if (issue2.code === "invalid_element") {
5410
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
5410
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
5411
5411
  } else {
5412
- const fullpath = [...path31, ...issue2.path];
5412
+ const fullpath = [...path32, ...issue2.path];
5413
5413
  if (fullpath.length === 0) {
5414
5414
  result2.errors.push(mapper(issue2));
5415
5415
  continue;
@@ -5448,8 +5448,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
5448
5448
  }
5449
5449
  function toDotPath(_path) {
5450
5450
  const segs = [];
5451
- const path31 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5452
- for (const seg of path31) {
5451
+ const path32 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5452
+ for (const seg of path32) {
5453
5453
  if (typeof seg === "number")
5454
5454
  segs.push(`[${seg}]`);
5455
5455
  else if (typeof seg === "symbol")
@@ -8564,9 +8564,9 @@ function partPattern(schema) {
8564
8564
  return own2;
8565
8565
  }
8566
8566
  if (def.options) {
8567
- const sources = def.options.map(partPattern);
8568
- if (sources.every(Boolean))
8569
- return `^(${sources.map((s) => cleanRegex(s)).join("|")})$`;
8567
+ const sources2 = def.options.map(partPattern);
8568
+ if (sources2.every(Boolean))
8569
+ return `^(${sources2.map((s) => cleanRegex(s)).join("|")})$`;
8570
8570
  }
8571
8571
  return leafPattern(schema);
8572
8572
  }
@@ -9314,8 +9314,8 @@ function az_default() {
9314
9314
  }
9315
9315
 
9316
9316
  // ../../node_modules/zod/v4/locales/be.js
9317
- function getBelarusianPlural(count3, one, few, many) {
9318
- const absCount = Math.abs(count3);
9317
+ function getBelarusianPlural(count4, one, few, many) {
9318
+ const absCount = Math.abs(count4);
9319
9319
  const lastDigit = absCount % 10;
9320
9320
  const lastTwoDigits = absCount % 100;
9321
9321
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -11962,8 +11962,8 @@ function hu_default() {
11962
11962
  }
11963
11963
 
11964
11964
  // ../../node_modules/zod/v4/locales/hy.js
11965
- function getArmenianPlural(count3, one, many) {
11966
- return Math.abs(count3) === 1 ? one : many;
11965
+ function getArmenianPlural(count4, one, many) {
11966
+ return Math.abs(count4) === 1 ? one : many;
11967
11967
  }
11968
11968
  function withDefiniteArticle(word) {
11969
11969
  if (!word)
@@ -14701,8 +14701,8 @@ function ro_default() {
14701
14701
  }
14702
14702
 
14703
14703
  // ../../node_modules/zod/v4/locales/ru.js
14704
- function getRussianPlural(count3, one, few, many) {
14705
- const absCount = Math.abs(count3);
14704
+ function getRussianPlural(count4, one, few, many) {
14705
+ const absCount = Math.abs(count4);
14706
14706
  const lastDigit = absCount % 10;
14707
14707
  const lastTwoDigits = absCount % 100;
14708
14708
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -19301,8 +19301,8 @@ function _stringFormat(Class2, format, fnOrRegex, _params = {}) {
19301
19301
  }
19302
19302
 
19303
19303
  // ../../node_modules/zod/v4/core/to-json-schema.js
19304
- function assignProps(target, ...sources) {
19305
- for (const source of sources) {
19304
+ function assignProps(target, ...sources2) {
19305
+ for (const source of sources2) {
19306
19306
  for (const key of Reflect.ownKeys(source)) {
19307
19307
  if (Object.prototype.propertyIsEnumerable.call(source, key)) {
19308
19308
  assignProp(target, key, source[key]);
@@ -22551,13 +22551,13 @@ function resolveRef(ref, ctx) {
22551
22551
  if (!ref.startsWith("#")) {
22552
22552
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
22553
22553
  }
22554
- const path31 = ref.slice(1).split("/").filter(Boolean);
22555
- if (path31.length === 0) {
22554
+ const path32 = ref.slice(1).split("/").filter(Boolean);
22555
+ if (path32.length === 0) {
22556
22556
  return ctx.rootSchema;
22557
22557
  }
22558
22558
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
22559
- if (path31[0] === defsKey) {
22560
- const key = path31[1] === void 0 ? void 0 : decodeJSONPointerSegment(path31[1]);
22559
+ if (path32[0] === defsKey) {
22560
+ const key = path32[1] === void 0 ? void 0 : decodeJSONPointerSegment(path32[1]);
22561
22561
  if (!key || !ctx.defs[key]) {
22562
22562
  throw new Error(`Reference not found: ${ref}`);
22563
22563
  }
@@ -24593,7 +24593,7 @@ var RelayBridge = class _RelayBridge {
24593
24593
  const upstream = netConnect({ host, port });
24594
24594
  this.tunnels.add(socket);
24595
24595
  this.tunnels.add(upstream);
24596
- let open14 = false;
24596
+ let open15 = false;
24597
24597
  const cleanup = () => {
24598
24598
  this.tunnels.delete(socket);
24599
24599
  this.tunnels.delete(upstream);
@@ -24601,13 +24601,13 @@ var RelayBridge = class _RelayBridge {
24601
24601
  upstream.destroy();
24602
24602
  };
24603
24603
  const timer = setTimeout(() => {
24604
- if (!open14) {
24604
+ if (!open15) {
24605
24605
  refuse("504 Gateway Timeout");
24606
24606
  cleanup();
24607
24607
  }
24608
24608
  }, CONNECT_TIMEOUT_MS);
24609
24609
  upstream.once("connect", () => {
24610
- open14 = true;
24610
+ open15 = true;
24611
24611
  clearTimeout(timer);
24612
24612
  socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
24613
24613
  if (head.length) upstream.write(head);
@@ -24616,7 +24616,7 @@ var RelayBridge = class _RelayBridge {
24616
24616
  });
24617
24617
  upstream.on("error", () => {
24618
24618
  clearTimeout(timer);
24619
- if (!open14) refuse("502 Bad Gateway");
24619
+ if (!open15) refuse("502 Bad Gateway");
24620
24620
  cleanup();
24621
24621
  });
24622
24622
  socket.on("error", cleanup);
@@ -24637,7 +24637,7 @@ var RelayBridge = class _RelayBridge {
24637
24637
  const remote = (0, import_stream.default)(ws, { allowHalfOpen: false });
24638
24638
  this.tunnels.add(socket);
24639
24639
  this.tunnels.add(remote);
24640
- let reply = Buffer.alloc(0), open14 = false;
24640
+ let reply = Buffer.alloc(0), open15 = false;
24641
24641
  const cleanup = () => {
24642
24642
  this.tunnels.delete(socket);
24643
24643
  this.tunnels.delete(remote);
@@ -24645,7 +24645,7 @@ var RelayBridge = class _RelayBridge {
24645
24645
  remote.destroy();
24646
24646
  };
24647
24647
  const timer = setTimeout(() => {
24648
- if (!open14) {
24648
+ if (!open15) {
24649
24649
  refuse("504 Gateway Timeout");
24650
24650
  cleanup();
24651
24651
  }
@@ -24667,7 +24667,7 @@ var RelayBridge = class _RelayBridge {
24667
24667
  cleanup();
24668
24668
  return;
24669
24669
  }
24670
- open14 = true;
24670
+ open15 = true;
24671
24671
  socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
24672
24672
  const rest = reply.subarray(end + 4);
24673
24673
  if (rest.length) socket.write(rest);
@@ -24684,7 +24684,7 @@ Proxy-Authorization: Basic ${Buffer.from("lc:" + route.token).toString("base64")
24684
24684
  remote.on("data", onReply);
24685
24685
  });
24686
24686
  remote.on("error", () => {
24687
- if (!open14) refuse("502 Bad Gateway");
24687
+ if (!open15) refuse("502 Bad Gateway");
24688
24688
  cleanup();
24689
24689
  });
24690
24690
  socket.on("error", cleanup);
@@ -25050,19 +25050,19 @@ import path2 from "node:path";
25050
25050
  import { spawn, spawnSync } from "node:child_process";
25051
25051
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
25052
25052
  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();
25053
- function networkPath(stateDirectory, name2) {
25054
- return path2.join(path2.dirname(stateDirectory), "Network", name2);
25053
+ function networkPath(stateDirectory2, name2) {
25054
+ return path2.join(path2.dirname(stateDirectory2), "Network", name2);
25055
25055
  }
25056
- async function networkDirectory(stateDirectory) {
25057
- const directory = path2.dirname(networkPath(stateDirectory, "x"));
25056
+ async function networkDirectory(stateDirectory2) {
25057
+ const directory = path2.dirname(networkPath(stateDirectory2, "x"));
25058
25058
  await fs.mkdir(directory, { recursive: true, mode: 448 });
25059
25059
  const stat2 = await fs.lstat(directory);
25060
25060
  if (!stat2.isDirectory() || stat2.isSymbolicLink()) throw Error("NETWORK_DIRECTORY_INVALID");
25061
25061
  return directory;
25062
25062
  }
25063
- async function networkPrepared(stateDirectory, identity) {
25063
+ async function networkPrepared(stateDirectory2, identity) {
25064
25064
  try {
25065
- const file3 = networkPath(stateDirectory, "network-prepared.json"), stat2 = await fs.lstat(file3);
25065
+ const file3 = networkPath(stateDirectory2, "network-prepared.json"), stat2 = await fs.lstat(file3);
25066
25066
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > 1024) return false;
25067
25067
  const receipt = Receipt.parse(JSON.parse(await fs.readFile(file3, "utf8"))), e = identity.enrollment;
25068
25068
  return !!e && receipt.deviceId === e.deviceId && receipt.tenantId === e.tenantId && receipt.accountId === e.accountId;
@@ -25100,9 +25100,9 @@ async function payload(binaryDirectory) {
25100
25100
  throw error62;
25101
25101
  }
25102
25102
  }
25103
- async function installedNetworkHelper(stateDirectory) {
25103
+ async function installedNetworkHelper(stateDirectory2) {
25104
25104
  try {
25105
- const receipt = Receipt.parse(JSON.parse(await fs.readFile(networkPath(stateDirectory, "network-prepared.json"), "utf8")));
25105
+ const receipt = Receipt.parse(JSON.parse(await fs.readFile(networkPath(stateDirectory2, "network-prepared.json"), "utf8")));
25106
25106
  const programFiles = process.env.ProgramW6432 ?? process.env.ProgramFiles ?? "C:\\Program Files";
25107
25107
  const helper = path2.join(programFiles, "LocalCommander", "Network", receipt.bundleId, "NetworkService.exe"), stat2 = await fs.lstat(helper);
25108
25108
  if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.size > 4 * 1024 * 1024 || (await fs.realpath(helper)).toLowerCase() !== path2.resolve(helper).toLowerCase()) return null;
@@ -25131,13 +25131,13 @@ async function elevated(helper, command, requestPath, directory) {
25131
25131
  await fs.rm(scriptPath, { force: true });
25132
25132
  }
25133
25133
  }
25134
- async function setupNetwork(binaryDirectory, stateDirectory, identity) {
25134
+ async function setupNetwork(binaryDirectory, stateDirectory2, identity) {
25135
25135
  const bundle = await payload(binaryDirectory);
25136
25136
  if (!bundle) return "not_packaged";
25137
25137
  const e = identity.enrollment;
25138
25138
  if (!e?.accountId) throw Error("NETWORK_ACCOUNT_BINDING_REQUIRED");
25139
25139
  const request = { ownerSid: windowsSid(), tenantId: e.tenantId, accountId: e.accountId, deviceId: e.deviceId, keyFingerprint: identity.fingerprint };
25140
- const directory = await networkDirectory(stateDirectory);
25140
+ const directory = await networkDirectory(stateDirectory2);
25141
25141
  const requestPath = path2.join(directory, "network-setup-" + randomUUID2() + ".json");
25142
25142
  await fs.writeFile(requestPath, JSON.stringify(request), { flag: "wx", mode: 384 });
25143
25143
  try {
@@ -25156,14 +25156,14 @@ async function setupNetwork(binaryDirectory, stateDirectory, identity) {
25156
25156
  await fs.rm(requestPath, { force: true });
25157
25157
  }
25158
25158
  }
25159
- async function removeNetwork(binaryDirectory, stateDirectory, identity) {
25159
+ async function removeNetwork(binaryDirectory, stateDirectory2, identity) {
25160
25160
  const e = identity.enrollment;
25161
- if (!e || !await networkPrepared(stateDirectory, identity)) return;
25161
+ if (!e || !await networkPrepared(stateDirectory2, identity)) return;
25162
25162
  await localNetworkControl(e.deviceId, "off");
25163
- const helper = (await payload(binaryDirectory))?.helper ?? await installedNetworkHelper(stateDirectory);
25163
+ const helper = (await payload(binaryDirectory))?.helper ?? await installedNetworkHelper(stateDirectory2);
25164
25164
  if (!helper) throw Error("NETWORK_REMOVAL_PACKAGE_REQUIRED");
25165
- await elevated(helper, "uninstall", void 0, await networkDirectory(stateDirectory));
25166
- await fs.rm(networkPath(stateDirectory, "network-prepared.json"), { force: true });
25165
+ await elevated(helper, "uninstall", void 0, await networkDirectory(stateDirectory2));
25166
+ await fs.rm(networkPath(stateDirectory2, "network-prepared.json"), { force: true });
25167
25167
  }
25168
25168
  async function openNetworkPanel(binaryDirectory, identity) {
25169
25169
  const bundle = await payload(binaryDirectory), e = identity.enrollment;
@@ -25177,8 +25177,8 @@ async function openNetworkPanel(binaryDirectory, identity) {
25177
25177
  }
25178
25178
 
25179
25179
  // agent/src/main.ts
25180
- import path30 from "node:path";
25181
- import os8 from "node:os";
25180
+ import path31 from "node:path";
25181
+ import os9 from "node:os";
25182
25182
 
25183
25183
  // agent/src/posix-store.ts
25184
25184
  import { constants } from "node:fs";
@@ -25597,7 +25597,7 @@ async function acquirePosixJournalGuard(directory, helper) {
25597
25597
  }
25598
25598
 
25599
25599
  // agent/src/main.ts
25600
- import { mkdir as mkdir15, open as open13, readFile as readFile13, realpath as realpath10, rm as rm11 } from "node:fs/promises";
25600
+ import { mkdir as mkdir16, open as open14, readFile as readFile14, realpath as realpath10, rm as rm12 } from "node:fs/promises";
25601
25601
  import { fileURLToPath } from "node:url";
25602
25602
 
25603
25603
  // packages/operations/src/crypto.ts
@@ -27153,7 +27153,7 @@ var NativeJournal = class _NativeJournal {
27153
27153
  * still alive; otherwise, including every entry from an older agent, it stays EXECUTION_UNKNOWN (#194). */
27154
27154
  recoverAfterRestart(liveness) {
27155
27155
  return this.enqueue(async () => {
27156
- let count3 = 0;
27156
+ let count4 = 0;
27157
27157
  const interrupted = [...this.entries.values()].filter((e) => ["accepted", "running"].includes(e.state));
27158
27158
  const pids = [...new Set(interrupted.flatMap((e) => e.supervisors ?? []))];
27159
27159
  const linuxSupervisors = interrupted.flatMap((e) => e.linuxSupervisors ?? []), darwinSupervisors = interrupted.flatMap((e) => e.darwinSupervisors ?? []);
@@ -27186,9 +27186,9 @@ var NativeJournal = class _NativeJournal {
27186
27186
  } });
27187
27187
  }
27188
27188
  await this.persist(e);
27189
- count3++;
27189
+ count4++;
27190
27190
  }
27191
- return count3;
27191
+ return count4;
27192
27192
  });
27193
27193
  }
27194
27194
  eligibleForPruning(entry, cutoff) {
@@ -27196,20 +27196,20 @@ var NativeJournal = class _NativeJournal {
27196
27196
  }
27197
27197
  admissionAvailable() {
27198
27198
  if (this.closed || this.lock.guard && !this.lock.guard.active) return false;
27199
- let count3 = this.entries.size, bytes3 = this.totalBytes;
27200
- if (count3 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27199
+ let count4 = this.entries.size, bytes3 = this.totalBytes;
27200
+ if (count4 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27201
27201
  const cutoff = this.now().getTime() - this.options.retentionMs;
27202
27202
  for (const entry of this.entries.values()) {
27203
27203
  if (!this.eligibleForPruning(entry, cutoff)) continue;
27204
- count3--;
27204
+ count4--;
27205
27205
  bytes3 -= this.sizes.get(entry.executionId);
27206
- if (count3 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27206
+ if (count4 < this.options.maxEntries && bytes3 + MAX_ENVELOPE <= this.options.maxBytes) return true;
27207
27207
  }
27208
27208
  return false;
27209
27209
  }
27210
27210
  // Called only inside the serialized queue; enqueueing prune here would deadlock.
27211
27211
  async pruneEligible() {
27212
- let count3 = 0;
27212
+ let count4 = 0;
27213
27213
  const cutoff = this.now().getTime() - this.options.retentionMs;
27214
27214
  for (const e of [...this.entries.values()]) {
27215
27215
  if (!this.eligibleForPruning(e, cutoff)) continue;
@@ -27219,9 +27219,9 @@ var NativeJournal = class _NativeJournal {
27219
27219
  this.entries.delete(e.executionId);
27220
27220
  this.sizes.delete(e.executionId);
27221
27221
  this.digests.delete(e.executionId);
27222
- count3++;
27222
+ count4++;
27223
27223
  }
27224
- return count3;
27224
+ return count4;
27225
27225
  }
27226
27226
  prune() {
27227
27227
  return this.enqueue(() => this.pruneEligible());
@@ -29559,11 +29559,11 @@ async function portalScreenshot(socket, uid, token, signal) {
29559
29559
  signal.addEventListener("abort", abort, { once: true });
29560
29560
  connection.on("error", fail7);
29561
29561
  connection.on("close", () => fail7(Error("CLOSED")));
29562
- const call = (destination, path31, iface, member, signature = "", body = () => {
29562
+ const call = (destination, path32, iface, member, signature = "", body = () => {
29563
29563
  }) => new Promise((done, failed) => {
29564
29564
  const payload2 = new Writer();
29565
29565
  body(payload2);
29566
- const header = new Writer(), fields = [[1, "o", path31], [2, "s", iface], [3, "s", member], [6, "s", destination]];
29566
+ const header = new Writer(), fields = [[1, "o", path32], [2, "s", iface], [3, "s", member], [6, "s", destination]];
29567
29567
  if (signature) fields.push([8, "g", signature]);
29568
29568
  header.byte(108);
29569
29569
  header.byte(1);
@@ -29746,8 +29746,8 @@ function downscale(image, edge) {
29746
29746
  sums[x * 3 + 2] = sums[x * 3 + 2] + image.rgb[i + 2];
29747
29747
  }
29748
29748
  for (let x = 0; x < width; x++) {
29749
- const count3 = (ys[y + 1] - ys[y]) * (xs[x + 1] - xs[x]);
29750
- for (let c = 0; c < 3; c++) rgb[(y * width + x) * 3 + c] = Math.round(sums[x * 3 + c] / count3);
29749
+ const count4 = (ys[y + 1] - ys[y]) * (xs[x + 1] - xs[x]);
29750
+ for (let c = 0; c < 3; c++) rgb[(y * width + x) * 3 + c] = Math.round(sums[x * 3 + c] / count4);
29751
29751
  }
29752
29752
  }
29753
29753
  return { width, height, rgb };
@@ -30223,8 +30223,8 @@ var HUFFMAN = [
30223
30223
  var CODES = HUFFMAN.map(([, counts, values]) => {
30224
30224
  const table2 = [];
30225
30225
  let code = 0, at = 0;
30226
- counts.forEach((count3, index) => {
30227
- for (let i = 0; i < count3; i++) table2[values[at++]] = [code++, index + 1];
30226
+ counts.forEach((count4, index) => {
30227
+ for (let i = 0; i < count4; i++) table2[values[at++]] = [code++, index + 1];
30228
30228
  code <<= 1;
30229
30229
  });
30230
30230
  return table2;
@@ -31094,16 +31094,16 @@ var NativeTools = class {
31094
31094
  if (value) selectedHeaders[name2] = value.slice(0, 2048);
31095
31095
  }
31096
31096
  const reader = response.body?.getReader(), chunks = [];
31097
- let count3 = 0, truncated = false;
31097
+ let count4 = 0, truncated = false;
31098
31098
  try {
31099
31099
  if (reader) for (; ; ) {
31100
31100
  const part = await reader.read();
31101
31101
  if (part.done) break;
31102
31102
  const b = Buffer.from(part.value);
31103
- const take = Math.min(b.length, 1e5 - count3);
31103
+ const take = Math.min(b.length, 1e5 - count4);
31104
31104
  chunks.push(b.subarray(0, take));
31105
- count3 += take;
31106
- if (take !== b.length || count3 >= 1e5) {
31105
+ count4 += take;
31106
+ if (take !== b.length || count4 >= 1e5) {
31107
31107
  truncated = true;
31108
31108
  break;
31109
31109
  }
@@ -31657,11 +31657,11 @@ function parseNodeTapShadow(input2) {
31657
31657
  return passThrough(input2, "unrecognized_record", true, notices);
31658
31658
  }
31659
31659
  if (line === "") continue;
31660
- const count3 = SUMMARY_COUNT.exec(line);
31661
- if (count3) {
31662
- const key = count3[1];
31660
+ const count4 = SUMMARY_COUNT.exec(line);
31661
+ if (count4) {
31662
+ const key = count4[1];
31663
31663
  if (counts.has(key)) return passThrough(input2, "summary_inconsistent", true, notices);
31664
- counts.set(key, Number(count3[2]));
31664
+ counts.set(key, Number(count4[2]));
31665
31665
  continue;
31666
31666
  }
31667
31667
  const summaryDuration = SUMMARY_DURATION.exec(line);
@@ -31775,11 +31775,11 @@ function parseNodeTapFailureShadow(input2) {
31775
31775
  let durationMs = null;
31776
31776
  for (const line of lines.slice(index + 1)) {
31777
31777
  if (!line) continue;
31778
- const count3 = SUMMARY_COUNT.exec(line);
31779
- if (count3) {
31780
- const key = count3[1];
31778
+ const count4 = SUMMARY_COUNT.exec(line);
31779
+ if (count4) {
31780
+ const key = count4[1];
31781
31781
  if (counts.has(key)) return fallback("summary_inconsistent");
31782
- counts.set(key, Number(count3[2]));
31782
+ counts.set(key, Number(count4[2]));
31783
31783
  } else {
31784
31784
  const duration3 = SUMMARY_DURATION.exec(line);
31785
31785
  if (duration3) {
@@ -36588,9 +36588,9 @@ var rev2026Codec = {
36588
36588
  });
36589
36589
  const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3);
36590
36590
  if (!parsed.success) for (const issue2 of parsed.error.issues) {
36591
- const path31 = issue2.path.map(String);
36592
- const key = path31.length > 0 ? path31.join(".") : "_meta";
36593
- if (path31.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
36591
+ const path32 = issue2.path.map(String);
36592
+ const key = path32.length > 0 ? path32.join(".") : "_meta";
36593
+ if (path32.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
36594
36594
  issues.push({
36595
36595
  key,
36596
36596
  problem: issue2.message
@@ -36892,29 +36892,29 @@ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
36892
36892
  function scanXMcpHeaderDeclarations(inputSchema) {
36893
36893
  const declarations = [];
36894
36894
  const seenLower = /* @__PURE__ */ new Map();
36895
- const visit2 = (node2, path31, reachable) => {
36895
+ const visit2 = (node2, path32, reachable) => {
36896
36896
  if (node2 === null || typeof node2 !== "object") return void 0;
36897
36897
  const schema = node2;
36898
36898
  if (X_MCP_HEADER_KEY in schema) {
36899
- 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)`;
36899
+ 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)`;
36900
36900
  const raw = schema[X_MCP_HEADER_KEY];
36901
- if (typeof raw !== "string" || raw.length === 0) return `${pathName(path31)}: x-mcp-header MUST be a non-empty string`;
36902
- 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)`;
36901
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path32)}: x-mcp-header MUST be a non-empty string`;
36902
+ 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)`;
36903
36903
  const type = typeof schema.type === "string" ? schema.type : void 0;
36904
- 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>"}`;
36904
+ 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>"}`;
36905
36905
  const lower = raw.toLowerCase();
36906
36906
  const prior = seenLower.get(lower);
36907
36907
  if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
36908
36908
  seenLower.set(lower, raw);
36909
36909
  declarations.push({
36910
- path: path31,
36910
+ path: path32,
36911
36911
  headerName: raw,
36912
36912
  type
36913
36913
  });
36914
36914
  }
36915
36915
  const properties = schema.properties;
36916
36916
  if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
36917
- const fault$1 = visit2(child, [...path31, key], reachable);
36917
+ const fault$1 = visit2(child, [...path32, key], reachable);
36918
36918
  if (fault$1 !== void 0) return fault$1;
36919
36919
  }
36920
36920
  for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
@@ -36922,7 +36922,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
36922
36922
  if (sub === void 0) continue;
36923
36923
  const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
36924
36924
  for (const branch of branches) {
36925
- const fault$1 = visit2(branch, [...path31, `<${k}>`], false);
36925
+ const fault$1 = visit2(branch, [...path32, `<${k}>`], false);
36926
36926
  if (fault$1 !== void 0) return fault$1;
36927
36927
  }
36928
36928
  }
@@ -36962,8 +36962,8 @@ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
36962
36962
  "$defs",
36963
36963
  "definitions"
36964
36964
  ]);
36965
- function pathName(path31) {
36966
- return path31.length === 0 ? "<root>" : path31.join(".");
36965
+ function pathName(path32) {
36966
+ return path32.length === 0 ? "<root>" : path32.join(".");
36967
36967
  }
36968
36968
  var HEADER_MISMATCH_ERROR_CODE = -32020;
36969
36969
  var INBOUND_VALIDATION_LADDER = [
@@ -37213,7 +37213,7 @@ var PROPERTY_KEYS_BY_TYPE = {
37213
37213
  array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])
37214
37214
  };
37215
37215
  var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options);
37216
- function walkProperty(node2, path31, vendor, unsupported) {
37216
+ function walkProperty(node2, path32, vendor, unsupported) {
37217
37217
  if (!isJsonObject(node2)) return node2;
37218
37218
  const allowedKeys = typeof node2.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node2.type) ? PROPERTY_KEYS_BY_TYPE[node2.type] : void 0;
37219
37219
  if (allowedKeys === void 0) return node2;
@@ -37221,8 +37221,8 @@ function walkProperty(node2, path31, vendor, unsupported) {
37221
37221
  for (const [key, value] of Object.entries(node2)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value;
37222
37222
  else if (key === "pattern" && node2.type === "string" && typeof node2.format === "string") {
37223
37223
  if (!SUPPORTED_STRING_FORMATS.has(node2.format)) pruned[key] = value;
37224
- else if (typeof value !== "string" || !isLibraryFormatPattern(node2.format, value, vendor)) unsupported.push(`${path31}.${key}`);
37225
- } else unsupported.push(`${path31}.${key}`);
37224
+ else if (typeof value !== "string" || !isLibraryFormatPattern(node2.format, value, vendor)) unsupported.push(`${path32}.${key}`);
37225
+ } else unsupported.push(`${path32}.${key}`);
37226
37226
  return pruned;
37227
37227
  }
37228
37228
  function walkRequestedSchema(converted, vendor) {
@@ -37239,11 +37239,11 @@ function describeUnsupportedProperties(pruned, fallback) {
37239
37239
  const offenders = Object.entries(pruned.properties).filter(([, node2]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node2).success).map(([name2]) => `properties.${name2}`);
37240
37240
  return offenders.length > 0 ? offenders.join(", ") : fallback;
37241
37241
  }
37242
- function findDroppedConstraintPaths(original, parsed, path31 = "") {
37243
- if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path31}[${index}]`));
37242
+ function findDroppedConstraintPaths(original, parsed, path32 = "") {
37243
+ if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path32}[${index}]`));
37244
37244
  if (!isJsonObject(original) || !isJsonObject(parsed)) return [];
37245
37245
  return Object.entries(original).flatMap(([key, value]) => {
37246
- const childPath = path31 ? `${path31}.${key}` : key;
37246
+ const childPath = path32 ? `${path32}.${key}` : key;
37247
37247
  if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];
37248
37248
  return findDroppedConstraintPaths(value, parsed[key], childPath);
37249
37249
  });
@@ -40473,15 +40473,15 @@ var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => {
40473
40473
  return false;
40474
40474
  }
40475
40475
  function countKeys(schema) {
40476
- let count3 = 0;
40476
+ let count4 = 0;
40477
40477
  for (const key in schema) {
40478
40478
  if (key === "$ref") return Infinity;
40479
- count3++;
40479
+ count4++;
40480
40480
  if (SIMPLE_INLINED.has(key)) continue;
40481
- if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count3 += countKeys(sch));
40482
- if (count3 === Infinity) return Infinity;
40481
+ if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count4 += countKeys(sch));
40482
+ if (count4 === Infinity) return Infinity;
40483
40483
  }
40484
- return count3;
40484
+ return count4;
40485
40485
  }
40486
40486
  function getFullPath(resolver, id2 = "", normalize) {
40487
40487
  if (normalize !== false) id2 = normalizeId(id2);
@@ -41319,8 +41319,8 @@ var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => {
41319
41319
  for (let i = 0; i < str.length; i++) if (str[i] === token) ind++;
41320
41320
  return ind;
41321
41321
  }
41322
- function removeDotSegments(path31) {
41323
- let input2 = path31;
41322
+ function removeDotSegments(path32) {
41323
+ let input2 = path32;
41324
41324
  const output2 = [];
41325
41325
  let nextSlash = -1;
41326
41326
  let len = 0;
@@ -41473,8 +41473,8 @@ var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
41473
41473
  wsComponent.secure = void 0;
41474
41474
  }
41475
41475
  if (wsComponent.resourceName) {
41476
- const [path31, query] = wsComponent.resourceName.split("?");
41477
- wsComponent.path = path31 && path31 !== "/" ? path31 : void 0;
41476
+ const [path32, query] = wsComponent.resourceName.split("?");
41477
+ wsComponent.path = path32 && path32 !== "/" ? path32 : void 0;
41478
41478
  wsComponent.query = query;
41479
41479
  wsComponent.resourceName = void 0;
41480
41480
  }
@@ -43081,8 +43081,8 @@ var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => {
43081
43081
  cxt.result(valid, () => cxt.reset());
43082
43082
  function validateItemsWithCount() {
43083
43083
  const schValid = gen.name("_valid");
43084
- const count3 = gen.let("count", 0);
43085
- validateItems(schValid, () => gen.if(schValid, () => checkLimits(count3)));
43084
+ const count4 = gen.let("count", 0);
43085
+ validateItems(schValid, () => gen.if(schValid, () => checkLimits(count4)));
43086
43086
  }
43087
43087
  function validateItems(_valid, block) {
43088
43088
  gen.forRange("i", 0, len, (i) => {
@@ -43095,13 +43095,13 @@ var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => {
43095
43095
  block();
43096
43096
  });
43097
43097
  }
43098
- function checkLimits(count3) {
43099
- gen.code((0, codegen_1._)`${count3}++`);
43100
- if (max === void 0) gen.if((0, codegen_1._)`${count3} >= ${min}`, () => gen.assign(valid, true).break());
43098
+ function checkLimits(count4) {
43099
+ gen.code((0, codegen_1._)`${count4}++`);
43100
+ if (max === void 0) gen.if((0, codegen_1._)`${count4} >= ${min}`, () => gen.assign(valid, true).break());
43101
43101
  else {
43102
- gen.if((0, codegen_1._)`${count3} > ${max}`, () => gen.assign(valid, false).break());
43102
+ gen.if((0, codegen_1._)`${count4} > ${max}`, () => gen.assign(valid, false).break());
43103
43103
  if (min === 1) gen.assign(valid, true);
43104
- else gen.if((0, codegen_1._)`${count3} >= ${min}`, () => gen.assign(valid, true));
43104
+ else gen.if((0, codegen_1._)`${count4} >= ${min}`, () => gen.assign(valid, true));
43105
43105
  }
43106
43106
  }
43107
43107
  }
@@ -47276,6 +47276,42 @@ var NativeIncidentProducer = class {
47276
47276
  }
47277
47277
  };
47278
47278
 
47279
+ // packages/contracts/src/token-usage-protocol.ts
47280
+ var TOKEN_USAGE_CAPABILITY = "tokenUsageV1";
47281
+ var uuid20 = external_exports.string().uuid().toLowerCase();
47282
+ var epoch3 = external_exports.string().refine((v) => /^[1-9]\d{0,18}$/.test(v) && BigInt(v) <= 9223372036854775807n);
47283
+ var tokens = external_exports.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
47284
+ var TokenUsageClientSchema = external_exports.enum(["claude-code", "codex"]);
47285
+ var TOKEN_USAGE_MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,79}$/;
47286
+ var TokenUsageRowSchema = external_exports.object({
47287
+ day: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((v) => Number.isFinite(Date.parse(v + "T00:00:00Z"))),
47288
+ client: TokenUsageClientSchema,
47289
+ model: external_exports.string().regex(TOKEN_USAGE_MODEL),
47290
+ requests: tokens,
47291
+ inputTokens: tokens,
47292
+ cachedInputTokens: tokens,
47293
+ cacheWriteTokens: tokens,
47294
+ outputTokens: tokens,
47295
+ reasoningTokens: tokens.nullable()
47296
+ }).strict().refine((row) => row.cachedInputTokens + row.cacheWriteTokens <= row.inputTokens && (row.reasoningTokens === null || row.reasoningTokens <= row.outputTokens), "Subset exceeds total");
47297
+ var TokenUsageBatchSchema = external_exports.object({
47298
+ type: external_exports.literal("tokenUsageBatch"),
47299
+ protocolVersion: external_exports.literal(1),
47300
+ batchId: uuid20,
47301
+ connectionEpoch: epoch3,
47302
+ /** Random per agent state; a new state counts only usage after it started, so states never overlap. */
47303
+ stateId: uuid20,
47304
+ rows: external_exports.array(TokenUsageRowSchema).min(1).max(64)
47305
+ }).strict().refine((batch) => new Set(batch.rows.map((r) => `${r.day}|${r.client}|${r.model}`)).size === batch.rows.length, "Duplicate rows");
47306
+ var TokenUsageBatchResultSchema = external_exports.enum(["accepted", "invalid", "stale", "disabled", "retry", "busy"]);
47307
+ var TokenUsageBatchAckSchema = external_exports.object({
47308
+ type: external_exports.literal("tokenUsageBatchAck"),
47309
+ protocolVersion: external_exports.literal(1),
47310
+ batchId: uuid20.optional(),
47311
+ result: TokenUsageBatchResultSchema
47312
+ }).strict();
47313
+ var TokenUsageStateSchema = external_exports.object({ type: external_exports.literal("tokenUsageState"), protocolVersion: external_exports.literal(1), connectionEpoch: epoch3, enabled: external_exports.boolean() }).strict();
47314
+
47279
47315
  // agent/src/relay-client.ts
47280
47316
  var RelayClientError = class extends Error {
47281
47317
  constructor(code) {
@@ -47311,7 +47347,7 @@ function relayUrlFromEnrollment(enrollment) {
47311
47347
  url2.pathname = "/api/agent/relay";
47312
47348
  return url2.toString();
47313
47349
  }
47314
- function uuid20(value, code) {
47350
+ function uuid21(value, code) {
47315
47351
  if (typeof value !== "string" || !UUID2.test(value)) fail5(code);
47316
47352
  return value.toLowerCase();
47317
47353
  }
@@ -47319,7 +47355,7 @@ function protocol(value, expected) {
47319
47355
  if (value !== expected) fail5("RELAY_PROTOCOL_INVALID");
47320
47356
  return expected;
47321
47357
  }
47322
- function epoch3(value) {
47358
+ function epoch4(value) {
47323
47359
  if (typeof value !== "string" || !EPOCH.test(value) || BigInt(value) > 9223372036854775807n) fail5("RELAY_EPOCH_INVALID");
47324
47360
  return value;
47325
47361
  }
@@ -47441,11 +47477,11 @@ function sendJson(socket, value, maxBytes) {
47441
47477
  function validateChallenge(frame, expectedProtocol) {
47442
47478
  if (frame.type !== "challenge") fail5("RELAY_HANDSHAKE_INVALID");
47443
47479
  protocol(frame.protocolVersion, expectedProtocol);
47444
- uuid20(frame.gatewayId, "RELAY_HANDSHAKE_INVALID");
47480
+ uuid21(frame.gatewayId, "RELAY_HANDSHAKE_INVALID");
47445
47481
  if (typeof frame.nonce !== "string" || frame.nonce.length < 32 || frame.nonce.length > 512 || /[\u0000-\u001f\u007f]/u.test(frame.nonce)) fail5("RELAY_HANDSHAKE_INVALID");
47446
47482
  if (typeof frame.expiresAt !== "string" || !Number.isFinite(Date.parse(frame.expiresAt)) || Date.parse(frame.expiresAt) <= Date.now()) fail5("RELAY_HANDSHAKE_INVALID");
47447
47483
  return {
47448
- challengeId: uuid20(frame.challengeId, "RELAY_HANDSHAKE_INVALID"),
47484
+ challengeId: uuid21(frame.challengeId, "RELAY_HANDSHAKE_INVALID"),
47449
47485
  nonce: frame.nonce,
47450
47486
  // Older servers offer no capabilities and verify only the v1 proof.
47451
47487
  machineIdentity: Array.isArray(frame.capabilities) && frame.capabilities.includes(MACHINE_IDENTITY_CAPABILITY)
@@ -47454,27 +47490,27 @@ function validateChallenge(frame, expectedProtocol) {
47454
47490
  function validateReady(frame, enrollment, expectedProtocol) {
47455
47491
  if (frame.type !== "connected") fail5("RELAY_HANDSHAKE_INVALID");
47456
47492
  protocol(frame.protocolVersion, expectedProtocol);
47457
- if (uuid20(frame.tenantId, "RELAY_HANDSHAKE_INVALID") !== enrollment.tenantId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47458
- if (uuid20(frame.deviceId, "RELAY_HANDSHAKE_INVALID") !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47493
+ if (uuid21(frame.tenantId, "RELAY_HANDSHAKE_INVALID") !== enrollment.tenantId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47494
+ if (uuid21(frame.deviceId, "RELAY_HANDSHAKE_INVALID") !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47459
47495
  const terminalMetrics2 = Array.isArray(frame.capabilities) && frame.capabilities.includes(TERMINAL_METRICS_CAPABILITY);
47460
- return { connectionEpoch: epoch3(frame.connectionEpoch), terminalMetrics: terminalMetrics2 };
47496
+ return { connectionEpoch: epoch4(frame.connectionEpoch), terminalMetrics: terminalMetrics2 };
47461
47497
  }
47462
47498
  function validateRequest(frame, enrollment, expectedProtocol, connectionEpoch) {
47463
47499
  if (frame.type !== "relayFrame") fail5("RELAY_REQUEST_INVALID");
47464
47500
  protocol(frame.protocolVersion, expectedProtocol);
47465
- const tenantId = uuid20(frame.tenantId, "RELAY_REQUEST_INVALID");
47466
- const deviceId = uuid20(frame.deviceId, "RELAY_REQUEST_INVALID");
47501
+ const tenantId = uuid21(frame.tenantId, "RELAY_REQUEST_INVALID");
47502
+ const deviceId = uuid21(frame.deviceId, "RELAY_REQUEST_INVALID");
47467
47503
  if (tenantId !== enrollment.tenantId.toLowerCase() || deviceId !== enrollment.deviceId.toLowerCase()) fail5("RELAY_ID_MISMATCH");
47468
- if (epoch3(frame.connectionEpoch) !== connectionEpoch) fail5("RELAY_EPOCH_MISMATCH");
47504
+ if (epoch4(frame.connectionEpoch) !== connectionEpoch) fail5("RELAY_EPOCH_MISMATCH");
47469
47505
  const kind = frame.kind;
47470
47506
  if (typeof kind !== "string" || !REQUEST_KINDS.has(kind)) fail5("RELAY_REQUEST_INVALID");
47471
47507
  return {
47472
- requestId: uuid20(frame.requestId, "RELAY_REQUEST_INVALID"),
47508
+ requestId: uuid21(frame.requestId, "RELAY_REQUEST_INVALID"),
47473
47509
  tenantId,
47474
47510
  deviceId,
47475
47511
  connectionEpoch,
47476
- operationId: uuid20(frame.operationId, "RELAY_REQUEST_INVALID"),
47477
- executionId: uuid20(frame.executionId, "RELAY_REQUEST_INVALID"),
47512
+ operationId: uuid21(frame.operationId, "RELAY_REQUEST_INVALID"),
47513
+ executionId: uuid21(frame.executionId, "RELAY_REQUEST_INVALID"),
47478
47514
  kind,
47479
47515
  payload: frame.payload,
47480
47516
  deadlineAt: isoDate(frame.deadlineAt),
@@ -47516,8 +47552,8 @@ async function connectOnce(options) {
47516
47552
  const identity = await options.store.load();
47517
47553
  if (!identity || !identity.enrollment) fail5("ENROLLMENT_MISSING");
47518
47554
  const enrollment = identity.enrollment;
47519
- const tenantId = uuid20(enrollment.tenantId, "ENROLLMENT_INVALID");
47520
- const deviceId = uuid20(enrollment.deviceId, "ENROLLMENT_INVALID");
47555
+ const tenantId = uuid21(enrollment.tenantId, "ENROLLMENT_INVALID");
47556
+ const deviceId = uuid21(enrollment.deviceId, "ENROLLMENT_INVALID");
47521
47557
  const url2 = relayUrlFromEnrollment(enrollment);
47522
47558
  const socket = new wrapper_default(url2, [], {
47523
47559
  followRedirects: false,
@@ -47536,7 +47572,8 @@ async function connectOnce(options) {
47536
47572
  guardIdentity: true,
47537
47573
  ...options.aiConnectivity ? { aiConnectivity: true } : {},
47538
47574
  ...options.onHeldLeases ? { heldLeases: true } : {},
47539
- ...options.onFullLogChoice ? { fullLogNotice: true } : {}
47575
+ ...options.onFullLogChoice ? { fullLogNotice: true } : {},
47576
+ ...options.onTokenUsageState ? { tokenUsage: true } : {}
47540
47577
  }, maxFrameBytes);
47541
47578
  const challenge = validateChallenge(await waitForMessage(socket, maxFrameBytes, connectTimeoutMs, "RELAY_HANDSHAKE_TIMEOUT"), protocolVersion2);
47542
47579
  const machine = challenge.machineIdentity ? options.machineIdentity?.(deviceId) ?? null : null;
@@ -47563,6 +47600,7 @@ async function connectOnce(options) {
47563
47600
  const { connectionEpoch, terminalMetrics: terminalMetrics2 } = validateReady(readyFrame, enrollment, protocolVersion2);
47564
47601
  const rejectionResults = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(REJECTION_RESULT_CAPABILITY);
47565
47602
  const incidents = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes("incidentBatchV1");
47603
+ const tokenUsage = !!options.onTokenUsageState && Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(TOKEN_USAGE_CAPABILITY);
47566
47604
  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;
47567
47605
  const nativeStatus = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(NATIVE_STATUS_CAPABILITY) && options.status;
47568
47606
  const accessModes = Array.isArray(readyFrame.capabilities) && readyFrame.capabilities.includes(WORKSPACE_ACCESS_MODE_CAPABILITY);
@@ -47650,6 +47688,26 @@ async function connectOnce(options) {
47650
47688
  }
47651
47689
  return;
47652
47690
  }
47691
+ if (frame.type === "tokenUsageState") {
47692
+ const state = TokenUsageStateSchema.safeParse(frame);
47693
+ if (tokenUsage && state.success && state.data.connectionEpoch === connectionEpoch) {
47694
+ try {
47695
+ options.onTokenUsageState?.(state.data.enabled);
47696
+ } catch {
47697
+ }
47698
+ }
47699
+ return;
47700
+ }
47701
+ if (frame.type === "tokenUsageBatchAck") {
47702
+ const ack = TokenUsageBatchAckSchema.safeParse(frame);
47703
+ if (tokenUsage && ack.success) {
47704
+ try {
47705
+ options.onTokenUsageAck?.(ack.data.batchId, ack.data.result);
47706
+ } catch {
47707
+ }
47708
+ }
47709
+ return;
47710
+ }
47653
47711
  if (frame.type === "aiConnectivityRevoked") {
47654
47712
  if (connectivity && frame.protocolVersion === 1 && frame.connectionEpoch === connectionEpoch) notifyConnectivityRevoked();
47655
47713
  return;
@@ -47780,6 +47838,15 @@ async function connectOnce(options) {
47780
47838
  return false;
47781
47839
  }
47782
47840
  } } : {},
47841
+ ...tokenUsage ? { sendTokenUsageBatch: (batch) => {
47842
+ try {
47843
+ if (socket.readyState !== wrapper_default.OPEN) return false;
47844
+ sendJson(socket, TokenUsageBatchSchema.parse({ type: "tokenUsageBatch", protocolVersion: 1, batchId: batch.batchId, connectionEpoch, stateId: batch.stateId, rows: batch.rows }), Math.min(maxFrameBytes, 32768));
47845
+ return true;
47846
+ } catch {
47847
+ return false;
47848
+ }
47849
+ } } : {},
47783
47850
  sendTerminal: (binding2, state, resultCode, metrics) => {
47784
47851
  if (state === "rejected" && !rejectionResults) return Promise.reject(new RelayClientError("RELAY_RESULT_UNSUPPORTED"));
47785
47852
  if (pendingTerminal.size >= 64) return Promise.reject(new RelayClientError("RELAY_PENDING_LIMIT"));
@@ -47998,10 +48065,10 @@ function canonicalOrigin2(value) {
47998
48065
  fail6("ORIGIN_INVALID");
47999
48066
  }
48000
48067
  }
48001
- function endpoint(origin, path31) {
48002
- return origin + path31;
48068
+ function endpoint(origin, path32) {
48069
+ return origin + path32;
48003
48070
  }
48004
- function uuid21(value, code) {
48071
+ function uuid22(value, code) {
48005
48072
  if (typeof value !== "string" || !UUID3.test(value)) fail6(code);
48006
48073
  return value.toLowerCase();
48007
48074
  }
@@ -48121,7 +48188,7 @@ var PairingClient = class {
48121
48188
  publicKey: identity.publicKeyPem,
48122
48189
  agentVersion: this.version
48123
48190
  }));
48124
- const pairingId = uuid21(response.pairingId, "PAIRING_RESPONSE_INVALID");
48191
+ const pairingId = uuid22(response.pairingId, "PAIRING_RESPONSE_INVALID");
48125
48192
  const expiresAt = parseDate(response.expiresAt, "PAIRING_RESPONSE_INVALID");
48126
48193
  const now = this.nowMs();
48127
48194
  if (expiresAt.getTime() <= now || expiresAt.getTime() - now > 30 * 6e4) fail6("PAIRING_RESPONSE_INVALID");
@@ -48155,7 +48222,7 @@ var PairingClient = class {
48155
48222
  }
48156
48223
  async completeOnce(beginResult, approved, displayNameValue) {
48157
48224
  const pairing = this.validateBeginResult(beginResult);
48158
- const tenantId = uuid21(approved.tenantId, "PAIRING_RESPONSE_INVALID");
48225
+ const tenantId = uuid22(approved.tenantId, "PAIRING_RESPONSE_INVALID");
48159
48226
  const email3 = accountEmail(approved.accountEmail);
48160
48227
  const name2 = displayName(displayNameValue);
48161
48228
  const identity = await this.currentIdentity();
@@ -48169,15 +48236,15 @@ var PairingClient = class {
48169
48236
  displayName: name2,
48170
48237
  agentVersion: this.version
48171
48238
  }));
48172
- const completedTenant = uuid21(response.tenantId, "PAIRING_RESPONSE_INVALID");
48239
+ const completedTenant = uuid22(response.tenantId, "PAIRING_RESPONSE_INVALID");
48173
48240
  if (completedTenant !== tenantId) fail6("PAIRING_RESPONSE_INVALID");
48174
- const deviceId = uuid21(response.deviceId, "PAIRING_RESPONSE_INVALID");
48241
+ const deviceId = uuid22(response.deviceId, "PAIRING_RESPONSE_INVALID");
48175
48242
  const enrollment = {
48176
48243
  tenantId,
48177
48244
  deviceId,
48178
48245
  serverOrigin: this.origin,
48179
48246
  accountEmail: email3,
48180
- ...response.accountId !== void 0 ? { accountId: uuid21(response.accountId, "PAIRING_RESPONSE_INVALID") } : {}
48247
+ ...response.accountId !== void 0 ? { accountId: uuid22(response.accountId, "PAIRING_RESPONSE_INVALID") } : {}
48181
48248
  };
48182
48249
  await this.store.saveEnrollment(enrollment);
48183
48250
  return { ...enrollment };
@@ -48191,7 +48258,7 @@ var PairingClient = class {
48191
48258
  state: response.state,
48192
48259
  expiresAt: parseDate(response.expiresAt, "PAIRING_RESPONSE_INVALID")
48193
48260
  };
48194
- if (response.tenantId !== void 0) result2.tenantId = uuid21(response.tenantId, "PAIRING_RESPONSE_INVALID");
48261
+ if (response.tenantId !== void 0) result2.tenantId = uuid22(response.tenantId, "PAIRING_RESPONSE_INVALID");
48195
48262
  if (response.accountEmail !== void 0) result2.accountEmail = accountEmail(response.accountEmail);
48196
48263
  return result2;
48197
48264
  }
@@ -48203,10 +48270,10 @@ var PairingClient = class {
48203
48270
  }
48204
48271
  validateBeginResult(value) {
48205
48272
  return {
48206
- pairingId: uuid21(value.pairingId, "PAIRING_INVALID"),
48273
+ pairingId: uuid22(value.pairingId, "PAIRING_INVALID"),
48207
48274
  pairingSecret: pairingSecret(value.pairingSecret),
48208
48275
  confirmationCode: confirmationCode(value.confirmationCode),
48209
- approvalUrl: approvalUrl(value.approvalUrl, this.origin, uuid21(value.pairingId, "PAIRING_INVALID")),
48276
+ approvalUrl: approvalUrl(value.approvalUrl, this.origin, uuid22(value.pairingId, "PAIRING_INVALID")),
48210
48277
  expiresAt: value.expiresAt instanceof Date ? new Date(value.expiresAt.getTime()) : parseDate(value.expiresAt, "PAIRING_INVALID"),
48211
48278
  keyFingerprint: fingerprint2(value.keyFingerprint)
48212
48279
  };
@@ -48737,9 +48804,9 @@ function commandSummary2(tool) {
48737
48804
  return { name: name2, command };
48738
48805
  }
48739
48806
  var ProductionMonitor = class {
48740
- constructor(directory, stateDirectory, agentVersion3) {
48807
+ constructor(directory, stateDirectory2, agentVersion3) {
48741
48808
  this.agentVersion = agentVersion3;
48742
- const key = createHash17("sha256").update(path23.resolve(stateDirectory).toLowerCase()).digest("hex");
48809
+ const key = createHash17("sha256").update(path23.resolve(stateDirectory2).toLowerCase()).digest("hex");
48743
48810
  this.file = path23.join(directory, key + ".json");
48744
48811
  this.transportFile = path23.join(directory, key + ".transport");
48745
48812
  }
@@ -49093,6 +49160,342 @@ var FullLogNotice = class {
49093
49160
  }
49094
49161
  };
49095
49162
 
49163
+ // agent/src/token-usage.ts
49164
+ import { randomUUID as randomUUID14 } from "node:crypto";
49165
+ 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";
49166
+ import os8 from "node:os";
49167
+ import path25 from "node:path";
49168
+ var KEEP_DAYS = 35;
49169
+ var MAX_FILES = 1e4;
49170
+ var MAX_SCAN_BYTES = 256 * 1024 * 1024;
49171
+ var CHUNK_BYTES = 4 * 1024 * 1024;
49172
+ var MAX_ROWS = 64;
49173
+ var DAY_MS = 864e5;
49174
+ function tokenUsageRoots(env = process.env) {
49175
+ const home = os8.homedir();
49176
+ const absolute2 = (value, fallback) => value && path25.isAbsolute(value) ? value : fallback;
49177
+ return { claude: absolute2(env.CLAUDE_CONFIG_DIR, path25.join(home, ".claude")), codex: absolute2(env.CODEX_HOME, path25.join(home, ".codex")) };
49178
+ }
49179
+ var stateDirectory = (directory) => path25.join(directory, "optimization");
49180
+ var stateFile = (directory) => path25.join(stateDirectory(directory), "token-usage.json");
49181
+ var utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
49182
+ var count2 = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
49183
+ var modelName = (value) => typeof value === "string" && TOKEN_USAGE_MODEL.test(value) ? value : "unknown";
49184
+ async function sources(roots, since) {
49185
+ const found = [];
49186
+ const entries = async (dir) => {
49187
+ try {
49188
+ return await readdir6(dir, { withFileTypes: true });
49189
+ } catch {
49190
+ return [];
49191
+ }
49192
+ };
49193
+ const add = async (client, file3) => {
49194
+ if (found.length >= MAX_FILES) return;
49195
+ try {
49196
+ const info = await lstat12(file3);
49197
+ if (info.isFile() && info.mtimeMs >= since) found.push({ client, file: file3 });
49198
+ } catch {
49199
+ }
49200
+ };
49201
+ const projects = path25.join(roots.claude, "projects");
49202
+ for (const project of await entries(projects)) {
49203
+ if (!project.isDirectory()) continue;
49204
+ for (const entry of await entries(path25.join(projects, project.name))) {
49205
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) await add("claude-code", path25.join(projects, project.name, entry.name));
49206
+ else if (entry.isDirectory()) {
49207
+ const subagents = path25.join(projects, project.name, entry.name, "subagents");
49208
+ for (const agent of await entries(subagents)) if (agent.isFile() && agent.name.endsWith(".jsonl")) await add("claude-code", path25.join(subagents, agent.name));
49209
+ }
49210
+ }
49211
+ }
49212
+ const sessions = path25.join(roots.codex, "sessions"), first = utcDay(since - DAY_MS);
49213
+ for (const year of await entries(sessions)) {
49214
+ if (!year.isDirectory() || !/^\d{4}$/.test(year.name) || year.name < first.slice(0, 4)) continue;
49215
+ for (const month of await entries(path25.join(sessions, year.name))) {
49216
+ if (!month.isDirectory() || !/^\d{2}$/.test(month.name) || `${year.name}-${month.name}` < first.slice(0, 7)) continue;
49217
+ for (const day of await entries(path25.join(sessions, year.name, month.name))) {
49218
+ if (!day.isDirectory() || !/^\d{2}$/.test(day.name) || `${year.name}-${month.name}-${day.name}` < first) continue;
49219
+ const folder = path25.join(sessions, year.name, month.name, day.name);
49220
+ for (const file3 of await entries(folder)) if (file3.isFile() && file3.name.endsWith(".jsonl")) await add("codex", path25.join(folder, file3.name));
49221
+ }
49222
+ }
49223
+ }
49224
+ return found;
49225
+ }
49226
+ function usageFromLine(client, line, file3) {
49227
+ if (client === "claude-code" ? !line.includes('"usage"') : !line.includes('"token_count"') && !line.includes('"turn_context"')) return null;
49228
+ let value;
49229
+ try {
49230
+ value = JSON.parse(line);
49231
+ } catch {
49232
+ return null;
49233
+ }
49234
+ const at = typeof value?.timestamp === "string" ? Date.parse(value.timestamp) : NaN;
49235
+ if (client === "claude-code") {
49236
+ const message2 = value?.type === "assistant" ? value.message : void 0, usage = message2?.usage;
49237
+ if (!usage || typeof message2.id !== "string" || message2.model === "<synthetic>") return null;
49238
+ if (message2.id === file3.lastMessageId) return null;
49239
+ file3.lastMessageId = message2.id.slice(0, 128);
49240
+ 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);
49241
+ if (input3 === null || cacheWrite2 === null || cached3 === null || output3 === null || !Number.isFinite(at)) return null;
49242
+ return { at, model: modelName(message2.model), input: input3 + cacheWrite2 + cached3, cached: cached3, cacheWrite: cacheWrite2, output: output3, reasoning: null };
49243
+ }
49244
+ if (value?.type === "turn_context") {
49245
+ file3.model = modelName(value.payload?.model);
49246
+ return null;
49247
+ }
49248
+ const info = value?.type === "event_msg" && value.payload?.type === "token_count" ? value.payload.info : void 0;
49249
+ const total = count2(info?.total_token_usage?.total_tokens), last = info?.last_token_usage;
49250
+ if (total === null || !last || total === file3.lastTotal) return null;
49251
+ file3.lastTotal = total;
49252
+ 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);
49253
+ if (input2 === null || cached2 === null || cacheWrite === null || output2 === null || reasoning === null || !Number.isFinite(at)) return null;
49254
+ if (cached2 + cacheWrite > input2 || reasoning > output2) return null;
49255
+ return { at, model: file3.model ?? "unknown", input: input2, cached: cached2, cacheWrite, output: output2, reasoning };
49256
+ }
49257
+ async function readNew(source, file3, size, budget, countFrom, add) {
49258
+ if (size < file3.offset) Object.assign(file3, { offset: 0, lastMessageId: void 0, lastTotal: void 0, skipping: false });
49259
+ let read = 0;
49260
+ const handle = await open10(source.file, "r");
49261
+ try {
49262
+ while (file3.offset < size && read < budget) {
49263
+ const length = Math.min(CHUNK_BYTES, size - file3.offset);
49264
+ const buffer = Buffer.alloc(length);
49265
+ const { bytesRead } = await handle.read(buffer, 0, length, file3.offset);
49266
+ if (bytesRead <= 0) break;
49267
+ read += bytesRead;
49268
+ const end = buffer.lastIndexOf(10, bytesRead - 1);
49269
+ if (end < 0) {
49270
+ if (bytesRead < CHUNK_BYTES) break;
49271
+ file3.offset += bytesRead;
49272
+ file3.skipping = true;
49273
+ continue;
49274
+ }
49275
+ let start = 0;
49276
+ if (file3.skipping) {
49277
+ start = buffer.indexOf(10) + 1;
49278
+ file3.skipping = false;
49279
+ }
49280
+ for (const line of buffer.toString("utf8", start, end).split("\n")) {
49281
+ const usage = usageFromLine(source.client, line, file3);
49282
+ if (usage && usage.at >= countFrom) add(source.client, usage);
49283
+ }
49284
+ file3.offset += end + 1;
49285
+ }
49286
+ } finally {
49287
+ await handle.close();
49288
+ }
49289
+ return read;
49290
+ }
49291
+ var TokenUsageReporter = class {
49292
+ constructor(directory, enrollment, options = {}) {
49293
+ this.directory = directory;
49294
+ this.enrollment = enrollment;
49295
+ this.options = options;
49296
+ }
49297
+ directory;
49298
+ enrollment;
49299
+ options;
49300
+ saved;
49301
+ send;
49302
+ enabled = false;
49303
+ wanted = false;
49304
+ timer;
49305
+ running;
49306
+ inFlight;
49307
+ closed = false;
49308
+ failed = false;
49309
+ /** The state frame can arrive before the connection is handed over, so both feed one decision. */
49310
+ connected(send) {
49311
+ this.send = send;
49312
+ this.apply();
49313
+ }
49314
+ disconnected() {
49315
+ this.send = void 0;
49316
+ this.wanted = false;
49317
+ this.apply();
49318
+ if (this.inFlight) {
49319
+ clearTimeout(this.inFlight.timer);
49320
+ this.inFlight = void 0;
49321
+ }
49322
+ }
49323
+ close() {
49324
+ this.closed = true;
49325
+ this.disconnected();
49326
+ }
49327
+ /** The server's choice for this computer, sent after connect and on every change. */
49328
+ state(enabled) {
49329
+ this.wanted = enabled;
49330
+ this.apply();
49331
+ if (!enabled) void this.exclusive(async () => {
49332
+ const saved2 = await this.load();
49333
+ if (!saved2.paused) {
49334
+ saved2.paused = true;
49335
+ await this.persist();
49336
+ }
49337
+ }).catch(() => {
49338
+ });
49339
+ }
49340
+ apply() {
49341
+ const on = this.wanted && !!this.send && !this.closed;
49342
+ if (on && !this.enabled) {
49343
+ this.enabled = true;
49344
+ this.schedule(this.options.firstDelayMs ?? 6e4);
49345
+ } else if (!on && this.enabled) {
49346
+ this.enabled = false;
49347
+ clearTimeout(this.timer);
49348
+ this.timer = void 0;
49349
+ }
49350
+ }
49351
+ ack(batchId, result2) {
49352
+ const flight = this.inFlight;
49353
+ if (!flight || batchId !== flight.batchId) return;
49354
+ clearTimeout(flight.timer);
49355
+ this.inFlight = void 0;
49356
+ if (result2 === "disabled") {
49357
+ this.state(false);
49358
+ return;
49359
+ }
49360
+ if (result2 !== "accepted" && result2 !== "invalid") return;
49361
+ void this.exclusive(async () => {
49362
+ const saved2 = await this.load();
49363
+ for (const [key, version2] of Object.entries(flight.versions)) if (saved2.dirty[key] === version2) delete saved2.dirty[key];
49364
+ await this.persist();
49365
+ if (result2 === "accepted") this.flush();
49366
+ });
49367
+ }
49368
+ /** One scan and report now; used by the timer and by manual checks. */
49369
+ async scanOnce() {
49370
+ await this.exclusive(async () => {
49371
+ const saved2 = await this.load(), now = this.now();
49372
+ if (saved2.paused) {
49373
+ saved2.countFrom = new Date(now).toISOString();
49374
+ saved2.files = {};
49375
+ saved2.baseline = true;
49376
+ delete saved2.paused;
49377
+ }
49378
+ const countFrom = Date.parse(saved2.countFrom);
49379
+ const since = Math.max(countFrom, now - KEEP_DAYS * DAY_MS);
49380
+ let budget = MAX_SCAN_BYTES;
49381
+ const seen = /* @__PURE__ */ new Set();
49382
+ const baseline = saved2.baseline === true;
49383
+ for (const source of await sources(this.roots(), since - DAY_MS)) {
49384
+ if (budget <= 0) break;
49385
+ seen.add(source.file);
49386
+ let info;
49387
+ try {
49388
+ info = await lstat12(source.file);
49389
+ } catch {
49390
+ continue;
49391
+ }
49392
+ const file3 = saved2.files[source.file] ??= { offset: baseline ? info.size : 0, mtimeMs: 0 };
49393
+ file3.mtimeMs = info.mtimeMs;
49394
+ if (info.size === file3.offset) continue;
49395
+ try {
49396
+ budget -= await readNew(source, file3, info.size, budget, countFrom, (client, usage) => this.add(saved2, client, usage));
49397
+ } catch {
49398
+ }
49399
+ }
49400
+ if (baseline) delete saved2.baseline;
49401
+ for (const [name2, file3] of Object.entries(saved2.files)) if (!seen.has(name2) && file3.mtimeMs < now - KEEP_DAYS * DAY_MS) delete saved2.files[name2];
49402
+ const oldest = utcDay(now - KEEP_DAYS * DAY_MS);
49403
+ for (const key of Object.keys(saved2.totals)) if (key.slice(0, 10) < oldest) {
49404
+ delete saved2.totals[key];
49405
+ delete saved2.dirty[key];
49406
+ }
49407
+ await this.persist();
49408
+ });
49409
+ this.flush();
49410
+ }
49411
+ add(saved2, client, usage) {
49412
+ const key = `${utcDay(usage.at)}|${client}|${usage.model}`;
49413
+ const row = saved2.totals[key] ??= { requests: 0, inputTokens: 0, cachedInputTokens: 0, cacheWriteTokens: 0, outputTokens: 0, reasoningTokens: client === "codex" ? 0 : null };
49414
+ row.requests++;
49415
+ row.inputTokens += usage.input;
49416
+ row.cachedInputTokens += usage.cached;
49417
+ row.cacheWriteTokens += usage.cacheWrite;
49418
+ row.outputTokens += usage.output;
49419
+ if (row.reasoningTokens !== null && usage.reasoning !== null) row.reasoningTokens += usage.reasoning;
49420
+ saved2.dirty[key] = (saved2.dirty[key] ?? 0) + 1;
49421
+ }
49422
+ flush() {
49423
+ const saved2 = this.saved, send = this.send;
49424
+ if (!saved2 || !send || !this.enabled || this.inFlight) return;
49425
+ const keys = Object.keys(saved2.dirty).filter((key) => saved2.totals[key]).sort().slice(0, MAX_ROWS);
49426
+ if (!keys.length) return;
49427
+ const rows = keys.map((key) => {
49428
+ const [day, client, model] = key.split("|");
49429
+ return { day, client, model, ...saved2.totals[key] };
49430
+ });
49431
+ const batchId = randomUUID14(), versions = Object.fromEntries(keys.map((key) => [key, saved2.dirty[key]]));
49432
+ let sent = false;
49433
+ try {
49434
+ sent = send({ batchId, stateId: saved2.stateId, rows });
49435
+ } catch {
49436
+ }
49437
+ if (sent) this.inFlight = { batchId, versions, timer: setTimeout(() => {
49438
+ if (this.inFlight?.batchId === batchId) this.inFlight = void 0;
49439
+ }, 3e4).unref() };
49440
+ }
49441
+ schedule(delay4) {
49442
+ clearTimeout(this.timer);
49443
+ this.timer = setTimeout(() => {
49444
+ if (!this.enabled) return;
49445
+ void this.scanOnce().catch(() => {
49446
+ if (!this.failed) {
49447
+ this.failed = true;
49448
+ process.stderr.write("TOKEN_USAGE_SCAN_FAILED\n");
49449
+ }
49450
+ }).finally(() => {
49451
+ if (this.enabled) this.schedule(this.options.intervalMs ?? 36e5);
49452
+ });
49453
+ }, delay4);
49454
+ this.timer.unref();
49455
+ }
49456
+ exclusive(task) {
49457
+ const next = (this.running ?? Promise.resolve()).then(task, task);
49458
+ this.running = next.catch(() => {
49459
+ });
49460
+ return next;
49461
+ }
49462
+ now() {
49463
+ return (this.options.now ?? Date.now)();
49464
+ }
49465
+ roots() {
49466
+ return this.options.roots ?? tokenUsageRoots();
49467
+ }
49468
+ async load() {
49469
+ if (this.saved) return this.saved;
49470
+ let value;
49471
+ try {
49472
+ const info = await lstat12(stateFile(this.directory));
49473
+ if (info.isFile() && !info.isSymbolicLink() && info.size <= 16 * 1024 * 1024) {
49474
+ const parsed = JSON.parse(await readFile11(stateFile(this.directory), "utf8"));
49475
+ 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;
49476
+ }
49477
+ } catch {
49478
+ }
49479
+ return this.saved = value ?? { version: 1, ...this.enrollment, stateId: randomUUID14(), countFrom: new Date(this.now()).toISOString(), files: {}, totals: {}, dirty: {}, baseline: true };
49480
+ }
49481
+ async persist() {
49482
+ if (!this.saved) return;
49483
+ await mkdir11(stateDirectory(this.directory), { mode: 448 }).catch((error62) => {
49484
+ if (error62.code !== "EEXIST") throw error62;
49485
+ });
49486
+ const parent = await lstat12(stateDirectory(this.directory));
49487
+ if (!parent.isDirectory() || parent.isSymbolicLink()) throw Error("TOKEN_USAGE_DIRECTORY_INVALID");
49488
+ const temporary = stateFile(this.directory) + "." + randomUUID14() + ".tmp";
49489
+ try {
49490
+ await writeFile5(temporary, JSON.stringify(this.saved), { flag: "wx", mode: 384 });
49491
+ await rename8(temporary, stateFile(this.directory));
49492
+ } finally {
49493
+ await rm10(temporary, { force: true }).catch(() => {
49494
+ });
49495
+ }
49496
+ }
49497
+ };
49498
+
49096
49499
  // agent/src/native-event-buffer.ts
49097
49500
  import { createHash as createHash18 } from "node:crypto";
49098
49501
  function nativeFingerprint(code, executionId = "") {
@@ -49375,7 +49778,7 @@ var NativeEventSupervisor = class {
49375
49778
  };
49376
49779
 
49377
49780
  // agent/src/native-fabric-observer.ts
49378
- 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;
49781
+ 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;
49379
49782
  var NativeFabricObserver = class {
49380
49783
  constructor(supervisor, source) {
49381
49784
  this.supervisor = supervisor;
@@ -49397,7 +49800,7 @@ var NativeFabricObserver = class {
49397
49800
  unsubscribe;
49398
49801
  connected(authenticatedDeviceId) {
49399
49802
  this.disconnected();
49400
- if (uuid22.test(authenticatedDeviceId)) this.deviceId = authenticatedDeviceId.toLowerCase();
49803
+ if (uuid23.test(authenticatedDeviceId)) this.deviceId = authenticatedDeviceId.toLowerCase();
49401
49804
  this.activity();
49402
49805
  }
49403
49806
  disconnected() {
@@ -49432,17 +49835,17 @@ var NativeFabricObserver = class {
49432
49835
  void Promise.resolve().then(() => this.source.mailbox.snapshot()).then((state) => {
49433
49836
  if (this.closed || expired || generation !== this.generation) return;
49434
49837
  if (state.workers.length > 64 || state.assignments.length > 256 || state.messages.length > 1024) throw Error("FABRIC_BOUND_INVALID");
49435
- const workers = new Set(state.workers.filter((w) => w.device?.deviceId.toLowerCase() === deviceId && uuid22.test(w.workerId)).map((w) => w.workerId));
49838
+ const workers = new Set(state.workers.filter((w) => w.device?.deviceId.toLowerCase() === deviceId && uuid23.test(w.workerId)).map((w) => w.workerId));
49436
49839
  const assignments = new Map(state.assignments.filter((a) => workers.has(a.workerId)).map((a) => [a.assignmentId, a]));
49437
49840
  const refs = /* @__PURE__ */ new Map();
49438
49841
  for (const a of assignments.values()) {
49439
49842
  const id2 = a.execution?.executionId;
49440
- if (!id2 || !uuid22.test(id2)) continue;
49843
+ if (!id2 || !uuid23.test(id2)) continue;
49441
49844
  if (refs.has(id2.toLowerCase())) throw Error("FABRIC_EXECUTION_CONFLICT");
49442
49845
  refs.set(id2.toLowerCase(), {
49443
49846
  executionId: id2.toLowerCase(),
49444
49847
  workerId: a.workerId.toLowerCase(),
49445
- ...uuid22.test(a.taskId) ? { taskId: a.taskId.toLowerCase() } : {}
49848
+ ...uuid23.test(a.taskId) ? { taskId: a.taskId.toLowerCase() } : {}
49446
49849
  });
49447
49850
  }
49448
49851
  this.referencesByExecution.clear();
@@ -49494,27 +49897,27 @@ var NativeFabricObserver = class {
49494
49897
  };
49495
49898
 
49496
49899
  // agent/src/native-fabric-startup.ts
49497
- import { lstat as lstat13, mkdir as mkdir13, open as open11, readFile as readFile11 } from "node:fs/promises";
49498
- import path27 from "node:path";
49900
+ import { lstat as lstat14, mkdir as mkdir14, open as open12, readFile as readFile12 } from "node:fs/promises";
49901
+ import path28 from "node:path";
49499
49902
 
49500
49903
  // src/agent-fabric-service.ts
49501
- import { lstat as lstat12, mkdir as mkdir12, realpath as realpath9 } from "node:fs/promises";
49904
+ import { lstat as lstat13, mkdir as mkdir13, realpath as realpath9 } from "node:fs/promises";
49502
49905
  import { watch } from "node:fs";
49503
- import path26 from "node:path";
49906
+ import path27 from "node:path";
49504
49907
 
49505
49908
  // src/agent-runtime-identity.ts
49506
- import { createHash as createHash19, randomBytes as randomBytes8, randomUUID as randomUUID15, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
49909
+ import { createHash as createHash19, randomBytes as randomBytes8, randomUUID as randomUUID16, timingSafeEqual as timingSafeEqual4 } from "node:crypto";
49507
49910
 
49508
49911
  // src/agent-fabric-state.ts
49509
- import { randomUUID as randomUUID14 } from "node:crypto";
49510
- import { mkdir as mkdir11, open as open10, rename as rename8, unlink as unlink3 } from "node:fs/promises";
49511
- import path25 from "node:path";
49912
+ import { randomUUID as randomUUID15 } from "node:crypto";
49913
+ import { mkdir as mkdir12, open as open11, rename as rename9, unlink as unlink3 } from "node:fs/promises";
49914
+ import path26 from "node:path";
49512
49915
  var queues = /* @__PURE__ */ new Map();
49513
49916
  var FabricStateFile = class {
49514
49917
  constructor(file3, maxBytes, parse4) {
49515
49918
  this.maxBytes = maxBytes;
49516
49919
  this.parse = parse4;
49517
- this.file = path25.resolve(file3);
49920
+ this.file = path26.resolve(file3);
49518
49921
  }
49519
49922
  maxBytes;
49520
49923
  parse;
@@ -49532,7 +49935,7 @@ var FabricStateFile = class {
49532
49935
  return result2;
49533
49936
  }
49534
49937
  async load() {
49535
- const handle = await open10(this.file, "r");
49938
+ const handle = await open11(this.file, "r");
49536
49939
  try {
49537
49940
  const info = await handle.stat();
49538
49941
  if (!info.isFile() || info.size > this.maxBytes) throw Error("FABRIC_STATE_LIMIT");
@@ -49558,10 +49961,10 @@ var FabricStateFile = class {
49558
49961
  }
49559
49962
  update(fn, create) {
49560
49963
  return this.serial(async () => {
49561
- if (create) await mkdir11(path25.dirname(this.file), { recursive: true });
49964
+ if (create) await mkdir12(path26.dirname(this.file), { recursive: true });
49562
49965
  const lockPath = this.file + ".lock";
49563
- const token = randomUUID14();
49564
- const lock = await open10(lockPath, "wx", 384).catch((error62) => {
49966
+ const token = randomUUID15();
49967
+ const lock = await open11(lockPath, "wx", 384).catch((error62) => {
49565
49968
  if (error62.code === "EEXIST") throw Error("FABRIC_STATE_BUSY");
49566
49969
  throw error62;
49567
49970
  });
@@ -49579,7 +49982,7 @@ var FabricStateFile = class {
49579
49982
  const encoded = JSON.stringify(this.parse(state));
49580
49983
  if (Buffer.byteLength(encoded) > this.maxBytes) throw Error("FABRIC_STATE_LIMIT");
49581
49984
  const temporary = this.file + "." + token + ".tmp";
49582
- const handle = await open10(temporary, "wx", 384);
49985
+ const handle = await open11(temporary, "wx", 384);
49583
49986
  try {
49584
49987
  try {
49585
49988
  await handle.writeFile(encoded, "utf8");
@@ -49587,7 +49990,7 @@ var FabricStateFile = class {
49587
49990
  } finally {
49588
49991
  await handle.close();
49589
49992
  }
49590
- await rename8(temporary, this.file);
49993
+ await rename9(temporary, this.file);
49591
49994
  } finally {
49592
49995
  await unlink3(temporary).catch((error62) => {
49593
49996
  if (error62.code !== "ENOENT") throw error62;
@@ -49596,7 +49999,7 @@ var FabricStateFile = class {
49596
49999
  return result2;
49597
50000
  } finally {
49598
50001
  await lock.close();
49599
- const current2 = await open10(lockPath, "r");
50002
+ const current2 = await open11(lockPath, "r");
49600
50003
  try {
49601
50004
  if ((await current2.stat()).size > 1024 || JSON.parse(await current2.readFile("utf8")).token !== token)
49602
50005
  throw Error("FABRIC_STATE_LOCK_CHANGED");
@@ -49656,7 +50059,7 @@ var AgentRuntimeIdentityStore = class {
49656
50059
  issue() {
49657
50060
  return this.serial((state) => {
49658
50061
  if (state.bindings.length >= MAX_BINDINGS) throw Error("RUNTIME_IDENTITY_LIMIT");
49659
- const runtimeId = "rt-" + randomUUID15();
50062
+ const runtimeId = "rt-" + randomUUID16();
49660
50063
  const runtimeKey = randomBytes8(32).toString("base64url");
49661
50064
  const now = this.now();
49662
50065
  state.bindings.push({ runtimeId, keyHash: encodedDigest(runtimeKey), createdAt: now, lastUsedAt: now, revoked: false });
@@ -49689,10 +50092,10 @@ var AgentRuntimeIdentityStore = class {
49689
50092
  };
49690
50093
 
49691
50094
  // src/agent-fabric-mailbox.ts
49692
- import { randomUUID as randomUUID17 } from "node:crypto";
50095
+ import { randomUUID as randomUUID18 } from "node:crypto";
49693
50096
 
49694
50097
  // src/agent-fabric-timeline.ts
49695
- import { randomUUID as randomUUID16 } from "node:crypto";
50098
+ import { randomUUID as randomUUID17 } from "node:crypto";
49696
50099
  import { performance as performance2 } from "node:perf_hooks";
49697
50100
  var FabricId = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/);
49698
50101
  var FabricUtc = external_exports.string().datetime({ precision: 3 }).refine((value) => new Date(value).toISOString() === value);
@@ -49701,7 +50104,7 @@ var FabricStampSchema = external_exports.strictObject({
49701
50104
  clockId: FabricId,
49702
50105
  monotonicMs: external_exports.number().finite().nonnegative().max(Number.MAX_SAFE_INTEGER)
49703
50106
  });
49704
- var processClockId = "clock-" + randomUUID16();
50107
+ var processClockId = "clock-" + randomUUID17();
49705
50108
  function createFabricClock() {
49706
50109
  return () => ({ atUtc: (/* @__PURE__ */ new Date()).toISOString(), clockId: processClockId, monotonicMs: performance2.now() });
49707
50110
  }
@@ -49958,7 +50361,7 @@ var AgentWorkerMailbox = class {
49958
50361
  const now = this.clock().atUtc;
49959
50362
  const worker = {
49960
50363
  ...registration,
49961
- workerId: randomUUID17(),
50364
+ workerId: randomUUID18(),
49962
50365
  controllerId: this.controllerId,
49963
50366
  runtimeId: null,
49964
50367
  attribution: WorkerAttributionSchema.parse({}),
@@ -49992,7 +50395,7 @@ var AgentWorkerMailbox = class {
49992
50395
  if (state.messages.length >= MAX_MESSAGES) throw Error("FABRIC_MESSAGE_LIMIT");
49993
50396
  const now = this.clock();
49994
50397
  const message2 = {
49995
- messageId: randomUUID17(),
50398
+ messageId: randomUUID18(),
49996
50399
  key: request.key,
49997
50400
  assignmentId: assignment.assignmentId,
49998
50401
  direction,
@@ -50022,7 +50425,7 @@ var AgentWorkerMailbox = class {
50022
50425
  const now = this.clock().atUtc;
50023
50426
  const assignment = {
50024
50427
  ...request,
50025
- assignmentId: randomUUID17(),
50428
+ assignmentId: randomUUID18(),
50026
50429
  phase: "assigned",
50027
50430
  createdAt: now,
50028
50431
  updatedAt: now,
@@ -50202,9 +50605,9 @@ var WorkerRequest = external_exports.discriminatedUnion("operation", [
50202
50605
  var AgentFabricService = class _AgentFabricService {
50203
50606
  constructor(directory, controllerId) {
50204
50607
  this.directory = directory;
50205
- this.identities = new AgentRuntimeIdentityStore(path26.join(directory, "identities.json"));
50608
+ this.identities = new AgentRuntimeIdentityStore(path27.join(directory, "identities.json"));
50206
50609
  this.mailbox = new AgentWorkerMailbox(
50207
- path26.join(directory, "mailbox.json"),
50610
+ path27.join(directory, "mailbox.json"),
50208
50611
  controllerId,
50209
50612
  this.identities,
50210
50613
  void 0,
@@ -50219,21 +50622,21 @@ var AgentFabricService = class _AgentFabricService {
50219
50622
  closed = false;
50220
50623
  static async open(directory, controllerId, device = null, initialize = true) {
50221
50624
  const expected = Binding.parse({ version: 1, controllerId, device, initialized: false });
50222
- const absolute2 = path26.resolve(directory);
50223
- for (let current2 = absolute2; ; current2 = path26.dirname(current2)) {
50625
+ const absolute2 = path27.resolve(directory);
50626
+ for (let current2 = absolute2; ; current2 = path27.dirname(current2)) {
50224
50627
  try {
50225
- if ((await lstat12(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50628
+ if ((await lstat13(current2)).isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50226
50629
  } catch (error62) {
50227
50630
  if (error62.code !== "ENOENT") throw error62;
50228
50631
  }
50229
- if (path26.dirname(current2) === current2) break;
50632
+ if (path27.dirname(current2) === current2) break;
50230
50633
  }
50231
- if (initialize) await mkdir12(absolute2, { recursive: true, mode: 448 });
50232
- if (!(await lstat12(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
50634
+ if (initialize) await mkdir13(absolute2, { recursive: true, mode: 448 });
50635
+ if (!(await lstat13(absolute2)).isDirectory() || (await realpath9(absolute2)).toLowerCase() !== absolute2.toLowerCase())
50233
50636
  throw Error("FABRIC_DIRECTORY_INVALID");
50234
50637
  const present = /* @__PURE__ */ new Set();
50235
50638
  for (const name2 of ["binding.json", "mailbox.json", "identities.json"]) {
50236
- const file3 = await lstat12(path26.join(absolute2, name2)).catch((error62) => {
50639
+ const file3 = await lstat13(path27.join(absolute2, name2)).catch((error62) => {
50237
50640
  if (error62.code === "ENOENT") return null;
50238
50641
  throw error62;
50239
50642
  });
@@ -50241,7 +50644,7 @@ var AgentFabricService = class _AgentFabricService {
50241
50644
  if (file3) present.add(name2);
50242
50645
  }
50243
50646
  if (!present.has("binding.json") && present.size) throw Error("FABRIC_BINDING_MISSING");
50244
- const binding2 = new FabricStateFile(path26.join(absolute2, "binding.json"), 2048, (value) => Binding.parse(value));
50647
+ const binding2 = new FabricStateFile(path27.join(absolute2, "binding.json"), 2048, (value) => Binding.parse(value));
50245
50648
  const service2 = new _AgentFabricService(absolute2, controllerId);
50246
50649
  await binding2.update(async (state) => {
50247
50650
  if (state.controllerId !== expected.controllerId || JSON.stringify(state.device) !== JSON.stringify(expected.device))
@@ -50256,7 +50659,7 @@ var AgentFabricService = class _AgentFabricService {
50256
50659
  state.initialized = true;
50257
50660
  }
50258
50661
  const snapshot2 = await service2.mailbox.snapshot();
50259
- if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat12(path26.join(absolute2, "identities.json"));
50662
+ if (snapshot2.workers.some((worker) => worker.runtimeId !== null)) await lstat13(path27.join(absolute2, "identities.json"));
50260
50663
  }, initialize ? () => expected : void 0);
50261
50664
  return service2;
50262
50665
  }
@@ -50340,26 +50743,26 @@ var OwnerRequest = external_exports.discriminatedUnion("operation", [
50340
50743
  })
50341
50744
  ]);
50342
50745
  var Delivery = external_exports.strictObject({ capability: external_exports.string().regex(/^[A-Za-z0-9+/]+={0,2}$/).max(4096), request: external_exports.unknown() });
50343
- async function openNativeFabric(stateDirectory, enrollment, box, initialize = true) {
50746
+ async function openNativeFabric(stateDirectory2, enrollment, box, initialize = true) {
50344
50747
  const controllerId = "device-" + external_exports.string().uuid().parse(enrollment.deviceId).toLowerCase();
50345
50748
  const tenantId = external_exports.string().uuid().parse(enrollment.tenantId).toLowerCase();
50346
- const parent = path27.join(stateDirectory, ".local-commander"), marker = path27.join(parent, "fabric-established.json");
50749
+ const parent = path28.join(stateDirectory2, ".local-commander"), marker = path28.join(parent, "fabric-established.json");
50347
50750
  try {
50348
- await mkdir13(parent, { mode: 448 });
50751
+ await mkdir14(parent, { mode: 448 });
50349
50752
  } catch (error62) {
50350
50753
  if (error62.code !== "EEXIST") throw error62;
50351
50754
  }
50352
- const parentInfo = await lstat13(parent);
50755
+ const parentInfo = await lstat14(parent);
50353
50756
  if (!parentInfo.isDirectory() || parentInfo.isSymbolicLink()) throw Error("FABRIC_DIRECTORY_INVALID");
50354
50757
  const expected = JSON.stringify({ version: 1, controllerId, tenantId });
50355
50758
  let fresh = false;
50356
50759
  try {
50357
- const info = await lstat13(marker);
50358
- if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile11(marker, "utf8") !== expected)
50760
+ const info = await lstat14(marker);
50761
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 2048 || await readFile12(marker, "utf8") !== expected)
50359
50762
  throw Error("FABRIC_BINDING_CHANGED");
50360
50763
  } catch (error62) {
50361
50764
  if (error62.code !== "ENOENT" || !initialize) throw error62;
50362
- const file3 = await open11(marker, "wx", 384);
50765
+ const file3 = await open12(marker, "wx", 384);
50363
50766
  try {
50364
50767
  await file3.writeFile(expected);
50365
50768
  await file3.datasync();
@@ -50369,22 +50772,22 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
50369
50772
  fresh = true;
50370
50773
  }
50371
50774
  const service2 = await AgentFabricService.open(
50372
- path27.join(stateDirectory, ".local-commander", "fabric"),
50775
+ path28.join(stateDirectory2, ".local-commander", "fabric"),
50373
50776
  controllerId,
50374
50777
  { deviceId: enrollment.deviceId.toLowerCase(), enrollmentEvidenceRef: "enrollment-" + tenantId },
50375
50778
  fresh
50376
50779
  );
50377
50780
  const purpose = "native-fabric:" + tenantId + ":" + controllerId;
50378
- const credentialFile = (workerId) => path27.join(service2.directory, external_exports.string().uuid().parse(workerId) + ".capability");
50781
+ const credentialFile = (workerId) => path28.join(service2.directory, external_exports.string().uuid().parse(workerId) + ".capability");
50379
50782
  const decode4 = (value) => {
50380
50783
  const credential = Credential.parse(JSON.parse(box.open(Buffer.from(value, "base64"), purpose).toString("utf8")));
50381
50784
  if (credential.controllerId !== controllerId) throw Error("FABRIC_WORKER_DENIED");
50382
50785
  return credential;
50383
50786
  };
50384
50787
  async function capability(workerId) {
50385
- const file3 = credentialFile(workerId), info = await lstat13(file3);
50788
+ const file3 = credentialFile(workerId), info = await lstat14(file3);
50386
50789
  if (!info.isFile() || info.isSymbolicLink() || info.size > 4096) throw Error("FABRIC_CREDENTIAL_UNKNOWN");
50387
- const encoded = await readFile11(file3, "utf8");
50790
+ const encoded = await readFile12(file3, "utf8");
50388
50791
  if (decode4(encoded).workerId !== workerId) throw Error("FABRIC_WORKER_DENIED");
50389
50792
  return encoded;
50390
50793
  }
@@ -50417,7 +50820,7 @@ async function openNativeFabric(stateDirectory, enrollment, box, initialize = tr
50417
50820
  } else {
50418
50821
  const credential = await service2.identities.issue();
50419
50822
  const encoded = box.seal(Buffer.from(JSON.stringify({ ...credential, workerId: worker.workerId, controllerId })), purpose).toString("base64");
50420
- const file3 = await open11(credentialFile(worker.workerId), "wx", 384);
50823
+ const file3 = await open12(credentialFile(worker.workerId), "wx", 384);
50421
50824
  try {
50422
50825
  await file3.writeFile(encoded);
50423
50826
  await file3.datasync();
@@ -50476,7 +50879,7 @@ async function readFabricRequest(input2 = process.stdin) {
50476
50879
 
50477
50880
  // agent/src/supervisor-liveness.ts
50478
50881
  import { spawn as spawn6 } from "node:child_process";
50479
- import path28 from "node:path";
50882
+ import path29 from "node:path";
50480
50883
  import { setTimeout as delay3 } from "node:timers/promises";
50481
50884
  var ROW = /^"([^"]+)","(\d{1,10})"/;
50482
50885
  function parseTasklist(output2, image) {
@@ -50491,7 +50894,7 @@ function parseTasklist(output2, image) {
50491
50894
  }
50492
50895
  function listProcesses(image, timeoutMs2 = 5e3) {
50493
50896
  if (process.platform !== "win32" || !/^[A-Za-z0-9._-]{1,64}\.exe$/i.test(image)) return Promise.resolve(null);
50494
- const tasklist = path28.join(process.env.SystemRoot || "C:\\Windows", "System32", "tasklist.exe");
50897
+ const tasklist = path29.join(process.env.SystemRoot || "C:\\Windows", "System32", "tasklist.exe");
50495
50898
  return new Promise((resolve) => {
50496
50899
  let output2 = "", settled = false;
50497
50900
  const finish = (value) => {
@@ -50520,8 +50923,8 @@ function listProcesses(image, timeoutMs2 = 5e3) {
50520
50923
  }
50521
50924
  function supervisorLiveness(helperPath, options = {}) {
50522
50925
  if (process.platform === "linux" && !options.list) return linuxSupervisorLiveness;
50523
- if (process.platform === "darwin" && !options.list) return (pids, _linux, darwin) => darwinSupervisorLiveness(path28.join(path28.dirname(helperPath), "posix-host"), pids, darwin);
50524
- const image = path28.basename(helperPath), waitMs = options.waitMs ?? 1e4, pollMs = options.pollMs ?? 500, list = options.list ?? listProcesses;
50926
+ if (process.platform === "darwin" && !options.list) return (pids, _linux, darwin) => darwinSupervisorLiveness(path29.join(path29.dirname(helperPath), "posix-host"), pids, darwin);
50927
+ const image = path29.basename(helperPath), waitMs = options.waitMs ?? 1e4, pollMs = options.pollMs ?? 500, list = options.list ?? listProcesses;
50525
50928
  return async (pids) => {
50526
50929
  const deadline = Date.now() + waitMs;
50527
50930
  for (; ; ) {
@@ -50536,8 +50939,8 @@ function supervisorLiveness(helperPath, options = {}) {
50536
50939
 
50537
50940
  // agent/src/content-audit.ts
50538
50941
  import { createReadStream } from "node:fs";
50539
- 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";
50540
- import path29 from "node:path";
50942
+ 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";
50943
+ import path30 from "node:path";
50541
50944
  import { performance as performance3 } from "node:perf_hooks";
50542
50945
  import { createInterface as createInterface2 } from "node:readline";
50543
50946
  import { randomBytes as randomBytes10 } from "node:crypto";
@@ -50704,19 +51107,19 @@ var AUDIT_MAX_BYTES = 512 * 1024 * 1024;
50704
51107
  var MAX_PENDING = 64;
50705
51108
  var FILE = /^(full|metrics)-(\d{4}-\d{2}-\d{2})\.jsonl$/;
50706
51109
  var PAUSED_FILE = "paused.json";
50707
- var DAY_MS = 864e5;
51110
+ var DAY_MS2 = 864e5;
50708
51111
  function contentAuditDirectory(stateDir) {
50709
- return path29.join(path29.dirname(path29.resolve(stateDir)), "Audit");
51112
+ return path30.join(path30.dirname(path30.resolve(stateDir)), "Audit");
50710
51113
  }
50711
51114
  async function plainDirectory(dir) {
50712
- await mkdir14(dir, { recursive: true, mode: 448 });
50713
- const info = await lstat14(dir);
51115
+ await mkdir15(dir, { recursive: true, mode: 448 });
51116
+ const info = await lstat15(dir);
50714
51117
  if (info.isSymbolicLink() || !info.isDirectory()) throw Error("AUDIT_DIRECTORY_INVALID");
50715
51118
  }
50716
51119
  async function auditFiles(dir) {
50717
51120
  let names;
50718
51121
  try {
50719
- names = await readdir6(dir);
51122
+ names = await readdir7(dir);
50720
51123
  } catch (error62) {
50721
51124
  if (error62.code === "ENOENT") return [];
50722
51125
  throw error62;
@@ -50725,7 +51128,7 @@ async function auditFiles(dir) {
50725
51128
  for (const name2 of names) {
50726
51129
  const match = FILE.exec(name2);
50727
51130
  if (!match) continue;
50728
- const info = await lstat14(path29.join(dir, name2));
51131
+ const info = await lstat15(path30.join(dir, name2));
50729
51132
  if (info.isFile()) files.push({ name: name2, kind: match[1], day: match[2], bytes: info.size });
50730
51133
  }
50731
51134
  return files.sort((a, b) => a.name.localeCompare(b.name));
@@ -50733,10 +51136,10 @@ async function auditFiles(dir) {
50733
51136
  async function writeJsonAtomic(file3, value) {
50734
51137
  const temp = `${file3}.${randomBytes10(6).toString("hex")}.tmp`;
50735
51138
  try {
50736
- await writeFile5(temp, JSON.stringify(value) + "\n", { flag: "wx", mode: 384 });
50737
- await rename9(temp, file3);
51139
+ await writeFile6(temp, JSON.stringify(value) + "\n", { flag: "wx", mode: 384 });
51140
+ await rename10(temp, file3);
50738
51141
  } finally {
50739
- await rm10(temp, { force: true }).catch(() => {
51142
+ await rm11(temp, { force: true }).catch(() => {
50740
51143
  });
50741
51144
  }
50742
51145
  }
@@ -50763,7 +51166,7 @@ var ContentAudit = class _ContentAudit {
50763
51166
  skipped = 0;
50764
51167
  closed = false;
50765
51168
  static async open(options) {
50766
- const dir = path29.resolve(options.directory);
51169
+ const dir = path30.resolve(options.directory);
50767
51170
  await plainDirectory(dir);
50768
51171
  const audit = new _ContentAudit(
50769
51172
  dir,
@@ -50772,7 +51175,7 @@ var ContentAudit = class _ContentAudit {
50772
51175
  { retentionDays: options.retentionDays ?? AUDIT_RETENTION_DAYS, maxBytes: options.maxBytes ?? AUDIT_MAX_BYTES },
50773
51176
  options.now ?? (() => /* @__PURE__ */ new Date())
50774
51177
  );
50775
- await rm10(path29.join(dir, PAUSED_FILE), { force: true });
51178
+ await rm11(path30.join(dir, PAUSED_FILE), { force: true });
50776
51179
  await audit.rollover(audit.now());
50777
51180
  if (audit.usedBytes >= audit.limits.maxBytes) await audit.pause("QUOTA_EXCEEDED");
50778
51181
  return audit;
@@ -50842,17 +51245,17 @@ var ContentAudit = class _ContentAudit {
50842
51245
  await this.pause("QUOTA_EXCEEDED");
50843
51246
  return;
50844
51247
  }
50845
- await appendFile(path29.join(this.dir, `full-${day}.jsonl`), line, { mode: 384 });
50846
- await appendFile(path29.join(this.dir, `metrics-${day}.jsonl`), metrics, { mode: 384 });
51248
+ await appendFile(path30.join(this.dir, `full-${day}.jsonl`), line, { mode: 384 });
51249
+ await appendFile(path30.join(this.dir, `metrics-${day}.jsonl`), metrics, { mode: 384 });
50847
51250
  this.usedBytes += bytes3;
50848
51251
  }
50849
51252
  /** Daily retention runs on the first write of a new day; no timer or background scan. */
50850
51253
  async rollover(at) {
50851
51254
  this.day = at.toISOString().slice(0, 10);
50852
- const cutoff = new Date(at.getTime() - this.limits.retentionDays * DAY_MS).toISOString().slice(0, 10);
51255
+ const cutoff = new Date(at.getTime() - this.limits.retentionDays * DAY_MS2).toISOString().slice(0, 10);
50853
51256
  let used = 0;
50854
51257
  for (const file3 of await auditFiles(this.dir)) {
50855
- if (file3.day <= cutoff) await rm10(path29.join(this.dir, file3.name), { force: true });
51258
+ if (file3.day <= cutoff) await rm11(path30.join(this.dir, file3.name), { force: true });
50856
51259
  else used += file3.bytes;
50857
51260
  }
50858
51261
  this.usedBytes = used;
@@ -50860,7 +51263,7 @@ var ContentAudit = class _ContentAudit {
50860
51263
  async pause(reason) {
50861
51264
  if (this.paused) return;
50862
51265
  this.paused = reason;
50863
- await writeJsonAtomic(path29.join(this.dir, PAUSED_FILE), { reason, at: this.now().toISOString() });
51266
+ await writeJsonAtomic(path30.join(this.dir, PAUSED_FILE), { reason, at: this.now().toISOString() });
50864
51267
  }
50865
51268
  };
50866
51269
  function percentiles(values) {
@@ -50880,15 +51283,15 @@ async function* jsonLines(file3) {
50880
51283
  }
50881
51284
  }
50882
51285
  }
50883
- var count2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
51286
+ var count3 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
50884
51287
  async function summarizeContentAudit(directory, key) {
50885
- const dir = path29.resolve(directory);
51288
+ const dir = path30.resolve(directory);
50886
51289
  const files = await auditFiles(dir);
50887
51290
  const days = /* @__PURE__ */ new Map();
50888
51291
  const sizes = [];
50889
51292
  const timings = [];
50890
51293
  for (const file3 of files.filter((f) => f.kind === "metrics")) {
50891
- for await (const line of jsonLines(path29.join(dir, file3.name))) {
51294
+ for await (const line of jsonLines(path30.join(dir, file3.name))) {
50892
51295
  let day = days.get(file3.day);
50893
51296
  if (!day) {
50894
51297
  day = { day: file3.day, records: 0, failed: 0, rawBytes: 0, sanitizedBytes: 0, compressedBytes: 0, envelopeBytes: 0 };
@@ -50896,19 +51299,19 @@ async function summarizeContentAudit(directory, key) {
50896
51299
  }
50897
51300
  day.records += 1;
50898
51301
  if (line.resultCode !== "SUCCESS") day.failed += 1;
50899
- day.rawBytes += count2(line.rawBytes);
50900
- day.sanitizedBytes += count2(line.sanitizedBytes);
50901
- day.compressedBytes += count2(line.compressedBytes);
50902
- day.envelopeBytes += count2(line.envelopeBytes);
51302
+ day.rawBytes += count3(line.rawBytes);
51303
+ day.sanitizedBytes += count3(line.sanitizedBytes);
51304
+ day.compressedBytes += count3(line.compressedBytes);
51305
+ day.envelopeBytes += count3(line.envelopeBytes);
50903
51306
  if (sizes.length < 1e5) {
50904
- sizes.push(count2(line.envelopeBytes));
50905
- timings.push(count2(line.encryptMs));
51307
+ sizes.push(count3(line.envelopeBytes));
51308
+ timings.push(count3(line.encryptMs));
50906
51309
  }
50907
51310
  }
50908
51311
  }
50909
51312
  let paused = null;
50910
51313
  try {
50911
- const value = JSON.parse(await readFile12(path29.join(dir, PAUSED_FILE), "utf8"));
51314
+ const value = JSON.parse(await readFile13(path30.join(dir, PAUSED_FILE), "utf8"));
50912
51315
  if (typeof value.reason === "string" && typeof value.at === "string") paused = { reason: value.reason.slice(0, 40), at: value.at.slice(0, 40) };
50913
51316
  } catch {
50914
51317
  }
@@ -50916,7 +51319,7 @@ async function summarizeContentAudit(directory, key) {
50916
51319
  const newest = files.filter((f) => f.kind === "full").at(-1);
50917
51320
  if (key && newest) {
50918
51321
  const tail = [];
50919
- for await (const line of jsonLines(path29.join(dir, newest.name))) {
51322
+ for await (const line of jsonLines(path30.join(dir, newest.name))) {
50920
51323
  tail.push(line);
50921
51324
  if (tail.length > 5) tail.shift();
50922
51325
  }
@@ -50950,10 +51353,10 @@ async function summarizeContentAudit(directory, key) {
50950
51353
  };
50951
51354
  }
50952
51355
  async function restoreContentAudit(input2, output2, key) {
50953
- const handle = await open12(path29.resolve(output2), "wx", 384);
51356
+ const handle = await open13(path30.resolve(output2), "wx", 384);
50954
51357
  let records = 0, failed = 0;
50955
51358
  try {
50956
- for await (const line of jsonLines(path29.resolve(input2))) {
51359
+ for await (const line of jsonLines(path30.resolve(input2))) {
50957
51360
  try {
50958
51361
  await handle.appendFile(JSON.stringify(decryptAuditRecord(line, key)) + "\n");
50959
51362
  records += 1;
@@ -50968,7 +51371,7 @@ async function restoreContentAudit(input2, output2, key) {
50968
51371
  }
50969
51372
 
50970
51373
  // agent/src/main.ts
50971
- var AGENT_VERSION2 = true ? "0.3.51" : "0.3.2";
51374
+ var AGENT_VERSION2 = true ? "0.3.52" : "0.3.2";
50972
51375
  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" : "";
50973
51376
  var AI_CONNECTION_SHIPPED = false;
50974
51377
  var QUARANTINE_RETRY_MS = 6e4;
@@ -50982,11 +51385,11 @@ function processAlive(pid) {
50982
51385
  }
50983
51386
  }
50984
51387
  async function claimAgentProcess(stateDir, runtimeDir, version2) {
50985
- await mkdir15(stateDir, { recursive: true });
50986
- const file3 = path30.join(stateDir, "agent-process.json");
51388
+ await mkdir16(stateDir, { recursive: true });
51389
+ const file3 = path31.join(stateDir, "agent-process.json");
50987
51390
  for (let attempt = 0; attempt < 2; attempt += 1) {
50988
51391
  try {
50989
- const handle = await open13(file3, "wx", 384);
51392
+ const handle = await open14(file3, "wx", 384);
50990
51393
  try {
50991
51394
  await handle.writeFile(JSON.stringify({ pid: process.pid, runtimeDir, version: version2, startedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", "utf8");
50992
51395
  } finally {
@@ -50994,8 +51397,8 @@ async function claimAgentProcess(stateDir, runtimeDir, version2) {
50994
51397
  }
50995
51398
  return async () => {
50996
51399
  try {
50997
- const current2 = JSON.parse(await readFile13(file3, "utf8"));
50998
- if (current2.pid === process.pid) await rm11(file3, { force: true });
51400
+ const current2 = JSON.parse(await readFile14(file3, "utf8"));
51401
+ if (current2.pid === process.pid) await rm12(file3, { force: true });
50999
51402
  } catch {
51000
51403
  }
51001
51404
  };
@@ -51003,12 +51406,12 @@ async function claimAgentProcess(stateDir, runtimeDir, version2) {
51003
51406
  if (!error62 || typeof error62 !== "object" || !("code" in error62) || error62.code !== "EEXIST") throw error62;
51004
51407
  let stale = true;
51005
51408
  try {
51006
- const current2 = JSON.parse(await readFile13(file3, "utf8"));
51409
+ const current2 = JSON.parse(await readFile14(file3, "utf8"));
51007
51410
  stale = typeof current2.pid !== "number" || !processAlive(current2.pid);
51008
51411
  } catch {
51009
51412
  }
51010
51413
  if (!stale) throw Error("AGENT_ALREADY_RUNNING");
51011
- await rm11(file3, { force: true });
51414
+ await rm12(file3, { force: true });
51012
51415
  }
51013
51416
  }
51014
51417
  throw Error("AGENT_ALREADY_RUNNING");
@@ -51132,6 +51535,7 @@ async function runAgent(options) {
51132
51535
  status: () => runtime.status(),
51133
51536
  onIncidentAck: (ack) => incidentProducer.ack(ack),
51134
51537
  onFullLogChoice: options.onFullLogChoice,
51538
+ ...options.tokenUsage ? { onTokenUsageState: (enabled) => options.tokenUsage.state(enabled), onTokenUsageAck: (batchId, result2) => options.tokenUsage.ack(batchId, result2) } : {},
51135
51539
  // After bridge.connected, like requests: the journal has recorded this connection first.
51136
51540
  onHeldLeases: (bindings) => {
51137
51541
  void readyPromise.then(() => bridge.heldLeases(bindings)).catch(() => {
@@ -51165,6 +51569,7 @@ async function runAgent(options) {
51165
51569
  await options.journal.prune();
51166
51570
  connection.reportStatus?.();
51167
51571
  incidentProducer.connected(connection.sendIncidentBatch);
51572
+ options.tokenUsage?.connected(connection.sendTokenUsageBatch);
51168
51573
  supervisor.observe({ kind: "connected" });
51169
51574
  monitor(() => options.monitor?.setConnection("connected", connection));
51170
51575
  if (options.monitor && !connection.monitorFreshnessMs) {
@@ -51220,6 +51625,7 @@ async function runAgent(options) {
51220
51625
  clearInterval(legacyMonitorTimer);
51221
51626
  legacyMonitorTimer = void 0;
51222
51627
  incidentProducer.disconnected();
51628
+ options.tokenUsage?.disconnected();
51223
51629
  if (!options.signal.aborted) supervisor.observe({ kind: "disconnected" });
51224
51630
  monitor(() => options.monitor?.setConnection("disconnected"));
51225
51631
  try {
@@ -51240,6 +51646,7 @@ async function runAgent(options) {
51240
51646
  } finally {
51241
51647
  fabric?.close();
51242
51648
  incidentProducer.close();
51649
+ options.tokenUsage?.close();
51243
51650
  supervisor.close();
51244
51651
  await options.journal.close();
51245
51652
  }
@@ -51266,10 +51673,10 @@ async function openContentAudit(store, stateDir) {
51266
51673
  async function main() {
51267
51674
  if (!["win32", "linux", "darwin"].includes(process.platform)) throw Error("PLATFORM_UNSUPPORTED");
51268
51675
  const appData = process.env.LC_AGENT_DATA_DIR ?? (process.platform === "win32" ? process.env.LOCALAPPDATA : posixDataHome());
51269
- if (!appData || !path30.isAbsolute(appData)) throw Error("APP_DATA_MISSING");
51270
- const stateDir = process.env.LC_AGENT_STATE_DIR ?? path30.join(appData, "LocalCommander", "Agent");
51271
- const binaryDir = path30.dirname(process.platform === "win32" ? process.execPath : await realpath10(process.execPath));
51272
- const ownerBridgePath = process.env.LC_OWNER_BRIDGE ?? path30.join(binaryDir, process.platform === "win32" ? "OwnerBridge.exe" : "owner-store");
51676
+ if (!appData || !path31.isAbsolute(appData)) throw Error("APP_DATA_MISSING");
51677
+ const stateDir = process.env.LC_AGENT_STATE_DIR ?? path31.join(appData, "LocalCommander", "Agent");
51678
+ const binaryDir = path31.dirname(process.platform === "win32" ? process.execPath : await realpath10(process.execPath));
51679
+ const ownerBridgePath = process.env.LC_OWNER_BRIDGE ?? path31.join(binaryDir, process.platform === "win32" ? "OwnerBridge.exe" : "owner-store");
51273
51680
  const store = await WindowsPrivateStore.open(stateDir, ownerBridgePath);
51274
51681
  const command = process.argv[2] ?? "run";
51275
51682
  if (process.platform !== "win32" && (command.startsWith("guard-") || command.startsWith("network-"))) throw Error("FEATURE_PLATFORM_UNSUPPORTED");
@@ -51279,7 +51686,7 @@ async function main() {
51279
51686
  const pairing = new PairingClient(store, { controlPlaneOrigin: origin, agentVersion: AGENT_VERSION2 });
51280
51687
  const begun = await pairing.begin();
51281
51688
  process.stdout.write(JSON.stringify({ approvalUrl: begun.approvalUrl, confirmationCode: begun.confirmationCode, expiresAt: begun.expiresAt.toISOString() }) + "\n");
51282
- await pairing.waitAndComplete(begun, os8.hostname().slice(0, 120));
51689
+ await pairing.waitAndComplete(begun, os9.hostname().slice(0, 120));
51283
51690
  process.stdout.write("DEVICE_PAIRED\n");
51284
51691
  return;
51285
51692
  }
@@ -51365,7 +51772,7 @@ async function main() {
51365
51772
  }
51366
51773
  if (command === "efficiency-report") {
51367
51774
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
51368
- const ledger = await OptimizationLedger.open(path30.join(stateDir, "optimization"));
51775
+ const ledger = await OptimizationLedger.open(path31.join(stateDir, "optimization"));
51369
51776
  try {
51370
51777
  process.stdout.write(JSON.stringify(await ledger.report(), null, 2) + "\n");
51371
51778
  } finally {
@@ -51375,7 +51782,7 @@ async function main() {
51375
51782
  }
51376
51783
  if (command === "guard-configure") {
51377
51784
  if (args.length !== 1) throw Error("AGENT_COMMAND_INVALID");
51378
- const filename = await (await import("node:fs/promises")).realpath(path30.resolve(args[0]));
51785
+ const filename = await (await import("node:fs/promises")).realpath(path31.resolve(args[0]));
51379
51786
  const input2 = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await readWindowsFile(ownerBridgePath, filename, 2e5)));
51380
51787
  if (!input2 || typeof input2 !== "object" || Object.keys(input2).sort().join(",") !== "compact,settings") throw Error("GUARD_CONFIGURATION_INVALID");
51381
51788
  await store.configureGuard(input2.settings, input2.compact);
@@ -51394,7 +51801,7 @@ async function main() {
51394
51801
  }
51395
51802
  if (command === "guard-evidence") {
51396
51803
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
51397
- const journal = await NativeJournal.open(path30.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51804
+ const journal = await NativeJournal.open(path31.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51398
51805
  try {
51399
51806
  process.stdout.write(JSON.stringify(await journal.guardEvidence()) + "\n");
51400
51807
  } finally {
@@ -51406,7 +51813,7 @@ async function main() {
51406
51813
  if (args.length !== (command === "guard-export" ? 0 : 1)) throw Error("AGENT_COMMAND_INVALID");
51407
51814
  const identity = await store.load();
51408
51815
  if (!identity?.enrollment) throw Error("ENROLLMENT_MISSING");
51409
- const journal = await NativeJournal.open(path30.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51816
+ const journal = await NativeJournal.open(path31.join(stateDir, "journal"), new SecretBox({ "1": await store.loadDataKey() }));
51410
51817
  try {
51411
51818
  const { tenantId, deviceId } = identity.enrollment;
51412
51819
  const records = (await journal.guardEvidence()).filter((record2) => record2.tenantId === tenantId && record2.deviceId === deviceId);
@@ -51484,27 +51891,27 @@ async function main() {
51484
51891
  if (args.length) throw Error("AGENT_COMMAND_INVALID");
51485
51892
  if (!(await store.load())?.enrollment) throw Error("ENROLLMENT_MISSING");
51486
51893
  const releaseProcess = await claimAgentProcess(stateDir, binaryDir, AGENT_VERSION2);
51487
- const monitor = new ProductionMonitor(path30.join(appData, "LocalCommander", "Monitor"), stateDir, AGENT_VERSION2);
51894
+ const monitor = new ProductionMonitor(path31.join(appData, "LocalCommander", "Monitor"), stateDir, AGENT_VERSION2);
51488
51895
  const publishMonitor = () => monitor.flush().catch(() => {
51489
51896
  process.stderr.write("MONITOR_WRITE_FAILED\n");
51490
51897
  });
51491
51898
  await publishMonitor();
51492
51899
  try {
51493
51900
  const journal = await NativeJournal.open(
51494
- path30.join(stateDir, "journal"),
51901
+ path31.join(stateDir, "journal"),
51495
51902
  new SecretBox({ "1": await store.loadDataKey() }),
51496
- process.platform === "win32" ? {} : { lockHelper: path30.join(binaryDir, "posix-host") }
51903
+ process.platform === "win32" ? {} : { lockHelper: path31.join(binaryDir, "posix-host") }
51497
51904
  );
51498
51905
  const ledgerLoss = () => {
51499
51906
  process.stderr.write("OPTIMIZATION_TELEMETRY_INCOMPLETE\n");
51500
51907
  };
51501
51908
  const efficiencyLedger = await new OptionalWork(ledgerLoss, 1e3, 1).run(
51502
- () => OptimizationLedger.open(path30.join(stateDir, "optimization")),
51909
+ () => OptimizationLedger.open(path31.join(stateDir, "optimization")),
51503
51910
  void 0,
51504
51911
  (ledger) => ledger.close()
51505
51912
  );
51506
51913
  try {
51507
- const helperPath = process.env.LC_JOB_HOST ?? path30.join(binaryDir, process.platform === "win32" ? "JobHost.exe" : "job-host.mjs");
51914
+ const helperPath = process.env.LC_JOB_HOST ?? path31.join(binaryDir, process.platform === "win32" ? "JobHost.exe" : "job-host.mjs");
51508
51915
  const tools = new NativeTools({ stateDirectory: stateDir, helperPath, ownerBridgePath, programs: await store.loadPrograms() });
51509
51916
  const stop = new AbortController();
51510
51917
  process.once("SIGINT", () => stop.abort());
@@ -51517,6 +51924,7 @@ async function main() {
51517
51924
  });
51518
51925
  };
51519
51926
  onFullLogChoice(null);
51927
+ const tokenUsage = process.env.LC_TOKEN_USAGE === "off" ? void 0 : new TokenUsageReporter(stateDir, enrollment);
51520
51928
  const fabric = await openNativeFabric(stateDir, enrollment, new SecretBox({ "1": await store.loadDataKey() })).catch(() => {
51521
51929
  process.stderr.write("FABRIC_STARTUP_FAILED\n");
51522
51930
  return void 0;
@@ -51546,6 +51954,7 @@ async function main() {
51546
51954
  efficiencyLedger,
51547
51955
  monitor,
51548
51956
  onFullLogChoice,
51957
+ ...tokenUsage ? { tokenUsage } : {},
51549
51958
  localDirect: { key: localDirectKey(await store.loadDataKey()), directory: localDirectDirectory(appData) },
51550
51959
  supervisorLiveness: supervisorLiveness(helperPath),
51551
51960
  ...proxyMode ? { proxyMode: { providers: proxyMode.providers, publicKeyPem: NETWORK_PUBLIC_KEY, endpoint: proxyEndpoint, onState: onProxyState } } : {},
@@ -51582,7 +51991,7 @@ async function main() {
51582
51991
  await releaseProcess();
51583
51992
  }
51584
51993
  }
51585
- var entrypoint = process.argv[1] && (process.platform === "win32" ? path30.resolve(process.argv[1]) : await realpath10(process.argv[1]).catch(() => null));
51994
+ var entrypoint = process.argv[1] && (process.platform === "win32" ? path31.resolve(process.argv[1]) : await realpath10(process.argv[1]).catch(() => null));
51586
51995
  if (entrypoint === fileURLToPath(import.meta.url)) {
51587
51996
  void main().catch((error62) => {
51588
51997
  const code = error62 instanceof Error && /^[A-Z0-9_]{1,64}$/.test(error62.message) ? error62.message : "AGENT_START_FAILED";