@0perator/operator 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +73 -0
  2. package/dist/auth/client.js +94 -0
  3. package/dist/auth/commands.js +99 -0
  4. package/dist/auth/store.js +99 -0
  5. package/dist/background/index.js +64 -0
  6. package/dist/cli.js +407 -0
  7. package/dist/config/settings.js +85 -0
  8. package/dist/engine/agent.js +232 -0
  9. package/dist/engine/aurora.js +213 -0
  10. package/dist/engine/compaction.js +111 -0
  11. package/dist/engine/contract.js +8 -0
  12. package/dist/engine/messages.js +85 -0
  13. package/dist/engine/router-adapter.js +29 -0
  14. package/dist/engine/selfheal.js +46 -0
  15. package/dist/engine/toolcalls.js +164 -0
  16. package/dist/index.browser.js +22 -0
  17. package/dist/index.js +23 -0
  18. package/dist/mcp/client.js +95 -0
  19. package/dist/mcp/config.js +73 -0
  20. package/dist/mcp/index.js +101 -0
  21. package/dist/mcp/stdio.js +149 -0
  22. package/dist/memory/index.js +0 -0
  23. package/dist/observability/index.js +60 -0
  24. package/dist/permissions/audit.js +50 -0
  25. package/dist/permissions/index.js +48 -0
  26. package/dist/permissions/policy.js +54 -0
  27. package/dist/router/router.js +94 -0
  28. package/dist/session.js +265 -0
  29. package/dist/tools/executor.js +0 -0
  30. package/dist/tools/registry.js +380 -0
  31. package/dist/tools/sandbox.js +90 -0
  32. package/dist/ui/ActivitySpinner.js +48 -0
  33. package/dist/ui/App.js +16 -0
  34. package/dist/ui/AuthScreen.js +17 -0
  35. package/dist/ui/BgPanel.js +24 -0
  36. package/dist/ui/Composer.js +119 -0
  37. package/dist/ui/Header.js +22 -0
  38. package/dist/ui/StatusRule.js +11 -0
  39. package/dist/ui/ThinkingSpinner.js +61 -0
  40. package/dist/ui/ToolStep.js +32 -0
  41. package/dist/ui/Transcript.js +22 -0
  42. package/dist/ui/format.js +6 -0
  43. package/dist/ui/index.js +9 -0
  44. package/dist/ui/types.js +3 -0
  45. package/dist/ui/useInputHistory.js +97 -0
  46. package/dist/update.js +57 -0
  47. package/package.json +47 -0
