thumbgate 1.39.1 → 1.40.2

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 (199) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.well-known/llms.txt +2 -2
  3. package/.well-known/mcp/server-card.json +1 -1
  4. package/README.md +5 -4
  5. package/adapters/claude/.mcp.json +6 -2
  6. package/adapters/codex/config.toml +5 -0
  7. package/adapters/forge/forge.yaml +4 -4
  8. package/adapters/future-agi/.mcp.json +1 -1
  9. package/adapters/future-agi/config.toml +1 -1
  10. package/adapters/future-agi/opencode.json +1 -1
  11. package/adapters/herdr/herdr-plugin.toml +2 -2
  12. package/adapters/mcp/server-stdio.js +82 -7
  13. package/adapters/opencode/opencode.json +1 -1
  14. package/bin/cli.js +128 -15
  15. package/config/brand-standards.json +131 -0
  16. package/config/gates/default.json +18 -1
  17. package/config/github-about.json +1 -1
  18. package/config/mcp-allowlists.json +16 -3
  19. package/config/merge-quality-checks.json +1 -0
  20. package/config/post-deploy-marketing-pages.json +3 -3
  21. package/config/schemas/task-outcome-receipt.schema.json +9 -0
  22. package/openapi/openapi.yaml +7 -3
  23. package/package.json +98 -31
  24. package/public/about.html +2 -2
  25. package/public/admin.html +771 -0
  26. package/public/agent-manager.html +3 -3
  27. package/public/agents-cost-savings.html +1 -1
  28. package/public/ai-malpractice-prevention.html +12 -12
  29. package/public/architecture.html +0 -1
  30. package/public/assets/diagrams/decision.svg +3 -3
  31. package/public/blog/2026-10-05-why-3-days-of-triage-wont-save-ai-speed-code.html +1 -1
  32. package/public/blog/2026-10-09-your-code-got-a-third-author-governance.html +1 -1
  33. package/public/blog/git-at-agent-scale.html +2 -2
  34. package/public/blog/inside-your-boundary.html +1 -1
  35. package/public/blog/process-over-outcome-gates.html +1 -1
  36. package/public/case-studies.html +1 -2
  37. package/public/codex-enterprise.html +1 -1
  38. package/public/codex-plugin.html +1 -1
  39. package/public/dashboard.html +773 -481
  40. package/public/diagnostic.html +8 -3
  41. package/public/enterprise-governance.html +26 -174
  42. package/public/eval-scorecard.html +3 -4
  43. package/public/eval-scorecard.json +2 -2
  44. package/public/evaluations.html +0 -1
  45. package/public/founders.html +3 -3
  46. package/public/gaming-playbook.html +4 -4
  47. package/public/guide.html +3 -5
  48. package/public/index.html +181 -205
  49. package/public/install.html +12 -11
  50. package/public/js/buyer-intent.js +49 -8
  51. package/public/lessons.html +103 -46
  52. package/public/numbers.html +32 -33
  53. package/public/operator-framework.html +44 -72
  54. package/public/peter.html +3 -3
  55. package/public/platform-partners.html +1 -1
  56. package/public/pricing.html +61 -327
  57. package/public/pro.html +3 -1
  58. package/public/project-switcher.js +76 -0
  59. package/public/whitepaper.html +1 -2
  60. package/scripts/activation-quickstart.js +15 -3
  61. package/scripts/activation-tracker.js +280 -3
  62. package/scripts/agent-action-inventory.js +235 -143
  63. package/scripts/agent-operations-planner.js +1 -1
  64. package/scripts/agent-readiness.js +36 -6
  65. package/scripts/agentic-prompt-pipelines.js +901 -0
  66. package/scripts/analytics-report.js +363 -0
  67. package/scripts/analytics-window.js +7 -1
  68. package/scripts/async-job-runner.js +66 -11
  69. package/scripts/audit-trail.js +37 -24
  70. package/scripts/auto-context-packs.js +249 -0
  71. package/scripts/auto-promote-gates.js +37 -27
  72. package/scripts/backfill-lesson-scopes.js +122 -0
  73. package/scripts/billing-setup.js +137 -0
  74. package/scripts/billing.js +889 -132
  75. package/scripts/bot-detection.js +112 -0
  76. package/scripts/brand-standards-gate.js +571 -0
  77. package/scripts/chatgpt-ads-readiness-pack.js +1 -1
  78. package/scripts/check-update.js +236 -0
  79. package/scripts/cli-schema.js +1 -1
  80. package/scripts/commercial-offer.js +2 -2
  81. package/scripts/contextfs.js +9 -3
  82. package/scripts/conversion-rate-stats.js +442 -0
  83. package/scripts/cost-cli.js +147 -0
  84. package/scripts/creator-campaigns.js +239 -0
  85. package/scripts/cross-encoder-reranker.js +4 -0
  86. package/scripts/cuda-gate-batch.js +560 -0
  87. package/scripts/daemon-manager.js +108 -0
  88. package/scripts/dashboard-chat.js +11 -0
  89. package/scripts/dashboard.js +576 -169
  90. package/scripts/decision-journal.js +7 -4
  91. package/scripts/delegation-runtime.js +1036 -0
  92. package/scripts/dispatch-brief.js +159 -0
  93. package/scripts/distribution-surfaces.js +110 -0
  94. package/scripts/docker-sandbox-planner.js +3 -3
  95. package/scripts/egm-goldfish-packet.js +95 -0
  96. package/scripts/embeddinggemma-adapter.js +407 -0
  97. package/scripts/export-dpo-pairs.js +12 -7
  98. package/scripts/feedback-aggregate.js +4 -0
  99. package/scripts/feedback-attribution.js +6 -4
  100. package/scripts/feedback-history-distiller.js +18 -6
  101. package/scripts/feedback-loop.js +255 -89
  102. package/scripts/feedback-paths.js +8 -1
  103. package/scripts/feedback-sanitizer.js +5 -0
  104. package/scripts/feedback-scope.js +106 -0
  105. package/scripts/feedback-session.js +8 -2
  106. package/scripts/filesystem-search.js +13 -8
  107. package/scripts/financial-control-plane.js +707 -45
  108. package/scripts/funnel-analytics.js +35 -0
  109. package/scripts/gate-semantic-layer.js +292 -0
  110. package/scripts/gate-stats.js +8 -2
  111. package/scripts/gates-engine.js +694 -230
  112. package/scripts/generate-eval-scorecard.js +0 -1
  113. package/scripts/harness-tool-names.js +31 -5
  114. package/scripts/hybrid-feedback-context.js +5 -2
  115. package/scripts/implementation-notes.js +241 -0
  116. package/scripts/intent-router.js +518 -0
  117. package/scripts/intervention-policy.js +2 -1
  118. package/scripts/latency-budget.js +164 -0
  119. package/scripts/lesson-canonical.js +2 -2
  120. package/scripts/lesson-db.js +55 -14
  121. package/scripts/lesson-graph.js +2 -1
  122. package/scripts/lesson-retrieval.js +95 -9
  123. package/scripts/lesson-search.js +86 -22
  124. package/scripts/lesson-synthesis.js +21 -5
  125. package/scripts/mailer/index.js +17 -1
  126. package/scripts/mailer/resend-mailer.js +213 -179
  127. package/scripts/mcp-writeguard.js +158 -0
  128. package/scripts/migrate-project-scope.js +209 -0
  129. package/scripts/model-candidates.js +414 -0
  130. package/scripts/openrouter-armor-partnership-diode.js +2419 -0
  131. package/scripts/operational-dashboard.js +172 -0
  132. package/scripts/operational-integrity.js +436 -3
  133. package/scripts/operational-summary.js +190 -0
  134. package/scripts/operator-artifacts.js +622 -0
  135. package/scripts/optimize-context.js +17 -0
  136. package/scripts/override-audit.js +2 -0
  137. package/scripts/owner-admin.js +338 -0
  138. package/scripts/pr-manager.js +194 -1
  139. package/scripts/predictive-insights.js +449 -0
  140. package/scripts/profound-aeo-citation-engine.js +583 -0
  141. package/scripts/progressive-signoff.js +260 -0
  142. package/scripts/project-catalog.js +243 -0
  143. package/scripts/project-dashboard.js +61 -0
  144. package/scripts/project-evidence.js +172 -0
  145. package/scripts/project-identity.js +182 -0
  146. package/scripts/project-scope.js +381 -0
  147. package/scripts/prompt-guard.js +446 -52
  148. package/scripts/proof-report.js +232 -0
  149. package/scripts/provider-action-normalizer.js +14 -6
  150. package/scripts/pulse.js +80 -0
  151. package/scripts/rate-limiter.js +41 -0
  152. package/scripts/rrsi-doctor.js +2698 -0
  153. package/scripts/secret-redaction.js +171 -25
  154. package/scripts/secret-scanner.js +101 -42
  155. package/scripts/self-protection.js +2 -2
  156. package/scripts/seo-gsd.js +14 -14
  157. package/scripts/session-context-dedupe.js +66 -0
  158. package/scripts/session-report.js +120 -0
  159. package/scripts/settings-hierarchy.js +4 -2
  160. package/scripts/statusline-meta.js +34 -23
  161. package/scripts/subagent-profiles.js +79 -0
  162. package/scripts/task-outcomes.js +29 -2
  163. package/scripts/telemetry-analytics.js +238 -13
  164. package/scripts/third-author-cli.js +118 -0
  165. package/scripts/third-author-governance.js +437 -0
  166. package/scripts/thumbgate-dream.js +878 -0
  167. package/scripts/thumbgate-search.js +23 -9
  168. package/scripts/tool-kpi-tracker.js +5 -2
  169. package/scripts/tool-registry.js +42 -1
  170. package/scripts/triage-savings-calculator.js +1 -1
  171. package/scripts/vector-store.js +4 -1
  172. package/scripts/verified-lessons.js +270 -0
  173. package/scripts/verify-marketing-pages-deployed.js +2 -2
  174. package/scripts/workflow-sentinel.js +29 -10
  175. package/server.json +2 -2
  176. package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
  177. package/src/api/server.js +2371 -451
  178. package/src/feedback.js +21 -0
  179. package/src/hermes-sync-plane.js +2 -1
  180. package/src/index.js +2 -0
  181. package/src/lesson-search.js +9 -0
  182. package/src/mckinsey-top-company-ai-coding.js +493 -0
  183. package/src/mcp/server.js +3 -0
  184. package/src/mcp-writeguard.js +772 -11
  185. package/src/openshell-lovable-engine.js +1475 -0
  186. package/src/task-outcome.js +3 -0
  187. package/config/evals/agent-safety-eval.json +0 -447
  188. package/config/evals/retrieval-ranking-golden.json +0 -522
  189. package/config/progressive/01-wire-only.json +0 -11
  190. package/config/progressive/02-dashboard-empty-ok.json +0 -10
  191. package/config/progressive/03-one-lesson.json +0 -10
  192. package/config/progressive/04-warn-fires.json +0 -11
  193. package/config/progressive/05-strict-optional.json +0 -11
  194. package/config/progressive/README.md +0 -15
  195. package/public/assets/diagrams/agent-integration.png +0 -0
  196. package/public/assets/diagrams/thumbgate-architecture.png +0 -0
  197. package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
  198. package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
  199. package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
