claude-use 11.90.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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();
@@ -6664,10 +6664,10 @@ var init_blockingSpawn = __esm({
6664
6664
  });
6665
6665
 
6666
6666
  // src/usage/signIn.ts
6667
- import { createHash as createHash3 } from "node:crypto";
6667
+ import { createHash as createHash4 } from "node:crypto";
6668
6668
  import path19 from "node:path";
6669
6669
  function claudeCodeKeychainService(configDir) {
6670
- return `${KEYCHAIN_SERVICE_PREFIX}-${createHash3("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
6670
+ return `${KEYCHAIN_SERVICE_PREFIX}-${createHash4("sha256").update(configDir).digest("hex").slice(0, KEYCHAIN_SERVICE_HASH_DIGITS)}`;
6671
6671
  }
6672
6672
  function keychainHasItem(run, configDir) {
6673
6673
  return run.run("security", ["find-generic-password", "-s", claudeCodeKeychainService(configDir)]).status === 0;
@@ -7071,9 +7071,9 @@ var init_supervisorProcesses = __esm({
7071
7071
  });
7072
7072
 
7073
7073
  // src/headroom/state.ts
7074
- import { createHash as createHash4 } from "node:crypto";
7074
+ import { createHash as createHash5 } from "node:crypto";
7075
7075
  import path21 from "node:path";
7076
- import { z as z13 } from "zod";
7076
+ import { z as z14 } from "zod";
7077
7077
  function parseJson(raw, schema) {
7078
7078
  if (raw === void 0 || raw.trim() === "") {
7079
7079
  return void 0;
@@ -7120,7 +7120,7 @@ function migrateHeadroomState(fs17, files, isRunning) {
7120
7120
  fs17.removeRecursive(files.legacyStateFile);
7121
7121
  }
7122
7122
  function hashAllowlist(allowlist) {
7123
- return createHash4("sha256").update(allowlist.join("\n")).digest("hex");
7123
+ return createHash5("sha256").update(allowlist.join("\n")).digest("hex");
7124
7124
  }
7125
7125
  function formatAllowlistFile(allowlist) {
7126
7126
  return allowlist.map((entry) => `${entry}
@@ -7230,32 +7230,32 @@ var init_state2 = __esm({
7230
7230
  "src/headroom/state.ts"() {
7231
7231
  "use strict";
7232
7232
  init_schema();
7233
- HeadroomStateSchema = z13.strictObject({
7233
+ HeadroomStateSchema = z14.strictObject({
7234
7234
  /** The supervisor process owning the daemon. Alive means someone is keeping headroom running. */
7235
- supervisorPid: z13.number().int().positive().optional(),
7235
+ supervisorPid: z14.number().int().positive().optional(),
7236
7236
  /** 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(),
7237
+ headroomPid: z14.number().int().positive().optional(),
7238
7238
  /**
7239
7239
  * 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
7240
  */
7241
- socketPath: z13.string().min(1).optional(),
7241
+ socketPath: z14.string().min(1).optional(),
7242
7242
  /** The `headroom --version` output of the running install. */
7243
- version: z13.string().optional(),
7243
+ version: z14.string().optional(),
7244
7244
  /**
7245
7245
  * 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
7246
  */
7247
- allowlistHash: z13.string().optional(),
7247
+ allowlistHash: z14.string().optional(),
7248
7248
  /** 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(),
7249
+ settingsHash: z14.string().optional(),
7250
7250
  /** The install spec the running install was last installed from, so a `source` config change is detected as drift. */
7251
- installedSource: z13.string().optional(),
7251
+ installedSource: z14.string().optional(),
7252
7252
  /** 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(),
7253
+ installing: z14.string().optional(),
7254
7254
  /** The last fatal error, kept across shutdowns so `headroom status` can explain a daemon that is not running. */
7255
- lastError: z13.string().optional()
7255
+ lastError: z14.string().optional()
7256
7256
  });
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() });
7257
+ HeadroomSessionSchema = z14.strictObject({ pid: z14.number().int().positive(), startedAt: z14.number(), supervisorPid: z14.number().int().positive() });
7258
+ HeadroomLockSchema = z14.strictObject({ pid: z14.number().int().positive(), at: z14.number() });
7259
7259
  HEADROOM_ALLOWLIST_FILE_FLAG = "--allowed-base-urls-file";
7260
7260
  ALLOWLIST_LINE_BREAKS = "\\n\\r\\u000b\\u000c\\u001c\\u001d\\u001e\\u0085\\u2028\\u2029";
7261
7261
  ALLOWLIST_WHITESPACE = "\\t\\n\\u000b\\u000c\\r\\u001c-\\u001f \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
@@ -7445,7 +7445,7 @@ var init_ensure = __esm({
7445
7445
  });
7446
7446
 
7447
7447
  // src/headroom/settings.ts
7448
- import { createHash as createHash5 } from "node:crypto";
7448
+ import { createHash as createHash6 } from "node:crypto";
7449
7449
  function settingsOf(config) {
7450
7450
  return {
7451
7451
  ...config.mode === void 0 ? {} : { mode: config.mode },
@@ -7470,7 +7470,7 @@ function settingsEnv(settings) {
7470
7470
  return settings.rolloutChannel === void 0 ? {} : { HEADROOM_ROLLOUT_CHANNEL: settings.rolloutChannel };
7471
7471
  }
7472
7472
  function hashSettings(settings) {
7473
- return createHash5("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
7473
+ return createHash6("sha256").update(JSON.stringify([...settingsArgs(settings), JSON.stringify(settingsEnv(settings))])).digest("hex");
7474
7474
  }
7475
7475
  var init_settings = __esm({
7476
7476
  "src/headroom/settings.ts"() {
@@ -7662,7 +7662,7 @@ var init_socket = __esm({
7662
7662
  });
7663
7663
 
7664
7664
  // src/headroom/source.ts
7665
- import { z as z14 } from "zod";
7665
+ import { z as z15 } from "zod";
7666
7666
  function isMovingGitSource(spec) {
7667
7667
  const match = GIT_SPEC_RE.exec(spec);
7668
7668
  if (match === null) {
@@ -7681,7 +7681,7 @@ var init_source = __esm({
7681
7681
  "use strict";
7682
7682
  GIT_SPEC_RE = /git\+[^@\s]+(?:@([^\s#]+))?/;
7683
7683
  COMMIT_SHA_RE = /^[0-9a-f]{40}$/i;
7684
- DirectUrlSchema = z14.object({ vcs_info: z14.object({ commit_id: z14.string() }) });
7684
+ DirectUrlSchema = z15.object({ vcs_info: z15.object({ commit_id: z15.string() }) });
7685
7685
  }
7686
7686
  });
7687
7687
 
@@ -8126,7 +8126,7 @@ var init_logStyle = __esm({
8126
8126
 
8127
8127
  // src/realPorts.ts
8128
8128
  import { execFile, spawn } from "node:child_process";
8129
- import { createHash as createHash6 } from "node:crypto";
8129
+ import { createHash as createHash7 } from "node:crypto";
8130
8130
  import fs6 from "node:fs";
8131
8131
  import os2 from "node:os";
8132
8132
  import path24 from "node:path";
@@ -8553,7 +8553,7 @@ var init_realPorts = __esm({
8553
8553
  },
8554
8554
  hashFile(filePath) {
8555
8555
  try {
8556
- return createHash6("sha256").update(fs6.readFileSync(filePath)).digest("hex");
8556
+ return createHash7("sha256").update(fs6.readFileSync(filePath)).digest("hex");
8557
8557
  } catch (error) {
8558
8558
  if (isEnoent3(error) || isErrorWithCode(error, "EISDIR")) {
8559
8559
  return void 0;
@@ -8995,7 +8995,7 @@ var init_candidateText = __esm({
8995
8995
  });
8996
8996
 
8997
8997
  // src/usage/plan.ts
8998
- import { z as z15 } from "zod";
8998
+ import { z as z16 } from "zod";
8999
8999
  function planOf(account) {
9000
9000
  const userTier = account?.userRateLimitTier;
9001
9001
  if (userTier !== void 0 && ZERO_TIER.test(userTier)) {
@@ -9019,19 +9019,19 @@ var PlanClassSchema, TIER_MULTIPLIER, ZERO_TIER, BASE_TIER;
9019
9019
  var init_plan2 = __esm({
9020
9020
  "src/usage/plan.ts"() {
9021
9021
  "use strict";
9022
- PlanClassSchema = z15.union([
9023
- z15.strictObject({
9024
- kind: z15.literal("subscription"),
9022
+ PlanClassSchema = z16.union([
9023
+ z16.strictObject({
9024
+ kind: z16.literal("subscription"),
9025
9025
  /** The plan's size as a multiple of the smallest subscription tier (Max is 5, Ultra is 20). */
9026
- capacity: z15.number().positive(),
9026
+ capacity: z16.number().positive(),
9027
9027
  /** 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(),
9028
+ recognised: z16.boolean(),
9029
9029
  /** The tier string the classification rests on, when the account had one. */
9030
- tier: z15.string().optional()
9030
+ tier: z16.string().optional()
9031
9031
  }),
9032
- z15.strictObject({
9033
- kind: z15.literal("pay-per-use"),
9034
- tier: z15.string().optional()
9032
+ z16.strictObject({
9033
+ kind: z16.literal("pay-per-use"),
9034
+ tier: z16.string().optional()
9035
9035
  })
9036
9036
  ]);
9037
9037
  TIER_MULTIPLIER = /(?:^|_)(\d+)x$/;
@@ -9041,21 +9041,21 @@ var init_plan2 = __esm({
9041
9041
  });
9042
9042
 
9043
9043
  // src/usage/scan.ts
9044
- import { z as z16 } from "zod";
9044
+ import { z as z17 } from "zod";
9045
9045
  var AnthropicUsageSchema, ErrorObjectSchema;
9046
9046
  var init_scan = __esm({
9047
9047
  "src/usage/scan.ts"() {
9048
9048
  "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()
9049
+ AnthropicUsageSchema = z17.looseObject({
9050
+ input_tokens: z17.number().int().nonnegative().nullish(),
9051
+ output_tokens: z17.number().int().nonnegative().nullish(),
9052
+ cache_creation_input_tokens: z17.number().int().nonnegative().nullish(),
9053
+ cache_read_input_tokens: z17.number().int().nonnegative().nullish()
9054
9054
  });
9055
- ErrorObjectSchema = z16.looseObject({
9056
- type: z16.string().optional(),
9057
- code: z16.union([z16.string(), z16.number()]).optional(),
9058
- message: z16.string().optional()
9055
+ ErrorObjectSchema = z17.looseObject({
9056
+ type: z17.string().optional(),
9057
+ code: z17.union([z17.string(), z17.number()]).optional(),
9058
+ message: z17.string().optional()
9059
9059
  });
9060
9060
  }
9061
9061
  });
@@ -9525,7 +9525,7 @@ var init_store2 = __esm({
9525
9525
 
9526
9526
  // src/usage/poolPick.ts
9527
9527
  import path26 from "node:path";
9528
- import { z as z17 } from "zod";
9528
+ import { z as z18 } from "zod";
9529
9529
  function errorMessage(error) {
9530
9530
  return error instanceof Error ? error.message : String(error);
9531
9531
  }
@@ -9727,20 +9727,20 @@ var init_poolPick = __esm({
9727
9727
  }
9728
9728
  };
9729
9729
  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)
9730
+ PickEntrySchema = z18.strictObject({ identity: z18.string().min(1), at: z18.iso.datetime() });
9731
+ PicksFileSchema = z18.strictObject({
9732
+ schemaVersion: z18.literal(SCHEMA_VERSION),
9733
+ picks: z18.record(z18.string().min(1), PickEntrySchema)
9734
9734
  });
9735
9735
  }
9736
9736
  });
9737
9737
 
9738
9738
  // src/identityRenameJournal.ts
9739
- import { createHash as createHash7 } from "node:crypto";
9739
+ import { createHash as createHash8 } from "node:crypto";
9740
9740
  import path27 from "node:path";
9741
- import { z as z18 } from "zod";
9741
+ import { z as z19 } from "zod";
9742
9742
  function renamePairFileName(from, to, suffix) {
9743
- return `${createHash7("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
9743
+ return `${createHash8("sha256").update(`${from}\0${to}`).digest("hex").slice(0, FILE_NAME_HASH_DIGITS)}${suffix}`;
9744
9744
  }
9745
9745
  function readRenameJournal(fs17, file) {
9746
9746
  const raw = fs17.readFileUtf8(file);
@@ -9816,20 +9816,20 @@ var init_identityRenameJournal = __esm({
9816
9816
  "src/identityRenameJournal.ts"() {
9817
9817
  "use strict";
9818
9818
  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(),
9819
+ RenameJournalSchema = z19.strictObject({
9820
+ version: z19.literal(1),
9821
+ from: z19.string().min(1),
9822
+ to: z19.string().min(1),
9823
+ startedAt: z19.iso.datetime(),
9824
9824
  /** 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),
9825
+ pid: z19.number().int().positive(),
9826
+ steps: z19.array(
9827
+ z19.strictObject({
9828
+ description: z19.string().min(1),
9829
9829
  /** Whether the step has been applied and marked so. */
9830
- done: z18.boolean(),
9830
+ done: z19.boolean(),
9831
9831
  /** 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()
9832
+ started: z19.boolean()
9833
9833
  })
9834
9834
  )
9835
9835
  });
@@ -9855,7 +9855,7 @@ var init_identityRenameJournal = __esm({
9855
9855
  // src/identityNameRenameRecord.ts
9856
9856
  import fs7 from "node:fs";
9857
9857
  import path28 from "node:path";
9858
- import { z as z19 } from "zod";
9858
+ import { z as z20 } from "zod";
9859
9859
  function readRecordFiles(paths) {
9860
9860
  if (!fs7.existsSync(paths.identityNameRenamesDir)) {
9861
9861
  return [];
@@ -9950,12 +9950,12 @@ var init_identityNameRenameRecord = __esm({
9950
9950
  init_poolPick();
9951
9951
  init_identityRecords();
9952
9952
  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()
9953
+ NameRenameRecordSchema = z20.strictObject({
9954
+ version: z20.literal(1),
9955
+ id: z20.string().min(1),
9956
+ from: z20.string().min(1),
9957
+ to: z20.string().min(1),
9958
+ startedAt: z20.iso.datetime()
9959
9959
  });
9960
9960
  RECORD_SUFFIX = ".json";
9961
9961
  InterruptedNameRenameError = class extends CliError {
@@ -9970,7 +9970,7 @@ var init_identityNameRenameRecord = __esm({
9970
9970
  // src/launcher/launchRecords.ts
9971
9971
  import path29 from "node:path";
9972
9972
  import { randomUUID as randomUUID4 } from "node:crypto";
9973
- import { z as z20 } from "zod";
9973
+ import { z as z21 } from "zod";
9974
9974
  function recordFile(directory, pid) {
9975
9975
  return path29.join(directory, `${String(pid)}.${randomUUID4()}${RECORD_SUFFIX2}`);
9976
9976
  }
@@ -10017,11 +10017,11 @@ var LaunchRecordSchema, RECORD_SUFFIX2;
10017
10017
  var init_launchRecords = __esm({
10018
10018
  "src/launcher/launchRecords.ts"() {
10019
10019
  "use strict";
10020
- LaunchRecordSchema = z20.strictObject({
10020
+ LaunchRecordSchema = z21.strictObject({
10021
10021
  /** 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()
10022
+ pid: z21.number().int().positive(),
10023
+ identity: z21.string().min(1),
10024
+ startedAt: z21.iso.datetime()
10025
10025
  });
10026
10026
  RECORD_SUFFIX2 = ".json";
10027
10027
  }
@@ -10492,7 +10492,7 @@ var init_package = __esm({
10492
10492
  "package.json"() {
10493
10493
  package_default = {
10494
10494
  name: "claude-use",
10495
- version: "11.90.0",
10495
+ version: "12.0.0",
10496
10496
  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
10497
  license: "MIT",
10498
10498
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -11102,14 +11102,14 @@ function requireProviderExists(paths, name) {
11102
11102
  throw new ProviderNotFoundError(name);
11103
11103
  }
11104
11104
  }
11105
- function isRecord8(value) {
11105
+ function isRecord9(value) {
11106
11106
  return typeof value === "object" && value !== null && !Array.isArray(value);
11107
11107
  }
11108
11108
  function legacyProviderConversion(raw) {
11109
- if (!isRecord8(raw) || "credential" in raw) {
11109
+ if (!isRecord9(raw) || "credential" in raw) {
11110
11110
  return void 0;
11111
11111
  }
11112
- const env = isRecord8(raw.env) ? raw.env : void 0;
11112
+ const env = isRecord9(raw.env) ? raw.env : void 0;
11113
11113
  const legacyEnvKeys = env === void 0 ? [] : Object.keys(env).filter((key) => LEGACY_ENV_CREDENTIAL_KEYS.includes(key));
11114
11114
  const fields = [...LEGACY_PROVIDER_FIELDS.filter((field) => field in raw), ...legacyEnvKeys.map((key) => `env.${key}`)];
11115
11115
  if (fields.length === 0) {
@@ -11591,13 +11591,13 @@ var init_headers = __esm({
11591
11591
  });
11592
11592
 
11593
11593
  // src/launcher/injected.ts
11594
- import { createHash as createHash8 } from "node:crypto";
11594
+ import { createHash as createHash9 } from "node:crypto";
11595
11595
  import { z as z26 } from "zod";
11596
11596
  function listKey(list) {
11597
11597
  return `${list},appended`;
11598
11598
  }
11599
11599
  function digest2(value) {
11600
- return createHash8("sha256").update(value).digest("hex");
11600
+ return createHash9("sha256").update(value).digest("hex");
11601
11601
  }
11602
11602
  function recordedDigests(env) {
11603
11603
  const raw = env[INJECTED_ENV];
@@ -12029,7 +12029,7 @@ var init_modelsStore = __esm({
12029
12029
  });
12030
12030
 
12031
12031
  // src/codex/catalogueCredential.ts
12032
- import { createHash as createHash9 } from "node:crypto";
12032
+ import { createHash as createHash10 } from "node:crypto";
12033
12033
  import path41 from "node:path";
12034
12034
  import { z as z35 } from "zod";
12035
12035
  function parseCatalogueBinding(raw) {
@@ -12042,7 +12042,7 @@ function parseCatalogueBinding(raw) {
12042
12042
  }
12043
12043
  }
12044
12044
  function catalogueCredentialFingerprint(cli, token, accountId) {
12045
- return createHash9("sha256").update(JSON.stringify([cli, token, accountId])).digest("hex");
12045
+ return createHash10("sha256").update(JSON.stringify([cli, token, accountId])).digest("hex");
12046
12046
  }
12047
12047
  function cliCatalogueFingerprint(raw) {
12048
12048
  if (raw === void 0) return void 0;
@@ -13534,7 +13534,7 @@ function withLauncherSettings(passthrough, settings) {
13534
13534
  }
13535
13535
  return [...kept, "--settings", settings, ...tail];
13536
13536
  }
13537
- function isRecord16(value) {
13537
+ function isRecord17(value) {
13538
13538
  return typeof value === "object" && value !== null && !Array.isArray(value);
13539
13539
  }
13540
13540
  function mergeSettings(parts) {
@@ -13545,7 +13545,7 @@ function mergeSettings(parts) {
13545
13545
  continue;
13546
13546
  }
13547
13547
  const parsed = JSON.parse(part);
13548
- if (!isRecord16(parsed)) {
13548
+ if (!isRecord17(parsed)) {
13549
13549
  throw new Error("a launch's settings part is not a JSON object");
13550
13550
  }
13551
13551
  for (const [key, value] of Object.entries(parsed)) {
@@ -14717,7 +14717,7 @@ var init_selfIdentity = __esm({
14717
14717
  });
14718
14718
 
14719
14719
  // src/frontdoor/trust.ts
14720
- import { createHash as createHash10 } from "node:crypto";
14720
+ import { createHash as createHash11 } from "node:crypto";
14721
14721
  import path53 from "node:path";
14722
14722
  function resolveTrustBundle(params) {
14723
14723
  const { caCertFile, bundlesDir, variable, inherited, fs: fs17 } = params;
@@ -14739,7 +14739,7 @@ function resolveTrustBundle(params) {
14739
14739
  }
14740
14740
  const combined = `${inheritedPem.trimEnd()}
14741
14741
  ${caPem}`;
14742
- const bundle = path53.join(bundlesDir, `${createHash10("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
14742
+ const bundle = path53.join(bundlesDir, `${createHash11("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
14743
14743
  if (!fs17.exists(bundle)) {
14744
14744
  fs17.mkdirp(bundlesDir);
14745
14745
  fs17.writeFileAtomic(bundle, combined);
@@ -15413,6 +15413,9 @@ var HTTP_STATUS = {
15413
15413
  // src/frontdoor/connectEffects.ts
15414
15414
  init_connect();
15415
15415
 
15416
+ // src/frontdoor/rcSessions.ts
15417
+ import { createHash as createHash3 } from "node:crypto";
15418
+
15416
15419
  // src/agents/liveTasks.ts
15417
15420
  import { z as z9 } from "zod";
15418
15421
 
@@ -15671,6 +15674,125 @@ function mergeLiveTasks(tree, live) {
15671
15674
  return { ...tree, agents, remoteSessions, liveOnly };
15672
15675
  }
15673
15676
 
15677
+ // src/frontdoor/rcQuestions.ts
15678
+ var RC_QUESTION_TOOL_NAME = "AskUserQuestion";
15679
+ var RC_QUESTIONS_MAX = 16;
15680
+ var RC_QUESTION_OPTIONS_MAX = 16;
15681
+ var RC_QUESTION_FIELD_MAX_CHARS = 1024;
15682
+ var MULTI_SELECT_SEPARATOR = ", ";
15683
+ function isRecord4(value) {
15684
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15685
+ }
15686
+ function fits(value) {
15687
+ return value === void 0 || value.length <= RC_QUESTION_FIELD_MAX_CHARS;
15688
+ }
15689
+ function optionOf(value) {
15690
+ if (!isRecord4(value) || typeof value.label !== "string" || value.label === "") {
15691
+ return "an option names no label";
15692
+ }
15693
+ const description = typeof value.description === "string" && value.description !== "" ? value.description : void 0;
15694
+ if (!fits(value.label) || !fits(description)) {
15695
+ return `an option is past ${String(RC_QUESTION_FIELD_MAX_CHARS)} characters`;
15696
+ }
15697
+ return description === void 0 ? { label: value.label } : { label: value.label, description };
15698
+ }
15699
+ function questionOf(value) {
15700
+ if (!isRecord4(value) || typeof value.question !== "string" || value.question === "" || !Array.isArray(value.options) || value.options.length === 0) {
15701
+ return "a question has no text or no options";
15702
+ }
15703
+ if (value.options.length > RC_QUESTION_OPTIONS_MAX) {
15704
+ return `a question has more than ${String(RC_QUESTION_OPTIONS_MAX)} options`;
15705
+ }
15706
+ const options = [];
15707
+ for (const candidate of value.options) {
15708
+ const option = optionOf(candidate);
15709
+ if (typeof option === "string") {
15710
+ return option;
15711
+ }
15712
+ if (options.some((existing) => existing.label === option.label)) {
15713
+ return `a question lists the option ${JSON.stringify(option.label)} twice`;
15714
+ }
15715
+ options.push(option);
15716
+ }
15717
+ const header = typeof value.header === "string" && value.header !== "" ? value.header : void 0;
15718
+ if (!fits(value.question) || !fits(header)) {
15719
+ return `a question is past ${String(RC_QUESTION_FIELD_MAX_CHARS)} characters`;
15720
+ }
15721
+ return { question: value.question, ...header === void 0 ? {} : { header }, multiSelect: value.multiSelect === true, options };
15722
+ }
15723
+ function rcQuestionsOfToolRequest(toolName, input) {
15724
+ if (toolName !== RC_QUESTION_TOOL_NAME) {
15725
+ return void 0;
15726
+ }
15727
+ if (!isRecord4(input) || !Array.isArray(input.questions) || input.questions.length === 0) {
15728
+ return { unanswerable: "the request names no questions" };
15729
+ }
15730
+ if (input.questions.length > RC_QUESTIONS_MAX) {
15731
+ return { unanswerable: `the request asks more than ${String(RC_QUESTIONS_MAX)} questions` };
15732
+ }
15733
+ const questions = [];
15734
+ for (const candidate of input.questions) {
15735
+ const question = questionOf(candidate);
15736
+ if (typeof question === "string") {
15737
+ return { unanswerable: question };
15738
+ }
15739
+ if (questions.some((existing) => existing.question === question.question)) {
15740
+ return { unanswerable: `the request asks ${JSON.stringify(question.question)} twice` };
15741
+ }
15742
+ questions.push(question);
15743
+ }
15744
+ return { questions };
15745
+ }
15746
+ function resolveSelection(question, questionNumber, selection) {
15747
+ if (typeof selection === "number") {
15748
+ const option = Number.isInteger(selection) ? question.options[selection - 1] : void 0;
15749
+ 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 };
15750
+ }
15751
+ if (typeof selection === "object") {
15752
+ const text = selection.text.trim();
15753
+ return text === "" ? { error: `question ${String(questionNumber)}'s free-text answer is empty` } : { text };
15754
+ }
15755
+ const exact = question.options.find((option) => option.label === selection);
15756
+ if (exact !== void 0) {
15757
+ return { text: exact.label };
15758
+ }
15759
+ const folded = question.options.filter((option) => option.label.toLowerCase() === selection.toLowerCase());
15760
+ const [only] = folded;
15761
+ if (only !== void 0 && folded.length === 1) {
15762
+ return { text: only.label };
15763
+ }
15764
+ return { error: `question ${String(questionNumber)} has no option labelled ${JSON.stringify(selection)}: its options are ${question.options.map((option) => JSON.stringify(option.label)).join(", ")}` };
15765
+ }
15766
+ function resolveRcQuestionAnswers(questions, choices) {
15767
+ if (choices.length !== questions.length) {
15768
+ 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)}` };
15769
+ }
15770
+ const answers = {};
15771
+ for (const [index, question] of questions.entries()) {
15772
+ const questionNumber = index + 1;
15773
+ const selections = choices[index] ?? [];
15774
+ if (selections.length === 0) {
15775
+ return { error: `question ${String(questionNumber)} has no selection` };
15776
+ }
15777
+ if (!question.multiSelect && selections.length > 1) {
15778
+ return { error: `question ${String(questionNumber)} takes one option, but ${String(selections.length)} were chosen` };
15779
+ }
15780
+ const texts = [];
15781
+ for (const selection of selections) {
15782
+ const resolved = resolveSelection(question, questionNumber, selection);
15783
+ if ("error" in resolved) {
15784
+ return resolved;
15785
+ }
15786
+ if (texts.includes(resolved.text)) {
15787
+ return { error: `question ${String(questionNumber)} chose ${JSON.stringify(resolved.text)} twice` };
15788
+ }
15789
+ texts.push(resolved.text);
15790
+ }
15791
+ answers[question.question] = texts.join(MULTI_SELECT_SEPARATOR);
15792
+ }
15793
+ return { answers };
15794
+ }
15795
+
15674
15796
  // src/frontdoor/rcSessions.ts
15675
15797
  var RC_SESSIONS_PATH_PREFIX = "/v1/code/sessions";
15676
15798
  function pathnameOf(url) {
@@ -15685,7 +15807,12 @@ var RC_IDLE_EXPIRY_MS = 45e3;
15685
15807
  var RC_CREATE_RESPONSE_CAP_BYTES = 8192;
15686
15808
  var CONFLICT_REASON_HEADER = "x-ccr-conflict-reason";
15687
15809
  var RC_STREAM_WORKER_SOURCE = "worker";
15688
- var RC_PENDING_DEADLINE_MS = 14e3;
15810
+ var HIGH_SURROGATE_FIRST = 55296;
15811
+ var HIGH_SURROGATE_LAST = 56319;
15812
+ var RC_WORKER_IDLE = "idle";
15813
+ var RC_PENDING_PER_SESSION_MAX = 64;
15814
+ var RC_REQUEST_ID_MAX_CHARS = 128;
15815
+ var RC_RETIRED_TOMBSTONES_MAX = 2 * RC_PENDING_PER_SESSION_MAX;
15689
15816
  var RC_REQUEST_PARSE_CAP_BYTES = 262144;
15690
15817
  var RC_PENDING_SUMMARY_EXCERPT_CHARS = 300;
15691
15818
  var SUCCESS_STATUS_MAX_EXCLUSIVE = 300;
@@ -15718,7 +15845,7 @@ function sessionCreateId(body) {
15718
15845
  const id = session.id;
15719
15846
  return typeof id === "string" && id.startsWith(RC_SESSION_ID_PREFIX) ? id : void 0;
15720
15847
  }
15721
- function isRecord4(value) {
15848
+ function isRecord5(value) {
15722
15849
  return typeof value === "object" && value !== null && !Array.isArray(value);
15723
15850
  }
15724
15851
  function parseJsonObject(body) {
@@ -15728,7 +15855,7 @@ function parseJsonObject(body) {
15728
15855
  } catch {
15729
15856
  return void 0;
15730
15857
  }
15731
- return isRecord4(parsed) ? parsed : void 0;
15858
+ return isRecord5(parsed) ? parsed : void 0;
15732
15859
  }
15733
15860
  function nonEmptyString(record, field) {
15734
15861
  const value = record === void 0 ? void 0 : record[field];
@@ -15738,8 +15865,16 @@ function finiteNumber(record, field) {
15738
15865
  const value = record === void 0 ? void 0 : record[field];
15739
15866
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
15740
15867
  }
15741
- function excerpt(text) {
15742
- return text.length <= RC_PENDING_SUMMARY_EXCERPT_CHARS ? text : `${text.slice(0, RC_PENDING_SUMMARY_EXCERPT_CHARS)}...`;
15868
+ function rcExcerpt(text) {
15869
+ if (text.length <= RC_PENDING_SUMMARY_EXCERPT_CHARS) {
15870
+ return text;
15871
+ }
15872
+ const cut = text.slice(0, RC_PENDING_SUMMARY_EXCERPT_CHARS);
15873
+ const last = cut.charCodeAt(cut.length - 1);
15874
+ return `${isHighSurrogate(last) ? cut.slice(0, -1) : cut}...`;
15875
+ }
15876
+ function isHighSurrogate(unit) {
15877
+ return unit >= HIGH_SURROGATE_FIRST && unit <= HIGH_SURROGATE_LAST;
15743
15878
  }
15744
15879
  function payloadEventsOf(body) {
15745
15880
  const parsed = parseJsonObject(body);
@@ -15749,11 +15884,11 @@ function payloadEventsOf(body) {
15749
15884
  }
15750
15885
  const payloads = [];
15751
15886
  for (const event of events) {
15752
- if (!isRecord4(event)) {
15887
+ if (!isRecord5(event)) {
15753
15888
  continue;
15754
15889
  }
15755
15890
  const payload = event.payload;
15756
- if (!isRecord4(payload)) {
15891
+ if (!isRecord5(payload)) {
15757
15892
  continue;
15758
15893
  }
15759
15894
  payloads.push(payload);
@@ -15761,6 +15896,14 @@ function payloadEventsOf(body) {
15761
15896
  return payloads;
15762
15897
  }
15763
15898
  function pendingOfControlRequestPayload(payload) {
15899
+ const parsed = fullPendingOfControlRequestPayload(payload);
15900
+ const isQuestion = parsed !== void 0 && (parsed.questions !== void 0 || parsed.unanswerable !== void 0);
15901
+ if (parsed === void 0 || !isQuestion || Buffer.byteLength(JSON.stringify(payload), "utf8") <= RC_REQUEST_PARSE_CAP_BYTES) {
15902
+ return parsed;
15903
+ }
15904
+ 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` };
15905
+ }
15906
+ function fullPendingOfControlRequestPayload(payload) {
15764
15907
  if (payload.type !== "control_request") {
15765
15908
  return void 0;
15766
15909
  }
@@ -15768,24 +15911,41 @@ function pendingOfControlRequestPayload(payload) {
15768
15911
  if (requestId === void 0) {
15769
15912
  return void 0;
15770
15913
  }
15771
- const request4 = isRecord4(payload.request) ? payload.request : void 0;
15914
+ const request4 = isRecord5(payload.request) ? payload.request : void 0;
15772
15915
  const subtype = nonEmptyString(request4, "subtype");
15773
15916
  const type = subtype ?? "control_request";
15774
15917
  let summary = "";
15918
+ let questions;
15919
+ let unanswerable;
15920
+ let toolInput;
15775
15921
  if (subtype === "can_use_tool") {
15776
- const toolName = nonEmptyString(request4, "tool_name") ?? "unknown tool";
15922
+ const toolName = nonEmptyString(request4, "tool_name");
15777
15923
  const input = request4 === void 0 ? void 0 : request4.input;
15778
- summary = input === void 0 ? toolName : `${toolName} ${excerpt(JSON.stringify(input))}`;
15924
+ summary = input === void 0 ? toolName ?? "unknown tool" : `${toolName ?? "unknown tool"} ${rcExcerpt(JSON.stringify(input))}`;
15925
+ const parsedQuestions = rcQuestionsOfToolRequest(toolName, input);
15926
+ if (parsedQuestions !== void 0 && "questions" in parsedQuestions) {
15927
+ questions = parsedQuestions.questions;
15928
+ toolInput = isRecord5(input) ? input : void 0;
15929
+ } else if (parsedQuestions !== void 0) {
15930
+ unanswerable = parsedQuestions.unanswerable;
15931
+ }
15779
15932
  } else if (request4 !== void 0) {
15780
- summary = excerpt(JSON.stringify(request4));
15933
+ summary = rcExcerpt(JSON.stringify(request4));
15781
15934
  }
15782
- return { requestId, type, summary };
15935
+ return { requestId, type, summary, questions, unanswerable, toolInput, oversized: false };
15936
+ }
15937
+ function withdrawnRequestIdsOfControlCancelPayload(payload) {
15938
+ if (payload.type !== "control_cancel_request") {
15939
+ return [];
15940
+ }
15941
+ const id = nonEmptyString(payload, "request_id");
15942
+ return id === void 0 ? [] : [id];
15783
15943
  }
15784
15944
  function answeredRequestIdsOfControlResponsePayload(payload) {
15785
15945
  if (payload.type !== "control_response") {
15786
15946
  return [];
15787
15947
  }
15788
- const response = isRecord4(payload.response) ? payload.response : void 0;
15948
+ const response = isRecord5(payload.response) ? payload.response : void 0;
15789
15949
  const id = nonEmptyString(response, "request_id") ?? nonEmptyString(payload, "request_id") ?? nonEmptyString(payload, "uuid");
15790
15950
  return id === void 0 ? [] : [id];
15791
15951
  }
@@ -15797,44 +15957,74 @@ function initFactsOfPayload(payload) {
15797
15957
  }
15798
15958
  function parseRcRequestBody(kind, body) {
15799
15959
  if (kind === "heartbeat") {
15800
- return { controlRequests: [], answeredRequestIds: [], idleSeconds: finiteNumber(parseJsonObject(body), "idle_seconds"), workerStatus: void 0, payloads: [] };
15960
+ return { controlRequests: [], answeredRequestIds: [], withdrawnRequestIds: [], idleSeconds: finiteNumber(parseJsonObject(body), "idle_seconds"), workerStatus: void 0, workerEpoch: void 0, payloads: [] };
15801
15961
  }
15802
15962
  if (kind === "worker-registration") {
15803
15963
  const registration = parseJsonObject(body);
15804
- const metadata = registration === void 0 || !isRecord4(registration.external_metadata) ? void 0 : registration.external_metadata;
15964
+ const metadata = registration === void 0 || !isRecord5(registration.external_metadata) ? void 0 : registration.external_metadata;
15805
15965
  const model = nonEmptyString(metadata, "model");
15806
- return { controlRequests: [], answeredRequestIds: [], idleSeconds: void 0, workerStatus: nonEmptyString(registration, "worker_status"), payloads: [], ...model === void 0 ? {} : { model } };
15966
+ return { controlRequests: [], answeredRequestIds: [], withdrawnRequestIds: [], idleSeconds: void 0, workerStatus: nonEmptyString(registration, "worker_status"), workerEpoch: finiteNumber(registration, "worker_epoch"), payloads: [], ...model === void 0 ? {} : { model } };
15807
15967
  }
15808
15968
  const controlRequests = [];
15809
15969
  const answeredRequestIds = [];
15970
+ const withdrawnRequestIds = [];
15810
15971
  const payloads = payloadEventsOf(body);
15811
15972
  for (const payload of payloads) {
15812
15973
  const pending = pendingOfControlRequestPayload(payload);
15813
15974
  if (pending !== void 0) {
15814
- controlRequests.push({ requestId: pending.requestId, type: pending.type, summary: pending.summary });
15975
+ controlRequests.push(pending);
15815
15976
  continue;
15816
15977
  }
15817
15978
  answeredRequestIds.push(...answeredRequestIdsOfControlResponsePayload(payload));
15979
+ if (kind === "worker-events") {
15980
+ withdrawnRequestIds.push(...withdrawnRequestIdsOfControlCancelPayload(payload));
15981
+ }
15818
15982
  }
15819
- return { controlRequests, answeredRequestIds, idleSeconds: void 0, workerStatus: void 0, payloads };
15983
+ return { controlRequests, answeredRequestIds, withdrawnRequestIds, idleSeconds: void 0, workerStatus: void 0, workerEpoch: void 0, payloads };
15984
+ }
15985
+ function rememberBounded(record, key) {
15986
+ record.delete(key);
15987
+ record.add(key);
15988
+ if (record.size > RC_RETIRED_TOMBSTONES_MAX) {
15989
+ const [oldest] = record;
15990
+ if (oldest !== void 0) {
15991
+ record.delete(oldest);
15992
+ }
15993
+ }
15994
+ }
15995
+ function droppedKeyOf(requestId) {
15996
+ return requestId.length <= RC_REQUEST_ID_MAX_CHARS ? requestId : createHash3("sha256").update(requestId).digest("hex");
15820
15997
  }
15821
15998
  function createRcSessionTracker(deps) {
15822
15999
  const entries = /* @__PURE__ */ new Map();
16000
+ let observationSequence = 0;
16001
+ const rememberRetired = (entry, requestId) => {
16002
+ rememberBounded(entry.retired, requestId);
16003
+ };
15823
16004
  const retirePending = (entry, requestId, reason) => {
15824
16005
  if (entry.pending.delete(requestId)) {
15825
- entry.retired.set(requestId, deps.now());
16006
+ rememberRetired(entry, requestId);
15826
16007
  deps.onTransition?.({ kind: "pending-retired", session: entry.id, requestId, reason, at: deps.now() });
15827
16008
  }
15828
16009
  };
15829
- const addPending = (entry, pending) => {
15830
- if (entry.retired.has(pending.requestId)) {
16010
+ const addPending = (entry, request4, now) => {
16011
+ const droppedKey = droppedKeyOf(request4.requestId);
16012
+ if (entry.retired.has(request4.requestId) || entry.dropped.has(droppedKey)) {
16013
+ return;
16014
+ }
16015
+ const already = entry.pending.get(request4.requestId);
16016
+ if (already !== void 0) {
16017
+ entry.pending.set(request4.requestId, { ...already, ...request4, observedAt: already.observedAt });
15831
16018
  return;
15832
16019
  }
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 });
16020
+ if (request4.requestId.length > RC_REQUEST_ID_MAX_CHARS || entry.pending.size >= RC_PENDING_PER_SESSION_MAX) {
16021
+ entry.droppedPending += 1;
16022
+ rememberBounded(entry.dropped, droppedKey);
16023
+ return;
15837
16024
  }
16025
+ observationSequence += 1;
16026
+ entry.pending.set(request4.requestId, { sessionId: entry.id, ...request4, observedAt: now, observedSequence: observationSequence });
16027
+ deps.onTransition?.({ kind: "pending-born", session: entry.id, requestId: request4.requestId, type: request4.type, summary: request4.summary, at: now });
15838
16028
  };
15839
16029
  const expire = (id, reason) => {
15840
16030
  const entry = entries.get(id);
@@ -15847,31 +16037,17 @@ function createRcSessionTracker(deps) {
15847
16037
  entries.delete(id);
15848
16038
  deps.onTransition?.({ kind: "session-ended", session: id, reason, at: deps.now() });
15849
16039
  };
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
16040
  const sweep = () => {
15863
16041
  for (const [id, entry] of entries) {
15864
16042
  if (deps.now() - entry.lastSeenAt >= deps.idleMs) {
15865
16043
  expire(id, "expired");
15866
- continue;
15867
16044
  }
15868
- expirePendings(entry, deps.now());
15869
16045
  }
15870
16046
  };
15871
- const timer = setInterval(sweep, Math.min(deps.idleMs, RC_PENDING_DEADLINE_MS));
16047
+ const timer = setInterval(sweep, deps.idleMs);
15872
16048
  timer.unref();
15873
16049
  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() };
16050
+ 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
16051
  entries.set(id, record);
15876
16052
  deps.onTransition?.({ kind: "session-appeared", session: id, at: record.createdAt });
15877
16053
  return record;
@@ -15902,6 +16078,7 @@ function createRcSessionTracker(deps) {
15902
16078
  return void 0;
15903
16079
  }
15904
16080
  const tail = pathnameOf(request4.url).slice(RC_SESSIONS_PATH_PREFIX.length);
16081
+ const startedAtSequence = observationSequence;
15905
16082
  const facts = {
15906
16083
  oauthAuthorization: oauthAuthorizationOf(request4.headers),
15907
16084
  anthropicVersion: singleHeader(request4.headers, "anthropic-version"),
@@ -15975,11 +16152,14 @@ function createRcSessionTracker(deps) {
15975
16152
  }
15976
16153
  const now = deps.now();
15977
16154
  for (const controlRequest of factsOfBody.controlRequests) {
15978
- addPending(entryNow, { sessionId: id, ...controlRequest, observedAt: now });
16155
+ addPending(entryNow, controlRequest, now);
15979
16156
  }
15980
16157
  for (const requestId of factsOfBody.answeredRequestIds) {
15981
16158
  retirePending(entryNow, requestId, "answered");
15982
16159
  }
16160
+ for (const requestId of factsOfBody.withdrawnRequestIds) {
16161
+ retirePending(entryNow, requestId, "withdrawn");
16162
+ }
15983
16163
  for (const payload of factsOfBody.payloads) {
15984
16164
  entryNow.liveTasks = applyAgentTaskEvent(entryNow.liveTasks, id, payload, now);
15985
16165
  noteInit(entryNow, payload);
@@ -15995,6 +16175,17 @@ function createRcSessionTracker(deps) {
15995
16175
  deps.onTransition?.({ kind: "worker-state", session: id, state: factsOfBody.workerStatus, ...previous === void 0 ? {} : { previous }, at: now });
15996
16176
  }
15997
16177
  }
16178
+ const epochChanged = factsOfBody.workerEpoch !== void 0 && entryNow.workerEpoch !== void 0 && factsOfBody.workerEpoch !== entryNow.workerEpoch;
16179
+ if (factsOfBody.workerEpoch !== void 0) {
16180
+ entryNow.workerEpoch = factsOfBody.workerEpoch;
16181
+ }
16182
+ if (epochChanged || factsOfBody.workerStatus === RC_WORKER_IDLE) {
16183
+ for (const [requestId, pending] of entryNow.pending) {
16184
+ if (pending.observedSequence <= startedAtSequence) {
16185
+ retirePending(entryNow, requestId, "worker-stopped");
16186
+ }
16187
+ }
16188
+ }
15998
16189
  };
15999
16190
  const archiving = method === "POST" && rest === `${id}/archive`;
16000
16191
  return {
@@ -16034,7 +16225,7 @@ function createRcSessionTracker(deps) {
16034
16225
  };
16035
16226
  };
16036
16227
  const summaryOf2 = ({ id, createdAt, lastSeenAt }) => ({ id, createdAt, lastSeenAt });
16037
- const pendingSummaryOf = ({ sessionId, requestId, type, summary, observedAt: observedAt2 }) => ({ sessionId, requestId, type, summary, observedAt: observedAt2 });
16228
+ 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
16229
  const sortedEntries = () => [...entries.values()].sort((left, right) => left.createdAt - right.createdAt || (left.id < right.id ? -1 : 1));
16039
16230
  const pendingSorted = (entry) => [...entry.pending.values()].sort((left, right) => left.observedAt - right.observedAt || (left.requestId < right.requestId ? -1 : 1)).map(pendingSummaryOf);
16040
16231
  return {
@@ -16052,7 +16243,8 @@ function createRcSessionTracker(deps) {
16052
16243
  pending: pendingSorted(entry),
16053
16244
  ...entry.identity === void 0 ? {} : { identity: entry.identity },
16054
16245
  ...entry.model === void 0 ? {} : { model: entry.model },
16055
- ...entry.cwd === void 0 ? {} : { cwd: entry.cwd }
16246
+ ...entry.cwd === void 0 ? {} : { cwd: entry.cwd },
16247
+ ...entry.droppedPending === 0 ? {} : { pendingDropped: entry.droppedPending }
16056
16248
  }));
16057
16249
  },
16058
16250
  pendingOf: (sessionId) => {
@@ -16090,7 +16282,7 @@ function createRcSessionTracker(deps) {
16090
16282
  return;
16091
16283
  }
16092
16284
  entry.sequenceNum = entry.sequenceNum === void 0 || event.sequence_num > entry.sequenceNum ? event.sequence_num : entry.sequenceNum;
16093
- if (!isRecord4(event.payload)) {
16285
+ if (!isRecord5(event.payload)) {
16094
16286
  return;
16095
16287
  }
16096
16288
  entry.liveTasks = applyAgentTaskEvent(entry.liveTasks, sessionId, event.payload, deps.now());
@@ -16098,13 +16290,18 @@ function createRcSessionTracker(deps) {
16098
16290
  const pending = pendingOfControlRequestPayload(event.payload);
16099
16291
  if (pending !== void 0) {
16100
16292
  if (event.source === RC_STREAM_WORKER_SOURCE) {
16101
- addPending(entry, { sessionId, ...pending, observedAt: deps.now() });
16293
+ addPending(entry, pending, deps.now());
16102
16294
  }
16103
16295
  return;
16104
16296
  }
16105
16297
  for (const requestId of answeredRequestIdsOfControlResponsePayload(event.payload)) {
16106
16298
  retirePending(entry, requestId, "answered");
16107
16299
  }
16300
+ if (event.source === RC_STREAM_WORKER_SOURCE) {
16301
+ for (const requestId of withdrawnRequestIdsOfControlCancelPayload(event.payload)) {
16302
+ retirePending(entry, requestId, "withdrawn");
16303
+ }
16304
+ }
16108
16305
  },
16109
16306
  liveTasksOf: (sessionId) => {
16110
16307
  sweep();
@@ -16116,6 +16313,17 @@ function createRcSessionTracker(deps) {
16116
16313
  retirePending(entry, requestId, "answered");
16117
16314
  }
16118
16315
  },
16316
+ claimPending: (sessionId, requestId) => {
16317
+ const entry = entries.get(sessionId);
16318
+ if (entry === void 0 || !entry.pending.has(requestId) || entry.answering.has(requestId)) {
16319
+ return void 0;
16320
+ }
16321
+ entry.answering.add(requestId);
16322
+ return () => {
16323
+ entry.answering.delete(requestId);
16324
+ };
16325
+ },
16326
+ pendingToolInputOf: (sessionId, requestId) => entries.get(sessionId)?.pending.get(requestId)?.toolInput,
16119
16327
  close: () => {
16120
16328
  clearInterval(timer);
16121
16329
  deps.onClose?.();
@@ -16282,8 +16490,8 @@ async function injectRcUserMessage(deps, sessionId, text) {
16282
16490
  }
16283
16491
  return result;
16284
16492
  }
16285
- function buildRcControlResponsePayload(requestId, decision) {
16286
- const result = decision.approve ? { behavior: "allow" } : { behavior: "deny", message: decision.message ?? "" };
16493
+ function buildRcControlResponsePayload(requestId, decision, updatedInput) {
16494
+ const result = decision.approve ? { behavior: "allow", ...updatedInput === void 0 ? {} : { updatedInput } } : { behavior: "deny", message: decision.message ?? "" };
16287
16495
  return { type: "control_response", response: { subtype: "success", request_id: requestId, response: result } };
16288
16496
  }
16289
16497
  var RC_PERMISSION_MODES = ["default", "acceptEdits", "bypassPermissions", "plan", "dontAsk", "auto"];
@@ -16340,6 +16548,27 @@ function buildRcMcpOAuthCallbackUrlPayload(requestId, serverName, callbackUrl) {
16340
16548
  function buildRcKeepAlivePayload() {
16341
16549
  return { type: "keep_alive" };
16342
16550
  }
16551
+ function questionAnswerInput(deps, sessionId, pending, decision) {
16552
+ const { questions, unanswerable } = pending;
16553
+ if (questions === void 0 && unanswerable === void 0) {
16554
+ 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` };
16555
+ }
16556
+ if (!decision.approve) {
16557
+ 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" };
16558
+ }
16559
+ if (questions === void 0) {
16560
+ 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` };
16561
+ }
16562
+ if (decision.choices === void 0) {
16563
+ 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` };
16564
+ }
16565
+ const input = deps.pendingToolInputOf(sessionId, pending.requestId);
16566
+ if (input === void 0) {
16567
+ return { error: `the front door holds no input for question ${pending.requestId} on session ${sessionId}, so it cannot write the answer the worker expects` };
16568
+ }
16569
+ const resolved = resolveRcQuestionAnswers(questions, decision.choices);
16570
+ return "error" in resolved ? resolved : { input: { ...input, answers: resolved.answers } };
16571
+ }
16343
16572
  async function answerRcControlRequest(deps, sessionId, requestId, decision) {
16344
16573
  const credential = deps.credentialOf(sessionId);
16345
16574
  if (credential === void 0) {
@@ -16348,15 +16577,26 @@ async function answerRcControlRequest(deps, sessionId, requestId, decision) {
16348
16577
  if (credential.authorization === void 0) {
16349
16578
  return noOAuthCredentialResult(sessionId);
16350
16579
  }
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` };
16580
+ const pending = deps.pendingOf(sessionId).find((candidate) => candidate.requestId === requestId);
16581
+ if (pending === void 0) {
16582
+ 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` };
16583
+ }
16584
+ const updatedInput = questionAnswerInput(deps, sessionId, pending, decision);
16585
+ if (updatedInput !== void 0 && "error" in updatedInput) {
16586
+ return { ok: false, message: updatedInput.error };
16353
16587
  }
16354
- const body = JSON.stringify(buildRcEventWriteBody(buildRcControlResponsePayload(requestId, decision)));
16588
+ const release = deps.claimPending(sessionId, requestId);
16589
+ if (release === void 0) {
16590
+ 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` };
16591
+ }
16592
+ const body = JSON.stringify(buildRcEventWriteBody(buildRcControlResponsePayload(requestId, decision, updatedInput?.input)));
16355
16593
  let answer;
16356
16594
  try {
16357
16595
  answer = await deps.dial.writeEvents(sessionId, rcWriteHeaders(credential), body);
16358
16596
  } catch (error) {
16359
16597
  return { ok: false, message: `the door could not reach the API host to answer on session ${sessionId}: ${error instanceof Error ? error.message : String(error)}` };
16598
+ } finally {
16599
+ release();
16360
16600
  }
16361
16601
  const result = rcEventWriteResultFromAnswer(answer);
16362
16602
  if (result.ok) {
@@ -16486,6 +16726,198 @@ init_legacy();
16486
16726
  // src/frontdoor/rcControl.ts
16487
16727
  import * as https from "node:https";
16488
16728
  init_capability();
16729
+
16730
+ // src/frontdoor/rcSchemas.ts
16731
+ import { z as z10 } from "zod";
16732
+ var RcPermissionModeSchema = z10.enum(RC_PERMISSION_MODES);
16733
+ var RcSessionSummarySchema = z10.strictObject({
16734
+ id: z10.string(),
16735
+ createdAt: z10.number(),
16736
+ lastSeenAt: z10.number()
16737
+ });
16738
+ function workerFactSchema(value) {
16739
+ return z10.strictObject({ value, observedAt: z10.number() });
16740
+ }
16741
+ var RcQuestionOptionSchema = z10.strictObject({
16742
+ label: z10.string(),
16743
+ description: z10.string().optional()
16744
+ });
16745
+ var RcPendingQuestionSchema = z10.strictObject({
16746
+ question: z10.string(),
16747
+ header: z10.string().optional(),
16748
+ multiSelect: z10.boolean(),
16749
+ options: z10.readonly(z10.array(RcQuestionOptionSchema))
16750
+ });
16751
+ var RcPendingRequestSummarySchema = z10.strictObject({
16752
+ sessionId: z10.string(),
16753
+ requestId: z10.string(),
16754
+ type: z10.string(),
16755
+ summary: z10.string(),
16756
+ questions: z10.readonly(z10.array(RcPendingQuestionSchema)).optional(),
16757
+ oversized: z10.literal(true).optional(),
16758
+ unanswerable: z10.string().optional(),
16759
+ observedAt: z10.number()
16760
+ });
16761
+ var RcSessionStatusSchema = z10.strictObject({
16762
+ ...RcSessionSummarySchema.shape,
16763
+ workerState: workerFactSchema(z10.string()).optional(),
16764
+ workerIdleSeconds: workerFactSchema(z10.number()).optional(),
16765
+ pending: z10.readonly(z10.array(RcPendingRequestSummarySchema)),
16766
+ /** The identity the session runs as, when known; absent otherwise. */
16767
+ identity: z10.string().optional(),
16768
+ /** The model the session last stated, when the door saw one. */
16769
+ model: z10.string().optional(),
16770
+ /** The session's name from the Claude Code session registry, when the registry holds it. */
16771
+ name: z10.string().optional(),
16772
+ /** The session process's id from the registry. */
16773
+ pid: z10.number().optional(),
16774
+ /** The session's working directory, from its init event or the registry. */
16775
+ cwd: z10.string().optional(),
16776
+ pendingDropped: z10.int().positive().optional()
16777
+ });
16778
+ var RcStreamEnvelopeSchema = z10.looseObject({
16779
+ /** The envelope's own event id, when the host sent one. */
16780
+ event_id: z10.string().optional(),
16781
+ /** The envelope's event type, the discriminator a consumer switches on (`control_request`, `user`, and kin). */
16782
+ event_type: z10.string(),
16783
+ /** The sequence number the host assigned, the value a resume continues after. */
16784
+ sequence_num: z10.int(),
16785
+ /** Who emitted the event (`worker` for the CLI's half, a client id for a client's). */
16786
+ source: z10.string(),
16787
+ /** 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. */
16788
+ payload: z10.unknown().optional(),
16789
+ /** 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. */
16790
+ created_at: z10.unknown().optional()
16791
+ });
16792
+ var RcStreamEventSchema = z10.strictObject({
16793
+ session: z10.string(),
16794
+ envelope: RcStreamEnvelopeSchema
16795
+ });
16796
+ var RcRateLimitWindowSchema = z10.looseObject({
16797
+ /** 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). */
16798
+ utilization: z10.number().optional(),
16799
+ /** 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. */
16800
+ resetsAt: z10.number().optional()
16801
+ });
16802
+ var RcRateLimitInfoSchema = z10.looseObject({
16803
+ /** The limiting window's own status (`allowed`, `allowed_warning`, `rejected`), asserted only as a string because the vocabulary grows with the CLI. */
16804
+ status: z10.string(),
16805
+ /** When the limiting window resets, in unix epoch seconds. */
16806
+ resetsAt: z10.number().optional(),
16807
+ /** Which window the top-level fields describe (`five_hour`, `seven_day`, and kin), the payload's own name for it. */
16808
+ rateLimitType: z10.string().optional(),
16809
+ /** The fraction of the limiting window used, on the same scale the per-window utilizations carry. */
16810
+ utilization: z10.number().optional(),
16811
+ /** Whether usage beyond the plan (extra usage) is currently covering the overflow, the payload's own flag for it. */
16812
+ isUsingOverage: z10.boolean().optional(),
16813
+ /** The overage's own status, the same vocabulary the limiting window's `status` carries. */
16814
+ overageStatus: z10.string().optional(),
16815
+ /** When the overage window resets, in unix epoch seconds. */
16816
+ overageResetsAt: z10.number().optional(),
16817
+ /** 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. */
16818
+ unifiedWindows: z10.looseObject({ five_hour: RcRateLimitWindowSchema.optional(), seven_day: RcRateLimitWindowSchema.optional(), seven_day_overage_included: RcRateLimitWindowSchema.optional() }).optional()
16819
+ });
16820
+ var RcLiveRateLimitSchema = z10.strictObject({
16821
+ session: z10.string(),
16822
+ observedAt: z10.number(),
16823
+ rateLimit: RcRateLimitInfoSchema
16824
+ });
16825
+ var RcSessionQuerySchema = z10.strictObject({
16826
+ session: z10.string().min(1).optional()
16827
+ });
16828
+ var RcSendInputSchema = z10.strictObject({
16829
+ session: z10.string().min(1),
16830
+ text: z10.string().min(1)
16831
+ });
16832
+ 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" }) })]);
16833
+ var RcQuestionChoicesSchema = z10.array(z10.array(RcQuestionSelectionSchema).min(1)).min(1);
16834
+ var RcAnswerInputSchema = z10.strictObject({
16835
+ session: z10.string().min(1),
16836
+ request: z10.string().min(1),
16837
+ approve: z10.boolean(),
16838
+ text: z10.string().optional(),
16839
+ choices: RcQuestionChoicesSchema.optional()
16840
+ }).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" });
16841
+ var RcInterruptInputSchema = z10.strictObject({
16842
+ session: z10.string().min(1)
16843
+ });
16844
+ var RcSetModelInputSchema = z10.strictObject({
16845
+ session: z10.string().min(1),
16846
+ model: z10.string().min(1)
16847
+ });
16848
+ var RcSetPermissionModeInputSchema = z10.strictObject({
16849
+ session: z10.string().min(1),
16850
+ mode: RcPermissionModeSchema
16851
+ });
16852
+ var RcEndSessionInputSchema = z10.strictObject({
16853
+ session: z10.string().min(1),
16854
+ reason: z10.string().min(1).optional()
16855
+ });
16856
+ var RcGetUsageInputSchema = z10.strictObject({
16857
+ session: z10.string().min(1),
16858
+ skipBehaviors: z10.boolean().optional()
16859
+ });
16860
+ var RcGetContextUsageInputSchema = z10.strictObject({
16861
+ session: z10.string().min(1),
16862
+ detail: z10.enum(RC_CONTEXT_USAGE_DETAILS).optional()
16863
+ });
16864
+ var RcReadFileInputSchema = z10.strictObject({
16865
+ session: z10.string().min(1),
16866
+ path: z10.string().min(1),
16867
+ maxBytes: z10.number().int().positive().optional(),
16868
+ encoding: z10.enum(RC_READ_FILE_ENCODINGS).optional()
16869
+ });
16870
+ var RcFileSuggestionsInputSchema = z10.strictObject({
16871
+ session: z10.string().min(1),
16872
+ query: z10.string()
16873
+ });
16874
+ var RcKeepAliveInputSchema = z10.strictObject({
16875
+ session: z10.string().min(1)
16876
+ });
16877
+ var RcMcpStatusInputSchema = z10.strictObject({
16878
+ session: z10.string().min(1)
16879
+ });
16880
+ var RcMcpReconnectInputSchema = z10.strictObject({
16881
+ session: z10.string().min(1),
16882
+ serverName: z10.string().min(1)
16883
+ });
16884
+ var RcMcpAuthenticateInputSchema = z10.strictObject({
16885
+ session: z10.string().min(1),
16886
+ serverName: z10.string().min(1),
16887
+ redirectUri: z10.string().min(1)
16888
+ });
16889
+ var RcMcpOAuthCallbackUrlInputSchema = z10.strictObject({
16890
+ session: z10.string().min(1),
16891
+ serverName: z10.string().min(1),
16892
+ callbackUrl: z10.string().min(1)
16893
+ });
16894
+ var RcTeleportInputSchema = z10.strictObject({
16895
+ session: z10.string().min(1),
16896
+ marker: z10.string().min(1)
16897
+ });
16898
+ var RcListOutputSchema = z10.strictObject({ sessions: z10.readonly(z10.array(RcSessionSummarySchema)) });
16899
+ var RcStatusOutputSchema = z10.strictObject({ statuses: z10.readonly(z10.array(RcSessionStatusSchema)) });
16900
+ var RcPendingOutputSchema = z10.strictObject({
16901
+ pending: z10.readonly(z10.array(RcPendingRequestSummarySchema)),
16902
+ /** 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. */
16903
+ dropped: z10.readonly(z10.array(z10.strictObject({ sessionId: z10.string(), count: z10.int().positive() }))).optional()
16904
+ });
16905
+ var RcWriteOutputSchema = z10.strictObject({
16906
+ session: z10.string(),
16907
+ sequenceNums: z10.readonly(z10.array(z10.number()))
16908
+ });
16909
+ var RcControlWriteOutputSchema = z10.strictObject({
16910
+ session: z10.string(),
16911
+ request: z10.string(),
16912
+ sequenceNums: z10.readonly(z10.array(z10.number()))
16913
+ });
16914
+ var RcAnswerOutputSchema = z10.strictObject({
16915
+ session: z10.string(),
16916
+ request: z10.string(),
16917
+ sequenceNums: z10.readonly(z10.array(z10.number()))
16918
+ });
16919
+
16920
+ // src/frontdoor/rcControl.ts
16489
16921
  var RC_PERMISSION_MODE_LIST = RC_PERMISSION_MODES.join(", ");
16490
16922
  var CONTROL_PATH_PREFIX = "/__agent-shim/rc";
16491
16923
  var CONTROL_BODY_CAP_BYTES = 10485760;
@@ -16742,11 +17174,20 @@ function createRcControlHandler(deps) {
16742
17174
  return;
16743
17175
  }
16744
17176
  const text = "text" in parsed && typeof parsed.text === "string" ? parsed.text : void 0;
17177
+ const choices = "choices" in parsed ? RcQuestionChoicesSchema.safeParse(parsed.choices) : void 0;
17178
+ if (choices !== void 0 && !choices.success) {
17179
+ 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": ...}' });
17180
+ return;
17181
+ }
17182
+ if (choices !== void 0 && !parsed.approve) {
17183
+ answerJson(response, HTTP_STATUS.badRequest, { error: "choices answer a question, so they come with approve: true; a denial dismisses the question" });
17184
+ return;
17185
+ }
16745
17186
  if (parsed.approve && text !== void 0 && text !== "") {
16746
17187
  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
17188
  return;
16748
17189
  }
16749
- const result = await deps.answer(parsed.session, parsed.request, { approve: parsed.approve, message: parsed.approve ? void 0 : text });
17190
+ 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
17191
  if (result.ok) {
16751
17192
  answerJson(response, HTTP_STATUS.ok, { session: parsed.session, request: parsed.request, sequenceNums: result.sequenceNums });
16752
17193
  return;
@@ -16868,6 +17309,9 @@ function isRcSessionStatus(value) {
16868
17309
  if ("workerState" in value && value.workerState !== void 0 && !isRcWorkerFact(value.workerState, (candidate) => typeof candidate === "string")) {
16869
17310
  return false;
16870
17311
  }
17312
+ if ("pendingDropped" in value && value.pendingDropped !== void 0 && typeof value.pendingDropped !== "number") {
17313
+ return false;
17314
+ }
16871
17315
  if ("workerIdleSeconds" in value && value.workerIdleSeconds !== void 0 && !isRcWorkerFact(value.workerIdleSeconds, (candidate) => typeof candidate === "number")) {
16872
17316
  return false;
16873
17317
  }
@@ -16877,13 +17321,7 @@ function isRcSessionStatus(value) {
16877
17321
  return value.pending.every((candidate) => isRcPendingRequestSummary(candidate));
16878
17322
  }
16879
17323
  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";
17324
+ return RcPendingRequestSummarySchema.safeParse(value).success;
16887
17325
  }
16888
17326
  function sequenceNumsOfBody(body) {
16889
17327
  let parsed;
@@ -17019,7 +17457,7 @@ function frontDoorRcControl(transport, token) {
17019
17457
  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
17458
  answerRequest: async (sessionId, requestId, decision) => await writeOf(
17021
17459
  `${CONTROL_PATH_PREFIX}/answer`,
17022
- JSON.stringify({ session: sessionId, request: requestId, approve: decision.approve, ...decision.approve || decision.message === void 0 ? {} : { text: decision.message } }),
17460
+ 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
17461
  (status, message) => `answering control request ${requestId} on ${sessionId} failed (HTTP ${String(status)}): ${message}`
17024
17462
  ),
17025
17463
  interruptSession: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/interrupt`, JSON.stringify({ session: sessionId }), (status, message) => `interrupting ${sessionId} failed (HTTP ${String(status)}): ${message}`),
@@ -17537,19 +17975,19 @@ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
17537
17975
  // src/frontdoor/rcSessionRegistry.ts
17538
17976
  init_identityStore();
17539
17977
  import path31 from "node:path";
17540
- import { z as z21 } from "zod";
17978
+ import { z as z22 } from "zod";
17541
17979
  var REGISTRY_BRIDGE_PREFIX = "session_";
17542
17980
  var DOOR_SESSION_PREFIX = "cse_";
17543
17981
  var REGISTRY_DIR = "sessions";
17544
17982
  var ENTRY_SUFFIX = ".json";
17545
17983
  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()
17984
+ var RegistryEntrySchema = z22.looseObject({
17985
+ sessionId: z22.string().min(1),
17986
+ pid: z22.int().positive(),
17987
+ bridgeSessionId: z22.union([z22.string().startsWith(REGISTRY_BRIDGE_PREFIX), z22.string().startsWith(DOOR_SESSION_PREFIX)]),
17988
+ cwd: z22.string().optional(),
17989
+ name: z22.string().optional(),
17990
+ updatedAt: z22.number().optional()
17553
17991
  });
17554
17992
  function supersedes(candidate, kept) {
17555
17993
  return candidate.updatedAt > kept.updatedAt || candidate.updatedAt === kept.updatedAt && candidate.session.pid > kept.session.pid;
@@ -17663,11 +18101,11 @@ import path32 from "node:path";
17663
18101
  function isSafeSessionId(sessionId) {
17664
18102
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
17665
18103
  }
17666
- function isRecord6(value) {
18104
+ function isRecord7(value) {
17667
18105
  return typeof value === "object" && value !== null && !Array.isArray(value);
17668
18106
  }
17669
18107
  function credentialOfJson(parsed) {
17670
- if (!isRecord6(parsed)) {
18108
+ if (!isRecord7(parsed)) {
17671
18109
  return void 0;
17672
18110
  }
17673
18111
  const { authorization, anthropicVersion, anthropicClientPlatform } = parsed;
@@ -17697,7 +18135,7 @@ function createRcCredentialStore(fs17, dir) {
17697
18135
  } catch {
17698
18136
  return void 0;
17699
18137
  }
17700
- return isRecord6(parsed) ? parsed : void 0;
18138
+ return isRecord7(parsed) ? parsed : void 0;
17701
18139
  };
17702
18140
  return {
17703
18141
  read: (sessionId) => {
@@ -17755,175 +18193,6 @@ var COMPACT_TIMEOUT_MS = 9e5;
17755
18193
  // src/frontdoor/rcApi.ts
17756
18194
  init_capability();
17757
18195
 
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
18196
  // src/frontdoor/rcSlashCommandSchemas.ts
17928
18197
  import { z as z23 } from "zod";
17929
18198
 
@@ -17961,26 +18230,26 @@ async function writeRcPersonMessage(deps, sessionId, text) {
17961
18230
  }
17962
18231
  return result;
17963
18232
  }
17964
- function isRecord7(value) {
18233
+ function isRecord8(value) {
17965
18234
  return typeof value === "object" && value !== null && !Array.isArray(value);
17966
18235
  }
17967
18236
  function rcLocalCommandAnswerOf(event, command, args) {
17968
18237
  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) {
18238
+ if (!isRecord8(payload) || payload.type !== "assistant" || !isRecord8(payload.local_command_run) || payload.local_command_run.command !== command || payload.local_command_run.args !== args) {
17970
18239
  return void 0;
17971
18240
  }
17972
18241
  const message = payload.message;
17973
- if (!isRecord7(message) || !Array.isArray(message.content)) {
18242
+ if (!isRecord8(message) || !Array.isArray(message.content)) {
17974
18243
  return void 0;
17975
18244
  }
17976
18245
  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;
18246
+ const text = blocks.flatMap((block) => isRecord8(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
18247
+ const outcome = isRecord8(payload.local_command_outcome) && typeof payload.local_command_outcome.kind === "string" ? payload.local_command_outcome.kind : void 0;
17979
18248
  return { text, outcome };
17980
18249
  }
17981
18250
  function rcManualCompactBoundaryOf(event) {
17982
18251
  const payload = event.envelope.payload;
17983
- if (!isRecord7(payload) || payload.type !== "system" || payload.subtype !== "compact_boundary" || !isRecord7(payload.compact_metadata)) {
18252
+ if (!isRecord8(payload) || payload.type !== "system" || payload.subtype !== "compact_boundary" || !isRecord8(payload.compact_metadata)) {
17984
18253
  return void 0;
17985
18254
  }
17986
18255
  const metadata = payload.compact_metadata;
@@ -17991,7 +18260,7 @@ function rcManualCompactBoundaryOf(event) {
17991
18260
  }
17992
18261
  function isPeerDelivery(event, text) {
17993
18262
  const payload = event.envelope.payload;
17994
- if (!isRecord7(payload) || payload.type !== "user" || !isRecord7(payload.origin) || payload.origin.kind !== "peer" || !isRecord7(payload.message)) {
18263
+ if (!isRecord8(payload) || payload.type !== "user" || !isRecord8(payload.origin) || payload.origin.kind !== "peer" || !isRecord8(payload.message)) {
17995
18264
  return false;
17996
18265
  }
17997
18266
  return typeof payload.message.content === "string" && payload.message.content.includes(text);
@@ -18108,7 +18377,7 @@ function createRcClaudeCodeVersions(fanout) {
18108
18377
  const versions = /* @__PURE__ */ new Map();
18109
18378
  fanout.subscribe(void 0, (event) => {
18110
18379
  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") {
18380
+ if (event.envelope.source === "worker" && isRecord8(payload) && payload.type === "system" && payload.subtype === "init" && typeof payload.claude_code_version === "string") {
18112
18381
  versions.set(event.session, payload.claude_code_version);
18113
18382
  }
18114
18383
  });
@@ -18414,14 +18683,16 @@ function createRcApiRouter(deps) {
18414
18683
  }),
18415
18684
  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
18685
  const pending = deps.pendingOf(input.session);
18417
- if (input.session !== void 0 && deps.statusOf(input.session).length === 0) {
18686
+ const statuses = deps.statusOf(input.session);
18687
+ if (input.session !== void 0 && statuses.length === 0) {
18418
18688
  throw new ORPCError("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
18419
18689
  }
18420
- return { pending };
18690
+ const dropped = statuses.flatMap((status) => status.pendingDropped === void 0 ? [] : [{ sessionId: status.id, count: status.pendingDropped }]);
18691
+ return { pending, ...dropped.length === 0 ? {} : { dropped } };
18421
18692
  }),
18422
18693
  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 };
18694
+ 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 }) => {
18695
+ const decision = { approve: input.approve, message: input.approve || input.text === void 0 ? void 0 : input.text, ...input.choices === void 0 ? {} : { choices: input.choices } };
18425
18696
  return { session: input.session, request: input.request, sequenceNums: delivered(input.session, await deps.answer(input.session, input.request, decision)) };
18426
18697
  }),
18427
18698
  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)) })),
@@ -21826,8 +22097,8 @@ function rcFanoutOnDoorHub(fanout, hub) {
21826
22097
 
21827
22098
  // src/frontdoor/rcEventLog.ts
21828
22099
  var RC_SESSION_EVENT_TOKEN_MAX_CHARS = 255;
21829
- var HIGH_SURROGATE_FIRST = 55296;
21830
- var HIGH_SURROGATE_LAST = 56319;
22100
+ var HIGH_SURROGATE_FIRST2 = 55296;
22101
+ var HIGH_SURROGATE_LAST2 = 56319;
21831
22102
  var LOW_SURROGATE_FIRST = 56320;
21832
22103
  var LOW_SURROGATE_LAST = 57343;
21833
22104
  var CUT_MARKER = "...";
@@ -21838,7 +22109,7 @@ var NUMBER_BYTES = Float64Array.BYTES_PER_ELEMENT;
21838
22109
  var NUMBER_FIELDS = ["at", "sequence"].length;
21839
22110
  var BYTES_PER_CODE_UNIT = Uint16Array.BYTES_PER_ELEMENT;
21840
22111
  var RC_SESSION_END_REASONS = ["expired", "archived", "conflict"];
21841
- var RC_PENDING_RETIRE_REASONS = ["answered", "expired", "session-ended"];
22112
+ var RC_PENDING_RETIRE_REASONS = ["answered", "withdrawn", "worker-stopped", "session-ended"];
21842
22113
  var transitionBase = { session: z43.string(), at: z43.number() };
21843
22114
  var cursorFields = { cursor: z43.string(), sequence: z43.int().positive() };
21844
22115
  var sessionAppearedShape = { kind: z43.literal("session-appeared"), ...transitionBase };
@@ -21899,7 +22170,7 @@ function parseCursor(cursor) {
21899
22170
  function codePointBoundary(text, at) {
21900
22171
  const before = text.charCodeAt(at - 1);
21901
22172
  const after = text.charCodeAt(at);
21902
- const isHigh = before >= HIGH_SURROGATE_FIRST && before <= HIGH_SURROGATE_LAST;
22173
+ const isHigh = before >= HIGH_SURROGATE_FIRST2 && before <= HIGH_SURROGATE_LAST2;
21903
22174
  const isLow = after >= LOW_SURROGATE_FIRST && after <= LOW_SURROGATE_LAST;
21904
22175
  return isHigh && isLow ? at - 1 : at;
21905
22176
  }
@@ -22377,15 +22648,15 @@ function createQuotaExpiringPublisher(hub, deps) {
22377
22648
 
22378
22649
  // src/frontdoor/rcLiveUsage.ts
22379
22650
  var RC_RATE_LIMIT_EVENT_TYPE = "rate_limit_event";
22380
- function isRecord9(value) {
22651
+ function isRecord10(value) {
22381
22652
  return typeof value === "object" && value !== null && !Array.isArray(value);
22382
22653
  }
22383
22654
  function rcRateLimitInfoOf(event) {
22384
22655
  const payload = event.envelope.payload;
22385
- if (!isRecord9(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
22656
+ if (!isRecord10(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
22386
22657
  return void 0;
22387
22658
  }
22388
- if (!isRecord9(payload.rate_limit_info)) {
22659
+ if (!isRecord10(payload.rate_limit_info)) {
22389
22660
  return void 0;
22390
22661
  }
22391
22662
  const parsed = RcRateLimitInfoSchema.safeParse(payload.rate_limit_info);
@@ -22473,7 +22744,7 @@ function createSseParser() {
22473
22744
  }
22474
22745
  };
22475
22746
  }
22476
- function isRecord10(value) {
22747
+ function isRecord11(value) {
22477
22748
  return typeof value === "object" && value !== null && !Array.isArray(value);
22478
22749
  }
22479
22750
  function sequenceNumOf(value) {
@@ -22495,7 +22766,7 @@ function parseRcStreamEnvelope(parsed) {
22495
22766
  } catch {
22496
22767
  return void 0;
22497
22768
  }
22498
- if (!isRecord10(data)) {
22769
+ if (!isRecord11(data)) {
22499
22770
  return void 0;
22500
22771
  }
22501
22772
  const eventType = data.event_type;
@@ -22748,7 +23019,7 @@ function withClientPlatform(payload, headers) {
22748
23019
  const platform = headers[CLIENT_PLATFORM_HEADER];
22749
23020
  return typeof platform === "string" && platform !== "" ? { ...rest, client_platform: platform } : rest;
22750
23021
  }
22751
- function isRecord11(value) {
23022
+ function isRecord12(value) {
22752
23023
  return typeof value === "object" && value !== null && !Array.isArray(value);
22753
23024
  }
22754
23025
  function parseJsonObject2(body) {
@@ -22758,7 +23029,7 @@ function parseJsonObject2(body) {
22758
23029
  } catch {
22759
23030
  return void 0;
22760
23031
  }
22761
- return isRecord11(parsed) ? parsed : void 0;
23032
+ return isRecord12(parsed) ? parsed : void 0;
22762
23033
  }
22763
23034
  function nonEmptyString2(record, field) {
22764
23035
  const value = record === void 0 ? void 0 : record[field];
@@ -22832,7 +23103,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
22832
23103
  }
22833
23104
  const results = [];
22834
23105
  for (const event of events) {
22835
- if (!isRecord11(event) || !isRecord11(event.payload)) {
23106
+ if (!isRecord12(event) || !isRecord12(event.payload)) {
22836
23107
  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
23108
  return true;
22838
23109
  }
@@ -22932,7 +23203,7 @@ async function serveRcCompatSessions(ctx, pathname, compatPath) {
22932
23203
  // src/frontdoor/rcSelfHostConversations.ts
22933
23204
  var RC_CONVERSATIONS_PATH_PREFIX = "/v1/code/conversations";
22934
23205
  var RC_CONVERSATION_ID_PREFIX = "conv_";
22935
- function isRecord12(value) {
23206
+ function isRecord13(value) {
22936
23207
  return typeof value === "object" && value !== null && !Array.isArray(value);
22937
23208
  }
22938
23209
  function parseJsonObject3(body) {
@@ -22942,7 +23213,7 @@ function parseJsonObject3(body) {
22942
23213
  } catch {
22943
23214
  return void 0;
22944
23215
  }
22945
- return isRecord12(parsed) ? parsed : void 0;
23216
+ return isRecord13(parsed) ? parsed : void 0;
22946
23217
  }
22947
23218
  function nonEmptyString3(record, field) {
22948
23219
  const value = record === void 0 ? void 0 : record[field];
@@ -22996,7 +23267,7 @@ async function serveRcConversations(ctx, pathname, method) {
22996
23267
  }
22997
23268
  const results = [];
22998
23269
  for (const event of events) {
22999
- if (!isRecord12(event) || !isRecord12(event.payload)) {
23270
+ if (!isRecord13(event) || !isRecord13(event.payload)) {
23000
23271
  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
23272
  return;
23002
23273
  }
@@ -23028,7 +23299,7 @@ var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:
23028
23299
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
23029
23300
  var MS_PER_SECOND6 = 1e3;
23030
23301
  var HTTP_SERVICE_UNAVAILABLE = 503;
23031
- function isRecord13(value) {
23302
+ function isRecord14(value) {
23032
23303
  return typeof value === "object" && value !== null && !Array.isArray(value);
23033
23304
  }
23034
23305
  function parseJsonObject4(body) {
@@ -23038,7 +23309,7 @@ function parseJsonObject4(body) {
23038
23309
  } catch {
23039
23310
  return void 0;
23040
23311
  }
23041
- return isRecord13(parsed) ? parsed : void 0;
23312
+ return isRecord14(parsed) ? parsed : void 0;
23042
23313
  }
23043
23314
  function growthBookFeatures() {
23044
23315
  return {
@@ -23392,7 +23663,7 @@ var RC_SELF_HOST_WORKER_EPOCH = 1;
23392
23663
  var RC_STREAM_EVENT_NAME2 = "client_event";
23393
23664
  var CONFLICT_REASON_HEADER2 = "x-ccr-conflict-reason";
23394
23665
  var CONFLICT_REASON_EPOCH_STALE = "epoch_stale";
23395
- function isRecord14(value) {
23666
+ function isRecord15(value) {
23396
23667
  return typeof value === "object" && value !== null && !Array.isArray(value);
23397
23668
  }
23398
23669
  function isWebSearchRefusal(value) {
@@ -23476,7 +23747,7 @@ function parseJsonObject5(body) {
23476
23747
  } catch {
23477
23748
  return void 0;
23478
23749
  }
23479
- return isRecord14(parsed) ? parsed : void 0;
23750
+ return isRecord15(parsed) ? parsed : void 0;
23480
23751
  }
23481
23752
  function mintWorkerJwt(randomToken, issuedAt) {
23482
23753
  const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
@@ -23736,7 +24007,7 @@ data: ${JSON.stringify(envelope)}
23736
24007
  if (status !== void 0) {
23737
24008
  session.workerStatus = status;
23738
24009
  }
23739
- if (isRecord14(body?.external_metadata)) {
24010
+ if (isRecord15(body?.external_metadata)) {
23740
24011
  session.externalMetadata = body.external_metadata;
23741
24012
  }
23742
24013
  await answerJson2(response, HTTP_STATUS.ok, {});
@@ -23766,7 +24037,7 @@ data: ${JSON.stringify(envelope)}
23766
24037
  }
23767
24038
  const results = [];
23768
24039
  for (const event of events) {
23769
- if (!isRecord14(event) || !isRecord14(event.payload)) {
24040
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
23770
24041
  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
24042
  return;
23772
24043
  }
@@ -23799,7 +24070,7 @@ data: ${JSON.stringify(envelope)}
23799
24070
  return;
23800
24071
  }
23801
24072
  for (const event of events) {
23802
- if (isRecord14(event)) {
24073
+ if (isRecord15(event)) {
23803
24074
  session.internalEvents.push({ eventId: deps.newUuid(), body: event });
23804
24075
  }
23805
24076
  }
@@ -23895,7 +24166,7 @@ data: ${JSON.stringify(envelope)}
23895
24166
  }
23896
24167
  const results = [];
23897
24168
  for (const event of events) {
23898
- if (!isRecord14(event) || !isRecord14(event.payload)) {
24169
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
23899
24170
  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
24171
  return;
23901
24172
  }
@@ -24033,7 +24304,7 @@ var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
24033
24304
  var RC_SELF_HOST_RECORD_FILE = "credential.json";
24034
24305
  var SELF_HOST_EMAIL = "selfhost@agent-shim.invalid";
24035
24306
  var SELF_HOST_SUBSCRIPTION_TYPE = "max";
24036
- function isRecord15(value) {
24307
+ function isRecord16(value) {
24037
24308
  return typeof value === "object" && value !== null && !Array.isArray(value);
24038
24309
  }
24039
24310
  function readJsonObject(fs17, file) {
@@ -24047,7 +24318,7 @@ function readJsonObject(fs17, file) {
24047
24318
  } catch {
24048
24319
  return void 0;
24049
24320
  }
24050
- return isRecord15(parsed) ? parsed : void 0;
24321
+ return isRecord16(parsed) ? parsed : void 0;
24051
24322
  }
24052
24323
  function readRcSelfHostRecord(fs17, frontdoorDir) {
24053
24324
  const parsed = readJsonObject(fs17, path45.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
@@ -24075,7 +24346,7 @@ function mintRcSelfHostCredential(deps) {
24075
24346
  const recordFile2 = path45.join(recordDir, RC_SELF_HOST_RECORD_FILE);
24076
24347
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
24077
24348
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
24078
- const existingOauth = isRecord15(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
24349
+ const existingOauth = isRecord16(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
24079
24350
  const existingToken = typeof existingOauth?.accessToken === "string" && existingOauth.accessToken !== "" ? existingOauth.accessToken : void 0;
24080
24351
  const existingIsOwn = existingToken !== void 0 && previousRecord?.accessToken === existingToken;
24081
24352
  if (existingToken !== void 0 && !existingIsOwn && !deps.force) {
@@ -24092,7 +24363,7 @@ function mintRcSelfHostCredential(deps) {
24092
24363
  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
24364
  `);
24094
24365
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
24095
- const existingBlock = (value) => isRecord15(value) ? value : {};
24366
+ const existingBlock = (value) => isRecord16(value) ? value : {};
24096
24367
  deps.fs.writeFilePrivate(claudeJsonFile, `${JSON.stringify({
24097
24368
  ...claudeJson,
24098
24369
  oauthAccount: {
@@ -24849,7 +25120,6 @@ export {
24849
25120
  RC_GOAL_CONDITION_MAX_CHARS,
24850
25121
  RC_IDLE_EXPIRY_MS,
24851
25122
  RC_ORPC_PATH_PREFIX,
24852
- RC_PENDING_DEADLINE_MS,
24853
25123
  RC_PENDING_RETIRE_REASONS,
24854
25124
  RC_PERMISSION_MODES,
24855
25125
  RC_READ_FILE_ENCODINGS,