agent-shim 14.20.1 → 14.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -40507,6 +40507,13 @@ ${request7.rawHeaders.reduce((accumulated, value3, index) => index % 2 === 0 ? `
40507
40507
  return;
40508
40508
  }
40509
40509
  if (host === config2.routedHost && servedByPipeline(request7.url)) {
40510
+ const lent = ownedBySurface(request7.socket) ? void 0 : await config2.rewriteForwardedAuthorization?.(host, request7, tunnelTokens.get(request7.socket));
40511
+ if (lent !== void 0) {
40512
+ request7.headers.authorization = lent.authorization;
40513
+ request7.url = lent.url;
40514
+ effects.forwardHttp(config2.upstreamFor(host), request7, response, config2.capture?.observePassthrough(request7));
40515
+ return;
40516
+ }
40510
40517
  const tunnelToken = tunnelTokens.get(request7.socket);
40511
40518
  if (tunnelToken !== void 0 && request7.headers[AUTH_HEADER] === void 0) {
40512
40519
  request7.headers[AUTH_HEADER] = tunnelToken;
@@ -41071,6 +41078,48 @@ var init_connectorProxyAuth = __esm({
41071
41078
  }
41072
41079
  });
41073
41080
 
41081
+ // src/toolSurfaceAuth.ts
41082
+ function toolSurfaceOfPath(url2) {
41083
+ const path107 = url2?.split("?", 1)[0];
41084
+ if (path107 === void 0) {
41085
+ return void 0;
41086
+ }
41087
+ return SURFACE_PATHS.find(([, prefix]) => path107 === prefix || path107.startsWith(`${prefix}/`))?.[0];
41088
+ }
41089
+ function toolSurfaceAuthorizationRewriter(deps) {
41090
+ return (host, request7, tunnelToken) => {
41091
+ const surface = host === CONNECT_INTERCEPT_HOST && tunnelToken !== void 0 ? toolSurfaceOfPath(request7.url) : void 0;
41092
+ const borrowerId = surface === void 0 || tunnelToken === void 0 ? void 0 : deps.identityOfToken(tunnelToken);
41093
+ if (surface === void 0 || borrowerId === void 0 || request7.url === void 0) {
41094
+ return void 0;
41095
+ }
41096
+ const identities = deps.identities();
41097
+ const lenderId = identities.find((identity) => identity.id === borrowerId)?.toolLogins?.[surface];
41098
+ const granted = lenderId !== void 0 && identities.find((identity) => identity.id === lenderId)?.grants?.some((grant) => grant.to === borrowerId && grant.features.includes("server-tools")) === true;
41099
+ const login = granted ? readLenderLogin(deps.loginPorts, deps.identitiesDir, lenderId) : void 0;
41100
+ if (login === void 0 || !lenderLoginUsable(login, deps.now(), LENDER_LOGIN_GRACE_MS2)) {
41101
+ return void 0;
41102
+ }
41103
+ return { authorization: `Bearer ${login.token}`, url: request7.url };
41104
+ };
41105
+ }
41106
+ var LENDER_LOGIN_GRACE_MS2, SURFACE_PATHS;
41107
+ var init_toolSurfaceAuth = __esm({
41108
+ "src/toolSurfaceAuth.ts"() {
41109
+ "use strict";
41110
+ init_connect();
41111
+ init_lenderLogin();
41112
+ LENDER_LOGIN_GRACE_MS2 = 3e4;
41113
+ SURFACE_PATHS = [
41114
+ ["design", "/v1/design"],
41115
+ ["claude-test", "/v1/claude/test"],
41116
+ ["pages", "/v1/pages"],
41117
+ ["triggers", "/v1/code/triggers"],
41118
+ ["triggers", "/v1/code/webhook-triggers"]
41119
+ ];
41120
+ }
41121
+ });
41122
+
41074
41123
  // src/codex/http.ts
41075
41124
  var HTTP_STATUS;
41076
41125
  var init_http = __esm({
@@ -41554,14 +41603,22 @@ function listIdentities(paths) {
41554
41603
  }
41555
41604
  return result.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
41556
41605
  }
41557
- function wiredConnectorProxyAuthorizationRewriter(paths, identityOfToken, loginPorts) {
41558
- return connectorProxyAuthorizationRewriter({
41606
+ function wiredAuthorizationRewriter(paths, identityOfToken, loginPorts) {
41607
+ const connector = connectorProxyAuthorizationRewriter({
41559
41608
  identityOfToken,
41560
41609
  identities: () => listIdentities(paths).flatMap((entry) => entry.problem === void 0 ? [{ id: entry.id, name: entry.name, grants: entry.identity.grants }] : []),
41561
41610
  identitiesDir: paths.identitiesDir,
41562
41611
  loginPorts,
41563
41612
  now: Date.now
41564
41613
  });
41614
+ const tools = toolSurfaceAuthorizationRewriter({
41615
+ identityOfToken,
41616
+ identities: () => listIdentities(paths).flatMap((entry) => entry.problem === void 0 ? [{ id: entry.id, name: entry.name, grants: entry.identity.grants, toolLogins: entry.identity.toolLogins }] : []),
41617
+ identitiesDir: paths.identitiesDir,
41618
+ loginPorts,
41619
+ now: Date.now
41620
+ });
41621
+ return (host, request7, tunnelToken) => connector(host, request7, tunnelToken) ?? tools(host, request7, tunnelToken);
41565
41622
  }
41566
41623
  function wiredMergeConnectorList2(paths, apiBase, loginPorts) {
41567
41624
  return wiredMergeConnectorList({
@@ -41778,6 +41835,7 @@ var init_identityStore = __esm({
41778
41835
  init_launchRecords();
41779
41836
  init_identityGrants();
41780
41837
  init_connectorProxyAuth();
41838
+ init_toolSurfaceAuth();
41781
41839
  init_connectorListMerge();
41782
41840
  init_lenderLogin();
41783
41841
  init_quotaHttp();
@@ -45429,14 +45487,20 @@ function rcEventWriteResultFromAnswer(answer) {
45429
45487
  }
45430
45488
  return { ok: true, sequenceNums };
45431
45489
  }
45490
+ function noOAuthCredentialMessage(sessionId) {
45491
+ return `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`;
45492
+ }
45432
45493
  function noOAuthCredentialResult(sessionId) {
45433
- 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" };
45494
+ return { ok: false, message: noOAuthCredentialMessage(sessionId), refusal: "session-state" };
45434
45495
  }
45435
45496
  function rcSessionNotObservedMessage(sessionId) {
45436
45497
  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)`;
45437
45498
  }
45438
45499
  function rcWriteHeaders(credential) {
45439
- const headers = { "content-type": "application/json" };
45500
+ return { "content-type": "application/json", ...rcReadHeaders(credential) };
45501
+ }
45502
+ function rcReadHeaders(credential) {
45503
+ const headers = {};
45440
45504
  if (credential.authorization !== void 0) {
45441
45505
  headers.authorization = credential.authorization;
45442
45506
  }
@@ -45695,10 +45759,40 @@ async function teleportRcSession(deps, sessionId, marker) {
45695
45759
  function buildRcMarkReadBody(eventId) {
45696
45760
  return eventId === void 0 ? {} : { event_id: eventId };
45697
45761
  }
45698
- var RC_SEND_DELIVERY_NOTE, RC_PERMISSION_MODES, RC_CONTEXT_USAGE_DETAILS, RC_READ_FILE_ENCODINGS;
45762
+ async function readRcServerState(deps, sessionId) {
45763
+ const credential = deps.credentialOf(sessionId);
45764
+ if (credential === void 0) {
45765
+ return { kind: "unknown", reason: rcSessionNotObservedMessage(sessionId) };
45766
+ }
45767
+ if (credential.authorization === void 0) {
45768
+ return { kind: "unknown", reason: noOAuthCredentialMessage(sessionId) };
45769
+ }
45770
+ let answer;
45771
+ try {
45772
+ answer = await deps.dial.readSession(sessionId, rcReadHeaders(credential));
45773
+ } catch (error63) {
45774
+ return { kind: "unknown", reason: `the door could not reach the API host to read the session: ${error63 instanceof Error ? error63.message : String(error63)}` };
45775
+ }
45776
+ if (!isSuccessful(answer.status)) {
45777
+ return { kind: "unknown", reason: `the API host answered ${String(answer.status)} to the session read` };
45778
+ }
45779
+ let parsed;
45780
+ try {
45781
+ parsed = JSON.parse(answer.body);
45782
+ } catch {
45783
+ return { kind: "unknown", reason: "the session read answered no status" };
45784
+ }
45785
+ const record3 = RcSessionAnswerSchema.safeParse(parsed);
45786
+ if (!record3.success) {
45787
+ return { kind: "unknown", reason: "the session read answered no status" };
45788
+ }
45789
+ return { kind: "read", status: record3.data.status, ...record3.data.worker_status === void 0 ? {} : { workerStatus: record3.data.worker_status }, ...record3.data.connection_status === void 0 ? {} : { connectionStatus: record3.data.connection_status } };
45790
+ }
45791
+ var RC_SEND_DELIVERY_NOTE, RC_PERMISSION_MODES, RC_CONTEXT_USAGE_DETAILS, RC_READ_FILE_ENCODINGS, RcSessionRecordSchema, RcSessionAnswerSchema;
45699
45792
  var init_rcWrites = __esm({
45700
45793
  "src/frontdoor/rcWrites.ts"() {
45701
45794
  "use strict";
45795
+ init_zod();
45702
45796
  init_http();
45703
45797
  init_rcSessions();
45704
45798
  init_rcQuestions();
@@ -45706,6 +45800,8 @@ var init_rcWrites = __esm({
45706
45800
  RC_PERMISSION_MODES = ["default", "acceptEdits", "bypassPermissions", "plan", "dontAsk", "auto"];
45707
45801
  RC_CONTEXT_USAGE_DETAILS = ["summary", "full"];
45708
45802
  RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
45803
+ RcSessionRecordSchema = external_exports.looseObject({ status: external_exports.string(), worker_status: external_exports.string().optional(), connection_status: external_exports.string().optional() });
45804
+ RcSessionAnswerSchema = external_exports.union([external_exports.looseObject({ response_shape: RcSessionRecordSchema }).transform((answer) => answer.response_shape), RcSessionRecordSchema]);
45709
45805
  }
45710
45806
  });
45711
45807
 
@@ -45730,7 +45826,7 @@ var init_machineLoad = __esm({
45730
45826
  function workerFactSchema(value3) {
45731
45827
  return external_exports.strictObject({ value: value3, observedAt: external_exports.number() });
45732
45828
  }
45733
- var RcPermissionModeSchema, RcSessionSummarySchema, RcQuestionOptionSchema, RcPendingQuestionSchema, RcPendingRequestSummarySchema, RcSessionStatusSchema, RcStreamEnvelopeSchema, RcStreamEventSchema, RcRateLimitWindowSchema, RcRateLimitInfoSchema, RcLiveRateLimitSchema, RcSessionQuerySchema, RcSendInputSchema, RcQuestionSelectionSchema, RcQuestionChoicesSchema, RcAnswerInputSchema, RcInterruptInputSchema, RcSetModelInputSchema, RcSetPermissionModeInputSchema, RcEndSessionInputSchema, RcGetUsageInputSchema, RcGetContextUsageInputSchema, RcReadFileInputSchema, RcFileSuggestionsInputSchema, RcKeepAliveInputSchema, RcMcpStatusInputSchema, RcMcpReconnectInputSchema, RcMcpAuthenticateInputSchema, RcMcpOAuthCallbackUrlInputSchema, RcTeleportInputSchema, RcListOutputSchema, RcSessionCommandRouteSchema, RcVersionGateWarningsSchema, RcSessionRouteSchema, RcStatusOutputSchema, RcPendingOutputSchema, RcWriteOutputSchema, RcControlWriteOutputSchema, RcAnswerOutputSchema;
45829
+ var RcPermissionModeSchema, RcSessionSummarySchema, RcQuestionOptionSchema, RcPendingQuestionSchema, RcPendingRequestSummarySchema, RcServerStateSchema, RcSessionStatusSchema, RcStreamEnvelopeSchema, RcStreamEventSchema, RcRateLimitWindowSchema, RcRateLimitInfoSchema, RcLiveRateLimitSchema, RcSessionQuerySchema, RcSendInputSchema, RcQuestionSelectionSchema, RcQuestionChoicesSchema, RcAnswerInputSchema, RcInterruptInputSchema, RcSetModelInputSchema, RcSetPermissionModeInputSchema, RcEndSessionInputSchema, RcGetUsageInputSchema, RcGetContextUsageInputSchema, RcReadFileInputSchema, RcFileSuggestionsInputSchema, RcKeepAliveInputSchema, RcMcpStatusInputSchema, RcMcpReconnectInputSchema, RcMcpAuthenticateInputSchema, RcMcpOAuthCallbackUrlInputSchema, RcTeleportInputSchema, RcListOutputSchema, RcSessionCommandRouteSchema, RcVersionGateWarningsSchema, RcSessionRouteSchema, RcStatusOutputSchema, RcPendingOutputSchema, RcWriteOutputSchema, RcControlWriteOutputSchema, RcAnswerOutputSchema;
45734
45830
  var init_rcSchemas = __esm({
45735
45831
  "src/frontdoor/rcSchemas.ts"() {
45736
45832
  "use strict";
@@ -45762,6 +45858,10 @@ var init_rcSchemas = __esm({
45762
45858
  unanswerable: external_exports.string().optional(),
45763
45859
  observedAt: external_exports.number()
45764
45860
  });
45861
+ RcServerStateSchema = external_exports.discriminatedUnion("kind", [
45862
+ external_exports.strictObject({ kind: external_exports.literal("read"), status: external_exports.string(), workerStatus: external_exports.string().optional(), connectionStatus: external_exports.string().optional() }),
45863
+ external_exports.strictObject({ kind: external_exports.literal("unknown"), reason: external_exports.string() })
45864
+ ]);
45765
45865
  RcSessionStatusSchema = external_exports.strictObject({
45766
45866
  ...RcSessionSummarySchema.shape,
45767
45867
  workerState: workerFactSchema(external_exports.string()).optional(),
@@ -45903,7 +46003,7 @@ var init_rcSchemas = __esm({
45903
46003
  RcSessionCommandRouteSchema = external_exports.enum(["supervised", "launched", "self-hosted"]);
45904
46004
  RcVersionGateWarningsSchema = external_exports.readonly(external_exports.array(external_exports.string()).min(1)).optional();
45905
46005
  RcSessionRouteSchema = external_exports.union([external_exports.strictObject({ route: RcSessionCommandRouteSchema, warnings: RcVersionGateWarningsSchema }), external_exports.strictObject({ route: external_exports.null(), refused: external_exports.string() })]);
45906
- RcStatusOutputSchema = external_exports.strictObject({ statuses: external_exports.readonly(external_exports.array(external_exports.strictObject({ ...RcSessionStatusSchema.shape, route: RcSessionRouteSchema }))) });
46006
+ RcStatusOutputSchema = external_exports.strictObject({ statuses: external_exports.readonly(external_exports.array(external_exports.strictObject({ ...RcSessionStatusSchema.shape, route: RcSessionRouteSchema, serverState: RcServerStateSchema }))) });
45907
46007
  RcPendingOutputSchema = external_exports.strictObject({
45908
46008
  pending: external_exports.readonly(external_exports.array(RcPendingRequestSummarySchema)),
45909
46009
  /** The sessions that had requests the door did not list (past the per-session cap, or with an id the protocol does not mint), each with how many: a question the caller expects may be among them. Absent when none did. */
@@ -46966,14 +47066,14 @@ function tlsFacts(options) {
46966
47066
  }
46967
47067
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
46968
47068
  const agent = new ExemptTlsAgent();
46969
- const post = async (path107, headers, body) => await new Promise((resolve3, reject) => {
47069
+ const send = async (method, path107, headers, body) => await new Promise((resolve3, reject) => {
46970
47070
  const options = {
46971
47071
  host: target.host,
46972
47072
  port: target.port,
46973
- method: "POST",
47073
+ method,
46974
47074
  path: path107,
46975
47075
  // The Host header names the host whose API this is, not the address dialled: a redirected test dials a loopback stand-in while still speaking to the API host by name, exactly as the forwarded paths present their SNI.
46976
- headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
47076
+ headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
46977
47077
  agent
46978
47078
  };
46979
47079
  options.servername = target.servername ?? target.host;
@@ -46993,9 +47093,15 @@ function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PO
46993
47093
  });
46994
47094
  });
46995
47095
  request7.once("error", reject);
46996
- request7.end(body);
47096
+ if (body === void 0) {
47097
+ request7.end();
47098
+ } else {
47099
+ request7.end(body);
47100
+ }
46997
47101
  });
47102
+ const post = async (path107, headers, body) => await send("POST", path107, headers, body);
46998
47103
  return {
47104
+ readSession: async (sessionId, headers) => await send("GET", `/v1/code/sessions/${encodeURIComponent(sessionId)}`, headers, void 0),
46999
47105
  writeEvents: async (sessionId, headers, body) => await post(`/v1/code/sessions/${encodeURIComponent(sessionId)}/events`, headers, body),
47000
47106
  writeTeleportEvents: async (sessionId, headers, body) => await post(`/v1/code/sessions/${encodeURIComponent(sessionId)}/teleport-events`, headers, body)
47001
47107
  };
@@ -47011,7 +47117,8 @@ function lateRcEventDial(resolve3) {
47011
47117
  };
47012
47118
  return {
47013
47119
  writeEvents: async (sessionId, headers, body) => await dialFor().writeEvents(sessionId, headers, body),
47014
- writeTeleportEvents: async (sessionId, headers, body) => await dialFor().writeTeleportEvents(sessionId, headers, body)
47120
+ writeTeleportEvents: async (sessionId, headers, body) => await dialFor().writeTeleportEvents(sessionId, headers, body),
47121
+ readSession: async (sessionId, headers) => await dialFor().readSession(sessionId, headers)
47015
47122
  };
47016
47123
  }
47017
47124
  function lateRcStreamDial(resolve3) {
@@ -76848,7 +76955,7 @@ var init_package = __esm({
76848
76955
  "package.json"() {
76849
76956
  package_default = {
76850
76957
  name: "agent-shim",
76851
- version: "14.20.1",
76958
+ version: "14.21.0",
76852
76959
  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.",
76853
76960
  license: "MIT",
76854
76961
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -148069,7 +148176,7 @@ function createRcApiRouter(deps) {
148069
148176
  if (input2.session !== void 0 && !statuses.some((entry) => entry.id === input2.session)) {
148070
148177
  throw new ORPCError("NOT_FOUND", { message: rcSessionNotObservedMessage(input2.session) });
148071
148178
  }
148072
- return { statuses: await Promise.all(statuses.map(async (status) => ({ ...status, route: await deps.routeOf(status.id) }))) };
148179
+ return { statuses: await Promise.all(statuses.map(async (status) => ({ ...status, route: await deps.routeOf(status.id), serverState: await deps.serverStateOf(status.id) }))) };
148073
148180
  }),
148074
148181
  pending: authed.meta(openapi({ method: "GET", path: "/rest/rc/pending", summary: "Read the control requests awaiting an answer", tags: [RC_API_TAG] })).input(RcSessionQuerySchema).output(RcPendingOutputSchema).handler(({ input: input2 }) => {
148075
148182
  const pending = deps.pendingOf(input2.session);
@@ -154675,6 +154782,7 @@ function formatRcSessionStatus(statuses) {
154675
154782
  status.workerIdleSeconds === void 0 ? "idle unknown" : `idle ${String(status.workerIdleSeconds.value)} s as of ${new Date(status.workerIdleSeconds.observedAt).toISOString()}`
154676
154783
  ].join(", ");
154677
154784
  lines.push(` worker: ${worker}`);
154785
+ lines.push(status.serverState.kind === "read" ? ` server: ${status.serverState.status}${[status.serverState.workerStatus === void 0 ? void 0 : `worker ${status.serverState.workerStatus}`, status.serverState.connectionStatus === void 0 ? void 0 : `connection ${status.serverState.connectionStatus}`].filter((part) => part !== void 0).map((part) => `, ${part}`).join("")}` : ` server: unknown (${status.serverState.reason})`);
154678
154786
  lines.push(status.route.route === null ? ` goal, compaction and turn verbs: refused: ${status.route.refused}` : ` goal, compaction and turn verbs: ${status.route.route} route`);
154679
154787
  if (status.route.route !== null) {
154680
154788
  lines.push(...(status.route.warnings ?? []).map((warning) => ` warning: ${warning}`));
@@ -158686,6 +158794,7 @@ function realFrontDoorSupervisorPorts(paths, respawnGeneration, lifecycle, track
158686
158794
  const rcMcpReconnect = async (sessionId, serverName) => await reconnectRcSessionMcpServer(rcControlRequestDeps, sessionId, serverName);
158687
158795
  const rcMcpAuthenticate = async (sessionId, serverName, redirectUri) => await authenticateRcSessionMcpServer(rcControlRequestDeps, sessionId, serverName, redirectUri);
158688
158796
  const rcMcpOAuthCallbackUrl = async (sessionId, serverName, callbackUrl) => await submitRcSessionMcpOAuthCallbackUrl(rcControlRequestDeps, sessionId, serverName, callbackUrl);
158797
+ const rcServerStateOf = async (sessionId) => await readRcServerState(rcControlRequestDeps, sessionId);
158689
158798
  const rcTeleport = async (sessionId, marker) => await teleportRcSession(rcControlRequestDeps, sessionId, marker);
158690
158799
  const rcSessionCommands = createDoorRcSessionCommands({
158691
158800
  paths,
@@ -158772,6 +158881,7 @@ function realFrontDoorSupervisorPorts(paths, respawnGeneration, lifecycle, track
158772
158881
  mcpAuthenticate: rcMcpAuthenticate,
158773
158882
  mcpOAuthCallbackUrl: rcMcpOAuthCallbackUrl,
158774
158883
  teleport: rcTeleport,
158884
+ serverStateOf: rcServerStateOf,
158775
158885
  ...rcSessionCommands,
158776
158886
  fanout: rcFanout,
158777
158887
  sessionEvents: rcSessionEvents,
@@ -158840,7 +158950,7 @@ function realFrontDoorSupervisorPorts(paths, respawnGeneration, lifecycle, track
158840
158950
  },
158841
158951
  leafFor,
158842
158952
  upstreamFor: (host) => ({ host, port: HTTPS_PORT, tls: true }),
158843
- rewriteForwardedAuthorization: wiredConnectorProxyAuthorizationRewriter(paths, sessionRegistry.identityOf, { fs: realFarmFs, run: realRunPort, platform: process.platform }),
158953
+ rewriteForwardedAuthorization: wiredAuthorizationRewriter(paths, sessionRegistry.identityOf, { fs: realFarmFs, run: realRunPort, platform: process.platform }),
158844
158954
  isLiveCapability: isLiveToken,
158845
158955
  ...wantedTransparentPort === void 0 || Number.isNaN(wantedTransparentPort) ? {} : { transparentPort: wantedTransparentPort, ...transparentCapability === void 0 ? {} : { transparentCapability } },
158846
158956
  limits: CONNECT_LIMITS,