claude-use 14.5.1 → 14.6.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
@@ -4462,13 +4462,31 @@ var init_capability = __esm({
4462
4462
  });
4463
4463
 
4464
4464
  // src/frontdoor/route.ts
4465
- var IDENTITY_HEADER, SESSION_HEADER, PROVIDER_HEADER, HEADROOM_FLAG_HEADER, PROJECT_ID_HEADER, AUTH_HEADER;
4465
+ function singleHeaderValue(value) {
4466
+ if (typeof value === "string") {
4467
+ return value;
4468
+ }
4469
+ if (Array.isArray(value)) {
4470
+ return value.join(", ");
4471
+ }
4472
+ return void 0;
4473
+ }
4474
+ function internalHeaderValue(headers, name) {
4475
+ for (const [key, value] of Object.entries(headers)) {
4476
+ if (key.toLowerCase() === name) {
4477
+ return singleHeaderValue(value);
4478
+ }
4479
+ }
4480
+ return void 0;
4481
+ }
4482
+ var IDENTITY_HEADER, SESSION_HEADER, PROVIDER_HEADER, SELF_HOSTED_HEADER, HEADROOM_FLAG_HEADER, PROJECT_ID_HEADER, AUTH_HEADER;
4466
4483
  var init_route = __esm({
4467
4484
  "src/frontdoor/route.ts"() {
4468
4485
  "use strict";
4469
4486
  IDENTITY_HEADER = "x-agent-shim-identity";
4470
4487
  SESSION_HEADER = "x-agent-shim-session";
4471
4488
  PROVIDER_HEADER = "x-agent-shim-provider";
4489
+ SELF_HOSTED_HEADER = "x-agent-shim-self-hosted";
4472
4490
  HEADROOM_FLAG_HEADER = "x-agent-shim-headroom";
4473
4491
  PROJECT_ID_HEADER = "x-headroom-project-id";
4474
4492
  AUTH_HEADER = "x-agent-shim-auth";
@@ -5480,7 +5498,7 @@ function pruneDeadFrontDoorDirectRecords(fs17, recordsDir, records, liveness) {
5480
5498
  }
5481
5499
  }
5482
5500
  function recordOf(details) {
5483
- return details === void 0 ? {} : { sessionId: details.sessionId, ...details.identity === void 0 ? {} : { identity: details.identity }, ...details.models === void 0 ? {} : { models: details.models } };
5501
+ return details === void 0 ? {} : { sessionId: details.sessionId, ...details.identity === void 0 ? {} : { identity: details.identity }, ...details.models === void 0 ? {} : { models: details.models }, ...details.configDir === void 0 ? {} : { configDir: details.configDir } };
5484
5502
  }
5485
5503
  function writeFrontDoorSession(fs17, sessionsDir, session) {
5486
5504
  fs17.mkdirPrivate(sessionsDir);
@@ -5556,9 +5574,9 @@ var init_state = __esm({
5556
5574
  import_zod9 = require("zod");
5557
5575
  init_schema();
5558
5576
  init_baseUrlDial();
5559
- FRONT_DOOR_PROTOCOL = 9;
5577
+ FRONT_DOOR_PROTOCOL = 10;
5560
5578
  FRONT_DOOR_HANDOVER_PROTOCOL = 6;
5561
- FrontDoorSessionSchema = import_zod9.z.strictObject({ pid: import_zod9.z.number().int().positive(), startedAt: import_zod9.z.number(), token: import_zod9.z.string().min(1), supervisorPid: import_zod9.z.number().int().positive().optional(), sessionId: import_zod9.z.string().min(1).optional(), identity: import_zod9.z.string().min(1).optional(), models: ModelsConfigSchema.optional() });
5579
+ FrontDoorSessionSchema = import_zod9.z.strictObject({ pid: import_zod9.z.number().int().positive(), startedAt: import_zod9.z.number(), token: import_zod9.z.string().min(1), supervisorPid: import_zod9.z.number().int().positive().optional(), sessionId: import_zod9.z.string().min(1).optional(), identity: import_zod9.z.string().min(1).optional(), models: ModelsConfigSchema.optional(), configDir: import_zod9.z.string().min(1).optional() });
5562
5580
  MAX_CONTEXT_TEXT_LENGTH = 256;
5563
5581
  ContextText = import_zod9.z.string().min(1).max(MAX_CONTEXT_TEXT_LENGTH);
5564
5582
  LaunchRouteSchema = import_zod9.z.union([import_zod9.z.strictObject({ kind: import_zod9.z.literal("anthropic") }), import_zod9.z.strictObject({ kind: import_zod9.z.literal("provider"), provider: import_zod9.z.string().min(1) })]);
@@ -5856,6 +5874,24 @@ function parseConnectTarget(authority) {
5856
5874
  function isInterceptedHost(host, interceptHosts) {
5857
5875
  return interceptHosts.includes(host);
5858
5876
  }
5877
+ function canonicalRequestTarget(target) {
5878
+ const raw = target ?? "/";
5879
+ const absolute = raw.startsWith("/") ? `${TARGET_BASE}${raw}` : void 0;
5880
+ if (absolute === void 0 ? !URL.canParse(raw, TARGET_BASE) : !URL.canParse(absolute)) {
5881
+ return void 0;
5882
+ }
5883
+ const parsed = absolute === void 0 ? new URL(raw, TARGET_BASE) : new URL(absolute);
5884
+ const canonical = `${parsed.pathname}${parsed.search}`;
5885
+ return new URL(canonical, TARGET_BASE).pathname === parsed.pathname ? canonical : void 0;
5886
+ }
5887
+ function answerAndClose(response, status) {
5888
+ if (response.headersSent) {
5889
+ response.destroy();
5890
+ return;
5891
+ }
5892
+ response.writeHead(status, { "content-length": "0", connection: "close" });
5893
+ response.end();
5894
+ }
5859
5895
  function servedByPipeline(path59) {
5860
5896
  return path59?.startsWith(ROUTED_PATH_PREFIX) === true;
5861
5897
  }
@@ -5914,10 +5950,36 @@ function caParses(ca) {
5914
5950
  }
5915
5951
  async function startConnectServer(config, effects, source) {
5916
5952
  const tunnelTokens = /* @__PURE__ */ new WeakMap();
5917
- const ledger = createConnectionLedger(config.limits, config.isLiveCapability);
5953
+ let generation = config.localSurface?.mintGeneration();
5954
+ const redirectedSessions = /* @__PURE__ */ new Set();
5955
+ const ledger = createConnectionLedger(config.limits, config.isLiveCapability, () => {
5956
+ checkGeneration();
5957
+ });
5958
+ function checkGeneration() {
5959
+ const surface = config.localSurface;
5960
+ if (surface === void 0) {
5961
+ return;
5962
+ }
5963
+ const current = surface.mintGeneration();
5964
+ if (current === generation) {
5965
+ return;
5966
+ }
5967
+ config.log?.("connect: the self-hosted mint changed, so every intercepted session and tunnel is ended and decided again on reconnection");
5968
+ generation = current;
5969
+ ledger.endAuthenticated();
5970
+ for (const secure of redirectedSessions) {
5971
+ secure.destroy();
5972
+ }
5973
+ }
5918
5974
  const lateSessionDeadlines = /* @__PURE__ */ new WeakMap();
5975
+ const owned = /* @__PURE__ */ new WeakMap();
5976
+ const ownedBySurface = (secure) => owned.get(secure) === true;
5919
5977
  const onUpgrade = (host) => (request4, socket, head) => {
5920
5978
  config.capture?.upgrade(request4);
5979
+ if (ownedBySurface(request4.socket)) {
5980
+ socket.end(REFUSED_UPGRADE_RESPONSE);
5981
+ return;
5982
+ }
5921
5983
  if (head.length > 0) {
5922
5984
  socket.pause();
5923
5985
  socket.unshift(head);
@@ -5928,8 +5990,8 @@ ${request4.rawHeaders.reduce((accumulated, value, index) => index % 2 === 0 ? `$
5928
5990
  `;
5929
5991
  pumpTapSession(socket, async (clientAlpn) => await effects.connectTlsUpstream(host, HTTPS_PORT, clientAlpn), config.capture?.tapStream?.(host), Buffer.from(headText, "utf8"));
5930
5992
  };
5931
- const sessions = config.interceptHosts.map((host) => {
5932
- if (config.tapHosts.includes(host) && !(config.localSurface?.parsesHost(host) ?? false)) {
5993
+ const sessionsFor = (ownedSet) => config.interceptHosts.map((host) => {
5994
+ if (config.tapHosts.includes(host) && !ownedSet) {
5933
5995
  const serveSecure2 = (secure) => {
5934
5996
  pumpTapSession(secure, async (clientAlpn) => await effects.connectTlsUpstream(host, HTTPS_PORT, clientAlpn), config.capture?.tapStream?.(host));
5935
5997
  };
@@ -5937,13 +5999,24 @@ ${request4.rawHeaders.reduce((accumulated, value, index) => index % 2 === 0 ? `$
5937
5999
  return { host, serveSecure: serveSecure2, tlsAcceptor: tlsAcceptor2 };
5938
6000
  }
5939
6001
  const handleHostRequest = async (request4, response) => {
6002
+ checkGeneration();
6003
+ if (request4.socket.destroyed) {
6004
+ return;
6005
+ }
6006
+ const target = canonicalRequestTarget(request4.url);
6007
+ if (target === void 0) {
6008
+ request4.resume();
6009
+ answerAndClose(response, REQUEST_STATUS.badRequest);
6010
+ return;
6011
+ }
6012
+ request4.url = target;
5940
6013
  if (ledger.retiring()) {
5941
6014
  clearTimeout(lateSessionDeadlines.get(request4.socket));
5942
6015
  response.once("close", () => {
5943
6016
  request4.socket.end();
5944
6017
  });
5945
6018
  }
5946
- if (config.localSurface !== void 0 && await config.localSurface.serve(host, request4, response)) {
6019
+ if (config.localSurface !== void 0 && ownedBySurface(request4.socket) && await config.localSurface.serve(host, request4, response)) {
5947
6020
  return;
5948
6021
  }
5949
6022
  if (host === config.routedHost && servedByPipeline(request4.url)) {
@@ -5951,17 +6024,28 @@ ${request4.rawHeaders.reduce((accumulated, value, index) => index % 2 === 0 ? `$
5951
6024
  if (tunnelToken !== void 0 && request4.headers[AUTH_HEADER] === void 0) {
5952
6025
  request4.headers[AUTH_HEADER] = tunnelToken;
5953
6026
  }
6027
+ request4.headers[SELF_HOSTED_HEADER] = ownedBySurface(request4.socket) ? "1" : void 0;
5954
6028
  config.serveRouted(request4, response);
5955
6029
  return;
5956
6030
  }
6031
+ if (ownedBySurface(request4.socket)) {
6032
+ request4.resume();
6033
+ answerAndClose(response, REQUEST_STATUS.notFound);
6034
+ return;
6035
+ }
5957
6036
  effects.forwardHttp(config.upstreamFor(host), request4, response, config.capture?.observePassthrough(request4));
5958
6037
  };
5959
6038
  const handler = (request4, response) => {
5960
- void handleHostRequest(request4, response);
6039
+ handleHostRequest(request4, response).catch((error) => {
6040
+ config.log?.(`connect: serving ${request4.method ?? "?"} on ${host} failed: ${error instanceof Error ? `${error.name}: ${error.message}` : String(error)}`);
6041
+ request4.resume();
6042
+ answerAndClose(response, REQUEST_STATUS.internalServerError);
6043
+ });
5961
6044
  };
5962
6045
  const httpSession = effects.createHttpSession(handler, onUpgrade(host));
5963
6046
  const serveSecure = (secure, capability) => {
5964
6047
  tunnelTokens.set(secure, capability);
6048
+ owned.set(secure, ownedSet);
5965
6049
  if (ledger.retiring()) {
5966
6050
  const deadline = setTimeout(() => {
5967
6051
  secure.destroy();
@@ -5974,18 +6058,42 @@ ${request4.rawHeaders.reduce((accumulated, value, index) => index % 2 === 0 ? `$
5974
6058
  const tlsAcceptor = effects.createTlsAcceptor(config.leafFor(host), serveSecure);
5975
6059
  return { host, serveSecure, httpSession, tlsAcceptor };
5976
6060
  });
6061
+ const sessions = sessionsFor(false);
6062
+ const ownedSessions = config.localSurface === void 0 ? void 0 : sessionsFor(true);
5977
6063
  const listener = await effects.listenLoopback(source, (socket) => {
5978
- handleConnect(socket, { config, effects, sessions, ledger });
6064
+ handleConnect(socket, { config, effects, sessions, ownedSessions, ledger, checkGeneration });
5979
6065
  });
5980
6066
  const apiSession = sessions.find((session) => session.host === config.routedHost);
5981
6067
  const sessionByHost = new Map(sessions.map((session) => [session.host, session]));
5982
- const sniAcceptor = effects.createSniTlsAcceptor(config.interceptHosts, config.leafFor, (secure, host) => {
5983
- const session = sessionByHost.get(host);
6068
+ const ownedSessionByHost = new Map((ownedSessions ?? []).map((session) => [session.host, session]));
6069
+ const serveRedirected = (secure, host, isOwned) => {
6070
+ redirectedSessions.add(secure);
6071
+ secure.once("close", () => {
6072
+ redirectedSessions.delete(secure);
6073
+ });
6074
+ const session = (isOwned ? ownedSessionByHost : sessionByHost).get(host);
5984
6075
  if (session === void 0) {
5985
6076
  secure.destroy();
5986
6077
  return;
5987
6078
  }
5988
6079
  session.serveSecure(secure, config.transparentCapability ?? "");
6080
+ };
6081
+ const sniAcceptor = effects.createSniTlsAcceptor(config.interceptHosts, config.leafFor, (secure, host) => {
6082
+ const surface = config.localSurface;
6083
+ if (surface === void 0) {
6084
+ serveRedirected(secure, host, false);
6085
+ return;
6086
+ }
6087
+ checkGeneration();
6088
+ surface.ownsPeer(secure.remotePort ?? 0).then(
6089
+ (isOwned) => {
6090
+ serveRedirected(secure, host, isOwned);
6091
+ },
6092
+ (error) => {
6093
+ config.log?.(`connect: attributing a redirected ${host} connection failed, so it is served as the local surface's: ${error instanceof Error ? error.message : String(error)}`);
6094
+ serveRedirected(secure, host, true);
6095
+ }
6096
+ );
5989
6097
  });
5990
6098
  const transparent = config.transparentPort === void 0 || apiSession === void 0 ? void 0 : await effects.listenLoopback({ preferredPort: config.transparentPort }, (socket) => {
5991
6099
  sniAcceptor.accept(socket);
@@ -5995,7 +6103,7 @@ ${request4.rawHeaders.reduce((accumulated, value, index) => index % 2 === 0 ? `$
5995
6103
  await listener.close();
5996
6104
  await transparent?.close();
5997
6105
  sniAcceptor.close();
5998
- for (const { httpSession, tlsAcceptor } of sessions) {
6106
+ for (const { httpSession, tlsAcceptor } of [...sessions, ...ownedSessions ?? []]) {
5999
6107
  tlsAcceptor.close();
6000
6108
  httpSession?.close();
6001
6109
  }
@@ -6014,7 +6122,7 @@ ${request4.rawHeaders.reduce((accumulated, value, index) => index % 2 === 0 ? `$
6014
6122
  close: closeSurface
6015
6123
  };
6016
6124
  }
6017
- function createConnectionLedger(limits, isLiveCapability2) {
6125
+ function createConnectionLedger(limits, isLiveCapability2, onRevalidate = () => void 0) {
6018
6126
  const pending = /* @__PURE__ */ new Map();
6019
6127
  const authenticated = /* @__PURE__ */ new Map();
6020
6128
  let tunnels = 0;
@@ -6030,6 +6138,7 @@ function createConnectionLedger(limits, isLiveCapability2) {
6030
6138
  }
6031
6139
  };
6032
6140
  const revalidation = setInterval(() => {
6141
+ onRevalidate();
6033
6142
  for (const [capability, sockets] of authenticated) {
6034
6143
  if (!isLiveCapability2(capability)) {
6035
6144
  for (const socket of sockets) {
@@ -6040,6 +6149,13 @@ function createConnectionLedger(limits, isLiveCapability2) {
6040
6149
  }, limits.revalidateMs);
6041
6150
  revalidation.unref();
6042
6151
  return {
6152
+ endAuthenticated: () => {
6153
+ for (const sockets of authenticated.values()) {
6154
+ for (const socket of sockets) {
6155
+ socket.destroy();
6156
+ }
6157
+ }
6158
+ },
6043
6159
  accept: (socket) => {
6044
6160
  const [oldest] = pending.keys();
6045
6161
  if (pending.size >= limits.maxPendingHeads && oldest !== void 0) {
@@ -6110,6 +6226,22 @@ function createConnectionLedger(limits, isLiveCapability2) {
6110
6226
  }
6111
6227
  };
6112
6228
  }
6229
+ function refuseWithReason(socket, status, rule, reason) {
6230
+ socket.removeAllListeners("data");
6231
+ socket.pause();
6232
+ if (socket.destroyed || socket.writableEnded) {
6233
+ return;
6234
+ }
6235
+ socket.end(`HTTP/1.1 ${status}\r
6236
+ x-agent-shim-refusal: ${rule}\r
6237
+ content-type: text/plain; charset=utf-8\r
6238
+ content-length: ${String(Buffer.byteLength(reason))}\r
6239
+ connection: close\r
6240
+ \r
6241
+ ${reason}`, () => {
6242
+ socket.destroy();
6243
+ });
6244
+ }
6113
6245
  function refuse(socket, status, headers = []) {
6114
6246
  socket.removeAllListeners("data");
6115
6247
  socket.pause();
@@ -6160,7 +6292,7 @@ function proxyAuthorizationOf(head) {
6160
6292
  return values.length === 1 ? value : void 0;
6161
6293
  }
6162
6294
  function routeConnect(socket, head, context) {
6163
- const { config, effects, sessions, ledger } = context;
6295
+ const { config, effects, sessions, ownedSessions, ledger } = context;
6164
6296
  const credential = proxyAuthorizationOf(head);
6165
6297
  const capability = credential === void 0 ? void 0 : capabilityFromProxyAuthorization(credential);
6166
6298
  if (capability === void 0 || !config.isLiveCapability(capability)) {
@@ -6175,7 +6307,14 @@ function routeConnect(socket, head, context) {
6175
6307
  refuse(socket, REFUSAL.badRequest, target === void 0 ? [] : [`${REFUSAL_HEADER}: ${target.refusal}`]);
6176
6308
  return;
6177
6309
  }
6178
- const session = sessions.find((entry) => entry.host === target.host);
6310
+ context.checkGeneration();
6311
+ const isOwned = config.localSurface?.ownsLaunch(capability) === true;
6312
+ const session = (isOwned && ownedSessions !== void 0 ? ownedSessions : sessions).find((entry) => entry.host === target.host);
6313
+ if (session === void 0 && isOwned) {
6314
+ config.capture?.refusedTunnel(target);
6315
+ refuseWithReason(socket, REFUSAL.forbidden, SELF_HOSTED_TUNNEL_REFUSAL, `the front door's self-hosted Remote Control mode does not tunnel to ${target.host}: a self-hosted session reaches no host the door does not serve itself`);
6316
+ return;
6317
+ }
6179
6318
  if (!ledger.establish(socket, capability, session === void 0 ? "blind" : "terminated")) {
6180
6319
  refuse(socket, REFUSAL.serviceUnavailable);
6181
6320
  return;
@@ -6243,7 +6382,7 @@ function realConnectCertStore(paths) {
6243
6382
  }
6244
6383
  };
6245
6384
  }
6246
- var import_node_crypto6, fs3, CONNECT_INTERCEPT_HOST, CONNECT_INTERCEPT_HOSTS, ROUTED_PATH_PREFIX, HTTPS_PORT, HTTP_BAD_GATEWAY, CA_KEY_FILE_MODE, CONNECT_LINE_TOKENS, HEAD_TERMINATOR, MAX_CONNECT_HEAD_BYTES, CONNECT_ESTABLISHED, REFUSAL_HEADER, REFUSAL, CONNECT_LIMITS, CA_VALIDITY_DAYS, LEAF_VALIDITY_DAYS, CA_SUBJECT_COMMON_NAME, MS_PER_DAY, HOP_BY_HOP_HEADERS, TAP_ALPN_PROTOCOLS;
6385
+ var import_node_crypto6, fs3, CONNECT_INTERCEPT_HOST, CONNECT_INTERCEPT_HOSTS, ROUTED_PATH_PREFIX, HTTPS_PORT, HTTP_BAD_GATEWAY, CA_KEY_FILE_MODE, CONNECT_LINE_TOKENS, HEAD_TERMINATOR, MAX_CONNECT_HEAD_BYTES, CONNECT_ESTABLISHED, REFUSAL_HEADER, REFUSAL, CONNECT_LIMITS, CA_VALIDITY_DAYS, LEAF_VALIDITY_DAYS, CA_SUBJECT_COMMON_NAME, MS_PER_DAY, TARGET_BASE, HOP_BY_HOP_HEADERS, REQUEST_STATUS, REFUSED_UPGRADE_RESPONSE, TAP_ALPN_PROTOCOLS, SELF_HOSTED_TUNNEL_REFUSAL;
6247
6386
  var init_connect = __esm({
6248
6387
  "src/frontdoor/connect.ts"() {
6249
6388
  "use strict";
@@ -6268,6 +6407,7 @@ var init_connect = __esm({
6268
6407
  REFUSAL_HEADER = "x-agent-shim-refusal";
6269
6408
  REFUSAL = {
6270
6409
  badRequest: "400 Bad Request",
6410
+ forbidden: "403 Forbidden",
6271
6411
  proxyAuthenticationRequired: "407 Proxy Authentication Required",
6272
6412
  requestTimeout: "408 Request Timeout",
6273
6413
  headTooLarge: "431 Request Header Fields Too Large",
@@ -6283,6 +6423,7 @@ var init_connect = __esm({
6283
6423
  LEAF_VALIDITY_DAYS = 397;
6284
6424
  CA_SUBJECT_COMMON_NAME = "agent-shim front door CA";
6285
6425
  MS_PER_DAY = 864e5;
6426
+ TARGET_BASE = "http://127.0.0.1";
6286
6427
  HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
6287
6428
  "connection",
6288
6429
  "keep-alive",
@@ -6294,7 +6435,14 @@ var init_connect = __esm({
6294
6435
  "transfer-encoding",
6295
6436
  "upgrade"
6296
6437
  ]);
6438
+ REQUEST_STATUS = {
6439
+ badRequest: 400,
6440
+ notFound: 404,
6441
+ internalServerError: 500
6442
+ };
6443
+ REFUSED_UPGRADE_RESPONSE = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
6297
6444
  TAP_ALPN_PROTOCOLS = ["h2", "http/1.1"];
6445
+ SELF_HOSTED_TUNNEL_REFUSAL = "self-hosted-remote-control";
6298
6446
  }
6299
6447
  });
6300
6448
 
@@ -14156,7 +14304,7 @@ var init_package = __esm({
14156
14304
  "package.json"() {
14157
14305
  package_default = {
14158
14306
  name: "claude-use",
14159
- version: "14.5.1",
14307
+ version: "14.6.0",
14160
14308
  description: "A profile manager and launcher for Claude Code that lets one person run multiple logins from one machine while controlling what gets shared between them.",
14161
14309
  license: "MIT",
14162
14310
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -18625,7 +18773,7 @@ function prepareRegisteredLaunch(params, onRecorded) {
18625
18773
  const sessionId = params.supervised?.sessionId ?? (0, import_node_crypto19.randomUUID)();
18626
18774
  const resolvedModels = decided.models ?? (decided.globalModels === void 0 ? void 0 : {});
18627
18775
  const sessionModels = (0, import_node_util2.isDeepStrictEqual)(resolvedModels, decided.globalModels) ? void 0 : resolvedModels;
18628
- const session = { sessionId, ...decided.farmIdentity === void 0 ? {} : { identity: decided.farmIdentity }, ...sessionModels === void 0 ? {} : { models: sessionModels } };
18776
+ const session = { sessionId, ...decided.farmIdentity === void 0 ? {} : { identity: decided.farmIdentity }, ...sessionModels === void 0 ? {} : { models: sessionModels }, configDir: decision.configDir ?? import_node_path55.default.join(import_node_os10.default.homedir(), ".claude") };
18629
18777
  let frontDoor = frontDoorEngaged && frontDoorPort !== void 0 ? frontDoorPort.ensure(env.NODE_EXTRA_CA_CERTS, session) : void 0;
18630
18778
  if (frontDoor !== void 0 && frontDoorPort !== void 0) {
18631
18779
  let beforePid = frontDoor.supervisorPid;
@@ -21436,7 +21584,7 @@ var ResetRowSchema = import_zod29.z.strictObject({
21436
21584
  var ResetScheduleSchema = import_zod29.z.strictObject({ resets: import_zod29.z.readonly(import_zod29.z.array(ResetRowSchema)) });
21437
21585
 
21438
21586
  // src/frontdoor/controlSchemas.ts
21439
- var import_node_path45 = __toESM(require("node:path"), 1);
21587
+ var import_node_path46 = __toESM(require("node:path"), 1);
21440
21588
  var import_zod39 = require("zod");
21441
21589
 
21442
21590
  // src/codex/doctor.ts
@@ -21522,7 +21670,7 @@ function resolveMiseDispatcher(target, pathDirs, env, trustedExecutable) {
21522
21670
  }
21523
21671
 
21524
21672
  // src/doctorReport.ts
21525
- var import_node_path44 = __toESM(require("node:path"), 1);
21673
+ var import_node_path45 = __toESM(require("node:path"), 1);
21526
21674
  init_signIn();
21527
21675
  init_identityAccounts();
21528
21676
  init_read();
@@ -22371,6 +22519,284 @@ function pushHeadroomAllowlist(push, allowlist, daemon) {
22371
22519
  // src/doctorReport.ts
22372
22520
  init_state2();
22373
22521
  init_supervisor2();
22522
+
22523
+ // src/frontdoor/rcSelfHostMint.ts
22524
+ var import_node_path44 = __toESM(require("node:path"), 1);
22525
+ init_identityRecords();
22526
+ init_account();
22527
+
22528
+ // src/frontdoor/rcSelfHostLocal.ts
22529
+ init_http();
22530
+ init_rcControl();
22531
+
22532
+ // src/frontdoor/rcSelfHostOffline.ts
22533
+ init_http();
22534
+ var GITHUB_SYNC_PATH = /^\/api\/oauth\/organizations\/[^/]+\/sync\/github\/auth$/;
22535
+ var OFF_STATE_ENTRIES = [
22536
+ { matches: (pathname) => pathname === "/api/claude_cli/bootstrap", answer: { status: HTTP_STATUS.ok, body: {} } },
22537
+ { matches: (pathname) => pathname === "/api/claude_code_penguin_mode", answer: { status: HTTP_STATUS.ok, body: { enabled: false, disabled_reason: "preference" } } },
22538
+ { matches: (pathname) => GITHUB_SYNC_PATH.test(pathname), answer: { status: HTTP_STATUS.ok, body: { is_authenticated: false } } },
22539
+ { matches: (pathname) => pathname === "/v1/mcp_servers", answer: { status: HTTP_STATUS.ok, body: { data: [], next_page: null } } },
22540
+ { matches: (pathname) => pathname === "/mcp-registry/v0/servers", answer: { status: HTTP_STATUS.ok, body: { servers: [], metadata: { count: 0 } } } }
22541
+ ];
22542
+ function rcSelfHostOfflineAnswer(pathname) {
22543
+ const entry = OFF_STATE_ENTRIES.find((candidate) => candidate.matches(pathname));
22544
+ if (entry !== void 0) {
22545
+ return entry.answer;
22546
+ }
22547
+ return {
22548
+ status: HTTP_STATUS.notFound,
22549
+ body: { type: "error", error: { type: "not_found_error", message: `the front door's self-hosted Remote Control mode serves nothing at ${pathname}: a self-hosted session's calls are answered on this machine and never forwarded to the Anthropic hosts` } }
22550
+ };
22551
+ }
22552
+ function isRcSessionFamilyPath(pathname) {
22553
+ return pathname === "/v1/code/sessions" || pathname.startsWith("/v1/code/sessions/") || pathname === "/v1/sessions" || pathname.startsWith("/v1/sessions/");
22554
+ }
22555
+
22556
+ // src/frontdoor/rcSelfHostLocal.ts
22557
+ init_route();
22558
+ var RC_SELF_HOST_OAUTH_HOST = "platform.claude.com";
22559
+ var RC_SELF_HOST_EMAIL = "selfhost@agent-shim.invalid";
22560
+ var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"];
22561
+ var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
22562
+ var MS_PER_SECOND6 = 1e3;
22563
+ var HTTP_SERVICE_UNAVAILABLE = 503;
22564
+ function isRecord10(value) {
22565
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22566
+ }
22567
+ function parseJsonObject2(body) {
22568
+ let parsed;
22569
+ try {
22570
+ parsed = JSON.parse(body);
22571
+ } catch {
22572
+ return void 0;
22573
+ }
22574
+ return isRecord10(parsed) ? parsed : void 0;
22575
+ }
22576
+ function growthBookFeatures() {
22577
+ return {
22578
+ tengu_ccr_bridge: { defaultValue: true },
22579
+ tengu_bridge_repl_v2: { defaultValue: true },
22580
+ tengu_bridge_repl_v2_cse_shim_enabled: { defaultValue: true },
22581
+ tengu_bridge_min_version: { defaultValue: { minVersion: "0.0.0" } }
22582
+ };
22583
+ }
22584
+ var answerServerJson = (response, status, body) => {
22585
+ const text = JSON.stringify(body);
22586
+ response.writeHead(status, { "content-type": "application/json", "content-length": String(Buffer.byteLength(text, "utf8")) });
22587
+ response.end(text);
22588
+ };
22589
+ function createRcSelfHostLocal(deps) {
22590
+ const answerOffline = (method, pathname, request4, response) => {
22591
+ request4.resume();
22592
+ const offline = rcSelfHostOfflineAnswer(pathname);
22593
+ deps.log?.(`rc selfhost: answered ${method} ${pathname} locally with ${String(offline.status)}; a self-hosted session's calls never leave the door`);
22594
+ answerServerJson(response, offline.status, offline.body);
22595
+ };
22596
+ return {
22597
+ ownsLaunch: deps.ownsLaunch,
22598
+ ownsPeer: deps.ownsPeer,
22599
+ mintGeneration: () => {
22600
+ const minted = deps.credentialRecord();
22601
+ return minted === void 0 ? "none" : minted.identityId === void 0 ? "every" : `identity:${minted.identityId}`;
22602
+ },
22603
+ serve: async (host, request4, response) => {
22604
+ const method = (request4.method ?? "").toUpperCase();
22605
+ const pathname = new URL(request4.url ?? "/", "http://127.0.0.1").pathname;
22606
+ const minted = deps.credentialRecord();
22607
+ if (minted !== void 0 && minted.identityId === void 0) {
22608
+ request4.resume();
22609
+ deps.log?.(`rc selfhost: refused ${method} ${pathname}: the minted credential names no identity; mint it again`);
22610
+ answerServerJson(response, HTTP_SERVICE_UNAVAILABLE, { type: "error", error: { type: "api_error", message: "the front door's self-hosted Remote Control credential was minted before the door recorded its identity, so no launch can be told apart from it; run agent-shim frontdoor rc selfhost mint <identity> again" } });
22611
+ return true;
22612
+ }
22613
+ if (host === RC_SELF_HOST_OAUTH_HOST) {
22614
+ if (method === "POST" && pathname === "/v1/oauth/token") {
22615
+ const body = parseJsonObject2(await deps.readBody(request4, CONTROL_BODY_CAP_BYTES));
22616
+ const record = deps.credentialRecord();
22617
+ if (record === void 0) {
22618
+ answerServerJson(response, HTTP_SERVICE_UNAVAILABLE, { error: "the front door's self-hosted Remote Control surface is on but no credential has been minted for it" });
22619
+ return true;
22620
+ }
22621
+ if (body?.grant_type !== void 0 && body.grant_type !== "refresh_token") {
22622
+ answerServerJson(response, HTTP_STATUS.badRequest, { error: "unsupported_grant_type" });
22623
+ return true;
22624
+ }
22625
+ answerServerJson(response, HTTP_STATUS.ok, { access_token: record.accessToken, refresh_token: record.refreshToken, expires_in: RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS, scope: RC_SELF_HOST_SCOPE_LIST.join(" ") });
22626
+ return true;
22627
+ }
22628
+ if (method === "GET" && pathname === "/v1/oauth/hello") {
22629
+ answerServerJson(response, HTTP_STATUS.ok, {});
22630
+ return true;
22631
+ }
22632
+ answerOffline(method, pathname, request4, response);
22633
+ return true;
22634
+ }
22635
+ if (method === "POST" && pathname.startsWith("/api/eval/")) {
22636
+ await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
22637
+ answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND6) });
22638
+ return true;
22639
+ }
22640
+ if (method === "GET" && pathname === "/api/oauth/profile") {
22641
+ const record = deps.credentialRecord();
22642
+ if (record === void 0) {
22643
+ answerServerJson(response, HTTP_SERVICE_UNAVAILABLE, { error: "the front door's self-hosted Remote Control surface is on but no credential has been minted for it" });
22644
+ return true;
22645
+ }
22646
+ answerServerJson(response, HTTP_STATUS.ok, {
22647
+ // The email is required: the client's profile schema rejects an answer without `account.email`, discarding the whole profile.
22648
+ account: { uuid: record.accountUuid, email: RC_SELF_HOST_EMAIL, display_name: "agent-shim self-hosted", created_at: (/* @__PURE__ */ new Date(0)).toISOString() },
22649
+ organization: { uuid: record.organizationUuid, organization_type: "claude_max" }
22650
+ });
22651
+ return true;
22652
+ }
22653
+ if (method === "GET" && pathname === "/api/claude_code/policy_limits") {
22654
+ answerServerJson(response, HTTP_STATUS.ok, {});
22655
+ return true;
22656
+ }
22657
+ if (method === "POST" && pathname === "/api/oauth/validate") {
22658
+ await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
22659
+ const record = deps.credentialRecord();
22660
+ if (record === void 0) {
22661
+ answerServerJson(response, HTTP_SERVICE_UNAVAILABLE, { error: "the front door's self-hosted Remote Control surface is on but no credential has been minted for it" });
22662
+ return true;
22663
+ }
22664
+ answerServerJson(response, HTTP_STATUS.ok, { scopes: [...RC_SELF_HOST_SCOPE_LIST], expiresAt: null, subscriptionType: "max", account_uuid: record.accountUuid, organization_uuid: record.organizationUuid });
22665
+ return true;
22666
+ }
22667
+ if (method === "POST" && (pathname === "/api/event_logging/v2/batch" || pathname === "/api/claude_code/metrics" || pathname === "/api/claude_cli_feedback")) {
22668
+ await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
22669
+ answerServerJson(response, HTTP_STATUS.ok, {});
22670
+ return true;
22671
+ }
22672
+ if (method === "GET" && pathname === "/api/hello") {
22673
+ answerServerJson(response, HTTP_STATUS.ok, {});
22674
+ return true;
22675
+ }
22676
+ if (pathname.startsWith("/v1/") && (isRcSessionFamilyPath(pathname) || internalHeaderValue(request4.headers, PROVIDER_HEADER) !== void 0)) {
22677
+ return false;
22678
+ }
22679
+ answerOffline(method, pathname, request4, response);
22680
+ return true;
22681
+ }
22682
+ };
22683
+ }
22684
+
22685
+ // src/frontdoor/rcSelfHostMint.ts
22686
+ init_capability();
22687
+ var CREDENTIALS_FILE2 = ".credentials.json";
22688
+ var CLAUDE_JSON2 = ".claude.json";
22689
+ var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
22690
+ var RC_SELF_HOST_RECORD_FILE = "credential.json";
22691
+ var SELF_HOST_SUBSCRIPTION_TYPE = "max";
22692
+ function isRecord11(value) {
22693
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22694
+ }
22695
+ function readJsonObject(fs17, file) {
22696
+ const raw = fs17.readFileUtf8(file);
22697
+ if (raw === void 0) {
22698
+ return void 0;
22699
+ }
22700
+ let parsed;
22701
+ try {
22702
+ parsed = JSON.parse(raw);
22703
+ } catch {
22704
+ return void 0;
22705
+ }
22706
+ return isRecord11(parsed) ? parsed : void 0;
22707
+ }
22708
+ function readRcSelfHostRecord(fs17, frontdoorDir) {
22709
+ const parsed = readJsonObject(fs17, import_node_path44.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
22710
+ if (parsed === void 0) {
22711
+ return void 0;
22712
+ }
22713
+ const { accessToken, refreshToken, organizationUuid, accountUuid, identityId } = parsed;
22714
+ if (typeof accessToken !== "string" || accessToken === "" || typeof refreshToken !== "string" || refreshToken === "" || typeof organizationUuid !== "string" || organizationUuid === "" || typeof accountUuid !== "string" || accountUuid === "") {
22715
+ return void 0;
22716
+ }
22717
+ return { accessToken, refreshToken, organizationUuid, accountUuid, ...typeof identityId === "string" && identityId !== "" ? { identityId } : {} };
22718
+ }
22719
+ function identitiesHoldingMint(fs17, identitiesDir, record) {
22720
+ return fs17.readdir(identitiesDir).filter((id) => {
22721
+ if (id.startsWith(".")) {
22722
+ return false;
22723
+ }
22724
+ const oauth = readJsonObject(fs17, import_node_path44.default.join(identitiesDir, id, CREDENTIALS_FILE2))?.claudeAiOauth;
22725
+ return isRecord11(oauth) && typeof oauth.accessToken === "string" && isLiveCapability(oauth.accessToken, [record.accessToken]);
22726
+ });
22727
+ }
22728
+ function rcSelfHostMintFacts(fs17, identitiesDir, frontdoorDir) {
22729
+ const record = readRcSelfHostRecord(fs17, frontdoorDir);
22730
+ if (record === void 0) {
22731
+ return {};
22732
+ }
22733
+ if (record.identityId !== void 0) {
22734
+ return { rcSelfHostMint: { attributable: true } };
22735
+ }
22736
+ const holders = identitiesHoldingMint(fs17, identitiesDir, record).length;
22737
+ return { rcSelfHostMint: { attributable: holders === 1, holders } };
22738
+ }
22739
+ function mintRcSelfHostCredential(deps) {
22740
+ if (!isIdentityName(deps.identity)) {
22741
+ throw new Error(`"${deps.identity}" is not a valid identity name.`);
22742
+ }
22743
+ const id = identityIdOver(deps.fs, deps.identitiesDir, deps.identity);
22744
+ if (id === void 0) {
22745
+ throw new Error(`No identity named "${deps.identity}".`);
22746
+ }
22747
+ const identityDir = import_node_path44.default.join(deps.identitiesDir, id);
22748
+ const credentialsFile = import_node_path44.default.join(identityDir, CREDENTIALS_FILE2);
22749
+ const claudeJsonFile = import_node_path44.default.join(identityDir, CLAUDE_JSON2);
22750
+ const recordDir = import_node_path44.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
22751
+ const recordFile2 = import_node_path44.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
22752
+ const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
22753
+ const existingCredentials = readJsonObject(deps.fs, credentialsFile);
22754
+ const existingOauth = isRecord11(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
22755
+ const existingToken = typeof existingOauth?.accessToken === "string" && existingOauth.accessToken !== "" ? existingOauth.accessToken : void 0;
22756
+ const existingIsOwn = existingToken !== void 0 && previousRecord?.accessToken === existingToken;
22757
+ if (existingToken !== void 0 && !existingIsOwn && !deps.force) {
22758
+ throw new Error(
22759
+ `identity ${deps.identity} already holds an OAuth credential this door did not mint (a real claude.ai login): pass --force to replace it, or mint into an identity with no login. The self-hosted mode expects no Anthropic credential to be in play.`
22760
+ );
22761
+ }
22762
+ const accessToken = `sk-ant-oat${deps.randomToken()}`;
22763
+ const refreshToken = deps.randomToken();
22764
+ const organizationUuid = deps.newUuid();
22765
+ const accountUuid = deps.newUuid();
22766
+ const mintedAt = new Date(deps.now()).toISOString();
22767
+ deps.fs.mkdirPrivate(import_node_path44.default.dirname(credentialsFile));
22768
+ deps.fs.writeFilePrivate(credentialsFile, `${JSON.stringify({ ...existingCredentials, claudeAiOauth: { accessToken, refreshToken, expiresAt: null, scopes: [...RC_SELF_HOST_SCOPE_LIST], subscriptionType: SELF_HOST_SUBSCRIPTION_TYPE, rateLimitTier: null } }, null, 2)}
22769
+ `);
22770
+ const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
22771
+ const existingBlock = (value) => isRecord11(value) ? value : {};
22772
+ deps.fs.writeFilePrivate(claudeJsonFile, `${JSON.stringify({
22773
+ ...claudeJson,
22774
+ oauthAccount: {
22775
+ ...existingBlock(claudeJson.oauthAccount),
22776
+ accountUuid,
22777
+ emailAddress: RC_SELF_HOST_EMAIL,
22778
+ organizationUuid,
22779
+ organizationName: "agent-shim self-hosted",
22780
+ // The billing and creation fields exist so the CLI's "populate the account block if it is missing" step finds a complete block and skips its profile fetch; the door answers that fetch locally anyway, so these are the quiet path, not a load-bearing claim.
22781
+ billingType: "stripe_subscription",
22782
+ accountCreatedAt: mintedAt,
22783
+ subscriptionCreatedAt: mintedAt
22784
+ },
22785
+ cachedGrowthBookFeatures: {
22786
+ ...existingBlock(claudeJson.cachedGrowthBookFeatures),
22787
+ tengu_ccr_bridge: true,
22788
+ tengu_bridge_repl_v2: true,
22789
+ tengu_bridge_repl_v2_cse_shim_enabled: true
22790
+ }
22791
+ }, null, 2)}
22792
+ `);
22793
+ deps.fs.mkdirPrivate(recordDir);
22794
+ deps.fs.writeFilePrivate(recordFile2, `${JSON.stringify({ accessToken, refreshToken, organizationUuid, accountUuid, identityId: id }, null, 2)}
22795
+ `);
22796
+ return { identity: deps.identity, organizationUuid, credentialsFile, claudeJsonFile, recordFile: recordFile2, replaced: existingIsOwn };
22797
+ }
22798
+
22799
+ // src/doctorReport.ts
22374
22800
  init_state();
22375
22801
 
22376
22802
  // src/doctorFrontDoor.ts
@@ -22432,6 +22858,17 @@ function pushFrontDoorListeners(push, readings) {
22432
22858
  );
22433
22859
  }
22434
22860
  }
22861
+ function pushRcSelfHostMint(push, mint) {
22862
+ if (mint !== void 0 && !mint.attributable) {
22863
+ push("frontdoor", "fail", `The self-hosted Remote Control credential was minted before the door recorded its identity, and ${mint.holders === 0 ? "no identity holds it" : "more than one identity holds it"}, so a door with the mode on refuses every launch's calls on the intercepted hosts. Mint it again: agent-shim frontdoor rc selfhost mint <identity>.`);
22864
+ }
22865
+ }
22866
+ function pushFrontDoorReadings(push, readings) {
22867
+ if (readings.listeners !== void 0) {
22868
+ pushFrontDoorListeners(push, readings.listeners);
22869
+ }
22870
+ pushRcSelfHostMint(push, readings.rcSelfHostMint);
22871
+ }
22435
22872
 
22436
22873
  // src/frontdoor/listenerReadings.ts
22437
22874
  var import_node_fs13 = __toESM(require("node:fs"), 1);
@@ -22624,7 +23061,7 @@ function tcpPortEraRecord(raw) {
22624
23061
  return (has("port") || has("lastPort")) && !has("socketPath");
22625
23062
  }
22626
23063
  function pushPathResolution(push, resolution) {
22627
- const ownDir = import_node_path44.default.dirname(resolution.ownExecutablePath);
23064
+ const ownDir = import_node_path45.default.dirname(resolution.ownExecutablePath);
22628
23065
  switch (resolution.agentShim.status) {
22629
23066
  case "ok":
22630
23067
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -22744,14 +23181,14 @@ function pushProvider(push, entry, cacheEnv, signIn, unreachable) {
22744
23181
  }
22745
23182
  function pushLegacyName(push, params) {
22746
23183
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
22747
- if (legacyVariables.length === 0 && import_node_path44.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
23184
+ if (legacyVariables.length === 0 && import_node_path45.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
22748
23185
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
22749
23186
  return;
22750
23187
  }
22751
23188
  for (const name of legacyVariables) {
22752
23189
  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);
22753
23190
  }
22754
- if (import_node_path44.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
23191
+ if (import_node_path45.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
22755
23192
  push(
22756
23193
  "legacy-name",
22757
23194
  "warn",
@@ -22841,7 +23278,7 @@ function runDoctor(params) {
22841
23278
  push("identity", "warn", `identities/${name} cannot be reached (${code}), so it is not counted as an identity. Repair the permissions of the directory or of what a symlink points through, or remove the entry.`, name);
22842
23279
  }
22843
23280
  for (const { file, detail } of params.renameJournals?.unreadable ?? []) {
22844
- push("identity", "fail", `${file} is not a rename journal this agent-shim can read (${detail}), so no identity can be renamed until it is fixed or removed, and it may be the trace of a rename that was left unfinished.`, import_node_path44.default.basename(file));
23281
+ push("identity", "fail", `${file} is not a rename journal this agent-shim can read (${detail}), so no identity can be renamed until it is fixed or removed, and it may be the trace of a rename that was left unfinished.`, import_node_path45.default.basename(file));
22845
23282
  }
22846
23283
  const validIdentityAgents = /* @__PURE__ */ new Map();
22847
23284
  const signedInAccounts = [];
@@ -23111,9 +23548,7 @@ function runDoctor(params) {
23111
23548
  if (params.frontDoor !== void 0) {
23112
23549
  const validated3 = params.frontDoor.state.raw === void 0 ? void 0 : validateJson(FrontDoorStateSchema, params.frontDoor.state);
23113
23550
  pushFrontDoor(push, params.frontDoor.supervisors, validated3?.ok === true ? validated3.data.supervisorPid : void 0, params.frontDoor.liveSessions, params.frontDoor.draining ?? []);
23114
- if (params.frontDoor.listeners !== void 0) {
23115
- pushFrontDoorListeners(push, params.frontDoor.listeners);
23116
- }
23551
+ pushFrontDoorReadings(push, params.frontDoor);
23117
23552
  }
23118
23553
  if (params.activeIdentity.raw === void 0) {
23119
23554
  push("active-identity", "pass", "No active identity set.");
@@ -23139,9 +23574,9 @@ function collectDoctorReport(params) {
23139
23574
  const { names: identityNames, unreachable: unreachableIdentities } = listIdentityDirectories(paths);
23140
23575
  const records = identityRecords(paths);
23141
23576
  const displacedIdentities = records.filter((record) => !identityIdExists(paths, record.id) && !unreachableIdentities.some((entry) => entry.name === record.id));
23142
- const identities = identityNames.filter((id) => (records.some((record) => record.id === id) || !import_node_fs14.default.existsSync(import_node_path44.default.join(paths.identitiesDir, id, "identity.json"))) && !displacedIdentities.some((record) => record.id === id)).map((id) => {
23143
- const farmRoot = import_node_path44.default.join(paths.identitiesDir, id);
23144
- const identityPath = import_node_path44.default.join(farmRoot, "identity.json");
23577
+ const identities = identityNames.filter((id) => (records.some((record) => record.id === id) || !import_node_fs14.default.existsSync(import_node_path45.default.join(paths.identitiesDir, id, "identity.json"))) && !displacedIdentities.some((record) => record.id === id)).map((id) => {
23578
+ const farmRoot = import_node_path45.default.join(paths.identitiesDir, id);
23579
+ const identityPath = import_node_path45.default.join(farmRoot, "identity.json");
23145
23580
  return { name: identityNameIn(records, id) ?? id, id, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot, credentialsFilePresent: import_node_fs14.default.existsSync(credentialsFilePath(farmRoot)), account: readIdentityAccount(realFsPort, paths.identitiesDir, id)?.account };
23146
23581
  });
23147
23582
  const usageSnapshots = {};
@@ -23159,12 +23594,12 @@ function collectDoctorReport(params) {
23159
23594
  }
23160
23595
  const profileNames = import_node_fs14.default.existsSync(paths.configProfilesDir) ? import_node_fs14.default.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
23161
23596
  const configProfiles = profileNames.map((name) => {
23162
- const profilePath = import_node_path44.default.join(paths.configProfilesDir, `${name}.json`);
23597
+ const profilePath = import_node_path45.default.join(paths.configProfilesDir, `${name}.json`);
23163
23598
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
23164
23599
  });
23165
23600
  const providerNames = import_node_fs14.default.existsSync(paths.providersDir) ? import_node_fs14.default.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
23166
23601
  const providers = providerNames.map((name) => {
23167
- const providerPath = import_node_path44.default.join(paths.providersDir, `${name}.json`);
23602
+ const providerPath = import_node_path45.default.join(paths.providersDir, `${name}.json`);
23168
23603
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
23169
23604
  });
23170
23605
  const ownExecutablePath = realOwnExecutablePath();
@@ -23176,12 +23611,12 @@ function collectDoctorReport(params) {
23176
23611
  binaryDiscovery = { ok: false, message: error instanceof Error ? error.message : String(error) };
23177
23612
  }
23178
23613
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
23179
- const pathDirs = (params.env.PATH ?? "").split(import_node_path44.default.delimiter).filter((dir) => dir !== "");
23614
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path45.default.delimiter).filter((dir) => dir !== "");
23180
23615
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
23181
23616
  findPathShadow({
23182
23617
  pathDirs,
23183
- targetDir: import_node_path44.default.dirname(shimState.targetPath),
23184
- targetFilename: import_node_path44.default.basename(shimState.targetPath),
23618
+ targetDir: import_node_path45.default.dirname(shimState.targetPath),
23619
+ targetFilename: import_node_path45.default.basename(shimState.targetPath),
23185
23620
  findExecutableInDir
23186
23621
  }),
23187
23622
  shimState.targetPath,
@@ -23210,7 +23645,7 @@ function collectDoctorReport(params) {
23210
23645
  catalogueRedirects: providersWithRedirectedCatalogue(realFarmFs, paths, new Map(providers.map((entry) => [entry.name, currentCatalogueSettings(paths, entry.name)]))),
23211
23646
  renameJournals: listRenameJournals(realFarmFs, paths.identityRenamesDir),
23212
23647
  unreachableIdentities,
23213
- identityRecords: { all: records, displaced: displacedIdentities.map((record) => ({ ...record, directoryPresent: import_node_fs14.default.existsSync(import_node_path44.default.join(paths.identitiesDir, record.id)) })), nameRenames: unfinishedNameRenames(paths).map((record) => ({ from: record.from, description: describeInterruptedNameRename(paths, record) })), strayNameRenameFiles: strayNameRenameRecordFiles(paths) },
23648
+ identityRecords: { all: records, displaced: displacedIdentities.map((record) => ({ ...record, directoryPresent: import_node_fs14.default.existsSync(import_node_path45.default.join(paths.identitiesDir, record.id)) })), nameRenames: unfinishedNameRenames(paths).map((record) => ({ from: record.from, description: describeInterruptedNameRename(paths, record) })), strayNameRenameFiles: strayNameRenameRecordFiles(paths) },
23214
23649
  directoryRules: { path: paths.directoryRulesFile, raw: realFsPort.readFileUtf8(paths.directoryRulesFile) },
23215
23650
  globalConfig: { path: paths.globalConfigFile, raw: realFsPort.readFileUtf8(paths.globalConfigFile) },
23216
23651
  models: readableOr(() => readGlobalConfig(paths)?.models, void 0),
@@ -23225,7 +23660,7 @@ function collectDoctorReport(params) {
23225
23660
  agentShim: refinePathShadow(
23226
23661
  findPathShadow({
23227
23662
  pathDirs,
23228
- targetDir: import_node_path44.default.dirname(ownExecutablePath),
23663
+ targetDir: import_node_path45.default.dirname(ownExecutablePath),
23229
23664
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
23230
23665
  findExecutableInDir
23231
23666
  }),
@@ -23259,7 +23694,7 @@ function collectDoctorReport(params) {
23259
23694
  logPath: paths.headroomLogPath
23260
23695
  }
23261
23696
  },
23262
- ...uid === void 0 ? {} : { frontDoor: { state: { path: paths.frontdoorStateFile, raw: realFsPort.readFileUtf8(paths.frontdoorStateFile) }, supervisors: listFrontDoorSupervisors(realRunPort, uid), liveSessions: listFrontDoorSessions(realFarmFs, paths.frontdoorSessionsDir).filter((session) => realIsProcessRunning(session.pid)), draining: listDrainingFrontDoors(realFarmFs, paths.frontdoorDrainingDir, realIsProcessRunning), listeners: servingDoorListeners(paths) } }
23697
+ ...uid === void 0 ? {} : { frontDoor: { state: { path: paths.frontdoorStateFile, raw: realFsPort.readFileUtf8(paths.frontdoorStateFile) }, supervisors: listFrontDoorSupervisors(realRunPort, uid), liveSessions: listFrontDoorSessions(realFarmFs, paths.frontdoorSessionsDir).filter((session) => realIsProcessRunning(session.pid)), draining: listDrainingFrontDoors(realFarmFs, paths.frontdoorDrainingDir, realIsProcessRunning), listeners: servingDoorListeners(paths), ...rcSelfHostMintFacts(realFarmFs, paths.identitiesDir, paths.frontdoorDir) } }
23263
23698
  });
23264
23699
  return report;
23265
23700
  }
@@ -23318,11 +23753,11 @@ var DOOR_REPORT_ENVIRONMENT_NOTE = "The report is collected in a worker thread o
23318
23753
  var CheckRunInputSchema = import_zod39.z.strictObject({
23319
23754
  path: import_zod39.z.string().min(1),
23320
23755
  identity: import_zod39.z.string().min(1).optional()
23321
- }).refine((input) => import_node_path45.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
23756
+ }).refine((input) => import_node_path46.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
23322
23757
  var PoolPickInputSchema = import_zod39.z.strictObject({
23323
23758
  pool: import_zod39.z.string().min(1),
23324
23759
  path: import_zod39.z.string().min(1)
23325
- }).refine((input) => import_node_path45.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
23760
+ }).refine((input) => import_node_path46.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
23326
23761
  var DoctorFindingSchema = import_zod39.z.strictObject({
23327
23762
  section: import_zod39.z.enum(DOCTOR_SECTIONS),
23328
23763
  subject: import_zod39.z.string().optional(),
@@ -24114,7 +24549,7 @@ var import_openapi6 = require("@orpc/openapi");
24114
24549
  init_cliError();
24115
24550
 
24116
24551
  // src/frontdoor/launchSchemas.ts
24117
- var import_node_path46 = __toESM(require("node:path"), 1);
24552
+ var import_node_path47 = __toESM(require("node:path"), 1);
24118
24553
  var import_zod45 = require("zod");
24119
24554
  init_statusline();
24120
24555
  init_claudeVersion();
@@ -24125,7 +24560,7 @@ var LaunchResolveInputSchema = import_zod45.z.strictObject({
24125
24560
  argv: import_zod45.z.readonly(import_zod45.z.array(import_zod45.z.string())).optional(),
24126
24561
  /** The launch's inherited environment. Absent means an empty one: the door's own environment is never a substitute for the caller's, so a caller that wants `AGENT_SHIM_*` switches or a `CLAUDE_CONFIG_DIR` considered names them here. Values are read, never reported. */
24127
24562
  env: import_zod45.z.record(import_zod45.z.string(), import_zod45.z.string()).optional()
24128
- }).refine((input) => import_node_path46.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
24563
+ }).refine((input) => import_node_path47.default.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
24129
24564
  var LaunchPoolDecisionSchema = import_zod45.z.strictObject({
24130
24565
  name: import_zod45.z.string(),
24131
24566
  reasons: import_zod45.z.readonly(import_zod45.z.array(import_zod45.z.string())),
@@ -24963,15 +25398,15 @@ init_verifiedVersions();
24963
25398
  // src/frontdoor/rcLiveUsage.ts
24964
25399
  init_rcSchemas();
24965
25400
  var RC_RATE_LIMIT_EVENT_TYPE = "rate_limit_event";
24966
- function isRecord10(value) {
25401
+ function isRecord12(value) {
24967
25402
  return typeof value === "object" && value !== null && !Array.isArray(value);
24968
25403
  }
24969
25404
  function rcRateLimitInfoOf(event) {
24970
25405
  const payload = event.envelope.payload;
24971
- if (!isRecord10(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
25406
+ if (!isRecord12(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
24972
25407
  return void 0;
24973
25408
  }
24974
- if (!isRecord10(payload.rate_limit_info)) {
25409
+ if (!isRecord12(payload.rate_limit_info)) {
24975
25410
  return void 0;
24976
25411
  }
24977
25412
  const parsed = RcRateLimitInfoSchema.safeParse(payload.rate_limit_info);
@@ -25060,7 +25495,7 @@ function createSseParser() {
25060
25495
  }
25061
25496
  };
25062
25497
  }
25063
- function isRecord11(value) {
25498
+ function isRecord13(value) {
25064
25499
  return typeof value === "object" && value !== null && !Array.isArray(value);
25065
25500
  }
25066
25501
  function sequenceNumOf(value) {
@@ -25082,7 +25517,7 @@ function parseRcStreamEnvelope(parsed) {
25082
25517
  } catch {
25083
25518
  return void 0;
25084
25519
  }
25085
- if (!isRecord11(data)) {
25520
+ if (!isRecord13(data)) {
25086
25521
  return void 0;
25087
25522
  }
25088
25523
  const eventType = data.event_type;
@@ -25339,17 +25774,17 @@ function withClientPlatform(payload, headers) {
25339
25774
  const platform = headers[CLIENT_PLATFORM_HEADER];
25340
25775
  return typeof platform === "string" && platform !== "" ? { ...rest, client_platform: platform } : rest;
25341
25776
  }
25342
- function isRecord12(value) {
25777
+ function isRecord14(value) {
25343
25778
  return typeof value === "object" && value !== null && !Array.isArray(value);
25344
25779
  }
25345
- function parseJsonObject2(body) {
25780
+ function parseJsonObject3(body) {
25346
25781
  let parsed;
25347
25782
  try {
25348
25783
  parsed = JSON.parse(body);
25349
25784
  } catch {
25350
25785
  return void 0;
25351
25786
  }
25352
- return isRecord12(parsed) ? parsed : void 0;
25787
+ return isRecord14(parsed) ? parsed : void 0;
25353
25788
  }
25354
25789
  function nonEmptyString2(record, field) {
25355
25790
  const value = record === void 0 ? void 0 : record[field];
@@ -25384,7 +25819,7 @@ function pageOfRcChannel(url, rows, idOf, rowOf3) {
25384
25819
  async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25385
25820
  const { request: request4, response, host } = ctx;
25386
25821
  if (tail === "client/presence" && method === "POST") {
25387
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25822
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25388
25823
  const clientId = nonEmptyString2(body, "client_id");
25389
25824
  const clear = body?.clear;
25390
25825
  if (clientId === void 0 || clear !== void 0 && typeof clear !== "boolean") {
@@ -25402,7 +25837,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25402
25837
  return true;
25403
25838
  }
25404
25839
  if (tail === "mark_read" && method === "POST") {
25405
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25840
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25406
25841
  const eventId = nonEmptyString2(body, "event_id");
25407
25842
  const clientId = nonEmptyString2(body, "client_id");
25408
25843
  if (body !== void 0 && "event_id" in body && eventId === void 0 || "client_id" in (body ?? {}) && clientId === void 0) {
@@ -25415,7 +25850,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25415
25850
  return true;
25416
25851
  }
25417
25852
  if (tail === "teleport-events" && method === "POST") {
25418
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25853
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25419
25854
  const events = body?.events;
25420
25855
  if (!Array.isArray(events) || events.length === 0 || events.length > maxBatchEvents) {
25421
25856
  await ctx.answerJson(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: `a teleport write is a non-empty array of at most ${String(maxBatchEvents)} events` } });
@@ -25423,7 +25858,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25423
25858
  }
25424
25859
  const results = [];
25425
25860
  for (const event of events) {
25426
- if (!isRecord12(event) || !isRecord12(event.payload)) {
25861
+ if (!isRecord14(event) || !isRecord14(event.payload)) {
25427
25862
  await ctx.answerJson(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "every event in a teleport write is an object carrying one payload object" } });
25428
25863
  return true;
25429
25864
  }
@@ -25487,7 +25922,7 @@ async function serveRcCompatSessions(ctx, pathname, compatPath) {
25487
25922
  await ctx.answerJson(response, HTTP_STATUS.notFound, { type: "error", error: { type: "api_error", message: `Session not found: ${address}` } });
25488
25923
  return;
25489
25924
  }
25490
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25925
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25491
25926
  const title = nonEmptyString2(body, "title");
25492
25927
  if (title === void 0) {
25493
25928
  await ctx.answerJson(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "a compatibility session update is JSON naming a non-empty title" } });
@@ -25525,17 +25960,17 @@ init_http();
25525
25960
  init_rcControl();
25526
25961
  var RC_CONVERSATIONS_PATH_PREFIX = "/v1/code/conversations";
25527
25962
  var RC_CONVERSATION_ID_PREFIX = "conv_";
25528
- function isRecord13(value) {
25963
+ function isRecord15(value) {
25529
25964
  return typeof value === "object" && value !== null && !Array.isArray(value);
25530
25965
  }
25531
- function parseJsonObject3(body) {
25966
+ function parseJsonObject4(body) {
25532
25967
  let parsed;
25533
25968
  try {
25534
25969
  parsed = JSON.parse(body);
25535
25970
  } catch {
25536
25971
  return void 0;
25537
25972
  }
25538
- return isRecord13(parsed) ? parsed : void 0;
25973
+ return isRecord15(parsed) ? parsed : void 0;
25539
25974
  }
25540
25975
  function nonEmptyString3(record, field) {
25541
25976
  const value = record === void 0 ? void 0 : record[field];
@@ -25581,7 +26016,7 @@ async function serveRcConversations(ctx, pathname, method) {
25581
26016
  return;
25582
26017
  }
25583
26018
  if (tail === "events" && method === "POST") {
25584
- const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
26019
+ const body = parseJsonObject4(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25585
26020
  const events = body?.events;
25586
26021
  if (!Array.isArray(events) || events.length === 0 || events.length > ctx.maxBatchEvents) {
25587
26022
  await ctx.answerJson(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: `a client event write is a non-empty array of at most ${String(ctx.maxBatchEvents)} events` } });
@@ -25589,7 +26024,7 @@ async function serveRcConversations(ctx, pathname, method) {
25589
26024
  }
25590
26025
  const results = [];
25591
26026
  for (const event of events) {
25592
- if (!isRecord13(event) || !isRecord13(event.payload)) {
26027
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
25593
26028
  await ctx.answerJson(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "every event in a write is an object carrying one payload object" } });
25594
26029
  return;
25595
26030
  }
@@ -25615,111 +26050,6 @@ async function serveRcConversations(ctx, pathname, method) {
25615
26050
  await ctx.answerJson(response, HTTP_STATUS.notFound, { type: "error", error: { type: "api_error", message: `the conversation family serves no path "${tail}"` } });
25616
26051
  }
25617
26052
 
25618
- // src/frontdoor/rcSelfHostLocal.ts
25619
- init_http();
25620
- init_rcControl();
25621
- var RC_SELF_HOST_OAUTH_HOST = "platform.claude.com";
25622
- var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"];
25623
- var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
25624
- var MS_PER_SECOND6 = 1e3;
25625
- var HTTP_SERVICE_UNAVAILABLE = 503;
25626
- function isRecord14(value) {
25627
- return typeof value === "object" && value !== null && !Array.isArray(value);
25628
- }
25629
- function parseJsonObject4(body) {
25630
- let parsed;
25631
- try {
25632
- parsed = JSON.parse(body);
25633
- } catch {
25634
- return void 0;
25635
- }
25636
- return isRecord14(parsed) ? parsed : void 0;
25637
- }
25638
- function growthBookFeatures() {
25639
- return {
25640
- tengu_ccr_bridge: { defaultValue: true },
25641
- tengu_bridge_repl_v2: { defaultValue: true },
25642
- tengu_bridge_repl_v2_cse_shim_enabled: { defaultValue: true },
25643
- tengu_bridge_min_version: { defaultValue: { minVersion: "0.0.0" } }
25644
- };
25645
- }
25646
- var answerServerJson = (response, status, body) => {
25647
- const text = JSON.stringify(body);
25648
- response.writeHead(status, { "content-type": "application/json", "content-length": String(Buffer.byteLength(text, "utf8")) });
25649
- response.end(text);
25650
- };
25651
- function createRcSelfHostLocal(deps) {
25652
- return {
25653
- parsesHost: (host) => host === RC_SELF_HOST_OAUTH_HOST,
25654
- serve: async (host, request4, response) => {
25655
- const method = (request4.method ?? "").toUpperCase();
25656
- const pathname = new URL(request4.url ?? "/", "http://127.0.0.1").pathname;
25657
- if (host === RC_SELF_HOST_OAUTH_HOST) {
25658
- if (method === "POST" && pathname === "/v1/oauth/token") {
25659
- const body = parseJsonObject4(await deps.readBody(request4, CONTROL_BODY_CAP_BYTES));
25660
- const record = deps.credentialRecord();
25661
- if (record === void 0) {
25662
- answerServerJson(response, HTTP_SERVICE_UNAVAILABLE, { error: "the front door's self-hosted Remote Control surface is on but no credential has been minted for it" });
25663
- return true;
25664
- }
25665
- if (body?.grant_type !== void 0 && body.grant_type !== "refresh_token") {
25666
- answerServerJson(response, HTTP_STATUS.badRequest, { error: "unsupported_grant_type" });
25667
- return true;
25668
- }
25669
- answerServerJson(response, HTTP_STATUS.ok, { access_token: record.accessToken, refresh_token: record.refreshToken, expires_in: RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS, scope: RC_SELF_HOST_SCOPE_LIST.join(" ") });
25670
- return true;
25671
- }
25672
- if (method === "GET" && pathname === "/v1/oauth/hello") {
25673
- answerServerJson(response, HTTP_STATUS.ok, {});
25674
- return true;
25675
- }
25676
- return false;
25677
- }
25678
- if (method === "POST" && pathname.startsWith("/api/eval/")) {
25679
- await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
25680
- answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND6) });
25681
- return true;
25682
- }
25683
- if (method === "GET" && pathname === "/api/oauth/profile") {
25684
- const record = deps.credentialRecord();
25685
- if (record === void 0) {
25686
- answerServerJson(response, HTTP_SERVICE_UNAVAILABLE, { error: "the front door's self-hosted Remote Control surface is on but no credential has been minted for it" });
25687
- return true;
25688
- }
25689
- answerServerJson(response, HTTP_STATUS.ok, {
25690
- account: { uuid: record.accountUuid, display_name: "agent-shim self-hosted", created_at: (/* @__PURE__ */ new Date(0)).toISOString() },
25691
- organization: { uuid: record.organizationUuid, organization_type: "claude_max" }
25692
- });
25693
- return true;
25694
- }
25695
- if (method === "GET" && pathname === "/api/claude_code/policy_limits") {
25696
- answerServerJson(response, HTTP_STATUS.ok, {});
25697
- return true;
25698
- }
25699
- if (method === "POST" && pathname === "/api/oauth/validate") {
25700
- await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
25701
- const record = deps.credentialRecord();
25702
- if (record === void 0) {
25703
- answerServerJson(response, HTTP_SERVICE_UNAVAILABLE, { error: "the front door's self-hosted Remote Control surface is on but no credential has been minted for it" });
25704
- return true;
25705
- }
25706
- answerServerJson(response, HTTP_STATUS.ok, { scopes: [...RC_SELF_HOST_SCOPE_LIST], expiresAt: null, subscriptionType: "max", account_uuid: record.accountUuid, organization_uuid: record.organizationUuid });
25707
- return true;
25708
- }
25709
- if (method === "POST" && (pathname === "/api/event_logging/v2/batch" || pathname === "/api/claude_code/metrics" || pathname === "/api/claude_cli_feedback")) {
25710
- await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
25711
- answerServerJson(response, HTTP_STATUS.ok, {});
25712
- return true;
25713
- }
25714
- if (method === "GET" && pathname === "/api/hello") {
25715
- answerServerJson(response, HTTP_STATUS.ok, {});
25716
- return true;
25717
- }
25718
- return false;
25719
- }
25720
- };
25721
- }
25722
-
25723
26053
  // src/frontdoor/rcWebFetch.ts
25724
26054
  var dns2 = __toESM(require("node:dns"), 1);
25725
26055
  var http2 = __toESM(require("node:http"), 1);
@@ -25998,7 +26328,7 @@ var RC_SELF_HOST_WORKER_EPOCH = 1;
25998
26328
  var RC_STREAM_EVENT_NAME2 = "client_event";
25999
26329
  var CONFLICT_REASON_HEADER2 = "x-ccr-conflict-reason";
26000
26330
  var CONFLICT_REASON_EPOCH_STALE = "epoch_stale";
26001
- function isRecord15(value) {
26331
+ function isRecord16(value) {
26002
26332
  return typeof value === "object" && value !== null && !Array.isArray(value);
26003
26333
  }
26004
26334
  function isWebSearchRefusal(value) {
@@ -26082,7 +26412,7 @@ function parseJsonObject5(body) {
26082
26412
  } catch {
26083
26413
  return void 0;
26084
26414
  }
26085
- return isRecord15(parsed) ? parsed : void 0;
26415
+ return isRecord16(parsed) ? parsed : void 0;
26086
26416
  }
26087
26417
  function mintWorkerJwt(randomToken, issuedAt) {
26088
26418
  const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
@@ -26342,7 +26672,7 @@ data: ${JSON.stringify(envelope)}
26342
26672
  if (status !== void 0) {
26343
26673
  session.workerStatus = status;
26344
26674
  }
26345
- if (isRecord15(body?.external_metadata)) {
26675
+ if (isRecord16(body?.external_metadata)) {
26346
26676
  session.externalMetadata = body.external_metadata;
26347
26677
  }
26348
26678
  await answerJson2(response, HTTP_STATUS.ok, {});
@@ -26372,7 +26702,7 @@ data: ${JSON.stringify(envelope)}
26372
26702
  }
26373
26703
  const results = [];
26374
26704
  for (const event of events) {
26375
- if (!isRecord15(event) || !isRecord15(event.payload)) {
26705
+ if (!isRecord16(event) || !isRecord16(event.payload)) {
26376
26706
  await answerJson2(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "every event in a batch is an object carrying one payload object" } });
26377
26707
  return;
26378
26708
  }
@@ -26405,7 +26735,7 @@ data: ${JSON.stringify(envelope)}
26405
26735
  return;
26406
26736
  }
26407
26737
  for (const event of events) {
26408
- if (isRecord15(event)) {
26738
+ if (isRecord16(event)) {
26409
26739
  session.internalEvents.push({ eventId: deps.newUuid(), body: event });
26410
26740
  }
26411
26741
  }
@@ -26501,7 +26831,7 @@ data: ${JSON.stringify(envelope)}
26501
26831
  }
26502
26832
  const results = [];
26503
26833
  for (const event of events) {
26504
- if (!isRecord15(event) || !isRecord15(event.payload)) {
26834
+ if (!isRecord16(event) || !isRecord16(event.payload)) {
26505
26835
  await answerJson2(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "every event in a write is an object carrying one payload object" } });
26506
26836
  return;
26507
26837
  }
@@ -26546,7 +26876,9 @@ data: ${JSON.stringify(envelope)}
26546
26876
  return;
26547
26877
  }
26548
26878
  if (pathname !== RC_SESSIONS_PATH_PREFIX2 && !pathname.startsWith(`${RC_SESSIONS_PATH_PREFIX2}/`)) {
26549
- await answerJson2(response, HTTP_STATUS.notFound, { type: "error", error: { type: "api_error", message: `the self-hosted Remote Control surface serves no path "${pathname}"` } });
26879
+ const offline = rcSelfHostOfflineAnswer(pathname);
26880
+ deps.log?.(`rc selfhost: answered ${method} ${pathname} locally with ${String(offline.status)}; a self-hosted session's calls never leave the door`);
26881
+ await answerJson2(response, offline.status, offline.body);
26550
26882
  return;
26551
26883
  }
26552
26884
  if (pathname === RC_SESSIONS_PATH_PREFIX2) {
@@ -26611,7 +26943,7 @@ data: ${JSON.stringify(envelope)}
26611
26943
  await serveSessionPath(sessions.get(id), tail, request4, response);
26612
26944
  }
26613
26945
  };
26614
- const local = createRcSelfHostLocal({ now: deps.now, credentialRecord: deps.credentialRecord, readBody: readBody2 });
26946
+ const local = createRcSelfHostLocal({ now: deps.now, credentialRecord: deps.credentialRecord, readBody: readBody2, ownsLaunch: deps.ownsLaunch, ownsPeer: deps.ownsPeer, ...deps.log === void 0 ? {} : { log: deps.log } });
26615
26947
  return {
26616
26948
  route,
26617
26949
  local,
@@ -26629,103 +26961,6 @@ data: ${JSON.stringify(envelope)}
26629
26961
  };
26630
26962
  }
26631
26963
 
26632
- // src/frontdoor/rcSelfHostMint.ts
26633
- var import_node_path47 = __toESM(require("node:path"), 1);
26634
- init_identityRecords();
26635
- init_account();
26636
- var CREDENTIALS_FILE2 = ".credentials.json";
26637
- var CLAUDE_JSON2 = ".claude.json";
26638
- var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
26639
- var RC_SELF_HOST_RECORD_FILE = "credential.json";
26640
- var SELF_HOST_EMAIL = "selfhost@agent-shim.invalid";
26641
- var SELF_HOST_SUBSCRIPTION_TYPE = "max";
26642
- function isRecord16(value) {
26643
- return typeof value === "object" && value !== null && !Array.isArray(value);
26644
- }
26645
- function readJsonObject(fs17, file) {
26646
- const raw = fs17.readFileUtf8(file);
26647
- if (raw === void 0) {
26648
- return void 0;
26649
- }
26650
- let parsed;
26651
- try {
26652
- parsed = JSON.parse(raw);
26653
- } catch {
26654
- return void 0;
26655
- }
26656
- return isRecord16(parsed) ? parsed : void 0;
26657
- }
26658
- function readRcSelfHostRecord(fs17, frontdoorDir) {
26659
- const parsed = readJsonObject(fs17, import_node_path47.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
26660
- if (parsed === void 0) {
26661
- return void 0;
26662
- }
26663
- const { accessToken, refreshToken, organizationUuid, accountUuid } = parsed;
26664
- if (typeof accessToken !== "string" || accessToken === "" || typeof refreshToken !== "string" || refreshToken === "" || typeof organizationUuid !== "string" || organizationUuid === "" || typeof accountUuid !== "string" || accountUuid === "") {
26665
- return void 0;
26666
- }
26667
- return { accessToken, refreshToken, organizationUuid, accountUuid };
26668
- }
26669
- function mintRcSelfHostCredential(deps) {
26670
- if (!isIdentityName(deps.identity)) {
26671
- throw new Error(`"${deps.identity}" is not a valid identity name.`);
26672
- }
26673
- const id = identityIdOver(deps.fs, deps.identitiesDir, deps.identity);
26674
- if (id === void 0) {
26675
- throw new Error(`No identity named "${deps.identity}".`);
26676
- }
26677
- const identityDir = import_node_path47.default.join(deps.identitiesDir, id);
26678
- const credentialsFile = import_node_path47.default.join(identityDir, CREDENTIALS_FILE2);
26679
- const claudeJsonFile = import_node_path47.default.join(identityDir, CLAUDE_JSON2);
26680
- const recordDir = import_node_path47.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
26681
- const recordFile2 = import_node_path47.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
26682
- const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
26683
- const existingCredentials = readJsonObject(deps.fs, credentialsFile);
26684
- const existingOauth = isRecord16(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
26685
- const existingToken = typeof existingOauth?.accessToken === "string" && existingOauth.accessToken !== "" ? existingOauth.accessToken : void 0;
26686
- const existingIsOwn = existingToken !== void 0 && previousRecord?.accessToken === existingToken;
26687
- if (existingToken !== void 0 && !existingIsOwn && !deps.force) {
26688
- throw new Error(
26689
- `identity ${deps.identity} already holds an OAuth credential this door did not mint (a real claude.ai login): pass --force to replace it, or mint into an identity with no login. The self-hosted mode expects no Anthropic credential to be in play.`
26690
- );
26691
- }
26692
- const accessToken = `sk-ant-oat${deps.randomToken()}`;
26693
- const refreshToken = deps.randomToken();
26694
- const organizationUuid = deps.newUuid();
26695
- const accountUuid = deps.newUuid();
26696
- const mintedAt = new Date(deps.now()).toISOString();
26697
- deps.fs.mkdirPrivate(import_node_path47.default.dirname(credentialsFile));
26698
- deps.fs.writeFilePrivate(credentialsFile, `${JSON.stringify({ ...existingCredentials, claudeAiOauth: { accessToken, refreshToken, expiresAt: null, scopes: [...RC_SELF_HOST_SCOPE_LIST], subscriptionType: SELF_HOST_SUBSCRIPTION_TYPE, rateLimitTier: null } }, null, 2)}
26699
- `);
26700
- const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
26701
- const existingBlock = (value) => isRecord16(value) ? value : {};
26702
- deps.fs.writeFilePrivate(claudeJsonFile, `${JSON.stringify({
26703
- ...claudeJson,
26704
- oauthAccount: {
26705
- ...existingBlock(claudeJson.oauthAccount),
26706
- accountUuid,
26707
- emailAddress: SELF_HOST_EMAIL,
26708
- organizationUuid,
26709
- organizationName: "agent-shim self-hosted",
26710
- // The billing and creation fields exist so the CLI's "populate the account block if it is missing" step finds a complete block and skips its profile fetch; the door answers that fetch locally anyway, so these are the quiet path, not a load-bearing claim.
26711
- billingType: "stripe_subscription",
26712
- accountCreatedAt: mintedAt,
26713
- subscriptionCreatedAt: mintedAt
26714
- },
26715
- cachedGrowthBookFeatures: {
26716
- ...existingBlock(claudeJson.cachedGrowthBookFeatures),
26717
- tengu_ccr_bridge: true,
26718
- tengu_bridge_repl_v2: true,
26719
- tengu_bridge_repl_v2_cse_shim_enabled: true
26720
- }
26721
- }, null, 2)}
26722
- `);
26723
- deps.fs.mkdirPrivate(recordDir);
26724
- deps.fs.writeFilePrivate(recordFile2, `${JSON.stringify({ accessToken, refreshToken, organizationUuid, accountUuid }, null, 2)}
26725
- `);
26726
- return { identity: deps.identity, organizationUuid, credentialsFile, claudeJsonFile, recordFile: recordFile2, replaced: existingIsOwn };
26727
- }
26728
-
26729
26964
  // src/index.ts
26730
26965
  init_ensure2();
26731
26966