claude-use 11.90.0 → 12.0.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.mjs CHANGED
@@ -5301,7 +5301,7 @@ var init_identity = __esm({
5301
5301
  });
5302
5302
 
5303
5303
  // src/statusline/keys.ts
5304
- import { z as z10 } from "zod";
5304
+ import { z as z11 } from "zod";
5305
5305
  function valueAt(source, path55) {
5306
5306
  let current = source;
5307
5307
  for (const part of path55) {
@@ -5317,37 +5317,37 @@ function acceptsNull(path55) {
5317
5317
  return StatuslineSchema.safeParse(layer).success;
5318
5318
  }
5319
5319
  function keyOf(path55, declared) {
5320
- const optional = declared instanceof z10.ZodOptional;
5320
+ const optional = declared instanceof z11.ZodOptional;
5321
5321
  const leaf = optional ? declared.unwrap() : declared;
5322
5322
  const common = { path: path55.join("."), description: declared.description ?? "", defaultValue: valueAt(STATUSLINE_DEFAULTS, path55), optional, unsettable: acceptsNull(path55) };
5323
- if (leaf instanceof z10.ZodNumber) {
5323
+ if (leaf instanceof z11.ZodNumber) {
5324
5324
  return { ...common, kind: "integer", choices: [] };
5325
5325
  }
5326
- if (leaf instanceof z10.ZodBoolean) {
5326
+ if (leaf instanceof z11.ZodBoolean) {
5327
5327
  return { ...common, kind: "boolean", choices: [] };
5328
5328
  }
5329
- if (leaf instanceof z10.ZodString) {
5329
+ if (leaf instanceof z11.ZodString) {
5330
5330
  return { ...common, kind: "text", choices: [] };
5331
5331
  }
5332
- if (leaf instanceof z10.ZodUnion) {
5332
+ if (leaf instanceof z11.ZodUnion) {
5333
5333
  return { ...common, kind: "colour", choices: [...STATUSLINE_COLOUR_NAMES] };
5334
5334
  }
5335
- if (leaf instanceof z10.ZodEnum) {
5335
+ if (leaf instanceof z11.ZodEnum) {
5336
5336
  return { ...common, kind: "choice", choices: Object.values(leaf.enum).map(String) };
5337
5337
  }
5338
- if (leaf instanceof z10.ZodArray && leaf.element instanceof z10.ZodEnum) {
5338
+ if (leaf instanceof z11.ZodArray && leaf.element instanceof z11.ZodEnum) {
5339
5339
  return { ...common, kind: "list", choices: Object.values(leaf.element.enum).map(String) };
5340
5340
  }
5341
- if (leaf instanceof z10.ZodArray && leaf.element instanceof z10.ZodArray && leaf.element.element instanceof z10.ZodEnum) {
5341
+ if (leaf instanceof z11.ZodArray && leaf.element instanceof z11.ZodArray && leaf.element.element instanceof z11.ZodEnum) {
5342
5342
  return { ...common, kind: "groups", choices: Object.values(leaf.element.element.enum).map(String) };
5343
5343
  }
5344
- if (leaf instanceof z10.ZodArray && leaf.element instanceof z10.ZodString) {
5344
+ if (leaf instanceof z11.ZodArray && leaf.element instanceof z11.ZodString) {
5345
5345
  return { ...common, kind: "textList", choices: [] };
5346
5346
  }
5347
5347
  throw new TypeError(`statusline setting ${path55.join(".")} has a kind the key listing does not describe`);
5348
5348
  }
5349
5349
  function walk(shape, prefix) {
5350
- return Object.entries(shape).flatMap(([name, schema]) => schema instanceof z10.ZodObject ? walk(schema.shape, [...prefix, name]) : [keyOf([...prefix, name], schema)]);
5350
+ return Object.entries(shape).flatMap(([name, schema]) => schema instanceof z11.ZodObject ? walk(schema.shape, [...prefix, name]) : [keyOf([...prefix, name], schema)]);
5351
5351
  }
5352
5352
  function statuslineKeys() {
5353
5353
  return walk(ResolvedStatuslineSchema.shape, []);
@@ -5762,164 +5762,164 @@ var init_poolStore = __esm({
5762
5762
  });
5763
5763
 
5764
5764
  // src/usage/schema.ts
5765
- import { z as z11 } from "zod";
5765
+ import { z as z12 } from "zod";
5766
5766
  var USAGE_SCHEMA_VERSION, VersionSchema, InstantSchema, CLIENT_SESSION_ID_PATTERN, TokenCountSchema, TokenUsageSchema, LIMIT_KINDS, LimitClassificationSchema, UsageRecordSchema, QuotaWindowSchema, ExtraUsageSpendSchema, UnifiedRateLimitSchema, RateLimitStateSchema, LimitEventSchema, ProviderQuotaWindowSchema, ProviderAccountSchema, ProviderQuotaSchema, ProviderUsageStateSchema, AccountMetadataSchema, UsageSnapshotSchema;
5767
5767
  var init_schema2 = __esm({
5768
5768
  "src/usage/schema.ts"() {
5769
5769
  "use strict";
5770
5770
  USAGE_SCHEMA_VERSION = 1;
5771
- VersionSchema = z11.literal(USAGE_SCHEMA_VERSION);
5772
- InstantSchema = z11.iso.datetime();
5771
+ VersionSchema = z12.literal(USAGE_SCHEMA_VERSION);
5772
+ InstantSchema = z12.iso.datetime();
5773
5773
  CLIENT_SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
5774
- TokenCountSchema = z11.number().int().nonnegative();
5775
- TokenUsageSchema = z11.strictObject({
5774
+ TokenCountSchema = z12.number().int().nonnegative();
5775
+ TokenUsageSchema = z12.strictObject({
5776
5776
  inputTokens: TokenCountSchema.optional(),
5777
5777
  outputTokens: TokenCountSchema.optional(),
5778
5778
  cacheCreationInputTokens: TokenCountSchema.optional(),
5779
5779
  cacheReadInputTokens: TokenCountSchema.optional()
5780
5780
  });
5781
5781
  LIMIT_KINDS = ["rate-limited", "quota-exhausted"];
5782
- LimitClassificationSchema = z11.strictObject({
5783
- kind: z11.enum(LIMIT_KINDS),
5782
+ LimitClassificationSchema = z12.strictObject({
5783
+ kind: z12.enum(LIMIT_KINDS),
5784
5784
  /** Seconds to wait before retrying, from the response's `retry-after`. */
5785
- retryAfterSeconds: z11.number().nonnegative().optional(),
5785
+ retryAfterSeconds: z12.number().nonnegative().optional(),
5786
5786
  /** When the limiting window resets, from the upstream's own reset header. */
5787
5787
  resetAt: InstantSchema.optional(),
5788
5788
  /** The window the upstream named as the binding one (`anthropic-ratelimit-unified-representative-claim`), such as `five_hour` or `seven_day`. */
5789
- window: z11.string().optional(),
5789
+ window: z12.string().optional(),
5790
5790
  /** The signals the classification rests on, each `<name>=<value>` from a response header or the error body's `type` or `code`. Never the error message. */
5791
- evidence: z11.array(z11.string())
5791
+ evidence: z12.array(z12.string())
5792
5792
  });
5793
- UsageRecordSchema = z11.strictObject({
5793
+ UsageRecordSchema = z12.strictObject({
5794
5794
  schemaVersion: VersionSchema,
5795
5795
  /** When the front door received the request. */
5796
5796
  at: InstantSchema,
5797
5797
  /** The id of the launching identity (the directory it is stored in, which a rename of its name keeps), when the launch resolved one: what the session's identity header carries. */
5798
- identity: z11.string().optional(),
5798
+ identity: z12.string().optional(),
5799
5799
  /** `anthropic` for an OAuth session's request to Claude Code's own API, otherwise the provider's name. */
5800
- provider: z11.string(),
5800
+ provider: z12.string(),
5801
5801
  /** The launch's session id, generated per launch. */
5802
- sessionId: z11.string().optional(),
5802
+ sessionId: z12.string().optional(),
5803
5803
  /** The client's own id for the conversation, from the request's `x-claude-code-session-id` header: it changes when the conversation is cleared inside one launch, which `sessionId` does not, so it is what ties a request to the client's per-conversation figures. Absent when the client sent none. */
5804
- clientSessionId: z11.string().regex(CLIENT_SESSION_ID_PATTERN).optional(),
5804
+ clientSessionId: z12.string().regex(CLIENT_SESSION_ID_PATTERN).optional(),
5805
5805
  /** The project the launch ran in (its git repository root), when the launch sent one: headroom launches do. */
5806
- project: z11.string().optional(),
5806
+ project: z12.string().optional(),
5807
5807
  /** Whether the request crossed headroom on its way upstream. Absent on a record written before the door recorded it, and false when the request went direct. */
5808
- viaHeadroom: z11.boolean().optional(),
5808
+ viaHeadroom: z12.boolean().optional(),
5809
5809
  /** The front-door route that served the request. */
5810
- route: z11.string(),
5811
- method: z11.string(),
5810
+ route: z12.string(),
5811
+ method: z12.string(),
5812
5812
  /** The API path as the upstream sees it (`/v1/messages`), without the provider prefix or a query string. */
5813
- endpoint: z11.string(),
5813
+ endpoint: z12.string(),
5814
5814
  /** The model the response named. */
5815
- model: z11.string().optional(),
5815
+ model: z12.string().optional(),
5816
5816
  /** The model the session requested when a routing layer chose a different model, or when no response model was available to compare it with. Absent when the response confirms that the requested name was served unchanged. */
5817
- requestedModel: z11.string().optional(),
5817
+ requestedModel: z12.string().optional(),
5818
5818
  /** The distinct providers the choice could have landed on, present only when there was more than one, so a reader can tell a choice that crossed providers from one that stayed inside a single provider's lineup. */
5819
- candidateProviders: z11.array(z11.string()).optional(),
5820
- status: z11.number().int(),
5819
+ candidateProviders: z12.array(z12.string()).optional(),
5820
+ status: z12.number().int(),
5821
5821
  /** Milliseconds from the request's arrival to its response head. */
5822
- latencyMs: z11.number().int().nonnegative(),
5822
+ latencyMs: z12.number().int().nonnegative(),
5823
5823
  /** Milliseconds from the request's arrival to the end of its response body. */
5824
- durationMs: z11.number().int().nonnegative(),
5824
+ durationMs: z12.number().int().nonnegative(),
5825
5825
  /** Whether the client received the whole body. */
5826
- outcome: z11.enum(["completed", "aborted"]),
5826
+ outcome: z12.enum(["completed", "aborted"]),
5827
5827
  usage: TokenUsageSchema.optional(),
5828
5828
  /** The response's quota and rate-limit headers, by name (see `isRateLimitHeader`). */
5829
- rateLimitHeaders: z11.record(z11.string(), z11.string()).optional(),
5829
+ rateLimitHeaders: z12.record(z12.string(), z12.string()).optional(),
5830
5830
  limit: LimitClassificationSchema.optional(),
5831
5831
  /** The upstream's request id (`request-id`), for matching a record to the provider's own logs. */
5832
- requestId: z11.string().optional()
5832
+ requestId: z12.string().optional()
5833
5833
  });
5834
- QuotaWindowSchema = z11.strictObject({
5834
+ QuotaWindowSchema = z12.strictObject({
5835
5835
  /** The fraction of the window used, as the upstream reports it (0 to 1). */
5836
- utilization: z11.number().nonnegative().optional(),
5836
+ utilization: z12.number().nonnegative().optional(),
5837
5837
  resetsAt: InstantSchema.optional(),
5838
5838
  /** The window's own status (`allowed`, `allowed_warning`, `rejected`). */
5839
- status: z11.string().optional(),
5839
+ status: z12.string().optional(),
5840
5840
  /** The fraction of the window's grace allowance used, while the upstream reports the window in grace (the five-hour window only). Requests are served beyond the window's own full mark while it grows, but refusals have been seen at a small value, so nothing ranks on it. */
5841
- graceUtilization: z11.number().nonnegative().optional()
5841
+ graceUtilization: z12.number().nonnegative().optional()
5842
5842
  });
5843
- ExtraUsageSpendSchema = z11.strictObject({
5843
+ ExtraUsageSpendSchema = z12.strictObject({
5844
5844
  /** Spent so far in the allowance's period, in the currency's minor units (pence, cents). */
5845
- usedMinor: z11.number().nonnegative(),
5845
+ usedMinor: z12.number().nonnegative(),
5846
5846
  /** The allowance's cap in the same units, when it has one. */
5847
- limitMinor: z11.number().nonnegative().optional(),
5847
+ limitMinor: z12.number().nonnegative().optional(),
5848
5848
  /** The ISO 4217 currency code. */
5849
- currency: z11.string()
5849
+ currency: z12.string()
5850
5850
  });
5851
- UnifiedRateLimitSchema = z11.strictObject({
5851
+ UnifiedRateLimitSchema = z12.strictObject({
5852
5852
  /** The overall status: `allowed`, `allowed_warning` or `rejected`. */
5853
- status: z11.string().optional(),
5853
+ status: z12.string().optional(),
5854
5854
  fiveHour: QuotaWindowSchema.optional(),
5855
5855
  sevenDay: QuotaWindowSchema.optional(),
5856
5856
  /** The weekly window of the models whose usage may continue as extra usage (`7d_oi`), reported by some plans beside the all-models weekly window. */
5857
5857
  sevenDayOverageIncluded: QuotaWindowSchema.optional(),
5858
5858
  /** The window that currently binds. */
5859
- representativeClaim: z11.string().optional(),
5859
+ representativeClaim: z12.string().optional(),
5860
5860
  /** When the binding window resets. */
5861
5861
  resetAt: InstantSchema.optional(),
5862
5862
  /** Whether usage beyond the plan (extra usage) is available: `allowed` or `rejected`. */
5863
- overageStatus: z11.string().optional(),
5863
+ overageStatus: z12.string().optional(),
5864
5864
  /** The fraction of the extra-usage allowance used, as the upstream reports it (0 to 1). An account with no plan windows, such as an Enterprise one, is metered by this alone. */
5865
- overageUtilization: z11.number().nonnegative().optional(),
5865
+ overageUtilization: z12.number().nonnegative().optional(),
5866
5866
  /** When the extra-usage allowance resets. */
5867
5867
  overageResetsAt: InstantSchema.optional(),
5868
5868
  /** Why extra usage is unavailable, as the upstream names it (`out_of_credits`, for one). */
5869
- overageDisabledReason: z11.string().optional(),
5869
+ overageDisabledReason: z12.string().optional(),
5870
5870
  /** Whether the response was served on extra usage, as the upstream states it. */
5871
- overageInUse: z11.boolean().optional(),
5871
+ overageInUse: z12.boolean().optional(),
5872
5872
  /** The allowance in money, from the usage endpoint (the response headers state only the fraction). */
5873
5873
  extraUsageSpend: ExtraUsageSpendSchema.optional(),
5874
5874
  /** True when the upstream offers a fallback while a window is rejected: some requests, by model, are still served, though the rest are refused. */
5875
- fallbackAvailable: z11.boolean().optional()
5875
+ fallbackAvailable: z12.boolean().optional()
5876
5876
  });
5877
- RateLimitStateSchema = z11.strictObject({
5877
+ RateLimitStateSchema = z12.strictObject({
5878
5878
  observedAt: InstantSchema,
5879
5879
  /** Every quota and rate-limit header on that response, by name. */
5880
- headers: z11.record(z11.string(), z11.string()),
5880
+ headers: z12.record(z12.string(), z12.string()),
5881
5881
  unified: UnifiedRateLimitSchema.optional(),
5882
5882
  /** When the usage endpoint last answered that it has no plan windows for the account, which a later response replaces. Its answer leaves the recorded `unified` state alone (a response's headers may be the only source of it), so this alone says the question was asked. */
5883
5883
  planWindowsUnavailableAt: InstantSchema.optional()
5884
5884
  });
5885
5885
  LimitEventSchema = LimitClassificationSchema.extend({
5886
5886
  observedAt: InstantSchema,
5887
- status: z11.number().int()
5887
+ status: z12.number().int()
5888
5888
  });
5889
- ProviderQuotaWindowSchema = z11.strictObject({
5889
+ ProviderQuotaWindowSchema = z12.strictObject({
5890
5890
  /** What the window measures, in the provider's terms (`tokens`, `tool-calls`). */
5891
- measures: z11.string(),
5891
+ measures: z12.string(),
5892
5892
  /** The window's length in milliseconds, when the provider's unit is one this project knows; absent for an unrecognised unit, with `period` carrying the raw code. */
5893
- periodMs: z11.number().int().positive().optional(),
5893
+ periodMs: z12.number().int().positive().optional(),
5894
5894
  /** The provider's own description of the period when `periodMs` could not be derived, such as `unit 4 x 1`. */
5895
- period: z11.string().optional(),
5895
+ period: z12.string().optional(),
5896
5896
  /** The fraction of the window used (0 to 1). */
5897
- utilization: z11.number().nonnegative(),
5897
+ utilization: z12.number().nonnegative(),
5898
5898
  resetsAt: InstantSchema.optional(),
5899
5899
  /** Absolute counts, when the provider reports them for this window. */
5900
- limit: z11.number().nonnegative().optional(),
5901
- used: z11.number().nonnegative().optional(),
5902
- remaining: z11.number().nonnegative().optional()
5900
+ limit: z12.number().nonnegative().optional(),
5901
+ used: z12.number().nonnegative().optional(),
5902
+ remaining: z12.number().nonnegative().optional()
5903
5903
  });
5904
- ProviderAccountSchema = z11.strictObject({
5905
- email: z11.string().optional(),
5906
- accountId: z11.string().optional()
5904
+ ProviderAccountSchema = z12.strictObject({
5905
+ email: z12.string().optional(),
5906
+ accountId: z12.string().optional()
5907
5907
  });
5908
- ProviderQuotaSchema = z11.strictObject({
5908
+ ProviderQuotaSchema = z12.strictObject({
5909
5909
  observedAt: InstantSchema,
5910
5910
  /** Which usage endpoint produced it (`z.ai`). */
5911
- source: z11.string(),
5911
+ source: z12.string(),
5912
5912
  /** The subscription level the endpoint reports, when it does. */
5913
- level: z11.string().optional(),
5913
+ level: z12.string().optional(),
5914
5914
  /** The account the provider's credential belongs to, when its endpoint reports it. */
5915
5915
  account: ProviderAccountSchema.optional(),
5916
- windows: z11.array(ProviderQuotaWindowSchema)
5916
+ windows: z12.array(ProviderQuotaWindowSchema)
5917
5917
  });
5918
- ProviderUsageStateSchema = z11.strictObject({
5918
+ ProviderUsageStateSchema = z12.strictObject({
5919
5919
  /** When the provider last served a request for the identity through the front door. Absent while the state holds only a rate-limit state fetched from the provider's usage endpoint, for an identity that has made no request. */
5920
5920
  lastRequestAt: InstantSchema.optional(),
5921
- lastStatus: z11.number().int().optional(),
5922
- lastModel: z11.string().optional(),
5921
+ lastStatus: z12.number().int().optional(),
5922
+ lastModel: z12.string().optional(),
5923
5923
  /** The latest rate-limit state, from the last response that carried any rate-limit header. */
5924
5924
  rateLimit: RateLimitStateSchema.optional(),
5925
5925
  /** The latest classified refusal. It stays after later successes, so a reader compares its `resetAt` (or `observedAt` plus `retryAfterSeconds`) with the current time. */
@@ -5927,31 +5927,31 @@ var init_schema2 = __esm({
5927
5927
  /** The latest quota the provider's usage endpoint reported, for providers whose quota is not visible in response headers. */
5928
5928
  quota: ProviderQuotaSchema.optional()
5929
5929
  });
5930
- AccountMetadataSchema = z11.strictObject({
5931
- accountUuid: z11.string().optional(),
5932
- emailAddress: z11.string().optional(),
5933
- displayName: z11.string().optional(),
5934
- organizationUuid: z11.string().optional(),
5935
- organizationName: z11.string().optional(),
5936
- organizationType: z11.string().optional(),
5937
- organizationRole: z11.string().optional(),
5938
- workspaceRole: z11.string().optional(),
5939
- billingType: z11.string().optional(),
5940
- seatTier: z11.string().optional(),
5941
- organizationRateLimitTier: z11.string().optional(),
5942
- userRateLimitTier: z11.string().optional(),
5943
- hasExtraUsageEnabled: z11.boolean().optional(),
5944
- subscriptionCreatedAt: z11.string().optional(),
5945
- accountCreatedAt: z11.string().optional()
5930
+ AccountMetadataSchema = z12.strictObject({
5931
+ accountUuid: z12.string().optional(),
5932
+ emailAddress: z12.string().optional(),
5933
+ displayName: z12.string().optional(),
5934
+ organizationUuid: z12.string().optional(),
5935
+ organizationName: z12.string().optional(),
5936
+ organizationType: z12.string().optional(),
5937
+ organizationRole: z12.string().optional(),
5938
+ workspaceRole: z12.string().optional(),
5939
+ billingType: z12.string().optional(),
5940
+ seatTier: z12.string().optional(),
5941
+ organizationRateLimitTier: z12.string().optional(),
5942
+ userRateLimitTier: z12.string().optional(),
5943
+ hasExtraUsageEnabled: z12.boolean().optional(),
5944
+ subscriptionCreatedAt: z12.string().optional(),
5945
+ accountCreatedAt: z12.string().optional()
5946
5946
  });
5947
- UsageSnapshotSchema = z11.strictObject({
5947
+ UsageSnapshotSchema = z12.strictObject({
5948
5948
  schemaVersion: VersionSchema,
5949
- identity: z11.string(),
5949
+ identity: z12.string(),
5950
5950
  updatedAt: InstantSchema,
5951
5951
  /** The identity's account metadata as of `updatedAt`. */
5952
5952
  account: AccountMetadataSchema.optional(),
5953
5953
  /** Latest state per provider, keyed by provider name (`anthropic` for OAuth sessions). */
5954
- providers: z11.record(z11.string(), ProviderUsageStateSchema)
5954
+ providers: z12.record(z12.string(), ProviderUsageStateSchema)
5955
5955
  });
5956
5956
  }
5957
5957
  });
@@ -6327,7 +6327,7 @@ var init_preflight = __esm({
6327
6327
  });
6328
6328
 
6329
6329
  // src/credentialCache.ts
6330
- import { z as z12 } from "zod";
6330
+ import { z as z13 } from "zod";
6331
6331
  function effectiveStore(cache, platform) {
6332
6332
  return cache.store ?? (platform === "darwin" ? "keychain" : "file");
6333
6333
  }
@@ -6394,11 +6394,11 @@ var init_credentialCache = __esm({
6394
6394
  init_schema();
6395
6395
  init_preflight();
6396
6396
  MS_PER_UNIT = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
6397
- CachedCredentialSchema = z12.strictObject({
6398
- token: z12.string().min(1),
6399
- fetchedAt: z12.number().int().nonnegative(),
6397
+ CachedCredentialSchema = z13.strictObject({
6398
+ token: z13.string().min(1),
6399
+ fetchedAt: z13.number().int().nonnegative(),
6400
6400
  source: CredentialSourceSchema,
6401
- owner: z12.string().min(1).optional()
6401
+ owner: z13.string().min(1).optional()
6402
6402
  });
6403
6403
  KEYCHAIN_CACHE_SERVICE = "agent-shim-credential-cache";
6404
6404
  KEYCHAIN_ITEM_NOT_FOUND_STATUS = 44;
@@ -6485,7 +6485,7 @@ function describeCredential(credential) {
6485
6485
  function cacheKeyOf(params) {
6486
6486
  return params.cacheKey ?? params.subject;
6487
6487
  }
6488
- function isRecord5(value) {
6488
+ function isRecord6(value) {
6489
6489
  return typeof value === "object" && value !== null && !Array.isArray(value);
6490
6490
  }
6491
6491
  function unpackKeyringToken(raw) {
@@ -6497,7 +6497,7 @@ function unpackKeyringToken(raw) {
6497
6497
  const base64Str = trimmed.slice(GO_KEYRING_BASE64_PREFIX.length);
6498
6498
  const decoded = Buffer.from(base64Str, "base64").toString("utf8");
6499
6499
  const parsed = JSON.parse(decoded);
6500
- if (isRecord5(parsed) && isRecord5(parsed.token)) {
6500
+ if (isRecord6(parsed) && isRecord6(parsed.token)) {
6501
6501
  const accessToken = parsed.token.access_token;
6502
6502
  if (typeof accessToken === "string" && accessToken.trim() !== "") {
6503
6503
  return accessToken.trim();
@@ -6663,11 +6663,226 @@ var init_blockingSpawn = __esm({
6663
6663
  }
6664
6664
  });
6665
6665
 
6666
+ // src/headroom/headers.ts
6667
+ function mergeAnthropicCustomHeaders(existing, additions) {
6668
+ const merged = /* @__PURE__ */ new Map();
6669
+ for (const block of existing) {
6670
+ if (block === void 0) {
6671
+ continue;
6672
+ }
6673
+ for (const line of block.split("\n")) {
6674
+ const entry = parseCustomHeaderLine(line);
6675
+ if (entry === void 0) {
6676
+ continue;
6677
+ }
6678
+ merged.set(entry.name, entry.value);
6679
+ }
6680
+ }
6681
+ for (const entry of additions) {
6682
+ merged.set(entry.name, entry.value);
6683
+ }
6684
+ return [...merged].map(([name, value]) => `${name}: ${value}`).join("\n");
6685
+ }
6686
+ function parseAnthropicCustomHeaders(block) {
6687
+ return block.split("\n").flatMap((line) => {
6688
+ const entry = parseCustomHeaderLine(line);
6689
+ return entry === void 0 ? [] : [entry];
6690
+ });
6691
+ }
6692
+ function withoutAnthropicCustomHeaders(block, remove) {
6693
+ const lines = block.split("\n");
6694
+ const kept = lines.filter((line) => {
6695
+ const entry = parseCustomHeaderLine(line);
6696
+ return entry === void 0 || !remove(entry);
6697
+ });
6698
+ return kept.length === lines.length ? block : kept.join("\n");
6699
+ }
6700
+ function parseCustomHeaderLine(line) {
6701
+ const trimmed = line.trim();
6702
+ if (trimmed === "") {
6703
+ return void 0;
6704
+ }
6705
+ const colon = trimmed.indexOf(":");
6706
+ if (colon <= 0) {
6707
+ return void 0;
6708
+ }
6709
+ return { name: trimmed.slice(0, colon).trim(), value: trimmed.slice(colon + 1).trim() };
6710
+ }
6711
+ var init_headers = __esm({
6712
+ "src/headroom/headers.ts"() {
6713
+ "use strict";
6714
+ }
6715
+ });
6716
+
6717
+ // src/launcher/injected.ts
6718
+ import { createHash as createHash4 } from "node:crypto";
6719
+ import { z as z14 } from "zod";
6720
+ function listKey(list) {
6721
+ return `${list},appended`;
6722
+ }
6723
+ function digest2(value) {
6724
+ return createHash4("sha256").update(value).digest("hex");
6725
+ }
6726
+ function recordedDigests(env) {
6727
+ const raw = env[INJECTED_ENV];
6728
+ if (raw === void 0 || raw === "") {
6729
+ return {};
6730
+ }
6731
+ let parsed;
6732
+ try {
6733
+ parsed = JSON.parse(raw);
6734
+ } catch {
6735
+ return {};
6736
+ }
6737
+ const result = InjectedSchema.safeParse(parsed);
6738
+ return result.success ? result.data : {};
6739
+ }
6740
+ function recordInjections(base) {
6741
+ const env = { ...base };
6742
+ const digests = new Map(Object.entries(recordedDigests(env)));
6743
+ return {
6744
+ env,
6745
+ set: (name, value) => {
6746
+ env[name] = value;
6747
+ digests.set(name, digest2(value));
6748
+ },
6749
+ unset: (name) => {
6750
+ env[name] = void 0;
6751
+ digests.delete(name);
6752
+ },
6753
+ recordHeaders: (names) => {
6754
+ const block = env[CUSTOM_HEADERS_ENV];
6755
+ for (const entry of block === void 0 ? [] : parseAnthropicCustomHeaders(block)) {
6756
+ if (names.includes(entry.name)) {
6757
+ digests.set(`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`, digest2(entry.value));
6758
+ }
6759
+ }
6760
+ },
6761
+ recordBypassHosts: (list, hosts) => {
6762
+ const recordedHosts = [.../* @__PURE__ */ new Set([...digests.get(listKey(list))?.split(",") ?? [], ...hosts.map((host) => host.trim().toLowerCase()).filter((host) => host !== "")])];
6763
+ if (recordedHosts.length > 0) {
6764
+ digests.set(listKey(list), recordedHosts.join(","));
6765
+ }
6766
+ },
6767
+ finish: () => {
6768
+ if (digests.size > 0) {
6769
+ env[INJECTED_ENV] = JSON.stringify(Object.fromEntries(digests));
6770
+ }
6771
+ }
6772
+ };
6773
+ }
6774
+ function withoutRecordedHosts(list, value, digests) {
6775
+ const recordedHosts = new Set(digests[listKey(list)]?.split(","));
6776
+ const entries = value.split(",");
6777
+ const kept = entries.filter((entry) => !recordedHosts.has(entry.trim().toLowerCase()));
6778
+ return kept.length === entries.length ? value : kept.join(",");
6779
+ }
6780
+ function launchEnvironment(env, configDirEscapeHatch) {
6781
+ return configDirEscapeHatch ? env : withoutInjected(env);
6782
+ }
6783
+ function withoutInjected(env) {
6784
+ const digests = recordedDigests(env);
6785
+ const entries = Object.entries(env).flatMap(([name, value]) => {
6786
+ if (name === INJECTED_ENV) {
6787
+ return [];
6788
+ }
6789
+ if (value === void 0) {
6790
+ return [[name, value]];
6791
+ }
6792
+ if (name === CUSTOM_HEADERS_ENV) {
6793
+ const remaining = withoutAnthropicCustomHeaders(value, (entry) => digests[`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`] === digest2(entry.value));
6794
+ return remaining !== value && remaining.trim() === "" ? [] : [[name, remaining]];
6795
+ }
6796
+ if (name === "NO_PROXY" || name === "no_proxy") {
6797
+ const remaining = withoutRecordedHosts(name, value, digests);
6798
+ return remaining !== value && remaining.split(",").every((entry) => entry.trim() === "") ? [] : [[name, remaining]];
6799
+ }
6800
+ return digests[name] === digest2(value) ? [] : [[name, value]];
6801
+ });
6802
+ return Object.fromEntries(entries);
6803
+ }
6804
+ var INJECTED_ENV, CUSTOM_HEADERS_ENV, HEADER_KEY_PREFIX, InjectedSchema;
6805
+ var init_injected = __esm({
6806
+ "src/launcher/injected.ts"() {
6807
+ "use strict";
6808
+ init_headers();
6809
+ INJECTED_ENV = "AGENT_SHIM_INJECTED";
6810
+ CUSTOM_HEADERS_ENV = "ANTHROPIC_CUSTOM_HEADERS";
6811
+ HEADER_KEY_PREFIX = `${CUSTOM_HEADERS_ENV}:`;
6812
+ InjectedSchema = z14.record(z14.string(), z14.string());
6813
+ }
6814
+ });
6815
+
6816
+ // src/launcher/guard.ts
6817
+ function detectAmbientCredential(env, injected) {
6818
+ for (const variable of AMBIENT_CREDENTIAL_VARS) {
6819
+ const value = env[variable];
6820
+ if (value === void 0 || value === "") {
6821
+ continue;
6822
+ }
6823
+ if (injected?.variable === variable && value === injected.token) {
6824
+ continue;
6825
+ }
6826
+ return { variable };
6827
+ }
6828
+ return void 0;
6829
+ }
6830
+ function formatAmbientCredentialGuardMessage(variable, identityName) {
6831
+ const identitySetCommand = identityName === void 0 ? "agent-shim identity set <name> --allow-ambient-credential" : `agent-shim identity set ${identityName} --allow-ambient-credential`;
6832
+ return [
6833
+ `error: ${variable} is set in the environment. This identity's isolated`,
6834
+ "credential would be bypassed \u2014 every identity authenticates as this same key",
6835
+ "while it's set. Unset it, or if this is deliberate, opt in per-launch with",
6836
+ "AGENT_SHIM_ALLOW_AMBIENT_CREDENTIAL=1, or persistently for this identity with",
6837
+ `\`${identitySetCommand}\`.`
6838
+ ].join("\n");
6839
+ }
6840
+ function evaluateAmbientCredentialGuard(params) {
6841
+ const detected = detectAmbientCredential(params.env, params.injectedCredential);
6842
+ if (detected === void 0) {
6843
+ return { ok: true };
6844
+ }
6845
+ if (params.allowAmbientCredentialOverride || params.allowAmbientCredential || params.providerSelected === true) {
6846
+ return { ok: true };
6847
+ }
6848
+ return {
6849
+ ok: false,
6850
+ variable: detected.variable,
6851
+ message: formatAmbientCredentialGuardMessage(detected.variable, params.identityName)
6852
+ };
6853
+ }
6854
+ function ambientCredentialFinding(env) {
6855
+ const named = detectAmbientCredential(launchEnvironment(env, false));
6856
+ if (named !== void 0) {
6857
+ return { severity: "warn", message: formatAmbientCredentialGuardMessage(named.variable) };
6858
+ }
6859
+ const bare = env.CLAUDE_CONFIG_DIR === void 0 || env.CLAUDE_CONFIG_DIR === "" ? void 0 : detectAmbientCredential(env);
6860
+ if (bare !== void 0) {
6861
+ return { severity: "warn", message: `${bare.variable} was set in this session by the launcher that started it. A launch that names an identity drops it, but a launch naming none keeps the session's CLAUDE_CONFIG_DIR and environment and is refused. Name an identity, as in \`claude @<name>\`.` };
6862
+ }
6863
+ return { severity: "pass", message: "No ambient-credential environment variable is set." };
6864
+ }
6865
+ var AMBIENT_CREDENTIAL_VARS;
6866
+ var init_guard = __esm({
6867
+ "src/launcher/guard.ts"() {
6868
+ "use strict";
6869
+ init_injected();
6870
+ AMBIENT_CREDENTIAL_VARS = [
6871
+ "ANTHROPIC_API_KEY",
6872
+ "ANTHROPIC_AUTH_TOKEN",
6873
+ "CLAUDE_CODE_OAUTH_TOKEN",
6874
+ "CLAUDE_CODE_USE_BEDROCK",
6875
+ "CLAUDE_CODE_USE_VERTEX",
6876
+ "CLAUDE_CODE_USE_FOUNDRY"
6877
+ ];
6878
+ }
6879
+ });
6880
+
6666
6881
  // src/usage/signIn.ts
6667
- import { createHash as createHash3 } from "node:crypto";
6882
+ import { createHash as createHash5 } from "node:crypto";
6668
6883
  import path19 from "node:path";
6669
6884
  function claudeCodeKeychainService(configDir) {
6670
- return `${KEYCHAIN_SERVICE_PREFIX}-${createHash3("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
6885
+ return `${KEYCHAIN_SERVICE_PREFIX}-${createHash5("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
6671
6886
  }
6672
6887
  function keychainHasItem(run, configDir) {
6673
6888
  return run.run("security", ["find-generic-password", "-s", claudeCodeKeychainService(configDir)]).status === 0;
@@ -6700,13 +6915,33 @@ function identitySignIn(fs17, probe, identity) {
6700
6915
  platform: probe.platform
6701
6916
  });
6702
6917
  }
6703
- var CREDENTIALS_FILE, KEYCHAIN_SERVICE_PREFIX, KEYCHAIN_SERVICE_HASH_DIGITS;
6918
+ function storedLoginUsable(run, claudeBin, configDir, env) {
6919
+ const childEnv = { ...env, CLAUDE_CONFIG_DIR: configDir };
6920
+ for (const variable of AMBIENT_CREDENTIAL_VARS) {
6921
+ childEnv[variable] = void 0;
6922
+ }
6923
+ const result = run.run(claudeBin, ["auth", "status"], void 0, { env: childEnv, timeoutMs: AUTH_STATUS_TIMEOUT_MS });
6924
+ if (result.status === null) {
6925
+ return void 0;
6926
+ }
6927
+ try {
6928
+ const status = JSON.parse(result.stdout);
6929
+ if (typeof status === "object" && status !== null && "loggedIn" in status && typeof status.loggedIn === "boolean") {
6930
+ return status.loggedIn;
6931
+ }
6932
+ } catch {
6933
+ }
6934
+ return void 0;
6935
+ }
6936
+ var CREDENTIALS_FILE, KEYCHAIN_SERVICE_PREFIX, KEYCHAIN_SERVICE_HASH_DIGITS, AUTH_STATUS_TIMEOUT_MS;
6704
6937
  var init_signIn = __esm({
6705
6938
  "src/usage/signIn.ts"() {
6706
6939
  "use strict";
6940
+ init_guard();
6707
6941
  CREDENTIALS_FILE = ".credentials.json";
6708
6942
  KEYCHAIN_SERVICE_PREFIX = "Claude Code-credentials";
6709
6943
  KEYCHAIN_SERVICE_HASH_DIGITS = 8;
6944
+ AUTH_STATUS_TIMEOUT_MS = 1e4;
6710
6945
  }
6711
6946
  });
6712
6947
 
@@ -7071,9 +7306,9 @@ var init_supervisorProcesses = __esm({
7071
7306
  });
7072
7307
 
7073
7308
  // src/headroom/state.ts
7074
- import { createHash as createHash4 } from "node:crypto";
7309
+ import { createHash as createHash6 } from "node:crypto";
7075
7310
  import path21 from "node:path";
7076
- import { z as z13 } from "zod";
7311
+ import { z as z15 } from "zod";
7077
7312
  function parseJson(raw, schema) {
7078
7313
  if (raw === void 0 || raw.trim() === "") {
7079
7314
  return void 0;
@@ -7120,7 +7355,7 @@ function migrateHeadroomState(fs17, files, isRunning) {
7120
7355
  fs17.removeRecursive(files.legacyStateFile);
7121
7356
  }
7122
7357
  function hashAllowlist(allowlist) {
7123
- return createHash4("sha256").update(allowlist.join("\n")).digest("hex");
7358
+ return createHash6("sha256").update(allowlist.join("\n")).digest("hex");
7124
7359
  }
7125
7360
  function formatAllowlistFile(allowlist) {
7126
7361
  return allowlist.map((entry) => `${entry}
@@ -7230,32 +7465,32 @@ var init_state2 = __esm({
7230
7465
  "src/headroom/state.ts"() {
7231
7466
  "use strict";
7232
7467
  init_schema();
7233
- HeadroomStateSchema = z13.strictObject({
7468
+ HeadroomStateSchema = z15.strictObject({
7234
7469
  /** The supervisor process owning the daemon. Alive means someone is keeping headroom running. */
7235
- supervisorPid: z13.number().int().positive().optional(),
7470
+ supervisorPid: z15.number().int().positive().optional(),
7236
7471
  /** The headroom proxy process itself, recorded as soon as it is spawned (before it is ready, which `socketPath` signals) so a successor can find a daemon whose supervisor died during its start. Absent while the supervisor is between restarts. */
7237
- headroomPid: z13.number().int().positive().optional(),
7472
+ headroomPid: z15.number().int().positive().optional(),
7238
7473
  /**
7239
7474
  * The unix socket the proxy serves on, inside the owner-only socket directory. Absent until the proxy has passed its readiness check, so "socketPath is set" is itself the ready signal a launcher polls for. The front door reads it on every hop, so a restart (which keeps the generation's path) is followed without anything being relaunched.
7240
7475
  */
7241
- socketPath: z13.string().min(1).optional(),
7476
+ socketPath: z15.string().min(1).optional(),
7242
7477
  /** The `headroom --version` output of the running install. */
7243
- version: z13.string().optional(),
7478
+ version: z15.string().optional(),
7244
7479
  /**
7245
7480
  * Hash of the allowlist the running proxy serves. The supervisor records it in the same tick it writes that allowlist to `LayoutPaths.headroomAllowlistFile`, which the proxy re-reads on its next request, so a provider launch, whose requests come back through its front door's direct origin, waits until this names an allowlist holding that origin. A supervisor from an earlier release records here the hash of the allowlist its daemon was started with instead (see `earlierRelease.ts`).
7246
7481
  */
7247
- allowlistHash: z13.string().optional(),
7482
+ allowlistHash: z15.string().optional(),
7248
7483
  /** Hash of the token-saving settings the running proxy was started with, so a settings change is detected as drift. */
7249
- settingsHash: z13.string().optional(),
7484
+ settingsHash: z15.string().optional(),
7250
7485
  /** The install spec the running install was last installed from, so a `source` config change is detected as drift. */
7251
- installedSource: z13.string().optional(),
7486
+ installedSource: z15.string().optional(),
7252
7487
  /** The install spec the supervisor is installing right now, present only while `uv tool install` runs, so a launcher that finds a live supervisor with no daemon yet keeps waiting for the install instead of counting it against its start bound. Cleared by the write that follows the install, whatever its outcome. */
7253
- installing: z13.string().optional(),
7488
+ installing: z15.string().optional(),
7254
7489
  /** The last fatal error, kept across shutdowns so `headroom status` can explain a daemon that is not running. */
7255
- lastError: z13.string().optional()
7490
+ lastError: z15.string().optional()
7256
7491
  });
7257
- HeadroomSessionSchema = z13.strictObject({ pid: z13.number().int().positive(), startedAt: z13.number(), supervisorPid: z13.number().int().positive() });
7258
- HeadroomLockSchema = z13.strictObject({ pid: z13.number().int().positive(), at: z13.number() });
7492
+ HeadroomSessionSchema = z15.strictObject({ pid: z15.number().int().positive(), startedAt: z15.number(), supervisorPid: z15.number().int().positive() });
7493
+ HeadroomLockSchema = z15.strictObject({ pid: z15.number().int().positive(), at: z15.number() });
7259
7494
  HEADROOM_ALLOWLIST_FILE_FLAG = "--allowed-base-urls-file";
7260
7495
  ALLOWLIST_LINE_BREAKS = "\\n\\r\\u000b\\u000c\\u001c\\u001d\\u001e\\u0085\\u2028\\u2029";
7261
7496
  ALLOWLIST_WHITESPACE = "\\t\\n\\u000b\\u000c\\r\\u001c-\\u001f \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
@@ -7445,7 +7680,7 @@ var init_ensure = __esm({
7445
7680
  });
7446
7681
 
7447
7682
  // src/headroom/settings.ts
7448
- import { createHash as createHash5 } from "node:crypto";
7683
+ import { createHash as createHash7 } from "node:crypto";
7449
7684
  function settingsOf(config) {
7450
7685
  return {
7451
7686
  ...config.mode === void 0 ? {} : { mode: config.mode },
@@ -7470,7 +7705,7 @@ function settingsEnv(settings) {
7470
7705
  return settings.rolloutChannel === void 0 ? {} : { HEADROOM_ROLLOUT_CHANNEL: settings.rolloutChannel };
7471
7706
  }
7472
7707
  function hashSettings(settings) {
7473
- return createHash5("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
7708
+ return createHash7("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
7474
7709
  }
7475
7710
  var init_settings = __esm({
7476
7711
  "src/headroom/settings.ts"() {
@@ -7662,7 +7897,7 @@ var init_socket = __esm({
7662
7897
  });
7663
7898
 
7664
7899
  // src/headroom/source.ts
7665
- import { z as z14 } from "zod";
7900
+ import { z as z16 } from "zod";
7666
7901
  function isMovingGitSource(spec) {
7667
7902
  const match = GIT_SPEC_RE.exec(spec);
7668
7903
  if (match === null) {
@@ -7681,7 +7916,7 @@ var init_source = __esm({
7681
7916
  "use strict";
7682
7917
  GIT_SPEC_RE = /git\+[^@\s]+(?:@([^\s#]+))?/;
7683
7918
  COMMIT_SHA_RE = /^[0-9a-f]{40}$/i;
7684
- DirectUrlSchema = z14.object({ vcs_info: z14.object({ commit_id: z14.string() }) });
7919
+ DirectUrlSchema = z16.object({ vcs_info: z16.object({ commit_id: z16.string() }) });
7685
7920
  }
7686
7921
  });
7687
7922
 
@@ -8126,7 +8361,7 @@ var init_logStyle = __esm({
8126
8361
 
8127
8362
  // src/realPorts.ts
8128
8363
  import { execFile, spawn } from "node:child_process";
8129
- import { createHash as createHash6 } from "node:crypto";
8364
+ import { createHash as createHash8 } from "node:crypto";
8130
8365
  import fs6 from "node:fs";
8131
8366
  import os2 from "node:os";
8132
8367
  import path24 from "node:path";
@@ -8193,6 +8428,9 @@ function realFrontDoorLiveness(pids) {
8193
8428
  return { status: result.status, stdout: result.stdout, stderr: result.stderr, ...result.error === void 0 ? {} : { error: result.error } };
8194
8429
  });
8195
8430
  }
8431
+ function definedEntries(env) {
8432
+ return Object.fromEntries(Object.entries(env).filter((entry) => entry[1] !== void 0));
8433
+ }
8196
8434
  function realRunAsyncWithin(timeoutMs) {
8197
8435
  return async (command, args) => await new Promise((resolve) => {
8198
8436
  execFile(command, [...args], { encoding: "utf8", timeout: timeoutMs }, (error, stdout, stderr) => {
@@ -8553,7 +8791,7 @@ var init_realPorts = __esm({
8553
8791
  },
8554
8792
  hashFile(filePath) {
8555
8793
  try {
8556
- return createHash6("sha256").update(fs6.readFileSync(filePath)).digest("hex");
8794
+ return createHash8("sha256").update(fs6.readFileSync(filePath)).digest("hex");
8557
8795
  } catch (error) {
8558
8796
  if (isEnoent3(error) || isErrorWithCode(error, "EISDIR")) {
8559
8797
  return void 0;
@@ -8593,8 +8831,14 @@ var init_realPorts = __esm({
8593
8831
  BYTES_PER_MIB2 = 1048576;
8594
8832
  RUN_OUTPUT_LIMIT_BYTES = RUN_OUTPUT_LIMIT_MIB * BYTES_PER_MIB2;
8595
8833
  realRunPort = {
8596
- run(command, args, input) {
8597
- const result = spawnSyncBlocking("an external command", command, args, { encoding: "utf8", maxBuffer: RUN_OUTPUT_LIMIT_BYTES, ...input === void 0 ? {} : { input } });
8834
+ run(command, args, input, options) {
8835
+ const result = spawnSyncBlocking("an external command", command, args, {
8836
+ encoding: "utf8",
8837
+ maxBuffer: RUN_OUTPUT_LIMIT_BYTES,
8838
+ ...input === void 0 ? {} : { input },
8839
+ ...options?.env === void 0 ? {} : { env: definedEntries(options.env) },
8840
+ ...options?.timeoutMs === void 0 ? {} : { timeout: options.timeoutMs }
8841
+ });
8598
8842
  return { status: result.status, stdout: result.stdout, stderr: result.stderr };
8599
8843
  }
8600
8844
  };
@@ -8995,7 +9239,7 @@ var init_candidateText = __esm({
8995
9239
  });
8996
9240
 
8997
9241
  // src/usage/plan.ts
8998
- import { z as z15 } from "zod";
9242
+ import { z as z17 } from "zod";
8999
9243
  function planOf(account) {
9000
9244
  const userTier = account?.userRateLimitTier;
9001
9245
  if (userTier !== void 0 && ZERO_TIER.test(userTier)) {
@@ -9019,19 +9263,19 @@ var PlanClassSchema, TIER_MULTIPLIER, ZERO_TIER, BASE_TIER;
9019
9263
  var init_plan2 = __esm({
9020
9264
  "src/usage/plan.ts"() {
9021
9265
  "use strict";
9022
- PlanClassSchema = z15.union([
9023
- z15.strictObject({
9024
- kind: z15.literal("subscription"),
9266
+ PlanClassSchema = z17.union([
9267
+ z17.strictObject({
9268
+ kind: z17.literal("subscription"),
9025
9269
  /** The plan's size as a multiple of the smallest subscription tier (Max is 5, Ultra is 20). */
9026
- capacity: z15.number().positive(),
9270
+ capacity: z17.number().positive(),
9027
9271
  /** False when the tier string named no multiplier and no tier this project knows, so `capacity` is the neutral 1 rather than a reading. */
9028
- recognised: z15.boolean(),
9272
+ recognised: z17.boolean(),
9029
9273
  /** The tier string the classification rests on, when the account had one. */
9030
- tier: z15.string().optional()
9274
+ tier: z17.string().optional()
9031
9275
  }),
9032
- z15.strictObject({
9033
- kind: z15.literal("pay-per-use"),
9034
- tier: z15.string().optional()
9276
+ z17.strictObject({
9277
+ kind: z17.literal("pay-per-use"),
9278
+ tier: z17.string().optional()
9035
9279
  })
9036
9280
  ]);
9037
9281
  TIER_MULTIPLIER = /(?:^|_)(\d+)x$/;
@@ -9041,21 +9285,21 @@ var init_plan2 = __esm({
9041
9285
  });
9042
9286
 
9043
9287
  // src/usage/scan.ts
9044
- import { z as z16 } from "zod";
9288
+ import { z as z18 } from "zod";
9045
9289
  var AnthropicUsageSchema, ErrorObjectSchema;
9046
9290
  var init_scan = __esm({
9047
9291
  "src/usage/scan.ts"() {
9048
9292
  "use strict";
9049
- AnthropicUsageSchema = z16.looseObject({
9050
- input_tokens: z16.number().int().nonnegative().nullish(),
9051
- output_tokens: z16.number().int().nonnegative().nullish(),
9052
- cache_creation_input_tokens: z16.number().int().nonnegative().nullish(),
9053
- cache_read_input_tokens: z16.number().int().nonnegative().nullish()
9293
+ AnthropicUsageSchema = z18.looseObject({
9294
+ input_tokens: z18.number().int().nonnegative().nullish(),
9295
+ output_tokens: z18.number().int().nonnegative().nullish(),
9296
+ cache_creation_input_tokens: z18.number().int().nonnegative().nullish(),
9297
+ cache_read_input_tokens: z18.number().int().nonnegative().nullish()
9054
9298
  });
9055
- ErrorObjectSchema = z16.looseObject({
9056
- type: z16.string().optional(),
9057
- code: z16.union([z16.string(), z16.number()]).optional(),
9058
- message: z16.string().optional()
9299
+ ErrorObjectSchema = z18.looseObject({
9300
+ type: z18.string().optional(),
9301
+ code: z18.union([z18.string(), z18.number()]).optional(),
9302
+ message: z18.string().optional()
9059
9303
  });
9060
9304
  }
9061
9305
  });
@@ -9525,7 +9769,7 @@ var init_store2 = __esm({
9525
9769
 
9526
9770
  // src/usage/poolPick.ts
9527
9771
  import path26 from "node:path";
9528
- import { z as z17 } from "zod";
9772
+ import { z as z19 } from "zod";
9529
9773
  function errorMessage(error) {
9530
9774
  return error instanceof Error ? error.message : String(error);
9531
9775
  }
@@ -9727,20 +9971,20 @@ var init_poolPick = __esm({
9727
9971
  }
9728
9972
  };
9729
9973
  SCHEMA_VERSION = 1;
9730
- PickEntrySchema = z17.strictObject({ identity: z17.string().min(1), at: z17.iso.datetime() });
9731
- PicksFileSchema = z17.strictObject({
9732
- schemaVersion: z17.literal(SCHEMA_VERSION),
9733
- picks: z17.record(z17.string().min(1), PickEntrySchema)
9974
+ PickEntrySchema = z19.strictObject({ identity: z19.string().min(1), at: z19.iso.datetime() });
9975
+ PicksFileSchema = z19.strictObject({
9976
+ schemaVersion: z19.literal(SCHEMA_VERSION),
9977
+ picks: z19.record(z19.string().min(1), PickEntrySchema)
9734
9978
  });
9735
9979
  }
9736
9980
  });
9737
9981
 
9738
9982
  // src/identityRenameJournal.ts
9739
- import { createHash as createHash7 } from "node:crypto";
9983
+ import { createHash as createHash9 } from "node:crypto";
9740
9984
  import path27 from "node:path";
9741
- import { z as z18 } from "zod";
9985
+ import { z as z20 } from "zod";
9742
9986
  function renamePairFileName(from, to, suffix) {
9743
- return `${createHash7("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
9987
+ return `${createHash9("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
9744
9988
  }
9745
9989
  function readRenameJournal(fs17, file) {
9746
9990
  const raw = fs17.readFileUtf8(file);
@@ -9816,20 +10060,20 @@ var init_identityRenameJournal = __esm({
9816
10060
  "src/identityRenameJournal.ts"() {
9817
10061
  "use strict";
9818
10062
  init_cliError();
9819
- RenameJournalSchema = z18.strictObject({
9820
- version: z18.literal(1),
9821
- from: z18.string().min(1),
9822
- to: z18.string().min(1),
9823
- startedAt: z18.iso.datetime(),
10063
+ RenameJournalSchema = z20.strictObject({
10064
+ version: z20.literal(1),
10065
+ from: z20.string().min(1),
10066
+ to: z20.string().min(1),
10067
+ startedAt: z20.iso.datetime(),
9824
10068
  /** The process that began the rename, for a person reading the file. Whether it is still running is told by the locks, not by this. */
9825
- pid: z18.number().int().positive(),
9826
- steps: z18.array(
9827
- z18.strictObject({
9828
- description: z18.string().min(1),
10069
+ pid: z20.number().int().positive(),
10070
+ steps: z20.array(
10071
+ z20.strictObject({
10072
+ description: z20.string().min(1),
9829
10073
  /** Whether the step has been applied and marked so. */
9830
- done: z18.boolean(),
10074
+ done: z20.boolean(),
9831
10075
  /** Whether the step was begun: written ahead of the step, before it runs, so a process that dies after the step took effect and before `done` was written still leaves a record that it may have. */
9832
- started: z18.boolean()
10076
+ started: z20.boolean()
9833
10077
  })
9834
10078
  )
9835
10079
  });
@@ -9855,7 +10099,7 @@ var init_identityRenameJournal = __esm({
9855
10099
  // src/identityNameRenameRecord.ts
9856
10100
  import fs7 from "node:fs";
9857
10101
  import path28 from "node:path";
9858
- import { z as z19 } from "zod";
10102
+ import { z as z21 } from "zod";
9859
10103
  function readRecordFiles(paths) {
9860
10104
  if (!fs7.existsSync(paths.identityNameRenamesDir)) {
9861
10105
  return [];
@@ -9950,12 +10194,12 @@ var init_identityNameRenameRecord = __esm({
9950
10194
  init_poolPick();
9951
10195
  init_identityRecords();
9952
10196
  init_identityRenameJournal();
9953
- NameRenameRecordSchema = z19.strictObject({
9954
- version: z19.literal(1),
9955
- id: z19.string().min(1),
9956
- from: z19.string().min(1),
9957
- to: z19.string().min(1),
9958
- startedAt: z19.iso.datetime()
10197
+ NameRenameRecordSchema = z21.strictObject({
10198
+ version: z21.literal(1),
10199
+ id: z21.string().min(1),
10200
+ from: z21.string().min(1),
10201
+ to: z21.string().min(1),
10202
+ startedAt: z21.iso.datetime()
9959
10203
  });
9960
10204
  RECORD_SUFFIX = ".json";
9961
10205
  InterruptedNameRenameError = class extends CliError {
@@ -9970,7 +10214,7 @@ var init_identityNameRenameRecord = __esm({
9970
10214
  // src/launcher/launchRecords.ts
9971
10215
  import path29 from "node:path";
9972
10216
  import { randomUUID as randomUUID4 } from "node:crypto";
9973
- import { z as z20 } from "zod";
10217
+ import { z as z22 } from "zod";
9974
10218
  function recordFile(directory, pid) {
9975
10219
  return path29.join(directory, `${String(pid)}.${randomUUID4()}${RECORD_SUFFIX2}`);
9976
10220
  }
@@ -10017,11 +10261,11 @@ var LaunchRecordSchema, RECORD_SUFFIX2;
10017
10261
  var init_launchRecords = __esm({
10018
10262
  "src/launcher/launchRecords.ts"() {
10019
10263
  "use strict";
10020
- LaunchRecordSchema = z20.strictObject({
10264
+ LaunchRecordSchema = z22.strictObject({
10021
10265
  /** The launcher's process id, which is what tells a launch in progress from a record a crashed launcher left behind. */
10022
- pid: z20.number().int().positive(),
10023
- identity: z20.string().min(1),
10024
- startedAt: z20.iso.datetime()
10266
+ pid: z22.number().int().positive(),
10267
+ identity: z22.string().min(1),
10268
+ startedAt: z22.iso.datetime()
10025
10269
  });
10026
10270
  RECORD_SUFFIX2 = ".json";
10027
10271
  }
@@ -10492,7 +10736,7 @@ var init_package = __esm({
10492
10736
  "package.json"() {
10493
10737
  package_default = {
10494
10738
  name: "claude-use",
10495
- version: "11.90.0",
10739
+ version: "12.0.1",
10496
10740
  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.",
10497
10741
  license: "MIT",
10498
10742
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -10838,7 +11082,7 @@ var init_paths = __esm({
10838
11082
  });
10839
11083
 
10840
11084
  // src/providerAliases.ts
10841
- import { z as z25 } from "zod";
11085
+ import { z as z26 } from "zod";
10842
11086
  function parseAliases(file, raw) {
10843
11087
  const parsed = ProviderAliasesSchema.safeParse(raw);
10844
11088
  if (!parsed.success) {
@@ -10877,7 +11121,7 @@ var init_providerAliases = __esm({
10877
11121
  init_cliError();
10878
11122
  init_load();
10879
11123
  init_store();
10880
- ProviderAliasesSchema = z25.record(z25.string().min(1), z25.string().min(1));
11124
+ ProviderAliasesSchema = z26.record(z26.string().min(1), z26.string().min(1));
10881
11125
  }
10882
11126
  });
10883
11127
 
@@ -11102,14 +11346,14 @@ function requireProviderExists(paths, name) {
11102
11346
  throw new ProviderNotFoundError(name);
11103
11347
  }
11104
11348
  }
11105
- function isRecord8(value) {
11349
+ function isRecord9(value) {
11106
11350
  return typeof value === "object" && value !== null && !Array.isArray(value);
11107
11351
  }
11108
11352
  function legacyProviderConversion(raw) {
11109
- if (!isRecord8(raw) || "credential" in raw) {
11353
+ if (!isRecord9(raw) || "credential" in raw) {
11110
11354
  return void 0;
11111
11355
  }
11112
- const env = isRecord8(raw.env) ? raw.env : void 0;
11356
+ const env = isRecord9(raw.env) ? raw.env : void 0;
11113
11357
  const legacyEnvKeys = env === void 0 ? [] : Object.keys(env).filter((key) => LEGACY_ENV_CREDENTIAL_KEYS.includes(key));
11114
11358
  const fields = [...LEGACY_PROVIDER_FIELDS.filter((field) => field in raw), ...legacyEnvKeys.map((key) => `env.${key}`)];
11115
11359
  if (fields.length === 0) {
@@ -11539,221 +11783,6 @@ var init_claudeVersion = __esm({
11539
11783
  }
11540
11784
  });
11541
11785
 
11542
- // src/headroom/headers.ts
11543
- function mergeAnthropicCustomHeaders(existing, additions) {
11544
- const merged = /* @__PURE__ */ new Map();
11545
- for (const block of existing) {
11546
- if (block === void 0) {
11547
- continue;
11548
- }
11549
- for (const line of block.split("\n")) {
11550
- const entry = parseCustomHeaderLine(line);
11551
- if (entry === void 0) {
11552
- continue;
11553
- }
11554
- merged.set(entry.name, entry.value);
11555
- }
11556
- }
11557
- for (const entry of additions) {
11558
- merged.set(entry.name, entry.value);
11559
- }
11560
- return [...merged].map(([name, value]) => `${name}: ${value}`).join("\n");
11561
- }
11562
- function parseAnthropicCustomHeaders(block) {
11563
- return block.split("\n").flatMap((line) => {
11564
- const entry = parseCustomHeaderLine(line);
11565
- return entry === void 0 ? [] : [entry];
11566
- });
11567
- }
11568
- function withoutAnthropicCustomHeaders(block, remove) {
11569
- const lines = block.split("\n");
11570
- const kept = lines.filter((line) => {
11571
- const entry = parseCustomHeaderLine(line);
11572
- return entry === void 0 || !remove(entry);
11573
- });
11574
- return kept.length === lines.length ? block : kept.join("\n");
11575
- }
11576
- function parseCustomHeaderLine(line) {
11577
- const trimmed = line.trim();
11578
- if (trimmed === "") {
11579
- return void 0;
11580
- }
11581
- const colon = trimmed.indexOf(":");
11582
- if (colon <= 0) {
11583
- return void 0;
11584
- }
11585
- return { name: trimmed.slice(0, colon).trim(), value: trimmed.slice(colon + 1).trim() };
11586
- }
11587
- var init_headers = __esm({
11588
- "src/headroom/headers.ts"() {
11589
- "use strict";
11590
- }
11591
- });
11592
-
11593
- // src/launcher/injected.ts
11594
- import { createHash as createHash8 } from "node:crypto";
11595
- import { z as z26 } from "zod";
11596
- function listKey(list) {
11597
- return `${list},appended`;
11598
- }
11599
- function digest2(value) {
11600
- return createHash8("sha256").update(value).digest("hex");
11601
- }
11602
- function recordedDigests(env) {
11603
- const raw = env[INJECTED_ENV];
11604
- if (raw === void 0 || raw === "") {
11605
- return {};
11606
- }
11607
- let parsed;
11608
- try {
11609
- parsed = JSON.parse(raw);
11610
- } catch {
11611
- return {};
11612
- }
11613
- const result = InjectedSchema.safeParse(parsed);
11614
- return result.success ? result.data : {};
11615
- }
11616
- function recordInjections(base) {
11617
- const env = { ...base };
11618
- const digests = new Map(Object.entries(recordedDigests(env)));
11619
- return {
11620
- env,
11621
- set: (name, value) => {
11622
- env[name] = value;
11623
- digests.set(name, digest2(value));
11624
- },
11625
- unset: (name) => {
11626
- env[name] = void 0;
11627
- digests.delete(name);
11628
- },
11629
- recordHeaders: (names) => {
11630
- const block = env[CUSTOM_HEADERS_ENV];
11631
- for (const entry of block === void 0 ? [] : parseAnthropicCustomHeaders(block)) {
11632
- if (names.includes(entry.name)) {
11633
- digests.set(`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`, digest2(entry.value));
11634
- }
11635
- }
11636
- },
11637
- recordBypassHosts: (list, hosts) => {
11638
- const recordedHosts = [.../* @__PURE__ */ new Set([...digests.get(listKey(list))?.split(",") ?? [], ...hosts.map((host) => host.trim().toLowerCase()).filter((host) => host !== "")])];
11639
- if (recordedHosts.length > 0) {
11640
- digests.set(listKey(list), recordedHosts.join(","));
11641
- }
11642
- },
11643
- finish: () => {
11644
- if (digests.size > 0) {
11645
- env[INJECTED_ENV] = JSON.stringify(Object.fromEntries(digests));
11646
- }
11647
- }
11648
- };
11649
- }
11650
- function withoutRecordedHosts(list, value, digests) {
11651
- const recordedHosts = new Set(digests[listKey(list)]?.split(","));
11652
- const entries = value.split(",");
11653
- const kept = entries.filter((entry) => !recordedHosts.has(entry.trim().toLowerCase()));
11654
- return kept.length === entries.length ? value : kept.join(",");
11655
- }
11656
- function launchEnvironment(env, configDirEscapeHatch) {
11657
- return configDirEscapeHatch ? env : withoutInjected(env);
11658
- }
11659
- function withoutInjected(env) {
11660
- const digests = recordedDigests(env);
11661
- const entries = Object.entries(env).flatMap(([name, value]) => {
11662
- if (name === INJECTED_ENV) {
11663
- return [];
11664
- }
11665
- if (value === void 0) {
11666
- return [[name, value]];
11667
- }
11668
- if (name === CUSTOM_HEADERS_ENV) {
11669
- const remaining = withoutAnthropicCustomHeaders(value, (entry) => digests[`${HEADER_KEY_PREFIX}${entry.name.toLowerCase()}`] === digest2(entry.value));
11670
- return remaining !== value && remaining.trim() === "" ? [] : [[name, remaining]];
11671
- }
11672
- if (name === "NO_PROXY" || name === "no_proxy") {
11673
- const remaining = withoutRecordedHosts(name, value, digests);
11674
- return remaining !== value && remaining.split(",").every((entry) => entry.trim() === "") ? [] : [[name, remaining]];
11675
- }
11676
- return digests[name] === digest2(value) ? [] : [[name, value]];
11677
- });
11678
- return Object.fromEntries(entries);
11679
- }
11680
- var INJECTED_ENV, CUSTOM_HEADERS_ENV, HEADER_KEY_PREFIX, InjectedSchema;
11681
- var init_injected = __esm({
11682
- "src/launcher/injected.ts"() {
11683
- "use strict";
11684
- init_headers();
11685
- INJECTED_ENV = "AGENT_SHIM_INJECTED";
11686
- CUSTOM_HEADERS_ENV = "ANTHROPIC_CUSTOM_HEADERS";
11687
- HEADER_KEY_PREFIX = `${CUSTOM_HEADERS_ENV}:`;
11688
- InjectedSchema = z26.record(z26.string(), z26.string());
11689
- }
11690
- });
11691
-
11692
- // src/launcher/guard.ts
11693
- function detectAmbientCredential(env, injected) {
11694
- for (const variable of AMBIENT_CREDENTIAL_VARS) {
11695
- const value = env[variable];
11696
- if (value === void 0 || value === "") {
11697
- continue;
11698
- }
11699
- if (injected?.variable === variable && value === injected.token) {
11700
- continue;
11701
- }
11702
- return { variable };
11703
- }
11704
- return void 0;
11705
- }
11706
- function formatAmbientCredentialGuardMessage(variable, identityName) {
11707
- const identitySetCommand = identityName === void 0 ? "agent-shim identity set <name> --allow-ambient-credential" : `agent-shim identity set ${identityName} --allow-ambient-credential`;
11708
- return [
11709
- `error: ${variable} is set in the environment. This identity's isolated`,
11710
- "credential would be bypassed \u2014 every identity authenticates as this same key",
11711
- "while it's set. Unset it, or if this is deliberate, opt in per-launch with",
11712
- "AGENT_SHIM_ALLOW_AMBIENT_CREDENTIAL=1, or persistently for this identity with",
11713
- `\`${identitySetCommand}\`.`
11714
- ].join("\n");
11715
- }
11716
- function evaluateAmbientCredentialGuard(params) {
11717
- const detected = detectAmbientCredential(params.env, params.injectedCredential);
11718
- if (detected === void 0) {
11719
- return { ok: true };
11720
- }
11721
- if (params.allowAmbientCredentialOverride || params.allowAmbientCredential || params.providerSelected === true) {
11722
- return { ok: true };
11723
- }
11724
- return {
11725
- ok: false,
11726
- variable: detected.variable,
11727
- message: formatAmbientCredentialGuardMessage(detected.variable, params.identityName)
11728
- };
11729
- }
11730
- function ambientCredentialFinding(env) {
11731
- const named = detectAmbientCredential(launchEnvironment(env, false));
11732
- if (named !== void 0) {
11733
- return { severity: "warn", message: formatAmbientCredentialGuardMessage(named.variable) };
11734
- }
11735
- const bare = env.CLAUDE_CONFIG_DIR === void 0 || env.CLAUDE_CONFIG_DIR === "" ? void 0 : detectAmbientCredential(env);
11736
- if (bare !== void 0) {
11737
- return { severity: "warn", message: `${bare.variable} was set in this session by the launcher that started it. A launch that names an identity drops it, but a launch naming none keeps the session's CLAUDE_CONFIG_DIR and environment and is refused. Name an identity, as in \`claude @<name>\`.` };
11738
- }
11739
- return { severity: "pass", message: "No ambient-credential environment variable is set." };
11740
- }
11741
- var AMBIENT_CREDENTIAL_VARS;
11742
- var init_guard = __esm({
11743
- "src/launcher/guard.ts"() {
11744
- "use strict";
11745
- init_injected();
11746
- AMBIENT_CREDENTIAL_VARS = [
11747
- "ANTHROPIC_API_KEY",
11748
- "ANTHROPIC_AUTH_TOKEN",
11749
- "CLAUDE_CODE_OAUTH_TOKEN",
11750
- "CLAUDE_CODE_USE_BEDROCK",
11751
- "CLAUDE_CODE_USE_VERTEX",
11752
- "CLAUDE_CODE_USE_FOUNDRY"
11753
- ];
11754
- }
11755
- });
11756
-
11757
11786
  // src/usage/resets.ts
11758
11787
  function formatPeriod(window) {
11759
11788
  if (window.periodMs === void 0) {
@@ -12029,7 +12058,7 @@ var init_modelsStore = __esm({
12029
12058
  });
12030
12059
 
12031
12060
  // src/codex/catalogueCredential.ts
12032
- import { createHash as createHash9 } from "node:crypto";
12061
+ import { createHash as createHash10 } from "node:crypto";
12033
12062
  import path41 from "node:path";
12034
12063
  import { z as z35 } from "zod";
12035
12064
  function parseCatalogueBinding(raw) {
@@ -12042,7 +12071,7 @@ function parseCatalogueBinding(raw) {
12042
12071
  }
12043
12072
  }
12044
12073
  function catalogueCredentialFingerprint(cli, token, accountId) {
12045
- return createHash9("sha256").update(JSON.stringify([cli, token, accountId])).digest("hex");
12074
+ return createHash10("sha256").update(JSON.stringify([cli, token, accountId])).digest("hex");
12046
12075
  }
12047
12076
  function cliCatalogueFingerprint(raw) {
12048
12077
  if (raw === void 0) return void 0;
@@ -13534,7 +13563,7 @@ function withLauncherSettings(passthrough, settings) {
13534
13563
  }
13535
13564
  return [...kept, "--settings", settings, ...tail];
13536
13565
  }
13537
- function isRecord16(value) {
13566
+ function isRecord17(value) {
13538
13567
  return typeof value === "object" && value !== null && !Array.isArray(value);
13539
13568
  }
13540
13569
  function mergeSettings(parts) {
@@ -13545,7 +13574,7 @@ function mergeSettings(parts) {
13545
13574
  continue;
13546
13575
  }
13547
13576
  const parsed = JSON.parse(part);
13548
- if (!isRecord16(parsed)) {
13577
+ if (!isRecord17(parsed)) {
13549
13578
  throw new Error("a launch's settings part is not a JSON object");
13550
13579
  }
13551
13580
  for (const [key, value] of Object.entries(parsed)) {
@@ -14304,10 +14333,22 @@ function decideLaunch(params, readOnly, onRecorded) {
14304
14333
  ...parsedArgv.delay === void 0 ? {} : { delay: parsedArgv.delay }
14305
14334
  }
14306
14335
  });
14307
- const loginlessProvider = requestedFlags.remoteControl && selectedProvider !== void 0 && farmIdentity !== void 0 && identityDecision.name !== void 0 && params.hasStoredLogin?.(farmIdentity) === false ? { identity: identityDecision.name, provider: selectedProvider.name } : void 0;
14336
+ const loginlessProvider = (() => {
14337
+ if (!requestedFlags.remoteControl || selectedProvider === void 0 || farmIdentity === void 0 || identityDecision.name === void 0) {
14338
+ return void 0;
14339
+ }
14340
+ const stored = params.hasStoredLogin?.(farmIdentity);
14341
+ if (stored === false) {
14342
+ return { identity: identityDecision.name, provider: selectedProvider.name, why: "has no stored login" };
14343
+ }
14344
+ if (stored === true && params.hasUsableLogin?.(farmIdentity, discovered.path) === false) {
14345
+ return { identity: identityDecision.name, provider: selectedProvider.name, why: "has a stored login that is no longer usable" };
14346
+ }
14347
+ return void 0;
14348
+ })();
14308
14349
  const notes = [];
14309
14350
  if (loginlessProvider !== void 0) {
14310
- notes.push(`${loginlessProvider.identity} has no stored login, so Remote Control is off; provider ${loginlessProvider.provider} runs without it`);
14351
+ notes.push(`${loginlessProvider.identity} ${loginlessProvider.why}, so Remote Control is off; provider ${loginlessProvider.provider} runs without it`);
14311
14352
  }
14312
14353
  const flags = loginlessProvider === void 0 ? requestedFlags : { ...requestedFlags, remoteControl: false };
14313
14354
  const globalModels = loadConfigFile(paths.globalConfigFile, GlobalConfigSchema, params.fs.readConfigFile)?.config.models;
@@ -14717,7 +14758,7 @@ var init_selfIdentity = __esm({
14717
14758
  });
14718
14759
 
14719
14760
  // src/frontdoor/trust.ts
14720
- import { createHash as createHash10 } from "node:crypto";
14761
+ import { createHash as createHash11 } from "node:crypto";
14721
14762
  import path53 from "node:path";
14722
14763
  function resolveTrustBundle(params) {
14723
14764
  const { caCertFile, bundlesDir, variable, inherited, fs: fs17 } = params;
@@ -14739,7 +14780,7 @@ function resolveTrustBundle(params) {
14739
14780
  }
14740
14781
  const combined = `${inheritedPem.trimEnd()}
14741
14782
  ${caPem}`;
14742
- const bundle = path53.join(bundlesDir, `${createHash10("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
14783
+ const bundle = path53.join(bundlesDir, `${createHash11("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
14743
14784
  if (!fs17.exists(bundle)) {
14744
14785
  fs17.mkdirp(bundlesDir);
14745
14786
  fs17.writeFileAtomic(bundle, combined);
@@ -14939,6 +14980,7 @@ function realPrepareLaunchParams(paths, options) {
14939
14980
  credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
14940
14981
  hold: realHoldPort,
14941
14982
  hasStoredLogin: (identity) => identitySignIn(realFarmFs, { platform: process.platform, run: options.run ?? realRunPort }, { farmRoot: path54.join(paths.identitiesDir, identity), hasCredentialBlock: false, provider: void 0 }).state !== "signed-out",
14983
+ hasUsableLogin: (identity, claudeBin) => storedLoginUsable(options.run ?? realRunPort, claudeBin, path54.join(paths.identitiesDir, identity), options.proc.env),
14942
14984
  ...farm.directoryIdentity === void 0 ? {} : { directoryPinnedIdentity: farm.directoryIdentity },
14943
14985
  ...farm.directoryConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: farm.directoryConfigProfile },
14944
14986
  ...farm.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: farm.globalDefaultConfigProfile },
@@ -15413,6 +15455,9 @@ var HTTP_STATUS = {
15413
15455
  // src/frontdoor/connectEffects.ts
15414
15456
  init_connect();
15415
15457
 
15458
+ // src/frontdoor/rcSessions.ts
15459
+ import { createHash as createHash3 } from "node:crypto";
15460
+
15416
15461
  // src/agents/liveTasks.ts
15417
15462
  import { z as z9 } from "zod";
15418
15463
 
@@ -15671,6 +15716,125 @@ function mergeLiveTasks(tree, live) {
15671
15716
  return { ...tree, agents, remoteSessions, liveOnly };
15672
15717
  }
15673
15718
 
15719
+ // src/frontdoor/rcQuestions.ts
15720
+ var RC_QUESTION_TOOL_NAME = "AskUserQuestion";
15721
+ var RC_QUESTIONS_MAX = 16;
15722
+ var RC_QUESTION_OPTIONS_MAX = 16;
15723
+ var RC_QUESTION_FIELD_MAX_CHARS = 1024;
15724
+ var MULTI_SELECT_SEPARATOR = ", ";
15725
+ function isRecord4(value) {
15726
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15727
+ }
15728
+ function fits(value) {
15729
+ return value === void 0 || value.length <= RC_QUESTION_FIELD_MAX_CHARS;
15730
+ }
15731
+ function optionOf(value) {
15732
+ if (!isRecord4(value) || typeof value.label !== "string" || value.label === "") {
15733
+ return "an option names no label";
15734
+ }
15735
+ const description = typeof value.description === "string" && value.description !== "" ? value.description : void 0;
15736
+ if (!fits(value.label) || !fits(description)) {
15737
+ return `an option is past ${String(RC_QUESTION_FIELD_MAX_CHARS)} characters`;
15738
+ }
15739
+ return description === void 0 ? { label: value.label } : { label: value.label, description };
15740
+ }
15741
+ function questionOf(value) {
15742
+ if (!isRecord4(value) || typeof value.question !== "string" || value.question === "" || !Array.isArray(value.options) || value.options.length === 0) {
15743
+ return "a question has no text or no options";
15744
+ }
15745
+ if (value.options.length > RC_QUESTION_OPTIONS_MAX) {
15746
+ return `a question has more than ${String(RC_QUESTION_OPTIONS_MAX)} options`;
15747
+ }
15748
+ const options = [];
15749
+ for (const candidate of value.options) {
15750
+ const option = optionOf(candidate);
15751
+ if (typeof option === "string") {
15752
+ return option;
15753
+ }
15754
+ if (options.some((existing) => existing.label === option.label)) {
15755
+ return `a question lists the option ${JSON.stringify(option.label)} twice`;
15756
+ }
15757
+ options.push(option);
15758
+ }
15759
+ const header = typeof value.header === "string" && value.header !== "" ? value.header : void 0;
15760
+ if (!fits(value.question) || !fits(header)) {
15761
+ return `a question is past ${String(RC_QUESTION_FIELD_MAX_CHARS)} characters`;
15762
+ }
15763
+ return { question: value.question, ...header === void 0 ? {} : { header }, multiSelect: value.multiSelect === true, options };
15764
+ }
15765
+ function rcQuestionsOfToolRequest(toolName, input) {
15766
+ if (toolName !== RC_QUESTION_TOOL_NAME) {
15767
+ return void 0;
15768
+ }
15769
+ if (!isRecord4(input) || !Array.isArray(input.questions) || input.questions.length === 0) {
15770
+ return { unanswerable: "the request names no questions" };
15771
+ }
15772
+ if (input.questions.length > RC_QUESTIONS_MAX) {
15773
+ return { unanswerable: `the request asks more than ${String(RC_QUESTIONS_MAX)} questions` };
15774
+ }
15775
+ const questions = [];
15776
+ for (const candidate of input.questions) {
15777
+ const question = questionOf(candidate);
15778
+ if (typeof question === "string") {
15779
+ return { unanswerable: question };
15780
+ }
15781
+ if (questions.some((existing) => existing.question === question.question)) {
15782
+ return { unanswerable: `the request asks ${JSON.stringify(question.question)} twice` };
15783
+ }
15784
+ questions.push(question);
15785
+ }
15786
+ return { questions };
15787
+ }
15788
+ function resolveSelection(question, questionNumber, selection) {
15789
+ if (typeof selection === "number") {
15790
+ const option = Number.isInteger(selection) ? question.options[selection - 1] : void 0;
15791
+ return option === void 0 ? { error: `question ${String(questionNumber)} has no option ${String(selection)}: its options are numbered 1 to ${String(question.options.length)}` } : { text: option.label };
15792
+ }
15793
+ if (typeof selection === "object") {
15794
+ const text = selection.text.trim();
15795
+ return text === "" ? { error: `question ${String(questionNumber)}'s free-text answer is empty` } : { text };
15796
+ }
15797
+ const exact = question.options.find((option) => option.label === selection);
15798
+ if (exact !== void 0) {
15799
+ return { text: exact.label };
15800
+ }
15801
+ const folded = question.options.filter((option) => option.label.toLowerCase() === selection.toLowerCase());
15802
+ const [only] = folded;
15803
+ if (only !== void 0 && folded.length === 1) {
15804
+ return { text: only.label };
15805
+ }
15806
+ return { error: `question ${String(questionNumber)} has no option labelled ${JSON.stringify(selection)}: its options are ${question.options.map((option) => JSON.stringify(option.label)).join(", ")}` };
15807
+ }
15808
+ function resolveRcQuestionAnswers(questions, choices) {
15809
+ if (choices.length !== questions.length) {
15810
+ return { error: `the request asks ${String(questions.length)} question(s), so the answer must choose for each of them in order, but it chose for ${String(choices.length)}` };
15811
+ }
15812
+ const answers = {};
15813
+ for (const [index, question] of questions.entries()) {
15814
+ const questionNumber = index + 1;
15815
+ const selections = choices[index] ?? [];
15816
+ if (selections.length === 0) {
15817
+ return { error: `question ${String(questionNumber)} has no selection` };
15818
+ }
15819
+ if (!question.multiSelect && selections.length > 1) {
15820
+ return { error: `question ${String(questionNumber)} takes one option, but ${String(selections.length)} were chosen` };
15821
+ }
15822
+ const texts = [];
15823
+ for (const selection of selections) {
15824
+ const resolved = resolveSelection(question, questionNumber, selection);
15825
+ if ("error" in resolved) {
15826
+ return resolved;
15827
+ }
15828
+ if (texts.includes(resolved.text)) {
15829
+ return { error: `question ${String(questionNumber)} chose ${JSON.stringify(resolved.text)} twice` };
15830
+ }
15831
+ texts.push(resolved.text);
15832
+ }
15833
+ answers[question.question] = texts.join(MULTI_SELECT_SEPARATOR);
15834
+ }
15835
+ return { answers };
15836
+ }
15837
+
15674
15838
  // src/frontdoor/rcSessions.ts
15675
15839
  var RC_SESSIONS_PATH_PREFIX = "/v1/code/sessions";
15676
15840
  function pathnameOf(url) {
@@ -15685,7 +15849,12 @@ var RC_IDLE_EXPIRY_MS = 45e3;
15685
15849
  var RC_CREATE_RESPONSE_CAP_BYTES = 8192;
15686
15850
  var CONFLICT_REASON_HEADER = "x-ccr-conflict-reason";
15687
15851
  var RC_STREAM_WORKER_SOURCE = "worker";
15688
- var RC_PENDING_DEADLINE_MS = 14e3;
15852
+ var HIGH_SURROGATE_FIRST = 55296;
15853
+ var HIGH_SURROGATE_LAST = 56319;
15854
+ var RC_WORKER_IDLE = "idle";
15855
+ var RC_PENDING_PER_SESSION_MAX = 64;
15856
+ var RC_REQUEST_ID_MAX_CHARS = 128;
15857
+ var RC_RETIRED_TOMBSTONES_MAX = 2 * RC_PENDING_PER_SESSION_MAX;
15689
15858
  var RC_REQUEST_PARSE_CAP_BYTES = 262144;
15690
15859
  var RC_PENDING_SUMMARY_EXCERPT_CHARS = 300;
15691
15860
  var SUCCESS_STATUS_MAX_EXCLUSIVE = 300;
@@ -15718,7 +15887,7 @@ function sessionCreateId(body) {
15718
15887
  const id = session.id;
15719
15888
  return typeof id === "string" && id.startsWith(RC_SESSION_ID_PREFIX) ? id : void 0;
15720
15889
  }
15721
- function isRecord4(value) {
15890
+ function isRecord5(value) {
15722
15891
  return typeof value === "object" && value !== null && !Array.isArray(value);
15723
15892
  }
15724
15893
  function parseJsonObject(body) {
@@ -15728,7 +15897,7 @@ function parseJsonObject(body) {
15728
15897
  } catch {
15729
15898
  return void 0;
15730
15899
  }
15731
- return isRecord4(parsed) ? parsed : void 0;
15900
+ return isRecord5(parsed) ? parsed : void 0;
15732
15901
  }
15733
15902
  function nonEmptyString(record, field) {
15734
15903
  const value = record === void 0 ? void 0 : record[field];
@@ -15738,8 +15907,16 @@ function finiteNumber(record, field) {
15738
15907
  const value = record === void 0 ? void 0 : record[field];
15739
15908
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
15740
15909
  }
15741
- function excerpt(text) {
15742
- return text.length <= RC_PENDING_SUMMARY_EXCERPT_CHARS ? text : `${text.slice(0, RC_PENDING_SUMMARY_EXCERPT_CHARS)}...`;
15910
+ function rcExcerpt(text) {
15911
+ if (text.length <= RC_PENDING_SUMMARY_EXCERPT_CHARS) {
15912
+ return text;
15913
+ }
15914
+ const cut = text.slice(0, RC_PENDING_SUMMARY_EXCERPT_CHARS);
15915
+ const last = cut.charCodeAt(cut.length - 1);
15916
+ return `${isHighSurrogate(last) ? cut.slice(0, -1) : cut}...`;
15917
+ }
15918
+ function isHighSurrogate(unit) {
15919
+ return unit >= HIGH_SURROGATE_FIRST && unit <= HIGH_SURROGATE_LAST;
15743
15920
  }
15744
15921
  function payloadEventsOf(body) {
15745
15922
  const parsed = parseJsonObject(body);
@@ -15749,11 +15926,11 @@ function payloadEventsOf(body) {
15749
15926
  }
15750
15927
  const payloads = [];
15751
15928
  for (const event of events) {
15752
- if (!isRecord4(event)) {
15929
+ if (!isRecord5(event)) {
15753
15930
  continue;
15754
15931
  }
15755
15932
  const payload = event.payload;
15756
- if (!isRecord4(payload)) {
15933
+ if (!isRecord5(payload)) {
15757
15934
  continue;
15758
15935
  }
15759
15936
  payloads.push(payload);
@@ -15761,6 +15938,14 @@ function payloadEventsOf(body) {
15761
15938
  return payloads;
15762
15939
  }
15763
15940
  function pendingOfControlRequestPayload(payload) {
15941
+ const parsed = fullPendingOfControlRequestPayload(payload);
15942
+ const isQuestion = parsed !== void 0 && (parsed.questions !== void 0 || parsed.unanswerable !== void 0);
15943
+ if (parsed === void 0 || !isQuestion || Buffer.byteLength(JSON.stringify(payload), "utf8") <= RC_REQUEST_PARSE_CAP_BYTES) {
15944
+ return parsed;
15945
+ }
15946
+ return { ...parsed, questions: void 0, toolInput: void 0, oversized: true, unanswerable: parsed.unanswerable ?? `the request is past the door's parse cap of ${String(RC_REQUEST_PARSE_CAP_BYTES)} bytes` };
15947
+ }
15948
+ function fullPendingOfControlRequestPayload(payload) {
15764
15949
  if (payload.type !== "control_request") {
15765
15950
  return void 0;
15766
15951
  }
@@ -15768,24 +15953,41 @@ function pendingOfControlRequestPayload(payload) {
15768
15953
  if (requestId === void 0) {
15769
15954
  return void 0;
15770
15955
  }
15771
- const request4 = isRecord4(payload.request) ? payload.request : void 0;
15956
+ const request4 = isRecord5(payload.request) ? payload.request : void 0;
15772
15957
  const subtype = nonEmptyString(request4, "subtype");
15773
15958
  const type = subtype ?? "control_request";
15774
15959
  let summary = "";
15960
+ let questions;
15961
+ let unanswerable;
15962
+ let toolInput;
15775
15963
  if (subtype === "can_use_tool") {
15776
- const toolName = nonEmptyString(request4, "tool_name") ?? "unknown tool";
15964
+ const toolName = nonEmptyString(request4, "tool_name");
15777
15965
  const input = request4 === void 0 ? void 0 : request4.input;
15778
- summary = input === void 0 ? toolName : `${toolName} ${excerpt(JSON.stringify(input))}`;
15966
+ summary = input === void 0 ? toolName ?? "unknown tool" : `${toolName ?? "unknown tool"} ${rcExcerpt(JSON.stringify(input))}`;
15967
+ const parsedQuestions = rcQuestionsOfToolRequest(toolName, input);
15968
+ if (parsedQuestions !== void 0 && "questions" in parsedQuestions) {
15969
+ questions = parsedQuestions.questions;
15970
+ toolInput = isRecord5(input) ? input : void 0;
15971
+ } else if (parsedQuestions !== void 0) {
15972
+ unanswerable = parsedQuestions.unanswerable;
15973
+ }
15779
15974
  } else if (request4 !== void 0) {
15780
- summary = excerpt(JSON.stringify(request4));
15975
+ summary = rcExcerpt(JSON.stringify(request4));
15781
15976
  }
15782
- return { requestId, type, summary };
15977
+ return { requestId, type, summary, questions, unanswerable, toolInput, oversized: false };
15978
+ }
15979
+ function withdrawnRequestIdsOfControlCancelPayload(payload) {
15980
+ if (payload.type !== "control_cancel_request") {
15981
+ return [];
15982
+ }
15983
+ const id = nonEmptyString(payload, "request_id");
15984
+ return id === void 0 ? [] : [id];
15783
15985
  }
15784
15986
  function answeredRequestIdsOfControlResponsePayload(payload) {
15785
15987
  if (payload.type !== "control_response") {
15786
15988
  return [];
15787
15989
  }
15788
- const response = isRecord4(payload.response) ? payload.response : void 0;
15990
+ const response = isRecord5(payload.response) ? payload.response : void 0;
15789
15991
  const id = nonEmptyString(response, "request_id") ?? nonEmptyString(payload, "request_id") ?? nonEmptyString(payload, "uuid");
15790
15992
  return id === void 0 ? [] : [id];
15791
15993
  }
@@ -15797,44 +15999,74 @@ function initFactsOfPayload(payload) {
15797
15999
  }
15798
16000
  function parseRcRequestBody(kind, body) {
15799
16001
  if (kind === "heartbeat") {
15800
- return { controlRequests: [], answeredRequestIds: [], idleSeconds: finiteNumber(parseJsonObject(body), "idle_seconds"), workerStatus: void 0, payloads: [] };
16002
+ return { controlRequests: [], answeredRequestIds: [], withdrawnRequestIds: [], idleSeconds: finiteNumber(parseJsonObject(body), "idle_seconds"), workerStatus: void 0, workerEpoch: void 0, payloads: [] };
15801
16003
  }
15802
16004
  if (kind === "worker-registration") {
15803
16005
  const registration = parseJsonObject(body);
15804
- const metadata = registration === void 0 || !isRecord4(registration.external_metadata) ? void 0 : registration.external_metadata;
16006
+ const metadata = registration === void 0 || !isRecord5(registration.external_metadata) ? void 0 : registration.external_metadata;
15805
16007
  const model = nonEmptyString(metadata, "model");
15806
- return { controlRequests: [], answeredRequestIds: [], idleSeconds: void 0, workerStatus: nonEmptyString(registration, "worker_status"), payloads: [], ...model === void 0 ? {} : { model } };
16008
+ return { controlRequests: [], answeredRequestIds: [], withdrawnRequestIds: [], idleSeconds: void 0, workerStatus: nonEmptyString(registration, "worker_status"), workerEpoch: finiteNumber(registration, "worker_epoch"), payloads: [], ...model === void 0 ? {} : { model } };
15807
16009
  }
15808
16010
  const controlRequests = [];
15809
16011
  const answeredRequestIds = [];
16012
+ const withdrawnRequestIds = [];
15810
16013
  const payloads = payloadEventsOf(body);
15811
16014
  for (const payload of payloads) {
15812
16015
  const pending = pendingOfControlRequestPayload(payload);
15813
16016
  if (pending !== void 0) {
15814
- controlRequests.push({ requestId: pending.requestId, type: pending.type, summary: pending.summary });
16017
+ controlRequests.push(pending);
15815
16018
  continue;
15816
16019
  }
15817
16020
  answeredRequestIds.push(...answeredRequestIdsOfControlResponsePayload(payload));
16021
+ if (kind === "worker-events") {
16022
+ withdrawnRequestIds.push(...withdrawnRequestIdsOfControlCancelPayload(payload));
16023
+ }
16024
+ }
16025
+ return { controlRequests, answeredRequestIds, withdrawnRequestIds, idleSeconds: void 0, workerStatus: void 0, workerEpoch: void 0, payloads };
16026
+ }
16027
+ function rememberBounded(record, key) {
16028
+ record.delete(key);
16029
+ record.add(key);
16030
+ if (record.size > RC_RETIRED_TOMBSTONES_MAX) {
16031
+ const [oldest] = record;
16032
+ if (oldest !== void 0) {
16033
+ record.delete(oldest);
16034
+ }
15818
16035
  }
15819
- return { controlRequests, answeredRequestIds, idleSeconds: void 0, workerStatus: void 0, payloads };
16036
+ }
16037
+ function droppedKeyOf(requestId) {
16038
+ return requestId.length <= RC_REQUEST_ID_MAX_CHARS ? requestId : createHash3("sha256").update(requestId).digest("hex");
15820
16039
  }
15821
16040
  function createRcSessionTracker(deps) {
15822
16041
  const entries = /* @__PURE__ */ new Map();
16042
+ let observationSequence = 0;
16043
+ const rememberRetired = (entry, requestId) => {
16044
+ rememberBounded(entry.retired, requestId);
16045
+ };
15823
16046
  const retirePending = (entry, requestId, reason) => {
15824
16047
  if (entry.pending.delete(requestId)) {
15825
- entry.retired.set(requestId, deps.now());
16048
+ rememberRetired(entry, requestId);
15826
16049
  deps.onTransition?.({ kind: "pending-retired", session: entry.id, requestId, reason, at: deps.now() });
15827
16050
  }
15828
16051
  };
15829
- const addPending = (entry, pending) => {
15830
- if (entry.retired.has(pending.requestId)) {
16052
+ const addPending = (entry, request4, now) => {
16053
+ const droppedKey = droppedKeyOf(request4.requestId);
16054
+ if (entry.retired.has(request4.requestId) || entry.dropped.has(droppedKey)) {
16055
+ return;
16056
+ }
16057
+ const already = entry.pending.get(request4.requestId);
16058
+ if (already !== void 0) {
16059
+ entry.pending.set(request4.requestId, { ...already, ...request4, observedAt: already.observedAt });
15831
16060
  return;
15832
16061
  }
15833
- const born = !entry.pending.has(pending.requestId);
15834
- entry.pending.set(pending.requestId, pending);
15835
- if (born) {
15836
- deps.onTransition?.({ kind: "pending-born", session: entry.id, requestId: pending.requestId, type: pending.type, summary: pending.summary, at: pending.observedAt });
16062
+ if (request4.requestId.length > RC_REQUEST_ID_MAX_CHARS || entry.pending.size >= RC_PENDING_PER_SESSION_MAX) {
16063
+ entry.droppedPending += 1;
16064
+ rememberBounded(entry.dropped, droppedKey);
16065
+ return;
15837
16066
  }
16067
+ observationSequence += 1;
16068
+ entry.pending.set(request4.requestId, { sessionId: entry.id, ...request4, observedAt: now, observedSequence: observationSequence });
16069
+ deps.onTransition?.({ kind: "pending-born", session: entry.id, requestId: request4.requestId, type: request4.type, summary: request4.summary, at: now });
15838
16070
  };
15839
16071
  const expire = (id, reason) => {
15840
16072
  const entry = entries.get(id);
@@ -15847,31 +16079,17 @@ function createRcSessionTracker(deps) {
15847
16079
  entries.delete(id);
15848
16080
  deps.onTransition?.({ kind: "session-ended", session: id, reason, at: deps.now() });
15849
16081
  };
15850
- const expirePendings = (entry, now) => {
15851
- for (const [requestId, pending] of entry.pending) {
15852
- if (now - pending.observedAt >= RC_PENDING_DEADLINE_MS) {
15853
- retirePending(entry, requestId, "expired");
15854
- }
15855
- }
15856
- for (const [requestId, retiredAt] of entry.retired) {
15857
- if (now - retiredAt >= RC_PENDING_DEADLINE_MS) {
15858
- entry.retired.delete(requestId);
15859
- }
15860
- }
15861
- };
15862
16082
  const sweep = () => {
15863
16083
  for (const [id, entry] of entries) {
15864
16084
  if (deps.now() - entry.lastSeenAt >= deps.idleMs) {
15865
16085
  expire(id, "expired");
15866
- continue;
15867
16086
  }
15868
- expirePendings(entry, deps.now());
15869
16087
  }
15870
16088
  };
15871
- const timer = setInterval(sweep, Math.min(deps.idleMs, RC_PENDING_DEADLINE_MS));
16089
+ const timer = setInterval(sweep, deps.idleMs);
15872
16090
  timer.unref();
15873
16091
  const birth = (id, facts) => {
15874
- const record = { id, createdAt: deps.now(), lastSeenAt: deps.now(), ...facts, pending: /* @__PURE__ */ new Map(), retired: /* @__PURE__ */ new Map(), workerState: void 0, workerIdleSeconds: void 0, model: void 0, cwd: void 0, sequenceNum: void 0, liveTasks: /* @__PURE__ */ new Map() };
16092
+ const record = { id, createdAt: deps.now(), lastSeenAt: deps.now(), ...facts, pending: /* @__PURE__ */ new Map(), retired: /* @__PURE__ */ new Set(), dropped: /* @__PURE__ */ new Set(), workerState: void 0, workerIdleSeconds: void 0, model: void 0, cwd: void 0, sequenceNum: void 0, liveTasks: /* @__PURE__ */ new Map(), workerEpoch: void 0, droppedPending: 0, answering: /* @__PURE__ */ new Set() };
15875
16093
  entries.set(id, record);
15876
16094
  deps.onTransition?.({ kind: "session-appeared", session: id, at: record.createdAt });
15877
16095
  return record;
@@ -15902,6 +16120,7 @@ function createRcSessionTracker(deps) {
15902
16120
  return void 0;
15903
16121
  }
15904
16122
  const tail = pathnameOf(request4.url).slice(RC_SESSIONS_PATH_PREFIX.length);
16123
+ const startedAtSequence = observationSequence;
15905
16124
  const facts = {
15906
16125
  oauthAuthorization: oauthAuthorizationOf(request4.headers),
15907
16126
  anthropicVersion: singleHeader(request4.headers, "anthropic-version"),
@@ -15975,11 +16194,14 @@ function createRcSessionTracker(deps) {
15975
16194
  }
15976
16195
  const now = deps.now();
15977
16196
  for (const controlRequest of factsOfBody.controlRequests) {
15978
- addPending(entryNow, { sessionId: id, ...controlRequest, observedAt: now });
16197
+ addPending(entryNow, controlRequest, now);
15979
16198
  }
15980
16199
  for (const requestId of factsOfBody.answeredRequestIds) {
15981
16200
  retirePending(entryNow, requestId, "answered");
15982
16201
  }
16202
+ for (const requestId of factsOfBody.withdrawnRequestIds) {
16203
+ retirePending(entryNow, requestId, "withdrawn");
16204
+ }
15983
16205
  for (const payload of factsOfBody.payloads) {
15984
16206
  entryNow.liveTasks = applyAgentTaskEvent(entryNow.liveTasks, id, payload, now);
15985
16207
  noteInit(entryNow, payload);
@@ -15995,6 +16217,17 @@ function createRcSessionTracker(deps) {
15995
16217
  deps.onTransition?.({ kind: "worker-state", session: id, state: factsOfBody.workerStatus, ...previous === void 0 ? {} : { previous }, at: now });
15996
16218
  }
15997
16219
  }
16220
+ const epochChanged = factsOfBody.workerEpoch !== void 0 && entryNow.workerEpoch !== void 0 && factsOfBody.workerEpoch !== entryNow.workerEpoch;
16221
+ if (factsOfBody.workerEpoch !== void 0) {
16222
+ entryNow.workerEpoch = factsOfBody.workerEpoch;
16223
+ }
16224
+ if (epochChanged || factsOfBody.workerStatus === RC_WORKER_IDLE) {
16225
+ for (const [requestId, pending] of entryNow.pending) {
16226
+ if (pending.observedSequence <= startedAtSequence) {
16227
+ retirePending(entryNow, requestId, "worker-stopped");
16228
+ }
16229
+ }
16230
+ }
15998
16231
  };
15999
16232
  const archiving = method === "POST" && rest === `${id}/archive`;
16000
16233
  return {
@@ -16034,7 +16267,7 @@ function createRcSessionTracker(deps) {
16034
16267
  };
16035
16268
  };
16036
16269
  const summaryOf2 = ({ id, createdAt, lastSeenAt }) => ({ id, createdAt, lastSeenAt });
16037
- const pendingSummaryOf = ({ sessionId, requestId, type, summary, observedAt: observedAt2 }) => ({ sessionId, requestId, type, summary, observedAt: observedAt2 });
16270
+ const pendingSummaryOf = ({ sessionId, requestId, type, summary, questions, unanswerable, oversized, observedAt: observedAt2 }) => ({ sessionId, requestId, type, summary, ...questions === void 0 ? {} : { questions }, ...oversized ? { oversized: true } : {}, ...unanswerable === void 0 ? {} : { unanswerable }, observedAt: observedAt2 });
16038
16271
  const sortedEntries = () => [...entries.values()].sort((left, right) => left.createdAt - right.createdAt || (left.id < right.id ? -1 : 1));
16039
16272
  const pendingSorted = (entry) => [...entry.pending.values()].sort((left, right) => left.observedAt - right.observedAt || (left.requestId < right.requestId ? -1 : 1)).map(pendingSummaryOf);
16040
16273
  return {
@@ -16052,7 +16285,8 @@ function createRcSessionTracker(deps) {
16052
16285
  pending: pendingSorted(entry),
16053
16286
  ...entry.identity === void 0 ? {} : { identity: entry.identity },
16054
16287
  ...entry.model === void 0 ? {} : { model: entry.model },
16055
- ...entry.cwd === void 0 ? {} : { cwd: entry.cwd }
16288
+ ...entry.cwd === void 0 ? {} : { cwd: entry.cwd },
16289
+ ...entry.droppedPending === 0 ? {} : { pendingDropped: entry.droppedPending }
16056
16290
  }));
16057
16291
  },
16058
16292
  pendingOf: (sessionId) => {
@@ -16090,7 +16324,7 @@ function createRcSessionTracker(deps) {
16090
16324
  return;
16091
16325
  }
16092
16326
  entry.sequenceNum = entry.sequenceNum === void 0 || event.sequence_num > entry.sequenceNum ? event.sequence_num : entry.sequenceNum;
16093
- if (!isRecord4(event.payload)) {
16327
+ if (!isRecord5(event.payload)) {
16094
16328
  return;
16095
16329
  }
16096
16330
  entry.liveTasks = applyAgentTaskEvent(entry.liveTasks, sessionId, event.payload, deps.now());
@@ -16098,13 +16332,18 @@ function createRcSessionTracker(deps) {
16098
16332
  const pending = pendingOfControlRequestPayload(event.payload);
16099
16333
  if (pending !== void 0) {
16100
16334
  if (event.source === RC_STREAM_WORKER_SOURCE) {
16101
- addPending(entry, { sessionId, ...pending, observedAt: deps.now() });
16335
+ addPending(entry, pending, deps.now());
16102
16336
  }
16103
16337
  return;
16104
16338
  }
16105
16339
  for (const requestId of answeredRequestIdsOfControlResponsePayload(event.payload)) {
16106
16340
  retirePending(entry, requestId, "answered");
16107
16341
  }
16342
+ if (event.source === RC_STREAM_WORKER_SOURCE) {
16343
+ for (const requestId of withdrawnRequestIdsOfControlCancelPayload(event.payload)) {
16344
+ retirePending(entry, requestId, "withdrawn");
16345
+ }
16346
+ }
16108
16347
  },
16109
16348
  liveTasksOf: (sessionId) => {
16110
16349
  sweep();
@@ -16116,6 +16355,17 @@ function createRcSessionTracker(deps) {
16116
16355
  retirePending(entry, requestId, "answered");
16117
16356
  }
16118
16357
  },
16358
+ claimPending: (sessionId, requestId) => {
16359
+ const entry = entries.get(sessionId);
16360
+ if (entry === void 0 || !entry.pending.has(requestId) || entry.answering.has(requestId)) {
16361
+ return void 0;
16362
+ }
16363
+ entry.answering.add(requestId);
16364
+ return () => {
16365
+ entry.answering.delete(requestId);
16366
+ };
16367
+ },
16368
+ pendingToolInputOf: (sessionId, requestId) => entries.get(sessionId)?.pending.get(requestId)?.toolInput,
16119
16369
  close: () => {
16120
16370
  clearInterval(timer);
16121
16371
  deps.onClose?.();
@@ -16282,8 +16532,8 @@ async function injectRcUserMessage(deps, sessionId, text) {
16282
16532
  }
16283
16533
  return result;
16284
16534
  }
16285
- function buildRcControlResponsePayload(requestId, decision) {
16286
- const result = decision.approve ? { behavior: "allow" } : { behavior: "deny", message: decision.message ?? "" };
16535
+ function buildRcControlResponsePayload(requestId, decision, updatedInput) {
16536
+ const result = decision.approve ? { behavior: "allow", ...updatedInput === void 0 ? {} : { updatedInput } } : { behavior: "deny", message: decision.message ?? "" };
16287
16537
  return { type: "control_response", response: { subtype: "success", request_id: requestId, response: result } };
16288
16538
  }
16289
16539
  var RC_PERMISSION_MODES = ["default", "acceptEdits", "bypassPermissions", "plan", "dontAsk", "auto"];
@@ -16340,6 +16590,27 @@ function buildRcMcpOAuthCallbackUrlPayload(requestId, serverName, callbackUrl) {
16340
16590
  function buildRcKeepAlivePayload() {
16341
16591
  return { type: "keep_alive" };
16342
16592
  }
16593
+ function questionAnswerInput(deps, sessionId, pending, decision) {
16594
+ const { questions, unanswerable } = pending;
16595
+ if (questions === void 0 && unanswerable === void 0) {
16596
+ return decision.choices === void 0 ? void 0 : { error: `control request ${pending.requestId} is not a question (it is ${pending.type}${pending.summary === "" ? "" : `: ${pending.summary}`}), so it has no options to choose; approve or deny it instead` };
16597
+ }
16598
+ if (!decision.approve) {
16599
+ return decision.choices === void 0 ? void 0 : { error: "a denial dismisses the question and carries no choices; choose options to answer it, or deny it without them" };
16600
+ }
16601
+ if (questions === void 0) {
16602
+ return { error: `control request ${pending.requestId} is a question the door cannot answer (${String(unanswerable)}), so it cannot write an answer the worker would read correctly; answer it in the session itself, or deny it to dismiss it` };
16603
+ }
16604
+ if (decision.choices === void 0) {
16605
+ return { error: `control request ${pending.requestId} is a question, so answering it means choosing an option for each of its ${String(questions.length)} question(s); deny it to dismiss it` };
16606
+ }
16607
+ const input = deps.pendingToolInputOf(sessionId, pending.requestId);
16608
+ if (input === void 0) {
16609
+ return { error: `the front door holds no input for question ${pending.requestId} on session ${sessionId}, so it cannot write the answer the worker expects` };
16610
+ }
16611
+ const resolved = resolveRcQuestionAnswers(questions, decision.choices);
16612
+ return "error" in resolved ? resolved : { input: { ...input, answers: resolved.answers } };
16613
+ }
16343
16614
  async function answerRcControlRequest(deps, sessionId, requestId, decision) {
16344
16615
  const credential = deps.credentialOf(sessionId);
16345
16616
  if (credential === void 0) {
@@ -16348,15 +16619,26 @@ async function answerRcControlRequest(deps, sessionId, requestId, decision) {
16348
16619
  if (credential.authorization === void 0) {
16349
16620
  return noOAuthCredentialResult(sessionId);
16350
16621
  }
16351
- if (!deps.pendingOf(sessionId).some((pending) => pending.requestId === requestId)) {
16352
- return { ok: false, message: `the front door has not observed control request ${requestId} pending on session ${sessionId}: it was answered already (by this door or by an attached client), it passed its answer deadline (the protocol's permission round-trip bound), or it never passed through this door` };
16622
+ const pending = deps.pendingOf(sessionId).find((candidate) => candidate.requestId === requestId);
16623
+ if (pending === void 0) {
16624
+ 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` };
16625
+ }
16626
+ const updatedInput = questionAnswerInput(deps, sessionId, pending, decision);
16627
+ if (updatedInput !== void 0 && "error" in updatedInput) {
16628
+ return { ok: false, message: updatedInput.error };
16629
+ }
16630
+ const release = deps.claimPending(sessionId, requestId);
16631
+ if (release === void 0) {
16632
+ 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` };
16353
16633
  }
16354
- const body = JSON.stringify(buildRcEventWriteBody(buildRcControlResponsePayload(requestId, decision)));
16634
+ const body = JSON.stringify(buildRcEventWriteBody(buildRcControlResponsePayload(requestId, decision, updatedInput?.input)));
16355
16635
  let answer;
16356
16636
  try {
16357
16637
  answer = await deps.dial.writeEvents(sessionId, rcWriteHeaders(credential), body);
16358
16638
  } catch (error) {
16359
16639
  return { ok: false, message: `the door could not reach the API host to answer on session ${sessionId}: ${error instanceof Error ? error.message : String(error)}` };
16640
+ } finally {
16641
+ release();
16360
16642
  }
16361
16643
  const result = rcEventWriteResultFromAnswer(answer);
16362
16644
  if (result.ok) {
@@ -16486,6 +16768,198 @@ init_legacy();
16486
16768
  // src/frontdoor/rcControl.ts
16487
16769
  import * as https from "node:https";
16488
16770
  init_capability();
16771
+
16772
+ // src/frontdoor/rcSchemas.ts
16773
+ import { z as z10 } from "zod";
16774
+ var RcPermissionModeSchema = z10.enum(RC_PERMISSION_MODES);
16775
+ var RcSessionSummarySchema = z10.strictObject({
16776
+ id: z10.string(),
16777
+ createdAt: z10.number(),
16778
+ lastSeenAt: z10.number()
16779
+ });
16780
+ function workerFactSchema(value) {
16781
+ return z10.strictObject({ value, observedAt: z10.number() });
16782
+ }
16783
+ var RcQuestionOptionSchema = z10.strictObject({
16784
+ label: z10.string(),
16785
+ description: z10.string().optional()
16786
+ });
16787
+ var RcPendingQuestionSchema = z10.strictObject({
16788
+ question: z10.string(),
16789
+ header: z10.string().optional(),
16790
+ multiSelect: z10.boolean(),
16791
+ options: z10.readonly(z10.array(RcQuestionOptionSchema))
16792
+ });
16793
+ var RcPendingRequestSummarySchema = z10.strictObject({
16794
+ sessionId: z10.string(),
16795
+ requestId: z10.string(),
16796
+ type: z10.string(),
16797
+ summary: z10.string(),
16798
+ questions: z10.readonly(z10.array(RcPendingQuestionSchema)).optional(),
16799
+ oversized: z10.literal(true).optional(),
16800
+ unanswerable: z10.string().optional(),
16801
+ observedAt: z10.number()
16802
+ });
16803
+ var RcSessionStatusSchema = z10.strictObject({
16804
+ ...RcSessionSummarySchema.shape,
16805
+ workerState: workerFactSchema(z10.string()).optional(),
16806
+ workerIdleSeconds: workerFactSchema(z10.number()).optional(),
16807
+ pending: z10.readonly(z10.array(RcPendingRequestSummarySchema)),
16808
+ /** The identity the session runs as, when known; absent otherwise. */
16809
+ identity: z10.string().optional(),
16810
+ /** The model the session last stated, when the door saw one. */
16811
+ model: z10.string().optional(),
16812
+ /** The session's name from the Claude Code session registry, when the registry holds it. */
16813
+ name: z10.string().optional(),
16814
+ /** The session process's id from the registry. */
16815
+ pid: z10.number().optional(),
16816
+ /** The session's working directory, from its init event or the registry. */
16817
+ cwd: z10.string().optional(),
16818
+ pendingDropped: z10.int().positive().optional()
16819
+ });
16820
+ var RcStreamEnvelopeSchema = z10.looseObject({
16821
+ /** The envelope's own event id, when the host sent one. */
16822
+ event_id: z10.string().optional(),
16823
+ /** The envelope's event type, the discriminator a consumer switches on (`control_request`, `user`, and kin). */
16824
+ event_type: z10.string(),
16825
+ /** The sequence number the host assigned, the value a resume continues after. */
16826
+ sequence_num: z10.int(),
16827
+ /** Who emitted the event (`worker` for the CLI's half, a client id for a client's). */
16828
+ source: z10.string(),
16829
+ /** The event's payload, carried verbatim: its shape is the payload family's, narrowed by whichever consumer needs it. Optional in the schema's own type because the door forwards the host's envelope as it arrived, asserting only the fields it relies on itself. */
16830
+ payload: z10.unknown().optional(),
16831
+ /** When the host created the event; the protocol's own type for this field is not established here, so it is forwarded rather than asserted. */
16832
+ created_at: z10.unknown().optional()
16833
+ });
16834
+ var RcStreamEventSchema = z10.strictObject({
16835
+ session: z10.string(),
16836
+ envelope: RcStreamEnvelopeSchema
16837
+ });
16838
+ var RcRateLimitWindowSchema = z10.looseObject({
16839
+ /** The fraction of the window used, usually between 0 and 1, above 1 when usage legitimately runs past the window's cap (the CLI's own field description states both). */
16840
+ utilization: z10.number().optional(),
16841
+ /** When the window resets, in unix epoch seconds: the unit is the CLI's own field description, stated in the 2.1.289 bundle's schema. */
16842
+ resetsAt: z10.number().optional()
16843
+ });
16844
+ var RcRateLimitInfoSchema = z10.looseObject({
16845
+ /** The limiting window's own status (`allowed`, `allowed_warning`, `rejected`), asserted only as a string because the vocabulary grows with the CLI. */
16846
+ status: z10.string(),
16847
+ /** When the limiting window resets, in unix epoch seconds. */
16848
+ resetsAt: z10.number().optional(),
16849
+ /** Which window the top-level fields describe (`five_hour`, `seven_day`, and kin), the payload's own name for it. */
16850
+ rateLimitType: z10.string().optional(),
16851
+ /** The fraction of the limiting window used, on the same scale the per-window utilizations carry. */
16852
+ utilization: z10.number().optional(),
16853
+ /** Whether usage beyond the plan (extra usage) is currently covering the overflow, the payload's own flag for it. */
16854
+ isUsingOverage: z10.boolean().optional(),
16855
+ /** The overage's own status, the same vocabulary the limiting window's `status` carries. */
16856
+ overageStatus: z10.string().optional(),
16857
+ /** When the overage window resets, in unix epoch seconds. */
16858
+ overageResetsAt: z10.number().optional(),
16859
+ /** Each subscription window the account's response headers carried: the session (five-hour), weekly (seven-day), and overage-included weekly windows, each present only when the account's responses carry it. */
16860
+ unifiedWindows: z10.looseObject({ five_hour: RcRateLimitWindowSchema.optional(), seven_day: RcRateLimitWindowSchema.optional(), seven_day_overage_included: RcRateLimitWindowSchema.optional() }).optional()
16861
+ });
16862
+ var RcLiveRateLimitSchema = z10.strictObject({
16863
+ session: z10.string(),
16864
+ observedAt: z10.number(),
16865
+ rateLimit: RcRateLimitInfoSchema
16866
+ });
16867
+ var RcSessionQuerySchema = z10.strictObject({
16868
+ session: z10.string().min(1).optional()
16869
+ });
16870
+ var RcSendInputSchema = z10.strictObject({
16871
+ session: z10.string().min(1),
16872
+ text: z10.string().min(1)
16873
+ });
16874
+ var RcQuestionSelectionSchema = z10.union([z10.string().min(1), z10.int().positive(), z10.strictObject({ text: z10.string().refine((text) => text.trim() !== "", { message: "free text must not be blank" }) })]);
16875
+ var RcQuestionChoicesSchema = z10.array(z10.array(RcQuestionSelectionSchema).min(1)).min(1);
16876
+ var RcAnswerInputSchema = z10.strictObject({
16877
+ session: z10.string().min(1),
16878
+ request: z10.string().min(1),
16879
+ approve: z10.boolean(),
16880
+ text: z10.string().optional(),
16881
+ choices: RcQuestionChoicesSchema.optional()
16882
+ }).refine((input) => !input.approve || input.text === void 0 || input.text === "", { message: "an approval carries no text (the protocol's allow result has no message field); text is the denial message" }).refine((input) => input.approve || input.choices === void 0, { message: "choices answer a question, so they come with approve: true; a denial dismisses the question" });
16883
+ var RcInterruptInputSchema = z10.strictObject({
16884
+ session: z10.string().min(1)
16885
+ });
16886
+ var RcSetModelInputSchema = z10.strictObject({
16887
+ session: z10.string().min(1),
16888
+ model: z10.string().min(1)
16889
+ });
16890
+ var RcSetPermissionModeInputSchema = z10.strictObject({
16891
+ session: z10.string().min(1),
16892
+ mode: RcPermissionModeSchema
16893
+ });
16894
+ var RcEndSessionInputSchema = z10.strictObject({
16895
+ session: z10.string().min(1),
16896
+ reason: z10.string().min(1).optional()
16897
+ });
16898
+ var RcGetUsageInputSchema = z10.strictObject({
16899
+ session: z10.string().min(1),
16900
+ skipBehaviors: z10.boolean().optional()
16901
+ });
16902
+ var RcGetContextUsageInputSchema = z10.strictObject({
16903
+ session: z10.string().min(1),
16904
+ detail: z10.enum(RC_CONTEXT_USAGE_DETAILS).optional()
16905
+ });
16906
+ var RcReadFileInputSchema = z10.strictObject({
16907
+ session: z10.string().min(1),
16908
+ path: z10.string().min(1),
16909
+ maxBytes: z10.number().int().positive().optional(),
16910
+ encoding: z10.enum(RC_READ_FILE_ENCODINGS).optional()
16911
+ });
16912
+ var RcFileSuggestionsInputSchema = z10.strictObject({
16913
+ session: z10.string().min(1),
16914
+ query: z10.string()
16915
+ });
16916
+ var RcKeepAliveInputSchema = z10.strictObject({
16917
+ session: z10.string().min(1)
16918
+ });
16919
+ var RcMcpStatusInputSchema = z10.strictObject({
16920
+ session: z10.string().min(1)
16921
+ });
16922
+ var RcMcpReconnectInputSchema = z10.strictObject({
16923
+ session: z10.string().min(1),
16924
+ serverName: z10.string().min(1)
16925
+ });
16926
+ var RcMcpAuthenticateInputSchema = z10.strictObject({
16927
+ session: z10.string().min(1),
16928
+ serverName: z10.string().min(1),
16929
+ redirectUri: z10.string().min(1)
16930
+ });
16931
+ var RcMcpOAuthCallbackUrlInputSchema = z10.strictObject({
16932
+ session: z10.string().min(1),
16933
+ serverName: z10.string().min(1),
16934
+ callbackUrl: z10.string().min(1)
16935
+ });
16936
+ var RcTeleportInputSchema = z10.strictObject({
16937
+ session: z10.string().min(1),
16938
+ marker: z10.string().min(1)
16939
+ });
16940
+ var RcListOutputSchema = z10.strictObject({ sessions: z10.readonly(z10.array(RcSessionSummarySchema)) });
16941
+ var RcStatusOutputSchema = z10.strictObject({ statuses: z10.readonly(z10.array(RcSessionStatusSchema)) });
16942
+ var RcPendingOutputSchema = z10.strictObject({
16943
+ pending: z10.readonly(z10.array(RcPendingRequestSummarySchema)),
16944
+ /** 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. */
16945
+ dropped: z10.readonly(z10.array(z10.strictObject({ sessionId: z10.string(), count: z10.int().positive() }))).optional()
16946
+ });
16947
+ var RcWriteOutputSchema = z10.strictObject({
16948
+ session: z10.string(),
16949
+ sequenceNums: z10.readonly(z10.array(z10.number()))
16950
+ });
16951
+ var RcControlWriteOutputSchema = z10.strictObject({
16952
+ session: z10.string(),
16953
+ request: z10.string(),
16954
+ sequenceNums: z10.readonly(z10.array(z10.number()))
16955
+ });
16956
+ var RcAnswerOutputSchema = z10.strictObject({
16957
+ session: z10.string(),
16958
+ request: z10.string(),
16959
+ sequenceNums: z10.readonly(z10.array(z10.number()))
16960
+ });
16961
+
16962
+ // src/frontdoor/rcControl.ts
16489
16963
  var RC_PERMISSION_MODE_LIST = RC_PERMISSION_MODES.join(", ");
16490
16964
  var CONTROL_PATH_PREFIX = "/__agent-shim/rc";
16491
16965
  var CONTROL_BODY_CAP_BYTES = 10485760;
@@ -16742,11 +17216,20 @@ function createRcControlHandler(deps) {
16742
17216
  return;
16743
17217
  }
16744
17218
  const text = "text" in parsed && typeof parsed.text === "string" ? parsed.text : void 0;
17219
+ const choices = "choices" in parsed ? RcQuestionChoicesSchema.safeParse(parsed.choices) : void 0;
17220
+ if (choices !== void 0 && !choices.success) {
17221
+ answerJson(response, HTTP_STATUS.badRequest, { error: 'choices must be one non-empty list per question of selections, each an option label, a one-based option number or {"text": ...}' });
17222
+ return;
17223
+ }
17224
+ if (choices !== void 0 && !parsed.approve) {
17225
+ answerJson(response, HTTP_STATUS.badRequest, { error: "choices answer a question, so they come with approve: true; a denial dismisses the question" });
17226
+ return;
17227
+ }
16745
17228
  if (parsed.approve && text !== void 0 && text !== "") {
16746
17229
  answerJson(response, HTTP_STATUS.badRequest, { error: "an approval carries no text (the protocol's allow result has no message field); text is the denial message" });
16747
17230
  return;
16748
17231
  }
16749
- const result = await deps.answer(parsed.session, parsed.request, { approve: parsed.approve, message: parsed.approve ? void 0 : text });
17232
+ const result = await deps.answer(parsed.session, parsed.request, { approve: parsed.approve, message: parsed.approve ? void 0 : text, ...choices === void 0 ? {} : { choices: choices.data } });
16750
17233
  if (result.ok) {
16751
17234
  answerJson(response, HTTP_STATUS.ok, { session: parsed.session, request: parsed.request, sequenceNums: result.sequenceNums });
16752
17235
  return;
@@ -16868,6 +17351,9 @@ function isRcSessionStatus(value) {
16868
17351
  if ("workerState" in value && value.workerState !== void 0 && !isRcWorkerFact(value.workerState, (candidate) => typeof candidate === "string")) {
16869
17352
  return false;
16870
17353
  }
17354
+ if ("pendingDropped" in value && value.pendingDropped !== void 0 && typeof value.pendingDropped !== "number") {
17355
+ return false;
17356
+ }
16871
17357
  if ("workerIdleSeconds" in value && value.workerIdleSeconds !== void 0 && !isRcWorkerFact(value.workerIdleSeconds, (candidate) => typeof candidate === "number")) {
16872
17358
  return false;
16873
17359
  }
@@ -16877,13 +17363,7 @@ function isRcSessionStatus(value) {
16877
17363
  return value.pending.every((candidate) => isRcPendingRequestSummary(candidate));
16878
17364
  }
16879
17365
  function isRcPendingRequestSummary(value) {
16880
- if (typeof value !== "object" || value === null) {
16881
- return false;
16882
- }
16883
- if (!("sessionId" in value) || !("requestId" in value) || !("type" in value) || !("summary" in value) || !("observedAt" in value)) {
16884
- return false;
16885
- }
16886
- return typeof value.sessionId === "string" && typeof value.requestId === "string" && typeof value.type === "string" && typeof value.summary === "string" && typeof value.observedAt === "number";
17366
+ return RcPendingRequestSummarySchema.safeParse(value).success;
16887
17367
  }
16888
17368
  function sequenceNumsOfBody(body) {
16889
17369
  let parsed;
@@ -17019,7 +17499,7 @@ function frontDoorRcControl(transport, token) {
17019
17499
  sendPrompt: async (sessionId, text) => await writeOf(`${CONTROL_PATH_PREFIX}/inject`, JSON.stringify({ session: sessionId, text }), (status, message) => `injecting into ${sessionId} failed (HTTP ${String(status)}): ${message}`),
17020
17500
  answerRequest: async (sessionId, requestId, decision) => await writeOf(
17021
17501
  `${CONTROL_PATH_PREFIX}/answer`,
17022
- JSON.stringify({ session: sessionId, request: requestId, approve: decision.approve, ...decision.approve || decision.message === void 0 ? {} : { text: decision.message } }),
17502
+ JSON.stringify({ session: sessionId, request: requestId, approve: decision.approve, ...decision.approve || decision.message === void 0 ? {} : { text: decision.message }, ...decision.choices === void 0 ? {} : { choices: decision.choices } }),
17023
17503
  (status, message) => `answering control request ${requestId} on ${sessionId} failed (HTTP ${String(status)}): ${message}`
17024
17504
  ),
17025
17505
  interruptSession: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/interrupt`, JSON.stringify({ session: sessionId }), (status, message) => `interrupting ${sessionId} failed (HTTP ${String(status)}): ${message}`),
@@ -17537,19 +18017,19 @@ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
17537
18017
  // src/frontdoor/rcSessionRegistry.ts
17538
18018
  init_identityStore();
17539
18019
  import path31 from "node:path";
17540
- import { z as z21 } from "zod";
18020
+ import { z as z23 } from "zod";
17541
18021
  var REGISTRY_BRIDGE_PREFIX = "session_";
17542
18022
  var DOOR_SESSION_PREFIX = "cse_";
17543
18023
  var REGISTRY_DIR = "sessions";
17544
18024
  var ENTRY_SUFFIX = ".json";
17545
18025
  var RC_REGISTRY_ENTRY_MAX_BYTES = 8192;
17546
- var RegistryEntrySchema = z21.looseObject({
17547
- sessionId: z21.string().min(1),
17548
- pid: z21.int().positive(),
17549
- bridgeSessionId: z21.union([z21.string().startsWith(REGISTRY_BRIDGE_PREFIX), z21.string().startsWith(DOOR_SESSION_PREFIX)]),
17550
- cwd: z21.string().optional(),
17551
- name: z21.string().optional(),
17552
- updatedAt: z21.number().optional()
18026
+ var RegistryEntrySchema = z23.looseObject({
18027
+ sessionId: z23.string().min(1),
18028
+ pid: z23.int().positive(),
18029
+ bridgeSessionId: z23.union([z23.string().startsWith(REGISTRY_BRIDGE_PREFIX), z23.string().startsWith(DOOR_SESSION_PREFIX)]),
18030
+ cwd: z23.string().optional(),
18031
+ name: z23.string().optional(),
18032
+ updatedAt: z23.number().optional()
17553
18033
  });
17554
18034
  function supersedes(candidate, kept) {
17555
18035
  return candidate.updatedAt > kept.updatedAt || candidate.updatedAt === kept.updatedAt && candidate.session.pid > kept.session.pid;
@@ -17663,11 +18143,11 @@ import path32 from "node:path";
17663
18143
  function isSafeSessionId(sessionId) {
17664
18144
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
17665
18145
  }
17666
- function isRecord6(value) {
18146
+ function isRecord7(value) {
17667
18147
  return typeof value === "object" && value !== null && !Array.isArray(value);
17668
18148
  }
17669
18149
  function credentialOfJson(parsed) {
17670
- if (!isRecord6(parsed)) {
18150
+ if (!isRecord7(parsed)) {
17671
18151
  return void 0;
17672
18152
  }
17673
18153
  const { authorization, anthropicVersion, anthropicClientPlatform } = parsed;
@@ -17697,7 +18177,7 @@ function createRcCredentialStore(fs17, dir) {
17697
18177
  } catch {
17698
18178
  return void 0;
17699
18179
  }
17700
- return isRecord6(parsed) ? parsed : void 0;
18180
+ return isRecord7(parsed) ? parsed : void 0;
17701
18181
  };
17702
18182
  return {
17703
18183
  read: (sessionId) => {
@@ -17755,177 +18235,8 @@ var COMPACT_TIMEOUT_MS = 9e5;
17755
18235
  // src/frontdoor/rcApi.ts
17756
18236
  init_capability();
17757
18237
 
17758
- // src/frontdoor/rcSchemas.ts
17759
- import { z as z22 } from "zod";
17760
- var RcPermissionModeSchema = z22.enum(RC_PERMISSION_MODES);
17761
- var RcSessionSummarySchema = z22.strictObject({
17762
- id: z22.string(),
17763
- createdAt: z22.number(),
17764
- lastSeenAt: z22.number()
17765
- });
17766
- function workerFactSchema(value) {
17767
- return z22.strictObject({ value, observedAt: z22.number() });
17768
- }
17769
- var RcPendingRequestSummarySchema = z22.strictObject({
17770
- sessionId: z22.string(),
17771
- requestId: z22.string(),
17772
- type: z22.string(),
17773
- summary: z22.string(),
17774
- observedAt: z22.number()
17775
- });
17776
- var RcSessionStatusSchema = z22.strictObject({
17777
- ...RcSessionSummarySchema.shape,
17778
- workerState: workerFactSchema(z22.string()).optional(),
17779
- workerIdleSeconds: workerFactSchema(z22.number()).optional(),
17780
- pending: z22.readonly(z22.array(RcPendingRequestSummarySchema)),
17781
- /** The identity the session runs as, when known; absent otherwise. */
17782
- identity: z22.string().optional(),
17783
- /** The model the session last stated, when the door saw one. */
17784
- model: z22.string().optional(),
17785
- /** The session's name from the Claude Code session registry, when the registry holds it. */
17786
- name: z22.string().optional(),
17787
- /** The session process's id from the registry. */
17788
- pid: z22.number().optional(),
17789
- /** The session's working directory, from its init event or the registry. */
17790
- cwd: z22.string().optional()
17791
- });
17792
- var RcStreamEnvelopeSchema = z22.looseObject({
17793
- /** The envelope's own event id, when the host sent one. */
17794
- event_id: z22.string().optional(),
17795
- /** The envelope's event type, the discriminator a consumer switches on (`control_request`, `user`, and kin). */
17796
- event_type: z22.string(),
17797
- /** The sequence number the host assigned, the value a resume continues after. */
17798
- sequence_num: z22.int(),
17799
- /** Who emitted the event (`worker` for the CLI's half, a client id for a client's). */
17800
- source: z22.string(),
17801
- /** The event's payload, carried verbatim: its shape is the payload family's, narrowed by whichever consumer needs it. Optional in the schema's own type because the door forwards the host's envelope as it arrived, asserting only the fields it relies on itself. */
17802
- payload: z22.unknown().optional(),
17803
- /** When the host created the event; the protocol's own type for this field is not established here, so it is forwarded rather than asserted. */
17804
- created_at: z22.unknown().optional()
17805
- });
17806
- var RcStreamEventSchema = z22.strictObject({
17807
- session: z22.string(),
17808
- envelope: RcStreamEnvelopeSchema
17809
- });
17810
- var RcRateLimitWindowSchema = z22.looseObject({
17811
- /** The fraction of the window used, usually between 0 and 1, above 1 when usage legitimately runs past the window's cap (the CLI's own field description states both). */
17812
- utilization: z22.number().optional(),
17813
- /** When the window resets, in unix epoch seconds: the unit is the CLI's own field description, stated in the 2.1.289 bundle's schema. */
17814
- resetsAt: z22.number().optional()
17815
- });
17816
- var RcRateLimitInfoSchema = z22.looseObject({
17817
- /** The limiting window's own status (`allowed`, `allowed_warning`, `rejected`), asserted only as a string because the vocabulary grows with the CLI. */
17818
- status: z22.string(),
17819
- /** When the limiting window resets, in unix epoch seconds. */
17820
- resetsAt: z22.number().optional(),
17821
- /** Which window the top-level fields describe (`five_hour`, `seven_day`, and kin), the payload's own name for it. */
17822
- rateLimitType: z22.string().optional(),
17823
- /** The fraction of the limiting window used, on the same scale the per-window utilizations carry. */
17824
- utilization: z22.number().optional(),
17825
- /** Whether usage beyond the plan (extra usage) is currently covering the overflow, the payload's own flag for it. */
17826
- isUsingOverage: z22.boolean().optional(),
17827
- /** The overage's own status, the same vocabulary the limiting window's `status` carries. */
17828
- overageStatus: z22.string().optional(),
17829
- /** When the overage window resets, in unix epoch seconds. */
17830
- overageResetsAt: z22.number().optional(),
17831
- /** Each subscription window the account's response headers carried: the session (five-hour), weekly (seven-day), and overage-included weekly windows, each present only when the account's responses carry it. */
17832
- unifiedWindows: z22.looseObject({ five_hour: RcRateLimitWindowSchema.optional(), seven_day: RcRateLimitWindowSchema.optional(), seven_day_overage_included: RcRateLimitWindowSchema.optional() }).optional()
17833
- });
17834
- var RcLiveRateLimitSchema = z22.strictObject({
17835
- session: z22.string(),
17836
- observedAt: z22.number(),
17837
- rateLimit: RcRateLimitInfoSchema
17838
- });
17839
- var RcSessionQuerySchema = z22.strictObject({
17840
- session: z22.string().min(1).optional()
17841
- });
17842
- var RcSendInputSchema = z22.strictObject({
17843
- session: z22.string().min(1),
17844
- text: z22.string().min(1)
17845
- });
17846
- var RcAnswerInputSchema = z22.strictObject({
17847
- session: z22.string().min(1),
17848
- request: z22.string().min(1),
17849
- approve: z22.boolean(),
17850
- text: z22.string().optional()
17851
- }).refine((input) => !input.approve || input.text === void 0 || input.text === "", { message: "an approval carries no text (the protocol's allow result has no message field); text is the denial message" });
17852
- var RcInterruptInputSchema = z22.strictObject({
17853
- session: z22.string().min(1)
17854
- });
17855
- var RcSetModelInputSchema = z22.strictObject({
17856
- session: z22.string().min(1),
17857
- model: z22.string().min(1)
17858
- });
17859
- var RcSetPermissionModeInputSchema = z22.strictObject({
17860
- session: z22.string().min(1),
17861
- mode: RcPermissionModeSchema
17862
- });
17863
- var RcEndSessionInputSchema = z22.strictObject({
17864
- session: z22.string().min(1),
17865
- reason: z22.string().min(1).optional()
17866
- });
17867
- var RcGetUsageInputSchema = z22.strictObject({
17868
- session: z22.string().min(1),
17869
- skipBehaviors: z22.boolean().optional()
17870
- });
17871
- var RcGetContextUsageInputSchema = z22.strictObject({
17872
- session: z22.string().min(1),
17873
- detail: z22.enum(RC_CONTEXT_USAGE_DETAILS).optional()
17874
- });
17875
- var RcReadFileInputSchema = z22.strictObject({
17876
- session: z22.string().min(1),
17877
- path: z22.string().min(1),
17878
- maxBytes: z22.number().int().positive().optional(),
17879
- encoding: z22.enum(RC_READ_FILE_ENCODINGS).optional()
17880
- });
17881
- var RcFileSuggestionsInputSchema = z22.strictObject({
17882
- session: z22.string().min(1),
17883
- query: z22.string()
17884
- });
17885
- var RcKeepAliveInputSchema = z22.strictObject({
17886
- session: z22.string().min(1)
17887
- });
17888
- var RcMcpStatusInputSchema = z22.strictObject({
17889
- session: z22.string().min(1)
17890
- });
17891
- var RcMcpReconnectInputSchema = z22.strictObject({
17892
- session: z22.string().min(1),
17893
- serverName: z22.string().min(1)
17894
- });
17895
- var RcMcpAuthenticateInputSchema = z22.strictObject({
17896
- session: z22.string().min(1),
17897
- serverName: z22.string().min(1),
17898
- redirectUri: z22.string().min(1)
17899
- });
17900
- var RcMcpOAuthCallbackUrlInputSchema = z22.strictObject({
17901
- session: z22.string().min(1),
17902
- serverName: z22.string().min(1),
17903
- callbackUrl: z22.string().min(1)
17904
- });
17905
- var RcTeleportInputSchema = z22.strictObject({
17906
- session: z22.string().min(1),
17907
- marker: z22.string().min(1)
17908
- });
17909
- var RcListOutputSchema = z22.strictObject({ sessions: z22.readonly(z22.array(RcSessionSummarySchema)) });
17910
- var RcStatusOutputSchema = z22.strictObject({ statuses: z22.readonly(z22.array(RcSessionStatusSchema)) });
17911
- var RcPendingOutputSchema = z22.strictObject({ pending: z22.readonly(z22.array(RcPendingRequestSummarySchema)) });
17912
- var RcWriteOutputSchema = z22.strictObject({
17913
- session: z22.string(),
17914
- sequenceNums: z22.readonly(z22.array(z22.number()))
17915
- });
17916
- var RcControlWriteOutputSchema = z22.strictObject({
17917
- session: z22.string(),
17918
- request: z22.string(),
17919
- sequenceNums: z22.readonly(z22.array(z22.number()))
17920
- });
17921
- var RcAnswerOutputSchema = z22.strictObject({
17922
- session: z22.string(),
17923
- request: z22.string(),
17924
- sequenceNums: z22.readonly(z22.array(z22.number()))
17925
- });
17926
-
17927
18238
  // src/frontdoor/rcSlashCommandSchemas.ts
17928
- import { z as z23 } from "zod";
18239
+ import { z as z24 } from "zod";
17929
18240
 
17930
18241
  // src/frontdoor/rcSessionCommands.ts
17931
18242
  import { setTimeout as sleep } from "node:timers/promises";
@@ -17961,26 +18272,26 @@ async function writeRcPersonMessage(deps, sessionId, text) {
17961
18272
  }
17962
18273
  return result;
17963
18274
  }
17964
- function isRecord7(value) {
18275
+ function isRecord8(value) {
17965
18276
  return typeof value === "object" && value !== null && !Array.isArray(value);
17966
18277
  }
17967
18278
  function rcLocalCommandAnswerOf(event, command, args) {
17968
18279
  const payload = event.envelope.payload;
17969
- if (!isRecord7(payload) || payload.type !== "assistant" || !isRecord7(payload.local_command_run) || payload.local_command_run.command !== command || payload.local_command_run.args !== args) {
18280
+ if (!isRecord8(payload) || payload.type !== "assistant" || !isRecord8(payload.local_command_run) || payload.local_command_run.command !== command || payload.local_command_run.args !== args) {
17970
18281
  return void 0;
17971
18282
  }
17972
18283
  const message = payload.message;
17973
- if (!isRecord7(message) || !Array.isArray(message.content)) {
18284
+ if (!isRecord8(message) || !Array.isArray(message.content)) {
17974
18285
  return void 0;
17975
18286
  }
17976
18287
  const blocks = message.content;
17977
- const text = blocks.flatMap((block) => isRecord7(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
17978
- const outcome = isRecord7(payload.local_command_outcome) && typeof payload.local_command_outcome.kind === "string" ? payload.local_command_outcome.kind : void 0;
18288
+ const text = blocks.flatMap((block) => isRecord8(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
18289
+ const outcome = isRecord8(payload.local_command_outcome) && typeof payload.local_command_outcome.kind === "string" ? payload.local_command_outcome.kind : void 0;
17979
18290
  return { text, outcome };
17980
18291
  }
17981
18292
  function rcManualCompactBoundaryOf(event) {
17982
18293
  const payload = event.envelope.payload;
17983
- if (!isRecord7(payload) || payload.type !== "system" || payload.subtype !== "compact_boundary" || !isRecord7(payload.compact_metadata)) {
18294
+ if (!isRecord8(payload) || payload.type !== "system" || payload.subtype !== "compact_boundary" || !isRecord8(payload.compact_metadata)) {
17984
18295
  return void 0;
17985
18296
  }
17986
18297
  const metadata = payload.compact_metadata;
@@ -17991,7 +18302,7 @@ function rcManualCompactBoundaryOf(event) {
17991
18302
  }
17992
18303
  function isPeerDelivery(event, text) {
17993
18304
  const payload = event.envelope.payload;
17994
- if (!isRecord7(payload) || payload.type !== "user" || !isRecord7(payload.origin) || payload.origin.kind !== "peer" || !isRecord7(payload.message)) {
18305
+ if (!isRecord8(payload) || payload.type !== "user" || !isRecord8(payload.origin) || payload.origin.kind !== "peer" || !isRecord8(payload.message)) {
17995
18306
  return false;
17996
18307
  }
17997
18308
  return typeof payload.message.content === "string" && payload.message.content.includes(text);
@@ -18108,7 +18419,7 @@ function createRcClaudeCodeVersions(fanout) {
18108
18419
  const versions = /* @__PURE__ */ new Map();
18109
18420
  fanout.subscribe(void 0, (event) => {
18110
18421
  const payload = event.envelope.payload;
18111
- if (event.envelope.source === "worker" && isRecord7(payload) && payload.type === "system" && payload.subtype === "init" && typeof payload.claude_code_version === "string") {
18422
+ if (event.envelope.source === "worker" && isRecord8(payload) && payload.type === "system" && payload.subtype === "init" && typeof payload.claude_code_version === "string") {
18112
18423
  versions.set(event.session, payload.claude_code_version);
18113
18424
  }
18114
18425
  });
@@ -18313,47 +18624,47 @@ function createRcSessionCommands(deps) {
18313
18624
  }
18314
18625
 
18315
18626
  // src/frontdoor/rcSlashCommandSchemas.ts
18316
- var WaitMsSchema = z23.int().positive().max(RC_SESSION_COMMAND_MAX_WAIT_MS).optional();
18317
- var RcGoalSessionInputSchema = z23.strictObject({
18318
- session: z23.string().min(1),
18627
+ var WaitMsSchema = z24.int().positive().max(RC_SESSION_COMMAND_MAX_WAIT_MS).optional();
18628
+ var RcGoalSessionInputSchema = z24.strictObject({
18629
+ session: z24.string().min(1),
18319
18630
  waitMs: WaitMsSchema
18320
18631
  });
18321
- var RcGoalSetInputSchema = z23.strictObject({
18322
- session: z23.string().min(1),
18323
- condition: z23.string().trim().min(1).max(RC_GOAL_CONDITION_MAX_CHARS).regex(/^[^\r\n]*$/u, "a goal condition is one line"),
18632
+ var RcGoalSetInputSchema = z24.strictObject({
18633
+ session: z24.string().min(1),
18634
+ condition: z24.string().trim().min(1).max(RC_GOAL_CONDITION_MAX_CHARS).regex(/^[^\r\n]*$/u, "a goal condition is one line"),
18324
18635
  waitMs: WaitMsSchema
18325
18636
  });
18326
- var RcCompactInputSchema = z23.strictObject({
18327
- session: z23.string().min(1),
18637
+ var RcCompactInputSchema = z24.strictObject({
18638
+ session: z24.string().min(1),
18328
18639
  waitMs: WaitMsSchema
18329
18640
  });
18330
- var RcCompactWithInstructionsInputSchema = z23.strictObject({
18331
- session: z23.string().min(1),
18332
- instructions: z23.string().trim().min(1).max(RC_COMPACT_INSTRUCTIONS_MAX_CHARS),
18641
+ var RcCompactWithInstructionsInputSchema = z24.strictObject({
18642
+ session: z24.string().min(1),
18643
+ instructions: z24.string().trim().min(1).max(RC_COMPACT_INSTRUCTIONS_MAX_CHARS),
18333
18644
  waitMs: WaitMsSchema
18334
18645
  });
18335
18646
  var commandAnswerShape = {
18336
- session: z23.string(),
18337
- route: z23.enum(["supervised", "self-hosted"])
18647
+ session: z24.string(),
18648
+ route: z24.enum(["supervised", "self-hosted"])
18338
18649
  };
18339
- var RcGoalGetOutputSchema = z23.strictObject({
18650
+ var RcGoalGetOutputSchema = z24.strictObject({
18340
18651
  ...commandAnswerShape,
18341
- goal: z23.strictObject({ condition: z23.string(), iterations: z23.int().nonnegative(), lastCheck: z23.string().optional() }).nullable()
18652
+ goal: z24.strictObject({ condition: z24.string(), iterations: z24.int().nonnegative(), lastCheck: z24.string().optional() }).nullable()
18342
18653
  });
18343
- var RcGoalSetOutputSchema = z23.strictObject({
18654
+ var RcGoalSetOutputSchema = z24.strictObject({
18344
18655
  ...commandAnswerShape,
18345
- condition: z23.string(),
18346
- superseded: z23.string().nullable()
18656
+ condition: z24.string(),
18657
+ superseded: z24.string().nullable()
18347
18658
  });
18348
- var RcGoalClearOutputSchema = z23.strictObject({
18659
+ var RcGoalClearOutputSchema = z24.strictObject({
18349
18660
  ...commandAnswerShape,
18350
- cleared: z23.string().nullable()
18661
+ cleared: z24.string().nullable()
18351
18662
  });
18352
- var RcCompactOutputSchema = z23.strictObject({
18663
+ var RcCompactOutputSchema = z24.strictObject({
18353
18664
  ...commandAnswerShape,
18354
- trigger: z23.string(),
18355
- preTokens: z23.number().optional(),
18356
- postTokens: z23.number().optional()
18665
+ trigger: z24.string(),
18666
+ preTokens: z24.number().optional(),
18667
+ postTokens: z24.number().optional()
18357
18668
  });
18358
18669
 
18359
18670
  // src/frontdoor/rcApi.ts
@@ -18414,14 +18725,16 @@ function createRcApiRouter(deps) {
18414
18725
  }),
18415
18726
  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 }) => {
18416
18727
  const pending = deps.pendingOf(input.session);
18417
- if (input.session !== void 0 && deps.statusOf(input.session).length === 0) {
18728
+ const statuses = deps.statusOf(input.session);
18729
+ if (input.session !== void 0 && statuses.length === 0) {
18418
18730
  throw new ORPCError("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
18419
18731
  }
18420
- return { pending };
18732
+ const dropped = statuses.flatMap((status) => status.pendingDropped === void 0 ? [] : [{ sessionId: status.id, count: status.pendingDropped }]);
18733
+ return { pending, ...dropped.length === 0 ? {} : { dropped } };
18421
18734
  }),
18422
18735
  send: authed.meta(openapi({ method: "POST", path: "/rest/rc/send", summary: "Send one message into a session", tags: [RC_API_TAG] })).input(RcSendInputSchema).output(RcWriteOutputSchema).handler(async ({ input }) => ({ session: input.session, sequenceNums: delivered(input.session, await deps.inject(input.session, input.text)) })),
18423
- answer: authed.meta(openapi({ method: "POST", path: "/rest/rc/answer", summary: "Answer one pending control request", tags: [RC_API_TAG] })).input(RcAnswerInputSchema).output(RcAnswerOutputSchema).handler(async ({ input }) => {
18424
- const decision = { approve: input.approve, message: input.approve || input.text === void 0 ? void 0 : input.text };
18736
+ answer: authed.meta(openapi({ method: "POST", path: "/rest/rc/answer", summary: "Answer one pending control request: approve or deny it, or choose the options of a pending question", tags: [RC_API_TAG] })).input(RcAnswerInputSchema).output(RcAnswerOutputSchema).handler(async ({ input }) => {
18737
+ const decision = { approve: input.approve, message: input.approve || input.text === void 0 ? void 0 : input.text, ...input.choices === void 0 ? {} : { choices: input.choices } };
18425
18738
  return { session: input.session, request: input.request, sequenceNums: delivered(input.session, await deps.answer(input.session, input.request, decision)) };
18426
18739
  }),
18427
18740
  interrupt: authed.meta(openapi({ method: "POST", path: "/rest/rc/interrupt", summary: "Interrupt a session's running turn", tags: [RC_API_TAG] })).input(RcInterruptInputSchema).output(RcControlWriteOutputSchema).handler(async ({ input }) => ({ session: input.session, ...deliveredControl(input.session, await deps.interrupt(input.session)) })),
@@ -18572,48 +18885,48 @@ init_cliError();
18572
18885
  init_package();
18573
18886
 
18574
18887
  // src/codex/appServerSchemas.ts
18575
- import { z as z24 } from "zod";
18888
+ import { z as z25 } from "zod";
18576
18889
  var CODEX_APP_SERVER_GENERATED_AGAINST = "0.160.0";
18577
- var RateLimitWindowSchema = z24.object({
18578
- usedPercent: z24.number(),
18579
- resetsAt: z24.number().nullish(),
18580
- windowDurationMins: z24.number().nullish()
18581
- });
18582
- var RateLimitSnapshotSchema = z24.object({
18583
- limitId: z24.string().nullish(),
18584
- limitName: z24.string().nullish(),
18585
- planType: z24.string().nullish(),
18890
+ var RateLimitWindowSchema = z25.object({
18891
+ usedPercent: z25.number(),
18892
+ resetsAt: z25.number().nullish(),
18893
+ windowDurationMins: z25.number().nullish()
18894
+ });
18895
+ var RateLimitSnapshotSchema = z25.object({
18896
+ limitId: z25.string().nullish(),
18897
+ limitName: z25.string().nullish(),
18898
+ planType: z25.string().nullish(),
18586
18899
  primary: RateLimitWindowSchema.nullish(),
18587
18900
  secondary: RateLimitWindowSchema.nullish(),
18588
- rateLimitReachedType: z24.string().nullish(),
18589
- spendControlReached: z24.boolean().nullish()
18590
- });
18591
- var RateLimitResetCreditSchema = z24.object({
18592
- id: z24.string(),
18593
- grantedAt: z24.number(),
18594
- expiresAt: z24.number().nullish(),
18595
- resetType: z24.string(),
18596
- status: z24.string(),
18597
- title: z24.string().nullish(),
18598
- description: z24.string().nullish()
18599
- });
18600
- var CodexAccountSchema = z24.discriminatedUnion("type", [
18601
- z24.object({ type: z24.literal("apiKey") }),
18602
- z24.object({ type: z24.literal("chatgpt"), email: z24.string().nullable(), planType: z24.string() }),
18603
- z24.object({ type: z24.literal("amazonBedrock"), usesCodexManagedCredentials: z24.boolean().default(false) })
18901
+ rateLimitReachedType: z25.string().nullish(),
18902
+ spendControlReached: z25.boolean().nullish()
18903
+ });
18904
+ var RateLimitResetCreditSchema = z25.object({
18905
+ id: z25.string(),
18906
+ grantedAt: z25.number(),
18907
+ expiresAt: z25.number().nullish(),
18908
+ resetType: z25.string(),
18909
+ status: z25.string(),
18910
+ title: z25.string().nullish(),
18911
+ description: z25.string().nullish()
18912
+ });
18913
+ var CodexAccountSchema = z25.discriminatedUnion("type", [
18914
+ z25.object({ type: z25.literal("apiKey") }),
18915
+ z25.object({ type: z25.literal("chatgpt"), email: z25.string().nullable(), planType: z25.string() }),
18916
+ z25.object({ type: z25.literal("amazonBedrock"), usesCodexManagedCredentials: z25.boolean().default(false) })
18604
18917
  ]);
18605
- var CodexAccountReadSchema = z24.object({
18918
+ var CodexAccountReadSchema = z25.object({
18606
18919
  account: CodexAccountSchema.nullable(),
18607
- requiresOpenaiAuth: z24.boolean()
18920
+ requiresOpenaiAuth: z25.boolean()
18608
18921
  });
18609
- var CodexRateLimitsReadSchema = z24.object({
18922
+ var CodexRateLimitsReadSchema = z25.object({
18610
18923
  rateLimits: RateLimitSnapshotSchema,
18611
- rateLimitsByLimitId: z24.record(z24.string(), RateLimitSnapshotSchema).nullish(),
18612
- rateLimitResetCredits: z24.object({ availableCount: z24.number(), credits: z24.array(RateLimitResetCreditSchema).nullish() }).nullish(),
18613
- accountId: z24.string().nullish(),
18614
- ordinaryUsageAllowed: z24.boolean().nullish()
18924
+ rateLimitsByLimitId: z25.record(z25.string(), RateLimitSnapshotSchema).nullish(),
18925
+ rateLimitResetCredits: z25.object({ availableCount: z25.number(), credits: z25.array(RateLimitResetCreditSchema).nullish() }).nullish(),
18926
+ accountId: z25.string().nullish(),
18927
+ ordinaryUsageAllowed: z25.boolean().nullish()
18615
18928
  });
18616
- var CodexInitializeResultSchema = z24.object({ userAgent: z24.string() });
18929
+ var CodexInitializeResultSchema = z25.object({ userAgent: z25.string() });
18617
18930
 
18618
18931
  // src/codex/appServer.ts
18619
18932
  var CodexAppServerUnavailableError = class extends CliError {
@@ -21826,8 +22139,8 @@ function rcFanoutOnDoorHub(fanout, hub) {
21826
22139
 
21827
22140
  // src/frontdoor/rcEventLog.ts
21828
22141
  var RC_SESSION_EVENT_TOKEN_MAX_CHARS = 255;
21829
- var HIGH_SURROGATE_FIRST = 55296;
21830
- var HIGH_SURROGATE_LAST = 56319;
22142
+ var HIGH_SURROGATE_FIRST2 = 55296;
22143
+ var HIGH_SURROGATE_LAST2 = 56319;
21831
22144
  var LOW_SURROGATE_FIRST = 56320;
21832
22145
  var LOW_SURROGATE_LAST = 57343;
21833
22146
  var CUT_MARKER = "...";
@@ -21838,7 +22151,7 @@ var NUMBER_BYTES = Float64Array.BYTES_PER_ELEMENT;
21838
22151
  var NUMBER_FIELDS = ["at", "sequence"].length;
21839
22152
  var BYTES_PER_CODE_UNIT = Uint16Array.BYTES_PER_ELEMENT;
21840
22153
  var RC_SESSION_END_REASONS = ["expired", "archived", "conflict"];
21841
- var RC_PENDING_RETIRE_REASONS = ["answered", "expired", "session-ended"];
22154
+ var RC_PENDING_RETIRE_REASONS = ["answered", "withdrawn", "worker-stopped", "session-ended"];
21842
22155
  var transitionBase = { session: z43.string(), at: z43.number() };
21843
22156
  var cursorFields = { cursor: z43.string(), sequence: z43.int().positive() };
21844
22157
  var sessionAppearedShape = { kind: z43.literal("session-appeared"), ...transitionBase };
@@ -21899,7 +22212,7 @@ function parseCursor(cursor) {
21899
22212
  function codePointBoundary(text, at) {
21900
22213
  const before = text.charCodeAt(at - 1);
21901
22214
  const after = text.charCodeAt(at);
21902
- const isHigh = before >= HIGH_SURROGATE_FIRST && before <= HIGH_SURROGATE_LAST;
22215
+ const isHigh = before >= HIGH_SURROGATE_FIRST2 && before <= HIGH_SURROGATE_LAST2;
21903
22216
  const isLow = after >= LOW_SURROGATE_FIRST && after <= LOW_SURROGATE_LAST;
21904
22217
  return isHigh && isLow ? at - 1 : at;
21905
22218
  }
@@ -22377,15 +22690,15 @@ function createQuotaExpiringPublisher(hub, deps) {
22377
22690
 
22378
22691
  // src/frontdoor/rcLiveUsage.ts
22379
22692
  var RC_RATE_LIMIT_EVENT_TYPE = "rate_limit_event";
22380
- function isRecord9(value) {
22693
+ function isRecord10(value) {
22381
22694
  return typeof value === "object" && value !== null && !Array.isArray(value);
22382
22695
  }
22383
22696
  function rcRateLimitInfoOf(event) {
22384
22697
  const payload = event.envelope.payload;
22385
- if (!isRecord9(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
22698
+ if (!isRecord10(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
22386
22699
  return void 0;
22387
22700
  }
22388
- if (!isRecord9(payload.rate_limit_info)) {
22701
+ if (!isRecord10(payload.rate_limit_info)) {
22389
22702
  return void 0;
22390
22703
  }
22391
22704
  const parsed = RcRateLimitInfoSchema.safeParse(payload.rate_limit_info);
@@ -22473,7 +22786,7 @@ function createSseParser() {
22473
22786
  }
22474
22787
  };
22475
22788
  }
22476
- function isRecord10(value) {
22789
+ function isRecord11(value) {
22477
22790
  return typeof value === "object" && value !== null && !Array.isArray(value);
22478
22791
  }
22479
22792
  function sequenceNumOf(value) {
@@ -22495,7 +22808,7 @@ function parseRcStreamEnvelope(parsed) {
22495
22808
  } catch {
22496
22809
  return void 0;
22497
22810
  }
22498
- if (!isRecord10(data)) {
22811
+ if (!isRecord11(data)) {
22499
22812
  return void 0;
22500
22813
  }
22501
22814
  const eventType = data.event_type;
@@ -22748,7 +23061,7 @@ function withClientPlatform(payload, headers) {
22748
23061
  const platform = headers[CLIENT_PLATFORM_HEADER];
22749
23062
  return typeof platform === "string" && platform !== "" ? { ...rest, client_platform: platform } : rest;
22750
23063
  }
22751
- function isRecord11(value) {
23064
+ function isRecord12(value) {
22752
23065
  return typeof value === "object" && value !== null && !Array.isArray(value);
22753
23066
  }
22754
23067
  function parseJsonObject2(body) {
@@ -22758,7 +23071,7 @@ function parseJsonObject2(body) {
22758
23071
  } catch {
22759
23072
  return void 0;
22760
23073
  }
22761
- return isRecord11(parsed) ? parsed : void 0;
23074
+ return isRecord12(parsed) ? parsed : void 0;
22762
23075
  }
22763
23076
  function nonEmptyString2(record, field) {
22764
23077
  const value = record === void 0 ? void 0 : record[field];
@@ -22832,7 +23145,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
22832
23145
  }
22833
23146
  const results = [];
22834
23147
  for (const event of events) {
22835
- if (!isRecord11(event) || !isRecord11(event.payload)) {
23148
+ if (!isRecord12(event) || !isRecord12(event.payload)) {
22836
23149
  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" } });
22837
23150
  return true;
22838
23151
  }
@@ -22932,7 +23245,7 @@ async function serveRcCompatSessions(ctx, pathname, compatPath) {
22932
23245
  // src/frontdoor/rcSelfHostConversations.ts
22933
23246
  var RC_CONVERSATIONS_PATH_PREFIX = "/v1/code/conversations";
22934
23247
  var RC_CONVERSATION_ID_PREFIX = "conv_";
22935
- function isRecord12(value) {
23248
+ function isRecord13(value) {
22936
23249
  return typeof value === "object" && value !== null && !Array.isArray(value);
22937
23250
  }
22938
23251
  function parseJsonObject3(body) {
@@ -22942,7 +23255,7 @@ function parseJsonObject3(body) {
22942
23255
  } catch {
22943
23256
  return void 0;
22944
23257
  }
22945
- return isRecord12(parsed) ? parsed : void 0;
23258
+ return isRecord13(parsed) ? parsed : void 0;
22946
23259
  }
22947
23260
  function nonEmptyString3(record, field) {
22948
23261
  const value = record === void 0 ? void 0 : record[field];
@@ -22996,7 +23309,7 @@ async function serveRcConversations(ctx, pathname, method) {
22996
23309
  }
22997
23310
  const results = [];
22998
23311
  for (const event of events) {
22999
- if (!isRecord12(event) || !isRecord12(event.payload)) {
23312
+ if (!isRecord13(event) || !isRecord13(event.payload)) {
23000
23313
  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" } });
23001
23314
  return;
23002
23315
  }
@@ -23028,7 +23341,7 @@ var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:
23028
23341
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
23029
23342
  var MS_PER_SECOND6 = 1e3;
23030
23343
  var HTTP_SERVICE_UNAVAILABLE = 503;
23031
- function isRecord13(value) {
23344
+ function isRecord14(value) {
23032
23345
  return typeof value === "object" && value !== null && !Array.isArray(value);
23033
23346
  }
23034
23347
  function parseJsonObject4(body) {
@@ -23038,7 +23351,7 @@ function parseJsonObject4(body) {
23038
23351
  } catch {
23039
23352
  return void 0;
23040
23353
  }
23041
- return isRecord13(parsed) ? parsed : void 0;
23354
+ return isRecord14(parsed) ? parsed : void 0;
23042
23355
  }
23043
23356
  function growthBookFeatures() {
23044
23357
  return {
@@ -23392,7 +23705,7 @@ var RC_SELF_HOST_WORKER_EPOCH = 1;
23392
23705
  var RC_STREAM_EVENT_NAME2 = "client_event";
23393
23706
  var CONFLICT_REASON_HEADER2 = "x-ccr-conflict-reason";
23394
23707
  var CONFLICT_REASON_EPOCH_STALE = "epoch_stale";
23395
- function isRecord14(value) {
23708
+ function isRecord15(value) {
23396
23709
  return typeof value === "object" && value !== null && !Array.isArray(value);
23397
23710
  }
23398
23711
  function isWebSearchRefusal(value) {
@@ -23476,7 +23789,7 @@ function parseJsonObject5(body) {
23476
23789
  } catch {
23477
23790
  return void 0;
23478
23791
  }
23479
- return isRecord14(parsed) ? parsed : void 0;
23792
+ return isRecord15(parsed) ? parsed : void 0;
23480
23793
  }
23481
23794
  function mintWorkerJwt(randomToken, issuedAt) {
23482
23795
  const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
@@ -23736,7 +24049,7 @@ data: ${JSON.stringify(envelope)}
23736
24049
  if (status !== void 0) {
23737
24050
  session.workerStatus = status;
23738
24051
  }
23739
- if (isRecord14(body?.external_metadata)) {
24052
+ if (isRecord15(body?.external_metadata)) {
23740
24053
  session.externalMetadata = body.external_metadata;
23741
24054
  }
23742
24055
  await answerJson2(response, HTTP_STATUS.ok, {});
@@ -23766,7 +24079,7 @@ data: ${JSON.stringify(envelope)}
23766
24079
  }
23767
24080
  const results = [];
23768
24081
  for (const event of events) {
23769
- if (!isRecord14(event) || !isRecord14(event.payload)) {
24082
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
23770
24083
  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" } });
23771
24084
  return;
23772
24085
  }
@@ -23799,7 +24112,7 @@ data: ${JSON.stringify(envelope)}
23799
24112
  return;
23800
24113
  }
23801
24114
  for (const event of events) {
23802
- if (isRecord14(event)) {
24115
+ if (isRecord15(event)) {
23803
24116
  session.internalEvents.push({ eventId: deps.newUuid(), body: event });
23804
24117
  }
23805
24118
  }
@@ -23895,7 +24208,7 @@ data: ${JSON.stringify(envelope)}
23895
24208
  }
23896
24209
  const results = [];
23897
24210
  for (const event of events) {
23898
- if (!isRecord14(event) || !isRecord14(event.payload)) {
24211
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
23899
24212
  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" } });
23900
24213
  return;
23901
24214
  }
@@ -24033,7 +24346,7 @@ var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
24033
24346
  var RC_SELF_HOST_RECORD_FILE = "credential.json";
24034
24347
  var SELF_HOST_EMAIL = "selfhost@agent-shim.invalid";
24035
24348
  var SELF_HOST_SUBSCRIPTION_TYPE = "max";
24036
- function isRecord15(value) {
24349
+ function isRecord16(value) {
24037
24350
  return typeof value === "object" && value !== null && !Array.isArray(value);
24038
24351
  }
24039
24352
  function readJsonObject(fs17, file) {
@@ -24047,7 +24360,7 @@ function readJsonObject(fs17, file) {
24047
24360
  } catch {
24048
24361
  return void 0;
24049
24362
  }
24050
- return isRecord15(parsed) ? parsed : void 0;
24363
+ return isRecord16(parsed) ? parsed : void 0;
24051
24364
  }
24052
24365
  function readRcSelfHostRecord(fs17, frontdoorDir) {
24053
24366
  const parsed = readJsonObject(fs17, path45.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
@@ -24075,7 +24388,7 @@ function mintRcSelfHostCredential(deps) {
24075
24388
  const recordFile2 = path45.join(recordDir, RC_SELF_HOST_RECORD_FILE);
24076
24389
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
24077
24390
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
24078
- const existingOauth = isRecord15(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
24391
+ const existingOauth = isRecord16(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
24079
24392
  const existingToken = typeof existingOauth?.accessToken === "string" && existingOauth.accessToken !== "" ? existingOauth.accessToken : void 0;
24080
24393
  const existingIsOwn = existingToken !== void 0 && previousRecord?.accessToken === existingToken;
24081
24394
  if (existingToken !== void 0 && !existingIsOwn && !deps.force) {
@@ -24092,7 +24405,7 @@ function mintRcSelfHostCredential(deps) {
24092
24405
  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)}
24093
24406
  `);
24094
24407
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
24095
- const existingBlock = (value) => isRecord15(value) ? value : {};
24408
+ const existingBlock = (value) => isRecord16(value) ? value : {};
24096
24409
  deps.fs.writeFilePrivate(claudeJsonFile, `${JSON.stringify({
24097
24410
  ...claudeJson,
24098
24411
  oauthAccount: {
@@ -24849,7 +25162,6 @@ export {
24849
25162
  RC_GOAL_CONDITION_MAX_CHARS,
24850
25163
  RC_IDLE_EXPIRY_MS,
24851
25164
  RC_ORPC_PATH_PREFIX,
24852
- RC_PENDING_DEADLINE_MS,
24853
25165
  RC_PENDING_RETIRE_REASONS,
24854
25166
  RC_PERMISSION_MODES,
24855
25167
  RC_READ_FILE_ENCODINGS,