@kernel.chat/kbot 2.13.1 → 2.14.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 +38 -2
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js.map +1 -1
- package/dist/emergent-swarm.d.ts +41 -0
- package/dist/emergent-swarm.d.ts.map +1 -0
- package/dist/emergent-swarm.js +246 -0
- package/dist/emergent-swarm.js.map +1 -0
- package/dist/entropy-context.d.ts +40 -0
- package/dist/entropy-context.d.ts.map +1 -0
- package/dist/entropy-context.js +144 -0
- package/dist/entropy-context.js.map +1 -0
- package/dist/error-correction.d.ts +37 -0
- package/dist/error-correction.d.ts.map +1 -0
- package/dist/error-correction.js +174 -0
- package/dist/error-correction.js.map +1 -0
- package/dist/godel-limits.d.ts +46 -0
- package/dist/godel-limits.d.ts.map +1 -0
- package/dist/godel-limits.js +251 -0
- package/dist/godel-limits.js.map +1 -0
- package/dist/simulation.d.ts +50 -0
- package/dist/simulation.d.ts.map +1 -0
- package/dist/simulation.js +240 -0
- package/dist/simulation.js.map +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Information-theoretic context management — inspired by Melvin Vopson's
|
|
2
|
+
// research that the universe minimizes informational load. Uses Shannon
|
|
3
|
+
// entropy to measure actual information content of conversation turns.
|
|
4
|
+
import { estimateTokens } from './context-manager.js';
|
|
5
|
+
export const STOPWORDS = new Set([
|
|
6
|
+
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
|
|
7
|
+
'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
|
|
8
|
+
'should', 'may', 'might', 'shall', 'can', 'to', 'of', 'in', 'for',
|
|
9
|
+
'on', 'with', 'at', 'by', 'from', 'as', 'into', 'through', 'during',
|
|
10
|
+
'before', 'after', 'and', 'but', 'or', 'nor', 'not', 'so', 'yet',
|
|
11
|
+
'it', 'its', 'this', 'that', 'these', 'those', 'i', 'you', 'he',
|
|
12
|
+
'she', 'we', 'they', 'me', 'him', 'her', 'us', 'them', 'my', 'your',
|
|
13
|
+
]);
|
|
14
|
+
/** Shannon entropy — bits per character. Higher = more diverse/novel text. */
|
|
15
|
+
export function calculateEntropy(text) {
|
|
16
|
+
if (!text || text.length === 0)
|
|
17
|
+
return 0;
|
|
18
|
+
const freq = new Map();
|
|
19
|
+
const lower = text.toLowerCase();
|
|
20
|
+
for (let i = 0; i < lower.length; i++) {
|
|
21
|
+
const ch = lower[i];
|
|
22
|
+
freq.set(ch, (freq.get(ch) || 0) + 1);
|
|
23
|
+
}
|
|
24
|
+
let entropy = 0;
|
|
25
|
+
const len = lower.length;
|
|
26
|
+
for (const count of freq.values()) {
|
|
27
|
+
const p = count / len;
|
|
28
|
+
if (p > 0)
|
|
29
|
+
entropy -= p * Math.log2(p);
|
|
30
|
+
}
|
|
31
|
+
return entropy;
|
|
32
|
+
}
|
|
33
|
+
/** How much new information a turn adds vs what's already in context. */
|
|
34
|
+
export function calculateSemanticNovelty(turn, previousTurns) {
|
|
35
|
+
if (previousTurns.length === 0)
|
|
36
|
+
return 1.0;
|
|
37
|
+
const turnBigrams = extractBigrams(turn);
|
|
38
|
+
if (turnBigrams.size === 0)
|
|
39
|
+
return 0.5;
|
|
40
|
+
const contextBigrams = new Set();
|
|
41
|
+
for (const prev of previousTurns) {
|
|
42
|
+
for (const bg of extractBigrams(prev)) {
|
|
43
|
+
contextBigrams.add(bg);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (contextBigrams.size === 0)
|
|
47
|
+
return 1.0;
|
|
48
|
+
// Jaccard distance: 1 - (intersection / union)
|
|
49
|
+
let intersection = 0;
|
|
50
|
+
for (const bg of turnBigrams) {
|
|
51
|
+
if (contextBigrams.has(bg))
|
|
52
|
+
intersection++;
|
|
53
|
+
}
|
|
54
|
+
const union = new Set([...turnBigrams, ...contextBigrams]).size;
|
|
55
|
+
return union === 0 ? 0 : 1 - (intersection / union);
|
|
56
|
+
}
|
|
57
|
+
/** Ratio of unique meaningful tokens to total tokens. */
|
|
58
|
+
export function informationDensity(text) {
|
|
59
|
+
const words = text.toLowerCase().split(/\s+/).filter(w => w.length > 0);
|
|
60
|
+
if (words.length === 0)
|
|
61
|
+
return 0;
|
|
62
|
+
const meaningful = words.filter(w => !STOPWORDS.has(w) && w.length > 2);
|
|
63
|
+
const unique = new Set(meaningful);
|
|
64
|
+
return unique.size / words.length;
|
|
65
|
+
}
|
|
66
|
+
function extractBigrams(text) {
|
|
67
|
+
const words = text.toLowerCase().split(/\s+/).filter(w => w.length > 1);
|
|
68
|
+
const bigrams = new Set();
|
|
69
|
+
for (let i = 0; i < words.length - 1; i++) {
|
|
70
|
+
bigrams.add(`${words[i]} ${words[i + 1]}`);
|
|
71
|
+
}
|
|
72
|
+
return bigrams;
|
|
73
|
+
}
|
|
74
|
+
function turnContent(turn) {
|
|
75
|
+
return typeof turn.content === 'string' ? turn.content : JSON.stringify(turn.content);
|
|
76
|
+
}
|
|
77
|
+
export class EntropyScorer {
|
|
78
|
+
/**
|
|
79
|
+
* Composite score formula:
|
|
80
|
+
* 0.4 * novelty + 0.35 * density + 0.25 * normalizedEntropy
|
|
81
|
+
*
|
|
82
|
+
* Novelty weighted highest: redundant info is the biggest waste.
|
|
83
|
+
* Density second: filler text wastes tokens.
|
|
84
|
+
* Raw entropy lowest: can be high for random/noisy text too.
|
|
85
|
+
*/
|
|
86
|
+
scoreTurn(turn, history) {
|
|
87
|
+
const content = turnContent(turn);
|
|
88
|
+
const prevContents = history.map(turnContent);
|
|
89
|
+
const entropy = calculateEntropy(content);
|
|
90
|
+
const novelty = calculateSemanticNovelty(content, prevContents);
|
|
91
|
+
const density = informationDensity(content);
|
|
92
|
+
// Normalize entropy to 0-1 (English text typically 3.5-4.5 bits/char)
|
|
93
|
+
const normalizedEntropy = Math.min(1, entropy / 5);
|
|
94
|
+
const composite = 0.4 * novelty + 0.35 * density + 0.25 * normalizedEntropy;
|
|
95
|
+
return { entropy, novelty, density, composite };
|
|
96
|
+
}
|
|
97
|
+
/** Rank all turns by information value (highest first). */
|
|
98
|
+
rankTurns(turns) {
|
|
99
|
+
const scored = turns.map((turn, i) => {
|
|
100
|
+
const history = turns.slice(0, i);
|
|
101
|
+
return { turn, score: this.scoreTurn(turn, history), rank: 0 };
|
|
102
|
+
});
|
|
103
|
+
scored.sort((a, b) => b.score.composite - a.score.composite);
|
|
104
|
+
scored.forEach((item, i) => item.rank = i + 1);
|
|
105
|
+
return scored;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Keep highest-entropy turns within token budget.
|
|
109
|
+
* Low-entropy turns are summarized or dropped.
|
|
110
|
+
*/
|
|
111
|
+
compress(turns, tokenBudget, keepRecentCount = 4) {
|
|
112
|
+
if (turns.length <= keepRecentCount)
|
|
113
|
+
return turns;
|
|
114
|
+
// Always keep recent turns
|
|
115
|
+
const recent = turns.slice(-keepRecentCount);
|
|
116
|
+
const older = turns.slice(0, -keepRecentCount);
|
|
117
|
+
const recentTokens = recent.reduce((sum, t) => sum + estimateTokens(turnContent(t)), 0);
|
|
118
|
+
const remaining = tokenBudget - recentTokens;
|
|
119
|
+
if (remaining <= 0)
|
|
120
|
+
return recent;
|
|
121
|
+
// Rank older turns by entropy, keep highest-value ones
|
|
122
|
+
const ranked = this.rankTurns(older);
|
|
123
|
+
const kept = [];
|
|
124
|
+
let used = 0;
|
|
125
|
+
for (const item of ranked) {
|
|
126
|
+
const tokens = estimateTokens(turnContent(item.turn));
|
|
127
|
+
if (used + tokens <= remaining) {
|
|
128
|
+
kept.push(item.turn);
|
|
129
|
+
used += tokens;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// Restore chronological order
|
|
133
|
+
const keptSet = new Set(kept);
|
|
134
|
+
const ordered = older.filter(t => keptSet.has(t));
|
|
135
|
+
return [...ordered, ...recent];
|
|
136
|
+
}
|
|
137
|
+
/** Returns true if turn adds < 0.2 novelty — candidate for eviction. */
|
|
138
|
+
shouldEvict(turn, history) {
|
|
139
|
+
const content = turnContent(turn);
|
|
140
|
+
const novelty = calculateSemanticNovelty(content, history.map(turnContent));
|
|
141
|
+
return novelty < 0.2;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=entropy-context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entropy-context.js","sourceRoot":"","sources":["../src/entropy-context.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,wEAAwE;AACxE,uEAAuE;AAEvE,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAgBrD,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC;IAC/B,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO;IACnE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO;IACnE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK;IACjE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ;IACnE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK;IAChE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI;IAC/D,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAA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orType {
|
|
2
|
+
hallucination = "hallucination",
|
|
3
|
+
wrong_tool = "wrong_tool",
|
|
4
|
+
stale_context = "stale_context",
|
|
5
|
+
incomplete = "incomplete",
|
|
6
|
+
off_topic = "off_topic",
|
|
7
|
+
syntax_error = "syntax_error",
|
|
8
|
+
logic_error = "logic_error"
|
|
9
|
+
}
|
|
10
|
+
export interface CorrectionStrategy {
|
|
11
|
+
errorType: ErrorType;
|
|
12
|
+
description: string;
|
|
13
|
+
correctionPrompt: string;
|
|
14
|
+
severity: number;
|
|
15
|
+
}
|
|
16
|
+
export interface ClassificationResult {
|
|
17
|
+
errorType: ErrorType;
|
|
18
|
+
confidence: number;
|
|
19
|
+
evidence: string;
|
|
20
|
+
}
|
|
21
|
+
export interface CorrectionRecord {
|
|
22
|
+
errorType: ErrorType;
|
|
23
|
+
confidence: number;
|
|
24
|
+
evidence: string;
|
|
25
|
+
correctionApplied: string;
|
|
26
|
+
attempt: number;
|
|
27
|
+
}
|
|
28
|
+
export interface ErrorCorrectionResult {
|
|
29
|
+
response: string;
|
|
30
|
+
corrections: CorrectionRecord[];
|
|
31
|
+
retries: number;
|
|
32
|
+
}
|
|
33
|
+
export declare const CORRECTION_STRATEGIES: Record<ErrorType, CorrectionStrategy>;
|
|
34
|
+
export declare function classifyError(query: string, response: string, context?: string): Promise<ClassificationResult | null>;
|
|
35
|
+
export declare function applyCorrection(query: string, response: string, errorType: ErrorType, evidence: string): string;
|
|
36
|
+
export declare function withErrorCorrection(generateFn: (injectedPrompt?: string) => Promise<string>, query: string, context?: string, maxRetries?: number): Promise<ErrorCorrectionResult>;
|
|
37
|
+
//# sourceMappingURL=error-correction.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-correction.d.ts","sourceRoot":"","sources":["../src/error-correction.ts"],"names":[],"mappings":"AAMA,oBAAY,SAAS;IACnB,aAAa,kBAAkB;IAC/B,UAAU,eAAe;IACzB,aAAa,kBAAkB;IAC/B,UAAU,eAA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CA0BhC"}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Error-Correcting Code patterns — inspired by James Gates' discovery of
|
|
2
|
+
// error-correcting codes in string theory. Classifies errors by type and
|
|
3
|
+
// applies targeted corrections instead of blind retry.
|
|
4
|
+
import { loadConfig } from './auth.js';
|
|
5
|
+
export var ErrorType;
|
|
6
|
+
(function (ErrorType) {
|
|
7
|
+
ErrorType["hallucination"] = "hallucination";
|
|
8
|
+
ErrorType["wrong_tool"] = "wrong_tool";
|
|
9
|
+
ErrorType["stale_context"] = "stale_context";
|
|
10
|
+
ErrorType["incomplete"] = "incomplete";
|
|
11
|
+
ErrorType["off_topic"] = "off_topic";
|
|
12
|
+
ErrorType["syntax_error"] = "syntax_error";
|
|
13
|
+
ErrorType["logic_error"] = "logic_error";
|
|
14
|
+
})(ErrorType || (ErrorType = {}));
|
|
15
|
+
export const CORRECTION_STRATEGIES = {
|
|
16
|
+
[ErrorType.hallucination]: {
|
|
17
|
+
errorType: ErrorType.hallucination,
|
|
18
|
+
description: 'Response contains unsupported claims',
|
|
19
|
+
correctionPrompt: 'Your previous response contained claims not supported by the provided context. Stick strictly to what\'s in the conversation and tool results. Do not invent facts, file paths, function names, or behaviors.',
|
|
20
|
+
severity: 4,
|
|
21
|
+
},
|
|
22
|
+
[ErrorType.wrong_tool]: {
|
|
23
|
+
errorType: ErrorType.wrong_tool,
|
|
24
|
+
description: 'Incorrect tool selection',
|
|
25
|
+
correctionPrompt: 'You used an incorrect tool for this task. Reconsider which tool best fits the user\'s request. Re-read the available tools and their descriptions before choosing.',
|
|
26
|
+
severity: 3,
|
|
27
|
+
},
|
|
28
|
+
[ErrorType.stale_context]: {
|
|
29
|
+
errorType: ErrorType.stale_context,
|
|
30
|
+
description: 'Referenced outdated information',
|
|
31
|
+
correctionPrompt: 'Your response referenced outdated information. Focus on the most recent context and tool results. Earlier conversation turns may contain stale state — prioritize the latest data.',
|
|
32
|
+
severity: 3,
|
|
33
|
+
},
|
|
34
|
+
[ErrorType.incomplete]: {
|
|
35
|
+
errorType: ErrorType.incomplete,
|
|
36
|
+
description: 'Response did not address all parts',
|
|
37
|
+
correctionPrompt: 'Your response was incomplete. Address all parts of the user\'s request. Re-read the original message and ensure every question or requirement is covered.',
|
|
38
|
+
severity: 2,
|
|
39
|
+
},
|
|
40
|
+
[ErrorType.off_topic]: {
|
|
41
|
+
errorType: ErrorType.off_topic,
|
|
42
|
+
description: 'Response diverged from the question',
|
|
43
|
+
correctionPrompt: 'Your response diverged from the user\'s question. Re-read the original request and answer directly. Do not add tangential information.',
|
|
44
|
+
severity: 2,
|
|
45
|
+
},
|
|
46
|
+
[ErrorType.syntax_error]: {
|
|
47
|
+
errorType: ErrorType.syntax_error,
|
|
48
|
+
description: 'Code output has syntax errors',
|
|
49
|
+
correctionPrompt: 'Your code output contained syntax errors. Fix the syntax and verify it compiles. Check for missing brackets, semicolons, type annotations, and import statements.',
|
|
50
|
+
severity: 5,
|
|
51
|
+
},
|
|
52
|
+
[ErrorType.logic_error]: {
|
|
53
|
+
errorType: ErrorType.logic_error,
|
|
54
|
+
description: 'Code has logical flaws',
|
|
55
|
+
correctionPrompt: 'Your code has a logical error. Trace through the logic step by step. Check edge cases, off-by-one errors, null handling, and conditional branches.',
|
|
56
|
+
severity: 4,
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
const CLASSIFY_PROMPT = `You are an error classifier for an AI agent's output. Analyze the response and classify any errors found.
|
|
60
|
+
|
|
61
|
+
USER QUERY:
|
|
62
|
+
{query}
|
|
63
|
+
|
|
64
|
+
AGENT RESPONSE:
|
|
65
|
+
{response}
|
|
66
|
+
|
|
67
|
+
{context_section}
|
|
68
|
+
|
|
69
|
+
Classify the primary error (if any). Respond in JSON:
|
|
70
|
+
{"errorType": "hallucination|wrong_tool|stale_context|incomplete|off_topic|syntax_error|logic_error|none", "confidence": 0.0-1.0, "evidence": "brief explanation"}
|
|
71
|
+
|
|
72
|
+
If no error found, use errorType "none" with confidence 1.0.
|
|
73
|
+
Respond ONLY with the JSON object.`;
|
|
74
|
+
export async function classifyError(query, response, context) {
|
|
75
|
+
const config = loadConfig();
|
|
76
|
+
if (!config)
|
|
77
|
+
return null;
|
|
78
|
+
const contextSection = context
|
|
79
|
+
? `CONTEXT PROVIDED:\n${context.slice(0, 2000)}`
|
|
80
|
+
: '';
|
|
81
|
+
const prompt = CLASSIFY_PROMPT
|
|
82
|
+
.replace('{query}', query)
|
|
83
|
+
.replace('{response}', response.slice(0, 3000))
|
|
84
|
+
.replace('{context_section}', contextSection);
|
|
85
|
+
try {
|
|
86
|
+
const text = await callFastModel(config, prompt);
|
|
87
|
+
const match = text.match(/\{[\s\S]*\}/);
|
|
88
|
+
if (!match)
|
|
89
|
+
return null;
|
|
90
|
+
const parsed = JSON.parse(match[0]);
|
|
91
|
+
if (parsed.errorType === 'none')
|
|
92
|
+
return null;
|
|
93
|
+
const errorType = parsed.errorType;
|
|
94
|
+
if (!Object.values(ErrorType).includes(errorType))
|
|
95
|
+
return null;
|
|
96
|
+
return {
|
|
97
|
+
errorType,
|
|
98
|
+
confidence: Math.max(0, Math.min(1, parsed.confidence || 0)),
|
|
99
|
+
evidence: parsed.evidence || '',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export function applyCorrection(query, response, errorType, evidence) {
|
|
107
|
+
const strategy = CORRECTION_STRATEGIES[errorType];
|
|
108
|
+
return [
|
|
109
|
+
`[ERROR CORRECTION — ${strategy.description}]`,
|
|
110
|
+
strategy.correctionPrompt,
|
|
111
|
+
`Evidence of error: ${evidence}`,
|
|
112
|
+
`Original query: ${query}`,
|
|
113
|
+
'Please provide a corrected response.',
|
|
114
|
+
].join('\n');
|
|
115
|
+
}
|
|
116
|
+
export async function withErrorCorrection(generateFn, query, context, maxRetries = 2) {
|
|
117
|
+
const corrections = [];
|
|
118
|
+
let response = await generateFn();
|
|
119
|
+
let retries = 0;
|
|
120
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
121
|
+
const classification = await classifyError(query, response, context);
|
|
122
|
+
if (!classification || classification.confidence < 0.7)
|
|
123
|
+
break;
|
|
124
|
+
const correctionPrompt = applyCorrection(query, response, classification.errorType, classification.evidence);
|
|
125
|
+
corrections.push({
|
|
126
|
+
errorType: classification.errorType,
|
|
127
|
+
confidence: classification.confidence,
|
|
128
|
+
evidence: classification.evidence,
|
|
129
|
+
correctionApplied: CORRECTION_STRATEGIES[classification.errorType].description,
|
|
130
|
+
attempt: attempt + 1,
|
|
131
|
+
});
|
|
132
|
+
response = await generateFn(correctionPrompt);
|
|
133
|
+
retries++;
|
|
134
|
+
}
|
|
135
|
+
return { response, corrections, retries };
|
|
136
|
+
}
|
|
137
|
+
// ── Multi-provider fast model call ──────────────────────────────────
|
|
138
|
+
async function callFastModel(config, prompt) {
|
|
139
|
+
const provider = config.provider || 'anthropic';
|
|
140
|
+
const key = config.apiKey || config.key;
|
|
141
|
+
if (provider === 'anthropic' || provider === 'claude') {
|
|
142
|
+
const res = await fetch('https://api.anthropic.com/v1/messages', {
|
|
143
|
+
method: 'POST',
|
|
144
|
+
headers: {
|
|
145
|
+
'Content-Type': 'application/json',
|
|
146
|
+
'x-api-key': key,
|
|
147
|
+
'anthropic-version': '2023-06-01',
|
|
148
|
+
},
|
|
149
|
+
body: JSON.stringify({
|
|
150
|
+
model: 'claude-haiku-4-5-20251001',
|
|
151
|
+
max_tokens: 256,
|
|
152
|
+
messages: [{ role: 'user', content: prompt }],
|
|
153
|
+
}),
|
|
154
|
+
});
|
|
155
|
+
const data = await res.json();
|
|
156
|
+
return data?.content?.[0]?.text || '';
|
|
157
|
+
}
|
|
158
|
+
if (provider === 'openai') {
|
|
159
|
+
const res = await fetch('https://api.openai.com/v1/chat/completions', {
|
|
160
|
+
method: 'POST',
|
|
161
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
|
|
162
|
+
body: JSON.stringify({
|
|
163
|
+
model: 'gpt-4o-mini',
|
|
164
|
+
max_tokens: 256,
|
|
165
|
+
messages: [{ role: 'user', content: prompt }],
|
|
166
|
+
}),
|
|
167
|
+
});
|
|
168
|
+
const data = await res.json();
|
|
169
|
+
return data?.choices?.[0]?.message?.content || '';
|
|
170
|
+
}
|
|
171
|
+
// Fallback: skip classification for unsupported providers
|
|
172
|
+
return '';
|
|
173
|
+
}
|
|
174
|
+
//# sourceMappingURL=error-correction.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-correction.js","sourceRoot":"","sources":["../src/error-correction.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,yEAAyE;AACzE,uDAAuD;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAEtC,MAAM,CAAN,IAAY,SAQX;AARD,WAAY,SAAS;IACnB,4CAA+B,CAAA;IAC/B,sCAAyB,CAAA;IACzB,4CAA+B,CAAA;IAC/B,sCAAyB,CAAA;IACzB,oCAAuB,CAAA;IACvB,0CAA6B,CAAA;IAC7B,wCAA2B,CAAA;AAC7B,CAAC,EARW,SAAS,KAAT,SAAS,QAQpB;AA6BD,MAAM,CAAC,MAAM,qBAAqB,GAA0C;IAC1E,CAAC,SAAS,CAAC,aAAa,CAAC,EAAE;QACzB,SAAS,EAAE,SAAS,CAAC,aAAa;QAClC,WAAW,EAAE,sCAAsC;QACnD,gBAAgB,EAAE,+MAA+M;QACjO,QAAQ,EAAE,CAAC;KACZ;IACD,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE;QACtB,SAAS,EAAE,SAAS,CAAC,UAAU;QAC/B,WAAW,EAAE,0BAA0B;QACvC,gBAAgB,EAAE,oKAAoK;QACtL,QAAQ,EAAE,CAAC;KACZ;IACD,CAAC,SAAS,CAAC,aAAa,CAAC,EAAE;QACzB,SAAS,EAAE,SAAS,CAAC,aAAa;QAClC,WAAW,EAAE,iCAAiC;QAC9C,gBAAgB,EAAE,o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@
|
|
|
1
|
+
export declare enum LoopPattern {
|
|
2
|
+
tool_repetition = "tool_repetition",
|
|
3
|
+
output_oscillation = "output_oscillation",
|
|
4
|
+
cost_spiral = "cost_spiral",
|
|
5
|
+
context_exhaustion = "context_exhaustion",
|
|
6
|
+
semantic_stagnation = "semantic_stagnation",
|
|
7
|
+
circular_reasoning = "circular_reasoning"
|
|
8
|
+
}
|
|
9
|
+
export interface DecidabilityScore {
|
|
10
|
+
decidable: boolean;
|
|
11
|
+
confidence: number;
|
|
12
|
+
pattern?: LoopPattern;
|
|
13
|
+
evidence: string;
|
|
14
|
+
recommendation: 'continue' | 'simplify' | 'handoff' | 'decompose';
|
|
15
|
+
tokensBurned: number;
|
|
16
|
+
costBurned: number;
|
|
17
|
+
}
|
|
18
|
+
interface Options {
|
|
19
|
+
maxToolRepeats: number;
|
|
20
|
+
maxCostUsd: number;
|
|
21
|
+
maxTokens: number;
|
|
22
|
+
similarityThreshold: number;
|
|
23
|
+
}
|
|
24
|
+
export declare function jaccardSimilarity(a: string, b: string): number;
|
|
25
|
+
export declare function detectOscillation(outputs: string[]): boolean;
|
|
26
|
+
export declare class LoopDetector {
|
|
27
|
+
private toolHistory;
|
|
28
|
+
private outputs;
|
|
29
|
+
private totalCost;
|
|
30
|
+
private costHistory;
|
|
31
|
+
private totalTokens;
|
|
32
|
+
private opts;
|
|
33
|
+
constructor(options?: Partial<Options>);
|
|
34
|
+
recordToolCall(toolName: string, args: string, result: string): void;
|
|
35
|
+
recordOutput(output: string): void;
|
|
36
|
+
recordCost(costUsd: number): void;
|
|
37
|
+
recordTokens(tokens: number): void;
|
|
38
|
+
check(): DecidabilityScore;
|
|
39
|
+
reset(): void;
|
|
40
|
+
private checkToolRepetition;
|
|
41
|
+
private checkCostSpiral;
|
|
42
|
+
private checkSemanticStagnation;
|
|
43
|
+
private checkCircularReasoning;
|
|
44
|
+
}
|
|
45
|
+
export {};
|
|
46
|
+
//# sourceMappingURL=godel-limits.d.ts.map
|
|
@@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