@parall/daemon 1.92.0 → 1.94.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(() => {
@@ -52139,7 +52139,13 @@ function appTemplateEndpoints(apiBase) {
52139
52139
  APP_TEMPLATES: `${apiBase}/app-templates`,
52140
52140
  APP_TEMPLATE: (id) => `${apiBase}/app-templates/${encodeURIComponent(id)}`,
52141
52141
  /** Where the answers' file paths start: one version's files. */
52142
- APP_TEMPLATE_FILES: `${apiBase}/app-templates/files/`
52142
+ APP_TEMPLATE_FILES: `${apiBase}/app-templates/files/`,
52143
+ /** An app's share as a template: share or update (POST), read (GET),
52144
+ * revoke (DELETE). */
52145
+ MINI_APP_TEMPLATE_SHARE: (orgId, appId) => `${apiBase}/orgs/${orgId}/apps/${appId}/template-share`,
52146
+ /** A shared template read from orgId, the reader's organization. */
52147
+ SHARED_APP_TEMPLATE: (orgId, id) => `${apiBase}/orgs/${orgId}/shared-app-templates/${encodeURIComponent(id)}`,
52148
+ SHARED_APP_TEMPLATE_PACKAGE: (orgId, id) => `${apiBase}/orgs/${orgId}/shared-app-templates/${encodeURIComponent(id)}/package`
52143
52149
  };
52144
52150
  }
52145
52151
 
@@ -52158,6 +52164,8 @@ var clipConnectionEndpoints = {
52158
52164
  CLIP_MCP_SUMMARIES: (orgId) => `/api/v1/orgs/${orgId}/clip-mcp-summaries`,
52159
52165
  EDGE_PROFILE_SUMMARIES: (orgId) => `/api/v1/orgs/${orgId}/edge/profile-summaries`,
52160
52166
  ORG_CLIP_MCP_OAUTH_ATTEMPT: (orgId, clipId, attemptId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/mcp-oauth-attempts/${attemptId}`,
52167
+ /** The publisher org's display-name request for one connector (PUT files, DELETE withdraws). */
52168
+ ORG_CLIP_REGISTRY_DISPLAY_NAME_REQUEST: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/display-name-request`,
52161
52169
  CLIP_CONNECTIONS_ALL: (orgId) => `/api/v1/orgs/${orgId}/clip-connections/all`,
52162
52170
  CLIP_CONNECTIONS: (orgId, clipId) => `/api/v1/orgs/${orgId}/clip-registry/${clipId}/connections`,
52163
52171
  CLIP_CONNECTION_ACCESS: (orgId, connId) => `/api/v1/orgs/${orgId}/clip-connections/${connId}/access`,
@@ -52259,7 +52267,11 @@ function billingEndpoints(apiBase) {
52259
52267
  BILLING_ACCOUNTS: (orgId) => `${apiBase}/orgs/${orgId}/billing/accounts`,
52260
52268
  BILLING_ACCOUNT_CLOSE: (orgId, accountId) => `${apiBase}/orgs/${orgId}/billing/accounts/${accountId}/close`,
52261
52269
  BILLING_SETTINGS: (orgId) => `${apiBase}/orgs/${orgId}/billing/settings`,
52262
- COMPUTE_PRICING: () => `${apiBase}/billing/compute-pricing`
52270
+ COMPUTE_PRICING: () => `${apiBase}/billing/compute-pricing`,
52271
+ // Gift credits earned while an organisation sets itself up.
52272
+ ONBOARDING_REWARDS: (orgId) => `${apiBase}/orgs/${orgId}/onboarding/rewards`,
52273
+ ONBOARDING_REWARDS_ENROLL: (orgId) => `${apiBase}/orgs/${orgId}/onboarding/rewards/enroll`,
52274
+ ONBOARDING_REWARDS_SURFACE: (orgId) => `${apiBase}/orgs/${orgId}/onboarding/rewards/surface`
52263
52275
  };
52264
52276
  }
52265
52277
 
@@ -52431,6 +52443,7 @@ var ENDPOINTS = {
52431
52443
  AGENT_ME: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me`,
52432
52444
  AGENT_REPLY_POLICY_CAPABILITY: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/reply-policy-capability`,
52433
52445
  AGENT_RUNTIME_REPORT: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/runtime-report`,
52446
+ AGENT_LLM_USAGE: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/llm-usage`,
52434
52447
  ...secretEndpoints(API_BASE2),
52435
52448
  AGENT_NEW_SESSION: (orgId, agentId) => `${API_BASE2}/orgs/${orgId}/agents/${agentId}/new-session`,
52436
52449
  AGENT_DEEP_RESET: (orgId, agentId) => `${API_BASE2}/orgs/${orgId}/agents/${agentId}/deep-reset`,
@@ -53748,6 +53761,10 @@ var ClipConnectionClient = class extends ChannelConversationClient {
53748
53761
  };
53749
53762
  return this.request("PUT", ENDPOINTS.ORG_CLIP_MCP_CONFIG_BY_ID(orgId, clipId, configId), req, void 0, false, { headers: { "If-Match": `"${expectedVersion}"` }, timeoutMs: 4e4 });
53750
53763
  }
53764
+ /** Server-resolved hosted authorization; no client URL or secret fields. */
53765
+ async connectManagedMCP(orgId, clipId, alias, target) {
53766
+ 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 });
53767
+ }
53751
53768
  // ---- Clip connections ----
53752
53769
  /** Missing keys are unknown/hidden; present empty arrays are known empty. */
53753
53770
  async listClipMCPSummaries(orgId, clipIds) {
@@ -53824,6 +53841,20 @@ var ClipConnectionClient = class extends ChannelConversationClient {
53824
53841
  async deleteMyConnection(orgId, connId) {
53825
53842
  return this.request("DELETE", ENDPOINTS.ORG_MY_CONNECTION(orgId, connId));
53826
53843
  }
53844
+ /**
53845
+ * Ask Parall to change the connector's display name (its author or a human
53846
+ * owner/admin of the publishing org). Nothing changes until review approves;
53847
+ * a new request replaces the pending one. `null` asks to show `name` again.
53848
+ */
53849
+ async requestClipDisplayName(orgId, clipId, displayName) {
53850
+ return this.request("PUT", ENDPOINTS.ORG_CLIP_REGISTRY_DISPLAY_NAME_REQUEST(orgId, clipId), {
53851
+ display_name: displayName
53852
+ });
53853
+ }
53854
+ /** Withdraw the pending display-name request (404 when there is none). */
53855
+ async withdrawClipDisplayNameRequest(orgId, clipId) {
53856
+ await this.request("DELETE", ENDPOINTS.ORG_CLIP_REGISTRY_DISPLAY_NAME_REQUEST(orgId, clipId));
53857
+ }
53827
53858
  };
53828
53859
 
53829
53860
  // ts/sdk/dist/hosted-profile-creation.js
@@ -54184,8 +54215,41 @@ var AppTemplateClient = class extends ApprovalApproversClient {
54184
54215
  }
54185
54216
  };
54186
54217
 
