tachibot-mcp 2.28.0 → 2.30.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 (46) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +16 -7
  3. package/dist/src/config/model-constants.js +51 -24
  4. package/dist/src/modes/challenger.js +2 -2
  5. package/dist/src/modes/scout.js +3 -3
  6. package/dist/src/optimization/model-router.js +34 -17
  7. package/dist/src/profiles/balanced.js +2 -1
  8. package/dist/src/profiles/code_focus.js +2 -1
  9. package/dist/src/profiles/full.js +2 -1
  10. package/dist/src/profiles/heavy_coding.js +2 -1
  11. package/dist/src/profiles/minimal.js +2 -1
  12. package/dist/src/profiles/research_power.js +2 -1
  13. package/dist/src/tools/diff-review-tool.js +14 -6
  14. package/dist/src/tools/gemini-tools.js +104 -46
  15. package/dist/src/tools/grok-enhanced.js +5 -3
  16. package/dist/src/tools/grok-search-lite-tool.js +21 -7
  17. package/dist/src/tools/grok-tools.js +9 -4
  18. package/dist/src/tools/jury-tool.js +69 -28
  19. package/dist/src/tools/openai-tools.js +26 -13
  20. package/dist/src/tools/openrouter-tools.js +6 -6
  21. package/dist/src/tools/plan-critique-tool.js +12 -5
  22. package/dist/src/tools/planner-tools.js +5 -2
  23. package/dist/src/tools/workflow-runner.js +1 -1
  24. package/dist/src/utils/judge-constants.js +83 -0
  25. package/dist/src/utils/judge-runner.js +58 -0
  26. package/dist/src/utils/provider-failure.js +18 -0
  27. package/dist/src/utils/provider-router.js +4 -4
  28. package/dist/src/utils/smart-api-client.js +3 -3
  29. package/dist/src/workflows/custom-workflows.js +8 -2
  30. package/dist/src/workflows/tool-mapper.js +34 -12
  31. package/docs/superpowers/plans/2026-08-12-kitchen-architecture.md +1600 -0
  32. package/docs/superpowers/plans/2026-08-12-openrouter-spec-table.md +1201 -0
  33. package/docs/superpowers/plans/2026-08-12-prompt-approach-repair.md +2059 -0
  34. package/docs/superpowers/plans/2026-08-12-provider-catalogs.md +1519 -0
  35. package/docs/superpowers/plans/2026-08-14-mcp-compliance-and-tool-surface.md +3035 -0
  36. package/package.json +1 -1
  37. package/profiles/balanced.json +2 -1
  38. package/profiles/code_focus.json +2 -1
  39. package/profiles/full.json +2 -1
  40. package/profiles/heavy_coding.json +2 -1
  41. package/profiles/minimal.json +2 -1
  42. package/profiles/research_power.json +2 -1
  43. package/skills/landing/SKILL.md +110 -0
  44. package/skills/release/SKILL.md +135 -0
  45. package/smithery.yaml +1 -1
  46. package/tools.config.json +65 -17
@@ -4,19 +4,44 @@
4
4
  * No need for separate gemini-mcp server
5
5
  */
6
6
  import { z } from "zod";
7
+ import { config } from "dotenv";
8
+ import * as path from "path";
9
+ import { fileURLToPath } from "url";
7
10
  import { validateToolInput } from "../utils/input-validator.js";
11
+ import { isProviderFailure } from "../utils/provider-failure.js";
8
12
  import { GEMINI_MODELS } from "../config/model-constants.js";
9
13
  import { tryOpenRouterGateway, isGatewayEnabled } from "../utils/openrouter-gateway.js";
10
14
  import { stripFormatting } from "../utils/format-stripper.js";
11
15
  import { FORMAT_INSTRUCTION } from "../utils/format-constants.js";
16
+ import { JUDGE_MODE_INSTRUCTIONS, JUDGE_METHOD, JUDGE_EPISTEMIC_LIMIT, JUDGE_BIAS_CONTROLS, JUDGE_FORMAT_EXCEPTION, } from "../utils/judge-constants.js";
12
17
  import { withHeartbeat } from "../utils/streaming-helper.js";
13
18
  import { getTimeoutConfig } from "../config/timeout-config.js";
14
19
  import { readFilesIntoContext } from "../utils/file-reader.js";
15
20
  import { defineModelTool } from "./factory/define-model-tool.js";
16
21
  import { filesField } from "./factory/base-schemas.js";
17
22
  // Note: renderOutput is applied centrally in server.ts safeAddTool() - no need to import here
18
- // NOTE: dotenv is loaded in server.ts before any imports
19
- // No need to reload here - just read from process.env
23
+ // Load .env here rather than relying on a sibling module to have done it.
24
+ //
25
+ // The old comment claimed "dotenv is loaded in server.ts before any imports". That is not
26
+ // true: server.ts is a 12-line bin dispatcher with ZERO static imports and no dotenv call
27
+ // at all, and server-main.ts's dotenvConfig({override:true}) runs in its module BODY —
28
+ // which ESM evaluates AFTER the entire static import graph, so it cannot reach the
29
+ // module-scope capture below.
30
+ //
31
+ // What actually made this work was import ORDER inside registry.ts: grok-tools.js (:43)
32
+ // calls config() at module scope, eleven lines before gemini-tools.js (:53) is reached, so
33
+ // process.env happened to be populated by the time we read it. Demonstrated:
34
+ //
35
+ // import openrouter-tools alone -> isOpenRouterAvailable() === false
36
+ // import grok-tools first, then it -> isOpenRouterAvailable() === true
37
+ //
38
+ // That coupling is invisible and load-bearing: reordering registry's imports, or dropping
39
+ // grok-tools, would silently unregister every Gemini tool. Loading dotenv here makes this
40
+ // module self-sufficient. Non-override, matching every other tool module, so an ambient
41
+ // var still wins — that precedence is deliberate (12-factor) and unchanged.
42
+ const __gtFilename = fileURLToPath(import.meta.url);
43
+ const __gtDirname = path.dirname(__gtFilename);
44
+ config({ path: path.resolve(__gtDirname, '../../../.env') });
20
45
  // Gemini API configuration
