dsh-harness-reflex 0.1.0 → 0.3.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 +20 -6
- package/client.js +3511 -185
- package/dist/attribution.d.ts +266 -0
- package/dist/attribution.js +238 -0
- package/dist/attribution.js.map +1 -0
- package/dist/bridge.d.ts +311 -13
- package/dist/bridge.js +714 -42
- package/dist/bridge.js.map +1 -1
- package/dist/client-bundle.js +4 -1
- package/dist/client-bundle.js.map +1 -1
- package/dist/command.js +10 -0
- package/dist/command.js.map +1 -1
- package/dist/config.d.ts +530 -22
- package/dist/config.js +808 -27
- package/dist/config.js.map +1 -1
- package/dist/delegation-dispatch.d.ts +132 -0
- package/dist/delegation-dispatch.js +186 -0
- package/dist/delegation-dispatch.js.map +1 -0
- package/dist/delegation-health.d.ts +131 -0
- package/dist/delegation-health.js +97 -0
- package/dist/delegation-health.js.map +1 -0
- package/dist/delegation.d.ts +148 -0
- package/dist/delegation.js +186 -0
- package/dist/delegation.js.map +1 -0
- package/dist/effort-delegation.d.ts +144 -0
- package/dist/effort-delegation.js +280 -0
- package/dist/effort-delegation.js.map +1 -0
- package/dist/effort.d.ts +141 -0
- package/dist/effort.js +251 -9
- package/dist/effort.js.map +1 -1
- package/dist/host-patch.d.ts +156 -0
- package/dist/host-patch.js +534 -0
- package/dist/host-patch.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.js +99 -7
- package/dist/index.js.map +1 -1
- package/dist/interventions.d.ts +98 -373
- package/dist/interventions.js +442 -1702
- package/dist/interventions.js.map +1 -1
- package/dist/panel-api.d.ts +328 -4
- package/dist/panel-api.js +322 -15
- package/dist/panel-api.js.map +1 -1
- package/dist/panel-mount.d.ts +81 -22
- package/dist/panel-mount.js +228 -7
- package/dist/panel-mount.js.map +1 -1
- package/dist/routing.d.ts +23 -18
- package/dist/routing.js +471 -153
- package/dist/routing.js.map +1 -1
- package/dist/session-audit.d.ts +70 -0
- package/dist/session-audit.js +73 -0
- package/dist/session-audit.js.map +1 -1
- package/dist/systemone-probe.d.ts +114 -0
- package/dist/systemone-probe.js +383 -0
- package/dist/systemone-probe.js.map +1 -0
- package/dist/testing.d.ts +212 -7
- package/dist/testing.js +333 -27
- package/dist/testing.js.map +1 -1
- package/dist/tools.d.ts +109 -3
- package/dist/tools.js +103 -4
- package/dist/tools.js.map +1 -1
- package/dist/unconfigured-backend.d.ts +72 -0
- package/dist/unconfigured-backend.js +94 -0
- package/dist/unconfigured-backend.js.map +1 -0
- package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
- package/dist/vendor/harness-reflex/backend/factory.js +18 -3
- package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
- package/dist/vendor/harness-reflex/backend/jev.js +11 -4
- package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
- package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
- package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
- package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
- package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
- package/dist/vendor/harness-reflex/core/closing.js +111 -0
- package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
- package/dist/vendor/harness-reflex/core/evidence.js +209 -0
- package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
- package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
- package/dist/vendor/harness-reflex/core/judge.js +251 -0
- package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
- package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
- package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
- package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
- package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
- package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
- package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
- package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
- package/dist/vendor/harness-reflex/core/policy.js +102 -0
- package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
- package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
- package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
- package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
- package/dist/vendor/harness-reflex/core/text.js +66 -0
- package/dist/vendor/harness-reflex/core/text.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
- package/dist/vendor/harness-reflex/ports/audit.js +11 -0
- package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/clock.js +11 -0
- package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
- package/dist/vendor/harness-reflex/ports/decision.js +2 -0
- package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
- package/dist/vendor/harness-reflex/ports/index.js +2 -0
- package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
- package/dist/vendor/harness-reflex/ports/log.js +12 -0
- package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
- package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
- package/dist/vendor/harness-reflex/ports/state.js +13 -0
- package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
- package/package.json +25 -13
|
@@ -2,6 +2,22 @@ import { DecisionBackend, ChoiceRequest, ChoiceResponse, ClaimClassificationRequ
|
|
|
2
2
|
export interface SimpleJevConfig {
|
|
3
3
|
vllmBaseUrl?: string;
|
|
4
4
|
apiKey?: string;
|
|
5
|
+
/**
|
|
6
|
+
* The caller has already resolved the credential (g-059).
|
|
7
|
+
*
|
|
8
|
+
* `true` means `apiKey` is used **verbatim**, including "absent": the
|
|
9
|
+
* environment chain below (`SYSTEM_ONE_API_KEY` -> `VLLM_API_KEY` ->
|
|
10
|
+
* `OPENAI_API_KEY`) and the `dummy` placeholder are all skipped, so a caller
|
|
11
|
+
* that resolved "no key" gets a request with no `Authorization` header instead
|
|
12
|
+
* of one whose credential nobody configured. Default `false` keeps the
|
|
13
|
+
* historical chain for every bare construction.
|
|
14
|
+
*
|
|
15
|
+
* **Plugin-only extension.** The vendored backends are a manual port verified
|
|
16
|
+
* by behaviour (`vendor-contract.test.ts`), not a generated mirror, so this
|
|
17
|
+
* field lives here first; the root adapter does not have it yet and is not
|
|
18
|
+
* changed by this goal. Consolidating the two copies is g-060.
|
|
19
|
+
*/
|
|
20
|
+
apiKeyResolved?: boolean;
|
|
5
21
|
model?: string;
|
|
6
22
|
timeoutMs?: number;
|
|
7
23
|
}
|
|
@@ -17,12 +17,17 @@ export class LogitsSystemOneBackend {
|
|
|
17
17
|
process.env.VLLM_BASE_URL ||
|
|
18
18
|
process.env.OPENAI_BASE_URL ||
|
|
19
19
|
'http://localhost:8000').replace(/\/$/, '');
|
|
20
|
+
// A caller that resolved the credential owns the answer, empty included
|
|
21
|
+
// (g-059); `dummy` in particular must not stand in for a key the caller
|
|
22
|
+
// decided is absent. See `SimpleJevConfig.apiKeyResolved`.
|
|
20
23
|
this.apiKey =
|
|
21
|
-
config?.
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
24
|
+
config?.apiKeyResolved === true
|
|
25
|
+
? config.apiKey ?? ''
|
|
26
|
+
: config?.apiKey ||
|
|
27
|
+
process.env.SYSTEM_ONE_API_KEY ||
|
|
28
|
+
process.env.VLLM_API_KEY ||
|
|
29
|
+
process.env.OPENAI_API_KEY ||
|
|
30
|
+
'dummy';
|
|
26
31
|
this.model =
|
|
27
32
|
config?.model ||
|
|
28
33
|
process.env.SYSTEM_ONE_MODEL ||
|
|
@@ -41,7 +46,13 @@ export class LogitsSystemOneBackend {
|
|
|
41
46
|
method: 'POST',
|
|
42
47
|
headers: {
|
|
43
48
|
'Content-Type': 'application/json',
|
|
44
|
-
Authorization: `Bearer
|
|
49
|
+
// An empty key sends no `Authorization` at all: `Bearer ` with nothing
|
|
50
|
+
// after it is a malformed header, not a credential, and a caller that
|
|
51
|
+
// resolved "no key" (g-059) must produce a request with no key rather
|
|
52
|
+
// than one the backend invented. Every non-empty key -- including the
|
|
53
|
+
// `dummy` placeholder of the environment chain -- is sent unchanged,
|
|
54
|
+
// so the historical behaviour is byte-identical.
|
|
55
|
+
...(this.apiKey.length > 0 ? { Authorization: `Bearer ${this.apiKey}` } : {})
|
|
45
56
|
},
|
|
46
57
|
body: JSON.stringify({
|
|
47
58
|
model: this.model,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simple-jev.js","sourceRoot":"","sources":["../../../../src/vendor/harness-reflex/backend/simple-jev.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAStD;;;;;GAKG;AACH,MAAM,OAAO,sBAAsB;IACxB,IAAI,GAAG,mBAAmB,CAAC;IAC3B,KAAK,CAAS;IACN,OAAO,CAAS;IACh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GAAG,sBAAsB,CAAC","sourcesContent":["import {\n DecisionBackend,\n ChoiceRequest,\n ChoiceResponse,\n ClaimClassificationRequest,\n ClaimClassificationResponse,\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 /**\n * Classify completion claims through the logits backend's choice primitive.\n *\n * This backend has no `postSystemOne` channel to batch score questions over,\n * so each sentence is one next-token choice; the two options mirror the Jev\n * batch's criterion order (index 1 is \"claims completion\").\n */\n async classifyClaims(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse> {\n const start = performance.now();\n const statements = Array.isArray(req.statements) ? req.statements : [];\n const results: ClaimClassificationResponse['results'] = [];\n for (const statement of statements) {\n try {\n const answer = await this.choice({\n question: `Does this sentence claim the task or its work is complete, successful, passing, or finished? A negated outcome is not a claim. Sentence: \"${statement}\"`,\n options: ['not a completion claim', 'completion claim'],\n context: req.intent\n });\n const positive = answer.options.find((option) => option.label === 'completion claim');\n const probability = positive?.probability ?? 0;\n results.push({ statement, isClaim: answer.bestOption === 'completion claim', confidence: probability });\n } catch {\n // Leave an unanswered sentence out; the caller's closing check fails open.\n }\n }\n return { results, latencyMs: Math.round(performance.now() - start) };\n }\n}\n\nexport const SimpleJevDecisionBackend = LogitsSystemOneBackend;\n\n"]}
|
|
1
|
+
{"version":3,"file":"simple-jev.js","sourceRoot":"","sources":["../../../../src/vendor/harness-reflex/backend/simple-jev.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,iBAA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,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,KAAK,kBAAkB,CAAC,CAAC;gBACtF,MAAM,WAAW,GAAG,QAAQ,EAAE,WAAW,IAAI,CAAC,CAAC;gBAC/C,OAAO,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,UAAU,KAAK,kBAAkB,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC,CAAC;YAC1G,CAAC;YAAC,MAAM,CAAC;gBACP,2EAA2E;YAC7E,CAAC;QACH,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,EAAE,CAAC;IACvE,CAAC;CACF;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG,sBAAsB,CAAC","sourcesContent":["import {\n DecisionBackend,\n ChoiceRequest,\n ChoiceResponse,\n ClaimClassificationRequest,\n ClaimClassificationResponse,\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 /**\n * The caller has already resolved the credential (g-059).\n *\n * `true` means `apiKey` is used **verbatim**, including \"absent\": the\n * environment chain below (`SYSTEM_ONE_API_KEY` -> `VLLM_API_KEY` ->\n * `OPENAI_API_KEY`) and the `dummy` placeholder are all skipped, so a caller\n * that resolved \"no key\" gets a request with no `Authorization` header instead\n * of one whose credential nobody configured. Default `false` keeps the\n * historical chain for every bare construction.\n *\n * **Plugin-only extension.** The vendored backends are a manual port verified\n * by behaviour (`vendor-contract.test.ts`), not a generated mirror, so this\n * field lives here first; the root adapter does not have it yet and is not\n * changed by this goal. Consolidating the two copies is g-060.\n */\n apiKeyResolved?: boolean;\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 // A caller that resolved the credential owns the answer, empty included\n // (g-059); `dummy` in particular must not stand in for a key the caller\n // decided is absent. See `SimpleJevConfig.apiKeyResolved`.\n this.apiKey =\n config?.apiKeyResolved === true\n ? config.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 // An empty key sends no `Authorization` at all: `Bearer ` with nothing\n // after it is a malformed header, not a credential, and a caller that\n // resolved \"no key\" (g-059) must produce a request with no key rather\n // than one the backend invented. Every non-empty key -- including the\n // `dummy` placeholder of the environment chain -- is sent unchanged,\n // so the historical behaviour is byte-identical.\n ...(this.apiKey.length > 0 ? { 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 /**\n * Classify completion claims through the logits backend's choice primitive.\n *\n * This backend has no `postSystemOne` channel to batch score questions over,\n * so each sentence is one next-token choice; the two options mirror the Jev\n * batch's criterion order (index 1 is \"claims completion\").\n */\n async classifyClaims(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse> {\n const start = performance.now();\n const statements = Array.isArray(req.statements) ? req.statements : [];\n const results: ClaimClassificationResponse['results'] = [];\n for (const statement of statements) {\n try {\n const answer = await this.choice({\n question: `Does this sentence claim the task or its work is complete, successful, passing, or finished? A negated outcome is not a claim. Sentence: \"${statement}\"`,\n options: ['not a completion claim', 'completion claim'],\n context: req.intent\n });\n const positive = answer.options.find((option) => option.label === 'completion claim');\n const probability = positive?.probability ?? 0;\n results.push({ statement, isClaim: answer.bestOption === 'completion claim', confidence: probability });\n } catch {\n // Leave an unanswered sentence out; the caller's closing check fails open.\n }\n }\n return { results, latencyMs: Math.round(performance.now() - start) };\n }\n}\n\nexport const SimpleJevDecisionBackend = LogitsSystemOneBackend;\n\n"]}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/** Completion claim candidates submitted to one closing judgment. */
|
|
2
|
+
export declare const MAX_CLAIMS = 3;
|
|
3
|
+
/** Minimum sentence length worth classifying as a claim candidate. */
|
|
4
|
+
export declare const MIN_CLAIM_CHARS = 8;
|
|
5
|
+
/** One classified candidate. */
|
|
6
|
+
export interface ClaimClassificationLike {
|
|
7
|
+
readonly statement: string;
|
|
8
|
+
readonly isClaim: boolean;
|
|
9
|
+
readonly confidence: number;
|
|
10
|
+
}
|
|
11
|
+
/** The classification half of a closing judgment's answer. */
|
|
12
|
+
export interface ClaimClassificationResponseLike {
|
|
13
|
+
readonly results: readonly ClaimClassificationLike[];
|
|
14
|
+
readonly latencyMs: number;
|
|
15
|
+
}
|
|
16
|
+
/** One verification result. */
|
|
17
|
+
export interface ClosingResultLike {
|
|
18
|
+
readonly statement: string;
|
|
19
|
+
readonly outcome: string;
|
|
20
|
+
readonly confidence: number;
|
|
21
|
+
}
|
|
22
|
+
/** The verification half of a closing judgment's answer. */
|
|
23
|
+
export interface ClosingVerdictLike {
|
|
24
|
+
readonly passed: boolean;
|
|
25
|
+
readonly results: readonly ClosingResultLike[];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The *candidate* sentences of one turn's assistant text.
|
|
29
|
+
*
|
|
30
|
+
* Deterministic and semantic-free on purpose: splitting, de-duplication, the
|
|
31
|
+
* length floor, and the last-{@link MAX_CLAIMS} bound are all the local work
|
|
32
|
+
* this module may do. Whether a candidate really claims completion is the
|
|
33
|
+
* backend's answer — an English word list would miss a Chinese "全部通过" and
|
|
34
|
+
* read `not complete` as the opposite, so there is none here.
|
|
35
|
+
*
|
|
36
|
+
* @param text - the turn's assistant text.
|
|
37
|
+
* @returns bounded, deduplicated candidates in their original order.
|
|
38
|
+
*/
|
|
39
|
+
export declare function claimCandidates(text: string): string[];
|
|
40
|
+
/**
|
|
41
|
+
* The classified statements that really claim completion, above the confidence
|
|
42
|
+
* floor.
|
|
43
|
+
* @param classification - the backend's answer.
|
|
44
|
+
* @param minConfidence - the resolved claim floor.
|
|
45
|
+
* @returns one assertion per accepted claim.
|
|
46
|
+
*/
|
|
47
|
+
export declare function claimsOf(classification: ClaimClassificationResponseLike, minConfidence: number): Array<{
|
|
48
|
+
statement: string;
|
|
49
|
+
}>;
|
|
50
|
+
/**
|
|
51
|
+
* The contradicted statements, clipped for the corrective message.
|
|
52
|
+
* @param verdict - the verification answer.
|
|
53
|
+
* @returns the statements whose evidence contradicts them.
|
|
54
|
+
*/
|
|
55
|
+
export declare function contradictedOf(verdict: ClosingVerdictLike): string[];
|
|
56
|
+
/**
|
|
57
|
+
* How many verification results could not decide.
|
|
58
|
+
* @param verdict - the verification answer.
|
|
59
|
+
* @returns the `escalate` count.
|
|
60
|
+
*/
|
|
61
|
+
export declare function undecidedOf(verdict: ClosingVerdictLike): number;
|
|
62
|
+
/**
|
|
63
|
+
* The skip reason of a closing judgment that does not object.
|
|
64
|
+
*
|
|
65
|
+
* `escalate` is not a contradiction: it means the gate could not decide — an
|
|
66
|
+
* unavailable backend degrades exactly this way — and steering a turn on an
|
|
67
|
+
* undecided verdict would turn a backend failure into a model-visible objection.
|
|
68
|
+
*
|
|
69
|
+
* @param verdict - the verification answer.
|
|
70
|
+
* @param contradicted - the statements that really contradict.
|
|
71
|
+
* @returns the machine reason to record, or `undefined` when the turn is steered.
|
|
72
|
+
*/
|
|
73
|
+
export declare function closingSkipReason(verdict: ClosingVerdictLike, contradicted: readonly string[]): string | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* Tokens the classification request reasoned about.
|
|
76
|
+
* @param statements - submitted candidates.
|
|
77
|
+
* @returns the estimated token count.
|
|
78
|
+
*/
|
|
79
|
+
export declare function classificationTokens(statements: readonly string[]): number;
|
|
80
|
+
/**
|
|
81
|
+
* Tokens the verification request reasoned about: the classification batch plus
|
|
82
|
+
* the evidence the gate read.
|
|
83
|
+
* @param classificationTokensSpent - tokens of the classification request.
|
|
84
|
+
* @param claims - accepted claims submitted to verification.
|
|
85
|
+
* @param evidence - the assembled evidence text.
|
|
86
|
+
* @returns the estimated token count.
|
|
87
|
+
*/
|
|
88
|
+
export declare function verificationTokens(classificationTokensSpent: number, claims: readonly {
|
|
89
|
+
statement: string;
|
|
90
|
+
}[], evidence: string): number;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Closing-check candidate selection and the closing decision.
|
|
3
|
+
*
|
|
4
|
+
* Two deterministic jobs live here: split a turn's own words into *candidate*
|
|
5
|
+
* completion claims (splitting, de-duplication, the length floor, the trailing
|
|
6
|
+
* cap), and decide what a classification/verification answer means. Whether a
|
|
7
|
+
* sentence really claims completion is a semantic question and is answered by
|
|
8
|
+
* the backend; this module never guesses with a word list.
|
|
9
|
+
*
|
|
10
|
+
* @module core/closing
|
|
11
|
+
*/
|
|
12
|
+
import { clip, estimateTokens } from './text.js';
|
|
13
|
+
/** Completion claim candidates submitted to one closing judgment. */
|
|
14
|
+
export const MAX_CLAIMS = 3;
|
|
15
|
+
/** Minimum sentence length worth classifying as a claim candidate. */
|
|
16
|
+
export const MIN_CLAIM_CHARS = 8;
|
|
17
|
+
/**
|
|
18
|
+
* The *candidate* sentences of one turn's assistant text.
|
|
19
|
+
*
|
|
20
|
+
* Deterministic and semantic-free on purpose: splitting, de-duplication, the
|
|
21
|
+
* length floor, and the last-{@link MAX_CLAIMS} bound are all the local work
|
|
22
|
+
* this module may do. Whether a candidate really claims completion is the
|
|
23
|
+
* backend's answer — an English word list would miss a Chinese "全部通过" and
|
|
24
|
+
* read `not complete` as the opposite, so there is none here.
|
|
25
|
+
*
|
|
26
|
+
* @param text - the turn's assistant text.
|
|
27
|
+
* @returns bounded, deduplicated candidates in their original order.
|
|
28
|
+
*/
|
|
29
|
+
export function claimCandidates(text) {
|
|
30
|
+
const candidates = [];
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
for (const raw of text.split(/(?<=[.!?。!?\n])/)) {
|
|
33
|
+
const sentence = raw.replace(/\s+/g, ' ').trim();
|
|
34
|
+
if (sentence.length < MIN_CLAIM_CHARS)
|
|
35
|
+
continue;
|
|
36
|
+
const statement = clip(sentence, 200);
|
|
37
|
+
if (seen.has(statement))
|
|
38
|
+
continue;
|
|
39
|
+
seen.add(statement);
|
|
40
|
+
candidates.push(statement);
|
|
41
|
+
}
|
|
42
|
+
return candidates.length > MAX_CLAIMS ? candidates.slice(candidates.length - MAX_CLAIMS) : candidates;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The classified statements that really claim completion, above the confidence
|
|
46
|
+
* floor.
|
|
47
|
+
* @param classification - the backend's answer.
|
|
48
|
+
* @param minConfidence - the resolved claim floor.
|
|
49
|
+
* @returns one assertion per accepted claim.
|
|
50
|
+
*/
|
|
51
|
+
export function claimsOf(classification, minConfidence) {
|
|
52
|
+
return classification.results
|
|
53
|
+
.filter((item) => item.isClaim && item.confidence >= minConfidence)
|
|
54
|
+
.map((item) => ({ statement: item.statement }));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The contradicted statements, clipped for the corrective message.
|
|
58
|
+
* @param verdict - the verification answer.
|
|
59
|
+
* @returns the statements whose evidence contradicts them.
|
|
60
|
+
*/
|
|
61
|
+
export function contradictedOf(verdict) {
|
|
62
|
+
return verdict.results
|
|
63
|
+
.filter((item) => item.outcome === 'contradicted')
|
|
64
|
+
.map((item) => clip(item.statement, 160));
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* How many verification results could not decide.
|
|
68
|
+
* @param verdict - the verification answer.
|
|
69
|
+
* @returns the `escalate` count.
|
|
70
|
+
*/
|
|
71
|
+
export function undecidedOf(verdict) {
|
|
72
|
+
return verdict.results.filter((item) => item.outcome === 'escalate').length;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The skip reason of a closing judgment that does not object.
|
|
76
|
+
*
|
|
77
|
+
* `escalate` is not a contradiction: it means the gate could not decide — an
|
|
78
|
+
* unavailable backend degrades exactly this way — and steering a turn on an
|
|
79
|
+
* undecided verdict would turn a backend failure into a model-visible objection.
|
|
80
|
+
*
|
|
81
|
+
* @param verdict - the verification answer.
|
|
82
|
+
* @param contradicted - the statements that really contradict.
|
|
83
|
+
* @returns the machine reason to record, or `undefined` when the turn is steered.
|
|
84
|
+
*/
|
|
85
|
+
export function closingSkipReason(verdict, contradicted) {
|
|
86
|
+
if (contradicted.length > 0)
|
|
87
|
+
return undefined;
|
|
88
|
+
const undecided = undecidedOf(verdict);
|
|
89
|
+
return undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed';
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Tokens the classification request reasoned about.
|
|
93
|
+
* @param statements - submitted candidates.
|
|
94
|
+
* @returns the estimated token count.
|
|
95
|
+
*/
|
|
96
|
+
export function classificationTokens(statements) {
|
|
97
|
+
return statements.reduce((sum, statement) => sum + estimateTokens(statement), 0);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Tokens the verification request reasoned about: the classification batch plus
|
|
101
|
+
* the evidence the gate read.
|
|
102
|
+
* @param classificationTokensSpent - tokens of the classification request.
|
|
103
|
+
* @param claims - accepted claims submitted to verification.
|
|
104
|
+
* @param evidence - the assembled evidence text.
|
|
105
|
+
* @returns the estimated token count.
|
|
106
|
+
*/
|
|
107
|
+
export function verificationTokens(classificationTokensSpent, claims, evidence) {
|
|
108
|
+
return (classificationTokensSpent
|
|
109
|
+
+ claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(evidence)));
|
|
110
|
+
}
|
|
111
|
+
//# sourceMappingURL=closing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"closing.js","sourceRoot":"","sources":["../../../../src/vendor/harness-reflex/core/closing.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjD,qEAAqE;AACrE,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,CAAC;AAC5B,sEAAsE;AACtE,MAAM,CAAC,MAAM,eAA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J,CAAC","sourcesContent":["/**\n * Closing-check candidate selection and the closing decision.\n *\n * Two deterministic jobs live here: split a turn's own words into *candidate*\n * completion claims (splitting, de-duplication, the length floor, the trailing\n * cap), and decide what a classification/verification answer means. Whether a\n * sentence really claims completion is a semantic question and is answered by\n * the backend; this module never guesses with a word list.\n *\n * @module core/closing\n */\nimport { clip, estimateTokens } from './text.js';\n\n/** Completion claim candidates submitted to one closing judgment. */\nexport const MAX_CLAIMS = 3;\n/** Minimum sentence length worth classifying as a claim candidate. */\nexport const MIN_CLAIM_CHARS = 8;\n\n/** One classified candidate. */\nexport interface ClaimClassificationLike {\n readonly statement: string;\n readonly isClaim: boolean;\n readonly confidence: number;\n}\n\n/** The classification half of a closing judgment's answer. */\nexport interface ClaimClassificationResponseLike {\n readonly results: readonly ClaimClassificationLike[];\n readonly latencyMs: number;\n}\n\n/** One verification result. */\nexport interface ClosingResultLike {\n readonly statement: string;\n readonly outcome: string;\n readonly confidence: number;\n}\n\n/** The verification half of a closing judgment's answer. */\nexport interface ClosingVerdictLike {\n readonly passed: boolean;\n readonly results: readonly ClosingResultLike[];\n}\n\n/**\n * The *candidate* sentences of one turn's assistant text.\n *\n * Deterministic and semantic-free on purpose: splitting, de-duplication, the\n * length floor, and the last-{@link MAX_CLAIMS} bound are all the local work\n * this module may do. Whether a candidate really claims completion is the\n * backend's answer — an English word list would miss a Chinese \"全部通过\" and\n * read `not complete` as the opposite, so there is none here.\n *\n * @param text - the turn's assistant text.\n * @returns bounded, deduplicated candidates in their original order.\n */\nexport function claimCandidates(text: string): string[] {\n const candidates: string[] = [];\n const seen = new Set<string>();\n for (const raw of text.split(/(?<=[.!?。!?\\n])/)) {\n const sentence = raw.replace(/\\s+/g, ' ').trim();\n if (sentence.length < MIN_CLAIM_CHARS) continue;\n const statement = clip(sentence, 200);\n if (seen.has(statement)) continue;\n seen.add(statement);\n candidates.push(statement);\n }\n return candidates.length > MAX_CLAIMS ? candidates.slice(candidates.length - MAX_CLAIMS) : candidates;\n}\n\n/**\n * The classified statements that really claim completion, above the confidence\n * floor.\n * @param classification - the backend's answer.\n * @param minConfidence - the resolved claim floor.\n * @returns one assertion per accepted claim.\n */\nexport function claimsOf(\n classification: ClaimClassificationResponseLike,\n minConfidence: number\n): Array<{ statement: string }> {\n return classification.results\n .filter((item) => item.isClaim && item.confidence >= minConfidence)\n .map((item) => ({ statement: item.statement }));\n}\n\n/**\n * The contradicted statements, clipped for the corrective message.\n * @param verdict - the verification answer.\n * @returns the statements whose evidence contradicts them.\n */\nexport function contradictedOf(verdict: ClosingVerdictLike): string[] {\n return verdict.results\n .filter((item) => item.outcome === 'contradicted')\n .map((item) => clip(item.statement, 160));\n}\n\n/**\n * How many verification results could not decide.\n * @param verdict - the verification answer.\n * @returns the `escalate` count.\n */\nexport function undecidedOf(verdict: ClosingVerdictLike): number {\n return verdict.results.filter((item) => item.outcome === 'escalate').length;\n}\n\n/**\n * The skip reason of a closing judgment that does not object.\n *\n * `escalate` is not a contradiction: it means the gate could not decide — an\n * unavailable backend degrades exactly this way — and steering a turn on an\n * undecided verdict would turn a backend failure into a model-visible objection.\n *\n * @param verdict - the verification answer.\n * @param contradicted - the statements that really contradict.\n * @returns the machine reason to record, or `undefined` when the turn is steered.\n */\nexport function closingSkipReason(verdict: ClosingVerdictLike, contradicted: readonly string[]): string | undefined {\n if (contradicted.length > 0) return undefined;\n const undecided = undecidedOf(verdict);\n return undecided > 0 ? 'closing-undecided' : verdict.passed ? 'closing-evidence-consistent' : 'closing-unconfirmed';\n}\n\n/**\n * Tokens the classification request reasoned about.\n * @param statements - submitted candidates.\n * @returns the estimated token count.\n */\nexport function classificationTokens(statements: readonly string[]): number {\n return statements.reduce((sum, statement) => sum + estimateTokens(statement), 0);\n}\n\n/**\n * Tokens the verification request reasoned about: the classification batch plus\n * the evidence the gate read.\n * @param classificationTokensSpent - tokens of the classification request.\n * @param claims - accepted claims submitted to verification.\n * @param evidence - the assembled evidence text.\n * @returns the estimated token count.\n */\nexport function verificationTokens(\n classificationTokensSpent: number,\n claims: readonly { statement: string }[],\n evidence: string\n): number {\n return (\n classificationTokensSpent\n + claims.reduce((sum, item) => sum + estimateTokens(item.statement), estimateTokens(evidence))\n );\n}\n"]}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Evidence candidates and their budget.
|
|
3
|
+
*
|
|
4
|
+
* The closing judgment reads a bounded, prioritised digest of what the turn's
|
|
5
|
+
* tool results said. This module builds those candidates from a *structural*
|
|
6
|
+
* result value — an error flag, a canonical value, a message — and truncates
|
|
7
|
+
* them by priority. It imports no tool-execution or message type from a host.
|
|
8
|
+
*
|
|
9
|
+
* @module core/evidence
|
|
10
|
+
*/
|
|
11
|
+
import type { TextBlockLike } from './text.js';
|
|
12
|
+
/** When one evidence line was retained, for truncation priority. */
|
|
13
|
+
export type EvidencePriority = 'diagnostic' | 'tail' | 'other';
|
|
14
|
+
/** One candidate the closing judgment may read. */
|
|
15
|
+
export interface EvidenceEntry {
|
|
16
|
+
/** Tool that produced the result. */
|
|
17
|
+
tool: string;
|
|
18
|
+
/** Bounded line or summary. */
|
|
19
|
+
text: string;
|
|
20
|
+
/** Truncation priority (lower is safer). */
|
|
21
|
+
priority: EvidencePriority;
|
|
22
|
+
/** Whether the result behind this entry is a failure suspicion. */
|
|
23
|
+
suspect: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** The structural result facts this module reads: no host type required. */
|
|
26
|
+
export interface ToolResultLike {
|
|
27
|
+
readonly isError?: boolean;
|
|
28
|
+
readonly value?: unknown;
|
|
29
|
+
readonly content?: readonly TextBlockLike[];
|
|
30
|
+
readonly error?: {
|
|
31
|
+
readonly message?: string;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Characters of one evidence line. */
|
|
35
|
+
export declare const EVIDENCE_CHARS = 400;
|
|
36
|
+
/** Characters of one result's tail summary. */
|
|
37
|
+
export declare const EVIDENCE_TAIL_CHARS = 240;
|
|
38
|
+
/** Characters of the "other" (non-diagnostic, non-tail) fallback per result. */
|
|
39
|
+
export declare const EVIDENCE_OTHER_CHARS = 120;
|
|
40
|
+
/**
|
|
41
|
+
* Matches the failure markers that make a result a *candidate* for the closing
|
|
42
|
+
* evidence. A hit is a safety floor: the line is kept whatever the budget says.
|
|
43
|
+
* A miss is never a "failure-free" conclusion — the tail summary goes to System
|
|
44
|
+
* One, which decides what the result means.
|
|
45
|
+
*/
|
|
46
|
+
export declare const FAILURE_MARKER: RegExp;
|
|
47
|
+
/**
|
|
48
|
+
* The exit status one tool result carries in its own canonical value.
|
|
49
|
+
*
|
|
50
|
+
* A shell result is *reported*, not errored: a command that exits 1 returns a
|
|
51
|
+
* successful result whose `value.exitCode` is the whole truth. The distinction
|
|
52
|
+
* matters twice over — a correction that never fires because the failure looked
|
|
53
|
+
* like a success, and a closing check that reads a green claim over a red build
|
|
54
|
+
* — so the status is taken from the tool's own structured field whenever the
|
|
55
|
+
* payload exposes one.
|
|
56
|
+
*
|
|
57
|
+
* @param value - the result's canonical value, when it has one.
|
|
58
|
+
* @returns the exit status, or `undefined` when the value is not a shell result.
|
|
59
|
+
*/
|
|
60
|
+
export declare function structuredExitStatus(value: unknown): {
|
|
61
|
+
exitCode: number;
|
|
62
|
+
signal?: string;
|
|
63
|
+
} | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* Whether the text ends in the host's own exit marker for a failed command.
|
|
66
|
+
*
|
|
67
|
+
* The marker is the last line of the model-facing content, so anchoring it to the
|
|
68
|
+
* end of the text keeps an *ordinary* result that merely mentions "exit code 1"
|
|
69
|
+
* in its body from being misread as a failure. This is the fallback for a result
|
|
70
|
+
* that carries no structured value — a virtual tool, a replay from an older
|
|
71
|
+
* record — not a replacement for {@link structuredExitStatus}.
|
|
72
|
+
* @param text - the model-facing text.
|
|
73
|
+
* @returns whether the last marker line reports a non-zero exit or a signal.
|
|
74
|
+
*/
|
|
75
|
+
export declare function exitMarkerFailure(text: string): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Whether one result is a failure the interventions may act on.
|
|
78
|
+
*
|
|
79
|
+
* Three sources, in order of authority: the host's own `isError` flag, the exit
|
|
80
|
+
* status inside the tool's structured value, and the exit marker the host appends
|
|
81
|
+
* to the text. A text heuristic over words like "failed" is deliberately absent:
|
|
82
|
+
* a test log that prints the word is not a failing command.
|
|
83
|
+
*
|
|
84
|
+
* @param result - the execution-local result.
|
|
85
|
+
* @param text - the effective model-facing text of that result.
|
|
86
|
+
* @returns whether the result proves a failure.
|
|
87
|
+
*/
|
|
88
|
+
export declare function failureOf(result: Readonly<ToolResultLike> | undefined, text: string): boolean;
|
|
89
|
+
/**
|
|
90
|
+
* Turn one observed result into closing-evidence candidates.
|
|
91
|
+
*
|
|
92
|
+
* The regex is a prefilter and a floor, never a conclusion: matching lines are
|
|
93
|
+
* kept whatever else happens, and a non-matching result still contributes its
|
|
94
|
+
* tail summary (with the structured facts) to System One. A result is a failure
|
|
95
|
+
* *suspicion* when a structured fact, a marker line, or a broader cue says so;
|
|
96
|
+
* what the result really means is decided by the closing judgment.
|
|
97
|
+
*
|
|
98
|
+
* @param tool - tool name that produced the result.
|
|
99
|
+
* @param result - the execution-local result.
|
|
100
|
+
* @param text - the effective model-facing text.
|
|
101
|
+
* @returns bounded candidates, diagnostics first.
|
|
102
|
+
*/
|
|
103
|
+
export declare function evidenceOf(tool: string, result: Readonly<ToolResultLike> | undefined, text: string): EvidenceEntry[];
|
|
104
|
+
/**
|
|
105
|
+
* Assemble the turn's evidence candidates into one budgeted string.
|
|
106
|
+
*
|
|
107
|
+
* Priority order is diagnostic → tail → other. A diagnostic line is the safety
|
|
108
|
+
* floor and is never dropped; everything else competes for the budget and the
|
|
109
|
+
* dropped characters are reported so the truncation is auditable.
|
|
110
|
+
*
|
|
111
|
+
* @param entries - candidates, oldest first.
|
|
112
|
+
* @param budget - character budget of the assembled text.
|
|
113
|
+
* @returns assembled text plus the kept/dropped character counts.
|
|
114
|
+
*/
|
|
115
|
+
export declare function assembleEvidence(entries: readonly EvidenceEntry[], budget: number): {
|
|
116
|
+
text: string;
|
|
117
|
+
retainedChars: number;
|
|
118
|
+
truncatedChars: number;
|
|
119
|
+
};
|