nexus-agents 4.32.3 → 4.32.4
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.
- package/dist/chunk-3NJFOC3L.js +7 -0
- package/dist/{chunk-GJ5XPWVR.js → chunk-HIXWQWNA.js} +3 -3
- package/dist/{chunk-FYXHSU6S.js → chunk-MUTREHSB.js} +1 -1
- package/dist/{chunk-FYXHSU6S.js.map → chunk-MUTREHSB.js.map} +1 -1
- package/dist/{chunk-VWLFVDVW.js → chunk-O2RQZFOJ.js} +2 -2
- package/dist/{chunk-2YOYMLRN.js → chunk-OFEXOT56.js} +8 -8
- package/dist/{chunk-UFJNPPWT.js → chunk-SYVBAREH.js} +2 -2
- package/dist/{chunk-J4NQLEBM.js → chunk-VDA4B6NO.js} +3 -3
- package/dist/cli.js +8 -8
- package/dist/cli.js.map +1 -1
- package/dist/{consensus-vote-IGRDOZ4K.js → consensus-vote-YMHPKKZV.js} +4 -4
- package/dist/{expert-bridge-FX2IHQPZ.js → expert-bridge-JHRGVFMI.js} +2 -2
- package/dist/{improvement-review-5SERWMDP.js → improvement-review-BTPKYYYU.js} +4 -4
- package/dist/index.js +8 -8
- package/dist/{setup-data-dir-HUAM3YOS.js → setup-data-dir-JQC5RC3M.js} +3 -3
- package/package.json +1 -1
- package/dist/chunk-XHNXEV3M.js +0 -7
- /package/dist/{chunk-XHNXEV3M.js.map → chunk-3NJFOC3L.js.map} +0 -0
- /package/dist/{chunk-GJ5XPWVR.js.map → chunk-HIXWQWNA.js.map} +0 -0
- /package/dist/{chunk-VWLFVDVW.js.map → chunk-O2RQZFOJ.js.map} +0 -0
- /package/dist/{chunk-2YOYMLRN.js.map → chunk-OFEXOT56.js.map} +0 -0
- /package/dist/{chunk-UFJNPPWT.js.map → chunk-SYVBAREH.js.map} +0 -0
- /package/dist/{chunk-J4NQLEBM.js.map → chunk-VDA4B6NO.js.map} +0 -0
- /package/dist/{consensus-vote-IGRDOZ4K.js.map → consensus-vote-YMHPKKZV.js.map} +0 -0
- /package/dist/{expert-bridge-FX2IHQPZ.js.map → expert-bridge-JHRGVFMI.js.map} +0 -0
- /package/dist/{improvement-review-5SERWMDP.js.map → improvement-review-BTPKYYYU.js.map} +0 -0
- /package/dist/{setup-data-dir-HUAM3YOS.js.map → setup-data-dir-JQC5RC3M.js.map} +0 -0
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-OQB3XC5O.js";
|
|
7
7
|
import {
|
|
8
8
|
VERSION
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-3NJFOC3L.js";
|
|
10
10
|
import {
|
|
11
11
|
capitalize
|
|
12
12
|
} from "./chunk-6T3EPABN.js";
|
|
@@ -1201,7 +1201,7 @@ async function runDoctorFix(result) {
|
|
|
1201
1201
|
writeLine2("\u2500".repeat(40));
|
|
1202
1202
|
let fixCount = 0;
|
|
1203
1203
|
if (!result.dataDirectory.rootExists || result.dataDirectory.subdirectories.some((d) => !d.exists || !d.writable)) {
|
|
1204
|
-
const { initDataDirectories: initDataDirectories2, describeDataDirFix: describeDataDirFix2 } = await import("./setup-data-dir-
|
|
1204
|
+
const { initDataDirectories: initDataDirectories2, describeDataDirFix: describeDataDirFix2 } = await import("./setup-data-dir-JQC5RC3M.js");
|
|
1205
1205
|
const outcome = describeDataDirFix2(initDataDirectories2());
|
|
1206
1206
|
writeLine2(outcome.line);
|
|
1207
1207
|
if (outcome.counted) fixCount++;
|
|
@@ -1303,4 +1303,4 @@ export {
|
|
|
1303
1303
|
startStdioServer,
|
|
1304
1304
|
closeServer
|
|
1305
1305
|
};
|
|
1306
|
-
//# sourceMappingURL=chunk-
|
|
1306
|
+
//# sourceMappingURL=chunk-HIXWQWNA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pipeline/expert-bridge.ts"],"sourcesContent":["/**\n * Expert Bridge — Programmatic access to the execute_expert pipeline (#1693)\n *\n * Provides a clean wrapper for calling experts with the full pipeline:\n * timeout, fallback cascade, degradation detection, heartbeat, outcome recording.\n *\n * DRY: reuses createBuiltInExpert + CompositeRouter instead of reimplementing.\n *\n * @module pipeline/expert-bridge\n */\n\nimport { createLogger, getTimeProvider } from '../core/index.js';\nimport type { BuiltInExpertType } from '../agents/experts/expert-config.js';\nimport { isRateLimitText } from '../adapters/rate-limit-detector.js';\nimport { resolveCliSlot } from '../config/model-availability.js';\nimport type { CliNameLiteral } from '../config/model-capabilities-types.js';\n\n/**\n * Resolves a CLI slot from the model string a (CLI or API) adapter returned.\n * Known models resolve to their exact slot; **unknown** models — new releases\n * or API/openrouter models not in the curated registry — fall back to the\n * vendor-derived slot (#3317 / #3293) so the outcome is recorded against a real\n * slot instead of being dropped with an undefined cli (the api-mode gap).\n * Returns undefined only when no model is present (the bridge failed before\n * dispatch — no execution to attribute).\n */\nfunction resolveCliFromModelString(model: string | undefined): CliNameLiteral | undefined {\n return resolveCliSlot(model);\n}\n\nconst logger = createLogger({ component: 'expert-bridge' });\n\n/** Base delay for rate limit retry backoff (ms). Scales linearly: 3s, 6s, 9s. */\nconst RATE_LIMIT_BASE_DELAY_MS = 3000;\n\n/** Result of an expert execution. */\nexport interface ExpertBridgeResult {\n readonly success: boolean;\n readonly text: string;\n readonly expertType: BuiltInExpertType;\n readonly durationMs: number;\n readonly error?: string;\n /**\n * CLI that actually executed the task, resolved from the underlying\n * `CliResponse.model` via `getCliForModelId`. Undefined when the bridge\n * failed before dispatch (no adapters / circuit-open / rate-limit cap).\n * Callers writing to OutcomeStore should use this rather than hardcoding\n * a cli — see #2823 (#1154 regression).\n */\n readonly cli?: CliNameLiteral;\n /**\n * Total tokens (input + output) the underlying CLI/adapter reported for this\n * call, when available (#3396). Best-effort: `CliResponse.usage` is optional\n * — CLI-subprocess paths whose `extractUsage` returns null leave this\n * undefined. Consumers (budget enforcement #3395, model.called attribution\n * #3387, routing-experience metrics) must tolerate `undefined`.\n */\n readonly tokensUsed?: number;\n /**\n * Concrete model id the underlying adapter reported (`CliResponse.model`),\n * when present (#3387). Distinct from {@link cli} (the slot): one CLI can run\n * several models. Undefined when the adapter didn't report a model or the\n * bridge failed before dispatch. Required to emit a `model.called` event.\n */\n readonly model?: string;\n /**\n * Input/output token split from the adapter's `CliResponse.usage` (#3387),\n * when reported. Best-effort like {@link tokensUsed}; both undefined together\n * when no usage was available. `tokensIn + tokensOut` reconciles with\n * `tokensUsed` (single source of truth — both derive from the same record).\n */\n readonly tokensIn?: number;\n readonly tokensOut?: number;\n}\n\n/**\n * Execute an expert task with the full nexus-agents expert pipeline.\n *\n * Creates a built-in expert, executes via CompositeRouter (for intelligent\n * CLI routing), and records outcomes. Falls back gracefully on failure.\n *\n * @param expertType - Built-in expert type (code, architecture, security, qa, etc.)\n * @param prompt - Task prompt for the expert\n * @returns Expert result with text output\n */\n/** Minimal router interface for the bridge. */\ninterface RouterLike {\n executeTask(task: { content: string; options?: Record<string, unknown> | undefined }): Promise<{\n ok: boolean;\n value: {\n text: string;\n cli?: CliNameLiteral;\n tokensUsed?: number;\n model?: string;\n tokensIn?: number;\n tokensOut?: number;\n };\n error: { message: string };\n }>;\n}\n\n// Cached router — lazily initialized, reused across calls within a session\nlet cachedRouter: RouterLike | null = null;\n\n// Cached MCP config — generated once, reused across expert calls (#1708)\nlet cachedMcpConfigPath: string | null = null;\n// Cached cleanup for the cached config's tempdir (closes #2946). Previously\n// the cleanup returned by `generateMcpConfig` was thrown away, so\n// `/tmp/nexus-mcp-XXXXXX/` accumulated one entry per MCP server lifetime.\n// Stored here + invoked by `shutdownExpertBridge()` from the server's\n// graceful-shutdown path.\nlet cachedMcpConfigCleanup: (() => Promise<void>) | null = null;\n// Coalesces concurrent init under voter fan-out (closes #2969). consensus_vote\n// fans out N=7 callers on cold start; without this each one ran the full init\n// including a mkdtemp() that the loser N-1 instances never cleaned up.\nlet mcpConfigInitPromise: Promise<string | null> | null = null;\n\n/** Get or create cached MCP config path for expert CLI sessions (#1708). */\nasync function getMcpConfigPath(): Promise<string | null> {\n if (cachedMcpConfigPath !== null) return cachedMcpConfigPath;\n mcpConfigInitPromise ??= (async (): Promise<string | null> => {\n try {\n const { generateMcpConfig } = await import('../cli-adapters/child-mcp-config.js');\n const config = await generateMcpConfig();\n cachedMcpConfigPath = config.configPath;\n cachedMcpConfigCleanup = config.cleanup;\n return cachedMcpConfigPath;\n } catch {\n mcpConfigInitPromise = null; // allow retry on next call\n return null; // MCP config not available — experts run without tools\n }\n })();\n return mcpConfigInitPromise;\n}\n\n/**\n * Removes the cached MCP-config tempdir (closes #2946). Invoke from the\n * server's graceful-shutdown path so stale nexus-mcp-* tempdirs (under\n * the OS tmpdir, see child-mcp-config.ts) don't accumulate across daemon\n * restarts. Idempotent; safe to call multiple times. Never throws —\n * cleanup failures are logged and swallowed.\n */\nexport async function shutdownExpertBridge(): Promise<void> {\n const cleanup = cachedMcpConfigCleanup;\n if (cleanup === null) return;\n cachedMcpConfigCleanup = null;\n cachedMcpConfigPath = null;\n mcpConfigInitPromise = null;\n try {\n await cleanup();\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n logger.debug('Expert-bridge MCP-config cleanup failed', { error: msg });\n }\n}\n\n/** Cached circuit breaker for health monitoring (#1766). */\nlet cachedCircuitBreaker: {\n getHealthStatus(): {\n systemHealthy: boolean;\n healthyCount: number;\n clis: ReadonlyArray<{ name: string; healthy: boolean }>;\n };\n} | null = null;\n\n/**\n * Adapt a CompositeRouter to the narrower RouterLike interface used by this\n * bridge. Previously did `as unknown as RouterLike` which hid any structural\n * mismatch between CompositeRouter's `Result<CliResponse, CliError>` and\n * RouterLike's flat `{ ok, value: { text }, error: { message } }` shape.\n * If CliResponse renames `.text` → `.output` (or similar), this adapter\n * breaks at compile time instead of silently returning wrong data (#1921).\n */\n/**\n * Total tokens from a best-effort `CliResponse.usage` record (#3396). Prefers\n * the reported `totalTokens`; falls back to input+output; returns undefined\n * when no usage was reported (so callers can distinguish \"0 tokens\" — which\n * never happens for a real call — from \"unknown\").\n */\nexport function totalTokensFromUsage(\n usage: { totalTokens?: number; inputTokens?: number; outputTokens?: number } | undefined\n): number | undefined {\n if (usage === undefined) return undefined;\n if (typeof usage.totalTokens === 'number') return usage.totalTokens;\n const total = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);\n return total > 0 ? total : undefined;\n}\n\n/**\n * Per-direction token split from a best-effort `CliResponse.usage` record\n * (#3387). Unlike {@link totalTokensFromUsage} this keeps `tokensIn`/`tokensOut`\n * separate — the granularity `ModelCalledEvent` requires for attribution.\n * Returns undefined when no usage was reported or both directions are zero (no\n * real call), so callers skip emitting a noise event instead of recording\n * zeros. Reconciles with the total: `tokensIn + tokensOut === totalTokensFromUsage`.\n */\nexport function tokenSplitFromUsage(\n usage: { inputTokens?: number; outputTokens?: number; totalTokens?: number } | undefined\n): { tokensIn: number; tokensOut: number } | undefined {\n if (usage === undefined) return undefined;\n const tokensIn = usage.inputTokens ?? 0;\n const tokensOut = usage.outputTokens ?? 0;\n if (tokensIn + tokensOut === 0) return undefined;\n return { tokensIn, tokensOut };\n}\n\nfunction adaptCompositeRouter(\n compositeRouter: import('../cli-adapters/composite-router.js').ICompositeRouter\n): RouterLike {\n return {\n async executeTask(task): Promise<{\n ok: boolean;\n value: {\n text: string;\n cli?: CliNameLiteral;\n tokensUsed?: number;\n model?: string;\n tokensIn?: number;\n tokensOut?: number;\n };\n error: { message: string };\n }> {\n const cliTask: import('../cli-adapters/types.js').CliTask = {\n content: task.content,\n ...(task.options !== undefined ? { options: task.options } : {}),\n };\n const result = await compositeRouter.executeTask(cliTask);\n if (result.ok) {\n // #2823: surface which CLI actually executed so callers writing to\n // OutcomeStore don't have to hardcode 'claude' (the bug #1154 fixed\n // and that regressed into the pipeline/ tree). Derive via the\n // canonical model→cli mapping in the registry — if the underlying\n // adapter didn't set `model` or the model isn't in the registry,\n // cli stays undefined and downstream code can skip the record\n // rather than lie.\n const cli = resolveCliFromModelString(result.value.model);\n // #3396: surface token usage (best-effort) so budget enforcement,\n // attribution, and routing-experience metrics get real numbers instead\n // of zeros. `usage` is optional and `totalTokens` may be absent — fall\n // back to input+output, and leave undefined when no usage was reported.\n const tokensUsed = totalTokensFromUsage(result.value.usage);\n // #3387: also surface the concrete model + per-direction token split so\n // a meaningful `model.called` event can be emitted. Both derive from the\n // same CliResponse, so tokensIn+tokensOut reconciles with tokensUsed.\n const model = result.value.model;\n const split = tokenSplitFromUsage(result.value.usage);\n return {\n ok: true,\n value: {\n text: result.value.text,\n ...(cli !== undefined && { cli }),\n ...(tokensUsed !== undefined && { tokensUsed }),\n ...(model !== undefined && { model }),\n ...(split !== undefined && { tokensIn: split.tokensIn, tokensOut: split.tokensOut }),\n },\n error: { message: '' },\n };\n }\n return { ok: false, value: { text: '' }, error: { message: result.error.message } };\n },\n };\n}\n\n// Coalesces concurrent router init the same way mcpConfigInitPromise does\n// (closes #2969). N=7 voter fan-out previously ran createAllAdapters() N times\n// — N sets of CLI probe subprocesses, all but one discarded.\nlet routerInitPromise: Promise<RouterLike | null> | null = null;\n\n/** Get or create a cached CompositeRouter with circuit breaker monitoring. */\nasync function getRouter(): Promise<RouterLike | null> {\n if (cachedRouter !== null) return cachedRouter;\n routerInitPromise ??= (async (): Promise<RouterLike | null> => {\n const { createAllAdapters } = await import('../cli-adapters/factory.js');\n const { createCompositeRouter } = await import('../cli-adapters/composite-router.js');\n const adapters = createAllAdapters();\n if (adapters.size === 0) {\n routerInitPromise = null; // allow retry once adapters become available\n return null;\n }\n cachedRouter = adaptCompositeRouter(createCompositeRouter(adapters));\n\n // Initialize circuit breaker monitoring (#1766)\n try {\n const { createCliCircuitBreakerIntegration } =\n await import('../cli-adapters/cli-circuit-breaker.js');\n cachedCircuitBreaker = createCliCircuitBreakerIntegration([...adapters.values()]);\n } catch (error: unknown) {\n // Circuit breaker not available — continue without it. Log so we can\n // notice if initialization silently stops working (#1913 Class B).\n const msg = error instanceof Error ? error.message : String(error);\n logger.debug('Circuit breaker init failed; continuing without it', { error: msg });\n }\n\n return cachedRouter;\n })();\n return routerInitPromise;\n}\n\n/** Check CLI health before dispatch (#1766). */\nfunction checkCircuitHealth(): { healthy: boolean; message: string } {\n if (cachedCircuitBreaker === null) return { healthy: true, message: '' };\n const status = cachedCircuitBreaker.getHealthStatus();\n if (!status.systemHealthy) {\n return {\n healthy: false,\n message: `All CLI circuits open (${String(status.healthyCount)}/${String(status.clis.length)} healthy)`,\n };\n }\n return { healthy: true, message: '' };\n}\n\n/** Dispatch task to router with rate limit retry (#1802). */\nasync function dispatchWithRateLimitRetry(\n router: RouterLike,\n task: { content: string; options?: Record<string, unknown> | undefined },\n expertType: BuiltInExpertType,\n start: number\n): Promise<ExpertBridgeResult> {\n const maxAttempts = 3;\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const result = await router.executeTask(task);\n const durationMs = getTimeProvider().now() - start;\n\n if (result.ok) {\n logger.info('Expert executed successfully', {\n expertType,\n durationMs,\n cli: result.value.cli,\n });\n return {\n success: true,\n text: result.value.text,\n expertType,\n durationMs,\n ...(result.value.cli !== undefined && { cli: result.value.cli }),\n ...(result.value.tokensUsed !== undefined && { tokensUsed: result.value.tokensUsed }),\n ...(result.value.model !== undefined && { model: result.value.model }),\n ...(result.value.tokensIn !== undefined && { tokensIn: result.value.tokensIn }),\n ...(result.value.tokensOut !== undefined && { tokensOut: result.value.tokensOut }),\n };\n }\n\n const isRateLimit = isRateLimitText(result.error.message);\n if (isRateLimit && attempt < maxAttempts - 1) {\n const backoffMs = RATE_LIMIT_BASE_DELAY_MS * (attempt + 1);\n logger.warn('Expert rate limited, retrying', { expertType, attempt: attempt + 1, backoffMs });\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n continue;\n }\n\n logger.warn('Expert execution failed', { expertType, error: result.error.message });\n return { success: false, text: '', expertType, durationMs, error: result.error.message };\n }\n\n return {\n success: false,\n text: '',\n expertType,\n durationMs: getTimeProvider().now() - start,\n error: 'Max retry attempts exceeded',\n };\n}\n\nexport async function executeExpert(\n expertType: BuiltInExpertType,\n prompt: string\n): Promise<ExpertBridgeResult> {\n const start = getTimeProvider().now();\n try {\n const { BUILT_IN_EXPERTS } = await import('../agents/experts/expert-config.js');\n const config = BUILT_IN_EXPERTS[expertType];\n const fullPrompt = `${config.systemPrompt}\\n\\n${prompt}`;\n\n const router = await getRouter();\n if (router === null) {\n return {\n success: false,\n text: `[No adapters] ${prompt}`,\n expertType,\n durationMs: getTimeProvider().now() - start,\n error: 'No CLI adapters available',\n };\n }\n\n // Check circuit breaker health before dispatch (#1766)\n const health = checkCircuitHealth();\n if (!health.healthy) {\n logger.warn('Circuit breaker: all CLIs unavailable', { expertType, reason: health.message });\n return {\n success: false,\n text: '',\n expertType,\n durationMs: getTimeProvider().now() - start,\n error: health.message,\n };\n }\n\n // Pass MCP config so CLI experts can call nexus-agents tools (#1708)\n const mcpConfigPath = await getMcpConfigPath();\n const task: { content: string; options?: Record<string, unknown> | undefined } = {\n content: fullPrompt,\n };\n if (mcpConfigPath !== null) task.options = { mcpConfigPath };\n\n return await dispatchWithRateLimitRetry(router, task, expertType, start);\n } catch (error) {\n const durationMs = getTimeProvider().now() - start;\n const msg = error instanceof Error ? error.message : String(error);\n logger.warn('Expert bridge error', { expertType, error: msg });\n return { success: false, text: '', expertType, durationMs, error: msg };\n }\n}\n"],"mappings":";;;;;;;;;;AA0BA,SAAS,0BAA0B,OAAuD;AACxF,SAAO,eAAe,KAAK;AAC7B;AAEA,IAAM,SAAS,aAAa,EAAE,WAAW,gBAAgB,CAAC;AAG1D,IAAM,2BAA2B;AAqEjC,IAAI,eAAkC;AAGtC,IAAI,sBAAqC;AAMzC,IAAI,yBAAuD;AAI3D,IAAI,uBAAsD;AAG1D,eAAe,mBAA2C;AACxD,MAAI,wBAAwB,KAAM,QAAO;AACzC,4BAA0B,YAAoC;AAC5D,QAAI;AACF,YAAM,EAAE,kBAAkB,IAAI,MAAM,OAAO,gCAAqC;AAChF,YAAM,SAAS,MAAM,kBAAkB;AACvC,4BAAsB,OAA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MAAM,YAAY,KAAK;AAAA,EACzE,SAAS,OAAO;AACd,UAAM,aAAa,gBAAgB,EAAE,IAAI,IAAI;AAC7C,UAAM,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACjE,WAAO,KAAK,uBAAuB,EAAE,YAAY,OAAO,IAAI,CAAC;AAC7D,WAAO,EAAE,SAAS,OAAO,MAAM,IAAI,YAAY,YAAY,OAAO,IAAI;AAAA,EACxE;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/pipeline/expert-bridge.ts"],"sourcesContent":["/**\n * Expert Bridge — Programmatic access to the execute_expert pipeline (#1693)\n *\n * Provides a clean wrapper for calling experts with the full pipeline:\n * timeout, fallback cascade, degradation detection, heartbeat, outcome recording.\n *\n * DRY: reuses createBuiltInExpert + CompositeRouter instead of reimplementing.\n *\n * @module pipeline/expert-bridge\n */\n\nimport { createLogger, getTimeProvider } from '../core/index.js';\nimport type { BuiltInExpertType } from '../agents/experts/expert-config.js';\nimport { isRateLimitText } from '../adapters/rate-limit-detector.js';\nimport { resolveCliSlot } from '../config/model-availability.js';\nimport type { CliNameLiteral } from '../config/model-capabilities-types.js';\n\n/**\n * Resolves a CLI slot from the model string a (CLI or API) adapter returned.\n * Known models resolve to their exact slot; **unknown** models — new releases\n * or API/openrouter models not in the curated registry — fall back to the\n * vendor-derived slot (#3317 / #3293) so the outcome is recorded against a real\n * slot instead of being dropped with an undefined cli (the api-mode gap).\n * Returns undefined only when no model is present (the bridge failed before\n * dispatch — no execution to attribute).\n */\nfunction resolveCliFromModelString(model: string | undefined): CliNameLiteral | undefined {\n return resolveCliSlot(model);\n}\n\nconst logger = createLogger({ component: 'expert-bridge' });\n\n/** Base delay for rate limit retry backoff (ms). Scales linearly: 3s, 6s, 9s. */\nconst RATE_LIMIT_BASE_DELAY_MS = 3000;\n\n/** Result of an expert execution. */\nexport interface ExpertBridgeResult {\n readonly success: boolean;\n readonly text: string;\n readonly expertType: BuiltInExpertType;\n readonly durationMs: number;\n readonly error?: string;\n /**\n * CLI that actually executed the task, resolved from the underlying\n * `CliResponse.model` via `getCliForModelId`. Undefined when the bridge\n * failed before dispatch (no adapters / circuit-open / rate-limit cap).\n * Callers writing to OutcomeStore should use this rather than hardcoding\n * a cli — see #2823 (#1154 regression).\n */\n readonly cli?: CliNameLiteral;\n /**\n * Total tokens (input + output) the underlying CLI/adapter reported for this\n * call, when available (#3396). Best-effort: `CliResponse.usage` is optional\n * — CLI-subprocess paths whose `extractUsage` returns null leave this\n * undefined. Consumers (budget enforcement #3395, model.called attribution\n * #3387, routing-experience metrics) must tolerate `undefined`.\n */\n readonly tokensUsed?: number;\n /**\n * Concrete model id the underlying adapter reported (`CliResponse.model`),\n * when present (#3387). Distinct from {@link cli} (the slot): one CLI can run\n * several models. Undefined when the adapter didn't report a model or the\n * bridge failed before dispatch. Required to emit a `model.called` event.\n */\n readonly model?: string;\n /**\n * Input/output token split from the adapter's `CliResponse.usage` (#3387),\n * when reported. Best-effort like {@link tokensUsed}; both undefined together\n * when no usage was available. `tokensIn + tokensOut` reconciles with\n * `tokensUsed` (single source of truth — both derive from the same record).\n */\n readonly tokensIn?: number;\n readonly tokensOut?: number;\n}\n\n/**\n * Execute an expert task with the full nexus-agents expert pipeline.\n *\n * Creates a built-in expert, executes via CompositeRouter (for intelligent\n * CLI routing), and records outcomes. Falls back gracefully on failure.\n *\n * @param expertType - Built-in expert type (code, architecture, security, qa, etc.)\n * @param prompt - Task prompt for the expert\n * @returns Expert result with text output\n */\n/** Minimal router interface for the bridge. */\ninterface RouterLike {\n executeTask(task: { content: string; options?: Record<string, unknown> | undefined }): Promise<{\n ok: boolean;\n value: {\n text: string;\n cli?: CliNameLiteral;\n tokensUsed?: number;\n model?: string;\n tokensIn?: number;\n tokensOut?: number;\n };\n error: { message: string };\n }>;\n}\n\n// Cached router — lazily initialized, reused across calls within a session\nlet cachedRouter: RouterLike | null = null;\n\n// Cached MCP config — generated once, reused across expert calls (#1708)\nlet cachedMcpConfigPath: string | null = null;\n// Cached cleanup for the cached config's tempdir (closes #2946). Previously\n// the cleanup returned by `generateMcpConfig` was thrown away, so\n// `/tmp/nexus-mcp-XXXXXX/` accumulated one entry per MCP server lifetime.\n// Stored here + invoked by `shutdownExpertBridge()` from the server's\n// graceful-shutdown path.\nlet cachedMcpConfigCleanup: (() => Promise<void>) | null = null;\n// Coalesces concurrent init under voter fan-out (closes #2969). consensus_vote\n// fans out N=7 callers on cold start; without this each one ran the full init\n// including a mkdtemp() that the loser N-1 instances never cleaned up.\nlet mcpConfigInitPromise: Promise<string | null> | null = null;\n\n/** Get or create cached MCP config path for expert CLI sessions (#1708). */\nasync function getMcpConfigPath(): Promise<string | null> {\n if (cachedMcpConfigPath !== null) return cachedMcpConfigPath;\n mcpConfigInitPromise ??= (async (): Promise<string | null> => {\n try {\n const { generateMcpConfig } = await import('../cli-adapters/child-mcp-config.js');\n const config = await generateMcpConfig();\n cachedMcpConfigPath = config.configPath;\n cachedMcpConfigCleanup = config.cleanup;\n return cachedMcpConfigPath;\n } catch {\n mcpConfigInitPromise = null; // allow retry on next call\n return null; // MCP config not available — experts run without tools\n }\n })();\n return mcpConfigInitPromise;\n}\n\n/**\n * Removes the cached MCP-config tempdir (closes #2946). Invoke from the\n * server's graceful-shutdown path so stale nexus-mcp-* tempdirs (under\n * the OS tmpdir, see child-mcp-config.ts) don't accumulate across daemon\n * restarts. Idempotent; safe to call multiple times. Never throws —\n * cleanup failures are logged and swallowed.\n */\nexport async function shutdownExpertBridge(): Promise<void> {\n const cleanup = cachedMcpConfigCleanup;\n if (cleanup === null) return;\n cachedMcpConfigCleanup = null;\n cachedMcpConfigPath = null;\n mcpConfigInitPromise = null;\n try {\n await cleanup();\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n logger.debug('Expert-bridge MCP-config cleanup failed', { error: msg });\n }\n}\n\n/** Cached circuit breaker for health monitoring (#1766). */\nlet cachedCircuitBreaker: {\n getHealthStatus(): {\n systemHealthy: boolean;\n healthyCount: number;\n clis: ReadonlyArray<{ name: string; healthy: boolean }>;\n };\n} | null = null;\n\n/**\n * Adapt a CompositeRouter to the narrower RouterLike interface used by this\n * bridge. Previously did `as unknown as RouterLike` which hid any structural\n * mismatch between CompositeRouter's `Result<CliResponse, CliError>` and\n * RouterLike's flat `{ ok, value: { text }, error: { message } }` shape.\n * If CliResponse renames `.text` → `.output` (or similar), this adapter\n * breaks at compile time instead of silently returning wrong data (#1921).\n */\n/**\n * Total tokens from a best-effort `CliResponse.usage` record (#3396). Prefers\n * the reported `totalTokens`; falls back to input+output; returns undefined\n * when no usage was reported (so callers can distinguish \"0 tokens\" — which\n * never happens for a real call — from \"unknown\").\n */\nexport function totalTokensFromUsage(\n usage: { totalTokens?: number; inputTokens?: number; outputTokens?: number } | undefined\n): number | undefined {\n if (usage === undefined) return undefined;\n if (typeof usage.totalTokens === 'number') return usage.totalTokens;\n const total = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);\n return total > 0 ? total : undefined;\n}\n\n/**\n * Per-direction token split from a best-effort `CliResponse.usage` record\n * (#3387). Unlike {@link totalTokensFromUsage} this keeps `tokensIn`/`tokensOut`\n * separate — the granularity `ModelCalledEvent` requires for attribution.\n * Returns undefined when no usage was reported or both directions are zero (no\n * real call), so callers skip emitting a noise event instead of recording\n * zeros. Reconciles with the total: `tokensIn + tokensOut === totalTokensFromUsage`.\n */\nexport function tokenSplitFromUsage(\n usage: { inputTokens?: number; outputTokens?: number; totalTokens?: number } | undefined\n): { tokensIn: number; tokensOut: number } | undefined {\n if (usage === undefined) return undefined;\n const tokensIn = usage.inputTokens ?? 0;\n const tokensOut = usage.outputTokens ?? 0;\n if (tokensIn + tokensOut === 0) return undefined;\n return { tokensIn, tokensOut };\n}\n\nfunction adaptCompositeRouter(\n compositeRouter: import('../cli-adapters/composite-router.js').ICompositeRouter\n): RouterLike {\n return {\n async executeTask(task): Promise<{\n ok: boolean;\n value: {\n text: string;\n cli?: CliNameLiteral;\n tokensUsed?: number;\n model?: string;\n tokensIn?: number;\n tokensOut?: number;\n };\n error: { message: string };\n }> {\n const cliTask: import('../cli-adapters/types.js').CliTask = {\n content: task.content,\n ...(task.options !== undefined ? { options: task.options } : {}),\n };\n const result = await compositeRouter.executeTask(cliTask);\n if (result.ok) {\n // #2823: surface which CLI actually executed so callers writing to\n // OutcomeStore don't have to hardcode 'claude' (the bug #1154 fixed\n // and that regressed into the pipeline/ tree). Derive via the\n // canonical model→cli mapping in the registry — if the underlying\n // adapter didn't set `model` or the model isn't in the registry,\n // cli stays undefined and downstream code can skip the record\n // rather than lie.\n const cli = resolveCliFromModelString(result.value.model);\n // #3396: surface token usage (best-effort) so budget enforcement,\n // attribution, and routing-experience metrics get real numbers instead\n // of zeros. `usage` is optional and `totalTokens` may be absent — fall\n // back to input+output, and leave undefined when no usage was reported.\n const tokensUsed = totalTokensFromUsage(result.value.usage);\n // #3387: also surface the concrete model + per-direction token split so\n // a meaningful `model.called` event can be emitted. Both derive from the\n // same CliResponse, so tokensIn+tokensOut reconciles with tokensUsed.\n const model = result.value.model;\n const split = tokenSplitFromUsage(result.value.usage);\n return {\n ok: true,\n value: {\n text: result.value.text,\n ...(cli !== undefined && { cli }),\n ...(tokensUsed !== undefined && { tokensUsed }),\n ...(model !== undefined && { model }),\n ...(split !== undefined && { tokensIn: split.tokensIn, tokensOut: split.tokensOut }),\n },\n error: { message: '' },\n };\n }\n return { ok: false, value: { text: '' }, error: { message: result.error.message } };\n },\n };\n}\n\n// Coalesces concurrent router init the same way mcpConfigInitPromise does\n// (closes #2969). N=7 voter fan-out previously ran createAllAdapters() N times\n// — N sets of CLI probe subprocesses, all but one discarded.\nlet routerInitPromise: Promise<RouterLike | null> | null = null;\n\n/** Get or create a cached CompositeRouter with circuit breaker monitoring. */\nasync function getRouter(): Promise<RouterLike | null> {\n if (cachedRouter !== null) return cachedRouter;\n routerInitPromise ??= (async (): Promise<RouterLike | null> => {\n // ROUTER CONSTRUCTION, a distinct operation from adapter acquisition\n // (#5191, ratified 5/6). `createCompositeRouter` needs\n // `Map<RoutingArmId, ICliAdapter>`; `getGlobalRegistry()` returns\n // `IResilientAdapter` (extends `IModelAdapter`) one CLI at a time, so the\n // canonical path cannot type-check here.\n //\n // It also should not be used: the router IS the selection/failover layer,\n // so resilient-wrapped arms would nest two failover mechanisms, and the\n // shared circuit breaker would make an arm report unavailable without the\n // router ever testing it. That is the doctor-probe defect (#5209) applied\n // to routing — and this map is the LinUCB arm space, so a coupled arm\n // availability would distort exploration signals.\n //\n // Pinned by `router-operation.test.ts`.\n const { createAllAdapters } = await import('../cli-adapters/factory.js');\n const { createCompositeRouter } = await import('../cli-adapters/composite-router.js');\n const adapters = createAllAdapters();\n if (adapters.size === 0) {\n routerInitPromise = null; // allow retry once adapters become available\n return null;\n }\n cachedRouter = adaptCompositeRouter(createCompositeRouter(adapters));\n\n // Initialize circuit breaker monitoring (#1766)\n try {\n const { createCliCircuitBreakerIntegration } =\n await import('../cli-adapters/cli-circuit-breaker.js');\n cachedCircuitBreaker = createCliCircuitBreakerIntegration([...adapters.values()]);\n } catch (error: unknown) {\n // Circuit breaker not available — continue without it. Log so we can\n // notice if initialization silently stops working (#1913 Class B).\n const msg = error instanceof Error ? error.message : String(error);\n logger.debug('Circuit breaker init failed; continuing without it', { error: msg });\n }\n\n return cachedRouter;\n })();\n return routerInitPromise;\n}\n\n/** Check CLI health before dispatch (#1766). */\nfunction checkCircuitHealth(): { healthy: boolean; message: string } {\n if (cachedCircuitBreaker === null) return { healthy: true, message: '' };\n const status = cachedCircuitBreaker.getHealthStatus();\n if (!status.systemHealthy) {\n return {\n healthy: false,\n message: `All CLI circuits open (${String(status.healthyCount)}/${String(status.clis.length)} healthy)`,\n };\n }\n return { healthy: true, message: '' };\n}\n\n/** Dispatch task to router with rate limit retry (#1802). */\nasync function dispatchWithRateLimitRetry(\n router: RouterLike,\n task: { content: string; options?: Record<string, unknown> | undefined },\n expertType: BuiltInExpertType,\n start: number\n): Promise<ExpertBridgeResult> {\n const maxAttempts = 3;\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const result = await router.executeTask(task);\n const durationMs = getTimeProvider().now() - start;\n\n if (result.ok) {\n logger.info('Expert executed successfully', {\n expertType,\n durationMs,\n cli: result.value.cli,\n });\n return {\n success: true,\n text: result.value.text,\n expertType,\n durationMs,\n ...(result.value.cli !== undefined && { cli: result.value.cli }),\n ...(result.value.tokensUsed !== undefined && { tokensUsed: result.value.tokensUsed }),\n ...(result.value.model !== undefined && { model: result.value.model }),\n ...(result.value.tokensIn !== undefined && { tokensIn: result.value.tokensIn }),\n ...(result.value.tokensOut !== undefined && { tokensOut: result.value.tokensOut }),\n };\n }\n\n const isRateLimit = isRateLimitText(result.error.message);\n if (isRateLimit && attempt < maxAttempts - 1) {\n const backoffMs = RATE_LIMIT_BASE_DELAY_MS * (attempt + 1);\n logger.warn('Expert rate limited, retrying', { expertType, attempt: attempt + 1, backoffMs });\n await new Promise((resolve) => setTimeout(resolve, backoffMs));\n continue;\n }\n\n logger.warn('Expert execution failed', { expertType, error: result.error.message });\n return { success: false, text: '', expertType, durationMs, error: result.error.message };\n }\n\n return {\n success: false,\n text: '',\n expertType,\n durationMs: getTimeProvider().now() - start,\n error: 'Max retry attempts exceeded',\n };\n}\n\nexport async function executeExpert(\n expertType: BuiltInExpertType,\n prompt: string\n): Promise<ExpertBridgeResult> {\n const start = getTimeProvider().now();\n try {\n const { BUILT_IN_EXPERTS } = await import('../agents/experts/expert-config.js');\n const config = BUILT_IN_EXPERTS[expertType];\n const fullPrompt = `${config.systemPrompt}\\n\\n${prompt}`;\n\n const router = await getRouter();\n if (router === null) {\n return {\n success: false,\n text: `[No adapters] ${prompt}`,\n expertType,\n durationMs: getTimeProvider().now() - start,\n error: 'No CLI adapters available',\n };\n }\n\n // Check circuit breaker health before dispatch (#1766)\n const health = checkCircuitHealth();\n if (!health.healthy) {\n logger.warn('Circuit breaker: all CLIs unavailable', { expertType, reason: health.message });\n return {\n success: false,\n text: '',\n expertType,\n durationMs: getTimeProvider().now() - start,\n error: health.message,\n };\n }\n\n // Pass MCP config so CLI experts can call nexus-agents tools (#1708)\n const mcpConfigPath = await getMcpConfigPath();\n const task: { content: string; options?: Record<string, unknown> | undefined } = {\n content: fullPrompt,\n };\n if (mcpConfigPath !== null) task.options = { mcpConfigPath };\n\n return await dispatchWithRateLimitRetry(router, task, expertType, start);\n } catch (error) {\n const durationMs = getTimeProvider().now() - start;\n const msg = error instanceof Error ? error.message : String(error);\n logger.warn('Expert bridge error', { expertType, error: msg });\n return { success: false, text: '', expertType, durationMs, error: msg };\n }\n}\n"],"mappings":";;;;;;;;;;AA0BA,SAAS,0BAA0B,OAAuD;AACxF,SAAO,eAAe,KAAK;AAC7B;AAEA,IAAM,SAAS,aAAa,EAAE,WAAW,gBAAgB,CAAC;AAG1D,IAAM,2BAA2B;AAqEjC,IAAI,eAAkC;AAGtC,IAAI,sBAAqC;AAMzC,IAAI,yBAAuD;AAI3D,IAAI,uBAAsD;AAG1D,eAAe,mBAA2C;AACxD,MAAI,wBAAwB,KAAM,QAAO;AACzC,4BAA0B,YAAoC;AAC5D,QAAI;AACF,YAAM,EAAE,kBAAkB,IAAI,MAAM,OAAO,gCAAqC;AAChF,YAAM,SAAS,MAAM,kBAAkB;AACvC,4BAAsB,OAAO;AAC7B,+BAAyB,OAAO;AAChC,aAAO;AAAA,IACT,QAAQ;AACN,6BAAuB;AACvB,aAAO;AAAA,IACT;AAAA,EACF,GAAG;AACH,SAAO;AACT;AASA,eAAsB,uBAAsC;AAC1D,QAAM,UAAU;AAChB,MAAI,YAAY,KAAM;AACtB,2BAAyB;AACzB,wBAAsB;AACtB,yBAAuB;AACvB,MAAI;AACF,UAAM,QAAQ;AAAA,EAChB,SAAS,OAAgB;AACvB,UAAM,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACjE,WAAO,MAAM,2CAA2C,EAAE,OAAO,IAAI,CAAC;AAAA,EACxE;AACF;AAGA,IAAI,u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
import {
|
|
5
5
|
emitClawGuardViolation
|
|
6
6
|
} from "./chunk-3U6L7DBT.js";
|
|
@@ -2116,4 +2116,4 @@ export {
|
|
|
2116
2116
|
VOTING_THRESHOLDS,
|
|
2117
2117
|
ConsensusMetricsSchema
|
|
2118
2118
|
};
|
|
2119
|
-
//# sourceMappingURL=chunk-
|
|
2119
|
+
//# sourceMappingURL=chunk-O2RQZFOJ.js.map
|
|
@@ -21,10 +21,10 @@ import {
|
|
|
21
21
|
import {
|
|
22
22
|
DEFAULT_TASK_TTL_MS,
|
|
23
23
|
clampTaskTtl
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-HIXWQWNA.js";
|
|
25
25
|
import {
|
|
26
26
|
executeExpert
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-MUTREHSB.js";
|
|
28
28
|
import {
|
|
29
29
|
JobStatusSchema,
|
|
30
30
|
VOTER_ROLES,
|
|
@@ -47,7 +47,7 @@ import {
|
|
|
47
47
|
simulationDeniedResult,
|
|
48
48
|
toJobSummary,
|
|
49
49
|
writeJobCancelled
|
|
50
|
-
} from "./chunk-
|
|
50
|
+
} from "./chunk-VDA4B6NO.js";
|
|
51
51
|
import {
|
|
52
52
|
allOf
|
|
53
53
|
} from "./chunk-OQB3XC5O.js";
|
|
@@ -64,7 +64,7 @@ import {
|
|
|
64
64
|
} from "./chunk-6FD2ANO6.js";
|
|
65
65
|
import {
|
|
66
66
|
withPrerequisite
|
|
67
|
-
} from "./chunk-
|
|
67
|
+
} from "./chunk-SYVBAREH.js";
|
|
68
68
|
import {
|
|
69
69
|
NOOP_NOTIFIER,
|
|
70
70
|
RateLimiter,
|
|
@@ -88,7 +88,7 @@ import {
|
|
|
88
88
|
withAuditTrail,
|
|
89
89
|
withProgressHeartbeat,
|
|
90
90
|
wrapToolWithTimeout
|
|
91
|
-
} from "./chunk-
|
|
91
|
+
} from "./chunk-O2RQZFOJ.js";
|
|
92
92
|
import {
|
|
93
93
|
createAuditTrail,
|
|
94
94
|
createGraphAuditBridge,
|
|
@@ -45527,7 +45527,7 @@ var VALID_TEMPLATES = /* @__PURE__ */ new Set([
|
|
|
45527
45527
|
]);
|
|
45528
45528
|
async function classifyWithLLM(task) {
|
|
45529
45529
|
try {
|
|
45530
|
-
const { executeExpert: executeExpert2 } = await import("./expert-bridge-
|
|
45530
|
+
const { executeExpert: executeExpert2 } = await import("./expert-bridge-JHRGVFMI.js");
|
|
45531
45531
|
const prompt = [
|
|
45532
45532
|
"Classify this task into exactly one pipeline template.",
|
|
45533
45533
|
"Templates: dev (implementation/bug fix/refactor), research (investigate/evaluate/compare),",
|
|
@@ -47541,7 +47541,7 @@ ${contextBlock}`;
|
|
|
47541
47541
|
const strategy = config.votingStrategy ?? "higher_order";
|
|
47542
47542
|
await postProgress(config, "Vote", `Running consensus with ${strategy} strategy...`);
|
|
47543
47543
|
try {
|
|
47544
|
-
const { executeVoting } = await import("./consensus-vote-
|
|
47544
|
+
const { executeVoting } = await import("./consensus-vote-YMHPKKZV.js");
|
|
47545
47545
|
const votingResult = await executeVoting(
|
|
47546
47546
|
{
|
|
47547
47547
|
proposal: buildVoteProposal(plan, research),
|
|
@@ -56169,4 +56169,4 @@ export {
|
|
|
56169
56169
|
shutdownFeedbackSubscriber,
|
|
56170
56170
|
createEventBusBridge
|
|
56171
56171
|
};
|
|
56172
|
-
//# sourceMappingURL=chunk-
|
|
56172
|
+
//# sourceMappingURL=chunk-OFEXOT56.js.map
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
toolStructuredError,
|
|
8
8
|
toolSuccessStructured,
|
|
9
9
|
wrapToolWithTimeout
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-O2RQZFOJ.js";
|
|
11
11
|
import {
|
|
12
12
|
JsonlStore,
|
|
13
13
|
SECURITY_KEYWORDS,
|
|
@@ -2159,4 +2159,4 @@ export {
|
|
|
2159
2159
|
runImprovementReview,
|
|
2160
2160
|
registerImprovementReviewTool
|
|
2161
2161
|
};
|
|
2162
|
-
//# sourceMappingURL=chunk-
|
|
2162
|
+
//# sourceMappingURL=chunk-SYVBAREH.js.map
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
toolSuccessStructured,
|
|
24
24
|
withProgressHeartbeat,
|
|
25
25
|
wrapToolWithTimeout
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-O2RQZFOJ.js";
|
|
27
27
|
import {
|
|
28
28
|
assessPanelIndependence,
|
|
29
29
|
countDistinctModels,
|
|
@@ -6216,7 +6216,7 @@ async function processVotesWithCascade(engineVotes, opts) {
|
|
|
6216
6216
|
var CONTRARIAN_ESCALATION_THRESHOLD = 0.8;
|
|
6217
6217
|
async function runContrarianCheck(proposal, log) {
|
|
6218
6218
|
try {
|
|
6219
|
-
const { executeExpert } = await import("./expert-bridge-
|
|
6219
|
+
const { executeExpert } = await import("./expert-bridge-JHRGVFMI.js");
|
|
6220
6220
|
const prompt = [
|
|
6221
6221
|
"You are a contrarian analyst. Your job is to find reasons this proposal should be REJECTED.",
|
|
6222
6222
|
"Look for: YAGNI (not needed), MISALIGNED (wrong tech/architecture), SECURITY_RISK, SCOPE_CREEP.",
|
|
@@ -6803,4 +6803,4 @@ export {
|
|
|
6803
6803
|
CONSENSUS_VOTE_TOOL_SCHEMA,
|
|
6804
6804
|
registerConsensusVoteTool
|
|
6805
6805
|
};
|
|
6806
|
-
//# sourceMappingURL=chunk-
|
|
6806
|
+
//# sourceMappingURL=chunk-VDA4B6NO.js.map
|
package/dist/cli.js
CHANGED
|
@@ -152,7 +152,7 @@ import {
|
|
|
152
152
|
validateNexusEnv,
|
|
153
153
|
validateWorkflow,
|
|
154
154
|
wrapInMarkdownFence
|
|
155
|
-
} from "./chunk-
|
|
155
|
+
} from "./chunk-OFEXOT56.js";
|
|
156
156
|
import "./chunk-TKEO2CET.js";
|
|
157
157
|
import "./chunk-HFOQKCD2.js";
|
|
158
158
|
import "./chunk-RSMG2DPB.js";
|
|
@@ -171,14 +171,14 @@ import {
|
|
|
171
171
|
doctorCommand,
|
|
172
172
|
initDataDirectories,
|
|
173
173
|
runDoctor
|
|
174
|
-
} from "./chunk-
|
|
174
|
+
} from "./chunk-HIXWQWNA.js";
|
|
175
175
|
import {
|
|
176
176
|
buildOpenAICompatAdapters,
|
|
177
177
|
readOpenAICompatEnv
|
|
178
178
|
} from "./chunk-QPV34W5L.js";
|
|
179
179
|
import {
|
|
180
180
|
shutdownExpertBridge
|
|
181
|
-
} from "./chunk-
|
|
181
|
+
} from "./chunk-MUTREHSB.js";
|
|
182
182
|
import {
|
|
183
183
|
ConsensusVoteInputSchema,
|
|
184
184
|
DEFAULT_VOTE_TIMEOUT_MS,
|
|
@@ -190,7 +190,7 @@ import {
|
|
|
190
190
|
recordAuthenticVote,
|
|
191
191
|
registerConsensusVoteTool,
|
|
192
192
|
toRecordDecision
|
|
193
|
-
} from "./chunk-
|
|
193
|
+
} from "./chunk-VDA4B6NO.js";
|
|
194
194
|
import {
|
|
195
195
|
loadUsageEvents,
|
|
196
196
|
rollupByModel
|
|
@@ -226,15 +226,15 @@ import {
|
|
|
226
226
|
registerImprovementReviewTool,
|
|
227
227
|
runImprovementReview,
|
|
228
228
|
scanForSecrets
|
|
229
|
-
} from "./chunk-
|
|
229
|
+
} from "./chunk-SYVBAREH.js";
|
|
230
230
|
import {
|
|
231
231
|
createDefaultPolicyFirewall,
|
|
232
232
|
setGlobalPolicyFirewall,
|
|
233
233
|
stagePolicyFirewallForRollout
|
|
234
|
-
} from "./chunk-
|
|
234
|
+
} from "./chunk-O2RQZFOJ.js";
|
|
235
235
|
import {
|
|
236
236
|
VERSION
|
|
237
|
-
} from "./chunk-
|
|
237
|
+
} from "./chunk-3NJFOC3L.js";
|
|
238
238
|
import "./chunk-3U6L7DBT.js";
|
|
239
239
|
import {
|
|
240
240
|
createUnifiedRegistry,
|
|
@@ -19553,7 +19553,7 @@ function startImprovementReviewScheduler(options) {
|
|
|
19553
19553
|
let running = false;
|
|
19554
19554
|
const runOnce = async () => {
|
|
19555
19555
|
try {
|
|
19556
|
-
const { runImprovementReview: runImprovementReview2, ImprovementReviewInputSchema: ImprovementReviewInputSchema2 } = await import("./improvement-review-
|
|
19556
|
+
const { runImprovementReview: runImprovementReview2, ImprovementReviewInputSchema: ImprovementReviewInputSchema2 } = await import("./improvement-review-BTPKYYYU.js");
|
|
19557
19557
|
const input = ImprovementReviewInputSchema2.parse({ fileIssues });
|
|
19558
19558
|
const result = await runImprovementReview2(input, { logger: logger22 });
|
|
19559
19559
|
logger22.info("Scheduled improvement_review complete", {
|