21
46
  const GEMINI_API_KEY = process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY;
22
47
  const GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta";
@@ -27,7 +52,57 @@ const GEMINI_API_URL = "https://generativelanguage.googleapis.com/v1beta";
27
52
  * - 'code-analysis': Relaxed for code analysis tools
28
53
  * - 'llm-orchestration': Medium for LLM-to-LLM calls
29
54
  */
55
+ /** Pull RetryInfo.retryDelay ("37s") out of a Google error body. Null when absent — and
56
+ * absence is itself a signal: Google omits RetryInfo for plan/daily caps, so a 429 with
57
+ * no retryDelay generally means waiting will not help. */
58
+ export function parseRetryDelayMs(body) {
59
+ const m = body.match(/"retryDelay"\s*:\s*"(\d+(?:\.\d+)?)s"/);
60
+ return m ? Math.ceil(parseFloat(m[1]) * 1000) : null;
61
+ }
62
+ /** Transient statuses worth retrying, as they appear in the marker string we get back. */
63
+ const GEMINI_RETRYABLE = /\b(429|500|502|503|504|Too Many Requests|RESOURCE_EXHAUSTED|UNAVAILABLE|overloaded|Internal Server Error|Service Unavailable)\b/i;
64
+ const GEMINI_MAX_ATTEMPTS = 3;
65
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
66
+ /**
67
+ * Public entry point: retry transient Gemini failures, then degrade to the Flash tier.
68
+ *
69
+ * Previously a single 429 killed the call outright — no retry, no fallback — which for the
70
+ * jury/council/diff_review/plan_critique judges meant the whole panel ran and billed and
71
+ * then died at synthesis. Two stages here:
72
+ *
73
+ * 1. Retry on transient statuses, honouring RetryInfo.retryDelay when Google supplies it
74
+ * and using exponential backoff when it doesn't.
75
+ * 2. Fall back Pro -> Flash. This helps when the cap is specific to the Pro PREVIEW model
76
+ * (preview models carry their own tighter quotas) but NOT when the key's whole quota
77
+ * is exhausted, since both tiers draw on it. Verified Aug 12 2026: with the key capped,
78
+ * 3.6 Flash 429s too. That limitation is why judges also need a cross-provider stage,
79
+ * which lives in utils/judge-runner.ts rather than here — a Gemini helper silently
80
+ * answering as GPT would be a surprise to every other caller.
81
+ */
30
82
  export async function callGemini(prompt, model = GEMINI_MODELS.GEMINI_3_PRO, systemPrompt, temperature = 0.7, validationContext = 'llm-orchestration', maxTokens = 18000) {
83
+ let last = "";
84
+ for (let attempt = 1; attempt <= GEMINI_MAX_ATTEMPTS; attempt++) {
85
+ last = await callGeminiAttempt(prompt, model, systemPrompt, temperature, validationContext, maxTokens);
86
+ if (!isProviderFailure(last) || !GEMINI_RETRYABLE.test(last))
87
+ break;
88
+ if (attempt === GEMINI_MAX_ATTEMPTS)
89
+ break;
90
+ const suggested = parseRetryDelayMs(last);
91
+ const delay = Math.min(suggested ?? 1000 * 2 ** (attempt - 1), 15000);
92
+ console.error(`⏳ [Gemini] ${model} transient failure (attempt ${attempt}/${GEMINI_MAX_ATTEMPTS}), retrying in ${delay}ms`);
93
+ await sleep(delay);
94
+ }
95
+ // Same-provider degrade: Pro -> Flash. Skipped when Flash was already the request.
96
+ if (isProviderFailure(last) && GEMINI_RETRYABLE.test(last) && model !== GEMINI_MODELS.FLASH) {
97
+ console.error(`🔻 [Gemini] ${model} exhausted, degrading to ${GEMINI_MODELS.FLASH}`);
98
+ const flash = await callGeminiAttempt(prompt, GEMINI_MODELS.FLASH, systemPrompt, temperature, validationContext, maxTokens);
99
+ if (!isProviderFailure(flash)) {
100
+ return `[degraded: ${model} unavailable, answered by ${GEMINI_MODELS.FLASH}]\n\n${flash}`;
101
+ }
102
+ }
103
+ return last;
104
+ }
105
+ async function callGeminiAttempt(prompt, model = GEMINI_MODELS.GEMINI_3_PRO, systemPrompt, temperature = 0.7, validationContext = 'llm-orchestration', maxTokens = 18000) {
31
106
  // Try OpenRouter gateway first if enabled
32
107
  if (isGatewayEnabled()) {
33
108
  const messages = [
@@ -118,7 +193,15 @@ export async function callGemini(prompt, model = GEMINI_MODELS.GEMINI_3_PRO, sys
118
193
  });
119
194
  clearTimeout(timeoutId);
120
195
  if (!response.ok) {
121
- throw new Error(`Gemini API error: ${response.statusText}`);
196
+ // Keep the BODY, not just statusText. Google puts the useful part there: which quota
197
+ // was hit, and a RetryInfo.retryDelay when the limit is a transient per-minute
198
+ // throttle rather than a plan/daily cap. Discarding it (as this did) turned every
199
+ // failure into an indistinguishable "Too Many Requests".
200
+ const body = await response.text().catch(() => "");
201
+ const err = new Error(`Gemini API error: ${response.statusText}${body ? ` - ${body.slice(0, 400)}` : ""}`);
202
+ err.status = response.status;
203
+ err.retryAfterMs = parseRetryDelayMs(body);
204
+ throw err;
122
205
  }
123
206
  const data = await response.json();
124
207
  // Debug logging for response structure
@@ -440,58 +523,33 @@ export const geminiJudgeTool = defineModelTool({
440
523
  return "Error: No content provided. Pass perspectives to judge in the 'perspectives' parameter.";
441
524
  }
442
525
  args.perspectives = perspectives;
443
- const modeInstructions = {
444
- synthesize: `SYNTHESIS MODE: Extract the best elements from each perspective and merge into one cohesive answer.
445
- Do NOT pick a winner. Find what is uniquely valuable in EACH perspective.
446
- The final answer must be BETTER than any single input.`,
447
- evaluate: `EVALUATION MODE: Score each perspective on these dimensions (1-10):
448
- - Accuracy: Factual correctness
449
- - Completeness: Coverage of the problem
450
- - Reasoning: Quality of logic and argumentation
451
- - Actionability: How useful/implementable the advice is
452
- - Novelty: Unique insights others missed
453
- Provide per-perspective scores and brief justification.`,
454
- rank: `RANKING MODE: Order perspectives from strongest to weakest.
455
- For each, state: rank, key strength, key weakness.
456
- Use pairwise comparison (compare each pair) to avoid position bias.`,
457
- resolve: `CONFLICT RESOLUTION MODE: Identify where perspectives disagree.
458
- For each conflict:
459
- 1. State the disagreement clearly
460
- 2. Evaluate evidence on both sides
461
- 3. Render a verdict with reasoning
462
- 4. Note confidence level (high/medium/low)`
463
- };
464
- const systemPrompt = `You are Gemini 3 Pro, acting as an expert judge and synthesizer.
526
+ const systemPrompt = `You are the presiding judge over a set of AI perspectives.
527
+ Evaluate them with intellectual rigor and fairness.
528
+
529
+ ${JUDGE_MODE_INSTRUCTIONS[args.mode || 'synthesize']}
465
530
 
466
- ROLE: Evaluate multiple AI perspectives with intellectual rigor and fairness.
531
+ ${JUDGE_METHOD}
467
532
 
468
- ${modeInstructions[args.mode || 'synthesize']}
533
+ ${JUDGE_EPISTEMIC_LIMIT}
469
534
 
470
- METHODOLOGY (based on LLM-as-a-Judge research — Gu et al. arXiv:2411.15594):
471
- 1. READ all perspectives completely before forming any opinion
472
- 2. DECOMPOSE evaluation across traits: accuracy, reasoning, completeness, novelty, actionability
473
- 3. MITIGATE BIAS: Don't favor the first, longest, or most verbose response — evaluate on substance
474
- 4. CHAIN-OF-THOUGHT: Show your reasoning step-by-step before concluding (chain_of_thought technique)
475
- 5. FIRST PRINCIPLES: Strip away assumptions, identify ground truths, rebuild from fundamentals
476
- 6. TREE OF THOUGHTS: Consider multiple synthesis paths, evaluate each, prune weak branches
477
- 7. ADVERSARIAL CHECK: For each conclusion, argue the counterpoint — does it survive scrutiny?
478
- 8. SELF-CONSISTENCY: If you arrived at this verdict 3 different ways, would you get the same answer?
479
- 9. EXTRACT before synthesizing: identify what each perspective contributes uniquely
535
+ ${JUDGE_BIAS_CONTROLS}
480
536
 
481
537
  OUTPUT STRUCTURE:
482
- ## Per-Perspective Analysis
483
- For each input, note: key contribution, strength, weakness, unique insight
538
+ 🧠 SUB-CLAIMS ───
539
+ The 2-5 claims the perspectives turn on, each tagged AGREED / CONTESTED / UNVERIFIED
484
540
 
485
- ## Consensus Points
486
- What all perspectives agree on (high confidence)
541
+ 🧠 PER-PERSPECTIVE ───
542
+ What each one uniquely contributes, and its weakest point
487
543
 
488
- ## Conflicts & Resolution
489
- Where they disagree — evidence on each side, verdict, confidence level
544
+ 🧠 RESOLUTION ───
545
+ Each CONTESTED sub-claim settled, with the reasoning that settled it and a
546
+ confidence level. Include the counter-case you tested and why it failed.
490
547
 
491
- ## Final Synthesis
492
- The unified answer combining the best elements — must be better than any single input
548
+ 🧠 VERDICT ───
549
+ The unified answer. State plainly if it is not better than the best single input.
493
550
 
494
- ${FORMAT_INSTRUCTION}`;
551
+ ${FORMAT_INSTRUCTION}
552
+ ${JUDGE_FORMAT_EXCEPTION}`;
495
553
  const userPrompt = args.question
496
554
  ? `QUESTION: ${args.question}\n\nPERSPECTIVES TO JUDGE:\n${args.perspectives}`
497
555
  : args.perspectives;
@@ -356,7 +356,7 @@ export const grokSearchTool = {
356
356
  const messages = [
357
357
  {
358
358
  role: "system",
359
- content: `You are Grok 4.5 with live search. Search for: "${query}".
359
+ content: `You are Grok 4.6 with live search. Search for: "${query}".
360
360
  ${recencyPrompt}
361
361
  Provide concise, factual results with sources.
362
362
  Limit search to ${max_search_results} sources for cost control.
@@ -367,13 +367,15 @@ ${FORMAT_INSTRUCTION}`
367
367
  content: `Search for: ${query}`
368
368
  }
369
369
  ];
370
- log?.info(`Grok Search: ${max_search_results} sources, recency: ${recency} (using grok-4.5 flagship)`);
370
+ log?.info(`Grok Search: ${max_search_results} sources, recency: ${recency} (using grok-4.6, verified grounded)`);
371
371
  // Extract domains from sources if specified
372
372
  const domains = sources
373
373
  ?.filter((s) => s.allowed_websites)
374
374
  ?.flatMap((s) => s.allowed_websites) || [];
375
375
  const result = await callGrokEnhanced(messages, {
376
- model: GrokModel.GROK_4_20_REASONING, // → grok-4.5 flagship (grok_search_lite is the cheap tier)
376
+ model: GrokModel.GROK_4_6, // grok-4.6: only current model that actually invokes web_search
377
+ // on /v1/responses — 4.5 answers ungrounded from training data
378
+ // (grok_search_lite is the cheap tier)
377
379
  enableLiveSearch: true,
378
380
  searchSources: max_search_results,
379
381
  searchDomains: domains,
@@ -1,10 +1,24 @@
1
1
  /**
2
2
  * Grok Search Lite — cost-optimized live web search.
3
3
  *
4
- * Same xAI live-search path as grok_search, but on grok-4-1-fast
5
- * (tool-calling optimized, 2M context, $0.20/$0.50 — ~10x cheaper than the
6
- * grok-4.5 flagship). Use for high-volume lookups, jury/council fan-outs, and
7
- * quick fact checks; use grok_search when synthesis quality matters most.
4
+ * Same xAI live-search path as grok_search, but on grok-4.3 (1M context,
5
+ * $1.25/$2.50) instead of the grok-4.5 flagship ($2/$6) — roughly 1.6x cheaper
6
+ * on input and 2.4x on output. Use for high-volume lookups, jury/council
7
+ * fan-outs, and quick fact checks; use grok_search when synthesis quality
8
+ * matters most.
9
+ *
10
+ * WAS grok-4-1-fast-non-reasoning ($0.20/$0.50, advertised as "10x cheaper").
11
+ * That id was retired by xAI, and the retirement is INVISIBLE at runtime: a
12
+ * request for it returns HTTP 200 and xAI silently serves grok-4.3, disclosing
13
+ * the swap only in the response body's `model` field. Verified Aug 12, 2026:
14
+ *
15
+ * requested grok-4-1-fast-non-reasoning -> HTTP 200, served "grok-4.3"
16
+ * requested grok-4.5 -> HTTP 200, served "grok-4.5" (control)
17
+ *
18
+ * So no error was ever raised, no fallback ever fired, and this tool billed at
19
+ * grok-4.3 rates while advertising grok-4-1-fast rates. Pointing at grok-4.3
20
+ * explicitly changes nothing about what runs — it just stops the tool lying
21
+ * about its own cost.
8
22
  */
9
23
  import { z } from "zod";
10
24
  import { callGrokEnhanced, GrokModel } from "./grok-enhanced.js";
@@ -23,7 +37,7 @@ ${FORMAT_INSTRUCTION}`;
23
37
  }
24
38
  export const grokSearchLiteTool = defineModelTool({
25
39
  name: "grok_search_lite",
26
- description: "Cheap web search (grok-4-1-fast, ~10x cheaper than grok_search). Put your QUERY in the 'query' parameter.",
40
+ description: "Cheap web search (grok-4.3, ~2x cheaper than grok_search). Put your QUERY in the 'query' parameter.",
27
41
  parameters: z.object({
28
42
  query: z.string(),
29
43
  sources: z
@@ -48,13 +62,13 @@ export const grokSearchLiteTool = defineModelTool({
48
62
  content: `Search for: ${query}`,
49
63
  },
50
64
  ];
51
- log?.info(`Grok Search Lite: ${max_search_results} sources, recency: ${recency} (using grok-4-1-fast, $0.20/$0.50)`);
65
+ log?.info(`Grok Search Lite: ${max_search_results} sources, recency: ${recency} (using grok-4.3, $1.25/$2.50)`);
52
66
  // Extract domains from sources if specified
53
67
  const domains = sources
54
68
  ?.filter((s) => s.allowed_websites)
55
69
  ?.flatMap((s) => s.allowed_websites) || [];
56
70
  const result = await callGrokEnhanced(messages, {
57
- model: GrokModel.GROK_4_1_FAST, // Tool-calling optimized cheap tier — the whole point of this tool
71
+ model: GrokModel.GROK_4_3, // Cheapest surviving general tier (see header note on the retired 4-1-fast id)
58
72
  enableLiveSearch: true,
59
73
  searchSources: max_search_results,
60
74
  searchDomains: domains,
@@ -23,11 +23,16 @@ config({ path: path.resolve(__dirname, '../../../.env') });
23
23
  // Grok API configuration
24
24
  const GROK_API_KEY = getGrokApiKey();
25
25
  const GROK_API_URL = "https://api.x.ai/v1/chat/completions";
26
- // Available Grok models - Updated 2026-07-11 with Grok 4.5 (Jul 8, 2026 flagship)
26
+ // Available Grok models - Updated 2026-08-14 with Grok 4.6 (verified against /v1/models)
27
27
  export var GrokModel;
28
28
  (function (GrokModel) {
29
- // Grok 4.5 (Jul 8, 2026) - CURRENT FLAGSHIP ("Opus-class")
29
+ // Grok 4.6 (Aug 2026) - CURRENT LATEST — verified against /v1/models on 2026-08-14.
30
+ // 500K ctx, $2/$6 (same as 4.5), cached input $0.50/M, no `-latest` alias yet.
31
+ // The only current model that actually invokes web_search on the Agent Tools API.
32
+ GrokModel["GROK_4_6"] = "grok-4.6";
33
+ // Grok 4.5 (Jul 8, 2026) - previous flagship ("Opus-class")
30
34
  // 500K ctx (smaller than 4.3's 1M), $2/$6, configurable reasoning effort.
35
+ // WARNING: does NOT invoke web_search on /v1/responses — do not pin search paths to it.
31
36
  GrokModel["GROK_4_5"] = "grok-4.5";
32
37
  // Grok 4.3 (Apr 30, 2026) - previous flagship, kept as FALLBACK
33
38
  GrokModel["GROK_4_3"] = "grok-4.3";
@@ -180,7 +185,7 @@ export const grokReasonTool = defineModelTool({
180
185
  {
181
186
  role: "system",
182
187
  content: `You are Grok 4.5, an expert at logical reasoning and problem-solving.
183
- ${approachPrompts[approach]}.
188
+ ${approachPrompts[approach] || approachPrompts["first-principles"]}.
184
189
  ${context ? `Context: ${context}` : ''}
185
190
  ${FORMAT_INSTRUCTION}`
186
191
  },
@@ -230,7 +235,7 @@ export const grokCodeTool = defineModelTool({
230
235
  {
231
236
  role: "system",
232
237
  content: `You are Grok 4.5, expert programmer and code analyst.
233
- Task: ${taskPrompts[task]}
238
+ Task: ${taskPrompts[task] || taskPrompts.analyze}
234
239
  ${language ? `Language: ${language}` : ''}
235
240
  ${requirements ? `Requirements: ${requirements}` : ''}
236
241
  ${FORMAT_INSTRUCTION}`
@@ -11,9 +11,10 @@ import { callGrok } from "./grok-tools.js";
11
11
  import { callOpenAI } from "./openai-tools.js";
12
12
  import { callOpenRouter, OpenRouterModel } from "./openrouter-tools.js";
13
13
  import { callLocal } from "./local-tools.js";
14
- import { callGemini } from "./gemini-tools.js";
15
- import { GEMINI_MODELS } from "../config/model-constants.js";
16
14
  import { FORMAT_INSTRUCTION } from "../utils/format-constants.js";
15
+ import { isProviderFailure } from "../utils/provider-failure.js";
16
+ import { runJudge, judgeAttribution } from "../utils/judge-runner.js";
17
+ import { JUDGE_MODE_INSTRUCTIONS, JUDGE_METHOD, JUDGE_EPISTEMIC_LIMIT, JUDGE_BIAS_CONTROLS, JUDGE_FORMAT_EXCEPTION, } from "../utils/judge-constants.js";
17
18
  import { stripFormatting } from "../utils/format-stripper.js";
18
19
  import { withHeartbeat } from "../utils/streaming-helper.js";
19
20
  // Per-juror output budget. Reasoning-heavy jurors (GLM, Kimi, DeepSeek,
@@ -21,6 +22,9 @@ import { withHeartbeat } from "../utils/streaming-helper.js";
21
22
  // BEFORE the visible answer, so a tight cap truncates the verdict mid-sentence
22
23
  // (finish_reason: "length"). 8000 leaves room for reasoning + a complete take.
23
24
  const JUROR_MAX_TOKENS = 8000;
25
+ // Re-exported for back-compat; the detector now lives in utils/provider-failure.ts so the
26
+ // judge runner can share it without importing this module (which would be a cycle).
27
+ export { isProviderFailure };
24
28
  // Available juror models and how to call them
25
29
  export const JUROR_REGISTRY = {
26
30
  grok: {
@@ -192,44 +196,81 @@ export const juryTool = defineModelTool({
192
196
  // MCP client keeps the connection alive through long parallel juror calls.
193
197
  }, reportFn, 10000);
194
198
  // Phase 2: Format perspectives for the judge
195
- const liveJurors = jurorResults.filter((j) => typeof j.result === "string" && j.result.length > 0);
196
- const droppedCount = jurorResults.length - liveJurors.length;
197
- if (droppedCount > 0) {
198
- console.error(`⚠️ ${droppedCount} juror(s) dropped (offline/error) — synthesizing from ${liveJurors.length}`);
199
+ const liveJurors = jurorResults.filter((j) => typeof j.result === "string" &&
200
+ j.result.length > 0 &&
201
+ !isProviderFailure(j.result));
202
+ const dropped = jurorResults.filter((j) => !liveJurors.includes(j));
203
+ if (dropped.length > 0) {
204
+ console.error(`⚠️ ${dropped.length} juror(s) dropped (offline/error) — synthesizing from ${liveJurors.length}`);
199
205
  }
200
- const perspectives = liveJurors
201
- .map(j => `--- ${j.label} ---\n${j.result}`)
206
+ if (liveJurors.length === 0) {
207
+ return `[Jury failed: all ${jurorResults.length} juror(s) errored or timed out. Run \`doctor\` to check provider keys and quota.]`;
208
+ }
209
+ // Anonymize before synthesis. The judge is asked to weigh reasoning, so it must not
210
+ // see which lab produced which perspective — identity bias is the one bias the old
211
+ // prompt debiased against while actively inducing it. The lens (the parenthetical in
212
+ // each label) survives because it states what angle the juror was asked to take; the
213
+ // vendor names are restored only in the roster printed below.
214
+ const anonymized = liveJurors.map((j, i) => ({
215
+ tag: `JUROR ${String.fromCharCode(65 + i)}`,
216
+ lens: j.label.match(/\(([^)]+)\)/)?.[1] ?? j.label,
217
+ text: j.result,
218
+ }));
219
+ const perspectives = anonymized
220
+ .map((a) => `--- ${a.tag} (${a.lens} lens) ---\n${a.text}`)
202
221
  .join("\n\n");
203
- // Phase 3: Gemini judge synthesizes
204
- const modeInstructions = {
205
- synthesize: "SYNTHESIZE the best elements from each juror into one unified answer. Do NOT pick a winner.",
206
- evaluate: "SCORE each juror on accuracy, completeness, reasoning, actionability, novelty (1-10).",
207
- rank: "RANK jurors from strongest to weakest. Use pairwise comparison to avoid position bias.",
208
- resolve: "IDENTIFY conflicts between jurors. For each, state the disagreement, evaluate evidence, render verdict."
209
- };
222
+ // Phase 3: judge synthesizes. Counts below MUST come from `anonymized`, not
223
+ // `validJurors` — the judge can only reason about perspectives it was actually shown,
224
+ // and telling it "4 jurors" while showing 2 miscalibrates every consensus claim.
225
+ const droppedNote = dropped.length > 0
226
+ ? `\nNOTE: ${dropped.length} of ${jurorResults.length} jurors failed (provider error or quota)
227
+ and are ABSENT below. Do not infer agreement from jurors you cannot see — calibrate
228
+ confidence to the ${anonymized.length} present, and say the panel was short-handed.\n`
229
+ : "";
210
230
  const judgePrompt = `JURY VERDICT REQUEST
211
231
 
212
232
  QUESTION: ${args.question}
213
233
 
214
- ${modeInstructions[args.mode || 'synthesize']}
234
+ ${JUDGE_MODE_INSTRUCTIONS[args.mode || 'synthesize']}
215
235
 
216
- JUROR PERSPECTIVES (${validJurors.length} jurors):
236
+ JUROR PERSPECTIVES (${anonymized.length}):
217
237
 
218
238
  ${perspectives}
219
239
 
220
- Apply chain-of-thought reasoning. Show your analysis before concluding. The final synthesis must be BETTER than any single juror.`;
221
- const judgeResult = await withHeartbeat(() => callGemini(judgePrompt, GEMINI_MODELS.GEMINI_3_PRO, `You are Gemini 3 Pro, acting as the presiding judge of an AI jury.
222
- Evaluate ${validJurors.length} juror perspectives with intellectual rigor.
223
- Decompose evaluation across traits: accuracy, reasoning, completeness, novelty.
224
- Mitigate bias: don't favor the first, longest, or most verbose response.
225
- Extract what each juror contributes uniquely before synthesizing.
226
- ${FORMAT_INSTRUCTION}`, 0.3, 'llm-orchestration'), reportFn);
227
- // Format output
228
- const jurorSummary = validJurors.map(j => `- ${JUROR_REGISTRY[j].label}`).join("\n");
229
- return stripFormatting(`JURY PANEL
240
+ ${JUDGE_METHOD}
241
+
242
+ ${JUDGE_EPISTEMIC_LIMIT}
243
+ ${droppedNote}`;
244
+ const judgeSystemPrompt = `You are the presiding judge of an AI jury, evaluating ${anonymized.length} anonymized
245
+ juror perspectives. Extract what each contributes uniquely before synthesizing.
246
+ ${JUDGE_BIAS_CONTROLS}
247
+ ${FORMAT_INSTRUCTION}
248
+ ${JUDGE_FORMAT_EXCEPTION}`;
249
+ const judged = (await withHeartbeat(() => runJudge(judgePrompt, judgeSystemPrompt, 0.3), reportFn));
250
+ // Format output. The judge saw anonymous letters; the USER gets the mapping back,
251
+ // plus an honest account of who never made it to the panel.
252
+ const jurorSummary = [
253
+ ...liveJurors.map((j, i) => `- ${String.fromCharCode(65 + i)}: ${j.label}`),
254
+ ...dropped.map(j => `- ${j.label} — DROPPED (provider error or quota)`),
255
+ ].join("\n");
256
+ // Every judge down. The panel already ran and was already billed, so hand back the raw
257
+ // perspectives rather than an error string — unsynthesized jurors are still the bulk of
258
+ // the value, and throwing them away is the one outcome with no upside.
259
+ if (judged.text === null) {
260
+ return stripFormatting(`JURY PANEL (${liveJurors.length}/${jurorResults.length} responded)
261
+ ${jurorSummary}
262
+
263
+ ⚠️ NO VERDICT — every judge was unavailable (Gemini and OpenAI both failed; usually
264
+ quota). The juror perspectives below are UNSYNTHESIZED and were not cross-checked
265
+ against each other. Run \`doctor\` to see provider status.
266
+
267
+ RAW PERSPECTIVES
268
+ ${perspectives}`);
269
+ }
270
+ return stripFormatting(`JURY PANEL (${liveJurors.length}/${jurorResults.length} responded)
230
271
  ${jurorSummary}
231
272
 
232
273
  VERDICT
233
- ${judgeResult}`);
274
+ ${judgeAttribution(judged)}${judged.text}`);
234
275
  }
235
276
  });
@@ -11,7 +11,7 @@ import * as path from 'path';
11
11
  import { fileURLToPath } from 'url';
12
12
  import { validateToolInput } from "../utils/input-validator.js";
13
13
  import { tryOpenRouterGateway, isGatewayEnabled } from "../utils/openrouter-gateway.js";
14
- import { OPENAI_MODELS } from "../config/model-constants.js";
14
+ import { OPENAI_MODELS, OPENAI_REASONING } from "../config/model-constants.js";
15
15
  import { FORMAT_INSTRUCTION } from "../utils/format-constants.js";
16
16
  import { stripFormatting } from "../utils/format-stripper.js";
17
17
  import { withHeartbeat } from "../utils/streaming-helper.js";
@@ -214,8 +214,11 @@ reasoningEffort = "low", requireConfirmation = false, skipValidation = false) {
214
214
  };
215
215
  }
216
216
  console.error(`🔍 TRACE: Using ${isGPT5 ? '/v1/responses' : '/v1/chat/completions'} endpoint for ${currentModel}`);
217
- // GPT-5.4 with high reasoning effort can take 2+ minutes
218
- const timeoutMs = (reasoningEffort === 'high' || reasoningEffort === 'xhigh') ? 180000 : 90000;
217
+ // High reasoning effort can take 2+ minutes; "max" is the slowest tier of all, so it
218
+ // gets the long timeout too — omitting it here would abort max-effort calls at 90s.
219
+ const timeoutMs = (reasoningEffort === 'high' || reasoningEffort === 'xhigh' || reasoningEffort === 'max')
220
+ ? 180000
221
+ : 90000;
219
222
  const controller = new AbortController();
220
223
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
221
224
  const response = await fetch(endpoint, {
@@ -340,7 +343,7 @@ export const gpt5ReasonTool = defineModelTool({
340
343
  const messages = [
341
344
  {
342
345
  role: "system",
343
- content: `You are GPT-5, the most advanced reasoning model.\n${modePrompts[args.mode || 'analytical']}.\nProvide step-by-step reasoning with clear explanations.\n${args.context ? `Context: ${args.context}` : ''}\n${FORMAT_INSTRUCTION}`
346
+ content: `You are GPT-5, the most advanced reasoning model.\n${modePrompts[args.mode] || modePrompts.analytical}.\nProvide step-by-step reasoning with clear explanations.\n${args.context ? `Context: ${args.context}` : ''}\n${FORMAT_INSTRUCTION}`
344
347
  },
345
348
  {
346
349
  role: "user",
@@ -375,7 +378,7 @@ export const gpt5MiniReasonTool = defineModelTool({
375
378
  const messages = [
376
379
  {
377
380
  role: "system",
378
- content: `You are GPT-5-mini, optimized for efficient reasoning.\n${modePrompts[args.mode || 'analytical']}.\nProvide clear, step-by-step reasoning.\n${args.context ? `Context: ${args.context}` : ''}\n${FORMAT_INSTRUCTION}`
381
+ content: `You are GPT-5-mini, optimized for efficient reasoning.\n${modePrompts[args.mode] || modePrompts.analytical}.\nProvide clear, step-by-step reasoning.\n${args.context ? `Context: ${args.context}` : ''}\n${FORMAT_INSTRUCTION}`
379
382
  },
380
383
  {
381
384
  role: "user",
@@ -412,7 +415,7 @@ export const openaiGpt5ReasonTool = defineModelTool({
412
415
  {
413
416
  role: "system",
414
417
  content: `You are an expert reasoner using advanced analytical capabilities.
415
- ${modePrompts[args.mode || 'analytical']}.
418
+ ${modePrompts[args.mode] || modePrompts.analytical}.
416
419
  Provide step-by-step reasoning with clear explanations.
417
420
  ${args.context ? `Context: ${args.context}` : ''}
418
421
  ${FORMAT_INSTRUCTION}`
@@ -422,9 +425,13 @@ ${FORMAT_INSTRUCTION}`
422
425
  content: args.query + fileContext
423
426
  }
424
427
  ];
425
- // Use heartbeat to prevent MCP timeout during reasoning
428
+ // Use heartbeat to prevent MCP timeout during reasoning.
429
+ // Effort is xhigh, not high: this is the dedicated deep-reasoning tool and sol supports
430
+ // none|low|medium|high|xhigh|max. "max" is deliberately NOT the default here — OpenAI
431
+ // recommends reserving it for the hardest quality-first work and comparing it against
432
+ // xhigh first, and it costs latency on every call. Both land in the 180s timeout branch.
426
433
  const reportFn = reportProgress ?? (async () => { });
427
- return await withHeartbeat(() => callOpenAI(messages, OPENAI_MODELS.DEFAULT, 0.7, 8000, "high"), reportFn);
434
+ return await withHeartbeat(() => callOpenAI(messages, OPENAI_MODELS.DEFAULT, 0.7, 8000, OPENAI_REASONING.XHIGH), reportFn);
428
435
  }
429
436
  });
430
437
  /**
@@ -442,9 +449,9 @@ export const openAIBrainstormTool = defineModelTool({
442
449
  model: z.enum(["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"])
443
450
  .optional()
444
451
  .describe("Model to use - gpt-5.6-sol (default, flagship), gpt-5.6-terra (balanced), gpt-5.6-luna (fast/cheap)"),
445
- reasoning_effort: z.enum(["none", "low", "medium", "high", "xhigh"])
452
+ reasoning_effort: z.enum(["none", "low", "medium", "high", "xhigh", "max"])
446
453
  .optional()
447
- .describe("Reasoning effort level - must be one of: none, low, medium, high, xhigh"),
454
+ .describe("Reasoning effort level - must be one of: none, low, medium, high, xhigh, max"),
448
455
  max_tokens: z.number().optional().describe("Maximum tokens for response")
449
456
  }),
450
457
  execute: async (args, options = {}) => {
@@ -575,8 +582,8 @@ export const openaiExplainTool = defineModelTool({
575
582
  {
576
583
  role: "system",
577
584
  content: `You are an expert educator.
578
- ${levelPrompts[args.level || 'intermediate']}.
579
- ${stylePrompts[args.style || 'simple']}.
585
+ ${levelPrompts[args.level] || levelPrompts.intermediate}.
586
+ ${stylePrompts[args.style] || stylePrompts.simple}.
580
587
  Make the explanation clear, engaging, and memorable.
581
588
  ${FORMAT_INSTRUCTION}`
582
589
  },
@@ -612,7 +619,13 @@ async function callOpenAIWithSearch(query, options = {}) {
612
619
  webSearchTool.user_location = userLocation;
613
620
  }
614
621
  const requestBody = {
615
- model: OPENAI_MODELS.DEFAULT, // gpt-5.4
622
+ // Web search bills a FLAT $10/1k calls regardless of model, so the model is the only
623
+ // cost lever here — and this was set to the $5/$30 flagship for what is mostly grounded
624
+ // lookup. Terra supports web_search identically (verified against OpenAI model docs,
625
+ // Aug 12 2026) at $2/$12, and keeps the long-context recall that luna trades away —
626
+ // which matters because search results are large inputs. Effort stays at the API
627
+ // default (medium) so multi-step queries still get agentic search.
628
+ model: OPENAI_MODELS.TERRA,
616
629
  input: [
617
630
  {
618
631
  role: "system",
@@ -584,7 +584,7 @@ export const kimiThinkingTool = defineModelTool({
584
584
  {
585
585
  role: "system",
586
586
  content: `You are Kimi K3, an expert reasoning model. Be concise and direct.
587
- ${approachPrompts[args.approach || 'step-by-step']}.
587
+ ${approachPrompts[args.approach] || approachPrompts['step-by-step']}.
588
588
  Use ${args.maxSteps} reasoning steps max. ${args.context ? `Context: ${args.context}` : ''}
589
589
  ${FORMAT_INSTRUCTION}`
590
590
  },
@@ -902,7 +902,7 @@ export const qwenReasonTool = defineModelTool({
902
902
  {
903
903
  role: "system",
904
904
  content: `You are Qwen3.8-Max, Alibaba's flagship reasoning model.
905
- ${approachPrompts[args.approach || 'mathematical']}.
905
+ ${approachPrompts[args.approach] || approachPrompts['mathematical']}.
906
906
  Show your complete reasoning process.
907
907
  ${args.context ? `Context: ${args.context}` : ''}
908
908
  ${FORMAT_INSTRUCTION}`
@@ -1094,7 +1094,7 @@ export const deepseekReasonTool = {
1094
1094
  {
1095
1095
  role: "system",
1096
1096
  content: `You are DeepSeek V4 Pro, an open-weight frontier reasoning model (MLA/GRPO) with elite math and chained-reasoning ability.
1097
- ${approachPrompts[args.approach || 'analytical']}.
1097
+ ${approachPrompts[args.approach] || approachPrompts['analytical']}.
1098
1098
  Show your reasoning chain, then state a clear conclusion. Flag any assumptions and uncertainty explicitly.
1099
1099
  ${args.context ? `Context: ${args.context}` : ''}
1100
1100
  ${FORMAT_INSTRUCTION}`
@@ -1197,7 +1197,7 @@ export const glmReasonTool = {
1197
1197
  {
1198
1198
  role: "system",
1199
1199
  content: `You are Zhipu GLM-5.2, a frontier open-weights agentic model with a 1M-token context, strong at long-horizon coding, tool-use planning and software-engineering reasoning.
1200
- ${approachPrompts[args.approach || 'agentic']}.
1200
+ ${approachPrompts[args.approach] || approachPrompts['agentic']}.
1201
1201
  State your plan, reason through it, then give a decisive conclusion. Flag assumptions and risks explicitly.
1202
1202
  ${args.context ? `Context: ${args.context}` : ''}
1203
1203
  ${FORMAT_INSTRUCTION}`
@@ -1241,7 +1241,7 @@ export const stepfunReasonTool = {
1241
1241
  {
1242
1242
  role: "system",
1243
1243
  content: `You are StepFun Step 3.7 Flash, an efficient reasoning model with strong AIME/SWE-Verified results.
1244
- ${approachPrompts[args.approach || 'analytical']}.
1244
+ ${approachPrompts[args.approach] || approachPrompts['analytical']}.
1245
1245
  Be efficient: reason tightly, then give a clear conclusion. Flag assumptions explicitly.
1246
1246
  ${args.context ? `Context: ${args.context}` : ''}
1247
1247
  ${FORMAT_INSTRUCTION}`
@@ -1283,7 +1283,7 @@ export const ernieReasonTool = {
1283
1283
  {
1284
1284
  role: "system",
1285
1285
  content: `You are Baidu ERNIE 4.5 VL, a 424B-parameter MoE with broad knowledge and strong human-preference alignment.
1286
- ${approachPrompts[args.approach || 'analytical']}.
1286
+ ${approachPrompts[args.approach] || approachPrompts['analytical']}.
1287
1287
  Give a well-rounded, decisive answer. Flag assumptions and uncertainty.
1288
1288
  ${args.context ? `Context: ${args.context}` : ''}
1289
1289
  ${FORMAT_INSTRUCTION}`