@@ -16,7 +16,7 @@ const crypto = require('node:crypto');
16
16
  const { spawnSync } = require('node:child_process');
17
17
  const fs = require('node:fs');
18
18
  const path = require('node:path');
19
- const { getFeedbackPaths } = require('./feedback-paths');
19
+ const { getFeedbackPaths, getRuntimeDir } = require('./feedback-paths');
20
20
  const { withFileLedgerLock } = require('./file-ledger-lock');
21
21
  const {
22
22
  consumeVerifiedApproval,
@@ -83,6 +83,10 @@ const ECONOMIC_ACTION_PATTERNS = [
83
83
  /\badd\s+(?:a\s+)?payment\s+method\b/i,
84
84
  /\b(?:buy|purchase|subscribe|top-?up)\b/i,
85
85
  /\bcharge\s+(?:me\s+)?(?:\$|usd\s*)\d/i,
86
+ /\bpay\s+now\b/i,
87
+ /\bpay\s+(?:\$|usd\s*)\d/i,
88
+ /\b(?:complete|confirm|place|submit|authorize)\s+(?:your\s+|the\s+|my\s+)?(?:purchase|order|payment|checkout|transaction)\b/i,
89
+ /\b(?:proceed|continue)\s+to\s+checkout\b/i,
86
90
  /\bupgrade\b.{0,40}\b(?:pro|premium|business|enterprise)\b/i,
87
91
  /\b(?:activate|cancel|change|create|update|upgrade)\s+(?:a\s+)?(?:\w+\s+){0,3}(?:plan|subscription|tier|seat)\b/i,
88
92
  /\b(?:activate|cancel|change|create|update|upgrade)\s+(?:a\s+)?(?:\w+\s+){0,3}(?:checkout|payment\s+method)\b/i,
@@ -112,20 +116,77 @@ const ECONOMIC_ACTION_PATTERNS = [
112
116
  /\b(?:finalize|pay|refund|send|update)\s+(?:a\s+)?(?:payout|refund|subscription|top-?up|transfer)\b/i,
113
117
  ];
114
118
 
115
- // Host/path URL surfaces that open paid checkout or plan-upgrade flows.
116
- // These are NOT covered by prose patterns alone (e.g. `open https://app.apollo.io/#/settings/plans/upgrade`
117
- // or WebFetch { url: 'https://checkout.stripe.com/...' }) — Apollo $588 incident class.
119
+ // Exported linear URL patterns for external callers; runtime URL classification
120
+ // runs normalized URL parsing in containsEconomicUrl.
118
121
  const ECONOMIC_URL_PATTERNS = [
119
- /(?:https?:\/\/)?(?:www\.)?checkout\.stripe\.com\b/i,
120
- /(?:https?:\/\/)?(?:www\.)?buy\.stripe\.com\b/i,
121
- /(?:https?:\/\/)?(?:www\.)?billing\.stripe\.com\b/i,
122
- /(?:https?:\/\/)?(?:www\.)?app\.apollo\.io\b[^\s"'`]*?(?:plans|upgrade|billing|checkout|subscription)/i,
123
- /(?:https?:\/\/)?(?:www\.)?apollo\.io\b[^\s"'`]*?(?:plans|upgrade|billing|checkout|subscription)/i,
122
+ /\b(?:checkout|buy|billing)\.stripe\.com\b/i,
123
+ /\bapi\.stripe\.com\/v\d+\/(?:charges|payment_intents|payment_methods|subscriptions|checkout\/sessions|invoices|refunds|payouts|transfers|topups|treasury)\b/i,
124
+ /\bapi(?:-m)?\.(?:sandbox\.)?paypal\.com\/v\d+\/(?:checkout\/orders|payments|billing\/subscriptions|invoicing)\b/i,
125
+ /\bconnect\.squareup(?:staging|sandbox)?\.com\/v\d+\/(?:payments|orders|subscriptions|invoices|refunds)\b/i,
126
+ /\b(?:console\.cloud\.google\.com\/billing|console\.aws\.amazon\.com\/(?:billing|cost-management))\b/i,
127
+ /\b(?:ads\.google\.com|adsmanager\.facebook\.com|business\.facebook\.com\/adsmanager|ads\.linkedin\.com|ads\.(?:x|twitter|reddit|tiktok)\.com)\b/i,
124
128
  ];
125
129
 
126
- const SCREEN_TOOL_PATTERN = /(?:browser|computer|playwright|puppeteer|selenium|click|tap|press)/i;
130
+ const NON_SPEND_HOST_PREFIXES = [
131
+ 'docs.', 'developer.', 'developers.', 'help.', 'support.', 'learn.', 'blog.', 'status.',
132
+ ];
133
+ const STRIPE_CHECKOUT_HOSTS = new Set([
134
+ 'checkout.stripe.com', 'buy.stripe.com', 'billing.stripe.com',
135
+ ]);
136
+ const THUMBGATE_CHECKOUT_HOSTS = new Set([
137
+ 'thumbgate.ai', 'mcp.thumbgate.ai', 'thumbgate.app', 'thumbgate-production.up.railway.app',
138
+ ]);
139
+ const THUMBGATE_SESSION_MINTING_GO_ROUTES = /^\/go\/(?:pro-direct|pro-annual|founding-100|diagnostic-pay|sprint-pay|bundle-49|playbook-999|playbook-10|operator-diagnostic|operator-turnkey|operator-retainer|operator-pro)(?:\/|$)/i;
140
+ const STRIPE_API_SPEND_SEGMENTS = new Set([
141
+ 'charges', 'payment_intents', 'payment_methods', 'payment_links', 'subscriptions',
142
+ 'invoices', 'refunds', 'payouts', 'transfers', 'topups', 'treasury', 'billing', 'issuing',
143
+ ]);
144
+ const PAYPAL_API_HOSTS = new Set([
145
+ 'api.paypal.com', 'api-m.paypal.com', 'api.sandbox.paypal.com', 'api-m.sandbox.paypal.com',
146
+ ]);
147
+ const PAYPAL_API_SPEND_PREFIXES = [
148
+ '/v1/payments', '/v2/payments', '/v2/checkout/orders', '/v1/billing/subscriptions', '/v1/invoicing', '/v2/invoicing',
149
+ ];
150
+ const SQUARE_API_HOSTS = new Set([
151
+ 'connect.squareup.com', 'connect.squareupstaging.com', 'connect.squareupsandbox.com',
152
+ ]);
153
+ const SQUARE_API_SPEND_SEGMENTS = new Set([
154
+ 'payments', 'orders', 'subscriptions', 'invoices', 'refunds',
155
+ ]);
156
+ const AD_SPEND_HOSTS = new Set([
157
+ 'ads.google.com', 'adsmanager.facebook.com', 'ads.linkedin.com',
158
+ 'ads.x.com', 'ads.twitter.com', 'ads.reddit.com', 'ads.tiktok.com',
159
+ ]);
160
+ const STRIPE_CLI_RESOURCES = new Set([
161
+ 'charges', 'charge', 'subscriptions', 'subscription', 'payment_intents', 'payment-intents',
162
+ 'payment_methods', 'payment-methods', 'payment_links', 'payment-links', 'checkout',
163
+ 'invoices', 'invoice', 'refunds', 'refund', 'payouts', 'payout', 'transfers', 'transfer',
164
+ 'topups', 'top-ups', 'top_ups', 'treasury', 'billing', 'billing_portal', 'billing-portal',
165
+ 'issuing', 'post', 'delete', 'trigger',
166
+ ]);
167
+ const AWS_DOMAIN_SPEND_ACTIONS = new Set([
168
+ 'register-domain', 'renew-domain', 'transfer-domain',
169
+ ]);
170
+ const GENERIC_SPEND_ROUTE_PATTERN = /(?:^|[\/#])(?:checkout|billing|subscriptions?|subscribe|upgrade|payments?|(?:settings|account)\/plans)(?:$|[\/#?])/i;
171
+ const GITHUB_SPEND_ROUTE_PATTERN = /^\/(?:settings\/(?:billing|plans)|organizations\/[^/]+\/settings\/(?:billing|plans)|sponsors\b|marketplace\/[^/]+\/order\b)/i;
172
+ const STRIPE_DASHBOARD_SPEND_PATTERN = /(?:^|\/)(?:payments|billing|subscriptions|invoices|payouts|topups|treasury|balances|checkout|settlement)(?:$|[\/?#])/i;
173
+ const APOLLO_SPEND_ROUTE_PATTERN = /(?:^|[\/#?&=_-])(?:plans|upgrade|billing|checkout|subscription)(?:$|[\/#?&=_-])/i;
174
+ const APP_STORE_BUY_PATTERN = /(?:^|[\/#?&=_-])(?:buy|purchase|checkout|subscribe)(?:$|[\/#?&=_-])/i;
175
+ const ASC_BILLING_PATTERN = /(?:^|[\/#?&=_-])(?:billing|agreements|tax-and-banking)(?:$|[\/#?&=_-])/i;
176
+
177
+ const SHELL_TOOL_PATTERN = /^(?:bash|shell|terminal|execute_command|exec_command)$/i;
178
+ const SCREEN_FORM_ACTION_PATTERN = /(?:fill|type|input|enter|submit|select|check)/i;
179
+ const SCREEN_TOOL_PATTERN = /(?:browser|chrome|computer|playwright|puppeteer|selenium|form[_-]?input|click|tap|press)/i;
127
180
  const SCREEN_MUTATION_PATTERN = /(?:click|double[_ -]?click|tap|press|select|submit|confirm|activate)/i;
128
181
  const SCREEN_OBSERVATION_PATTERN = /(?:screenshot|snapshot)/i;
182
+ const BROWSER_PAGE_STATE_FILE = 'browser-page-urls.json';
183
+ const MAX_TRACKED_BROWSER_PAGES = 256;
184
+ const DISALLOWED_PAGE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
185
+ const BROWSER_ACT_TOOL_PATTERN = /(?:^|[_.:-])act$/i;
186
+ const BROWSER_NAVIGATE_TOOL_PATTERN = /(?:^|[_.:-])(?:navigate(?:[_-]page)?|goto|tabs?[_-](?:new|create)|new[_-](?:page|tab))(?:[_-]mcp)?$/i;
187
+ const BROWSER_TABS_TOOL_PATTERN = /(?:^|[_.:-])tabs$/i;
188
+ const BROWSER_NAVIGATE_ACTION_SET = new Set(['navigate', 'goto', 'new_tab', 'tabs-new']);
189
+ const BROWSER_TABS_NEW_ACTION_SET = new Set(['new', 'open', 'create', 'new_tab', 'tabs-new']);
129
190
 
130
191
  // A process principal cannot be selected through a tool call. Operators that
131
192
  // need an approved purchase to survive separate MCP/hook processes must set a
@@ -371,58 +432,541 @@ function advanceFinancialLedgerAnchor(previousHead, event, options = {}) {
371
432
  return next;
372
433
  }
373
434
 
374
- function detectEconomicAction(toolName, toolInput = {}) {
375
- const normalizedToolName = String(toolName || '').trim();
376
- if (isRemedyControlTool(normalizedToolName)) return false;
377
- if ([...CONTROL_PLANE_TOOLS].some((name) => (
378
- normalizedToolName === name || normalizedToolName.endsWith(`__${name}`)
379
- ))) return false;
380
- const metadata = objectValue(toolInput.metadata);
435
+ function safeDecodeUri(value) {
436
+ try {
437
+ return decodeURIComponent(value);
438
+ } catch {
439
+ return value;
440
+ }
441
+ }
442
+
443
+ function trimUrlDelimiters(rawToken) {
444
+ const trimChars = '"\'`<>()[]{},;';
445
+ let start = 0;
446
+ let end = rawToken.length;
447
+ while (start < end && trimChars.includes(rawToken[start])) start += 1;
448
+ while (end > start && trimChars.includes(rawToken[end - 1])) end -= 1;
449
+ const sliced = rawToken.slice(start, end);
450
+ for (const scheme of ['https://', 'http://']) {
451
+ const idx = sliced.toLowerCase().indexOf(scheme);
452
+ if (idx > 0 && '=:"\'([<'.includes(sliced[idx - 1])) {
453
+ return trimUrlDelimiters(sliced.slice(idx));
454
+ }
455
+ }
456
+ return sliced;
457
+ }
458
+
459
+ function looksLikeBareHostUrl(token) {
460
+ const slashIdx = token.indexOf('/');
461
+ const hostPart = (slashIdx === -1 ? token : token.slice(0, slashIdx)).replace(/\.$/, '');
462
+ if (!hostPart || !hostPart.includes('.')) return false;
463
+ const firstCode = hostPart.charCodeAt(0);
464
+ const isAlnum = (firstCode >= 48 && firstCode <= 57)
465
+ || (firstCode >= 65 && firstCode <= 90)
466
+ || (firstCode >= 97 && firstCode <= 122);
467
+ return isAlnum && !hostPart.includes(':');
468
+ }
469
+
470
+ function parseEconomicCandidateUrl(rawToken) {
471
+ const cleaned = trimUrlDelimiters(String(rawToken || ''));
472
+ if (!cleaned) return null;
473
+ const lower = cleaned.toLowerCase();
474
+ const hasExplicitScheme = lower.startsWith('http://') || lower.startsWith('https://');
475
+ if (!hasExplicitScheme && !looksLikeBareHostUrl(lower)) return null;
476
+ try {
477
+ const parsed = new URL(hasExplicitScheme ? cleaned : `https://${cleaned}`);
478
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, '').replace(/^www\./, '');
479
+ const decodedPath = path.posix.normalize(safeDecodeUri(parsed.pathname).toLowerCase());
480
+ const decodedSearch = safeDecodeUri(parsed.search).toLowerCase();
481
+ const decodedHash = safeDecodeUri(parsed.hash).toLowerCase();
482
+ return {
483
+ host,
484
+ pathname: decodedPath,
485
+ search: decodedSearch,
486
+ route: `${decodedPath}${decodedSearch}${decodedHash}`,
487
+ spaRoute: `${decodedPath}${decodedHash}`,
488
+ hasExplicitScheme,
489
+ };
490
+ } catch {
491
+ return null;
492
+ }
493
+ }
494
+
495
+ function isPaymentGatewayApiUrl(host, pathname) {
496
+ const parts = pathname.split('/').filter(Boolean);
497
+ if (host === 'api.stripe.com' && /^v\d+$/.test(parts[0] || '')) {
498
+ if (parts[1] === 'checkout' && parts[2] === 'sessions') return true;
499
+ return STRIPE_API_SPEND_SEGMENTS.has(parts[1] || '');
500
+ }
501
+ if (PAYPAL_API_HOSTS.has(host)) {
502
+ return PAYPAL_API_SPEND_PREFIXES.some((prefix) => pathname.startsWith(prefix));
503
+ }
504
+ if (SQUARE_API_HOSTS.has(host) && /^v\d+$/.test(parts[0] || '')) {
505
+ return SQUARE_API_SPEND_SEGMENTS.has(parts[1] || '');
506
+ }
507
+ return false;
508
+ }
509
+
510
+ function isStripeOrApolloSpendUrl(host, pathname, route) {
511
+ if (STRIPE_CHECKOUT_HOSTS.has(host)) return true;
512
+ if (host === 'dashboard.stripe.com' && STRIPE_DASHBOARD_SPEND_PATTERN.test(route)) return true;
513
+ if (host === 'stripe.com' && !pathname.startsWith('/docs')
514
+ && /^\/(?:checkout|billing|payments)(?:\/|$)/.test(pathname)) {
515
+ return true;
516
+ }
517
+ return (host === 'apollo.io' || host === 'app.apollo.io') && APOLLO_SPEND_ROUTE_PATTERN.test(route);
518
+ }
519
+
520
+ function isThumbGateLiveCheckoutMintUrl({ host, pathname, search = '' }) {
521
+ if (!THUMBGATE_CHECKOUT_HOSTS.has(host)) return false;
522
+ if (!THUMBGATE_SESSION_MINTING_GO_ROUTES.test(pathname)) return false;
523
+ return !/(?:^|[?&])probe=(?:1|true)(?:&|$)/i.test(search);
524
+ }
525
+
526
+ function isAdsSpendUrl(host, route) {
527
+ if (AD_SPEND_HOSTS.has(host)) return true;
528
+ if (host === 'business.facebook.com' && route.startsWith('/adsmanager')) return true;
529
+ return host === 'linkedin.com' && route.startsWith('/campaignmanager');
530
+ }
531
+
532
+ function isCloudConsoleSpendUrl(host, route) {
533
+ if (host === 'console.cloud.google.com' && route.startsWith('/billing')) return true;
534
+ if ((host === 'console.aws.amazon.com' || host.endsWith('.console.aws.amazon.com'))
535
+ && (route.startsWith('/billing') || route.startsWith('/cost-management'))) {
536
+ return true;
537
+ }
538
+ if (host === 'portal.azure.com' && route.includes('billing')) return true;
539
+ return host === 'dash.cloudflare.com' && route.includes('/billing');
540
+ }
541
+
542
+ function isAppStoreSpendUrl(host, route) {
543
+ if (host === 'apps.apple.com' && APP_STORE_BUY_PATTERN.test(route)) return true;
544
+ if (host === 'play.google.com' && route.startsWith('/store') && APP_STORE_BUY_PATTERN.test(route)) return true;
545
+ return host === 'appstoreconnect.apple.com' && ASC_BILLING_PATTERN.test(route);
546
+ }
547
+
548
+ function isProviderSpendUrl({ host, pathname, search, route }) {
549
+ return isPaymentGatewayApiUrl(host, pathname)
550
+ || isStripeOrApolloSpendUrl(host, pathname, route)
551
+ || isThumbGateLiveCheckoutMintUrl({ host, pathname, search })
552
+ || isAdsSpendUrl(host, route)
553
+ || isCloudConsoleSpendUrl(host, route)
554
+ || isAppStoreSpendUrl(host, route);
555
+ }
556
+
557
+ function isEconomicUrlCandidate(candidate) {
558
+ if (!candidate) return false;
559
+ if (NON_SPEND_HOST_PREFIXES.some((prefix) => candidate.host.startsWith(prefix))) return false;
560
+ if (isProviderSpendUrl(candidate)) return true;
561
+ if (!candidate.hasExplicitScheme) return false;
562
+ if (candidate.host === 'github.com' || candidate.host === 'gitlab.com') {
563
+ return GITHUB_SPEND_ROUTE_PATTERN.test(candidate.pathname);
564
+ }
565
+ return GENERIC_SPEND_ROUTE_PATTERN.test(candidate.spaRoute);
566
+ }
567
+
568
+ function containsEconomicUrl(text) {
569
+ const input = String(text || '');
570
+ if (!input) return false;
571
+ for (const token of input.split(/\s+/)) {
572
+ if (token && isEconomicUrlCandidate(parseEconomicCandidateUrl(token))) return true;
573
+ }
574
+ for (const match of input.matchAll(/https?:\/\/[^\s"'`<>()[\]{},;]+/gi)) {
575
+ if (isEconomicUrlCandidate(parseEconomicCandidateUrl(match[0]))) return true;
576
+ }
577
+ return false;
578
+ }
579
+
580
+ function isAwsEconomicCli(positional) {
581
+ const service = positional[0] || '';
582
+ const action = positional[1] || '';
583
+ if (service === 'billing' || service === 'billingconductor' || service === 'ce') return true;
584
+ if (service === 'budgets') {
585
+ return action.startsWith('create') || action.startsWith('update') || action.startsWith('delete');
586
+ }
587
+ if (service === 'ec2' || service === 'rds') return action.startsWith('purchase-');
588
+ if (service === 'savingsplans') return action.startsWith('create-');
589
+ return service === 'route53domains' && AWS_DOMAIN_SPEND_ACTIONS.has(action);
590
+ }
591
+
592
+ function isHerokuEconomicCli(pos) {
593
+ return Boolean(pos[0] && (pos[0].startsWith('addons:create') || pos[0].startsWith('addons:upgrade')));
594
+ }
595
+
596
+ function isFlyEconomicCli(pos) {
597
+ return pos[0] === 'scale' || (pos[0] === 'volumes' && pos[1] === 'create');
598
+ }
599
+
600
+ function isVercelEconomicCli(pos) {
601
+ return pos[0] === 'billing' || (pos[0] === 'domains' && pos[1] === 'buy');
602
+ }
603
+
604
+ function isPlatformEconomicCli(executable, positional) {
605
+ switch (executable) {
606
+ case 'stripe':
607
+ return positional.some((tok) => STRIPE_CLI_RESOURCES.has(tok));
608
+ case 'gcloud':
609
+ return positional.includes('billing');
610
+ case 'aws':
611
+ return isAwsEconomicCli(positional);
612
+ case 'az':
613
+ return positional[0] === 'billing' || positional[0] === 'consumption';
614
+ case 'heroku':
615
+ return isHerokuEconomicCli(positional);
616
+ case 'fly':
617
+ case 'flyctl':
618
+ return isFlyEconomicCli(positional);
619
+ case 'wrangler':
620
+ return positional[0] === 'billing';
621
+ case 'vercel':
622
+ return isVercelEconomicCli(positional);
623
+ default:
624
+ return false;
625
+ }
626
+ }
627
+
628
+ const PACKAGE_RUNNERS = new Set(['npx', 'bunx']);
629
+ const GLOBAL_VALUE_FLAGS = new Set([
630
+ '--profile', '--region', '--project', '--api-key', '--config', '--account', '--subscription', '--scope',
631
+ ]);
632
+
633
+ function isShellPrefixToken(tok) {
634
+ return tok === 'sudo' || tok === 'env' || /^[a-z_]\w*=/.test(tok);
635
+ }
636
+
637
+ function resolveSegmentCommand(tokens) {
638
+ let idx = 0;
639
+ while (idx < tokens.length && isShellPrefixToken(tokens[idx])) idx += 1;
640
+ let executable = (tokens[idx] || '').split('/').at(-1);
641
+ idx += 1;
642
+ if (executable && PACKAGE_RUNNERS.has(executable)) {
643
+ while (idx < tokens.length && tokens[idx].startsWith('-')) idx += 1;
644
+ executable = (tokens[idx] || '').split('/').at(-1).split('@')[0];
645
+ idx += 1;
646
+ }
647
+ return { executable: executable || '', startIdx: idx };
648
+ }
649
+
650
+ function collectPositionalCliArgs(tokens, startIdx) {
651
+ const positional = [];
652
+ let idx = startIdx;
653
+ while (idx < tokens.length) {
654
+ const tok = tokens[idx];
655
+ if (GLOBAL_VALUE_FLAGS.has(tok)) {
656
+ idx += 2;
657
+ } else if (tok.startsWith('-')) {
658
+ idx += 1;
659
+ } else {
660
+ positional.push(tok);
661
+ idx += 1;
662
+ }
663
+ }
664
+ return positional;
665
+ }
666
+
667
+ function isEconomicCliSegment(rawSegment) {
668
+ const tokens = stripNonEconomicQuotedStrings(rawSegment)
669
+ .trim()
670
+ .split(/\s+/)
671
+ .filter(Boolean)
672
+ .map((tok) => tok.toLowerCase());
673
+ const { executable, startIdx } = resolveSegmentCommand(tokens);
674
+ if (!executable || NON_ECONOMIC_SHELL_EXECUTABLES.has(executable)) return false;
675
+ return isPlatformEconomicCli(executable, collectPositionalCliArgs(tokens, startIdx));
676
+ }
677
+
678
+ const SUBSHELL_EXECUTABLES = new Set(['bash', 'sh', 'zsh']);
679
+
680
+ function stripLeadingShellPrefixes(segment) {
681
+ let rest = segment.trimStart();
682
+ while (rest) {
683
+ const firstSpace = rest.search(/\s/);
684
+ if (firstSpace < 0) break;
685
+ if (!isShellPrefixToken(rest.slice(0, firstSpace).toLowerCase())) break;
686
+ rest = rest.slice(firstSpace).trimStart();
687
+ }
688
+ return rest;
689
+ }
690
+
691
+ function hasShellEconomicCliCommand(rawCommand) {
692
+ for (const segment of splitShellSegmentsOutsideQuotes(String(rawCommand || ''))) {
693
+ const stripped = stripLeadingShellPrefixes(segment.trim());
694
+ if (!stripped) continue;
695
+ const firstExec = /^([\w./-]+)/.exec(stripped)?.[1]?.split('/').at(-1)?.toLowerCase();
696
+ if (SUBSHELL_EXECUTABLES.has(firstExec || '')) {
697
+ const subshell = extractSubshellCommand(stripped);
698
+ if (subshell !== null && hasShellEconomicCliCommand(subshell)) return true;
699
+ }
700
+ if (isEconomicCliSegment(stripped)) return true;
701
+ }
702
+ return false;
703
+ }
704
+
705
+ function hasExplicitEconomicSignal(toolInput, metadata) {
381
706
  const financialControl = objectValue(toolInput.financialControl || toolInput.financial_control);
382
707
  if (toolInput.economicAction === true || metadata.economicAction === true) return true;
383
- if (financialControl.requisitionId || financialControl.reservationId) return true;
384
- // Native browser/computer-use locators do not reveal what a click will do.
385
- // Treat them as economic until the exact screen mutation is independently
386
- // approved; caller-supplied prose must never downgrade a blind click.
387
- if (detectOpaqueScreenMutation(normalizedToolName, toolInput)) return true;
388
- const command = shellEconomicText(normalizedToolName, toolInput.command || toolInput.cmd);
389
- const screenMutationProse = isDeclaredScreenMutation(normalizedToolName, toolInput)
390
- ? [toolInput.goal, toolInput.description, toolInput.prompt, metadata.context]
391
- : [];
392
- // WebFetch / browser navigate often put the spend surface only in url/uri/href.
393
- const navigationTargets = [
708
+ return Boolean(financialControl.requisitionId || financialControl.reservationId);
709
+ }
710
+
711
+ function detectShellEconomicAction(normalizedToolName, toolInput, metadata) {
712
+ const rawCommand = toolInput.command || toolInput.cmd;
713
+ const shellText = shellEconomicText(normalizedToolName, rawCommand);
714
+ if (!String(shellText || '').trim()) return false;
715
+ if (containsEconomicUrl(shellText)) return true;
716
+ if (hasShellEconomicCliCommand(rawCommand)) return true;
717
+ const metadataContext = String(metadata.context || '');
718
+ if (!metadataContext) return false;
719
+ return containsEconomicUrl(metadataContext)
720
+ || ECONOMIC_ACTION_PATTERNS.some((pattern) => pattern.test(metadataContext));
721
+ }
722
+
723
+ function collectFieldEntryTargets(fieldsInput) {
724
+ if (!Array.isArray(fieldsInput)) return [];
725
+ const out = [];
726
+ for (const entry of fieldsInput) {
727
+ const item = objectValue(entry);
728
+ const entryOp = [item.action, item.operation, item.type, item.kind].map((v) => String(v || '')).join(' ');
729
+ out.push(item.element, item.label, item.name, item.title, item.placeholder, item.ariaLabel, item.aria_label);
730
+ if (SCREEN_MUTATION_PATTERN.test(entryOp)) out.push(item.text, item.value);
731
+ }
732
+ return out;
733
+ }
734
+
735
+ function collectScreenMutationTargets(normalizedToolName, toolInput, metadata) {
736
+ if (!isDeclaredScreenMutation(normalizedToolName, toolInput)) return [];
737
+ const declaredOperation = [toolInput.action, toolInput.operation, toolInput.type, toolInput.kind]
738
+ .map((value) => String(value || ''))
739
+ .join(' ');
740
+ const isClickOrSubmit = SCREEN_MUTATION_PATTERN.test(normalizedToolName)
741
+ || SCREEN_MUTATION_PATTERN.test(declaredOperation);
742
+ const nonUrlTarget = parseEconomicCandidateUrl(toolInput.target) ? '' : toolInput.target;
743
+ const fields = [
744
+ toolInput.element,
745
+ toolInput.label,
746
+ toolInput.name,
747
+ toolInput.title,
748
+ toolInput.button,
749
+ toolInput.control,
750
+ toolInput.selector,
751
+ toolInput.ariaLabel,
752
+ toolInput.aria_label,
753
+ toolInput.placeholder,
754
+ toolInput.goal,
755
+ toolInput.description,
756
+ toolInput.prompt,
757
+ nonUrlTarget,
758
+ metadata.context,
759
+ ...collectFieldEntryTargets(toolInput.fields),
760
+ ];
761
+ if (isClickOrSubmit) {
762
+ fields.push(toolInput.text, toolInput.value);
763
+ }
764
+ return fields.map((value) => String(value || '').replace(/[_-]+/g, ' '));
765
+ }
766
+
767
+ function collectNavigationTargets(toolInput, metadata) {
768
+ return [
394
769
  toolInput.url,
395
770
  toolInput.uri,
396
771
  toolInput.href,
397
772
  toolInput.link,
398
773
  toolInput.navigate,
399
774
  toolInput.target,
775
+ toolInput.pageUrl,
776
+ toolInput.page_url,
777
+ toolInput.tabUrl,
778
+ toolInput.tab_url,
779
+ toolInput.currentUrl,
780
+ toolInput.current_url,
781
+ toolInput.origin,
782
+ toolInput.code,
783
+ toolInput.script,
784
+ toolInput.expression,
785
+ metadata.url,
786
+ metadata.pageUrl,
787
+ metadata.tabUrl,
400
788
  ].map((value) => String(value || '')).join(' ');
789
+ }
790
+
791
+ function getBrowserPageStatePath(options = {}) {
792
+ const explicitDir = optionalString(options.runtimeDir)
793
+ || optionalString(process.env.THUMBGATE_RUNTIME_DIR);
794
+ const runtimeDir = explicitDir ? path.resolve(explicitDir) : getRuntimeDir(options);
795
+ return path.join(runtimeDir, BROWSER_PAGE_STATE_FILE);
796
+ }
797
+
798
+ function normalizeBrowserPageId(value) {
799
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
800
+ if (typeof value !== 'string') return '';
801
+ const trimmed = value.trim();
802
+ if (!trimmed || trimmed.length > 128 || DISALLOWED_PAGE_KEYS.has(trimmed)) return '';
803
+ return trimmed;
804
+ }
805
+
806
+ function extractBrowserPageIds(toolInput = {}) {
807
+ const input = objectValue(toolInput);
808
+ const ids = [];
809
+ for (const candidate of [input.page, input.pageId, input.page_id, input.tabId, input.tab_id, input.tab]) {
810
+ const normalized = normalizeBrowserPageId(candidate);
811
+ if (normalized && !ids.includes(normalized)) ids.push(normalized);
812
+ }
813
+ return ids;
814
+ }
815
+
816
+ function extractExplicitPageUrl(toolInput = {}, metadata = {}) {
817
+ for (const candidate of [
818
+ toolInput.url,
819
+ toolInput.uri,
820
+ toolInput.href,
821
+ toolInput.navigate,
822
+ toolInput.pageUrl,
823
+ toolInput.page_url,
824
+ toolInput.tabUrl,
825
+ toolInput.tab_url,
826
+ toolInput.currentUrl,
827
+ toolInput.current_url,
828
+ metadata.url,
829
+ metadata.pageUrl,
830
+ metadata.tabUrl,
831
+ ]) {
832
+ const text = optionalString(candidate);
833
+ if (text && parseEconomicCandidateUrl(text)) return text;
834
+ }
835
+ return '';
836
+ }
837
+
838
+ function readBrowserPageStateMap(options = {}) {
839
+ try {
840
+ const parsed = JSON.parse(fs.readFileSync(getBrowserPageStatePath(options), 'utf8'));
841
+ const pages = objectValue(parsed?.pages);
842
+ const map = new Map();
843
+ for (const [key, value] of Object.entries(pages)) {
844
+ if (!DISALLOWED_PAGE_KEYS.has(key) && typeof value === 'string' && value) {
845
+ map.set(key, value);
846
+ }
847
+ }
848
+ return map;
849
+ } catch {
850
+ return new Map();
851
+ }
852
+ }
853
+
854
+ function writeBrowserPageStateMap(map, options = {}) {
855
+ const statePath = getBrowserPageStatePath(options);
856
+ const pages = Object.fromEntries(Array.from(map.entries()).slice(-MAX_TRACKED_BROWSER_PAGES));
857
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
858
+ const tempPath = `${statePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
859
+ fs.writeFileSync(tempPath, `${JSON.stringify({ pages }, null, 2)}\n`, 'utf8');
860
+ fs.renameSync(tempPath, statePath);
861
+ }
862
+
863
+ function isBrowserNavigateOrTabsNewCall(normalizedToolName, toolInput) {
864
+ if (!SCREEN_TOOL_PATTERN.test(normalizedToolName)) return false;
865
+ if (BROWSER_NAVIGATE_TOOL_PATTERN.test(normalizedToolName)) return true;
866
+ const action = String(toolInput.action || toolInput.kind || toolInput.operation || toolInput.mode || '')
867
+ .trim()
868
+ .toLowerCase();
869
+ if (BROWSER_TABS_TOOL_PATTERN.test(normalizedToolName)) {
870
+ return BROWSER_TABS_NEW_ACTION_SET.has(action);
871
+ }
872
+ return toolInput.new_tab === true || BROWSER_NAVIGATE_ACTION_SET.has(action);
873
+ }
874
+
875
+ function recordBrowserPageNavigation(toolName, toolInput = {}, options = {}) {
876
+ try {
877
+ const normalizedToolName = String(toolName || '').trim();
878
+ const input = objectValue(toolInput);
879
+ if (!isBrowserNavigateOrTabsNewCall(normalizedToolName, input)) return false;
880
+ const pageIds = extractBrowserPageIds(input);
881
+ const url = extractExplicitPageUrl(input, objectValue(input.metadata));
882
+ if (pageIds.length === 0 || !url) return false;
883
+ const map = readBrowserPageStateMap(options);
884
+ for (const pageId of pageIds) {
885
+ map.delete(pageId);
886
+ map.set(pageId, url);
887
+ }
888
+ writeBrowserPageStateMap(map, options);
889
+ return true;
890
+ } catch {
891
+ return false;
892
+ }
893
+ }
894
+
895
+ function lookupRecordedBrowserPageUrl(pageId, options = {}) {
896
+ const normalizedPageId = normalizeBrowserPageId(pageId);
897
+ if (!normalizedPageId) return '';
898
+ return readBrowserPageStateMap(options).get(normalizedPageId) || '';
899
+ }
900
+
901
+ function hasRecordedEconomicPageUrl(normalizedToolName, toolInput, metadata, options) {
902
+ if (!isDeclaredScreenMutation(normalizedToolName, toolInput)) return false;
903
+ if (extractExplicitPageUrl(toolInput, metadata)) return false;
904
+ const pageIds = extractBrowserPageIds(toolInput);
905
+ if (pageIds.length === 0) return false;
906
+ const stateMap = readBrowserPageStateMap(options);
907
+ return pageIds.some((id) => containsEconomicUrl(stateMap.get(id) || ''));
908
+ }
909
+
910
+ function detectEconomicAction(toolName, toolInput = {}, options = {}) {
911
+ const normalizedToolName = String(toolName || '').trim();
912
+ if (isRemedyControlTool(normalizedToolName)) return false;
913
+ const metadata = objectValue(toolInput.metadata);
914
+ if (hasExplicitEconomicSignal(toolInput, metadata)) return true;
915
+ if (isScreenObservationOnly(normalizedToolName, toolInput)) return false;
916
+ if (SHELL_TOOL_PATTERN.test(normalizedToolName)) {
917
+ return detectShellEconomicAction(normalizedToolName, toolInput, metadata);
918
+ }
919
+ const navigationTargets = collectNavigationTargets(toolInput, metadata);
920
+ if (containsEconomicUrl(navigationTargets)) return true;
921
+ if (hasRecordedEconomicPageUrl(normalizedToolName, toolInput, metadata, options)) return true;
922
+ const command = shellEconomicText(normalizedToolName, toolInput.command || toolInput.cmd);
923
+ if (containsEconomicUrl(command)) return true;
924
+ const screenMutationTargets = collectScreenMutationTargets(normalizedToolName, toolInput, metadata);
401
925
  const combined = [
402
926
  normalizedToolName.replace(/[_-]+/g, ' '),
403
927
  command,
404
928
  toolInput.action,
405
929
  toolInput.operation,
406
- navigationTargets,
407
- ...screenMutationProse,
930
+ toolInput.kind,
931
+ ...screenMutationTargets,
408
932
  ].map((value) => String(value || '')).join(' ');
409
- if (ECONOMIC_URL_PATTERNS.some((pattern) => pattern.test(combined))) return true;
410
933
  return ECONOMIC_ACTION_PATTERNS.some((pattern) => pattern.test(combined));
411
934
  }
412
935
 
936
+ function isScreenObservationOnly(toolName, toolInput = {}) {
937
+ const normalizedToolName = String(toolName || '').trim();
938
+ if (!SCREEN_TOOL_PATTERN.test(normalizedToolName)) return false;
939
+ const input = objectValue(toolInput);
940
+ const declaredOperation = [input.action, input.operation, input.type, input.kind]
941
+ .map((value) => String(value || ''))
942
+ .join(' ');
943
+ const toolDeclaresMutation = SCREEN_MUTATION_PATTERN.test(normalizedToolName);
944
+ const declaredMutation = SCREEN_MUTATION_PATTERN.test(declaredOperation);
945
+ const toolDeclaresObservation = SCREEN_OBSERVATION_PATTERN.test(normalizedToolName);
946
+ const declaredObservation = SCREEN_OBSERVATION_PATTERN.test(declaredOperation);
947
+ return toolDeclaresObservation || (!toolDeclaresMutation && !declaredMutation && declaredObservation);
948
+ }
949
+
413
950
  function isDeclaredScreenMutation(toolName, toolInput = {}) {
414
- if (!SCREEN_TOOL_PATTERN.test(String(toolName || ''))) return false;
951
+ const normalizedToolName = String(toolName || '').trim();
952
+ if (!SCREEN_TOOL_PATTERN.test(normalizedToolName)) return false;
953
+ if (isScreenObservationOnly(normalizedToolName, toolInput)) return false;
415
954
  const input = objectValue(toolInput);
416
- const declaredOperation = [input.action, input.operation, input.type]
955
+ if (Array.isArray(input.fields) && input.fields.length > 0) return true;
956
+ const declaredOperation = [input.action, input.operation, input.type, input.kind]
417
957
  .map((value) => String(value || ''))
418
958
  .join(' ');
419
- return SCREEN_MUTATION_PATTERN.test(toolName) || SCREEN_MUTATION_PATTERN.test(declaredOperation);
959
+ return BROWSER_ACT_TOOL_PATTERN.test(normalizedToolName)
960
+ || SCREEN_MUTATION_PATTERN.test(normalizedToolName)
961
+ || SCREEN_MUTATION_PATTERN.test(declaredOperation)
962
+ || SCREEN_FORM_ACTION_PATTERN.test(normalizedToolName)
963
+ || SCREEN_FORM_ACTION_PATTERN.test(declaredOperation);
420
964
  }
421
965
 
422
966
  function detectOpaqueScreenMutation(toolName, toolInput = {}) {
423
967
  const normalizedToolName = String(toolName || '').trim();
424
968
  const input = objectValue(toolInput);
425
- const declaredOperation = [input.action, input.operation, input.type]
969
+ const declaredOperation = [input.action, input.operation, input.type, input.kind]
426
970
  .map((value) => String(value || ''))
427
971
  .join(' ');
428
972
  const toolDeclaresMutation = SCREEN_MUTATION_PATTERN.test(normalizedToolName);
@@ -448,23 +992,128 @@ function detectOpaqueScreenMutation(toolName, toolInput = {}) {
448
992
  || /(?:browser|computer|playwright|puppeteer|selenium)/i.test(normalizedToolName);
449
993
  }
450
994
 
995
+ const NON_ECONOMIC_SHELL_EXECUTABLES = new Set([
996
+ 'rg', 'grep', 'egrep', 'fgrep', 'git', 'cat', 'head', 'tail', 'less', 'more',
997
+ 'echo', 'printf', 'herdr', 'sed', 'awk', 'jq', 'ls', 'find', 'wc', 'diff',
998
+ 'stat', 'mdfind', 'true', 'false', 'cd', 'pwd',
999
+ ]);
1000
+
1001
+ function splitShellSegmentsOutsideQuotes(command) {
1002
+ const segments = [];
1003
+ let current = '';
1004
+ let quote = null;
1005
+ for (let i = 0; i < command.length; i += 1) {
1006
+ const ch = command[i];
1007
+ if (quote) {
1008
+ current += ch;
1009
+ if (ch === '\\' && quote === '"' && i + 1 < command.length) {
1010
+ i += 1;
1011
+ current += command[i];
1012
+ } else if (ch === quote) {
1013
+ quote = null;
1014
+ }
1015
+ continue;
1016
+ }
1017
+ if (ch === '\'' || ch === '"') {
1018
+ quote = ch;
1019
+ current += ch;
1020
+ continue;
1021
+ }
1022
+ if (ch === '\\' && i + 1 < command.length) {
1023
+ current += ch + command[i + 1];
1024
+ i += 1;
1025
+ continue;
1026
+ }
1027
+ if ((ch === '&' && command[i + 1] === '&') || (ch === '|' && command[i + 1] === '|')) {
1028
+ segments.push(current);
1029
+ current = '';
1030
+ i += 1;
1031
+ continue;
1032
+ }
1033
+ if (ch === ';' || ch === '\n' || ch === '|') {
1034
+ segments.push(current);
1035
+ current = '';
1036
+ continue;
1037
+ }
1038
+ current += ch;
1039
+ }
1040
+ if (current) segments.push(current);
1041
+ return segments;
1042
+ }
1043
+
1044
+ function stripNonEconomicQuotedStrings(segment) {
1045
+ let out = '';
1046
+ let i = 0;
1047
+ while (i < segment.length) {
1048
+ const ch = segment[i];
1049
+ if (ch !== '\'' && ch !== '"') {
1050
+ if (ch === '\\' && i + 1 < segment.length) {
1051
+ out += ch + segment[i + 1];
1052
+ i += 2;
1053
+ } else {
1054
+ out += ch;
1055
+ i += 1;
1056
+ }
1057
+ continue;
1058
+ }
1059
+ const quote = ch;
1060
+ let j = i + 1;
1061
+ while (j < segment.length) {
1062
+ if (segment[j] === '\\' && quote === '"' && j + 1 < segment.length) {
1063
+ j += 2;
1064
+ continue;
1065
+ }
1066
+ if (segment[j] === quote) break;
1067
+ j += 1;
1068
+ }
1069
+ if (j >= segment.length) {
1070
+ out += segment.slice(i);
1071
+ break;
1072
+ }
1073
+ const full = segment.slice(i, j + 1);
1074
+ const inner = segment.slice(i + 1, j);
1075
+ out += containsEconomicUrl(inner) ? full : ' ';
1076
+ i = j + 1;
1077
+ }
1078
+ return out;
1079
+ }
1080
+
1081
+ function extractSubshellCommand(clean) {
1082
+ const flagMatch = /^[\w./-]+\s+-[a-z]*c\s+/i.exec(clean);
1083
+ if (!flagMatch) return null;
1084
+ const rest = clean.slice(flagMatch[0].length).trim();
1085
+ if (rest.length >= 2 && (rest[0] === '\'' || rest[0] === '"') && rest.at(-1) === rest[0]) {
1086
+ return rest.slice(1, -1);
1087
+ }
1088
+ return null;
1089
+ }
1090
+
451
1091
  function shellEconomicText(toolName, rawCommand) {
452
1092
  if (!/^(?:bash|shell|terminal|execute_command|exec_command)$/i.test(toolName)) {
453
1093
  return rawCommand;
454
1094
  }
455
1095
  const command = String(rawCommand || '');
456
- return command
457
- .split(/(?:&&|\|\||[;\n]|(?<!\|)\|(?!\|))/)
1096
+ return splitShellSegmentsOutsideQuotes(command)
458
1097
  .map((segment) => {
459
- const clean = segment.trim().replace(/^(?:sudo\s+)?(?:env\s+)?(?:[A-Za-z_]\w*=[^\s]+\s+)*/, '');
1098
+ let clean = segment.trim();
1099
+ while (/^(?:sudo|env)\s+/.test(clean) || /^[A-Za-z_]\w*=[^\s]+\s+/.test(clean)) {
1100
+ clean = clean.replace(/^(?:sudo|env)\s+/, '').replace(/^[A-Za-z_]\w*=[^\s]+\s+/, '');
1101
+ }
1102
+ if (!clean) return '';
460
1103
  const executable = /^([\w./-]+)/.exec(clean)?.[1]?.split('/').at(-1)?.toLowerCase();
461
- if (['rg', 'grep', 'git', 'cat', 'head', 'tail', 'less', 'more', 'echo', 'printf'].includes(executable)) {
1104
+ if (!executable || NON_ECONOMIC_SHELL_EXECUTABLES.has(executable)) {
462
1105
  return '';
463
1106
  }
464
- if (executable === 'gh' && /\b(?:issue|pr)\s+(?:create|view|list|status|edit|comment)\b/i.test(clean)) {
1107
+ if (['bash', 'sh', 'zsh'].includes(executable)) {
1108
+ const subshellCmd = extractSubshellCommand(clean);
1109
+ if (subshellCmd !== null) {
1110
+ return shellEconomicText('Bash', subshellCmd);
1111
+ }
1112
+ }
1113
+ if (executable === 'gh' && /\b(?:issue|pr|release|run|workflow|repo|status|search)\b/i.test(clean)) {
465
1114
  return '';
466
1115
  }
467
- return clean;
1116
+ return stripNonEconomicQuotedStrings(clean);
468
1117
  })
469
1118
  .join(' ');
470
1119
  }
@@ -479,7 +1128,7 @@ function createPurchaseRequisition(input = {}, options = {}) {
479
1128
  const sourceMessageId = requiredString(input.sourceMessageId, 'sourceMessageId');
480
1129
  const amountUsd = positiveMoney(input.amountUsd, 'amountUsd');
481
1130
  const approvedAction = buildActionAuthorization(input.toolName, input.toolInput, amountUsd);
482
- if (!detectEconomicAction(approvedAction.toolName, objectValue(input.toolInput))) {
1131
+ if (!detectEconomicAction(approvedAction.toolName, objectValue(input.toolInput), options)) {
483
1132
  throw financialError('purchase requisitions must bind an exact economic tool action');
484
1133
  }
485
1134
  const evidence = stringArray(input.evidence);
@@ -803,11 +1452,19 @@ function reconcilePurchaseLedgerUnlocked(options = {}) {
803
1452
  };
804
1453
  }
805
1454
 
1455
+ function maybeRecordAllowedBrowserPage(input, options, allowed) {
1456
+ if (!allowed || options.consumeReservation !== true) return;
1457
+ recordBrowserPageNavigation(input.toolName, input.toolInput, options);
1458
+ }
1459
+
806
1460
  function evaluateFinancialControl(input = {}, options = {}) {
807
1461
  const actionProfile = objectValue(input.actionProfile);
808
1462
  const economicAction = actionProfile.economicAction === true
809
- || detectEconomicAction(input.toolName, input.toolInput);
810
- if (!economicAction) return allowNonEconomicAction();
1463
+ || detectEconomicAction(input.toolName, input.toolInput, options);
1464
+ if (!economicAction) {
1465
+ maybeRecordAllowedBrowserPage(input, options, true);
1466
+ return allowNonEconomicAction();
1467
+ }
811
1468
 
812
1469
  const result = financialEvaluationContext(input, options);
813
1470
  validateBudget(result);
@@ -815,7 +1472,9 @@ function evaluateFinancialControl(input = {}, options = {}) {
815
1472
  validateRequisition(result, options);
816
1473
  validateCostControl(result);
817
1474
  consumeReservationIfAuthorized(result, input, options);
818
- return buildFinancialDecision(result);
1475
+ const decision = buildFinancialDecision(result);
1476
+ maybeRecordAllowedBrowserPage(input, options, decision.mode === 'allow');
1477
+ return decision;
819
1478
  }
820
1479
 
821
1480
  function allowNonEconomicAction() {
@@ -1657,14 +2316,17 @@ module.exports = {
1657
2316
  isRemedyControlTool,
1658
2317
  detectOpaqueScreenMutation,
1659
2318
  evaluateFinancialControl,
2319
+ getBrowserPageStatePath,
1660
2320
  getLedgerHeadPath,
1661
2321
  getLedgerJournalPath,
1662
2322
  getLedgerPath,
1663
2323
  getFinancialControlRuntimeOptions,
1664
2324
  getRuntimePrincipal,
1665
2325
  listPurchaseRequisitions,
2326
+ lookupRecordedBrowserPageUrl,
1666
2327
  projectRequisition,
1667
2328
  readEvents,
2329
+ recordBrowserPageNavigation,
1668
2330
  reconcilePurchaseLedger,
1669
2331
  reservePurchaseRequisition,
1670
2332
  settlePurchaseRequisition,