@parall/daemon 1.92.0 → 1.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22809,8 +22809,8 @@ var require_BatchSpanProcessorBase = __commonJS({
22809
22809
  _flushAll() {
22810
22810
  return new Promise((resolve4, reject) => {
22811
22811
  const promises = [];
22812
- const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
22813
- for (let i = 0, j = count; i < j; i++) {
22812
+ const count2 = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize);
22813
+ for (let i = 0, j = count2; i < j; i++) {
22814
22814
  promises.push(this._flushOneBatch());
22815
22815
  }
22816
22816
  Promise.all(promises).then(() => {
@@ -52431,6 +52431,7 @@ var ENDPOINTS = {
52431
52431
  AGENT_ME: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me`,
52432
52432
  AGENT_REPLY_POLICY_CAPABILITY: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/reply-policy-capability`,
52433
52433
  AGENT_RUNTIME_REPORT: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/runtime-report`,
52434
+ AGENT_LLM_USAGE: (orgId) => `${API_BASE2}/orgs/${orgId}/agents/me/llm-usage`,
52434
52435
  ...secretEndpoints(API_BASE2),
52435
52436
  AGENT_NEW_SESSION: (orgId, agentId) => `${API_BASE2}/orgs/${orgId}/agents/${agentId}/new-session`,
52436
52437
  AGENT_DEEP_RESET: (orgId, agentId) => `${API_BASE2}/orgs/${orgId}/agents/${agentId}/deep-reset`,
@@ -53748,6 +53749,10 @@ var ClipConnectionClient = class extends ChannelConversationClient {
53748
53749
  };
53749
53750
  return this.request("PUT", ENDPOINTS.ORG_CLIP_MCP_CONFIG_BY_ID(orgId, clipId, configId), req, void 0, false, { headers: { "If-Match": `"${expectedVersion}"` }, timeoutMs: 4e4 });
53750
53751
  }
53752
+ /** Server-resolved hosted authorization; no client URL or secret fields. */
53753
+ async connectManagedMCP(orgId, clipId, alias, target) {
53754
+ return this.request(target ? "PUT" : "POST", target ? ENDPOINTS.ORG_CLIP_MCP_CONFIG_BY_ID(orgId, clipId, target.config_id) : ENDPOINTS.ORG_CLIP_MCP_CONFIGS(orgId, clipId), { auth_type: "managed", ...alias ? { alias } : {} }, void 0, false, { headers: target ? { "If-Match": `"${target.version}"` } : void 0, timeoutMs: 11e4 });
53755
+ }
53751
53756
  // ---- Clip connections ----
53752
53757
  /** Missing keys are unknown/hidden; present empty arrays are known empty. */
53753
53758
  async listClipMCPSummaries(orgId, clipIds) {
@@ -54249,10 +54254,25 @@ var AgentOwningTeamClient = class extends AgentTeamOnlyClient {
54249
54254
  }
54250
54255
  };
54251
54256
 
54257
+ // ts/sdk/dist/runtime-auth-llm-usage-client.js
54258
+ var RuntimeAuthLlmUsageClient = class extends AgentOwningTeamClient {
54259
+ /**
54260
+ * Record one batch of usage. The agent's own API key only (403 AGENT_ONLY
54261
+ * otherwise); 204 also for a batch already recorded; 400 for a batch out of
54262
+ * bounds; 409 LLM_ROUTE_NOT_RUNTIME_AUTH when the agent's model route is
54263
+ * not runtime_auth. A server without the endpoint answers 404 with no error
54264
+ * code. Every refusal surfaces as an ApiError with its status and code: what
54265
+ * to do about it is the caller's decision.
54266
+ */
54267
+ async reportRuntimeAuthLlmUsage(orgId, report, opts) {
54268
+ await this.request("POST", ENDPOINTS.AGENT_LLM_USAGE(orgId), report, void 0, false, opts);
54269
+ }
54270
+ };
54271
+
54252
54272
  // ts/sdk/dist/team-graph-client.js
54253
- var TeamGraphClient = class extends AgentOwningTeamClient {
54273
+ var TeamGraphClient = class extends RuntimeAuthLlmUsageClient {
54254
54274
  async getTeamGraph(orgId, opts) {
54255
- const query = opts?.includeAccess ? "?include=access" : "";
54275
+ const query = opts?.includeAccess ? "?include=access&include=apps" : "";
54256
54276
  return this.request("GET", `${ENDPOINTS.TEAM_GRAPH(orgId)}${query}`);
54257
54277
  }
54258
54278
  /**
@@ -57112,9 +57132,8 @@ var ParallClient = class _ParallClient extends TemplateCatalogClient {
57112
57132
  }
57113
57133
  async createClipMCPConnection(orgId, clipId, req) {
57114
57134
  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
57135
+ // Managed no-auth cards also perform a bounded session probe and completion.
57136
+ timeoutMs: "approval_id" in req ? 11e4 : 4e4
57118
57137
  });
57119
57138
  }
57120
57139
  /** Delete one MCP config and its paired connection. */
@@ -57141,8 +57160,8 @@ var ParallClient = class _ParallClient extends TemplateCatalogClient {
57141
57160
  void 0,
57142
57161
  void 0,
57143
57162
  false,
57144
- // Same fixed 30s server-side probe budget as PUT (see putClipMCPConfig).
57145
- { timeoutMs: 4e4 }
57163
+ // Managed refresh includes account readback and session creation (60s).
57164
+ { timeoutMs: 7e4 }
57146
57165
  );
57147
57166
  }
57148
57167
  // ---- Deprecated method aliases (External* → Trigger* rename; same endpoints) ----
@@ -57278,6 +57297,10 @@ function buildApiError(res, rawErrorBody) {
57278
57297
  return apiError;
57279
57298
  }
57280
57299
 
57300
+ // ts/sdk/dist/runtime-auth-llm-usage-types.js
57301
+ var RUNTIME_AUTH_LLM_USAGE_MAX_MODELS = 8;
57302
+ var LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE = "LLM_ROUTE_NOT_RUNTIME_AUTH";
57303
+
57281
57304
  // ts/sdk/dist/ws.js
57282
57305
  function describeWsStateDetail(detail) {
57283
57306
  if (!detail)
@@ -57708,6 +57731,13 @@ function clearAllProviderCreds(env) {
57708
57731
  delete env[name];
57709
57732
  delete env.PRLL_CLAUDE_ALLOW_API_KEY;
57710
57733
  }
57734
+ function isParallModelEndpoint(endpoint, apiUrl) {
57735
+ const base = endpoint?.trim().replace(/\/+$/, "");
57736
+ const api = apiUrl?.trim().replace(/\/+$/, "");
57737
+ if (!base || !api)
57738
+ return false;
57739
+ return base === api || base.startsWith(`${api}/`);
57740
+ }
57711
57741
  function parseProviderConfig(env) {
57712
57742
  const raw = env.PRLL_PROVIDER_CONFIG?.trim();
57713
57743
  if (!raw)
@@ -58730,8 +58760,8 @@ var OtlpSpoolStore = class {
58730
58760
  return this.opts.dir;
58731
58761
  }
58732
58762
  /** 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 });
58763
+ recordDrop(signal2, reason, count2 = 1) {
58764
+ this.opts.onEvent?.({ kind: "dropped", signal: signal2, reason, count: count2 });
58735
58765
  }
58736
58766
  /**
58737
58767
  * Append one serialized request. Resolves once the file is renamed into
@@ -59041,6 +59071,19 @@ var dispatchSpans = /* @__PURE__ */ new WeakSet();
59041
59071
  var recordedErrors = /* @__PURE__ */ new WeakSet();
59042
59072
  var dispatchCounter = null;
59043
59073
  var dispatchDuration = null;
59074
+ var DISPATCH_DURATION_BUCKETS_MS = [
59075
+ 1e3,
59076
+ 2500,
59077
+ 5e3,
59078
+ 1e4,
59079
+ 2e4,
59080
+ 3e4,
59081
+ 6e4,
59082
+ 12e4,
59083
+ 3e5,
59084
+ 6e5,
59085
+ 18e5
59086
+ ];
59044
59087
  var missingReplyCounter = null;
59045
59088
  var turnTokensCounter = null;
59046
59089
  var turnCostCounter = null;
@@ -59194,7 +59237,7 @@ async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
59194
59237
  const metricExporter = spooled(new OTLPMetricExporter({ url: `${otelEndpoint}/v1/metrics`, headers: authHeaders }), "metrics", serializers?.ProtobufMetricsSerializer);
59195
59238
  const metricReader = new PeriodicExportingMetricReader({
59196
59239
  exporter: metricExporter,
59197
- exportIntervalMillis: 15e3
59240
+ exportIntervalMillis: 6e4
59198
59241
  });
59199
59242
  const meterProvider = new MeterProvider({ resource, readers: [metricReader] });
59200
59243
  metrics.setGlobalMeterProvider(meterProvider);
@@ -59208,7 +59251,8 @@ async function initAgentTelemetry(serviceName, runtimeType, opts = {}) {
59208
59251
  });
59209
59252
  dispatchDuration = meter.createHistogram("parall.dispatch.duration", {
59210
59253
  description: "Dispatch cycle duration in milliseconds",
59211
- unit: "ms"
59254
+ unit: "ms",
59255
+ advice: { explicitBucketBoundaries: DISPATCH_DURATION_BUCKETS_MS }
59212
59256
  });
59213
59257
  missingReplyCounter = meter.createCounter("parall.dispatch.missing_reply", {
59214
59258
  description: "Dispatches where agent produced text but sent no reply message"
@@ -61429,6 +61473,224 @@ async function closeRuntimeChildSession(host, sessionKey, reason) {
61429
61473
  }
61430
61474
  }
61431
61475
 
61476
+ // ts/agent-core/dist/gateway/runtime-usage-reporter.js
61477
+ import { randomUUID as randomUUID4 } from "node:crypto";
61478
+ var DEFAULT_INTERVAL_MS = 5 * 6e4;
61479
+ var DEFAULT_RETRY_DELAYS_MS3 = [5e3, 3e4, 12e4];
61480
+ var DEFAULT_FLUSH_MS = 5e3;
61481
+ var MAX_MODEL_NAME = 200;
61482
+ var MAX_COUNT = 1e12;
61483
+ var MAX_QUEUED_BATCHES = 64;
61484
+ var RuntimeUsageReporter = class {
61485
+ opts;
61486
+ enabled;
61487
+ /** Usage not cut into a batch yet, per model. */
61488
+ held = /* @__PURE__ */ new Map();
61489
+ /** Cut batches, oldest first; the head is the one being sent. */
61490
+ queue = [];
61491
+ /** Why the server refused the endpoint; null while reporting. Cleared by the next hello. */
61492
+ stoppedBy = null;
61493
+ disposed = false;
61494
+ flushing = false;
61495
+ sending = null;
61496
+ /** Ends a retry's backoff early (exit flush, dispose). */
61497
+ wake = null;
61498
+ inFlight = new AbortController();
61499
+ warnedRefusals = /* @__PURE__ */ new Set();
61500
+ timer = null;
61501
+ unsubscribe;
61502
+ constructor(opts) {
61503
+ this.opts = opts;
61504
+ const subscribe = opts.dispatchAdapter.subscribeUsage?.bind(opts.dispatchAdapter);
61505
+ this.enabled = opts.reportRuntimeUsage === true && subscribe !== void 0;
61506
+ if (!this.enabled || !subscribe)
61507
+ return;
61508
+ this.unsubscribe = subscribe((sample) => this.add(sample));
61509
+ this.timer = setInterval(() => this.cut(), opts.runtimeUsageIntervalMs ?? DEFAULT_INTERVAL_MS);
61510
+ this.timer.unref?.();
61511
+ }
61512
+ /**
61513
+ * Every hello. A 404 or a route refusal stops reporting until the next
61514
+ * connection: a rolling deploy's brief 404 must not silence the process
61515
+ * for its lifetime.
61516
+ */
61517
+ resume() {
61518
+ if (this.stoppedBy === null || this.disposed)
61519
+ return;
61520
+ this.opts.log?.info(`runtime usage: reporting resumed on hello (stopped by ${this.stoppedBy})`);
61521
+ this.stoppedBy = null;
61522
+ }
61523
+ /**
61524
+ * Shutdown, beside the step flush: cut what is held and send every waiting
61525
+ * batch once (a batch in its retry backoff goes now), within budgetMs.
61526
+ * Whatever has not gone out by then is dropped. Absorbing, like dispose().
61527
+ */
61528
+ async flush(budgetMs = this.opts.runtimeUsageFlushMs ?? DEFAULT_FLUSH_MS) {
61529
+ if (!this.enabled || this.disposed)
61530
+ return;
61531
+ let expired = false;
61532
+ let timer;
61533
+ try {
61534
+ this.flushing = true;
61535
+ this.stopObserving();
61536
+ this.cut();
61537
+ this.wake?.();
61538
+ const deadline = new Promise((resolve4) => {
61539
+ timer = setTimeout(() => {
61540
+ expired = true;
61541
+ resolve4();
61542
+ }, Math.max(0, budgetMs));
61543
+ });
61544
+ while (this.sending && !expired)
61545
+ await Promise.race([this.sending, deadline]);
61546
+ } catch (err) {
61547
+ this.opts.log?.warn(`runtime usage: exit flush failed: ${String(err)}`);
61548
+ } finally {
61549
+ clearTimeout(timer);
61550
+ this.dispose();
61551
+ }
61552
+ }
61553
+ /** No more samples, timers or posts; what is held or in flight is dropped. */
61554
+ dispose() {
61555
+ if (this.disposed)
61556
+ return;
61557
+ this.disposed = true;
61558
+ this.stopObserving();
61559
+ this.inFlight.abort();
61560
+ this.wake?.();
61561
+ const unsent = this.queue.length + (this.held.size > 0 ? 1 : 0);
61562
+ if (unsent > 0 && this.stoppedBy === null) {
61563
+ this.opts.log?.warn(`runtime usage: ${unsent} batch(es) not sent before exit, dropped`);
61564
+ }
61565
+ this.queue = [];
61566
+ this.held.clear();
61567
+ }
61568
+ stopObserving() {
61569
+ this.unsubscribe?.();
61570
+ if (this.timer)
61571
+ clearInterval(this.timer);
61572
+ }
61573
+ add(sample) {
61574
+ if (this.disposed || this.stoppedBy !== null)
61575
+ return;
61576
+ const counts = {
61577
+ input_tokens: tokenCount(sample.inputTokens),
61578
+ cache_read_tokens: tokenCount(sample.cacheReadTokens),
61579
+ cache_write_tokens: tokenCount(sample.cacheWriteTokens),
61580
+ output_tokens: tokenCount(sample.outputTokens)
61581
+ };
61582
+ if (Object.values(counts).every((n) => n === 0))
61583
+ return;
61584
+ const model = modelName(sample.model);
61585
+ const held = this.held.get(model);
61586
+ if (!held) {
61587
+ this.held.set(model, counts);
61588
+ return;
61589
+ }
61590
+ for (const key of Object.keys(counts)) {
61591
+ held[key] = Math.min(MAX_COUNT, held[key] + counts[key]);
61592
+ }
61593
+ }
61594
+ /** Held usage → batches of at most 8 models, each with its own id. */
61595
+ cut() {
61596
+ if (this.disposed || this.held.size === 0)
61597
+ return;
61598
+ const models = [...this.held].map(([model, counts]) => ({ model, ...counts }));
61599
+ this.held.clear();
61600
+ for (let i = 0; i < models.length; i += RUNTIME_AUTH_LLM_USAGE_MAX_MODELS) {
61601
+ const chunk = models.slice(i, i + RUNTIME_AUTH_LLM_USAGE_MAX_MODELS);
61602
+ this.queue.push({ id: randomUUID4(), models: chunk, attempts: 0 });
61603
+ }
61604
+ if (this.queue.length > MAX_QUEUED_BATCHES) {
61605
+ const dropped = this.queue.splice(0, this.queue.length - MAX_QUEUED_BATCHES);
61606
+ this.opts.log?.warn(`runtime usage: ${dropped.length} unsent batch(es) dropped (backlog)`);
61607
+ }
61608
+ this.kick();
61609
+ }
61610
+ /** One send loop at a time; a batch cut while it was finishing starts the next. */
61611
+ kick() {
61612
+ if (this.sending || this.disposed)
61613
+ return;
61614
+ this.sending = this.sendQueued().catch((err) => this.opts.log?.warn(`runtime usage: send loop failed: ${String(err)}`)).finally(() => {
61615
+ this.sending = null;
61616
+ if (this.queue.length > 0 && this.stoppedBy === null)
61617
+ this.kick();
61618
+ });
61619
+ }
61620
+ async sendQueued() {
61621
+ const delays = this.opts.runtimeUsageRetryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS3;
61622
+ while (this.queue.length > 0 && this.stoppedBy === null && !this.disposed) {
61623
+ const batch = this.queue[0];
61624
+ const outcome = await this.post(batch);
61625
+ if (outcome === "stopped")
61626
+ return;
61627
+ if (outcome === "retry") {
61628
+ const delay = delays[batch.attempts - 1];
61629
+ if (delay !== void 0 && !this.flushing && !this.disposed) {
61630
+ await this.backoff(delay);
61631
+ continue;
61632
+ }
61633
+ if (!this.disposed) {
61634
+ this.opts.log?.warn(`runtime usage: batch ${batch.id} dropped after ${batch.attempts} attempt(s)`);
61635
+ }
61636
+ }
61637
+ if (this.queue[0] === batch)
61638
+ this.queue.shift();
61639
+ }
61640
+ }
61641
+ async post(batch) {
61642
+ batch.attempts += 1;
61643
+ try {
61644
+ await this.opts.client.reportRuntimeAuthLlmUsage(this.opts.config.org_id, { batch_id: batch.id, models: batch.models }, { signal: this.inFlight.signal });
61645
+ return "done";
61646
+ } catch (err) {
61647
+ if (!(err instanceof ApiError) || err.status === 0 || err.status >= 500)
61648
+ return "retry";
61649
+ if (err.status === 404 && !err.code) {
61650
+ this.stop("a server without the usage endpoint (404)");
61651
+ return "stopped";
61652
+ }
61653
+ if (err.status === 409 && err.code === LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE) {
61654
+ this.stop(`the server (${LLM_ROUTE_NOT_RUNTIME_AUTH_ERROR_CODE})`);
61655
+ return "stopped";
61656
+ }
61657
+ const kind = err.code ?? `HTTP ${err.status}`;
61658
+ if (!this.warnedRefusals.has(kind)) {
61659
+ this.warnedRefusals.add(kind);
61660
+ this.opts.log?.warn(`runtime usage: batch ${batch.id} refused, dropped: ${String(err)}`);
61661
+ }
61662
+ return "done";
61663
+ }
61664
+ }
61665
+ /** Stop until the next hello; nothing held survives it. */
61666
+ stop(by) {
61667
+ const dropped = this.queue.length + (this.held.size > 0 ? 1 : 0);
61668
+ this.stoppedBy = by;
61669
+ this.queue = [];
61670
+ this.held.clear();
61671
+ this.opts.log?.info(`runtime usage: reporting stopped by ${by} until the next hello; ${dropped} batch(es) dropped`);
61672
+ }
61673
+ backoff(ms) {
61674
+ return new Promise((resolve4) => {
61675
+ const done = () => {
61676
+ clearTimeout(timer);
61677
+ if (this.wake === done)
61678
+ this.wake = null;
61679
+ resolve4();
61680
+ };
61681
+ const timer = setTimeout(done, ms);
61682
+ timer.unref?.();
61683
+ this.wake = done;
61684
+ });
61685
+ }
61686
+ };
61687
+ function tokenCount(value) {
61688
+ return Number.isFinite(value) && value > 0 ? Math.min(MAX_COUNT, Math.floor(value)) : 0;
61689
+ }
61690
+ function modelName(model) {
61691
+ return (model.trim() || "unknown").slice(0, MAX_MODEL_NAME);
61692
+ }
61693
+
61432
61694
  // ts/agent-core/dist/gateway/drain.js
61433
61695
  var DrainGate = class {
61434
61696
  isDrained;
@@ -61609,7 +61871,7 @@ var DispatchInactivityDeadlines = class {
61609
61871
  };
61610
61872
 
61611
61873
  // ts/agent-core/dist/session/step-retry-queue.js
61612
- var DEFAULT_RETRY_DELAYS_MS3 = [5e3, 1e4, 2e4, 4e4, 6e4];
61874
+ var DEFAULT_RETRY_DELAYS_MS4 = [5e3, 1e4, 2e4, 4e4, 6e4];
61613
61875
  async function raceWithDeadline2(work, ms) {
61614
61876
  let timer;
61615
61877
  const timeout = new Promise((resolve4) => {
@@ -61639,7 +61901,7 @@ var StepRetryQueue = class {
61639
61901
  disposed = false;
61640
61902
  constructor(opts) {
61641
61903
  this.opts = opts;
61642
- this.retryDelays = opts.retryDelaysMs?.length ? opts.retryDelaysMs : DEFAULT_RETRY_DELAYS_MS3;
61904
+ this.retryDelays = opts.retryDelaysMs?.length ? opts.retryDelaysMs : DEFAULT_RETRY_DELAYS_MS4;
61643
61905
  }
61644
61906
  hasPending(sessionId) {
61645
61907
  return (this.queues.get(sessionId)?.length ?? 0) > 0;
@@ -62078,14 +62340,14 @@ function recordToolCall(sessionKey) {
62078
62340
  }
62079
62341
 
62080
62342
  // ts/agent-core/dist/gateway/input-steps.js
62081
- import { randomUUID as randomUUID4 } from "node:crypto";
62343
+ import { randomUUID as randomUUID5 } from "node:crypto";
62082
62344
  function inputStepIdempotencyKey(event) {
62083
62345
  if (event.type === "message" || event.type === "channel_message") {
62084
- return event.messageId ? `input:${event.messageId}` : randomUUID4();
62346
+ return event.messageId ? `input:${event.messageId}` : randomUUID5();
62085
62347
  }
62086
62348
  if (event.dispatchEventId)
62087
62349
  return `input:${event.dispatchEventId}`;
62088
- return randomUUID4();
62350
+ return randomUUID5();
62089
62351
  }
62090
62352
  function resolveStepTarget(event) {
62091
62353
  if (event.input?.step_target) {
@@ -62971,12 +63233,12 @@ async function catchUpFromDispatch(host) {
62971
63233
  let expireSummary = null;
62972
63234
  let overflowMode = false;
62973
63235
  try {
62974
- const { count } = await host.opts.client.getDispatchPendingCount(host.opts.config.org_id);
62975
- if (count > OVERFLOW_THRESHOLD) {
63236
+ const { count: count2 } = await host.opts.client.getDispatchPendingCount(host.opts.config.org_id);
63237
+ if (count2 > OVERFLOW_THRESHOLD) {
62976
63238
  overflowMode = true;
62977
63239
  const result = await host.opts.client.expireDispatch(host.opts.config.org_id, EXPIRE_AGE_HOURS);
62978
63240
  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`);
63241
+ host.opts.log?.warn(`dispatch catch-up overflow: ${count2} pending, expired ${result.total} events older than ${EXPIRE_AGE_HOURS}h`);
62980
63242
  expireSummary = host.buildOfflineSummary(result.groups);
62981
63243
  }
62982
63244
  }
@@ -63030,7 +63292,7 @@ async function catchUpFromDispatch(host) {
63030
63292
  if (expireSummary)
63031
63293
  parts.push(expireSummary);
63032
63294
  if (skipped > 0) {
63033
- const recentLines = [...skippedByType.entries()].map(([type, count]) => `- ${count} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
63295
+ const recentLines = [...skippedByType.entries()].map(([type, count2]) => `- ${count2} recent ${type.replace(".", " ").replace("_", " ")} events`).join("\n");
63034
63296
  parts.push(expireSummary ? `Additionally, ${skipped} recent events exceeded the catch-up limit and were skipped:
63035
63297
  ${recentLines}` : `[Offline Summary] You were offline. ${skipped} pending events exceeded the catch-up limit and were skipped:
63036
63298
  ${recentLines}
@@ -63174,6 +63436,7 @@ async function handleHello(host, data) {
63174
63436
  log2?.info("re-probing dispatch ledger after reconnect (was disabled)");
63175
63437
  host.ledgerDisabled = false;
63176
63438
  }
63439
+ host.runtimeUsage.resume();
63177
63440
  const intervalSec = data.heartbeat_interval > 0 ? data.heartbeat_interval : 30;
63178
63441
  let openFence = () => {
63179
63442
  };
@@ -63290,6 +63553,7 @@ async function shutdown(host, opts = { skipDrain: false }) {
63290
63553
  if (!settled()) {
63291
63554
  await host.drainGate.wait(5e3, settled);
63292
63555
  }
63556
+ const usageFlushed = host.runtimeUsage.flush();
63293
63557
  if (host.stepPersister.pendingTotal() > 0) {
63294
63558
  const remaining = await host.stepPersister.flush(1e4);
63295
63559
  if (remaining > 0) {
@@ -63297,6 +63561,7 @@ async function shutdown(host, opts = { skipDrain: false }) {
63297
63561
  }
63298
63562
  }
63299
63563
  host.stepPersister.dispose();
63564
+ await usageFlushed;
63300
63565
  const lifecycleRemaining = await host.sessionLifecycle.flush(5e3);
63301
63566
  if (lifecycleRemaining > 0) {
63302
63567
  host.opts.log?.warn(`${lifecycleRemaining} session lifecycle write(s) unreconciled at shutdown`);
@@ -63376,6 +63641,8 @@ var ParallAgentGateway = class {
63376
63641
  drainGate = new DrainGate(() => this.isDrained());
63377
63642
  runtimeActivity = createRuntimeActivityState();
63378
63643
  unsubscribeRuntimeActivity;
63644
+ // The runtime's own-login model usage, batched (gateway/runtime-usage-reporter.ts).
63645
+ runtimeUsage;
63379
63646
  pendingRestartNotification = null;
63380
63647
  laneLedger;
63381
63648
  stepPersister;
@@ -63419,6 +63686,7 @@ var ParallAgentGateway = class {
63419
63686
  this.DISPATCH_DEADLINE_MS = opts.dispatchDeadlineMs ?? 0;
63420
63687
  this.INACTIVITY_WARN_MS = opts.inactivityWarnMs ?? 30 * 6e4;
63421
63688
  this.unsubscribeRuntimeActivity = opts.dispatchAdapter.subscribeRuntimeActivity?.((event) => this.handleRuntimeActivity(event));
63689
+ this.runtimeUsage = new RuntimeUsageReporter(opts);
63422
63690
  this.stepPersister = new StepPersister({
63423
63691
  client: opts.client,
63424
63692
  orgId: opts.config.org_id,
@@ -66046,6 +66314,7 @@ var RuntimeActivityPort = class {
66046
66314
  label;
66047
66315
  log;
66048
66316
  handler = null;
66317
+ usageHandler = null;
66049
66318
  constructor(label, log2) {
66050
66319
  this.label = label;
66051
66320
  this.log = log2;
@@ -66059,6 +66328,15 @@ var RuntimeActivityPort = class {
66059
66328
  this.handler = null;
66060
66329
  };
66061
66330
  }
66331
+ subscribeUsage(handler) {
66332
+ if (this.usageHandler)
66333
+ throw new Error(`${this.label} supports a single usage subscriber`);
66334
+ this.usageHandler = handler;
66335
+ return () => {
66336
+ if (this.usageHandler === handler)
66337
+ this.usageHandler = null;
66338
+ };
66339
+ }
66062
66340
  /** Hand an event to the subscriber; false when there is none or it threw. */
66063
66341
  emit(event, log2 = this.log) {
66064
66342
  if (!this.handler)
@@ -66071,6 +66349,14 @@ var RuntimeActivityPort = class {
66071
66349
  return false;
66072
66350
  }
66073
66351
  }
66352
+ /** One piece of model usage to the subscriber, if any; a throwing subscriber never breaks the caller. */
66353
+ emitUsage(sample, log2 = this.log) {
66354
+ try {
66355
+ this.usageHandler?.(sample);
66356
+ } catch (err) {
66357
+ log2?.warn?.(`usage subscriber threw: ${String(err)}`);
66358
+ }
66359
+ }
66074
66360
  /** A turn opened: to the subscriber when eligible, else drained here. */
66075
66361
  surfaceTurn(turn, eligible = true, log2 = this.log) {
66076
66362
  if (eligible && this.emit({ kind: "turn", turn }, log2))
@@ -66078,29 +66364,29 @@ var RuntimeActivityPort = class {
66078
66364
  void this.drainLocally(turn, log2);
66079
66365
  }
66080
66366
  async drainLocally(turn, log2 = this.log) {
66081
- let count = 0;
66367
+ let count2 = 0;
66082
66368
  let outcome;
66083
66369
  try {
66084
66370
  for await (const event of turn.events) {
66085
- count += 1;
66371
+ count2 += 1;
66086
66372
  if (event.type === "turn_outcome")
66087
66373
  outcome = event.outcome;
66088
66374
  }
66089
66375
  } catch (err) {
66090
66376
  log2?.warn?.(`local drain of runtime-initiated turn ${turn.groupKey} failed: ${String(err)}`);
66091
66377
  }
66092
- log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count} event(s), outcome=${outcome ?? "ok"}`);
66378
+ log2?.info?.(`runtime-initiated turn ${turn.groupKey} on ${turn.sessionKey} (${describeRuntimeTurnTrigger(turn.trigger)}) drained locally: ${count2} event(s), outcome=${outcome ?? "ok"}`);
66093
66379
  }
66094
66380
  };
66095
66381
 
66096
66382
  // ts/agent-core/dist/runtime-turn-base.js
66097
- import { randomUUID as randomUUID5 } from "node:crypto";
66383
+ import { randomUUID as randomUUID6 } from "node:crypto";
66098
66384
  var RuntimeTurnBase = class {
66099
66385
  sessionKey;
66100
66386
  trigger;
66101
66387
  onDetach;
66102
66388
  childKind;
66103
- groupKey = randomUUID5();
66389
+ groupKey = randomUUID6();
66104
66390
  startedAt = (/* @__PURE__ */ new Date()).toISOString();
66105
66391
  activityListeners = [];
66106
66392
  detached = false;
@@ -66304,6 +66590,7 @@ var JsonRpcStdioClient = class {
66304
66590
  buffer = "";
66305
66591
  onNotification = null;
66306
66592
  onServerRequest = null;
66593
+ observer = null;
66307
66594
  disposed = false;
66308
66595
  constructor(proc, requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, killProcess) {
66309
66596
  this.proc = proc;
@@ -66321,6 +66608,9 @@ var JsonRpcStdioClient = class {
66321
66608
  setServerRequestHandler(handler) {
66322
66609
  this.onServerRequest = handler;
66323
66610
  }
66611
+ observe(observer) {
66612
+ this.observer = observer;
66613
+ }
66324
66614
  /**
66325
66615
  * `options.timeoutMs` overrides the client-wide budget for this request.
66326
66616
  * `options.lethalTimeout: false` makes a timeout reject WITHOUT killing the
@@ -66348,7 +66638,7 @@ var JsonRpcStdioClient = class {
66348
66638
  this.killUnhealthy(new Error(`request "${method}" timed out; subprocess assumed hung`));
66349
66639
  }
66350
66640
  }, timeoutMs);
66351
- this.pending.set(id, { resolve: resolve4, reject, timer });
66641
+ this.pending.set(id, { resolve: resolve4, reject, timer, method, params });
66352
66642
  });
66353
66643
  this.writeFrame(request3);
66354
66644
  return promise;
@@ -66417,6 +66707,7 @@ var JsonRpcStdioClient = class {
66417
66707
  if (message.error) {
66418
66708
  pending.reject(new JsonRpcError(message.error.code, message.error.message, message.error.data));
66419
66709
  } else {
66710
+ this.tellObserver((o) => o.response(pending.method, pending.params, message.result));
66420
66711
  pending.resolve(message.result);
66421
66712
  }
66422
66713
  return;
@@ -66426,7 +66717,17 @@ var JsonRpcStdioClient = class {
66426
66717
  return;
66427
66718
  }
66428
66719
  if (isNotification(message)) {
66429
- this.onNotification?.(message.method, message.params);
66720
+ const { method, params } = message;
66721
+ this.tellObserver((o) => o.notification(method, params));
66722
+ this.onNotification?.(method, params);
66723
+ }
66724
+ }
66725
+ tellObserver(tell) {
66726
+ if (!this.observer)
66727
+ return;
66728
+ try {
66729
+ tell(this.observer);
66730
+ } catch {
66430
66731
  }
66431
66732
  }
66432
66733
  answerServerRequest(request3) {
@@ -66499,7 +66800,7 @@ function errToString(err) {
66499
66800
  }
66500
66801
 
66501
66802
  // ts/codex-agent/dist/dispatch.js
66502
- import { randomUUID as randomUUID7 } from "node:crypto";
66803
+ import { randomUUID as randomUUID8 } from "node:crypto";
66503
66804
  import * as path13 from "node:path";
66504
66805
 
66505
66806
  // ts/agent-core/dist/internal/attachment-input.js
@@ -68152,11 +68453,11 @@ var ForeignThreadRegistry = class {
68152
68453
  return this.threads.size;
68153
68454
  }
68154
68455
  openTurns() {
68155
- let count = 0;
68456
+ let count2 = 0;
68156
68457
  for (const thread of this.threads.values())
68157
68458
  if (thread.turn)
68158
- count += 1;
68159
- return count;
68459
+ count2 += 1;
68460
+ return count2;
68160
68461
  }
68161
68462
  /**
68162
68463
  * Notifications for a thread no dispatch owns. Returns false when the
@@ -68355,7 +68656,7 @@ function errToString4(err) {
68355
68656
  }
68356
68657
 
68357
68658
  // ts/codex-agent/dist/input-receipts.js
68358
- import { randomUUID as randomUUID6 } from "node:crypto";
68659
+ import { randomUUID as randomUUID7 } from "node:crypto";
68359
68660
  var CodexInputReceipts = class {
68360
68661
  log;
68361
68662
  inputs = /* @__PURE__ */ new Map();
@@ -68364,7 +68665,7 @@ var CodexInputReceipts = class {
68364
68665
  }
68365
68666
  register(sessionKey, threadId, lifecycle, turnId) {
68366
68667
  const input = {
68367
- clientId: randomUUID6(),
68668
+ clientId: randomUUID7(),
68368
68669
  sessionKey,
68369
68670
  threadId,
68370
68671
  turnId,
@@ -68718,6 +69019,93 @@ function errToString5(err) {
68718
69019
  return err instanceof Error ? err.message : String(err);
68719
69020
  }
68720
69021
 
69022
+ // ts/codex-agent/dist/token-usage.js
69023
+ var MAX_TRACKED = 1024;
69024
+ var CodexProcessUsage = class {
69025
+ port;
69026
+ startedTurns = /* @__PURE__ */ new Set();
69027
+ threadModels = /* @__PURE__ */ new Map();
69028
+ constructor(port) {
69029
+ this.port = port;
69030
+ }
69031
+ notification(method, params) {
69032
+ if (method === "turn/started") {
69033
+ const turnId = extractTurnId(params);
69034
+ if (turnId)
69035
+ remember(this.startedTurns, turnId);
69036
+ return;
69037
+ }
69038
+ if (method !== "thread/tokenUsage/updated")
69039
+ return;
69040
+ const p = params ?? {};
69041
+ if (typeof p.turnId !== "string" || !this.startedTurns.has(p.turnId))
69042
+ return;
69043
+ const sample = sampleOf(p.tokenUsage?.last, this.modelOf(extractThreadIdFromNotification(params)));
69044
+ if (sample)
69045
+ this.port.emitUsage(sample);
69046
+ }
69047
+ response(method, params, result) {
69048
+ switch (method) {
69049
+ case "thread/start":
69050
+ case "thread/resume":
69051
+ case "thread/fork": {
69052
+ const threadId = extractThreadId(result) ?? (method === "thread/resume" ? paramOf(params, "threadId") : void 0);
69053
+ this.setModel(threadId, paramOf(result, "model"));
69054
+ return;
69055
+ }
69056
+ case "turn/start":
69057
+ this.setModel(paramOf(params, "threadId"), paramOf(params, "model"));
69058
+ return;
69059
+ }
69060
+ }
69061
+ setModel(threadId, model) {
69062
+ if (!threadId || !model)
69063
+ return;
69064
+ this.threadModels.delete(threadId);
69065
+ this.threadModels.set(threadId, model);
69066
+ if (this.threadModels.size > MAX_TRACKED) {
69067
+ this.threadModels.delete(this.threadModels.keys().next().value);
69068
+ }
69069
+ }
69070
+ /** The thread's model, refreshed as recently used so a busy thread is never evicted. */
69071
+ modelOf(threadId) {
69072
+ const model = threadId ? this.threadModels.get(threadId) : void 0;
69073
+ if (!threadId || !model)
69074
+ return "unknown";
69075
+ this.setModel(threadId, model);
69076
+ return model;
69077
+ }
69078
+ };
69079
+ function sampleOf(last, model) {
69080
+ if (!last || typeof last !== "object")
69081
+ return void 0;
69082
+ const usage = last;
69083
+ const input = count(usage.inputTokens);
69084
+ const cached = count(usage.cachedInputTokens);
69085
+ const sample = {
69086
+ model,
69087
+ inputTokens: Math.max(0, input - cached),
69088
+ cacheReadTokens: cached,
69089
+ cacheWriteTokens: count(usage.cacheWriteInputTokens),
69090
+ outputTokens: count(usage.outputTokens)
69091
+ };
69092
+ if (input === 0 && sample.cacheWriteTokens === 0 && sample.outputTokens === 0)
69093
+ return void 0;
69094
+ return sample;
69095
+ }
69096
+ function remember(set, value) {
69097
+ set.add(value);
69098
+ if (set.size > MAX_TRACKED)
69099
+ set.delete(set.values().next().value);
69100
+ }
69101
+ function paramOf(value, key) {
69102
+ const field = value && typeof value === "object" ? value[key] : void 0;
69103
+ return typeof field === "string" && field.trim() ? field : void 0;
69104
+ }
69105
+ function count(value) {
69106
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
69107
+ }
69108
+
68721
69109
  // ts/codex-agent/dist/dispatch.js
68722
69110
  var NEW_SESSION_ENDED = "Codex turn ended by New Session";
68723
69111
  var CodexAppServerAdapter = class {
@@ -68939,6 +69327,9 @@ var CodexAppServerAdapter = class {
68939
69327
  subscribeRuntimeActivity(handler) {
68940
69328
  return this.activity.subscribe(handler);
68941
69329
  }
69330
+ subscribeUsage(handler) {
69331
+ return this.activity.subscribeUsage(handler);
69332
+ }
68942
69333
  /**
68943
69334
  * Busy = a dispatch turn, a dispatch opening its thread (possibly running
68944
69335
  * the instructions-refresh compaction turn), or a subagent thread's turn
@@ -69009,7 +69400,7 @@ var CodexAppServerAdapter = class {
69009
69400
  }
69010
69401
  const sink = new TurnSink(noteActivity);
69011
69402
  this.setActiveTurn(threadId, sink, log2);
69012
- const groupKey = randomUUID7();
69403
+ const groupKey = randomUUID8();
69013
69404
  let sawTurnEnd = false;
69014
69405
  let releasePreparedAttachments = () => {
69015
69406
  };
@@ -69213,9 +69604,6 @@ var CodexAppServerAdapter = class {
69213
69604
  }
69214
69605
  return { ok: true, client, threadId, reconcile };
69215
69606
  }
69216
- getBranchPoint(_sessionKey) {
69217
- return void 0;
69218
- }
69219
69607
  async forkSession({ sessionKey: parentSessionKey }) {
69220
69608
  const client = this.client;
69221
69609
  if (!client)
@@ -69243,16 +69631,13 @@ var CodexAppServerAdapter = class {
69243
69631
  this.opts.sessionManager.recordThreadId(handle.sessionKey, forkedThreadId);
69244
69632
  return handle;
69245
69633
  } catch (err) {
69246
- return this.logForkFailure(err);
69634
+ this.opts.log?.warn?.(`thread/fork failed: ${errToString6(err)}`);
69635
+ return null;
69247
69636
  }
69248
69637
  }
69249
69638
  cleanupFork({ fork }) {
69250
69639
  this.opts.sessionManager.cleanupFork(fork.sessionKey);
69251
69640
  }
69252
- logForkFailure(err) {
69253
- this.opts.log?.warn?.(`thread/fork failed: ${errToString6(err)}`);
69254
- return null;
69255
- }
69256
69641
  /**
69257
69642
  * Lazily restart the app-server before the NEXT turn, so a subprocess that
69258
69643
  * has been running since before a capability change starts clean. Deferred
@@ -69375,6 +69760,7 @@ var CodexAppServerAdapter = class {
69375
69760
  log: log2 ?? this.opts.log
69376
69761
  });
69377
69762
  const client = new JsonRpcStdioClient(proc, void 0, (p) => this.appServers.retire(p));
69763
+ client.observe(new CodexProcessUsage(this.activity));
69378
69764
  client.setNotificationHandler((method, params) => this.routeNotification(method, params));
69379
69765
  client.setServerRequestHandler((method, params) => {
69380
69766
  const denial = answerServerRequest(method);
@@ -69799,11 +70185,7 @@ function resolveWriteTarget(filePath) {
69799
70185
  throw new Error(`symlink chain deeper than 40 while resolving ${filePath}`);
69800
70186
  }
69801
70187
  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}/`);
70188
+ return isParallModelEndpoint(env.OPENAI_BASE_URL, env.PRLL_API_URL);
69807
70189
  }
69808
70190
  function tomlBasicString(value) {
69809
70191
  let out = "";
@@ -70110,6 +70492,8 @@ async function main() {
70110
70492
  driver: "app-server"
70111
70493
  },
70112
70494
  dispatchAdapter: adapter,
70495
+ // The CLI's own-login usage, not the Parall proxy's (already metered).
70496
+ reportRuntimeUsage: !useParallProvider,
70113
70497
  log: agentLog,
70114
70498
  // Live capability view for hint routing: the channel reply hint points
70115
70499
  // at the vendor CLI only while the grant is active.