claude-use 14.5.1 → 14.6.1

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
 
@@ -7384,7 +7532,7 @@ function rcEventWriteResultFromAnswer(answer) {
7384
7532
  return { ok: true, sequenceNums };
7385
7533
  }
7386
7534
  function noOAuthCredentialResult(sessionId) {
7387
- return { ok: false, message: `no claude.ai OAuth bearer has been observed for session ${sessionId}: only worker calls crossed this door, and the worker JWT they carry is answered 401 on the client half. Reconnect Remote Control through this door and the create's own bearer will be observed` };
7535
+ return { ok: false, message: `no claude.ai OAuth bearer has been observed for session ${sessionId}: only worker calls crossed this door, and the worker JWT they carry is answered 401 on the client half. Reconnect Remote Control through this door and the create's own bearer will be observed`, refusal: "session-state" };
7388
7536
  }
7389
7537
  function rcSessionNotObservedMessage(sessionId) {
7390
7538
  return `the front door has not observed Remote Control session ${sessionId}: it may never have passed through this door, or it ended or expired (an entry lives only a bounded idle period past its last observed traffic)`;
@@ -7405,7 +7553,7 @@ function rcWriteHeaders(credential) {
7405
7553
  async function injectRcUserMessage(deps, sessionId, text) {
7406
7554
  const credential = deps.credentialOf(sessionId);
7407
7555
  if (credential === void 0) {
7408
- return { ok: false, message: rcSessionNotObservedMessage(sessionId) };
7556
+ return { ok: false, message: rcSessionNotObservedMessage(sessionId), refusal: "not-observed" };
7409
7557
  }
7410
7558
  if (credential.authorization === void 0) {
7411
7559
  return noOAuthCredentialResult(sessionId);
@@ -7502,22 +7650,22 @@ function questionAnswerInput(deps, sessionId, pending, decision) {
7502
7650
  async function answerRcControlRequest(deps, sessionId, requestId, decision) {
7503
7651
  const credential = deps.credentialOf(sessionId);
7504
7652
  if (credential === void 0) {
7505
- return { ok: false, message: rcSessionNotObservedMessage(sessionId) };
7653
+ return { ok: false, message: rcSessionNotObservedMessage(sessionId), refusal: "not-observed" };
7506
7654
  }
7507
7655
  if (credential.authorization === void 0) {
7508
7656
  return noOAuthCredentialResult(sessionId);
7509
7657
  }
7510
7658
  const pending = deps.pendingOf(sessionId).find((candidate) => candidate.requestId === requestId);
7511
7659
  if (pending === void 0) {
7512
- return { ok: false, message: `the front door has not observed control request ${requestId} pending on session ${sessionId}: it was answered already (by this door, by an attached client or in the session's own terminal), the worker withdrew it, or it never passed through this door` };
7660
+ return { ok: false, message: `the front door has not observed control request ${requestId} pending on session ${sessionId}: it was answered already (by this door, by an attached client or in the session's own terminal), the worker withdrew it, or it never passed through this door`, refusal: "not-observed" };
7513
7661
  }
7514
7662
  const updatedInput = questionAnswerInput(deps, sessionId, pending, decision);
7515
7663
  if (updatedInput !== void 0 && "error" in updatedInput) {
7516
- return { ok: false, message: updatedInput.error };
7664
+ return { ok: false, message: updatedInput.error, refusal: "invalid-input" };
7517
7665
  }
7518
7666
  const release = deps.claimPending(sessionId, requestId);
7519
7667
  if (release === void 0) {
7520
- return { ok: false, message: `another answer to control request ${requestId} on session ${sessionId} is being written right now; the worker takes only one, so this one was not sent` };
7668
+ return { ok: false, message: `another answer to control request ${requestId} on session ${sessionId} is being written right now; the worker takes only one, so this one was not sent`, refusal: "session-state" };
7521
7669
  }
7522
7670
  const body = JSON.stringify(buildRcEventWriteBody(buildRcControlResponsePayload(requestId, decision, updatedInput?.input)));
7523
7671
  let answer;
@@ -7538,7 +7686,7 @@ async function answerRcControlRequest(deps, sessionId, requestId, decision) {
7538
7686
  async function deliverRcClientPayload(deps, sessionId, payload, action, to = "events") {
7539
7687
  const credential = deps.credentialOf(sessionId);
7540
7688
  if (credential === void 0) {
7541
- return { ok: false, message: rcSessionNotObservedMessage(sessionId) };
7689
+ return { ok: false, message: rcSessionNotObservedMessage(sessionId), refusal: "not-observed" };
7542
7690
  }
7543
7691
  if (credential.authorization === void 0) {
7544
7692
  return noOAuthCredentialResult(sessionId);
@@ -7563,7 +7711,7 @@ async function interruptRcSession(deps, sessionId) {
7563
7711
  }
7564
7712
  async function setRcSessionModel(deps, sessionId, model) {
7565
7713
  if (model === "") {
7566
- return { ok: false, message: "a set-model write needs a non-empty model id: the SDK's own field treats an omitted or null value as a reset to the session default, which this operation never sends, and an empty string is neither" };
7714
+ return { ok: false, message: "a set-model write needs a non-empty model id: the SDK's own field treats an omitted or null value as a reset to the session default, which this operation never sends, and an empty string is neither", refusal: "invalid-input" };
7567
7715
  }
7568
7716
  const requestId = deps.newUuid();
7569
7717
  const result = await deliverRcClientPayload(deps, sessionId, buildRcSetModelPayload(requestId, model), `set the model on session ${sessionId}`);
@@ -7576,7 +7724,7 @@ async function setRcSessionPermissionMode(deps, sessionId, mode) {
7576
7724
  }
7577
7725
  async function endRcSession(deps, sessionId, reason) {
7578
7726
  if (reason === "") {
7579
- return { ok: false, message: "an end-session write needs either no reason or a non-empty one: the worker reads an absent reason as its own unspecified form, and an empty string is neither" };
7727
+ return { ok: false, message: "an end-session write needs either no reason or a non-empty one: the worker reads an absent reason as its own unspecified form, and an empty string is neither", refusal: "invalid-input" };
7580
7728
  }
7581
7729
  const requestId = deps.newUuid();
7582
7730
  const result = await deliverRcClientPayload(deps, sessionId, buildRcEndSessionPayload(requestId, reason), `end session ${sessionId}`);
@@ -7594,10 +7742,10 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
7594
7742
  }
7595
7743
  async function readRcSessionFile(deps, sessionId, path59, options) {
7596
7744
  if (path59 === "") {
7597
- return { ok: false, message: "a read-file write needs a non-empty path: the SDK's own field names the file the worker resolves against the session's cwd, and an empty string names none" };
7745
+ return { ok: false, message: "a read-file write needs a non-empty path: the SDK's own field names the file the worker resolves against the session's cwd, and an empty string names none", refusal: "invalid-input" };
7598
7746
  }
7599
7747
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
7600
- return { ok: false, message: "a read-file write's max-bytes is a positive whole number of bytes: the SDK's own field caps the read, and a zero or negative cap reads nothing" };
7748
+ return { ok: false, message: "a read-file write's max-bytes is a positive whole number of bytes: the SDK's own field caps the read, and a zero or negative cap reads nothing", refusal: "invalid-input" };
7601
7749
  }
7602
7750
  const requestId = deps.newUuid();
7603
7751
  const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path59, options), `read ${path59} from session ${sessionId}`);
@@ -7615,7 +7763,7 @@ async function getRcSessionMcpStatus(deps, sessionId) {
7615
7763
  }
7616
7764
  async function reconnectRcSessionMcpServer(deps, sessionId, serverName) {
7617
7765
  if (serverName === "") {
7618
- return { ok: false, message: "an mcp-reconnect write needs a non-empty server name: the SDK's own field names the server as mcp_status reports it, and an empty string names none" };
7766
+ return { ok: false, message: "an mcp-reconnect write needs a non-empty server name: the SDK's own field names the server as mcp_status reports it, and an empty string names none", refusal: "invalid-input" };
7619
7767
  }
7620
7768
  const requestId = deps.newUuid();
7621
7769
  const result = await deliverRcClientPayload(deps, sessionId, buildRcMcpReconnectPayload(requestId, serverName), `reconnect MCP server ${serverName} on session ${sessionId}`);
@@ -7623,7 +7771,7 @@ async function reconnectRcSessionMcpServer(deps, sessionId, serverName) {
7623
7771
  }
7624
7772
  async function authenticateRcSessionMcpServer(deps, sessionId, serverName, redirectUri) {
7625
7773
  if (serverName === "" || redirectUri === "") {
7626
- return { ok: false, message: "an mcp-authenticate write needs a non-empty server name and redirect URI: the CLI's own request names the server and where its OAuth flow redirects back to, and an empty string names neither" };
7774
+ return { ok: false, message: "an mcp-authenticate write needs a non-empty server name and redirect URI: the CLI's own request names the server and where its OAuth flow redirects back to, and an empty string names neither", refusal: "invalid-input" };
7627
7775
  }
7628
7776
  const requestId = deps.newUuid();
7629
7777
  const result = await deliverRcClientPayload(deps, sessionId, buildRcMcpAuthenticatePayload(requestId, serverName, redirectUri), `authenticate MCP server ${serverName} on session ${sessionId}`);
@@ -7631,7 +7779,7 @@ async function authenticateRcSessionMcpServer(deps, sessionId, serverName, redir
7631
7779
  }
7632
7780
  async function submitRcSessionMcpOAuthCallbackUrl(deps, sessionId, serverName, callbackUrl) {
7633
7781
  if (serverName === "" || callbackUrl === "") {
7634
- return { ok: false, message: "an mcp-oauth-callback-url write needs a non-empty server name and callback URL: the CLI's own request names the server and the URL its OAuth flow landed on, and an empty string names neither" };
7782
+ return { ok: false, message: "an mcp-oauth-callback-url write needs a non-empty server name and callback URL: the CLI's own request names the server and the URL its OAuth flow landed on, and an empty string names neither", refusal: "invalid-input" };
7635
7783
  }
7636
7784
  const requestId = deps.newUuid();
7637
7785
  const result = await deliverRcClientPayload(deps, sessionId, buildRcMcpOAuthCallbackUrlPayload(requestId, serverName, callbackUrl), `hand MCP server ${serverName}'s OAuth callback to session ${sessionId}`);
@@ -7642,7 +7790,7 @@ async function sendRcKeepAlive(deps, sessionId) {
7642
7790
  }
7643
7791
  async function teleportRcSession(deps, sessionId, marker) {
7644
7792
  if (marker === "") {
7645
- return { ok: false, message: "a teleport write needs a non-empty marker: the teleport relay anchors on a marker line's uuid and string content, and an empty string carries neither" };
7793
+ return { ok: false, message: "a teleport write needs a non-empty marker: the teleport relay anchors on a marker line's uuid and string content, and an empty string carries neither", refusal: "invalid-input" };
7646
7794
  }
7647
7795
  return await deliverRcClientPayload(deps, sessionId, buildRcUserMessagePayload(deps.newUuid(), sessionId, marker), `teleport a marker into session ${sessionId}`, "teleport-events");
7648
7796
  }
@@ -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.1",
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;
@@ -20477,10 +20625,10 @@ function createRcSessionCommands(deps) {
20477
20625
  return void 0;
20478
20626
  }
20479
20627
  if ("refused" in target) {
20480
- return { kind: "refused", message: target.refused };
20628
+ return { kind: "refused", message: target.refused, refusal: "session-state" };
20481
20629
  }
20482
20630
  if (target.version === void 0 || !RC_SESSION_COMMAND_VERIFIED_VERSIONS.includes(target.version)) {
20483
- return { kind: "refused", message: unverifiedVersionMessage(sessionId, target.version, route === "supervised" ? "its supervisor's control plugin has not loaded" : "its launch's control plugin has not loaded") };
20631
+ return { kind: "refused", message: unverifiedVersionMessage(sessionId, target.version, route === "supervised" ? "its supervisor's control plugin has not loaded" : "its launch's control plugin has not loaded"), refusal: "session-state" };
20484
20632
  }
20485
20633
  return { kind: route, target };
20486
20634
  };
@@ -20494,18 +20642,18 @@ function createRcSessionCommands(deps) {
20494
20642
  return launched;
20495
20643
  }
20496
20644
  if (!deps.isObserved(sessionId)) {
20497
- return { kind: "refused", message: `the front door has not observed Remote Control session ${sessionId}` };
20645
+ return { kind: "refused", message: `the front door has not observed Remote Control session ${sessionId}`, refusal: "not-observed" };
20498
20646
  }
20499
20647
  if (deps.selfHost === void 0) {
20500
- return { kind: "refused", message: unsupportedMessage(sessionId) };
20648
+ return { kind: "refused", message: unsupportedMessage(sessionId), refusal: "session-state" };
20501
20649
  }
20502
20650
  const unavailable = deps.selfHost.unavailable();
20503
20651
  if (unavailable !== void 0) {
20504
- return { kind: "refused", message: `${noPluginReason(sessionId)}, and the door's self-hosted surface cannot take a command: ${unavailable}` };
20652
+ return { kind: "refused", message: `${noPluginReason(sessionId)}, and the door's self-hosted surface cannot take a command: ${unavailable}`, refusal: "session-state" };
20505
20653
  }
20506
20654
  const version = deps.selfHost.versionOf(sessionId);
20507
20655
  if (version === void 0 || !RC_SESSION_COMMAND_VERIFIED_VERSIONS.includes(version)) {
20508
- return { kind: "refused", message: unverifiedVersionMessage(sessionId, version, "no system/init from its worker has been observed on its stream; send it a prompt so it reports one") };
20656
+ return { kind: "refused", message: unverifiedVersionMessage(sessionId, version, "no system/init from its worker has been observed on its stream; send it a prompt so it reports one"), refusal: "session-state" };
20509
20657
  }
20510
20658
  return { kind: "self-hosted", selfHost: deps.selfHost };
20511
20659
  };
@@ -20516,7 +20664,7 @@ function createRcSessionCommands(deps) {
20516
20664
  }
20517
20665
  const resolved = await resolveRoute(sessionId);
20518
20666
  if (resolved.kind === "refused") {
20519
- return { ok: false, message: resolved.message };
20667
+ return { ok: false, message: resolved.message, refusal: resolved.refusal };
20520
20668
  }
20521
20669
  if (resolved.kind !== "self-hosted") {
20522
20670
  const waitMs2 = options.waitMs ?? COMPACT_TIMEOUT_MS;
@@ -20542,7 +20690,7 @@ function createRcSessionCommands(deps) {
20542
20690
  const transcriptGoal = async (sessionId, target) => {
20543
20691
  const goal = target.transcriptPath === void 0 ? void 0 : await deps.goalOf(target.transcriptPath);
20544
20692
  if (goal === void 0) {
20545
- return { ok: false, message: `session ${sessionId}'s transcript has not been recorded yet, which is where its goal is read from; retry once it has finished a turn` };
20693
+ return { ok: false, message: `session ${sessionId}'s transcript has not been recorded yet, which is where its goal is read from; retry once it has finished a turn`, refusal: "session-state" };
20546
20694
  }
20547
20695
  return { ok: true, report: goal };
20548
20696
  };
@@ -20558,7 +20706,7 @@ function createRcSessionCommands(deps) {
20558
20706
  const waitOf = (options) => options.waitMs;
20559
20707
  const transcriptPluginTurns = async (sessionId, target) => {
20560
20708
  const turns = target.transcriptPath === void 0 ? void 0 : await deps.pluginTurnsOf(target.transcriptPath);
20561
- return turns === void 0 ? { ok: false, message: `session ${sessionId}'s transcript has not been recorded yet, which is where a turn is confirmed from; retry once it has finished a turn` } : { ok: true, report: turns };
20709
+ return turns === void 0 ? { ok: false, message: `session ${sessionId}'s transcript has not been recorded yet, which is where a turn is confirmed from; retry once it has finished a turn`, refusal: "session-state" } : { ok: true, report: turns };
20562
20710
  };
20563
20711
  return {
20564
20712
  /** Which route the verbs would take for the session now, or the refusal naming why none would; reads only, outside the session's queue, so a verb waiting on the session never delays it. */
@@ -20571,13 +20719,13 @@ function createRcSessionCommands(deps) {
20571
20719
  */
20572
20720
  turn: async (sessionId, text, options = {}) => {
20573
20721
  if (text.trim() === "") {
20574
- return { ok: false, message: "a turn needs non-empty text" };
20722
+ return { ok: false, message: "a turn needs non-empty text", refusal: "invalid-input" };
20575
20723
  }
20576
20724
  if (text.trimStart().startsWith("/")) {
20577
- return { ok: false, message: "a turn's text starts with /, which the session would read as a slash command rather than a message, and the turn could not be confirmed as one; use the goal or compaction verbs for those commands, or start the text with something else" };
20725
+ return { ok: false, message: "a turn's text starts with /, which the session would read as a slash command rather than a message, and the turn could not be confirmed as one; use the goal or compaction verbs for those commands, or start the text with something else", refusal: "invalid-input" };
20578
20726
  }
20579
20727
  if (text.length > RC_TURN_TEXT_MAX_CHARS) {
20580
- return { ok: false, message: `a turn's text is limited to ${String(RC_TURN_TEXT_MAX_CHARS)} characters, and this one has ${String(text.length)}` };
20728
+ return { ok: false, message: `a turn's text is limited to ${String(RC_TURN_TEXT_MAX_CHARS)} characters, and this one has ${String(text.length)}`, refusal: "invalid-input" };
20581
20729
  }
20582
20730
  return await onRoute(sessionId, options, {
20583
20731
  plugin: async (target, route, signal, waitMs) => {
@@ -20626,16 +20774,16 @@ function createRcSessionCommands(deps) {
20626
20774
  goalSet: async (sessionId, condition, options = {}) => {
20627
20775
  const trimmed = condition.trim();
20628
20776
  if (trimmed === "") {
20629
- return { ok: false, message: "a goal set needs a non-empty condition" };
20777
+ return { ok: false, message: "a goal set needs a non-empty condition", refusal: "invalid-input" };
20630
20778
  }
20631
20779
  if (RC_GOAL_CLEAR_WORDS.includes(trimmed.toLowerCase())) {
20632
- return { ok: false, message: `"${trimmed}" cannot be set as a goal condition: /goal reads ${RC_GOAL_CLEAR_WORDS.join(", ")} as a request to clear the goal, so use the clear verb for that` };
20780
+ return { ok: false, message: `"${trimmed}" cannot be set as a goal condition: /goal reads ${RC_GOAL_CLEAR_WORDS.join(", ")} as a request to clear the goal, so use the clear verb for that`, refusal: "invalid-input" };
20633
20781
  }
20634
20782
  if (/[\r\n]/u.test(trimmed)) {
20635
- return { ok: false, message: "a goal condition is one line: /goal reads its condition from the line it is typed on, and both routes confirm the goal by the exact condition, so a condition spanning lines is refused rather than set as something else" };
20783
+ return { ok: false, message: "a goal condition is one line: /goal reads its condition from the line it is typed on, and both routes confirm the goal by the exact condition, so a condition spanning lines is refused rather than set as something else", refusal: "invalid-input" };
20636
20784
  }
20637
20785
  if (trimmed.length > RC_GOAL_CONDITION_MAX_CHARS) {
20638
- return { ok: false, message: `a goal condition is limited to ${String(RC_GOAL_CONDITION_MAX_CHARS)} characters, and this one has ${String(trimmed.length)}` };
20786
+ return { ok: false, message: `a goal condition is limited to ${String(RC_GOAL_CONDITION_MAX_CHARS)} characters, and this one has ${String(trimmed.length)}`, refusal: "invalid-input" };
20639
20787
  }
20640
20788
  return await onRoute(sessionId, options, {
20641
20789
  plugin: async (target, route, signal, waitMs) => {
@@ -20778,17 +20926,25 @@ function doorApiAuth(expectedToken) {
20778
20926
  }
20779
20927
  var RC_API_TAG = "remote-control";
20780
20928
  var RC_DIRECTIVE_TAG = "remote-control-directives";
20929
+ var RC_REFUSAL_CODES = {
20930
+ "invalid-input": "BAD_REQUEST",
20931
+ "not-observed": "NOT_FOUND",
20932
+ "session-state": "CONFLICT"
20933
+ };
20934
+ function refusalOf(failure) {
20935
+ return new import_client.ORPCError(failure.refusal === void 0 ? "BAD_GATEWAY" : RC_REFUSAL_CODES[failure.refusal], { message: failure.message });
20936
+ }
20781
20937
  function createRcApiRouter(deps) {
20782
20938
  const authed = doorApiAuth(deps.expectedToken);
20783
20939
  const delivered = (sessionId, result) => {
20784
20940
  if (!result.ok) {
20785
- throw new import_client.ORPCError("BAD_GATEWAY", { message: result.message });
20941
+ throw refusalOf(result);
20786
20942
  }
20787
20943
  return result.sequenceNums;
20788
20944
  };
20789
20945
  const deliveredControl = (sessionId, result) => {
20790
20946
  if (!result.ok) {
20791
- throw new import_client.ORPCError("BAD_GATEWAY", { message: result.message });
20947
+ throw refusalOf(result);
20792
20948
  }
20793
20949
  if (result.requestId === void 0) {
20794
20950
  throw new import_client.ORPCError("INTERNAL_SERVER_ERROR", { message: "the control request was delivered but the door cannot name the request id it minted, so the worker's answer cannot be matched" });
@@ -20797,7 +20953,7 @@ function createRcApiRouter(deps) {
20797
20953
  };
20798
20954
  const commanded = (sessionId, result) => {
20799
20955
  if (!result.ok) {
20800
- throw new import_client.ORPCError("BAD_GATEWAY", { message: result.message });
20956
+ throw refusalOf(result);
20801
20957
  }
20802
20958
  return { session: sessionId, ...result.report };
20803
20959
  };
@@ -21436,7 +21592,7 @@ var ResetRowSchema = import_zod29.z.strictObject({
21436
21592
  var ResetScheduleSchema = import_zod29.z.strictObject({ resets: import_zod29.z.readonly(import_zod29.z.array(ResetRowSchema)) });
21437
21593
 
21438
21594
  // src/frontdoor/controlSchemas.ts
21439
- var import_node_path45 = __toESM(require("node:path"), 1);
21595
+ var import_node_path46 = __toESM(require("node:path"), 1);
21440
21596
  var import_zod39 = require("zod");
21441
21597
 
21442
21598
  // src/codex/doctor.ts
@@ -21522,7 +21678,7 @@ function resolveMiseDispatcher(target, pathDirs, env, trustedExecutable) {
21522
21678
  }
21523
21679
 
21524
21680
  // src/doctorReport.ts
21525
- var import_node_path44 = __toESM(require("node:path"), 1);
21681
+ var import_node_path45 = __toESM(require("node:path"), 1);
21526
21682
  init_signIn();
21527
21683
  init_identityAccounts();
21528
21684
  init_read();
@@ -22371,6 +22527,284 @@ function pushHeadroomAllowlist(push, allowlist, daemon) {
22371
22527
  // src/doctorReport.ts
22372
22528
  init_state2();
22373
22529
  init_supervisor2();
22530
+
22531
+ // src/frontdoor/rcSelfHostMint.ts
22532
+ var import_node_path44 = __toESM(require("node:path"), 1);
22533
+ init_identityRecords();
22534
+ init_account();
22535
+
22536
+ // src/frontdoor/rcSelfHostLocal.ts
22537
+ init_http();
22538
+ init_rcControl();
22539
+
22540
+ // src/frontdoor/rcSelfHostOffline.ts
22541
+ init_http();
22542
+ var GITHUB_SYNC_PATH = /^\/api\/oauth\/organizations\/[^/]+\/sync\/github\/auth$/;
22543
+ var OFF_STATE_ENTRIES = [
22544
+ { matches: (pathname) => pathname === "/api/claude_cli/bootstrap", answer: { status: HTTP_STATUS.ok, body: {} } },
22545
+ { matches: (pathname) => pathname === "/api/claude_code_penguin_mode", answer: { status: HTTP_STATUS.ok, body: { enabled: false, disabled_reason: "preference" } } },
22546
+ { matches: (pathname) => GITHUB_SYNC_PATH.test(pathname), answer: { status: HTTP_STATUS.ok, body: { is_authenticated: false } } },
22547
+ { matches: (pathname) => pathname === "/v1/mcp_servers", answer: { status: HTTP_STATUS.ok, body: { data: [], next_page: null } } },
22548
+ { matches: (pathname) => pathname === "/mcp-registry/v0/servers", answer: { status: HTTP_STATUS.ok, body: { servers: [], metadata: { count: 0 } } } }
22549
+ ];
22550
+ function rcSelfHostOfflineAnswer(pathname) {
22551
+ const entry = OFF_STATE_ENTRIES.find((candidate) => candidate.matches(pathname));
22552
+ if (entry !== void 0) {
22553
+ return entry.answer;
22554
+ }
22555
+ return {
22556
+ status: HTTP_STATUS.notFound,
22557
+ 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` } }
22558
+ };
22559
+ }
22560
+ function isRcSessionFamilyPath(pathname) {
22561
+ return pathname === "/v1/code/sessions" || pathname.startsWith("/v1/code/sessions/") || pathname === "/v1/sessions" || pathname.startsWith("/v1/sessions/");
22562
+ }
22563
+
22564
+ // src/frontdoor/rcSelfHostLocal.ts
22565
+ init_route();
22566
+ var RC_SELF_HOST_OAUTH_HOST = "platform.claude.com";
22567
+ var RC_SELF_HOST_EMAIL = "selfhost@agent-shim.invalid";
22568
+ var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"];
22569
+ var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
22570
+ var MS_PER_SECOND6 = 1e3;
22571
+ var HTTP_SERVICE_UNAVAILABLE = 503;
22572
+ function isRecord10(value) {
22573
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22574
+ }
22575
+ function parseJsonObject2(body) {
22576
+ let parsed;
22577
+ try {
22578
+ parsed = JSON.parse(body);
22579
+ } catch {
22580
+ return void 0;
22581
+ }
22582
+ return isRecord10(parsed) ? parsed : void 0;
22583
+ }
22584
+ function growthBookFeatures() {
22585
+ return {
22586
+ tengu_ccr_bridge: { defaultValue: true },
22587
+ tengu_bridge_repl_v2: { defaultValue: true },
22588
+ tengu_bridge_repl_v2_cse_shim_enabled: { defaultValue: true },
22589
+ tengu_bridge_min_version: { defaultValue: { minVersion: "0.0.0" } }
22590
+ };
22591
+ }
22592
+ var answerServerJson = (response, status, body) => {
22593
+ const text = JSON.stringify(body);
22594
+ response.writeHead(status, { "content-type": "application/json", "content-length": String(Buffer.byteLength(text, "utf8")) });
22595
+ response.end(text);
22596
+ };
22597
+ function createRcSelfHostLocal(deps) {
22598
+ const answerOffline = (method, pathname, request4, response) => {
22599
+ request4.resume();
22600
+ const offline = rcSelfHostOfflineAnswer(pathname);
22601
+ deps.log?.(`rc selfhost: answered ${method} ${pathname} locally with ${String(offline.status)}; a self-hosted session's calls never leave the door`);
22602
+ answerServerJson(response, offline.status, offline.body);
22603
+ };
22604
+ return {
22605
+ ownsLaunch: deps.ownsLaunch,
22606
+ ownsPeer: deps.ownsPeer,
22607
+ mintGeneration: () => {
22608
+ const minted = deps.credentialRecord();
22609
+ return minted === void 0 ? "none" : minted.identityId === void 0 ? "every" : `identity:${minted.identityId}`;
22610
+ },
22611
+ serve: async (host, request4, response) => {
22612
+ const method = (request4.method ?? "").toUpperCase();
22613
+ const pathname = new URL(request4.url ?? "/", "http://127.0.0.1").pathname;
22614
+ const minted = deps.credentialRecord();
22615
+ if (minted !== void 0 && minted.identityId === void 0) {
22616
+ request4.resume();
22617
+ deps.log?.(`rc selfhost: refused ${method} ${pathname}: the minted credential names no identity; mint it again`);
22618
+ 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" } });
22619
+ return true;
22620
+ }
22621
+ if (host === RC_SELF_HOST_OAUTH_HOST) {
22622
+ if (method === "POST" && pathname === "/v1/oauth/token") {
22623
+ const body = parseJsonObject2(await deps.readBody(request4, CONTROL_BODY_CAP_BYTES));
22624
+ const record = deps.credentialRecord();
22625
+ if (record === void 0) {
22626
+ 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" });
22627
+ return true;
22628
+ }
22629
+ if (body?.grant_type !== void 0 && body.grant_type !== "refresh_token") {
22630
+ answerServerJson(response, HTTP_STATUS.badRequest, { error: "unsupported_grant_type" });
22631
+ return true;
22632
+ }
22633
+ 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(" ") });
22634
+ return true;
22635
+ }
22636
+ if (method === "GET" && pathname === "/v1/oauth/hello") {
22637
+ answerServerJson(response, HTTP_STATUS.ok, {});
22638
+ return true;
22639
+ }
22640
+ answerOffline(method, pathname, request4, response);
22641
+ return true;
22642
+ }
22643
+ if (method === "POST" && pathname.startsWith("/api/eval/")) {
22644
+ await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
22645
+ answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND6) });
22646
+ return true;
22647
+ }
22648
+ if (method === "GET" && pathname === "/api/oauth/profile") {
22649
+ const record = deps.credentialRecord();
22650
+ if (record === void 0) {
22651
+ 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" });
22652
+ return true;
22653
+ }
22654
+ answerServerJson(response, HTTP_STATUS.ok, {
22655
+ // The email is required: the client's profile schema rejects an answer without `account.email`, discarding the whole profile.
22656
+ account: { uuid: record.accountUuid, email: RC_SELF_HOST_EMAIL, display_name: "agent-shim self-hosted", created_at: (/* @__PURE__ */ new Date(0)).toISOString() },
22657
+ organization: { uuid: record.organizationUuid, organization_type: "claude_max" }
22658
+ });
22659
+ return true;
22660
+ }
22661
+ if (method === "GET" && pathname === "/api/claude_code/policy_limits") {
22662
+ answerServerJson(response, HTTP_STATUS.ok, {});
22663
+ return true;
22664
+ }
22665
+ if (method === "POST" && pathname === "/api/oauth/validate") {
22666
+ await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
22667
+ const record = deps.credentialRecord();
22668
+ if (record === void 0) {
22669
+ 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" });
22670
+ return true;
22671
+ }
22672
+ answerServerJson(response, HTTP_STATUS.ok, { scopes: [...RC_SELF_HOST_SCOPE_LIST], expiresAt: null, subscriptionType: "max", account_uuid: record.accountUuid, organization_uuid: record.organizationUuid });
22673
+ return true;
22674
+ }
22675
+ if (method === "POST" && (pathname === "/api/event_logging/v2/batch" || pathname === "/api/claude_code/metrics" || pathname === "/api/claude_cli_feedback")) {
22676
+ await deps.readBody(request4, CONTROL_BODY_CAP_BYTES);
22677
+ answerServerJson(response, HTTP_STATUS.ok, {});
22678
+ return true;
22679
+ }
22680
+ if (method === "GET" && pathname === "/api/hello") {
22681
+ answerServerJson(response, HTTP_STATUS.ok, {});
22682
+ return true;
22683
+ }
22684
+ if (pathname.startsWith("/v1/") && (isRcSessionFamilyPath(pathname) || internalHeaderValue(request4.headers, PROVIDER_HEADER) !== void 0)) {
22685
+ return false;
22686
+ }
22687
+ answerOffline(method, pathname, request4, response);
22688
+ return true;
22689
+ }
22690
+ };
22691
+ }
22692
+
22693
+ // src/frontdoor/rcSelfHostMint.ts
22694
+ init_capability();
22695
+ var CREDENTIALS_FILE2 = ".credentials.json";
22696
+ var CLAUDE_JSON2 = ".claude.json";
22697
+ var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
22698
+ var RC_SELF_HOST_RECORD_FILE = "credential.json";
22699
+ var SELF_HOST_SUBSCRIPTION_TYPE = "max";
22700
+ function isRecord11(value) {
22701
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22702
+ }
22703
+ function readJsonObject(fs17, file) {
22704
+ const raw = fs17.readFileUtf8(file);
22705
+ if (raw === void 0) {
22706
+ return void 0;
22707
+ }
22708
+ let parsed;
22709
+ try {
22710
+ parsed = JSON.parse(raw);
22711
+ } catch {
22712
+ return void 0;
22713
+ }
22714
+ return isRecord11(parsed) ? parsed : void 0;
22715
+ }
22716
+ function readRcSelfHostRecord(fs17, frontdoorDir) {
22717
+ const parsed = readJsonObject(fs17, import_node_path44.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
22718
+ if (parsed === void 0) {
22719
+ return void 0;
22720
+ }
22721
+ const { accessToken, refreshToken, organizationUuid, accountUuid, identityId } = parsed;
22722
+ if (typeof accessToken !== "string" || accessToken === "" || typeof refreshToken !== "string" || refreshToken === "" || typeof organizationUuid !== "string" || organizationUuid === "" || typeof accountUuid !== "string" || accountUuid === "") {
22723
+ return void 0;
22724
+ }
22725
+ return { accessToken, refreshToken, organizationUuid, accountUuid, ...typeof identityId === "string" && identityId !== "" ? { identityId } : {} };
22726
+ }
22727
+ function identitiesHoldingMint(fs17, identitiesDir, record) {
22728
+ return fs17.readdir(identitiesDir).filter((id) => {
22729
+ if (id.startsWith(".")) {
22730
+ return false;
22731
+ }
22732
+ const oauth = readJsonObject(fs17, import_node_path44.default.join(identitiesDir, id, CREDENTIALS_FILE2))?.claudeAiOauth;
22733
+ return isRecord11(oauth) && typeof oauth.accessToken === "string" && isLiveCapability(oauth.accessToken, [record.accessToken]);
22734
+ });
22735
+ }
22736
+ function rcSelfHostMintFacts(fs17, identitiesDir, frontdoorDir) {
22737
+ const record = readRcSelfHostRecord(fs17, frontdoorDir);
22738
+ if (record === void 0) {
22739
+ return {};
22740
+ }
22741
+ if (record.identityId !== void 0) {
22742
+ return { rcSelfHostMint: { attributable: true } };
22743
+ }
22744
+ const holders = identitiesHoldingMint(fs17, identitiesDir, record).length;
22745
+ return { rcSelfHostMint: { attributable: holders === 1, holders } };
22746
+ }
22747
+ function mintRcSelfHostCredential(deps) {
22748
+ if (!isIdentityName(deps.identity)) {
22749
+ throw new Error(`"${deps.identity}" is not a valid identity name.`);
22750
+ }
22751
+ const id = identityIdOver(deps.fs, deps.identitiesDir, deps.identity);
22752
+ if (id === void 0) {
22753
+ throw new Error(`No identity named "${deps.identity}".`);
22754
+ }
22755
+ const identityDir = import_node_path44.default.join(deps.identitiesDir, id);
22756
+ const credentialsFile = import_node_path44.default.join(identityDir, CREDENTIALS_FILE2);
22757
+ const claudeJsonFile = import_node_path44.default.join(identityDir, CLAUDE_JSON2);
22758
+ const recordDir = import_node_path44.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
22759
+ const recordFile2 = import_node_path44.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
22760
+ const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
22761
+ const existingCredentials = readJsonObject(deps.fs, credentialsFile);
22762
+ const existingOauth = isRecord11(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
22763
+ const existingToken = typeof existingOauth?.accessToken === "string" && existingOauth.accessToken !== "" ? existingOauth.accessToken : void 0;
22764
+ const existingIsOwn = existingToken !== void 0 && previousRecord?.accessToken === existingToken;
22765
+ if (existingToken !== void 0 && !existingIsOwn && !deps.force) {
22766
+ throw new Error(
22767
+ `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.`
22768
+ );
22769
+ }
22770
+ const accessToken = `sk-ant-oat${deps.randomToken()}`;
22771
+ const refreshToken = deps.randomToken();
22772
+ const organizationUuid = deps.newUuid();
22773
+ const accountUuid = deps.newUuid();
22774
+ const mintedAt = new Date(deps.now()).toISOString();
22775
+ deps.fs.mkdirPrivate(import_node_path44.default.dirname(credentialsFile));
22776
+ 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)}
22777
+ `);
22778
+ const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
22779
+ const existingBlock = (value) => isRecord11(value) ? value : {};
22780
+ deps.fs.writeFilePrivate(claudeJsonFile, `${JSON.stringify({
22781
+ ...claudeJson,
22782
+ oauthAccount: {
22783
+ ...existingBlock(claudeJson.oauthAccount),
22784
+ accountUuid,
22785
+ emailAddress: RC_SELF_HOST_EMAIL,
22786
+ organizationUuid,
22787
+ organizationName: "agent-shim self-hosted",
22788
+ // 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.
22789
+ billingType: "stripe_subscription",
22790
+ accountCreatedAt: mintedAt,
22791
+ subscriptionCreatedAt: mintedAt
22792
+ },
22793
+ cachedGrowthBookFeatures: {
22794
+ ...existingBlock(claudeJson.cachedGrowthBookFeatures),
22795
+ tengu_ccr_bridge: true,
22796
+ tengu_bridge_repl_v2: true,
22797
+ tengu_bridge_repl_v2_cse_shim_enabled: true
22798
+ }
22799
+ }, null, 2)}
22800
+ `);
22801
+ deps.fs.mkdirPrivate(recordDir);
22802
+ deps.fs.writeFilePrivate(recordFile2, `${JSON.stringify({ accessToken, refreshToken, organizationUuid, accountUuid, identityId: id }, null, 2)}
22803
+ `);
22804
+ return { identity: deps.identity, organizationUuid, credentialsFile, claudeJsonFile, recordFile: recordFile2, replaced: existingIsOwn };
22805
+ }
22806
+
22807
+ // src/doctorReport.ts
22374
22808
  init_state();
22375
22809
 
22376
22810
  // src/doctorFrontDoor.ts
@@ -22432,6 +22866,17 @@ function pushFrontDoorListeners(push, readings) {
22432
22866
  );
22433
22867
  }
22434
22868
  }
22869
+ function pushRcSelfHostMint(push, mint) {
22870
+ if (mint !== void 0 && !mint.attributable) {
22871
+ 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>.`);
22872
+ }
22873
+ }
22874
+ function pushFrontDoorReadings(push, readings) {
22875
+ if (readings.listeners !== void 0) {
22876
+ pushFrontDoorListeners(push, readings.listeners);
22877
+ }
22878
+ pushRcSelfHostMint(push, readings.rcSelfHostMint);
22879
+ }
22435
22880
 
22436
22881
  // src/frontdoor/listenerReadings.ts
22437
22882
  var import_node_fs13 = __toESM(require("node:fs"), 1);
@@ -22624,7 +23069,7 @@ function tcpPortEraRecord(raw) {
22624
23069
  return (has("port") || has("lastPort")) && !has("socketPath");
22625
23070
  }
22626
23071
  function pushPathResolution(push, resolution) {
22627
- const ownDir = import_node_path44.default.dirname(resolution.ownExecutablePath);
23072
+ const ownDir = import_node_path45.default.dirname(resolution.ownExecutablePath);
22628
23073
  switch (resolution.agentShim.status) {
22629
23074
  case "ok":
22630
23075
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -22744,14 +23189,14 @@ function pushProvider(push, entry, cacheEnv, signIn, unreachable) {
22744
23189
  }
22745
23190
  function pushLegacyName(push, params) {
22746
23191
  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) {
23192
+ if (legacyVariables.length === 0 && import_node_path45.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
22748
23193
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
22749
23194
  return;
22750
23195
  }
22751
23196
  for (const name of legacyVariables) {
22752
23197
  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
23198
  }
22754
- if (import_node_path44.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
23199
+ if (import_node_path45.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
22755
23200
  push(
22756
23201
  "legacy-name",
22757
23202
  "warn",
@@ -22841,7 +23286,7 @@ function runDoctor(params) {
22841
23286
  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
23287
  }
22843
23288
  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));
23289
+ 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
23290
  }
22846
23291
  const validIdentityAgents = /* @__PURE__ */ new Map();
22847
23292
  const signedInAccounts = [];
@@ -23111,9 +23556,7 @@ function runDoctor(params) {
23111
23556
  if (params.frontDoor !== void 0) {
23112
23557
  const validated3 = params.frontDoor.state.raw === void 0 ? void 0 : validateJson(FrontDoorStateSchema, params.frontDoor.state);
23113
23558
  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
- }
23559
+ pushFrontDoorReadings(push, params.frontDoor);
23117
23560
  }
23118
23561
  if (params.activeIdentity.raw === void 0) {
23119
23562
  push("active-identity", "pass", "No active identity set.");
@@ -23139,9 +23582,9 @@ function collectDoctorReport(params) {
23139
23582
  const { names: identityNames, unreachable: unreachableIdentities } = listIdentityDirectories(paths);
23140
23583
  const records = identityRecords(paths);
23141
23584
  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");
23585
+ 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) => {
23586
+ const farmRoot = import_node_path45.default.join(paths.identitiesDir, id);
23587
+ const identityPath = import_node_path45.default.join(farmRoot, "identity.json");
23145
23588
  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
23589
  });
23147
23590
  const usageSnapshots = {};
@@ -23159,12 +23602,12 @@ function collectDoctorReport(params) {
23159
23602
  }
23160
23603
  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
23604
  const configProfiles = profileNames.map((name) => {
23162
- const profilePath = import_node_path44.default.join(paths.configProfilesDir, `${name}.json`);
23605
+ const profilePath = import_node_path45.default.join(paths.configProfilesDir, `${name}.json`);
23163
23606
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
23164
23607
  });
23165
23608
  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
23609
  const providers = providerNames.map((name) => {
23167
- const providerPath = import_node_path44.default.join(paths.providersDir, `${name}.json`);
23610
+ const providerPath = import_node_path45.default.join(paths.providersDir, `${name}.json`);
23168
23611
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
23169
23612
  });
23170
23613
  const ownExecutablePath = realOwnExecutablePath();
@@ -23176,12 +23619,12 @@ function collectDoctorReport(params) {
23176
23619
  binaryDiscovery = { ok: false, message: error instanceof Error ? error.message : String(error) };
23177
23620
  }
23178
23621
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
23179
- const pathDirs = (params.env.PATH ?? "").split(import_node_path44.default.delimiter).filter((dir) => dir !== "");
23622
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path45.default.delimiter).filter((dir) => dir !== "");
23180
23623
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
23181
23624
  findPathShadow({
23182
23625
  pathDirs,
23183
- targetDir: import_node_path44.default.dirname(shimState.targetPath),
23184
- targetFilename: import_node_path44.default.basename(shimState.targetPath),
23626
+ targetDir: import_node_path45.default.dirname(shimState.targetPath),
23627
+ targetFilename: import_node_path45.default.basename(shimState.targetPath),
23185
23628
  findExecutableInDir
23186
23629
  }),
23187
23630
  shimState.targetPath,
@@ -23210,7 +23653,7 @@ function collectDoctorReport(params) {
23210
23653
  catalogueRedirects: providersWithRedirectedCatalogue(realFarmFs, paths, new Map(providers.map((entry) => [entry.name, currentCatalogueSettings(paths, entry.name)]))),
23211
23654
  renameJournals: listRenameJournals(realFarmFs, paths.identityRenamesDir),
23212
23655
  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) },
23656
+ 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
23657
  directoryRules: { path: paths.directoryRulesFile, raw: realFsPort.readFileUtf8(paths.directoryRulesFile) },
23215
23658
  globalConfig: { path: paths.globalConfigFile, raw: realFsPort.readFileUtf8(paths.globalConfigFile) },
23216
23659
  models: readableOr(() => readGlobalConfig(paths)?.models, void 0),
@@ -23225,7 +23668,7 @@ function collectDoctorReport(params) {
23225
23668
  agentShim: refinePathShadow(
23226
23669
  findPathShadow({
23227
23670
  pathDirs,
23228
- targetDir: import_node_path44.default.dirname(ownExecutablePath),
23671
+ targetDir: import_node_path45.default.dirname(ownExecutablePath),
23229
23672
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
23230
23673
  findExecutableInDir
23231
23674
  }),
@@ -23259,7 +23702,7 @@ function collectDoctorReport(params) {
23259
23702
  logPath: paths.headroomLogPath
23260
23703
  }
23261
23704
  },
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) } }
23705
+ ...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
23706
  });
23264
23707
  return report;
23265
23708
  }
@@ -23318,11 +23761,11 @@ var DOOR_REPORT_ENVIRONMENT_NOTE = "The report is collected in a worker thread o
23318
23761
  var CheckRunInputSchema = import_zod39.z.strictObject({
23319
23762
  path: import_zod39.z.string().min(1),
23320
23763
  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" });
23764
+ }).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
23765
  var PoolPickInputSchema = import_zod39.z.strictObject({
23323
23766
  pool: import_zod39.z.string().min(1),
23324
23767
  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" });
23768
+ }).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
23769
  var DoctorFindingSchema = import_zod39.z.strictObject({
23327
23770
  section: import_zod39.z.enum(DOCTOR_SECTIONS),
23328
23771
  subject: import_zod39.z.string().optional(),
@@ -24114,7 +24557,7 @@ var import_openapi6 = require("@orpc/openapi");
24114
24557
  init_cliError();
24115
24558
 
24116
24559
  // src/frontdoor/launchSchemas.ts
24117
- var import_node_path46 = __toESM(require("node:path"), 1);
24560
+ var import_node_path47 = __toESM(require("node:path"), 1);
24118
24561
  var import_zod45 = require("zod");
24119
24562
  init_statusline();
24120
24563
  init_claudeVersion();
@@ -24125,7 +24568,7 @@ var LaunchResolveInputSchema = import_zod45.z.strictObject({
24125
24568
  argv: import_zod45.z.readonly(import_zod45.z.array(import_zod45.z.string())).optional(),
24126
24569
  /** 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
24570
  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" });
24571
+ }).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
24572
  var LaunchPoolDecisionSchema = import_zod45.z.strictObject({
24130
24573
  name: import_zod45.z.string(),
24131
24574
  reasons: import_zod45.z.readonly(import_zod45.z.array(import_zod45.z.string())),
@@ -24963,15 +25406,15 @@ init_verifiedVersions();
24963
25406
  // src/frontdoor/rcLiveUsage.ts
24964
25407
  init_rcSchemas();
24965
25408
  var RC_RATE_LIMIT_EVENT_TYPE = "rate_limit_event";
24966
- function isRecord10(value) {
25409
+ function isRecord12(value) {
24967
25410
  return typeof value === "object" && value !== null && !Array.isArray(value);
24968
25411
  }
24969
25412
  function rcRateLimitInfoOf(event) {
24970
25413
  const payload = event.envelope.payload;
24971
- if (!isRecord10(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
25414
+ if (!isRecord12(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
24972
25415
  return void 0;
24973
25416
  }
24974
- if (!isRecord10(payload.rate_limit_info)) {
25417
+ if (!isRecord12(payload.rate_limit_info)) {
24975
25418
  return void 0;
24976
25419
  }
24977
25420
  const parsed = RcRateLimitInfoSchema.safeParse(payload.rate_limit_info);
@@ -25060,7 +25503,7 @@ function createSseParser() {
25060
25503
  }
25061
25504
  };
25062
25505
  }
25063
- function isRecord11(value) {
25506
+ function isRecord13(value) {
25064
25507
  return typeof value === "object" && value !== null && !Array.isArray(value);
25065
25508
  }
25066
25509
  function sequenceNumOf(value) {
@@ -25082,7 +25525,7 @@ function parseRcStreamEnvelope(parsed) {
25082
25525
  } catch {
25083
25526
  return void 0;
25084
25527
  }
25085
- if (!isRecord11(data)) {
25528
+ if (!isRecord13(data)) {
25086
25529
  return void 0;
25087
25530
  }
25088
25531
  const eventType = data.event_type;
@@ -25339,17 +25782,17 @@ function withClientPlatform(payload, headers) {
25339
25782
  const platform = headers[CLIENT_PLATFORM_HEADER];
25340
25783
  return typeof platform === "string" && platform !== "" ? { ...rest, client_platform: platform } : rest;
25341
25784
  }
25342
- function isRecord12(value) {
25785
+ function isRecord14(value) {
25343
25786
  return typeof value === "object" && value !== null && !Array.isArray(value);
25344
25787
  }
25345
- function parseJsonObject2(body) {
25788
+ function parseJsonObject3(body) {
25346
25789
  let parsed;
25347
25790
  try {
25348
25791
  parsed = JSON.parse(body);
25349
25792
  } catch {
25350
25793
  return void 0;
25351
25794
  }
25352
- return isRecord12(parsed) ? parsed : void 0;
25795
+ return isRecord14(parsed) ? parsed : void 0;
25353
25796
  }
25354
25797
  function nonEmptyString2(record, field) {
25355
25798
  const value = record === void 0 ? void 0 : record[field];
@@ -25384,7 +25827,7 @@ function pageOfRcChannel(url, rows, idOf, rowOf3) {
25384
25827
  async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25385
25828
  const { request: request4, response, host } = ctx;
25386
25829
  if (tail === "client/presence" && method === "POST") {
25387
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25830
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25388
25831
  const clientId = nonEmptyString2(body, "client_id");
25389
25832
  const clear = body?.clear;
25390
25833
  if (clientId === void 0 || clear !== void 0 && typeof clear !== "boolean") {
@@ -25402,7 +25845,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25402
25845
  return true;
25403
25846
  }
25404
25847
  if (tail === "mark_read" && method === "POST") {
25405
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25848
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25406
25849
  const eventId = nonEmptyString2(body, "event_id");
25407
25850
  const clientId = nonEmptyString2(body, "client_id");
25408
25851
  if (body !== void 0 && "event_id" in body && eventId === void 0 || "client_id" in (body ?? {}) && clientId === void 0) {
@@ -25415,7 +25858,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25415
25858
  return true;
25416
25859
  }
25417
25860
  if (tail === "teleport-events" && method === "POST") {
25418
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25861
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25419
25862
  const events = body?.events;
25420
25863
  if (!Array.isArray(events) || events.length === 0 || events.length > maxBatchEvents) {
25421
25864
  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 +25866,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
25423
25866
  }
25424
25867
  const results = [];
25425
25868
  for (const event of events) {
25426
- if (!isRecord12(event) || !isRecord12(event.payload)) {
25869
+ if (!isRecord14(event) || !isRecord14(event.payload)) {
25427
25870
  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
25871
  return true;
25429
25872
  }
@@ -25487,7 +25930,7 @@ async function serveRcCompatSessions(ctx, pathname, compatPath) {
25487
25930
  await ctx.answerJson(response, HTTP_STATUS.notFound, { type: "error", error: { type: "api_error", message: `Session not found: ${address}` } });
25488
25931
  return;
25489
25932
  }
25490
- const body = parseJsonObject2(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25933
+ const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25491
25934
  const title = nonEmptyString2(body, "title");
25492
25935
  if (title === void 0) {
25493
25936
  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 +25968,17 @@ init_http();
25525
25968
  init_rcControl();
25526
25969
  var RC_CONVERSATIONS_PATH_PREFIX = "/v1/code/conversations";
25527
25970
  var RC_CONVERSATION_ID_PREFIX = "conv_";
25528
- function isRecord13(value) {
25971
+ function isRecord15(value) {
25529
25972
  return typeof value === "object" && value !== null && !Array.isArray(value);
25530
25973
  }
25531
- function parseJsonObject3(body) {
25974
+ function parseJsonObject4(body) {
25532
25975
  let parsed;
25533
25976
  try {
25534
25977
  parsed = JSON.parse(body);
25535
25978
  } catch {
25536
25979
  return void 0;
25537
25980
  }
25538
- return isRecord13(parsed) ? parsed : void 0;
25981
+ return isRecord15(parsed) ? parsed : void 0;
25539
25982
  }
25540
25983
  function nonEmptyString3(record, field) {
25541
25984
  const value = record === void 0 ? void 0 : record[field];
@@ -25581,7 +26024,7 @@ async function serveRcConversations(ctx, pathname, method) {
25581
26024
  return;
25582
26025
  }
25583
26026
  if (tail === "events" && method === "POST") {
25584
- const body = parseJsonObject3(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
26027
+ const body = parseJsonObject4(await ctx.readBody(request4.body, CONTROL_BODY_CAP_BYTES));
25585
26028
  const events = body?.events;
25586
26029
  if (!Array.isArray(events) || events.length === 0 || events.length > ctx.maxBatchEvents) {
25587
26030
  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 +26032,7 @@ async function serveRcConversations(ctx, pathname, method) {
25589
26032
  }
25590
26033
  const results = [];
25591
26034
  for (const event of events) {
25592
- if (!isRecord13(event) || !isRecord13(event.payload)) {
26035
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
25593
26036
  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
26037
  return;
25595
26038
  }
@@ -25615,111 +26058,6 @@ async function serveRcConversations(ctx, pathname, method) {
25615
26058
  await ctx.answerJson(response, HTTP_STATUS.notFound, { type: "error", error: { type: "api_error", message: `the conversation family serves no path "${tail}"` } });
25616
26059
  }
25617
26060
 
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
26061
  // src/frontdoor/rcWebFetch.ts
25724
26062
  var dns2 = __toESM(require("node:dns"), 1);
25725
26063
  var http2 = __toESM(require("node:http"), 1);
@@ -25998,7 +26336,7 @@ var RC_SELF_HOST_WORKER_EPOCH = 1;
25998
26336
  var RC_STREAM_EVENT_NAME2 = "client_event";
25999
26337
  var CONFLICT_REASON_HEADER2 = "x-ccr-conflict-reason";
26000
26338
  var CONFLICT_REASON_EPOCH_STALE = "epoch_stale";
26001
- function isRecord15(value) {
26339
+ function isRecord16(value) {
26002
26340
  return typeof value === "object" && value !== null && !Array.isArray(value);
26003
26341
  }
26004
26342
  function isWebSearchRefusal(value) {
@@ -26082,7 +26420,7 @@ function parseJsonObject5(body) {
26082
26420
  } catch {
26083
26421
  return void 0;
26084
26422
  }
26085
- return isRecord15(parsed) ? parsed : void 0;
26423
+ return isRecord16(parsed) ? parsed : void 0;
26086
26424
  }
26087
26425
  function mintWorkerJwt(randomToken, issuedAt) {
26088
26426
  const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
@@ -26342,7 +26680,7 @@ data: ${JSON.stringify(envelope)}
26342
26680
  if (status !== void 0) {
26343
26681
  session.workerStatus = status;
26344
26682
  }
26345
- if (isRecord15(body?.external_metadata)) {
26683
+ if (isRecord16(body?.external_metadata)) {
26346
26684
  session.externalMetadata = body.external_metadata;
26347
26685
  }
26348
26686
  await answerJson2(response, HTTP_STATUS.ok, {});
@@ -26372,7 +26710,7 @@ data: ${JSON.stringify(envelope)}
26372
26710
  }
26373
26711
  const results = [];
26374
26712
  for (const event of events) {
26375
- if (!isRecord15(event) || !isRecord15(event.payload)) {
26713
+ if (!isRecord16(event) || !isRecord16(event.payload)) {
26376
26714
  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
26715
  return;
26378
26716
  }
@@ -26405,7 +26743,7 @@ data: ${JSON.stringify(envelope)}
26405
26743
  return;
26406
26744
  }
26407
26745
  for (const event of events) {
26408
- if (isRecord15(event)) {
26746
+ if (isRecord16(event)) {
26409
26747
  session.internalEvents.push({ eventId: deps.newUuid(), body: event });
26410
26748
  }
26411
26749
  }
@@ -26501,7 +26839,7 @@ data: ${JSON.stringify(envelope)}
26501
26839
  }
26502
26840
  const results = [];
26503
26841
  for (const event of events) {
26504
- if (!isRecord15(event) || !isRecord15(event.payload)) {
26842
+ if (!isRecord16(event) || !isRecord16(event.payload)) {
26505
26843
  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
26844
  return;
26507
26845
  }
@@ -26546,7 +26884,9 @@ data: ${JSON.stringify(envelope)}
26546
26884
  return;
26547
26885
  }
26548
26886
  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}"` } });
26887
+ const offline = rcSelfHostOfflineAnswer(pathname);
26888
+ deps.log?.(`rc selfhost: answered ${method} ${pathname} locally with ${String(offline.status)}; a self-hosted session's calls never leave the door`);
26889
+ await answerJson2(response, offline.status, offline.body);
26550
26890
  return;
26551
26891
  }
26552
26892
  if (pathname === RC_SESSIONS_PATH_PREFIX2) {
@@ -26611,7 +26951,7 @@ data: ${JSON.stringify(envelope)}
26611
26951
  await serveSessionPath(sessions.get(id), tail, request4, response);
26612
26952
  }
26613
26953
  };
26614
- const local = createRcSelfHostLocal({ now: deps.now, credentialRecord: deps.credentialRecord, readBody: readBody2 });
26954
+ 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
26955
  return {
26616
26956
  route,
26617
26957
  local,
@@ -26629,103 +26969,6 @@ data: ${JSON.stringify(envelope)}
26629
26969
  };
26630
26970
  }
26631
26971
 
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
26972
  // src/index.ts
26730
26973
  init_ensure2();
26731
26974