thumbgate 1.38.0 → 1.39.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.
Files changed (105) hide show
  1. package/.agents/skills/bolt-forge-opt-in-not-clone/SKILL.md +72 -0
  2. package/.agents/skills/decisive-step-evaluator/SKILL.md +47 -0
  3. package/.agents/skills/fiddler-control-plane-honesty/SKILL.md +61 -0
  4. package/.agents/skills/harness-evolution-ceiling/SKILL.md +52 -0
  5. package/.agents/skills/omp-coordination-honesty-not-clone/SKILL.md +94 -0
  6. package/.agents/skills/saas-moat-honesty-not-clone/SKILL.md +22 -0
  7. package/.agents/skills/siren-mcp-governance/SKILL.md +50 -0
  8. package/.agents/skills/vs-coverage-gap-not-clone/SKILL.md +69 -0
  9. package/.agents/skills/wisdom-context-artifact-not-clone/SKILL.md +67 -0
  10. package/.claude-plugin/plugin.json +1 -1
  11. package/.well-known/mcp/server-card.json +1 -1
  12. package/adapters/claude/.mcp.json +2 -2
  13. package/adapters/forge/forge.yaml +3 -3
  14. package/adapters/future-agi/.mcp.json +1 -1
  15. package/adapters/future-agi/config.toml +1 -1
  16. package/adapters/future-agi/opencode.json +1 -1
  17. package/adapters/herdr/herdr-plugin.toml +2 -2
  18. package/adapters/hotdata/hotdata-vector-store.js +575 -0
  19. package/adapters/mcp/server-stdio.js +1 -1
  20. package/adapters/opencode/opencode.json +1 -1
  21. package/adapters/strands/strands-box-diode.js +344 -0
  22. package/adapters/strands/strands-decider-adapter.js +445 -0
  23. package/bin/cli.js +472 -21
  24. package/config/gate-templates.json +37 -0
  25. package/config/gates/default.json +13 -0
  26. package/config/schemas/task-outcome-receipt.schema.json +12 -0
  27. package/package.json +102 -18
  28. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +119 -0
  29. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +141 -0
  30. package/public/connectors.html +329 -0
  31. package/public/enterprise-governance.html +311 -0
  32. package/public/gaming-playbook.html +732 -0
  33. package/public/index.html +77 -51
  34. package/public/install.html +7 -7
  35. package/public/learn.html +14 -0
  36. package/public/numbers.html +2 -2
  37. package/public/operator-framework.html +385 -0
  38. package/public/pricing.html +14 -10
  39. package/scripts/activesaddler-curriculum-doctor.js +357 -0
  40. package/scripts/agent-context-artifact.js +325 -0
  41. package/scripts/agent-egress-policy.js +2 -2
  42. package/scripts/agent-operations-planner.js +1 -1
  43. package/scripts/agent-outcome-eval.js +1 -1
  44. package/scripts/agent-reliability-client.js +148 -0
  45. package/scripts/apple-minions-idle-compute-steal.js +428 -0
  46. package/scripts/billing.js +0 -1
  47. package/scripts/cli-demo.js +505 -1
  48. package/scripts/cli-schema.js +36 -0
  49. package/scripts/colab-compute-honesty.js +93 -0
  50. package/scripts/corporate-email-isolation-diode.js +299 -0
  51. package/scripts/coverage-gap.js +396 -0
  52. package/scripts/dashboard-chat.js +3 -3
  53. package/scripts/dashboard.js +2 -2
  54. package/scripts/decisive-step-doctor.js +256 -0
  55. package/scripts/decisive-step-evaluator.js +390 -0
  56. package/scripts/entitlement.js +18 -7
  57. package/scripts/feedback-loop.js +26 -3
  58. package/scripts/fiddler-control-plane-honesty.js +303 -0
  59. package/scripts/financial-control-plane.js +10 -2
  60. package/scripts/gates-engine.js +3 -1
  61. package/scripts/github-license-compliance-diode.js +378 -0
  62. package/scripts/harness-ceiling-doctor.js +326 -0
  63. package/scripts/hf-papers.js +1 -1
  64. package/scripts/human-escalation.js +7 -1
  65. package/scripts/hybrid-feedback-context.js +53 -7
  66. package/scripts/lesson-graph.js +785 -0
  67. package/scripts/lesson-inference.js +1 -1
  68. package/scripts/lesson-retrieval.js +26 -18
  69. package/scripts/license.js +122 -21
  70. package/scripts/llm-behavior-monitor.js +1 -1
  71. package/scripts/llm-obs-honesty.js +52 -0
  72. package/scripts/local-model-profile.js +11 -7
  73. package/scripts/mailer/resend-mailer.js +6 -3
  74. package/scripts/mcp-transport-strategy.js +1 -1
  75. package/scripts/migrate-lesson-graph.js +442 -0
  76. package/scripts/model-distress-doctor.js +168 -0
  77. package/scripts/multi-harness-invariants.js +305 -0
  78. package/scripts/omp-coordination-honesty.js +488 -0
  79. package/scripts/pro-local-dashboard.js +20 -3
  80. package/scripts/prompt-eval.js +1 -1
  81. package/scripts/prove-herdr-adapter.js +367 -3
  82. package/scripts/rag-embedding-identity.js +1 -1
  83. package/scripts/rrsi-regularizer.js +86 -0
  84. package/scripts/saas-moat-honesty.js +443 -0
  85. package/scripts/secret-redaction.js +58 -0
  86. package/scripts/session-export-gate.js +368 -0
  87. package/scripts/siren-mcp-governance.js +539 -0
  88. package/scripts/strands-box-doctor.js +130 -0
  89. package/scripts/stripe-revenue-catalog-audit.js +12 -0
  90. package/scripts/stripe-revenue-catalog.js +40 -0
  91. package/scripts/switchyard-router.js +153 -0
  92. package/scripts/task-outcomes.js +148 -3
  93. package/scripts/thumbgate-board-loop.js +4 -2
  94. package/scripts/thumbgate-daily-discoveries-publish.js +86 -38
  95. package/scripts/triage-savings-calculator.js +181 -0
  96. package/scripts/vector-store.js +41 -2
  97. package/scripts/vulnerability-pre-action-diode.js +319 -0
  98. package/scripts/windbg-evidence-diagnostics.js +241 -0
  99. package/scripts/workflow-intake-queue.js +1 -1
  100. package/scripts/workspace-agent-routines.js +534 -6
  101. package/server.json +2 -2
  102. package/skills/siren-mcp-governance/SKILL.md +50 -0
  103. package/src/api/server.js +158 -1
  104. package/src/mcp-writeguard.js +1 -1
  105. package/src/session-interactivity.js +284 -0
