@parall/daemon 1.91.0 → 1.93.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.
@@ -22809,8 +22809,8 @@ var require_BatchSpanProcessorBase = __commonJS({
22809
22809
  _flushAll() {
22810
22810
  return new Promise((resolve4, reject) => {
22811
22811
  const promises = [];
22812
- const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
22813
- for (let i = 0, j = count; i < j; i++) {
22812
+ const count2 = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
22813
+ for (let i = 0, j = count2; i < j; i++) {
22814
22814
  promises.push(this._flushOneBatch());
22815
22815
  }
22816
22816
  Promise.all(promises).then(() => {
@@ -52161,6 +52161,8 @@ var clipConnectionEndpoints = {
52161
52161
  CLIP_CONNECTIONS_ALL: (orgId) => `/api/v1/orgs/${orgId}/clip-connections/all`,
52162
52162
  CLIP_CONNECTIONS: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/connections`,
52163
52163
  CLIP_CONNECTION_ACCESS: (orgId, connId) => `/api/v1/orgs/${orgId}/clip-connections/${connId}/access`,
52164
+ /** Who among the org's agents may use one account (per-account setting). */
52165
+ CLIP_CONNECTION_AGENT_ACCESS: (orgId, connId) => `/api/v1/orgs/${orgId}/clip-connections/${connId}/agent-access`,
52164
52166
  CLIP_CONNECTION: (orgId, connId) => `/api/v1/orgs/${orgId}/clip-connections/${connId}`,
52165
52167
  /** The caller's own (person-owned) connections; login session only. */
52166
52168
  ORG_MY_CONNECTIONS: (orgId) => `/api/v1/orgs/${orgId}/me/connections`,
@@ -52429,6 +52431,7 @@ var ENDPOINTS = {
52429
52431
  AGENT_ME: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me`,
52430
52432
  AGENT_REPLY_POLICY_CAPABILITY: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/reply-policy-capability`,
52431
52433
  AGENT_RUNTIME_REPORT: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/runtime-report`,
52434
+ AGENT_LLM_USAGE: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/llm-usage`,
52432
52435
  ...secretEndpoints(API_BASE2),
52433
52436
  AGENT_NEW_SESSION: (orgId, agentId) => `${API_BASE2}/orgs/${orgId}/agents/${agentId}/new-session`,
52434
52437
  AGENT_DEEP_RESET: (orgId, agentId) => `${API_BASE2}/orgs/${orgId}/agents/${agentId}/deep-reset`,
@@ -53507,8 +53510,16 @@ var MiniAppAccessClient = class extends MiniAppActionClient {
53507
53510
  async removeMiniAppAccessGrant(orgId, appId, userId) {
53508
53511
  return this.request("DELETE", `${access(orgId, appId)}/grants/${encodeURIComponent(userId)}`);
53509
53512
  }
53510
- /** The change record, newest first: member_access, the access list and
53511
- * the author roster. */
53513
+ /** Puts a team of the organization on the app's access list, or changes
53514
+ * its level: everyone the team reaches gets at least that much. */
53515
+ async setMiniAppAccessTeamGrant(orgId, appId, teamId, level) {
53516
+ return this.request("PUT", `${access(orgId, appId)}/team-grants/${encodeURIComponent(teamId)}`, { access: level });
53517
+ }
53518
+ async removeMiniAppAccessTeamGrant(orgId, appId, teamId) {
53519
+ return this.request("DELETE", `${access(orgId, appId)}/team-grants/${encodeURIComponent(teamId)}`);
53520
+ }
53521
+ /** The change record, newest first: member_access, the access list (people
53522
+ * and teams) and the author roster. */
53512
53523
  async getMiniAppAccessLog(orgId, appId, query = {}) {
53513
53524
  const response = await this.request("GET", `${access(orgId, appId)}/log`, void 0, { limit: query.limit, before_id: query.before_id });
53514
53525
  return response.data;
@@ -53738,6 +53749,10 @@ var ClipConnectionClient = class extends ChannelConversationClient {
53738
53749
  };
53739
53750
  return this.request("PUT", ENDPOINTS.ORG_CLIP_MCP_CONFIG_BY_ID(orgId, clipId, configId), req, void 0, false, { headers: { "If-Match": `"${expectedVersion}"` }, timeoutMs: 4e4 });
53740
53751
  }
53752
+ /** Server-resolved hosted authorization; no client URL or secret fields. */
53753
+ async connectManagedMCP(orgId, clipId, alias, target) {
53754
+ return this.request(target ? "PUT" : "POST", target ? ENDPOINTS.ORG_CLIP_MCP_CONFIG_BY_ID(orgId, clipId, target.config_id) : ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId), { auth_type: "managed", ...alias ? { alias } : {} }, void 0, false, { headers: target ? { "If-Match": `"${target.version}"` } : void 0, timeoutMs: 11e4 });
53755
+ }
53741
53756
  // ---- Clip connections ----
53742
53757
  /** Missing keys are unknown/hidden; present empty arrays are known empty. */
53743
53758
  async listClipMCPSummaries(orgId, clipIds) {
@@ -53776,6 +53791,17 @@ var ClipConnectionClient = class extends ChannelConversationClient {
53776
53791
  async putClipConnectionAccess(orgId, connId, input) {
53777
53792
  return this.request("PUT", ENDPOINTS.CLIP_CONNECTION_ACCESS(orgId, connId), input);
53778
53793
  }
53794
+ /** Who among the org's agents may use this account. Any org member may read. */
53795
+ async getClipConnectionAgentAccess(orgId, connId) {
53796
+ return this.request("GET", ENDPOINTS.CLIP_CONNECTION_AGENT_ACCESS(orgId, connId));
53797
+ }
53798
+ /**
53799
+ * Replace this account's agent access. Human org owner/admin only (JWT or
53800
+ * personal key); saving `selected` also turns `org_public` off.
53801
+ */
53802
+ async putClipConnectionAgentAccess(orgId, connId, input) {
53803
+ return this.request("PUT", ENDPOINTS.CLIP_CONNECTION_AGENT_ACCESS(orgId, connId), input);
53804
+ }
53779
53805
  /** Start OAuth using the reviewed platform app or provider registration ladder.
53780
53806
  * Allow discovery (30s), persistence (10s), and network overhead to finish. */
53781
53807
  async createClipMCPOAuthConnection(orgId, clipId, serverUrl, alias, oauthClient) {
@@ -54228,10 +54254,25 @@ var AgentOwningTeamClient = class extends AgentTeamOnlyClient {
54228
54254
  }
54229
54255
  };
54230
54256
 
54257
+ // ts/sdk/dist/runtime-auth-llm-usage-client.js
54258
+ var RuntimeAuthLlmUsageClient = class extends AgentOwningTeamClient {
54259
+ /**
54260
+ * Record one batch of usage. The agent's own API key only (403 AGENT_ONLY
54261
+ * otherwise); 204 also for a batch already recorded; 400 for a batch out of
54262
+ * bounds; 409 LLM_ROUTE_NOT_RUNTIME_AUTH when the agent's model route is
54263
+ * not runtime_auth. A server without the endpoint answers 404 with no error
54264
+ * code. Every refusal surfaces as an ApiError with its status and code: what
54265
+ * to do about it is the caller's decision.
54266
+ */
54267
+ async reportRuntimeAuthLlmUsage(orgId, report, opts) {
54268
+ await this.request("POST", ENDPOINTS.AGENT_LLM_USAGE(orgId), report, void 0, false, opts);
54269
+ }
54270
+ };
54271
+
54231
54272
  // ts/sdk/dist/team-graph-client.js
54232
- var TeamGraphClient = class extends AgentOwningTeamClient {
54273
+ var TeamGraphClient = class extends RuntimeAuthLlmUsageClient {
54233
54274
  async getTeamGraph(orgId, opts) {
54234
- const query = opts?.includeAccess ? "?include=access" : "";
54275
+ const query = opts?.includeAccess ? "?include=access&include=apps" : "";
54235
54276
  return this.request("GET", `${ENDPOINTS.TEAM_GRAPH(orgId)}${query}`);
54236
54277
  }
54237
54278
  /**
@@ -54241,9 +54282,12 @@ var TeamGraphClient = class extends AgentOwningTeamClient {
54241
54282
  * would refuse, with the same codes. 503 when it cannot compute the whole answer
54242
54283
  * (`TEAM_MOVE_PREVIEW_WIKI_UNAVAILABLE`, `TEAM_MOVE_PREVIEW_TIMEOUT`,
54243
54284
  * `TEAM_MOVE_PREVIEW_TOO_LARGE`). Send `tree_revision` back on `setTeamParent`.
54285
+ * Asks for Mini Apps too (`include=apps`): without it, a move that changes
54286
+ * someone's access to an app answers 503 `TEAM_MOVE_PREVIEW_APPS_UNSUPPORTED`
54287
+ * (mini-app-access-team-grants-design.md §5).
54244
54288
  */
54245
54289
  async previewTeamMove(orgId, teamId, parentTeamId) {
54246
- return this.request("POST", ENDPOINTS.TEAM_PARENT_PREVIEW(orgId, teamId), {
54290
+ return this.request("POST", `${ENDPOINTS.TEAM_PARENT_PREVIEW(orgId, teamId)}?include=apps`, {
54247
54291
  parent_team_id: parentTeamId
54248
54292
  });
54249
54293
  }
@@ -54498,6 +54542,20 @@ var ChatBookmarksClient = class extends WikiPageShareClient {
54498
54542
  }
54499
54543
  };
54500
54544
 
54545
+ // ts/sdk/dist/template-catalog-client.js
54546
+ var templateCatalogPath = (orgId) => `${API_BASE2}/orgs/${orgId}/templates/catalog`;
54547
+ var TemplateCatalogClient = class extends ChatBookmarksClient {
54548
+ /**
54549
+ * The published team templates this organization can hire. Open to every
54550
+ * member, people and agents alike (owners and admins also have the full
54551
+ * definitions through `listOfficialTemplates`).
54552
+ */
54553
+ async listTemplateCatalog(orgId) {
54554
+ const res = await this.request("GET", templateCatalogPath(orgId));
54555
+ return res.templates ?? [];
54556
+ }
54557
+ };
54558
+
54501
54559
  // ts/sdk/dist/wiki-changeset.js
54502
54560
  function normalizeWikiChangeset(changeset) {
54503
54561
  return {
@@ -54533,7 +54591,7 @@ function legacyHeartbeatFromReport(report) {
54533
54591
  detectedRuntimes
54534
54592
  };
54535
54593
  }
54536
- var ParallClient = class _ParallClient extends ChatBookmarksClient {
54594
+ var ParallClient = class _ParallClient extends TemplateCatalogClient {
54537
54595
  baseUrl;
54538
54596
  wikiBaseUrl;
54539
54597
  token;
@@ -56837,9 +56895,11 @@ var ParallClient = class _ParallClient extends ChatBookmarksClient {
56837
56895
  });
56838
56896
  }
56839
56897
  /** Idempotently begin deleting a hosted Cloud Profile; every repeat returns
56840
- * `202 deleting` until the pod and stored browser state are finalized. */
56841
- async deleteEdgeDevice(orgId, edgeId) {
56842
- return this.request("DELETE", ENDPOINTS.ORG_EDGE_DEVICE(orgId, edgeId));
56898
+ * `202 deleting` until the pod and stored browser state are finalized.
56899
+ * `ifUnused` deletes only when no connection runs on it and no browser
56900
+ * profile on it is shared or granted; otherwise `409 EDGE_IN_USE`. */
56901
+ async deleteEdgeDevice(orgId, edgeId, options) {
56902
+ return this.request("DELETE", ENDPOINTS.ORG_EDGE_DEVICE(orgId, edgeId), void 0, options?.ifUnused ? { if_unused: "true" } : void 0);
56843
56903
  }
56844
56904
  /** Move the human caller's OWN BYOC device between the org layer and their
56845
56905
  * personal layer (ADR-020). `member` takes the device — and every clip
@@ -57072,9 +57132,8 @@ var ParallClient = class _ParallClient extends ChatBookmarksClient {
57072
57132
  }
57073
57133
  async createClipMCPConnection(orgId, clipId, req) {
57074
57134
  return this.request("POST", ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId), req, void 0, false, {
57075
- // A card may start OAuth: allow discovery (30s) and persistence like
57076
- // createClipMCPOAuthConnection.
57077
- timeoutMs: "approval_id" in req ? 5e4 : 4e4
57135
+ // Managed no-auth cards also perform a bounded session probe and completion.
57136
+ timeoutMs: "approval_id" in req ? 11e4 : 4e4
57078
57137
  });
57079
57138
  }
57080
57139
  /** Delete one MCP config and its paired connection. */
@@ -57101,8 +57160,8 @@ var ParallClient = class _ParallClient extends ChatBookmarksClient {
57101
57160
  void 0,
57102
57161
  void 0,
57103
57162
  false,
57104
- // Same fixed 30s server-side probe budget as PUT (see putClipMCPConfig).
57105
- { timeoutMs: 4e4 }
57163
+ // Managed refresh includes account readback and session creation (60s).
57164
+ { timeoutMs: 7e4 }
57106
57165
  );
57107
57166
  }
57108
57167
  // ---- Deprecated method aliases (External* → Trigger* rename; same endpoints) ----
@@ -57238,6 +57297,10 @@ function buildApiError(res, rawErrorBody) {
57238
57297
  return apiError;
57239
57298
  }
57240
57299
 
57300
+ // ts/sdk/dist/runtime-auth-llm-usage-types.js
57301
+ var RUNTIME_AUTH_LLM_USAGE_MAX_MODELS = 8;
57302
+ var LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE = "LLM_ROUTE_NOT_RUNTIME_AUTH";
57303
+
57241
57304
  // ts/sdk/dist/ws.js
57242
57305
  function describeWsStateDetail(detail) {
57243
57306
  if (!detail)
@@ -57668,6 +57731,13 @@ function clearAllProviderCreds(env) {
57668
57731
  delete env[name];
57669
57732
  delete env.PRLL_CLAUDE_ALLOW_API_KEY;
57670
57733
  }
57734
+ function isParallModelEndpoint(endpoint, apiUrl) {
57735
+ const base = endpoint?.trim().replace(/\/+$/, "");
57736
+ const api = apiUrl?.trim().replace(/\/+$/, "");
57737
+ if (!base || !api)
57738
+ return false;
57739
+ return base === api || base.startsWith(`${api}/`);
57740
+ }
57671
57741
  function parseProviderConfig(env) {
57672
57742
  const raw = env.PRLL_PROVIDER_CONFIG?.trim();
57673
57743
  if (!raw)
@@ -58690,8 +58760,8 @@ var OtlpSpoolStore = class {
58690
58760
  return this.opts.dir;
58691
58761
  }
58692
58762
  /** Count a batch the exporter dropped for a permanent status (never spooled). */
58693
- recordDrop(signal2, reason, count = 1) {
58694
- this.opts.onEvent?.({ kind: "dropped", signal: signal2, reason, count });
58763
+ recordDrop(signal2, reason, count2 = 1) {
58764
+ this.opts.onEvent?.({ kind: "dropped", signal: signal2, reason, count: count2 });
58695
58765
  }
58696
58766
  /**
58697
58767
  * Append one serialized request. Resolves once the file is renamed into
@@ -59001,6 +59071,19 @@ var dispatchSpans = /* @__PURE__ */ new WeakSet();
59001
59071
  var recordedErrors = /* @__PURE__ */ new WeakSet();
59002
59072
  var dispatchCounter = null;
59003
59073
  var dispatchDuration = null;
59074
+ var DISPATCH_DURATION_BUCKETS_MS = [
59075
+ 1e3,
59076
+ 2500,
59077
+ 5e3,
59078
+ 1e4,
59079
+ 2e4,
59080
+ 3e4,
59081
+ 6e4,
59082
+ 12e4,
59083
+ 3e5,
59084
+ 6e5,
59085
+ 18e5
59086
+ ];
59004
59087
  var missingReplyCounter = null;
59005
59088
  var turnTokensCounter = null;
59006
59089
  var turnCostCounter = null;
@@ -59154,7 +59237,7 @@ async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
59154
59237
  const metricExporter = spooled(new OTLPMetricExporter({ url: `${otelEndpoint}/v1/metrics`, headers: authHeaders }), "metrics", serializers?.ProtobufMetricsSerializer);
59155
59238
  const metricReader = new PeriodicExportingMetricReader({
59156
59239
  exporter: metricExporter,
59157
- exportIntervalMillis: 15e3
59240
+ exportIntervalMillis: 6e4
59158
59241
  });
59159
59242
  const meterProvider = new MeterProvider({ resource, readers: [metricReader] });
59160
59243
  metrics.setGlobalMeterProvider(meterProvider);
@@ -59168,7 +59251,8 @@ async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
59168
59251
  });
59169
59252
  dispatchDuration = meter.createHistogram("parall.dispatch.duration", {
59170
59253
  description: "Dispatch cycle duration in milliseconds",
59171
- unit: "ms"
59254
+ unit: "ms",
59255
+ advice: { explicitBucketBoundaries: DISPATCH_DURATION_BUCKETS_MS }
59172
59256
  });
59173
59257
  missingReplyCounter = meter.createCounter("parall.dispatch.missing_reply", {
59174
59258
  description: "Dispatches where agent produced text but sent no reply message"
@@ -61389,6 +61473,224 @@ async function closeRuntimeChildSession(host, sessionKey, reason) {
61389
61473
  }
61390
61474
  }
61391
61475
 
61476
+ // ts/agent-core/dist/gateway/runtime-usage-reporter.js
61477
+ import { randomUUID as randomUUID4 } from "node:crypto";
61478
+ var DEFAULT_INTERVAL_MS = 5 * 6e4;
61479
+ var DEFAULT_RETRY_DELAYS_MS3 = [5e3, 3e4, 12e4];
61480
+ var DEFAULT_FLUSH_MS = 5e3;
61481
+ var MAX_MODEL_NAME = 200;
61482
+ var MAX_COUNT = 1e12;
61483
+ var MAX_QUEUED_BATCHES = 64;
61484
+ var RuntimeUsageReporter = class {
61485
+ opts;
61486
+ enabled;
61487
+ /** Usage not cut into a batch yet, per model. */
61488
+ held = /* @__PURE__ */ new Map();
61489
+ /** Cut batches, oldest first; the head is the one being sent. */
61490
+ queue = [];
61491
+ /** Why the server refused the endpoint; null while reporting. Cleared by the next hello. */
61492
+ stoppedBy = null;
61493
+ disposed = false;
61494
+ flushing = false;
61495
+ sending = null;
61496
+ /** Ends a retry's backoff early (exit flush, dispose). */
61497
+ wake = null;
61498
+ inFlight = new AbortController();
61499
+ warnedRefusals = /* @__PURE__ */ new Set();
61500
+ timer = null;
61501
+ unsubscribe;
61502
+ constructor(opts) {
61503
+ this.opts = opts;
61504
+ const subscribe = opts.dispatchAdapter.subscribeUsage?.bind(opts.dispatchAdapter);
61505
+ this.enabled = opts.reportRuntimeUsage === true && subscribe !== void 0;
61506
+ if (!this.enabled || !subscribe)
61507
+ return;
61508
+ this.unsubscribe = subscribe((sample) => this.add(sample));
61509
+ this.timer = setInterval(() => this.cut(), opts.runtimeUsageIntervalMs ?? DEFAULT_INTERVAL_MS);
61510
+ this.timer.unref?.();
61511
+ }
61512
+ /**
61513
+ * Every hello. A 404 or a route refusal stops reporting until the next
61514
+ * connection: a rolling deploy's brief 404 must not silence the process
61515
+ * for its lifetime.
61516
+ */
61517
+ resume() {
61518
+ if (this.stoppedBy === null || this.disposed)
61519
+ return;
61520
+ this.opts.log?.info(`runtime usage: reporting resumed on hello (stopped by ${this.stoppedBy})`);
61521
+ this.stoppedBy = null;
61522
+ }
61523
+ /**
61524
+ * Shutdown, beside the step flush: cut what is held and send every waiting
61525
+ * batch once (a batch in its retry backoff goes now), within budgetMs.
61526
+ * Whatever has not gone out by then is dropped. Absorbing, like dispose().
61527
+ */
61528
+ async flush(budgetMs = this.opts.runtimeUsageFlushMs ?? DEFAULT_FLUSH_MS) {
61529
+ if (!this.enabled || this.disposed)
61530
+ return;
61531
+ let expired = false;
61532
+ let timer;
61533
+ try {
61534
+ this.flushing = true;
61535
+ this.stopObserving();
61536
+ this.cut();
61537
+ this.wake?.();
61538
+ const deadline = new Promise((resolve4) => {
61539
+ timer = setTimeout(() => {
61540
+ expired = true;
61541
+ resolve4();
61542
+ }, Math.max(0, budgetMs));
61543
+ });
61544
+ while (this.sending && !expired)
61545
+ await Promise.race([this.sending, deadline]);
61546
+ } catch (err) {
61547
+ this.opts.log?.warn(`runtime usage: exit flush failed: ${String(err)}`);
61548
+ } finally {
61549
+ clearTimeout(timer);
61550
+ this.dispose();
61551
+ }
61552
+ }
61553
+ /** No more samples, timers or posts; what is held or in flight is dropped. */
61554
+ dispose() {
61555
+ if (this.disposed)
61556
+ return;
61557
+ this.disposed = true;
61558
+ this.stopObserving();
61559
+ this.inFlight.abort();
61560
+ this.wake?.();
61561
+ const unsent = this.queue.length + (this.held.size > 0 ? 1 : 0);
61562
+ if (unsent > 0 && this.stoppedBy === null) {
61563
+ this.opts.log?.warn(`runtime usage: ${unsent} batch(es) not sent before exit, dropped`);
61564
+ }
61565
+ this.queue = [];
61566
+ this.held.clear();
61567
+ }
61568
+ stopObserving() {
61569
+ this.unsubscribe?.();
61570
+ if (this.timer)
61571
+ clearInterval(this.timer);
61572
+ }
61573
+ add(sample) {
61574
+ if (this.disposed || this.stoppedBy !== null)
61575
+ return;
61576
+ const counts = {
61577
+ input_tokens: tokenCount(sample.inputTokens),
61578
+ cache_read_tokens: tokenCount(sample.cacheReadTokens),
61579
+ cache_write_tokens: tokenCount(sample.cacheWriteTokens),
61580
+ output_tokens: tokenCount(sample.outputTokens)
61581
+ };
61582
+ if (Object.values(counts).every((n) => n === 0))
61583
+ return;
61584
+ const model = modelName(sample.model);
61585
+ const held = this.held.get(model);
61586
+ if (!held) {
61587
+ this.held.set(model, counts);
61588
+ return;
61589
+ }
61590
+ for (const key of Object.keys(counts)) {
61591
+ held[key] = Math.min(MAX_COUNT, held[key] + counts[key]);
61592
+ }
61593
+ }
61594
+ /** Held usage → batches of at most 8 models, each with its own id. */
61595
+ cut() {
61596
+ if (this.disposed || this.held.size === 0)
61597
+ return;
61598
+ const models = [...this.held].map(([model, counts]) => ({ model, ...counts }));
61599
+ this.held.clear();
61600
+ for (let i = 0; i < models.length; i += RUNTIME_AUTH_LLM_USAGE_MAX_MODELS) {
61601
+ const chunk = models.slice(i, i + RUNTIME_AUTH_LLM_USAGE_MAX_MODELS);
61602
+ this.queue.push({ id: randomUUID4(), models: chunk, attempts: 0 });
61603
+ }
61604
+ if (this.queue.length > MAX_QUEUED_BATCHES) {
61605
+ const dropped = this.queue.splice(0, this.queue.length - MAX_QUEUED_BATCHES);
61606
+ this.opts.log?.warn(`runtime usage: ${dropped.length} unsent batch(es) dropped (backlog)`);
61607
+ }
61608
+ this.kick();
61609
+ }
61610
+ /** One send loop at a time; a batch cut while it was finishing starts the next. */
61611
+ kick() {
61612
+ if (this.sending || this.disposed)
61613
+ return;
61614
+ this.sending = this.sendQueued().catch((err) => this.opts.log?.warn(`runtime usage: send loop failed: ${String(err)}`)).finally(() => {
61615
+ this.sending = null;
61616
+ if (this.queue.length > 0 && this.stoppedBy === null)
61617
+ this.kick();
61618
+ });
61619
+ }
61620
+ async sendQueued() {
61621
+ const delays = this.opts.runtimeUsageRetryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS3;
61622
+ while (this.queue.length > 0 && this.stoppedBy === null && !this.disposed) {
61623
+ const batch = this.queue[0];
61624
+ const outcome = await this.post(batch);
61625
+ if (outcome === "stopped")
61626
+ return;
61627
+ if (outcome === "retry") {
61628
+ const delay = delays[batch.attempts - 1];
61629
+ if (delay !== void 0 && !this.flushing && !this.disposed) {
61630
+ await this.backoff(delay);
61631
+ continue;
61632
+ }
61633
+ if (!this.disposed) {
61634
+ this.opts.log?.warn(`runtime usage: batch ${batch.id} dropped after ${batch.attempts} attempt(s)`);
61635
+ }
61636
+ }
61637
+ if (this.queue[0] === batch)
61638
+ this.queue.shift();
61639
+ }
61640
+ }
61641
+ async post(batch) {
61642
+ batch.attempts += 1;
61643
+ try {
61644
+ await this.opts.client.reportRuntimeAuthLlmUsage(this.opts.config.org_id, { batch_id: batch.id, models: batch.models }, { signal: this.inFlight.signal });
61645
+ return "done";
61646
+ } catch (err) {
61647
+ if (!(err instanceof ApiError) || err.status === 0 || err.status >= 500)
61648
+ return "retry";
61649
+ if (err.status === 404 && !err.code) {
61650
+ this.stop("a server without the usage endpoint (404)");
61651
+ return "stopped";
61652
+ }
61653
+ if (err.status === 409 && err.code === LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE) {
61654
+ this.stop(`the server (${LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE})`);
61655
+ return "stopped";
61656
+ }
61657
+ const kind = err.code ?? `HTTP ${err.status}`;
61658
+ if (!this.warnedRefusals.has(kind)) {
61659
+ this.warnedRefusals.add(kind);
61660
+ this.opts.log?.warn(`runtime usage: batch ${batch.id} refused, dropped: ${String(err)}`);
61661
+ }
61662
+ return "done";
61663
+ }
61664
+ }
61665
+ /** Stop until the next hello; nothing held survives it. */
61666
+ stop(by) {
61667
+ const dropped = this.queue.length + (this.held.size > 0 ? 1 : 0);
61668
+ this.stoppedBy = by;
61669
+ this.queue = [];
61670
+ this.held.clear();
61671
+ this.opts.log?.info(`runtime usage: reporting stopped by ${by} until the next hello; ${dropped} batch(es) dropped`);
61672
+ }
61673
+ backoff(ms) {
61674
+ return new Promise((resolve4) => {
61675
+ const done = () => {
61676
+ clearTimeout(timer);
61677
+ if (this.wake === done)
61678
+ this.wake = null;
61679
+ resolve4();
61680
+ };
61681
+ const timer = setTimeout(done, ms);
61682
+ timer.unref?.();
61683
+ this.wake = done;
61684
+ });
61685
+ }
61686
+ };
61687
+ function tokenCount(value) {
61688
+ return Number.isFinite(value) && value > 0 ? Math.min(MAX_COUNT, Math.floor(value)) : 0;
61689
+ }
61690
+ function modelName(model) {
61691
+ return (model.trim() || "unknown").slice(0, MAX_MODEL_NAME);
61692
+ }
61693
+
61392
61694
  // ts/agent-core/dist/gateway/drain.js
61393
61695
  var DrainGate = class {
61394
61696
  isDrained;
@@ -61569,7 +61871,7 @@ var DispatchInactivityDeadlines = class {
61569
61871
  };
61570
61872
 
61571
61873
  // ts/agent-core/dist/session/step-retry-queue.js
61572
- var DEFAULT_RETRY_DELAYS_MS3 = [5e3, 1e4, 2e4, 4e4, 6e4];
61874
+ var DEFAULT_RETRY_DELAYS_MS4 = [5e3, 1e4, 2e4, 4e4, 6e4];
61573
61875
  async function raceWithDeadline2(work, ms) {
61574
61876
  let timer;
61575
61877
  const timeout = new Promise((resolve4) => {
@@ -61599,7 +61901,7 @@ var StepRetryQueue = class {
61599
61901
  disposed = false;
61600
61902
  constructor(opts) {
61601
61903
  this.opts = opts;
61602
- this.retryDelays = opts.retryDelaysMs?.length ? opts.retryDelaysMs : DEFAULT_RETRY_DELAYS_MS3;
61904
+ this.retryDelays = opts.retryDelaysMs?.length ? opts.retryDelaysMs : DEFAULT_RETRY_DELAYS_MS4;
61603
61905
  }
61604
61906
  hasPending(sessionId) {
61605
61907
  return (this.queues.get(sessionId)?.length ?? 0) > 0;
@@ -62038,14 +62340,14 @@ function recordToolCall(sessionKey) {
62038
62340
  }
62039
62341
 
62040
62342
  // ts/agent-core/dist/gateway/input-steps.js
62041
- import { randomUUID as randomUUID4 } from "node:crypto";
62343
+ import { randomUUID as randomUUID5 } from "node:crypto";
62042
62344
  function inputStepIdempotencyKey(event) {
62043
62345
  if (event.type === "message" || event.type === "channel_message") {
62044
- return event.messageId ? `input:${event.messageId}` : randomUUID4();
62346
+ return event.messageId ? `input:${event.messageId}` : randomUUID5();
62045
62347
  }
62046
62348
  if (event.dispatchEventId)
62047
62349
  return `input:${event.dispatchEventId}`;
62048
- return randomUUID4();
62350
+ return randomUUID5();
62049
62351
  }
62050
62352
  function resolveStepTarget(event) {
62051
62353
  if (event.input?.step_target) {
@@ -62931,12 +63233,12 @@ async function catchUpFromDispatch(host) {
62931
63233
  let expireSummary = null;
62932
63234
  let overflowMode = false;
62933
63235
  try {
62934
- const { count } = await host.opts.client.getDispatchPendingCount(host.opts.config.org_id);
62935
- if (count > OVERFLOW_THRESHOLD) {
63236
+ const { count: count2 } = await host.opts.client.getDispatchPendingCount(host.opts.config.org_id);
63237
+ if (count2 > OVERFLOW_THRESHOLD) {
62936
63238
  overflowMode = true;
62937
63239
  const result = await host.opts.client.expireDispatch(host.opts.config.org_id, EXPIRE_AGE_HOURS);
62938
63240
  if (result.total > 0) {
62939
- host.opts.log?.warn(`dispatch catch-up overflow: ${count} pending, expired ${result.total} events older than ${EXPIRE_AGE_HOURS}h`);
63241
+ host.opts.log?.warn(`dispatch catch-up overflow: ${count2} pending, expired ${result.total} events older than ${EXPIRE_AGE_HOURS}h`);
62940
63242
  expireSummary = host.buildOfflineSummary(result.groups);
62941
63243
  }
62942
63244
  }
@@ -62990,7 +63292,7 @@ async function catchUpFromDispatch(host) {
62990
63292
  if (expireSummary)
62991
63293
  parts.push(expireSummary);
62992
63294
  if (skipped > 0) {
62993
- const recentLines = [...skippedByType.entries()].map(([type, count]) => `- ${count} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
63295
+ const recentLines = [...skippedByType.entries()].map(([type, count2]) => `- ${count2} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
62994
63296
  parts.push(expireSummary ? `Additionally, ${skipped} recent events exceeded the catch-up limit and were skipped:
62995
63297
  ${recentLines}` : `[Offline Summary] You were offline. ${skipped} pending events exceeded the catch-up limit and were skipped:
62996
63298
  ${recentLines}
@@ -63134,6 +63436,7 @@ async function handleHello(host, data) {
63134
63436
  log2?.info("re-probing dispatch ledger after reconnect (was disabled)");
63135
63437
  host.ledgerDisabled = false;
63136
63438
  }
63439
+ host.runtimeUsage.resume();
63137
63440
  const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
63138
63441
  let openFence = () => {
63139
63442
  };
@@ -63250,6 +63553,7 @@ async function shutdown(host, opts = { skipDrain: false }) {
63250
63553
  if (!settled()) {
63251
63554
  await host.drainGate.wait(5e3, settled);
63252
63555
  }
63556
+ const usageFlushed = host.runtimeUsage.flush();
63253
63557
  if (host.stepPersister.pendingTotal() > 0) {
63254
63558
  const remaining = await host.stepPersister.flush(1e4);
63255
63559
  if (remaining > 0) {
@@ -63257,6 +63561,7 @@ async function shutdown(host, opts = { skipDrain: false }) {
63257
63561
  }
63258
63562
  }
63259
63563
  host.stepPersister.dispose();
63564
+ await usageFlushed;
63260
63565
  const lifecycleRemaining = await host.sessionLifecycle.flush(5e3);
63261
63566
  if (lifecycleRemaining > 0) {
63262
63567
  host.opts.log?.warn(`${lifecycleRemaining} session lifecycle write(s) unreconciled at shutdown`);
@@ -63336,6 +63641,8 @@ var ParallAgentGateway = class {
63336
63641
  drainGate = new DrainGate(() => this.isDrained());
63337
63642
  runtimeActivity = createRuntimeActivityState();
63338
63643
  unsubscribeRuntimeActivity;
63644
+ // The runtime's own-login model usage, batched (gateway/runtime-usage-reporter.ts).
63645
+ runtimeUsage;
63339
63646
  pendingRestartNotification = null;
63340
63647
  laneLedger;
63341
63648
  stepPersister;
@@ -63379,6 +63686,7 @@ var ParallAgentGateway = class {
63379
63686
  this.DISPATCH_DEADLINE_MS = opts.dispatchDeadlineMs ?? 0;
63380
63687
  this.INACTIVITY_WARN_MS = opts.inactivityWarnMs ?? 30 * 6e4;
63381
63688
  this.unsubscribeRuntimeActivity = opts.dispatchAdapter.subscribeRuntimeActivity?.((event) => this.handleRuntimeActivity(event));
63689
+ this.runtimeUsage = new RuntimeUsageReporter(opts);
63382
63690
  this.stepPersister = new StepPersister({
63383
63691
  client: opts.client,
63384
63692
  orgId: opts.config.org_id,
@@ -66006,6 +66314,7 @@ var RuntimeActivityPort = class {
66006
66314
  label;
66007
66315
  log;
66008
66316
  handler = null;
66317
+ usageHandler = null;
66009
66318
  constructor(label, log2) {
66010
66319
  this.label = label;
66011
66320
  this.log = log2;
@@ -66019,6 +66328,15 @@ var RuntimeActivityPort = class {
66019
66328
  this.handler = null;
66020
66329
  };
66021
66330
  }
66331
+ subscribeUsage(handler) {
66332
+ if (this.usageHandler)
66333
+ throw new Error(`${this.label} supports a single usage subscriber`);
66334
+ this.usageHandler = handler;
66335
+ return () => {
66336
+ if (this.usageHandler === handler)
66337
+ this.usageHandler = null;
66338
+ };
66339
+ }
66022
66340
  /** Hand an event to the subscriber; false when there is none or it threw. */
66023
66341
  emit(event, log2 = this.log) {
66024
66342
  if (!this.handler)
@@ -66031,6 +66349,14 @@ var RuntimeActivityPort = class {
66031
66349
  return false;
66032
66350
  }
66033
66351
  }
66352
+ /** One piece of model usage to the subscriber, if any; a throwing subscriber never breaks the caller. */
66353
+ emitUsage(sample, log2 = this.log) {
66354
+ try {
66355
+ this.usageHandler?.(sample);
66356
+ } catch (err) {
66357
+ log2?.warn?.(`usage subscriber threw: ${String(err)}`);
66358
+ }
66359
+ }
66034
66360
  /** A turn opened: to the subscriber when eligible, else drained here. */
66035
66361
  surfaceTurn(turn, eligible = true, log2 = this.log) {
66036
66362
  if (eligible && this.emit({ kind: "turn", turn }, log2))
@@ -66038,29 +66364,29 @@ var RuntimeActivityPort = class {
66038
66364
  void this.drainLocally(turn, log2);
66039
66365
  }
66040
66366
  async drainLocally(turn, log2 = this.log) {
66041
- let count = 0;
66367
+ let count2 = 0;
66042
66368
  let outcome;
66043
66369
  try {
66044
66370
  for await (const event of turn.events) {
66045
- count += 1;
66371
+ count2 += 1;
66046
66372
  if (event.type === "turn_outcome")
66047
66373
  outcome = event.outcome;
66048
66374
  }
66049
66375
  } catch (err) {
66050
66376
  log2?.warn?.(`local drain of runtime-initiated turn ${turn.groupKey} failed: ${String(err)}`);
66051
66377
  }
66052
- log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count} event(s), outcome=${outcome ?? "ok"}`);
66378
+ log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count2} event(s), outcome=${outcome ?? "ok"}`);
66053
66379
  }
66054
66380
  };
66055
66381
 
66056
66382
  // ts/agent-core/dist/runtime-turn-base.js
66057
- import { randomUUID as randomUUID5 } from "node:crypto";
66383
+ import { randomUUID as randomUUID6 } from "node:crypto";
66058
66384
  var RuntimeTurnBase = class {
66059
66385
  sessionKey;
66060
66386
  trigger;
66061
66387
  onDetach;
66062
66388
  childKind;
66063
- groupKey = randomUUID5();
66389
+ groupKey = randomUUID6();
66064
66390
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
66065
66391
  activityListeners = [];
66066
66392
  detached = false;
@@ -66264,6 +66590,7 @@ var JsonRpcStdioClient = class {
66264
66590
  buffer = "";
66265
66591
  onNotification = null;
66266
66592
  onServerRequest = null;
66593
+ observer = null;
66267
66594
  disposed = false;
66268
66595
  constructor(proc, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, killProcess) {
66269
66596
  this.proc = proc;
@@ -66281,6 +66608,9 @@ var JsonRpcStdioClient = class {
66281
66608
  setServerRequestHandler(handler) {
66282
66609
  this.onServerRequest = handler;
66283
66610
  }
66611
+ observe(observer) {
66612
+ this.observer = observer;
66613
+ }
66284
66614
  /**
66285
66615
  * `options.timeoutMs` overrides the client-wide budget for this request.
66286
66616
  * `options.lethalTimeout: false` makes a timeout reject WITHOUT killing the
@@ -66308,7 +66638,7 @@ var JsonRpcStdioClient = class {
66308
66638
  this.killUnhealthy(new Error(`request "${method}" timed out; subprocess assumed hung`));
66309
66639
  }
66310
66640
  }, timeoutMs);
66311
- this.pending.set(id, { resolve: resolve4, reject, timer });
66641
+ this.pending.set(id, { resolve: resolve4, reject, timer, method, params });
66312
66642
  });
66313
66643
  this.writeFrame(request3);
66314
66644
  return promise;
@@ -66377,6 +66707,7 @@ var JsonRpcStdioClient = class {
66377
66707
  if (message.error) {
66378
66708
  pending.reject(new JsonRpcError(message.error.code, message.error.message, message.error.data));
66379
66709
  } else {
66710
+ this.tellObserver((o) => o.response(pending.method, pending.params, message.result));
66380
66711
  pending.resolve(message.result);
66381
66712
  }
66382
66713
  return;
@@ -66386,7 +66717,17 @@ var JsonRpcStdioClient = class {
66386
66717
  return;
66387
66718
  }
66388
66719
  if (isNotification(message)) {
66389
- this.onNotification?.(message.method, message.params);
66720
+ const { method, params } = message;
66721
+ this.tellObserver((o) => o.notification(method, params));
66722
+ this.onNotification?.(method, params);
66723
+ }
66724
+ }
66725
+ tellObserver(tell) {
66726
+ if (!this.observer)
66727
+ return;
66728
+ try {
66729
+ tell(this.observer);
66730
+ } catch {
66390
66731
  }
66391
66732
  }
66392
66733
  answerServerRequest(request3) {
@@ -66459,7 +66800,7 @@ function errToString(err) {
66459
66800
  }
66460
66801
 
66461
66802
  // ts/codex-agent/dist/dispatch.js
66462
- import { randomUUID as randomUUID7 } from "node:crypto";
66803
+ import { randomUUID as randomUUID8 } from "node:crypto";
66463
66804
  import * as path13 from "node:path";
66464
66805
 
66465
66806
  // ts/agent-core/dist/internal/attachment-input.js
@@ -68112,11 +68453,11 @@ var ForeignThreadRegistry = class {
68112
68453
  return this.threads.size;
68113
68454
  }
68114
68455
  openTurns() {
68115
- let count = 0;
68456
+ let count2 = 0;
68116
68457
  for (const thread of this.threads.values())
68117
68458
  if (thread.turn)
68118
- count += 1;
68119
- return count;
68459
+ count2 += 1;
68460
+ return count2;
68120
68461
  }
68121
68462
  /**
68122
68463
  * Notifications for a thread no dispatch owns. Returns false when the
@@ -68315,7 +68656,7 @@ function errToString4(err) {
68315
68656
  }
68316
68657
 
68317
68658
  // ts/codex-agent/dist/input-receipts.js
68318
- import { randomUUID as randomUUID6 } from "node:crypto";
68659
+ import { randomUUID as randomUUID7 } from "node:crypto";
68319
68660
  var CodexInputReceipts = class {
68320
68661
  log;
68321
68662
  inputs = /* @__PURE__ */ new Map();
@@ -68324,7 +68665,7 @@ var CodexInputReceipts = class {
68324
68665
  }
68325
68666
  register(sessionKey, threadId, lifecycle, turnId) {
68326
68667
  const input = {
68327
- clientId: randomUUID6(),
68668
+ clientId: randomUUID7(),
68328
68669
  sessionKey,
68329
68670
  threadId,
68330
68671
  turnId,
@@ -68678,6 +69019,93 @@ function errToString5(err) {
68678
69019
  return err instanceof Error ? err.message : String(err);
68679
69020
  }
68680
69021
 
69022
+ // ts/codex-agent/dist/token-usage.js
69023
+ var MAX_TRACKED = 1024;
69024
+ var CodexProcessUsage = class {
69025
+ port;
69026
+ startedTurns = /* @__PURE__ */ new Set();
69027
+ threadModels = /* @__PURE__ */ new Map();
69028
+ constructor(port) {
69029
+ this.port = port;
69030
+ }
69031
+ notification(method, params) {
69032
+ if (method === "turn/started") {
69033
+ const turnId = extractTurnId(params);
69034
+ if (turnId)
69035
+ remember(this.startedTurns, turnId);
69036
+ return;
69037
+ }
69038
+ if (method !== "thread/tokenUsage/updated")
69039
+ return;
69040
+ const p = params ?? {};
69041
+ if (typeof p.turnId !== "string" || !this.startedTurns.has(p.turnId))
69042
+ return;
69043
+ const sample = sampleOf(p.tokenUsage?.last, this.modelOf(extractThreadIdFromNotification(params)));
69044
+ if (sample)
69045
+ this.port.emitUsage(sample);
69046
+ }
69047
+ response(method, params, result) {
69048
+ switch (method) {
69049
+ case "thread/start":
69050
+ case "thread/resume":
69051
+ case "thread/fork": {
69052
+ const threadId = extractThreadId(result) ?? (method === "thread/resume" ? paramOf(params, "threadId") : void 0);
69053
+ this.setModel(threadId, paramOf(result, "model"));
69054
+ return;
69055
+ }
69056
+ case "turn/start":
69057
+ this.setModel(paramOf(params, "threadId"), paramOf(params, "model"));
69058
+ return;
69059
+ }
69060
+ }
69061
+ setModel(threadId, model) {
69062
+ if (!threadId || !model)
69063
+ return;
69064
+ this.threadModels.delete(threadId);
69065
+ this.threadModels.set(threadId, model);
69066
+ if (this.threadModels.size > MAX_TRACKED) {
69067
+ this.threadModels.delete(this.threadModels.keys().next().value);
69068
+ }
69069
+ }
69070
+ /** The thread's model, refreshed as recently used so a busy thread is never evicted. */
69071
+ modelOf(threadId) {
69072
+ const model = threadId ? this.threadModels.get(threadId) : void 0;
69073
+ if (!threadId || !model)
69074
+ return "unknown";
69075
+ this.setModel(threadId, model);
69076
+ return model;
69077
+ }
69078
+ };
69079
+ function sampleOf(last, model) {
69080
+ if (!last || typeof last !== "object")
69081
+ return void 0;
69082
+ const usage = last;
69083
+ const input = count(usage.inputTokens);
69084
+ const cached = count(usage.cachedInputTokens);
69085
+ const sample = {
69086
+ model,
69087
+ inputTokens: Math.max(0, input - cached),
69088
+ cacheReadTokens: cached,
69089
+ cacheWriteTokens: count(usage.cacheWriteInputTokens),
69090
+ outputTokens: count(usage.outputTokens)
69091
+ };
69092
+ if (input === 0 && sample.cacheWriteTokens === 0 && sample.outputTokens === 0)
69093
+ return void 0;
69094
+ return sample;
69095
+ }
69096
+ function remember(set, value) {
69097
+ set.add(value);
69098
+ if (set.size > MAX_TRACKED)
69099
+ set.delete(set.values().next().value);
69100
+ }
69101
+ function paramOf(value, key) {
69102
+ const field = value && typeof value === "object" ? value[key] : void 0;
69103
+ return typeof field === "string" && field.trim() ? field : void 0;
69104
+ }
69105
+ function count(value) {
69106
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
69107
+ }
69108
+
68681
69109
  // ts/codex-agent/dist/dispatch.js
68682
69110
  var NEW_SESSION_ENDED = "Codex turn ended by New Session";
68683
69111
  var CodexAppServerAdapter = class {
@@ -68899,6 +69327,9 @@ var CodexAppServerAdapter = class {
68899
69327
  subscribeRuntimeActivity(handler) {
68900
69328
  return this.activity.subscribe(handler);
68901
69329
  }
69330
+ subscribeUsage(handler) {
69331
+ return this.activity.subscribeUsage(handler);
69332
+ }
68902
69333
  /**
68903
69334
  * Busy = a dispatch turn, a dispatch opening its thread (possibly running
68904
69335
  * the instructions-refresh compaction turn), or a subagent thread's turn
@@ -68969,7 +69400,7 @@ var CodexAppServerAdapter = class {
68969
69400
  }
68970
69401
  const sink = new TurnSink(noteActivity);
68971
69402
  this.setActiveTurn(threadId, sink, log2);
68972
- const groupKey = randomUUID7();
69403
+ const groupKey = randomUUID8();
68973
69404
  let sawTurnEnd = false;
68974
69405
  let releasePreparedAttachments = () => {
68975
69406
  };
@@ -69173,9 +69604,6 @@ var CodexAppServerAdapter = class {
69173
69604
  }
69174
69605
  return { ok: true, client, threadId, reconcile };
69175
69606
  }
69176
- getBranchPoint(_sessionKey) {
69177
- return void 0;
69178
- }
69179
69607
  async forkSession({ sessionKey: parentSessionKey }) {
69180
69608
  const client = this.client;
69181
69609
  if (!client)
@@ -69203,16 +69631,13 @@ var CodexAppServerAdapter = class {
69203
69631
  this.opts.sessionManager.recordThreadId(handle.sessionKey, forkedThreadId);
69204
69632
  return handle;
69205
69633
  } catch (err) {
69206
- return this.logForkFailure(err);
69634
+ this.opts.log?.warn?.(`thread/fork failed: ${errToString6(err)}`);
69635
+ return null;
69207
69636
  }
69208
69637
  }
69209
69638
  cleanupFork({ fork }) {
69210
69639
  this.opts.sessionManager.cleanupFork(fork.sessionKey);
69211
69640
  }
69212
- logForkFailure(err) {
69213
- this.opts.log?.warn?.(`thread/fork failed: ${errToString6(err)}`);
69214
- return null;
69215
- }
69216
69641
  /**
69217
69642
  * Lazily restart the app-server before the NEXT turn, so a subprocess that
69218
69643
  * has been running since before a capability change starts clean. Deferred
@@ -69335,6 +69760,7 @@ var CodexAppServerAdapter = class {
69335
69760
  log: log2 ?? this.opts.log
69336
69761
  });
69337
69762
  const client = new JsonRpcStdioClient(proc, void 0, (p) => this.appServers.retire(p));
69763
+ client.observe(new CodexProcessUsage(this.activity));
69338
69764
  client.setNotificationHandler((method, params) => this.routeNotification(method, params));
69339
69765
  client.setServerRequestHandler((method, params) => {
69340
69766
  const denial = answerServerRequest(method);
@@ -69759,11 +70185,7 @@ function resolveWriteTarget(filePath) {
69759
70185
  throw new Error(`symlink chain deeper than 40 while resolving ${filePath}`);
69760
70186
  }
69761
70187
  function isParallProxyMode(env = process.env) {
69762
- const baseUrl = env.OPENAI_BASE_URL?.trim()?.replace(/\/+$/, "");
69763
- const apiUrl = env.PRLL_API_URL?.trim()?.replace(/\/+$/, "");
69764
- if (!baseUrl || !apiUrl)
69765
- return false;
69766
- return baseUrl === apiUrl || baseUrl.startsWith(`${apiUrl}/`);
70188
+ return isParallModelEndpoint(env.OPENAI_BASE_URL, env.PRLL_API_URL);
69767
70189
  }
69768
70190
  function tomlBasicString(value) {
69769
70191
  let out = "";
@@ -70070,6 +70492,8 @@ async function main() {
70070
70492
  driver: "app-server"
70071
70493
  },
70072
70494
  dispatchAdapter: adapter,
70495
+ // The CLI's own-login usage, not the Parall proxy's (already metered).
70496
+ reportRuntimeUsage: !useParallProvider,
70073
70497
  log: agentLog,
70074
70498
  // Live capability view for hint routing: the channel reply hint points
70075
70499
  // at the vendor CLI only while the grant is active.