claude-use 11.87.5 → 11.88.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.cjs CHANGED
@@ -5189,7 +5189,7 @@ var init_package = __esm({
5189
5189
  "package.json"() {
5190
5190
  package_default = {
5191
5191
  name: "claude-use",
5192
- version: "11.87.5",
5192
+ version: "11.88.0",
5193
5193
  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.",
5194
5194
  license: "MIT",
5195
5195
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -15089,11 +15089,11 @@ var init_identityClaude = __esm({
15089
15089
  });
15090
15090
 
15091
15091
  // src/usage/providerQuota.ts
15092
- var import_zod41, MS_PER_SECOND9, SECONDS_PER_HOUR3, HOURS_PER_DAY6, DAYS_PER_MONTH, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZaiLimitSchema, ZaiResponseSchema, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, ANTIGRAVITY_HOST, ANTIGRAVITY_QUOTA_URL, ANTIGRAVITY_USER_URL, FIVE_HOURS2, DAYS_PER_WEEK2, FIVE_HOURS_MS, WEEK_MS, AntigravityBucketSchema, AntigravitySummarySchema, GoogleTokenInfoSchema, AntigravityUserSchema;
15092
+ var import_zod42, MS_PER_SECOND9, SECONDS_PER_HOUR3, HOURS_PER_DAY6, DAYS_PER_MONTH, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZaiLimitSchema, ZaiResponseSchema, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, ANTIGRAVITY_HOST, ANTIGRAVITY_QUOTA_URL, ANTIGRAVITY_USER_URL, FIVE_HOURS2, DAYS_PER_WEEK2, FIVE_HOURS_MS, WEEK_MS, AntigravityBucketSchema, AntigravitySummarySchema, GoogleTokenInfoSchema, AntigravityUserSchema;
15093
15093
  var init_providerQuota = __esm({
15094
15094
  "src/usage/providerQuota.ts"() {
15095
15095
  "use strict";
15096
- import_zod41 = require("zod");
15096
+ import_zod42 = require("zod");
15097
15097
  init_cloudUpstream();
15098
15098
  init_schema2();
15099
15099
  MS_PER_SECOND9 = 1e3;
@@ -15108,35 +15108,35 @@ var init_providerQuota = __esm({
15108
15108
  [ZAI_UNIT_HOURS, SECONDS_PER_HOUR3 * MS_PER_SECOND9],
15109
15109
  [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9]
15110
15110
  ]);
15111
- ZaiLimitSchema = import_zod41.z.object({
15112
- type: import_zod41.z.string(),
15113
- unit: import_zod41.z.number().int(),
15114
- number: import_zod41.z.number().int().positive(),
15115
- percentage: import_zod41.z.number().nonnegative(),
15116
- nextResetTime: import_zod41.z.number().positive().optional(),
15117
- usage: import_zod41.z.number().nonnegative().optional(),
15118
- currentValue: import_zod41.z.number().nonnegative().optional(),
15119
- remaining: import_zod41.z.number().nonnegative().optional()
15111
+ ZaiLimitSchema = import_zod42.z.object({
15112
+ type: import_zod42.z.string(),
15113
+ unit: import_zod42.z.number().int(),
15114
+ number: import_zod42.z.number().int().positive(),
15115
+ percentage: import_zod42.z.number().nonnegative(),
15116
+ nextResetTime: import_zod42.z.number().positive().optional(),
15117
+ usage: import_zod42.z.number().nonnegative().optional(),
15118
+ currentValue: import_zod42.z.number().nonnegative().optional(),
15119
+ remaining: import_zod42.z.number().nonnegative().optional()
15120
15120
  });
15121
- ZaiResponseSchema = import_zod41.z.object({
15122
- success: import_zod41.z.boolean(),
15123
- msg: import_zod41.z.string().optional(),
15124
- data: import_zod41.z.object({ level: import_zod41.z.string().optional(), limits: import_zod41.z.array(ZaiLimitSchema) })
15121
+ ZaiResponseSchema = import_zod42.z.object({
15122
+ success: import_zod42.z.boolean(),
15123
+ msg: import_zod42.z.string().optional(),
15124
+ data: import_zod42.z.object({ level: import_zod42.z.string().optional(), limits: import_zod42.z.array(ZaiLimitSchema) })
15125
15125
  });
15126
15126
  OPENROUTER_HOST = "openrouter.ai";
15127
15127
  OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
15128
15128
  OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
15129
15129
  MS_PER_DAY2 = HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15130
- OpenRouterKeySchema = import_zod41.z.object({
15131
- data: import_zod41.z.object({
15132
- limit: import_zod41.z.number().nonnegative().nullable(),
15133
- limit_remaining: import_zod41.z.number().nullable(),
15134
- limit_reset: import_zod41.z.string().nullable(),
15135
- is_free_tier: import_zod41.z.boolean().optional(),
15136
- free_model_daily_requests: import_zod41.z.object({ used: import_zod41.z.number().nonnegative(), limit: import_zod41.z.number().nonnegative(), remaining: import_zod41.z.number() }).optional()
15130
+ OpenRouterKeySchema = import_zod42.z.object({
15131
+ data: import_zod42.z.object({
15132
+ limit: import_zod42.z.number().nonnegative().nullable(),
15133
+ limit_remaining: import_zod42.z.number().nullable(),
15134
+ limit_reset: import_zod42.z.string().nullable(),
15135
+ is_free_tier: import_zod42.z.boolean().optional(),
15136
+ free_model_daily_requests: import_zod42.z.object({ used: import_zod42.z.number().nonnegative(), limit: import_zod42.z.number().nonnegative(), remaining: import_zod42.z.number() }).optional()
15137
15137
  })
15138
15138
  });
15139
- OpenRouterCreditsSchema = import_zod41.z.object({ data: import_zod41.z.object({ total_credits: import_zod41.z.number().nonnegative(), total_usage: import_zod41.z.number().nonnegative() }) });
15139
+ OpenRouterCreditsSchema = import_zod42.z.object({ data: import_zod42.z.object({ total_credits: import_zod42.z.number().nonnegative(), total_usage: import_zod42.z.number().nonnegative() }) });
15140
15140
  ANTIGRAVITY_HOST = "daily-cloudcode-pa.googleapis.com";
15141
15141
  ANTIGRAVITY_QUOTA_URL = `https://${ANTIGRAVITY_HOST}/v1internal:retrieveUserQuotaSummary`;
15142
15142
  ANTIGRAVITY_USER_URL = `https://${ANTIGRAVITY_HOST}/v1internal:loadCodeAssist`;
@@ -15144,21 +15144,21 @@ var init_providerQuota = __esm({
15144
15144
  DAYS_PER_WEEK2 = 7;
15145
15145
  FIVE_HOURS_MS = FIVE_HOURS2 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15146
15146
  WEEK_MS = DAYS_PER_WEEK2 * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15147
- AntigravityBucketSchema = import_zod41.z.object({
15148
- bucketId: import_zod41.z.string(),
15149
- remainingFraction: import_zod41.z.number().optional(),
15150
- resetTime: import_zod41.z.string().optional()
15147
+ AntigravityBucketSchema = import_zod42.z.object({
15148
+ bucketId: import_zod42.z.string(),
15149
+ remainingFraction: import_zod42.z.number().optional(),
15150
+ resetTime: import_zod42.z.string().optional()
15151
15151
  });
15152
- AntigravitySummarySchema = import_zod41.z.object({ groups: import_zod41.z.array(import_zod41.z.object({ buckets: import_zod41.z.array(AntigravityBucketSchema) })) });
15153
- GoogleTokenInfoSchema = import_zod41.z.object({
15154
- email: import_zod41.z.string().optional(),
15155
- sub: import_zod41.z.string().optional()
15152
+ AntigravitySummarySchema = import_zod42.z.object({ groups: import_zod42.z.array(import_zod42.z.object({ buckets: import_zod42.z.array(AntigravityBucketSchema) })) });
15153
+ GoogleTokenInfoSchema = import_zod42.z.object({
15154
+ email: import_zod42.z.string().optional(),
15155
+ sub: import_zod42.z.string().optional()
15156
15156
  });
15157
- AntigravityUserSchema = import_zod41.z.object({
15157
+ AntigravityUserSchema = import_zod42.z.object({
15158
15158
  /** The code-assist tier context, which defaults to the free tier for every account. */
15159
- currentTier: import_zod41.z.object({ name: import_zod41.z.string().optional(), id: import_zod41.z.string().optional() }).optional(),
15159
+ currentTier: import_zod42.z.object({ name: import_zod42.z.string().optional(), id: import_zod42.z.string().optional() }).optional(),
15160
15160
  /** The account's paid subscription; absent when the account has none. */
15161
- paidTier: import_zod41.z.object({ name: import_zod41.z.string().optional(), id: import_zod41.z.string().optional() }).optional()
15161
+ paidTier: import_zod42.z.object({ name: import_zod42.z.string().optional(), id: import_zod42.z.string().optional() }).optional()
15162
15162
  });
15163
15163
  }
15164
15164
  });
@@ -15381,6 +15381,7 @@ __export(index_exports, {
15381
15381
  RC_IDLE_EXPIRY_MS: () => RC_IDLE_EXPIRY_MS,
15382
15382
  RC_ORPC_PATH_PREFIX: () => RC_ORPC_PATH_PREFIX,
15383
15383
  RC_PENDING_DEADLINE_MS: () => RC_PENDING_DEADLINE_MS,
15384
+ RC_PENDING_RETIRE_REASONS: () => RC_PENDING_RETIRE_REASONS,
15384
15385
  RC_PERMISSION_MODES: () => RC_PERMISSION_MODES,
15385
15386
  RC_READ_FILE_ENCODINGS: () => RC_READ_FILE_ENCODINGS,
15386
15387
  RC_REQUEST_PARSE_CAP_BYTES: () => RC_REQUEST_PARSE_CAP_BYTES,
@@ -15392,6 +15393,8 @@ __export(index_exports, {
15392
15393
  RC_SELF_HOST_SCOPE_LIST: () => RC_SELF_HOST_SCOPE_LIST,
15393
15394
  RC_SELF_HOST_WORKER_JWT_TTL_SECONDS: () => RC_SELF_HOST_WORKER_JWT_TTL_SECONDS,
15394
15395
  RC_SESSIONS_PATH_PREFIX: () => RC_SESSIONS_PATH_PREFIX,
15396
+ RC_SESSION_END_REASONS: () => RC_SESSION_END_REASONS,
15397
+ RC_SESSION_EVENT_LOG_CAPACITY: () => RC_SESSION_EVENT_LOG_CAPACITY,
15395
15398
  RC_STREAM_BACKOFF_MS: () => RC_STREAM_BACKOFF_MS,
15396
15399
  RC_WEB_FETCH_ALLOW_PRIVATE_ENV: () => RC_WEB_FETCH_ALLOW_PRIVATE_ENV,
15397
15400
  RC_WEB_FETCH_DEADLINE_MS: () => RC_WEB_FETCH_DEADLINE_MS,
@@ -15402,6 +15405,13 @@ __export(index_exports, {
15402
15405
  RcPermissionModeSchema: () => RcPermissionModeSchema,
15403
15406
  RcRateLimitInfoSchema: () => RcRateLimitInfoSchema,
15404
15407
  RcRateLimitWindowSchema: () => RcRateLimitWindowSchema,
15408
+ RcSessionEventCursorExpiredError: () => RcSessionEventCursorExpiredError,
15409
+ RcSessionEventSchema: () => RcSessionEventSchema,
15410
+ RcSessionEventsPageInputSchema: () => RcSessionEventsPageInputSchema,
15411
+ RcSessionEventsReadInputSchema: () => RcSessionEventsReadInputSchema,
15412
+ RcSessionEventsReadOutputSchema: () => RcSessionEventsReadOutputSchema,
15413
+ RcSessionEventsStreamInputSchema: () => RcSessionEventsStreamInputSchema,
15414
+ RcSessionTransitionSchema: () => RcSessionTransitionSchema,
15405
15415
  RcStreamEnvelopeSchema: () => RcStreamEnvelopeSchema,
15406
15416
  RcStreamEventSchema: () => RcStreamEventSchema,
15407
15417
  ResetRowSchema: () => ResetRowSchema,
@@ -15483,6 +15493,8 @@ __export(index_exports, {
15483
15493
  createRcEventFanout: () => createRcEventFanout,
15484
15494
  createRcLiveUsage: () => createRcLiveUsage,
15485
15495
  createRcSelfHostSurface: () => createRcSelfHostSurface,
15496
+ createRcSessionEventLog: () => createRcSessionEventLog,
15497
+ createRcSessionEventsApiRouter: () => createRcSessionEventsApiRouter,
15486
15498
  createRcSessionTracker: () => createRcSessionTracker,
15487
15499
  createRcStreamHub: () => createRcStreamHub,
15488
15500
  createSseParser: () => createSseParser,
@@ -15498,6 +15510,7 @@ __export(index_exports, {
15498
15510
  evaluateAmbientCredentialGuard: () => evaluateAmbientCredentialGuard,
15499
15511
  evaluateWhen: () => evaluateWhen,
15500
15512
  fetchThroughWebProxy: () => fetchThroughWebProxy,
15513
+ followRcSessionEvents: () => followRcSessionEvents,
15501
15514
  formatAmbientCredentialGuardMessage: () => formatAmbientCredentialGuardMessage,
15502
15515
  formatCheckReport: () => formatCheckReport,
15503
15516
  formatDoctorReport: () => formatDoctorReport,
@@ -16066,30 +16079,60 @@ function parseRcRequestBody(kind, body) {
16066
16079
  }
16067
16080
  function createRcSessionTracker(deps) {
16068
16081
  const entries = /* @__PURE__ */ new Map();
16069
- const expire = (id) => {
16082
+ const retirePending = (entry, requestId, reason) => {
16083
+ if (entry.pending.delete(requestId)) {
16084
+ entry.retired.set(requestId, deps.now());
16085
+ deps.onTransition?.({ kind: "pending-retired", session: entry.id, requestId, reason, at: deps.now() });
16086
+ }
16087
+ };
16088
+ const addPending = (entry, pending) => {
16089
+ if (entry.retired.has(pending.requestId)) {
16090
+ return;
16091
+ }
16092
+ const born = !entry.pending.has(pending.requestId);
16093
+ entry.pending.set(pending.requestId, pending);
16094
+ if (born) {
16095
+ deps.onTransition?.({ kind: "pending-born", session: entry.id, requestId: pending.requestId, type: pending.type, summary: pending.summary, at: pending.observedAt });
16096
+ }
16097
+ };
16098
+ const expire = (id, reason) => {
16099
+ const entry = entries.get(id);
16100
+ if (entry === void 0) {
16101
+ return;
16102
+ }
16103
+ for (const requestId of [...entry.pending.keys()]) {
16104
+ retirePending(entry, requestId, "session-ended");
16105
+ }
16070
16106
  entries.delete(id);
16107
+ deps.onTransition?.({ kind: "session-ended", session: id, reason, at: deps.now() });
16071
16108
  };
16072
16109
  const expirePendings = (entry, now) => {
16073
16110
  for (const [requestId, pending] of entry.pending) {
16074
16111
  if (now - pending.observedAt >= RC_PENDING_DEADLINE_MS) {
16075
- entry.pending.delete(requestId);
16112
+ retirePending(entry, requestId, "expired");
16113
+ }
16114
+ }
16115
+ for (const [requestId, retiredAt] of entry.retired) {
16116
+ if (now - retiredAt >= RC_PENDING_DEADLINE_MS) {
16117
+ entry.retired.delete(requestId);
16076
16118
  }
16077
16119
  }
16078
16120
  };
16079
16121
  const sweep = () => {
16080
16122
  for (const [id, entry] of entries) {
16081
16123
  if (deps.now() - entry.lastSeenAt >= deps.idleMs) {
16082
- expire(id);
16124
+ expire(id, "expired");
16083
16125
  continue;
16084
16126
  }
16085
16127
  expirePendings(entry, deps.now());
16086
16128
  }
16087
16129
  };
16088
- const timer = setInterval(sweep, deps.idleMs);
16130
+ const timer = setInterval(sweep, Math.min(deps.idleMs, RC_PENDING_DEADLINE_MS));
16089
16131
  timer.unref();
16090
16132
  const birth = (id, facts) => {
16091
- 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() };
16133
+ const record = { id, createdAt: deps.now(), lastSeenAt: deps.now(), ...facts, pending: /* @__PURE__ */ new Map(), retired: /* @__PURE__ */ new Map(), workerState: void 0, workerIdleSeconds: void 0, sequenceNum: void 0, liveTasks: /* @__PURE__ */ new Map() };
16092
16134
  entries.set(id, record);
16135
+ deps.onTransition?.({ kind: "session-appeared", session: id, at: record.createdAt });
16093
16136
  return record;
16094
16137
  };
16095
16138
  const persistCredential = (entry) => {
@@ -16097,6 +16140,13 @@ function createRcSessionTracker(deps) {
16097
16140
  deps.credentialStore?.write(entry.id, { authorization: entry.oauthAuthorization, anthropicVersion: entry.anthropicVersion, anthropicClientPlatform: entry.anthropicClientPlatform });
16098
16141
  }
16099
16142
  };
16143
+ const refresh = (entry, facts) => {
16144
+ entry.lastSeenAt = deps.now();
16145
+ entry.oauthAuthorization = facts.oauthAuthorization ?? entry.oauthAuthorization;
16146
+ entry.anthropicVersion = facts.anthropicVersion ?? entry.anthropicVersion;
16147
+ entry.anthropicClientPlatform = facts.anthropicClientPlatform ?? entry.anthropicClientPlatform;
16148
+ persistCredential(entry);
16149
+ };
16100
16150
  const observeExchange = (request4) => {
16101
16151
  const method = (request4.method ?? "").toUpperCase();
16102
16152
  if (!isRcSessionExchange(request4.url)) {
@@ -16135,7 +16185,12 @@ function createRcSessionTracker(deps) {
16135
16185
  if (id2 === void 0) {
16136
16186
  return;
16137
16187
  }
16138
- persistCredential(birth(id2, facts));
16188
+ const existing = entries.get(id2);
16189
+ if (existing === void 0) {
16190
+ persistCredential(birth(id2, facts));
16191
+ return;
16192
+ }
16193
+ refresh(existing, facts);
16139
16194
  }
16140
16195
  };
16141
16196
  }
@@ -16144,12 +16199,10 @@ function createRcSessionTracker(deps) {
16144
16199
  if (id?.startsWith(RC_SESSION_ID_PREFIX) !== true) {
16145
16200
  return void 0;
16146
16201
  }
16147
- const entry = entries.get(id) ?? birth(id, facts);
16148
- entry.lastSeenAt = deps.now();
16149
- entry.oauthAuthorization = facts.oauthAuthorization ?? entry.oauthAuthorization;
16150
- entry.anthropicVersion = facts.anthropicVersion ?? entry.anthropicVersion;
16151
- entry.anthropicClientPlatform = facts.anthropicClientPlatform ?? entry.anthropicClientPlatform;
16152
- persistCredential(entry);
16202
+ const tracked = entries.get(id);
16203
+ if (tracked !== void 0) {
16204
+ refresh(tracked, facts);
16205
+ }
16153
16206
  const bodyKind = method === "POST" && rest === `${id}/worker/events` ? "worker-events" : method === "POST" && rest === `${id}/events` ? "client-events" : method === "POST" && rest === `${id}/worker/heartbeat` ? "heartbeat" : method === "PUT" && rest === `${id}/worker` ? "worker-registration" : void 0;
16154
16207
  let chunks = [];
16155
16208
  let buffered = 0;
@@ -16170,10 +16223,10 @@ function createRcSessionTracker(deps) {
16170
16223
  }
16171
16224
  const now = deps.now();
16172
16225
  for (const controlRequest of factsOfBody.controlRequests) {
16173
- entryNow.pending.set(controlRequest.requestId, { sessionId: id, ...controlRequest, observedAt: now });
16226
+ addPending(entryNow, { sessionId: id, ...controlRequest, observedAt: now });
16174
16227
  }
16175
16228
  for (const requestId of factsOfBody.answeredRequestIds) {
16176
- entryNow.pending.delete(requestId);
16229
+ retirePending(entryNow, requestId, "answered");
16177
16230
  }
16178
16231
  for (const payload of factsOfBody.payloads) {
16179
16232
  entryNow.liveTasks = applyAgentTaskEvent(entryNow.liveTasks, id, payload, now);
@@ -16182,7 +16235,11 @@ function createRcSessionTracker(deps) {
16182
16235
  entryNow.workerIdleSeconds = { value: factsOfBody.idleSeconds, observedAt: now };
16183
16236
  }
16184
16237
  if (factsOfBody.workerStatus !== void 0) {
16238
+ const previous = entryNow.workerState?.value;
16185
16239
  entryNow.workerState = { value: factsOfBody.workerStatus, observedAt: now };
16240
+ if (previous !== factsOfBody.workerStatus) {
16241
+ deps.onTransition?.({ kind: "worker-state", session: id, state: factsOfBody.workerStatus, ...previous === void 0 ? {} : { previous }, at: now });
16242
+ }
16186
16243
  }
16187
16244
  };
16188
16245
  const archiving = method === "POST" && rest === `${id}/archive`;
@@ -16207,10 +16264,13 @@ function createRcSessionTracker(deps) {
16207
16264
  onResponse: (status, headers) => {
16208
16265
  if (singleHeader(headers, CONFLICT_REASON_HEADER) !== void 0 || archiving && isSuccessful(status)) {
16209
16266
  deps.credentialStore?.remove(id);
16210
- expire(id);
16267
+ expire(id, singleHeader(headers, CONFLICT_REASON_HEADER) === void 0 ? "archived" : "conflict");
16211
16268
  return;
16212
16269
  }
16213
16270
  accepted = isSuccessful(status);
16271
+ if (accepted && !entries.has(id)) {
16272
+ persistCredential(birth(id, facts));
16273
+ }
16214
16274
  file();
16215
16275
  },
16216
16276
  onBodyChunk: () => {
@@ -16275,12 +16335,12 @@ function createRcSessionTracker(deps) {
16275
16335
  const pending = pendingOfControlRequestPayload(event.payload);
16276
16336
  if (pending !== void 0) {
16277
16337
  if (event.source === RC_STREAM_WORKER_SOURCE) {
16278
- entry.pending.set(pending.requestId, { sessionId, ...pending, observedAt: deps.now() });
16338
+ addPending(entry, { sessionId, ...pending, observedAt: deps.now() });
16279
16339
  }
16280
16340
  return;
16281
16341
  }
16282
16342
  for (const requestId of answeredRequestIdsOfControlResponsePayload(event.payload)) {
16283
- entry.pending.delete(requestId);
16343
+ retirePending(entry, requestId, "answered");
16284
16344
  }
16285
16345
  },
16286
16346
  liveTasksOf: (sessionId) => {
@@ -16288,10 +16348,14 @@ function createRcSessionTracker(deps) {
16288
16348
  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)));
16289
16349
  },
16290
16350
  completePending: (sessionId, requestId) => {
16291
- entries.get(sessionId)?.pending.delete(requestId);
16351
+ const entry = entries.get(sessionId);
16352
+ if (entry !== void 0) {
16353
+ retirePending(entry, requestId, "answered");
16354
+ }
16292
16355
  },
16293
16356
  close: () => {
16294
16357
  clearInterval(timer);
16358
+ deps.onClose?.();
16295
16359
  }
16296
16360
  };
16297
16361
  }
@@ -18371,8 +18435,8 @@ init_cliError();
18371
18435
  init_realPorts();
18372
18436
 
18373
18437
  // src/frontdoor/controlApi.ts
18374
- var import_client7 = require("@orpc/client");
18375
- var import_openapi8 = require("@orpc/openapi");
18438
+ var import_client8 = require("@orpc/client");
18439
+ var import_openapi9 = require("@orpc/openapi");
18376
18440
 
18377
18441
  // src/checkReport.ts
18378
18442
  var import_node_os5 = __toESM(require("node:os"), 1);
@@ -21273,6 +21337,381 @@ function createAgentTreesApiRouter(deps) {
21273
21337
  };
21274
21338
  }
21275
21339
 
21340
+ // src/frontdoor/rcEventLogApi.ts
21341
+ var import_client7 = require("@orpc/client");
21342
+ var import_openapi8 = require("@orpc/openapi");
21343
+ var import_server4 = require("@orpc/server");
21344
+
21345
+ // src/frontdoor/rcEventLog.ts
21346
+ var import_zod40 = require("zod");
21347
+
21348
+ // src/frontdoor/eventHub.ts
21349
+ var DOOR_EVENT_BUFFER_EVENTS = 100;
21350
+ function createDoorEventHub() {
21351
+ const sequences = /* @__PURE__ */ new Map();
21352
+ const registered = /* @__PURE__ */ new Set();
21353
+ const every = /* @__PURE__ */ new Set();
21354
+ const bySource = /* @__PURE__ */ new Map();
21355
+ const deliver = (event) => {
21356
+ for (const listener of every) {
21357
+ listener(event);
21358
+ }
21359
+ for (const listener of bySource.get(event.source) ?? []) {
21360
+ listener(event);
21361
+ }
21362
+ };
21363
+ const publish = (source, payload) => {
21364
+ const sequence2 = (sequences.get(source) ?? 0) + 1;
21365
+ sequences.set(source, sequence2);
21366
+ deliver({ source, sequence: sequence2, payload });
21367
+ };
21368
+ const addListener = (sources, listener) => {
21369
+ if (sources === void 0) {
21370
+ every.add(listener);
21371
+ return () => {
21372
+ every.delete(listener);
21373
+ };
21374
+ }
21375
+ const listenersFor = (source) => {
21376
+ const listeners = bySource.get(source) ?? /* @__PURE__ */ new Set();
21377
+ bySource.set(source, listeners);
21378
+ return listeners;
21379
+ };
21380
+ const detachers = sources.map((source) => {
21381
+ const listeners = listenersFor(source);
21382
+ listeners.add(listener);
21383
+ return () => {
21384
+ listeners.delete(listener);
21385
+ if (listeners.size === 0) {
21386
+ bySource.delete(source);
21387
+ }
21388
+ };
21389
+ });
21390
+ return () => {
21391
+ for (const detach of detachers) {
21392
+ detach();
21393
+ }
21394
+ };
21395
+ };
21396
+ return {
21397
+ publisher: (source) => {
21398
+ registered.add(source);
21399
+ return {
21400
+ source,
21401
+ publish: (payload) => {
21402
+ publish(source, payload);
21403
+ }
21404
+ };
21405
+ },
21406
+ subscribe: addListener,
21407
+ stream: (sources) => {
21408
+ const queue = [];
21409
+ let wake;
21410
+ let closed = false;
21411
+ const detach = addListener(sources, (event) => {
21412
+ if (queue.length >= DOOR_EVENT_BUFFER_EVENTS) {
21413
+ queue.shift();
21414
+ }
21415
+ queue.push(event);
21416
+ wake?.();
21417
+ });
21418
+ return {
21419
+ next: async () => {
21420
+ for (; ; ) {
21421
+ const event = queue.shift();
21422
+ if (event !== void 0) {
21423
+ return { value: event, done: false };
21424
+ }
21425
+ if (closed) {
21426
+ return { value: void 0, done: true };
21427
+ }
21428
+ await new Promise((resolve) => {
21429
+ wake = resolve;
21430
+ });
21431
+ }
21432
+ },
21433
+ close: () => {
21434
+ closed = true;
21435
+ detach();
21436
+ wake?.();
21437
+ }
21438
+ };
21439
+ },
21440
+ sources: () => [...registered].sort()
21441
+ };
21442
+ }
21443
+ function rcFanoutOnDoorHub(fanout, hub) {
21444
+ const publisher = hub.publisher(DOOR_EVENT_SOURCE_RC);
21445
+ return {
21446
+ publish: (event) => {
21447
+ fanout.publish(event);
21448
+ publisher.publish(event);
21449
+ },
21450
+ subscribe: (session, listener) => fanout.subscribe(session, listener)
21451
+ };
21452
+ }
21453
+
21454
+ // src/frontdoor/rcEventLog.ts
21455
+ var RC_SESSION_EVENT_TOKEN_MAX_CHARS = 255;
21456
+ var HIGH_SURROGATE_FIRST = 55296;
21457
+ var HIGH_SURROGATE_LAST = 56319;
21458
+ var LOW_SURROGATE_FIRST = 56320;
21459
+ var LOW_SURROGATE_LAST = 57343;
21460
+ var CUT_MARKER = "...";
21461
+ var RC_SESSION_EVENT_SUMMARY_MAX_CHARS = RC_SESSION_EVENT_TOKEN_MAX_CHARS + " ".length + RC_PENDING_SUMMARY_EXCERPT_CHARS + CUT_MARKER.length;
21462
+ var RC_SESSION_EVENT_GENERATION_MAX_CHARS = "00000000-0000-4000-8000-000000000000".length;
21463
+ var SEQUENCE_MAX_DIGITS = String(Number.MAX_SAFE_INTEGER).length;
21464
+ var NUMBER_BYTES = Float64Array.BYTES_PER_ELEMENT;
21465
+ var NUMBER_FIELDS = ["at", "sequence"].length;
21466
+ var BYTES_PER_CODE_UNIT = Uint16Array.BYTES_PER_ELEMENT;
21467
+ var RC_SESSION_END_REASONS = ["expired", "archived", "conflict"];
21468
+ var RC_PENDING_RETIRE_REASONS = ["answered", "expired", "session-ended"];
21469
+ var transitionBase = { session: import_zod40.z.string(), at: import_zod40.z.number() };
21470
+ var cursorFields = { cursor: import_zod40.z.string(), sequence: import_zod40.z.int().positive() };
21471
+ var sessionAppearedShape = { kind: import_zod40.z.literal("session-appeared"), ...transitionBase };
21472
+ var sessionEndedShape = { kind: import_zod40.z.literal("session-ended"), reason: import_zod40.z.enum(RC_SESSION_END_REASONS), ...transitionBase };
21473
+ var workerStateShape = { kind: import_zod40.z.literal("worker-state"), state: import_zod40.z.string(), previous: import_zod40.z.string().optional(), ...transitionBase };
21474
+ var pendingBornShape = { kind: import_zod40.z.literal("pending-born"), requestId: import_zod40.z.string(), type: import_zod40.z.string(), summary: import_zod40.z.string(), ...transitionBase };
21475
+ var pendingRetiredShape = { kind: import_zod40.z.literal("pending-retired"), requestId: import_zod40.z.string(), reason: import_zod40.z.enum(RC_PENDING_RETIRE_REASONS), ...transitionBase };
21476
+ var RcSessionTransitionSchema = import_zod40.z.discriminatedUnion("kind", [
21477
+ import_zod40.z.strictObject(sessionAppearedShape),
21478
+ import_zod40.z.strictObject(sessionEndedShape),
21479
+ import_zod40.z.strictObject(workerStateShape),
21480
+ import_zod40.z.strictObject(pendingBornShape),
21481
+ import_zod40.z.strictObject(pendingRetiredShape)
21482
+ ]);
21483
+ var KIND_MAX_CHARS = Math.max(...RcSessionTransitionSchema.options.map((option) => option.shape.kind.value.length));
21484
+ var RC_SESSION_EVENT_MAX_BYTES = (RC_SESSION_EVENT_GENERATION_MAX_CHARS + ".".length + SEQUENCE_MAX_DIGITS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + KIND_MAX_CHARS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + RC_SESSION_EVENT_TOKEN_MAX_CHARS + RC_SESSION_EVENT_SUMMARY_MAX_CHARS) * BYTES_PER_CODE_UNIT + NUMBER_FIELDS * NUMBER_BYTES;
21485
+ var RC_SESSION_EVENT_LOG_CAPACITY = Math.floor(CONTROL_BODY_CAP_BYTES / RC_SESSION_EVENT_MAX_BYTES);
21486
+ var RcSessionEventSchema = import_zod40.z.discriminatedUnion("kind", [
21487
+ import_zod40.z.strictObject({ ...cursorFields, ...sessionAppearedShape }),
21488
+ import_zod40.z.strictObject({ ...cursorFields, ...sessionEndedShape }),
21489
+ import_zod40.z.strictObject({ ...cursorFields, ...workerStateShape }),
21490
+ import_zod40.z.strictObject({ ...cursorFields, ...pendingBornShape }),
21491
+ import_zod40.z.strictObject({ ...cursorFields, ...pendingRetiredShape })
21492
+ ]);
21493
+ var RcSessionEventsReadInputSchema = import_zod40.z.strictObject({
21494
+ /** The cursor of the last event the caller saw; every retained event when omitted. */
21495
+ since: import_zod40.z.string().min(1).optional(),
21496
+ /** One `cse_` session id; every session when omitted. */
21497
+ session: import_zod40.z.string().min(1).optional(),
21498
+ /** The most events one answer carries; every event after `since` when omitted. */
21499
+ limit: import_zod40.z.int().positive().optional()
21500
+ });
21501
+ var RcSessionEventsPageInputSchema = RcSessionEventsReadInputSchema.extend({
21502
+ /** The most events this page carries: by default and at most, the bound the door's event backbone already holds per slow consumer (`DOOR_EVENT_BUFFER_EVENTS`, oRPC's own documented default for that case). A page lands whole in its reader, so a reader receives at most one consumer buffer's worth at a time (at worst `DOOR_EVENT_BUFFER_EVENTS` times `RC_SESSION_EVENT_MAX_BYTES`) and pages on with the cursor for more; a maximum of the whole window would let one page carry the log's entire memory budget into an agent's context. */
21503
+ limit: import_zod40.z.int().positive().max(DOOR_EVENT_BUFFER_EVENTS).default(DOOR_EVENT_BUFFER_EVENTS)
21504
+ });
21505
+ var RcSessionEventsStreamInputSchema = RcSessionEventsReadInputSchema.omit({ limit: true });
21506
+ var RcSessionEventsReadOutputSchema = import_zod40.z.discriminatedUnion("status", [
21507
+ import_zod40.z.strictObject({ status: import_zod40.z.literal("ok"), events: import_zod40.z.readonly(import_zod40.z.array(RcSessionEventSchema)), cursor: import_zod40.z.string(), more: import_zod40.z.boolean(), head: import_zod40.z.string() }),
21508
+ import_zod40.z.strictObject({ status: import_zod40.z.literal("expired"), message: import_zod40.z.string(), head: import_zod40.z.string() })
21509
+ ]);
21510
+ var CURSOR_SEPARATOR = ".";
21511
+ var RESYNC_ADVICE = "cursor expired, resync from status: read `rc status` for every session's present state, then resume after the head this answer names";
21512
+ function cursorOf(generation, sequence2) {
21513
+ return `${generation}${CURSOR_SEPARATOR}${String(sequence2)}`;
21514
+ }
21515
+ function parseCursor(cursor) {
21516
+ const at = cursor.lastIndexOf(CURSOR_SEPARATOR);
21517
+ if (at <= 0) {
21518
+ return void 0;
21519
+ }
21520
+ const digits = cursor.slice(at + 1);
21521
+ if (!/^[0-9]+$/.test(digits)) {
21522
+ return void 0;
21523
+ }
21524
+ return { generation: cursor.slice(0, at), sequence: Number(digits) };
21525
+ }
21526
+ function codePointBoundary(text, at) {
21527
+ const before = text.charCodeAt(at - 1);
21528
+ const after = text.charCodeAt(at);
21529
+ const isHigh = before >= HIGH_SURROGATE_FIRST && before <= HIGH_SURROGATE_LAST;
21530
+ const isLow = after >= LOW_SURROGATE_FIRST && after <= LOW_SURROGATE_LAST;
21531
+ return isHigh && isLow ? at - 1 : at;
21532
+ }
21533
+ function bounded2(text, maxChars) {
21534
+ const kept = text.length <= maxChars ? text : `${text.slice(0, codePointBoundary(text, maxChars - CUT_MARKER.length))}${CUT_MARKER}`;
21535
+ return Buffer.from(kept, "utf16le").toString("utf16le");
21536
+ }
21537
+ function boundedTransition(transition) {
21538
+ const session = bounded2(transition.session, RC_SESSION_EVENT_TOKEN_MAX_CHARS);
21539
+ if (transition.kind === "worker-state") {
21540
+ return { ...transition, session, state: bounded2(transition.state, RC_SESSION_EVENT_TOKEN_MAX_CHARS), ...transition.previous === void 0 ? {} : { previous: bounded2(transition.previous, RC_SESSION_EVENT_TOKEN_MAX_CHARS) } };
21541
+ }
21542
+ if (transition.kind === "pending-born") {
21543
+ return { ...transition, session, requestId: bounded2(transition.requestId, RC_SESSION_EVENT_TOKEN_MAX_CHARS), type: bounded2(transition.type, RC_SESSION_EVENT_TOKEN_MAX_CHARS), summary: bounded2(transition.summary, RC_SESSION_EVENT_SUMMARY_MAX_CHARS) };
21544
+ }
21545
+ if (transition.kind === "pending-retired") {
21546
+ return { ...transition, session, requestId: bounded2(transition.requestId, RC_SESSION_EVENT_TOKEN_MAX_CHARS) };
21547
+ }
21548
+ return { ...transition, session };
21549
+ }
21550
+ function createRcSessionEventLog(deps) {
21551
+ if (deps.generation.includes(CURSOR_SEPARATOR)) {
21552
+ throw new Error(`a door generation id must not contain "${CURSOR_SEPARATOR}", which separates a cursor's generation from its sequence`);
21553
+ }
21554
+ if (deps.generation.length > RC_SESSION_EVENT_GENERATION_MAX_CHARS) {
21555
+ throw new Error(`a door generation id must be at most ${String(RC_SESSION_EVENT_GENERATION_MAX_CHARS)} characters, a UUID's length`);
21556
+ }
21557
+ const events = [];
21558
+ let lastSequence = 0;
21559
+ const listeners = /* @__PURE__ */ new Set();
21560
+ let isClosed = false;
21561
+ const expired = (reason) => ({ status: "expired", message: `${reason}; ${RESYNC_ADVICE}`, head: cursorOf(deps.generation, lastSequence) });
21562
+ return {
21563
+ append: (transition) => {
21564
+ lastSequence += 1;
21565
+ events.push({ ...boundedTransition(transition), cursor: cursorOf(deps.generation, lastSequence), sequence: lastSequence });
21566
+ if (events.length > deps.capacity) {
21567
+ events.splice(0, events.length - deps.capacity);
21568
+ }
21569
+ for (const listener of listeners) {
21570
+ listener();
21571
+ }
21572
+ },
21573
+ head: () => cursorOf(deps.generation, lastSequence),
21574
+ read: ({ since, session, limit }) => {
21575
+ let after = 0;
21576
+ if (since !== void 0) {
21577
+ const parsed = parseCursor(since);
21578
+ if (parsed === void 0) {
21579
+ return expired(`"${since}" is not a cursor this door issues`);
21580
+ }
21581
+ if (parsed.generation !== deps.generation) {
21582
+ return expired(`the cursor "${since}" was issued by another generation of the front door, whose events this one never held`);
21583
+ }
21584
+ if (parsed.sequence > lastSequence) {
21585
+ return expired(`the cursor "${since}" names an event past this door's newest`);
21586
+ }
21587
+ const oldest = events[0]?.sequence ?? lastSequence + 1;
21588
+ if (parsed.sequence < oldest - 1) {
21589
+ return expired(`the events after "${since}" have been evicted (the log retains the newest ${String(deps.capacity)} and the oldest it still holds is "${cursorOf(deps.generation, oldest)}")`);
21590
+ }
21591
+ after = parsed.sequence;
21592
+ }
21593
+ const selected2 = [];
21594
+ let cursor = cursorOf(deps.generation, lastSequence);
21595
+ let more = false;
21596
+ for (const event of events) {
21597
+ if (event.sequence <= after || session !== void 0 && event.session !== session) {
21598
+ continue;
21599
+ }
21600
+ if (limit !== void 0 && selected2.length === limit) {
21601
+ more = true;
21602
+ cursor = selected2.at(-1)?.cursor ?? cursor;
21603
+ break;
21604
+ }
21605
+ selected2.push(event);
21606
+ }
21607
+ return { status: "ok", events: selected2, cursor, more, head: cursorOf(deps.generation, lastSequence) };
21608
+ },
21609
+ onAppend: (listener) => {
21610
+ listeners.add(listener);
21611
+ return () => {
21612
+ listeners.delete(listener);
21613
+ };
21614
+ },
21615
+ close: () => {
21616
+ if (isClosed) {
21617
+ return;
21618
+ }
21619
+ isClosed = true;
21620
+ for (const listener of listeners) {
21621
+ listener();
21622
+ }
21623
+ },
21624
+ closed: () => isClosed
21625
+ };
21626
+ }
21627
+ var RcSessionEventCursorExpiredError = class extends Error {
21628
+ /** The cursor naming the log's newest event at the moment of the refusal: where to resume after once the status read has restated the present. */
21629
+ head;
21630
+ constructor(message, head) {
21631
+ super(message);
21632
+ this.name = "RcSessionEventCursorExpiredError";
21633
+ this.head = head;
21634
+ }
21635
+ };
21636
+ function followRcSessionEvents(log, input, signal) {
21637
+ return followAfter(log, input.since ?? log.head(), input.session, signal);
21638
+ }
21639
+ async function* followAfter(log, since, session, signal) {
21640
+ let cursor = since;
21641
+ let onAbort = () => void 0;
21642
+ const aborted = new Promise((resolve) => {
21643
+ onAbort = resolve;
21644
+ });
21645
+ signal?.addEventListener("abort", onAbort, { once: true });
21646
+ try {
21647
+ for (; ; ) {
21648
+ signal?.throwIfAborted();
21649
+ const closedBeforeRead = log.closed();
21650
+ let detach = () => void 0;
21651
+ const woken = new Promise((resolve) => {
21652
+ detach = log.onAppend(resolve);
21653
+ });
21654
+ try {
21655
+ const read = log.read({ since: cursor, ...session === void 0 ? {} : { session } });
21656
+ if (read.status === "expired") {
21657
+ throw new RcSessionEventCursorExpiredError(read.message, read.head);
21658
+ }
21659
+ if (read.events.length === 0) {
21660
+ cursor = read.cursor;
21661
+ if (closedBeforeRead) {
21662
+ return;
21663
+ }
21664
+ await Promise.race([woken, aborted]);
21665
+ continue;
21666
+ }
21667
+ for (const event of read.events) {
21668
+ yield event;
21669
+ cursor = event.cursor;
21670
+ }
21671
+ cursor = read.cursor;
21672
+ } finally {
21673
+ detach();
21674
+ }
21675
+ }
21676
+ } finally {
21677
+ signal?.removeEventListener("abort", onAbort);
21678
+ }
21679
+ }
21680
+
21681
+ // src/frontdoor/rcEventLogApi.ts
21682
+ var RC_API_TAG2 = "remote-control";
21683
+ var CURSOR_EXPIRED_CODE = "GONE";
21684
+ async function* sseOf(follower) {
21685
+ try {
21686
+ for await (const event of follower) {
21687
+ yield (0, import_server4.withEventMeta)(event, { id: event.cursor });
21688
+ }
21689
+ } catch (error) {
21690
+ if (error instanceof RcSessionEventCursorExpiredError) {
21691
+ throw new import_client7.ORPCError(CURSOR_EXPIRED_CODE, { message: error.message, data: { head: error.head } });
21692
+ }
21693
+ throw error;
21694
+ }
21695
+ }
21696
+ function createRcSessionEventsApiRouter(deps) {
21697
+ const authed = doorApiAuth(deps.expectedToken);
21698
+ return {
21699
+ rcSessions: {
21700
+ events: authed.meta((0, import_openapi8.openapi)({ method: "GET", path: "/rest/rc/session-events", summary: "Stream every observed session's state transitions, pending requests and endings (SSE), resumable by cursor", tags: [RC_API_TAG2] })).input(RcSessionEventsStreamInputSchema).output((0, import_server4.eventIterator)(RcSessionEventSchema)).handler(({ input, signal, lastEventId }) => sseOf(followRcSessionEvents(deps.sessionEvents, { since: lastEventId ?? input.since, session: input.session }, signal))),
21701
+ eventsPage: authed.meta(
21702
+ (0, import_openapi8.openapi)({
21703
+ method: "POST",
21704
+ path: "/rest/rc/session-events/page",
21705
+ summary: "Read every observed session's state transitions, pending requests and endings after a cursor, one page at a time",
21706
+ tags: [RC_API_TAG2],
21707
+ // A POST because the page size is a number a query string cannot type, but the answer changes nothing.
21708
+ spec: (current) => ({ ...current, [READ_ONLY_OPERATION_EXTENSION]: true })
21709
+ })
21710
+ ).input(RcSessionEventsPageInputSchema).output(RcSessionEventsReadOutputSchema).handler(({ input }) => deps.sessionEvents.read(input))
21711
+ }
21712
+ };
21713
+ }
21714
+
21276
21715
  // src/frontdoor/controlApi.ts
21277
21716
  var USAGE_API_TAG = "usage";
21278
21717
  var FRONTDOOR_API_TAG2 = "frontdoor";
@@ -21283,12 +21722,12 @@ function createControlApiRouter(deps) {
21283
21722
  const authed = doorApiAuth(deps.expectedToken);
21284
21723
  return {
21285
21724
  usage: {
21286
- list: authed.meta((0, import_openapi8.openapi)({ method: "GET", path: "/rest/usage/snapshots", summary: "List every identity's usage snapshot", tags: [USAGE_API_TAG] })).output(UsageListOutputSchema).handler(() => ({ snapshots: deps.usageSnapshots() })),
21287
- resets: authed.meta((0, import_openapi8.openapi)({ 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())),
21288
- effectiveWindow: authed.meta((0, import_openapi8.openapi)({ method: "GET", path: "/rest/usage/windows", summary: "Read one identity's effective quota windows", tags: [USAGE_API_TAG] })).input(UsageWindowsInputSchema).output(UsageWindowsOutputSchema).handler(({ input }) => {
21725
+ list: authed.meta((0, import_openapi9.openapi)({ method: "GET", path: "/rest/usage/snapshots", summary: "List every identity's usage snapshot", tags: [USAGE_API_TAG] })).output(UsageListOutputSchema).handler(() => ({ snapshots: deps.usageSnapshots() })),
21726
+ resets: authed.meta((0, import_openapi9.openapi)({ 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())),
21727
+ effectiveWindow: authed.meta((0, import_openapi9.openapi)({ method: "GET", path: "/rest/usage/windows", summary: "Read one identity's effective quota windows", tags: [USAGE_API_TAG] })).input(UsageWindowsInputSchema).output(UsageWindowsOutputSchema).handler(({ input }) => {
21289
21728
  const snapshot = deps.usageSnapshotOf(input.identity);
21290
21729
  if (snapshot === void 0) {
21291
- throw new import_client7.ORPCError("NOT_FOUND", { message: `identity ${input.identity} has no usage snapshot yet, so no quota window has been observed for it` });
21730
+ throw new import_client8.ORPCError("NOT_FOUND", { message: `identity ${input.identity} has no usage snapshot yet, so no quota window has been observed for it` });
21292
21731
  }
21293
21732
  const provider = input.provider ?? ANTHROPIC_PROVIDER;
21294
21733
  const rateLimit = snapshot.providers[provider]?.rateLimit;
@@ -21302,34 +21741,34 @@ function createControlApiRouter(deps) {
21302
21741
  ...unified?.sevenDay === void 0 ? {} : { sevenDay: effectiveWindow(unified.sevenDay, now) }
21303
21742
  };
21304
21743
  }),
21305
- live: authed.meta((0, import_openapi8.openapi)({ 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 }) => {
21744
+ live: authed.meta((0, import_openapi9.openapi)({ 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 }) => {
21306
21745
  const sessions = deps.liveRateLimits(input.session);
21307
21746
  if (input.session !== void 0 && sessions.length === 0) {
21308
21747
  if (deps.list().some((session) => session.id === input.session)) {
21309
- throw new import_client7.ORPCError("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` });
21748
+ throw new import_client8.ORPCError("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` });
21310
21749
  }
21311
- throw new import_client7.ORPCError("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
21750
+ throw new import_client8.ORPCError("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
21312
21751
  }
21313
21752
  return { latest: deps.latestRateLimit(), sessions };
21314
21753
  })
21315
21754
  },
21316
21755
  frontdoor: {
21317
- status: authed.meta((0, import_openapi8.openapi)({ method: "GET", path: "/rest/frontdoor/status", summary: "Read the front door's status", tags: [FRONTDOOR_API_TAG2] })).output(FrontDoorStatusOutputSchema).handler(() => deps.frontDoorStatus()),
21318
- sessions: authed.meta((0, import_openapi8.openapi)({ 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 }))
21756
+ status: authed.meta((0, import_openapi9.openapi)({ method: "GET", path: "/rest/frontdoor/status", summary: "Read the front door's status", tags: [FRONTDOOR_API_TAG2] })).output(FrontDoorStatusOutputSchema).handler(() => deps.frontDoorStatus()),
21757
+ sessions: authed.meta((0, import_openapi9.openapi)({ 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 }))
21319
21758
  },
21320
21759
  check: {
21321
21760
  // 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.
21322
- run: authed.meta((0, import_openapi8.openapi)({ 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)))
21761
+ run: authed.meta((0, import_openapi9.openapi)({ 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)))
21323
21762
  },
21324
21763
  doctor: {
21325
- run: authed.meta((0, import_openapi8.openapi)({ method: "GET", path: "/rest/doctor", summary: "Run the doctor report", tags: [DOCTOR_API_TAG] })).output(DoctorRunOutputSchema).handler(() => deps.doctorReport())
21764
+ run: authed.meta((0, import_openapi9.openapi)({ method: "GET", path: "/rest/doctor", summary: "Run the doctor report", tags: [DOCTOR_API_TAG] })).output(DoctorRunOutputSchema).handler(() => deps.doctorReport())
21326
21765
  },
21327
21766
  pool: {
21328
- pick: authed.meta((0, import_openapi8.openapi)({ 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 }) => {
21767
+ pick: authed.meta((0, import_openapi9.openapi)({ 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 }) => {
21329
21768
  const report = deps.poolPick(input.pool, input.path);
21330
21769
  if (report === void 0) {
21331
21770
  const live = deps.poolNames();
21332
- throw new import_client7.ORPCError("NOT_FOUND", {
21771
+ throw new import_client8.ORPCError("NOT_FOUND", {
21333
21772
  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(", ")}`
21334
21773
  });
21335
21774
  }
@@ -21341,13 +21780,13 @@ function createControlApiRouter(deps) {
21341
21780
  function createDoorApiRouter(deps) {
21342
21781
  const control = createControlApiRouter(deps);
21343
21782
  const lifecycle = createLifecycleApiRouter(deps);
21344
- return { ...createRcApiRouter(deps), ...control, ...lifecycle, ...createConfigApiRouter(deps), ...createCodexApiRouter(deps), ...createLaunchApiRouter(deps), ...createAgentTreesApiRouter(deps), ...createEventsApiRouter(deps), frontdoor: { ...control.frontdoor, ...lifecycle.frontdoor } };
21783
+ return { ...createRcApiRouter(deps), ...createRcSessionEventsApiRouter(deps), ...control, ...lifecycle, ...createConfigApiRouter(deps), ...createCodexApiRouter(deps), ...createLaunchApiRouter(deps), ...createAgentTreesApiRouter(deps), ...createEventsApiRouter(deps), frontdoor: { ...control.frontdoor, ...lifecycle.frontdoor } };
21345
21784
  }
21346
21785
  function createDoorApiNodeHandler(deps) {
21347
21786
  return doorApiNodeHandlerOf(createDoorApiRouter(deps), deps.expectedToken);
21348
21787
  }
21349
21788
  function frontDoorApiClient(port, ca, token) {
21350
- return (0, import_client7.createORPCClient)(frontDoorApiLink(port, ca, token));
21789
+ return (0, import_client8.createORPCClient)(frontDoorApiLink(port, ca, token));
21351
21790
  }
21352
21791
 
21353
21792
  // src/frontdoor/doorClient.ts
@@ -21447,112 +21886,6 @@ function formatFrontDoorStatus(status, caCertPath) {
21447
21886
  // src/index.ts
21448
21887
  init_state();
21449
21888
 
21450
- // src/frontdoor/eventHub.ts
21451
- var DOOR_EVENT_BUFFER_EVENTS = 100;
21452
- function createDoorEventHub() {
21453
- const sequences = /* @__PURE__ */ new Map();
21454
- const registered = /* @__PURE__ */ new Set();
21455
- const every = /* @__PURE__ */ new Set();
21456
- const bySource = /* @__PURE__ */ new Map();
21457
- const deliver = (event) => {
21458
- for (const listener of every) {
21459
- listener(event);
21460
- }
21461
- for (const listener of bySource.get(event.source) ?? []) {
21462
- listener(event);
21463
- }
21464
- };
21465
- const publish = (source, payload) => {
21466
- const sequence2 = (sequences.get(source) ?? 0) + 1;
21467
- sequences.set(source, sequence2);
21468
- deliver({ source, sequence: sequence2, payload });
21469
- };
21470
- const addListener = (sources, listener) => {
21471
- if (sources === void 0) {
21472
- every.add(listener);
21473
- return () => {
21474
- every.delete(listener);
21475
- };
21476
- }
21477
- const listenersFor = (source) => {
21478
- const listeners = bySource.get(source) ?? /* @__PURE__ */ new Set();
21479
- bySource.set(source, listeners);
21480
- return listeners;
21481
- };
21482
- const detachers = sources.map((source) => {
21483
- const listeners = listenersFor(source);
21484
- listeners.add(listener);
21485
- return () => {
21486
- listeners.delete(listener);
21487
- if (listeners.size === 0) {
21488
- bySource.delete(source);
21489
- }
21490
- };
21491
- });
21492
- return () => {
21493
- for (const detach of detachers) {
21494
- detach();
21495
- }
21496
- };
21497
- };
21498
- return {
21499
- publisher: (source) => {
21500
- registered.add(source);
21501
- return {
21502
- source,
21503
- publish: (payload) => {
21504
- publish(source, payload);
21505
- }
21506
- };
21507
- },
21508
- subscribe: addListener,
21509
- stream: (sources) => {
21510
- const queue = [];
21511
- let wake;
21512
- let closed = false;
21513
- const detach = addListener(sources, (event) => {
21514
- if (queue.length >= DOOR_EVENT_BUFFER_EVENTS) {
21515
- queue.shift();
21516
- }
21517
- queue.push(event);
21518
- wake?.();
21519
- });
21520
- return {
21521
- next: async () => {
21522
- for (; ; ) {
21523
- const event = queue.shift();
21524
- if (event !== void 0) {
21525
- return { value: event, done: false };
21526
- }
21527
- if (closed) {
21528
- return { value: void 0, done: true };
21529
- }
21530
- await new Promise((resolve) => {
21531
- wake = resolve;
21532
- });
21533
- }
21534
- },
21535
- close: () => {
21536
- closed = true;
21537
- detach();
21538
- wake?.();
21539
- }
21540
- };
21541
- },
21542
- sources: () => [...registered].sort()
21543
- };
21544
- }
21545
- function rcFanoutOnDoorHub(fanout, hub) {
21546
- const publisher = hub.publisher(DOOR_EVENT_SOURCE_RC);
21547
- return {
21548
- publish: (event) => {
21549
- fanout.publish(event);
21550
- publisher.publish(event);
21551
- },
21552
- subscribe: (session, listener) => fanout.subscribe(session, listener)
21553
- };
21554
- }
21555
-
21556
21889
  // src/frontdoor/launchEvents.ts
21557
21890
  function createLaunchEventPublisher(hub, now) {
21558
21891
  const publisher = hub.publisher(LAUNCH_EVENT_SOURCE);
@@ -23500,7 +23833,7 @@ init_poolPick();
23500
23833
 
23501
23834
  // src/agents/read.ts
23502
23835
  var import_node_path46 = __toESM(require("node:path"), 1);
23503
- var import_zod40 = require("zod");
23836
+ var import_zod41 = require("zod");
23504
23837
  var PROJECTS_DIR = "projects";
23505
23838
  var TASKS_DIR = "tasks";
23506
23839
  var SUBAGENTS_DIR = "subagents";
@@ -23619,14 +23952,14 @@ function parseJson2(text) {
23619
23952
  return void 0;
23620
23953
  }
23621
23954
  }
23622
- var TaskFileSchema = import_zod40.z.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: import_zod40.z.array(import_zod40.z.string()).default([]), blockedBy: import_zod40.z.array(import_zod40.z.string()).default([]) });
23623
- var WorkflowRunFileSchema = import_zod40.z.object({
23624
- runId: import_zod40.z.string(),
23625
- workflowName: import_zod40.z.string().optional(),
23626
- status: import_zod40.z.string().optional(),
23627
- startTime: import_zod40.z.number().optional(),
23628
- phases: import_zod40.z.array(import_zod40.z.object({ title: import_zod40.z.string() })).default([]),
23629
- summary: import_zod40.z.string().optional()
23955
+ var TaskFileSchema = import_zod41.z.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: import_zod41.z.array(import_zod41.z.string()).default([]), blockedBy: import_zod41.z.array(import_zod41.z.string()).default([]) });
23956
+ var WorkflowRunFileSchema = import_zod41.z.object({
23957
+ runId: import_zod41.z.string(),
23958
+ workflowName: import_zod41.z.string().optional(),
23959
+ status: import_zod41.z.string().optional(),
23960
+ startTime: import_zod41.z.number().optional(),
23961
+ phases: import_zod41.z.array(import_zod41.z.object({ title: import_zod41.z.string() })).default([]),
23962
+ summary: import_zod41.z.string().optional()
23630
23963
  });
23631
23964
  function summariseSession(fs17, configDir, ref) {
23632
23965
  const sessionRelative = import_node_path46.default.join(PROJECTS_DIR, ref.project, ref.entry);
@@ -24134,6 +24467,7 @@ init_ownCli();
24134
24467
  RC_IDLE_EXPIRY_MS,
24135
24468
  RC_ORPC_PATH_PREFIX,
24136
24469
  RC_PENDING_DEADLINE_MS,
24470
+ RC_PENDING_RETIRE_REASONS,
24137
24471
  RC_PERMISSION_MODES,
24138
24472
  RC_READ_FILE_ENCODINGS,
24139
24473
  RC_REQUEST_PARSE_CAP_BYTES,
@@ -24145,6 +24479,8 @@ init_ownCli();
24145
24479
  RC_SELF_HOST_SCOPE_LIST,
24146
24480
  RC_SELF_HOST_WORKER_JWT_TTL_SECONDS,
24147
24481
  RC_SESSIONS_PATH_PREFIX,
24482
+ RC_SESSION_END_REASONS,
24483
+ RC_SESSION_EVENT_LOG_CAPACITY,
24148
24484
  RC_STREAM_BACKOFF_MS,
24149
24485
  RC_WEB_FETCH_ALLOW_PRIVATE_ENV,
24150
24486
  RC_WEB_FETCH_DEADLINE_MS,
@@ -24155,6 +24491,13 @@ init_ownCli();
24155
24491
  RcPermissionModeSchema,
24156
24492
  RcRateLimitInfoSchema,
24157
24493
  RcRateLimitWindowSchema,
24494
+ RcSessionEventCursorExpiredError,
24495
+ RcSessionEventSchema,
24496
+ RcSessionEventsPageInputSchema,
24497
+ RcSessionEventsReadInputSchema,
24498
+ RcSessionEventsReadOutputSchema,
24499
+ RcSessionEventsStreamInputSchema,
24500
+ RcSessionTransitionSchema,
24158
24501
  RcStreamEnvelopeSchema,
24159
24502
  RcStreamEventSchema,
24160
24503
  ResetRowSchema,
@@ -24236,6 +24579,8 @@ init_ownCli();
24236
24579
  createRcEventFanout,
24237
24580
  createRcLiveUsage,
24238
24581
  createRcSelfHostSurface,
24582
+ createRcSessionEventLog,
24583
+ createRcSessionEventsApiRouter,
24239
24584
  createRcSessionTracker,
24240
24585
  createRcStreamHub,
24241
24586
  createSseParser,
@@ -24251,6 +24596,7 @@ init_ownCli();
24251
24596
  evaluateAmbientCredentialGuard,
24252
24597
  evaluateWhen,
24253
24598
  fetchThroughWebProxy,
24599
+ followRcSessionEvents,
24254
24600
  formatAmbientCredentialGuardMessage,
24255
24601
  formatCheckReport,
24256
24602
  formatDoctorReport,