54218
+ // ts/sdk/dist/app-template-share-client.js
54219
+ var SHARE_TIMEOUT_MS = 1e5;
54220
+ var AppTemplateShareClient = class extends AppTemplateClient {
54221
+ /** Share the app's current version as a template, or update its open
54222
+ * share to it (app.publish: an author of the app or an org owner/admin).
54223
+ * A 422 APP_TEMPLATE_SHARE_BLOCKED stores nothing; its findings are in
54224
+ * the error's extras. */
54225
+ async shareMiniAppTemplate(orgId, appId, data, opts) {
54226
+ return this.request("POST", ENDPOINTS.MINI_APP_TEMPLATE_SHARE(orgId, appId), data, void 0, false, { timeoutMs: SHARE_TIMEOUT_MS, signal: opts?.signal });
54227
+ }
54228
+ /** The app's open share; null when it has none (never shared, revoked or
54229
+ * expired). */
54230
+ async getMiniAppTemplateShare(orgId, appId) {
54231
+ const res = await this.request("GET", ENDPOINTS.MINI_APP_TEMPLATE_SHARE(orgId, appId));
54232
+ return res.share ?? null;
54233
+ }
54234
+ /** Revoke the app's open share: its link stops opening at once. Nothing
54235
+ * happens when the app has none. */
54236
+ async revokeMiniAppTemplateShare(orgId, appId) {
54237
+ await this.request("DELETE", ENDPOINTS.MINI_APP_TEMPLATE_SHARE(orgId, appId));
54238
+ }
54239
+ /** A shared template, read from orgId — the reader's organization, not
54240
+ * the sharer's. 404 APP_TEMPLATE_NOT_FOUND for every link that does not
54241
+ * open, whatever the reason. */
54242
+ async getSharedAppTemplate(orgId, id, opts) {
54243
+ return this.request("GET", ENDPOINTS.SHARED_APP_TEMPLATE(orgId, id), void 0, void 0, false, opts);
54244
+ }
54245
+ /** Where to download a shared template's source, for a few minutes. */
54246
+ async getSharedAppTemplatePackage(orgId, id) {
54247
+ return this.request("GET", ENDPOINTS.SHARED_APP_TEMPLATE_PACKAGE(orgId, id));
54248
+ }
54249
+ };
54250
+
54187
54251
  // ts/sdk/dist/chat-team-grant-client.js
