harness-reflex 0.0.0-stage → 0.1.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.
- package/README.md +186 -2
- package/USER_GUIDE.md +561 -0
- package/dist/adapters/agy.d.ts +8 -0
- package/dist/adapters/agy.js +80 -0
- package/dist/adapters/agy.js.map +1 -0
- package/dist/adapters/claude.d.ts +13 -0
- package/dist/adapters/claude.js +46 -0
- package/dist/adapters/claude.js.map +1 -0
- package/dist/adapters/codex.d.ts +10 -0
- package/dist/adapters/codex.js +45 -0
- package/dist/adapters/codex.js.map +1 -0
- package/dist/backend/factory.d.ts +11 -0
- package/dist/backend/factory.js +40 -0
- package/dist/backend/factory.js.map +1 -0
- package/dist/backend/jev.d.ts +524 -0
- package/dist/backend/jev.js +1485 -0
- package/dist/backend/jev.js.map +1 -0
- package/dist/backend/mock.d.ts +15 -0
- package/dist/backend/mock.js +286 -0
- package/dist/backend/mock.js.map +1 -0
- package/dist/backend/route-prompt.d.ts +37 -0
- package/dist/backend/route-prompt.js +42 -0
- package/dist/backend/route-prompt.js.map +1 -0
- package/dist/backend/simple-jev.d.ts +35 -0
- package/dist/backend/simple-jev.js +272 -0
- package/dist/backend/simple-jev.js.map +1 -0
- package/dist/backend/types.d.ts +236 -0
- package/dist/backend/types.js +5 -0
- package/dist/backend/types.js.map +1 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +276 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/core/calibrate.d.ts +56 -0
- package/dist/core/calibrate.js +144 -0
- package/dist/core/calibrate.js.map +1 -0
- package/dist/core/gate.d.ts +25 -0
- package/dist/core/gate.js +114 -0
- package/dist/core/gate.js.map +1 -0
- package/dist/core/ledger.d.ts +67 -0
- package/dist/core/ledger.js +173 -0
- package/dist/core/ledger.js.map +1 -0
- package/dist/core/prune.d.ts +30 -0
- package/dist/core/prune.js +73 -0
- package/dist/core/prune.js.map +1 -0
- package/dist/core/route.d.ts +35 -0
- package/dist/core/route.js +39 -0
- package/dist/core/route.js.map +1 -0
- package/dist/core/score.d.ts +40 -0
- package/dist/core/score.js +49 -0
- package/dist/core/score.js.map +1 -0
- package/dist/core/screen.d.ts +22 -0
- package/dist/core/screen.js +117 -0
- package/dist/core/screen.js.map +1 -0
- package/dist/core/stagnation.d.ts +23 -0
- package/dist/core/stagnation.js +93 -0
- package/dist/core/stagnation.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/server.d.ts +12 -0
- package/dist/mcp/server.js +368 -0
- package/dist/mcp/server.js.map +1 -0
- package/docs/USER_GUIDE.en.md +678 -0
- package/docs/dsh-plugin.md +578 -0
- package/docs/reflex-ui-regression-2026-10-20.md +34 -0
- package/docs/release-checklist-v0.1.0.md +304 -0
- package/docs/release-handbook-porting-notes.md +106 -0
- package/docs/release-handbook.md +368 -0
- package/docs/release-notes-v0.1.0.md +50 -0
- package/experiments/data/calibration_sample.json +14 -0
- package/experiments/index.ts +29 -0
- package/experiments/runner.ts +156 -0
- package/package.json +73 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mock.js","sourceRoot":"","sources":["../../src/backend/mock.ts"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;GAaG;AACH,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,4BAA4B,CAAC,EAAE,CAAC;QAC3E,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACjC,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACnC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;gBAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACxC,SAAS;QACX,CAAC;QACD,KAAK,I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B,MAAM,EAAE,WAAW,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,iBAAiB;aACjF,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;QACzC,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;QAC3B,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QAErC,OAAO;YACL,gBAAgB,EAAE,MAAM;YACxB,aAAa,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI;YAC9B,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;SACjD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n DecisionBackend,\n ChoiceRequest,\n ChoiceResponse,\n GateRequest,\n GateResponse,\n PruneRequest,\n PruneResponse,\n StagnationCheckRequest,\n StagnationCheckResponse,\n RouteRequest,\n RouteResponse,\n GateResultItem,\n GateOutcome\n} from './types.js';\n\n/**\n * Vocabulary one option contributes to the overlap score.\n *\n * ASCII words keep the historical `length > 2` filter. Chinese is written\n * without spaces and nearly every technical term is two characters (并发, 证明,\n * 迁移), so a whitespace split drops the entire vocabulary of a Chinese turn and\n * collapses every option into an indistinguishable tie — which then reads as a\n * confident decision. A Han run therefore contributes its two-character grams as\n * well as the run itself, so an option's cue word matches inside an unspaced\n * sentence.\n *\n * @param text - one candidate option.\n * @returns distinct matchable terms, in option order.\n */\nfunction matchTerms(text: string): string[] {\n const terms: string[] = [];\n for (const chunk of text.toLowerCase().split(/[^\\p{Script=Han}a-z0-9_]+/u)) {\n if (chunk.length === 0) continue;\n if (!/\\p{Script=Han}/u.test(chunk)) {\n if (chunk.length > 2) terms.push(chunk);\n continue;\n }\n for (let i = 0; i + 2 <= chunk.length; i++) terms.push(chunk.slice(i, i + 2));\n if (chunk.length > 2) terms.push(chunk);\n }\n return terms;\n}\n\n/**\n * Ignore explicit zero counters, not failure words in general. Both count-first\n * (pytest/Jest) and label-first (node:test) summaries occur in captured output.\n * Replace nonzero counters with a cue so another zero counter cannot hide them.\n * This is only a mock heuristic, not semantic verification of arbitrary logs.\n */\nfunction hasFailureEvidence(evidence: string): boolean {\n const withoutCounters = evidence.replace(\n /\\b(\\d+(?:[.,]\\d+)*|zero)\\s+(fail(?:ed|ures?)?|errors?)\\b|\\b(fail(?:ed|ures?)?|errors?)\\s*[:=]?\\s*(\\d+(?:[.,]\\d+)*|zero)\\b/g,\n (_match, before: string | undefined, _beforeLabel: string | undefined, _afterLabel: string | undefined, after: string | undefined) => {\n const count = before ?? after!;\n return count === 'zero' || Number(count.replaceAll(',', '')) === 0 ? '' : ' failure ';\n }\n );\n // An explicit error diagnostic is not a summary, even if its message starts with 0.\n return evidence.includes('error:') || /fail|\\berrors?\\b/.test(withoutCounters);\n}\n\n/**\n * Mock & Heuristic Decision Backend\n * Provides instant (<5ms) deterministic decision evaluation for testing,\n * local development, and offline baseline comparisons.\n */\nexport class MockDecisionBackend implements DecisionBackend {\n readonly name = 'mock-heuristic-v1';\n readonly model = 'mock-system-one';\n\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n if (req.options.length === 0) {\n throw new Error('Choice options cannot be empty');\n }\n\n // Heuristic: rank options based on semantic relevance to question & context\n const qLower = req.question.toLowerCase();\n const ctxLower = (req.context || '').toLowerCase();\n\n const scores = req.options.map((opt) => {\n let score = 1.0;\n // Match the option's own vocabulary against the question and the context.\n for (const term of matchTerms(opt)) {\n if (qLower.includes(term)) score += 2.0;\n if (ctxLower.includes(term)) score += 1.5;\n }\n return score;\n });\n\n const sum = scores.reduce((a, b) => a + b, 0);\n const options = req.options.map((opt, i) => ({\n label: opt,\n probability: Number((scores[i] / sum).toFixed(4))\n }));\n\n // Sort descending\n options.sort((a, b) => b.probability - a.probability);\n\n return {\n options,\n bestOption: options[0].label,\n confidence: options[0].probability,\n uncalibrated: true,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const evidenceLower = req.evidence.toLowerCase();\n const hasErrorOrFail = hasFailureEvidence(evidenceLower);\n const results: GateResultItem[] = [];\n let allPassed = true;\n let needsEscalation = false;\n\n for (const assertion of req.assertions) {\n const stmt = assertion.statement;\n const stmtLower = stmt.toLowerCase();\n\n // Check for contradiction cues\n const claimsSuccess = stmtLower.includes('success') || stmtLower.includes('pass') || stmtLower.includes('finished') || stmtLower.includes('complete');\n\n let outcome: GateOutcome = 'not_addressed';\n let confidence = 0.85;\n let explanation = 'Evaluated against evidence.';\n\n if (claimsSuccess && hasErrorOrFail) {\n outcome = 'contradicted';\n explanation = 'Assertion claims success, but evidence contains explicit error or failure output.';\n allPassed = false;\n } else {\n // Keyword overlap\n const words = stmtLower.replace(/[^a-z0-9_\\s]/g, '').split(/\\s+/).filter((w) => w.length > 3);\n const matches = words.filter((w) => evidenceLower.includes(w));\n const matchRatio = words.length > 0 ? matches.length / words.length : 0;\n\n if (matchRatio >= 0.4) {\n outcome = 'verified';\n explanation = `Direct evidence found supporting assertion (matching terms: ${matches.slice(0, 3).join(', ')}).`;\n } else if (words.length > 0) {\n outcome = 'not_addressed';\n explanation = 'Evidence does not contain sufficient details to verify this assertion.';\n allPassed = false;\n if (req.strictness === 'high') {\n needsEscalation = true;\n }\n } else {\n outcome = 'escalate';\n explanation = 'Insufficient assertion details to determine truth.';\n needsEscalation = true;\n allPassed = false;\n }\n }\n\n results.push({\n statement: stmt,\n outcome,\n confidence,\n explanation\n });\n }\n\n return {\n passed: allPassed && !needsEscalation,\n results,\n needsEscalation,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n const raw = req.rawOutput;\n const lines = raw.split('\\n');\n\n // Deterministic + Semantic pruning:\n // Drop repetitive progress bars, redundant empty lines, unhelpful stack traces\n const filteredLines: string[] = [];\n const intentWords = req.intent.toLowerCase().split(/\\s+/).filter((w) => w.length > 2);\n\n let consecutiveEmpty = 0;\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed) {\n consecutiveEmpty++;\n if (consecutiveEmpty <= 1) filteredLines.push(line);\n continue;\n }\n consecutiveEmpty = 0;\n\n // Filter progress bar indicators\n if (line.includes('[===') || line.includes('████') || line.includes('\\r')) {\n continue;\n }\n\n // Filter typical node_modules / site-packages deep internals unless relevant\n if (line.includes('node_modules/') && !intentWords.some((w) => line.toLowerCase().includes(w))) {\n continue;\n }\n\n filteredLines.push(line);\n }\n\n const prunedOutput = filteredLines.join('\\n');\n const originalChars = raw.length;\n const prunedChars = prunedOutput.length;\n const estOriginalTokens = Math.ceil(originalChars / 4);\n const estPrunedTokens = Math.ceil(prunedChars / 4);\n const tokensSaved = Math.max(0, estOriginalTokens - estPrunedTokens);\n const reduction = originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0;\n\n return {\n processedOutput: req.shadowMode ? raw : prunedOutput,\n originalChars,\n prunedChars,\n estimatedTokensSaved: tokensSaved,\n reductionPercentage: reduction,\n shadow: !!req.shadowMode,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = req.history || [];\n const window = req.windowSize || 6;\n const recent = history.slice(-window);\n\n if (recent.length < 3) {\n return {\n isStuck: false,\n confidence: 0.95,\n diagnosis: 'Action history too short to establish stagnation.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 1: Identical consecutive tool calls\n const tools = recent.map((r) => `${r.tool}:${r.input.trim()}`);\n let identicalCount = 1;\n for (let i = tools.length - 1; i > 0; i--) {\n if (tools[i] === tools[i - 1]) {\n identicalCount++;\n } else {\n break;\n }\n }\n\n if (identicalCount >= 3) {\n return {\n isStuck: true,\n patternType: 'repetition',\n confidence: 0.98,\n diagnosis: `Identical tool execution repeated ${identicalCount} times consecutively with no change in input.`,\n recommendedIntervention: 'Interrupt execution. Suggest alternative tool or inspect previous failure output.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 2: Repeated failure / error cycle\n const failingSteps = recent.filter((r) => !!r.error || (r.output && (r.output.includes('Error') || r.output.includes('Failed'))));\n if (failingSteps.length >= 3 && recent.length >= 4) {\n return {\n isStuck: true,\n patternType: 'failing_retry',\n confidence: 0.91,\n diagnosis: `${failingSteps.length} of the last ${recent.length} actions failed with recurring errors.`,\n recommendedIntervention: 'Step back to analyze root cause before attempting the same action again.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n // Check 3: Oscillation between two files or two commands\n if (recent.length >= 4) {\n const last4 = recent.slice(-4);\n if (last4[0].tool === last4[2].tool && last4[1].tool === last4[3].tool && last4[0].input === last4[2].input && last4[1].input === last4[3].input) {\n return {\n isStuck: true,\n patternType: 'oscillation',\n confidence: 0.94,\n diagnosis: 'Agent is oscillating between two identical alternating commands/edits.',\n recommendedIntervention: 'Break loop: stop alternating and clarify requirements or test independently.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n return {\n isStuck: false,\n patternType: 'none',\n confidence: 0.88,\n diagnosis: 'Execution flow appears progressive.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const goalLower = req.goal.toLowerCase();\n \n const scored = req.candidates.map((cand) => {\n let score = 0.1;\n const text = `${cand.name} ${cand.description}`.toLowerCase();\n const words = goalLower.split(/\\s+/).filter((w) => w.length > 2);\n for (const w of words) {\n if (text.includes(w)) score += 1.0;\n }\n return {\n name: cand.name,\n score: Number(score.toFixed(3)),\n reason: `Matched ${words.filter((w) => text.includes(w)).length} query keywords`\n };\n });\n\n scored.sort((a, b) => b.score - a.score);\n const topK = req.topK || 3;\n const ranked = scored.slice(0, topK);\n\n return {\n rankedCandidates: ranked,\n bestCandidate: ranked[0]?.name,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n}\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt rendering for one System 1 route decision.
|
|
3
|
+
*
|
|
4
|
+
* The affinity facts ({@link RouteRequest.state}) and the policy instructions
|
|
5
|
+
* ({@link RouteRequest.instructions}) are part of the decision *prompt*, not of
|
|
6
|
+
* the decision *result*: a backend that builds a text prompt (the logits
|
|
7
|
+
* backend, and the HTTP body of the Jev gateway) renders them with these pure
|
|
8
|
+
* helpers, so what the model reads is unit-testable without a network call.
|
|
9
|
+
*
|
|
10
|
+
* Rendering one request with no state and no instructions reproduces the
|
|
11
|
+
* historical `name: description` context block byte for byte, so an unchanged
|
|
12
|
+
* caller sees an unchanged prompt.
|
|
13
|
+
*
|
|
14
|
+
* @module harness-reflex/backend/route-prompt
|
|
15
|
+
*/
|
|
16
|
+
import type { RouteCandidateItem, RouteRequest, RouteRequestState } from './types.js';
|
|
17
|
+
/** How the incumbent candidate is marked inside a decision prompt. */
|
|
18
|
+
export declare const CURRENT_MODEL_MARK = "[current model \u2014 keeping it preserves the prompt cache]";
|
|
19
|
+
/**
|
|
20
|
+
* Render one candidate line, marking the session's incumbent model.
|
|
21
|
+
* @param candidate - one pool candidate.
|
|
22
|
+
* @returns `name: description`, plus the incumbent mark when the candidate is current.
|
|
23
|
+
*/
|
|
24
|
+
export declare function renderCandidateLine(candidate: RouteCandidateItem): string;
|
|
25
|
+
/**
|
|
26
|
+
* Render the session facts and the policy instructions of one decision.
|
|
27
|
+
* @param state - cache-affinity facts, when the caller supplied any.
|
|
28
|
+
* @param instructions - policy instructions, when the caller supplied any.
|
|
29
|
+
* @returns one line per fact; an empty array when there is nothing to say.
|
|
30
|
+
*/
|
|
31
|
+
export declare function renderRouteStateLines(state: RouteRequestState | undefined, instructions: string | undefined): string[];
|
|
32
|
+
/**
|
|
33
|
+
* Build the context block one System 1 route decision receives.
|
|
34
|
+
* @param req - the route request being decided.
|
|
35
|
+
* @returns candidate lines followed by the session facts and instructions.
|
|
36
|
+
*/
|
|
37
|
+
export declare function buildRouteContext(req: RouteRequest): string;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** How the incumbent candidate is marked inside a decision prompt. */
|
|
2
|
+
export const CURRENT_MODEL_MARK = '[current model — keeping it preserves the prompt cache]';
|
|
3
|
+
/**
|
|
4
|
+
* Render one candidate line, marking the session's incumbent model.
|
|
5
|
+
* @param candidate - one pool candidate.
|
|
6
|
+
* @returns `name: description`, plus the incumbent mark when the candidate is current.
|
|
7
|
+
*/
|
|
8
|
+
export function renderCandidateLine(candidate) {
|
|
9
|
+
const mark = candidate.current ? ` ${CURRENT_MODEL_MARK}` : '';
|
|
10
|
+
return `${candidate.name}: ${candidate.description}${mark}`;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Render the session facts and the policy instructions of one decision.
|
|
14
|
+
* @param state - cache-affinity facts, when the caller supplied any.
|
|
15
|
+
* @param instructions - policy instructions, when the caller supplied any.
|
|
16
|
+
* @returns one line per fact; an empty array when there is nothing to say.
|
|
17
|
+
*/
|
|
18
|
+
export function renderRouteStateLines(state, instructions) {
|
|
19
|
+
const lines = [];
|
|
20
|
+
if (state?.currentModel)
|
|
21
|
+
lines.push(`current physical model: ${state.currentModel}`);
|
|
22
|
+
if (typeof state?.contextTokens === 'number' || typeof state?.contextChars === 'number') {
|
|
23
|
+
const tokens = typeof state?.contextTokens === 'number' ? state.contextTokens : 0;
|
|
24
|
+
const chars = typeof state?.contextChars === 'number' ? state.contextChars : 0;
|
|
25
|
+
lines.push(`accumulated session context: about ${String(tokens)} tokens (${String(chars)} characters)`);
|
|
26
|
+
}
|
|
27
|
+
const instruction = instructions?.trim();
|
|
28
|
+
if (instruction)
|
|
29
|
+
lines.push(instruction);
|
|
30
|
+
return lines;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Build the context block one System 1 route decision receives.
|
|
34
|
+
* @param req - the route request being decided.
|
|
35
|
+
* @returns candidate lines followed by the session facts and instructions.
|
|
36
|
+
*/
|
|
37
|
+
export function buildRouteContext(req) {
|
|
38
|
+
return [...req.candidates.map(renderCandidateLine), ...renderRouteStateLines(req.state, req.instructions)]
|
|
39
|
+
.filter((line) => line.length > 0)
|
|
40
|
+
.join('\n');
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=route-prompt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"route-prompt.js","sourceRoot":"","sources":["../../src/backend/route-prompt.ts"],"names":[],"mappings":"AAiBA,sEAAsE;AACtE,MAAM,CAAC,MAAM,kBAAkB,GAAG,yDAAyD,CAAC;AAE5F;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,SAA6B;IAC/D,MAAM,IAAI,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,kBAAkB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IAC/D,OAAO,GAAG,SAAS,CAAC,IAAI,KAAK,SAAS,CAAC,WAAW,GAAG,IAAI,EAAE,CAAC;AAC9D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CACnC,KAAoC,EACpC,YAAgC;IAEhC,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,KAAK,EAAE,YAAY;QAAE,KAAK,CAAC,IAAI,CAAC,2BAA2B,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC;IAErF,IAAI,OAAO,KAAK,EAAE,aAAa,KAAK,QAAQ,IAAI,OAAO,KAAK,EAAE,YAAY,KAAK,QAAQ,EAAE,CAAC;QACxF,MAAM,MAAM,GAAG,OAAO,KAAK,EAAE,aAAa,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC;QAClF,MAAM,KAAK,GAAG,OAAO,KAAK,EAAE,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/E,KAAK,CAAC,IAAI,CAAC,sCAAsC,MAAM,CAAC,MAAM,CAAC,YAAY,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IAC1G,CAAC;IAED,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,EAAE,CAAC;IACzC,IAAI,WAAW;QAAE,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACzC,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAiB;IACjD,OAAO,CAAC,GAAG,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,mBAAmB,CAAC,EAAE,GAAG,qBAAqB,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,YAAY,CAAC,CAAC;SACvG,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;SACjC,IAAI,CAAC,IAAI,CAAC,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Prompt rendering for one System 1 route decision.\n *\n * The affinity facts ({@link RouteRequest.state}) and the policy instructions\n * ({@link RouteRequest.instructions}) are part of the decision *prompt*, not of\n * the decision *result*: a backend that builds a text prompt (the logits\n * backend, and the HTTP body of the Jev gateway) renders them with these pure\n * helpers, so what the model reads is unit-testable without a network call.\n *\n * Rendering one request with no state and no instructions reproduces the\n * historical `name: description` context block byte for byte, so an unchanged\n * caller sees an unchanged prompt.\n *\n * @module harness-reflex/backend/route-prompt\n */\nimport type { RouteCandidateItem, RouteRequest, RouteRequestState } from './types.js';\n\n/** How the incumbent candidate is marked inside a decision prompt. */\nexport const CURRENT_MODEL_MARK = '[current model — keeping it preserves the prompt cache]';\n\n/**\n * Render one candidate line, marking the session's incumbent model.\n * @param candidate - one pool candidate.\n * @returns `name: description`, plus the incumbent mark when the candidate is current.\n */\nexport function renderCandidateLine(candidate: RouteCandidateItem): string {\n const mark = candidate.current ? ` ${CURRENT_MODEL_MARK}` : '';\n return `${candidate.name}: ${candidate.description}${mark}`;\n}\n\n/**\n * Render the session facts and the policy instructions of one decision.\n * @param state - cache-affinity facts, when the caller supplied any.\n * @param instructions - policy instructions, when the caller supplied any.\n * @returns one line per fact; an empty array when there is nothing to say.\n */\nexport function renderRouteStateLines(\n state: RouteRequestState | undefined,\n instructions: string | undefined\n): string[] {\n const lines: string[] = [];\n if (state?.currentModel) lines.push(`current physical model: ${state.currentModel}`);\n\n if (typeof state?.contextTokens === 'number' || typeof state?.contextChars === 'number') {\n const tokens = typeof state?.contextTokens === 'number' ? state.contextTokens : 0;\n const chars = typeof state?.contextChars === 'number' ? state.contextChars : 0;\n lines.push(`accumulated session context: about ${String(tokens)} tokens (${String(chars)} characters)`);\n }\n\n const instruction = instructions?.trim();\n if (instruction) lines.push(instruction);\n return lines;\n}\n\n/**\n * Build the context block one System 1 route decision receives.\n * @param req - the route request being decided.\n * @returns candidate lines followed by the session facts and instructions.\n */\nexport function buildRouteContext(req: RouteRequest): string {\n return [...req.candidates.map(renderCandidateLine), ...renderRouteStateLines(req.state, req.instructions)]\n .filter((line) => line.length > 0)\n .join('\\n');\n}\n"]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { DecisionBackend, ChoiceRequest, ChoiceResponse, GateRequest, GateResponse, PruneRequest, PruneResponse, StagnationCheckRequest, StagnationCheckResponse, RouteRequest, RouteResponse } from './types.js';
|
|
2
|
+
export interface SimpleJevConfig {
|
|
3
|
+
vllmBaseUrl?: string;
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
model?: string;
|
|
6
|
+
timeoutMs?: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Logits-based System One Provider (Zero-RLCD, Next-Token Logits Scoring via vLLM / OpenAI API)
|
|
10
|
+
*
|
|
11
|
+
* Implements System One decision API on top of standard open LLM weights (e.g. Qwen2.5 / DeepSeek)
|
|
12
|
+
* using next-token logprobs with max_tokens: 1.
|
|
13
|
+
*/
|
|
14
|
+
export declare class LogitsSystemOneBackend implements DecisionBackend {
|
|
15
|
+
readonly name = "system-one-logits";
|
|
16
|
+
readonly model: string;
|
|
17
|
+
private readonly baseUrl;
|
|
18
|
+
private readonly apiKey;
|
|
19
|
+
private readonly timeoutMs;
|
|
20
|
+
constructor(config?: SimpleJevConfig);
|
|
21
|
+
/**
|
|
22
|
+
* Request next-token logprobs from vLLM /v1/completions
|
|
23
|
+
*/
|
|
24
|
+
private getNextTokenLogprobs;
|
|
25
|
+
/**
|
|
26
|
+
* Normalizes logprobs across target token labels via Softmax
|
|
27
|
+
*/
|
|
28
|
+
private computeNormalizedProbabilities;
|
|
29
|
+
choice(req: ChoiceRequest): Promise<ChoiceResponse>;
|
|
30
|
+
gate(req: GateRequest): Promise<GateResponse>;
|
|
31
|
+
prune(req: PruneRequest): Promise<PruneResponse>;
|
|
32
|
+
checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse>;
|
|
33
|
+
route(req: RouteRequest): Promise<RouteResponse>;
|
|
34
|
+
}
|
|
35
|
+
export declare const SimpleJevDecisionBackend: typeof LogitsSystemOneBackend;
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { buildRouteContext } from './route-prompt.js';
|
|
2
|
+
/**
|
|
3
|
+
* Logits-based System One Provider (Zero-RLCD, Next-Token Logits Scoring via vLLM / OpenAI API)
|
|
4
|
+
*
|
|
5
|
+
* Implements System One decision API on top of standard open LLM weights (e.g. Qwen2.5 / DeepSeek)
|
|
6
|
+
* using next-token logprobs with max_tokens: 1.
|
|
7
|
+
*/
|
|
8
|
+
export class LogitsSystemOneBackend {
|
|
9
|
+
name = 'system-one-logits';
|
|
10
|
+
model;
|
|
11
|
+
baseUrl;
|
|
12
|
+
apiKey;
|
|
13
|
+
timeoutMs;
|
|
14
|
+
constructor(config) {
|
|
15
|
+
this.baseUrl = (config?.vllmBaseUrl ||
|
|
16
|
+
process.env.SYSTEM_ONE_BASE_URL ||
|
|
17
|
+
process.env.VLLM_BASE_URL ||
|
|
18
|
+
process.env.OPENAI_BASE_URL ||
|
|
19
|
+
'http://localhost:8000').replace(/\/$/, '');
|
|
20
|
+
this.apiKey =
|
|
21
|
+
config?.apiKey ||
|
|
22
|
+
process.env.SYSTEM_ONE_API_KEY ||
|
|
23
|
+
process.env.VLLM_API_KEY ||
|
|
24
|
+
process.env.OPENAI_API_KEY ||
|
|
25
|
+
'dummy';
|
|
26
|
+
this.model =
|
|
27
|
+
config?.model ||
|
|
28
|
+
process.env.SYSTEM_ONE_MODEL ||
|
|
29
|
+
process.env.VLLM_MODEL ||
|
|
30
|
+
'Qwen/Qwen2.5-7B-Instruct';
|
|
31
|
+
this.timeoutMs = config?.timeoutMs || 8000;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Request next-token logprobs from vLLM /v1/completions
|
|
35
|
+
*/
|
|
36
|
+
async getNextTokenLogprobs(prompt, topLogprobs = 20) {
|
|
37
|
+
const controller = new AbortController();
|
|
38
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
39
|
+
try {
|
|
40
|
+
const resp = await fetch(`${this.baseUrl}/v1/completions`, {
|
|
41
|
+
method: 'POST',
|
|
42
|
+
headers: {
|
|
43
|
+
'Content-Type': 'application/json',
|
|
44
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
45
|
+
},
|
|
46
|
+
body: JSON.stringify({
|
|
47
|
+
model: this.model,
|
|
48
|
+
prompt,
|
|
49
|
+
max_tokens: 1,
|
|
50
|
+
temperature: 0.0,
|
|
51
|
+
logprobs: topLogprobs
|
|
52
|
+
}),
|
|
53
|
+
signal: controller.signal
|
|
54
|
+
});
|
|
55
|
+
if (!resp.ok) {
|
|
56
|
+
throw new Error(`vLLM endpoint error: ${resp.status} ${resp.statusText}`);
|
|
57
|
+
}
|
|
58
|
+
const data = await resp.json();
|
|
59
|
+
const firstChoice = data?.choices?.[0];
|
|
60
|
+
const logprobsObj = firstChoice?.logprobs?.top_logprobs?.[0] || {};
|
|
61
|
+
return logprobsObj;
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Normalizes logprobs across target token labels via Softmax
|
|
69
|
+
*/
|
|
70
|
+
computeNormalizedProbabilities(logprobsMap, labels) {
|
|
71
|
+
// Extract logprobs for each label (accounting for leading spaces)
|
|
72
|
+
const logValues = labels.map((label) => {
|
|
73
|
+
let maxLog = -Infinity;
|
|
74
|
+
for (const [token, logp] of Object.entries(logprobsMap)) {
|
|
75
|
+
if (token.trim().toLowerCase() === label.trim().toLowerCase()) {
|
|
76
|
+
if (logp > maxLog)
|
|
77
|
+
maxLog = logp;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return maxLog === -Infinity ? -20 : maxLog; // baseline floor for unseen tokens
|
|
81
|
+
});
|
|
82
|
+
const maxLogVal = Math.max(...logValues);
|
|
83
|
+
const expValues = logValues.map((v) => Math.exp(v - maxLogVal));
|
|
84
|
+
const sumExp = expValues.reduce((a, b) => a + b, 0);
|
|
85
|
+
return labels.map((label, idx) => ({
|
|
86
|
+
label,
|
|
87
|
+
probability: Number((expValues[idx] / sumExp).toFixed(4))
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
async choice(req) {
|
|
91
|
+
const start = performance.now();
|
|
92
|
+
const optionsLetters = req.options.map((_, i) => String.fromCharCode(65 + i)); // A, B, C...
|
|
93
|
+
const prompt = `Context: ${req.context || 'None'}
|
|
94
|
+
Question: ${req.question}
|
|
95
|
+
Options:
|
|
96
|
+
${req.options.map((opt, i) => `${optionsLetters[i]}. ${opt}`).join('\n')}
|
|
97
|
+
|
|
98
|
+
Answer with the single letter of the best option:`;
|
|
99
|
+
try {
|
|
100
|
+
const topLogprobs = await this.getNextTokenLogprobs(prompt, 20);
|
|
101
|
+
const probabilities = this.computeNormalizedProbabilities(topLogprobs, optionsLetters);
|
|
102
|
+
const mappedOptions = req.options.map((opt, i) => ({
|
|
103
|
+
label: opt,
|
|
104
|
+
probability: probabilities[i].probability
|
|
105
|
+
}));
|
|
106
|
+
mappedOptions.sort((a, b) => b.probability - a.probability);
|
|
107
|
+
return {
|
|
108
|
+
options: mappedOptions,
|
|
109
|
+
bestOption: mappedOptions[0].label,
|
|
110
|
+
confidence: mappedOptions[0].probability,
|
|
111
|
+
uncalibrated: true,
|
|
112
|
+
latencyMs: Math.round(performance.now() - start)
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
throw new Error(`[SimpleJevBackend.choice] Failed: ${err.message}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async gate(req) {
|
|
120
|
+
const start = performance.now();
|
|
121
|
+
const results = [];
|
|
122
|
+
let allPassed = true;
|
|
123
|
+
let needsEscalation = false;
|
|
124
|
+
try {
|
|
125
|
+
for (const assertion of req.assertions) {
|
|
126
|
+
const prompt = `Evidence:
|
|
127
|
+
"""
|
|
128
|
+
${req.evidence.slice(0, 3000)}
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
Statement: "${assertion.statement}"
|
|
132
|
+
|
|
133
|
+
Is this statement strictly verified by the evidence?
|
|
134
|
+
Options:
|
|
135
|
+
A. Yes (Verified)
|
|
136
|
+
B. No (Contradicted or False)
|
|
137
|
+
C. Unknown (Not addressed in evidence)
|
|
138
|
+
|
|
139
|
+
Best Answer (A, B, or C):`;
|
|
140
|
+
const logprobs = await this.getNextTokenLogprobs(prompt, 10);
|
|
141
|
+
const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B', 'C']);
|
|
142
|
+
const top = probs.sort((a, b) => b.probability - a.probability)[0];
|
|
143
|
+
let outcome = 'not_addressed';
|
|
144
|
+
if (top.label === 'A')
|
|
145
|
+
outcome = 'verified';
|
|
146
|
+
else if (top.label === 'B')
|
|
147
|
+
outcome = 'contradicted';
|
|
148
|
+
else
|
|
149
|
+
outcome = 'not_addressed';
|
|
150
|
+
if (outcome !== 'verified') {
|
|
151
|
+
allPassed = false;
|
|
152
|
+
}
|
|
153
|
+
results.push({
|
|
154
|
+
statement: assertion.statement,
|
|
155
|
+
outcome,
|
|
156
|
+
confidence: top.probability,
|
|
157
|
+
explanation: `Classified via token logits: P(${top.label}) = ${top.probability}`
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
passed: allPassed,
|
|
162
|
+
results,
|
|
163
|
+
needsEscalation,
|
|
164
|
+
latencyMs: Math.round(performance.now() - start)
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
// Fail-closed to escalate
|
|
169
|
+
return {
|
|
170
|
+
passed: false,
|
|
171
|
+
needsEscalation: true,
|
|
172
|
+
results: req.assertions.map((a) => ({
|
|
173
|
+
statement: a.statement,
|
|
174
|
+
outcome: 'escalate',
|
|
175
|
+
confidence: 0,
|
|
176
|
+
explanation: `SimpleJev backend failed: ${err.message}. Fail-closed escalation.`
|
|
177
|
+
})),
|
|
178
|
+
latencyMs: Math.round(performance.now() - start)
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async prune(req) {
|
|
183
|
+
const start = performance.now();
|
|
184
|
+
// In Simple-Jev, line scoring can be done by heuristic filter + teacher-forcing scoring
|
|
185
|
+
// Here we provide high-throughput line extraction
|
|
186
|
+
const raw = req.rawOutput;
|
|
187
|
+
const lines = raw.split('\n');
|
|
188
|
+
const intentLower = req.intent.toLowerCase();
|
|
189
|
+
const selectedLines = lines.filter((line) => {
|
|
190
|
+
const lower = line.toLowerCase();
|
|
191
|
+
if (lower.includes('error') || lower.includes('fail') || lower.includes('warning'))
|
|
192
|
+
return true;
|
|
193
|
+
if (lower.includes('passed') || lower.includes('complete') || lower.includes('status'))
|
|
194
|
+
return true;
|
|
195
|
+
return intentLower.split(/\s+/).some((term) => term.length > 3 && lower.includes(term));
|
|
196
|
+
});
|
|
197
|
+
const prunedOutput = selectedLines.length > 0 ? selectedLines.join('\n') : lines.slice(0, 30).join('\n');
|
|
198
|
+
const originalChars = raw.length;
|
|
199
|
+
const prunedChars = prunedOutput.length;
|
|
200
|
+
const reduction = originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0;
|
|
201
|
+
const tokensSaved = Math.max(0, Math.ceil((originalChars - prunedChars) / 4));
|
|
202
|
+
return {
|
|
203
|
+
processedOutput: req.shadowMode ? raw : prunedOutput,
|
|
204
|
+
originalChars,
|
|
205
|
+
prunedChars,
|
|
206
|
+
estimatedTokensSaved: tokensSaved,
|
|
207
|
+
reductionPercentage: reduction,
|
|
208
|
+
shadow: !!req.shadowMode,
|
|
209
|
+
latencyMs: Math.round(performance.now() - start)
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
async checkStagnation(req) {
|
|
213
|
+
const start = performance.now();
|
|
214
|
+
const history = req.history || [];
|
|
215
|
+
if (history.length < 3) {
|
|
216
|
+
return {
|
|
217
|
+
isStuck: false,
|
|
218
|
+
confidence: 0.9,
|
|
219
|
+
diagnosis: 'Action history short.',
|
|
220
|
+
latencyMs: Math.round(performance.now() - start)
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
const summary = history.slice(-5).map((h, i) => `${i + 1}. Tool: ${h.tool} | Input: ${h.input.slice(0, 80)} | Output: ${(h.output || h.error || '').slice(0, 80)}`).join('\n');
|
|
224
|
+
const prompt = `Inspect this recent agent execution trajectory:
|
|
225
|
+
${summary}
|
|
226
|
+
|
|
227
|
+
Is the agent stuck in an unproductive loop (repeating failing actions or oscillating without progress)?
|
|
228
|
+
Options:
|
|
229
|
+
A. Yes, stuck
|
|
230
|
+
B. No, making progress
|
|
231
|
+
|
|
232
|
+
Answer (A or B):`;
|
|
233
|
+
try {
|
|
234
|
+
const logprobs = await this.getNextTokenLogprobs(prompt, 5);
|
|
235
|
+
const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B']);
|
|
236
|
+
const aProb = probs.find((p) => p.label === 'A')?.probability ?? 0;
|
|
237
|
+
const isStuck = aProb > 0.6;
|
|
238
|
+
return {
|
|
239
|
+
isStuck,
|
|
240
|
+
patternType: isStuck ? 'repetition' : 'none',
|
|
241
|
+
confidence: probs[0].probability,
|
|
242
|
+
diagnosis: isStuck ? 'Logits classified execution trajectory as unproductive repeating loop.' : 'Trajectory classified as progressive.',
|
|
243
|
+
recommendedIntervention: isStuck ? 'Stop repeating this command. Change approach or review inputs.' : undefined,
|
|
244
|
+
latencyMs: Math.round(performance.now() - start)
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
catch (err) {
|
|
248
|
+
return {
|
|
249
|
+
isStuck: false,
|
|
250
|
+
confidence: 0.5,
|
|
251
|
+
diagnosis: `SimpleJev stagnation check failed: ${err.message}`,
|
|
252
|
+
latencyMs: Math.round(performance.now() - start)
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
async route(req) {
|
|
257
|
+
const start = performance.now();
|
|
258
|
+
const options = req.candidates.map((c) => c.name);
|
|
259
|
+
const choiceRes = await this.choice({
|
|
260
|
+
question: `Which tool or skill is best suited to achieve the goal: "${req.goal}"?`,
|
|
261
|
+
options,
|
|
262
|
+
context: buildRouteContext(req)
|
|
263
|
+
});
|
|
264
|
+
return {
|
|
265
|
+
rankedCandidates: choiceRes.options.map((o) => ({ name: o.label, score: o.probability })),
|
|
266
|
+
bestCandidate: choiceRes.bestOption,
|
|
267
|
+
latencyMs: Math.round(performance.now() - start)
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
export const SimpleJevDecisionBackend = LogitsSystemOneBackend;
|
|
272
|
+
//# sourceMappingURL=simple-jev.js.map
|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,CAAC,GAAG,CAAC;SAChC,CAAC,CAAC;QAEH,OAAO;YACL,gBAAgB,EAAE,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;YACzF,aAAa,EAAE,SAAS,CAAC,UAAU;YACnC,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC;SACjD,CAAC;IACJ,CAAC;CACF;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,sBAAsB,CAAC","sourcesContent":["import {\n DecisionBackend,\n ChoiceRequest,\n ChoiceResponse,\n GateRequest,\n GateResponse,\n PruneRequest,\n PruneResponse,\n StagnationCheckRequest,\n StagnationCheckResponse,\n RouteRequest,\n RouteResponse\n} from './types.js';\nimport { buildRouteContext } from './route-prompt.js';\n\nexport interface SimpleJevConfig {\n vllmBaseUrl?: string;\n apiKey?: string;\n model?: string;\n timeoutMs?: number;\n}\n\n/**\n * Logits-based System One Provider (Zero-RLCD, Next-Token Logits Scoring via vLLM / OpenAI API)\n *\n * Implements System One decision API on top of standard open LLM weights (e.g. Qwen2.5 / DeepSeek)\n * using next-token logprobs with max_tokens: 1.\n */\nexport class LogitsSystemOneBackend implements DecisionBackend {\n readonly name = 'system-one-logits';\n readonly model: string;\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n\n constructor(config?: SimpleJevConfig) {\n this.baseUrl = (\n config?.vllmBaseUrl ||\n process.env.SYSTEM_ONE_BASE_URL ||\n process.env.VLLM_BASE_URL ||\n process.env.OPENAI_BASE_URL ||\n 'http://localhost:8000'\n ).replace(/\\/$/, '');\n this.apiKey =\n config?.apiKey ||\n process.env.SYSTEM_ONE_API_KEY ||\n process.env.VLLM_API_KEY ||\n process.env.OPENAI_API_KEY ||\n 'dummy';\n this.model =\n config?.model ||\n process.env.SYSTEM_ONE_MODEL ||\n process.env.VLLM_MODEL ||\n 'Qwen/Qwen2.5-7B-Instruct';\n this.timeoutMs = config?.timeoutMs || 8000;\n }\n\n /**\n * Request next-token logprobs from vLLM /v1/completions\n */\n private async getNextTokenLogprobs(prompt: string, topLogprobs: number = 20): Promise<Record<string, number>> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const resp = await fetch(`${this.baseUrl}/v1/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.apiKey}`\n },\n body: JSON.stringify({\n model: this.model,\n prompt,\n max_tokens: 1,\n temperature: 0.0,\n logprobs: topLogprobs\n }),\n signal: controller.signal\n });\n\n if (!resp.ok) {\n throw new Error(`vLLM endpoint error: ${resp.status} ${resp.statusText}`);\n }\n\n const data = await resp.json() as any;\n const firstChoice = data?.choices?.[0];\n const logprobsObj = firstChoice?.logprobs?.top_logprobs?.[0] || {};\n return logprobsObj;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Normalizes logprobs across target token labels via Softmax\n */\n private computeNormalizedProbabilities(\n logprobsMap: Record<string, number>,\n labels: string[]\n ): Array<{ label: string; probability: number }> {\n // Extract logprobs for each label (accounting for leading spaces)\n const logValues = labels.map((label) => {\n let maxLog = -Infinity;\n for (const [token, logp] of Object.entries(logprobsMap)) {\n if (token.trim().toLowerCase() === label.trim().toLowerCase()) {\n if (logp > maxLog) maxLog = logp;\n }\n }\n return maxLog === -Infinity ? -20 : maxLog; // baseline floor for unseen tokens\n });\n\n const maxLogVal = Math.max(...logValues);\n const expValues = logValues.map((v) => Math.exp(v - maxLogVal));\n const sumExp = expValues.reduce((a, b) => a + b, 0);\n\n return labels.map((label, idx) => ({\n label,\n probability: Number((expValues[idx] / sumExp).toFixed(4))\n }));\n }\n\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n const optionsLetters = req.options.map((_, i) => String.fromCharCode(65 + i)); // A, B, C...\n\n const prompt = `Context: ${req.context || 'None'}\nQuestion: ${req.question}\nOptions:\n${req.options.map((opt, i) => `${optionsLetters[i]}. ${opt}`).join('\\n')}\n\nAnswer with the single letter of the best option:`;\n\n try {\n const topLogprobs = await this.getNextTokenLogprobs(prompt, 20);\n const probabilities = this.computeNormalizedProbabilities(topLogprobs, optionsLetters);\n\n const mappedOptions = req.options.map((opt, i) => ({\n label: opt,\n probability: probabilities[i].probability\n }));\n\n mappedOptions.sort((a, b) => b.probability - a.probability);\n\n return {\n options: mappedOptions,\n bestOption: mappedOptions[0].label,\n confidence: mappedOptions[0].probability,\n uncalibrated: true,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n throw new Error(`[SimpleJevBackend.choice] Failed: ${err.message}`);\n }\n }\n\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const results = [];\n let allPassed = true;\n let needsEscalation = false;\n\n try {\n for (const assertion of req.assertions) {\n const prompt = `Evidence:\n\"\"\"\n${req.evidence.slice(0, 3000)}\n\"\"\"\n\nStatement: \"${assertion.statement}\"\n\nIs this statement strictly verified by the evidence?\nOptions:\nA. Yes (Verified)\nB. No (Contradicted or False)\nC. Unknown (Not addressed in evidence)\n\nBest Answer (A, B, or C):`;\n\n const logprobs = await this.getNextTokenLogprobs(prompt, 10);\n const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B', 'C']);\n const top = probs.sort((a, b) => b.probability - a.probability)[0];\n\n let outcome: 'verified' | 'contradicted' | 'not_addressed' | 'escalate' = 'not_addressed';\n if (top.label === 'A') outcome = 'verified';\n else if (top.label === 'B') outcome = 'contradicted';\n else outcome = 'not_addressed';\n\n if (outcome !== 'verified') {\n allPassed = false;\n }\n\n results.push({\n statement: assertion.statement,\n outcome,\n confidence: top.probability,\n explanation: `Classified via token logits: P(${top.label}) = ${top.probability}`\n });\n }\n\n return {\n passed: allPassed,\n results,\n needsEscalation,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n // Fail-closed to escalate\n return {\n passed: false,\n needsEscalation: true,\n results: req.assertions.map((a) => ({\n statement: a.statement,\n outcome: 'escalate' as const,\n confidence: 0,\n explanation: `SimpleJev backend failed: ${err.message}. Fail-closed escalation.`\n })),\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n // In Simple-Jev, line scoring can be done by heuristic filter + teacher-forcing scoring\n // Here we provide high-throughput line extraction\n const raw = req.rawOutput;\n const lines = raw.split('\\n');\n const intentLower = req.intent.toLowerCase();\n\n const selectedLines = lines.filter((line) => {\n const lower = line.toLowerCase();\n if (lower.includes('error') || lower.includes('fail') || lower.includes('warning')) return true;\n if (lower.includes('passed') || lower.includes('complete') || lower.includes('status')) return true;\n return intentLower.split(/\\s+/).some((term) => term.length > 3 && lower.includes(term));\n });\n\n const prunedOutput = selectedLines.length > 0 ? selectedLines.join('\\n') : lines.slice(0, 30).join('\\n');\n const originalChars = raw.length;\n const prunedChars = prunedOutput.length;\n const reduction = originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0;\n const tokensSaved = Math.max(0, Math.ceil((originalChars - prunedChars) / 4));\n\n return {\n processedOutput: req.shadowMode ? raw : prunedOutput,\n originalChars,\n prunedChars,\n estimatedTokensSaved: tokensSaved,\n reductionPercentage: reduction,\n shadow: !!req.shadowMode,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = req.history || [];\n if (history.length < 3) {\n return {\n isStuck: false,\n confidence: 0.9,\n diagnosis: 'Action history short.',\n latencyMs: Math.round(performance.now() - start)\n };\n }\n\n const summary = history.slice(-5).map((h, i) => `${i + 1}. Tool: ${h.tool} | Input: ${h.input.slice(0, 80)} | Output: ${(h.output || h.error || '').slice(0, 80)}`).join('\\n');\n const prompt = `Inspect this recent agent execution trajectory:\n${summary}\n\nIs the agent stuck in an unproductive loop (repeating failing actions or oscillating without progress)?\nOptions:\nA. Yes, stuck\nB. No, making progress\n\nAnswer (A or B):`;\n\n try {\n const logprobs = await this.getNextTokenLogprobs(prompt, 5);\n const probs = this.computeNormalizedProbabilities(logprobs, ['A', 'B']);\n const aProb = probs.find((p) => p.label === 'A')?.probability ?? 0;\n const isStuck = aProb > 0.6;\n\n return {\n isStuck,\n patternType: isStuck ? 'repetition' : 'none',\n confidence: probs[0].probability,\n diagnosis: isStuck ? 'Logits classified execution trajectory as unproductive repeating loop.' : 'Trajectory classified as progressive.',\n recommendedIntervention: isStuck ? 'Stop repeating this command. Change approach or review inputs.' : undefined,\n latencyMs: Math.round(performance.now() - start)\n };\n } catch (err: any) {\n return {\n isStuck: false,\n confidence: 0.5,\n diagnosis: `SimpleJev stagnation check failed: ${err.message}`,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n }\n\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const options = req.candidates.map((c) => c.name);\n const choiceRes = await this.choice({\n question: `Which tool or skill is best suited to achieve the goal: \"${req.goal}\"?`,\n options,\n context: buildRouteContext(req)\n });\n\n return {\n rankedCandidates: choiceRes.options.map((o) => ({ name: o.label, score: o.probability })),\n bestCandidate: choiceRes.bestOption,\n latencyMs: Math.round(performance.now() - start)\n };\n }\n}\n\nexport const SimpleJevDecisionBackend = LogitsSystemOneBackend;\n\n"]}
|