claude-use 11.87.4 → 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.mjs CHANGED
@@ -5164,7 +5164,7 @@ var init_package = __esm({
5164
5164
  "package.json"() {
5165
5165
  package_default = {
5166
5166
  name: "claude-use",
5167
- version: "11.87.4",
5167
+ version: "11.88.0",
5168
5168
  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.",
5169
5169
  license: "MIT",
5170
5170
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -15056,7 +15056,7 @@ var init_identityClaude = __esm({
15056
15056
  });
15057
15057
 
15058
15058
  // src/usage/providerQuota.ts
15059
- import { z as z41 } from "zod";
15059
+ import { z as z42 } from "zod";
15060
15060
  var MS_PER_SECOND9, SECONDS_PER_HOUR3, HOURS_PER_DAY6, DAYS_PER_MONTH, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZaiLimitSchema, ZaiResponseSchema, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, ANTIGRAVITY_HOST, ANTIGRAVITY_QUOTA_URL, ANTIGRAVITY_USER_URL, FIVE_HOURS2, DAYS_PER_WEEK2, FIVE_HOURS_MS, WEEK_MS, AntigravityBucketSchema, AntigravitySummarySchema, GoogleTokenInfoSchema, AntigravityUserSchema;
15061
15061
  var init_providerQuota = __esm({
15062
15062
  "src/usage/providerQuota.ts"() {
@@ -15075,35 +15075,35 @@ var init_providerQuota = __esm({
15075
15075
  [ZAI_UNIT_HOURS, SECONDS_PER_HOUR3 * MS_PER_SECOND9],
15076
15076
  [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9]
15077
15077
  ]);
15078
- ZaiLimitSchema = z41.object({
15079
- type: z41.string(),
15080
- unit: z41.number().int(),
15081
- number: z41.number().int().positive(),
15082
- percentage: z41.number().nonnegative(),
15083
- nextResetTime: z41.number().positive().optional(),
15084
- usage: z41.number().nonnegative().optional(),
15085
- currentValue: z41.number().nonnegative().optional(),
15086
- remaining: z41.number().nonnegative().optional()
15078
+ ZaiLimitSchema = z42.object({
15079
+ type: z42.string(),
15080
+ unit: z42.number().int(),
15081
+ number: z42.number().int().positive(),
15082
+ percentage: z42.number().nonnegative(),
15083
+ nextResetTime: z42.number().positive().optional(),
15084
+ usage: z42.number().nonnegative().optional(),
15085
+ currentValue: z42.number().nonnegative().optional(),
15086
+ remaining: z42.number().nonnegative().optional()
15087
15087
  });
15088
- ZaiResponseSchema = z41.object({
15089
- success: z41.boolean(),
15090
- msg: z41.string().optional(),
15091
- data: z41.object({ level: z41.string().optional(), limits: z41.array(ZaiLimitSchema) })
15088
+ ZaiResponseSchema = z42.object({
15089
+ success: z42.boolean(),
15090
+ msg: z42.string().optional(),
15091
+ data: z42.object({ level: z42.string().optional(), limits: z42.array(ZaiLimitSchema) })
15092
15092
  });
15093
15093
  OPENROUTER_HOST = "openrouter.ai";
15094
15094
  OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
15095
15095
  OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
15096
15096
  MS_PER_DAY2 = HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15097
- OpenRouterKeySchema = z41.object({
15098
- data: z41.object({
15099
- limit: z41.number().nonnegative().nullable(),
15100
- limit_remaining: z41.number().nullable(),
15101
- limit_reset: z41.string().nullable(),
15102
- is_free_tier: z41.boolean().optional(),
15103
- free_model_daily_requests: z41.object({ used: z41.number().nonnegative(), limit: z41.number().nonnegative(), remaining: z41.number() }).optional()
15097
+ OpenRouterKeySchema = z42.object({
15098
+ data: z42.object({
15099
+ limit: z42.number().nonnegative().nullable(),
15100
+ limit_remaining: z42.number().nullable(),
15101
+ limit_reset: z42.string().nullable(),
15102
+ is_free_tier: z42.boolean().optional(),
15103
+ free_model_daily_requests: z42.object({ used: z42.number().nonnegative(), limit: z42.number().nonnegative(), remaining: z42.number() }).optional()
15104
15104
  })
15105
15105
  });
15106
- OpenRouterCreditsSchema = z41.object({ data: z41.object({ total_credits: z41.number().nonnegative(), total_usage: z41.number().nonnegative() }) });
15106
+ OpenRouterCreditsSchema = z42.object({ data: z42.object({ total_credits: z42.number().nonnegative(), total_usage: z42.number().nonnegative() }) });
15107
15107
  ANTIGRAVITY_HOST = "daily-cloudcode-pa.googleapis.com";
15108
15108
  ANTIGRAVITY_QUOTA_URL = `https://${ANTIGRAVITY_HOST}/v1internal:retrieveUserQuotaSummary`;
15109
15109
  ANTIGRAVITY_USER_URL = `https://${ANTIGRAVITY_HOST}/v1internal:loadCodeAssist`;
@@ -15111,21 +15111,21 @@ var init_providerQuota = __esm({
15111
15111
  DAYS_PER_WEEK2 = 7;
15112
15112
  FIVE_HOURS_MS = FIVE_HOURS2 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15113
15113
  WEEK_MS = DAYS_PER_WEEK2 * HOURS_PER_DAY6 * SECONDS_PER_HOUR3 * MS_PER_SECOND9;
15114
- AntigravityBucketSchema = z41.object({
15115
- bucketId: z41.string(),
15116
- remainingFraction: z41.number().optional(),
15117
- resetTime: z41.string().optional()
15114
+ AntigravityBucketSchema = z42.object({
15115
+ bucketId: z42.string(),
15116
+ remainingFraction: z42.number().optional(),
15117
+ resetTime: z42.string().optional()
15118
15118
  });
15119
- AntigravitySummarySchema = z41.object({ groups: z41.array(z41.object({ buckets: z41.array(AntigravityBucketSchema) })) });
15120
- GoogleTokenInfoSchema = z41.object({
15121
- email: z41.string().optional(),
15122
- sub: z41.string().optional()
15119
+ AntigravitySummarySchema = z42.object({ groups: z42.array(z42.object({ buckets: z42.array(AntigravityBucketSchema) })) });
15120
+ GoogleTokenInfoSchema = z42.object({
15121
+ email: z42.string().optional(),
15122
+ sub: z42.string().optional()
15123
15123
  });
15124
- AntigravityUserSchema = z41.object({
15124
+ AntigravityUserSchema = z42.object({
15125
15125
  /** The code-assist tier context, which defaults to the free tier for every account. */
15126
- currentTier: z41.object({ name: z41.string().optional(), id: z41.string().optional() }).optional(),
15126
+ currentTier: z42.object({ name: z42.string().optional(), id: z42.string().optional() }).optional(),
15127
15127
  /** The account's paid subscription; absent when the account has none. */
15128
- paidTier: z41.object({ name: z41.string().optional(), id: z41.string().optional() }).optional()
15128
+ paidTier: z42.object({ name: z42.string().optional(), id: z42.string().optional() }).optional()
15129
15129
  });
15130
15130
  }
15131
15131
  });
@@ -15640,30 +15640,60 @@ function parseRcRequestBody(kind, body) {
15640
15640
  }
15641
15641
  function createRcSessionTracker(deps) {
15642
15642
  const entries = /* @__PURE__ */ new Map();
15643
- const expire = (id) => {
15643
+ const retirePending = (entry, requestId, reason) => {
15644
+ if (entry.pending.delete(requestId)) {
15645
+ entry.retired.set(requestId, deps.now());
15646
+ deps.onTransition?.({ kind: "pending-retired", session: entry.id, requestId, reason, at: deps.now() });
15647
+ }
15648
+ };
15649
+ const addPending = (entry, pending) => {
15650
+ if (entry.retired.has(pending.requestId)) {
15651
+ return;
15652
+ }
15653
+ const born = !entry.pending.has(pending.requestId);
15654
+ entry.pending.set(pending.requestId, pending);
15655
+ if (born) {
15656
+ deps.onTransition?.({ kind: "pending-born", session: entry.id, requestId: pending.requestId, type: pending.type, summary: pending.summary, at: pending.observedAt });
15657
+ }
15658
+ };
15659
+ const expire = (id, reason) => {
15660
+ const entry = entries.get(id);
15661
+ if (entry === void 0) {
15662
+ return;
15663
+ }
15664
+ for (const requestId of [...entry.pending.keys()]) {
15665
+ retirePending(entry, requestId, "session-ended");
15666
+ }
15644
15667
  entries.delete(id);
15668
+ deps.onTransition?.({ kind: "session-ended", session: id, reason, at: deps.now() });
15645
15669
  };
15646
15670
  const expirePendings = (entry, now) => {
15647
15671
  for (const [requestId, pending] of entry.pending) {
15648
15672
  if (now - pending.observedAt >= RC_PENDING_DEADLINE_MS) {
15649
- entry.pending.delete(requestId);
15673
+ retirePending(entry, requestId, "expired");
15674
+ }
15675
+ }
15676
+ for (const [requestId, retiredAt] of entry.retired) {
15677
+ if (now - retiredAt >= RC_PENDING_DEADLINE_MS) {
15678
+ entry.retired.delete(requestId);
15650
15679
  }
15651
15680
  }
15652
15681
  };
15653
15682
  const sweep = () => {
15654
15683
  for (const [id, entry] of entries) {
15655
15684
  if (deps.now() - entry.lastSeenAt >= deps.idleMs) {
15656
- expire(id);
15685
+ expire(id, "expired");
15657
15686
  continue;
15658
15687
  }
15659
15688
  expirePendings(entry, deps.now());
15660
15689
  }
15661
15690
  };
15662
- const timer = setInterval(sweep, deps.idleMs);
15691
+ const timer = setInterval(sweep, Math.min(deps.idleMs, RC_PENDING_DEADLINE_MS));
15663
15692
  timer.unref();
15664
15693
  const birth = (id, facts) => {
15665
- 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() };
15694
+ 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() };
15666
15695
  entries.set(id, record);
15696
+ deps.onTransition?.({ kind: "session-appeared", session: id, at: record.createdAt });
15667
15697
  return record;
15668
15698
  };
15669
15699
  const persistCredential = (entry) => {
@@ -15671,6 +15701,13 @@ function createRcSessionTracker(deps) {
15671
15701
  deps.credentialStore?.write(entry.id, { authorization: entry.oauthAuthorization, anthropicVersion: entry.anthropicVersion, anthropicClientPlatform: entry.anthropicClientPlatform });
15672
15702
  }
15673
15703
  };
15704
+ const refresh = (entry, facts) => {
15705
+ entry.lastSeenAt = deps.now();
15706
+ entry.oauthAuthorization = facts.oauthAuthorization ?? entry.oauthAuthorization;
15707
+ entry.anthropicVersion = facts.anthropicVersion ?? entry.anthropicVersion;
15708
+ entry.anthropicClientPlatform = facts.anthropicClientPlatform ?? entry.anthropicClientPlatform;
15709
+ persistCredential(entry);
15710
+ };
15674
15711
  const observeExchange = (request4) => {
15675
15712
  const method = (request4.method ?? "").toUpperCase();
15676
15713
  if (!isRcSessionExchange(request4.url)) {
@@ -15709,7 +15746,12 @@ function createRcSessionTracker(deps) {
15709
15746
  if (id2 === void 0) {
15710
15747
  return;
15711
15748
  }
15712
- persistCredential(birth(id2, facts));
15749
+ const existing = entries.get(id2);
15750
+ if (existing === void 0) {
15751
+ persistCredential(birth(id2, facts));
15752
+ return;
15753
+ }
15754
+ refresh(existing, facts);
15713
15755
  }
15714
15756
  };
15715
15757
  }
@@ -15718,12 +15760,10 @@ function createRcSessionTracker(deps) {
15718
15760
  if (id?.startsWith(RC_SESSION_ID_PREFIX) !== true) {
15719
15761
  return void 0;
15720
15762
  }
15721
- const entry = entries.get(id) ?? birth(id, facts);
15722
- entry.lastSeenAt = deps.now();
15723
- entry.oauthAuthorization = facts.oauthAuthorization ?? entry.oauthAuthorization;
15724
- entry.anthropicVersion = facts.anthropicVersion ?? entry.anthropicVersion;
15725
- entry.anthropicClientPlatform = facts.anthropicClientPlatform ?? entry.anthropicClientPlatform;
15726
- persistCredential(entry);
15763
+ const tracked = entries.get(id);
15764
+ if (tracked !== void 0) {
15765
+ refresh(tracked, facts);
15766
+ }
15727
15767
  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;
15728
15768
  let chunks = [];
15729
15769
  let buffered = 0;
@@ -15744,10 +15784,10 @@ function createRcSessionTracker(deps) {
15744
15784
  }
15745
15785
  const now = deps.now();
15746
15786
  for (const controlRequest of factsOfBody.controlRequests) {
15747
- entryNow.pending.set(controlRequest.requestId, { sessionId: id, ...controlRequest, observedAt: now });
15787
+ addPending(entryNow, { sessionId: id, ...controlRequest, observedAt: now });
15748
15788
  }
15749
15789
  for (const requestId of factsOfBody.answeredRequestIds) {
15750
- entryNow.pending.delete(requestId);
15790
+ retirePending(entryNow, requestId, "answered");
15751
15791
  }
15752
15792
  for (const payload of factsOfBody.payloads) {
15753
15793
  entryNow.liveTasks = applyAgentTaskEvent(entryNow.liveTasks, id, payload, now);
@@ -15756,7 +15796,11 @@ function createRcSessionTracker(deps) {
15756
15796
  entryNow.workerIdleSeconds = { value: factsOfBody.idleSeconds, observedAt: now };
15757
15797
  }
15758
15798
  if (factsOfBody.workerStatus !== void 0) {
15799
+ const previous = entryNow.workerState?.value;
15759
15800
  entryNow.workerState = { value: factsOfBody.workerStatus, observedAt: now };
15801
+ if (previous !== factsOfBody.workerStatus) {
15802
+ deps.onTransition?.({ kind: "worker-state", session: id, state: factsOfBody.workerStatus, ...previous === void 0 ? {} : { previous }, at: now });
15803
+ }
15760
15804
  }
15761
15805
  };
15762
15806
  const archiving = method === "POST" && rest === `${id}/archive`;
@@ -15781,10 +15825,13 @@ function createRcSessionTracker(deps) {
15781
15825
  onResponse: (status, headers) => {
15782
15826
  if (singleHeader(headers, CONFLICT_REASON_HEADER) !== void 0 || archiving && isSuccessful(status)) {
15783
15827
  deps.credentialStore?.remove(id);
15784
- expire(id);
15828
+ expire(id, singleHeader(headers, CONFLICT_REASON_HEADER) === void 0 ? "archived" : "conflict");
15785
15829
  return;
15786
15830
  }
15787
15831
  accepted = isSuccessful(status);
15832
+ if (accepted && !entries.has(id)) {
15833
+ persistCredential(birth(id, facts));
15834
+ }
15788
15835
  file();
15789
15836
  },
15790
15837
  onBodyChunk: () => {
@@ -15849,12 +15896,12 @@ function createRcSessionTracker(deps) {
15849
15896
  const pending = pendingOfControlRequestPayload(event.payload);
15850
15897
  if (pending !== void 0) {
15851
15898
  if (event.source === RC_STREAM_WORKER_SOURCE) {
15852
- entry.pending.set(pending.requestId, { sessionId, ...pending, observedAt: deps.now() });
15899
+ addPending(entry, { sessionId, ...pending, observedAt: deps.now() });
15853
15900
  }
15854
15901
  return;
15855
15902
  }
15856
15903
  for (const requestId of answeredRequestIdsOfControlResponsePayload(event.payload)) {
15857
- entry.pending.delete(requestId);
15904
+ retirePending(entry, requestId, "answered");
15858
15905
  }
15859
15906
  },
15860
15907
  liveTasksOf: (sessionId) => {
@@ -15862,10 +15909,14 @@ function createRcSessionTracker(deps) {
15862
15909
  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)));
15863
15910
  },
15864
15911
  completePending: (sessionId, requestId) => {
15865
- entries.get(sessionId)?.pending.delete(requestId);
15912
+ const entry = entries.get(sessionId);
15913
+ if (entry !== void 0) {
15914
+ retirePending(entry, requestId, "answered");
15915
+ }
15866
15916
  },
15867
15917
  close: () => {
15868
15918
  clearInterval(timer);
15919
+ deps.onClose?.();
15869
15920
  }
15870
15921
  };
15871
15922
  }
@@ -17945,8 +17996,8 @@ init_cliError();
17945
17996
  init_realPorts();
17946
17997
 
17947
17998
  // src/frontdoor/controlApi.ts
17948
- import { createORPCClient as createORPCClient2, ORPCError as ORPCError7 } from "@orpc/client";
17949
- import { openapi as openapi8 } from "@orpc/openapi";
17999
+ import { createORPCClient as createORPCClient2, ORPCError as ORPCError8 } from "@orpc/client";
18000
+ import { openapi as openapi9 } from "@orpc/openapi";
17950
18001
 
17951
18002
  // src/checkReport.ts
17952
18003
  init_cliError();
@@ -20847,6 +20898,381 @@ function createAgentTreesApiRouter(deps) {
20847
20898
  };
20848
20899
  }
20849
20900
 
20901
+ // src/frontdoor/rcEventLogApi.ts
20902
+ import { ORPCError as ORPCError7 } from "@orpc/client";
20903
+ import { openapi as openapi8 } from "@orpc/openapi";
20904
+ import { eventIterator as eventIterator3, withEventMeta as withEventMeta3 } from "@orpc/server";
20905
+
20906
+ // src/frontdoor/rcEventLog.ts
20907
+ import { z as z40 } from "zod";
20908
+
20909
+ // src/frontdoor/eventHub.ts
20910
+ var DOOR_EVENT_BUFFER_EVENTS = 100;
20911
+ function createDoorEventHub() {
20912
+ const sequences = /* @__PURE__ */ new Map();
20913
+ const registered = /* @__PURE__ */ new Set();
20914
+ const every = /* @__PURE__ */ new Set();
20915
+ const bySource = /* @__PURE__ */ new Map();
20916
+ const deliver = (event) => {
20917
+ for (const listener of every) {
20918
+ listener(event);
20919
+ }
20920
+ for (const listener of bySource.get(event.source) ?? []) {
20921
+ listener(event);
20922
+ }
20923
+ };
20924
+ const publish = (source, payload) => {
20925
+ const sequence2 = (sequences.get(source) ?? 0) + 1;
20926
+ sequences.set(source, sequence2);
20927
+ deliver({ source, sequence: sequence2, payload });
20928
+ };
20929
+ const addListener = (sources, listener) => {
20930
+ if (sources === void 0) {
20931
+ every.add(listener);
20932
+ return () => {
20933
+ every.delete(listener);
20934
+ };
20935
+ }
20936
+ const listenersFor = (source) => {
20937
+ const listeners = bySource.get(source) ?? /* @__PURE__ */ new Set();
20938
+ bySource.set(source, listeners);
20939
+ return listeners;
20940
+ };
20941
+ const detachers = sources.map((source) => {
20942
+ const listeners = listenersFor(source);
20943
+ listeners.add(listener);
20944
+ return () => {
20945
+ listeners.delete(listener);
20946
+ if (listeners.size === 0) {
20947
+ bySource.delete(source);
20948
+ }
20949
+ };
20950
+ });
20951
+ return () => {
20952
+ for (const detach of detachers) {
20953
+ detach();
20954
+ }
20955
+ };
20956
+ };
20957
+ return {
20958
+ publisher: (source) => {
20959
+ registered.add(source);
20960
+ return {
20961
+ source,
20962
+ publish: (payload) => {
20963
+ publish(source, payload);
20964
+ }
20965
+ };
20966
+ },
20967
+ subscribe: addListener,
20968
+ stream: (sources) => {
20969
+ const queue = [];
20970
+ let wake;
20971
+ let closed = false;
20972
+ const detach = addListener(sources, (event) => {
20973
+ if (queue.length >= DOOR_EVENT_BUFFER_EVENTS) {
20974
+ queue.shift();
20975
+ }
20976
+ queue.push(event);
20977
+ wake?.();
20978
+ });
20979
+ return {
20980
+ next: async () => {
20981
+ for (; ; ) {
20982
+ const event = queue.shift();
20983
+ if (event !== void 0) {
20984
+ return { value: event, done: false };
20985
+ }
20986
+ if (closed) {
20987
+ return { value: void 0, done: true };
20988
+ }
20989
+ await new Promise((resolve) => {
20990
+ wake = resolve;
20991
+ });
20992
+ }
20993
+ },
20994
+ close: () => {
20995
+ closed = true;
20996
+ detach();
20997
+ wake?.();
20998
+ }
20999
+ };
21000
+ },
21001
+ sources: () => [...registered].sort()
21002
+ };
21003
+ }
21004
+ function rcFanoutOnDoorHub(fanout, hub) {
21005
+ const publisher = hub.publisher(DOOR_EVENT_SOURCE_RC);
21006
+ return {
21007
+ publish: (event) => {
21008
+ fanout.publish(event);
21009
+ publisher.publish(event);
21010
+ },
21011
+ subscribe: (session, listener) => fanout.subscribe(session, listener)
21012
+ };
21013
+ }
21014
+
21015
+ // src/frontdoor/rcEventLog.ts
21016
+ var RC_SESSION_EVENT_TOKEN_MAX_CHARS = 255;
21017
+ var HIGH_SURROGATE_FIRST = 55296;
21018
+ var HIGH_SURROGATE_LAST = 56319;
21019
+ var LOW_SURROGATE_FIRST = 56320;
21020
+ var LOW_SURROGATE_LAST = 57343;
21021
+ var CUT_MARKER = "...";
21022
+ var RC_SESSION_EVENT_SUMMARY_MAX_CHARS = RC_SESSION_EVENT_TOKEN_MAX_CHARS + " ".length + RC_PENDING_SUMMARY_EXCERPT_CHARS + CUT_MARKER.length;
21023
+ var RC_SESSION_EVENT_GENERATION_MAX_CHARS = "00000000-0000-4000-8000-000000000000".length;
21024
+ var SEQUENCE_MAX_DIGITS = String(Number.MAX_SAFE_INTEGER).length;
21025
+ var NUMBER_BYTES = Float64Array.BYTES_PER_ELEMENT;
21026
+ var NUMBER_FIELDS = ["at", "sequence"].length;
21027
+ var BYTES_PER_CODE_UNIT = Uint16Array.BYTES_PER_ELEMENT;
21028
+ var RC_SESSION_END_REASONS = ["expired", "archived", "conflict"];
21029
+ var RC_PENDING_RETIRE_REASONS = ["answered", "expired", "session-ended"];
21030
+ var transitionBase = { session: z40.string(), at: z40.number() };
21031
+ var cursorFields = { cursor: z40.string(), sequence: z40.int().positive() };
21032
+ var sessionAppearedShape = { kind: z40.literal("session-appeared"), ...transitionBase };
21033
+ var sessionEndedShape = { kind: z40.literal("session-ended"), reason: z40.enum(RC_SESSION_END_REASONS), ...transitionBase };
21034
+ var workerStateShape = { kind: z40.literal("worker-state"), state: z40.string(), previous: z40.string().optional(), ...transitionBase };
21035
+ var pendingBornShape = { kind: z40.literal("pending-born"), requestId: z40.string(), type: z40.string(), summary: z40.string(), ...transitionBase };
21036
+ var pendingRetiredShape = { kind: z40.literal("pending-retired"), requestId: z40.string(), reason: z40.enum(RC_PENDING_RETIRE_REASONS), ...transitionBase };
21037
+ var RcSessionTransitionSchema = z40.discriminatedUnion("kind", [
21038
+ z40.strictObject(sessionAppearedShape),
21039
+ z40.strictObject(sessionEndedShape),
21040
+ z40.strictObject(workerStateShape),
21041
+ z40.strictObject(pendingBornShape),
21042
+ z40.strictObject(pendingRetiredShape)
21043
+ ]);
21044
+ var KIND_MAX_CHARS = Math.max(...RcSessionTransitionSchema.options.map((option) => option.shape.kind.value.length));
21045
+ 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;
21046
+ var RC_SESSION_EVENT_LOG_CAPACITY = Math.floor(CONTROL_BODY_CAP_BYTES / RC_SESSION_EVENT_MAX_BYTES);
21047
+ var RcSessionEventSchema = z40.discriminatedUnion("kind", [
21048
+ z40.strictObject({ ...cursorFields, ...sessionAppearedShape }),
21049
+ z40.strictObject({ ...cursorFields, ...sessionEndedShape }),
21050
+ z40.strictObject({ ...cursorFields, ...workerStateShape }),
21051
+ z40.strictObject({ ...cursorFields, ...pendingBornShape }),
21052
+ z40.strictObject({ ...cursorFields, ...pendingRetiredShape })
21053
+ ]);
21054
+ var RcSessionEventsReadInputSchema = z40.strictObject({
21055
+ /** The cursor of the last event the caller saw; every retained event when omitted. */
21056
+ since: z40.string().min(1).optional(),
21057
+ /** One `cse_` session id; every session when omitted. */
21058
+ session: z40.string().min(1).optional(),
21059
+ /** The most events one answer carries; every event after `since` when omitted. */
21060
+ limit: z40.int().positive().optional()
21061
+ });
21062
+ var RcSessionEventsPageInputSchema = RcSessionEventsReadInputSchema.extend({
21063
+ /** 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. */
21064
+ limit: z40.int().positive().max(DOOR_EVENT_BUFFER_EVENTS).default(DOOR_EVENT_BUFFER_EVENTS)
21065
+ });
21066
+ var RcSessionEventsStreamInputSchema = RcSessionEventsReadInputSchema.omit({ limit: true });
21067
+ var RcSessionEventsReadOutputSchema = z40.discriminatedUnion("status", [
21068
+ z40.strictObject({ status: z40.literal("ok"), events: z40.readonly(z40.array(RcSessionEventSchema)), cursor: z40.string(), more: z40.boolean(), head: z40.string() }),
21069
+ z40.strictObject({ status: z40.literal("expired"), message: z40.string(), head: z40.string() })
21070
+ ]);
21071
+ var CURSOR_SEPARATOR = ".";
21072
+ 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";
21073
+ function cursorOf(generation, sequence2) {
21074
+ return `${generation}${CURSOR_SEPARATOR}${String(sequence2)}`;
21075
+ }
21076
+ function parseCursor(cursor) {
21077
+ const at = cursor.lastIndexOf(CURSOR_SEPARATOR);
21078
+ if (at <= 0) {
21079
+ return void 0;
21080
+ }
21081
+ const digits = cursor.slice(at + 1);
21082
+ if (!/^[0-9]+$/.test(digits)) {
21083
+ return void 0;
21084
+ }
21085
+ return { generation: cursor.slice(0, at), sequence: Number(digits) };
21086
+ }
21087
+ function codePointBoundary(text, at) {
21088
+ const before = text.charCodeAt(at - 1);
21089
+ const after = text.charCodeAt(at);
21090
+ const isHigh = before >= HIGH_SURROGATE_FIRST && before <= HIGH_SURROGATE_LAST;
21091
+ const isLow = after >= LOW_SURROGATE_FIRST && after <= LOW_SURROGATE_LAST;
21092
+ return isHigh && isLow ? at - 1 : at;
21093
+ }
21094
+ function bounded2(text, maxChars) {
21095
+ const kept = text.length <= maxChars ? text : `${text.slice(0, codePointBoundary(text, maxChars - CUT_MARKER.length))}${CUT_MARKER}`;
21096
+ return Buffer.from(kept, "utf16le").toString("utf16le");
21097
+ }
21098
+ function boundedTransition(transition) {
21099
+ const session = bounded2(transition.session, RC_SESSION_EVENT_TOKEN_MAX_CHARS);
21100
+ if (transition.kind === "worker-state") {
21101
+ 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) } };
21102
+ }
21103
+ if (transition.kind === "pending-born") {
21104
+ 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) };
21105
+ }
21106
+ if (transition.kind === "pending-retired") {
21107
+ return { ...transition, session, requestId: bounded2(transition.requestId, RC_SESSION_EVENT_TOKEN_MAX_CHARS) };
21108
+ }
21109
+ return { ...transition, session };
21110
+ }
21111
+ function createRcSessionEventLog(deps) {
21112
+ if (deps.generation.includes(CURSOR_SEPARATOR)) {
21113
+ throw new Error(`a door generation id must not contain "${CURSOR_SEPARATOR}", which separates a cursor's generation from its sequence`);
21114
+ }
21115
+ if (deps.generation.length > RC_SESSION_EVENT_GENERATION_MAX_CHARS) {
21116
+ throw new Error(`a door generation id must be at most ${String(RC_SESSION_EVENT_GENERATION_MAX_CHARS)} characters, a UUID's length`);
21117
+ }
21118
+ const events = [];
21119
+ let lastSequence = 0;
21120
+ const listeners = /* @__PURE__ */ new Set();
21121
+ let isClosed = false;
21122
+ const expired = (reason) => ({ status: "expired", message: `${reason}; ${RESYNC_ADVICE}`, head: cursorOf(deps.generation, lastSequence) });
21123
+ return {
21124
+ append: (transition) => {
21125
+ lastSequence += 1;
21126
+ events.push({ ...boundedTransition(transition), cursor: cursorOf(deps.generation, lastSequence), sequence: lastSequence });
21127
+ if (events.length > deps.capacity) {
21128
+ events.splice(0, events.length - deps.capacity);
21129
+ }
21130
+ for (const listener of listeners) {
21131
+ listener();
21132
+ }
21133
+ },
21134
+ head: () => cursorOf(deps.generation, lastSequence),
21135
+ read: ({ since, session, limit }) => {
21136
+ let after = 0;
21137
+ if (since !== void 0) {
21138
+ const parsed = parseCursor(since);
21139
+ if (parsed === void 0) {
21140
+ return expired(`"${since}" is not a cursor this door issues`);
21141
+ }
21142
+ if (parsed.generation !== deps.generation) {
21143
+ return expired(`the cursor "${since}" was issued by another generation of the front door, whose events this one never held`);
21144
+ }
21145
+ if (parsed.sequence > lastSequence) {
21146
+ return expired(`the cursor "${since}" names an event past this door's newest`);
21147
+ }
21148
+ const oldest = events[0]?.sequence ?? lastSequence + 1;
21149
+ if (parsed.sequence < oldest - 1) {
21150
+ 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)}")`);
21151
+ }
21152
+ after = parsed.sequence;
21153
+ }
21154
+ const selected2 = [];
21155
+ let cursor = cursorOf(deps.generation, lastSequence);
21156
+ let more = false;
21157
+ for (const event of events) {
21158
+ if (event.sequence <= after || session !== void 0 && event.session !== session) {
21159
+ continue;
21160
+ }
21161
+ if (limit !== void 0 && selected2.length === limit) {
21162
+ more = true;
21163
+ cursor = selected2.at(-1)?.cursor ?? cursor;
21164
+ break;
21165
+ }
21166
+ selected2.push(event);
21167
+ }
21168
+ return { status: "ok", events: selected2, cursor, more, head: cursorOf(deps.generation, lastSequence) };
21169
+ },
21170
+ onAppend: (listener) => {
21171
+ listeners.add(listener);
21172
+ return () => {
21173
+ listeners.delete(listener);
21174
+ };
21175
+ },
21176
+ close: () => {
21177
+ if (isClosed) {
21178
+ return;
21179
+ }
21180
+ isClosed = true;
21181
+ for (const listener of listeners) {
21182
+ listener();
21183
+ }
21184
+ },
21185
+ closed: () => isClosed
21186
+ };
21187
+ }
21188
+ var RcSessionEventCursorExpiredError = class extends Error {
21189
+ /** 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. */
21190
+ head;
21191
+ constructor(message, head) {
21192
+ super(message);
21193
+ this.name = "RcSessionEventCursorExpiredError";
21194
+ this.head = head;
21195
+ }
21196
+ };
21197
+ function followRcSessionEvents(log, input, signal) {
21198
+ return followAfter(log, input.since ?? log.head(), input.session, signal);
21199
+ }
21200
+ async function* followAfter(log, since, session, signal) {
21201
+ let cursor = since;
21202
+ let onAbort = () => void 0;
21203
+ const aborted = new Promise((resolve) => {
21204
+ onAbort = resolve;
21205
+ });
21206
+ signal?.addEventListener("abort", onAbort, { once: true });
21207
+ try {
21208
+ for (; ; ) {
21209
+ signal?.throwIfAborted();
21210
+ const closedBeforeRead = log.closed();
21211
+ let detach = () => void 0;
21212
+ const woken = new Promise((resolve) => {
21213
+ detach = log.onAppend(resolve);
21214
+ });
21215
+ try {
21216
+ const read = log.read({ since: cursor, ...session === void 0 ? {} : { session } });
21217
+ if (read.status === "expired") {
21218
+ throw new RcSessionEventCursorExpiredError(read.message, read.head);
21219
+ }
21220
+ if (read.events.length === 0) {
21221
+ cursor = read.cursor;
21222
+ if (closedBeforeRead) {
21223
+ return;
21224
+ }
21225
+ await Promise.race([woken, aborted]);
21226
+ continue;
21227
+ }
21228
+ for (const event of read.events) {
21229
+ yield event;
21230
+ cursor = event.cursor;
21231
+ }
21232
+ cursor = read.cursor;
21233
+ } finally {
21234
+ detach();
21235
+ }
21236
+ }
21237
+ } finally {
21238
+ signal?.removeEventListener("abort", onAbort);
21239
+ }
21240
+ }
21241
+
21242
+ // src/frontdoor/rcEventLogApi.ts
21243
+ var RC_API_TAG2 = "remote-control";
21244
+ var CURSOR_EXPIRED_CODE = "GONE";
21245
+ async function* sseOf(follower) {
21246
+ try {
21247
+ for await (const event of follower) {
21248
+ yield withEventMeta3(event, { id: event.cursor });
21249
+ }
21250
+ } catch (error) {
21251
+ if (error instanceof RcSessionEventCursorExpiredError) {
21252
+ throw new ORPCError7(CURSOR_EXPIRED_CODE, { message: error.message, data: { head: error.head } });
21253
+ }
21254
+ throw error;
21255
+ }
21256
+ }
21257
+ function createRcSessionEventsApiRouter(deps) {
21258
+ const authed = doorApiAuth(deps.expectedToken);
21259
+ return {
21260
+ rcSessions: {
21261
+ events: authed.meta(openapi8({ 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(eventIterator3(RcSessionEventSchema)).handler(({ input, signal, lastEventId }) => sseOf(followRcSessionEvents(deps.sessionEvents, { since: lastEventId ?? input.since, session: input.session }, signal))),
21262
+ eventsPage: authed.meta(
21263
+ openapi8({
21264
+ method: "POST",
21265
+ path: "/rest/rc/session-events/page",
21266
+ summary: "Read every observed session's state transitions, pending requests and endings after a cursor, one page at a time",
21267
+ tags: [RC_API_TAG2],
21268
+ // A POST because the page size is a number a query string cannot type, but the answer changes nothing.
21269
+ spec: (current) => ({ ...current, [READ_ONLY_OPERATION_EXTENSION]: true })
21270
+ })
21271
+ ).input(RcSessionEventsPageInputSchema).output(RcSessionEventsReadOutputSchema).handler(({ input }) => deps.sessionEvents.read(input))
21272
+ }
21273
+ };
21274
+ }
21275
+
20850
21276
  // src/frontdoor/controlApi.ts
20851
21277
  var USAGE_API_TAG = "usage";
20852
21278
  var FRONTDOOR_API_TAG2 = "frontdoor";
@@ -20857,12 +21283,12 @@ function createControlApiRouter(deps) {
20857
21283
  const authed = doorApiAuth(deps.expectedToken);
20858
21284
  return {
20859
21285
  usage: {
20860
- 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() })),
20861
- 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())),
20862
- 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 }) => {
21286
+ list: authed.meta(openapi9({ 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(openapi9({ 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(openapi9({ method: "GET", path: "/rest/usage/windows", summary: "Read one identity's effective quota windows", tags: [USAGE_API_TAG] })).input(UsageWindowsInputSchema).output(UsageWindowsOutputSchema).handler(({ input }) => {
20863
21289
  const snapshot = deps.usageSnapshotOf(input.identity);
20864
21290
  if (snapshot === void 0) {
20865
- throw new ORPCError7("NOT_FOUND", { message: `identity ${input.identity} has no usage snapshot yet, so no quota window has been observed for it` });
21291
+ throw new ORPCError8("NOT_FOUND", { message: `identity ${input.identity} has no usage snapshot yet, so no quota window has been observed for it` });
20866
21292
  }
20867
21293
  const provider = input.provider ?? ANTHROPIC_PROVIDER;
20868
21294
  const rateLimit = snapshot.providers[provider]?.rateLimit;
@@ -20876,34 +21302,34 @@ function createControlApiRouter(deps) {
20876
21302
  ...unified?.sevenDay === void 0 ? {} : { sevenDay: effectiveWindow(unified.sevenDay, now) }
20877
21303
  };
20878
21304
  }),
20879
- 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 }) => {
21305
+ live: authed.meta(openapi9({ 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 }) => {
20880
21306
  const sessions = deps.liveRateLimits(input.session);
20881
21307
  if (input.session !== void 0 && sessions.length === 0) {
20882
21308
  if (deps.list().some((session) => session.id === input.session)) {
20883
- 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` });
21309
+ throw new ORPCError8("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` });
20884
21310
  }
20885
- throw new ORPCError7("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
21311
+ throw new ORPCError8("NOT_FOUND", { message: rcSessionNotObservedMessage(input.session) });
20886
21312
  }
20887
21313
  return { latest: deps.latestRateLimit(), sessions };
20888
21314
  })
20889
21315
  },
20890
21316
  frontdoor: {
20891
- 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()),
20892
- 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 }))
21317
+ status: authed.meta(openapi9({ 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(openapi9({ 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 }))
20893
21319
  },
20894
21320
  check: {
20895
21321
  // 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.
20896
- 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)))
21322
+ run: authed.meta(openapi9({ 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)))
20897
21323
  },
20898
21324
  doctor: {
20899
- run: authed.meta(openapi8({ method: "GET", path: "/rest/doctor", summary: "Run the doctor report", tags: [DOCTOR_API_TAG] })).output(DoctorRunOutputSchema).handler(() => deps.doctorReport())
21325
+ run: authed.meta(openapi9({ method: "GET", path: "/rest/doctor", summary: "Run the doctor report", tags: [DOCTOR_API_TAG] })).output(DoctorRunOutputSchema).handler(() => deps.doctorReport())
20900
21326
  },
20901
21327
  pool: {
20902
- 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 }) => {
21328
+ pick: authed.meta(openapi9({ 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 }) => {
20903
21329
  const report = deps.poolPick(input.pool, input.path);
20904
21330
  if (report === void 0) {
20905
21331
  const live = deps.poolNames();
20906
- throw new ORPCError7("NOT_FOUND", {
21332
+ throw new ORPCError8("NOT_FOUND", {
20907
21333
  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(", ")}`
20908
21334
  });
20909
21335
  }
@@ -20915,7 +21341,7 @@ function createControlApiRouter(deps) {
20915
21341
  function createDoorApiRouter(deps) {
20916
21342
  const control = createControlApiRouter(deps);
20917
21343
  const lifecycle = createLifecycleApiRouter(deps);
20918
- return { ...createRcApiRouter(deps), ...control, ...lifecycle, ...createConfigApiRouter(deps), ...createCodexApiRouter(deps), ...createLaunchApiRouter(deps), ...createAgentTreesApiRouter(deps), ...createEventsApiRouter(deps), frontdoor: { ...control.frontdoor, ...lifecycle.frontdoor } };
21344
+ return { ...createRcApiRouter(deps), ...createRcSessionEventsApiRouter(deps), ...control, ...lifecycle, ...createConfigApiRouter(deps), ...createCodexApiRouter(deps), ...createLaunchApiRouter(deps), ...createAgentTreesApiRouter(deps), ...createEventsApiRouter(deps), frontdoor: { ...control.frontdoor, ...lifecycle.frontdoor } };
20919
21345
  }
20920
21346
  function createDoorApiNodeHandler(deps) {
20921
21347
  return doorApiNodeHandlerOf(createDoorApiRouter(deps), deps.expectedToken);
@@ -21021,112 +21447,6 @@ function formatFrontDoorStatus(status, caCertPath) {
21021
21447
  // src/index.ts
21022
21448
  init_state();
21023
21449
 
21024
- // src/frontdoor/eventHub.ts
21025
- var DOOR_EVENT_BUFFER_EVENTS = 100;
21026
- function createDoorEventHub() {
21027
- const sequences = /* @__PURE__ */ new Map();
21028
- const registered = /* @__PURE__ */ new Set();
21029
- const every = /* @__PURE__ */ new Set();
21030
- const bySource = /* @__PURE__ */ new Map();
21031
- const deliver = (event) => {
21032
- for (const listener of every) {
21033
- listener(event);
21034
- }
21035
- for (const listener of bySource.get(event.source) ?? []) {
21036
- listener(event);
21037
- }
21038
- };
21039
- const publish = (source, payload) => {
21040
- const sequence2 = (sequences.get(source) ?? 0) + 1;
21041
- sequences.set(source, sequence2);
21042
- deliver({ source, sequence: sequence2, payload });
21043
- };
21044
- const addListener = (sources, listener) => {
21045
- if (sources === void 0) {
21046
- every.add(listener);
21047
- return () => {
21048
- every.delete(listener);
21049
- };
21050
- }
21051
- const listenersFor = (source) => {
21052
- const listeners = bySource.get(source) ?? /* @__PURE__ */ new Set();
21053
- bySource.set(source, listeners);
21054
- return listeners;
21055
- };
21056
- const detachers = sources.map((source) => {
21057
- const listeners = listenersFor(source);
21058
- listeners.add(listener);
21059
- return () => {
21060
- listeners.delete(listener);
21061
- if (listeners.size === 0) {
21062
- bySource.delete(source);
21063
- }
21064
- };
21065
- });
21066
- return () => {
21067
- for (const detach of detachers) {
21068
- detach();
21069
- }
21070
- };
21071
- };
21072
- return {
21073
- publisher: (source) => {
21074
- registered.add(source);
21075
- return {
21076
- source,
21077
- publish: (payload) => {
21078
- publish(source, payload);
21079
- }
21080
- };
21081
- },
21082
- subscribe: addListener,
21083
- stream: (sources) => {
21084
- const queue = [];
21085
- let wake;
21086
- let closed = false;
21087
- const detach = addListener(sources, (event) => {
21088
- if (queue.length >= DOOR_EVENT_BUFFER_EVENTS) {
21089
- queue.shift();
21090
- }
21091
- queue.push(event);
21092
- wake?.();
21093
- });
21094
- return {
21095
- next: async () => {
21096
- for (; ; ) {
21097
- const event = queue.shift();
21098
- if (event !== void 0) {
21099
- return { value: event, done: false };
21100
- }
21101
- if (closed) {
21102
- return { value: void 0, done: true };
21103
- }
21104
- await new Promise((resolve) => {
21105
- wake = resolve;
21106
- });
21107
- }
21108
- },
21109
- close: () => {
21110
- closed = true;
21111
- detach();
21112
- wake?.();
21113
- }
21114
- };
21115
- },
21116
- sources: () => [...registered].sort()
21117
- };
21118
- }
21119
- function rcFanoutOnDoorHub(fanout, hub) {
21120
- const publisher = hub.publisher(DOOR_EVENT_SOURCE_RC);
21121
- return {
21122
- publish: (event) => {
21123
- fanout.publish(event);
21124
- publisher.publish(event);
21125
- },
21126
- subscribe: (session, listener) => fanout.subscribe(session, listener)
21127
- };
21128
- }
21129
-
21130
21450
  // src/frontdoor/launchEvents.ts
21131
21451
  function createLaunchEventPublisher(hub, now) {
21132
21452
  const publisher = hub.publisher(LAUNCH_EVENT_SOURCE);
@@ -23074,7 +23394,7 @@ init_poolPick();
23074
23394
 
23075
23395
  // src/agents/read.ts
23076
23396
  import path46 from "node:path";
23077
- import { z as z40 } from "zod";
23397
+ import { z as z41 } from "zod";
23078
23398
  var PROJECTS_DIR = "projects";
23079
23399
  var TASKS_DIR = "tasks";
23080
23400
  var SUBAGENTS_DIR = "subagents";
@@ -23193,14 +23513,14 @@ function parseJson2(text) {
23193
23513
  return void 0;
23194
23514
  }
23195
23515
  }
23196
- var TaskFileSchema = z40.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z40.array(z40.string()).default([]), blockedBy: z40.array(z40.string()).default([]) });
23197
- var WorkflowRunFileSchema = z40.object({
23198
- runId: z40.string(),
23199
- workflowName: z40.string().optional(),
23200
- status: z40.string().optional(),
23201
- startTime: z40.number().optional(),
23202
- phases: z40.array(z40.object({ title: z40.string() })).default([]),
23203
- summary: z40.string().optional()
23516
+ var TaskFileSchema = z41.object({ ...TaskItemSchema.omit({ taskList: true }).shape, blocks: z41.array(z41.string()).default([]), blockedBy: z41.array(z41.string()).default([]) });
23517
+ var WorkflowRunFileSchema = z41.object({
23518
+ runId: z41.string(),
23519
+ workflowName: z41.string().optional(),
23520
+ status: z41.string().optional(),
23521
+ startTime: z41.number().optional(),
23522
+ phases: z41.array(z41.object({ title: z41.string() })).default([]),
23523
+ summary: z41.string().optional()
23204
23524
  });
23205
23525
  function summariseSession(fs17, configDir, ref) {
23206
23526
  const sessionRelative = path46.join(PROJECTS_DIR, ref.project, ref.entry);
@@ -23707,6 +24027,7 @@ export {
23707
24027
  RC_IDLE_EXPIRY_MS,
23708
24028
  RC_ORPC_PATH_PREFIX,
23709
24029
  RC_PENDING_DEADLINE_MS,
24030
+ RC_PENDING_RETIRE_REASONS,
23710
24031
  RC_PERMISSION_MODES,
23711
24032
  RC_READ_FILE_ENCODINGS,
23712
24033
  RC_REQUEST_PARSE_CAP_BYTES,
@@ -23718,6 +24039,8 @@ export {
23718
24039
  RC_SELF_HOST_SCOPE_LIST,
23719
24040
  RC_SELF_HOST_WORKER_JWT_TTL_SECONDS,
23720
24041
  RC_SESSIONS_PATH_PREFIX,
24042
+ RC_SESSION_END_REASONS,
24043
+ RC_SESSION_EVENT_LOG_CAPACITY,
23721
24044
  RC_STREAM_BACKOFF_MS,
23722
24045
  RC_WEB_FETCH_ALLOW_PRIVATE_ENV,
23723
24046
  RC_WEB_FETCH_DEADLINE_MS,
@@ -23728,6 +24051,13 @@ export {
23728
24051
  RcPermissionModeSchema,
23729
24052
  RcRateLimitInfoSchema,
23730
24053
  RcRateLimitWindowSchema,
24054
+ RcSessionEventCursorExpiredError,
24055
+ RcSessionEventSchema,
24056
+ RcSessionEventsPageInputSchema,
24057
+ RcSessionEventsReadInputSchema,
24058
+ RcSessionEventsReadOutputSchema,
24059
+ RcSessionEventsStreamInputSchema,
24060
+ RcSessionTransitionSchema,
23731
24061
  RcStreamEnvelopeSchema,
23732
24062
  RcStreamEventSchema,
23733
24063
  ResetRowSchema,
@@ -23809,6 +24139,8 @@ export {
23809
24139
  createRcEventFanout,
23810
24140
  createRcLiveUsage,
23811
24141
  createRcSelfHostSurface,
24142
+ createRcSessionEventLog,
24143
+ createRcSessionEventsApiRouter,
23812
24144
  createRcSessionTracker,
23813
24145
  createRcStreamHub,
23814
24146
  createSseParser,
@@ -23824,6 +24156,7 @@ export {
23824
24156
  evaluateAmbientCredentialGuard,
23825
24157
  evaluateWhen,
23826
24158
  fetchThroughWebProxy,
24159
+ followRcSessionEvents,
23827
24160
  formatAmbientCredentialGuardMessage,
23828
24161
  formatCheckReport,
23829
24162
  formatDoctorReport,