claude-use 11.89.1 → 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";
@@ -7268,30 +7268,30 @@ var init_state2 = __esm({
7268
7268
  });
7269
7269
 
7270
7270
  // src/headroom/earlierRelease.ts
7271
- function withoutOurSocket(commandLine, socketPath) {
7271
+ function withoutOurSocket(commandLine2, socketPath) {
7272
7272
  for (const argument of [`--uds ${socketPath}`, `--uds=${socketPath}`]) {
7273
7273
  let from = 0;
7274
7274
  for (; ; ) {
7275
- const index = commandLine.indexOf(argument, from);
7275
+ const index = commandLine2.indexOf(argument, from);
7276
7276
  if (index === -1) {
7277
7277
  break;
7278
7278
  }
7279
7279
  const end = index + argument.length;
7280
- const startsArgument = index === 0 || /\s/.test(commandLine.charAt(index - 1));
7281
- const endsArgument = end === commandLine.length || /\s/.test(commandLine.charAt(end));
7280
+ const startsArgument = index === 0 || /\s/.test(commandLine2.charAt(index - 1));
7281
+ const endsArgument = end === commandLine2.length || /\s/.test(commandLine2.charAt(end));
7282
7282
  if (startsArgument && endsArgument) {
7283
- return `${commandLine.slice(0, index)} ${commandLine.slice(end)}`;
7283
+ return `${commandLine2.slice(0, index)} ${commandLine2.slice(end)}`;
7284
7284
  }
7285
7285
  from = index + 1;
7286
7286
  }
7287
7287
  }
7288
7288
  return void 0;
7289
7289
  }
7290
- function daemonIdentity(commandLine, socketPath) {
7291
- if (commandLine === void 0) {
7290
+ function daemonIdentity(commandLine2, socketPath) {
7291
+ if (commandLine2 === void 0) {
7292
7292
  return "unreadable";
7293
7293
  }
7294
- const rest = withoutOurSocket(commandLine, socketPath);
7294
+ const rest = withoutOurSocket(commandLine2, socketPath);
7295
7295
  const argumentsList = rest === void 0 ? [] : rest.trim().split(/\s+/);
7296
7296
  if (rest === void 0 || !argumentsList.includes("proxy")) {
7297
7297
  return "not-headroom";
@@ -7390,8 +7390,8 @@ function ensureHeadroom(params) {
7390
7390
  writeSession(ports.fs, paths.headroomSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), supervisorPid: state.supervisorPid });
7391
7391
  return { socketPath: state.socketPath };
7392
7392
  }
7393
- const commandLine = commandLineOf(state.headroomPid);
7394
- const earlierRelease = earlierReleaseDaemon(ports.fs, paths, { commandLine, socketPath: state.socketPath, recordedHash: state.allowlistHash });
7393
+ const commandLine2 = commandLineOf(state.headroomPid);
7394
+ const earlierRelease = earlierReleaseDaemon(ports.fs, paths, { commandLine: commandLine2, socketPath: state.socketPath, recordedHash: state.allowlistHash });
7395
7395
  if (earlierRelease !== void 0) {
7396
7396
  if (earlierRelease.admitsServingDoor) {
7397
7397
  writeSession(ports.fs, paths.headroomSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), supervisorPid: state.supervisorPid });
@@ -7401,7 +7401,7 @@ function ensureHeadroom(params) {
7401
7401
  `the running headroom daemon (pid ${String(state.headroomPid)}) was ${EARLIER_RELEASE_ALLOWLIST}, and its allowlist cannot be shown to admit the serving front door; launch with --no-headroom until then. Supervisor and daemon log: ${paths.headroomLogPath}`
7402
7402
  );
7403
7403
  }
7404
- awaiting = { daemonPid: state.headroomPid, identity: daemonIdentity(commandLine, state.socketPath) };
7404
+ awaiting = { daemonPid: state.headroomPid, identity: daemonIdentity(commandLine2, state.socketPath) };
7405
7405
  }
7406
7406
  if (state.lastError !== void 0) {
7407
7407
  throw new HeadroomStartError(
@@ -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.89.1",
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>",
@@ -10838,7 +10838,7 @@ var init_paths = __esm({
10838
10838
  });
10839
10839
 
10840
10840
  // src/providerAliases.ts
10841
- import { z as z24 } from "zod";
10841
+ import { z as z25 } from "zod";
10842
10842
  function parseAliases(file, raw) {
10843
10843
  const parsed = ProviderAliasesSchema.safeParse(raw);
10844
10844
  if (!parsed.success) {
@@ -10877,7 +10877,7 @@ var init_providerAliases = __esm({
10877
10877
  init_cliError();
10878
10878
  init_load();
10879
10879
  init_store();
10880
- ProviderAliasesSchema = z24.record(z24.string().min(1), z24.string().min(1));
10880
+ ProviderAliasesSchema = z25.record(z25.string().min(1), z25.string().min(1));
10881
10881
  }
10882
10882
  });
10883
10883
 
@@ -11102,14 +11102,14 @@ function requireProviderExists(paths, name) {
11102
11102
  throw new ProviderNotFoundError(name);
11103
11103
  }
11104
11104
  }
11105
- function isRecord7(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 (!isRecord7(raw) || "credential" in raw) {
11109
+ if (!isRecord9(raw) || "credential" in raw) {
11110
11110
  return void 0;
11111
11111
  }
11112
- const env = isRecord7(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";
11595
- import { z as z25 } from "zod";
11594
+ import { createHash as createHash9 } from "node:crypto";
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];
@@ -11685,7 +11685,7 @@ var init_injected = __esm({
11685
11685
  INJECTED_ENV = "AGENT_SHIM_INJECTED";
11686
11686
  CUSTOM_HEADERS_ENV = "ANTHROPIC_CUSTOM_HEADERS";
11687
11687
  HEADER_KEY_PREFIX = `${CUSTOM_HEADERS_ENV}:`;
11688
- InjectedSchema = z25.record(z25.string(), z25.string());
11688
+ InjectedSchema = z26.record(z26.string(), z26.string());
11689
11689
  }
11690
11690
  });
11691
11691
 
@@ -11821,7 +11821,7 @@ var init_commandDeps = __esm({
11821
11821
  // src/claudeShim.ts
11822
11822
  import fs11 from "node:fs";
11823
11823
  import path38 from "node:path";
11824
- import { z as z30 } from "zod";
11824
+ import { z as z31 } from "zod";
11825
11825
  function commandFilename(ownExecutablePath, commandName) {
11826
11826
  return ownExecutablePath.toLowerCase().endsWith(".exe") ? `${commandName}.exe` : commandName;
11827
11827
  }
@@ -11871,35 +11871,35 @@ var init_claudeShim = __esm({
11871
11871
  init_store();
11872
11872
  init_realPorts();
11873
11873
  init_cliError();
11874
- ClaudeShimStateSchema = z30.strictObject({
11875
- targetPath: z30.string().min(1),
11876
- method: z30.enum(["hardlink", "copy"]),
11877
- installedAtMs: z30.number()
11874
+ ClaudeShimStateSchema = z31.strictObject({
11875
+ targetPath: z31.string().min(1),
11876
+ method: z31.enum(["hardlink", "copy"]),
11877
+ installedAtMs: z31.number()
11878
11878
  });
11879
11879
  nodeLinkFs = { link: fs11.linkSync, copyFile: fs11.copyFileSync, chmod: fs11.chmodSync };
11880
11880
  }
11881
11881
  });
11882
11882
 
11883
11883
  // src/codex/auth.ts
11884
- import { z as z31 } from "zod";
11884
+ import { z as z32 } from "zod";
11885
11885
  var AuthFileSchema, TokenGrantSchema, CodexAuthError;
11886
11886
  var init_auth = __esm({
11887
11887
  "src/codex/auth.ts"() {
11888
11888
  "use strict";
11889
- AuthFileSchema = z31.looseObject({
11890
- tokens: z31.looseObject({
11891
- access_token: z31.string().optional(),
11892
- refresh_token: z31.string().optional(),
11893
- id_token: z31.string().optional(),
11894
- account_id: z31.string().optional()
11889
+ AuthFileSchema = z32.looseObject({
11890
+ tokens: z32.looseObject({
11891
+ access_token: z32.string().optional(),
11892
+ refresh_token: z32.string().optional(),
11893
+ id_token: z32.string().optional(),
11894
+ account_id: z32.string().optional()
11895
11895
  }).nullish(),
11896
- last_refresh: z31.string().optional()
11896
+ last_refresh: z32.string().optional()
11897
11897
  });
11898
- TokenGrantSchema = z31.looseObject({
11899
- access_token: z31.string().min(1).optional(),
11900
- refresh_token: z31.string().min(1).optional(),
11901
- id_token: z31.string().min(1).optional(),
11902
- account_id: z31.string().min(1).optional()
11898
+ TokenGrantSchema = z32.looseObject({
11899
+ access_token: z32.string().min(1).optional(),
11900
+ refresh_token: z32.string().min(1).optional(),
11901
+ id_token: z32.string().min(1).optional(),
11902
+ account_id: z32.string().min(1).optional()
11903
11903
  });
11904
11904
  CodexAuthError = class extends Error {
11905
11905
  constructor(message) {
@@ -11911,7 +11911,7 @@ var init_auth = __esm({
11911
11911
  });
11912
11912
 
11913
11913
  // src/codex/siwc.ts
11914
- import { z as z32 } from "zod";
11914
+ import { z as z33 } from "zod";
11915
11915
  var SIWC_RESOURCE, SIWC_RESPONSES_URL, SIWC_PLAN_SCOPE, TokenResponseSchema, JwtHeaderSchema, IdTokenClaimsSchema, JwksSchema;
11916
11916
  var init_siwc = __esm({
11917
11917
  "src/codex/siwc.ts"() {
@@ -11919,28 +11919,28 @@ var init_siwc = __esm({
11919
11919
  SIWC_RESOURCE = "https://api.openai.com/v1";
11920
11920
  SIWC_RESPONSES_URL = `${SIWC_RESOURCE}/responses`;
11921
11921
  SIWC_PLAN_SCOPE = "chatgpt.tokens.use.direct";
11922
- TokenResponseSchema = z32.looseObject({
11923
- access_token: z32.string().min(1),
11924
- refresh_token: z32.string().min(1).optional(),
11925
- id_token: z32.string().min(1).optional(),
11926
- expires_in: z32.number().positive(),
11927
- scope: z32.string().optional()
11922
+ TokenResponseSchema = z33.looseObject({
11923
+ access_token: z33.string().min(1),
11924
+ refresh_token: z33.string().min(1).optional(),
11925
+ id_token: z33.string().min(1).optional(),
11926
+ expires_in: z33.number().positive(),
11927
+ scope: z33.string().optional()
11928
11928
  });
11929
- JwtHeaderSchema = z32.looseObject({ alg: z32.string(), kid: z32.string().optional() });
11930
- IdTokenClaimsSchema = z32.looseObject({
11931
- iss: z32.string(),
11932
- sub: z32.string().min(1),
11933
- aud: z32.union([z32.string(), z32.array(z32.string())]),
11934
- exp: z32.number(),
11935
- nonce: z32.string().optional(),
11936
- email: z32.string().optional()
11929
+ JwtHeaderSchema = z33.looseObject({ alg: z33.string(), kid: z33.string().optional() });
11930
+ IdTokenClaimsSchema = z33.looseObject({
11931
+ iss: z33.string(),
11932
+ sub: z33.string().min(1),
11933
+ aud: z33.union([z33.string(), z33.array(z33.string())]),
11934
+ exp: z33.number(),
11935
+ nonce: z33.string().optional(),
11936
+ email: z33.string().optional()
11937
11937
  });
11938
- JwksSchema = z32.object({ keys: z32.array(z32.looseObject({ kid: z32.string().optional(), kty: z32.string() })) });
11938
+ JwksSchema = z33.object({ keys: z33.array(z33.looseObject({ kid: z33.string().optional(), kty: z33.string() })) });
11939
11939
  }
11940
11940
  });
11941
11941
 
11942
11942
  // src/codex/siwcStore.ts
11943
- import { z as z33 } from "zod";
11943
+ import { z as z34 } from "zod";
11944
11944
  function parseSiwcFile(raw, filePath) {
11945
11945
  let json;
11946
11946
  try {
@@ -11960,18 +11960,18 @@ var init_siwcStore = __esm({
11960
11960
  "use strict";
11961
11961
  init_auth();
11962
11962
  init_siwc();
11963
- SiwcGrantSchema = z33.strictObject({
11964
- clientId: z33.string().min(1),
11965
- sub: z33.string().min(1),
11966
- email: z33.string().optional(),
11967
- idToken: z33.string().min(1),
11968
- accessToken: z33.string().min(1),
11969
- refreshToken: z33.string().min(1),
11970
- scopes: z33.array(z33.string()).readonly(),
11963
+ SiwcGrantSchema = z34.strictObject({
11964
+ clientId: z34.string().min(1),
11965
+ sub: z34.string().min(1),
11966
+ email: z34.string().optional(),
11967
+ idToken: z34.string().min(1),
11968
+ accessToken: z34.string().min(1),
11969
+ refreshToken: z34.string().min(1),
11970
+ scopes: z34.array(z34.string()).readonly(),
11971
11971
  /** When the access token stops working, in milliseconds since the epoch. */
11972
- expiresAt: z33.number()
11972
+ expiresAt: z34.number()
11973
11973
  });
11974
- SiwcFileSchema = z33.strictObject({ registeredClientId: z33.string().min(1).optional(), grant: SiwcGrantSchema.optional() });
11974
+ SiwcFileSchema = z34.strictObject({ registeredClientId: z34.string().min(1).optional(), grant: SiwcGrantSchema.optional() });
11975
11975
  }
11976
11976
  });
11977
11977
 
@@ -12029,9 +12029,9 @@ 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
- import { z as z34 } from "zod";
12034
+ import { z as z35 } from "zod";
12035
12035
  function parseCatalogueBinding(raw) {
12036
12036
  if (raw === void 0) return void 0;
12037
12037
  try {
@@ -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;
@@ -12072,7 +12072,7 @@ var init_catalogueCredential = __esm({
12072
12072
  "src/codex/catalogueCredential.ts"() {
12073
12073
  "use strict";
12074
12074
  init_siwcStore();
12075
- CatalogueBindingSchema = z34.strictObject({ fingerprint: z34.string().min(1), source: z34.string().min(1), revision: z34.string().min(1) });
12075
+ CatalogueBindingSchema = z35.strictObject({ fingerprint: z35.string().min(1), source: z35.string().min(1), revision: z35.string().min(1) });
12076
12076
  }
12077
12077
  });
12078
12078
 
@@ -12123,64 +12123,64 @@ var init_signatures = __esm({
12123
12123
  });
12124
12124
 
12125
12125
  // src/codex/anthropic.ts
12126
- import { z as z35 } from "zod";
12126
+ import { z as z36 } from "zod";
12127
12127
  var TextBlockSchema, Base64ImageSourceSchema, UrlImageSourceSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultContentBlockSchema, ToolResultBlockSchema, OtherBlockSchema, ContentBlockSchema, MessageSchema, ToolSchema, ToolChoiceSchema, SystemSchema, MessagesRequestSchema, CountTokensRequestSchema;
12128
12128
  var init_anthropic = __esm({
12129
12129
  "src/codex/anthropic.ts"() {
12130
12130
  "use strict";
12131
- TextBlockSchema = z35.looseObject({ type: z35.literal("text"), text: z35.string() });
12132
- Base64ImageSourceSchema = z35.looseObject({ type: z35.literal("base64"), media_type: z35.string().min(1), data: z35.string() });
12133
- UrlImageSourceSchema = z35.looseObject({ type: z35.literal("url"), url: z35.string().min(1) });
12134
- ImageBlockSchema = z35.looseObject({
12135
- type: z35.literal("image"),
12136
- source: z35.union([Base64ImageSourceSchema, UrlImageSourceSchema])
12131
+ TextBlockSchema = z36.looseObject({ type: z36.literal("text"), text: z36.string() });
12132
+ Base64ImageSourceSchema = z36.looseObject({ type: z36.literal("base64"), media_type: z36.string().min(1), data: z36.string() });
12133
+ UrlImageSourceSchema = z36.looseObject({ type: z36.literal("url"), url: z36.string().min(1) });
12134
+ ImageBlockSchema = z36.looseObject({
12135
+ type: z36.literal("image"),
12136
+ source: z36.union([Base64ImageSourceSchema, UrlImageSourceSchema])
12137
12137
  });
12138
- ToolUseBlockSchema = z35.looseObject({
12139
- type: z35.literal("tool_use"),
12140
- id: z35.string().min(1),
12141
- name: z35.string().min(1),
12142
- input: z35.unknown()
12138
+ ToolUseBlockSchema = z36.looseObject({
12139
+ type: z36.literal("tool_use"),
12140
+ id: z36.string().min(1),
12141
+ name: z36.string().min(1),
12142
+ input: z36.unknown()
12143
12143
  });
12144
- ToolResultContentBlockSchema = z35.union([TextBlockSchema, z35.looseObject({ type: z35.string() })]);
12145
- ToolResultBlockSchema = z35.looseObject({
12146
- type: z35.literal("tool_result"),
12147
- tool_use_id: z35.string().min(1),
12148
- content: z35.union([z35.string(), z35.array(ToolResultContentBlockSchema)]).optional()
12144
+ ToolResultContentBlockSchema = z36.union([TextBlockSchema, z36.looseObject({ type: z36.string() })]);
12145
+ ToolResultBlockSchema = z36.looseObject({
12146
+ type: z36.literal("tool_result"),
12147
+ tool_use_id: z36.string().min(1),
12148
+ content: z36.union([z36.string(), z36.array(ToolResultContentBlockSchema)]).optional()
12149
12149
  });
12150
- OtherBlockSchema = z35.looseObject({ type: z35.string() });
12151
- ContentBlockSchema = z35.union([TextBlockSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultBlockSchema, OtherBlockSchema]);
12152
- MessageSchema = z35.looseObject({
12153
- role: z35.enum(["user", "assistant", "system"]),
12154
- content: z35.union([z35.string(), z35.array(ContentBlockSchema)])
12150
+ OtherBlockSchema = z36.looseObject({ type: z36.string() });
12151
+ ContentBlockSchema = z36.union([TextBlockSchema, ImageBlockSchema, ToolUseBlockSchema, ToolResultBlockSchema, OtherBlockSchema]);
12152
+ MessageSchema = z36.looseObject({
12153
+ role: z36.enum(["user", "assistant", "system"]),
12154
+ content: z36.union([z36.string(), z36.array(ContentBlockSchema)])
12155
12155
  });
12156
- ToolSchema = z35.looseObject({
12157
- name: z35.string().min(1),
12158
- description: z35.string().optional(),
12159
- input_schema: z35.record(z35.string(), z35.unknown()).optional(),
12160
- allowed_domains: z35.array(z35.string()).optional(),
12161
- blocked_domains: z35.array(z35.string()).optional()
12156
+ ToolSchema = z36.looseObject({
12157
+ name: z36.string().min(1),
12158
+ description: z36.string().optional(),
12159
+ input_schema: z36.record(z36.string(), z36.unknown()).optional(),
12160
+ allowed_domains: z36.array(z36.string()).optional(),
12161
+ blocked_domains: z36.array(z36.string()).optional()
12162
12162
  });
12163
- ToolChoiceSchema = z35.union([
12164
- z35.looseObject({ type: z35.enum(["auto", "none", "any"]) }),
12165
- z35.looseObject({ type: z35.literal("tool"), name: z35.string().min(1) })
12163
+ ToolChoiceSchema = z36.union([
12164
+ z36.looseObject({ type: z36.enum(["auto", "none", "any"]) }),
12165
+ z36.looseObject({ type: z36.literal("tool"), name: z36.string().min(1) })
12166
12166
  ]);
12167
- SystemSchema = z35.union([z35.string(), z35.array(z35.union([TextBlockSchema, OtherBlockSchema]))]);
12168
- MessagesRequestSchema = z35.looseObject({
12169
- model: z35.string().optional(),
12167
+ SystemSchema = z36.union([z36.string(), z36.array(z36.union([TextBlockSchema, OtherBlockSchema]))]);
12168
+ MessagesRequestSchema = z36.looseObject({
12169
+ model: z36.string().optional(),
12170
12170
  system: SystemSchema.optional(),
12171
- messages: z35.array(MessageSchema),
12172
- tools: z35.array(ToolSchema).optional(),
12171
+ messages: z36.array(MessageSchema),
12172
+ tools: z36.array(ToolSchema).optional(),
12173
12173
  tool_choice: ToolChoiceSchema.optional(),
12174
- stream: z35.boolean().optional(),
12174
+ stream: z36.boolean().optional(),
12175
12175
  /** `user_id` is stable for one Claude Code session and differs between sessions, which is what makes it the right key for both the backend's prompt cache and its session header. */
12176
- metadata: z35.looseObject({ user_id: z35.string().optional() }).optional(),
12176
+ metadata: z36.looseObject({ user_id: z36.string().optional() }).optional(),
12177
12177
  /** Claude Code's effort setting. Any string is accepted; the translator honours only the levels the backend understands. */
12178
- output_config: z35.looseObject({ effort: z35.string().optional(), format: z35.object({ type: z35.literal("json_schema"), schema: z35.record(z35.string(), z35.unknown()) }).optional() }).optional()
12178
+ output_config: z36.looseObject({ effort: z36.string().optional(), format: z36.object({ type: z36.literal("json_schema"), schema: z36.record(z36.string(), z36.unknown()) }).optional() }).optional()
12179
12179
  });
12180
- CountTokensRequestSchema = z35.looseObject({
12181
- system: z35.unknown().optional(),
12182
- messages: z35.unknown().optional(),
12183
- tools: z35.unknown().optional()
12180
+ CountTokensRequestSchema = z36.looseObject({
12181
+ system: z36.unknown().optional(),
12182
+ messages: z36.unknown().optional(),
12183
+ tools: z36.unknown().optional()
12184
12184
  });
12185
12185
  }
12186
12186
  });
@@ -13534,7 +13534,7 @@ function withLauncherSettings(passthrough, settings) {
13534
13534
  }
13535
13535
  return [...kept, "--settings", settings, ...tail];
13536
13536
  }
13537
- function isRecord15(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 (!isRecord15(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);
@@ -15227,7 +15227,7 @@ var init_identityClaude = __esm({
15227
15227
  });
15228
15228
 
15229
15229
  // src/usage/providerQuota.ts
15230
- import { z as z44 } from "zod";
15230
+ import { z as z45 } from "zod";
15231
15231
  var MS_PER_SECOND9, SECONDS_PER_HOUR3, HOURS_PER_DAY6, DAYS_PER_MONTH, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZaiLimitSchema, ZaiResponseSchema, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, ANTIGRAVITY_HOST, ANTIGRAVITY_QUOTA_URL, ANTIGRAVITY_USER_URL, FIVE_HOURS2, DAYS_PER_WEEK2, FIVE_HOURS_MS, WEEK_MS, AntigravityBucketSchema, AntigravitySummarySchema, GoogleTokenInfoSchema, AntigravityUserSchema;
15232
15232
  var init_providerQuota = __esm({
15233
15233
  "src/usage/providerQuota.ts"() {
@@ -15246,35 +15246,35 @@ var init_providerQuota = __esm({
15246
15246
  [ZAI_UNIT_HOURS, SECONDS_PER_HOUR3 * MS_PER_SECOND9],
15247
15247
  [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9]
15248
15248
  ]);
15249
- ZaiLimitSchema = z44.object({
15250
- type: z44.string(),
15251
- unit: z44.number().int(),
15252
- number: z44.number().int().positive(),
15253
- percentage: z44.number().nonnegative(),
15254
- nextResetTime: z44.number().positive().optional(),
15255
- usage: z44.number().nonnegative().optional(),
15256
- currentValue: z44.number().nonnegative().optional(),
15257
- remaining: z44.number().nonnegative().optional()
15249
+ ZaiLimitSchema = z45.object({
15250
+ type: z45.string(),
15251
+ unit: z45.number().int(),
15252
+ number: z45.number().int().positive(),
15253
+ percentage: z45.number().nonnegative(),
15254
+ nextResetTime: z45.number().positive().optional(),
15255
+ usage: z45.number().nonnegative().optional(),
15256
+ currentValue: z45.number().nonnegative().optional(),
15257
+ remaining: z45.number().nonnegative().optional()
15258
15258
  });
15259
- ZaiResponseSchema = z44.object({
15260
- success: z44.boolean(),
15261
- msg: z44.string().optional(),
15262
- data: z44.object({ level: z44.string().optional(), limits: z44.array(ZaiLimitSchema) })
15259
+ ZaiResponseSchema = z45.object({
15260
+ success: z45.boolean(),
15261
+ msg: z45.string().optional(),
15262
+ data: z45.object({ level: z45.string().optional(), limits: z45.array(ZaiLimitSchema) })
15263
15263
  });
15264
15264
  OPENROUTER_HOST = "openrouter.ai";
15265
15265
  OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
15266
15266
  OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
15267
15267
  MS_PER_DAY2 = HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15268
- OpenRouterKeySchema = z44.object({
15269
- data: z44.object({
15270
- limit: z44.number().nonnegative().nullable(),
15271
- limit_remaining: z44.number().nullable(),
15272
- limit_reset: z44.string().nullable(),
15273
- is_free_tier: z44.boolean().optional(),
15274
- free_model_daily_requests: z44.object({ used: z44.number().nonnegative(), limit: z44.number().nonnegative(), remaining: z44.number() }).optional()
15268
+ OpenRouterKeySchema = z45.object({
15269
+ data: z45.object({
15270
+ limit: z45.number().nonnegative().nullable(),
15271
+ limit_remaining: z45.number().nullable(),
15272
+ limit_reset: z45.string().nullable(),
15273
+ is_free_tier: z45.boolean().optional(),
15274
+ free_model_daily_requests: z45.object({ used: z45.number().nonnegative(), limit: z45.number().nonnegative(), remaining: z45.number() }).optional()
15275
15275
  })
15276
15276
  });
15277
- OpenRouterCreditsSchema = z44.object({ data: z44.object({ total_credits: z44.number().nonnegative(), total_usage: z44.number().nonnegative() }) });
15277
+ OpenRouterCreditsSchema = z45.object({ data: z45.object({ total_credits: z45.number().nonnegative(), total_usage: z45.number().nonnegative() }) });
15278
15278
  ANTIGRAVITY_HOST = "daily-cloudcode-pa.googleapis.com";
15279
15279
  ANTIGRAVITY_QUOTA_URL = `https://${ANTIGRAVITY_HOST}/v1internal:retrieveUserQuotaSummary`;
15280
15280
  ANTIGRAVITY_USER_URL = `https://${ANTIGRAVITY_HOST}/v1internal:loadCodeAssist`;
@@ -15282,21 +15282,21 @@ var init_providerQuota = __esm({
15282
15282
  DAYS_PER_WEEK2 = 7;
15283
15283
  FIVE_HOURS_MS = FIVE_HOURS2 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15284
15284
  WEEK_MS = DAYS_PER_WEEK2 * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15285
- AntigravityBucketSchema = z44.object({
15286
- bucketId: z44.string(),
15287
- remainingFraction: z44.number().optional(),
15288
- resetTime: z44.string().optional()
15285
+ AntigravityBucketSchema = z45.object({
15286
+ bucketId: z45.string(),
15287
+ remainingFraction: z45.number().optional(),
15288
+ resetTime: z45.string().optional()
15289
15289
  });
15290
- AntigravitySummarySchema = z44.object({ groups: z44.array(z44.object({ buckets: z44.array(AntigravityBucketSchema) })) });
15291
- GoogleTokenInfoSchema = z44.object({
15292
- email: z44.string().optional(),
15293
- sub: z44.string().optional()
15290
+ AntigravitySummarySchema = z45.object({ groups: z45.array(z45.object({ buckets: z45.array(AntigravityBucketSchema) })) });
15291
+ GoogleTokenInfoSchema = z45.object({
15292
+ email: z45.string().optional(),
15293
+ sub: z45.string().optional()
15294
15294
  });
15295
- AntigravityUserSchema = z44.object({
15295
+ AntigravityUserSchema = z45.object({
15296
15296
  /** The code-assist tier context, which defaults to the free tier for every account. */
15297
- currentTier: z44.object({ name: z44.string().optional(), id: z44.string().optional() }).optional(),
15297
+ currentTier: z45.object({ name: z45.string().optional(), id: z45.string().optional() }).optional(),
15298
15298
  /** The account's paid subscription; absent when the account has none. */
15299
- paidTier: z44.object({ name: z44.string().optional(), id: z44.string().optional() }).optional()
15299
+ paidTier: z45.object({ name: z45.string().optional(), id: z45.string().optional() }).optional()
15300
15300
  });
15301
15301
  }
15302
15302
  });
@@ -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
+ }
15982
+ }
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
+ }
15818
15993
  }
15819
- return { controlRequests, answeredRequestIds, idleSeconds: void 0, workerStatus: void 0, payloads };
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"),
@@ -15949,9 +16126,11 @@ function createRcSessionTracker(deps) {
15949
16126
  if (id?.startsWith(RC_SESSION_ID_PREFIX) !== true) {
15950
16127
  return void 0;
15951
16128
  }
16129
+ const isClientWrite = method === "POST" && (rest === `${id}/events` || rest === `${id}/teleport-events`);
16130
+ const sessionFacts = isClientWrite ? { ...facts, anthropicClientPlatform: void 0 } : facts;
15952
16131
  const tracked = entries.get(id);
15953
16132
  if (tracked !== void 0) {
15954
- refresh(tracked, facts);
16133
+ refresh(tracked, sessionFacts);
15955
16134
  }
15956
16135
  const bodyKind = method === "POST" && rest === `${id}/worker/events` ? "worker-events" : method === "POST" && rest === `${id}/events` ? "client-events" : method === "POST" && rest === `${id}/worker/heartbeat` ? "heartbeat" : method === "PUT" && rest === `${id}/worker` ? "worker-registration" : void 0;
15957
16136
  let chunks = [];
@@ -15973,11 +16152,14 @@ function createRcSessionTracker(deps) {
15973
16152
  }
15974
16153
  const now = deps.now();
15975
16154
  for (const controlRequest of factsOfBody.controlRequests) {
15976
- addPending(entryNow, { sessionId: id, ...controlRequest, observedAt: now });
16155
+ addPending(entryNow, controlRequest, now);
15977
16156
  }
15978
16157
  for (const requestId of factsOfBody.answeredRequestIds) {
15979
16158
  retirePending(entryNow, requestId, "answered");
15980
16159
  }
16160
+ for (const requestId of factsOfBody.withdrawnRequestIds) {
16161
+ retirePending(entryNow, requestId, "withdrawn");
16162
+ }
15981
16163
  for (const payload of factsOfBody.payloads) {
15982
16164
  entryNow.liveTasks = applyAgentTaskEvent(entryNow.liveTasks, id, payload, now);
15983
16165
  noteInit(entryNow, payload);
@@ -15993,6 +16175,17 @@ function createRcSessionTracker(deps) {
15993
16175
  deps.onTransition?.({ kind: "worker-state", session: id, state: factsOfBody.workerStatus, ...previous === void 0 ? {} : { previous }, at: now });
15994
16176
  }
15995
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
+ }
15996
16189
  };
15997
16190
  const archiving = method === "POST" && rest === `${id}/archive`;
15998
16191
  return {
@@ -16021,7 +16214,7 @@ function createRcSessionTracker(deps) {
16021
16214
  }
16022
16215
  accepted = isSuccessful(status);
16023
16216
  if (accepted && !entries.has(id)) {
16024
- persistCredential(birth(id, facts));
16217
+ persistCredential(birth(id, sessionFacts));
16025
16218
  }
16026
16219
  file();
16027
16220
  },
@@ -16032,7 +16225,7 @@ function createRcSessionTracker(deps) {
16032
16225
  };
16033
16226
  };
16034
16227
  const summaryOf2 = ({ id, createdAt, lastSeenAt }) => ({ id, createdAt, lastSeenAt });
16035
- 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 });
16036
16229
  const sortedEntries = () => [...entries.values()].sort((left, right) => left.createdAt - right.createdAt || (left.id < right.id ? -1 : 1));
16037
16230
  const pendingSorted = (entry) => [...entry.pending.values()].sort((left, right) => left.observedAt - right.observedAt || (left.requestId < right.requestId ? -1 : 1)).map(pendingSummaryOf);
16038
16231
  return {
@@ -16050,7 +16243,8 @@ function createRcSessionTracker(deps) {
16050
16243
  pending: pendingSorted(entry),
16051
16244
  ...entry.identity === void 0 ? {} : { identity: entry.identity },
16052
16245
  ...entry.model === void 0 ? {} : { model: entry.model },
16053
- ...entry.cwd === void 0 ? {} : { cwd: entry.cwd }
16246
+ ...entry.cwd === void 0 ? {} : { cwd: entry.cwd },
16247
+ ...entry.droppedPending === 0 ? {} : { pendingDropped: entry.droppedPending }
16054
16248
  }));
16055
16249
  },
16056
16250
  pendingOf: (sessionId) => {
@@ -16088,7 +16282,7 @@ function createRcSessionTracker(deps) {
16088
16282
  return;
16089
16283
  }
16090
16284
  entry.sequenceNum = entry.sequenceNum === void 0 || event.sequence_num > entry.sequenceNum ? event.sequence_num : entry.sequenceNum;
16091
- if (!isRecord4(event.payload)) {
16285
+ if (!isRecord5(event.payload)) {
16092
16286
  return;
16093
16287
  }
16094
16288
  entry.liveTasks = applyAgentTaskEvent(entry.liveTasks, sessionId, event.payload, deps.now());
@@ -16096,13 +16290,18 @@ function createRcSessionTracker(deps) {
16096
16290
  const pending = pendingOfControlRequestPayload(event.payload);
16097
16291
  if (pending !== void 0) {
16098
16292
  if (event.source === RC_STREAM_WORKER_SOURCE) {
16099
- addPending(entry, { sessionId, ...pending, observedAt: deps.now() });
16293
+ addPending(entry, pending, deps.now());
16100
16294
  }
16101
16295
  return;
16102
16296
  }
16103
16297
  for (const requestId of answeredRequestIdsOfControlResponsePayload(event.payload)) {
16104
16298
  retirePending(entry, requestId, "answered");
16105
16299
  }
16300
+ if (event.source === RC_STREAM_WORKER_SOURCE) {
16301
+ for (const requestId of withdrawnRequestIdsOfControlCancelPayload(event.payload)) {
16302
+ retirePending(entry, requestId, "withdrawn");
16303
+ }
16304
+ }
16106
16305
  },
16107
16306
  liveTasksOf: (sessionId) => {
16108
16307
  sweep();
@@ -16114,6 +16313,17 @@ function createRcSessionTracker(deps) {
16114
16313
  retirePending(entry, requestId, "answered");
16115
16314
  }
16116
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,
16117
16327
  close: () => {
16118
16328
  clearInterval(timer);
16119
16329
  deps.onClose?.();
@@ -16280,8 +16490,8 @@ async function injectRcUserMessage(deps, sessionId, text) {
16280
16490
  }
16281
16491
  return result;
16282
16492
  }
16283
- function buildRcControlResponsePayload(requestId, decision) {
16284
- 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 ?? "" };
16285
16495
  return { type: "control_response", response: { subtype: "success", request_id: requestId, response: result } };
16286
16496
  }
16287
16497
  var RC_PERMISSION_MODES = ["default", "acceptEdits", "bypassPermissions", "plan", "dontAsk", "auto"];
@@ -16338,6 +16548,27 @@ function buildRcMcpOAuthCallbackUrlPayload(requestId, serverName, callbackUrl) {
16338
16548
  function buildRcKeepAlivePayload() {
16339
16549
  return { type: "keep_alive" };
16340
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
+ }
16341
16572
  async function answerRcControlRequest(deps, sessionId, requestId, decision) {
16342
16573
  const credential = deps.credentialOf(sessionId);
16343
16574
  if (credential === void 0) {
@@ -16346,15 +16577,26 @@ async function answerRcControlRequest(deps, sessionId, requestId, decision) {
16346
16577
  if (credential.authorization === void 0) {
16347
16578
  return noOAuthCredentialResult(sessionId);
16348
16579
  }
16349
- if (!deps.pendingOf(sessionId).some((pending) => pending.requestId === requestId)) {
16350
- 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 };
16587
+ }
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` };
16351
16591
  }
16352
- const body = JSON.stringify(buildRcEventWriteBody(buildRcControlResponsePayload(requestId, decision)));
16592
+ const body = JSON.stringify(buildRcEventWriteBody(buildRcControlResponsePayload(requestId, decision, updatedInput?.input)));
16353
16593
  let answer;
16354
16594
  try {
16355
16595
  answer = await deps.dial.writeEvents(sessionId, rcWriteHeaders(credential), body);
16356
16596
  } catch (error) {
16357
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();
16358
16600
  }
16359
16601
  const result = rcEventWriteResultFromAnswer(answer);
16360
16602
  if (result.ok) {
@@ -16484,6 +16726,198 @@ init_legacy();
16484
16726
  // src/frontdoor/rcControl.ts
16485
16727
  import * as https from "node:https";
16486
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
16487
16921
  var RC_PERMISSION_MODE_LIST = RC_PERMISSION_MODES.join(", ");
16488
16922
  var CONTROL_PATH_PREFIX = "/__agent-shim/rc";
16489
16923
  var CONTROL_BODY_CAP_BYTES = 10485760;
@@ -16740,11 +17174,20 @@ function createRcControlHandler(deps) {
16740
17174
  return;
16741
17175
  }
16742
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
+ }
16743
17186
  if (parsed.approve && text !== void 0 && text !== "") {
16744
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" });
16745
17188
  return;
16746
17189
  }
16747
- 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 } });
16748
17191
  if (result.ok) {
16749
17192
  answerJson(response, HTTP_STATUS.ok, { session: parsed.session, request: parsed.request, sequenceNums: result.sequenceNums });
16750
17193
  return;
@@ -16866,6 +17309,9 @@ function isRcSessionStatus(value) {
16866
17309
  if ("workerState" in value && value.workerState !== void 0 && !isRcWorkerFact(value.workerState, (candidate) => typeof candidate === "string")) {
16867
17310
  return false;
16868
17311
  }
17312
+ if ("pendingDropped" in value && value.pendingDropped !== void 0 && typeof value.pendingDropped !== "number") {
17313
+ return false;
17314
+ }
16869
17315
  if ("workerIdleSeconds" in value && value.workerIdleSeconds !== void 0 && !isRcWorkerFact(value.workerIdleSeconds, (candidate) => typeof candidate === "number")) {
16870
17316
  return false;
16871
17317
  }
@@ -16875,13 +17321,7 @@ function isRcSessionStatus(value) {
16875
17321
  return value.pending.every((candidate) => isRcPendingRequestSummary(candidate));
16876
17322
  }
16877
17323
  function isRcPendingRequestSummary(value) {
16878
- if (typeof value !== "object" || value === null) {
16879
- return false;
16880
- }
16881
- if (!("sessionId" in value) || !("requestId" in value) || !("type" in value) || !("summary" in value) || !("observedAt" in value)) {
16882
- return false;
16883
- }
16884
- 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;
16885
17325
  }
16886
17326
  function sequenceNumsOfBody(body) {
16887
17327
  let parsed;
@@ -17017,7 +17457,7 @@ function frontDoorRcControl(transport, token) {
17017
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}`),
17018
17458
  answerRequest: async (sessionId, requestId, decision) => await writeOf(
17019
17459
  `${CONTROL_PATH_PREFIX}/answer`,
17020
- 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 } }),
17021
17461
  (status, message) => `answering control request ${requestId} on ${sessionId} failed (HTTP ${String(status)}): ${message}`
17022
17462
  ),
17023
17463
  interruptSession: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/interrupt`, JSON.stringify({ session: sessionId }), (status, message) => `interrupting ${sessionId} failed (HTTP ${String(status)}): ${message}`),
@@ -17535,19 +17975,19 @@ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
17535
17975
  // src/frontdoor/rcSessionRegistry.ts
17536
17976
  init_identityStore();
17537
17977
  import path31 from "node:path";
17538
- import { z as z21 } from "zod";
17978
+ import { z as z22 } from "zod";
17539
17979
  var REGISTRY_BRIDGE_PREFIX = "session_";
17540
17980
  var DOOR_SESSION_PREFIX = "cse_";
17541
17981
  var REGISTRY_DIR = "sessions";
17542
17982
  var ENTRY_SUFFIX = ".json";
17543
17983
  var RC_REGISTRY_ENTRY_MAX_BYTES = 8192;
17544
- var RegistryEntrySchema = z21.looseObject({
17545
- sessionId: z21.string().min(1),
17546
- pid: z21.int().positive(),
17547
- bridgeSessionId: z21.union([z21.string().startsWith(REGISTRY_BRIDGE_PREFIX), z21.string().startsWith(DOOR_SESSION_PREFIX)]),
17548
- cwd: z21.string().optional(),
17549
- name: z21.string().optional(),
17550
- 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()
17551
17991
  });
17552
17992
  function supersedes(candidate, kept) {
17553
17993
  return candidate.updatedAt > kept.updatedAt || candidate.updatedAt === kept.updatedAt && candidate.session.pid > kept.session.pid;
@@ -17661,11 +18101,11 @@ import path32 from "node:path";
17661
18101
  function isSafeSessionId(sessionId) {
17662
18102
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
17663
18103
  }
17664
- function isRecord6(value) {
18104
+ function isRecord7(value) {
17665
18105
  return typeof value === "object" && value !== null && !Array.isArray(value);
17666
18106
  }
17667
18107
  function credentialOfJson(parsed) {
17668
- if (!isRecord6(parsed)) {
18108
+ if (!isRecord7(parsed)) {
17669
18109
  return void 0;
17670
18110
  }
17671
18111
  const { authorization, anthropicVersion, anthropicClientPlatform } = parsed;
@@ -17695,7 +18135,7 @@ function createRcCredentialStore(fs17, dir) {
17695
18135
  } catch {
17696
18136
  return void 0;
17697
18137
  }
17698
- return isRecord6(parsed) ? parsed : void 0;
18138
+ return isRecord7(parsed) ? parsed : void 0;
17699
18139
  };
17700
18140
  return {
17701
18141
  read: (sessionId) => {
@@ -17746,175 +18186,443 @@ import { OpenAPIHandler } from "@orpc/openapi/node";
17746
18186
  import { eventIterator, os as os3, withEventMeta } from "@orpc/server";
17747
18187
  import { BodyLimitPlugin, RPCHandler } from "@orpc/server/node";
17748
18188
  import { Agent as Agent3, fetch as undiciFetch } from "undici";
18189
+
18190
+ // src/supervise/compactTimeout.ts
18191
+ var COMPACT_TIMEOUT_MS = 9e5;
18192
+
18193
+ // src/frontdoor/rcApi.ts
17749
18194
  init_capability();
17750
18195
 
17751
- // src/frontdoor/rcSchemas.ts
17752
- import { z as z22 } from "zod";
17753
- var RcPermissionModeSchema = z22.enum(RC_PERMISSION_MODES);
17754
- var RcSessionSummarySchema = z22.strictObject({
17755
- id: z22.string(),
17756
- createdAt: z22.number(),
17757
- lastSeenAt: z22.number()
17758
- });
17759
- function workerFactSchema(value) {
17760
- return z22.strictObject({ value, observedAt: z22.number() });
18196
+ // src/frontdoor/rcSlashCommandSchemas.ts
18197
+ import { z as z23 } from "zod";
18198
+
18199
+ // src/frontdoor/rcSessionCommands.ts
18200
+ import { setTimeout as sleep } from "node:timers/promises";
18201
+
18202
+ // src/supervise/sessionControl.ts
18203
+ var RESULT_POLL_MS = 250;
18204
+ var REQUEST_INSTANT_DIGITS = String(Number.MAX_SAFE_INTEGER).length;
18205
+
18206
+ // src/frontdoor/rcSelfHostCommands.ts
18207
+ var RC_PERSON_CLIENT_PLATFORM = "web_claude_ai";
18208
+ async function writeRcPersonMessage(deps, sessionId, text) {
18209
+ const credential = deps.credentialOf(sessionId);
18210
+ if (credential === void 0) {
18211
+ return { ok: false, message: rcSessionNotObservedMessage(sessionId) };
18212
+ }
18213
+ if (credential.authorization === void 0) {
18214
+ return noOAuthCredentialResult(sessionId);
18215
+ }
18216
+ const body = JSON.stringify(buildRcEventWriteBody(buildRcUserMessagePayload(deps.newUuid(), sessionId, text)));
18217
+ const bytes = Buffer.byteLength(body, "utf8");
18218
+ if (bytes > CONTROL_BODY_CAP_BYTES) {
18219
+ return { ok: false, message: `the command for session ${sessionId} makes an event write of ${String(bytes)} bytes, over the ${String(CONTROL_BODY_CAP_BYTES)} bytes the door's self-hosted surface reads; shorten its arguments` };
18220
+ }
18221
+ let answer;
18222
+ try {
18223
+ answer = await deps.dial.writeEvents(sessionId, rcWriteHeaders({ ...credential, anthropicClientPlatform: RC_PERSON_CLIENT_PLATFORM }), body);
18224
+ } catch (error) {
18225
+ return { ok: false, message: `the door could not write to its own self-hosted surface for session ${sessionId}: ${error instanceof Error ? error.message : String(error)}` };
18226
+ }
18227
+ const result = rcEventWriteResultFromAnswer(answer);
18228
+ if (result.ok) {
18229
+ deps.noteSequenceNums(sessionId, result.sequenceNums);
18230
+ }
18231
+ return result;
17761
18232
  }
17762
- var RcPendingRequestSummarySchema = z22.strictObject({
17763
- sessionId: z22.string(),
17764
- requestId: z22.string(),
17765
- type: z22.string(),
17766
- summary: z22.string(),
17767
- observedAt: z22.number()
17768
- });
17769
- var RcSessionStatusSchema = z22.strictObject({
17770
- ...RcSessionSummarySchema.shape,
17771
- workerState: workerFactSchema(z22.string()).optional(),
17772
- workerIdleSeconds: workerFactSchema(z22.number()).optional(),
17773
- pending: z22.readonly(z22.array(RcPendingRequestSummarySchema)),
17774
- /** The identity the session runs as, when known; absent otherwise. */
17775
- identity: z22.string().optional(),
17776
- /** The model the session last stated, when the door saw one. */
17777
- model: z22.string().optional(),
17778
- /** The session's name from the Claude Code session registry, when the registry holds it. */
17779
- name: z22.string().optional(),
17780
- /** The session process's id from the registry. */
17781
- pid: z22.number().optional(),
17782
- /** The session's working directory, from its init event or the registry. */
17783
- cwd: z22.string().optional()
17784
- });
17785
- var RcStreamEnvelopeSchema = z22.looseObject({
17786
- /** The envelope's own event id, when the host sent one. */
17787
- event_id: z22.string().optional(),
17788
- /** The envelope's event type, the discriminator a consumer switches on (`control_request`, `user`, and kin). */
17789
- event_type: z22.string(),
17790
- /** The sequence number the host assigned, the value a resume continues after. */
17791
- sequence_num: z22.int(),
17792
- /** Who emitted the event (`worker` for the CLI's half, a client id for a client's). */
17793
- source: z22.string(),
17794
- /** 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. */
17795
- payload: z22.unknown().optional(),
17796
- /** 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. */
17797
- created_at: z22.unknown().optional()
17798
- });
17799
- var RcStreamEventSchema = z22.strictObject({
17800
- session: z22.string(),
17801
- envelope: RcStreamEnvelopeSchema
17802
- });
17803
- var RcRateLimitWindowSchema = z22.looseObject({
17804
- /** 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). */
17805
- utilization: z22.number().optional(),
17806
- /** 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. */
17807
- resetsAt: z22.number().optional()
17808
- });
17809
- var RcRateLimitInfoSchema = z22.looseObject({
17810
- /** The limiting window's own status (`allowed`, `allowed_warning`, `rejected`), asserted only as a string because the vocabulary grows with the CLI. */
17811
- status: z22.string(),
17812
- /** When the limiting window resets, in unix epoch seconds. */
17813
- resetsAt: z22.number().optional(),
17814
- /** Which window the top-level fields describe (`five_hour`, `seven_day`, and kin), the payload's own name for it. */
17815
- rateLimitType: z22.string().optional(),
17816
- /** The fraction of the limiting window used, on the same scale the per-window utilizations carry. */
17817
- utilization: z22.number().optional(),
17818
- /** Whether usage beyond the plan (extra usage) is currently covering the overflow, the payload's own flag for it. */
17819
- isUsingOverage: z22.boolean().optional(),
17820
- /** The overage's own status, the same vocabulary the limiting window's `status` carries. */
17821
- overageStatus: z22.string().optional(),
17822
- /** When the overage window resets, in unix epoch seconds. */
17823
- overageResetsAt: z22.number().optional(),
17824
- /** 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. */
17825
- unifiedWindows: z22.looseObject({ five_hour: RcRateLimitWindowSchema.optional(), seven_day: RcRateLimitWindowSchema.optional(), seven_day_overage_included: RcRateLimitWindowSchema.optional() }).optional()
17826
- });
17827
- var RcLiveRateLimitSchema = z22.strictObject({
17828
- session: z22.string(),
17829
- observedAt: z22.number(),
17830
- rateLimit: RcRateLimitInfoSchema
17831
- });
17832
- var RcSessionQuerySchema = z22.strictObject({
17833
- session: z22.string().min(1).optional()
17834
- });
17835
- var RcSendInputSchema = z22.strictObject({
17836
- session: z22.string().min(1),
17837
- text: z22.string().min(1)
17838
- });
17839
- var RcAnswerInputSchema = z22.strictObject({
17840
- session: z22.string().min(1),
17841
- request: z22.string().min(1),
17842
- approve: z22.boolean(),
17843
- text: z22.string().optional()
17844
- }).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" });
17845
- var RcInterruptInputSchema = z22.strictObject({
17846
- session: z22.string().min(1)
17847
- });
17848
- var RcSetModelInputSchema = z22.strictObject({
17849
- session: z22.string().min(1),
17850
- model: z22.string().min(1)
17851
- });
17852
- var RcSetPermissionModeInputSchema = z22.strictObject({
17853
- session: z22.string().min(1),
17854
- mode: RcPermissionModeSchema
17855
- });
17856
- var RcEndSessionInputSchema = z22.strictObject({
17857
- session: z22.string().min(1),
17858
- reason: z22.string().min(1).optional()
17859
- });
17860
- var RcGetUsageInputSchema = z22.strictObject({
17861
- session: z22.string().min(1),
17862
- skipBehaviors: z22.boolean().optional()
17863
- });
17864
- var RcGetContextUsageInputSchema = z22.strictObject({
17865
- session: z22.string().min(1),
17866
- detail: z22.enum(RC_CONTEXT_USAGE_DETAILS).optional()
17867
- });
17868
- var RcReadFileInputSchema = z22.strictObject({
17869
- session: z22.string().min(1),
17870
- path: z22.string().min(1),
17871
- maxBytes: z22.number().int().positive().optional(),
17872
- encoding: z22.enum(RC_READ_FILE_ENCODINGS).optional()
17873
- });
17874
- var RcFileSuggestionsInputSchema = z22.strictObject({
17875
- session: z22.string().min(1),
17876
- query: z22.string()
17877
- });
17878
- var RcKeepAliveInputSchema = z22.strictObject({
17879
- session: z22.string().min(1)
17880
- });
17881
- var RcMcpStatusInputSchema = z22.strictObject({
17882
- session: z22.string().min(1)
18233
+ function isRecord8(value) {
18234
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18235
+ }
18236
+ function rcLocalCommandAnswerOf(event, command, args) {
18237
+ const payload = event.envelope.payload;
18238
+ if (!isRecord8(payload) || payload.type !== "assistant" || !isRecord8(payload.local_command_run) || payload.local_command_run.command !== command || payload.local_command_run.args !== args) {
18239
+ return void 0;
18240
+ }
18241
+ const message = payload.message;
18242
+ if (!isRecord8(message) || !Array.isArray(message.content)) {
18243
+ return void 0;
18244
+ }
18245
+ const blocks = message.content;
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;
18248
+ return { text, outcome };
18249
+ }
18250
+ function rcManualCompactBoundaryOf(event) {
18251
+ const payload = event.envelope.payload;
18252
+ if (!isRecord8(payload) || payload.type !== "system" || payload.subtype !== "compact_boundary" || !isRecord8(payload.compact_metadata)) {
18253
+ return void 0;
18254
+ }
18255
+ const metadata = payload.compact_metadata;
18256
+ if (metadata.trigger !== "manual" || typeof metadata.pre_tokens !== "number" || typeof metadata.post_tokens !== "number") {
18257
+ return void 0;
18258
+ }
18259
+ return { trigger: metadata.trigger, preTokens: metadata.pre_tokens, postTokens: metadata.post_tokens };
18260
+ }
18261
+ function isPeerDelivery(event, text) {
18262
+ const payload = event.envelope.payload;
18263
+ if (!isRecord8(payload) || payload.type !== "user" || !isRecord8(payload.origin) || payload.origin.kind !== "peer" || !isRecord8(payload.message)) {
18264
+ return false;
18265
+ }
18266
+ return typeof payload.message.content === "string" && payload.message.content.includes(text);
18267
+ }
18268
+ var NO_GOAL_PREFIX = "No goal set";
18269
+ var ACTIVE_GOAL_PATTERN = /^Goal active: (?<condition>[\s\S]*?) \((?:not yet evaluated|(?<iterations>\d+) turns?)\)(?:\nLast check: (?<lastCheck>[\s\S]*))?$/u;
18270
+ function parseRcGoalOutput(output) {
18271
+ if (output.startsWith(NO_GOAL_PREFIX)) {
18272
+ return { goal: null };
18273
+ }
18274
+ const groups = ACTIVE_GOAL_PATTERN.exec(output)?.groups;
18275
+ const condition = groups?.condition;
18276
+ if (condition === void 0) {
18277
+ return void 0;
18278
+ }
18279
+ return { goal: { condition, iterations: groups?.iterations === void 0 ? 0 : Number(groups.iterations), ...groups?.lastCheck === void 0 ? {} : { lastCheck: groups.lastCheck } } };
18280
+ }
18281
+ var GOAL_CLEARED_PREFIX = "Goal cleared: ";
18282
+ var GOAL_SET_PREFIX = "Goal set: ";
18283
+ function commandLine(command) {
18284
+ if (command.kind === "goal-set") {
18285
+ return { name: "goal", args: command.condition };
18286
+ }
18287
+ if (command.kind === "compact") {
18288
+ return { name: "compact", args: command.instructions ?? "" };
18289
+ }
18290
+ return { name: "goal", args: command.kind === "goal-clear" ? "clear" : "" };
18291
+ }
18292
+ function recognise(command, event, name, args) {
18293
+ if (command.kind === "compact") {
18294
+ const boundary = rcManualCompactBoundaryOf(event);
18295
+ if (boundary !== void 0) {
18296
+ return { ok: true, report: boundary };
18297
+ }
18298
+ }
18299
+ const answer = rcLocalCommandAnswerOf(event, name, args);
18300
+ if (answer === void 0) {
18301
+ return void 0;
18302
+ }
18303
+ if (answer.outcome === "failed") {
18304
+ return { ok: false, message: `the worker reported /${name} failed: ${answer.text}` };
18305
+ }
18306
+ if (command.kind === "goal-get") {
18307
+ const report = parseRcGoalOutput(answer.text);
18308
+ return report === void 0 ? { ok: false, message: `the worker answered /goal with text the verified versions never produce: ${answer.text}` } : { ok: true, report };
18309
+ }
18310
+ if (command.kind === "goal-set") {
18311
+ return answer.text.startsWith(GOAL_SET_PREFIX) ? { ok: true, report: { condition: answer.text.slice(GOAL_SET_PREFIX.length) } } : { ok: false, message: `the worker did not set the goal: ${answer.text}` };
18312
+ }
18313
+ if (command.kind === "goal-clear") {
18314
+ if (answer.text.startsWith(GOAL_CLEARED_PREFIX)) {
18315
+ return { ok: true, report: { cleared: answer.text.slice(GOAL_CLEARED_PREFIX.length) } };
18316
+ }
18317
+ return answer.text === NO_GOAL_PREFIX ? { ok: true, report: { cleared: null } } : { ok: false, message: `the worker answered /goal clear with text the verified versions never produce: ${answer.text}` };
18318
+ }
18319
+ return { ok: false, message: `the worker did not compact the session: ${answer.text}` };
18320
+ }
18321
+ async function runSelfHostedSlashCommand(deps, sessionId, command, waitMs, signal) {
18322
+ const { name, args } = commandLine(command);
18323
+ const text = args === "" ? `/${name}` : `/${name} ${args}`;
18324
+ const early = [];
18325
+ let after;
18326
+ let settle;
18327
+ const judge = (event) => {
18328
+ if (after === void 0) {
18329
+ early.push(event);
18330
+ return;
18331
+ }
18332
+ if (event.envelope.sequence_num <= after || event.envelope.source !== "worker") {
18333
+ return;
18334
+ }
18335
+ if (isPeerDelivery(event, text)) {
18336
+ settle?.({ ok: false, message: `session ${sessionId}'s worker passed ${text} to its model as a peer's message instead of running it, so it did not read the write as a person's` });
18337
+ return;
18338
+ }
18339
+ const outcome = recognise(command, event, name, args);
18340
+ if (outcome !== void 0) {
18341
+ settle?.(outcome);
18342
+ }
18343
+ };
18344
+ const detach = deps.fanout.subscribe(sessionId, judge);
18345
+ let cancelTimer;
18346
+ const onAbort = () => {
18347
+ settle?.({ ok: false, message: `the request for ${text} on session ${sessionId} was aborted before the worker answered` });
18348
+ };
18349
+ signal.addEventListener("abort", onAbort, { once: true });
18350
+ try {
18351
+ const answered = new Promise((resolve) => {
18352
+ settle = resolve;
18353
+ });
18354
+ const written = await writeRcPersonMessage(deps.personWrite, sessionId, text);
18355
+ if (!written.ok) {
18356
+ return written;
18357
+ }
18358
+ if (signal.aborted) {
18359
+ return { ok: false, message: `the request for ${text} on session ${sessionId} was aborted after it was written (sequence_num ${written.sequenceNums.join(", ")})` };
18360
+ }
18361
+ after = Math.max(...written.sequenceNums);
18362
+ const bound = waitMs ?? deps.defaultWaitMs;
18363
+ cancelTimer = deps.setTimer(() => {
18364
+ settle?.({ ok: false, message: `${text} was delivered to session ${sessionId} (sequence_num ${written.sequenceNums.join(", ")}) but the worker reported no outcome within ${String(bound)} ms; it may still be queued behind a running turn, so read the session's stream before sending it again` });
18365
+ }, bound);
18366
+ for (const event of early.splice(0)) {
18367
+ judge(event);
18368
+ }
18369
+ return await answered;
18370
+ } finally {
18371
+ signal.removeEventListener("abort", onAbort);
18372
+ cancelTimer?.();
18373
+ detach();
18374
+ }
18375
+ }
18376
+ function createRcClaudeCodeVersions(fanout) {
18377
+ const versions = /* @__PURE__ */ new Map();
18378
+ fanout.subscribe(void 0, (event) => {
18379
+ const payload = event.envelope.payload;
18380
+ if (event.envelope.source === "worker" && isRecord8(payload) && payload.type === "system" && payload.subtype === "init" && typeof payload.claude_code_version === "string") {
18381
+ versions.set(event.session, payload.claude_code_version);
18382
+ }
18383
+ });
18384
+ return {
18385
+ versionOf: (sessionId) => versions.get(sessionId),
18386
+ sweep: (isTracked) => {
18387
+ for (const sessionId of [...versions.keys()]) {
18388
+ if (!isTracked(sessionId)) {
18389
+ versions.delete(sessionId);
18390
+ }
18391
+ }
18392
+ }
18393
+ };
18394
+ }
18395
+
18396
+ // src/frontdoor/rcSessionCommands.ts
18397
+ var RC_SESSION_COMMAND_VERIFIED_VERSIONS = ["2.1.319"];
18398
+ var RC_GOAL_CLEAR_WORDS = ["clear", "stop", "off", "reset", "none", "cancel"];
18399
+ var RC_GOAL_CONDITION_MAX_CHARS = 4e3;
18400
+ var MAX_JSON_BYTES_PER_CODE_UNIT = 6;
18401
+ var RC_COMPACT_INSTRUCTIONS_MAX_CHARS = Math.floor(CONTROL_BODY_CAP_BYTES / MAX_JSON_BYTES_PER_CODE_UNIT);
18402
+ var RC_SESSION_COMMAND_MAX_WAIT_MS = 2147483647;
18403
+ function unverifiedVersionMessage(sessionId, version, source) {
18404
+ const verified = RC_SESSION_COMMAND_VERIFIED_VERSIONS.join(", ");
18405
+ return version === void 0 ? `session ${sessionId} has not reported its Claude Code version (${source}), and goal and compaction control is verified only on Claude Code ${verified}` : `session ${sessionId} runs Claude Code ${version}, and goal and compaction control is verified only on Claude Code ${verified}: the door will not act on a version whose behaviour it has not verified`;
18406
+ }
18407
+ function unsupportedMessage(sessionId) {
18408
+ return `session ${sessionId} was not launched under an agent-shim supervisor, so the door has no in-process channel into it, and it is not on the door's own self-hosted surface. Over the real Remote Control service, Claude Code ${RC_SESSION_COMMAND_VERIFIED_VERSIONS.join(", ")} runs a slash command only when a person's app wrote it and treats any other writer as a peer, whose message the model reads as text, and the door does not claim to be a person's app on a service it does not run. Launch the session under a pool with resumeOnLimit (which supervises it), or run it against the door's self-hosted surface.`;
18409
+ }
18410
+ function createRcSessionCommands(deps) {
18411
+ const queues = /* @__PURE__ */ new Map();
18412
+ const serialised = async (sessionId, work) => {
18413
+ const before = queues.get(sessionId) ?? Promise.resolve();
18414
+ const run = before.then(work, work);
18415
+ const settled = run.then(() => void 0, () => void 0);
18416
+ queues.set(sessionId, settled);
18417
+ try {
18418
+ return await run;
18419
+ } finally {
18420
+ if (queues.get(sessionId) === settled) {
18421
+ queues.delete(sessionId);
18422
+ }
18423
+ }
18424
+ };
18425
+ const onRoute = async (sessionId, options, actions) => await serialised(sessionId, async () => {
18426
+ const signal = options.signal ?? new AbortController().signal;
18427
+ if (signal.aborted) {
18428
+ return { ok: false, message: `the request for session ${sessionId} was aborted before it ran` };
18429
+ }
18430
+ const target = await deps.supervisedOf(sessionId);
18431
+ if (target !== void 0 && "refused" in target) {
18432
+ return { ok: false, message: target.refused };
18433
+ }
18434
+ if (target !== void 0) {
18435
+ if (target.version === void 0 || !RC_SESSION_COMMAND_VERIFIED_VERSIONS.includes(target.version)) {
18436
+ return { ok: false, message: unverifiedVersionMessage(sessionId, target.version, "its supervisor's control plugin has not loaded") };
18437
+ }
18438
+ const waitMs = options.waitMs ?? COMPACT_TIMEOUT_MS;
18439
+ const timeout = AbortSignal.timeout(waitMs);
18440
+ const bounded3 = AbortSignal.any([signal, timeout]);
18441
+ try {
18442
+ return await actions.supervised(target, bounded3, waitMs);
18443
+ } catch (error) {
18444
+ if (timeout.aborted) {
18445
+ return { ok: false, message: `session ${sessionId}'s control plugin did not answer within ${String(waitMs)} ms. A request the plugin had not started is withdrawn; one it had started runs once the session is idle (a turn waiting on a permission prompt holds it), so read the session's goal or transcript before asking again` };
18446
+ }
18447
+ return { ok: false, message: `session ${sessionId}'s control plugin did not complete the request: ${error instanceof Error ? error.message : String(error)}` };
18448
+ }
18449
+ }
18450
+ if (!deps.isObserved(sessionId)) {
18451
+ return { ok: false, message: `the front door has not observed Remote Control session ${sessionId}` };
18452
+ }
18453
+ if (deps.selfHost !== void 0) {
18454
+ const unavailable = deps.selfHost.unavailable();
18455
+ if (unavailable !== void 0) {
18456
+ return { ok: false, message: `session ${sessionId} was not launched under an agent-shim supervisor, and the door's self-hosted surface cannot take a command: ${unavailable}` };
18457
+ }
18458
+ const version = deps.selfHost.versionOf(sessionId);
18459
+ if (version === void 0 || !RC_SESSION_COMMAND_VERIFIED_VERSIONS.includes(version)) {
18460
+ return { ok: false, message: unverifiedVersionMessage(sessionId, version, "no system/init from its worker has been observed on its stream; send it a prompt so it reports one") };
18461
+ }
18462
+ const waitMs = options.waitMs ?? deps.selfHost.defaultWaitMs;
18463
+ const timeout = AbortSignal.timeout(waitMs);
18464
+ const result = await actions.selfHosted(deps.selfHost, AbortSignal.any([signal, timeout]));
18465
+ if (!result.ok && timeout.aborted) {
18466
+ return { ok: false, message: `session ${sessionId}'s worker did not answer within ${String(waitMs)} ms in all; it may still be queued behind a running turn, so read the session's stream before asking again` };
18467
+ }
18468
+ return result;
18469
+ }
18470
+ return { ok: false, message: unsupportedMessage(sessionId) };
18471
+ });
18472
+ const transcriptGoal = async (sessionId, target) => {
18473
+ const goal = target.transcriptPath === void 0 ? void 0 : await deps.goalOf(target.transcriptPath);
18474
+ if (goal === void 0) {
18475
+ return { ok: false, message: `session ${sessionId}'s supervisor has not recorded its transcript yet, which is where its goal is read from; retry once it has finished a turn` };
18476
+ }
18477
+ return { ok: true, report: goal };
18478
+ };
18479
+ const settledGoal = async (sessionId, target, signal, holds) => {
18480
+ for (; ; ) {
18481
+ const read = await transcriptGoal(sessionId, target);
18482
+ if (!read.ok || holds(read.report) || signal.aborted) {
18483
+ return read;
18484
+ }
18485
+ await sleep(RESULT_POLL_MS);
18486
+ }
18487
+ };
18488
+ const waitOf = (options) => options.waitMs;
18489
+ return {
18490
+ /** Reads the session's goal: from the transcript for a supervised session, with no effect on it; by running `/goal` on the self-hosted surface otherwise. */
18491
+ goalGet: async (sessionId, options = {}) => await onRoute(sessionId, options, {
18492
+ supervised: async (target) => {
18493
+ const read = await transcriptGoal(sessionId, target);
18494
+ return await Promise.resolve(read.ok ? { ok: true, report: { route: "supervised", goal: read.report } } : read);
18495
+ },
18496
+ selfHosted: async (selfHost, signal) => {
18497
+ const read = await runSelfHostedSlashCommand(selfHost, sessionId, { kind: "goal-get" }, waitOf(options), signal);
18498
+ return read.ok ? { ok: true, report: { route: "self-hosted", goal: read.report.goal } } : read;
18499
+ }
18500
+ }),
18501
+ /**
18502
+ * Sets the session's goal: the goal check then keeps the session working until the condition holds, and the condition reaches its model as a directive (`docs/rc-slash-commands.md`, the trust boundary). Refused unsent: an empty condition, one `/goal` reads as a clear, and one longer than it accepts. The answer names the goal it replaced.
18503
+ */
18504
+ goalSet: async (sessionId, condition, options = {}) => {
18505
+ const trimmed = condition.trim();
18506
+ if (trimmed === "") {
18507
+ return { ok: false, message: "a goal set needs a non-empty condition" };
18508
+ }
18509
+ if (RC_GOAL_CLEAR_WORDS.includes(trimmed.toLowerCase())) {
18510
+ return { ok: false, message: `"${trimmed}" cannot be set as a goal condition: /goal reads ${RC_GOAL_CLEAR_WORDS.join(", ")} as a request to clear the goal, so use the clear verb for that` };
18511
+ }
18512
+ if (/[\r\n]/u.test(trimmed)) {
18513
+ return { ok: false, message: "a goal condition is one line: /goal reads its condition from the line it is typed on, and both routes confirm the goal by the exact condition, so a condition spanning lines is refused rather than set as something else" };
18514
+ }
18515
+ if (trimmed.length > RC_GOAL_CONDITION_MAX_CHARS) {
18516
+ return { ok: false, message: `a goal condition is limited to ${String(RC_GOAL_CONDITION_MAX_CHARS)} characters, and this one has ${String(trimmed.length)}` };
18517
+ }
18518
+ return await onRoute(sessionId, options, {
18519
+ supervised: async (target, signal, waitMs) => {
18520
+ const before = await transcriptGoal(sessionId, target);
18521
+ if (!before.ok) {
18522
+ return before;
18523
+ }
18524
+ await target.runGoal(trimmed, signal, waitMs);
18525
+ const after = await settledGoal(sessionId, target, signal, (goal) => goal?.condition === trimmed);
18526
+ if (!after.ok) {
18527
+ return after;
18528
+ }
18529
+ return after.report?.condition === trimmed ? { ok: true, report: { route: "supervised", condition: trimmed, superseded: before.report?.condition ?? null } } : { ok: false, message: `session ${sessionId} ran /goal but its transcript does not record the goal as set` };
18530
+ },
18531
+ selfHosted: async (selfHost, signal) => {
18532
+ const before = await runSelfHostedSlashCommand(selfHost, sessionId, { kind: "goal-get" }, waitOf(options), signal);
18533
+ if (!before.ok) {
18534
+ return before;
18535
+ }
18536
+ const set = await runSelfHostedSlashCommand(selfHost, sessionId, { kind: "goal-set", condition: trimmed }, waitOf(options), signal);
18537
+ return set.ok ? { ok: true, report: { route: "self-hosted", condition: set.report.condition, superseded: before.report.goal?.condition ?? null } } : set;
18538
+ }
18539
+ });
18540
+ },
18541
+ /** Clears the session's goal and names the condition it cleared, or `null` when there was none, which is not a failure (clearing is idempotent). */
18542
+ goalClear: async (sessionId, options = {}) => await onRoute(sessionId, options, {
18543
+ supervised: async (target, signal, waitMs) => {
18544
+ const before = await transcriptGoal(sessionId, target);
18545
+ if (!before.ok) {
18546
+ return before;
18547
+ }
18548
+ if (before.report === null) {
18549
+ return { ok: true, report: { route: "supervised", cleared: null } };
18550
+ }
18551
+ await target.runGoal("clear", signal, waitMs);
18552
+ const after = await settledGoal(sessionId, target, signal, (goal) => goal === null);
18553
+ if (!after.ok) {
18554
+ return after;
18555
+ }
18556
+ return after.report === null ? { ok: true, report: { route: "supervised", cleared: before.report.condition } } : { ok: false, message: `session ${sessionId} ran /goal clear but its transcript still records the goal "${after.report.condition}"` };
18557
+ },
18558
+ selfHosted: async (selfHost, signal) => {
18559
+ const cleared = await runSelfHostedSlashCommand(selfHost, sessionId, { kind: "goal-clear" }, waitOf(options), signal);
18560
+ return cleared.ok ? { ok: true, report: { route: "self-hosted", cleared: cleared.report.cleared } } : cleared;
18561
+ }
18562
+ }),
18563
+ /** Compacts the session's conversation, with custom summary instructions when given, and resolves with the outcome: the trigger and token counts, or the session's reason for not compacting. */
18564
+ compact: async (sessionId, options = {}) => {
18565
+ const instructions = options.instructions?.trim();
18566
+ const given = instructions === void 0 || instructions === "" ? void 0 : instructions;
18567
+ return await onRoute(sessionId, options, {
18568
+ supervised: async (target, signal, waitMs) => {
18569
+ const result = await target.compact(signal, given, waitMs);
18570
+ if (result.kind === "unchanged") {
18571
+ return { ok: false, message: `session ${sessionId} was not compacted: ${result.reason}` };
18572
+ }
18573
+ return { ok: true, report: { route: "supervised", trigger: "plugin", ...result.beforeTokens === void 0 ? {} : { preTokens: result.beforeTokens }, ...result.afterTokens === void 0 ? {} : { postTokens: result.afterTokens } } };
18574
+ },
18575
+ selfHosted: async (selfHost, signal) => {
18576
+ const compacted = await runSelfHostedSlashCommand(selfHost, sessionId, { kind: "compact", instructions: given }, waitOf(options), signal);
18577
+ return compacted.ok ? { ok: true, report: { route: "self-hosted", ...compacted.report } } : compacted;
18578
+ }
18579
+ });
18580
+ }
18581
+ };
18582
+ }
18583
+
18584
+ // src/frontdoor/rcSlashCommandSchemas.ts
18585
+ var WaitMsSchema = z23.int().positive().max(RC_SESSION_COMMAND_MAX_WAIT_MS).optional();
18586
+ var RcGoalSessionInputSchema = z23.strictObject({
18587
+ session: z23.string().min(1),
18588
+ waitMs: WaitMsSchema
17883
18589
  });
17884
- var RcMcpReconnectInputSchema = z22.strictObject({
17885
- session: z22.string().min(1),
17886
- serverName: z22.string().min(1)
18590
+ var RcGoalSetInputSchema = z23.strictObject({
18591
+ session: z23.string().min(1),
18592
+ condition: z23.string().trim().min(1).max(RC_GOAL_CONDITION_MAX_CHARS).regex(/^[^\r\n]*$/u, "a goal condition is one line"),
18593
+ waitMs: WaitMsSchema
17887
18594
  });
17888
- var RcMcpAuthenticateInputSchema = z22.strictObject({
17889
- session: z22.string().min(1),
17890
- serverName: z22.string().min(1),
17891
- redirectUri: z22.string().min(1)
18595
+ var RcCompactInputSchema = z23.strictObject({
18596
+ session: z23.string().min(1),
18597
+ waitMs: WaitMsSchema
17892
18598
  });
17893
- var RcMcpOAuthCallbackUrlInputSchema = z22.strictObject({
17894
- session: z22.string().min(1),
17895
- serverName: z22.string().min(1),
17896
- callbackUrl: z22.string().min(1)
18599
+ var RcCompactWithInstructionsInputSchema = z23.strictObject({
18600
+ session: z23.string().min(1),
18601
+ instructions: z23.string().trim().min(1).max(RC_COMPACT_INSTRUCTIONS_MAX_CHARS),
18602
+ waitMs: WaitMsSchema
17897
18603
  });
17898
- var RcTeleportInputSchema = z22.strictObject({
17899
- session: z22.string().min(1),
17900
- marker: z22.string().min(1)
18604
+ var commandAnswerShape = {
18605
+ session: z23.string(),
18606
+ route: z23.enum(["supervised", "self-hosted"])
18607
+ };
18608
+ var RcGoalGetOutputSchema = z23.strictObject({
18609
+ ...commandAnswerShape,
18610
+ goal: z23.strictObject({ condition: z23.string(), iterations: z23.int().nonnegative(), lastCheck: z23.string().optional() }).nullable()
17901
18611
  });
17902
- var RcListOutputSchema = z22.strictObject({ sessions: z22.readonly(z22.array(RcSessionSummarySchema)) });
17903
- var RcStatusOutputSchema = z22.strictObject({ statuses: z22.readonly(z22.array(RcSessionStatusSchema)) });
17904
- var RcPendingOutputSchema = z22.strictObject({ pending: z22.readonly(z22.array(RcPendingRequestSummarySchema)) });
17905
- var RcWriteOutputSchema = z22.strictObject({
17906
- session: z22.string(),
17907
- sequenceNums: z22.readonly(z22.array(z22.number()))
18612
+ var RcGoalSetOutputSchema = z23.strictObject({
18613
+ ...commandAnswerShape,
18614
+ condition: z23.string(),
18615
+ superseded: z23.string().nullable()
17908
18616
  });
17909
- var RcControlWriteOutputSchema = z22.strictObject({
17910
- session: z22.string(),
17911
- request: z22.string(),
17912
- sequenceNums: z22.readonly(z22.array(z22.number()))
18617
+ var RcGoalClearOutputSchema = z23.strictObject({
18618
+ ...commandAnswerShape,
18619
+ cleared: z23.string().nullable()
17913
18620
  });
17914
- var RcAnswerOutputSchema = z22.strictObject({
17915
- session: z22.string(),
17916
- request: z22.string(),
17917
- sequenceNums: z22.readonly(z22.array(z22.number()))
18621
+ var RcCompactOutputSchema = z23.strictObject({
18622
+ ...commandAnswerShape,
18623
+ trigger: z23.string(),
18624
+ preTokens: z23.number().optional(),
18625
+ postTokens: z23.number().optional()
17918
18626
  });
17919
18627
 
17920
18628
  // src/frontdoor/rcApi.ts
@@ -17938,6 +18646,7 @@ function doorApiAuth(expectedToken) {
17938
18646
  });
17939
18647
  }
17940
18648
  var RC_API_TAG = "remote-control";
18649
+ var RC_DIRECTIVE_TAG = "remote-control-directives";
17941
18650
  function createRcApiRouter(deps) {
17942
18651
  const authed = doorApiAuth(deps.expectedToken);
17943
18652
  const delivered = (sessionId, result) => {
@@ -17955,6 +18664,13 @@ function createRcApiRouter(deps) {
17955
18664
  }
17956
18665
  return { request: result.requestId, sequenceNums: result.sequenceNums };
17957
18666
  };
18667
+ const commanded = (sessionId, result) => {
18668
+ if (!result.ok) {
18669
+ throw new ORPCError("BAD_GATEWAY", { message: result.message });
18670
+ }
18671
+ return { session: sessionId, ...result.report };
18672
+ };
18673
+ const optionsOf = (waitMs, signal) => ({ ...waitMs === void 0 ? {} : { waitMs }, ...signal === void 0 ? {} : { signal } });
17958
18674
  return {
17959
18675
  rc: {
17960
18676
  list: authed.meta(openapi({ method: "GET", path: "/rest/rc/sessions", summary: "List the observed Remote Control sessions", tags: [RC_API_TAG] })).output(RcListOutputSchema).handler(() => ({ sessions: deps.list() })),
@@ -17967,14 +18683,16 @@ function createRcApiRouter(deps) {
17967
18683
  }),
17968
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 }) => {
17969
18685
  const pending = deps.pendingOf(input.session);
17970
- 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) {
17971
18688
  throw new ORPCError("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
17972
18689
  }
17973
- 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 } };
17974
18692
  }),
17975
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)) })),
17976
- 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 }) => {
17977
- 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 } };
17978
18696
  return { session: input.session, request: input.request, sequenceNums: delivered(input.session, await deps.answer(input.session, input.request, decision)) };
17979
18697
  }),
17980
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)) })),
@@ -17991,6 +18709,11 @@ function createRcApiRouter(deps) {
17991
18709
  mcpAuthenticate: authed.meta(openapi({ method: "POST", path: "/rest/rc/mcp-authenticate", summary: "Start OAuth for one MCP server on a session", tags: [RC_API_TAG] })).input(RcMcpAuthenticateInputSchema).output(RcControlWriteOutputSchema).handler(async ({ input }) => ({ session: input.session, ...deliveredControl(input.session, await deps.mcpAuthenticate(input.session, input.serverName, input.redirectUri)) })),
17992
18710
  mcpOAuthCallbackUrl: authed.meta(openapi({ method: "POST", path: "/rest/rc/mcp-oauth-callback-url", summary: "Hand a completed MCP OAuth callback to a session", tags: [RC_API_TAG] })).input(RcMcpOAuthCallbackUrlInputSchema).output(RcControlWriteOutputSchema).handler(async ({ input }) => ({ session: input.session, ...deliveredControl(input.session, await deps.mcpOAuthCallbackUrl(input.session, input.serverName, input.callbackUrl)) })),
17993
18711
  teleport: authed.meta(openapi({ method: "POST", path: "/rest/rc/teleport", summary: "Teleport a session to a conversation marker", tags: [RC_API_TAG] })).input(RcTeleportInputSchema).output(RcWriteOutputSchema).handler(async ({ input }) => ({ session: input.session, sequenceNums: delivered(input.session, await deps.teleport(input.session, input.marker)) })),
18712
+ goalGet: authed.meta(openapi({ method: "POST", path: "/rest/rc/goal/get", summary: "Read a session's goal", tags: [RC_API_TAG] })).input(RcGoalSessionInputSchema).output(RcGoalGetOutputSchema).handler(async ({ input, signal }) => commanded(input.session, await deps.goalGet(input.session, optionsOf(input.waitMs, signal)))),
18713
+ goalSet: authed.meta(openapi({ method: "POST", path: "/rest/rc/goal/set", summary: "Set a session's goal, a directive its model then works to", tags: [RC_DIRECTIVE_TAG] })).input(RcGoalSetInputSchema).output(RcGoalSetOutputSchema).handler(async ({ input, signal }) => commanded(input.session, await deps.goalSet(input.session, input.condition, optionsOf(input.waitMs, signal)))),
18714
+ goalClear: authed.meta(openapi({ method: "POST", path: "/rest/rc/goal/clear", summary: "Clear a session's goal", tags: [RC_API_TAG] })).input(RcGoalSessionInputSchema).output(RcGoalClearOutputSchema).handler(async ({ input, signal }) => commanded(input.session, await deps.goalClear(input.session, optionsOf(input.waitMs, signal)))),
18715
+ compact: authed.meta(openapi({ method: "POST", path: "/rest/rc/compact", summary: "Compact a session's conversation", tags: [RC_API_TAG] })).input(RcCompactInputSchema).output(RcCompactOutputSchema).handler(async ({ input, signal }) => commanded(input.session, await deps.compact(input.session, optionsOf(input.waitMs, signal)))),
18716
+ compactWithInstructions: authed.meta(openapi({ method: "POST", path: "/rest/rc/compact-with-instructions", summary: "Compact a session's conversation under summary instructions, a directive to its model", tags: [RC_DIRECTIVE_TAG] })).input(RcCompactWithInstructionsInputSchema).output(RcCompactOutputSchema).handler(async ({ input, signal }) => commanded(input.session, await deps.compact(input.session, { ...optionsOf(input.waitMs, signal), instructions: input.instructions }))),
17994
18717
  subscribe: authed.meta(openapi({ method: "GET", path: "/rest/rc/events", summary: "Stream a session's Remote Control events (SSE)", tags: [RC_API_TAG] })).input(RcSessionQuerySchema).output(eventIterator(RcStreamEventSchema)).handler(async function* ({ input, signal }) {
17995
18718
  const queue = [];
17996
18719
  let wake;
@@ -18071,8 +18794,27 @@ function doorApiNodeHandlerOf(router, expectedToken) {
18071
18794
  function createRcApiNodeHandler(deps) {
18072
18795
  return doorApiNodeHandlerOf(createRcApiRouter(deps), deps.expectedToken);
18073
18796
  }
18797
+ var DEFAULT_HEADERS_TIMEOUT_MS = 3e5;
18798
+ var SESSION_COMMAND_PROCEDURES = ["rc/goalGet", "rc/goalSet", "rc/goalClear", "rc/compact", "rc/compactWithInstructions"];
18799
+ function headersTimeoutOf(url, body) {
18800
+ if (!SESSION_COMMAND_PROCEDURES.some((procedure) => url.endsWith(`${RC_ORPC_PATH_PREFIX}/${procedure}`))) {
18801
+ return DEFAULT_HEADERS_TIMEOUT_MS;
18802
+ }
18803
+ const parsed = body === void 0 ? void 0 : JSON.parse(body.toString("utf8"));
18804
+ const waitMs = typeof parsed === "object" && parsed !== null && "json" in parsed && typeof parsed.json === "object" && parsed.json !== null && "waitMs" in parsed.json && typeof parsed.json.waitMs === "number" ? parsed.json.waitMs : COMPACT_TIMEOUT_MS;
18805
+ return Math.min(waitMs + DEFAULT_HEADERS_TIMEOUT_MS, RC_SESSION_COMMAND_MAX_WAIT_MS);
18806
+ }
18074
18807
  function frontDoorApiLink(port, ca, token) {
18075
- const dispatcher = new Agent3({ connect: { ca } });
18808
+ const dispatchers = /* @__PURE__ */ new Map();
18809
+ const dispatcherFor = (headersTimeout) => {
18810
+ const existing = dispatchers.get(headersTimeout);
18811
+ if (existing !== void 0) {
18812
+ return existing;
18813
+ }
18814
+ const created = new Agent3({ connect: { ca }, headersTimeout });
18815
+ dispatchers.set(headersTimeout, created);
18816
+ return created;
18817
+ };
18076
18818
  return new RPCLink({
18077
18819
  origin: `https://127.0.0.1:${String(port)}`,
18078
18820
  url: RC_ORPC_PATH_PREFIX,
@@ -18085,7 +18827,7 @@ function frontDoorApiLink(port, ca, token) {
18085
18827
  method: request4.method,
18086
18828
  headers: [...request4.headers],
18087
18829
  ...body === void 0 ? {} : { body },
18088
- dispatcher,
18830
+ dispatcher: dispatcherFor(headersTimeoutOf(request4.url, body)),
18089
18831
  ...options.signal === void 0 ? {} : { signal: options.signal }
18090
18832
  });
18091
18833
  return new Response(answered.body, { status: answered.status, statusText: answered.statusText, headers: [...answered.headers] });
@@ -18101,48 +18843,48 @@ init_cliError();
18101
18843
  init_package();
18102
18844
 
18103
18845
  // src/codex/appServerSchemas.ts
18104
- import { z as z23 } from "zod";
18846
+ import { z as z24 } from "zod";
18105
18847
  var CODEX_APP_SERVER_GENERATED_AGAINST = "0.160.0";
18106
- var RateLimitWindowSchema = z23.object({
18107
- usedPercent: z23.number(),
18108
- resetsAt: z23.number().nullish(),
18109
- windowDurationMins: z23.number().nullish()
18110
- });
18111
- var RateLimitSnapshotSchema = z23.object({
18112
- limitId: z23.string().nullish(),
18113
- limitName: z23.string().nullish(),
18114
- planType: z23.string().nullish(),
18848
+ var RateLimitWindowSchema = z24.object({
18849
+ usedPercent: z24.number(),
18850
+ resetsAt: z24.number().nullish(),
18851
+ windowDurationMins: z24.number().nullish()
18852
+ });
18853
+ var RateLimitSnapshotSchema = z24.object({
18854
+ limitId: z24.string().nullish(),
18855
+ limitName: z24.string().nullish(),
18856
+ planType: z24.string().nullish(),
18115
18857
  primary: RateLimitWindowSchema.nullish(),
18116
18858
  secondary: RateLimitWindowSchema.nullish(),
18117
- rateLimitReachedType: z23.string().nullish(),
18118
- spendControlReached: z23.boolean().nullish()
18119
- });
18120
- var RateLimitResetCreditSchema = z23.object({
18121
- id: z23.string(),
18122
- grantedAt: z23.number(),
18123
- expiresAt: z23.number().nullish(),
18124
- resetType: z23.string(),
18125
- status: z23.string(),
18126
- title: z23.string().nullish(),
18127
- description: z23.string().nullish()
18128
- });
18129
- var CodexAccountSchema = z23.discriminatedUnion("type", [
18130
- z23.object({ type: z23.literal("apiKey") }),
18131
- z23.object({ type: z23.literal("chatgpt"), email: z23.string().nullable(), planType: z23.string() }),
18132
- z23.object({ type: z23.literal("amazonBedrock"), usesCodexManagedCredentials: z23.boolean().default(false) })
18859
+ rateLimitReachedType: z24.string().nullish(),
18860
+ spendControlReached: z24.boolean().nullish()
18861
+ });
18862
+ var RateLimitResetCreditSchema = z24.object({
18863
+ id: z24.string(),
18864
+ grantedAt: z24.number(),
18865
+ expiresAt: z24.number().nullish(),
18866
+ resetType: z24.string(),
18867
+ status: z24.string(),
18868
+ title: z24.string().nullish(),
18869
+ description: z24.string().nullish()
18870
+ });
18871
+ var CodexAccountSchema = z24.discriminatedUnion("type", [
18872
+ z24.object({ type: z24.literal("apiKey") }),
18873
+ z24.object({ type: z24.literal("chatgpt"), email: z24.string().nullable(), planType: z24.string() }),
18874
+ z24.object({ type: z24.literal("amazonBedrock"), usesCodexManagedCredentials: z24.boolean().default(false) })
18133
18875
  ]);
18134
- var CodexAccountReadSchema = z23.object({
18876
+ var CodexAccountReadSchema = z24.object({
18135
18877
  account: CodexAccountSchema.nullable(),
18136
- requiresOpenaiAuth: z23.boolean()
18878
+ requiresOpenaiAuth: z24.boolean()
18137
18879
  });
18138
- var CodexRateLimitsReadSchema = z23.object({
18880
+ var CodexRateLimitsReadSchema = z24.object({
18139
18881
  rateLimits: RateLimitSnapshotSchema,
18140
- rateLimitsByLimitId: z23.record(z23.string(), RateLimitSnapshotSchema).nullish(),
18141
- rateLimitResetCredits: z23.object({ availableCount: z23.number(), credits: z23.array(RateLimitResetCreditSchema).nullish() }).nullish(),
18142
- accountId: z23.string().nullish(),
18143
- ordinaryUsageAllowed: z23.boolean().nullish()
18882
+ rateLimitsByLimitId: z24.record(z24.string(), RateLimitSnapshotSchema).nullish(),
18883
+ rateLimitResetCredits: z24.object({ availableCount: z24.number(), credits: z24.array(RateLimitResetCreditSchema).nullish() }).nullish(),
18884
+ accountId: z24.string().nullish(),
18885
+ ordinaryUsageAllowed: z24.boolean().nullish()
18144
18886
  });
18145
- var CodexInitializeResultSchema = z23.object({ userAgent: z23.string() });
18887
+ var CodexInitializeResultSchema = z24.object({ userAgent: z24.string() });
18146
18888
 
18147
18889
  // src/codex/appServer.ts
18148
18890
  var CodexAppServerUnavailableError = class extends CliError {
@@ -18482,7 +19224,7 @@ init_projects();
18482
19224
  init_injected();
18483
19225
  init_pipeline();
18484
19226
  import path37 from "node:path";
18485
- import { z as z26 } from "zod";
19227
+ import { z as z27 } from "zod";
18486
19228
  var HISTORY_PROJECTS_KEY_PREFIX = "history/projects/";
18487
19229
  function projectFragmentOf(rawKey) {
18488
19230
  return rawKey.startsWith(HISTORY_PROJECTS_KEY_PREFIX) ? rawKey.slice(HISTORY_PROJECTS_KEY_PREFIX.length) : void 0;
@@ -18551,9 +19293,9 @@ function lookupKeychainService(run, farmRoot) {
18551
19293
  }
18552
19294
  return { checked: true, found: true, serviceName, note: `Keychain service name for this identity: "${serviceName}".` };
18553
19295
  }
18554
- var SettingsSecretsShapeSchema = z26.looseObject({
18555
- env: z26.record(z26.string(), z26.unknown()).optional(),
18556
- hooks: z26.record(z26.string(), z26.array(z26.unknown())).optional()
19296
+ var SettingsSecretsShapeSchema = z27.looseObject({
19297
+ env: z27.record(z27.string(), z27.unknown()).optional(),
19298
+ hooks: z27.record(z27.string(), z27.array(z27.unknown())).optional()
18557
19299
  });
18558
19300
  function hookCommandCountOf(group) {
18559
19301
  if (typeof group !== "object" || group === null) {
@@ -18858,7 +19600,7 @@ init_schema();
18858
19600
  init_claudeVersion();
18859
19601
  init_identity();
18860
19602
  init_projects();
18861
- import { z as z28 } from "zod";
19603
+ import { z as z29 } from "zod";
18862
19604
 
18863
19605
  // src/resolve/types.ts
18864
19606
  var LAYER_KINDS = [
@@ -18919,123 +19661,123 @@ var DIAGNOSTIC_SEVERITIES = ["error", "warning", "info"];
18919
19661
 
18920
19662
  // src/usage/pickReportSchema.ts
18921
19663
  init_plan2();
18922
- import { z as z27 } from "zod";
18923
- var PoolPickCandidateViewSchema = z27.strictObject({
18924
- identity: z27.string(),
19664
+ import { z as z28 } from "zod";
19665
+ var PoolPickCandidateViewSchema = z28.strictObject({
19666
+ identity: z28.string(),
18925
19667
  /** In pick order: `scored` has usable quota data, `unknown` has none and no plan known to bill by use, `pay-per-use` bills by use whether or not usage is recorded, `ineligible` is refused right now. */
18926
- class: z27.enum(["scored", "unknown", "pay-per-use", "ineligible"]),
19668
+ class: z28.enum(["scored", "unknown", "pay-per-use", "ineligible"]),
18927
19669
  /** Plan-size-weighted remaining quota per hour until its reset; present for `scored` only. */
18928
- score: z27.number().optional(),
19670
+ score: z28.number().optional(),
18929
19671
  /** Which window's reset divides the score: the seven-day window, or the five-hour one when the member reports no seven-day utilisation or its measured-ratio five-hour term outranks the weekly one; present with `score`. */
18930
- scoreWindow: z27.enum(["sevenDay", "fiveHour"]).optional(),
19672
+ scoreWindow: z28.enum(["sevenDay", "fiveHour"]).optional(),
18931
19673
  /** False when the five-hour window would run dry, at the observed pace, before it resets. */
18932
- feasible: z27.boolean(),
19674
+ feasible: z28.boolean(),
18933
19675
  /** When an `ineligible` member can be used again, as an ISO instant. */
18934
- blockedUntil: z27.iso.datetime().optional(),
19676
+ blockedUntil: z28.iso.datetime().optional(),
18935
19677
  plan: PlanClassSchema,
18936
19678
  /** The facts behind the class and score, in the order they matter. */
18937
- reasons: z27.array(z27.string())
19679
+ reasons: z28.array(z28.string())
18938
19680
  });
18939
- var PoolPickReportSchema = z27.strictObject({
18940
- pool: z27.string(),
18941
- directory: z27.string(),
19681
+ var PoolPickReportSchema = z28.strictObject({
19682
+ pool: z28.string(),
19683
+ directory: z28.string(),
18942
19684
  /** The member a launch would run as, absent when every member is refused. */
18943
- pick: z27.string().optional(),
18944
- candidates: z27.array(PoolPickCandidateViewSchema),
19685
+ pick: z28.string().optional(),
19686
+ candidates: z28.array(PoolPickCandidateViewSchema),
18945
19687
  /** Identity members anywhere in the pool's graph that do not exist; a launch skips them. */
18946
- missing: z27.array(z27.string()),
19688
+ missing: z28.array(z28.string()),
18947
19689
  /** When nothing can be picked, the soonest any member returns. */
18948
- earliestReturn: z27.strictObject({ identity: z27.string(), at: z27.iso.datetime() }).optional(),
19690
+ earliestReturn: z28.strictObject({ identity: z28.string(), at: z28.iso.datetime() }).optional(),
18949
19691
  /** The member a resumed conversation started on but moved off, and why, when the ranking could not keep it. */
18950
- movedOff: z27.strictObject({ identity: z27.string(), reason: z27.string() }).optional(),
19692
+ movedOff: z28.strictObject({ identity: z28.string(), reason: z28.string() }).optional(),
18951
19693
  /** Why the last-pick record could not be read, when that is the case. */
18952
- stickyProblem: z27.string().optional()
19694
+ stickyProblem: z28.string().optional()
18953
19695
  });
18954
19696
 
18955
19697
  // src/checkReportSchema.ts
18956
19698
  var CHECK_CREDENTIAL_APPLIES = ["provider", "identity", "stored-login"];
18957
- var CheckLayerViewSchema = z28.strictObject({
18958
- id: z28.int(),
18959
- kind: z28.enum(LAYER_KINDS),
18960
- source: z28.string()
18961
- });
18962
- var CheckEntryViewSchema = z28.strictObject({
18963
- path: z28.string(),
18964
- shared: z28.boolean(),
18965
- via: z28.enum(DECISION_VIAS),
19699
+ var CheckLayerViewSchema = z29.strictObject({
19700
+ id: z29.int(),
19701
+ kind: z29.enum(LAYER_KINDS),
19702
+ source: z29.string()
19703
+ });
19704
+ var CheckEntryViewSchema = z29.strictObject({
19705
+ path: z29.string(),
19706
+ shared: z29.boolean(),
19707
+ via: z29.enum(DECISION_VIAS),
18966
19708
  /** The entry's real category, or null when nothing classifies it. */
18967
- category: z28.enum(CATEGORY_NAMES).nullable(),
18968
- rule: z28.strictObject({ key: z28.string(), layer: z28.int() }).optional(),
19709
+ category: z29.enum(CATEGORY_NAMES).nullable(),
19710
+ rule: z29.strictObject({ key: z29.string(), layer: z29.int() }).optional(),
18969
19711
  /** Rules that matched but whose `when` condition failed, each with the conditions that failed. */
18970
- eliminated: z28.readonly(z28.array(z28.strictObject({ key: z28.string(), failed: z28.readonly(z28.array(z28.string())) }))).optional()
18971
- });
18972
- var CheckDiagnosticSchema = z28.strictObject({
18973
- code: z28.enum(DIAGNOSTIC_CODES),
18974
- severity: z28.enum(DIAGNOSTIC_SEVERITIES),
18975
- message: z28.string(),
18976
- subject: z28.string().optional(),
18977
- layer: z28.int().optional()
18978
- });
18979
- var CheckAmbientCredentialSchema = z28.union([z28.strictObject({ ok: z28.literal(true) }), z28.strictObject({ ok: z28.literal(false), variable: z28.string(), message: z28.string() })]);
18980
- var CheckKeychainSchema = z28.strictObject({
18981
- checked: z28.literal(true),
18982
- found: z28.boolean(),
18983
- serviceName: z28.string().optional(),
18984
- note: z28.string()
18985
- });
18986
- var CheckSettingsExposureSchema = z28.strictObject({
18987
- file: z28.string(),
18988
- envKeyNames: z28.readonly(z28.array(z28.string())),
18989
- hookEventNames: z28.readonly(z28.array(z28.string())),
18990
- hookCommandCount: z28.int().nonnegative()
18991
- });
18992
- var CredentialSourceSummarySchema = z28.union([
18993
- z28.strictObject({ kind: z28.literal("env"), variable: z28.string() }),
18994
- z28.strictObject({ kind: z28.literal("file"), path: z28.string() }),
18995
- z28.strictObject({ kind: z28.literal("command"), program: z28.string() }),
18996
- z28.strictObject({ kind: z28.literal("op"), reference: z28.string() }),
18997
- z28.strictObject({ kind: z28.literal("keychain"), service: z28.string(), account: z28.string().optional() }),
18998
- z28.strictObject({ kind: z28.literal("literal") })
19712
+ eliminated: z29.readonly(z29.array(z29.strictObject({ key: z29.string(), failed: z29.readonly(z29.array(z29.string())) }))).optional()
19713
+ });
19714
+ var CheckDiagnosticSchema = z29.strictObject({
19715
+ code: z29.enum(DIAGNOSTIC_CODES),
19716
+ severity: z29.enum(DIAGNOSTIC_SEVERITIES),
19717
+ message: z29.string(),
19718
+ subject: z29.string().optional(),
19719
+ layer: z29.int().optional()
19720
+ });
19721
+ var CheckAmbientCredentialSchema = z29.union([z29.strictObject({ ok: z29.literal(true) }), z29.strictObject({ ok: z29.literal(false), variable: z29.string(), message: z29.string() })]);
19722
+ var CheckKeychainSchema = z29.strictObject({
19723
+ checked: z29.literal(true),
19724
+ found: z29.boolean(),
19725
+ serviceName: z29.string().optional(),
19726
+ note: z29.string()
19727
+ });
19728
+ var CheckSettingsExposureSchema = z29.strictObject({
19729
+ file: z29.string(),
19730
+ envKeyNames: z29.readonly(z29.array(z29.string())),
19731
+ hookEventNames: z29.readonly(z29.array(z29.string())),
19732
+ hookCommandCount: z29.int().nonnegative()
19733
+ });
19734
+ var CredentialSourceSummarySchema = z29.union([
19735
+ z29.strictObject({ kind: z29.literal("env"), variable: z29.string() }),
19736
+ z29.strictObject({ kind: z29.literal("file"), path: z29.string() }),
19737
+ z29.strictObject({ kind: z29.literal("command"), program: z29.string() }),
19738
+ z29.strictObject({ kind: z29.literal("op"), reference: z29.string() }),
19739
+ z29.strictObject({ kind: z29.literal("keychain"), service: z29.string(), account: z29.string().optional() }),
19740
+ z29.strictObject({ kind: z29.literal("literal") })
18999
19741
  ]);
19000
- var CredentialSummarySchema = z28.strictObject({
19001
- target: z28.enum(CREDENTIAL_TARGETS),
19002
- sources: z28.readonly(z28.array(CredentialSourceSummarySchema)),
19742
+ var CredentialSummarySchema = z29.strictObject({
19743
+ target: z29.enum(CREDENTIAL_TARGETS),
19744
+ sources: z29.readonly(z29.array(CredentialSourceSummarySchema)),
19003
19745
  cache: CredentialCacheSchema.optional()
19004
19746
  });
19005
- var CachedCredentialStateSchema = z28.union([
19006
- z28.strictObject({ store: z28.enum(CREDENTIAL_CACHE_STORES), status: z28.literal("empty") }),
19007
- z28.strictObject({ store: z28.enum(CREDENTIAL_CACHE_STORES), status: z28.literal("unreadable"), reason: z28.string() }),
19008
- z28.strictObject({ store: z28.enum(CREDENTIAL_CACHE_STORES), status: z28.enum(["fresh", "expired"]), ageMs: z28.number(), expiresInMs: z28.number().optional() })
19747
+ var CachedCredentialStateSchema = z29.union([
19748
+ z29.strictObject({ store: z29.enum(CREDENTIAL_CACHE_STORES), status: z29.literal("empty") }),
19749
+ z29.strictObject({ store: z29.enum(CREDENTIAL_CACHE_STORES), status: z29.literal("unreadable"), reason: z29.string() }),
19750
+ z29.strictObject({ store: z29.enum(CREDENTIAL_CACHE_STORES), status: z29.enum(["fresh", "expired"]), ageMs: z29.number(), expiresInMs: z29.number().optional() })
19009
19751
  ]);
19010
- var CheckCredentialProviderSchema = z28.union([
19011
- z28.strictObject({ name: z28.string(), credential: CredentialSummarySchema.optional(), cached: CachedCredentialStateSchema.optional() }),
19012
- z28.strictObject({ name: z28.string(), problem: z28.string() })
19752
+ var CheckCredentialProviderSchema = z29.union([
19753
+ z29.strictObject({ name: z29.string(), credential: CredentialSummarySchema.optional(), cached: CachedCredentialStateSchema.optional() }),
19754
+ z29.strictObject({ name: z29.string(), problem: z29.string() })
19013
19755
  ]);
19014
- var CheckCredentialSchema = z28.strictObject({
19015
- applies: z28.enum(CHECK_CREDENTIAL_APPLIES),
19756
+ var CheckCredentialSchema = z29.strictObject({
19757
+ applies: z29.enum(CHECK_CREDENTIAL_APPLIES),
19016
19758
  provider: CheckCredentialProviderSchema.optional(),
19017
19759
  identity: CredentialSummarySchema.optional(),
19018
19760
  identityCached: CachedCredentialStateSchema.optional()
19019
19761
  });
19020
- var CheckClaudeVersionSchema = z28.strictObject({
19021
- pinned: z28.strictObject({ version: z28.string(), source: z28.enum(CLAUDE_VERSION_SOURCES), installed: z28.boolean() }).optional(),
19022
- highestInstalled: z28.string().optional(),
19023
- installed: z28.readonly(z28.array(z28.string()))
19762
+ var CheckClaudeVersionSchema = z29.strictObject({
19763
+ pinned: z29.strictObject({ version: z29.string(), source: z29.enum(CLAUDE_VERSION_SOURCES), installed: z29.boolean() }).optional(),
19764
+ highestInstalled: z29.string().optional(),
19765
+ installed: z29.readonly(z29.array(z29.string()))
19024
19766
  });
19025
- var CheckReportJsonSchema = z28.strictObject({
19026
- identity: z28.strictObject({ name: z28.string().nullable(), source: z28.enum(IDENTITY_DECISION_SOURCES) }),
19767
+ var CheckReportJsonSchema = z29.strictObject({
19768
+ identity: z29.strictObject({ name: z29.string().nullable(), source: z29.enum(IDENTITY_DECISION_SOURCES) }),
19027
19769
  /** The pool ranking, when the launch named a pool instead of an identity. */
19028
19770
  pool: PoolPickReportSchema.optional(),
19029
- configProfile: z28.strictObject({ name: z28.string().nullable(), source: z28.enum(CONFIG_PROFILE_DECISION_SOURCES) }),
19030
- layers: z28.readonly(z28.array(CheckLayerViewSchema)),
19031
- entries: z28.readonly(z28.array(CheckEntryViewSchema)),
19032
- projectEncodingAmbiguities: z28.readonly(
19033
- z28.array(z28.strictObject({ fragment: z28.string(), encoded: z28.string(), reason: z28.enum(ENCODING_AMBIGUITY_REASONS), detail: z28.string() }))
19771
+ configProfile: z29.strictObject({ name: z29.string().nullable(), source: z29.enum(CONFIG_PROFILE_DECISION_SOURCES) }),
19772
+ layers: z29.readonly(z29.array(CheckLayerViewSchema)),
19773
+ entries: z29.readonly(z29.array(CheckEntryViewSchema)),
19774
+ projectEncodingAmbiguities: z29.readonly(
19775
+ z29.array(z29.strictObject({ fragment: z29.string(), encoded: z29.string(), reason: z29.enum(ENCODING_AMBIGUITY_REASONS), detail: z29.string() }))
19034
19776
  ),
19035
- diagnostics: z28.readonly(z28.array(CheckDiagnosticSchema)),
19777
+ diagnostics: z29.readonly(z29.array(CheckDiagnosticSchema)),
19036
19778
  ambientCredential: CheckAmbientCredentialSchema,
19037
19779
  keychain: CheckKeychainSchema.optional(),
19038
- settingsExposure: z28.readonly(z28.array(CheckSettingsExposureSchema)),
19780
+ settingsExposure: z29.readonly(z29.array(CheckSettingsExposureSchema)),
19039
19781
  credential: CheckCredentialSchema,
19040
19782
  claudeVersion: CheckClaudeVersionSchema.optional()
19041
19783
  });
@@ -19046,28 +19788,28 @@ init_preflight();
19046
19788
  init_resets();
19047
19789
 
19048
19790
  // src/usage/resetsSchema.ts
19049
- import { z as z29 } from "zod";
19050
- var ResetRowSchema = z29.strictObject({
19051
- identity: z29.string(),
19052
- provider: z29.string(),
19791
+ import { z as z30 } from "zod";
19792
+ var ResetRowSchema = z30.strictObject({
19793
+ identity: z30.string(),
19794
+ provider: z30.string(),
19053
19795
  /** What the window is: `5h`, `7d` or `extra usage` for an Anthropic account, or the provider's own measure and period (`tokens 5h`). */
19054
- window: z29.string(),
19796
+ window: z30.string(),
19055
19797
  /** When the state the window comes from was observed, as an ISO instant. */
19056
- observedAt: z29.iso.datetime(),
19798
+ observedAt: z30.iso.datetime(),
19057
19799
  /** When the window resets, as an ISO instant; absent when the upstream reported none. */
19058
- resetsAt: z29.iso.datetime().optional(),
19800
+ resetsAt: z30.iso.datetime().optional(),
19059
19801
  /** True when the reset time has passed, so the recorded observation describes a window that no longer exists and its utilisation reads as 0. */
19060
- reset: z29.boolean(),
19802
+ reset: z30.boolean(),
19061
19803
  /** The fraction used, as `effectiveWindow` reads it at the report's own clock. */
19062
- utilization: z29.number().optional(),
19804
+ utilization: z30.number().optional(),
19063
19805
  /** The window's own status, for a window that has not reset yet. */
19064
- status: z29.string().optional()
19806
+ status: z30.string().optional()
19065
19807
  });
19066
- var ResetScheduleSchema = z29.strictObject({ resets: z29.readonly(z29.array(ResetRowSchema)) });
19808
+ var ResetScheduleSchema = z30.strictObject({ resets: z30.readonly(z30.array(ResetRowSchema)) });
19067
19809
 
19068
19810
  // src/frontdoor/controlSchemas.ts
19069
19811
  import path43 from "node:path";
19070
- import { z as z36 } from "zod";
19812
+ import { z as z37 } from "zod";
19071
19813
 
19072
19814
  // src/codex/doctor.ts
19073
19815
  function codexIdentityFindings(entry, identity) {
@@ -20294,92 +21036,92 @@ function collectDoctorReport(params) {
20294
21036
  // src/frontdoor/controlSchemas.ts
20295
21037
  init_schema2();
20296
21038
  init_state();
20297
- var UsageListOutputSchema = z36.strictObject({ snapshots: z36.readonly(z36.array(UsageSnapshotSchema)) });
20298
- var UsageWindowsInputSchema = z36.strictObject({
20299
- identity: z36.string().min(1),
20300
- provider: z36.string().min(1).optional()
21039
+ var UsageListOutputSchema = z37.strictObject({ snapshots: z37.readonly(z37.array(UsageSnapshotSchema)) });
21040
+ var UsageWindowsInputSchema = z37.strictObject({
21041
+ identity: z37.string().min(1),
21042
+ provider: z37.string().min(1).optional()
20301
21043
  });
20302
- var EffectiveWindowSchema = z36.strictObject({
21044
+ var EffectiveWindowSchema = z37.strictObject({
20303
21045
  /** True when the window's reset time has passed, so the recorded observation describes a window that no longer exists. */
20304
- reset: z36.boolean(),
21046
+ reset: z37.boolean(),
20305
21047
  /** The fraction used: 0 for a reset window, otherwise what was last observed, absent when none was reported. */
20306
- utilization: z36.number().optional(),
21048
+ utilization: z37.number().optional(),
20307
21049
  /** The reset instant, for a window that has not reset yet and reported one. */
20308
- resetsAtMs: z36.number().optional(),
21050
+ resetsAtMs: z37.number().optional(),
20309
21051
  /** The window's own status, for a window that has not reset yet. */
20310
- status: z36.string().optional()
21052
+ status: z37.string().optional()
20311
21053
  });
20312
- var UsageWindowsOutputSchema = z36.strictObject({
20313
- identity: z36.string(),
20314
- provider: z36.string(),
21054
+ var UsageWindowsOutputSchema = z37.strictObject({
21055
+ identity: z37.string(),
21056
+ provider: z37.string(),
20315
21057
  /** When the rate-limit state the windows come from was observed. */
20316
- observedAt: z36.iso.datetime().optional(),
21058
+ observedAt: z37.iso.datetime().optional(),
20317
21059
  fiveHour: EffectiveWindowSchema.optional(),
20318
21060
  sevenDay: EffectiveWindowSchema.optional()
20319
21061
  });
20320
- var UsageLiveOutputSchema = z36.strictObject({
21062
+ var UsageLiveOutputSchema = z37.strictObject({
20321
21063
  /** The freshest observation the door holds, never narrowed by the read's session filter because it is the door's single latest statement of the account's quota; absent while no rate_limit_event has been filed at all. */
20322
21064
  latest: RcLiveRateLimitSchema.optional(),
20323
21065
  /** One observation per session whose stream has filed a rate_limit_event this door generation. */
20324
- sessions: z36.readonly(z36.array(RcLiveRateLimitSchema))
21066
+ sessions: z37.readonly(z37.array(RcLiveRateLimitSchema))
20325
21067
  });
20326
- var FrontDoorSessionStatusSchema = z36.strictObject({
20327
- pid: z36.int().positive(),
20328
- startedAt: z36.number(),
20329
- alive: z36.boolean()
21068
+ var FrontDoorSessionStatusSchema = z37.strictObject({
21069
+ pid: z37.int().positive(),
21070
+ startedAt: z37.number(),
21071
+ alive: z37.boolean()
20330
21072
  });
20331
- var HeadroomSocketTargetSchema = z36.union([z36.strictObject({ socketPath: z36.string() }), z36.strictObject({ refused: z36.string() })]);
20332
- var FrontDoorStatusOutputSchema = z36.strictObject({
21073
+ var HeadroomSocketTargetSchema = z37.union([z37.strictObject({ socketPath: z37.string() }), z37.strictObject({ refused: z37.string() })]);
21074
+ var FrontDoorStatusOutputSchema = z37.strictObject({
20333
21075
  state: FrontDoorStateSchema,
20334
- supervisorAlive: z36.boolean(),
21076
+ supervisorAlive: z37.boolean(),
20335
21077
  /** The pids of earlier doors that released their addresses and are finishing the connections they carried: running, but not serving anything new. */
20336
- draining: z36.readonly(z36.array(z36.number().int().positive())),
20337
- sessions: z36.readonly(z36.array(FrontDoorSessionStatusSchema)),
21078
+ draining: z37.readonly(z37.array(z37.number().int().positive())),
21079
+ sessions: z37.readonly(z37.array(FrontDoorSessionStatusSchema)),
20338
21080
  headroomSocket: HeadroomSocketTargetSchema.optional(),
20339
- logPath: z36.string(),
20340
- logExists: z36.boolean()
21081
+ logPath: z37.string(),
21082
+ logExists: z37.boolean()
20341
21083
  });
20342
- var FrontDoorSessionsOutputSchema = z36.strictObject({ sessions: z36.readonly(z36.array(FrontDoorSessionStatusSchema)) });
20343
- var CheckRunInputSchema = z36.strictObject({
20344
- path: z36.string().min(1),
20345
- identity: z36.string().min(1).optional()
21084
+ var FrontDoorSessionsOutputSchema = z37.strictObject({ sessions: z37.readonly(z37.array(FrontDoorSessionStatusSchema)) });
21085
+ var CheckRunInputSchema = z37.strictObject({
21086
+ path: z37.string().min(1),
21087
+ identity: z37.string().min(1).optional()
20346
21088
  }).refine((input) => path43.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
20347
- var PoolPickInputSchema = z36.strictObject({
20348
- pool: z36.string().min(1),
20349
- path: z36.string().min(1)
21089
+ var PoolPickInputSchema = z37.strictObject({
21090
+ pool: z37.string().min(1),
21091
+ path: z37.string().min(1)
20350
21092
  }).refine((input) => path43.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
20351
- var DoctorFindingSchema = z36.strictObject({
20352
- section: z36.enum(DOCTOR_SECTIONS),
20353
- subject: z36.string().optional(),
20354
- severity: z36.enum(DOCTOR_SEVERITIES),
20355
- message: z36.string()
21093
+ var DoctorFindingSchema = z37.strictObject({
21094
+ section: z37.enum(DOCTOR_SECTIONS),
21095
+ subject: z37.string().optional(),
21096
+ severity: z37.enum(DOCTOR_SEVERITIES),
21097
+ message: z37.string()
20356
21098
  });
20357
- var DoctorRunOutputSchema = z36.strictObject({
21099
+ var DoctorRunOutputSchema = z37.strictObject({
20358
21100
  /** False exactly when any finding is a `fail`; a `warn` never fails the report on its own. */
20359
- ok: z36.boolean(),
20360
- findings: z36.readonly(z36.array(DoctorFindingSchema))
20361
- });
20362
- var FrontDoorRestartOutputSchema = z36.strictObject({
20363
- action: z36.literal("restarting"),
20364
- previousPid: z36.int().positive()
20365
- });
20366
- var UpdateCheckOutputSchema = z36.strictObject({
20367
- current: z36.string(),
20368
- latest: z36.string(),
20369
- action: z36.enum(["current", "available", "updated"])
20370
- });
20371
- var CodexSignInSchema = z36.discriminatedUnion("state", [
20372
- z36.strictObject({ state: z36.literal("none") }),
20373
- z36.strictObject({ state: z36.literal("signed-in"), email: z36.string().optional(), planScope: z36.boolean(), accessTokenExpiresAt: z36.number() }),
20374
- z36.strictObject({ state: z36.literal("unreadable"), message: z36.string() })
21101
+ ok: z37.boolean(),
21102
+ findings: z37.readonly(z37.array(DoctorFindingSchema))
21103
+ });
21104
+ var FrontDoorRestartOutputSchema = z37.strictObject({
21105
+ action: z37.literal("restarting"),
21106
+ previousPid: z37.int().positive()
21107
+ });
21108
+ var UpdateCheckOutputSchema = z37.strictObject({
21109
+ current: z37.string(),
21110
+ latest: z37.string(),
21111
+ action: z37.enum(["current", "available", "updated"])
21112
+ });
21113
+ var CodexSignInSchema = z37.discriminatedUnion("state", [
21114
+ z37.strictObject({ state: z37.literal("none") }),
21115
+ z37.strictObject({ state: z37.literal("signed-in"), email: z37.string().optional(), planScope: z37.boolean(), accessTokenExpiresAt: z37.number() }),
21116
+ z37.strictObject({ state: z37.literal("unreadable"), message: z37.string() })
20375
21117
  ]);
20376
- var CodexStatusOutputSchema = z36.strictObject({
21118
+ var CodexStatusOutputSchema = z37.strictObject({
20377
21119
  signIn: CodexSignInSchema,
20378
- codexProviders: z36.readonly(z36.array(z36.string()))
21120
+ codexProviders: z37.readonly(z37.array(z37.string()))
20379
21121
  });
20380
- var CodexLogoutOutputSchema = z36.strictObject({
20381
- hadGrant: z36.boolean(),
20382
- revoked: z36.boolean()
21122
+ var CodexLogoutOutputSchema = z37.strictObject({
21123
+ hadGrant: z37.boolean(),
21124
+ revoked: z37.boolean()
20383
21125
  });
20384
21126
 
20385
21127
  // src/frontdoor/codexApi.ts
@@ -20447,67 +21189,67 @@ init_schema();
20447
21189
  init_names();
20448
21190
  init_keychainLogin();
20449
21191
  init_statusline();
20450
- import { z as z37 } from "zod";
20451
- var RemovalConfirmationSchema = z37.boolean();
20452
- var CredentialWriteSchema = (targets) => z37.strictObject({
20453
- sources: z37.array(RemoteCredentialSourceSchema).min(1).optional(),
20454
- target: z37.enum(targets).optional(),
20455
- cache: z37.union([z37.literal(false), CredentialCacheSchema]).optional()
20456
- });
20457
- var CredentialSummarySchema2 = z37.strictObject({
20458
- target: z37.enum(CREDENTIAL_TARGETS),
20459
- sources: z37.readonly(z37.array(
20460
- z37.discriminatedUnion("kind", [
20461
- z37.strictObject({ kind: z37.literal("env"), variable: z37.string() }),
20462
- z37.strictObject({ kind: z37.literal("file"), path: z37.string() }),
20463
- z37.strictObject({ kind: z37.literal("command"), program: z37.string() }),
20464
- z37.strictObject({ kind: z37.literal("op"), reference: z37.string() }),
20465
- z37.strictObject({ kind: z37.literal("keychain"), service: z37.string(), account: z37.string().optional() }),
20466
- z37.strictObject({ kind: z37.literal("literal") })
21192
+ import { z as z38 } from "zod";
21193
+ var RemovalConfirmationSchema = z38.boolean();
21194
+ var CredentialWriteSchema = (targets) => z38.strictObject({
21195
+ sources: z38.array(RemoteCredentialSourceSchema).min(1).optional(),
21196
+ target: z38.enum(targets).optional(),
21197
+ cache: z38.union([z38.literal(false), CredentialCacheSchema]).optional()
21198
+ });
21199
+ var CredentialSummarySchema2 = z38.strictObject({
21200
+ target: z38.enum(CREDENTIAL_TARGETS),
21201
+ sources: z38.readonly(z38.array(
21202
+ z38.discriminatedUnion("kind", [
21203
+ z38.strictObject({ kind: z38.literal("env"), variable: z38.string() }),
21204
+ z38.strictObject({ kind: z38.literal("file"), path: z38.string() }),
21205
+ z38.strictObject({ kind: z38.literal("command"), program: z38.string() }),
21206
+ z38.strictObject({ kind: z38.literal("op"), reference: z38.string() }),
21207
+ z38.strictObject({ kind: z38.literal("keychain"), service: z38.string(), account: z38.string().optional() }),
21208
+ z38.strictObject({ kind: z38.literal("literal") })
20467
21209
  ])
20468
21210
  )),
20469
21211
  cache: CredentialCacheSchema.optional()
20470
21212
  });
20471
- var mutationOutput = (kind, action) => z37.strictObject({ action: z37.literal(action), kind: z37.literal(kind), name: z37.string() });
20472
- var storedMutationOutput = (kind, action, value) => z37.strictObject({ action: z37.literal(action), kind: z37.literal(kind), name: z37.string(), value });
20473
- var IdentityValueSchema = z37.strictObject({
20474
- name: z37.string(),
20475
- label: z37.string().optional(),
20476
- defaultConfigProfile: z37.string().optional(),
20477
- provider: z37.string().optional(),
20478
- allowAmbientCredential: z37.boolean(),
21213
+ var mutationOutput = (kind, action) => z38.strictObject({ action: z38.literal(action), kind: z38.literal(kind), name: z38.string() });
21214
+ var storedMutationOutput = (kind, action, value) => z38.strictObject({ action: z38.literal(action), kind: z38.literal(kind), name: z38.string(), value });
21215
+ var IdentityValueSchema = z38.strictObject({
21216
+ name: z38.string(),
21217
+ label: z38.string().optional(),
21218
+ defaultConfigProfile: z38.string().optional(),
21219
+ provider: z38.string().optional(),
21220
+ allowAmbientCredential: z38.boolean(),
20479
21221
  credential: CredentialSummarySchema2.optional(),
20480
- anchors: z37.array(AnchorSchema).optional()
21222
+ anchors: z38.array(AnchorSchema).optional()
20481
21223
  });
20482
21224
  var ProfileValueSchema = ConfigProfileSchema.omit({ $schema: true });
20483
- var ProviderValueSchema = z37.strictObject({
20484
- name: z37.string(),
20485
- kind: z37.enum(PROVIDER_KINDS),
20486
- displayName: z37.string(),
20487
- baseUrl: z37.string().optional(),
21225
+ var ProviderValueSchema = z38.strictObject({
21226
+ name: z38.string(),
21227
+ kind: z38.enum(PROVIDER_KINDS),
21228
+ displayName: z38.string(),
21229
+ baseUrl: z38.string().optional(),
20488
21230
  codex: CodexProviderConfigSchema.optional(),
20489
21231
  credential: CredentialSummarySchema2.optional(),
20490
- env: z37.record(z37.string(), z37.string()).optional()
21232
+ env: z38.record(z38.string(), z38.string()).optional()
20491
21233
  });
20492
- var ConfigNameInputSchema = z37.strictObject({ name: z37.string().min(1) });
20493
- var ConfigIdentityAddInputSchema = z37.strictObject({ name: z37.string().min(1), keepKeychainLogin: z37.boolean().optional().describe(KEEP_KEYCHAIN_LOGIN_DESCRIPTION) });
21234
+ var ConfigNameInputSchema = z38.strictObject({ name: z38.string().min(1) });
21235
+ var ConfigIdentityAddInputSchema = z38.strictObject({ name: z38.string().min(1), keepKeychainLogin: z38.boolean().optional().describe(KEEP_KEYCHAIN_LOGIN_DESCRIPTION) });
20494
21236
  var ConfigIdentityAddOutputSchema = storedMutationOutput("identity", "created", IdentityValueSchema);
20495
- var ConfigIdentitySetInputSchema = z37.strictObject({
20496
- name: z37.string().min(1),
21237
+ var ConfigIdentitySetInputSchema = z38.strictObject({
21238
+ name: z38.string().min(1),
20497
21239
  /** The identity's display label; `false` clears it. */
20498
- label: z37.union([IdentityLabelSchema, z37.literal(false)]).optional(),
20499
- defaultConfigProfile: z37.union([z37.string().min(1), z37.literal(false)]).optional(),
21240
+ label: z38.union([IdentityLabelSchema, z38.literal(false)]).optional(),
21241
+ defaultConfigProfile: z38.union([z38.string().min(1), z38.literal(false)]).optional(),
20500
21242
  /** The provider the identity exists for; `false` clears it. */
20501
- provider: z37.union([z37.string().min(1), z37.literal(false)]).optional(),
20502
- allowAmbientCredential: z37.boolean().optional(),
20503
- credential: z37.union([z37.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
21243
+ provider: z38.union([z38.string().min(1), z38.literal(false)]).optional(),
21244
+ allowAmbientCredential: z38.boolean().optional(),
21245
+ credential: z38.union([z38.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
20504
21246
  /** `false` removes the anchors; a list replaces them. */
20505
- anchors: z37.union([z37.literal(false), z37.array(AnchorSchema).min(1)]).optional()
21247
+ anchors: z38.union([z38.literal(false), z38.array(AnchorSchema).min(1)]).optional()
20506
21248
  });
20507
21249
  var ConfigIdentitySetOutputSchema = storedMutationOutput("identity", "updated", IdentityValueSchema);
20508
- var ConfigIdentityRemoveInputSchema = z37.strictObject({ name: z37.string().min(1), confirm: RemovalConfirmationSchema });
21250
+ var ConfigIdentityRemoveInputSchema = z38.strictObject({ name: z38.string().min(1), confirm: RemovalConfirmationSchema });
20509
21251
  var ConfigIdentityRemoveOutputSchema = mutationOutput("identity", "removed");
20510
- var ConfigStatuslineSetSchema = z37.record(z37.string(), z37.unknown()).superRefine((settings, context) => {
21252
+ var ConfigStatuslineSetSchema = z38.record(z38.string(), z38.unknown()).superRefine((settings, context) => {
20511
21253
  for (const key of Object.keys(settings)) {
20512
21254
  if (key === STATUSLINE_EXTRA_GROUP || key.startsWith(`${STATUSLINE_EXTRA_GROUP}.`)) {
20513
21255
  context.addIssue({ code: "custom", path: [key], message: `a config write through the API cannot set "${key}": the extra segment's command runs a program, so only your own configuration (the global config, a profile you edit yourself, a directory rule or a command-line assignment) may set it` });
@@ -20515,93 +21257,93 @@ var ConfigStatuslineSetSchema = z37.record(z37.string(), z37.unknown()).superRef
20515
21257
  }
20516
21258
  });
20517
21259
  var ConfigIdentityUseOutputSchema = mutationOutput("identity", "selected");
20518
- var ConfigProfileAddInputSchema = z37.strictObject({
20519
- name: z37.string().min(1),
20520
- extends: z37.array(z37.string().min(1)).optional(),
20521
- description: z37.string().optional()
21260
+ var ConfigProfileAddInputSchema = z38.strictObject({
21261
+ name: z38.string().min(1),
21262
+ extends: z38.array(z38.string().min(1)).optional(),
21263
+ description: z38.string().optional()
20522
21264
  });
20523
21265
  var ConfigProfileAddOutputSchema = storedMutationOutput("profile", "created", ProfileValueSchema);
20524
- var ConfigProfileSetInputSchema = z37.strictObject({
20525
- name: z37.string().min(1),
20526
- category: z37.record(z37.string(), z37.boolean()).optional(),
20527
- entry: z37.record(z37.string(), z37.boolean()).optional(),
20528
- extends: z37.union([z37.array(z37.string().min(1)), z37.literal(false)]).optional(),
20529
- description: z37.union([z37.string(), z37.literal(false)]).optional(),
20530
- launch: z37.strictObject({
20531
- skipPermissions: z37.boolean().optional(),
20532
- remoteControl: z37.boolean().optional(),
20533
- headroom: z37.boolean().optional(),
20534
- trackUsage: z37.boolean().optional(),
20535
- provider: z37.union([z37.string().min(1), z37.literal(false)]).optional(),
20536
- claudeVersion: z37.union([z37.string().min(1), z37.literal(false)]).optional(),
20537
- delay: z37.union([z37.string().regex(DURATION_RE), z37.literal(false)]).optional(),
20538
- pause: z37.boolean().optional(),
20539
- explain: z37.boolean().optional(),
20540
- proxyBypass: z37.union([z37.array(z37.string().min(1)), z37.literal(false)]).optional(),
20541
- statusline: z37.strictObject({
21266
+ var ConfigProfileSetInputSchema = z38.strictObject({
21267
+ name: z38.string().min(1),
21268
+ category: z38.record(z38.string(), z38.boolean()).optional(),
21269
+ entry: z38.record(z38.string(), z38.boolean()).optional(),
21270
+ extends: z38.union([z38.array(z38.string().min(1)), z38.literal(false)]).optional(),
21271
+ description: z38.union([z38.string(), z38.literal(false)]).optional(),
21272
+ launch: z38.strictObject({
21273
+ skipPermissions: z38.boolean().optional(),
21274
+ remoteControl: z38.boolean().optional(),
21275
+ headroom: z38.boolean().optional(),
21276
+ trackUsage: z38.boolean().optional(),
21277
+ provider: z38.union([z38.string().min(1), z38.literal(false)]).optional(),
21278
+ claudeVersion: z38.union([z38.string().min(1), z38.literal(false)]).optional(),
21279
+ delay: z38.union([z38.string().regex(DURATION_RE), z38.literal(false)]).optional(),
21280
+ pause: z38.boolean().optional(),
21281
+ explain: z38.boolean().optional(),
21282
+ proxyBypass: z38.union([z38.array(z38.string().min(1)), z38.literal(false)]).optional(),
21283
+ statusline: z38.strictObject({
20542
21284
  set: ConfigStatuslineSetSchema.optional(),
20543
- unset: z37.array(z37.string()).optional()
21285
+ unset: z38.array(z38.string()).optional()
20544
21286
  }).optional()
20545
21287
  }).optional()
20546
21288
  });
20547
21289
  var ConfigProfileSetOutputSchema = storedMutationOutput("profile", "updated", ProfileValueSchema);
20548
- var ConfigProfileRemoveInputSchema = z37.strictObject({ name: z37.string().min(1), confirm: RemovalConfirmationSchema });
21290
+ var ConfigProfileRemoveInputSchema = z38.strictObject({ name: z38.string().min(1), confirm: RemovalConfirmationSchema });
20549
21291
  var ConfigProfileRemoveOutputSchema = mutationOutput("profile", "removed");
20550
21292
  var ConfigProfileUseOutputSchema = mutationOutput("profile", "selected");
20551
- var PoolMembersInputSchema = z37.array(z37.string().min(1)).min(1);
20552
- var ConfigPoolAddInputSchema = z37.strictObject({
20553
- name: z37.string().min(1),
21293
+ var PoolMembersInputSchema = z38.array(z38.string().min(1)).min(1);
21294
+ var ConfigPoolAddInputSchema = z38.strictObject({
21295
+ name: z38.string().min(1),
20554
21296
  identities: PoolMembersInputSchema,
20555
- preference: z37.enum(POOL_PREFERENCES).optional(),
20556
- resumeOnLimit: z37.boolean().optional(),
20557
- compactBeforeLimit: z37.boolean().optional(),
21297
+ preference: z38.enum(POOL_PREFERENCES).optional(),
21298
+ resumeOnLimit: z38.boolean().optional(),
21299
+ compactBeforeLimit: z38.boolean().optional(),
20558
21300
  compactAtUtilisation: CompactAtUtilisationSchema.optional()
20559
21301
  });
20560
21302
  var ConfigPoolAddOutputSchema = storedMutationOutput("pool", "created", PoolSchema);
20561
- var ConfigPoolSetInputSchema = z37.strictObject({
20562
- name: z37.string().min(1),
21303
+ var ConfigPoolSetInputSchema = z38.strictObject({
21304
+ name: z38.string().min(1),
20563
21305
  identities: PoolMembersInputSchema.optional(),
20564
- preference: z37.union([z37.enum(POOL_PREFERENCES), z37.literal(false)]).optional(),
20565
- resumeOnLimit: z37.boolean().optional(),
20566
- compactBeforeLimit: z37.boolean().optional(),
20567
- compactAtUtilisation: z37.union([CompactAtUtilisationSchema, z37.literal(false)]).optional()
21306
+ preference: z38.union([z38.enum(POOL_PREFERENCES), z38.literal(false)]).optional(),
21307
+ resumeOnLimit: z38.boolean().optional(),
21308
+ compactBeforeLimit: z38.boolean().optional(),
21309
+ compactAtUtilisation: z38.union([CompactAtUtilisationSchema, z38.literal(false)]).optional()
20568
21310
  });
20569
21311
  var ConfigPoolSetOutputSchema = storedMutationOutput("pool", "updated", PoolSchema);
20570
- var ConfigPoolRemoveInputSchema = z37.strictObject({ name: z37.string().min(1), confirm: RemovalConfirmationSchema });
21312
+ var ConfigPoolRemoveInputSchema = z38.strictObject({ name: z38.string().min(1), confirm: RemovalConfirmationSchema });
20571
21313
  var ConfigPoolRemoveOutputSchema = mutationOutput("pool", "removed");
20572
21314
  var ConfigPoolUseOutputSchema = mutationOutput("pool", "selected");
20573
- var ConfigProviderAddInputSchema = z37.strictObject({
20574
- name: z37.string().min(1),
20575
- kind: z37.enum(PROVIDER_KINDS).optional(),
20576
- displayName: z37.string().min(1),
20577
- baseUrl: z37.string().min(1).optional(),
21315
+ var ConfigProviderAddInputSchema = z38.strictObject({
21316
+ name: z38.string().min(1),
21317
+ kind: z38.enum(PROVIDER_KINDS).optional(),
21318
+ displayName: z38.string().min(1),
21319
+ baseUrl: z38.string().min(1).optional(),
20578
21320
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).required({ sources: true }),
20579
21321
  codex: CodexProviderConfigSchema.optional()
20580
21322
  });
20581
21323
  var ConfigProviderAddOutputSchema = storedMutationOutput("provider", "created", ProviderValueSchema);
20582
- var ConfigProviderSetInputSchema = z37.strictObject({
20583
- name: z37.string().min(1),
20584
- displayName: z37.string().min(1).optional(),
20585
- baseUrl: z37.string().min(1).optional(),
21324
+ var ConfigProviderSetInputSchema = z38.strictObject({
21325
+ name: z38.string().min(1),
21326
+ displayName: z38.string().min(1).optional(),
21327
+ baseUrl: z38.string().min(1).optional(),
20586
21328
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).optional(),
20587
21329
  codex: CodexProviderConfigSchema.optional()
20588
21330
  });
20589
21331
  var ConfigProviderSetOutputSchema = storedMutationOutput("provider", "updated", ProviderValueSchema);
20590
- var ConfigProviderRemoveInputSchema = z37.strictObject({ name: z37.string().min(1), confirm: RemovalConfirmationSchema });
21332
+ var ConfigProviderRemoveInputSchema = z38.strictObject({ name: z38.string().min(1), confirm: RemovalConfirmationSchema });
20591
21333
  var ConfigProviderRemoveOutputSchema = mutationOutput("provider", "removed");
20592
- var ConfigRuleAddInputSchema = z37.strictObject({
20593
- path: z37.string().min(1),
20594
- configProfile: z37.string().min(1).optional(),
20595
- identity: z37.string().min(1).optional()
21334
+ var ConfigRuleAddInputSchema = z38.strictObject({
21335
+ path: z38.string().min(1),
21336
+ configProfile: z38.string().min(1).optional(),
21337
+ identity: z38.string().min(1).optional()
20596
21338
  });
20597
21339
  var ConfigRuleAddOutputSchema = storedMutationOutput("rule", "created", DirectoryRuleSchema);
20598
- var ConfigRuleSetInputSchema = z37.strictObject({
20599
- path: z37.string().min(1),
20600
- configProfile: z37.union([z37.string().min(1), z37.literal(false)]).optional(),
20601
- identity: z37.union([z37.string().min(1), z37.literal(false)]).optional()
21340
+ var ConfigRuleSetInputSchema = z38.strictObject({
21341
+ path: z38.string().min(1),
21342
+ configProfile: z38.union([z38.string().min(1), z38.literal(false)]).optional(),
21343
+ identity: z38.union([z38.string().min(1), z38.literal(false)]).optional()
20602
21344
  });
20603
21345
  var ConfigRuleSetOutputSchema = storedMutationOutput("rule", "updated", DirectoryRuleSchema);
20604
- var ConfigRuleRemoveInputSchema = z37.strictObject({ path: z37.string().min(1), confirm: RemovalConfirmationSchema });
21346
+ var ConfigRuleRemoveInputSchema = z38.strictObject({ path: z38.string().min(1), confirm: RemovalConfirmationSchema });
20605
21347
  var ConfigRuleRemoveOutputSchema = mutationOutput("rule", "removed");
20606
21348
 
20607
21349
  // src/frontdoor/configApi.ts
@@ -20954,50 +21696,50 @@ import { eventIterator as eventIterator2, withEventMeta as withEventMeta2 } from
20954
21696
 
20955
21697
  // src/frontdoor/eventSchemas.ts
20956
21698
  init_schema2();
20957
- import { z as z38 } from "zod";
21699
+ import { z as z39 } from "zod";
20958
21700
  var DOOR_EVENT_SOURCE_RC = "rc";
20959
21701
  var LAUNCH_EVENT_SOURCE = "launch";
20960
21702
  var USAGE_EVENT_SOURCE = "usage";
20961
21703
  var DOOR_HEALTH_EVENT_SOURCE = "door";
20962
21704
  var QUOTA_EXPIRING_EVENT_SOURCE = "quota-expiring";
20963
- var DoorEventSchema = z38.strictObject({
20964
- source: z38.string().min(1),
21705
+ var DoorEventSchema = z39.strictObject({
21706
+ source: z39.string().min(1),
20965
21707
  /** A positive integer because the backbone's counters start at one and only ever increase. */
20966
- sequence: z38.number().int().positive(),
20967
- payload: z38.unknown()
20968
- });
20969
- var DoorEventSourceQuerySchema = z38.strictObject({
20970
- sources: z38.array(z38.string().min(1)).min(1).optional()
20971
- });
20972
- var LaunchLifecycleEventSchema = z38.strictObject({
20973
- kind: z38.enum(["registered", "pruned", "ended"]),
20974
- pid: z38.number().int().positive(),
20975
- startedAt: z38.number(),
20976
- observedAt: z38.number()
20977
- });
20978
- var DoorHealthEventSchema = z38.discriminatedUnion("kind", [
20979
- z38.strictObject({ kind: z38.literal("generation"), pid: z38.number().int().positive(), providerPort: z38.number().int().positive(), connectPort: z38.number().int().positive(), directPort: z38.number().int().positive(), observedAt: z38.number() }),
20980
- z38.strictObject({ kind: z38.literal("listenerFailed"), pid: z38.number().int().positive(), listener: z38.enum(["provider", "connect", "direct"]), message: z38.string(), observedAt: z38.number() }),
20981
- z38.strictObject({ kind: z38.literal("binaryTurnover"), pid: z38.number().int().positive(), observedAt: z38.number() }),
20982
- z38.strictObject({ kind: z38.literal("idleShutdown"), pid: z38.number().int().positive(), observedAt: z38.number() }),
20983
- z38.strictObject({ kind: z38.literal("superseded"), pid: z38.number().int().positive(), ownerPid: z38.number().int().positive(), observedAt: z38.number() }),
20984
- z38.strictObject({ kind: z38.literal("drained"), pid: z38.number().int().positive(), observedAt: z38.number() })
21708
+ sequence: z39.number().int().positive(),
21709
+ payload: z39.unknown()
21710
+ });
21711
+ var DoorEventSourceQuerySchema = z39.strictObject({
21712
+ sources: z39.array(z39.string().min(1)).min(1).optional()
21713
+ });
21714
+ var LaunchLifecycleEventSchema = z39.strictObject({
21715
+ kind: z39.enum(["registered", "pruned", "ended"]),
21716
+ pid: z39.number().int().positive(),
21717
+ startedAt: z39.number(),
21718
+ observedAt: z39.number()
21719
+ });
21720
+ var DoorHealthEventSchema = z39.discriminatedUnion("kind", [
21721
+ z39.strictObject({ kind: z39.literal("generation"), pid: z39.number().int().positive(), providerPort: z39.number().int().positive(), connectPort: z39.number().int().positive(), directPort: z39.number().int().positive(), observedAt: z39.number() }),
21722
+ z39.strictObject({ kind: z39.literal("listenerFailed"), pid: z39.number().int().positive(), listener: z39.enum(["provider", "connect", "direct"]), message: z39.string(), observedAt: z39.number() }),
21723
+ z39.strictObject({ kind: z39.literal("binaryTurnover"), pid: z39.number().int().positive(), observedAt: z39.number() }),
21724
+ z39.strictObject({ kind: z39.literal("idleShutdown"), pid: z39.number().int().positive(), observedAt: z39.number() }),
21725
+ z39.strictObject({ kind: z39.literal("superseded"), pid: z39.number().int().positive(), ownerPid: z39.number().int().positive(), observedAt: z39.number() }),
21726
+ z39.strictObject({ kind: z39.literal("drained"), pid: z39.number().int().positive(), observedAt: z39.number() })
20985
21727
  ]);
20986
- var QuotaExpiringEventSchema = z38.strictObject({
21728
+ var QuotaExpiringEventSchema = z39.strictObject({
20987
21729
  /** The id of the identity whose window it is: what its usage is filed under, which a rename keeps. */
20988
- id: z38.string().min(1),
21730
+ id: z39.string().min(1),
20989
21731
  /** The identity's name when the event was published, absent for an identity no longer stored under the id. */
20990
- name: z38.string().min(1).optional(),
20991
- provider: z38.string().min(1),
20992
- window: z38.enum(["fiveHour", "sevenDay"]),
21732
+ name: z39.string().min(1).optional(),
21733
+ provider: z39.string().min(1),
21734
+ window: z39.enum(["fiveHour", "sevenDay"]),
20993
21735
  /** The fraction of the window already used when it was seen expiring, always below one because a fully used window has nothing left to spend. */
20994
- utilization: z38.number().min(0).max(1),
20995
- resetsAt: z38.iso.datetime(),
20996
- observedAt: z38.number()
21736
+ utilization: z39.number().min(0).max(1),
21737
+ resetsAt: z39.iso.datetime(),
21738
+ observedAt: z39.number()
20997
21739
  });
20998
21740
  var UsageChangeEventSchema = UsageSnapshotSchema.extend({
20999
- id: z38.string().min(1),
21000
- name: z38.string().min(1).optional()
21741
+ id: z39.string().min(1),
21742
+ name: z39.string().min(1).optional()
21001
21743
  });
21002
21744
 
21003
21745
  // src/frontdoor/eventsApi.ts
@@ -21042,14 +21784,14 @@ function createEventsApiRouter(deps) {
21042
21784
  init_update();
21043
21785
  import { ORPCError as ORPCError4 } from "@orpc/client";
21044
21786
  import { openapi as openapi5 } from "@orpc/openapi";
21045
- import { z as z39 } from "zod";
21787
+ import { z as z40 } from "zod";
21046
21788
  var FRONTDOOR_API_TAG = "frontdoor";
21047
21789
  var UPDATE_API_TAG = "update";
21048
21790
  function createLifecycleApiRouter(deps) {
21049
21791
  const authed = doorApiAuth(deps.expectedToken);
21050
21792
  return {
21051
21793
  frontdoor: {
21052
- refreshCatalogues: authed.meta(openapi5({ method: "POST", path: "/rest/frontdoor/catalogues/refresh", summary: "Request a catalogue refresh tick", tags: [FRONTDOOR_API_TAG] })).output(z39.strictObject({ requested: z39.literal(true) })).handler(() => {
21794
+ refreshCatalogues: authed.meta(openapi5({ method: "POST", path: "/rest/frontdoor/catalogues/refresh", summary: "Request a catalogue refresh tick", tags: [FRONTDOOR_API_TAG] })).output(z40.strictObject({ requested: z40.literal(true) })).handler(() => {
21053
21795
  deps.refreshCatalogues();
21054
21796
  return { requested: true };
21055
21797
  }),
@@ -21086,62 +21828,62 @@ import { openapi as openapi6 } from "@orpc/openapi";
21086
21828
 
21087
21829
  // src/frontdoor/launchSchemas.ts
21088
21830
  import path44 from "node:path";
21089
- import { z as z40 } from "zod";
21831
+ import { z as z41 } from "zod";
21090
21832
  init_statusline();
21091
21833
  init_claudeVersion();
21092
21834
  init_identity();
21093
- var LaunchResolveInputSchema = z40.strictObject({
21094
- path: z40.string().min(1),
21835
+ var LaunchResolveInputSchema = z41.strictObject({
21836
+ path: z41.string().min(1),
21095
21837
  /** `@name`, launch flags, then the arguments for `claude`; empty for a bare launch. */
21096
- argv: z40.readonly(z40.array(z40.string())).optional(),
21838
+ argv: z41.readonly(z41.array(z41.string())).optional(),
21097
21839
  /** The launch's inherited environment. Absent means an empty one: the door's own environment is never a substitute for the caller's, so a caller that wants `AGENT_SHIM_*` switches or a `CLAUDE_CONFIG_DIR` considered names them here. Values are read, never reported. */
21098
- env: z40.record(z40.string(), z40.string()).optional()
21840
+ env: z41.record(z41.string(), z41.string()).optional()
21099
21841
  }).refine((input) => path44.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
21100
- var LaunchPoolDecisionSchema = z40.strictObject({
21101
- name: z40.string(),
21102
- reasons: z40.readonly(z40.array(z40.string())),
21103
- movedOff: z40.strictObject({ identity: z40.string(), reason: z40.string() }).optional()
21104
- });
21105
- var LaunchDecisionSchema = z40.strictObject({
21106
- identity: z40.string().optional(),
21107
- identityId: z40.string().optional(),
21108
- identitySource: z40.enum(IDENTITY_DECISION_SOURCES),
21842
+ var LaunchPoolDecisionSchema = z41.strictObject({
21843
+ name: z41.string(),
21844
+ reasons: z41.readonly(z41.array(z41.string())),
21845
+ movedOff: z41.strictObject({ identity: z41.string(), reason: z41.string() }).optional()
21846
+ });
21847
+ var LaunchDecisionSchema = z41.strictObject({
21848
+ identity: z41.string().optional(),
21849
+ identityId: z41.string().optional(),
21850
+ identitySource: z41.enum(IDENTITY_DECISION_SOURCES),
21109
21851
  pool: LaunchPoolDecisionSchema.optional(),
21110
21852
  /** True when `CLAUDE_CONFIG_DIR` was already set and nothing on the command line named an identity; an identity named there outranks the variable and leaves it false. */
21111
- configDirEscapeHatch: z40.boolean(),
21112
- configDir: z40.string().optional(),
21113
- configProfile: z40.string().optional(),
21114
- configProfileSource: z40.enum(CONFIG_PROFILE_DECISION_SOURCES),
21115
- provider: z40.string().optional()
21116
- });
21117
- var LaunchFlagsSchema = z40.strictObject({
21118
- skipPermissions: z40.boolean(),
21119
- remoteControl: z40.boolean(),
21120
- headroom: z40.boolean(),
21121
- trackUsage: z40.boolean(),
21122
- pause: z40.boolean(),
21123
- explain: z40.boolean(),
21853
+ configDirEscapeHatch: z41.boolean(),
21854
+ configDir: z41.string().optional(),
21855
+ configProfile: z41.string().optional(),
21856
+ configProfileSource: z41.enum(CONFIG_PROFILE_DECISION_SOURCES),
21857
+ provider: z41.string().optional()
21858
+ });
21859
+ var LaunchFlagsSchema = z41.strictObject({
21860
+ skipPermissions: z41.boolean(),
21861
+ remoteControl: z41.boolean(),
21862
+ headroom: z41.boolean(),
21863
+ trackUsage: z41.boolean(),
21864
+ pause: z41.boolean(),
21865
+ explain: z41.boolean(),
21124
21866
  /** How long the launch waits after its own output before it starts claude, in milliseconds. */
21125
- delayMs: z40.number(),
21867
+ delayMs: z41.number(),
21126
21868
  /** The hosts the launch keeps off the front door by adding them to the child's `NO_PROXY`. */
21127
- proxyBypass: z40.array(z40.string()).readonly(),
21869
+ proxyBypass: z41.array(z41.string()).readonly(),
21128
21870
  /** How the session's built-in statusline looks, when the launch configures any of it. */
21129
21871
  statusline: StatuslineSchema.optional()
21130
21872
  });
21131
- var LaunchResolveOutputSchema = z40.strictObject({
21873
+ var LaunchResolveOutputSchema = z41.strictObject({
21132
21874
  decision: LaunchDecisionSchema,
21133
21875
  flags: LaunchFlagsSchema,
21134
- claudeVersion: z40.strictObject({ version: z40.string(), source: z40.enum(CLAUDE_VERSION_SOURCES) }).optional(),
21876
+ claudeVersion: z41.strictObject({ version: z41.string(), source: z41.enum(CLAUDE_VERSION_SOURCES) }).optional(),
21135
21877
  /** The real `claude` binary the launch would spawn, on the door's host. */
21136
- bin: z40.string(),
21878
+ bin: z41.string(),
21137
21879
  /** The arguments the launch would pass it: the tool's own flags, then `CLAUDE_EXTRA_FLAGS`, then the caller's own. */
21138
- args: z40.readonly(z40.array(z40.string())),
21880
+ args: z41.readonly(z41.array(z41.string())),
21139
21881
  /** The credential the launch would authenticate with, by target and source kinds. Absent when none applies. */
21140
- credential: z40.strictObject({ subject: z40.enum(["provider", "identity"]), name: z40.string(), summary: CredentialSummarySchema }).optional(),
21141
- routing: z40.strictObject({ frontDoor: z40.boolean(), headroom: z40.boolean() }),
21882
+ credential: z41.strictObject({ subject: z41.enum(["provider", "identity"]), name: z41.string(), summary: CredentialSummarySchema }).optional(),
21883
+ routing: z41.strictObject({ frontDoor: z41.boolean(), headroom: z41.boolean() }),
21142
21884
  /** The names of the environment variables the launch would set or unset, sorted. Values are not reported. */
21143
- environment: z40.readonly(z40.array(z40.string())),
21144
- warnings: z40.readonly(z40.array(z40.string()))
21885
+ environment: z41.readonly(z41.array(z41.string())),
21886
+ warnings: z41.readonly(z41.array(z41.string()))
21145
21887
  });
21146
21888
 
21147
21889
  // src/frontdoor/launchApi.ts
@@ -21177,22 +21919,22 @@ function createLaunchApiRouter(deps) {
21177
21919
  // src/frontdoor/agentTreesApi.ts
21178
21920
  import { ORPCError as ORPCError6 } from "@orpc/client";
21179
21921
  import { openapi as openapi7 } from "@orpc/openapi";
21180
- import { z as z41 } from "zod";
21922
+ import { z as z42 } from "zod";
21181
21923
  init_cliError();
21182
- var AgentTreesListInputSchema = z41.strictObject({
21924
+ var AgentTreesListInputSchema = z42.strictObject({
21183
21925
  /** Only this identity's sessions. */
21184
- identity: z41.string().optional(),
21926
+ identity: z42.string().optional(),
21185
21927
  /** Include sessions that spawned no agent and ran no workflow. */
21186
- all: z41.boolean().optional()
21928
+ all: z42.boolean().optional()
21187
21929
  });
21188
- var AgentTreesListOutputSchema = z41.array(SessionSummarySchema);
21189
- var AgentTreesShowInputSchema = z41.strictObject({
21930
+ var AgentTreesListOutputSchema = z42.array(SessionSummarySchema);
21931
+ var AgentTreesShowInputSchema = z42.strictObject({
21190
21932
  /** A session id, or an unambiguous prefix of one. */
21191
- session: z41.string().min(1),
21933
+ session: z42.string().min(1),
21192
21934
  /** Look only in this identity. */
21193
- identity: z41.string().optional()
21935
+ identity: z42.string().optional()
21194
21936
  });
21195
- var AgentTreesShowOutputSchema = z41.strictObject({ identities: z41.array(z41.string()), ...MergedAgentTreeSchema.shape });
21937
+ var AgentTreesShowOutputSchema = z42.strictObject({ identities: z42.array(z42.string()), ...MergedAgentTreeSchema.shape });
21196
21938
  function asBadRequest(error) {
21197
21939
  if (error instanceof CliError) {
21198
21940
  throw new ORPCError6("BAD_REQUEST", { message: error.message });
@@ -21245,7 +21987,7 @@ import { openapi as openapi8 } from "@orpc/openapi";
21245
21987
  import { eventIterator as eventIterator3, withEventMeta as withEventMeta3 } from "@orpc/server";
21246
21988
 
21247
21989
  // src/frontdoor/rcEventLog.ts
21248
- import { z as z42 } from "zod";
21990
+ import { z as z43 } from "zod";
21249
21991
 
21250
21992
  // src/frontdoor/eventHub.ts
21251
21993
  var DOOR_EVENT_BUFFER_EVENTS = 100;
@@ -21355,8 +22097,8 @@ function rcFanoutOnDoorHub(fanout, hub) {
21355
22097
 
21356
22098
  // src/frontdoor/rcEventLog.ts
21357
22099
  var RC_SESSION_EVENT_TOKEN_MAX_CHARS = 255;
21358
- var HIGH_SURROGATE_FIRST = 55296;
21359
- var HIGH_SURROGATE_LAST = 56319;
22100
+ var HIGH_SURROGATE_FIRST2 = 55296;
22101
+ var HIGH_SURROGATE_LAST2 = 56319;
21360
22102
  var LOW_SURROGATE_FIRST = 56320;
21361
22103
  var LOW_SURROGATE_LAST = 57343;
21362
22104
  var CUT_MARKER = "...";
@@ -21367,47 +22109,47 @@ var NUMBER_BYTES = Float64Array.BYTES_PER_ELEMENT;
21367
22109
  var NUMBER_FIELDS = ["at", "sequence"].length;
21368
22110
  var BYTES_PER_CODE_UNIT = Uint16Array.BYTES_PER_ELEMENT;
21369
22111
  var RC_SESSION_END_REASONS = ["expired", "archived", "conflict"];
21370
- var RC_PENDING_RETIRE_REASONS = ["answered", "expired", "session-ended"];
21371
- var transitionBase = { session: z42.string(), at: z42.number() };
21372
- var cursorFields = { cursor: z42.string(), sequence: z42.int().positive() };
21373
- var sessionAppearedShape = { kind: z42.literal("session-appeared"), ...transitionBase };
21374
- var sessionEndedShape = { kind: z42.literal("session-ended"), reason: z42.enum(RC_SESSION_END_REASONS), ...transitionBase };
21375
- var workerStateShape = { kind: z42.literal("worker-state"), state: z42.string(), previous: z42.string().optional(), ...transitionBase };
21376
- var pendingBornShape = { kind: z42.literal("pending-born"), requestId: z42.string(), type: z42.string(), summary: z42.string(), ...transitionBase };
21377
- var pendingRetiredShape = { kind: z42.literal("pending-retired"), requestId: z42.string(), reason: z42.enum(RC_PENDING_RETIRE_REASONS), ...transitionBase };
21378
- var RcSessionTransitionSchema = z42.discriminatedUnion("kind", [
21379
- z42.strictObject(sessionAppearedShape),
21380
- z42.strictObject(sessionEndedShape),
21381
- z42.strictObject(workerStateShape),
21382
- z42.strictObject(pendingBornShape),
21383
- z42.strictObject(pendingRetiredShape)
22112
+ var RC_PENDING_RETIRE_REASONS = ["answered", "withdrawn", "worker-stopped", "session-ended"];
22113
+ var transitionBase = { session: z43.string(), at: z43.number() };
22114
+ var cursorFields = { cursor: z43.string(), sequence: z43.int().positive() };
22115
+ var sessionAppearedShape = { kind: z43.literal("session-appeared"), ...transitionBase };
22116
+ var sessionEndedShape = { kind: z43.literal("session-ended"), reason: z43.enum(RC_SESSION_END_REASONS), ...transitionBase };
22117
+ var workerStateShape = { kind: z43.literal("worker-state"), state: z43.string(), previous: z43.string().optional(), ...transitionBase };
22118
+ var pendingBornShape = { kind: z43.literal("pending-born"), requestId: z43.string(), type: z43.string(), summary: z43.string(), ...transitionBase };
22119
+ var pendingRetiredShape = { kind: z43.literal("pending-retired"), requestId: z43.string(), reason: z43.enum(RC_PENDING_RETIRE_REASONS), ...transitionBase };
22120
+ var RcSessionTransitionSchema = z43.discriminatedUnion("kind", [
22121
+ z43.strictObject(sessionAppearedShape),
22122
+ z43.strictObject(sessionEndedShape),
22123
+ z43.strictObject(workerStateShape),
22124
+ z43.strictObject(pendingBornShape),
22125
+ z43.strictObject(pendingRetiredShape)
21384
22126
  ]);
21385
22127
  var KIND_MAX_CHARS = Math.max(...RcSessionTransitionSchema.options.map((option) => option.shape.kind.value.length));
21386
22128
  var RC_SESSION_EVENT_MAX_BYTES = (RC_SESSION_EVENT_GENERATION_MAX_CHARS + ".".length + SEQUENCE_MAX_DIGITS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + KIND_MAX_CHARS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + RC_SESSION_EVENT_SUMMARY_MAX_CHARS) * BYTES_PER_CODE_UNIT + NUMBER_FIELDS * NUMBER_BYTES;
21387
22129
  var RC_SESSION_EVENT_LOG_CAPACITY = Math.floor(CONTROL_BODY_CAP_BYTES / RC_SESSION_EVENT_MAX_BYTES);
21388
- var RcSessionEventSchema = z42.discriminatedUnion("kind", [
21389
- z42.strictObject({ ...cursorFields, ...sessionAppearedShape }),
21390
- z42.strictObject({ ...cursorFields, ...sessionEndedShape }),
21391
- z42.strictObject({ ...cursorFields, ...workerStateShape }),
21392
- z42.strictObject({ ...cursorFields, ...pendingBornShape }),
21393
- z42.strictObject({ ...cursorFields, ...pendingRetiredShape })
22130
+ var RcSessionEventSchema = z43.discriminatedUnion("kind", [
22131
+ z43.strictObject({ ...cursorFields, ...sessionAppearedShape }),
22132
+ z43.strictObject({ ...cursorFields, ...sessionEndedShape }),
22133
+ z43.strictObject({ ...cursorFields, ...workerStateShape }),
22134
+ z43.strictObject({ ...cursorFields, ...pendingBornShape }),
22135
+ z43.strictObject({ ...cursorFields, ...pendingRetiredShape })
21394
22136
  ]);
21395
- var RcSessionEventsReadInputSchema = z42.strictObject({
22137
+ var RcSessionEventsReadInputSchema = z43.strictObject({
21396
22138
  /** The cursor of the last event the caller saw; every retained event when omitted. */
21397
- since: z42.string().min(1).optional(),
22139
+ since: z43.string().min(1).optional(),
21398
22140
  /** One `cse_` session id; every session when omitted. */
21399
- session: z42.string().min(1).optional(),
22141
+ session: z43.string().min(1).optional(),
21400
22142
  /** The most events one answer carries; every event after `since` when omitted. */
21401
- limit: z42.int().positive().optional()
22143
+ limit: z43.int().positive().optional()
21402
22144
  });
21403
22145
  var RcSessionEventsPageInputSchema = RcSessionEventsReadInputSchema.extend({
21404
22146
  /** The most events this page carries: by default and at most, the bound the door's event backbone already holds per slow consumer (`DOOR_EVENT_BUFFER_EVENTS`, oRPC's own documented default for that case). A page lands whole in its reader, so a reader receives at most one consumer buffer's worth at a time (at worst `DOOR_EVENT_BUFFER_EVENTS` times `RC_SESSION_EVENT_MAX_BYTES`) and pages on with the cursor for more; a maximum of the whole window would let one page carry the log's entire memory budget into an agent's context. */
21405
- limit: z42.int().positive().max(DOOR_EVENT_BUFFER_EVENTS).default(DOOR_EVENT_BUFFER_EVENTS)
22147
+ limit: z43.int().positive().max(DOOR_EVENT_BUFFER_EVENTS).default(DOOR_EVENT_BUFFER_EVENTS)
21406
22148
  });
21407
22149
  var RcSessionEventsStreamInputSchema = RcSessionEventsReadInputSchema.omit({ limit: true });
21408
- var RcSessionEventsReadOutputSchema = z42.discriminatedUnion("status", [
21409
- z42.strictObject({ status: z42.literal("ok"), events: z42.readonly(z42.array(RcSessionEventSchema)), cursor: z42.string(), more: z42.boolean(), head: z42.string() }),
21410
- z42.strictObject({ status: z42.literal("expired"), message: z42.string(), head: z42.string() })
22150
+ var RcSessionEventsReadOutputSchema = z43.discriminatedUnion("status", [
22151
+ z43.strictObject({ status: z43.literal("ok"), events: z43.readonly(z43.array(RcSessionEventSchema)), cursor: z43.string(), more: z43.boolean(), head: z43.string() }),
22152
+ z43.strictObject({ status: z43.literal("expired"), message: z43.string(), head: z43.string() })
21411
22153
  ]);
21412
22154
  var CURSOR_SEPARATOR = ".";
21413
22155
  var RESYNC_ADVICE = "cursor expired, resync from status: read `rc status` for every session's present state, then resume after the head this answer names";
@@ -21428,7 +22170,7 @@ function parseCursor(cursor) {
21428
22170
  function codePointBoundary(text, at) {
21429
22171
  const before = text.charCodeAt(at - 1);
21430
22172
  const after = text.charCodeAt(at);
21431
- const isHigh = before >= HIGH_SURROGATE_FIRST && before <= HIGH_SURROGATE_LAST;
22173
+ const isHigh = before >= HIGH_SURROGATE_FIRST2 && before <= HIGH_SURROGATE_LAST2;
21432
22174
  const isLow = after >= LOW_SURROGATE_FIRST && after <= LOW_SURROGATE_LAST;
21433
22175
  return isHigh && isLow ? at - 1 : at;
21434
22176
  }
@@ -21906,15 +22648,15 @@ function createQuotaExpiringPublisher(hub, deps) {
21906
22648
 
21907
22649
  // src/frontdoor/rcLiveUsage.ts
21908
22650
  var RC_RATE_LIMIT_EVENT_TYPE = "rate_limit_event";
21909
- function isRecord8(value) {
22651
+ function isRecord10(value) {
21910
22652
  return typeof value === "object" && value !== null && !Array.isArray(value);
21911
22653
  }
21912
22654
  function rcRateLimitInfoOf(event) {
21913
22655
  const payload = event.envelope.payload;
21914
- if (!isRecord8(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
22656
+ if (!isRecord10(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
21915
22657
  return void 0;
21916
22658
  }
21917
- if (!isRecord8(payload.rate_limit_info)) {
22659
+ if (!isRecord10(payload.rate_limit_info)) {
21918
22660
  return void 0;
21919
22661
  }
21920
22662
  const parsed = RcRateLimitInfoSchema.safeParse(payload.rate_limit_info);
@@ -22002,7 +22744,7 @@ function createSseParser() {
22002
22744
  }
22003
22745
  };
22004
22746
  }
22005
- function isRecord9(value) {
22747
+ function isRecord11(value) {
22006
22748
  return typeof value === "object" && value !== null && !Array.isArray(value);
22007
22749
  }
22008
22750
  function sequenceNumOf(value) {
@@ -22024,7 +22766,7 @@ function parseRcStreamEnvelope(parsed) {
22024
22766
  } catch {
22025
22767
  return void 0;
22026
22768
  }
22027
- if (!isRecord9(data)) {
22769
+ if (!isRecord11(data)) {
22028
22770
  return void 0;
22029
22771
  }
22030
22772
  const eventType = data.event_type;
@@ -22271,7 +23013,13 @@ init_capability();
22271
23013
  // src/frontdoor/rcSelfHostEndpoints.ts
22272
23014
  var RC_SOURCE_WORKER = "worker";
22273
23015
  var RC_SOURCE_CLIENT = "client";
22274
- function isRecord10(value) {
23016
+ var CLIENT_PLATFORM_HEADER = "anthropic-client-platform";
23017
+ function withClientPlatform(payload, headers) {
23018
+ const rest = Object.fromEntries(Object.entries(payload).filter(([key]) => key !== "client_platform"));
23019
+ const platform = headers[CLIENT_PLATFORM_HEADER];
23020
+ return typeof platform === "string" && platform !== "" ? { ...rest, client_platform: platform } : rest;
23021
+ }
23022
+ function isRecord12(value) {
22275
23023
  return typeof value === "object" && value !== null && !Array.isArray(value);
22276
23024
  }
22277
23025
  function parseJsonObject2(body) {
@@ -22281,7 +23029,7 @@ function parseJsonObject2(body) {
22281
23029
  } catch {
22282
23030
  return void 0;
22283
23031
  }
22284
- return isRecord10(parsed) ? parsed : void 0;
23032
+ return isRecord12(parsed) ? parsed : void 0;
22285
23033
  }
22286
23034
  function nonEmptyString2(record, field) {
22287
23035
  const value = record === void 0 ? void 0 : record[field];
@@ -22355,11 +23103,11 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
22355
23103
  }
22356
23104
  const results = [];
22357
23105
  for (const event of events) {
22358
- if (!isRecord10(event) || !isRecord10(event.payload)) {
23106
+ if (!isRecord12(event) || !isRecord12(event.payload)) {
22359
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" } });
22360
23108
  return true;
22361
23109
  }
22362
- const published = ctx.publish(host.conversation, host.writer, RC_SOURCE_CLIENT, event.payload);
23110
+ const published = ctx.publish(host.conversation, host.writer, RC_SOURCE_CLIENT, withClientPlatform(event.payload, request4.headers));
22363
23111
  results.push({ sequence_num: String(published.sequenceNum), duplicate: published.duplicate });
22364
23112
  }
22365
23113
  ctx.sweep();
@@ -22455,7 +23203,7 @@ async function serveRcCompatSessions(ctx, pathname, compatPath) {
22455
23203
  // src/frontdoor/rcSelfHostConversations.ts
22456
23204
  var RC_CONVERSATIONS_PATH_PREFIX = "/v1/code/conversations";
22457
23205
  var RC_CONVERSATION_ID_PREFIX = "conv_";
22458
- function isRecord11(value) {
23206
+ function isRecord13(value) {
22459
23207
  return typeof value === "object" && value !== null && !Array.isArray(value);
22460
23208
  }
22461
23209
  function parseJsonObject3(body) {
@@ -22465,7 +23213,7 @@ function parseJsonObject3(body) {
22465
23213
  } catch {
22466
23214
  return void 0;
22467
23215
  }
22468
- return isRecord11(parsed) ? parsed : void 0;
23216
+ return isRecord13(parsed) ? parsed : void 0;
22469
23217
  }
22470
23218
  function nonEmptyString3(record, field) {
22471
23219
  const value = record === void 0 ? void 0 : record[field];
@@ -22519,11 +23267,11 @@ async function serveRcConversations(ctx, pathname, method) {
22519
23267
  }
22520
23268
  const results = [];
22521
23269
  for (const event of events) {
22522
- if (!isRecord11(event) || !isRecord11(event.payload)) {
23270
+ if (!isRecord13(event) || !isRecord13(event.payload)) {
22523
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" } });
22524
23272
  return;
22525
23273
  }
22526
- const published = ctx.publish(conversation, { session: void 0, half: "client" }, RC_SOURCE_CLIENT, event.payload);
23274
+ const published = ctx.publish(conversation, { session: void 0, half: "client" }, RC_SOURCE_CLIENT, withClientPlatform(event.payload, request4.headers));
22527
23275
  results.push({ sequence_num: String(published.sequenceNum), duplicate: published.duplicate });
22528
23276
  }
22529
23277
  ctx.sweep();
@@ -22551,7 +23299,7 @@ var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:
22551
23299
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
22552
23300
  var MS_PER_SECOND6 = 1e3;
22553
23301
  var HTTP_SERVICE_UNAVAILABLE = 503;
22554
- function isRecord12(value) {
23302
+ function isRecord14(value) {
22555
23303
  return typeof value === "object" && value !== null && !Array.isArray(value);
22556
23304
  }
22557
23305
  function parseJsonObject4(body) {
@@ -22561,7 +23309,7 @@ function parseJsonObject4(body) {
22561
23309
  } catch {
22562
23310
  return void 0;
22563
23311
  }
22564
- return isRecord12(parsed) ? parsed : void 0;
23312
+ return isRecord14(parsed) ? parsed : void 0;
22565
23313
  }
22566
23314
  function growthBookFeatures() {
22567
23315
  return {
@@ -22915,7 +23663,7 @@ var RC_SELF_HOST_WORKER_EPOCH = 1;
22915
23663
  var RC_STREAM_EVENT_NAME2 = "client_event";
22916
23664
  var CONFLICT_REASON_HEADER2 = "x-ccr-conflict-reason";
22917
23665
  var CONFLICT_REASON_EPOCH_STALE = "epoch_stale";
22918
- function isRecord13(value) {
23666
+ function isRecord15(value) {
22919
23667
  return typeof value === "object" && value !== null && !Array.isArray(value);
22920
23668
  }
22921
23669
  function isWebSearchRefusal(value) {
@@ -22999,7 +23747,7 @@ function parseJsonObject5(body) {
22999
23747
  } catch {
23000
23748
  return void 0;
23001
23749
  }
23002
- return isRecord13(parsed) ? parsed : void 0;
23750
+ return isRecord15(parsed) ? parsed : void 0;
23003
23751
  }
23004
23752
  function mintWorkerJwt(randomToken, issuedAt) {
23005
23753
  const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
@@ -23259,7 +24007,7 @@ data: ${JSON.stringify(envelope)}
23259
24007
  if (status !== void 0) {
23260
24008
  session.workerStatus = status;
23261
24009
  }
23262
- if (isRecord13(body?.external_metadata)) {
24010
+ if (isRecord15(body?.external_metadata)) {
23263
24011
  session.externalMetadata = body.external_metadata;
23264
24012
  }
23265
24013
  await answerJson2(response, HTTP_STATUS.ok, {});
@@ -23289,7 +24037,7 @@ data: ${JSON.stringify(envelope)}
23289
24037
  }
23290
24038
  const results = [];
23291
24039
  for (const event of events) {
23292
- if (!isRecord13(event) || !isRecord13(event.payload)) {
24040
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
23293
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" } });
23294
24042
  return;
23295
24043
  }
@@ -23322,7 +24070,7 @@ data: ${JSON.stringify(envelope)}
23322
24070
  return;
23323
24071
  }
23324
24072
  for (const event of events) {
23325
- if (isRecord13(event)) {
24073
+ if (isRecord15(event)) {
23326
24074
  session.internalEvents.push({ eventId: deps.newUuid(), body: event });
23327
24075
  }
23328
24076
  }
@@ -23418,11 +24166,11 @@ data: ${JSON.stringify(envelope)}
23418
24166
  }
23419
24167
  const results = [];
23420
24168
  for (const event of events) {
23421
- if (!isRecord13(event) || !isRecord13(event.payload)) {
24169
+ if (!isRecord15(event) || !isRecord15(event.payload)) {
23422
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" } });
23423
24171
  return;
23424
24172
  }
23425
- const published = publish(session.conversation, { session: session.id, half: "client" }, RC_SOURCE_CLIENT, event.payload);
24173
+ const published = publish(session.conversation, { session: session.id, half: "client" }, RC_SOURCE_CLIENT, withClientPlatform(event.payload, request4.headers));
23426
24174
  results.push({ sequence_num: String(published.sequenceNum), duplicate: published.duplicate });
23427
24175
  }
23428
24176
  sweep();
@@ -23556,7 +24304,7 @@ var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
23556
24304
  var RC_SELF_HOST_RECORD_FILE = "credential.json";
23557
24305
  var SELF_HOST_EMAIL = "selfhost@agent-shim.invalid";
23558
24306
  var SELF_HOST_SUBSCRIPTION_TYPE = "max";
23559
- function isRecord14(value) {
24307
+ function isRecord16(value) {
23560
24308
  return typeof value === "object" && value !== null && !Array.isArray(value);
23561
24309
  }
23562
24310
  function readJsonObject(fs17, file) {
@@ -23570,7 +24318,7 @@ function readJsonObject(fs17, file) {
23570
24318
  } catch {
23571
24319
  return void 0;
23572
24320
  }
23573
- return isRecord14(parsed) ? parsed : void 0;
24321
+ return isRecord16(parsed) ? parsed : void 0;
23574
24322
  }
23575
24323
  function readRcSelfHostRecord(fs17, frontdoorDir) {
23576
24324
  const parsed = readJsonObject(fs17, path45.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
@@ -23598,7 +24346,7 @@ function mintRcSelfHostCredential(deps) {
23598
24346
  const recordFile2 = path45.join(recordDir, RC_SELF_HOST_RECORD_FILE);
23599
24347
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
23600
24348
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
23601
- const existingOauth = isRecord14(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
24349
+ const existingOauth = isRecord16(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
23602
24350
  const existingToken = typeof existingOauth?.accessToken === "string" && existingOauth.accessToken !== "" ? existingOauth.accessToken : void 0;
23603
24351
  const existingIsOwn = existingToken !== void 0 && previousRecord?.accessToken === existingToken;
23604
24352
  if (existingToken !== void 0 && !existingIsOwn && !deps.force) {
@@ -23615,7 +24363,7 @@ function mintRcSelfHostCredential(deps) {
23615
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)}
23616
24364
  `);
23617
24365
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
23618
- const existingBlock = (value) => isRecord14(value) ? value : {};
24366
+ const existingBlock = (value) => isRecord16(value) ? value : {};
23619
24367
  deps.fs.writeFilePrivate(claudeJsonFile, `${JSON.stringify({
23620
24368
  ...claudeJson,
23621
24369
  oauthAccount: {
@@ -23738,7 +24486,7 @@ init_poolPick();
23738
24486
 
23739
24487
  // src/agents/read.ts
23740
24488
  import path47 from "node:path";
23741
- import { z as z43 } from "zod";
24489
+ import { z as z44 } from "zod";
23742
24490
  var PROJECTS_DIR = "projects";
23743
24491
  var TASKS_DIR = "tasks";
23744
24492
  var SUBAGENTS_DIR = "subagents";
@@ -23857,14 +24605,14 @@ function parseJson2(text) {
23857
24605
  return void 0;
23858
24606
  }
23859
24607
  }
23860
- var TaskFileSchema = z43.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z43.array(z43.string()).default([]), blockedBy: z43.array(z43.string()).default([]) });
23861
- var WorkflowRunFileSchema = z43.object({
23862
- runId: z43.string(),
23863
- workflowName: z43.string().optional(),
23864
- status: z43.string().optional(),
23865
- startTime: z43.number().optional(),
23866
- phases: z43.array(z43.object({ title: z43.string() })).default([]),
23867
- summary: z43.string().optional()
24608
+ var TaskFileSchema = z44.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z44.array(z44.string()).default([]), blockedBy: z44.array(z44.string()).default([]) });
24609
+ var WorkflowRunFileSchema = z44.object({
24610
+ runId: z44.string(),
24611
+ workflowName: z44.string().optional(),
24612
+ status: z44.string().optional(),
24613
+ startTime: z44.number().optional(),
24614
+ phases: z44.array(z44.object({ title: z44.string() })).default([]),
24615
+ summary: z44.string().optional()
23868
24616
  });
23869
24617
  function summariseSession(fs17, configDir, ref) {
23870
24618
  const sessionRelative = path47.join(PROJECTS_DIR, ref.project, ref.entry);
@@ -24368,9 +25116,10 @@ export {
24368
25116
  QUOTA_EXPIRING_EVENT_SOURCE,
24369
25117
  QuotaExpiringEventSchema,
24370
25118
  RC_CONTEXT_USAGE_DETAILS,
25119
+ RC_GOAL_CLEAR_WORDS,
25120
+ RC_GOAL_CONDITION_MAX_CHARS,
24371
25121
  RC_IDLE_EXPIRY_MS,
24372
25122
  RC_ORPC_PATH_PREFIX,
24373
- RC_PENDING_DEADLINE_MS,
24374
25123
  RC_PENDING_RETIRE_REASONS,
24375
25124
  RC_PERMISSION_MODES,
24376
25125
  RC_READ_FILE_ENCODINGS,
@@ -24383,6 +25132,8 @@ export {
24383
25132
  RC_SELF_HOST_SCOPE_LIST,
24384
25133
  RC_SELF_HOST_WORKER_JWT_TTL_SECONDS,
24385
25134
  RC_SESSIONS_PATH_PREFIX,
25135
+ RC_SESSION_COMMAND_MAX_WAIT_MS,
25136
+ RC_SESSION_COMMAND_VERIFIED_VERSIONS,
24386
25137
  RC_SESSION_END_REASONS,
24387
25138
  RC_SESSION_EVENT_LOG_CAPACITY,
24388
25139
  RC_STREAM_BACKOFF_MS,
@@ -24478,11 +25229,13 @@ export {
24478
25229
  createQuotaExpiringPublisher,
24479
25230
  createRcApiNodeHandler,
24480
25231
  createRcApiRouter,
25232
+ createRcClaudeCodeVersions,
24481
25233
  createRcControlHandler,
24482
25234
  createRcCredentialStore,
24483
25235
  createRcEventFanout,
24484
25236
  createRcLiveUsage,
24485
25237
  createRcSelfHostSurface,
25238
+ createRcSessionCommands,
24486
25239
  createRcSessionEventLog,
24487
25240
  createRcSessionEventsApiRouter,
24488
25241
  createRcSessionRegistryReader,
@@ -24545,6 +25298,7 @@ export {
24545
25298
  mintRcSelfHostCredential,
24546
25299
  observingRoutedRoute,
24547
25300
  parseConnectTarget,
25301
+ parseRcGoalOutput,
24548
25302
  parseRcStreamEnvelope,
24549
25303
  planOf,
24550
25304
  poolIdentities,
@@ -24556,6 +25310,8 @@ export {
24556
25310
  rankPool,
24557
25311
  rcEventWriteResultFromAnswer,
24558
25312
  rcFanoutOnDoorHub,
25313
+ rcLocalCommandAnswerOf,
25314
+ rcManualCompactBoundaryOf,
24559
25315
  rcObserverAsPassthrough,
24560
25316
  rcRateLimitInfoOf,
24561
25317
  rcSelfHostFromEnv,