@@ -0,0 +1,232 @@
1
+ // The agentic loop — SPEC §3, tying together transport (aurora.ts), message shape (messages.ts),
2
+ // text tool-call recovery (toolcalls.ts) and compaction (compaction.ts). Tools and routing are
3
+ // NOT implemented here — this file depends only on the two interfaces below, which the
4
+ // kode-tsi/src/tools/** + kode-tsi/src/router/** lane implements.
5
+ import { chat } from "./aurora.js";
6
+ import { buildMessages } from "./messages.js";
7
+ import { recoverToolCalls } from "./toolcalls.js";
8
+ import { compact, needsCompaction, clampMaxTokens } from "./compaction.js";
9
+ import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
10
+ const MAX_SELF_HEAL_PER_TURN = 3;
11
+ const LOOP_GUARD_LIMIT = 3;
12
+ const MAX_EMPTY_RETRIES = 1; // one nudge on an empty "dud" round before finalizing
13
+ /** Thrown by runTurn when the turn is interrupted via AgentOpts.signal (SPEC §9). One type for hosts to catch. */
14
+ export class TurnAbortedError extends Error {
15
+ constructor() {
16
+ super("turn aborted");
17
+ this.name = "TurnAbortedError";
18
+ }
19
+ }
20
+ function throwIfAborted(signal) {
21
+ if (signal?.aborted)
22
+ throw new TurnAbortedError();
23
+ }
24
+ /**
25
+ * True when `err` is (or happened during) an abort. Checking `signal.aborted` first is what makes
26
+ * this robust: once the user aborts, fetch rejects with a DOMException("AbortError") we must NOT
27
+ * mistake for a transport failure to self-heal — so any error inside the aborted window counts.
28
+ */
29
+ function isAbort(err, signal) {
30
+ if (signal?.aborted)
31
+ return true;
32
+ return err instanceof TurnAbortedError || (err instanceof Error && err.name === "AbortError");
33
+ }
34
+ function callSignature(name, args) {
35
+ return `${name}:${JSON.stringify(args)}`;
36
+ }
37
+ function stripScratchpad(content) {
38
+ // Drop scratchpad and any inline reasoning that leaked into content (some chat templates emit
39
+ // <think> in the content channel instead of reasoning_content). An unclosed <think> means the
40
+ // whole tail is reasoning — drop from the tag onward.
41
+ return content
42
+ .replace(/<scratchpad>[\s\S]*?<\/scratchpad>/g, "")
43
+ .replace(/<think>[\s\S]*?<\/think>/g, "")
44
+ .replace(/<think>[\s\S]*$/g, "")
45
+ .trim();
46
+ }
47
+ function parseArgs(raw) {
48
+ if (!raw || raw.trim() === "")
49
+ return { ok: true, args: {} };
50
+ try {
51
+ const parsed = JSON.parse(raw);
52
+ if (typeof parsed === "object" && parsed !== null)
53
+ return { ok: true, args: parsed };
54
+ return { ok: false, error: "arguments did not parse to an object" };
55
+ }
56
+ catch (err) {
57
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
58
+ }
59
+ }
60
+ /**
61
+ * Runs tool_calls (structured or text-recovered) through the executor, honoring the loop
62
+ * guard (SPEC §2: identical (name,args) ≥3× this turn is short-circuited) and reporting the
63
+ * batch via onToolBatch with a real (unrounded) duration.
64
+ */
65
+ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolStart) {
66
+ const pending = [];
67
+ const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
68
+ const parsedArgs = new Map();
69
+ for (const tc of toolCalls) {
70
+ const parsed = parseArgs(tc.function.arguments);
71
+ if (!parsed.ok) {
72
+ preResolved.set(tc.id, `Error: could not parse arguments for tool "${tc.function.name}": ${parsed.error}`);
73
+ parsedArgs.set(tc.id, {});
74
+ continue;
75
+ }
76
+ parsedArgs.set(tc.id, parsed.args);
77
+ const sig = callSignature(tc.function.name, parsed.args);
78
+ const count = (callCounts.get(sig) ?? 0) + 1;
79
+ callCounts.set(sig, count);
80
+ if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the 3rd identical call (matches executor's guard)
81
+ preResolved.set(tc.id, `Loop guard: "${tc.function.name}" has been called ${count} times this turn with identical ` +
82
+ `arguments. Try a different approach instead of repeating this call.`);
83
+ continue;
84
+ }
85
+ pending.push({ id: tc.id, name: tc.function.name, args: parsed.args });
86
+ }
87
+ if (pending.length)
88
+ onToolStart?.(pending.map((p) => p.name));
89
+ const started = performance.now();
90
+ const executed = pending.length ? await tools.executeParallel(pending) : [];
91
+ const durationMs = performance.now() - started;
92
+ const resultById = new Map(preResolved);
93
+ pending.forEach((p, i) => resultById.set(p.id, executed[i]));
94
+ if (onToolBatch) {
95
+ const events = toolCalls.map((tc) => ({
96
+ name: tc.function.name,
97
+ args: parsedArgs.get(tc.id) ?? {},
98
+ result: resultById.get(tc.id) ?? "",
99
+ }));
100
+ onToolBatch(events, durationMs);
101
+ }
102
+ return toolCalls.map((tc) => ({ role: "tool", content: resultById.get(tc.id) ?? "", tool_call_id: tc.id }));
103
+ }
104
+ /** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
105
+ export async function runTurn(userInput, conversation, opts) {
106
+ const softRounds = opts.maxRounds ?? 10;
107
+ const hardCap = opts.maxRoundsHard ?? Math.max(40, softRounds * 4);
108
+ const callCounts = new Map();
109
+ let selfHealBudget = MAX_SELF_HEAL_PER_TURN;
110
+ conversation.user(userInput);
111
+ let rounds = 0;
112
+ let toolCallTotal = 0;
113
+ let tokensTotal = 0; // output tokens summed across rounds (from llama.cpp timings)
114
+ let genMsTotal = 0; // server-side generation ms summed across rounds
115
+ let emptyRetries = 0; // reasoning models sometimes return a "dud" round (no content, no tool calls)
116
+ for (; rounds < hardCap; rounds++) {
117
+ throwIfAborted(opts.signal); // stop before spending another round (covers compaction below too)
118
+ if (rounds === softRounds)
119
+ opts.onAutoContinue?.(rounds); // crossed the soft budget, still working — keep going to hardCap
120
+ let endpoint = opts.router.select(buildMessages(opts.systemPrompt, conversation.all), opts.toolSchemas);
121
+ opts.onRoute?.(endpoint);
122
+ // Endpoint-aware (SPEC §5): rebuild against whichever endpoint is current, since self-heal
123
+ // failover below can swap endpoints mid-round and each has its own ctx_window.
124
+ const compactionOptsFor = (ep) => ({
125
+ ctxWindow: ep.ctxWindow,
126
+ systemPrompt: opts.systemPrompt,
127
+ tools: opts.toolSchemas,
128
+ summarize: opts.summarize,
129
+ threshold: opts.compactionThreshold,
130
+ minKeepTurns: opts.minKeepTurns,
131
+ });
132
+ if (needsCompaction(conversation.all, compactionOptsFor(endpoint))) {
133
+ conversation.replaceAll(await compact(conversation.all, compactionOptsFor(endpoint)));
134
+ }
135
+ let response;
136
+ for (;;) {
137
+ const messages = buildMessages(opts.systemPrompt, conversation.all);
138
+ // Clamp generation to the room left after the real prompt (incl. tool_calls args + schemas) so a
139
+ // deep-session request never overflows the window into a truncated reply. See clampMaxTokens.
140
+ const maxTokens = clampMaxTokens(messages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192);
141
+ try {
142
+ response = await chat(messages, {
143
+ base: endpoint.base,
144
+ model: endpoint.model,
145
+ maxTokens,
146
+ temperature: opts.temperature,
147
+ tools: opts.toolSchemas,
148
+ signal: opts.signal,
149
+ onDelta: opts.onDelta,
150
+ });
151
+ tokensTotal += response.tokens ?? 0;
152
+ genMsTotal += response.genMs ?? 0; // accumulate real gen metrics across rounds
153
+ break;
154
+ }
155
+ catch (err) {
156
+ if (isAbort(err, opts.signal))
157
+ throw new TurnAbortedError(); // never self-heal an interrupt
158
+ const recovery = classifyFailure(err);
159
+ // Non-retryable: a malformed request (a bad tool call) or bad credentials won't be fixed by
160
+ // resending — fail fast rather than spin (that futile-retry storm is what burned minutes).
161
+ if (recovery === "bad_request" || recovery === "auth" || selfHealBudget <= 0)
162
+ throw err;
163
+ const attempt = MAX_SELF_HEAL_PER_TURN - selfHealBudget; // 0-based
164
+ selfHealBudget -= 1;
165
+ if (recovery === "context") {
166
+ // Real context pressure: widen the window, or compact THIS one (only if actually over budget).
167
+ opts.onSelfHeal?.("context_exceeded", attempt + 1);
168
+ const bigger = opts.router.recover(endpoint, "context_exceeded");
169
+ if (bigger) {
170
+ endpoint = bigger;
171
+ opts.onRoute?.(endpoint);
172
+ continue;
173
+ }
174
+ // The SERVER said context is exceeded — trust it over our token estimate (the endpoint's real
175
+ // n_ctx can be far smaller than the advertised ctxWindow, so needsCompaction() can wrongly say
176
+ // "plenty of room"). Force-compact; only give up if there's genuinely too little to shed.
177
+ const beforeLen = conversation.all.length;
178
+ conversation.replaceAll(await compact(conversation.all, compactionOptsFor(endpoint)));
179
+ if (conversation.all.length >= beforeLen)
180
+ throw err; // couldn't shrink (too few turns kept)
181
+ continue;
182
+ }
183
+ // transient (429 / 5xx / network drop): a busy or unhealthy backend, NOT a context problem.
184
+ // Fail over to a healthy endpoint AND back off (exponential + jitter) so we don't storm a server
185
+ // that's already struggling. NEVER compact here — that was the "compacted at 0%" wasted work.
186
+ opts.onSelfHeal?.("server_error", attempt + 1);
187
+ const healthy = opts.router.recover(endpoint, "server_error");
188
+ if (healthy) {
189
+ endpoint = healthy;
190
+ opts.onRoute?.(endpoint);
191
+ }
192
+ await sleep(backoffMs(attempt, err), opts.signal, () => new TurnAbortedError());
193
+ continue;
194
+ }
195
+ }
196
+ if (response.toolCalls.length > 0) {
197
+ throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
198
+ conversation.assistant(response.content, response.toolCalls);
199
+ const toolMsgs = await runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart);
200
+ for (const tm of toolMsgs)
201
+ conversation.tool(tm.tool_call_id, tm.content);
202
+ toolCallTotal += response.toolCalls.length;
203
+ continue;
204
+ }
205
+ // No structured tool_calls — check for text-encoded ones before treating this as final.
206
+ const recovered = recoverToolCalls(response.content);
207
+ if (recovered.calls.length > 0) {
208
+ throwIfAborted(opts.signal);
209
+ conversation.assistant(recovered.cleanedContent, recovered.calls);
210
+ const toolMsgs = await runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, opts.onToolStart);
211
+ for (const tm of toolMsgs)
212
+ conversation.tool(tm.tool_call_id, tm.content);
213
+ toolCallTotal += recovered.calls.length;
214
+ continue;
215
+ }
216
+ const final = stripScratchpad(recovered.cleanedContent);
217
+ // Empty "dud" round (a reasoning model that spent its budget thinking and emitted nothing, and
218
+ // called no tool). Don't silently finalize blank — nudge it once to act, then fall back to the
219
+ // reasoning text or a clear message so the turn is never a mystery blank.
220
+ if (!final && emptyRetries < MAX_EMPTY_RETRIES) {
221
+ emptyRetries += 1;
222
+ conversation.user("(Your previous turn produced no output. Use your tools to gather what you need, then answer directly.)");
223
+ continue;
224
+ }
225
+ const answer = final || stripScratchpad(response.reasoningContent ?? "") || "(the model returned an empty response — try rephrasing.)";
226
+ conversation.assistant(answer);
227
+ return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal };
228
+ }
229
+ const timeoutMsg = `[stopped after ${hardCap} tool rounds — the task may be unfinished; ask me to continue and I'll pick up where I left off]`;
230
+ conversation.assistant(timeoutMsg);
231
+ return { content: timeoutMsg, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal };
232
+ }
@@ -0,0 +1,213 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Decode-time degeneration guard (SPEC §1). This is NOT a sampling penalty — it changes no
3
+ // logits and touches no request knob, so a healthy model is completely unaffected. It only
4
+ // watches the streamed text and STOPS a stream that is provably looping (a reasoning model
5
+ // spiralling "…Final Answer:… Wait…" forever), the way production harnesses cut runaway
6
+ // generation instead of re-feeding the model its own rambling. Penalties broke tool-calling
7
+ // here before; this replaces that whole idea with a clean stream stop + prefix trim.
8
+ // ---------------------------------------------------------------------------
9
+ const LOOP_MIN_LINE_LEN = 12; // ignore short/structural lines (braces, bullets, "OK")
10
+ const LOOP_LINE_REPEATS = 6; // same substantial line seen this many times => degenerate
11
+ const LOOP_TAIL = 260; // chars of tail scanned for a back-to-back repeating cycle
12
+ const LOOP_CHECK_EVERY = 200; // only run the scan every ~N new chars (cheap amortization)
13
+ function hasAlpha(s) {
14
+ return /[a-zA-Z]/.test(s);
15
+ }
16
+ /** True once the accumulated text is provably looping — a repeated substantial line, or a short cycle repeated in the tail. */
17
+ export function isDegenerate(text) {
18
+ if (text.length < LOOP_MIN_LINE_LEN * 3)
19
+ return false;
20
+ // (a) a substantial line repeated many times anywhere in the output
21
+ const counts = new Map();
22
+ for (const raw of text.split("\n")) {
23
+ const line = raw.trim();
24
+ if (line.length < LOOP_MIN_LINE_LEN || !hasAlpha(line))
25
+ continue;
26
+ const n = (counts.get(line) ?? 0) + 1;
27
+ if (n >= LOOP_LINE_REPEATS)
28
+ return true;
29
+ counts.set(line, n);
30
+ }
31
+ // (b) the tail is one short cycle repeated back-to-back (token loop with no newlines)
32
+ const tail = text.slice(-LOOP_TAIL * 3);
33
+ for (let cyc = 6; cyc <= LOOP_TAIL; cyc++) {
34
+ if (tail.length < cyc * 3)
35
+ break;
36
+ const a = tail.slice(-cyc);
37
+ if (a === tail.slice(-2 * cyc, -cyc) && a === tail.slice(-3 * cyc, -2 * cyc) && hasAlpha(a))
38
+ return true;
39
+ }
40
+ return false;
41
+ }
42
+ /** Drop the looping tail from a degenerate response: keep at most the first 2 copies of any substantial line. */
43
+ export function trimLoop(text) {
44
+ const seen = new Map();
45
+ const out = [];
46
+ for (const raw of text.split("\n")) {
47
+ const line = raw.trim();
48
+ if (line.length >= LOOP_MIN_LINE_LEN && hasAlpha(line)) {
49
+ const n = (seen.get(line) ?? 0) + 1;
50
+ seen.set(line, n);
51
+ if (n > 2)
52
+ continue; // 3rd+ occurrence is the loop — drop it
53
+ }
54
+ out.push(raw);
55
+ }
56
+ return out.join("\n").trim();
57
+ }
58
+ function requestBody(messages, o, stream) {
59
+ return JSON.stringify({
60
+ model: o.model, messages, stream,
61
+ max_tokens: o.maxTokens ?? 8192, temperature: o.temperature ?? 0.7,
62
+ ...(o.tools?.length ? { tools: o.tools, tool_choice: "auto" } : {}),
63
+ // NO repeat/presence/frequency penalty knobs — SPEC §1: they break tool-calling.
64
+ });
65
+ }
66
+ /** Shared SSE parse loop. Yields each `data:` line's `choices[0].delta`, raw. */
67
+ async function* streamDeltas(messages, o) {
68
+ const res = await fetch(`${o.base}/v1/chat/completions`, {
69
+ method: "POST",
70
+ headers: { "Content-Type": "application/json" },
71
+ body: requestBody(messages, o, true),
72
+ signal: o.signal, // SPEC §9 interrupt parity: tears down the in-flight stream on abort, not at the next loop boundary
73
+ });
74
+ if (!res.ok || !res.body) {
75
+ let detail = "";
76
+ try {
77
+ detail = (await res.text()).slice(0, 500);
78
+ }
79
+ catch { /* body already consumed / unreadable */ }
80
+ // Carry the status + body so the self-heal policy can classify WHY (context vs shape vs busy),
81
+ // not just guess from the number. `retryAfterMs` honors a Retry-After header on 429/503.
82
+ const err = new Error(`aurora /v1 ${res.status}${detail ? `: ${detail}` : ""}`);
83
+ err.status = res.status;
84
+ const ra = res.headers.get("retry-after");
85
+ if (ra)
86
+ err.retryAfterMs = /^\d+$/.test(ra.trim()) ? Number(ra) * 1000 : Math.max(0, Date.parse(ra) - Date.now());
87
+ throw err;
88
+ }
89
+ const reader = res.body.getReader();
90
+ const dec = new TextDecoder();
91
+ let buf = "";
92
+ // finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
93
+ try {
94
+ for (;;) {
95
+ const { value, done } = await reader.read();
96
+ if (done)
97
+ break;
98
+ buf += dec.decode(value, { stream: true });
99
+ for (const line of buf.split("\n")) {
100
+ const t = line.trim();
101
+ if (!t.startsWith("data:"))
102
+ continue;
103
+ const d = t.slice(5).trim();
104
+ if (d === "[DONE]")
105
+ return;
106
+ try {
107
+ const j = JSON.parse(d);
108
+ // llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
109
+ if (j.timings || j.usage)
110
+ o.onMeta?.({ tokens: j.timings?.predicted_n ?? j.usage?.completion_tokens, genMs: j.timings?.predicted_ms });
111
+ const delta = j.choices?.[0]?.delta;
112
+ if (delta)
113
+ yield delta;
114
+ }
115
+ catch { }
116
+ }
117
+ buf = buf.slice(buf.lastIndexOf("\n") + 1);
118
+ }
119
+ }
120
+ finally {
121
+ await reader.cancel().catch(() => { });
122
+ }
123
+ }
124
+ /** Streaming content-only view (existing consumers keep working unchanged). */
125
+ export async function* streamChat(messages, o) {
126
+ let content = "";
127
+ let sinceCheck = 0;
128
+ for await (const delta of streamDeltas(messages, o)) {
129
+ if (!delta.content)
130
+ continue;
131
+ yield delta.content;
132
+ content += delta.content;
133
+ sinceCheck += delta.content.length;
134
+ if (sinceCheck >= LOOP_CHECK_EVERY) { // stop the display stream on a provable loop (breaks → fetch torn down)
135
+ sinceCheck = 0;
136
+ if (isDegenerate(content))
137
+ break;
138
+ }
139
+ }
140
+ }
141
+ /**
142
+ * Non-streaming view over the same SSE transport: drains it fully, accumulating
143
+ * delta.tool_calls[] by index (SPEC §1), and returns the finished message.
144
+ */
145
+ export async function chat(messages, o) {
146
+ let content = "";
147
+ let reasoning = "";
148
+ let degenerate = false;
149
+ let sinceCheck = 0;
150
+ const acc = new Map();
151
+ const meta = {};
152
+ const oo = { ...o, onMeta: (m) => { if (m.tokens != null)
153
+ meta.tokens = m.tokens; if (m.genMs != null)
154
+ meta.genMs = m.genMs; o.onMeta?.(m); } };
155
+ for await (const delta of streamDeltas(messages, oo)) {
156
+ if (delta.content) {
157
+ content += delta.content;
158
+ o.onDelta?.(delta.content);
159
+ }
160
+ if (delta.reasoning_content)
161
+ reasoning += delta.reasoning_content;
162
+ if (delta.tool_calls) {
163
+ for (const tc of delta.tool_calls) {
164
+ const idx = tc.index ?? 0;
165
+ const entry = acc.get(idx) ?? { id: tc.id, type: tc.type ?? "function", name: "", args: "" };
166
+ if (tc.id)
167
+ entry.id = tc.id;
168
+ if (tc.type)
169
+ entry.type = tc.type;
170
+ if (tc.function?.name)
171
+ entry.name += tc.function.name;
172
+ if (tc.function?.arguments)
173
+ entry.args += tc.function.arguments;
174
+ acc.set(idx, entry);
175
+ }
176
+ }
177
+ // Loop breaker: only scan a tool-free response (a tool-calling turn is legitimately terminal),
178
+ // amortized to every ~LOOP_CHECK_EVERY chars. Break tears down the fetch via streamDeltas' finally.
179
+ if (acc.size === 0) {
180
+ sinceCheck += (delta.content?.length ?? 0) + (delta.reasoning_content?.length ?? 0);
181
+ if (sinceCheck >= LOOP_CHECK_EVERY) {
182
+ sinceCheck = 0;
183
+ if (isDegenerate(content) || isDegenerate(reasoning)) {
184
+ degenerate = true;
185
+ break;
186
+ }
187
+ }
188
+ }
189
+ }
190
+ if (degenerate)
191
+ content = trimLoop(content);
192
+ const toolCalls = [...acc.entries()]
193
+ .sort(([a], [b]) => a - b)
194
+ .map(([idx, e]) => ({
195
+ id: e.id ?? `call_${idx}`,
196
+ type: "function",
197
+ function: { name: e.name, arguments: e.args },
198
+ }));
199
+ return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason: degenerate ? "repetition" : undefined, tokens: meta.tokens, genMs: meta.genMs };
200
+ }
201
+ /** GET {base}/health → true iff {"status":"ok"}. Used by Router (SPEC §4) for self-heal failover. */
202
+ export async function health(base) {
203
+ try {
204
+ const res = await fetch(`${base}/health`);
205
+ if (!res.ok)
206
+ return false;
207
+ const j = await res.json();
208
+ return j?.status === "ok";
209
+ }
210
+ catch {
211
+ return false;
212
+ }
213
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Fact-preserving compaction prompt. The instruction forces VERBATIM retention of concrete values
3
+ * (a generic "summarize, be terse" drops buried identifiers) and a FACTS/STATE shape so specifics
4
+ * survive an aggressive squeeze. A host wires `summarize` with it AND a reasoning fallback:
5
+ *
6
+ * summarize: (span) => chat([{role:"user", content: summaryPrompt(span)}], {base, model, maxTokens: 1200})
7
+ * .then(r => (r.content?.trim()) || (r.reasoningContent ?? "").trim() || "(summary unavailable)")
8
+ *
9
+ * The `|| reasoningContent` fallback is REQUIRED with Aurora: its always-on thinking often spends the
10
+ * whole token budget on `reasoning_content` and returns empty `content` — the facts still live in the
11
+ * reasoning channel, so falling back to it is what makes fact-preservation reliable (the Python core
12
+ * does the same). Give the call generous maxTokens (>=1200) so reasoning can finish.
13
+ */
14
+ export function summaryPrompt(span) {
15
+ const transcript = span
16
+ .filter((m) => m.content)
17
+ .map((m) => `${m.role}: ${m.content.slice(0, 800)}`)
18
+ .join("\n")
19
+ .slice(0, 6000);
20
+ return ("You are compacting an agent conversation to free context. Write a compact note a later turn " +
21
+ "can fully rely on. PRESERVE VERBATIM every specific value that appears — identifiers, codes, " +
22
+ "tokens, numbers, versions, file paths, function/class/variable names, URLs, endpoints, config " +
23
+ "keys and values, commands, and error text. Copy each one EXACTLY; never paraphrase, round, or " +
24
+ "omit a concrete value. Terseness applies to prose, NEVER to specifics.\n" +
25
+ "Format exactly:\n" +
26
+ "FACTS:\n- <every concrete value, decision, and named thing, verbatim>\n" +
27
+ "STATE:\n- <1-3 lines: what was done, what is still open>\n" +
28
+ "No preamble, no closing remarks.\n\n" +
29
+ transcript);
30
+ }
31
+ /** chars/4 ≈ tokens. Crude but dependency-free; swap in a real tokenizer via estimateTokens. */
32
+ export function estimateTokensHeuristic(messages) {
33
+ let chars = 0;
34
+ for (const m of messages) {
35
+ chars += m.content.length;
36
+ if (m.tool_calls?.length)
37
+ chars += JSON.stringify(m.tool_calls).length;
38
+ }
39
+ return Math.ceil(chars / 4);
40
+ }
41
+ function fullRequestEstimate(conversation, opts) {
42
+ const estimate = opts.estimateTokens ?? estimateTokensHeuristic;
43
+ const system = opts.systemPrompt ? [{ role: "system", content: opts.systemPrompt }] : [];
44
+ const toolsTokens = opts.tools?.length ? Math.ceil(JSON.stringify(opts.tools).length / 4) : 0;
45
+ return estimate([...system, ...conversation]) + toolsTokens;
46
+ }
47
+ export function usageRatio(conversation, opts) {
48
+ if (opts.ctxWindow <= 0)
49
+ return 0;
50
+ return fullRequestEstimate(conversation, opts) / opts.ctxWindow;
51
+ }
52
+ export function needsCompaction(conversation, opts) {
53
+ return usageRatio(conversation, opts) >= (opts.threshold ?? 0.85);
54
+ }
55
+ /** Clamp generation length so prompt + output never exceeds the window. A static max_tokens plus a
56
+ * deep-session prompt otherwise gets the model squeezed to a truncated reply (parity with the Python
57
+ * core's _predict_budget). `built` already includes the system message, so pass systemPrompt:undefined
58
+ * to avoid double-counting it; tool-schema tokens still come from opts.tools. Floored so a reply stays
59
+ * usable — if even the floor won't fit, the prompt is over budget and the caller's compaction handles it. */
60
+ export function clampMaxTokens(built, opts, want, min = 512) {
61
+ const promptEst = fullRequestEstimate(built, { ...opts, systemPrompt: undefined });
62
+ const room = opts.ctxWindow - promptEst - 256; // margin for chat-template/role tokens the estimate omits
63
+ return Math.max(min, Math.min(want, room));
64
+ }
65
+ /** A "turn" starts at a user message. Returns the index of each turn start, in order. */
66
+ function turnStarts(conversation) {
67
+ const idxs = [];
68
+ conversation.forEach((m, i) => {
69
+ if (m.role === "user")
70
+ idxs.push(i);
71
+ });
72
+ return idxs;
73
+ }
74
+ /** A tool message with no preceding assistant(tool_calls) in view is invalid to send — drop any leading run of them. */
75
+ function dropLeadingOrphanTools(messages) {
76
+ let i = 0;
77
+ while (i < messages.length && messages[i].role === "tool")
78
+ i++;
79
+ return messages.slice(i);
80
+ }
81
+ /**
82
+ * Summarize and evict everything before the last `minKeepTurns` user-turns, replacing it
83
+ * with a single USER message. No-op (returns the conversation unchanged) if there aren't
84
+ * enough turns to safely evict past the floor.
85
+ *
86
+ * Call this proactively when needsCompaction() is true, or directly (forced) on a 400 with
87
+ * no bigger endpoint to route to (SPEC §4 self-heal) or on `/compact`.
88
+ */
89
+ export async function compact(conversation, opts) {
90
+ const minKeep = opts.minKeepTurns ?? 4;
91
+ const starts = turnStarts(conversation);
92
+ if (starts.length <= minKeep)
93
+ return [...conversation];
94
+ const cutIndex = starts[starts.length - minKeep];
95
+ const evicted = conversation.slice(0, cutIndex);
96
+ const kept = dropLeadingOrphanTools(conversation.slice(cutIndex));
97
+ if (!evicted.length)
98
+ return kept;
99
+ const summaryText = (await opts.summarize(evicted)).trim();
100
+ // Never destroy the evicted span behind an EMPTY summary. If the summarizer produced nothing (e.g.
101
+ // a model that spent its whole token budget on reasoning and returned empty content — hosts should
102
+ // pass content||reasoningContent, but guard here regardless), SKIP this compaction rather than replace
103
+ // real history with a bare "[Compacted summary of N]" header. The caller retries; nothing is lost.
104
+ if (!summaryText)
105
+ return [...conversation];
106
+ const summaryMsg = {
107
+ role: "user", // never a 2nd system message — SPEC §1/§5
108
+ content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}`,
109
+ };
110
+ return [summaryMsg, ...kept];
111
+ }
@@ -0,0 +1,8 @@
1
+ // The engine's public contract version (semver). A host that embeds the bundled engine asserts MAJOR
2
+ // compatibility at load — refusing an incompatible bundle loudly at startup beats failing mid-turn:
3
+ // MAJOR breaking change to runTurn / AgentOpts / the injected ToolExecutor|Router shape
4
+ // MINOR additive (new optional opt, new callback) — older hosts keep working
5
+ // PATCH internal fix, no contract change (e.g. clampMaxTokens)
6
+ // Bump MAJOR only when a host must change how it calls the engine. This is the single source of truth;
7
+ // both barrels (index.ts, index.browser.ts) re-export it, and the SPEC conformance fixtures pin it.
8
+ export const ENGINE_CONTRACT = "1.3.0"; // 1.3.0: + permissions surface (withPermissions, PermissionPolicy, ApproveFn) for client-side gating (additive)
@@ -0,0 +1,85 @@
1
+ // Message types + conversation builder — SPEC §1, §3. Single source of truth for `Msg` so
2
+ // aurora.ts, toolcalls.ts, agent.ts and compaction.ts all agree on shape.
3
+ /**
4
+ * Guards the one invariant llama.cpp's chat template 400s on (SPEC §1):
5
+ * two system messages, or a system message immediately followed by an assistant message.
6
+ */
7
+ export function assertValidMessages(messages) {
8
+ const systemCount = messages.reduce((n, m) => n + (m.role === "system" ? 1 : 0), 0);
9
+ if (systemCount > 1) {
10
+ throw new Error("kode-tsi: request has >1 system message — would 400 the Aurora endpoint");
11
+ }
12
+ if (messages[0]?.role === "system" && messages[1]?.role === "assistant") {
13
+ throw new Error("kode-tsi: system message directly followed by assistant — would 400 the Aurora endpoint");
14
+ }
15
+ }
16
+ /**
17
+ * Repairs dangling tool_calls: llama.cpp 400s when an assistant `tool_calls` turn is not followed
18
+ * by a `tool` result for every id. This happens when a turn is INTERRUPTED mid-tool (AgentOpts.signal
19
+ * fires after the assistant turn is recorded but before results land). For any unanswered id we
20
+ * synthesize an "[interrupted]" tool result so the sequence always renders. Idempotent.
21
+ */
22
+ function repairToolPairs(messages) {
23
+ const out = [];
24
+ for (let i = 0; i < messages.length; i++) {
25
+ const m = messages[i];
26
+ if (m.role === "assistant" && m.tool_calls?.length) {
27
+ out.push(m);
28
+ const answered = new Set();
29
+ let j = i + 1;
30
+ while (j < messages.length && messages[j].role === "tool") {
31
+ const tm = messages[j];
32
+ out.push(tm);
33
+ if (tm.tool_call_id)
34
+ answered.add(tm.tool_call_id);
35
+ j++;
36
+ }
37
+ for (const tc of m.tool_calls) {
38
+ if (!answered.has(tc.id))
39
+ out.push({ role: "tool", content: "[interrupted — no result]", tool_call_id: tc.id });
40
+ }
41
+ i = j - 1; // already emitted the tool messages in this run
42
+ }
43
+ else {
44
+ out.push(m);
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+ /** Prepends the system prompt (if any), repairs interrupted tool pairs, and validates the result. */
50
+ export function buildMessages(systemPrompt, conversation) {
51
+ const withSystem = systemPrompt
52
+ ? [{ role: "system", content: systemPrompt }, ...conversation]
53
+ : [...conversation];
54
+ const messages = repairToolPairs(withSystem);
55
+ assertValidMessages(messages);
56
+ return messages;
57
+ }
58
+ /** Mutable conversation state for one session. Never holds the system message itself —
59
+ * that's supplied per-request by build() so compaction can never accidentally produce a 2nd one. */
60
+ export class Conversation {
61
+ messages = [];
62
+ get all() {
63
+ return this.messages;
64
+ }
65
+ user(content) {
66
+ this.messages.push({ role: "user", content });
67
+ }
68
+ assistant(content, toolCalls) {
69
+ this.messages.push({
70
+ role: "assistant",
71
+ content,
72
+ ...(toolCalls && toolCalls.length ? { tool_calls: toolCalls } : {}),
73
+ });
74
+ }
75
+ tool(toolCallId, content) {
76
+ this.messages.push({ role: "tool", content, tool_call_id: toolCallId });
77
+ }
78
+ /** Used by compaction to splice in [summary, ...keptTurns]. */
79
+ replaceAll(messages) {
80
+ this.messages = messages;
81
+ }
82
+ build(systemPrompt) {
83
+ return buildMessages(systemPrompt, this.messages);
84
+ }
85
+ }