package/src/api/server.js CHANGED
@@ -37,6 +37,12 @@ const PRO_CHECKOUT_URL = 'https://buy.stripe.com/8x2dR91M84r4cSd9uj3sI3f';
37
37
  // missing Railway env cannot silently charge $499 under a $1500 label.
38
38
  const SPRINT_DIAGNOSTIC_CHECKOUT_URL = 'https://buy.stripe.com/9B69ATbmI4r4aK5eOD3sI3k';
39
39
  const WORKFLOW_SPRINT_CHECKOUT_URL = 'https://www.paypal.com/ncp/payment/LTQFR7P9AR3QG';
40
+ // Operator Framework service rails (public/operator-framework.html). Stripe
41
+ // Payment Links stay server-side behind /go/operator-* so public HTML never
42
+ // exposes buy.stripe.com and bots are deflected back to the page.
43
+ const OPERATOR_DIAGNOSTIC_CHECKOUT_URL = 'https://buy.stripe.com/fZueVd9eA4r42dz7mb3sI2W';
44
+ const OPERATOR_TURNKEY_CHECKOUT_URL = 'https://buy.stripe.com/14A8wP62o0aOcSd35V3sJ0Q';
45
+ const OPERATOR_RETAINER_CHECKOUT_URL = 'https://buy.stripe.com/9B614n0I43n03hD35V3sJ0P';
40
46
 
