agent-shim 8.10.0 → 8.11.0

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/dist/index.cjs CHANGED
@@ -115,6 +115,7 @@ __export(index_exports, {
115
115
  createRcApiNodeHandler: () => createRcApiNodeHandler,
116
116
  createRcApiRouter: () => createRcApiRouter,
117
117
  createRcControlHandler: () => createRcControlHandler,
118
+ createRcCredentialStore: () => createRcCredentialStore,
118
119
  createRcEventFanout: () => createRcEventFanout,
119
120
  createRcSessionTracker: () => createRcSessionTracker,
120
121
  createRcStreamHub: () => createRcStreamHub,
@@ -3029,8 +3030,8 @@ function parseConnectTarget(authority) {
3029
3030
  function isInterceptedHost(host, interceptHosts) {
3030
3031
  return interceptHosts.includes(host);
3031
3032
  }
3032
- function servedByPipeline(path29) {
3033
- return path29?.startsWith(ROUTED_PATH_PREFIX) === true;
3033
+ function servedByPipeline(path30) {
3034
+ return path30?.startsWith(ROUTED_PATH_PREFIX) === true;
3034
3035
  }
3035
3036
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
3036
3037
  "connection",
@@ -3554,13 +3555,18 @@ function createRcSessionTracker(deps) {
3554
3555
  entries.set(id, record);
3555
3556
  return record;
3556
3557
  };
3558
+ const persistCredential = (entry) => {
3559
+ if (entry.oauthAuthorization !== void 0) {
3560
+ deps.credentialStore?.write(entry.id, { authorization: entry.oauthAuthorization, anthropicVersion: entry.anthropicVersion, anthropicClientPlatform: entry.anthropicClientPlatform });
3561
+ }
3562
+ };
3557
3563
  const observeExchange = (request4) => {
3558
3564
  const method = (request4.method ?? "").toUpperCase();
3559
- const path29 = new URL(request4.url ?? "/", "http://127.0.0.1").pathname;
3560
- if (!path29.startsWith(RC_SESSIONS_PATH_PREFIX)) {
3565
+ const path30 = new URL(request4.url ?? "/", "http://127.0.0.1").pathname;
3566
+ if (!path30.startsWith(RC_SESSIONS_PATH_PREFIX)) {
3561
3567
  return void 0;
3562
3568
  }
3563
- const tail = path29.slice(RC_SESSIONS_PATH_PREFIX.length);
3569
+ const tail = path30.slice(RC_SESSIONS_PATH_PREFIX.length);
3564
3570
  const facts = {
3565
3571
  oauthAuthorization: oauthAuthorizationOf(request4.headers),
3566
3572
  anthropicVersion: singleHeader(request4.headers, "anthropic-version"),
@@ -3593,7 +3599,7 @@ function createRcSessionTracker(deps) {
3593
3599
  if (id2 === void 0) {
3594
3600
  return;
3595
3601
  }
3596
- birth(id2, facts);
3602
+ persistCredential(birth(id2, facts));
3597
3603
  }
3598
3604
  };
3599
3605
  }
@@ -3607,6 +3613,7 @@ function createRcSessionTracker(deps) {
3607
3613
  entry.oauthAuthorization = facts.oauthAuthorization ?? entry.oauthAuthorization;
3608
3614
  entry.anthropicVersion = facts.anthropicVersion ?? entry.anthropicVersion;
3609
3615
  entry.anthropicClientPlatform = facts.anthropicClientPlatform ?? entry.anthropicClientPlatform;
3616
+ persistCredential(entry);
3610
3617
  const bodyKind = method === "POST" && rest === `${id}/worker/events` ? "worker-events" : method === "POST" && rest === `${id}/events` ? "client-events" : method === "POST" && rest === `${id}/worker/heartbeat` ? "heartbeat" : method === "PUT" && rest === `${id}/worker` ? "worker-registration" : void 0;
3611
3618
  let chunks = [];
3612
3619
  let buffered = 0;
@@ -3660,6 +3667,7 @@ function createRcSessionTracker(deps) {
3660
3667
  },
3661
3668
  onResponse: (status, headers) => {
3662
3669
  if (singleHeader(headers, CONFLICT_REASON_HEADER) !== void 0 || archiving && isSuccessful(status)) {
3670
+ deps.credentialStore?.remove(id);
3663
3671
  expire(id);
3664
3672
  return;
3665
3673
  }
@@ -3692,7 +3700,18 @@ function createRcSessionTracker(deps) {
3692
3700
  },
3693
3701
  credentialOf: (sessionId) => {
3694
3702
  const entry = entries.get(sessionId);
3695
- return entry === void 0 ? void 0 : { authorization: entry.oauthAuthorization, anthropicVersion: entry.anthropicVersion, anthropicClientPlatform: entry.anthropicClientPlatform };
3703
+ if (entry === void 0) {
3704
+ return void 0;
3705
+ }
3706
+ if (entry.oauthAuthorization === void 0 && deps.credentialStore !== void 0) {
3707
+ const persisted = deps.credentialStore.read(sessionId);
3708
+ if (persisted?.authorization !== void 0) {
3709
+ entry.oauthAuthorization = persisted.authorization;
3710
+ entry.anthropicVersion = entry.anthropicVersion ?? persisted.anthropicVersion;
3711
+ entry.anthropicClientPlatform = entry.anthropicClientPlatform ?? persisted.anthropicClientPlatform;
3712
+ }
3713
+ }
3714
+ return { authorization: entry.oauthAuthorization, anthropicVersion: entry.anthropicVersion, anthropicClientPlatform: entry.anthropicClientPlatform };
3696
3715
  },
3697
3716
  noteSequenceNums: (sessionId, sequenceNums) => {
3698
3717
  const entry = entries.get(sessionId);
@@ -4308,9 +4327,9 @@ function sequenceNumsOfBody(body) {
4308
4327
  }
4309
4328
  function frontDoorRcControl(transport, token) {
4310
4329
  const headers = { authorization: `Bearer ${token}` };
4311
- const listAnswerOf = async (path29, what) => {
4330
+ const listAnswerOf = async (path30, what) => {
4312
4331
  try {
4313
- return await transport.request({ method: "GET", path: path29, headers });
4332
+ return await transport.request({ method: "GET", path: path30, headers });
4314
4333
  } catch (error) {
4315
4334
  throw new Error(`${what}: could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
4316
4335
  }
@@ -4382,10 +4401,10 @@ function frontDoorRcControl(transport, token) {
4382
4401
  }
4383
4402
  return pending;
4384
4403
  };
4385
- const writeOf = async (path29, body, describeFailure) => {
4404
+ const writeOf = async (path30, body, describeFailure) => {
4386
4405
  let answer;
4387
4406
  try {
4388
- answer = await transport.request({ method: "POST", path: path29, headers: { ...headers, "content-type": "application/json" }, body });
4407
+ answer = await transport.request({ method: "POST", path: path30, headers: { ...headers, "content-type": "application/json" }, body });
4389
4408
  } catch (error) {
4390
4409
  return { ok: false, message: `could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}` };
4391
4410
  }
@@ -4433,15 +4452,27 @@ var SUCCESS_STATUS_MAX_EXCLUSIVE2 = 300;
4433
4452
  function isSuccessful2(status) {
4434
4453
  return status >= HTTP_STATUS.ok && status < SUCCESS_STATUS_MAX_EXCLUSIVE2;
4435
4454
  }
4436
- var UPSTREAM_LOCAL_PORT_START = 47900;
4437
- var UPSTREAM_LOCAL_PORT_END = 47919;
4438
- var UPSTREAM_LOCAL_PORT_COUNT = UPSTREAM_LOCAL_PORT_END - UPSTREAM_LOCAL_PORT_START + 1;
4439
- var nextUpstreamLocalPort = UPSTREAM_LOCAL_PORT_START;
4440
- function upstreamLocalPort() {
4441
- const port = nextUpstreamLocalPort;
4442
- nextUpstreamLocalPort = nextUpstreamLocalPort === UPSTREAM_LOCAL_PORT_END ? UPSTREAM_LOCAL_PORT_START : nextUpstreamLocalPort + 1;
4443
- return port;
4444
- }
4455
+ var SourcePortRange = class {
4456
+ constructor(start, end) {
4457
+ this.start = start;
4458
+ this.end = end;
4459
+ this.count = end - start + 1;
4460
+ this.next = start;
4461
+ }
4462
+ start;
4463
+ end;
4464
+ count;
4465
+ next;
4466
+ /** The next port in rotation, wrapping from the end back to the start. */
4467
+ take() {
4468
+ const port = this.next;
4469
+ this.next = this.next === this.end ? this.start : this.next + 1;
4470
+ return port;
4471
+ }
4472
+ };
4473
+ var DOOR_SOURCE_PORT_START = 47900;
4474
+ var DOOR_SOURCE_PORT_END = 47919;
4475
+ var DOOR_SOURCE_PORTS = new SourcePortRange(DOOR_SOURCE_PORT_START, DOOR_SOURCE_PORT_END);
4445
4476
  var realAddressLookup = (host, _options, callback) => {
4446
4477
  if (net2.isIP(host) !== 0) {
4447
4478
  callback(null, [{ address: host, family: net2.isIP(host) }]);
@@ -4479,14 +4510,14 @@ function dialTarget(options, defaultPort) {
4479
4510
  function literalDial(target) {
4480
4511
  return net2.connect({ host: target.host, port: target.port });
4481
4512
  }
4482
- async function reservedDial(target) {
4513
+ async function reservedDial(target, ports) {
4483
4514
  for (let attempt = 0; ; attempt += 1) {
4484
- const outcome = await dialOnce({ host: target.host, port: target.port, localPort: upstreamLocalPort(), lookup: realAddressLookup });
4515
+ const outcome = await dialOnce({ host: target.host, port: target.port, localPort: ports.take(), lookup: realAddressLookup });
4485
4516
  if (outcome.error === null) {
4486
4517
  return outcome;
4487
4518
  }
4488
4519
  const held = outcome.error.code !== void 0 && HELD_PORT_ERRNOS.has(outcome.error.code);
4489
- if (!held || attempt === UPSTREAM_LOCAL_PORT_COUNT - 1) {
4520
+ if (!held || attempt === ports.count - 1) {
4490
4521
  return outcome;
4491
4522
  }
4492
4523
  }
@@ -4495,26 +4526,36 @@ function requestServername(options, fallback) {
4495
4526
  return "servername" in options && typeof options.servername === "string" && options.servername !== "" ? options.servername : fallback;
4496
4527
  }
4497
4528
  var ExemptHttpAgent = class extends http.Agent {
4529
+ constructor(ports = DOOR_SOURCE_PORTS) {
4530
+ super();
4531
+ this.ports = ports;
4532
+ }
4533
+ ports;
4498
4534
  // A reserved-port dial that has to retry cannot produce its socket synchronously, so it settles first and arrives through the callback (node's documented asynchronous createConnection form); a literal dial has nothing to retry and keeps node's own synchronous shape.
4499
4535
  createConnection(options, oncreate) {
4500
4536
  const target = dialTarget(options, HTTP_PORT);
4501
4537
  if (net2.isIP(target.host) !== 0) {
4502
4538
  return literalDial(target);
4503
4539
  }
4504
- void reservedDial(target).then((outcome) => {
4540
+ void reservedDial(target, this.ports).then((outcome) => {
4505
4541
  oncreate?.(outcome.error, outcome.socket);
4506
4542
  });
4507
4543
  return void 0;
4508
4544
  }
4509
4545
  };
4510
4546
  var ExemptTlsAgent = class extends https2.Agent {
4547
+ constructor(ports = DOOR_SOURCE_PORTS) {
4548
+ super();
4549
+ this.ports = ports;
4550
+ }
4551
+ ports;
4511
4552
  // The same split as the plain sibling: a literal dial wraps TLS around the socket node's own agent would have returned, a reserved dial settles (retries included) first and arrives through the callback, which is exactly where node's own agent wraps its own dials.
4512
4553
  createConnection(options, oncreate) {
4513
4554
  const target = dialTarget(options, HTTPS_PORT);
4514
4555
  if (net2.isIP(target.host) !== 0) {
4515
4556
  return tls.connect({ socket: literalDial(target), servername: requestServername(options, target.host), ...tlsFacts(options) });
4516
4557
  }
4517
- void reservedDial(target).then((outcome) => {
4558
+ void reservedDial(target, this.ports).then((outcome) => {
4518
4559
  if (outcome.error !== null) {
4519
4560
  oncreate?.(outcome.error, outcome.socket);
4520
4561
  return;
@@ -4575,12 +4616,12 @@ var NO_CHUNKS = {
4575
4616
  };
4576
4617
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
4577
4618
  const agent = new ExemptTlsAgent();
4578
- const request4 = async (method, path29, headers, body, signal) => await new Promise((resolve, reject) => {
4619
+ const request4 = async (method, path30, headers, body, signal) => await new Promise((resolve, reject) => {
4579
4620
  const options = {
4580
4621
  host: target.host,
4581
4622
  port: target.port,
4582
4623
  method,
4583
- path: path29,
4624
+ path: path30,
4584
4625
  // The Host header names the host whose API this is, not the address dialled: a redirected test dials a loopback stand-in while still speaking to the API host by name, exactly as the forwarded paths present their SNI.
4585
4626
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
4586
4627
  agent,
@@ -4617,9 +4658,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
4617
4658
  return { status, body: await readAll(response) };
4618
4659
  },
4619
4660
  openStream: async (sessionId, headers, resume, signal) => {
4620
- const path29 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
4661
+ const path30 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
4621
4662
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
4622
- const { status, response } = await request4("GET", path29, streamHeaders, void 0, signal);
4663
+ const { status, response } = await request4("GET", path30, streamHeaders, void 0, signal);
4623
4664
  if (!isSuccessful2(status)) {
4624
4665
  await readAll(response);
4625
4666
  return { status, chunks: NO_CHUNKS };
@@ -4628,9 +4669,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
4628
4669
  }
4629
4670
  };
4630
4671
  }
4631
- function realConnectEffects() {
4632
- const plainAgent = new ExemptHttpAgent();
4633
- const tlsAgent = new ExemptTlsAgent();
4672
+ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
4673
+ const plainAgent = new ExemptHttpAgent(ports);
4674
+ const tlsAgent = new ExemptTlsAgent(ports);
4634
4675
  const listenOnce = async (port, onSocket) => await new Promise((resolve, reject) => {
4635
4676
  const accepted = /* @__PURE__ */ new Set();
4636
4677
  const server = net2.createServer((socket) => {
@@ -4748,7 +4789,7 @@ function realConnectEffects() {
4748
4789
  };
4749
4790
  },
4750
4791
  connectTlsUpstream: async (host, port, clientAlpn) => {
4751
- const dialled = await reservedDial({ host, port });
4792
+ const dialled = await reservedDial({ host, port }, ports);
4752
4793
  if (dialled.error !== null) {
4753
4794
  throw dialled.error;
4754
4795
  }
@@ -4830,6 +4871,64 @@ function realConnectEffects() {
4830
4871
  };
4831
4872
  }
4832
4873
 
4874
+ // src/frontdoor/rcCredentialStore.ts
4875
+ var import_node_path9 = __toESM(require("node:path"), 1);
4876
+ function isSafeSessionId(sessionId) {
4877
+ return /^[A-Za-z0-9_-]+$/.test(sessionId);
4878
+ }
4879
+ function isRecord3(value) {
4880
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4881
+ }
4882
+ function credentialOfJson(parsed) {
4883
+ if (!isRecord3(parsed)) {
4884
+ return void 0;
4885
+ }
4886
+ const { authorization, anthropicVersion, anthropicClientPlatform } = parsed;
4887
+ if (typeof authorization !== "string" || authorization === "") {
4888
+ return void 0;
4889
+ }
4890
+ return {
4891
+ authorization,
4892
+ anthropicVersion: typeof anthropicVersion === "string" ? anthropicVersion : void 0,
4893
+ anthropicClientPlatform: typeof anthropicClientPlatform === "string" ? anthropicClientPlatform : void 0
4894
+ };
4895
+ }
4896
+ function createRcCredentialStore(fs12, dir) {
4897
+ fs12.mkdirPrivate(dir);
4898
+ const fileFor = (sessionId) => import_node_path9.default.join(dir, `${sessionId}.json`);
4899
+ return {
4900
+ read: (sessionId) => {
4901
+ if (!isSafeSessionId(sessionId)) {
4902
+ return void 0;
4903
+ }
4904
+ const raw = fs12.readFileUtf8(fileFor(sessionId));
4905
+ if (raw === void 0) {
4906
+ return void 0;
4907
+ }
4908
+ let parsed;
4909
+ try {
4910
+ parsed = JSON.parse(raw);
4911
+ } catch {
4912
+ return void 0;
4913
+ }
4914
+ return credentialOfJson(parsed);
4915
+ },
4916
+ write: (sessionId, credential) => {
4917
+ if (!isSafeSessionId(sessionId)) {
4918
+ return;
4919
+ }
4920
+ fs12.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(credential, null, 2)}
4921
+ `);
4922
+ },
4923
+ remove: (sessionId) => {
4924
+ if (!isSafeSessionId(sessionId)) {
4925
+ return;
4926
+ }
4927
+ fs12.removeRecursive(fileFor(sessionId));
4928
+ }
4929
+ };
4930
+ }
4931
+
4833
4932
  // src/frontdoor/rcApi.ts
4834
4933
  var import_client = require("@orpc/client");
4835
4934
  var import_fetch = require("@orpc/client/fetch");
@@ -5087,7 +5186,7 @@ function createSseParser() {
5087
5186
  }
5088
5187
  };
5089
5188
  }
5090
- function isRecord3(value) {
5189
+ function isRecord4(value) {
5091
5190
  return typeof value === "object" && value !== null && !Array.isArray(value);
5092
5191
  }
5093
5192
  function sequenceNumOf(value) {
@@ -5109,7 +5208,7 @@ function parseRcStreamEnvelope(parsed) {
5109
5208
  } catch {
5110
5209
  return void 0;
5111
5210
  }
5112
- if (!isRecord3(data)) {
5211
+ if (!isRecord4(data)) {
5113
5212
  return void 0;
5114
5213
  }
5115
5214
  const eventType = data.event_type;
@@ -5198,6 +5297,7 @@ function createRcStreamHub(deps) {
5198
5297
  if (!isSuccessful3(answer.status)) {
5199
5298
  throw new Error(`the client read stream answered HTTP ${String(answer.status)}`);
5200
5299
  }
5300
+ deps.log?.(`rc stream ${attachment.sessionId}: attached as client ${attachment.clientId}${resume === void 0 ? ", reading from the stream's own head" : `, resuming after sequence number ${String(resume.fromSequenceNum)}`}`);
5201
5301
  const parser = createSseParser();
5202
5302
  for await (const chunk of answer.chunks) {
5203
5303
  attachment.controller.signal.throwIfAborted();
@@ -5221,6 +5321,7 @@ function createRcStreamHub(deps) {
5221
5321
  const live = deps.trackedSessions().includes(attachment.sessionId);
5222
5322
  const credential = deps.credentialOf(attachment.sessionId);
5223
5323
  if (!live || credential?.authorization === void 0) {
5324
+ deps.log?.(`rc stream ${attachment.sessionId}: the attachment ended (${live ? "the session's client credential is no longer known" : "the tracker gave up on the session"})`);
5224
5325
  if (attachments.get(attachment.sessionId) === attachment) {
5225
5326
  attachments.delete(attachment.sessionId);
5226
5327
  }
@@ -5242,6 +5343,7 @@ function createRcStreamHub(deps) {
5242
5343
  return;
5243
5344
  }
5244
5345
  if (outcome === "dropped") {
5346
+ deps.log?.(`rc stream ${attachment.sessionId}: the stream ended of its own accord, reconnecting`);
5245
5347
  retriedUnauthorized = false;
5246
5348
  continue;
5247
5349
  }
@@ -5291,7 +5393,7 @@ var import_node_crypto7 = require("node:crypto");
5291
5393
 
5292
5394
  // src/headroom/state.ts
5293
5395
  var import_node_crypto6 = require("node:crypto");
5294
- var import_node_path9 = __toESM(require("node:path"), 1);
5396
+ var import_node_path10 = __toESM(require("node:path"), 1);
5295
5397
  var import_zod5 = require("zod");
5296
5398
  var HEADROOM_ANTHROPIC_UPSTREAM = "https://api.anthropic.com";
5297
5399
  var HEADROOM_STATE_SCHEMA_VERSION = 2;
@@ -5332,7 +5434,7 @@ function readHeadroomState(fs12, stateFile) {
5332
5434
  }
5333
5435
  }
5334
5436
  function writeHeadroomState(fs12, stateFile, state) {
5335
- fs12.mkdirp(import_node_path9.default.dirname(stateFile));
5437
+ fs12.mkdirp(import_node_path10.default.dirname(stateFile));
5336
5438
  fs12.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
5337
5439
  `);
5338
5440
  }
@@ -5360,7 +5462,7 @@ function readAllProviders(fs12, providersDir) {
5360
5462
  continue;
5361
5463
  }
5362
5464
  try {
5363
- const parsed = parseJson(fs12.readFileUtf8(import_node_path9.default.join(providersDir, name)), ProviderSchema);
5465
+ const parsed = parseJson(fs12.readFileUtf8(import_node_path10.default.join(providersDir, name)), ProviderSchema);
5364
5466
  if (parsed !== void 0) {
5365
5467
  result.push({ name: name.slice(0, -".json".length), provider: parsed });
5366
5468
  }
@@ -5372,11 +5474,11 @@ function readAllProviders(fs12, providersDir) {
5372
5474
  }
5373
5475
  function writeSession(fs12, sessionsDir, session) {
5374
5476
  fs12.mkdirp(sessionsDir);
5375
- fs12.writeFileUtf8(import_node_path9.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
5477
+ fs12.writeFileUtf8(import_node_path10.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
5376
5478
  `);
5377
5479
  }
5378
5480
  function removeSession(fs12, sessionsDir, pid) {
5379
- fs12.removeRecursive(import_node_path9.default.join(sessionsDir, `${String(pid)}.json`));
5481
+ fs12.removeRecursive(import_node_path10.default.join(sessionsDir, `${String(pid)}.json`));
5380
5482
  }
5381
5483
  function listSessions(fs12, sessionsDir) {
5382
5484
  const sessions = [];
@@ -5385,7 +5487,7 @@ function listSessions(fs12, sessionsDir) {
5385
5487
  continue;
5386
5488
  }
5387
5489
  try {
5388
- const parsed = parseJson(fs12.readFileUtf8(import_node_path9.default.join(sessionsDir, name)), HeadroomSessionSchema);
5490
+ const parsed = parseJson(fs12.readFileUtf8(import_node_path10.default.join(sessionsDir, name)), HeadroomSessionSchema);
5389
5491
  if (parsed !== void 0) {
5390
5492
  sessions.push(parsed);
5391
5493
  }
@@ -5490,10 +5592,10 @@ function ensureFrontDoor(params) {
5490
5592
  }
5491
5593
 
5492
5594
  // src/usage/read.ts
5493
- var import_node_path11 = __toESM(require("node:path"), 1);
5595
+ var import_node_path12 = __toESM(require("node:path"), 1);
5494
5596
 
5495
5597
  // src/usage/account.ts
5496
- var import_node_path10 = __toESM(require("node:path"), 1);
5598
+ var import_node_path11 = __toESM(require("node:path"), 1);
5497
5599
 
5498
5600
  // src/usage/schema.ts
5499
5601
  var import_zod6 = require("zod");
@@ -5659,7 +5761,7 @@ function isIdentityName(name) {
5659
5761
  return IdentitySchema.shape.name.safeParse(name).success;
5660
5762
  }
5661
5763
  function claudeJsonPath(identitiesDir, identity) {
5662
- return import_node_path10.default.join(identitiesDir, identity, CLAUDE_JSON);
5764
+ return import_node_path11.default.join(identitiesDir, identity, CLAUDE_JSON);
5663
5765
  }
5664
5766
  function readAccountMetadata(fs12, identitiesDir, identity) {
5665
5767
  if (!isIdentityName(identity)) {
@@ -5718,7 +5820,7 @@ function readUsageLog(fs12, logDir, options = {}) {
5718
5820
  if (sinceMs !== void 0 && segment.endsAt <= sinceMs) {
5719
5821
  continue;
5720
5822
  }
5721
- const contents = fs12.readFileUtf8(import_node_path11.default.join(logDir, segment.name));
5823
+ const contents = fs12.readFileUtf8(import_node_path12.default.join(logDir, segment.name));
5722
5824
  if (contents === void 0) {
5723
5825
  continue;
5724
5826
  }
@@ -5760,7 +5862,7 @@ function snapshotPath(snapshotsDir, identity) {
5760
5862
  if (!isIdentityName(identity)) {
5761
5863
  throw new Error(`"${identity}" is not a valid identity name.`);
5762
5864
  }
5763
- return import_node_path11.default.join(snapshotsDir, `${identity}.json`);
5865
+ return import_node_path12.default.join(snapshotsDir, `${identity}.json`);
5764
5866
  }
5765
5867
  function readUsageSnapshot(fs12, snapshotsDir, identity) {
5766
5868
  const file = snapshotPath(snapshotsDir, identity);
@@ -6094,7 +6196,7 @@ function rankPool(input) {
6094
6196
  }
6095
6197
 
6096
6198
  // src/usage/poolPick.ts
6097
- var import_node_path12 = __toESM(require("node:path"), 1);
6199
+ var import_node_path13 = __toESM(require("node:path"), 1);
6098
6200
  var import_zod9 = require("zod");
6099
6201
 
6100
6202
  // src/usage/store.ts
@@ -6161,13 +6263,13 @@ function recordStickyPick(fs12, picksFile, directory, identity, nowMs) {
6161
6263
  const current = readPicksFile(fs12, picksFile).file.picks;
6162
6264
  const kept = Object.entries(current).filter(([, entry]) => nowMs - Date.parse(entry.at) <= USAGE_RETENTION_MS);
6163
6265
  const next = { schemaVersion: SCHEMA_VERSION, picks: { ...Object.fromEntries(kept), [directory]: { identity, at: new Date(nowMs).toISOString() } } };
6164
- fs12.mkdirPrivate(import_node_path12.default.dirname(picksFile));
6266
+ fs12.mkdirPrivate(import_node_path13.default.dirname(picksFile));
6165
6267
  fs12.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
6166
6268
  `);
6167
6269
  }
6168
6270
 
6169
6271
  // src/launcher/identity.ts
6170
- var import_node_path13 = __toESM(require("node:path"), 1);
6272
+ var import_node_path14 = __toESM(require("node:path"), 1);
6171
6273
  function poolNameOf(selector) {
6172
6274
  return selector.startsWith(POOL_SELECTOR_PREFIX) ? selector.slice(POOL_SELECTOR_PREFIX.length) : void 0;
6173
6275
  }
@@ -6216,7 +6318,7 @@ function decideConfigProfile(params) {
6216
6318
  return { source: "none" };
6217
6319
  }
6218
6320
  function loadIdentity(identitiesDir, name, fs12) {
6219
- return loadConfigFile(import_node_path13.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs12.readConfigFile);
6321
+ return loadConfigFile(import_node_path14.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs12.readConfigFile);
6220
6322
  }
6221
6323
 
6222
6324
  // src/launcher/pool.ts
@@ -6431,7 +6533,7 @@ function hashSettings(settings) {
6431
6533
  }
6432
6534
 
6433
6535
  // src/headroom/socket.ts
6434
- var import_node_path14 = __toESM(require("node:path"), 1);
6536
+ var import_node_path15 = __toESM(require("node:path"), 1);
6435
6537
  var GROUP_OR_OTHER_BITS = 63;
6436
6538
  var OCTAL_RADIX = 8;
6437
6539
  var MODE_DIGITS = 4;
@@ -6440,7 +6542,7 @@ var HEADROOM_SOCKET_NAME = /^(\d+)\.sock$/;
6440
6542
  var UNIX_SOCKET_PATH_MAX_BYTES = 103;
6441
6543
  var PLATFORMS_WITHOUT_UNIX_SOCKETS = ["win32"];
6442
6544
  function headroomSocketPath(paths, supervisorPid) {
6443
- return import_node_path14.default.join(paths.headroomSocketDir, `${String(supervisorPid)}${HEADROOM_SOCKET_SUFFIX}`);
6545
+ return import_node_path15.default.join(paths.headroomSocketDir, `${String(supervisorPid)}${HEADROOM_SOCKET_SUFFIX}`);
6444
6546
  }
6445
6547
  function platformRefusal(platform) {
6446
6548
  return PLATFORMS_WITHOUT_UNIX_SOCKETS.includes(platform) ? `headroom routing needs a unix domain socket, which headroom cannot serve on ${platform}; agent-shim never falls back to a TCP port for this hop` : void 0;
@@ -6489,7 +6591,7 @@ function pruneStaleHeadroomSockets(fs12, paths, isRunning) {
6489
6591
  if (pid === void 0 || isRunning(Number.parseInt(pid, 10))) {
6490
6592
  continue;
6491
6593
  }
6492
- fs12.removeRecursive(import_node_path14.default.join(paths.headroomSocketDir, name));
6594
+ fs12.removeRecursive(import_node_path15.default.join(paths.headroomSocketDir, name));
6493
6595
  removed.push(name);
6494
6596
  }
6495
6597
  return removed;
@@ -6813,14 +6915,14 @@ function evaluateAmbientCredentialGuard(params) {
6813
6915
  // src/paths.ts
6814
6916
  var import_node_fs2 = __toESM(require("node:fs"), 1);
6815
6917
  var import_node_os2 = __toESM(require("node:os"), 1);
6816
- var import_node_path15 = __toESM(require("node:path"), 1);
6918
+ var import_node_path16 = __toESM(require("node:path"), 1);
6817
6919
  function resolveAgentShimHome(env = process.env, home = import_node_os2.default.homedir(), isDirectory = isExistingDirectory) {
6818
6920
  const fromEnv = env.AGENT_SHIM_HOME;
6819
6921
  if (fromEnv !== void 0 && fromEnv !== "") {
6820
6922
  return fromEnv;
6821
6923
  }
6822
- const current = import_node_path15.default.join(home, HOME_DIRNAME);
6823
- const legacy = import_node_path15.default.join(home, LEGACY_HOME_DIRNAME);
6924
+ const current = import_node_path16.default.join(home, HOME_DIRNAME);
6925
+ const legacy = import_node_path16.default.join(home, LEGACY_HOME_DIRNAME);
6824
6926
  return !isDirectory(current) && isDirectory(legacy) ? legacy : current;
6825
6927
  }
6826
6928
  function isExistingDirectory(candidate) {
@@ -6831,40 +6933,41 @@ function resolveClaudeHome() {
6831
6933
  if (fromEnv !== void 0 && fromEnv !== "") {
6832
6934
  return fromEnv;
6833
6935
  }
6834
- return import_node_path15.default.join(import_node_os2.default.homedir(), ".claude");
6936
+ return import_node_path16.default.join(import_node_os2.default.homedir(), ".claude");
6835
6937
  }
6836
6938
  function buildLayoutPaths(root) {
6837
6939
  return {
6838
6940
  root,
6839
- identitiesDir: import_node_path15.default.join(root, "identities"),
6840
- configProfilesDir: import_node_path15.default.join(root, "config-profiles"),
6841
- providersDir: import_node_path15.default.join(root, "providers"),
6842
- directoryRulesFile: import_node_path15.default.join(root, "directory-rules.json"),
6843
- activeIdentityFile: import_node_path15.default.join(root, "active-identity"),
6844
- globalConfigFile: import_node_path15.default.join(root, "config.json"),
6845
- categoriesLocalFile: import_node_path15.default.join(root, "categories.local.json"),
6846
- claudeShimFile: import_node_path15.default.join(root, "claude-shim.json"),
6847
- headroomDir: import_node_path15.default.join(root, "headroom"),
6848
- headroomStateFile: import_node_path15.default.join(root, "headroom", `state.v${String(HEADROOM_STATE_SCHEMA_VERSION)}.json`),
6849
- headroomSocketDir: import_node_path15.default.join(root, "headroom", "run"),
6850
- headroomLockFile: import_node_path15.default.join(root, "headroom", "start.lock"),
6851
- headroomSessionsDir: import_node_path15.default.join(root, "headroom", "sessions"),
6852
- logsDir: import_node_path15.default.join(root, "logs"),
6853
- headroomLogPath: import_node_path15.default.join(root, "logs", "headroom.log"),
6854
- frontdoorDir: import_node_path15.default.join(root, "frontdoor"),
6855
- frontdoorCaDir: import_node_path15.default.join(root, "frontdoor", "ca"),
6856
- frontdoorCaCertFile: import_node_path15.default.join(root, "frontdoor", "ca", "ca.pem"),
6857
- frontdoorCaKeyFile: import_node_path15.default.join(root, "frontdoor", "ca", "ca.key"),
6858
- frontdoorCaBundlesDir: import_node_path15.default.join(root, "frontdoor", "ca", "bundles"),
6859
- frontdoorStateFile: import_node_path15.default.join(root, "frontdoor", "state.json"),
6860
- frontdoorLockFile: import_node_path15.default.join(root, "frontdoor", "start.lock"),
6861
- frontdoorControlTokenFile: import_node_path15.default.join(root, "frontdoor", "control-token"),
6862
- frontdoorSessionsDir: import_node_path15.default.join(root, "frontdoor", "sessions"),
6863
- frontdoorLogPath: import_node_path15.default.join(root, "logs", "frontdoor.log"),
6864
- usageDir: import_node_path15.default.join(root, "usage"),
6865
- usageLogDir: import_node_path15.default.join(root, "usage", "log"),
6866
- usageSnapshotsDir: import_node_path15.default.join(root, "usage", "snapshots"),
6867
- usagePicksFile: import_node_path15.default.join(root, "usage", "picks.json")
6941
+ identitiesDir: import_node_path16.default.join(root, "identities"),
6942
+ configProfilesDir: import_node_path16.default.join(root, "config-profiles"),
6943
+ providersDir: import_node_path16.default.join(root, "providers"),
6944
+ directoryRulesFile: import_node_path16.default.join(root, "directory-rules.json"),
6945
+ activeIdentityFile: import_node_path16.default.join(root, "active-identity"),
6946
+ globalConfigFile: import_node_path16.default.join(root, "config.json"),
6947
+ categoriesLocalFile: import_node_path16.default.join(root, "categories.local.json"),
6948
+ claudeShimFile: import_node_path16.default.join(root, "claude-shim.json"),
6949
+ headroomDir: import_node_path16.default.join(root, "headroom"),
6950
+ headroomStateFile: import_node_path16.default.join(root, "headroom", `state.v${String(HEADROOM_STATE_SCHEMA_VERSION)}.json`),
6951
+ headroomSocketDir: import_node_path16.default.join(root, "headroom", "run"),
6952
+ headroomLockFile: import_node_path16.default.join(root, "headroom", "start.lock"),
6953
+ headroomSessionsDir: import_node_path16.default.join(root, "headroom", "sessions"),
6954
+ logsDir: import_node_path16.default.join(root, "logs"),
6955
+ headroomLogPath: import_node_path16.default.join(root, "logs", "headroom.log"),
6956
+ frontdoorDir: import_node_path16.default.join(root, "frontdoor"),
6957
+ frontdoorCaDir: import_node_path16.default.join(root, "frontdoor", "ca"),
6958
+ frontdoorCaCertFile: import_node_path16.default.join(root, "frontdoor", "ca", "ca.pem"),
6959
+ frontdoorCaKeyFile: import_node_path16.default.join(root, "frontdoor", "ca", "ca.key"),
6960
+ frontdoorCaBundlesDir: import_node_path16.default.join(root, "frontdoor", "ca", "bundles"),
6961
+ frontdoorStateFile: import_node_path16.default.join(root, "frontdoor", "state.json"),
6962
+ frontdoorLockFile: import_node_path16.default.join(root, "frontdoor", "start.lock"),
6963
+ frontdoorControlTokenFile: import_node_path16.default.join(root, "frontdoor", "control-token"),
6964
+ frontdoorSessionsDir: import_node_path16.default.join(root, "frontdoor", "sessions"),
6965
+ frontdoorRcCredentialsDir: import_node_path16.default.join(root, "frontdoor", "rc-credentials"),
6966
+ frontdoorLogPath: import_node_path16.default.join(root, "logs", "frontdoor.log"),
6967
+ usageDir: import_node_path16.default.join(root, "usage"),
6968
+ usageLogDir: import_node_path16.default.join(root, "usage", "log"),
6969
+ usageSnapshotsDir: import_node_path16.default.join(root, "usage", "snapshots"),
6970
+ usagePicksFile: import_node_path16.default.join(root, "usage", "picks.json")
6868
6971
  };
6869
6972
  }
6870
6973
  function resolveLayoutPaths() {
@@ -6873,11 +6976,11 @@ function resolveLayoutPaths() {
6873
6976
 
6874
6977
  // src/identityStore.ts
6875
6978
  var import_node_fs4 = __toESM(require("node:fs"), 1);
6876
- var import_node_path17 = __toESM(require("node:path"), 1);
6979
+ var import_node_path18 = __toESM(require("node:path"), 1);
6877
6980
 
6878
6981
  // src/configProfilesStore.ts
6879
6982
  var import_node_fs3 = __toESM(require("node:fs"), 1);
6880
- var import_node_path16 = __toESM(require("node:path"), 1);
6983
+ var import_node_path17 = __toESM(require("node:path"), 1);
6881
6984
  var ProfileNotFoundError = class extends CliError {
6882
6985
  constructor(profileName) {
6883
6986
  super(`No configuration profile named "${profileName}". Run \`agent-shim profile add ${profileName}\` first.`);
@@ -6903,7 +7006,7 @@ var InvalidCategoryNameError = class extends CliError {
6903
7006
  categoryName;
6904
7007
  };
6905
7008
  function profileJsonPath(paths, name) {
6906
- return import_node_path16.default.join(paths.configProfilesDir, `${name}.json`);
7009
+ return import_node_path17.default.join(paths.configProfilesDir, `${name}.json`);
6907
7010
  }
6908
7011
  function profileExists(paths, name) {
6909
7012
  return import_node_fs3.default.existsSync(profileJsonPath(paths, name));
@@ -7091,7 +7194,7 @@ var InvalidIdentityNameError = class extends CliError {
7091
7194
  attemptedName;
7092
7195
  };
7093
7196
  function identityJsonPath(paths, name) {
7094
- return import_node_path17.default.join(paths.identitiesDir, name, "identity.json");
7197
+ return import_node_path18.default.join(paths.identitiesDir, name, "identity.json");
7095
7198
  }
7096
7199
  function identityExists(paths, name) {
7097
7200
  return import_node_fs4.default.existsSync(identityJsonPath(paths, name));
@@ -7192,7 +7295,7 @@ function setIdentityCredential(paths, identityName, change) {
7192
7295
  });
7193
7296
  }
7194
7297
  function belongsToIdentity(entry, name) {
7195
- return entry === name || entry === import_node_path17.default.basename(identityLockPath("", name)) || entry.startsWith(`.${name}.scratch.`) || entry.startsWith(`.${name}.previous.`);
7298
+ return entry === name || entry === import_node_path18.default.basename(identityLockPath("", name)) || entry.startsWith(`.${name}.scratch.`) || entry.startsWith(`.${name}.previous.`);
7196
7299
  }
7197
7300
  function removeIdentity(paths, name) {
7198
7301
  if (!identityExists(paths, name)) {
@@ -7200,7 +7303,7 @@ function removeIdentity(paths, name) {
7200
7303
  }
7201
7304
  for (const entry of import_node_fs4.default.readdirSync(paths.identitiesDir)) {
7202
7305
  if (belongsToIdentity(entry, name)) {
7203
- import_node_fs4.default.rmSync(import_node_path17.default.join(paths.identitiesDir, entry), { recursive: true, force: true });
7306
+ import_node_fs4.default.rmSync(import_node_path18.default.join(paths.identitiesDir, entry), { recursive: true, force: true });
7204
7307
  }
7205
7308
  }
7206
7309
  if (readActiveIdentity(paths) === name) {
@@ -7210,7 +7313,7 @@ function removeIdentity(paths, name) {
7210
7313
 
7211
7314
  // src/providersStore.ts
7212
7315
  var import_node_fs5 = __toESM(require("node:fs"), 1);
7213
- var import_node_path18 = __toESM(require("node:path"), 1);
7316
+ var import_node_path19 = __toESM(require("node:path"), 1);
7214
7317
 
7215
7318
  // src/credentialCache.ts
7216
7319
  var import_zod12 = require("zod");
@@ -7475,7 +7578,7 @@ var InvalidProviderNameError = class extends CliError {
7475
7578
  };
7476
7579
  var PROVIDER_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/;
7477
7580
  function providerJsonPath(paths, name) {
7478
- return import_node_path18.default.join(paths.providersDir, `${name}.json`);
7581
+ return import_node_path19.default.join(paths.providersDir, `${name}.json`);
7479
7582
  }
7480
7583
  function providerExists(paths, name) {
7481
7584
  return import_node_fs5.default.existsSync(providerJsonPath(paths, name));
@@ -7483,14 +7586,14 @@ function providerExists(paths, name) {
7483
7586
  var LEGACY_PROVIDER_FIELDS = ["tokenEnv", "tokenCommand", "authScheme"];
7484
7587
  var LEGACY_ENV_CREDENTIAL_KEYS = Object.values(CREDENTIAL_TARGET_VARS);
7485
7588
  var LEGACY_LITERAL_PLACEHOLDER = "<the value of env.ANTHROPIC_AUTH_TOKEN>";
7486
- function isRecord4(value) {
7589
+ function isRecord5(value) {
7487
7590
  return typeof value === "object" && value !== null && !Array.isArray(value);
7488
7591
  }
7489
7592
  function legacyProviderConversion(raw) {
7490
- if (!isRecord4(raw) || "credential" in raw) {
7593
+ if (!isRecord5(raw) || "credential" in raw) {
7491
7594
  return void 0;
7492
7595
  }
7493
- const env = isRecord4(raw.env) ? raw.env : void 0;
7596
+ const env = isRecord5(raw.env) ? raw.env : void 0;
7494
7597
  const legacyEnvKeys = env === void 0 ? [] : Object.keys(env).filter((key) => LEGACY_ENV_CREDENTIAL_KEYS.includes(key));
7495
7598
  const fields = [...LEGACY_PROVIDER_FIELDS.filter((field) => field in raw), ...legacyEnvKeys.map((key) => `env.${key}`)];
7496
7599
  if (fields.length === 0) {
@@ -7551,7 +7654,7 @@ function readProvider(paths, name) {
7551
7654
  return parseProviderFile(filePath, raw);
7552
7655
  }
7553
7656
  function loadProvider(providersDir, name, port) {
7554
- const filePath = import_node_path18.default.join(providersDir, `${name}.json`);
7657
+ const filePath = import_node_path19.default.join(providersDir, `${name}.json`);
7555
7658
  const raw = port.readConfigFile(filePath);
7556
7659
  return raw === void 0 ? void 0 : parseProviderFile(filePath, raw);
7557
7660
  }
@@ -7806,21 +7909,21 @@ function removeDirectoryRule(paths, rulePath) {
7806
7909
  var import_node_os4 = __toESM(require("node:os"), 1);
7807
7910
 
7808
7911
  // src/launcher/cascade.ts
7809
- var import_node_path20 = __toESM(require("node:path"), 1);
7912
+ var import_node_path21 = __toESM(require("node:path"), 1);
7810
7913
 
7811
7914
  // src/pathNorm.ts
7812
- var import_node_path19 = __toESM(require("node:path"), 1);
7915
+ var import_node_path20 = __toESM(require("node:path"), 1);
7813
7916
  function expandTilde(value, home) {
7814
7917
  if (value === "~") {
7815
7918
  return home;
7816
7919
  }
7817
7920
  if (value.startsWith("~/")) {
7818
- return import_node_path19.default.join(home, value.slice(2));
7921
+ return import_node_path20.default.join(home, value.slice(2));
7819
7922
  }
7820
7923
  return value;
7821
7924
  }
7822
7925
  function normaliseRulePath(rulePath, home) {
7823
- return import_node_path19.default.resolve(expandTilde(rulePath, home));
7926
+ return import_node_path20.default.resolve(expandTilde(rulePath, home));
7824
7927
  }
7825
7928
 
7826
7929
  // src/launcher/cascade.ts
@@ -7830,7 +7933,7 @@ function loadCascadeInput(params) {
7830
7933
  const globalConfig = loadConfigFile(params.paths.globalConfigFile, GlobalConfigSchema, params.read);
7831
7934
  const directoryRules = loadConfigFile(params.paths.directoryRulesFile, DirectoryRulesSchema, params.read);
7832
7935
  const loadProfile = (name) => {
7833
- const filepath = import_node_path20.default.join(params.paths.configProfilesDir, `${name}.json`);
7936
+ const filepath = import_node_path21.default.join(params.paths.configProfilesDir, `${name}.json`);
7834
7937
  const loaded = loadConfigFile(filepath, ConfigProfileSchema, params.read);
7835
7938
  if (loaded === void 0) {
7836
7939
  return void 0;
@@ -7845,8 +7948,8 @@ function loadCascadeInput(params) {
7845
7948
  });
7846
7949
  const levels = [];
7847
7950
  for (const dir of dirs) {
7848
- const portable = loadConfigFile(import_node_path20.default.join(dir, PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(import_node_path20.default.join(dir, LEGACY_PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read);
7849
- const portableLocal = loadConfigFile(import_node_path20.default.join(dir, PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(import_node_path20.default.join(dir, LEGACY_PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read);
7951
+ const portable = loadConfigFile(import_node_path21.default.join(dir, PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(import_node_path21.default.join(dir, LEGACY_PORTABLE_CONFIG_FILENAME), PortableConfigSchema, params.read);
7952
+ const portableLocal = loadConfigFile(import_node_path21.default.join(dir, PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read) ?? loadConfigFile(import_node_path21.default.join(dir, LEGACY_PORTABLE_LOCAL_CONFIG_FILENAME), PortableConfigSchema, params.read);
7850
7953
  const rules = (directoryRules?.config.rules ?? []).map((rule, index) => ({ rule, index })).filter(({ rule }) => normaliseRulePath(rule.path, params.home) === dir).map(({ rule, index }) => {
7851
7954
  const entryOrder = directoryRules?.ruleEntryOrders[index];
7852
7955
  return {
@@ -7897,7 +8000,7 @@ function readDirectorySelections(loaded) {
7897
8000
  // src/realCredentialCache.ts
7898
8001
  var import_node_child_process = require("node:child_process");
7899
8002
  var import_node_fs6 = __toESM(require("node:fs"), 1);
7900
- var import_node_path21 = __toESM(require("node:path"), 1);
8003
+ var import_node_path22 = __toESM(require("node:path"), 1);
7901
8004
  var KEYCHAIN_CACHE_SERVICE = "agent-shim-credential-cache";
7902
8005
  var CACHE_DIR_MODE = 448;
7903
8006
  var CACHE_FILE_MODE = 384;
@@ -7924,8 +8027,8 @@ function security(args, stdin) {
7924
8027
  return { status: result.status, stdout: result.stdout };
7925
8028
  }
7926
8029
  function createRealCredentialCache(root) {
7927
- const dir = import_node_path21.default.join(root, "credential-cache");
7928
- const filePath = (owner) => import_node_path21.default.join(dir, cacheFileNameFor(owner));
8030
+ const dir = import_node_path22.default.join(root, "credential-cache");
8031
+ const filePath = (owner) => import_node_path22.default.join(dir, cacheFileNameFor(owner));
7929
8032
  return {
7930
8033
  read(store, owner) {
7931
8034
  if (store === "file") {
@@ -7977,7 +8080,7 @@ var import_node_child_process2 = require("node:child_process");
7977
8080
  var import_node_crypto9 = require("node:crypto");
7978
8081
  var import_node_fs7 = __toESM(require("node:fs"), 1);
7979
8082
  var import_node_os3 = __toESM(require("node:os"), 1);
7980
- var import_node_path22 = __toESM(require("node:path"), 1);
8083
+ var import_node_path23 = __toESM(require("node:path"), 1);
7981
8084
  var import_node_sea = require("node:sea");
7982
8085
  function isEnoent3(error) {
7983
8086
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
@@ -8136,7 +8239,7 @@ var realRunPort = {
8136
8239
  }
8137
8240
  };
8138
8241
  function expandHome2(filePath) {
8139
- return filePath.startsWith("~/") ? import_node_path22.default.join(import_node_os3.default.homedir(), filePath.slice(1)) : filePath;
8242
+ return filePath.startsWith("~/") ? import_node_path23.default.join(import_node_os3.default.homedir(), filePath.slice(1)) : filePath;
8140
8243
  }
8141
8244
  var MACOS_GUI_SESSION_MANAGER = "Aqua";
8142
8245
  function hasDesktopSession() {
@@ -8209,7 +8312,7 @@ function spawnDaemonThrough(executable) {
8209
8312
  return (paths, subcommand, logPath) => spawnDetachedDaemon({ command: executable, args: [subcommand] }, paths, subcommand, logPath);
8210
8313
  }
8211
8314
  function spawnDetachedDaemon(invocation, paths, subcommand, logPath) {
8212
- import_node_fs7.default.mkdirSync(import_node_path22.default.dirname(logPath), { recursive: true });
8315
+ import_node_fs7.default.mkdirSync(import_node_path23.default.dirname(logPath), { recursive: true });
8213
8316
  const logFd = import_node_fs7.default.openSync(logPath, "a");
8214
8317
  try {
8215
8318
  const child = (0, import_node_child_process2.spawn)(invocation.command, invocation.args, detachedDaemonSpawnOptions(logFd, { ...process.env, AGENT_SHIM_HOME: paths.root }));
@@ -8291,7 +8394,7 @@ function listVersionsDir(dir) {
8291
8394
  throw error;
8292
8395
  }
8293
8396
  return entries.filter((entry) => entry.isFile()).map((entry) => {
8294
- const fullPath = import_node_path22.default.join(dir, entry.name);
8397
+ const fullPath = import_node_path23.default.join(dir, entry.name);
8295
8398
  const stat = import_node_fs7.default.statSync(fullPath);
8296
8399
  return {
8297
8400
  name: entry.name,
@@ -8306,7 +8409,7 @@ function windowsPathExtensions(pathext) {
8306
8409
  return (pathext ?? WINDOWS_DEFAULT_PATHEXT).split(";").map((ext) => ext.trim()).filter((ext) => ext.length > 0);
8307
8410
  }
8308
8411
  function resolveExecutableCandidate(dir, name, env) {
8309
- const candidate = import_node_path22.default.join(dir, name);
8412
+ const candidate = import_node_path23.default.join(dir, name);
8310
8413
  if (env.platform === "win32") {
8311
8414
  const extensions = windowsPathExtensions(env.pathext);
8312
8415
  const alreadyHasRecognisedExtension = extensions.some((ext) => candidate.toLowerCase().endsWith(ext.toLowerCase()));
@@ -8355,13 +8458,13 @@ function resolveOwnExecutablePath(env) {
8355
8458
  if (env.argv1 !== void 0 && !env.argv1.includes("/") && !env.argv1.includes("\\")) {
8356
8459
  return searchPathForExecutable(env.pathDirs, env.argv1, env.findExecutableInDir) ?? env.execPath;
8357
8460
  }
8358
- const candidate = env.argv1 === void 0 ? env.execPath : import_node_path22.default.resolve(env.cwd, env.argv1);
8359
- const candidateDir = import_node_path22.default.dirname(candidate);
8360
- const candidateDirOnPath = env.pathDirs.some((dir) => import_node_path22.default.resolve(dir) === candidateDir);
8461
+ const candidate = env.argv1 === void 0 ? env.execPath : import_node_path23.default.resolve(env.cwd, env.argv1);
8462
+ const candidateDir = import_node_path23.default.dirname(candidate);
8463
+ const candidateDirOnPath = env.pathDirs.some((dir) => import_node_path23.default.resolve(dir) === candidateDir);
8361
8464
  if (candidateDirOnPath) {
8362
8465
  return candidate;
8363
8466
  }
8364
- const viaPath = searchPathForExecutable(env.pathDirs, import_node_path22.default.basename(candidate), env.findExecutableInDir);
8467
+ const viaPath = searchPathForExecutable(env.pathDirs, import_node_path23.default.basename(candidate), env.findExecutableInDir);
8365
8468
  return viaPath ?? candidate;
8366
8469
  }
8367
8470
  function realOwnExecutablePath() {
@@ -8369,7 +8472,7 @@ function realOwnExecutablePath() {
8369
8472
  argv1: process.argv[1],
8370
8473
  execPath: process.execPath,
8371
8474
  cwd: process.cwd(),
8372
- pathDirs: (process.env.PATH ?? "").split(import_node_path22.default.delimiter).filter((dir) => dir !== ""),
8475
+ pathDirs: (process.env.PATH ?? "").split(import_node_path23.default.delimiter).filter((dir) => dir !== ""),
8373
8476
  findExecutableInDir
8374
8477
  });
8375
8478
  }
@@ -8382,7 +8485,7 @@ function realContentSourcePath() {
8382
8485
  function realResolveClaudeBinary(isOwnBinary) {
8383
8486
  return (request4) => discoverClaudeBinary({
8384
8487
  listVersionsDir,
8385
- pathDirs: (process.env.PATH ?? "").split(import_node_path22.default.delimiter).filter((dir) => dir !== ""),
8488
+ pathDirs: (process.env.PATH ?? "").split(import_node_path23.default.delimiter).filter((dir) => dir !== ""),
8386
8489
  findExecutableInDir,
8387
8490
  isOwnBinary,
8388
8491
  ...request4?.version === void 0 ? {} : { version: request4.version }
@@ -8393,7 +8496,7 @@ function realInstalledClaudeVersions() {
8393
8496
  }
8394
8497
 
8395
8498
  // src/checkReport.ts
8396
- var import_node_path23 = __toESM(require("node:path"), 1);
8499
+ var import_node_path24 = __toESM(require("node:path"), 1);
8397
8500
  var import_zod13 = require("zod");
8398
8501
 
8399
8502
  // src/cli/bool.ts
@@ -8825,10 +8928,10 @@ function collectCheckReport(params) {
8825
8928
  }).input;
8826
8929
  const providerName = cascadeProviderName(cascade);
8827
8930
  const provider = providerName === void 0 ? void 0 : loadCheckProvider(paths, providerName);
8828
- const farmRoot = identityDecision.name === void 0 ? void 0 : import_node_path23.default.join(paths.identitiesDir, identityDecision.name);
8931
+ const farmRoot = identityDecision.name === void 0 ? void 0 : import_node_path24.default.join(paths.identitiesDir, identityDecision.name);
8829
8932
  const settingsFiles = {
8830
- "settings.json": realFsPort.readFileUtf8(import_node_path23.default.join(claudeHome, "settings.json")),
8831
- "settings.local.json": realFsPort.readFileUtf8(import_node_path23.default.join(claudeHome, "settings.local.json"))
8933
+ "settings.json": realFsPort.readFileUtf8(import_node_path24.default.join(claudeHome, "settings.json")),
8934
+ "settings.local.json": realFsPort.readFileUtf8(import_node_path24.default.join(claudeHome, "settings.local.json"))
8832
8935
  };
8833
8936
  const report = runCheck({
8834
8937
  cwd,
@@ -8860,7 +8963,7 @@ function collectCheckReport(params) {
8860
8963
 
8861
8964
  // src/claudeShim.ts
8862
8965
  var import_node_fs8 = __toESM(require("node:fs"), 1);
8863
- var import_node_path24 = __toESM(require("node:path"), 1);
8966
+ var import_node_path25 = __toESM(require("node:path"), 1);
8864
8967
  var import_zod14 = require("zod");
8865
8968
  var ClaudeShimStateSchema = import_zod14.z.strictObject({
8866
8969
  targetPath: import_zod14.z.string().min(1),
@@ -8872,10 +8975,10 @@ function commandFilename(ownExecutablePath, commandName) {
8872
8975
  }
8873
8976
  function resolveOwnBinaryCheck(paths, contentSourcePath) {
8874
8977
  const state = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
8875
- const recordedTarget = state === void 0 ? void 0 : import_node_path24.default.resolve(state.targetPath);
8978
+ const recordedTarget = state === void 0 ? void 0 : import_node_path25.default.resolve(state.targetPath);
8876
8979
  let ownStat;
8877
8980
  return (candidate) => {
8878
- if (recordedTarget !== void 0 && import_node_path24.default.resolve(candidate) === recordedTarget) {
8981
+ if (recordedTarget !== void 0 && import_node_path25.default.resolve(candidate) === recordedTarget) {
8879
8982
  return true;
8880
8983
  }
8881
8984
  ownStat ??= statOrUndefined(contentSourcePath);
@@ -8899,20 +9002,20 @@ function statOrUndefined(target) {
8899
9002
  }
8900
9003
  var nodeLinkFs = { link: import_node_fs8.default.linkSync, copyFile: import_node_fs8.default.copyFileSync, chmod: import_node_fs8.default.chmodSync };
8901
9004
  function findPathShadow(params) {
8902
- const resolvedTargetDir = import_node_path24.default.resolve(params.targetDir);
9005
+ const resolvedTargetDir = import_node_path25.default.resolve(params.targetDir);
8903
9006
  for (const dir of params.pathDirs) {
8904
9007
  const found = params.findExecutableInDir(dir, params.targetFilename);
8905
9008
  if (found === void 0) {
8906
9009
  continue;
8907
9010
  }
8908
- return import_node_path24.default.resolve(dir) === resolvedTargetDir ? { status: "ok" } : { status: "shadowed", by: found };
9011
+ return import_node_path25.default.resolve(dir) === resolvedTargetDir ? { status: "ok" } : { status: "shadowed", by: found };
8909
9012
  }
8910
- return params.pathDirs.some((dir) => import_node_path24.default.resolve(dir) === resolvedTargetDir) ? { status: "ok" } : { status: "not-on-path" };
9013
+ return params.pathDirs.some((dir) => import_node_path25.default.resolve(dir) === resolvedTargetDir) ? { status: "ok" } : { status: "not-on-path" };
8911
9014
  }
8912
9015
 
8913
9016
  // src/doctorReport.ts
8914
9017
  var import_node_fs9 = __toESM(require("node:fs"), 1);
8915
- var import_node_path25 = __toESM(require("node:path"), 1);
9018
+ var import_node_path26 = __toESM(require("node:path"), 1);
8916
9019
  function refinePathShadow(status, ownExecutablePath, realpath) {
8917
9020
  if (status.status !== "shadowed") {
8918
9021
  return status;
@@ -8936,7 +9039,7 @@ function validateJson(schema, input) {
8936
9039
  return { ok: true, data: result.data };
8937
9040
  }
8938
9041
  function pushPathResolution(push, resolution) {
8939
- const ownDir = import_node_path25.default.dirname(resolution.ownExecutablePath);
9042
+ const ownDir = import_node_path26.default.dirname(resolution.ownExecutablePath);
8940
9043
  switch (resolution.agentShim.status) {
8941
9044
  case "ok":
8942
9045
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -9012,14 +9115,14 @@ function pushProvider(push, entry, cacheEnv) {
9012
9115
  }
9013
9116
  function pushLegacyName(push, params) {
9014
9117
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
9015
- if (legacyVariables.length === 0 && import_node_path25.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
9118
+ if (legacyVariables.length === 0 && import_node_path26.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
9016
9119
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
9017
9120
  return;
9018
9121
  }
9019
9122
  for (const name of legacyVariables) {
9020
9123
  push("legacy-name", "warn", `${name} is the former name of ${name.replace(LEGACY_ENV_PREFIX, ENV_PREFIX)}. Rename it; the old name still works but is only a fallback.`, name);
9021
9124
  }
9022
- if (import_node_path25.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
9125
+ if (import_node_path26.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
9023
9126
  push(
9024
9127
  "legacy-name",
9025
9128
  "warn",
@@ -9338,18 +9441,18 @@ function collectDoctorReport(params) {
9338
9441
  const { paths } = params;
9339
9442
  const identityNames = import_node_fs9.default.existsSync(paths.identitiesDir) ? import_node_fs9.default.readdirSync(paths.identitiesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isIdentityDirectoryName(entry.name)).map((entry) => entry.name).sort() : [];
9340
9443
  const identities = identityNames.map((name) => {
9341
- const farmRoot = import_node_path25.default.join(paths.identitiesDir, name);
9342
- const identityPath = import_node_path25.default.join(farmRoot, "identity.json");
9444
+ const farmRoot = import_node_path26.default.join(paths.identitiesDir, name);
9445
+ const identityPath = import_node_path26.default.join(farmRoot, "identity.json");
9343
9446
  return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot };
9344
9447
  });
9345
9448
  const profileNames = import_node_fs9.default.existsSync(paths.configProfilesDir) ? import_node_fs9.default.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
9346
9449
  const configProfiles = profileNames.map((name) => {
9347
- const profilePath = import_node_path25.default.join(paths.configProfilesDir, `${name}.json`);
9450
+ const profilePath = import_node_path26.default.join(paths.configProfilesDir, `${name}.json`);
9348
9451
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
9349
9452
  });
9350
9453
  const providerNames = import_node_fs9.default.existsSync(paths.providersDir) ? import_node_fs9.default.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
9351
9454
  const providers = providerNames.map((name) => {
9352
- const providerPath = import_node_path25.default.join(paths.providersDir, `${name}.json`);
9455
+ const providerPath = import_node_path26.default.join(paths.providersDir, `${name}.json`);
9353
9456
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
9354
9457
  });
9355
9458
  const ownExecutablePath = realOwnExecutablePath();
@@ -9361,12 +9464,12 @@ function collectDoctorReport(params) {
9361
9464
  binaryDiscovery = { ok: false, message: error instanceof Error ? error.message : String(error) };
9362
9465
  }
9363
9466
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
9364
- const pathDirs = (params.env.PATH ?? "").split(import_node_path25.default.delimiter).filter((dir) => dir !== "");
9467
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path26.default.delimiter).filter((dir) => dir !== "");
9365
9468
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
9366
9469
  findPathShadow({
9367
9470
  pathDirs,
9368
- targetDir: import_node_path25.default.dirname(shimState.targetPath),
9369
- targetFilename: import_node_path25.default.basename(shimState.targetPath),
9471
+ targetDir: import_node_path26.default.dirname(shimState.targetPath),
9472
+ targetFilename: import_node_path26.default.basename(shimState.targetPath),
9370
9473
  findExecutableInDir
9371
9474
  }),
9372
9475
  shimState.targetPath,
@@ -9391,7 +9494,7 @@ function collectDoctorReport(params) {
9391
9494
  agentShim: refinePathShadow(
9392
9495
  findPathShadow({
9393
9496
  pathDirs,
9394
- targetDir: import_node_path25.default.dirname(ownExecutablePath),
9497
+ targetDir: import_node_path26.default.dirname(ownExecutablePath),
9395
9498
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
9396
9499
  findExecutableInDir
9397
9500
  }),
@@ -9412,7 +9515,7 @@ function collectDoctorReport(params) {
9412
9515
 
9413
9516
  // src/launcher.ts
9414
9517
  var import_node_crypto10 = require("node:crypto");
9415
- var import_node_path27 = __toESM(require("node:path"), 1);
9518
+ var import_node_path28 = __toESM(require("node:path"), 1);
9416
9519
 
9417
9520
  // src/launcher/argv.ts
9418
9521
  var ConflictingIdentityError = class extends UsageError {
@@ -9677,7 +9780,7 @@ function buildCliOverride(params) {
9677
9780
  }
9678
9781
 
9679
9782
  // src/launcher/flags.ts
9680
- var import_node_path26 = __toESM(require("node:path"), 1);
9783
+ var import_node_path27 = __toESM(require("node:path"), 1);
9681
9784
 
9682
9785
  // src/headroom/headers.ts
9683
9786
  function mergeAnthropicCustomHeaders(existing, additions) {
@@ -9747,7 +9850,7 @@ function buildEnv(params) {
9747
9850
  const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
9748
9851
  let providerCustomHeaders;
9749
9852
  if (!params.configDirEscapeHatch && params.resolvedIdentityName !== void 0) {
9750
- env.CLAUDE_CONFIG_DIR = import_node_path26.default.join(params.identitiesDir, params.resolvedIdentityName);
9853
+ env.CLAUDE_CONFIG_DIR = import_node_path27.default.join(params.identitiesDir, params.resolvedIdentityName);
9751
9854
  }
9752
9855
  if (params.provider !== void 0) {
9753
9856
  const providerEnv = params.provider.definition.env ?? {};
@@ -9908,7 +10011,7 @@ function prepareLaunch(params) {
9908
10011
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
9909
10012
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
9910
10013
  });
9911
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs12.readConfigFile(import_node_path27.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
10014
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs12.readConfigFile(import_node_path28.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
9912
10015
  log.error(
9913
10016
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
9914
10017
  );
@@ -10154,11 +10257,11 @@ function probeFrontDoorSync(port, caPem) {
10154
10257
 
10155
10258
  // src/frontdoor/trust.ts
10156
10259
  var import_node_crypto11 = require("node:crypto");
10157
- var import_node_path28 = __toESM(require("node:path"), 1);
10260
+ var import_node_path29 = __toESM(require("node:path"), 1);
10158
10261
  var BUNDLE_NAME_HEX_DIGITS = 16;
10159
10262
  function resolveTrustBundle(params) {
10160
10263
  const { caCertFile, bundlesDir, variable, inherited, fs: fs12 } = params;
10161
- if (inherited === void 0 || inherited === "" || import_node_path28.default.resolve(inherited) === import_node_path28.default.resolve(caCertFile)) {
10264
+ if (inherited === void 0 || inherited === "" || import_node_path29.default.resolve(inherited) === import_node_path29.default.resolve(caCertFile)) {
10162
10265
  return { path: caCertFile };
10163
10266
  }
10164
10267
  const caPem = fs12.readFileUtf8(caCertFile);
@@ -10176,7 +10279,7 @@ function resolveTrustBundle(params) {
10176
10279
  }
10177
10280
  const combined = `${inheritedPem.trimEnd()}
10178
10281
  ${caPem}`;
10179
- const bundle = import_node_path28.default.join(bundlesDir, `${(0, import_node_crypto11.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
10282
+ const bundle = import_node_path29.default.join(bundlesDir, `${(0, import_node_crypto11.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
10180
10283
  if (!fs12.exists(bundle)) {
10181
10284
  fs12.mkdirp(bundlesDir);
10182
10285
  fs12.writeFileAtomic(bundle, combined);
@@ -10404,6 +10507,7 @@ function prepareClaudeLaunch(options) {
10404
10507
  createRcApiNodeHandler,
10405
10508
  createRcApiRouter,
10406
10509
  createRcControlHandler,
10510
+ createRcCredentialStore,
10407
10511
  createRcEventFanout,
10408
10512
  createRcSessionTracker,
10409
10513
  createRcStreamHub,