54188
- var ChatTeamGrantClient = class extends AppTemplateClient {
54252
+ var ChatTeamGrantClient = class extends AppTemplateShareClient {
54189
54253
  /** The chat's team grants, for its members. */
54190
54254
  async listChatTeamGrants(orgId, chatId) {
54191
54255
  return this.request("GET", ENDPOINTS.CHAT_TEAM_GRANTS(orgId, chatId));
@@ -54249,10 +54313,25 @@ var AgentOwningTeamClient = class extends AgentTeamOnlyClient {
54249
54313
  }
54250
54314
  };
54251
54315
 
54316
+ // ts/sdk/dist/runtime-auth-llm-usage-client.js
54317
+ var RuntimeAuthLlmUsageClient = class extends AgentOwningTeamClient {
54318
+ /**
54319
+ * Record one batch of usage. The agent's own API key only (403 AGENT_ONLY
54320
+ * otherwise); 204 also for a batch already recorded; 400 for a batch out of
54321
+ * bounds; 409 LLM_ROUTE_NOT_RUNTIME_AUTH when the agent's model route is
54322
+ * not runtime_auth. A server without the endpoint answers 404 with no error
54323
+ * code. Every refusal surfaces as an ApiError with its status and code: what
54324
+ * to do about it is the caller's decision.
54325
+ */
54326
+ async reportRuntimeAuthLlmUsage(orgId, report, opts) {
54327
+ await this.request("POST", ENDPOINTS.AGENT_LLM_USAGE(orgId), report, void 0, false, opts);
54328
+ }
54329
+ };
54330
+
54252
54331
  // ts/sdk/dist/team-graph-client.js
54253
- var TeamGraphClient = class extends AgentOwningTeamClient {
54332
+ var TeamGraphClient = class extends RuntimeAuthLlmUsageClient {
54254
54333
  async getTeamGraph(orgId, opts) {
54255
- const query = opts?.includeAccess ? "?include=access" : "";
54334
+ const query = opts?.includeAccess ? "?include=access&include=apps" : "";
54256
54335
  return this.request("GET", `${ENDPOINTS.TEAM_GRAPH(orgId)}${query}`);
54257
54336
  }
54258
54337
  /**
@@ -54387,6 +54466,21 @@ var BillingClient = class extends TeamGraphClient {
54387
54466
  async updateBillingSettings(orgId, req) {
54388
54467
  return this.request("PATCH", ENDPOINTS.BILLING_SETTINGS(orgId), req);
54389
54468
  }
54469
+ // ---- Onboarding rewards (gift credits earned while setting up) ----
54470
+ /** What the organisation has earned so far and what each step pays. */
54471
+ async getOnboardingRewards(orgId) {
54472
+ return this.request("GET", ENDPOINTS.ONBOARDING_REWARDS(orgId));
54473
+ }
54474
+ /** Start earning (the owner only). An organisation that does not qualify
54475
+ * answers 200 with `enrolled: false`; calling it again changes nothing. */
54476
+ async enrollOnboardingRewards(orgId) {
54477
+ return this.request("POST", ENDPOINTS.ONBOARDING_REWARDS_ENROLL(orgId));
54478
+ }
54479
+ /** Record where the team works (owner or admin). Paid once, whatever is
54480
+ * chosen first; repeating it is a no-op. */
54481
+ async claimOnboardingSurface(orgId, surface) {
54482
+ return this.request("POST", ENDPOINTS.ONBOARDING_REWARDS_SURFACE(orgId), { surface });
54483
+ }
54390
54484
  // The admin grant endpoints (POST/GET /internal/admin/orgs/
54391
54485
  // {id}/grants) intentionally do NOT live on this public client — they
54392
54486
  // are mounted on the unauthenticated `/internal/*` surface and reachable
@@ -54536,6 +54630,25 @@ var TemplateCatalogClient = class extends ChatBookmarksClient {
54536
54630
  }
54537
54631
  };
54538
54632
 
54633
+ // ts/sdk/dist/org-deletion-client.js
54634
+ var orgDeletionPath = (orgId) => `${API_BASE2}/orgs/${orgId}/deletion`;
54635
+ var OrgDeletionClient = class extends TemplateCatalogClient {
54636
+ /**
54637
+ * Delete the organization: every member and agent loses access at once,
54638
+ * and its data is purged 30 days later. Only its owner, from a signed-in
54639
+ * session (an API key gets 403 JWT_REQUIRED), and never a personal
54640
+ * organization. `confirmName` must equal the organization's name exactly.
54641
+ * Refusals specific to this request are `ORG_DELETION_ERROR_CODES`.
54642
+ *
54643
+ * This is the deletion path; `deleteOrg` (`DELETE /orgs/{orgId}`) is always
54644
+ * refused by the server.
54645
+ */
54646
+ async requestOrgDeletion(orgId, confirmName) {
54647
+ const body = { confirm_name: confirmName };
54648
+ return this.request("POST", orgDeletionPath(orgId), body);
54649
+ }
54650
+ };
54651
+
54539
54652
  // ts/sdk/dist/wiki-changeset.js
54540
54653
  function normalizeWikiChangeset(changeset) {
54541
54654
  return {
@@ -54571,7 +54684,7 @@ function legacyHeartbeatFromReport(report) {
54571
54684
  detectedRuntimes
54572
54685
  };
54573
54686
  }
54574
- var ParallClient = class _ParallClient extends TemplateCatalogClient {
54687
+ var ParallClient = class _ParallClient extends OrgDeletionClient {
54575
54688
  baseUrl;
54576
54689
  wikiBaseUrl;
54577
54690
  token;
@@ -57112,9 +57225,8 @@ var ParallClient = class _ParallClient extends TemplateCatalogClient {
57112
57225
  }
57113
57226
  async createClipMCPConnection(orgId, clipId, req) {
57114
57227
  return this.request("POST", ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId), req, void 0, false, {
57115
- // A card may start OAuth: allow discovery (30s) and persistence like
57116
- // createClipMCPOAuthConnection.
57117
- timeoutMs: "approval_id" in req ? 5e4 : 4e4
57228
+ // Managed no-auth cards also perform a bounded session probe and completion.
57229
+ timeoutMs: "approval_id" in req ? 11e4 : 4e4
57118
57230
  });
57119
57231
  }
57120
57232
  /** Delete one MCP config and its paired connection. */
@@ -57141,8 +57253,8 @@ var ParallClient = class _ParallClient extends TemplateCatalogClient {
57141
57253
  void 0,
57142
57254
  void 0,
57143
57255
  false,
57144
- // Same fixed 30s server-side probe budget as PUT (see putClipMCPConfig).
57145
- { timeoutMs: 4e4 }
57256
+ // Managed refresh includes account readback and session creation (60s).
57257
+ { timeoutMs: 7e4 }
57146
57258
  );
57147
57259
  }
57148
57260
  // ---- Deprecated method aliases (External* → Trigger* rename; same endpoints) ----
@@ -57278,6 +57390,10 @@ function buildApiError(res, rawErrorBody) {
57278
57390
  return apiError;
57279
57391
  }
57280
57392
 
57393
+ // ts/sdk/dist/runtime-auth-llm-usage-types.js
57394
+ var RUNTIME_AUTH_LLM_USAGE_MAX_MODELS = 8;
57395
+ var LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE = "LLM_ROUTE_NOT_RUNTIME_AUTH";
57396
+
57281
57397
  // ts/sdk/dist/ws.js
57282
57398
  function describeWsStateDetail(detail) {
57283
57399
  if (!detail)
@@ -57708,6 +57824,13 @@ function clearAllProviderCreds(env) {
57708
57824
  delete env[name];
57709
57825
  delete env.PRLL_CLAUDE_ALLOW_API_KEY;
57710
57826
  }
57827
+ function isParallModelEndpoint(endpoint, apiUrl) {
57828
+ const base = endpoint?.trim().replace(/\/+$/, "");
57829
+ const api = apiUrl?.trim().replace(/\/+$/, "");
57830
+ if (!base || !api)
57831
+ return false;
57832
+ return base === api || base.startsWith(`${api}/`);
57833
+ }
57711
57834
  function parseProviderConfig(env) {
57712
57835
  const raw = env.PRLL_PROVIDER_CONFIG?.trim();
57713
57836
  if (!raw)
@@ -58730,8 +58853,8 @@ var OtlpSpoolStore = class {
58730
58853
  return this.opts.dir;
58731
58854
  }
58732
58855
  /** Count a batch the exporter dropped for a permanent status (never spooled). */
58733
- recordDrop(signal2, reason, count = 1) {
58734
- this.opts.onEvent?.({ kind: "dropped", signal: signal2, reason, count });
58856
+ recordDrop(signal2, reason, count2 = 1) {
58857
+ this.opts.onEvent?.({ kind: "dropped", signal: signal2, reason, count: count2 });
58735
58858
  }
58736
58859
  /**
58737
58860
  * Append one serialized request. Resolves once the file is renamed into
@@ -59041,6 +59164,19 @@ var dispatchSpans = /* @__PURE__ */ new WeakSet();
59041
59164
  var recordedErrors = /* @__PURE__ */ new WeakSet();
59042
59165
  var dispatchCounter = null;
59043
59166
  var dispatchDuration = null;
59167
+ var DISPATCH_DURATION_BUCKETS_MS = [
59168
+ 1e3,
59169
+ 2500,
59170
+ 5e3,
59171
+ 1e4,
59172
+ 2e4,
59173
+ 3e4,
59174
+ 6e4,
59175
+ 12e4,
59176
+ 3e5,
59177
+ 6e5,
59178
+ 18e5
59179
+ ];
59044
59180
  var missingReplyCounter = null;
59045
59181
  var turnTokensCounter = null;
59046
59182
  var turnCostCounter = null;
@@ -59194,7 +59330,7 @@ async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
59194
59330
  const metricExporter = spooled(new OTLPMetricExporter({ url: `${otelEndpoint}/v1/metrics`, headers: authHeaders }), "metrics", serializers?.ProtobufMetricsSerializer);
59195
59331
  const metricReader = new PeriodicExportingMetricReader({
59196
59332
  exporter: metricExporter,
59197
- exportIntervalMillis: 15e3
59333
+ exportIntervalMillis: 6e4
59198
59334
  });
59199
59335
  const meterProvider = new MeterProvider({ resource, readers: [metricReader] });
59200
59336
  metrics.setGlobalMeterProvider(meterProvider);
@@ -59208,7 +59344,8 @@ async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
59208
59344
  });
59209
59345
  dispatchDuration = meter.createHistogram("parall.dispatch.duration", {
59210
59346
  description: "Dispatch cycle duration in milliseconds",
59211
- unit: "ms"
59347
+ unit: "ms",
59348
+ advice: { explicitBucketBoundaries: DISPATCH_DURATION_BUCKETS_MS }
59212
59349
  });
59213
59350
  missingReplyCounter = meter.createCounter("parall.dispatch.missing_reply", {
59214
59351
  description: "Dispatches where agent produced text but sent no reply message"
@@ -61429,6 +61566,224 @@ async function closeRuntimeChildSession(host, sessionKey, reason) {
61429
61566
  }
61430
61567
  }
61431
61568
 
61569
+ // ts/agent-core/dist/gateway/runtime-usage-reporter.js
61570
+ import { randomUUID as randomUUID4 } from "node:crypto";
61571
+ var DEFAULT_INTERVAL_MS = 5 * 6e4;
61572
+ var DEFAULT_RETRY_DELAYS_MS3 = [5e3, 3e4, 12e4];
61573
+ var DEFAULT_FLUSH_MS = 5e3;
61574
+ var MAX_MODEL_NAME = 200;
61575
+ var MAX_COUNT = 1e12;
61576
+ var MAX_QUEUED_BATCHES = 64;
61577
+ var RuntimeUsageReporter = class {
61578
+ opts;
61579
+ enabled;
61580
+ /** Usage not cut into a batch yet, per model. */
61581
+ held = /* @__PURE__ */ new Map();
61582
+ /** Cut batches, oldest first; the head is the one being sent. */
61583
+ queue = [];
61584
+ /** Why the server refused the endpoint; null while reporting. Cleared by the next hello. */
61585
+ stoppedBy = null;
61586
+ disposed = false;
61587
+ flushing = false;
61588
+ sending = null;
61589
+ /** Ends a retry's backoff early (exit flush, dispose). */
61590
+ wake = null;
61591
+ inFlight = new AbortController();
61592
+ warnedRefusals = /* @__PURE__ */ new Set();
61593
+ timer = null;
61594
+ unsubscribe;
61595
+ constructor(opts) {
61596
+ this.opts = opts;
61597
+ const subscribe = opts.dispatchAdapter.subscribeUsage?.bind(opts.dispatchAdapter);
61598
+ this.enabled = opts.reportRuntimeUsage === true && subscribe !== void 0;
61599
+ if (!this.enabled || !subscribe)
61600
+ return;
61601
+ this.unsubscribe = subscribe((sample) => this.add(sample));
61602
+ this.timer = setInterval(() => this.cut(), opts.runtimeUsageIntervalMs ?? DEFAULT_INTERVAL_MS);
61603
+ this.timer.unref?.();
61604
+ }
61605
+ /**
61606
+ * Every hello. A 404 or a route refusal stops reporting until the next
61607
+ * connection: a rolling deploy's brief 404 must not silence the process
61608
+ * for its lifetime.
61609
+ */
61610
+ resume() {
61611
+ if (this.stoppedBy === null || this.disposed)
61612
+ return;
61613
+ this.opts.log?.info(`runtime usage: reporting resumed on hello (stopped by ${this.stoppedBy})`);
61614
+ this.stoppedBy = null;
61615
+ }
61616
+ /**
61617
+ * Shutdown, beside the step flush: cut what is held and send every waiting
61618
+ * batch once (a batch in its retry backoff goes now), within budgetMs.
61619
+ * Whatever has not gone out by then is dropped. Absorbing, like dispose().
61620
+ */
61621
+ async flush(budgetMs = this.opts.runtimeUsageFlushMs ?? DEFAULT_FLUSH_MS) {
61622
+ if (!this.enabled || this.disposed)
61623
+ return;
61624
+ let expired = false;
61625
+ let timer;
61626
+ try {
61627
+ this.flushing = true;
61628
+ this.stopObserving();
61629
+ this.cut();
61630
+ this.wake?.();
61631
+ const deadline = new Promise((resolve4) => {
61632
+ timer = setTimeout(() => {
61633
+ expired = true;
61634
+ resolve4();
61635
+ }, Math.max(0, budgetMs));
61636
+ });
61637
+ while (this.sending && !expired)
61638
+ await Promise.race([this.sending, deadline]);
61639
+ } catch (err) {
61640
+ this.opts.log?.warn(`runtime usage: exit flush failed: ${String(err)}`);
61641
+ } finally {
61642
+ clearTimeout(timer);
61643
+ this.dispose();
61644
+ }
61645
+ }
61646
+ /** No more samples, timers or posts; what is held or in flight is dropped. */
61647
+ dispose() {
61648
+ if (this.disposed)
61649
+ return;
61650
+ this.disposed = true;
61651
+ this.stopObserving();
61652
+ this.inFlight.abort();
61653
+ this.wake?.();
61654
+ const unsent = this.queue.length + (this.held.size > 0 ? 1 : 0);
61655
+ if (unsent > 0 && this.stoppedBy === null) {
61656
+ this.opts.log?.warn(`runtime usage: ${unsent} batch(es) not sent before exit, dropped`);
61657
+ }
61658
+ this.queue = [];
61659
+ this.held.clear();
61660
+ }
61661
+ stopObserving() {
61662
+ this.unsubscribe?.();
61663
+ if (this.timer)
61664
+ clearInterval(this.timer);
61665
+ }
61666
+ add(sample) {
61667
+ if (this.disposed || this.stoppedBy !== null)
61668
+ return;
61669
+ const counts = {
61670
+ input_tokens: tokenCount(sample.inputTokens),
61671
+ cache_read_tokens: tokenCount(sample.cacheReadTokens),
61672
+ cache_write_tokens: tokenCount(sample.cacheWriteTokens),
61673
+ output_tokens: tokenCount(sample.outputTokens)
61674
+ };
61675
+ if (Object.values(counts).every((n) => n === 0))
61676
+ return;
61677
+ const model = modelName(sample.model);
61678
+ const held = this.held.get(model);
61679
+ if (!held) {
61680
+ this.held.set(model, counts);
61681
+ return;
61682
+ }
61683
+ for (const key of Object.keys(counts)) {
61684
+ held[key] = Math.min(MAX_COUNT, held[key] + counts[key]);
61685
+ }
61686
+ }
61687
+ /** Held usage → batches of at most 8 models, each with its own id. */
61688
+ cut() {
61689
+ if (this.disposed || this.held.size === 0)
61690
+ return;
61691
+ const models = [...this.held].map(([model, counts]) => ({ model, ...counts }));
61692
+ this.held.clear();
61693
+ for (let i = 0; i < models.length; i += RUNTIME_AUTH_LLM_USAGE_MAX_MODELS) {
61694
+ const chunk = models.slice(i, i + RUNTIME_AUTH_LLM_USAGE_MAX_MODELS);
61695
+ this.queue.push({ id: randomUUID4(), models: chunk, attempts: 0 });
61696
+ }
61697
+ if (this.queue.length > MAX_QUEUED_BATCHES) {
61698
+ const dropped = this.queue.splice(0, this.queue.length - MAX_QUEUED_BATCHES);
61699
+ this.opts.log?.warn(`runtime usage: ${dropped.length} unsent batch(es) dropped (backlog)`);
61700
+ }
61701
+ this.kick();
61702
+ }
61703
+ /** One send loop at a time; a batch cut while it was finishing starts the next. */
61704
+ kick() {
61705
+ if (this.sending || this.disposed)
61706
+ return;
61707
+ this.sending = this.sendQueued().catch((err) => this.opts.log?.warn(`runtime usage: send loop failed: ${String(err)}`)).finally(() => {
61708
+ this.sending = null;
61709
+ if (this.queue.length > 0 && this.stoppedBy === null)
61710
+ this.kick();
61711
+ });
61712
+ }
61713
+ async sendQueued() {
61714
+ const delays = this.opts.runtimeUsageRetryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS3;
61715
+ while (this.queue.length > 0 && this.stoppedBy === null && !this.disposed) {
61716
+ const batch = this.queue[0];
61717
+ const outcome = await this.post(batch);
61718
+ if (outcome === "stopped")
61719
+ return;
61720
+ if (outcome === "retry") {
61721
+ const delay = delays[batch.attempts - 1];
61722
+ if (delay !== void 0 && !this.flushing && !this.disposed) {
61723
+ await this.backoff(delay);
61724
+ continue;
61725
+ }
61726
+ if (!this.disposed) {
61727
+ this.opts.log?.warn(`runtime usage: batch ${batch.id} dropped after ${batch.attempts} attempt(s)`);
61728
+ }
61729
+ }
61730
+ if (this.queue[0] === batch)
61731
+ this.queue.shift();
61732
+ }
61733
+ }
61734
+ async post(batch) {
61735
+ batch.attempts += 1;
61736
+ try {
61737
+ await this.opts.client.reportRuntimeAuthLlmUsage(this.opts.config.org_id, { batch_id: batch.id, models: batch.models }, { signal: this.inFlight.signal });
61738
+ return "done";
61739
+ } catch (err) {
61740
+ if (!(err instanceof ApiError) || err.status === 0 || err.status >= 500)
61741
+ return "retry";
61742
+ if (err.status === 404 && !err.code) {
61743
+ this.stop("a server without the usage endpoint (404)");
61744
+ return "stopped";
61745
+ }
61746
+ if (err.status === 409 && err.code === LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE) {
61747
+ this.stop(`the server (${LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE})`);
61748
+ return "stopped";
61749
+ }
61750
+ const kind = err.code ?? `HTTP ${err.status}`;
61751
+ if (!this.warnedRefusals.has(kind)) {
61752
+ this.warnedRefusals.add(kind);
61753
+ this.opts.log?.warn(`runtime usage: batch ${batch.id} refused, dropped: ${String(err)}`);
61754
+ }
61755
+ return "done";
61756
+ }
61757
+ }
61758
+ /** Stop until the next hello; nothing held survives it. */
61759
+ stop(by) {
61760
+ const dropped = this.queue.length + (this.held.size > 0 ? 1 : 0);
61761
+ this.stoppedBy = by;
61762
+ this.queue = [];
61763
+ this.held.clear();
61764
+ this.opts.log?.info(`runtime usage: reporting stopped by ${by} until the next hello; ${dropped} batch(es) dropped`);
61765
+ }
61766
+ backoff(ms) {
61767
+ return new Promise((resolve4) => {
61768
+ const done = () => {
61769
+ clearTimeout(timer);
61770
+ if (this.wake === done)
61771
+ this.wake = null;
61772
+ resolve4();
61773
+ };
61774
+ const timer = setTimeout(done, ms);
61775
+ timer.unref?.();
61776
+ this.wake = done;
61777
+ });
61778
+ }
61779
+ };
61780
+ function tokenCount(value) {
61781
+ return Number.isFinite(value) && value > 0 ? Math.min(MAX_COUNT, Math.floor(value)) : 0;
61782
+ }
61783
+ function modelName(model) {
61784
+ return (model.trim() || "unknown").slice(0, MAX_MODEL_NAME);
61785
+ }
61786
+
61432
61787
  // ts/agent-core/dist/gateway/drain.js
61433
61788
  var DrainGate = class {
61434
61789
  isDrained;
@@ -61609,7 +61964,7 @@ var DispatchInactivityDeadlines = class {
61609
61964
  };
61610
61965
 
61611
61966
  // ts/agent-core/dist/session/step-retry-queue.js
61612
- var DEFAULT_RETRY_DELAYS_MS3 = [5e3, 1e4, 2e4, 4e4, 6e4];
61967
+ var DEFAULT_RETRY_DELAYS_MS4 = [5e3, 1e4, 2e4, 4e4, 6e4];
61613
61968
  async function raceWithDeadline2(work, ms) {
61614
61969
  let timer;
61615
61970
  const timeout = new Promise((resolve4) => {
@@ -61639,7 +61994,7 @@ var StepRetryQueue = class {
61639
61994
  disposed = false;
61640
61995
  constructor(opts) {
61641
61996
  this.opts = opts;
61642
- this.retryDelays = opts.retryDelaysMs?.length ? opts.retryDelaysMs : DEFAULT_RETRY_DELAYS_MS3;
61997
+ this.retryDelays = opts.retryDelaysMs?.length ? opts.retryDelaysMs : DEFAULT_RETRY_DELAYS_MS4;
61643
61998
  }
61644
61999
  hasPending(sessionId) {
61645
62000
  return (this.queues.get(sessionId)?.length ?? 0) > 0;
@@ -62078,14 +62433,14 @@ function recordToolCall(sessionKey) {
62078
62433
  }
62079
62434
 
62080
62435
  // ts/agent-core/dist/gateway/input-steps.js
62081
- import { randomUUID as randomUUID4 } from "node:crypto";
62436
+ import { randomUUID as randomUUID5 } from "node:crypto";
62082
62437
  function inputStepIdempotencyKey(event) {
62083
62438
  if (event.type === "message" || event.type === "channel_message") {
62084
- return event.messageId ? `input:${event.messageId}` : randomUUID4();
62439
+ return event.messageId ? `input:${event.messageId}` : randomUUID5();
62085
62440
  }
62086
62441
  if (event.dispatchEventId)
62087
62442
  return `input:${event.dispatchEventId}`;
62088
- return randomUUID4();
62443
+ return randomUUID5();
62089
62444
  }
62090
62445
  function resolveStepTarget(event) {
62091
62446
  if (event.input?.step_target) {
@@ -62971,12 +63326,12 @@ async function catchUpFromDispatch(host) {
62971
63326
  let expireSummary = null;
62972
63327
  let overflowMode = false;
62973
63328
  try {
62974
- const { count } = await host.opts.client.getDispatchPendingCount(host.opts.config.org_id);
62975
- if (count > OVERFLOW_THRESHOLD) {
63329
+ const { count: count2 } = await host.opts.client.getDispatchPendingCount(host.opts.config.org_id);
63330
+ if (count2 > OVERFLOW_THRESHOLD) {
62976
63331
  overflowMode = true;
62977
63332
  const result = await host.opts.client.expireDispatch(host.opts.config.org_id, EXPIRE_AGE_HOURS);
62978
63333
  if (result.total > 0) {
62979
- host.opts.log?.warn(`dispatch catch-up overflow: ${count} pending, expired ${result.total} events older than ${EXPIRE_AGE_HOURS}h`);
63334
+ host.opts.log?.warn(`dispatch catch-up overflow: ${count2} pending, expired ${result.total} events older than ${EXPIRE_AGE_HOURS}h`);
62980
63335
  expireSummary = host.buildOfflineSummary(result.groups);
62981
63336
  }
62982
63337
  }
@@ -63030,7 +63385,7 @@ async function catchUpFromDispatch(host) {
63030
63385
  if (expireSummary)
63031
63386
  parts.push(expireSummary);
63032
63387
  if (skipped > 0) {
63033
- const recentLines = [...skippedByType.entries()].map(([type, count]) => `- ${count} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
63388
+ const recentLines = [...skippedByType.entries()].map(([type, count2]) => `- ${count2} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
63034
63389
  parts.push(expireSummary ? `Additionally, ${skipped} recent events exceeded the catch-up limit and were skipped:
63035
63390
  ${recentLines}` : `[Offline Summary] You were offline. ${skipped} pending events exceeded the catch-up limit and were skipped:
63036
63391
  ${recentLines}
@@ -63174,6 +63529,7 @@ async function handleHello(host, data) {
63174
63529
  log2?.info("re-probing dispatch ledger after reconnect (was disabled)");
63175
63530
  host.ledgerDisabled = false;
63176
63531
  }
63532
+ host.runtimeUsage.resume();
63177
63533
  const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
63178
63534
  let openFence = () => {
63179
63535
  };
@@ -63290,6 +63646,7 @@ async function shutdown(host, opts = { skipDrain: false }) {
63290
63646
  if (!settled()) {
63291
63647
  await host.drainGate.wait(5e3, settled);
63292
63648
  }
63649
+ const usageFlushed = host.runtimeUsage.flush();
63293
63650
  if (host.stepPersister.pendingTotal() > 0) {
63294
63651
  const remaining = await host.stepPersister.flush(1e4);
63295
63652
  if (remaining > 0) {
@@ -63297,6 +63654,7 @@ async function shutdown(host, opts = { skipDrain: false }) {
63297
63654
  }
63298
63655
  }
63299
63656
  host.stepPersister.dispose();
63657
+ await usageFlushed;
63300
63658
  const lifecycleRemaining = await host.sessionLifecycle.flush(5e3);
63301
63659
  if (lifecycleRemaining > 0) {
63302
63660
  host.opts.log?.warn(`${lifecycleRemaining} session lifecycle write(s) unreconciled at shutdown`);
@@ -63376,6 +63734,8 @@ var ParallAgentGateway = class {
63376
63734
  drainGate = new DrainGate(() => this.isDrained());
63377
63735
  runtimeActivity = createRuntimeActivityState();
63378
63736
  unsubscribeRuntimeActivity;
63737
+ // The runtime's own-login model usage, batched (gateway/runtime-usage-reporter.ts).
63738
+ runtimeUsage;
63379
63739
  pendingRestartNotification = null;
63380
63740
  laneLedger;
63381
63741
  stepPersister;
@@ -63419,6 +63779,7 @@ var ParallAgentGateway = class {
63419
63779
  this.DISPATCH_DEADLINE_MS = opts.dispatchDeadlineMs ?? 0;
63420
63780
  this.INACTIVITY_WARN_MS = opts.inactivityWarnMs ?? 30 * 6e4;
63421
63781
  this.unsubscribeRuntimeActivity = opts.dispatchAdapter.subscribeRuntimeActivity?.((event) => this.handleRuntimeActivity(event));
63782
+ this.runtimeUsage = new RuntimeUsageReporter(opts);
63422
63783
  this.stepPersister = new StepPersister({
63423
63784
  client: opts.client,
63424
63785
  orgId: opts.config.org_id,
@@ -66046,6 +66407,7 @@ var RuntimeActivityPort = class {
66046
66407
  label;
66047
66408
  log;
66048
66409
  handler = null;
66410
+ usageHandler = null;
66049
66411
  constructor(label, log2) {
66050
66412
  this.label = label;
66051
66413
  this.log = log2;
@@ -66059,6 +66421,15 @@ var RuntimeActivityPort = class {
66059
66421
  this.handler = null;
66060
66422
  };
66061
66423
  }
66424
+ subscribeUsage(handler) {
66425
+ if (this.usageHandler)
66426
+ throw new Error(`${this.label} supports a single usage subscriber`);
66427
+ this.usageHandler = handler;
66428
+ return () => {
66429
+ if (this.usageHandler === handler)
66430
+ this.usageHandler = null;
66431
+ };
66432
+ }
66062
66433
  /** Hand an event to the subscriber; false when there is none or it threw. */
66063
66434
  emit(event, log2 = this.log) {
66064
66435
  if (!this.handler)
@@ -66071,6 +66442,14 @@ var RuntimeActivityPort = class {
66071
66442
  return false;
66072
66443
  }
66073
66444
  }
66445
+ /** One piece of model usage to the subscriber, if any; a throwing subscriber never breaks the caller. */
66446
+ emitUsage(sample, log2 = this.log) {
66447
+ try {
66448
+ this.usageHandler?.(sample);
66449
+ } catch (err) {
66450
+ log2?.warn?.(`usage subscriber threw: ${String(err)}`);
66451
+ }
66452
+ }
66074
66453
  /** A turn opened: to the subscriber when eligible, else drained here. */
66075
66454
  surfaceTurn(turn, eligible = true, log2 = this.log) {
66076
66455
  if (eligible && this.emit({ kind: "turn", turn }, log2))
@@ -66078,29 +66457,29 @@ var RuntimeActivityPort = class {
66078
66457
  void this.drainLocally(turn, log2);
66079
66458
  }
66080
66459
  async drainLocally(turn, log2 = this.log) {
66081
- let count = 0;
66460
+ let count2 = 0;
66082
66461
  let outcome;
66083
66462
  try {
66084
66463
  for await (const event of turn.events) {
66085
- count += 1;
66464
+ count2 += 1;
66086
66465
  if (event.type === "turn_outcome")
66087
66466
  outcome = event.outcome;
66088
66467
  }
66089
66468
  } catch (err) {
66090
66469
  log2?.warn?.(`local drain of runtime-initiated turn ${turn.groupKey} failed: ${String(err)}`);
66091
66470
  }
66092
- log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count} event(s), outcome=${outcome ?? "ok"}`);
66471
+ log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count2} event(s), outcome=${outcome ?? "ok"}`);
66093
66472
  }
66094
66473
  };
66095
66474
 
66096
66475
  // ts/agent-core/dist/runtime-turn-base.js
66097
- import { randomUUID as randomUUID5 } from "node:crypto";
66476
+ import { randomUUID as randomUUID6 } from "node:crypto";
66098
66477
  var RuntimeTurnBase = class {
66099
66478
  sessionKey;
66100
66479
  trigger;
66101
66480
  onDetach;
66102
66481
  childKind;
66103
- groupKey = randomUUID5();
66482
+ groupKey = randomUUID6();
66104
66483
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
66105
66484
  activityListeners = [];
66106
66485
  detached = false;
@@ -66304,6 +66683,7 @@ var JsonRpcStdioClient = class {
66304
66683
  buffer = "";
66305
66684
  onNotification = null;
66306
66685
  onServerRequest = null;
66686
+ observer = null;
66307
66687
  disposed = false;
66308
66688
  constructor(proc, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, killProcess) {
66309
66689
  this.proc = proc;
@@ -66321,6 +66701,9 @@ var JsonRpcStdioClient = class {
66321
66701
  setServerRequestHandler(handler) {
66322
66702
  this.onServerRequest = handler;
66323
66703
  }
66704
+ observe(observer) {
66705
+ this.observer = observer;
66706
+ }
66324
66707
  /**
66325
66708
  * `options.timeoutMs` overrides the client-wide budget for this request.
66326
66709
  * `options.lethalTimeout: false` makes a timeout reject WITHOUT killing the
@@ -66348,7 +66731,7 @@ var JsonRpcStdioClient = class {
66348
66731
  this.killUnhealthy(new Error(`request "${method}" timed out; subprocess assumed hung`));
66349
66732
  }
66350
66733
  }, timeoutMs);
66351
- this.pending.set(id, { resolve: resolve4, reject, timer });
66734
+ this.pending.set(id, { resolve: resolve4, reject, timer, method, params });
66352
66735
  });
66353
66736
  this.writeFrame(request3);
66354
66737
  return promise;
@@ -66417,6 +66800,7 @@ var JsonRpcStdioClient = class {
66417
66800
  if (message.error) {
66418
66801
  pending.reject(new JsonRpcError(message.error.code, message.error.message, message.error.data));
66419
66802
  } else {
66803
+ this.tellObserver((o) => o.response(pending.method, pending.params, message.result));
66420
66804
  pending.resolve(message.result);
66421
66805
  }
66422
66806
  return;
@@ -66426,7 +66810,17 @@ var JsonRpcStdioClient = class {
66426
66810
  return;
66427
66811
  }
66428
66812
  if (isNotification(message)) {
66429
- this.onNotification?.(message.method, message.params);
66813
+ const { method, params } = message;
66814
+ this.tellObserver((o) => o.notification(method, params));
66815
+ this.onNotification?.(method, params);
66816
+ }
66817
+ }
66818
+ tellObserver(tell) {
66819
+ if (!this.observer)
66820
+ return;
66821
+ try {
66822
+ tell(this.observer);
66823
+ } catch {
66430
66824
  }
66431
66825
  }
66432
66826
  answerServerRequest(request3) {
@@ -66499,7 +66893,7 @@ function errToString(err) {
66499
66893
  }
66500
66894
 
66501
66895
  // ts/codex-agent/dist/dispatch.js
66502
- import { randomUUID as randomUUID7 } from "node:crypto";
66896
+ import { randomUUID as randomUUID8 } from "node:crypto";
66503
66897
  import * as path13 from "node:path";
66504
66898
 
66505
66899
  // ts/agent-core/dist/internal/attachment-input.js
@@ -68152,11 +68546,11 @@ var ForeignThreadRegistry = class {
68152
68546
  return this.threads.size;
68153
68547
  }
68154
68548
  openTurns() {
68155
- let count = 0;
68549
+ let count2 = 0;
68156
68550
  for (const thread of this.threads.values())
68157
68551
  if (thread.turn)
68158
- count += 1;
68159
- return count;
68552
+ count2 += 1;
68553
+ return count2;
68160
68554
  }
68161
68555
  /**
68162
68556
  * Notifications for a thread no dispatch owns. Returns false when the
@@ -68355,7 +68749,7 @@ function errToString4(err) {
68355
68749
  }
68356
68750
 
68357
68751
  // ts/codex-agent/dist/input-receipts.js
68358
- import { randomUUID as randomUUID6 } from "node:crypto";
68752
+ import { randomUUID as randomUUID7 } from "node:crypto";
68359
68753
  var CodexInputReceipts = class {
68360
68754
  log;
68361
68755
  inputs = /* @__PURE__ */ new Map();
@@ -68364,7 +68758,7 @@ var CodexInputReceipts = class {
68364
68758
  }
68365
68759
  register(sessionKey, threadId, lifecycle, turnId) {
68366
68760
  const input = {
68367
- clientId: randomUUID6(),
68761
+ clientId: randomUUID7(),
68368
68762
  sessionKey,
68369
68763
  threadId,
68370
68764
  turnId,
@@ -68643,12 +69037,22 @@ function buildThreadConfigOverrides({ reasoningEffort, capabilityBinDir: capabil
68643
69037
  }
68644
69038
  return Object.keys(config).length > 0 ? config : void 0;
68645
69039
  }
69040
+ var PARALL_PROVIDER = "parall";
69041
+ function assertResumedOnCurrentSource(result, useParallProvider) {
69042
+ if (useParallProvider)
69043
+ return;
69044
+ const resumed = result;
69045
+ const provider = resumed?.modelProvider ?? resumed?.thread?.modelProvider;
69046
+ if (provider === PARALL_PROVIDER) {
69047
+ throw new Error("the thread was opened on the Parall model source, which this agent no longer uses");
69048
+ }
69049
+ }
68646
69050
  function buildThreadOpenParams(opts, threadConfig) {
68647
69051
  const commonParams = {
68648
69052
  approvalPolicy: normalizeApprovalPolicy(opts.approvalPolicy)
68649
69053
  };
68650
69054
  if (opts.useParallProvider) {
68651
- commonParams.modelProvider = "parall";
69055
+ commonParams.modelProvider = PARALL_PROVIDER;
68652
69056
  }
68653
69057
  commonParams.sandbox = normalizeSandbox(opts.sandbox);
68654
69058
  if (opts.developerInstructions) {
@@ -68718,6 +69122,93 @@ function errToString5(err) {
68718
69122
  return err instanceof Error ? err.message : String(err);
68719
69123
  }
68720
69124
 
69125
+ // ts/codex-agent/dist/token-usage.js
69126
+ var MAX_TRACKED = 1024;
69127
+ var CodexProcessUsage = class {
69128
+ port;
69129
+ startedTurns = /* @__PURE__ */ new Set();
69130
+ threadModels = /* @__PURE__ */ new Map();
69131
+ constructor(port) {
69132
+ this.port = port;
69133
+ }
69134
+ notification(method, params) {
69135
+ if (method === "turn/started") {
69136
+ const turnId = extractTurnId(params);
69137
+ if (turnId)
69138
+ remember(this.startedTurns, turnId);
69139
+ return;
69140
+ }
69141
+ if (method !== "thread/tokenUsage/updated")
69142
+ return;
69143
+ const p = params ?? {};
69144
+ if (typeof p.turnId !== "string" || !this.startedTurns.has(p.turnId))
69145
+ return;
69146
+ const sample = sampleOf(p.tokenUsage?.last, this.modelOf(extractThreadIdFromNotification(params)));
69147
+ if (sample)
69148
+ this.port.emitUsage(sample);
69149
+ }
69150
+ response(method, params, result) {
69151
+ switch (method) {
69152
+ case "thread/start":
69153
+ case "thread/resume":
69154
+ case "thread/fork": {
69155
+ const threadId = extractThreadId(result) ?? (method === "thread/resume" ? paramOf(params, "threadId") : void 0);
69156
+ this.setModel(threadId, paramOf(result, "model"));
69157
+ return;
69158
+ }
69159
+ case "turn/start":
69160
+ this.setModel(paramOf(params, "threadId"), paramOf(params, "model"));
69161
+ return;
69162
+ }
69163
+ }
69164
+ setModel(threadId, model) {
69165
+ if (!threadId || !model)
69166
+ return;
69167
+ this.threadModels.delete(threadId);
69168
+ this.threadModels.set(threadId, model);
69169
+ if (this.threadModels.size > MAX_TRACKED) {
69170
+ this.threadModels.delete(this.threadModels.keys().next().value);
69171
+ }
69172
+ }
69173
+ /** The thread's model, refreshed as recently used so a busy thread is never evicted. */
69174
+ modelOf(threadId) {
69175
+ const model = threadId ? this.threadModels.get(threadId) : void 0;
69176
+ if (!threadId || !model)
69177
+ return "unknown";
69178
+ this.setModel(threadId, model);
69179
+ return model;
69180
+ }
69181
+ };
69182
+ function sampleOf(last, model) {
69183
+ if (!last || typeof last !== "object")
69184
+ return void 0;
69185
+ const usage = last;
69186
+ const input = count(usage.inputTokens);
69187
+ const cached = count(usage.cachedInputTokens);
69188
+ const sample = {
69189
+ model,
69190
+ inputTokens: Math.max(0, input - cached),
69191
+ cacheReadTokens: cached,
69192
+ cacheWriteTokens: count(usage.cacheWriteInputTokens),
69193
+ outputTokens: count(usage.outputTokens)
69194
+ };
69195
+ if (input === 0 && sample.cacheWriteTokens === 0 && sample.outputTokens === 0)
69196
+ return void 0;
69197
+ return sample;
69198
+ }
69199
+ function remember(set, value) {
69200
+ set.add(value);
69201
+ if (set.size > MAX_TRACKED)
69202
+ set.delete(set.values().next().value);
69203
+ }
69204
+ function paramOf(value, key) {
69205
+ const field = value && typeof value === "object" ? value[key] : void 0;
69206
+ return typeof field === "string" && field.trim() ? field : void 0;
69207
+ }
69208
+ function count(value) {
69209
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
69210
+ }
69211
+
68721
69212
  // ts/codex-agent/dist/dispatch.js
68722
69213
  var NEW_SESSION_ENDED = "Codex turn ended by New Session";
68723
69214
  var CodexAppServerAdapter = class {
@@ -68838,7 +69329,7 @@ var CodexAppServerAdapter = class {
68838
69329
  /**
68839
69330
  * Replace the variables the agent's shell commands receive. They ride
68840
69331
  * `shell_environment_policy.set` in thread-open params, and a thread that
68841
- * is already open ignores a changed policy (probes/shell-env-0.166.0.md), so
69332
+ * is already open ignores a changed policy (probes/shell-env-0.169.0.md), so
68842
69333
  * a running app-server is restarted at the next safe point. A thread opened
68843
69334
  * after this call — a fork — carries the new set without that restart (same
68844
69335
  * record, S5). Re-sending the version already held changes nothing.
@@ -68939,6 +69430,9 @@ var CodexAppServerAdapter = class {
68939
69430
  subscribeRuntimeActivity(handler) {
68940
69431
  return this.activity.subscribe(handler);
68941
69432
  }
69433
+ subscribeUsage(handler) {
69434
+ return this.activity.subscribeUsage(handler);
69435
+ }
68942
69436
  /**
68943
69437
  * Busy = a dispatch turn, a dispatch opening its thread (possibly running
68944
69438
  * the instructions-refresh compaction turn), or a subagent thread's turn
@@ -69009,7 +69503,7 @@ var CodexAppServerAdapter = class {
69009
69503
  }
69010
69504
  const sink = new TurnSink(noteActivity);
69011
69505
  this.setActiveTurn(threadId, sink, log2);
69012
- const groupKey = randomUUID7();
69506
+ const groupKey = randomUUID8();
69013
69507
  let sawTurnEnd = false;
69014
69508
  let releasePreparedAttachments = () => {
69015
69509
  };
@@ -69213,9 +69707,6 @@ var CodexAppServerAdapter = class {
69213
69707
  }
69214
69708
  return { ok: true, client, threadId, reconcile };
69215
69709
  }
69216
- getBranchPoint(_sessionKey) {
69217
- return void 0;
69218
- }
69219
69710
  async forkSession({ sessionKey: parentSessionKey }) {
69220
69711
  const client = this.client;
69221
69712
  if (!client)
@@ -69243,16 +69734,13 @@ var CodexAppServerAdapter = class {
69243
69734
  this.opts.sessionManager.recordThreadId(handle.sessionKey, forkedThreadId);
69244
69735
  return handle;
69245
69736
  } catch (err) {
69246
- return this.logForkFailure(err);
69737
+ this.opts.log?.warn?.(`thread/fork failed: ${errToString6(err)}`);
69738
+ return null;
69247
69739
  }
69248
69740
  }
69249
69741
  cleanupFork({ fork }) {
69250
69742
  this.opts.sessionManager.cleanupFork(fork.sessionKey);
69251
69743
  }
69252
- logForkFailure(err) {
69253
- this.opts.log?.warn?.(`thread/fork failed: ${errToString6(err)}`);
69254
- return null;
69255
- }
69256
69744
  /**
69257
69745
  * Lazily restart the app-server before the NEXT turn, so a subprocess that
69258
69746
  * has been running since before a capability change starts clean. Deferred
@@ -69375,6 +69863,7 @@ var CodexAppServerAdapter = class {
69375
69863
  log: log2 ?? this.opts.log
69376
69864
  });
69377
69865
  const client = new JsonRpcStdioClient(proc, void 0, (p) => this.appServers.retire(p));
69866
+ client.observe(new CodexProcessUsage(this.activity));
69378
69867
  client.setNotificationHandler((method, params) => this.routeNotification(method, params));
69379
69868
  client.setServerRequestHandler((method, params) => {
69380
69869
  const denial = answerServerRequest(method);
@@ -69441,6 +69930,8 @@ var CodexAppServerAdapter = class {
69441
69930
  ...commonParams
69442
69931
  } : { cwd: this.opts.workspaceDir, ...commonParams };
69443
69932
  const result = await client.sendRequest(method, params);
69933
+ if (opts.resumeId)
69934
+ assertResumedOnCurrentSource(result, this.opts.useParallProvider);
69444
69935
  const threadId = extractThreadId(result) ?? opts.resumeId;
69445
69936
  if (!threadId) {
69446
69937
  throw new Error(`${method} returned no thread id`);
@@ -69799,11 +70290,7 @@ function resolveWriteTarget(filePath) {
69799
70290
  throw new Error(`symlink chain deeper than 40 while resolving ${filePath}`);
69800
70291
  }
69801
70292
  function isParallProxyMode(env = process.env) {
69802
- const baseUrl = env.OPENAI_BASE_URL?.trim()?.replace(/\/+$/, "");
69803
- const apiUrl = env.PRLL_API_URL?.trim()?.replace(/\/+$/, "");
69804
- if (!baseUrl || !apiUrl)
69805
- return false;
69806
- return baseUrl === apiUrl || baseUrl.startsWith(`${apiUrl}/`);
70293
+ return isParallModelEndpoint(env.OPENAI_BASE_URL, env.PRLL_API_URL);
69807
70294
  }
69808
70295
  function tomlBasicString(value) {
69809
70296
  let out = "";
@@ -70110,6 +70597,8 @@ async function main() {
70110
70597
  driver: "app-server"
70111
70598
  },
70112
70599
  dispatchAdapter: adapter,
70600
+ // The CLI's own-login usage, not the Parall proxy's (already metered).
70601
+ reportRuntimeUsage: !useParallProvider,
70113
70602
  log: agentLog,
70114
70603
  // Live capability view for hint routing: the channel reply hint points
70115
70604
  // at the vendor CLI only while the grant is active.