41
47
  function getPosthogProxyPath(pathname) {
42
48
  return pathname.slice('/ingest'.length) || '/';
@@ -329,7 +335,10 @@ const WHITEPAPER_PAGE_PATH = path.resolve(__dirname, '../../public/whitepaper.ht
329
335
  const EVAL_SCORECARD_PAGE_PATH = path.resolve(__dirname, '../../public/eval-scorecard.html');
330
336
  const EVALUATIONS_PAGE_PATH = path.resolve(__dirname, '../../public/evaluations.html');
331
337
  const CASE_STUDIES_PAGE_PATH = path.resolve(__dirname, '../../public/case-studies.html');
338
+ const OPERATOR_FRAMEWORK_PAGE_PATH = path.resolve(__dirname, '../../public/operator-framework.html');
332
339
  const FEDERAL_PAGE_PATH = path.resolve(__dirname, '../../public/federal.html');
340
+ const ENTERPRISE_GOVERNANCE_PAGE_PATH = path.resolve(__dirname, '../../public/enterprise-governance.html');
341
+ const GAMING_PLAYBOOK_PAGE_PATH = path.resolve(__dirname, '../../public/gaming-playbook.html');
333
342
  const YT_PAGE_PATH = path.resolve(__dirname, '../../public/yt.html');
334
343
  const PRICING_PAGE_PATH = path.resolve(__dirname, '../../public/pricing.html');
335
344
  const ABOUT_PAGE_PATH = path.resolve(__dirname, '../../public/about.html');
@@ -560,6 +569,64 @@ const TRACKED_LINK_TARGETS = Object.freeze({
560
569
  allowCustomerEmail: true,
561
570
  prefillStripeEmail: true,
562
571
  },
572
+ // Operator Framework offers (/operator-framework). Same-origin hop keeps
573
+ // buy.stripe.com out of public HTML; bots are deflected to the page.
574
+ 'operator-diagnostic': {
575
+ fallbackHref: OPERATOR_DIAGNOSTIC_CHECKOUT_URL,
576
+ external: true,
577
+ botDeflectPath: '/operator-framework',
578
+ ctaId: 'operator_diagnostic_buy',
579
+ ctaPlacement: 'operator_framework',
580
+ eventType: 'operator_framework_checkout_click',
581
+ defaults: {
582
+ utm_source: 'operator_framework',
583
+ utm_medium: 'offer_card',
584
+ utm_campaign: 'operator_framework',
585
+ plan_id: 'sprint_diagnostic',
586
+ },
587
+ },
588
+ 'operator-turnkey': {
589
+ fallbackHref: OPERATOR_TURNKEY_CHECKOUT_URL,
590
+ external: true,
591
+ botDeflectPath: '/operator-framework',
592
+ ctaId: 'operator_turnkey_buy',
593
+ ctaPlacement: 'operator_framework',
594
+ eventType: 'operator_framework_checkout_click',
595
+ defaults: {
596
+ utm_source: 'operator_framework',
597
+ utm_medium: 'offer_card',
598
+ utm_campaign: 'operator_framework',
599
+ plan_id: 'turnkey_setup',
600
+ },
601
+ },
602
+ 'operator-retainer': {
603
+ fallbackHref: OPERATOR_RETAINER_CHECKOUT_URL,
604
+ external: true,
605
+ botDeflectPath: '/operator-framework',
606
+ ctaId: 'operator_retainer_buy',
607
+ ctaPlacement: 'operator_framework',
608
+ eventType: 'operator_framework_checkout_click',
609
+ defaults: {
610
+ utm_source: 'operator_framework',
611
+ utm_medium: 'offer_card',
612
+ utm_campaign: 'operator_framework',
613
+ plan_id: 'managed_retainer',
614
+ },
615
+ },
616
+ 'operator-pro': {
617
+ fallbackHref: PRO_CHECKOUT_URL,
618
+ external: true,
619
+ botDeflectPath: '/operator-framework',
620
+ ctaId: 'operator_pro_buy',
621
+ ctaPlacement: 'operator_framework',
622
+ eventType: 'operator_framework_checkout_click',
623
+ defaults: {
624
+ utm_source: 'operator_framework',
625
+ utm_medium: 'offer_card',
626
+ utm_campaign: 'operator_framework',
627
+ plan_id: 'pro',
628
+ },
629
+ },
563
630
  // 2026-06-02: Teams/Aiventyx deprecated. Redirect legacy links to Pro.
564
631
  teams: {
565
632
  path: '/go/pro?utm_source=legacy_teams&utm_medium=redirect',
@@ -2271,7 +2338,7 @@ function appendFeedbackListLines(lines, { entries, signal, intent }) {
2271
2338
  }
2272
2339
  lines.push(
2273
2340
  `${FEEDBACK_LIST_LABELS[signal] || 'Recent feedback'} (${intent.windowLabel}):`,
2274
- ...entries.map(formatFeedbackEntry)
2341
+ ...entries.map((x) => formatFeedbackEntry(x))
2275
2342
  );
2276
2343
  }
2277
2344
 
@@ -2827,6 +2894,26 @@ ${hiddenInputs}
2827
2894
  }
2828
2895
  fetch('/v1/telemetry/ping', { method:'POST', headers:{ 'content-type':'application/json' }, body: body, keepalive: true }).catch(function(){});
2829
2896
  }
2897
+ var emailInput = document.querySelector('input[name=customer_email]');
2898
+ var skipLink = document.querySelector('a[data-i=pro_checkout_direct_stripe]');
2899
+ function updateSkipLink() {
2900
+ if (!skipLink) return;
2901
+ try {
2902
+ var u = new URL(skipLink.href, window.location.origin);
2903
+ var email = emailInput ? emailInput.value.trim() : '';
2904
+ if (email && email.length <= 320 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
2905
+ u.searchParams.set('customer_email', email);
2906
+ } else {
2907
+ u.searchParams.delete('customer_email');
2908
+ }
2909
+ skipLink.href = u.toString();
2910
+ } catch(_) {}
2911
+ }
2912
+ if (emailInput) {
2913
+ emailInput.addEventListener('input', updateSkipLink);
2914
+ emailInput.addEventListener('change', updateSkipLink);
2915
+ updateSkipLink();
2916
+ }
2830
2917
  document.querySelector('form').addEventListener('submit', function(){
2831
2918
  submitted = true;
2832
2919
  var emailInput = document.querySelector('input[name=customer_email]');
@@ -3564,6 +3651,10 @@ function loadPricingPageHtml(runtimeConfig, pageContext = {}) {
3564
3651
  return loadPublicMarketingTemplateHtml(PRICING_PAGE_PATH, runtimeConfig, pageContext);
3565
3652
  }
3566
3653
 
3654
+ function loadOperatorFrameworkPageHtml(runtimeConfig, pageContext = {}) {
3655
+ return loadPublicMarketingTemplateHtml(OPERATOR_FRAMEWORK_PAGE_PATH, runtimeConfig, pageContext);
3656
+ }
3657
+
3567
3658
  function loadAboutPageHtml(runtimeConfig, pageContext = {}) {
3568
3659
  return loadPublicMarketingTemplateHtml(ABOUT_PAGE_PATH, runtimeConfig, pageContext);
3569
3660
  }
@@ -4199,6 +4290,7 @@ function renderSitemapXml(runtimeConfig) {
4199
4290
  { path: '/pro', changefreq: 'weekly', priority: '0.9' },
4200
4291
  { path: '/diagnostic', changefreq: 'weekly', priority: '0.9' },
4201
4292
  { path: '/founders', changefreq: 'weekly', priority: '0.95' },
4293
+ { path: '/operator-framework', changefreq: 'weekly', priority: '0.9' },
4202
4294
  { path: '/peter', changefreq: 'weekly', priority: '0.9' },
4203
4295
  { path: '/workflow-hardening-sprint', changefreq: 'weekly', priority: '0.9' },
4204
4296
  { path: '/install', changefreq: 'weekly', priority: '0.9' },
@@ -6892,6 +6984,51 @@ async function addContext(){
6892
6984
  return;
6893
6985
  }
6894
6986
 
6987
+ if (isGetLikeRequest && (
6988
+ pathname === '/enterprise-governance'
6989
+ || pathname === '/enterprise-governance.html'
6990
+ || pathname === '/enterprise'
6991
+ || pathname === '/gemini-at-work'
6992
+ )) {
6993
+ try {
6994
+ servePublicMarketingPage({
6995
+ req,
6996
+ res,
6997
+ parsed,
6998
+ hostedConfig,
6999
+ isHeadRequest,
7000
+ renderHtml: () => fs.readFileSync(ENTERPRISE_GOVERNANCE_PAGE_PATH, 'utf-8'),
7001
+ extraTelemetry: { pageType: 'enterprise-governance' },
7002
+ });
7003
+ } catch {
7004
+ sendJson(res, 404, { error: 'Enterprise governance page not found' });
7005
+ }
7006
+ return;
7007
+ }
7008
+
7009
+ if (isGetLikeRequest && (
7010
+ pathname === '/gaming-playbook'
7011
+ || pathname === '/gaming-playbook.html'
7012
+ || pathname === '/gaming'
7013
+ || pathname === '/industry-playbook'
7014
+ || pathname === '/industry-playbook/gaming'
7015
+ )) {
7016
+ try {
7017
+ servePublicMarketingPage({
7018
+ req,
7019
+ res,
7020
+ parsed,
7021
+ hostedConfig,
7022
+ isHeadRequest,
7023
+ renderHtml: () => fs.readFileSync(GAMING_PLAYBOOK_PAGE_PATH, 'utf-8'),
7024
+ extraTelemetry: { pageType: 'gaming-playbook' },
7025
+ });
7026
+ } catch {
7027
+ sendJson(res, 404, { error: 'Gaming playbook page not found' });
7028
+ }
7029
+ return;
7030
+ }
7031
+
6895
7032
  if (isGetLikeRequest && (
6896
7033
  pathname === '/yt'
6897
7034
  || pathname === '/yt.html'
@@ -8925,6 +9062,26 @@ footer{margin-top:40px;padding-top:20px;border-top:1px solid #e5e7eb;color:#6b72
8925
9062
  return;
8926
9063
  }
8927
9064
 
9065
+ // Operator Framework: done-for-you ThumbGate offers + agency partner program.
9066
+ if (isGetLikeRequest && (pathname === '/operator-framework' || pathname === '/operator-framework.html')) {
9067
+ try {
9068
+ servePublicMarketingPage({
9069
+ req,
9070
+ res,
9071
+ parsed,
9072
+ hostedConfig,
9073
+ isHeadRequest,
9074
+ renderHtml: loadOperatorFrameworkPageHtml,
9075
+ extraTelemetry: {
9076
+ pageType: 'operator_framework',
9077
+ },
9078
+ });
9079
+ } catch (err) {
9080
+ sendText(res, 500, err.message || 'Operator Framework page unavailable');
9081
+ }
9082
+ return;
9083
+ }
9084
+
8928
9085
  // Public canonical pricing page.
8929
9086
  if (isGetLikeRequest && (pathname === '/pricing' || pathname === '/pricing.html')) {
8930
9087
  try {
@@ -176,7 +176,7 @@ function scrubSensitiveData(value) {
176
176
  }
177
177
 
178
178
  if (Array.isArray(value)) {
179
- return value.map(scrubSensitiveData);
179
+ return value.map((x) => scrubSensitiveData(x));
180
180
  }
181
181
 
182
182
  if (typeof value === 'object') {
@@ -0,0 +1,284 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Session-level interactivity: what the user actually waited, not what the
5
+ * server was busy for.
6
+ *
7
+ * Taken from NVIDIA's SemiAnalysis AgentX methodology, which reports two rates
8
+ * side by side and treats the gap between them as the finding:
9
+ *
10
+ * Standard Interactivity
11
+ * "output tokens divided by the elapsed time from the first token to the
12
+ * last"
13
+ *
14
+ * E2E Normalized Interactivity
15
+ * "average output-token rate per user over the full request, calculated by
16
+ * dividing total output tokens by the time from request submission to
17
+ * final-token delivery"
18
+ *
19
+ * Standard starts the clock at the first token. Everything before that -- queue
20
+ * time, scheduling, a runner that has not claimed the work yet -- is invisible
21
+ * to it. E2E starts at submission, so it counts what the person counts.
22
+ *
23
+ * WHY THIS EXISTS HERE
24
+ *
25
+ * 2026-08-25, production: a task was created at 17:34:08Z and completed at
26
+ * 17:34:53Z. The execution itself was quick and the UI advertised a "90s
27
+ * lease", so by any server-side measure the system was healthy. The user spent
28
+ * that time looking at a spinner reading "Waiting for the fenced VPS runner to
29
+ * pick this up". Standard Interactivity would have scored that request well.
30
+ *
31
+ * A metric that cannot see queue time cannot see that outage. This module
32
+ * exists so that class of defect shows up as a number rather than as a
33
+ * screenshot.
34
+ *
35
+ * WHY SESSIONS AND NOT REQUESTS
36
+ *
37
+ * Also from AgentX: "Agentic sessions are long, stateful, and variable: they
38
+ * chain model calls, tool use, and growing context rather than following a
39
+ * fixed prompt-and-response pattern." Their sample session grows from roughly
40
+ * 60K to 400K tokens, and industry figures they cite put a single agentic
41
+ * request at ~15x the tokens of ordinary chat. Per-call averages hide all of
42
+ * that, so everything below aggregates over a whole session and keeps tool
43
+ * gaps in the denominator: a tool call the user waits through is wait, whoever
44
+ * is executing it.
45
+ */
46
+
47
+ /** A turn is only usable if these are present and ordered. */
48
+ const REQUIRED = ['submittedAt', 'firstTokenAt', 'lastTokenAt'];
49
+
50
+ /**
51
+ * Fraction of total wall time that may be invisible to Standard Interactivity
52
+ * before it is called out. Deliberately generous: this is meant to catch a
53
+ * request that spent most of its life queued, not to police a slow scheduler.
54
+ */
55
+ const HIDDEN_WAIT_BUDGET = 0.25;
56
+
57
+ function isFiniteNumber(value) {
58
+ return typeof value === 'number' && Number.isFinite(value);
59
+ }
60
+
61
+ /**
62
+ * Validate one turn, returning a reason string when unusable.
63
+ *
64
+ * Unusable turns are never silently dropped: a session whose turns cannot be
65
+ * measured must report as UNKNOWN rather than as fast, for the same reason the
66
+ * incident above went unnoticed.
67
+ */
68
+ function turnProblem(turn) {
69
+ if (!turn || typeof turn !== 'object') return 'not an object';
70
+ for (const field of REQUIRED) {
71
+ if (!isFiniteNumber(turn[field])) return `missing or non-numeric ${field}`;
72
+ }
73
+ if (turn.firstTokenAt < turn.submittedAt) return 'firstTokenAt precedes submittedAt';
74
+ if (turn.lastTokenAt < turn.firstTokenAt) return 'lastTokenAt precedes firstTokenAt';
75
+ if (!isFiniteNumber(turn.outputTokens) || turn.outputTokens < 0) {
76
+ return 'missing or negative outputTokens';
77
+ }
78
+ return null;
79
+ }
80
+
81
+ /**
82
+ * Measure a single turn.
83
+ *
84
+ * Rates are tokens per second. A zero-length generation window yields a null
85
+ * rate rather than Infinity -- an unmeasurable rate is not an infinitely fast
86
+ * one, and reporting Infinity here would flatter exactly the pathological case
87
+ * this module is watching for.
88
+ */
89
+ function measureTurn(turn) {
90
+ const problem = turnProblem(turn);
91
+ if (problem) return { ok: false, problem };
92
+
93
+ const queueMs = turn.firstTokenAt - turn.submittedAt;
94
+ const generationMs = turn.lastTokenAt - turn.firstTokenAt;
95
+ const totalMs = turn.lastTokenAt - turn.submittedAt;
96
+ const rate = (ms) => (ms > 0 ? (turn.outputTokens / ms) * 1000 : null);
97
+
98
+ return {
99
+ ok: true,
100
+ outputTokens: turn.outputTokens,
101
+ queueMs,
102
+ generationMs,
103
+ totalMs,
104
+ ttftMs: queueMs,
105
+ standardInteractivity: rate(generationMs),
106
+ e2eNormalizedInteractivity: rate(totalMs),
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Aggregate a whole session.
112
+ *
113
+ * The denominator for E2E is submission of the first turn to the final token of
114
+ * the last, which means time spent in tool calls between turns stays counted.
115
+ * That is intentional: from the user's chair a tool call is indistinguishable
116
+ * from thinking, and a serving stack that offloads work into tools should not
117
+ * get to subtract that time from its own score.
118
+ *
119
+ * @param {Object} session - { id, turns: [{ submittedAt, firstTokenAt, lastTokenAt, outputTokens, promptTokens? }] }
120
+ * @returns {Object} measurement, always including `status`
121
+ */
122
+ function measureSession(session) {
123
+ const turns = session && Array.isArray(session.turns) ? session.turns : null;
124
+ if (!turns || turns.length === 0) {
125
+ return { status: 'NO_DATA', id: session && session.id, reason: 'no turns supplied' };
126
+ }
127
+
128
+ const measured = [];
129
+ const problems = [];
130
+ turns.forEach((turn, index) => {
131
+ const result = measureTurn(turn);
132
+ if (result.ok) measured.push({ index, ...result });
133
+ else problems.push({ index, problem: result.problem });
134
+ });
135
+
136
+ // Any unmeasurable turn makes the session total unknowable. Reporting the
137
+ // measurable subset would understate the wait, which is the failure mode.
138
+ if (problems.length) {
139
+ return {
140
+ status: 'UNKNOWN',
141
+ id: session && session.id,
142
+ reason: 'one or more turns could not be measured',
143
+ problems,
144
+ measuredTurns: measured.length,
145
+ totalTurns: turns.length,
146
+ };
147
+ }
148
+
149
+ const ordered = [...turns].sort((a, b) => a.submittedAt - b.submittedAt);
150
+ if (ordered.some((turn, index) => index > 0 && turn.submittedAt < ordered[index - 1].lastTokenAt)) {
151
+ return { status: 'UNKNOWN', id: session.id, reason: 'overlapping turns cannot be measured as a sequential session' };
152
+ }
153
+
154
+ const outputTokens = measured.reduce((sum, t) => sum + t.outputTokens, 0);
155
+ const sessionStart = Math.min(...turns.map((t) => t.submittedAt));
156
+ const sessionEnd = Math.max(...turns.map((t) => t.lastTokenAt));
157
+ const wallMs = sessionEnd - sessionStart;
158
+
159
+ const generationMs = measured.reduce((sum, t) => sum + t.generationMs, 0);
160
+ const queueMs = measured.reduce((sum, t) => sum + t.queueMs, 0);
161
+ // Whatever is left is time between turns: tool execution, agent deliberation,
162
+ // scheduling. The user waited through all of it.
163
+ const gapMs = Math.max(0, wallMs - generationMs - queueMs);
164
+
165
+ const rate = (ms) => (ms > 0 ? (outputTokens / ms) * 1000 : null);
166
+ const standard = rate(generationMs);
167
+ const e2e = rate(wallMs);
168
+
169
+ const hiddenMs = wallMs - generationMs;
170
+ const hiddenFraction = wallMs > 0 ? hiddenMs / wallMs : 0;
171
+
172
+ return {
173
+ status: 'OK',
174
+ id: session && session.id,
175
+ turns: measured.length,
176
+ outputTokens,
177
+ promptTokensFirst: firstPromptTokens(ordered),
178
+ promptTokensLast: lastPromptTokens(ordered),
179
+ wallMs,
180
+ generationMs,
181
+ queueMs,
182
+ gapMs,
183
+ standardInteractivity: standard,
184
+ e2eNormalizedInteractivity: e2e,
185
+ // The headline: how much of the user's wait the standard metric cannot see.
186
+ hiddenWaitMs: hiddenMs,
187
+ hiddenWaitFraction: hiddenFraction,
188
+ hiddenWaitExceedsBudget: hiddenFraction > HIDDEN_WAIT_BUDGET,
189
+ };
190
+ }
191
+
192
+ function firstPromptTokens(turns) {
193
+ const first = turns.find((t) => isFiniteNumber(t && t.promptTokens));
194
+ return first ? first.promptTokens : null;
195
+ }
196
+
197
+ function lastPromptTokens(turns) {
198
+ for (let i = turns.length - 1; i >= 0; i -= 1) {
199
+ if (isFiniteNumber(turns[i] && turns[i].promptTokens)) return turns[i].promptTokens;
200
+ }
201
+ return null;
202
+ }
203
+
204
+ /**
205
+ * Context growth across a session, the other thing fixed-length benchmarks
206
+ * cannot show. AgentX reports a session growing ~60K -> ~400K tokens; a
207
+ * benchmark pinned at 8K in / 1K out would call that the same workload.
208
+ */
209
+ function contextGrowth(session) {
210
+ const measurement = measureSession(session);
211
+ if (measurement.status !== 'OK') return measurement;
212
+ const { promptTokensFirst: first, promptTokensLast: last } = measurement;
213
+ const observations = session.turns.filter((turn) => isFiniteNumber(turn.promptTokens));
214
+ if (observations.length < 2 || !isFiniteNumber(first) || !isFiniteNumber(last) || first <= 0) {
215
+ return { status: 'NO_DATA', reason: 'promptTokens not reported on enough turns' };
216
+ }
217
+ return { status: 'OK', first, last, growthFactor: last / first };
218
+ }
219
+
220
+ /**
221
+ * Compare two serving configurations over the SAME recorded sessions.
222
+ *
223
+ * AgentX is explicit about why replay matters: "Because every system receives
224
+ * the same recorded traffic, observed differences reflect the serving stack
225
+ * rather than benchmark-specific tuning." Comparing runs over different traffic
226
+ * measures the traffic.
227
+ */
228
+ function compareRuns(baseline, candidate) {
229
+ const ids = (run) => Array.isArray(run) ? run.map((session) => session && session.id) : [];
230
+ const aIds = ids(baseline);
231
+ const bIds = ids(candidate);
232
+ const validIds = (values) => values.length > 0
233
+ && values.every((id) => typeof id === 'string' && id.trim().length > 0)
234
+ && new Set(values).size === values.length;
235
+ if (!validIds(aIds) || !validIds(bIds) || aIds.length !== bIds.length
236
+ || aIds.some((id, index) => id !== bIds[index])) {
237
+ return {
238
+ status: 'INVALID',
239
+ reason: 'runs did not replay the same sessions in the same order',
240
+ };
241
+ }
242
+
243
+ const summarize = (run) => {
244
+ const results = run.map((x) => measureSession(x));
245
+ if (results.some((r) => r.status !== 'OK')) {
246
+ return { status: 'UNKNOWN', results };
247
+ }
248
+ const tokens = results.reduce((sum, r) => sum + r.outputTokens, 0);
249
+ const wall = results.reduce((sum, r) => sum + r.wallMs, 0);
250
+ return {
251
+ status: 'OK',
252
+ results,
253
+ outputTokens: tokens,
254
+ wallMs: wall,
255
+ e2eNormalizedInteractivity: wall > 0 ? (tokens / wall) * 1000 : null,
256
+ };
257
+ };
258
+
259
+ const a = summarize(baseline);
260
+ const b = summarize(candidate);
261
+ if (a.status !== 'OK' || b.status !== 'OK') {
262
+ return { status: 'UNKNOWN', reason: 'a session in one run could not be measured', baseline: a, candidate: b };
263
+ }
264
+ if (!a.e2eNormalizedInteractivity) {
265
+ return { status: 'UNKNOWN', reason: 'baseline rate is not measurable' };
266
+ }
267
+
268
+ return {
269
+ status: 'OK',
270
+ baseline: a.e2eNormalizedInteractivity,
271
+ candidate: b.e2eNormalizedInteractivity,
272
+ speedup: b.e2eNormalizedInteractivity / a.e2eNormalizedInteractivity,
273
+ sessions: baseline.length,
274
+ };
275
+ }
276
+
277
+ module.exports = {
278
+ measureTurn,
279
+ measureSession,
280
+ contextGrowth,
281
+ compareRuns,
282
+ turnProblem,
283
+ HIDDEN_WAIT_BUDGET,
284
+ };