claude-use 9.17.0 → 9.19.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
@@ -696,7 +696,7 @@ function compile(pattern, category, source, ordinal) {
696
696
  matches: isExact ? (name) => name === pattern : (name) => matcher(name)
697
697
  };
698
698
  }
699
- function compileClassificationPatterns(defaults, overlay) {
699
+ function compileClassificationPatterns(defaults, overlay2) {
700
700
  const compiled = [];
701
701
  let ordinal = 0;
702
702
  for (const category of CATEGORY_NAMES) {
@@ -705,9 +705,9 @@ function compileClassificationPatterns(defaults, overlay) {
705
705
  ordinal += 1;
706
706
  }
707
707
  }
708
- if (overlay !== void 0) {
708
+ if (overlay2 !== void 0) {
709
709
  for (const category of CATEGORY_NAMES) {
710
- for (const pattern of overlay[category] ?? []) {
710
+ for (const pattern of overlay2[category] ?? []) {
711
711
  compiled.push(compile(pattern, category, "local", ordinal));
712
712
  ordinal += 1;
713
713
  }
@@ -728,10 +728,10 @@ function compareClassificationPatterns(a, b) {
728
728
  return a.ordinal - b.ordinal;
729
729
  }
730
730
  function loadClassification(paths) {
731
- const overlay = readJson(paths.categoriesLocalFile, CategoryClassificationOverlaySchema);
731
+ const overlay2 = readJson(paths.categoriesLocalFile, CategoryClassificationOverlaySchema);
732
732
  return {
733
733
  defaults: CategoryClassificationSchema.parse(categories_default_default),
734
- ...overlay === void 0 ? {} : { overlay }
734
+ ...overlay2 === void 0 ? {} : { overlay: overlay2 }
735
735
  };
736
736
  }
737
737
  function classifyEntries(names, options) {
@@ -2669,7 +2669,7 @@ var init_package = __esm({
2669
2669
  "package.json"() {
2670
2670
  package_default = {
2671
2671
  name: "claude-use",
2672
- version: "9.17.0",
2672
+ version: "9.19.0",
2673
2673
  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.",
2674
2674
  license: "MIT",
2675
2675
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -2805,7 +2805,7 @@ var init_supervisorProcesses = __esm({
2805
2805
  // src/headroom/state.ts
2806
2806
  import { createHash as createHash3 } from "node:crypto";
2807
2807
  import path11 from "node:path";
2808
- import { z as z6 } from "zod";
2808
+ import { z as z8 } from "zod";
2809
2809
  function parseJson(raw, schema) {
2810
2810
  if (raw === void 0 || raw.trim() === "") {
2811
2811
  return void 0;
@@ -2936,28 +2936,28 @@ var init_state2 = __esm({
2936
2936
  "use strict";
2937
2937
  init_schema();
2938
2938
  HEADROOM_ANTHROPIC_UPSTREAM = "https://api.anthropic.com";
2939
- HeadroomStateSchema = z6.strictObject({
2939
+ HeadroomStateSchema = z8.strictObject({
2940
2940
  /** The supervisor process owning the daemon. Alive means someone is keeping headroom running. */
2941
- supervisorPid: z6.number().int().positive().optional(),
2941
+ supervisorPid: z8.number().int().positive().optional(),
2942
2942
  /** The headroom proxy process itself. Absent while the supervisor is between restarts. */
2943
- headroomPid: z6.number().int().positive().optional(),
2943
+ headroomPid: z8.number().int().positive().optional(),
2944
2944
  /**
2945
2945
  * 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.
2946
2946
  */
2947
- socketPath: z6.string().min(1).optional(),
2947
+ socketPath: z8.string().min(1).optional(),
2948
2948
  /** The `headroom --version` output of the running install. */
2949
- version: z6.string().optional(),
2949
+ version: z8.string().optional(),
2950
2950
  /** Hash of the allowlist the running proxy was started with, so a provider-file change is detected as drift. */
2951
- allowlistHash: z6.string().optional(),
2951
+ allowlistHash: z8.string().optional(),
2952
2952
  /** Hash of the token-saving settings the running proxy was started with, so a settings change is detected as drift. */
2953
- settingsHash: z6.string().optional(),
2953
+ settingsHash: z8.string().optional(),
2954
2954
  /** The install spec the running install was last installed from, so a `source` config change is detected as drift. */
2955
- installedSource: z6.string().optional(),
2955
+ installedSource: z8.string().optional(),
2956
2956
  /** The last fatal error, kept across shutdowns so `headroom status` can explain a daemon that is not running. */
2957
- lastError: z6.string().optional()
2957
+ lastError: z8.string().optional()
2958
2958
  });
2959
- HeadroomSessionSchema = z6.strictObject({ pid: z6.number().int().positive(), startedAt: z6.number(), supervisorPid: z6.number().int().positive() });
2960
- HeadroomLockSchema = z6.strictObject({ pid: z6.number().int().positive(), at: z6.number() });
2959
+ HeadroomSessionSchema = z8.strictObject({ pid: z8.number().int().positive(), startedAt: z8.number(), supervisorPid: z8.number().int().positive() });
2960
+ HeadroomLockSchema = z8.strictObject({ pid: z8.number().int().positive(), at: z8.number() });
2961
2961
  }
2962
2962
  });
2963
2963
 
@@ -3151,7 +3151,7 @@ var init_socket = __esm({
3151
3151
  });
3152
3152
 
3153
3153
  // src/headroom/source.ts
3154
- import { z as z7 } from "zod";
3154
+ import { z as z9 } from "zod";
3155
3155
  function isMovingGitSource(spec) {
3156
3156
  const match = GIT_SPEC_RE.exec(spec);
3157
3157
  if (match === null) {
@@ -3170,7 +3170,7 @@ var init_source = __esm({
3170
3170
  "use strict";
3171
3171
  GIT_SPEC_RE = /git\+[^@\s]+(?:@([^\s#]+))?/;
3172
3172
  COMMIT_SHA_RE = /^[0-9a-f]{40}$/i;
3173
- DirectUrlSchema = z7.object({ vcs_info: z7.object({ commit_id: z7.string() }) });
3173
+ DirectUrlSchema = z9.object({ vcs_info: z9.object({ commit_id: z9.string() }) });
3174
3174
  }
3175
3175
  });
3176
3176
 
@@ -4085,149 +4085,149 @@ var init_identity = __esm({
4085
4085
  });
4086
4086
 
4087
4087
  // src/usage/schema.ts
4088
- import { z as z8 } from "zod";
4088
+ import { z as z10 } from "zod";
4089
4089
  var USAGE_SCHEMA_VERSION, VersionSchema, InstantSchema, TokenCountSchema, TokenUsageSchema, LIMIT_KINDS, LimitClassificationSchema, UsageRecordSchema, QuotaWindowSchema, ExtraUsageSpendSchema, UnifiedRateLimitSchema, RateLimitStateSchema, LimitEventSchema, ProviderQuotaWindowSchema, ProviderQuotaSchema, ProviderUsageStateSchema, AccountMetadataSchema, UsageSnapshotSchema;
4090
4090
  var init_schema2 = __esm({
4091
4091
  "src/usage/schema.ts"() {
4092
4092
  "use strict";
4093
4093
  USAGE_SCHEMA_VERSION = 1;
4094
- VersionSchema = z8.literal(USAGE_SCHEMA_VERSION);
4095
- InstantSchema = z8.iso.datetime();
4096
- TokenCountSchema = z8.number().int().nonnegative();
4097
- TokenUsageSchema = z8.strictObject({
4094
+ VersionSchema = z10.literal(USAGE_SCHEMA_VERSION);
4095
+ InstantSchema = z10.iso.datetime();
4096
+ TokenCountSchema = z10.number().int().nonnegative();
4097
+ TokenUsageSchema = z10.strictObject({
4098
4098
  inputTokens: TokenCountSchema.optional(),
4099
4099
  outputTokens: TokenCountSchema.optional(),
4100
4100
  cacheCreationInputTokens: TokenCountSchema.optional(),
4101
4101
  cacheReadInputTokens: TokenCountSchema.optional()
4102
4102
  });
4103
4103
  LIMIT_KINDS = ["rate-limited", "quota-exhausted"];
4104
- LimitClassificationSchema = z8.strictObject({
4105
- kind: z8.enum(LIMIT_KINDS),
4104
+ LimitClassificationSchema = z10.strictObject({
4105
+ kind: z10.enum(LIMIT_KINDS),
4106
4106
  /** Seconds to wait before retrying, from the response's `retry-after`. */
4107
- retryAfterSeconds: z8.number().nonnegative().optional(),
4107
+ retryAfterSeconds: z10.number().nonnegative().optional(),
4108
4108
  /** When the limiting window resets, from the upstream's own reset header. */
4109
4109
  resetAt: InstantSchema.optional(),
4110
4110
  /** The window the upstream named as the binding one (`anthropic-ratelimit-unified-representative-claim`), such as `five_hour` or `seven_day`. */
4111
- window: z8.string().optional(),
4111
+ window: z10.string().optional(),
4112
4112
  /** 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. */
4113
- evidence: z8.array(z8.string())
4113
+ evidence: z10.array(z10.string())
4114
4114
  });
4115
- UsageRecordSchema = z8.strictObject({
4115
+ UsageRecordSchema = z10.strictObject({
4116
4116
  schemaVersion: VersionSchema,
4117
4117
  /** When the front door received the request. */
4118
4118
  at: InstantSchema,
4119
4119
  /** The launching identity, when the launch resolved one. */
4120
- identity: z8.string().optional(),
4120
+ identity: z10.string().optional(),
4121
4121
  /** `anthropic` for an OAuth session's request to Claude Code's own API, otherwise the provider's name. */
4122
- provider: z8.string(),
4122
+ provider: z10.string(),
4123
4123
  /** The launch's session id, generated per launch. */
4124
- sessionId: z8.string().optional(),
4124
+ sessionId: z10.string().optional(),
4125
4125
  /** The project the launch ran in (its git repository root), when the launch sent one: headroom launches do. */
4126
- project: z8.string().optional(),
4126
+ project: z10.string().optional(),
4127
4127
  /** The front-door route that served the request. */
4128
- route: z8.string(),
4129
- method: z8.string(),
4128
+ route: z10.string(),
4129
+ method: z10.string(),
4130
4130
  /** The API path as the upstream sees it (`/v1/messages`), without the provider prefix or a query string. */
4131
- endpoint: z8.string(),
4131
+ endpoint: z10.string(),
4132
4132
  /** The model the response named. */
4133
- model: z8.string().optional(),
4134
- status: z8.number().int(),
4133
+ model: z10.string().optional(),
4134
+ status: z10.number().int(),
4135
4135
  /** Milliseconds from the request's arrival to its response head. */
4136
- latencyMs: z8.number().int().nonnegative(),
4136
+ latencyMs: z10.number().int().nonnegative(),
4137
4137
  /** Milliseconds from the request's arrival to the end of its response body. */
4138
- durationMs: z8.number().int().nonnegative(),
4138
+ durationMs: z10.number().int().nonnegative(),
4139
4139
  /** Whether the client received the whole body. */
4140
- outcome: z8.enum(["completed", "aborted"]),
4140
+ outcome: z10.enum(["completed", "aborted"]),
4141
4141
  usage: TokenUsageSchema.optional(),
4142
4142
  /** The response's quota and rate-limit headers, by name (see `isRateLimitHeader`). */
4143
- rateLimitHeaders: z8.record(z8.string(), z8.string()).optional(),
4143
+ rateLimitHeaders: z10.record(z10.string(), z10.string()).optional(),
4144
4144
  limit: LimitClassificationSchema.optional(),
4145
4145
  /** The upstream's request id (`request-id`), for matching a record to the provider's own logs. */
4146
- requestId: z8.string().optional()
4146
+ requestId: z10.string().optional()
4147
4147
  });
4148
- QuotaWindowSchema = z8.strictObject({
4148
+ QuotaWindowSchema = z10.strictObject({
4149
4149
  /** The fraction of the window used, as the upstream reports it (0 to 1). */
4150
- utilization: z8.number().nonnegative().optional(),
4150
+ utilization: z10.number().nonnegative().optional(),
4151
4151
  resetsAt: InstantSchema.optional(),
4152
4152
  /** The window's own status (`allowed`, `allowed_warning`, `rejected`). */
4153
- status: z8.string().optional(),
4153
+ status: z10.string().optional(),
4154
4154
  /** 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. */
4155
- graceUtilization: z8.number().nonnegative().optional()
4155
+ graceUtilization: z10.number().nonnegative().optional()
4156
4156
  });
4157
- ExtraUsageSpendSchema = z8.strictObject({
4157
+ ExtraUsageSpendSchema = z10.strictObject({
4158
4158
  /** Spent so far in the allowance's period, in the currency's minor units (pence, cents). */
4159
- usedMinor: z8.number().nonnegative(),
4159
+ usedMinor: z10.number().nonnegative(),
4160
4160
  /** The allowance's cap in the same units, when it has one. */
4161
- limitMinor: z8.number().nonnegative().optional(),
4161
+ limitMinor: z10.number().nonnegative().optional(),
4162
4162
  /** The ISO 4217 currency code. */
4163
- currency: z8.string()
4163
+ currency: z10.string()
4164
4164
  });
4165
- UnifiedRateLimitSchema = z8.strictObject({
4165
+ UnifiedRateLimitSchema = z10.strictObject({
4166
4166
  /** The overall status: `allowed`, `allowed_warning` or `rejected`. */
4167
- status: z8.string().optional(),
4167
+ status: z10.string().optional(),
4168
4168
  fiveHour: QuotaWindowSchema.optional(),
4169
4169
  sevenDay: QuotaWindowSchema.optional(),
4170
4170
  /** 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. */
4171
4171
  sevenDayOverageIncluded: QuotaWindowSchema.optional(),
4172
4172
  /** The window that currently binds. */
4173
- representativeClaim: z8.string().optional(),
4173
+ representativeClaim: z10.string().optional(),
4174
4174
  /** When the binding window resets. */
4175
4175
  resetAt: InstantSchema.optional(),
4176
4176
  /** Whether usage beyond the plan (extra usage) is available: `allowed` or `rejected`. */
4177
- overageStatus: z8.string().optional(),
4177
+ overageStatus: z10.string().optional(),
4178
4178
  /** 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. */
4179
- overageUtilization: z8.number().nonnegative().optional(),
4179
+ overageUtilization: z10.number().nonnegative().optional(),
4180
4180
  /** When the extra-usage allowance resets. */
4181
4181
  overageResetsAt: InstantSchema.optional(),
4182
4182
  /** Why extra usage is unavailable, as the upstream names it (`out_of_credits`, for one). */
4183
- overageDisabledReason: z8.string().optional(),
4183
+ overageDisabledReason: z10.string().optional(),
4184
4184
  /** Whether the response was served on extra usage, as the upstream states it. */
4185
- overageInUse: z8.boolean().optional(),
4185
+ overageInUse: z10.boolean().optional(),
4186
4186
  /** The allowance in money, from the usage endpoint (the response headers state only the fraction). */
4187
4187
  extraUsageSpend: ExtraUsageSpendSchema.optional(),
4188
4188
  /** True when the upstream offers a fallback while a window is rejected: some requests, by model, are still served, though the rest are refused. */
4189
- fallbackAvailable: z8.boolean().optional()
4189
+ fallbackAvailable: z10.boolean().optional()
4190
4190
  });
4191
- RateLimitStateSchema = z8.strictObject({
4191
+ RateLimitStateSchema = z10.strictObject({
4192
4192
  observedAt: InstantSchema,
4193
4193
  /** Every quota and rate-limit header on that response, by name. */
4194
- headers: z8.record(z8.string(), z8.string()),
4194
+ headers: z10.record(z10.string(), z10.string()),
4195
4195
  unified: UnifiedRateLimitSchema.optional(),
4196
4196
  /** 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. */
4197
4197
  planWindowsUnavailableAt: InstantSchema.optional()
4198
4198
  });
4199
4199
  LimitEventSchema = LimitClassificationSchema.extend({
4200
4200
  observedAt: InstantSchema,
4201
- status: z8.number().int()
4201
+ status: z10.number().int()
4202
4202
  });
4203
- ProviderQuotaWindowSchema = z8.strictObject({
4203
+ ProviderQuotaWindowSchema = z10.strictObject({
4204
4204
  /** What the window measures, in the provider's terms (`tokens`, `tool-calls`). */
4205
- measures: z8.string(),
4205
+ measures: z10.string(),
4206
4206
  /** 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. */
4207
- periodMs: z8.number().int().positive().optional(),
4207
+ periodMs: z10.number().int().positive().optional(),
4208
4208
  /** The provider's own description of the period when `periodMs` could not be derived, such as `unit 4 x 1`. */
4209
- period: z8.string().optional(),
4209
+ period: z10.string().optional(),
4210
4210
  /** The fraction of the window used (0 to 1). */
4211
- utilization: z8.number().nonnegative(),
4211
+ utilization: z10.number().nonnegative(),
4212
4212
  resetsAt: InstantSchema.optional(),
4213
4213
  /** Absolute counts, when the provider reports them for this window. */
4214
- limit: z8.number().nonnegative().optional(),
4215
- used: z8.number().nonnegative().optional(),
4216
- remaining: z8.number().nonnegative().optional()
4214
+ limit: z10.number().nonnegative().optional(),
4215
+ used: z10.number().nonnegative().optional(),
4216
+ remaining: z10.number().nonnegative().optional()
4217
4217
  });
4218
- ProviderQuotaSchema = z8.strictObject({
4218
+ ProviderQuotaSchema = z10.strictObject({
4219
4219
  observedAt: InstantSchema,
4220
4220
  /** Which usage endpoint produced it (`z.ai`). */
4221
- source: z8.string(),
4221
+ source: z10.string(),
4222
4222
  /** The subscription level the endpoint reports, when it does. */
4223
- level: z8.string().optional(),
4224
- windows: z8.array(ProviderQuotaWindowSchema)
4223
+ level: z10.string().optional(),
4224
+ windows: z10.array(ProviderQuotaWindowSchema)
4225
4225
  });
4226
- ProviderUsageStateSchema = z8.strictObject({
4226
+ ProviderUsageStateSchema = z10.strictObject({
4227
4227
  /** 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. */
4228
4228
  lastRequestAt: InstantSchema.optional(),
4229
- lastStatus: z8.number().int().optional(),
4230
- lastModel: z8.string().optional(),
4229
+ lastStatus: z10.number().int().optional(),
4230
+ lastModel: z10.string().optional(),
4231
4231
  /** The latest rate-limit state, from the last response that carried any rate-limit header. */
4232
4232
  rateLimit: RateLimitStateSchema.optional(),
4233
4233
  /** The latest classified refusal. It stays after later successes, so a reader compares its `resetAt` (or `observedAt` plus `retryAfterSeconds`) with the current time. */
@@ -4235,31 +4235,31 @@ var init_schema2 = __esm({
4235
4235
  /** The latest quota the provider's usage endpoint reported, for providers whose quota is not visible in response headers. */
4236
4236
  quota: ProviderQuotaSchema.optional()
4237
4237
  });
4238
- AccountMetadataSchema = z8.strictObject({
4239
- accountUuid: z8.string().optional(),
4240
- emailAddress: z8.string().optional(),
4241
- displayName: z8.string().optional(),
4242
- organizationUuid: z8.string().optional(),
4243
- organizationName: z8.string().optional(),
4244
- organizationType: z8.string().optional(),
4245
- organizationRole: z8.string().optional(),
4246
- workspaceRole: z8.string().optional(),
4247
- billingType: z8.string().optional(),
4248
- seatTier: z8.string().optional(),
4249
- organizationRateLimitTier: z8.string().optional(),
4250
- userRateLimitTier: z8.string().optional(),
4251
- hasExtraUsageEnabled: z8.boolean().optional(),
4252
- subscriptionCreatedAt: z8.string().optional(),
4253
- accountCreatedAt: z8.string().optional()
4238
+ AccountMetadataSchema = z10.strictObject({
4239
+ accountUuid: z10.string().optional(),
4240
+ emailAddress: z10.string().optional(),
4241
+ displayName: z10.string().optional(),
4242
+ organizationUuid: z10.string().optional(),
4243
+ organizationName: z10.string().optional(),
4244
+ organizationType: z10.string().optional(),
4245
+ organizationRole: z10.string().optional(),
4246
+ workspaceRole: z10.string().optional(),
4247
+ billingType: z10.string().optional(),
4248
+ seatTier: z10.string().optional(),
4249
+ organizationRateLimitTier: z10.string().optional(),
4250
+ userRateLimitTier: z10.string().optional(),
4251
+ hasExtraUsageEnabled: z10.boolean().optional(),
4252
+ subscriptionCreatedAt: z10.string().optional(),
4253
+ accountCreatedAt: z10.string().optional()
4254
4254
  });
4255
- UsageSnapshotSchema = z8.strictObject({
4255
+ UsageSnapshotSchema = z10.strictObject({
4256
4256
  schemaVersion: VersionSchema,
4257
- identity: z8.string(),
4257
+ identity: z10.string(),
4258
4258
  updatedAt: InstantSchema,
4259
4259
  /** The identity's account metadata as of `updatedAt`. */
4260
4260
  account: AccountMetadataSchema.optional(),
4261
4261
  /** Latest state per provider, keyed by provider name (`anthropic` for OAuth sessions). */
4262
- providers: z8.record(z8.string(), ProviderUsageStateSchema)
4262
+ providers: z10.record(z10.string(), ProviderUsageStateSchema)
4263
4263
  });
4264
4264
  }
4265
4265
  });
@@ -4347,7 +4347,7 @@ var init_account = __esm({
4347
4347
  });
4348
4348
 
4349
4349
  // src/usage/plan.ts
4350
- import { z as z9 } from "zod";
4350
+ import { z as z11 } from "zod";
4351
4351
  function planOf(account) {
4352
4352
  const userTier = account?.userRateLimitTier;
4353
4353
  if (userTier !== void 0 && ZERO_TIER.test(userTier)) {
@@ -4371,19 +4371,19 @@ var PlanClassSchema, TIER_MULTIPLIER, ZERO_TIER, BASE_TIER;
4371
4371
  var init_plan2 = __esm({
4372
4372
  "src/usage/plan.ts"() {
4373
4373
  "use strict";
4374
- PlanClassSchema = z9.union([
4375
- z9.strictObject({
4376
- kind: z9.literal("subscription"),
4374
+ PlanClassSchema = z11.union([
4375
+ z11.strictObject({
4376
+ kind: z11.literal("subscription"),
4377
4377
  /** The plan's size as a multiple of the smallest subscription tier (Max 5x is 5, Max 20x is 20). */
4378
- capacity: z9.number().positive(),
4378
+ capacity: z11.number().positive(),
4379
4379
  /** False when the tier string named no multiplier and no tier this project knows, so `capacity` is the neutral 1 rather than a reading. */
4380
- recognised: z9.boolean(),
4380
+ recognised: z11.boolean(),
4381
4381
  /** The tier string the classification rests on, when the account had one. */
4382
- tier: z9.string().optional()
4382
+ tier: z11.string().optional()
4383
4383
  }),
4384
- z9.strictObject({
4385
- kind: z9.literal("pay-per-use"),
4386
- tier: z9.string().optional()
4384
+ z11.strictObject({
4385
+ kind: z11.literal("pay-per-use"),
4386
+ tier: z11.string().optional()
4387
4387
  })
4388
4388
  ]);
4389
4389
  TIER_MULTIPLIER = /(?:^|_)(\d+)x$/;
@@ -4484,21 +4484,21 @@ var init_rateLimit = __esm({
4484
4484
  });
4485
4485
 
4486
4486
  // src/usage/scan.ts
4487
- import { z as z10 } from "zod";
4487
+ import { z as z12 } from "zod";
4488
4488
  var AnthropicUsageSchema, ErrorObjectSchema;
4489
4489
  var init_scan = __esm({
4490
4490
  "src/usage/scan.ts"() {
4491
4491
  "use strict";
4492
- AnthropicUsageSchema = z10.looseObject({
4493
- input_tokens: z10.number().int().nonnegative().nullish(),
4494
- output_tokens: z10.number().int().nonnegative().nullish(),
4495
- cache_creation_input_tokens: z10.number().int().nonnegative().nullish(),
4496
- cache_read_input_tokens: z10.number().int().nonnegative().nullish()
4492
+ AnthropicUsageSchema = z12.looseObject({
4493
+ input_tokens: z12.number().int().nonnegative().nullish(),
4494
+ output_tokens: z12.number().int().nonnegative().nullish(),
4495
+ cache_creation_input_tokens: z12.number().int().nonnegative().nullish(),
4496
+ cache_read_input_tokens: z12.number().int().nonnegative().nullish()
4497
4497
  });
4498
- ErrorObjectSchema = z10.looseObject({
4499
- type: z10.string().optional(),
4500
- code: z10.union([z10.string(), z10.number()]).optional(),
4501
- message: z10.string().optional()
4498
+ ErrorObjectSchema = z12.looseObject({
4499
+ type: z12.string().optional(),
4500
+ code: z12.union([z12.string(), z12.number()]).optional(),
4501
+ message: z12.string().optional()
4502
4502
  });
4503
4503
  }
4504
4504
  });
@@ -4791,22 +4791,25 @@ function rankPool(input) {
4791
4791
  return { ...candidate, feasible: true };
4792
4792
  }
4793
4793
  const drySpots = [];
4794
+ const dryAfterMs = [];
4794
4795
  if (fiveHour !== void 0 && pace !== void 0) {
4795
4796
  const runsDryInMs = fiveHour.remaining / pace;
4796
4797
  if (runsDryInMs < fiveHour.untilResetMs) {
4798
+ dryAfterMs.push(runsDryInMs);
4797
4799
  drySpots.push(`5h window would run dry in ${formatAge(runsDryInMs)}, before it resets in ${formatAge(fiveHour.untilResetMs)}`);
4798
4800
  }
4799
4801
  }
4800
4802
  if (sevenDay !== void 0 && sevenDayBurn !== void 0) {
4801
4803
  const runsDryInMs = sevenDay.remaining / sevenDayBurn;
4802
4804
  if (runsDryInMs < sevenDay.untilResetMs) {
4805
+ dryAfterMs.push(runsDryInMs);
4803
4806
  drySpots.push(`7d window would run dry in ${formatAge(runsDryInMs)}, before it resets in ${formatAge(sevenDay.untilResetMs)}`);
4804
4807
  }
4805
4808
  }
4806
4809
  if (drySpots.length === 0) {
4807
4810
  return { ...candidate, feasible: true };
4808
4811
  }
4809
- return { ...candidate, feasible: false, reasons: [...drySpots, ...candidate.reasons] };
4812
+ return { ...candidate, feasible: false, runsDryAtMs: nowMs + Math.min(...dryAfterMs), reasons: [...drySpots, ...candidate.reasons] };
4810
4813
  });
4811
4814
  const ordered = input.preference === "listed" ? [...candidates] : [...candidates].sort(
4812
4815
  (left, right) => CLASS_ORDER[left.class] - CLASS_ORDER[right.class] || Number(left.policyDemoted ?? false) - Number(right.policyDemoted ?? false) || Number(right.feasible) - Number(left.feasible) || (right.headroom ?? 1) - (left.headroom ?? 1) || (right.score ?? 0) - (left.score ?? 0) || left.identity.localeCompare(right.identity)
@@ -4828,11 +4831,13 @@ function rankPool(input) {
4828
4831
  const pick = ordered.find((candidate) => candidate.class !== "ineligible");
4829
4832
  const returns = ordered.flatMap((candidate) => candidate.blockedUntilMs === void 0 ? [] : [{ identity: candidate.identity, atMs: candidate.blockedUntilMs }]);
4830
4833
  const earliestReturn = returns.length === 0 ? void 0 : returns.reduce((soonest, entry) => entry.atMs < soonest.atMs ? entry : soonest);
4834
+ const holdForReturn = pick?.runsDryAtMs === void 0 ? void 0 : returns.filter((entry) => entry.atMs < (pick.runsDryAtMs ?? 0)).reduce((soonest, entry) => soonest === void 0 || entry.atMs < soonest.atMs ? entry : soonest, void 0);
4831
4835
  return {
4832
4836
  candidates: ordered,
4833
4837
  ...pick === void 0 ? { ...earliestReturn === void 0 ? {} : { earliestReturn } } : { pick },
4834
4838
  ...movedOff === void 0 || pick === void 0 ? {} : { movedOff },
4835
- ...pick?.planReturnsAtMs === void 0 ? {} : { planReturn: { identity: pick.identity, atMs: pick.planReturnsAtMs } }
4839
+ ...pick?.planReturnsAtMs === void 0 ? {} : { planReturn: { identity: pick.identity, atMs: pick.planReturnsAtMs } },
4840
+ ...holdForReturn === void 0 ? {} : { holdForReturn }
4836
4841
  };
4837
4842
  }
4838
4843
  var MS_PER_SECOND4, MS_PER_HOUR2, HOURS_PER_DAY2, FIVE_HOURS, PROMPT_CACHE_TTL_HOURS, PERCENT, SEVEN_DAYS, FIVE_HOUR_WINDOW_MS, SEVEN_DAY_WINDOW_MS, PROMPT_CACHE_TTL_MS, CLASS_ORDER;
@@ -5098,7 +5103,7 @@ var init_store2 = __esm({
5098
5103
 
5099
5104
  // src/usage/poolPick.ts
5100
5105
  import path20 from "node:path";
5101
- import { z as z11 } from "zod";
5106
+ import { z as z13 } from "zod";
5102
5107
  function errorMessage(error) {
5103
5108
  return error instanceof Error ? error.message : String(error);
5104
5109
  }
@@ -5248,10 +5253,10 @@ var init_poolPick = __esm({
5248
5253
  }
5249
5254
  };
5250
5255
  SCHEMA_VERSION = 1;
5251
- PickEntrySchema = z11.strictObject({ identity: z11.string().min(1), at: z11.iso.datetime() });
5252
- PicksFileSchema = z11.strictObject({
5253
- schemaVersion: z11.literal(SCHEMA_VERSION),
5254
- picks: z11.record(z11.string().min(1), PickEntrySchema)
5256
+ PickEntrySchema = z13.strictObject({ identity: z13.string().min(1), at: z13.iso.datetime() });
5257
+ PicksFileSchema = z13.strictObject({
5258
+ schemaVersion: z13.literal(SCHEMA_VERSION),
5259
+ picks: z13.record(z13.string().min(1), PickEntrySchema)
5255
5260
  });
5256
5261
  }
5257
5262
  });
@@ -5331,7 +5336,7 @@ var init_paths = __esm({
5331
5336
  });
5332
5337
 
5333
5338
  // src/credentialCache.ts
5334
- import { z as z12 } from "zod";
5339
+ import { z as z14 } from "zod";
5335
5340
  function effectiveStore(cache, platform) {
5336
5341
  return cache.store ?? (platform === "darwin" ? "keychain" : "file");
5337
5342
  }
@@ -5398,9 +5403,9 @@ var init_credentialCache = __esm({
5398
5403
  init_schema();
5399
5404
  init_preflight();
5400
5405
  MS_PER_UNIT = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
5401
- CachedCredentialSchema = z12.strictObject({
5402
- token: z12.string().min(1),
5403
- fetchedAt: z12.number().int().nonnegative(),
5406
+ CachedCredentialSchema = z14.strictObject({
5407
+ token: z14.string().min(1),
5408
+ fetchedAt: z14.number().int().nonnegative(),
5404
5409
  source: CredentialSourceSchema
5405
5410
  });
5406
5411
  }
@@ -5673,14 +5678,14 @@ function providerJsonPath(paths, name) {
5673
5678
  function providerExists(paths, name) {
5674
5679
  return fs7.existsSync(providerJsonPath(paths, name));
5675
5680
  }
5676
- function isRecord4(value) {
5681
+ function isRecord5(value) {
5677
5682
  return typeof value === "object" && value !== null && !Array.isArray(value);
5678
5683
  }
5679
5684
  function legacyProviderConversion(raw) {
5680
- if (!isRecord4(raw) || "credential" in raw) {
5685
+ if (!isRecord5(raw) || "credential" in raw) {
5681
5686
  return void 0;
5682
5687
  }
5683
- const env = isRecord4(raw.env) ? raw.env : void 0;
5688
+ const env = isRecord5(raw.env) ? raw.env : void 0;
5684
5689
  const legacyEnvKeys = env === void 0 ? [] : Object.keys(env).filter((key) => LEGACY_ENV_CREDENTIAL_KEYS.includes(key));
5685
5690
  const fields = [...LEGACY_PROVIDER_FIELDS.filter((field) => field in raw), ...legacyEnvKeys.map((key) => `env.${key}`)];
5686
5691
  if (fields.length === 0) {
@@ -6102,7 +6107,7 @@ var init_commandDeps = __esm({
6102
6107
  // src/claudeShim.ts
6103
6108
  import fs8 from "node:fs";
6104
6109
  import path26 from "node:path";
6105
- import { z as z17 } from "zod";
6110
+ import { z as z19 } from "zod";
6106
6111
  function commandFilename(ownExecutablePath, commandName) {
6107
6112
  return ownExecutablePath.toLowerCase().endsWith(".exe") ? `${commandName}.exe` : commandName;
6108
6113
  }
@@ -6152,10 +6157,10 @@ var init_claudeShim = __esm({
6152
6157
  init_store();
6153
6158
  init_realPorts();
6154
6159
  init_cliError();
6155
- ClaudeShimStateSchema = z17.strictObject({
6156
- targetPath: z17.string().min(1),
6157
- method: z17.enum(["hardlink", "copy"]),
6158
- installedAtMs: z17.number()
6160
+ ClaudeShimStateSchema = z19.strictObject({
6161
+ targetPath: z19.string().min(1),
6162
+ method: z19.enum(["hardlink", "copy"]),
6163
+ installedAtMs: z19.number()
6159
6164
  });
6160
6165
  nodeLinkFs = { link: fs8.linkSync, copyFile: fs8.copyFileSync, chmod: fs8.chmodSync };
6161
6166
  }
@@ -6630,7 +6635,7 @@ var init_headers = __esm({
6630
6635
  });
6631
6636
 
6632
6637
  // src/launcher/flags.ts
6633
- import path34 from "node:path";
6638
+ import path35 from "node:path";
6634
6639
  function resolveLaunchFlags(params) {
6635
6640
  return {
6636
6641
  skipPermissions: params.flags?.skipPermissions ?? parseEnvBool("AGENT_SHIM_SKIP_PERMISSIONS", params.env.AGENT_SHIM_SKIP_PERMISSIONS) ?? params.cascade?.skipPermissions ?? false,
@@ -6661,7 +6666,7 @@ function buildEnv(params) {
6661
6666
  const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
6662
6667
  let providerCustomHeaders;
6663
6668
  if (!params.configDirEscapeHatch && params.resolvedIdentityName !== void 0) {
6664
- env.CLAUDE_CONFIG_DIR = path34.join(params.identitiesDir, params.resolvedIdentityName);
6669
+ env.CLAUDE_CONFIG_DIR = path35.join(params.identitiesDir, params.resolvedIdentityName);
6665
6670
  }
6666
6671
  if (params.provider !== void 0) {
6667
6672
  const providerEnv = params.provider.definition.env ?? {};
@@ -6782,12 +6787,17 @@ function resolvePoolLaunch(params) {
6782
6787
  if (graph.ranking.candidates.length === 0) {
6783
6788
  return { ok: false, message: `agent-shim: no member of pool "${poolName}" is an existing identity.` };
6784
6789
  }
6785
- const { pick, earliestReturn, movedOff, planReturn } = graph.ranking;
6790
+ const { pick, earliestReturn, movedOff, planReturn, holdForReturn } = graph.ranking;
6786
6791
  if (pick !== void 0 && params.wait && planReturn !== void 0) {
6787
6792
  log.info(`agent-shim: pool "${poolName}" would continue ${planReturn.identity} on extra usage; waiting until ${new Date(planReturn.atMs).toISOString()} for its plan window`);
6788
6793
  params.sleep(Math.max(planReturn.atMs - nowMs, 0));
6789
6794
  continue;
6790
6795
  }
6796
+ if (pick !== void 0 && params.wait && holdForReturn !== void 0) {
6797
+ log.info(`agent-shim: pool "${poolName}" pick ${pick.identity} would run dry before its window resets; waiting until ${new Date(holdForReturn.atMs).toISOString()} for ${holdForReturn.identity}`);
6798
+ params.sleep(Math.max(holdForReturn.atMs - nowMs, 0));
6799
+ continue;
6800
+ }
6791
6801
  if (pick !== void 0) {
6792
6802
  if (params.recordPick) {
6793
6803
  recordStickyPick(params.usageFs, params.paths.usagePicksFile, params.cwd, pick.identity, nowMs);
@@ -6928,7 +6938,7 @@ var init_launchHook = __esm({
6928
6938
 
6929
6939
  // src/launcher.ts
6930
6940
  import { randomUUID as randomUUID4 } from "node:crypto";
6931
- import path35 from "node:path";
6941
+ import path36 from "node:path";
6932
6942
  function resolveIdentityCredential(identity, credential, env, port) {
6933
6943
  if (port === void 0) {
6934
6944
  return { ok: false, status: 1, message: `agent-shim: identity ${identity} needs its credential resolved, but this launcher has no credential port wired` };
@@ -7038,7 +7048,7 @@ function decideLaunch(params, readOnly) {
7038
7048
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
7039
7049
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
7040
7050
  });
7041
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs12.readConfigFile(path35.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
7051
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs12.readConfigFile(path36.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
7042
7052
  log.error(
7043
7053
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
7044
7054
  );
@@ -7150,7 +7160,7 @@ function decideLaunch(params, readOnly) {
7150
7160
  extraFlags: splitExtraFlags(env.CLAUDE_EXTRA_FLAGS),
7151
7161
  passthrough: parsedArgv.rest
7152
7162
  });
7153
- const configDir = configDirEscapeHatchApplies || identityDecision.name === void 0 ? env.CLAUDE_CONFIG_DIR : path35.join(paths.identitiesDir, identityDecision.name);
7163
+ const configDir = configDirEscapeHatchApplies || identityDecision.name === void 0 ? env.CLAUDE_CONFIG_DIR : path36.join(paths.identitiesDir, identityDecision.name);
7154
7164
  const decision = {
7155
7165
  identitySource: identityDecision.source,
7156
7166
  configDirEscapeHatch: identityDecision.configDirEscapeHatch,
@@ -7191,7 +7201,7 @@ function prepareLaunch(params) {
7191
7201
  );
7192
7202
  const updateCheck = runLaunchUpdateCheck({
7193
7203
  mode: params.updateMode ?? "off",
7194
- checkPath: path35.join(paths.root, "update.check"),
7204
+ checkPath: path36.join(paths.root, "update.check"),
7195
7205
  currentVersion: package_default.version,
7196
7206
  port: params.update
7197
7207
  });
@@ -7351,12 +7361,12 @@ var init_launcher = __esm({
7351
7361
  });
7352
7362
 
7353
7363
  // src/ownCli.ts
7354
- import path36 from "node:path";
7364
+ import path37 from "node:path";
7355
7365
  function agentShimCliPath(distDir = typeof __AGENT_SHIM_DIST_DIR__ === "string" ? __AGENT_SHIM_DIST_DIR__ : void 0) {
7356
7366
  if (distDir === void 0) {
7357
7367
  throw new OwnCliPathUnknownError();
7358
7368
  }
7359
- return path36.join(distDir, OWN_CLI_FILE_NAME);
7369
+ return path37.join(distDir, OWN_CLI_FILE_NAME);
7360
7370
  }
7361
7371
  var OWN_CLI_FILE_NAME, OwnCliPathUnknownError;
7362
7372
  var init_ownCli = __esm({
@@ -7445,10 +7455,10 @@ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " :
7445
7455
 
7446
7456
  // src/frontdoor/trust.ts
7447
7457
  import { createHash as createHash6 } from "node:crypto";
7448
- import path37 from "node:path";
7458
+ import path38 from "node:path";
7449
7459
  function resolveTrustBundle(params) {
7450
7460
  const { caCertFile, bundlesDir, variable, inherited, fs: fs12 } = params;
7451
- if (inherited === void 0 || inherited === "" || path37.resolve(inherited) === path37.resolve(caCertFile)) {
7461
+ if (inherited === void 0 || inherited === "" || path38.resolve(inherited) === path38.resolve(caCertFile)) {
7452
7462
  return { path: caCertFile };
7453
7463
  }
7454
7464
  const caPem = fs12.readFileUtf8(caCertFile);
@@ -7466,7 +7476,7 @@ function resolveTrustBundle(params) {
7466
7476
  }
7467
7477
  const combined = `${inheritedPem.trimEnd()}
7468
7478
  ${caPem}`;
7469
- const bundle = path37.join(bundlesDir, `${createHash6("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
7479
+ const bundle = path38.join(bundlesDir, `${createHash6("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
7470
7480
  if (!fs12.exists(bundle)) {
7471
7481
  fs12.mkdirp(bundlesDir);
7472
7482
  fs12.writeFileAtomic(bundle, combined);
@@ -7866,7 +7876,7 @@ var init_identityClaude = __esm({
7866
7876
  });
7867
7877
 
7868
7878
  // src/usage/providerQuota.ts
7869
- import { z as z27 } from "zod";
7879
+ import { z as z29 } from "zod";
7870
7880
  var MS_PER_SECOND7, SECONDS_PER_HOUR, HOURS_PER_DAY4, 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_DAY3, OpenRouterKeySchema, OpenRouterCreditsSchema;
7871
7881
  var init_providerQuota = __esm({
7872
7882
  "src/usage/providerQuota.ts"() {
@@ -7884,35 +7894,35 @@ var init_providerQuota = __esm({
7884
7894
  [ZAI_UNIT_HOURS, SECONDS_PER_HOUR * MS_PER_SECOND7],
7885
7895
  [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY4 * SECONDS_PER_HOUR * MS_PER_SECOND7]
7886
7896
  ]);
7887
- ZaiLimitSchema = z27.object({
7888
- type: z27.string(),
7889
- unit: z27.number().int(),
7890
- number: z27.number().int().positive(),
7891
- percentage: z27.number().nonnegative(),
7892
- nextResetTime: z27.number().positive().optional(),
7893
- usage: z27.number().nonnegative().optional(),
7894
- currentValue: z27.number().nonnegative().optional(),
7895
- remaining: z27.number().nonnegative().optional()
7897
+ ZaiLimitSchema = z29.object({
7898
+ type: z29.string(),
7899
+ unit: z29.number().int(),
7900
+ number: z29.number().int().positive(),
7901
+ percentage: z29.number().nonnegative(),
7902
+ nextResetTime: z29.number().positive().optional(),
7903
+ usage: z29.number().nonnegative().optional(),
7904
+ currentValue: z29.number().nonnegative().optional(),
7905
+ remaining: z29.number().nonnegative().optional()
7896
7906
  });
7897
- ZaiResponseSchema = z27.object({
7898
- success: z27.boolean(),
7899
- msg: z27.string().optional(),
7900
- data: z27.object({ level: z27.string().optional(), limits: z27.array(ZaiLimitSchema) })
7907
+ ZaiResponseSchema = z29.object({
7908
+ success: z29.boolean(),
7909
+ msg: z29.string().optional(),
7910
+ data: z29.object({ level: z29.string().optional(), limits: z29.array(ZaiLimitSchema) })
7901
7911
  });
7902
7912
  OPENROUTER_HOST = "openrouter.ai";
7903
7913
  OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
7904
7914
  OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
7905
7915
  MS_PER_DAY3 = HOURS_PER_DAY4 * SECONDS_PER_HOUR * MS_PER_SECOND7;
7906
- OpenRouterKeySchema = z27.object({
7907
- data: z27.object({
7908
- limit: z27.number().nonnegative().nullable(),
7909
- limit_remaining: z27.number().nullable(),
7910
- limit_reset: z27.string().nullable(),
7911
- is_free_tier: z27.boolean().optional(),
7912
- free_model_daily_requests: z27.object({ used: z27.number().nonnegative(), limit: z27.number().nonnegative(), remaining: z27.number() }).optional()
7916
+ OpenRouterKeySchema = z29.object({
7917
+ data: z29.object({
7918
+ limit: z29.number().nonnegative().nullable(),
7919
+ limit_remaining: z29.number().nullable(),
7920
+ limit_reset: z29.string().nullable(),
7921
+ is_free_tier: z29.boolean().optional(),
7922
+ free_model_daily_requests: z29.object({ used: z29.number().nonnegative(), limit: z29.number().nonnegative(), remaining: z29.number() }).optional()
7913
7923
  })
7914
7924
  });
7915
- OpenRouterCreditsSchema = z27.object({ data: z27.object({ total_credits: z27.number().nonnegative(), total_usage: z27.number().nonnegative() }) });
7925
+ OpenRouterCreditsSchema = z29.object({ data: z29.object({ total_credits: z29.number().nonnegative(), total_usage: z29.number().nonnegative() }) });
7916
7926
  }
7917
7927
  });
7918
7928
 
@@ -8525,8 +8535,8 @@ function parseConnectTarget(authority) {
8525
8535
  function isInterceptedHost(host, interceptHosts) {
8526
8536
  return interceptHosts.includes(host);
8527
8537
  }
8528
- function servedByPipeline(path38) {
8529
- return path38?.startsWith(ROUTED_PATH_PREFIX) === true;
8538
+ function servedByPipeline(path39) {
8539
+ return path39?.startsWith(ROUTED_PATH_PREFIX) === true;
8530
8540
  }
8531
8541
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
8532
8542
  "connection",
@@ -8896,6 +8906,264 @@ var HTTP_STATUS = {
8896
8906
  badGateway: 502
8897
8907
  };
8898
8908
 
8909
+ // src/agents/liveTasks.ts
8910
+ import { z as z5 } from "zod";
8911
+
8912
+ // src/agents/schema.ts
8913
+ import { z as z4 } from "zod";
8914
+ var AgentMetaSchema = z4.looseObject({
8915
+ agentType: z4.string(),
8916
+ isFork: z4.boolean().optional(),
8917
+ description: z4.string().optional(),
8918
+ name: z4.string().optional(),
8919
+ toolUseId: z4.string().optional(),
8920
+ spawnDepth: z4.number().int().nonnegative().optional(),
8921
+ parentAgentId: z4.string().optional(),
8922
+ model: z4.string().optional(),
8923
+ requestShape: z4.string().optional(),
8924
+ requestNonInteractive: z4.boolean().optional(),
8925
+ workflowPhase: z4.string().optional(),
8926
+ taskKind: z4.string().optional(),
8927
+ teamName: z4.string().optional(),
8928
+ worktreePath: z4.string().optional(),
8929
+ worktreeBranch: z4.string().optional(),
8930
+ stoppedByUser: z4.boolean().optional()
8931
+ });
8932
+ var AgentKindSchema = z4.enum(["subagent", "fork", "workflow-agent", "teammate"]);
8933
+ var AgentNodeFields = {
8934
+ id: z4.string(),
8935
+ kind: AgentKindSchema,
8936
+ agentType: z4.string(),
8937
+ description: z4.string().optional(),
8938
+ name: z4.string().optional(),
8939
+ toolUseId: z4.string().optional(),
8940
+ spawnDepth: z4.number().int().nonnegative().optional(),
8941
+ model: z4.string().optional(),
8942
+ background: z4.boolean().optional(),
8943
+ workflowRunId: z4.string().optional(),
8944
+ workflowPhase: z4.string().optional(),
8945
+ teamName: z4.string().optional(),
8946
+ stoppedByUser: z4.boolean().optional(),
8947
+ transcript: z4.string()
8948
+ };
8949
+ var AgentNodeSchema = z4.lazy(() => z4.strictObject({ ...AgentNodeFields, children: z4.array(AgentNodeSchema) }));
8950
+ var TaskItemSchema = z4.strictObject({
8951
+ id: z4.string(),
8952
+ subject: z4.string(),
8953
+ description: z4.string().optional(),
8954
+ status: z4.string(),
8955
+ /** What a spinner shows while the task runs. */
8956
+ activeForm: z4.string().optional(),
8957
+ /** The teammate or agent name the task is assigned to, as Agent Teams writes it. */
8958
+ owner: z4.string().optional(),
8959
+ /** Free-form data the harness attaches to a task, kept as written. */
8960
+ metadata: z4.record(z4.string(), z4.unknown()).optional(),
8961
+ blocks: z4.array(z4.string()),
8962
+ blockedBy: z4.array(z4.string()),
8963
+ /** The id of the shared task list this task belongs to (a team's name, or a custom list id), absent for the session's own list. */
8964
+ taskList: z4.string().optional()
8965
+ });
8966
+ var WorkflowRunSchema = z4.strictObject({
8967
+ runId: z4.string(),
8968
+ workflowName: z4.string().optional(),
8969
+ status: z4.string().optional(),
8970
+ startTime: z4.number().optional(),
8971
+ phases: z4.array(z4.string()),
8972
+ summary: z4.string().optional()
8973
+ });
8974
+ var AgentTreeProblemSchema = z4.strictObject({
8975
+ /** Relative to the identity's configuration directory. */
8976
+ path: z4.string(),
8977
+ reason: z4.string()
8978
+ });
8979
+ var SessionSummarySchema = z4.strictObject({
8980
+ project: z4.string(),
8981
+ sessionId: z4.string(),
8982
+ superseded: z4.boolean(),
8983
+ /** The directory and transcript stem exactly as on disk, which differs from `sessionId` for a superseded session. */
8984
+ entry: z4.string(),
8985
+ agentCount: z4.number().int().nonnegative(),
8986
+ workflowRunCount: z4.number().int().nonnegative(),
8987
+ /** When the transcript was last written, as an ISO instant; absent when there is no transcript file. */
8988
+ updatedAt: z4.iso.datetime().optional(),
8989
+ identities: z4.array(z4.string())
8990
+ });
8991
+ var SessionAgentTreeSchema = z4.strictObject({
8992
+ project: z4.string(),
8993
+ sessionId: z4.string(),
8994
+ /** True for a session directory a resume superseded (`<session-id>.superseded-<epoch-ms>`). */
8995
+ superseded: z4.boolean(),
8996
+ /** The agents the session itself spawned, each with its descendants. */
8997
+ agents: z4.array(AgentNodeSchema),
8998
+ tasks: z4.array(TaskItemSchema),
8999
+ workflowRuns: z4.array(WorkflowRunSchema),
9000
+ problems: z4.array(AgentTreeProblemSchema)
9001
+ });
9002
+
9003
+ // src/agents/liveTasks.ts
9004
+ var LIVE_TASK_CAP = 512;
9005
+ var RUNNING_STATUS = "running";
9006
+ var LiveTaskUsageSchema = z5.strictObject({
9007
+ totalTokens: z5.number().optional(),
9008
+ toolUses: z5.number().optional(),
9009
+ durationMs: z5.number().optional()
9010
+ });
9011
+ var LiveTaskSchema = z5.strictObject({
9012
+ /** The `task_id`: for an unnamed subagent the stem of its `agent-<id>` files on disk. */
9013
+ taskId: z5.string(),
9014
+ /** The `cse_` session whose stream carried the task. */
9015
+ sessionId: z5.string(),
9016
+ runId: z5.string().optional(),
9017
+ /** The `tool_use` block in the spawning transcript, which is the meta file's `toolUseId`. */
9018
+ toolUseId: z5.string().optional(),
9019
+ /** `local_agent` for a subagent, `local_bash` for a backgrounded command; open because other kinds may exist. */
9020
+ taskType: z5.string().optional(),
9021
+ description: z5.string().optional(),
9022
+ subagentType: z5.string().optional(),
9023
+ spawnDepth: z5.number().int().nonnegative().optional(),
9024
+ parentTaskId: z5.string().optional(),
9025
+ backgrounded: z5.boolean().optional(),
9026
+ status: z5.string(),
9027
+ /** `<tmpdir>/<project-slug>/<local session id>/tasks/<task_id>.output`, which embeds the local session id. */
9028
+ outputFile: z5.string().optional(),
9029
+ summary: z5.string().optional(),
9030
+ lastToolName: z5.string().optional(),
9031
+ usage: LiveTaskUsageSchema.optional(),
9032
+ /** When the door last observed an event for this task, in epoch milliseconds from its injected clock. */
9033
+ observedAt: z5.number()
9034
+ });
9035
+ var SYSTEM_SUBTYPES = ["task_started", "task_progress", "task_updated", "task_notification", "background_tasks_changed"];
9036
+ function isRecord2(value) {
9037
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9038
+ }
9039
+ function stringField(record, field) {
9040
+ const value = record[field];
9041
+ return typeof value === "string" && value !== "" ? value : void 0;
9042
+ }
9043
+ function numberField(record, field) {
9044
+ const value = record[field];
9045
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
9046
+ }
9047
+ function booleanField(record, field) {
9048
+ const value = record[field];
9049
+ return typeof value === "boolean" ? value : void 0;
9050
+ }
9051
+ function usageOf(record) {
9052
+ const raw = record.usage;
9053
+ if (!isRecord2(raw)) {
9054
+ return void 0;
9055
+ }
9056
+ const totalTokens = numberField(raw, "total_tokens");
9057
+ const toolUses = numberField(raw, "tool_uses");
9058
+ const durationMs = numberField(raw, "duration_ms");
9059
+ if (totalTokens === void 0 && toolUses === void 0 && durationMs === void 0) {
9060
+ return void 0;
9061
+ }
9062
+ return { ...totalTokens === void 0 ? {} : { totalTokens }, ...toolUses === void 0 ? {} : { toolUses }, ...durationMs === void 0 ? {} : { durationMs } };
9063
+ }
9064
+ function overlay(base, fields) {
9065
+ const defined = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
9066
+ return LiveTaskSchema.parse({ ...base, ...defined });
9067
+ }
9068
+ function isFinished(task) {
9069
+ return task.status !== RUNNING_STATUS;
9070
+ }
9071
+ function bounded(book) {
9072
+ if (book.size <= LIVE_TASK_CAP) {
9073
+ return book;
9074
+ }
9075
+ const evictable = [...book.values()].filter(isFinished).sort((left, right) => left.observedAt - right.observedAt);
9076
+ for (const task of evictable) {
9077
+ if (book.size <= LIVE_TASK_CAP) {
9078
+ break;
9079
+ }
9080
+ book.delete(task.taskId);
9081
+ }
9082
+ return book;
9083
+ }
9084
+ function applyAgentTaskEvent(book, sessionId, payload, observedAt2) {
9085
+ if (!isRecord2(payload) || payload.type !== "system") {
9086
+ return book;
9087
+ }
9088
+ const subtype = payload.subtype;
9089
+ if (typeof subtype !== "string" || !SYSTEM_SUBTYPES.some((known) => known === subtype)) {
9090
+ return book;
9091
+ }
9092
+ const next = new Map(book);
9093
+ const upsert = (taskId2, fields) => {
9094
+ const existing = next.get(taskId2);
9095
+ const base = existing ?? { taskId: taskId2, sessionId, status: RUNNING_STATUS, observedAt: observedAt2 };
9096
+ next.set(taskId2, overlay(base, { ...fields, observedAt: observedAt2 }));
9097
+ };
9098
+ if (subtype === "background_tasks_changed") {
9099
+ const tasks = Array.isArray(payload.tasks) ? payload.tasks : [];
9100
+ for (const raw of tasks) {
9101
+ const taskId2 = isRecord2(raw) ? stringField(raw, "task_id") : void 0;
9102
+ if (isRecord2(raw) && taskId2 !== void 0) {
9103
+ upsert(taskId2, { runId: stringField(raw, "run_id"), taskType: stringField(raw, "task_type"), description: stringField(raw, "description") });
9104
+ }
9105
+ }
9106
+ return bounded(next);
9107
+ }
9108
+ const taskId = stringField(payload, "task_id");
9109
+ if (taskId === void 0) {
9110
+ return book;
9111
+ }
9112
+ const common = { runId: stringField(payload, "run_id"), toolUseId: stringField(payload, "tool_use_id"), description: stringField(payload, "description") };
9113
+ if (subtype === "task_started") {
9114
+ upsert(taskId, {
9115
+ ...common,
9116
+ taskType: stringField(payload, "task_type"),
9117
+ subagentType: stringField(payload, "subagent_type"),
9118
+ spawnDepth: numberField(payload, "spawn_depth"),
9119
+ parentTaskId: stringField(payload, "parent_task_id"),
9120
+ backgrounded: booleanField(payload, "is_backgrounded")
9121
+ });
9122
+ } else if (subtype === "task_progress") {
9123
+ upsert(taskId, { ...common, subagentType: stringField(payload, "subagent_type"), lastToolName: stringField(payload, "last_tool_name"), usage: usageOf(payload) });
9124
+ } else if (subtype === "task_updated") {
9125
+ const patch = isRecord2(payload.patch) ? payload.patch : {};
9126
+ upsert(taskId, { runId: stringField(payload, "run_id"), status: stringField(patch, "status") });
9127
+ } else {
9128
+ upsert(taskId, { ...common, status: stringField(payload, "status"), outputFile: stringField(payload, "output_file"), summary: stringField(payload, "summary"), usage: usageOf(payload) });
9129
+ }
9130
+ return bounded(next);
9131
+ }
9132
+ var MergedProvenanceSchema = z5.enum(["disk", "both"]);
9133
+ var MergedAgentNodeSchema = z5.lazy(
9134
+ () => z5.strictObject({
9135
+ ...AgentNodeFields,
9136
+ provenance: MergedProvenanceSchema,
9137
+ live: LiveTaskSchema.optional(),
9138
+ children: z5.array(MergedAgentNodeSchema)
9139
+ })
9140
+ );
9141
+ var MergedAgentTreeSchema = z5.strictObject({
9142
+ ...SessionAgentTreeSchema.shape,
9143
+ agents: z5.array(MergedAgentNodeSchema),
9144
+ /** The `cse_` sessions whose live tasks matched this session. Empty when the session is not live or the door has not observed it. */
9145
+ remoteSessions: z5.array(z5.string()),
9146
+ /** Live tasks of those sessions that match no disk agent (a backgrounded command, or an agent whose files have not appeared yet). */
9147
+ liveOnly: z5.array(LiveTaskSchema)
9148
+ });
9149
+ function mergeLiveTasks(tree, live) {
9150
+ const byTaskId = new Map(live.map((task) => [task.taskId, task]));
9151
+ const byToolUseId = new Map(live.flatMap((task) => task.toolUseId === void 0 ? [] : [[task.toolUseId, task]]));
9152
+ const claimed = /* @__PURE__ */ new Set();
9153
+ const merge = (node) => {
9154
+ const task = byTaskId.get(node.id) ?? (node.toolUseId === void 0 ? void 0 : byToolUseId.get(node.toolUseId));
9155
+ if (task !== void 0) {
9156
+ claimed.add(task.taskId);
9157
+ }
9158
+ return { ...node, provenance: task === void 0 ? "disk" : "both", ...task === void 0 ? {} : { live: task }, children: node.children.map(merge) };
9159
+ };
9160
+ const agents = tree.agents.map(merge);
9161
+ const sessionMarker = `/${tree.sessionId}/`;
9162
+ const liveOnly = live.filter((task) => !claimed.has(task.taskId) && task.outputFile?.includes(sessionMarker) === true);
9163
+ const remoteSessions = [...new Set([...claimed, ...liveOnly.map((task) => task.taskId)].flatMap((taskId) => byTaskId.get(taskId)?.sessionId ?? []))].sort();
9164
+ return { ...tree, agents, remoteSessions, liveOnly };
9165
+ }
9166
+
8899
9167
  // src/frontdoor/rcSessions.ts
8900
9168
  var RC_SESSIONS_PATH_PREFIX = "/v1/code/sessions";
8901
9169
  var RC_SESSION_ID_PREFIX = "cse_";
@@ -8936,7 +9204,7 @@ function sessionCreateId(body) {
8936
9204
  const id = session.id;
8937
9205
  return typeof id === "string" && id.startsWith(RC_SESSION_ID_PREFIX) ? id : void 0;
8938
9206
  }
8939
- function isRecord2(value) {
9207
+ function isRecord3(value) {
8940
9208
  return typeof value === "object" && value !== null && !Array.isArray(value);
8941
9209
  }
8942
9210
  function parseJsonObject(body) {
@@ -8946,7 +9214,7 @@ function parseJsonObject(body) {
8946
9214
  } catch {
8947
9215
  return void 0;
8948
9216
  }
8949
- return isRecord2(parsed) ? parsed : void 0;
9217
+ return isRecord3(parsed) ? parsed : void 0;
8950
9218
  }
8951
9219
  function nonEmptyString(record, field) {
8952
9220
  const value = record === void 0 ? void 0 : record[field];
@@ -8967,11 +9235,11 @@ function payloadEventsOf(body) {
8967
9235
  }
8968
9236
  const payloads = [];
8969
9237
  for (const event of events) {
8970
- if (!isRecord2(event)) {
9238
+ if (!isRecord3(event)) {
8971
9239
  continue;
8972
9240
  }
8973
9241
  const payload = event.payload;
8974
- if (!isRecord2(payload)) {
9242
+ if (!isRecord3(payload)) {
8975
9243
  continue;
8976
9244
  }
8977
9245
  payloads.push(payload);
@@ -8986,7 +9254,7 @@ function pendingOfControlRequestPayload(payload) {
8986
9254
  if (requestId === void 0) {
8987
9255
  return void 0;
8988
9256
  }
8989
- const request4 = isRecord2(payload.request) ? payload.request : void 0;
9257
+ const request4 = isRecord3(payload.request) ? payload.request : void 0;
8990
9258
  const subtype = nonEmptyString(request4, "subtype");
8991
9259
  const type = subtype ?? "control_request";
8992
9260
  let summary = "";
@@ -9003,20 +9271,21 @@ function answeredRequestIdsOfControlResponsePayload(payload) {
9003
9271
  if (payload.type !== "control_response") {
9004
9272
  return [];
9005
9273
  }
9006
- const response = isRecord2(payload.response) ? payload.response : void 0;
9274
+ const response = isRecord3(payload.response) ? payload.response : void 0;
9007
9275
  const id = nonEmptyString(response, "request_id") ?? nonEmptyString(payload, "request_id") ?? nonEmptyString(payload, "uuid");
9008
9276
  return id === void 0 ? [] : [id];
9009
9277
  }
9010
9278
  function parseRcRequestBody(kind, body) {
9011
9279
  if (kind === "heartbeat") {
9012
- return { controlRequests: [], answeredRequestIds: [], idleSeconds: finiteNumber(parseJsonObject(body), "idle_seconds"), workerStatus: void 0 };
9280
+ return { controlRequests: [], answeredRequestIds: [], idleSeconds: finiteNumber(parseJsonObject(body), "idle_seconds"), workerStatus: void 0, payloads: [] };
9013
9281
  }
9014
9282
  if (kind === "worker-registration") {
9015
- return { controlRequests: [], answeredRequestIds: [], idleSeconds: void 0, workerStatus: nonEmptyString(parseJsonObject(body), "worker_status") };
9283
+ return { controlRequests: [], answeredRequestIds: [], idleSeconds: void 0, workerStatus: nonEmptyString(parseJsonObject(body), "worker_status"), payloads: [] };
9016
9284
  }
9017
9285
  const controlRequests = [];
9018
9286
  const answeredRequestIds = [];
9019
- for (const payload of payloadEventsOf(body)) {
9287
+ const payloads = payloadEventsOf(body);
9288
+ for (const payload of payloads) {
9020
9289
  const pending = pendingOfControlRequestPayload(payload);
9021
9290
  if (pending !== void 0) {
9022
9291
  controlRequests.push({ requestId: pending.requestId, type: pending.type, summary: pending.summary });
@@ -9024,7 +9293,7 @@ function parseRcRequestBody(kind, body) {
9024
9293
  }
9025
9294
  answeredRequestIds.push(...answeredRequestIdsOfControlResponsePayload(payload));
9026
9295
  }
9027
- return { controlRequests, answeredRequestIds, idleSeconds: void 0, workerStatus: void 0 };
9296
+ return { controlRequests, answeredRequestIds, idleSeconds: void 0, workerStatus: void 0, payloads };
9028
9297
  }
9029
9298
  function createRcSessionTracker(deps) {
9030
9299
  const entries = /* @__PURE__ */ new Map();
@@ -9050,7 +9319,7 @@ function createRcSessionTracker(deps) {
9050
9319
  const timer = setInterval(sweep, deps.idleMs);
9051
9320
  timer.unref();
9052
9321
  const birth = (id, facts) => {
9053
- const record = { id, createdAt: deps.now(), lastSeenAt: deps.now(), ...facts, pending: /* @__PURE__ */ new Map(), workerState: void 0, workerIdleSeconds: void 0, sequenceNum: void 0 };
9322
+ const record = { id, createdAt: deps.now(), lastSeenAt: deps.now(), ...facts, pending: /* @__PURE__ */ new Map(), workerState: void 0, workerIdleSeconds: void 0, sequenceNum: void 0, liveTasks: /* @__PURE__ */ new Map() };
9054
9323
  entries.set(id, record);
9055
9324
  return record;
9056
9325
  };
@@ -9061,11 +9330,11 @@ function createRcSessionTracker(deps) {
9061
9330
  };
9062
9331
  const observeExchange = (request4) => {
9063
9332
  const method = (request4.method ?? "").toUpperCase();
9064
- const path38 = new URL(request4.url ?? "/", "http://127.0.0.1").pathname;
9065
- if (!path38.startsWith(RC_SESSIONS_PATH_PREFIX)) {
9333
+ const path39 = new URL(request4.url ?? "/", "http://127.0.0.1").pathname;
9334
+ if (!path39.startsWith(RC_SESSIONS_PATH_PREFIX)) {
9066
9335
  return void 0;
9067
9336
  }
9068
- const tail = path38.slice(RC_SESSIONS_PATH_PREFIX.length);
9337
+ const tail = path39.slice(RC_SESSIONS_PATH_PREFIX.length);
9069
9338
  const facts = {
9070
9339
  oauthAuthorization: oauthAuthorizationOf(request4.headers),
9071
9340
  anthropicVersion: singleHeader(request4.headers, "anthropic-version"),
@@ -9138,6 +9407,9 @@ function createRcSessionTracker(deps) {
9138
9407
  for (const requestId of factsOfBody.answeredRequestIds) {
9139
9408
  entryNow.pending.delete(requestId);
9140
9409
  }
9410
+ for (const payload of factsOfBody.payloads) {
9411
+ entryNow.liveTasks = applyAgentTaskEvent(entryNow.liveTasks, id, payload, now);
9412
+ }
9141
9413
  if (factsOfBody.idleSeconds !== void 0) {
9142
9414
  entryNow.workerIdleSeconds = { value: factsOfBody.idleSeconds, observedAt: now };
9143
9415
  }
@@ -9228,9 +9500,10 @@ function createRcSessionTracker(deps) {
9228
9500
  return;
9229
9501
  }
9230
9502
  entry.sequenceNum = entry.sequenceNum === void 0 || event.sequence_num > entry.sequenceNum ? event.sequence_num : entry.sequenceNum;
9231
- if (!isRecord2(event.payload)) {
9503
+ if (!isRecord3(event.payload)) {
9232
9504
  return;
9233
9505
  }
9506
+ entry.liveTasks = applyAgentTaskEvent(entry.liveTasks, sessionId, event.payload, deps.now());
9234
9507
  const pending = pendingOfControlRequestPayload(event.payload);
9235
9508
  if (pending !== void 0) {
9236
9509
  if (event.source === RC_STREAM_WORKER_SOURCE) {
@@ -9242,6 +9515,10 @@ function createRcSessionTracker(deps) {
9242
9515
  entry.pending.delete(requestId);
9243
9516
  }
9244
9517
  },
9518
+ liveTasksOf: (sessionId) => {
9519
+ sweep();
9520
+ return sortedEntries().filter((entry) => sessionId === void 0 || entry.id === sessionId).flatMap((entry) => [...entry.liveTasks.values()].sort((left, right) => left.observedAt - right.observedAt || (left.taskId < right.taskId ? -1 : 1)));
9521
+ },
9245
9522
  completePending: (sessionId, requestId) => {
9246
9523
  entries.get(sessionId)?.pending.delete(requestId);
9247
9524
  },
@@ -9447,8 +9724,8 @@ var RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
9447
9724
  function isRcReadFileEncoding(value) {
9448
9725
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value);
9449
9726
  }
9450
- function buildRcReadFilePayload(requestId, path38, options) {
9451
- return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path38, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
9727
+ function buildRcReadFilePayload(requestId, path39, options) {
9728
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path39, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
9452
9729
  }
9453
9730
  function buildRcFileSuggestionsPayload(requestId, query) {
9454
9731
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -9550,15 +9827,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
9550
9827
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
9551
9828
  return result.ok ? { ...result, requestId } : result;
9552
9829
  }
9553
- async function readRcSessionFile(deps, sessionId, path38, options) {
9554
- if (path38 === "") {
9830
+ async function readRcSessionFile(deps, sessionId, path39, options) {
9831
+ if (path39 === "") {
9555
9832
  return { ok: false, message: "a read-file write needs a non-empty path: the SDK's own field names the file the worker resolves against the session's cwd, and an empty string names none" };
9556
9833
  }
9557
9834
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
9558
9835
  return { ok: false, message: "a read-file write's max-bytes is a positive whole number of bytes: the SDK's own field caps the read, and a zero or negative cap reads nothing" };
9559
9836
  }
9560
9837
  const requestId = deps.newUuid();
9561
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path38, options), `read ${path38} from session ${sessionId}`);
9838
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path39, options), `read ${path39} from session ${sessionId}`);
9562
9839
  return result.ok ? { ...result, requestId } : result;
9563
9840
  }
9564
9841
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -9727,11 +10004,11 @@ function createRcControlHandler(deps) {
9727
10004
  path: "read-file",
9728
10005
  read: (body) => {
9729
10006
  const session = bodyString(body, "session");
9730
- const path38 = bodyString(body, "path");
10007
+ const path39 = bodyString(body, "path");
9731
10008
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
9732
10009
  const encoding = "encoding" in body && isRcReadFileEncoding(body.encoding) ? body.encoding : void 0;
9733
- const refused2 = session === void 0 || path38 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
9734
- return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path38, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
10010
+ const refused2 = session === void 0 || path39 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
10011
+ return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path39, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
9735
10012
  }
9736
10013
  },
9737
10014
  {
@@ -10041,9 +10318,9 @@ function requestIdOfBody(body) {
10041
10318
  }
10042
10319
  function frontDoorRcControl(transport, token) {
10043
10320
  const headers = { authorization: `Bearer ${token}` };
10044
- const listAnswerOf = async (path38, what) => {
10321
+ const listAnswerOf = async (path39, what) => {
10045
10322
  try {
10046
- return await transport.request({ method: "GET", path: path38, headers });
10323
+ return await transport.request({ method: "GET", path: path39, headers });
10047
10324
  } catch (error) {
10048
10325
  throw new Error(`${what}: could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
10049
10326
  }
@@ -10115,10 +10392,10 @@ function frontDoorRcControl(transport, token) {
10115
10392
  }
10116
10393
  return pending;
10117
10394
  };
10118
- const writeOf = async (path38, body, describeFailure2) => {
10395
+ const writeOf = async (path39, body, describeFailure2) => {
10119
10396
  let answer;
10120
10397
  try {
10121
- answer = await transport.request({ method: "POST", path: path38, headers: { ...headers, "content-type": "application/json" }, body });
10398
+ answer = await transport.request({ method: "POST", path: path39, headers: { ...headers, "content-type": "application/json" }, body });
10122
10399
  } catch (error) {
10123
10400
  return { ok: false, message: `could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}` };
10124
10401
  }
@@ -10149,10 +10426,10 @@ function frontDoorRcControl(transport, token) {
10149
10426
  endSession: async (sessionId, reason) => await writeOf(`${CONTROL_PATH_PREFIX}/end-session`, JSON.stringify({ session: sessionId, ...reason === void 0 ? {} : { reason } }), (status, message) => `ending ${sessionId} failed (HTTP ${String(status)}): ${message}`),
10150
10427
  getUsage: async (sessionId, skipBehaviors) => await writeOf(`${CONTROL_PATH_PREFIX}/get-usage`, JSON.stringify({ session: sessionId, ...skipBehaviors === void 0 ? {} : { skipBehaviors } }), (status, message) => `requesting the usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
10151
10428
  getContextUsage: async (sessionId, detail) => await writeOf(`${CONTROL_PATH_PREFIX}/get-context-usage`, JSON.stringify({ session: sessionId, ...detail === void 0 ? {} : { detail } }), (status, message) => `requesting the context usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
10152
- readFile: async (sessionId, path38, options) => await writeOf(
10429
+ readFile: async (sessionId, path39, options) => await writeOf(
10153
10430
  `${CONTROL_PATH_PREFIX}/read-file`,
10154
- JSON.stringify({ session: sessionId, path: path38, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
10155
- (status, message) => `reading ${path38} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
10431
+ JSON.stringify({ session: sessionId, path: path39, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
10432
+ (status, message) => `reading ${path39} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
10156
10433
  ),
10157
10434
  fileSuggestions: async (sessionId, query) => await writeOf(`${CONTROL_PATH_PREFIX}/file-suggestions`, JSON.stringify({ session: sessionId, query }), (status, message) => `requesting file suggestions from ${sessionId} failed (HTTP ${String(status)}): ${message}`),
10158
10435
  keepAlive: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/keep-alive`, JSON.stringify({ session: sessionId }), (status, message) => `keeping ${sessionId} alive failed (HTTP ${String(status)}): ${message}`),
@@ -10311,12 +10588,12 @@ function tlsFacts(options) {
10311
10588
  }
10312
10589
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
10313
10590
  const agent = new ExemptTlsAgent();
10314
- const post = async (path38, headers, body) => await new Promise((resolve, reject) => {
10591
+ const post = async (path39, headers, body) => await new Promise((resolve, reject) => {
10315
10592
  const options = {
10316
10593
  host: target.host,
10317
10594
  port: target.port,
10318
10595
  method: "POST",
10319
- path: path38,
10596
+ path: path39,
10320
10597
  // The Host header names the host whose API this is, not the address dialled: a redirected test dials a loopback stand-in while still speaking to the API host by name, exactly as the forwarded paths present their SNI.
10321
10598
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
10322
10599
  agent
@@ -10381,12 +10658,12 @@ function lateRcStreamDial(resolve) {
10381
10658
  }
10382
10659
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
10383
10660
  const agent = new ExemptTlsAgent();
10384
- const request4 = async (method, path38, headers, body, signal) => await new Promise((resolve, reject) => {
10661
+ const request4 = async (method, path39, headers, body, signal) => await new Promise((resolve, reject) => {
10385
10662
  const options = {
10386
10663
  host: target.host,
10387
10664
  port: target.port,
10388
10665
  method,
10389
- path: path38,
10666
+ path: path39,
10390
10667
  // The Host header names the host whose API this is, not the address dialled: a redirected test dials a loopback stand-in while still speaking to the API host by name, exactly as the forwarded paths present their SNI.
10391
10668
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
10392
10669
  agent,
@@ -10428,9 +10705,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
10428
10705
  return { status, body: await readAll(response) };
10429
10706
  },
10430
10707
  openStream: async (sessionId, headers, resume, signal) => {
10431
- const path38 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
10708
+ const path39 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
10432
10709
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
10433
- const { status, response } = await request4("GET", path38, streamHeaders, void 0, signal);
10710
+ const { status, response } = await request4("GET", path39, streamHeaders, void 0, signal);
10434
10711
  if (!isSuccessful2(status)) {
10435
10712
  await readAll(response);
10436
10713
  return { status, chunks: NO_CHUNKS };
@@ -10646,11 +10923,11 @@ import path10 from "node:path";
10646
10923
  function isSafeSessionId(sessionId) {
10647
10924
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
10648
10925
  }
10649
- function isRecord3(value) {
10926
+ function isRecord4(value) {
10650
10927
  return typeof value === "object" && value !== null && !Array.isArray(value);
10651
10928
  }
10652
10929
  function credentialOfJson(parsed) {
10653
- if (!isRecord3(parsed)) {
10930
+ if (!isRecord4(parsed)) {
10654
10931
  return void 0;
10655
10932
  }
10656
10933
  const { authorization, anthropicVersion, anthropicClientPlatform } = parsed;
@@ -10680,7 +10957,7 @@ function createRcCredentialStore(fs12, dir) {
10680
10957
  } catch {
10681
10958
  return void 0;
10682
10959
  }
10683
- return isRecord3(parsed) ? parsed : void 0;
10960
+ return isRecord4(parsed) ? parsed : void 0;
10684
10961
  };
10685
10962
  return {
10686
10963
  read: (sessionId) => {
@@ -10734,162 +11011,162 @@ import { Agent as Agent3, fetch as undiciFetch } from "undici";
10734
11011
  init_capability();
10735
11012
 
10736
11013
  // src/frontdoor/rcSchemas.ts
10737
- import { z as z4 } from "zod";
10738
- var RcPermissionModeSchema = z4.enum(RC_PERMISSION_MODES);
10739
- var RcSessionSummarySchema = z4.strictObject({
10740
- id: z4.string(),
10741
- createdAt: z4.number(),
10742
- lastSeenAt: z4.number()
11014
+ import { z as z6 } from "zod";
11015
+ var RcPermissionModeSchema = z6.enum(RC_PERMISSION_MODES);
11016
+ var RcSessionSummarySchema = z6.strictObject({
11017
+ id: z6.string(),
11018
+ createdAt: z6.number(),
11019
+ lastSeenAt: z6.number()
10743
11020
  });
10744
11021
  function workerFactSchema(value) {
10745
- return z4.strictObject({ value, observedAt: z4.number() });
10746
- }
10747
- var RcPendingRequestSummarySchema = z4.strictObject({
10748
- sessionId: z4.string(),
10749
- requestId: z4.string(),
10750
- type: z4.string(),
10751
- summary: z4.string(),
10752
- observedAt: z4.number()
11022
+ return z6.strictObject({ value, observedAt: z6.number() });
11023
+ }
11024
+ var RcPendingRequestSummarySchema = z6.strictObject({
11025
+ sessionId: z6.string(),
11026
+ requestId: z6.string(),
11027
+ type: z6.string(),
11028
+ summary: z6.string(),
11029
+ observedAt: z6.number()
10753
11030
  });
10754
- var RcSessionStatusSchema = z4.strictObject({
11031
+ var RcSessionStatusSchema = z6.strictObject({
10755
11032
  ...RcSessionSummarySchema.shape,
10756
- workerState: workerFactSchema(z4.string()).optional(),
10757
- workerIdleSeconds: workerFactSchema(z4.number()).optional(),
10758
- pending: z4.readonly(z4.array(RcPendingRequestSummarySchema))
11033
+ workerState: workerFactSchema(z6.string()).optional(),
11034
+ workerIdleSeconds: workerFactSchema(z6.number()).optional(),
11035
+ pending: z6.readonly(z6.array(RcPendingRequestSummarySchema))
10759
11036
  });
10760
- var RcStreamEnvelopeSchema = z4.looseObject({
11037
+ var RcStreamEnvelopeSchema = z6.looseObject({
10761
11038
  /** The envelope's own event id, when the host sent one. */
10762
- event_id: z4.string().optional(),
11039
+ event_id: z6.string().optional(),
10763
11040
  /** The envelope's event type, the discriminator a consumer switches on (`control_request`, `user`, and kin). */
10764
- event_type: z4.string(),
11041
+ event_type: z6.string(),
10765
11042
  /** The sequence number the host assigned, the value a resume continues after. */
10766
- sequence_num: z4.int(),
11043
+ sequence_num: z6.int(),
10767
11044
  /** Who emitted the event (`worker` for the CLI's half, a client id for a client's). */
10768
- source: z4.string(),
11045
+ source: z6.string(),
10769
11046
  /** 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. */
10770
- payload: z4.unknown().optional(),
11047
+ payload: z6.unknown().optional(),
10771
11048
  /** 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. */
10772
- created_at: z4.unknown().optional()
11049
+ created_at: z6.unknown().optional()
10773
11050
  });
10774
- var RcStreamEventSchema = z4.strictObject({
10775
- session: z4.string(),
11051
+ var RcStreamEventSchema = z6.strictObject({
11052
+ session: z6.string(),
10776
11053
  envelope: RcStreamEnvelopeSchema
10777
11054
  });
10778
- var RcRateLimitWindowSchema = z4.looseObject({
11055
+ var RcRateLimitWindowSchema = z6.looseObject({
10779
11056
  /** 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). */
10780
- utilization: z4.number().optional(),
11057
+ utilization: z6.number().optional(),
10781
11058
  /** 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. */
10782
- resetsAt: z4.number().optional()
11059
+ resetsAt: z6.number().optional()
10783
11060
  });
10784
- var RcRateLimitInfoSchema = z4.looseObject({
11061
+ var RcRateLimitInfoSchema = z6.looseObject({
10785
11062
  /** The limiting window's own status (`allowed`, `allowed_warning`, `rejected`), asserted only as a string because the vocabulary grows with the CLI. */
10786
- status: z4.string(),
11063
+ status: z6.string(),
10787
11064
  /** When the limiting window resets, in unix epoch seconds. */
10788
- resetsAt: z4.number().optional(),
11065
+ resetsAt: z6.number().optional(),
10789
11066
  /** Which window the top-level fields describe (`five_hour`, `seven_day`, and kin), the payload's own name for it. */
10790
- rateLimitType: z4.string().optional(),
11067
+ rateLimitType: z6.string().optional(),
10791
11068
  /** The fraction of the limiting window used, on the same scale the per-window utilizations carry. */
10792
- utilization: z4.number().optional(),
11069
+ utilization: z6.number().optional(),
10793
11070
  /** Whether usage beyond the plan (extra usage) is currently covering the overflow, the payload's own flag for it. */
10794
- isUsingOverage: z4.boolean().optional(),
11071
+ isUsingOverage: z6.boolean().optional(),
10795
11072
  /** The overage's own status, the same vocabulary the limiting window's `status` carries. */
10796
- overageStatus: z4.string().optional(),
11073
+ overageStatus: z6.string().optional(),
10797
11074
  /** When the overage window resets, in unix epoch seconds. */
10798
- overageResetsAt: z4.number().optional(),
11075
+ overageResetsAt: z6.number().optional(),
10799
11076
  /** 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. */
10800
- unifiedWindows: z4.looseObject({ five_hour: RcRateLimitWindowSchema.optional(), seven_day: RcRateLimitWindowSchema.optional(), seven_day_overage_included: RcRateLimitWindowSchema.optional() }).optional()
11077
+ unifiedWindows: z6.looseObject({ five_hour: RcRateLimitWindowSchema.optional(), seven_day: RcRateLimitWindowSchema.optional(), seven_day_overage_included: RcRateLimitWindowSchema.optional() }).optional()
10801
11078
  });
10802
- var RcLiveRateLimitSchema = z4.strictObject({
10803
- session: z4.string(),
10804
- observedAt: z4.number(),
11079
+ var RcLiveRateLimitSchema = z6.strictObject({
11080
+ session: z6.string(),
11081
+ observedAt: z6.number(),
10805
11082
  rateLimit: RcRateLimitInfoSchema
10806
11083
  });
10807
- var RcSessionQuerySchema = z4.strictObject({
10808
- session: z4.string().min(1).optional()
11084
+ var RcSessionQuerySchema = z6.strictObject({
11085
+ session: z6.string().min(1).optional()
10809
11086
  });
10810
- var RcSendInputSchema = z4.strictObject({
10811
- session: z4.string().min(1),
10812
- text: z4.string().min(1)
11087
+ var RcSendInputSchema = z6.strictObject({
11088
+ session: z6.string().min(1),
11089
+ text: z6.string().min(1)
10813
11090
  });
10814
- var RcAnswerInputSchema = z4.strictObject({
10815
- session: z4.string().min(1),
10816
- request: z4.string().min(1),
10817
- approve: z4.boolean(),
10818
- text: z4.string().optional()
11091
+ var RcAnswerInputSchema = z6.strictObject({
11092
+ session: z6.string().min(1),
11093
+ request: z6.string().min(1),
11094
+ approve: z6.boolean(),
11095
+ text: z6.string().optional()
10819
11096
  }).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" });
10820
- var RcInterruptInputSchema = z4.strictObject({
10821
- session: z4.string().min(1)
11097
+ var RcInterruptInputSchema = z6.strictObject({
11098
+ session: z6.string().min(1)
10822
11099
  });
10823
- var RcSetModelInputSchema = z4.strictObject({
10824
- session: z4.string().min(1),
10825
- model: z4.string().min(1)
11100
+ var RcSetModelInputSchema = z6.strictObject({
11101
+ session: z6.string().min(1),
11102
+ model: z6.string().min(1)
10826
11103
  });
10827
- var RcSetPermissionModeInputSchema = z4.strictObject({
10828
- session: z4.string().min(1),
11104
+ var RcSetPermissionModeInputSchema = z6.strictObject({
11105
+ session: z6.string().min(1),
10829
11106
  mode: RcPermissionModeSchema
10830
11107
  });
10831
- var RcEndSessionInputSchema = z4.strictObject({
10832
- session: z4.string().min(1),
10833
- reason: z4.string().min(1).optional()
11108
+ var RcEndSessionInputSchema = z6.strictObject({
11109
+ session: z6.string().min(1),
11110
+ reason: z6.string().min(1).optional()
10834
11111
  });
10835
- var RcGetUsageInputSchema = z4.strictObject({
10836
- session: z4.string().min(1),
10837
- skipBehaviors: z4.boolean().optional()
11112
+ var RcGetUsageInputSchema = z6.strictObject({
11113
+ session: z6.string().min(1),
11114
+ skipBehaviors: z6.boolean().optional()
10838
11115
  });
10839
- var RcGetContextUsageInputSchema = z4.strictObject({
10840
- session: z4.string().min(1),
10841
- detail: z4.enum(RC_CONTEXT_USAGE_DETAILS).optional()
11116
+ var RcGetContextUsageInputSchema = z6.strictObject({
11117
+ session: z6.string().min(1),
11118
+ detail: z6.enum(RC_CONTEXT_USAGE_DETAILS).optional()
10842
11119
  });
10843
- var RcReadFileInputSchema = z4.strictObject({
10844
- session: z4.string().min(1),
10845
- path: z4.string().min(1),
10846
- maxBytes: z4.number().int().positive().optional(),
10847
- encoding: z4.enum(RC_READ_FILE_ENCODINGS).optional()
11120
+ var RcReadFileInputSchema = z6.strictObject({
11121
+ session: z6.string().min(1),
11122
+ path: z6.string().min(1),
11123
+ maxBytes: z6.number().int().positive().optional(),
11124
+ encoding: z6.enum(RC_READ_FILE_ENCODINGS).optional()
10848
11125
  });
10849
- var RcFileSuggestionsInputSchema = z4.strictObject({
10850
- session: z4.string().min(1),
10851
- query: z4.string()
11126
+ var RcFileSuggestionsInputSchema = z6.strictObject({
11127
+ session: z6.string().min(1),
11128
+ query: z6.string()
10852
11129
  });
10853
- var RcKeepAliveInputSchema = z4.strictObject({
10854
- session: z4.string().min(1)
11130
+ var RcKeepAliveInputSchema = z6.strictObject({
11131
+ session: z6.string().min(1)
10855
11132
  });
10856
- var RcMcpStatusInputSchema = z4.strictObject({
10857
- session: z4.string().min(1)
11133
+ var RcMcpStatusInputSchema = z6.strictObject({
11134
+ session: z6.string().min(1)
10858
11135
  });
10859
- var RcMcpReconnectInputSchema = z4.strictObject({
10860
- session: z4.string().min(1),
10861
- serverName: z4.string().min(1)
11136
+ var RcMcpReconnectInputSchema = z6.strictObject({
11137
+ session: z6.string().min(1),
11138
+ serverName: z6.string().min(1)
10862
11139
  });
10863
- var RcMcpAuthenticateInputSchema = z4.strictObject({
10864
- session: z4.string().min(1),
10865
- serverName: z4.string().min(1),
10866
- redirectUri: z4.string().min(1)
11140
+ var RcMcpAuthenticateInputSchema = z6.strictObject({
11141
+ session: z6.string().min(1),
11142
+ serverName: z6.string().min(1),
11143
+ redirectUri: z6.string().min(1)
10867
11144
  });
10868
- var RcMcpOAuthCallbackUrlInputSchema = z4.strictObject({
10869
- session: z4.string().min(1),
10870
- serverName: z4.string().min(1),
10871
- callbackUrl: z4.string().min(1)
11145
+ var RcMcpOAuthCallbackUrlInputSchema = z6.strictObject({
11146
+ session: z6.string().min(1),
11147
+ serverName: z6.string().min(1),
11148
+ callbackUrl: z6.string().min(1)
10872
11149
  });
10873
- var RcTeleportInputSchema = z4.strictObject({
10874
- session: z4.string().min(1),
10875
- marker: z4.string().min(1)
11150
+ var RcTeleportInputSchema = z6.strictObject({
11151
+ session: z6.string().min(1),
11152
+ marker: z6.string().min(1)
10876
11153
  });
10877
- var RcListOutputSchema = z4.strictObject({ sessions: z4.readonly(z4.array(RcSessionSummarySchema)) });
10878
- var RcStatusOutputSchema = z4.strictObject({ statuses: z4.readonly(z4.array(RcSessionStatusSchema)) });
10879
- var RcPendingOutputSchema = z4.strictObject({ pending: z4.readonly(z4.array(RcPendingRequestSummarySchema)) });
10880
- var RcWriteOutputSchema = z4.strictObject({
10881
- session: z4.string(),
10882
- sequenceNums: z4.readonly(z4.array(z4.number()))
11154
+ var RcListOutputSchema = z6.strictObject({ sessions: z6.readonly(z6.array(RcSessionSummarySchema)) });
11155
+ var RcStatusOutputSchema = z6.strictObject({ statuses: z6.readonly(z6.array(RcSessionStatusSchema)) });
11156
+ var RcPendingOutputSchema = z6.strictObject({ pending: z6.readonly(z6.array(RcPendingRequestSummarySchema)) });
11157
+ var RcWriteOutputSchema = z6.strictObject({
11158
+ session: z6.string(),
11159
+ sequenceNums: z6.readonly(z6.array(z6.number()))
10883
11160
  });
10884
- var RcControlWriteOutputSchema = z4.strictObject({
10885
- session: z4.string(),
10886
- request: z4.string(),
10887
- sequenceNums: z4.readonly(z4.array(z4.number()))
11161
+ var RcControlWriteOutputSchema = z6.strictObject({
11162
+ session: z6.string(),
11163
+ request: z6.string(),
11164
+ sequenceNums: z6.readonly(z6.array(z6.number()))
10888
11165
  });
10889
- var RcAnswerOutputSchema = z4.strictObject({
10890
- session: z4.string(),
10891
- request: z4.string(),
10892
- sequenceNums: z4.readonly(z4.array(z4.number()))
11166
+ var RcAnswerOutputSchema = z6.strictObject({
11167
+ session: z6.string(),
11168
+ request: z6.string(),
11169
+ sequenceNums: z6.readonly(z6.array(z6.number()))
10893
11170
  });
10894
11171
 
10895
11172
  // src/frontdoor/rcApi.ts
@@ -10897,6 +11174,7 @@ var RC_ORPC_PATH_PREFIX = "/__agent-shim/orpc";
10897
11174
  var RC_OPENAPI_DOC_PATH = "/openapi.json";
10898
11175
  var RC_SUBSCRIBER_BUFFER_EVENTS = 100;
10899
11176
  var READ_ONLY_OPERATION_EXTENSION = "x-agent-shim-read-only";
11177
+ var SESSION_HISTORY_TAG = "agent-trees";
10900
11178
  function doorApiBearer(headers) {
10901
11179
  const presented = headers.authorization;
10902
11180
  const bearerPrefix = "bearer ".length;
@@ -11075,48 +11353,48 @@ init_cliError();
11075
11353
  init_package();
11076
11354
 
11077
11355
  // src/codex/appServerSchemas.ts
11078
- import { z as z5 } from "zod";
11356
+ import { z as z7 } from "zod";
11079
11357
  var CODEX_APP_SERVER_GENERATED_AGAINST = "0.160.0";
11080
- var RateLimitWindowSchema = z5.object({
11081
- usedPercent: z5.number(),
11082
- resetsAt: z5.number().nullish(),
11083
- windowDurationMins: z5.number().nullish()
11358
+ var RateLimitWindowSchema = z7.object({
11359
+ usedPercent: z7.number(),
11360
+ resetsAt: z7.number().nullish(),
11361
+ windowDurationMins: z7.number().nullish()
11084
11362
  });
11085
- var RateLimitSnapshotSchema = z5.object({
11086
- limitId: z5.string().nullish(),
11087
- limitName: z5.string().nullish(),
11088
- planType: z5.string().nullish(),
11363
+ var RateLimitSnapshotSchema = z7.object({
11364
+ limitId: z7.string().nullish(),
11365
+ limitName: z7.string().nullish(),
11366
+ planType: z7.string().nullish(),
11089
11367
  primary: RateLimitWindowSchema.nullish(),
11090
11368
  secondary: RateLimitWindowSchema.nullish(),
11091
- rateLimitReachedType: z5.string().nullish(),
11092
- spendControlReached: z5.boolean().nullish()
11369
+ rateLimitReachedType: z7.string().nullish(),
11370
+ spendControlReached: z7.boolean().nullish()
11093
11371
  });
11094
- var RateLimitResetCreditSchema = z5.object({
11095
- id: z5.string(),
11096
- grantedAt: z5.number(),
11097
- expiresAt: z5.number().nullish(),
11098
- resetType: z5.string(),
11099
- status: z5.string(),
11100
- title: z5.string().nullish(),
11101
- description: z5.string().nullish()
11372
+ var RateLimitResetCreditSchema = z7.object({
11373
+ id: z7.string(),
11374
+ grantedAt: z7.number(),
11375
+ expiresAt: z7.number().nullish(),
11376
+ resetType: z7.string(),
11377
+ status: z7.string(),
11378
+ title: z7.string().nullish(),
11379
+ description: z7.string().nullish()
11102
11380
  });
11103
- var CodexAccountSchema = z5.discriminatedUnion("type", [
11104
- z5.object({ type: z5.literal("apiKey") }),
11105
- z5.object({ type: z5.literal("chatgpt"), email: z5.string().nullable(), planType: z5.string() }),
11106
- z5.object({ type: z5.literal("amazonBedrock"), usesCodexManagedCredentials: z5.boolean().default(false) })
11381
+ var CodexAccountSchema = z7.discriminatedUnion("type", [
11382
+ z7.object({ type: z7.literal("apiKey") }),
11383
+ z7.object({ type: z7.literal("chatgpt"), email: z7.string().nullable(), planType: z7.string() }),
11384
+ z7.object({ type: z7.literal("amazonBedrock"), usesCodexManagedCredentials: z7.boolean().default(false) })
11107
11385
  ]);
11108
- var CodexAccountReadSchema = z5.object({
11386
+ var CodexAccountReadSchema = z7.object({
11109
11387
  account: CodexAccountSchema.nullable(),
11110
- requiresOpenaiAuth: z5.boolean()
11388
+ requiresOpenaiAuth: z7.boolean()
11111
11389
  });
11112
- var CodexRateLimitsReadSchema = z5.object({
11390
+ var CodexRateLimitsReadSchema = z7.object({
11113
11391
  rateLimits: RateLimitSnapshotSchema,
11114
- rateLimitsByLimitId: z5.record(z5.string(), RateLimitSnapshotSchema).nullish(),
11115
- rateLimitResetCredits: z5.object({ availableCount: z5.number(), credits: z5.array(RateLimitResetCreditSchema).nullish() }).nullish(),
11116
- accountId: z5.string().nullish(),
11117
- ordinaryUsageAllowed: z5.boolean().nullish()
11392
+ rateLimitsByLimitId: z7.record(z7.string(), RateLimitSnapshotSchema).nullish(),
11393
+ rateLimitResetCredits: z7.object({ availableCount: z7.number(), credits: z7.array(RateLimitResetCreditSchema).nullish() }).nullish(),
11394
+ accountId: z7.string().nullish(),
11395
+ ordinaryUsageAllowed: z7.boolean().nullish()
11118
11396
  });
11119
- var CodexInitializeResultSchema = z5.object({ userAgent: z5.string() });
11397
+ var CodexInitializeResultSchema = z7.object({ userAgent: z7.string() });
11120
11398
 
11121
11399
  // src/codex/appServer.ts
11122
11400
  var CodexAppServerUnavailableError = class extends CliError {
@@ -11311,8 +11589,8 @@ init_cliError();
11311
11589
  init_realPorts();
11312
11590
 
11313
11591
  // src/frontdoor/controlApi.ts
11314
- import { createORPCClient as createORPCClient2, ORPCError as ORPCError6 } from "@orpc/client";
11315
- import { openapi as openapi7 } from "@orpc/openapi";
11592
+ import { createORPCClient as createORPCClient2, ORPCError as ORPCError7 } from "@orpc/client";
11593
+ import { openapi as openapi8 } from "@orpc/openapi";
11316
11594
 
11317
11595
  // src/checkReport.ts
11318
11596
  init_classify();
@@ -11581,19 +11859,19 @@ function writePools(paths, pools) {
11581
11859
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
11582
11860
  }
11583
11861
  function poolCycleOf(pools, name) {
11584
- const walk = (current, path38) => {
11862
+ const walk = (current, path39) => {
11585
11863
  for (const entry of pools[current]?.identities ?? []) {
11586
11864
  const nested = poolNameOf(poolMemberIdentity(entry));
11587
11865
  if (nested === void 0) {
11588
11866
  continue;
11589
11867
  }
11590
11868
  if (nested === name) {
11591
- return [...path38, nested];
11869
+ return [...path39, nested];
11592
11870
  }
11593
- if (path38.includes(nested)) {
11871
+ if (path39.includes(nested)) {
11594
11872
  continue;
11595
11873
  }
11596
- const found = walk(nested, [...path38, nested]);
11874
+ const found = walk(nested, [...path39, nested]);
11597
11875
  if (found !== void 0) {
11598
11876
  return found;
11599
11877
  }
@@ -11704,7 +11982,7 @@ init_providersStore();
11704
11982
  init_projects();
11705
11983
  init_pipeline();
11706
11984
  import path25 from "node:path";
11707
- import { z as z13 } from "zod";
11985
+ import { z as z15 } from "zod";
11708
11986
  var HISTORY_PROJECTS_KEY_PREFIX = "history/projects/";
11709
11987
  function projectFragmentOf(rawKey) {
11710
11988
  return rawKey.startsWith(HISTORY_PROJECTS_KEY_PREFIX) ? rawKey.slice(HISTORY_PROJECTS_KEY_PREFIX.length) : void 0;
@@ -11781,9 +12059,9 @@ function lookupKeychainService(run, farmRoot) {
11781
12059
  note: serviceName === void 0 ? `A Keychain entry was found for account "${farmRoot}" but its service name could not be parsed from security's output.` : `Keychain service name for this identity: "${serviceName}".`
11782
12060
  };
11783
12061
  }
11784
- var SettingsSecretsShapeSchema = z13.looseObject({
11785
- env: z13.record(z13.string(), z13.unknown()).optional(),
11786
- hooks: z13.record(z13.string(), z13.array(z13.unknown())).optional()
12062
+ var SettingsSecretsShapeSchema = z15.looseObject({
12063
+ env: z15.record(z15.string(), z15.unknown()).optional(),
12064
+ hooks: z15.record(z15.string(), z15.array(z15.unknown())).optional()
11787
12065
  });
11788
12066
  function hookCommandCountOf(group) {
11789
12067
  if (typeof group !== "object" || group === null) {
@@ -12079,7 +12357,7 @@ init_schema();
12079
12357
  init_claudeVersion();
12080
12358
  init_identity();
12081
12359
  init_projects();
12082
- import { z as z15 } from "zod";
12360
+ import { z as z17 } from "zod";
12083
12361
 
12084
12362
  // src/resolve/types.ts
12085
12363
  var LAYER_KINDS = [
@@ -12140,123 +12418,123 @@ var DIAGNOSTIC_SEVERITIES = ["error", "warning", "info"];
12140
12418
 
12141
12419
  // src/usage/pickReportSchema.ts
12142
12420
  init_plan2();
12143
- import { z as z14 } from "zod";
12144
- var PoolPickCandidateViewSchema = z14.strictObject({
12145
- identity: z14.string(),
12421
+ import { z as z16 } from "zod";
12422
+ var PoolPickCandidateViewSchema = z16.strictObject({
12423
+ identity: z16.string(),
12146
12424
  /** In pick order: `scored` has usable quota data, `unknown` has none, `pay-per-use` bills by use, `ineligible` is refused right now. */
12147
- class: z14.enum(["scored", "unknown", "pay-per-use", "ineligible"]),
12425
+ class: z16.enum(["scored", "unknown", "pay-per-use", "ineligible"]),
12148
12426
  /** Plan-size-weighted remaining quota per hour until its reset; present for `scored` only. */
12149
- score: z14.number().optional(),
12427
+ score: z16.number().optional(),
12150
12428
  /** 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`. */
12151
- scoreWindow: z14.enum(["sevenDay", "fiveHour"]).optional(),
12429
+ scoreWindow: z16.enum(["sevenDay", "fiveHour"]).optional(),
12152
12430
  /** False when the five-hour window would run dry, at the observed pace, before it resets. */
12153
- feasible: z14.boolean(),
12431
+ feasible: z16.boolean(),
12154
12432
  /** When an `ineligible` member can be used again, as an ISO instant. */
12155
- blockedUntil: z14.iso.datetime().optional(),
12433
+ blockedUntil: z16.iso.datetime().optional(),
12156
12434
  plan: PlanClassSchema,
12157
12435
  /** The facts behind the class and score, in the order they matter. */
12158
- reasons: z14.array(z14.string())
12436
+ reasons: z16.array(z16.string())
12159
12437
  });
12160
- var PoolPickReportSchema = z14.strictObject({
12161
- pool: z14.string(),
12162
- directory: z14.string(),
12438
+ var PoolPickReportSchema = z16.strictObject({
12439
+ pool: z16.string(),
12440
+ directory: z16.string(),
12163
12441
  /** The member a launch would run as, absent when every member is refused. */
12164
- pick: z14.string().optional(),
12165
- candidates: z14.array(PoolPickCandidateViewSchema),
12442
+ pick: z16.string().optional(),
12443
+ candidates: z16.array(PoolPickCandidateViewSchema),
12166
12444
  /** Identity members anywhere in the pool's graph that do not exist; a launch skips them. */
12167
- missing: z14.array(z14.string()),
12445
+ missing: z16.array(z16.string()),
12168
12446
  /** When nothing can be picked, the soonest any member returns. */
12169
- earliestReturn: z14.strictObject({ identity: z14.string(), at: z14.iso.datetime() }).optional(),
12447
+ earliestReturn: z16.strictObject({ identity: z16.string(), at: z16.iso.datetime() }).optional(),
12170
12448
  /** The member a resumed conversation started on but moved off, and why, when the ranking could not keep it. */
12171
- movedOff: z14.strictObject({ identity: z14.string(), reason: z14.string() }).optional(),
12449
+ movedOff: z16.strictObject({ identity: z16.string(), reason: z16.string() }).optional(),
12172
12450
  /** Why the last-pick record could not be read, when that is the case. */
12173
- stickyProblem: z14.string().optional()
12451
+ stickyProblem: z16.string().optional()
12174
12452
  });
12175
12453
 
12176
12454
  // src/checkReportSchema.ts
12177
12455
  var CHECK_CREDENTIAL_APPLIES = ["provider", "identity", "stored-login"];
12178
- var CheckLayerViewSchema = z15.strictObject({
12179
- id: z15.int(),
12180
- kind: z15.enum(LAYER_KINDS),
12181
- source: z15.string()
12456
+ var CheckLayerViewSchema = z17.strictObject({
12457
+ id: z17.int(),
12458
+ kind: z17.enum(LAYER_KINDS),
12459
+ source: z17.string()
12182
12460
  });
12183
- var CheckEntryViewSchema = z15.strictObject({
12184
- path: z15.string(),
12185
- shared: z15.boolean(),
12186
- via: z15.enum(DECISION_VIAS),
12461
+ var CheckEntryViewSchema = z17.strictObject({
12462
+ path: z17.string(),
12463
+ shared: z17.boolean(),
12464
+ via: z17.enum(DECISION_VIAS),
12187
12465
  /** The entry's real category, or null when nothing classifies it. */
12188
- category: z15.enum(CATEGORY_NAMES).nullable(),
12189
- rule: z15.strictObject({ key: z15.string(), layer: z15.int() }).optional(),
12466
+ category: z17.enum(CATEGORY_NAMES).nullable(),
12467
+ rule: z17.strictObject({ key: z17.string(), layer: z17.int() }).optional(),
12190
12468
  /** Rules that matched but whose `when` condition failed, each with the conditions that failed. */
12191
- eliminated: z15.readonly(z15.array(z15.strictObject({ key: z15.string(), failed: z15.readonly(z15.array(z15.string())) }))).optional()
12469
+ eliminated: z17.readonly(z17.array(z17.strictObject({ key: z17.string(), failed: z17.readonly(z17.array(z17.string())) }))).optional()
12192
12470
  });
12193
- var CheckDiagnosticSchema = z15.strictObject({
12194
- code: z15.enum(DIAGNOSTIC_CODES),
12195
- severity: z15.enum(DIAGNOSTIC_SEVERITIES),
12196
- message: z15.string(),
12197
- subject: z15.string().optional(),
12198
- layer: z15.int().optional()
12471
+ var CheckDiagnosticSchema = z17.strictObject({
12472
+ code: z17.enum(DIAGNOSTIC_CODES),
12473
+ severity: z17.enum(DIAGNOSTIC_SEVERITIES),
12474
+ message: z17.string(),
12475
+ subject: z17.string().optional(),
12476
+ layer: z17.int().optional()
12199
12477
  });
12200
- var CheckAmbientCredentialSchema = z15.union([z15.strictObject({ ok: z15.literal(true) }), z15.strictObject({ ok: z15.literal(false), variable: z15.string(), message: z15.string() })]);
12201
- var CheckKeychainSchema = z15.strictObject({
12202
- checked: z15.literal(true),
12203
- found: z15.boolean(),
12204
- serviceName: z15.string().optional(),
12205
- note: z15.string()
12478
+ var CheckAmbientCredentialSchema = z17.union([z17.strictObject({ ok: z17.literal(true) }), z17.strictObject({ ok: z17.literal(false), variable: z17.string(), message: z17.string() })]);
12479
+ var CheckKeychainSchema = z17.strictObject({
12480
+ checked: z17.literal(true),
12481
+ found: z17.boolean(),
12482
+ serviceName: z17.string().optional(),
12483
+ note: z17.string()
12206
12484
  });
12207
- var CheckSettingsExposureSchema = z15.strictObject({
12208
- file: z15.string(),
12209
- envKeyNames: z15.readonly(z15.array(z15.string())),
12210
- hookEventNames: z15.readonly(z15.array(z15.string())),
12211
- hookCommandCount: z15.int().nonnegative()
12485
+ var CheckSettingsExposureSchema = z17.strictObject({
12486
+ file: z17.string(),
12487
+ envKeyNames: z17.readonly(z17.array(z17.string())),
12488
+ hookEventNames: z17.readonly(z17.array(z17.string())),
12489
+ hookCommandCount: z17.int().nonnegative()
12212
12490
  });
12213
- var CredentialSourceSummarySchema = z15.union([
12214
- z15.strictObject({ kind: z15.literal("env"), variable: z15.string() }),
12215
- z15.strictObject({ kind: z15.literal("file"), path: z15.string() }),
12216
- z15.strictObject({ kind: z15.literal("command"), program: z15.string() }),
12217
- z15.strictObject({ kind: z15.literal("op"), reference: z15.string() }),
12218
- z15.strictObject({ kind: z15.literal("keychain"), service: z15.string(), account: z15.string().optional() }),
12219
- z15.strictObject({ kind: z15.literal("literal") })
12491
+ var CredentialSourceSummarySchema = z17.union([
12492
+ z17.strictObject({ kind: z17.literal("env"), variable: z17.string() }),
12493
+ z17.strictObject({ kind: z17.literal("file"), path: z17.string() }),
12494
+ z17.strictObject({ kind: z17.literal("command"), program: z17.string() }),
12495
+ z17.strictObject({ kind: z17.literal("op"), reference: z17.string() }),
12496
+ z17.strictObject({ kind: z17.literal("keychain"), service: z17.string(), account: z17.string().optional() }),
12497
+ z17.strictObject({ kind: z17.literal("literal") })
12220
12498
  ]);
12221
- var CredentialSummarySchema = z15.strictObject({
12222
- target: z15.enum(CREDENTIAL_TARGETS),
12223
- sources: z15.readonly(z15.array(CredentialSourceSummarySchema)),
12499
+ var CredentialSummarySchema = z17.strictObject({
12500
+ target: z17.enum(CREDENTIAL_TARGETS),
12501
+ sources: z17.readonly(z17.array(CredentialSourceSummarySchema)),
12224
12502
  cache: CredentialCacheSchema.optional()
12225
12503
  });
12226
- var CachedCredentialStateSchema = z15.union([
12227
- z15.strictObject({ store: z15.enum(CREDENTIAL_CACHE_STORES), status: z15.literal("empty") }),
12228
- z15.strictObject({ store: z15.enum(CREDENTIAL_CACHE_STORES), status: z15.literal("unreadable"), reason: z15.string() }),
12229
- z15.strictObject({ store: z15.enum(CREDENTIAL_CACHE_STORES), status: z15.enum(["fresh", "expired"]), ageMs: z15.number(), expiresInMs: z15.number().optional() })
12504
+ var CachedCredentialStateSchema = z17.union([
12505
+ z17.strictObject({ store: z17.enum(CREDENTIAL_CACHE_STORES), status: z17.literal("empty") }),
12506
+ z17.strictObject({ store: z17.enum(CREDENTIAL_CACHE_STORES), status: z17.literal("unreadable"), reason: z17.string() }),
12507
+ z17.strictObject({ store: z17.enum(CREDENTIAL_CACHE_STORES), status: z17.enum(["fresh", "expired"]), ageMs: z17.number(), expiresInMs: z17.number().optional() })
12230
12508
  ]);
12231
- var CheckCredentialProviderSchema = z15.union([
12232
- z15.strictObject({ name: z15.string(), credential: CredentialSummarySchema, cached: CachedCredentialStateSchema.optional() }),
12233
- z15.strictObject({ name: z15.string(), problem: z15.string() })
12509
+ var CheckCredentialProviderSchema = z17.union([
12510
+ z17.strictObject({ name: z17.string(), credential: CredentialSummarySchema, cached: CachedCredentialStateSchema.optional() }),
12511
+ z17.strictObject({ name: z17.string(), problem: z17.string() })
12234
12512
  ]);
12235
- var CheckCredentialSchema = z15.strictObject({
12236
- applies: z15.enum(CHECK_CREDENTIAL_APPLIES),
12513
+ var CheckCredentialSchema = z17.strictObject({
12514
+ applies: z17.enum(CHECK_CREDENTIAL_APPLIES),
12237
12515
  provider: CheckCredentialProviderSchema.optional(),
12238
12516
  identity: CredentialSummarySchema.optional(),
12239
12517
  identityCached: CachedCredentialStateSchema.optional()
12240
12518
  });
12241
- var CheckClaudeVersionSchema = z15.strictObject({
12242
- pinned: z15.strictObject({ version: z15.string(), source: z15.enum(CLAUDE_VERSION_SOURCES), installed: z15.boolean() }).optional(),
12243
- highestInstalled: z15.string().optional(),
12244
- installed: z15.readonly(z15.array(z15.string()))
12519
+ var CheckClaudeVersionSchema = z17.strictObject({
12520
+ pinned: z17.strictObject({ version: z17.string(), source: z17.enum(CLAUDE_VERSION_SOURCES), installed: z17.boolean() }).optional(),
12521
+ highestInstalled: z17.string().optional(),
12522
+ installed: z17.readonly(z17.array(z17.string()))
12245
12523
  });
12246
- var CheckReportJsonSchema = z15.strictObject({
12247
- identity: z15.strictObject({ name: z15.string().nullable(), source: z15.enum(IDENTITY_DECISION_SOURCES) }),
12524
+ var CheckReportJsonSchema = z17.strictObject({
12525
+ identity: z17.strictObject({ name: z17.string().nullable(), source: z17.enum(IDENTITY_DECISION_SOURCES) }),
12248
12526
  /** The pool ranking, when the launch named a pool instead of an identity. */
12249
12527
  pool: PoolPickReportSchema.optional(),
12250
- configProfile: z15.strictObject({ name: z15.string().nullable(), source: z15.enum(CONFIG_PROFILE_DECISION_SOURCES) }),
12251
- layers: z15.readonly(z15.array(CheckLayerViewSchema)),
12252
- entries: z15.readonly(z15.array(CheckEntryViewSchema)),
12253
- projectEncodingAmbiguities: z15.readonly(
12254
- z15.array(z15.strictObject({ fragment: z15.string(), encoded: z15.string(), reason: z15.enum(ENCODING_AMBIGUITY_REASONS), detail: z15.string() }))
12528
+ configProfile: z17.strictObject({ name: z17.string().nullable(), source: z17.enum(CONFIG_PROFILE_DECISION_SOURCES) }),
12529
+ layers: z17.readonly(z17.array(CheckLayerViewSchema)),
12530
+ entries: z17.readonly(z17.array(CheckEntryViewSchema)),
12531
+ projectEncodingAmbiguities: z17.readonly(
12532
+ z17.array(z17.strictObject({ fragment: z17.string(), encoded: z17.string(), reason: z17.enum(ENCODING_AMBIGUITY_REASONS), detail: z17.string() }))
12255
12533
  ),
12256
- diagnostics: z15.readonly(z15.array(CheckDiagnosticSchema)),
12534
+ diagnostics: z17.readonly(z17.array(CheckDiagnosticSchema)),
12257
12535
  ambientCredential: CheckAmbientCredentialSchema,
12258
12536
  keychain: CheckKeychainSchema.optional(),
12259
- settingsExposure: z15.readonly(z15.array(CheckSettingsExposureSchema)),
12537
+ settingsExposure: z17.readonly(z17.array(CheckSettingsExposureSchema)),
12260
12538
  credential: CheckCredentialSchema,
12261
12539
  claudeVersion: CheckClaudeVersionSchema.optional()
12262
12540
  });
@@ -12316,28 +12594,28 @@ function collectResets(snapshots, nowMs) {
12316
12594
  }
12317
12595
 
12318
12596
  // src/usage/resetsSchema.ts
12319
- import { z as z16 } from "zod";
12320
- var ResetRowSchema = z16.strictObject({
12321
- identity: z16.string(),
12322
- provider: z16.string(),
12597
+ import { z as z18 } from "zod";
12598
+ var ResetRowSchema = z18.strictObject({
12599
+ identity: z18.string(),
12600
+ provider: z18.string(),
12323
12601
  /** What the window is: `5h`, `7d` or `extra usage` for an Anthropic account, or the provider's own measure and period (`tokens 5h`). */
12324
- window: z16.string(),
12602
+ window: z18.string(),
12325
12603
  /** When the state the window comes from was observed, as an ISO instant. */
12326
- observedAt: z16.iso.datetime(),
12604
+ observedAt: z18.iso.datetime(),
12327
12605
  /** When the window resets, as an ISO instant; absent when the upstream reported none. */
12328
- resetsAt: z16.iso.datetime().optional(),
12606
+ resetsAt: z18.iso.datetime().optional(),
12329
12607
  /** True when the reset time has passed, so the recorded observation describes a window that no longer exists and its utilisation reads as 0. */
12330
- reset: z16.boolean(),
12608
+ reset: z18.boolean(),
12331
12609
  /** The fraction used, as `effectiveWindow` reads it at the report's own clock. */
12332
- utilization: z16.number().optional(),
12610
+ utilization: z18.number().optional(),
12333
12611
  /** The window's own status, for a window that has not reset yet. */
12334
- status: z16.string().optional()
12612
+ status: z18.string().optional()
12335
12613
  });
12336
- var ResetScheduleSchema = z16.strictObject({ resets: z16.readonly(z16.array(ResetRowSchema)) });
12614
+ var ResetScheduleSchema = z18.strictObject({ resets: z18.readonly(z18.array(ResetRowSchema)) });
12337
12615
 
12338
12616
  // src/frontdoor/controlSchemas.ts
12339
12617
  import path30 from "node:path";
12340
- import { z as z21 } from "zod";
12618
+ import { z as z23 } from "zod";
12341
12619
 
12342
12620
  // src/doctorReport.ts
12343
12621
  init_claudeShim();
@@ -12538,24 +12816,24 @@ function credentialsFilePath(farmRoot) {
12538
12816
  }
12539
12817
 
12540
12818
  // src/codex/siwcStore.ts
12541
- import { z as z20 } from "zod";
12819
+ import { z as z22 } from "zod";
12542
12820
 
12543
12821
  // src/codex/auth.ts
12544
- import { z as z18 } from "zod";
12545
- var AuthFileSchema = z18.looseObject({
12546
- tokens: z18.looseObject({
12547
- access_token: z18.string().optional(),
12548
- refresh_token: z18.string().optional(),
12549
- id_token: z18.string().optional(),
12550
- account_id: z18.string().optional()
12822
+ import { z as z20 } from "zod";
12823
+ var AuthFileSchema = z20.looseObject({
12824
+ tokens: z20.looseObject({
12825
+ access_token: z20.string().optional(),
12826
+ refresh_token: z20.string().optional(),
12827
+ id_token: z20.string().optional(),
12828
+ account_id: z20.string().optional()
12551
12829
  }).nullish(),
12552
- last_refresh: z18.string().optional()
12830
+ last_refresh: z20.string().optional()
12553
12831
  });
12554
- var TokenGrantSchema = z18.looseObject({
12555
- access_token: z18.string().min(1).optional(),
12556
- refresh_token: z18.string().min(1).optional(),
12557
- id_token: z18.string().min(1).optional(),
12558
- account_id: z18.string().min(1).optional()
12832
+ var TokenGrantSchema = z20.looseObject({
12833
+ access_token: z20.string().min(1).optional(),
12834
+ refresh_token: z20.string().min(1).optional(),
12835
+ id_token: z20.string().min(1).optional(),
12836
+ account_id: z20.string().min(1).optional()
12559
12837
  });
12560
12838
  var CodexAuthError = class extends Error {
12561
12839
  constructor(message) {
@@ -12565,41 +12843,41 @@ var CodexAuthError = class extends Error {
12565
12843
  };
12566
12844
 
12567
12845
  // src/codex/siwc.ts
12568
- import { z as z19 } from "zod";
12846
+ import { z as z21 } from "zod";
12569
12847
  var SIWC_RESOURCE = "https://api.openai.com/v1";
12570
12848
  var SIWC_RESPONSES_URL = `${SIWC_RESOURCE}/responses`;
12571
12849
  var SIWC_PLAN_SCOPE = "chatgpt.tokens.use.direct";
12572
- var TokenResponseSchema = z19.looseObject({
12573
- access_token: z19.string().min(1),
12574
- refresh_token: z19.string().min(1).optional(),
12575
- id_token: z19.string().min(1).optional(),
12576
- expires_in: z19.number().positive(),
12577
- scope: z19.string().optional()
12850
+ var TokenResponseSchema = z21.looseObject({
12851
+ access_token: z21.string().min(1),
12852
+ refresh_token: z21.string().min(1).optional(),
12853
+ id_token: z21.string().min(1).optional(),
12854
+ expires_in: z21.number().positive(),
12855
+ scope: z21.string().optional()
12578
12856
  });
12579
- var JwtHeaderSchema = z19.looseObject({ alg: z19.string(), kid: z19.string().optional() });
12580
- var IdTokenClaimsSchema = z19.looseObject({
12581
- iss: z19.string(),
12582
- sub: z19.string().min(1),
12583
- aud: z19.union([z19.string(), z19.array(z19.string())]),
12584
- exp: z19.number(),
12585
- nonce: z19.string().optional(),
12586
- email: z19.string().optional()
12857
+ var JwtHeaderSchema = z21.looseObject({ alg: z21.string(), kid: z21.string().optional() });
12858
+ var IdTokenClaimsSchema = z21.looseObject({
12859
+ iss: z21.string(),
12860
+ sub: z21.string().min(1),
12861
+ aud: z21.union([z21.string(), z21.array(z21.string())]),
12862
+ exp: z21.number(),
12863
+ nonce: z21.string().optional(),
12864
+ email: z21.string().optional()
12587
12865
  });
12588
- var JwksSchema = z19.object({ keys: z19.array(z19.looseObject({ kid: z19.string().optional(), kty: z19.string() })) });
12866
+ var JwksSchema = z21.object({ keys: z21.array(z21.looseObject({ kid: z21.string().optional(), kty: z21.string() })) });
12589
12867
 
12590
12868
  // src/codex/siwcStore.ts
12591
- var SiwcGrantSchema = z20.strictObject({
12592
- clientId: z20.string().min(1),
12593
- sub: z20.string().min(1),
12594
- email: z20.string().optional(),
12595
- idToken: z20.string().min(1),
12596
- accessToken: z20.string().min(1),
12597
- refreshToken: z20.string().min(1),
12598
- scopes: z20.array(z20.string()).readonly(),
12869
+ var SiwcGrantSchema = z22.strictObject({
12870
+ clientId: z22.string().min(1),
12871
+ sub: z22.string().min(1),
12872
+ email: z22.string().optional(),
12873
+ idToken: z22.string().min(1),
12874
+ accessToken: z22.string().min(1),
12875
+ refreshToken: z22.string().min(1),
12876
+ scopes: z22.array(z22.string()).readonly(),
12599
12877
  /** When the access token stops working, in milliseconds since the epoch. */
12600
- expiresAt: z20.number()
12878
+ expiresAt: z22.number()
12601
12879
  });
12602
- var SiwcFileSchema = z20.strictObject({ registeredClientId: z20.string().min(1).optional(), grant: SiwcGrantSchema.optional() });
12880
+ var SiwcFileSchema = z22.strictObject({ registeredClientId: z22.string().min(1).optional(), grant: SiwcGrantSchema.optional() });
12603
12881
  function parseSiwcFile(raw, filePath) {
12604
12882
  let json;
12605
12883
  try {
@@ -13296,90 +13574,90 @@ function collectDoctorReport(params) {
13296
13574
  // src/frontdoor/controlSchemas.ts
13297
13575
  init_schema2();
13298
13576
  init_state();
13299
- var UsageListOutputSchema = z21.strictObject({ snapshots: z21.readonly(z21.array(UsageSnapshotSchema)) });
13300
- var UsageWindowsInputSchema = z21.strictObject({
13301
- identity: z21.string().min(1),
13302
- provider: z21.string().min(1).optional()
13577
+ var UsageListOutputSchema = z23.strictObject({ snapshots: z23.readonly(z23.array(UsageSnapshotSchema)) });
13578
+ var UsageWindowsInputSchema = z23.strictObject({
13579
+ identity: z23.string().min(1),
13580
+ provider: z23.string().min(1).optional()
13303
13581
  });
13304
- var EffectiveWindowSchema = z21.strictObject({
13582
+ var EffectiveWindowSchema = z23.strictObject({
13305
13583
  /** True when the window's reset time has passed, so the recorded observation describes a window that no longer exists. */
13306
- reset: z21.boolean(),
13584
+ reset: z23.boolean(),
13307
13585
  /** The fraction used: 0 for a reset window, otherwise what was last observed, absent when none was reported. */
13308
- utilization: z21.number().optional(),
13586
+ utilization: z23.number().optional(),
13309
13587
  /** The reset instant, for a window that has not reset yet and reported one. */
13310
- resetsAtMs: z21.number().optional(),
13588
+ resetsAtMs: z23.number().optional(),
13311
13589
  /** The window's own status, for a window that has not reset yet. */
13312
- status: z21.string().optional()
13590
+ status: z23.string().optional()
13313
13591
  });
13314
- var UsageWindowsOutputSchema = z21.strictObject({
13315
- identity: z21.string(),
13316
- provider: z21.string(),
13592
+ var UsageWindowsOutputSchema = z23.strictObject({
13593
+ identity: z23.string(),
13594
+ provider: z23.string(),
13317
13595
  /** When the rate-limit state the windows come from was observed. */
13318
- observedAt: z21.iso.datetime().optional(),
13596
+ observedAt: z23.iso.datetime().optional(),
13319
13597
  fiveHour: EffectiveWindowSchema.optional(),
13320
13598
  sevenDay: EffectiveWindowSchema.optional()
13321
13599
  });
13322
- var UsageLiveOutputSchema = z21.strictObject({
13600
+ var UsageLiveOutputSchema = z23.strictObject({
13323
13601
  /** 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. */
13324
13602
  latest: RcLiveRateLimitSchema.optional(),
13325
13603
  /** One observation per session whose stream has filed a rate_limit_event this door generation. */
13326
- sessions: z21.readonly(z21.array(RcLiveRateLimitSchema))
13604
+ sessions: z23.readonly(z23.array(RcLiveRateLimitSchema))
13327
13605
  });
13328
- var FrontDoorSessionStatusSchema = z21.strictObject({
13329
- pid: z21.int().positive(),
13330
- startedAt: z21.number(),
13331
- alive: z21.boolean()
13606
+ var FrontDoorSessionStatusSchema = z23.strictObject({
13607
+ pid: z23.int().positive(),
13608
+ startedAt: z23.number(),
13609
+ alive: z23.boolean()
13332
13610
  });
13333
- var HeadroomSocketTargetSchema = z21.union([z21.strictObject({ socketPath: z21.string() }), z21.strictObject({ refused: z21.string() })]);
13334
- var FrontDoorStatusOutputSchema = z21.strictObject({
13611
+ var HeadroomSocketTargetSchema = z23.union([z23.strictObject({ socketPath: z23.string() }), z23.strictObject({ refused: z23.string() })]);
13612
+ var FrontDoorStatusOutputSchema = z23.strictObject({
13335
13613
  state: FrontDoorStateSchema,
13336
- supervisorAlive: z21.boolean(),
13337
- sessions: z21.readonly(z21.array(FrontDoorSessionStatusSchema)),
13614
+ supervisorAlive: z23.boolean(),
13615
+ sessions: z23.readonly(z23.array(FrontDoorSessionStatusSchema)),
13338
13616
  headroomSocket: HeadroomSocketTargetSchema.optional(),
13339
- logPath: z21.string(),
13340
- logExists: z21.boolean()
13617
+ logPath: z23.string(),
13618
+ logExists: z23.boolean()
13341
13619
  });
13342
- var FrontDoorSessionsOutputSchema = z21.strictObject({ sessions: z21.readonly(z21.array(FrontDoorSessionStatusSchema)) });
13343
- var CheckRunInputSchema = z21.strictObject({
13344
- path: z21.string().min(1),
13345
- identity: z21.string().min(1).optional()
13620
+ var FrontDoorSessionsOutputSchema = z23.strictObject({ sessions: z23.readonly(z23.array(FrontDoorSessionStatusSchema)) });
13621
+ var CheckRunInputSchema = z23.strictObject({
13622
+ path: z23.string().min(1),
13623
+ identity: z23.string().min(1).optional()
13346
13624
  }).refine((input) => path30.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
13347
- var PoolPickInputSchema = z21.strictObject({
13348
- pool: z21.string().min(1),
13349
- path: z21.string().min(1)
13625
+ var PoolPickInputSchema = z23.strictObject({
13626
+ pool: z23.string().min(1),
13627
+ path: z23.string().min(1)
13350
13628
  }).refine((input) => path30.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
13351
- var DoctorFindingSchema = z21.strictObject({
13352
- section: z21.enum(DOCTOR_SECTIONS),
13353
- subject: z21.string().optional(),
13354
- severity: z21.enum(DOCTOR_SEVERITIES),
13355
- message: z21.string()
13629
+ var DoctorFindingSchema = z23.strictObject({
13630
+ section: z23.enum(DOCTOR_SECTIONS),
13631
+ subject: z23.string().optional(),
13632
+ severity: z23.enum(DOCTOR_SEVERITIES),
13633
+ message: z23.string()
13356
13634
  });
13357
- var DoctorRunOutputSchema = z21.strictObject({
13635
+ var DoctorRunOutputSchema = z23.strictObject({
13358
13636
  /** False exactly when any finding is a `fail`; a `warn` never fails the report on its own. */
13359
- ok: z21.boolean(),
13360
- findings: z21.readonly(z21.array(DoctorFindingSchema))
13637
+ ok: z23.boolean(),
13638
+ findings: z23.readonly(z23.array(DoctorFindingSchema))
13361
13639
  });
13362
- var FrontDoorRestartOutputSchema = z21.strictObject({
13363
- action: z21.literal("restarting"),
13364
- previousPid: z21.int().positive()
13640
+ var FrontDoorRestartOutputSchema = z23.strictObject({
13641
+ action: z23.literal("restarting"),
13642
+ previousPid: z23.int().positive()
13365
13643
  });
13366
- var UpdateCheckOutputSchema = z21.strictObject({
13367
- current: z21.string(),
13368
- latest: z21.string(),
13369
- action: z21.enum(["current", "available", "updated"])
13644
+ var UpdateCheckOutputSchema = z23.strictObject({
13645
+ current: z23.string(),
13646
+ latest: z23.string(),
13647
+ action: z23.enum(["current", "available", "updated"])
13370
13648
  });
13371
- var CodexSignInSchema = z21.discriminatedUnion("state", [
13372
- z21.strictObject({ state: z21.literal("none") }),
13373
- z21.strictObject({ state: z21.literal("signed-in"), email: z21.string().optional(), planScope: z21.boolean(), accessTokenExpiresAt: z21.number() }),
13374
- z21.strictObject({ state: z21.literal("unreadable"), message: z21.string() })
13649
+ var CodexSignInSchema = z23.discriminatedUnion("state", [
13650
+ z23.strictObject({ state: z23.literal("none") }),
13651
+ z23.strictObject({ state: z23.literal("signed-in"), email: z23.string().optional(), planScope: z23.boolean(), accessTokenExpiresAt: z23.number() }),
13652
+ z23.strictObject({ state: z23.literal("unreadable"), message: z23.string() })
13375
13653
  ]);
13376
- var CodexStatusOutputSchema = z21.strictObject({
13654
+ var CodexStatusOutputSchema = z23.strictObject({
13377
13655
  signIn: CodexSignInSchema,
13378
- codexProviders: z21.readonly(z21.array(z21.string()))
13656
+ codexProviders: z23.readonly(z23.array(z23.string()))
13379
13657
  });
13380
- var CodexLogoutOutputSchema = z21.strictObject({
13381
- hadGrant: z21.boolean(),
13382
- revoked: z21.boolean()
13658
+ var CodexLogoutOutputSchema = z23.strictObject({
13659
+ hadGrant: z23.boolean(),
13660
+ revoked: z23.boolean()
13383
13661
  });
13384
13662
 
13385
13663
  // src/frontdoor/codexApi.ts
@@ -13536,133 +13814,133 @@ init_providersStore();
13536
13814
 
13537
13815
  // src/frontdoor/configSchemas.ts
13538
13816
  init_schema();
13539
- import { z as z22 } from "zod";
13540
- var RemovalConfirmationSchema = z22.boolean();
13541
- var CredentialWriteSchema = (targets) => z22.strictObject({
13542
- sources: z22.array(RemoteCredentialSourceSchema).min(1).optional(),
13543
- target: z22.enum(targets).optional(),
13544
- cache: z22.union([z22.literal(false), CredentialCacheSchema]).optional()
13817
+ import { z as z24 } from "zod";
13818
+ var RemovalConfirmationSchema = z24.boolean();
13819
+ var CredentialWriteSchema = (targets) => z24.strictObject({
13820
+ sources: z24.array(RemoteCredentialSourceSchema).min(1).optional(),
13821
+ target: z24.enum(targets).optional(),
13822
+ cache: z24.union([z24.literal(false), CredentialCacheSchema]).optional()
13545
13823
  });
13546
- var CredentialSummarySchema2 = z22.strictObject({
13547
- target: z22.enum(CREDENTIAL_TARGETS),
13548
- sources: z22.readonly(z22.array(
13549
- z22.discriminatedUnion("kind", [
13550
- z22.strictObject({ kind: z22.literal("env"), variable: z22.string() }),
13551
- z22.strictObject({ kind: z22.literal("file"), path: z22.string() }),
13552
- z22.strictObject({ kind: z22.literal("command"), program: z22.string() }),
13553
- z22.strictObject({ kind: z22.literal("op"), reference: z22.string() }),
13554
- z22.strictObject({ kind: z22.literal("keychain"), service: z22.string(), account: z22.string().optional() }),
13555
- z22.strictObject({ kind: z22.literal("literal") })
13824
+ var CredentialSummarySchema2 = z24.strictObject({
13825
+ target: z24.enum(CREDENTIAL_TARGETS),
13826
+ sources: z24.readonly(z24.array(
13827
+ z24.discriminatedUnion("kind", [
13828
+ z24.strictObject({ kind: z24.literal("env"), variable: z24.string() }),
13829
+ z24.strictObject({ kind: z24.literal("file"), path: z24.string() }),
13830
+ z24.strictObject({ kind: z24.literal("command"), program: z24.string() }),
13831
+ z24.strictObject({ kind: z24.literal("op"), reference: z24.string() }),
13832
+ z24.strictObject({ kind: z24.literal("keychain"), service: z24.string(), account: z24.string().optional() }),
13833
+ z24.strictObject({ kind: z24.literal("literal") })
13556
13834
  ])
13557
13835
  )),
13558
13836
  cache: CredentialCacheSchema.optional()
13559
13837
  });
13560
- var mutationOutput = (kind, action) => z22.strictObject({ action: z22.literal(action), kind: z22.literal(kind), name: z22.string() });
13561
- var storedMutationOutput = (kind, action, value) => z22.strictObject({ action: z22.literal(action), kind: z22.literal(kind), name: z22.string(), value });
13562
- var IdentityValueSchema = z22.strictObject({
13563
- name: z22.string(),
13564
- defaultConfigProfile: z22.string().optional(),
13565
- allowAmbientCredential: z22.boolean(),
13838
+ var mutationOutput = (kind, action) => z24.strictObject({ action: z24.literal(action), kind: z24.literal(kind), name: z24.string() });
13839
+ var storedMutationOutput = (kind, action, value) => z24.strictObject({ action: z24.literal(action), kind: z24.literal(kind), name: z24.string(), value });
13840
+ var IdentityValueSchema = z24.strictObject({
13841
+ name: z24.string(),
13842
+ defaultConfigProfile: z24.string().optional(),
13843
+ allowAmbientCredential: z24.boolean(),
13566
13844
  credential: CredentialSummarySchema2.optional(),
13567
- anchors: z22.array(AnchorSchema).optional()
13845
+ anchors: z24.array(AnchorSchema).optional()
13568
13846
  });
13569
13847
  var ProfileValueSchema = ConfigProfileSchema.omit({ $schema: true });
13570
- var ProviderValueSchema = z22.strictObject({
13571
- name: z22.string(),
13572
- kind: z22.enum(PROVIDER_KINDS),
13573
- displayName: z22.string(),
13574
- baseUrl: z22.string().optional(),
13848
+ var ProviderValueSchema = z24.strictObject({
13849
+ name: z24.string(),
13850
+ kind: z24.enum(PROVIDER_KINDS),
13851
+ displayName: z24.string(),
13852
+ baseUrl: z24.string().optional(),
13575
13853
  codex: CodexProviderConfigSchema.optional(),
13576
13854
  credential: CredentialSummarySchema2,
13577
- env: z22.record(z22.string(), z22.string()).optional()
13855
+ env: z24.record(z24.string(), z24.string()).optional()
13578
13856
  });
13579
- var ConfigNameInputSchema = z22.strictObject({ name: z22.string().min(1) });
13857
+ var ConfigNameInputSchema = z24.strictObject({ name: z24.string().min(1) });
13580
13858
  var ConfigIdentityAddOutputSchema = storedMutationOutput("identity", "created", IdentityValueSchema);
13581
- var ConfigIdentitySetInputSchema = z22.strictObject({
13582
- name: z22.string().min(1),
13583
- defaultConfigProfile: z22.union([z22.string().min(1), z22.literal(false)]).optional(),
13584
- allowAmbientCredential: z22.boolean().optional(),
13585
- credential: z22.union([z22.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
13859
+ var ConfigIdentitySetInputSchema = z24.strictObject({
13860
+ name: z24.string().min(1),
13861
+ defaultConfigProfile: z24.union([z24.string().min(1), z24.literal(false)]).optional(),
13862
+ allowAmbientCredential: z24.boolean().optional(),
13863
+ credential: z24.union([z24.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
13586
13864
  /** `false` removes the anchors; a list replaces them. */
13587
- anchors: z22.union([z22.literal(false), z22.array(AnchorSchema).min(1)]).optional()
13865
+ anchors: z24.union([z24.literal(false), z24.array(AnchorSchema).min(1)]).optional()
13588
13866
  });
13589
13867
  var ConfigIdentitySetOutputSchema = storedMutationOutput("identity", "updated", IdentityValueSchema);
13590
- var ConfigIdentityRemoveInputSchema = z22.strictObject({ name: z22.string().min(1), confirm: RemovalConfirmationSchema });
13868
+ var ConfigIdentityRemoveInputSchema = z24.strictObject({ name: z24.string().min(1), confirm: RemovalConfirmationSchema });
13591
13869
  var ConfigIdentityRemoveOutputSchema = mutationOutput("identity", "removed");
13592
13870
  var ConfigIdentityUseOutputSchema = mutationOutput("identity", "selected");
13593
- var ConfigProfileAddInputSchema = z22.strictObject({
13594
- name: z22.string().min(1),
13595
- extends: z22.array(z22.string().min(1)).optional(),
13596
- description: z22.string().optional()
13871
+ var ConfigProfileAddInputSchema = z24.strictObject({
13872
+ name: z24.string().min(1),
13873
+ extends: z24.array(z24.string().min(1)).optional(),
13874
+ description: z24.string().optional()
13597
13875
  });
13598
13876
  var ConfigProfileAddOutputSchema = storedMutationOutput("profile", "created", ProfileValueSchema);
13599
- var ConfigProfileSetInputSchema = z22.strictObject({
13600
- name: z22.string().min(1),
13601
- category: z22.record(z22.string(), z22.boolean()).optional(),
13602
- entry: z22.record(z22.string(), z22.boolean()).optional(),
13603
- extends: z22.union([z22.array(z22.string().min(1)), z22.literal(false)]).optional(),
13604
- description: z22.union([z22.string(), z22.literal(false)]).optional(),
13605
- launch: z22.strictObject({
13606
- skipPermissions: z22.boolean().optional(),
13607
- remoteControl: z22.boolean().optional(),
13608
- headroom: z22.boolean().optional(),
13609
- trackUsage: z22.boolean().optional(),
13610
- provider: z22.union([z22.string().min(1), z22.literal(false)]).optional(),
13611
- claudeVersion: z22.union([z22.string().min(1), z22.literal(false)]).optional()
13877
+ var ConfigProfileSetInputSchema = z24.strictObject({
13878
+ name: z24.string().min(1),
13879
+ category: z24.record(z24.string(), z24.boolean()).optional(),
13880
+ entry: z24.record(z24.string(), z24.boolean()).optional(),
13881
+ extends: z24.union([z24.array(z24.string().min(1)), z24.literal(false)]).optional(),
13882
+ description: z24.union([z24.string(), z24.literal(false)]).optional(),
13883
+ launch: z24.strictObject({
13884
+ skipPermissions: z24.boolean().optional(),
13885
+ remoteControl: z24.boolean().optional(),
13886
+ headroom: z24.boolean().optional(),
13887
+ trackUsage: z24.boolean().optional(),
13888
+ provider: z24.union([z24.string().min(1), z24.literal(false)]).optional(),
13889
+ claudeVersion: z24.union([z24.string().min(1), z24.literal(false)]).optional()
13612
13890
  }).optional()
13613
13891
  });
13614
13892
  var ConfigProfileSetOutputSchema = storedMutationOutput("profile", "updated", ProfileValueSchema);
13615
- var ConfigProfileRemoveInputSchema = z22.strictObject({ name: z22.string().min(1), confirm: RemovalConfirmationSchema });
13893
+ var ConfigProfileRemoveInputSchema = z24.strictObject({ name: z24.string().min(1), confirm: RemovalConfirmationSchema });
13616
13894
  var ConfigProfileRemoveOutputSchema = mutationOutput("profile", "removed");
13617
13895
  var ConfigProfileUseOutputSchema = mutationOutput("profile", "selected");
13618
- var PoolMembersInputSchema = z22.array(z22.string().min(1)).min(1);
13619
- var ConfigPoolAddInputSchema = z22.strictObject({
13620
- name: z22.string().min(1),
13896
+ var PoolMembersInputSchema = z24.array(z24.string().min(1)).min(1);
13897
+ var ConfigPoolAddInputSchema = z24.strictObject({
13898
+ name: z24.string().min(1),
13621
13899
  identities: PoolMembersInputSchema,
13622
- preference: z22.enum(POOL_PREFERENCES).optional()
13900
+ preference: z24.enum(POOL_PREFERENCES).optional()
13623
13901
  });
13624
13902
  var ConfigPoolAddOutputSchema = storedMutationOutput("pool", "created", PoolSchema);
13625
- var ConfigPoolSetInputSchema = z22.strictObject({
13626
- name: z22.string().min(1),
13903
+ var ConfigPoolSetInputSchema = z24.strictObject({
13904
+ name: z24.string().min(1),
13627
13905
  identities: PoolMembersInputSchema.optional(),
13628
- preference: z22.union([z22.enum(POOL_PREFERENCES), z22.literal(false)]).optional()
13906
+ preference: z24.union([z24.enum(POOL_PREFERENCES), z24.literal(false)]).optional()
13629
13907
  });
13630
13908
  var ConfigPoolSetOutputSchema = storedMutationOutput("pool", "updated", PoolSchema);
13631
- var ConfigPoolRemoveInputSchema = z22.strictObject({ name: z22.string().min(1), confirm: RemovalConfirmationSchema });
13909
+ var ConfigPoolRemoveInputSchema = z24.strictObject({ name: z24.string().min(1), confirm: RemovalConfirmationSchema });
13632
13910
  var ConfigPoolRemoveOutputSchema = mutationOutput("pool", "removed");
13633
13911
  var ConfigPoolUseOutputSchema = mutationOutput("pool", "selected");
13634
- var ConfigProviderAddInputSchema = z22.strictObject({
13635
- name: z22.string().min(1),
13636
- kind: z22.enum(PROVIDER_KINDS).optional(),
13637
- displayName: z22.string().min(1),
13638
- baseUrl: z22.string().min(1).optional(),
13912
+ var ConfigProviderAddInputSchema = z24.strictObject({
13913
+ name: z24.string().min(1),
13914
+ kind: z24.enum(PROVIDER_KINDS).optional(),
13915
+ displayName: z24.string().min(1),
13916
+ baseUrl: z24.string().min(1).optional(),
13639
13917
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).required({ sources: true }),
13640
13918
  codex: CodexProviderConfigSchema.optional()
13641
13919
  });
13642
13920
  var ConfigProviderAddOutputSchema = storedMutationOutput("provider", "created", ProviderValueSchema);
13643
- var ConfigProviderSetInputSchema = z22.strictObject({
13644
- name: z22.string().min(1),
13645
- displayName: z22.string().min(1).optional(),
13646
- baseUrl: z22.string().min(1).optional(),
13921
+ var ConfigProviderSetInputSchema = z24.strictObject({
13922
+ name: z24.string().min(1),
13923
+ displayName: z24.string().min(1).optional(),
13924
+ baseUrl: z24.string().min(1).optional(),
13647
13925
  credential: CredentialWriteSchema(PROVIDER_CREDENTIAL_TARGETS).optional(),
13648
13926
  codex: CodexProviderConfigSchema.optional()
13649
13927
  });
13650
13928
  var ConfigProviderSetOutputSchema = storedMutationOutput("provider", "updated", ProviderValueSchema);
13651
- var ConfigProviderRemoveInputSchema = z22.strictObject({ name: z22.string().min(1), confirm: RemovalConfirmationSchema });
13929
+ var ConfigProviderRemoveInputSchema = z24.strictObject({ name: z24.string().min(1), confirm: RemovalConfirmationSchema });
13652
13930
  var ConfigProviderRemoveOutputSchema = mutationOutput("provider", "removed");
13653
- var ConfigRuleAddInputSchema = z22.strictObject({
13654
- path: z22.string().min(1),
13655
- configProfile: z22.string().min(1).optional(),
13656
- identity: z22.string().min(1).optional()
13931
+ var ConfigRuleAddInputSchema = z24.strictObject({
13932
+ path: z24.string().min(1),
13933
+ configProfile: z24.string().min(1).optional(),
13934
+ identity: z24.string().min(1).optional()
13657
13935
  });
13658
13936
  var ConfigRuleAddOutputSchema = storedMutationOutput("rule", "created", DirectoryRuleSchema);
13659
- var ConfigRuleSetInputSchema = z22.strictObject({
13660
- path: z22.string().min(1),
13661
- configProfile: z22.union([z22.string().min(1), z22.literal(false)]).optional(),
13662
- identity: z22.union([z22.string().min(1), z22.literal(false)]).optional()
13937
+ var ConfigRuleSetInputSchema = z24.strictObject({
13938
+ path: z24.string().min(1),
13939
+ configProfile: z24.union([z24.string().min(1), z24.literal(false)]).optional(),
13940
+ identity: z24.union([z24.string().min(1), z24.literal(false)]).optional()
13663
13941
  });
13664
13942
  var ConfigRuleSetOutputSchema = storedMutationOutput("rule", "updated", DirectoryRuleSchema);
13665
- var ConfigRuleRemoveInputSchema = z22.strictObject({ path: z22.string().min(1), confirm: RemovalConfirmationSchema });
13943
+ var ConfigRuleRemoveInputSchema = z24.strictObject({ path: z24.string().min(1), confirm: RemovalConfirmationSchema });
13666
13944
  var ConfigRuleRemoveOutputSchema = mutationOutput("rule", "removed");
13667
13945
 
13668
13946
  // src/frontdoor/configApi.ts
@@ -13727,7 +14005,7 @@ function profileValue(name, paths) {
13727
14005
  function createConfigApiRouter(deps) {
13728
14006
  const authed = doorApiAuth(deps.expectedToken);
13729
14007
  const { paths } = deps;
13730
- const route = (path38, summary) => authed.meta(openapi3({ method: "POST", path: path38, summary, tags: [CONFIG_API_TAG] }));
14008
+ const route = (path39, summary) => authed.meta(openapi3({ method: "POST", path: path39, summary, tags: [CONFIG_API_TAG] }));
13731
14009
  return {
13732
14010
  config: {
13733
14011
  identity: {
@@ -13972,43 +14250,43 @@ import { openapi as openapi4 } from "@orpc/openapi";
13972
14250
  import { eventIterator as eventIterator2, withEventMeta as withEventMeta2 } from "@orpc/server";
13973
14251
 
13974
14252
  // src/frontdoor/eventSchemas.ts
13975
- import { z as z23 } from "zod";
14253
+ import { z as z25 } from "zod";
13976
14254
  var DOOR_EVENT_SOURCE_RC = "rc";
13977
14255
  var LAUNCH_EVENT_SOURCE = "launch";
13978
14256
  var USAGE_EVENT_SOURCE = "usage";
13979
14257
  var DOOR_HEALTH_EVENT_SOURCE = "door";
13980
14258
  var QUOTA_EXPIRING_EVENT_SOURCE = "quota-expiring";
13981
- var DoorEventSchema = z23.strictObject({
13982
- source: z23.string().min(1),
14259
+ var DoorEventSchema = z25.strictObject({
14260
+ source: z25.string().min(1),
13983
14261
  /** A positive integer because the backbone's counters start at one and only ever increase. */
13984
- sequence: z23.number().int().positive(),
13985
- payload: z23.unknown()
14262
+ sequence: z25.number().int().positive(),
14263
+ payload: z25.unknown()
13986
14264
  });
13987
- var DoorEventSourceQuerySchema = z23.strictObject({
13988
- sources: z23.array(z23.string().min(1)).min(1).optional()
14265
+ var DoorEventSourceQuerySchema = z25.strictObject({
14266
+ sources: z25.array(z25.string().min(1)).min(1).optional()
13989
14267
  });
13990
- var LaunchLifecycleEventSchema = z23.strictObject({
13991
- kind: z23.enum(["registered", "pruned", "ended"]),
13992
- pid: z23.number().int().positive(),
13993
- startedAt: z23.number(),
13994
- observedAt: z23.number()
14268
+ var LaunchLifecycleEventSchema = z25.strictObject({
14269
+ kind: z25.enum(["registered", "pruned", "ended"]),
14270
+ pid: z25.number().int().positive(),
14271
+ startedAt: z25.number(),
14272
+ observedAt: z25.number()
13995
14273
  });
13996
- var DoorHealthEventSchema = z23.discriminatedUnion("kind", [
13997
- z23.strictObject({ kind: z23.literal("generation"), pid: z23.number().int().positive(), providerPort: z23.number().int().positive(), connectPort: z23.number().int().positive(), directPort: z23.number().int().positive(), observedAt: z23.number() }),
13998
- z23.strictObject({ kind: z23.literal("listenerFailed"), pid: z23.number().int().positive(), listener: z23.enum(["provider", "connect", "direct"]), message: z23.string(), observedAt: z23.number() }),
13999
- z23.strictObject({ kind: z23.literal("binaryTurnover"), pid: z23.number().int().positive(), observedAt: z23.number() }),
14000
- z23.strictObject({ kind: z23.literal("idleShutdown"), pid: z23.number().int().positive(), observedAt: z23.number() }),
14001
- z23.strictObject({ kind: z23.literal("superseded"), pid: z23.number().int().positive(), ownerPid: z23.number().int().positive(), observedAt: z23.number() }),
14002
- z23.strictObject({ kind: z23.literal("drained"), pid: z23.number().int().positive(), observedAt: z23.number() })
14274
+ var DoorHealthEventSchema = z25.discriminatedUnion("kind", [
14275
+ z25.strictObject({ kind: z25.literal("generation"), pid: z25.number().int().positive(), providerPort: z25.number().int().positive(), connectPort: z25.number().int().positive(), directPort: z25.number().int().positive(), observedAt: z25.number() }),
14276
+ z25.strictObject({ kind: z25.literal("listenerFailed"), pid: z25.number().int().positive(), listener: z25.enum(["provider", "connect", "direct"]), message: z25.string(), observedAt: z25.number() }),
14277
+ z25.strictObject({ kind: z25.literal("binaryTurnover"), pid: z25.number().int().positive(), observedAt: z25.number() }),
14278
+ z25.strictObject({ kind: z25.literal("idleShutdown"), pid: z25.number().int().positive(), observedAt: z25.number() }),
14279
+ z25.strictObject({ kind: z25.literal("superseded"), pid: z25.number().int().positive(), ownerPid: z25.number().int().positive(), observedAt: z25.number() }),
14280
+ z25.strictObject({ kind: z25.literal("drained"), pid: z25.number().int().positive(), observedAt: z25.number() })
14003
14281
  ]);
14004
- var QuotaExpiringEventSchema = z23.strictObject({
14005
- identity: z23.string().min(1),
14006
- provider: z23.string().min(1),
14007
- window: z23.enum(["fiveHour", "sevenDay"]),
14282
+ var QuotaExpiringEventSchema = z25.strictObject({
14283
+ identity: z25.string().min(1),
14284
+ provider: z25.string().min(1),
14285
+ window: z25.enum(["fiveHour", "sevenDay"]),
14008
14286
  /** 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. */
14009
- utilization: z23.number().min(0).max(1),
14010
- resetsAt: z23.iso.datetime(),
14011
- observedAt: z23.number()
14287
+ utilization: z25.number().min(0).max(1),
14288
+ resetsAt: z25.iso.datetime(),
14289
+ observedAt: z25.number()
14012
14290
  });
14013
14291
 
14014
14292
  // src/frontdoor/eventsApi.ts
@@ -14092,51 +14370,51 @@ import { openapi as openapi6 } from "@orpc/openapi";
14092
14370
 
14093
14371
  // src/frontdoor/launchSchemas.ts
14094
14372
  import path31 from "node:path";
14095
- import { z as z24 } from "zod";
14373
+ import { z as z26 } from "zod";
14096
14374
  init_claudeVersion();
14097
14375
  init_identity();
14098
- var LaunchResolveInputSchema = z24.strictObject({
14099
- path: z24.string().min(1),
14376
+ var LaunchResolveInputSchema = z26.strictObject({
14377
+ path: z26.string().min(1),
14100
14378
  /** `@name`, launch flags, then the arguments for `claude`; empty for a bare launch. */
14101
- argv: z24.readonly(z24.array(z24.string())).optional(),
14379
+ argv: z26.readonly(z26.array(z26.string())).optional(),
14102
14380
  /** 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. */
14103
- env: z24.record(z24.string(), z24.string()).optional()
14381
+ env: z26.record(z26.string(), z26.string()).optional()
14104
14382
  }).refine((input) => path31.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
14105
- var LaunchPoolDecisionSchema = z24.strictObject({
14106
- name: z24.string(),
14107
- reasons: z24.readonly(z24.array(z24.string())),
14108
- movedOff: z24.strictObject({ identity: z24.string(), reason: z24.string() }).optional()
14383
+ var LaunchPoolDecisionSchema = z26.strictObject({
14384
+ name: z26.string(),
14385
+ reasons: z26.readonly(z26.array(z26.string())),
14386
+ movedOff: z26.strictObject({ identity: z26.string(), reason: z26.string() }).optional()
14109
14387
  });
14110
- var LaunchDecisionSchema = z24.strictObject({
14111
- identity: z24.string().optional(),
14112
- identitySource: z24.enum(IDENTITY_DECISION_SOURCES),
14388
+ var LaunchDecisionSchema = z26.strictObject({
14389
+ identity: z26.string().optional(),
14390
+ identitySource: z26.enum(IDENTITY_DECISION_SOURCES),
14113
14391
  pool: LaunchPoolDecisionSchema.optional(),
14114
- configDirEscapeHatch: z24.boolean(),
14115
- configDir: z24.string().optional(),
14116
- configProfile: z24.string().optional(),
14117
- configProfileSource: z24.enum(CONFIG_PROFILE_DECISION_SOURCES),
14118
- provider: z24.string().optional()
14392
+ configDirEscapeHatch: z26.boolean(),
14393
+ configDir: z26.string().optional(),
14394
+ configProfile: z26.string().optional(),
14395
+ configProfileSource: z26.enum(CONFIG_PROFILE_DECISION_SOURCES),
14396
+ provider: z26.string().optional()
14119
14397
  });
14120
- var LaunchFlagsSchema = z24.strictObject({
14121
- skipPermissions: z24.boolean(),
14122
- remoteControl: z24.boolean(),
14123
- headroom: z24.boolean(),
14124
- trackUsage: z24.boolean()
14398
+ var LaunchFlagsSchema = z26.strictObject({
14399
+ skipPermissions: z26.boolean(),
14400
+ remoteControl: z26.boolean(),
14401
+ headroom: z26.boolean(),
14402
+ trackUsage: z26.boolean()
14125
14403
  });
14126
- var LaunchResolveOutputSchema = z24.strictObject({
14404
+ var LaunchResolveOutputSchema = z26.strictObject({
14127
14405
  decision: LaunchDecisionSchema,
14128
14406
  flags: LaunchFlagsSchema,
14129
- claudeVersion: z24.strictObject({ version: z24.string(), source: z24.enum(CLAUDE_VERSION_SOURCES) }).optional(),
14407
+ claudeVersion: z26.strictObject({ version: z26.string(), source: z26.enum(CLAUDE_VERSION_SOURCES) }).optional(),
14130
14408
  /** The real `claude` binary the launch would spawn, on the door's host. */
14131
- bin: z24.string(),
14409
+ bin: z26.string(),
14132
14410
  /** The arguments the launch would pass it: the tool's own flags, then `CLAUDE_EXTRA_FLAGS`, then the caller's own. */
14133
- args: z24.readonly(z24.array(z24.string())),
14411
+ args: z26.readonly(z26.array(z26.string())),
14134
14412
  /** The credential the launch would authenticate with, by target and source kinds. Absent when none applies. */
14135
- credential: z24.strictObject({ subject: z24.enum(["provider", "identity"]), name: z24.string(), summary: CredentialSummarySchema }).optional(),
14136
- routing: z24.strictObject({ frontDoor: z24.boolean(), headroom: z24.boolean() }),
14413
+ credential: z26.strictObject({ subject: z26.enum(["provider", "identity"]), name: z26.string(), summary: CredentialSummarySchema }).optional(),
14414
+ routing: z26.strictObject({ frontDoor: z26.boolean(), headroom: z26.boolean() }),
14137
14415
  /** The names of the environment variables the launch would set or unset, sorted. Values are not reported. */
14138
- environment: z24.readonly(z24.array(z24.string())),
14139
- warnings: z24.readonly(z24.array(z24.string()))
14416
+ environment: z26.readonly(z26.array(z26.string())),
14417
+ warnings: z26.readonly(z26.array(z26.string()))
14140
14418
  });
14141
14419
 
14142
14420
  // src/frontdoor/launchApi.ts
@@ -14169,6 +14447,71 @@ function createLaunchApiRouter(deps) {
14169
14447
  };
14170
14448
  }
14171
14449
 
14450
+ // src/frontdoor/agentTreesApi.ts
14451
+ import { ORPCError as ORPCError6 } from "@orpc/client";
14452
+ import { openapi as openapi7 } from "@orpc/openapi";
14453
+ import { z as z27 } from "zod";
14454
+ init_cliError();
14455
+ var AgentTreesListInputSchema = z27.strictObject({
14456
+ /** Only this identity's sessions. */
14457
+ identity: z27.string().optional(),
14458
+ /** Include sessions that spawned no agent and ran no workflow. */
14459
+ all: z27.boolean().optional()
14460
+ });
14461
+ var AgentTreesListOutputSchema = z27.array(SessionSummarySchema);
14462
+ var AgentTreesShowInputSchema = z27.strictObject({
14463
+ /** A session id, or an unambiguous prefix of one. */
14464
+ session: z27.string().min(1),
14465
+ /** Look only in this identity. */
14466
+ identity: z27.string().optional()
14467
+ });
14468
+ var AgentTreesShowOutputSchema = z27.strictObject({ identities: z27.array(z27.string()), ...MergedAgentTreeSchema.shape });
14469
+ function asBadRequest(error) {
14470
+ if (error instanceof CliError) {
14471
+ throw new ORPCError6("BAD_REQUEST", { message: error.message });
14472
+ }
14473
+ throw error;
14474
+ }
14475
+ function createAgentTreesApiRouter(deps) {
14476
+ const authed = doorApiAuth(deps.expectedToken);
14477
+ return {
14478
+ agentTrees: {
14479
+ list: authed.meta(
14480
+ openapi7({
14481
+ method: "POST",
14482
+ path: "/rest/agent-trees/list",
14483
+ summary: "List the sessions that spawned agents or ran workflows, newest transcript first",
14484
+ tags: [SESSION_HISTORY_TAG],
14485
+ // A POST because the filters are a body, but the answer changes nothing.
14486
+ spec: (current) => ({ ...current, [READ_ONLY_OPERATION_EXTENSION]: true })
14487
+ })
14488
+ ).input(AgentTreesListInputSchema).output(AgentTreesListOutputSchema).handler(({ input }) => {
14489
+ try {
14490
+ return deps.sessionList(input).map((session) => ({ ...session, identities: [...session.identities] }));
14491
+ } catch (error) {
14492
+ return asBadRequest(error);
14493
+ }
14494
+ }),
14495
+ show: authed.meta(
14496
+ openapi7({
14497
+ method: "POST",
14498
+ path: "/rest/agent-trees/show",
14499
+ summary: "Show one session's agent tree, task list and workflow runs, with the live Remote Control tasks merged in",
14500
+ tags: [SESSION_HISTORY_TAG],
14501
+ spec: (current) => ({ ...current, [READ_ONLY_OPERATION_EXTENSION]: true })
14502
+ })
14503
+ ).input(AgentTreesShowInputSchema).output(AgentTreesShowOutputSchema).handler(({ input }) => {
14504
+ try {
14505
+ const view = deps.sessionShow(input.session, input.identity);
14506
+ return { identities: [...view.identities], ...mergeLiveTasks(view.tree, deps.liveTasks()) };
14507
+ } catch (error) {
14508
+ return asBadRequest(error);
14509
+ }
14510
+ })
14511
+ }
14512
+ };
14513
+ }
14514
+
14172
14515
  // src/frontdoor/controlApi.ts
14173
14516
  var USAGE_API_TAG = "usage";
14174
14517
  var FRONTDOOR_API_TAG2 = "frontdoor";
@@ -14179,12 +14522,12 @@ function createControlApiRouter(deps) {
14179
14522
  const authed = doorApiAuth(deps.expectedToken);
14180
14523
  return {
14181
14524
  usage: {
14182
- list: authed.meta(openapi7({ method: "GET", path: "/rest/usage/snapshots", summary: "List every identity's usage snapshot", tags: [USAGE_API_TAG] })).output(UsageListOutputSchema).handler(() => ({ snapshots: deps.usageSnapshots() })),
14183
- resets: authed.meta(openapi7({ method: "GET", path: "/rest/usage/resets", summary: "List every recorded quota window with when it resets", tags: [USAGE_API_TAG] })).output(ResetScheduleSchema).handler(() => collectResets(deps.usageSnapshots(), deps.now())),
14184
- effectiveWindow: authed.meta(openapi7({ method: "GET", path: "/rest/usage/windows", summary: "Read one identity's effective quota windows", tags: [USAGE_API_TAG] })).input(UsageWindowsInputSchema).output(UsageWindowsOutputSchema).handler(({ input }) => {
14525
+ list: authed.meta(openapi8({ method: "GET", path: "/rest/usage/snapshots", summary: "List every identity's usage snapshot", tags: [USAGE_API_TAG] })).output(UsageListOutputSchema).handler(() => ({ snapshots: deps.usageSnapshots() })),
14526
+ resets: authed.meta(openapi8({ method: "GET", path: "/rest/usage/resets", summary: "List every recorded quota window with when it resets", tags: [USAGE_API_TAG] })).output(ResetScheduleSchema).handler(() => collectResets(deps.usageSnapshots(), deps.now())),
14527
+ effectiveWindow: authed.meta(openapi8({ method: "GET", path: "/rest/usage/windows", summary: "Read one identity's effective quota windows", tags: [USAGE_API_TAG] })).input(UsageWindowsInputSchema).output(UsageWindowsOutputSchema).handler(({ input }) => {
14185
14528
  const snapshot = deps.usageSnapshotOf(input.identity);
14186
14529
  if (snapshot === void 0) {
14187
- throw new ORPCError6("NOT_FOUND", { message: `identity ${input.identity} has no usage snapshot yet, so no quota window has been observed for it` });
14530
+ throw new ORPCError7("NOT_FOUND", { message: `identity ${input.identity} has no usage snapshot yet, so no quota window has been observed for it` });
14188
14531
  }
14189
14532
  const provider = input.provider ?? ANTHROPIC_PROVIDER;
14190
14533
  const rateLimit = snapshot.providers[provider]?.rateLimit;
@@ -14198,34 +14541,34 @@ function createControlApiRouter(deps) {
14198
14541
  ...unified?.sevenDay === void 0 ? {} : { sevenDay: effectiveWindow(unified.sevenDay, now) }
14199
14542
  };
14200
14543
  }),
14201
- live: authed.meta(openapi7({ method: "GET", path: "/rest/usage/live", summary: "Read the live rate-limit observations the event backbone files", tags: [USAGE_API_TAG] })).input(RcSessionQuerySchema).output(UsageLiveOutputSchema).handler(({ input }) => {
14544
+ live: authed.meta(openapi8({ method: "GET", path: "/rest/usage/live", summary: "Read the live rate-limit observations the event backbone files", tags: [USAGE_API_TAG] })).input(RcSessionQuerySchema).output(UsageLiveOutputSchema).handler(({ input }) => {
14202
14545
  const sessions = deps.liveRateLimits(input.session);
14203
14546
  if (input.session !== void 0 && sessions.length === 0) {
14204
14547
  if (deps.list().some((session) => session.id === input.session)) {
14205
- throw new ORPCError6("NOT_FOUND", { message: `session ${input.session} has filed no rate_limit_event on its stream yet: the worker emits one only once a turn has completed, so retry after this session's next turn` });
14548
+ throw new ORPCError7("NOT_FOUND", { message: `session ${input.session} has filed no rate_limit_event on its stream yet: the worker emits one only once a turn has completed, so retry after this session's next turn` });
14206
14549
  }
14207
- throw new ORPCError6("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
14550
+ throw new ORPCError7("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
14208
14551
  }
14209
14552
  return { latest: deps.latestRateLimit(), sessions };
14210
14553
  })
14211
14554
  },
14212
14555
  frontdoor: {
14213
- status: authed.meta(openapi7({ method: "GET", path: "/rest/frontdoor/status", summary: "Read the front door's status", tags: [FRONTDOOR_API_TAG2] })).output(FrontDoorStatusOutputSchema).handler(() => deps.frontDoorStatus()),
14214
- sessions: authed.meta(openapi7({ method: "GET", path: "/rest/frontdoor/sessions", summary: "Read the front door's session registry", tags: [FRONTDOOR_API_TAG2] })).output(FrontDoorSessionsOutputSchema).handler(() => ({ sessions: deps.frontDoorStatus().sessions }))
14556
+ status: authed.meta(openapi8({ method: "GET", path: "/rest/frontdoor/status", summary: "Read the front door's status", tags: [FRONTDOOR_API_TAG2] })).output(FrontDoorStatusOutputSchema).handler(() => deps.frontDoorStatus()),
14557
+ sessions: authed.meta(openapi8({ method: "GET", path: "/rest/frontdoor/sessions", summary: "Read the front door's session registry", tags: [FRONTDOOR_API_TAG2] })).output(FrontDoorSessionsOutputSchema).handler(() => ({ sessions: deps.frontDoorStatus().sessions }))
14215
14558
  },
14216
14559
  check: {
14217
14560
  // The report's own JSON shape is the contract (the same one `check --json` prints and `checkReportSchema.ts` defines), so the procedure returns exactly that conversion.
14218
- run: authed.meta(openapi7({ method: "GET", path: "/rest/check", summary: "Run the check report for one directory", tags: [CHECK_API_TAG] })).input(CheckRunInputSchema).output(CheckReportJsonSchema).handler(({ input }) => checkReportToJson(deps.checkReport(input.path, input.identity)))
14561
+ run: authed.meta(openapi8({ method: "GET", path: "/rest/check", summary: "Run the check report for one directory", tags: [CHECK_API_TAG] })).input(CheckRunInputSchema).output(CheckReportJsonSchema).handler(({ input }) => checkReportToJson(deps.checkReport(input.path, input.identity)))
14219
14562
  },
14220
14563
  doctor: {
14221
- run: authed.meta(openapi7({ method: "GET", path: "/rest/doctor", summary: "Run the doctor report", tags: [DOCTOR_API_TAG] })).output(DoctorRunOutputSchema).handler(() => deps.doctorReport())
14564
+ run: authed.meta(openapi8({ method: "GET", path: "/rest/doctor", summary: "Run the doctor report", tags: [DOCTOR_API_TAG] })).output(DoctorRunOutputSchema).handler(() => deps.doctorReport())
14222
14565
  },
14223
14566
  pool: {
14224
- pick: authed.meta(openapi7({ method: "GET", path: "/rest/pool/pick", summary: "Rank one pool exactly as a launch from a directory would right now", tags: [POOL_API_TAG] })).input(PoolPickInputSchema).output(PoolPickReportSchema).handler(({ input }) => {
14567
+ pick: authed.meta(openapi8({ method: "GET", path: "/rest/pool/pick", summary: "Rank one pool exactly as a launch from a directory would right now", tags: [POOL_API_TAG] })).input(PoolPickInputSchema).output(PoolPickReportSchema).handler(({ input }) => {
14225
14568
  const report = deps.poolPick(input.pool, input.path);
14226
14569
  if (report === void 0) {
14227
14570
  const live = deps.poolNames();
14228
- throw new ORPCError6("NOT_FOUND", {
14571
+ throw new ORPCError7("NOT_FOUND", {
14229
14572
  message: live.length === 0 ? `no pools are configured, so none is named ${input.pool}` : `no pool is named ${input.pool}; the live pools are ${live.map((name) => `"${name}"`).join(", ")}`
14230
14573
  });
14231
14574
  }
@@ -14237,7 +14580,7 @@ function createControlApiRouter(deps) {
14237
14580
  function createDoorApiRouter(deps) {
14238
14581
  const control = createControlApiRouter(deps);
14239
14582
  const lifecycle = createLifecycleApiRouter(deps);
14240
- return { ...createRcApiRouter(deps), ...control, ...lifecycle, ...createConfigApiRouter(deps), ...createCodexApiRouter(deps), ...createLaunchApiRouter(deps), ...createEventsApiRouter(deps), frontdoor: { ...control.frontdoor, ...lifecycle.frontdoor } };
14583
+ return { ...createRcApiRouter(deps), ...control, ...lifecycle, ...createConfigApiRouter(deps), ...createCodexApiRouter(deps), ...createLaunchApiRouter(deps), ...createAgentTreesApiRouter(deps), ...createEventsApiRouter(deps), frontdoor: { ...control.frontdoor, ...lifecycle.frontdoor } };
14241
14584
  }
14242
14585
  function createDoorApiNodeHandler(deps) {
14243
14586
  return doorApiNodeHandlerOf(createDoorApiRouter(deps), deps.expectedToken);
@@ -14568,15 +14911,15 @@ function createQuotaExpiringPublisher(hub, deps) {
14568
14911
 
14569
14912
  // src/frontdoor/rcLiveUsage.ts
14570
14913
  var RC_RATE_LIMIT_EVENT_TYPE = "rate_limit_event";
14571
- function isRecord5(value) {
14914
+ function isRecord6(value) {
14572
14915
  return typeof value === "object" && value !== null && !Array.isArray(value);
14573
14916
  }
14574
14917
  function rcRateLimitInfoOf(event) {
14575
14918
  const payload = event.envelope.payload;
14576
- if (!isRecord5(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
14919
+ if (!isRecord6(payload) || payload.type !== RC_RATE_LIMIT_EVENT_TYPE) {
14577
14920
  return void 0;
14578
14921
  }
14579
- if (!isRecord5(payload.rate_limit_info)) {
14922
+ if (!isRecord6(payload.rate_limit_info)) {
14580
14923
  return void 0;
14581
14924
  }
14582
14925
  const parsed = RcRateLimitInfoSchema.safeParse(payload.rate_limit_info);
@@ -14664,7 +15007,7 @@ function createSseParser() {
14664
15007
  }
14665
15008
  };
14666
15009
  }
14667
- function isRecord6(value) {
15010
+ function isRecord7(value) {
14668
15011
  return typeof value === "object" && value !== null && !Array.isArray(value);
14669
15012
  }
14670
15013
  function sequenceNumOf(value) {
@@ -14686,7 +15029,7 @@ function parseRcStreamEnvelope(parsed) {
14686
15029
  } catch {
14687
15030
  return void 0;
14688
15031
  }
14689
- if (!isRecord6(data)) {
15032
+ if (!isRecord7(data)) {
14690
15033
  return void 0;
14691
15034
  }
14692
15035
  const eventType = data.event_type;
@@ -14927,7 +15270,7 @@ init_capability();
14927
15270
  // src/frontdoor/rcSelfHostEndpoints.ts
14928
15271
  var RC_SOURCE_WORKER = "worker";
14929
15272
  var RC_SOURCE_CLIENT = "client";
14930
- function isRecord7(value) {
15273
+ function isRecord8(value) {
14931
15274
  return typeof value === "object" && value !== null && !Array.isArray(value);
14932
15275
  }
14933
15276
  function parseJsonObject2(body) {
@@ -14937,7 +15280,7 @@ function parseJsonObject2(body) {
14937
15280
  } catch {
14938
15281
  return void 0;
14939
15282
  }
14940
- return isRecord7(parsed) ? parsed : void 0;
15283
+ return isRecord8(parsed) ? parsed : void 0;
14941
15284
  }
14942
15285
  function nonEmptyString2(record, field) {
14943
15286
  const value = record === void 0 ? void 0 : record[field];
@@ -15011,7 +15354,7 @@ async function serveRcClientChannels(ctx, tail, method, maxBatchEvents) {
15011
15354
  }
15012
15355
  const results = [];
15013
15356
  for (const event of events) {
15014
- if (!isRecord7(event) || !isRecord7(event.payload)) {
15357
+ if (!isRecord8(event) || !isRecord8(event.payload)) {
15015
15358
  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" } });
15016
15359
  return true;
15017
15360
  }
@@ -15111,7 +15454,7 @@ async function serveRcCompatSessions(ctx, pathname, compatPath) {
15111
15454
  // src/frontdoor/rcSelfHostConversations.ts
15112
15455
  var RC_CONVERSATIONS_PATH_PREFIX = "/v1/code/conversations";
15113
15456
  var RC_CONVERSATION_ID_PREFIX = "conv_";
15114
- function isRecord8(value) {
15457
+ function isRecord9(value) {
15115
15458
  return typeof value === "object" && value !== null && !Array.isArray(value);
15116
15459
  }
15117
15460
  function parseJsonObject3(body) {
@@ -15121,7 +15464,7 @@ function parseJsonObject3(body) {
15121
15464
  } catch {
15122
15465
  return void 0;
15123
15466
  }
15124
- return isRecord8(parsed) ? parsed : void 0;
15467
+ return isRecord9(parsed) ? parsed : void 0;
15125
15468
  }
15126
15469
  function nonEmptyString3(record, field) {
15127
15470
  const value = record === void 0 ? void 0 : record[field];
@@ -15175,7 +15518,7 @@ async function serveRcConversations(ctx, pathname, method) {
15175
15518
  }
15176
15519
  const results = [];
15177
15520
  for (const event of events) {
15178
- if (!isRecord8(event) || !isRecord8(event.payload)) {
15521
+ if (!isRecord9(event) || !isRecord9(event.payload)) {
15179
15522
  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" } });
15180
15523
  return;
15181
15524
  }
@@ -15207,7 +15550,7 @@ var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:
15207
15550
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
15208
15551
  var MS_PER_SECOND5 = 1e3;
15209
15552
  var HTTP_SERVICE_UNAVAILABLE = 503;
15210
- function isRecord9(value) {
15553
+ function isRecord10(value) {
15211
15554
  return typeof value === "object" && value !== null && !Array.isArray(value);
15212
15555
  }
15213
15556
  function parseJsonObject4(body) {
@@ -15217,7 +15560,7 @@ function parseJsonObject4(body) {
15217
15560
  } catch {
15218
15561
  return void 0;
15219
15562
  }
15220
- return isRecord9(parsed) ? parsed : void 0;
15563
+ return isRecord10(parsed) ? parsed : void 0;
15221
15564
  }
15222
15565
  function growthBookFeatures() {
15223
15566
  return {
@@ -15571,7 +15914,7 @@ var RC_SELF_HOST_WORKER_EPOCH = 1;
15571
15914
  var RC_STREAM_EVENT_NAME2 = "client_event";
15572
15915
  var CONFLICT_REASON_HEADER2 = "x-ccr-conflict-reason";
15573
15916
  var CONFLICT_REASON_EPOCH_STALE = "epoch_stale";
15574
- function isRecord10(value) {
15917
+ function isRecord11(value) {
15575
15918
  return typeof value === "object" && value !== null && !Array.isArray(value);
15576
15919
  }
15577
15920
  function isWebSearchRefusal(value) {
@@ -15655,7 +15998,7 @@ function parseJsonObject5(body) {
15655
15998
  } catch {
15656
15999
  return void 0;
15657
16000
  }
15658
- return isRecord10(parsed) ? parsed : void 0;
16001
+ return isRecord11(parsed) ? parsed : void 0;
15659
16002
  }
15660
16003
  function mintWorkerJwt(randomToken, issuedAt) {
15661
16004
  const encode = (value) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
@@ -15915,7 +16258,7 @@ data: ${JSON.stringify(envelope)}
15915
16258
  if (status !== void 0) {
15916
16259
  session.workerStatus = status;
15917
16260
  }
15918
- if (isRecord10(body?.external_metadata)) {
16261
+ if (isRecord11(body?.external_metadata)) {
15919
16262
  session.externalMetadata = body.external_metadata;
15920
16263
  }
15921
16264
  await answerJson2(response, HTTP_STATUS.ok, {});
@@ -15945,7 +16288,7 @@ data: ${JSON.stringify(envelope)}
15945
16288
  }
15946
16289
  const results = [];
15947
16290
  for (const event of events) {
15948
- if (!isRecord10(event) || !isRecord10(event.payload)) {
16291
+ if (!isRecord11(event) || !isRecord11(event.payload)) {
15949
16292
  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" } });
15950
16293
  return;
15951
16294
  }
@@ -15978,7 +16321,7 @@ data: ${JSON.stringify(envelope)}
15978
16321
  return;
15979
16322
  }
15980
16323
  for (const event of events) {
15981
- if (isRecord10(event)) {
16324
+ if (isRecord11(event)) {
15982
16325
  session.internalEvents.push({ eventId: deps.newUuid(), body: event });
15983
16326
  }
15984
16327
  }
@@ -16074,7 +16417,7 @@ data: ${JSON.stringify(envelope)}
16074
16417
  }
16075
16418
  const results = [];
16076
16419
  for (const event of events) {
16077
- if (!isRecord10(event) || !isRecord10(event.payload)) {
16420
+ if (!isRecord11(event) || !isRecord11(event.payload)) {
16078
16421
  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" } });
16079
16422
  return;
16080
16423
  }
@@ -16211,7 +16554,7 @@ var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
16211
16554
  var RC_SELF_HOST_RECORD_FILE = "credential.json";
16212
16555
  var SELF_HOST_EMAIL = "selfhost@agent-shim.invalid";
16213
16556
  var SELF_HOST_SUBSCRIPTION_TYPE = "max";
16214
- function isRecord11(value) {
16557
+ function isRecord12(value) {
16215
16558
  return typeof value === "object" && value !== null && !Array.isArray(value);
16216
16559
  }
16217
16560
  function readJsonObject(fs12, file) {
@@ -16225,7 +16568,7 @@ function readJsonObject(fs12, file) {
16225
16568
  } catch {
16226
16569
  return void 0;
16227
16570
  }
16228
- return isRecord11(parsed) ? parsed : void 0;
16571
+ return isRecord12(parsed) ? parsed : void 0;
16229
16572
  }
16230
16573
  function readRcSelfHostRecord(fs12, frontdoorDir) {
16231
16574
  const parsed = readJsonObject(fs12, path32.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
@@ -16249,7 +16592,7 @@ function mintRcSelfHostCredential(deps) {
16249
16592
  const recordFile = path32.join(recordDir, RC_SELF_HOST_RECORD_FILE);
16250
16593
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
16251
16594
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
16252
- const existingOauth = isRecord11(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
16595
+ const existingOauth = isRecord12(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
16253
16596
  const existingToken = typeof existingOauth?.accessToken === "string" && existingOauth.accessToken !== "" ? existingOauth.accessToken : void 0;
16254
16597
  const existingIsOwn = existingToken !== void 0 && previousRecord?.accessToken === existingToken;
16255
16598
  if (existingToken !== void 0 && !existingIsOwn && !deps.force) {
@@ -16266,7 +16609,7 @@ function mintRcSelfHostCredential(deps) {
16266
16609
  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)}
16267
16610
  `);
16268
16611
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
16269
- const existingBlock = (value) => isRecord11(value) ? value : {};
16612
+ const existingBlock = (value) => isRecord12(value) ? value : {};
16270
16613
  deps.fs.writeFilePrivate(claudeJsonFile, `${JSON.stringify({
16271
16614
  ...claudeJson,
16272
16615
  oauthAccount: {
@@ -16305,90 +16648,7 @@ init_poolPick();
16305
16648
 
16306
16649
  // src/agents/read.ts
16307
16650
  import path33 from "node:path";
16308
- import { z as z26 } from "zod";
16309
-
16310
- // src/agents/schema.ts
16311
- import { z as z25 } from "zod";
16312
- var AgentMetaSchema = z25.looseObject({
16313
- agentType: z25.string(),
16314
- isFork: z25.boolean().optional(),
16315
- description: z25.string().optional(),
16316
- name: z25.string().optional(),
16317
- toolUseId: z25.string().optional(),
16318
- spawnDepth: z25.number().int().nonnegative().optional(),
16319
- parentAgentId: z25.string().optional(),
16320
- model: z25.string().optional(),
16321
- requestShape: z25.string().optional(),
16322
- requestNonInteractive: z25.boolean().optional(),
16323
- workflowPhase: z25.string().optional(),
16324
- taskKind: z25.string().optional(),
16325
- teamName: z25.string().optional(),
16326
- worktreePath: z25.string().optional(),
16327
- worktreeBranch: z25.string().optional(),
16328
- stoppedByUser: z25.boolean().optional()
16329
- });
16330
- var AgentKindSchema = z25.enum(["subagent", "fork", "workflow-agent", "teammate"]);
16331
- var AgentNodeSchema = z25.lazy(
16332
- () => z25.strictObject({
16333
- id: z25.string(),
16334
- kind: AgentKindSchema,
16335
- agentType: z25.string(),
16336
- description: z25.string().optional(),
16337
- name: z25.string().optional(),
16338
- toolUseId: z25.string().optional(),
16339
- spawnDepth: z25.number().int().nonnegative().optional(),
16340
- model: z25.string().optional(),
16341
- background: z25.boolean().optional(),
16342
- workflowRunId: z25.string().optional(),
16343
- workflowPhase: z25.string().optional(),
16344
- teamName: z25.string().optional(),
16345
- stoppedByUser: z25.boolean().optional(),
16346
- transcript: z25.string(),
16347
- children: z25.array(AgentNodeSchema)
16348
- })
16349
- );
16350
- var TaskItemSchema = z25.strictObject({
16351
- id: z25.string(),
16352
- subject: z25.string(),
16353
- description: z25.string().optional(),
16354
- status: z25.string(),
16355
- /** What a spinner shows while the task runs. */
16356
- activeForm: z25.string().optional(),
16357
- /** The teammate or agent name the task is assigned to, as Agent Teams writes it. */
16358
- owner: z25.string().optional(),
16359
- /** Free-form data the harness attaches to a task, kept as written. */
16360
- metadata: z25.record(z25.string(), z25.unknown()).optional(),
16361
- blocks: z25.array(z25.string()),
16362
- blockedBy: z25.array(z25.string()),
16363
- /** The id of the shared task list this task belongs to (a team's name, or a custom list id), absent for the session's own list. */
16364
- taskList: z25.string().optional()
16365
- });
16366
- var WorkflowRunSchema = z25.strictObject({
16367
- runId: z25.string(),
16368
- workflowName: z25.string().optional(),
16369
- status: z25.string().optional(),
16370
- startTime: z25.number().optional(),
16371
- phases: z25.array(z25.string()),
16372
- summary: z25.string().optional()
16373
- });
16374
- var AgentTreeProblemSchema = z25.strictObject({
16375
- /** Relative to the identity's configuration directory. */
16376
- path: z25.string(),
16377
- reason: z25.string()
16378
- });
16379
- var SessionAgentTreeSchema = z25.strictObject({
16380
- project: z25.string(),
16381
- sessionId: z25.string(),
16382
- /** True for a session directory a resume superseded (`<session-id>.superseded-<epoch-ms>`). */
16383
- superseded: z25.boolean(),
16384
- /** The agents the session itself spawned, each with its descendants. */
16385
- agents: z25.array(AgentNodeSchema),
16386
- tasks: z25.array(TaskItemSchema),
16387
- workflowRuns: z25.array(WorkflowRunSchema),
16388
- problems: z25.array(AgentTreeProblemSchema)
16389
- });
16390
-
16391
- // src/agents/read.ts
16651
+ import { z as z28 } from "zod";
16392
16652
  var PROJECTS_DIR = "projects";
16393
16653
  var TASKS_DIR = "tasks";
16394
16654
  var SUBAGENTS_DIR = "subagents";
@@ -16507,15 +16767,30 @@ function parseJson2(text) {
16507
16767
  return void 0;
16508
16768
  }
16509
16769
  }
16510
- var TaskFileSchema = z26.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z26.array(z26.string()).default([]), blockedBy: z26.array(z26.string()).default([]) });
16511
- var WorkflowRunFileSchema = z26.object({
16512
- runId: z26.string(),
16513
- workflowName: z26.string().optional(),
16514
- status: z26.string().optional(),
16515
- startTime: z26.number().optional(),
16516
- phases: z26.array(z26.object({ title: z26.string() })).default([]),
16517
- summary: z26.string().optional()
16770
+ var TaskFileSchema = z28.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z28.array(z28.string()).default([]), blockedBy: z28.array(z28.string()).default([]) });
16771
+ var WorkflowRunFileSchema = z28.object({
16772
+ runId: z28.string(),
16773
+ workflowName: z28.string().optional(),
16774
+ status: z28.string().optional(),
16775
+ startTime: z28.number().optional(),
16776
+ phases: z28.array(z28.object({ title: z28.string() })).default([]),
16777
+ summary: z28.string().optional()
16518
16778
  });
16779
+ function summariseSession(fs12, configDir, ref) {
16780
+ const sessionRelative = path33.join(PROJECTS_DIR, ref.project, ref.entry);
16781
+ const subagentsRelative = path33.join(sessionRelative, SUBAGENTS_DIR);
16782
+ const workflowsUnderSubagents = path33.join(subagentsRelative, WORKFLOWS_DIR);
16783
+ const isMeta = (name) => name.startsWith(AGENT_FILE_PREFIX) && name.endsWith(META_SUFFIX);
16784
+ let agentCount = fs12.readdir(path33.join(configDir, subagentsRelative)).filter(isMeta).length;
16785
+ for (const runDir of fs12.readdir(path33.join(configDir, workflowsUnderSubagents))) {
16786
+ if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
16787
+ agentCount += fs12.readdir(path33.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
16788
+ }
16789
+ }
16790
+ const workflowRunCount = fs12.readdir(path33.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
16791
+ const transcript = fs12.lstat(path33.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
16792
+ return { ...ref, agentCount, workflowRunCount, ...transcript === void 0 ? {} : { updatedAt: new Date(transcript.mtimeMs).toISOString() } };
16793
+ }
16519
16794
  function readSessionAgentTree(fs12, configDir, ref, options = {}) {
16520
16795
  const problems = [];
16521
16796
  const report = (problem) => {
@@ -16671,6 +16946,94 @@ function readWorkflowRuns(fs12, configDir, relativeDir, report) {
16671
16946
  return runs;
16672
16947
  }
16673
16948
 
16949
+ // src/agents/sessions.ts
16950
+ init_cliError();
16951
+ import path34 from "node:path";
16952
+ var SessionLookupError = class extends CliError {
16953
+ constructor(message) {
16954
+ super(message);
16955
+ this.name = "SessionLookupError";
16956
+ }
16957
+ };
16958
+ function identityConfigDir(identitiesDir, identity) {
16959
+ return path34.join(identitiesDir, identity);
16960
+ }
16961
+ function historyStores(fs12, identitiesDir, identities) {
16962
+ const byRealPath = /* @__PURE__ */ new Map();
16963
+ for (const identity of identities) {
16964
+ const configDir = identityConfigDir(identitiesDir, identity);
16965
+ const real = fs12.realpath(path34.join(configDir, "projects"));
16966
+ if (real === void 0) {
16967
+ continue;
16968
+ }
16969
+ const store = byRealPath.get(real);
16970
+ if (store === void 0) {
16971
+ byRealPath.set(real, { configDir, identities: [identity] });
16972
+ } else {
16973
+ store.identities.push(identity);
16974
+ }
16975
+ }
16976
+ return [...byRealPath.values()];
16977
+ }
16978
+ function collectSessionList(fs12, identitiesDir, identities, filters) {
16979
+ const names = filters.identity === void 0 ? identities : identities.filter((name) => name === filters.identity);
16980
+ if (filters.identity !== void 0 && names.length === 0) {
16981
+ throw new SessionLookupError(`no identity named "${filters.identity}"`);
16982
+ }
16983
+ const sessions = [];
16984
+ for (const store of historyStores(fs12, identitiesDir, names)) {
16985
+ for (const ref of listSessions2(fs12, store.configDir)) {
16986
+ const summary = summariseSession(fs12, store.configDir, ref);
16987
+ if (filters.all === true || summary.agentCount > 0 || summary.workflowRunCount > 0) {
16988
+ sessions.push({ ...summary, identities: store.identities });
16989
+ }
16990
+ }
16991
+ }
16992
+ return sessions.sort((left, right) => (right.updatedAt ?? "").localeCompare(left.updatedAt ?? "") || left.sessionId.localeCompare(right.sessionId));
16993
+ }
16994
+ function locateSession(fs12, identitiesDir, identities, query, onlyIdentity) {
16995
+ const names = onlyIdentity === void 0 ? identities : identities.filter((name) => name === onlyIdentity);
16996
+ if (onlyIdentity !== void 0 && names.length === 0) {
16997
+ throw new SessionLookupError(`no identity named "${onlyIdentity}"`);
16998
+ }
16999
+ const matches = [];
17000
+ for (const store of historyStores(fs12, identitiesDir, names)) {
17001
+ for (const ref of listSessions2(fs12, store.configDir)) {
17002
+ if (ref.sessionId.startsWith(query)) {
17003
+ matches.push({ identities: store.identities, configDir: store.configDir, ref });
17004
+ }
17005
+ }
17006
+ }
17007
+ const exact = matches.filter((match) => match.ref.sessionId === query);
17008
+ const candidates = exact.length > 0 ? exact : matches;
17009
+ const only = candidates[0];
17010
+ if (candidates.length === 1 && only !== void 0) {
17011
+ return only;
17012
+ }
17013
+ if (candidates.length === 0) {
17014
+ throw new SessionLookupError(`no session matches "${query}"`);
17015
+ }
17016
+ throw new SessionLookupError(`"${query}" matches ${String(candidates.length)} sessions: ${candidates.map((match) => `${match.ref.sessionId} (${match.identities.join(", ")})`).join("; ")}; give more of the id or pass --identity`);
17017
+ }
17018
+ function showSession(fs12, identitiesDir, identities, query, onlyIdentity) {
17019
+ const located = locateSession(fs12, identitiesDir, identities, query, onlyIdentity);
17020
+ return { identities: located.identities, tree: readSessionAgentTree(fs12, located.configDir, located.ref) };
17021
+ }
17022
+
17023
+ // src/agents/realFs.ts
17024
+ init_realPorts();
17025
+ import nodeFs from "node:fs";
17026
+ var realSessionFs = {
17027
+ ...realFarmFs,
17028
+ realpath: (candidate) => {
17029
+ try {
17030
+ return nodeFs.realpathSync(candidate);
17031
+ } catch {
17032
+ return void 0;
17033
+ }
17034
+ }
17035
+ };
17036
+
16674
17037
  // src/index.ts
16675
17038
  init_conditions();
16676
17039
  init_ensure();
@@ -16782,6 +17145,10 @@ export {
16782
17145
  AgentKindSchema,
16783
17146
  AgentMetaSchema,
16784
17147
  AgentNodeSchema,
17148
+ AgentTreesListInputSchema,
17149
+ AgentTreesListOutputSchema,
17150
+ AgentTreesShowInputSchema,
17151
+ AgentTreesShowOutputSchema,
16785
17152
  CHECK_CREDENTIAL_APPLIES,
16786
17153
  CODEX_APP_SERVER_GENERATED_AGAINST,
16787
17154
  CODEX_APP_SERVER_TIMEOUT_MS,
@@ -16877,11 +17244,15 @@ export {
16877
17244
  InvalidIdentityNameError,
16878
17245
  InvalidProviderNameError,
16879
17246
  LAUNCH_EVENT_SOURCE,
17247
+ LIVE_TASK_CAP,
16880
17248
  LaunchLifecycleEventSchema,
16881
17249
  LaunchRefusedError,
16882
17250
  LaunchResolveInputSchema,
16883
17251
  LaunchResolveOutputSchema,
16884
17252
  LegacyProviderFileError,
17253
+ LiveTaskSchema,
17254
+ MergedAgentNodeSchema,
17255
+ MergedAgentTreeSchema,
16885
17256
  OWN_CLI_FILE_NAME,
16886
17257
  PROMPT_CACHE_TTL_MS,
16887
17258
  PlanClassSchema,
@@ -16929,6 +17300,8 @@ export {
16929
17300
  ResetRowSchema,
16930
17301
  ResetScheduleSchema,
16931
17302
  SessionAgentTreeSchema,
17303
+ SessionLookupError,
17304
+ SessionSummarySchema,
16932
17305
  TaskItemSchema,
16933
17306
  USAGE_EVENT_SOURCE,
16934
17307
  UpdateCheckOutputSchema,
@@ -16947,6 +17320,7 @@ export {
16947
17320
  addProvider,
16948
17321
  agentShimCliPath,
16949
17322
  answerRcControlRequest,
17323
+ applyAgentTaskEvent,
16950
17324
  authenticateRcSessionMcpServer,
16951
17325
  buildEntryFacts,
16952
17326
  buildLayoutPaths,
@@ -16976,6 +17350,8 @@ export {
16976
17350
  collectFrontDoorStatus,
16977
17351
  collectPoolPick,
16978
17352
  collectResets,
17353
+ collectSessionList,
17354
+ createAgentTreesApiRouter,
16979
17355
  createCodexApiRouter,
16980
17356
  createConfigApiRouter,
16981
17357
  createControlApiRouter,
@@ -17044,7 +17420,9 @@ export {
17044
17420
  listProviders,
17045
17421
  listSessions2 as listSessions,
17046
17422
  listUsageSnapshots,
17423
+ locateSession,
17047
17424
  matchBranch,
17425
+ mergeLiveTasks,
17048
17426
  mintLeaf,
17049
17427
  mintRcSelfHostCredential,
17050
17428
  observingRoutedRoute,
@@ -17086,6 +17464,7 @@ export {
17086
17464
  realRcEventDial,
17087
17465
  realRcStreamDial,
17088
17466
  realRcWebFetch,
17467
+ realSessionFs,
17089
17468
  reconnectRcSessionMcpServer,
17090
17469
  recoverFarm,
17091
17470
  recoveryDiagnostics,
@@ -17127,11 +17506,13 @@ export {
17127
17506
  setProfileMetadata,
17128
17507
  setRcSessionModel,
17129
17508
  setRcSessionPermissionMode,
17509
+ showSession,
17130
17510
  snapshotPath,
17131
17511
  spawnClaude,
17132
17512
  startConnectServer,
17133
17513
  submitRcSessionMcpOAuthCallbackUrl,
17134
17514
  suggestRcSessionFiles,
17515
+ summariseSession,
17135
17516
  teleportRcSession,
17136
17517
  topLevelNames,
17137
17518
  updateDirectoryRule,