@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((resolve3, 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(signal, reason, count = 1) {
58734
- this.opts.onEvent?.({ kind: "dropped", signal, reason, count });
58856
+ recordDrop(signal, reason, count2 = 1) {
58857
+ this.opts.onEvent?.({ kind: "dropped", signal, 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((resolve3) => {
61632
+ timer = setTimeout(() => {
61633
+ expired = true;
61634
+ resolve3();
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((resolve3) => {
61768
+ const done = () => {
61769
+ clearTimeout(timer);
61770
+ if (this.wake === done)
61771
+ this.wake = null;
61772
+ resolve3();
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((resolve3) => {
@@ -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,
@@ -66055,6 +66416,7 @@ var RuntimeActivityPort = class {
66055
66416
  label;
66056
66417
  log;
66057
66418
  handler = null;
66419
+ usageHandler = null;
66058
66420
  constructor(label, log2) {
66059
66421
  this.label = label;
66060
66422
  this.log = log2;
@@ -66068,6 +66430,15 @@ var RuntimeActivityPort = class {
66068
66430
  this.handler = null;
66069
66431
  };
66070
66432
  }
66433
+ subscribeUsage(handler) {
66434
+ if (this.usageHandler)
66435
+ throw new Error(`${this.label} supports a single usage subscriber`);
66436
+ this.usageHandler = handler;
66437
+ return () => {
66438
+ if (this.usageHandler === handler)
66439
+ this.usageHandler = null;
66440
+ };
66441
+ }
66071
66442
  /** Hand an event to the subscriber; false when there is none or it threw. */
66072
66443
  emit(event, log2 = this.log) {
66073
66444
  if (!this.handler)
@@ -66080,6 +66451,14 @@ var RuntimeActivityPort = class {
66080
66451
  return false;
66081
66452
  }
66082
66453
  }
66454
+ /** One piece of model usage to the subscriber, if any; a throwing subscriber never breaks the caller. */
66455
+ emitUsage(sample, log2 = this.log) {
66456
+ try {
66457
+ this.usageHandler?.(sample);
66458
+ } catch (err) {
66459
+ log2?.warn?.(`usage subscriber threw: ${String(err)}`);
66460
+ }
66461
+ }
66083
66462
  /** A turn opened: to the subscriber when eligible, else drained here. */
66084
66463
  surfaceTurn(turn, eligible = true, log2 = this.log) {
66085
66464
  if (eligible && this.emit({ kind: "turn", turn }, log2))
@@ -66087,29 +66466,29 @@ var RuntimeActivityPort = class {
66087
66466
  void this.drainLocally(turn, log2);
66088
66467
  }
66089
66468
  async drainLocally(turn, log2 = this.log) {
66090
- let count = 0;
66469
+ let count2 = 0;
66091
66470
  let outcome;
66092
66471
  try {
66093
66472
  for await (const event of turn.events) {
66094
- count += 1;
66473
+ count2 += 1;
66095
66474
  if (event.type === "turn_outcome")
66096
66475
  outcome = event.outcome;
66097
66476
  }
66098
66477
  } catch (err) {
66099
66478
  log2?.warn?.(`local drain of runtime-initiated turn ${turn.groupKey} failed: ${String(err)}`);
66100
66479
  }
66101
- log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count} event(s), outcome=${outcome ?? "ok"}`);
66480
+ log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count2} event(s), outcome=${outcome ?? "ok"}`);
66102
66481
  }
66103
66482
  };
66104
66483
 
66105
66484
  // ts/agent-core/dist/runtime-turn-base.js
66106
- import { randomUUID as randomUUID5 } from "node:crypto";
66485
+ import { randomUUID as randomUUID6 } from "node:crypto";
66107
66486
  var RuntimeTurnBase = class {
66108
66487
  sessionKey;
66109
66488
  trigger;
66110
66489
  onDetach;
66111
66490
  childKind;
66112
- groupKey = randomUUID5();
66491
+ groupKey = randomUUID6();
66113
66492
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
66114
66493
  activityListeners = [];
66115
66494
  detached = false;
@@ -66188,6 +66567,9 @@ function resolveClaudeAgentConfig(env = process.env) {
66188
66567
  allowApiKey: env.PRLL_CLAUDE_ALLOW_API_KEY?.trim() === "1"
66189
66568
  };
66190
66569
  }
66570
+ function reportsRuntimeUsage(env = process.env) {
66571
+ return !isParallModelEndpoint(env.ANTHROPIC_BASE_URL, env.PRLL_API_URL);
66572
+ }
66191
66573
  function resolveWsUrl(apiUrl, explicitWsUrl, swimlaneName) {
66192
66574
  const base = explicitWsUrl || `${apiUrl.replace(/\/$/, "").replace(/^http/, "ws")}/ws`;
66193
66575
  if (!swimlaneName)
@@ -66280,7 +66662,7 @@ function createCommandEnv(opts) {
66280
66662
 
66281
66663
  // ts/claude-agent/dist/dispatch.js
66282
66664
  import { execSync as execSync2, spawn } from "node:child_process";
66283
- import { randomUUID as randomUUID10 } from "node:crypto";
66665
+ import { randomUUID as randomUUID11 } from "node:crypto";
66284
66666
  import * as fs11 from "node:fs";
66285
66667
  import * as path14 from "node:path";
66286
66668
 
@@ -66857,7 +67239,7 @@ function parseContentLength(value) {
66857
67239
  }
66858
67240
 
66859
67241
  // ts/claude-agent/dist/compact.js
66860
- import { randomUUID as randomUUID6 } from "node:crypto";
67242
+ import { randomUUID as randomUUID7 } from "node:crypto";
66861
67243
  async function runClaudeCompact(host, { sessionKey, signal, log: log2 }) {
66862
67244
  if (signal.aborted)
66863
67245
  return { status: "timeout" };
@@ -66871,7 +67253,7 @@ async function runClaudeCompact(host, { sessionKey, signal, log: log2 }) {
66871
67253
  if (state.inputs.hasPendingInjections() || state.inputs.hasUnsettledInjections()) {
66872
67254
  return { status: "failed", detail: "injections still pending on the session" };
66873
67255
  }
66874
- const delivery = state.inputs.register(`compact:${randomUUID6()}`, void 0, false);
67256
+ const delivery = state.inputs.register(`compact:${randomUUID7()}`, void 0, false);
66875
67257
  try {
66876
67258
  host.writeUserMessage(state.handle, "/compact", delivery.commandUuid);
66877
67259
  } catch (err) {
@@ -66944,7 +67326,7 @@ var ClaudeBusyTracker = class {
66944
67326
  * REPLACE frame arrives BEFORE the task_notification for the task it
66945
67327
  * removed (2.1.292 sends it after), and the notification itself carries
66946
67328
  * only a summary. Both orders occur — self-hosted machines run whatever
66947
- * CLI the user installed (probes/background-tasks-2.1.318.md).
67329
+ * CLI the user installed (probes/background-tasks-2.1.325.md).
66948
67330
  */
66949
67331
  finishedDescriptions = /* @__PURE__ */ new Map();
66950
67332
  constructor(holdMs = DEFAULT_FOLLOW_UP_HOLD_MS) {
@@ -67060,6 +67442,106 @@ function aggregateBusyState(states) {
67060
67442
  return { activeTurns, backgroundWork, ...holdUntil !== void 0 ? { holdUntil } : {} };
67061
67443
  }
67062
67444
 
67445
+ // ts/claude-agent/dist/result-usage.js
67446
+ function parseResultUsage(frame) {
67447
+ const sinceLastResult = perModel(frame.model_usage_since_last_result);
67448
+ const cumulative = perModel(frame.modelUsage);
67449
+ const usage = isRecord(frame.usage) ? frame.usage : void 0;
67450
+ const mainLoop = usage ? {
67451
+ inputTokens: count(usage.input_tokens),
67452
+ cacheReadTokens: count(usage.cache_read_input_tokens),
67453
+ cacheWriteTokens: count(usage.cache_creation_input_tokens),
67454
+ outputTokens: count(usage.output_tokens)
67455
+ } : void 0;
67456
+ if (!sinceLastResult && !cumulative && !mainLoop)
67457
+ return void 0;
67458
+ return {
67459
+ ...sinceLastResult ? { sinceLastResult } : {},
67460
+ ...cumulative ? { cumulative } : {},
67461
+ ...mainLoop ? { mainLoop } : {}
67462
+ };
67463
+ }
67464
+ var ClaudeUsageMeter = class {
67465
+ /** The init frame's model: where the first result's main-loop usage is booked. */
67466
+ mainModel;
67467
+ /** The last `modelUsage` seen, for CLIs without the per-result field. */
67468
+ baseline;
67469
+ noteInit(model) {
67470
+ if (model)
67471
+ this.mainModel = model;
67472
+ }
67473
+ samples(usage) {
67474
+ if (!usage)
67475
+ return [];
67476
+ const previous = this.baseline;
67477
+ if (usage.cumulative)
67478
+ this.baseline = usage.cumulative;
67479
+ if (usage.sinceLastResult)
67480
+ return samplesOf(usage.sinceLastResult);
67481
+ if (!previous) {
67482
+ return usage.mainLoop ? samplesOf(/* @__PURE__ */ new Map([[this.mainModel ?? "unknown", usage.mainLoop]])) : [];
67483
+ }
67484
+ if (!usage.cumulative)
67485
+ return [];
67486
+ if (decreased(previous, usage.cumulative))
67487
+ return samplesOf(usage.cumulative);
67488
+ return samplesOf(difference(usage.cumulative, previous));
67489
+ }
67490
+ };
67491
+ var FIELDS = ["inputTokens", "cacheReadTokens", "cacheWriteTokens", "outputTokens"];
67492
+ function decreased(previous, current) {
67493
+ for (const [model, before] of previous) {
67494
+ const now = current.get(model);
67495
+ if (FIELDS.some((field) => (now?.[field] ?? 0) < before[field]))
67496
+ return true;
67497
+ }
67498
+ return false;
67499
+ }
67500
+ function difference(current, previous) {
67501
+ const out = /* @__PURE__ */ new Map();
67502
+ for (const [model, now] of current) {
67503
+ const before = previous.get(model);
67504
+ out.set(model, {
67505
+ inputTokens: now.inputTokens - (before?.inputTokens ?? 0),
67506
+ cacheReadTokens: now.cacheReadTokens - (before?.cacheReadTokens ?? 0),
67507
+ cacheWriteTokens: now.cacheWriteTokens - (before?.cacheWriteTokens ?? 0),
67508
+ outputTokens: now.outputTokens - (before?.outputTokens ?? 0)
67509
+ });
67510
+ }
67511
+ return out;
67512
+ }
67513
+ function samplesOf(perModelCounts) {
67514
+ const samples = [];
67515
+ for (const [model, counts] of perModelCounts) {
67516
+ if (FIELDS.every((field) => counts[field] === 0))
67517
+ continue;
67518
+ samples.push({ model, ...counts });
67519
+ }
67520
+ return samples;
67521
+ }
67522
+ function perModel(value) {
67523
+ if (!isRecord(value))
67524
+ return void 0;
67525
+ const out = /* @__PURE__ */ new Map();
67526
+ for (const [model, entry] of Object.entries(value)) {
67527
+ if (!model.trim() || !isRecord(entry))
67528
+ continue;
67529
+ out.set(model, {
67530
+ inputTokens: count(entry.inputTokens),
67531
+ cacheReadTokens: count(entry.cacheReadInputTokens),
67532
+ cacheWriteTokens: count(entry.cacheCreationInputTokens),
67533
+ outputTokens: count(entry.outputTokens)
67534
+ });
67535
+ }
67536
+ return out;
67537
+ }
67538
+ function isRecord(value) {
67539
+ return value !== null && typeof value === "object" && !Array.isArray(value);
67540
+ }
67541
+ function count(value) {
67542
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
67543
+ }
67544
+
67063
67545
  // ts/claude-agent/dist/runtime-observations.js
67064
67546
  function claudeObservation(frame) {
67065
67547
  const sessionId = observationField(frame.session_id);
@@ -67232,10 +67714,12 @@ async function* parseClaudeStreamJson(readable) {
67232
67714
  if (eventRecord.subtype === "init") {
67233
67715
  const sessionId = asTrimmedString(eventRecord.session_id);
67234
67716
  const capabilities = Array.isArray(eventRecord.capabilities) ? eventRecord.capabilities.map((capability) => asTrimmedString(capability)).filter((capability) => Boolean(capability)) : [];
67717
+ const model = asTrimmedString(eventRecord.model);
67235
67718
  yield {
67236
67719
  type: "runtime_init",
67237
67720
  ...sessionId ? { sessionId } : {},
67238
- capabilities
67721
+ capabilities,
67722
+ ...model ? { model } : {}
67239
67723
  };
67240
67724
  if (observation)
67241
67725
  yield observation;
@@ -67348,13 +67832,15 @@ async function* parseClaudeStreamJson(readable) {
67348
67832
  toolUses.clear();
67349
67833
  const numTurns = asFiniteNumber(eventRecord.num_turns);
67350
67834
  const userMessageUuid = asTrimmedString(eventRecord.user_message_uuid) || asTrimmedString(eventRecord.command_uuid);
67835
+ const usage = parseResultUsage(eventRecord);
67351
67836
  yield {
67352
67837
  type: "turn_end",
67353
67838
  sessionId: asTrimmedString(eventRecord.session_id),
67354
67839
  ...userMessageUuid ? { userMessageUuid } : {},
67355
67840
  isError,
67356
67841
  ...numTurns !== void 0 ? { numTurns } : {},
67357
- resultMeta: extractResultMeta(eventRecord, isError, numTurns)
67842
+ resultMeta: extractResultMeta(eventRecord, isError, numTurns),
67843
+ ...usage ? { usage } : {}
67358
67844
  };
67359
67845
  continue;
67360
67846
  }
@@ -67500,11 +67986,11 @@ function extractResultMeta(frame, isError, numTurns) {
67500
67986
  }
67501
67987
 
67502
67988
  // ts/claude-agent/dist/stdin-frames.js
67503
- import { randomUUID as randomUUID7 } from "node:crypto";
67989
+ import { randomUUID as randomUUID8 } from "node:crypto";
67504
67990
  function writeCapabilityProbe(handle) {
67505
67991
  const payload = JSON.stringify({
67506
67992
  type: "user",
67507
- uuid: randomUUID7(),
67993
+ uuid: randomUUID8(),
67508
67994
  parent_tool_use_id: null,
67509
67995
  message: { role: "user", content: [] }
67510
67996
  });
@@ -67543,7 +68029,7 @@ var ClaudeCapabilityProbe = class {
67543
68029
  * Whether spawns pass `--system-prompt-snapshot off`. The CLI records the
67544
68030
  * system prompt on a conversation's first request and resends that record on
67545
68031
  * every later request and --resume, so a rewritten prompt file would never
67546
- * reach a resumed session (probes/system-prompt-snapshot-2.1.318.md). CLIs
68032
+ * reach a resumed session (probes/system-prompt-snapshot-2.1.325.md). CLIs
67547
68033
  * that predate the recording also lack the flag and exit on it; the probe
67548
68034
  * observes that once and spawns without it from then on.
67549
68035
  */
@@ -67621,7 +68107,7 @@ var ClaudeCapabilityProbe = class {
67621
68107
  };
67622
68108
 
67623
68109
  // ts/claude-agent/dist/input-lifecycle.js
67624
- import { randomUUID as randomUUID8 } from "node:crypto";
68110
+ import { randomUUID as randomUUID9 } from "node:crypto";
67625
68111
 
67626
68112
  // ts/claude-agent/dist/turn-outcome.js
67627
68113
  var LIMIT_TEXT = /you'?ve (hit|reached) your .*limit|usage limit reached|weekly limit/i;
@@ -67873,7 +68359,7 @@ var ClaudeInputRegistry = class {
67873
68359
  if (this.byKey.has(deliveryKey)) {
67874
68360
  throw new Error(`duplicate Claude delivery key ${deliveryKey}`);
67875
68361
  }
67876
- const commandUuid = randomUUID8();
68362
+ const commandUuid = randomUUID9();
67877
68363
  const delivery = {
67878
68364
  deliveryKey,
67879
68365
  commandUuid,
@@ -68342,6 +68828,8 @@ var ClaudeProcessPump = class {
68342
68828
  activeDrain = null;
68343
68829
  now;
68344
68830
  pendingObservations = [];
68831
+ /** The model usage this process's result frames state (result-usage.ts). */
68832
+ usage = new ClaudeUsageMeter();
68345
68833
  constructor(opts) {
68346
68834
  this.opts = opts;
68347
68835
  this.now = opts.now ?? Date.now;
@@ -68378,7 +68866,7 @@ var ClaudeProcessPump = class {
68378
68866
  * A local input may join only a turn executing now (a started dispatch or
68379
68867
  * steer delivery, or an open runtime-initiated turn), and never while any
68380
68868
  * input waits to start: queued inputs start together as one turn that
68381
- * answers only the last (probes/queue-steer-2.1.318.md S3).
68869
+ * answers only the last (probes/queue-steer-2.1.325.md S3).
68382
68870
  */
68383
68871
  acceptsLocalInput() {
68384
68872
  let executing = this.runtimeTurn !== null;
@@ -68413,7 +68901,7 @@ var ClaudeProcessPump = class {
68413
68901
  /**
68414
68902
  * Dispatch abort: fail every live delivery and release its drain. Local
68415
68903
  * inputs are left alone: the CLI still runs a queued one, even after stdin
68416
- * closes (probes/queue-steer-2.1.318.md S5), so failing it here would
68904
+ * closes (probes/queue-steer-2.1.325.md S5), so failing it here would
68417
68905
  * report it undelivered and hand it out a second time.
68418
68906
  */
68419
68907
  abortDeliveries(message) {
@@ -68647,6 +69135,7 @@ var ClaudeProcessPump = class {
68647
69135
  }
68648
69136
  handleInit(init) {
68649
69137
  this.capabilities = new Set(init.capabilities);
69138
+ this.usage.noteInit(init.model);
68650
69139
  if (init.sessionId)
68651
69140
  this.sessionId = init.sessionId;
68652
69141
  const fatal = this.opts.hooks.onRuntimeInit(init);
@@ -68728,6 +69217,8 @@ var ClaudeProcessPump = class {
68728
69217
  }
68729
69218
  }
68730
69219
  async handleTurnEnd(parsed) {
69220
+ for (const sample of this.usage.samples(parsed.usage))
69221
+ this.opts.activity.emitUsage(sample);
68731
69222
  const live = this.liveDeliveries();
68732
69223
  const owner = this.ownerFor(false);
68733
69224
  if (parsed.numTurns !== 0 && owner)
@@ -68812,7 +69303,7 @@ function ownsFrames(delivery) {
68812
69303
  // ts/claude-agent/dist/session-manager.js
68813
69304
  import * as fs9 from "node:fs";
68814
69305
  import * as path12 from "node:path";
68815
- import { randomUUID as randomUUID9 } from "node:crypto";
69306
+ import { randomUUID as randomUUID10 } from "node:crypto";
68816
69307
  var ClaudeSessionManager = class _ClaudeSessionManager {
68817
69308
  mainSessionKey;
68818
69309
  stateFilePath;
@@ -68854,7 +69345,7 @@ var ClaudeSessionManager = class _ClaudeSessionManager {
68854
69345
  const parentSessionId = this.sessionIds.get(parentSessionKey);
68855
69346
  if (!parentSessionId)
68856
69347
  return null;
68857
- const sessionKey = `${_ClaudeSessionManager.FORK_LANE_PREFIX}${randomUUID9()}`;
69348
+ const sessionKey = `${_ClaudeSessionManager.FORK_LANE_PREFIX}${randomUUID10()}`;
68858
69349
  this.pendingForkParents.set(sessionKey, parentSessionId);
68859
69350
  return {
68860
69351
  sessionKey,
@@ -69107,14 +69598,13 @@ var ClaudeCodeAdapter = class {
69107
69598
  terminateHandle: (handle) => this.terminateHandle(handle)
69108
69599
  });
69109
69600
  shuttingDown = false;
69110
- activity;
69601
+ activity = new RuntimeActivityPort("ClaudeCodeAdapter");
69111
69602
  _model;
69112
69603
  _effortLevel;
69113
69604
  _contextWindow;
69114
69605
  _maxTokens;
69115
69606
  constructor(opts) {
69116
69607
  this.opts = opts;
69117
- this.activity = new RuntimeActivityPort("ClaudeCodeAdapter");
69118
69608
  this._model = opts.model;
69119
69609
  this._contextWindow = opts.contextWindow;
69120
69610
  this._maxTokens = opts.maxTokens;
@@ -69157,6 +69647,9 @@ var ClaudeCodeAdapter = class {
69157
69647
  subscribeRuntimeActivity(handler) {
69158
69648
  return this.activity.subscribe(handler);
69159
69649
  }
69650
+ subscribeUsage(handler) {
69651
+ return this.activity.subscribeUsage(handler);
69652
+ }
69160
69653
  busyState(now = this.now()) {
69161
69654
  const states = [];
69162
69655
  for (const state of this.processes.values()) {
@@ -69316,9 +69809,6 @@ var ClaudeCodeAdapter = class {
69316
69809
  releasePreparedAttachments();
69317
69810
  }
69318
69811
  }
69319
- getBranchPoint(_sessionKey) {
69320
- return void 0;
69321
- }
69322
69812
  getSessionHistoryPath(sessionKey) {
69323
69813
  const sessionId = this.opts.sessionManager.getSessionId(sessionKey);
69324
69814
  if (!sessionId)
@@ -69412,7 +69902,7 @@ var ClaudeCodeAdapter = class {
69412
69902
  async *consumeDelivery(sessionKey, state, target, noteActivity) {
69413
69903
  if (target.terminal)
69414
69904
  return;
69415
- const groupKey = randomUUID10();
69905
+ const groupKey = randomUUID11();
69416
69906
  state.pump.setActiveDrain(target, noteActivity);
69417
69907
  try {
69418
69908
  while (true) {
@@ -69901,6 +70391,8 @@ async function main() {
69901
70391
  claude_home: config.claudeHome
69902
70392
  },
69903
70393
  dispatchAdapter: adapter,
70394
+ // After resolveProviderEnv: the CLI's own-login usage, not Parall's metered models.
70395
+ reportRuntimeUsage: reportsRuntimeUsage(),
69904
70396
  log: agentLog,
69905
70397
  // Live capability view for hint routing: the channel reply hint points
69906
70398
  // at the vendor CLI only while the grant is active (config manager