minicode-ai 0.9.26
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/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- package/vendor/minicore/src/providers/openai-compat.ts +366 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
// The heart of the kernel: one deterministic model → tool → observation loop.
|
|
2
|
+
|
|
3
|
+
import { AgentError, ProviderError, abortError } from "./errors.ts";
|
|
4
|
+
import type { RecoveryAction } from "./errors.ts";
|
|
5
|
+
import type { ExecutorDeps } from "./executor.ts";
|
|
6
|
+
import type { StreamRequest, FinishReason } from "./provider.ts";
|
|
7
|
+
import { snapshotMessages, snapshotState, snapshotStep, snapshotToolCall, snapshotToolResult, snapshotToolSchemas } from "./snapshot.ts";
|
|
8
|
+
import { estimateSessionContext } from "./tokens.ts";
|
|
9
|
+
import type { ToolSchema } from "./tool.ts";
|
|
10
|
+
import type { ToolCall, ToolResult } from "./types.ts";
|
|
11
|
+
import type { SessionInternal, Step, TurnResult } from "./session.ts";
|
|
12
|
+
|
|
13
|
+
/** Resolve mode permission sesi untuk deps turn ini (string langsung atau
|
|
14
|
+
* getter live). Tak pernah melempar — gagal = undefined. */
|
|
15
|
+
function resolvePermissionMode(mode: SessionInternal["permissionMode"]): string | undefined {
|
|
16
|
+
try {
|
|
17
|
+
if (typeof mode === "function") {
|
|
18
|
+
const v = (mode as () => unknown)();
|
|
19
|
+
return typeof v === "string" ? v : undefined;
|
|
20
|
+
}
|
|
21
|
+
return mode;
|
|
22
|
+
} catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function executeTurn(
|
|
28
|
+
s: SessionInternal,
|
|
29
|
+
input: string,
|
|
30
|
+
signal: AbortSignal,
|
|
31
|
+
modelOverride?: string,
|
|
32
|
+
): Promise<TurnResult> {
|
|
33
|
+
const turn = s.state.turnCount;
|
|
34
|
+
s.events.emit({ type: "turn:started", turn });
|
|
35
|
+
s.state.turnCount++;
|
|
36
|
+
|
|
37
|
+
const store = s.store;
|
|
38
|
+
store.append({ role: "user", content: input });
|
|
39
|
+
|
|
40
|
+
const steps: Step[] = [];
|
|
41
|
+
let stepIndex = 0;
|
|
42
|
+
let finalText: string | undefined;
|
|
43
|
+
// Kontrak kompaksi (Phase 6): DUA flag terpisah — budget compaction dan
|
|
44
|
+
// recovery compaction punya semantics berbeda. Flag tunggal dulu mengaburkan
|
|
45
|
+
// keduanya: kompaksi budget membakar satu-satunya retry recovery (padahal
|
|
46
|
+
// recovery belum pernah dicoba), dan sebaliknya. Recovery flag SELALU diset
|
|
47
|
+
// (anti loop abadi: force_compact_and_retry tidak dihitung maxProviderRetries);
|
|
48
|
+
// budget flag diset saat kompaksi budget dicoba (kompaksi per-turn, anti
|
|
49
|
+
// berulang tiap step O(n)).
|
|
50
|
+
let compactedForBudget = false;
|
|
51
|
+
let compactedForRecovery = false;
|
|
52
|
+
|
|
53
|
+
while (true) {
|
|
54
|
+
if (signal.aborted) throw abortError(signal);
|
|
55
|
+
if (stepIndex >= s.maxSteps) throw new AgentError("max_steps_exceeded", `exceeded ${s.maxSteps} steps`);
|
|
56
|
+
|
|
57
|
+
// Budget policy → compaction strategy (separate concerns, orchestrated here).
|
|
58
|
+
// The budget counts messages plus the fixed per-request cost of the system
|
|
59
|
+
// prompt and tool schemas, which are sent on every request.
|
|
60
|
+
let pressure = s.budget.evaluate({
|
|
61
|
+
usedTokens: contextTokens(s),
|
|
62
|
+
limitTokens: s.contextWindowTokens,
|
|
63
|
+
});
|
|
64
|
+
if (s.budget.shouldCompact(pressure) && !compactedForBudget) {
|
|
65
|
+
const before = s.store.messages.length;
|
|
66
|
+
await compactStore(s, signal);
|
|
67
|
+
compactedForBudget = true;
|
|
68
|
+
// reason membedakan pemicu + apakah kompaksi benar-benar mengurangi
|
|
69
|
+
// (no-op = tidak ada yang bisa dibuang dari messages — operator harus
|
|
70
|
+
// tahu bedanya dari fixed overhead, bukan dari kompaksi sia-sia).
|
|
71
|
+
const reduced = s.store.messages.length < before;
|
|
72
|
+
s.events.emit({
|
|
73
|
+
type: "context:compacted",
|
|
74
|
+
reason: reduced ? `budget:${pressure}` : `budget:${pressure}:no-op`,
|
|
75
|
+
});
|
|
76
|
+
pressure = s.budget.evaluate({
|
|
77
|
+
usedTokens: contextTokens(s),
|
|
78
|
+
limitTokens: s.contextWindowTokens,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (pressure === "critical" && compactedForBudget) {
|
|
82
|
+
throw new AgentError("budget_exceeded", "context window exceeded after compaction");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Sample from the provider with deterministic recovery.
|
|
86
|
+
const toolCalls: ToolCall[] = [];
|
|
87
|
+
let text = "";
|
|
88
|
+
let reasoning = ""; // DeepSeek-style thinking content
|
|
89
|
+
let attempt = 0;
|
|
90
|
+
|
|
91
|
+
while (true) {
|
|
92
|
+
attempt++;
|
|
93
|
+
// Each attempt starts from a clean slate: a failed attempt must not leak
|
|
94
|
+
// its partial text or tool calls into the next one.
|
|
95
|
+
text = "";
|
|
96
|
+
reasoning = "";
|
|
97
|
+
toolCalls.length = 0;
|
|
98
|
+
let action: RecoveryAction | null = null;
|
|
99
|
+
let errorMessage: string | undefined;
|
|
100
|
+
let completed: FinishReason | undefined;
|
|
101
|
+
try {
|
|
102
|
+
for await (const ev of s.provider.stream(buildRequest(s, modelOverride), signal)) {
|
|
103
|
+
if (signal.aborted) throw abortError(signal);
|
|
104
|
+
// Setelah finish: hanya `extension` (mis. usage/reasoning tail dari
|
|
105
|
+
// b.ai dll.) yang diterima — tidak boleh ada text/tool deltas baru,
|
|
106
|
+
// karena itu berarti output protokol rusak dan harus retryable error.
|
|
107
|
+
if (completed !== undefined) {
|
|
108
|
+
if (ev.type === "extension") {
|
|
109
|
+
s.events.emit({ type: "provider:extension", kind: ev.kind, data: ev.data });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
throw new ProviderError("network", "provider stream emitted an event after finish");
|
|
113
|
+
}
|
|
114
|
+
switch (ev.type) {
|
|
115
|
+
case "text":
|
|
116
|
+
text += ev.text;
|
|
117
|
+
s.events.emit({ type: "provider:text", text: ev.text });
|
|
118
|
+
break;
|
|
119
|
+
case "extension":
|
|
120
|
+
s.events.emit({ type: "provider:extension", kind: ev.kind, data: ev.data });
|
|
121
|
+
if (ev.kind === "reasoning") reasoning += (ev.data as { text?: string }).text ?? "";
|
|
122
|
+
break;
|
|
123
|
+
case "tool_call":
|
|
124
|
+
toolCalls.push(snapshotToolCall({ id: ev.id, name: ev.name, args: ev.args }));
|
|
125
|
+
break;
|
|
126
|
+
case "finish":
|
|
127
|
+
completed = ev.reason;
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (signal.aborted) throw abortError(signal);
|
|
132
|
+
// A well-formed provider stream always ends with a finish event; a
|
|
133
|
+
// clean shutdown without one means the response was cut short, so treat
|
|
134
|
+
// it as a retryable provider error instead of silently accepting
|
|
135
|
+
// partial text or incomplete tool calls.
|
|
136
|
+
if (completed === undefined) {
|
|
137
|
+
throw new ProviderError("network", "stream ended without a finish reason");
|
|
138
|
+
}
|
|
139
|
+
if (completed === "length") {
|
|
140
|
+
errorMessage = "provider output reached length limit";
|
|
141
|
+
// Kontrak (Phase 6): onLength membaca flag RECOVERY — bukan flag
|
|
142
|
+
// budget. Dulu flag tunggal membuat kompaksi budget membakar
|
|
143
|
+
// retry recovery ini.
|
|
144
|
+
action = s.recovery.onLength(compactedForRecovery);
|
|
145
|
+
} else if (completed === "error") {
|
|
146
|
+
action = { type: "throw" };
|
|
147
|
+
errorMessage = "provider finished with error reason";
|
|
148
|
+
} else if (completed === "abort") {
|
|
149
|
+
action = { type: "throw" };
|
|
150
|
+
errorMessage = "provider aborted the stream";
|
|
151
|
+
}
|
|
152
|
+
} catch (error) {
|
|
153
|
+
const cause = toProviderError(error, signal);
|
|
154
|
+
s.events.emit({
|
|
155
|
+
type: "provider:extension",
|
|
156
|
+
kind: "error",
|
|
157
|
+
data: { category: cause.category, message: cause.message },
|
|
158
|
+
});
|
|
159
|
+
errorMessage = cause.message;
|
|
160
|
+
action = s.recovery.onError(cause, attempt);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (action === null) break;
|
|
164
|
+
switch (action.type) {
|
|
165
|
+
case "throw":
|
|
166
|
+
throw new AgentError("provider", errorMessage ?? "provider error", { cause: action });
|
|
167
|
+
case "force_compact_and_retry": {
|
|
168
|
+
if (compactedForRecovery)
|
|
169
|
+
throw new AgentError("budget_exceeded", errorMessage ?? "context too large", { cause: action });
|
|
170
|
+
await compactStore(s, signal);
|
|
171
|
+
// Recovery flag SELALU diset (no-op pun): force_compact_and_retry
|
|
172
|
+
// tidak dihitung maxProviderRetries — no-op berulang = loop abadi.
|
|
173
|
+
compactedForRecovery = true;
|
|
174
|
+
s.events.emit({ type: "context:compacted", reason: "recovery" });
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
case "retry":
|
|
178
|
+
await delay(action.delayMs, signal);
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Dispatch.
|
|
184
|
+
if (signal.aborted) throw abortError(signal);
|
|
185
|
+
// Reasoning (DeepSeek-style thinking) disimpan di assistant message agar
|
|
186
|
+
// provider thinking-mode bisa menerima history (butuh reasoning_content).
|
|
187
|
+
const reasoningNote = reasoning.length ? { reasoning } : {};
|
|
188
|
+
if (toolCalls.length === 0) {
|
|
189
|
+
store.append({ role: "assistant", content: text, ...reasoningNote });
|
|
190
|
+
finalText = text || undefined;
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const actionCalls = toolCalls.map(snapshotToolCall);
|
|
195
|
+
store.append({ role: "assistant", content: text, ...reasoningNote, toolCalls: actionCalls.map(snapshotToolCall) });
|
|
196
|
+
const started: Step = { index: stepIndex, toolCalls: actionCalls.map(snapshotToolCall), results: [] };
|
|
197
|
+
s.events.emit({ type: "step:started", step: snapshotStep(started) });
|
|
198
|
+
|
|
199
|
+
const deps: ExecutorDeps = {
|
|
200
|
+
registry: s.registry,
|
|
201
|
+
permissions: s.permissions,
|
|
202
|
+
events: s.events,
|
|
203
|
+
signal,
|
|
204
|
+
state: snapshotState(s.state),
|
|
205
|
+
maxResultTokens: s.toolResultMaxTokens,
|
|
206
|
+
cwd: s.cwd,
|
|
207
|
+
// Resolve per turn agar getter live (mis. ganti mode via Shift+Tab)
|
|
208
|
+
// tercermin di ctx tool berikutnya. Gagal resolve = undefined (aman).
|
|
209
|
+
permissionMode: resolvePermissionMode(s.permissionMode),
|
|
210
|
+
};
|
|
211
|
+
let rawResults: readonly ToolResult[];
|
|
212
|
+
try {
|
|
213
|
+
rawResults = await s.executor.execute(actionCalls.map(snapshotToolCall), deps);
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (signal.aborted) throw abortError(signal);
|
|
216
|
+
rawResults = actionCalls.map((call) =>
|
|
217
|
+
toolErrorResult(call, `executor error: ${error instanceof Error ? error.message : String(error)}`),
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
// The executor can outlive the turn when a tool ignores the abort signal
|
|
221
|
+
// and settles late. Never write those results back into the shared store
|
|
222
|
+
// after the turn has settled — a late result must not leak into the next
|
|
223
|
+
// run's history. (This is the only store mutation reachable across a
|
|
224
|
+
// suspension that can resolve after an abort; the other appends are
|
|
225
|
+
// synchronous relative to their awaits.)
|
|
226
|
+
if (signal.aborted) throw abortError(signal);
|
|
227
|
+
const results = pairToolResults(actionCalls, rawResults);
|
|
228
|
+
store.appendAll(results.map(snapshotToolResult));
|
|
229
|
+
|
|
230
|
+
const step: Step = {
|
|
231
|
+
index: stepIndex,
|
|
232
|
+
toolCalls: actionCalls.map(snapshotToolCall),
|
|
233
|
+
results: results.map(snapshotToolResult),
|
|
234
|
+
};
|
|
235
|
+
steps.push(step);
|
|
236
|
+
s.state.stepCount = stepIndex + 1;
|
|
237
|
+
s.events.emit({ type: "step:completed", step: snapshotStep(step) });
|
|
238
|
+
stepIndex++;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const result: TurnResult = {
|
|
242
|
+
finalText,
|
|
243
|
+
steps,
|
|
244
|
+
usage: { turns: s.state.turnCount, steps: stepIndex },
|
|
245
|
+
};
|
|
246
|
+
s.state.stepCount = stepIndex;
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function buildRequest(s: SessionInternal, modelOverride?: string): StreamRequest {
|
|
251
|
+
const tools: ToolSchema[] = s.registry.list().map((tool) => ({
|
|
252
|
+
name: tool.name,
|
|
253
|
+
description: tool.description,
|
|
254
|
+
parameters: tool.parameters,
|
|
255
|
+
}));
|
|
256
|
+
return {
|
|
257
|
+
messages: snapshotMessages(s.store.messages),
|
|
258
|
+
tools: tools.length ? snapshotToolSchemas(tools) : undefined,
|
|
259
|
+
system: s.system,
|
|
260
|
+
model: modelOverride ?? s.model,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function pairToolResults(calls: readonly ToolCall[], results: readonly ToolResult[]): readonly ToolResult[] {
|
|
265
|
+
const byId = new Map<string, ToolResult[]>();
|
|
266
|
+
for (const result of results) {
|
|
267
|
+
const list = byId.get(result.toolCallId) ?? [];
|
|
268
|
+
list.push(result);
|
|
269
|
+
byId.set(result.toolCallId, list);
|
|
270
|
+
}
|
|
271
|
+
return calls.map((call) => {
|
|
272
|
+
const result = byId.get(call.id)?.shift();
|
|
273
|
+
if (!result) return toolErrorResult(call, `executor returned no result for tool call: ${call.id}`);
|
|
274
|
+
if (result.name !== call.name) {
|
|
275
|
+
return toolErrorResult(call, `executor returned result for "${result.name}" but call expected "${call.name}"`);
|
|
276
|
+
}
|
|
277
|
+
return snapshotToolResult(result);
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function toolErrorResult(call: ToolCall, message: string): ToolResult {
|
|
282
|
+
return {
|
|
283
|
+
role: "tool",
|
|
284
|
+
toolCallId: call.id,
|
|
285
|
+
name: call.name,
|
|
286
|
+
content: message,
|
|
287
|
+
isError: true,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function toProviderError(error: unknown, signal: AbortSignal): ProviderError {
|
|
292
|
+
if (signal.aborted) throw abortError(signal);
|
|
293
|
+
if (error instanceof ProviderError) return error;
|
|
294
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
295
|
+
throw abortError(signal);
|
|
296
|
+
}
|
|
297
|
+
return new ProviderError("unknown", error instanceof Error ? error.message : String(error));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
301
|
+
return new Promise((resolve, reject) => {
|
|
302
|
+
if (signal.aborted) {
|
|
303
|
+
reject(abortError(signal));
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const timer = setTimeout(() => {
|
|
307
|
+
cleanup();
|
|
308
|
+
resolve();
|
|
309
|
+
}, Math.max(0, ms));
|
|
310
|
+
const onAbort = () => {
|
|
311
|
+
clearTimeout(timer);
|
|
312
|
+
cleanup();
|
|
313
|
+
reject(abortError(signal));
|
|
314
|
+
};
|
|
315
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
316
|
+
function cleanup() {
|
|
317
|
+
signal.removeEventListener("abort", onAbort);
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function contextTokens(s: SessionInternal): number {
|
|
323
|
+
// Kontrak (Phase 6): single source di tokens.ts `estimateSessionContext` —
|
|
324
|
+
// dipakai loop DAN Session getter sehingga tidak ada estimator duplikat.
|
|
325
|
+
return estimateSessionContext(s.store, s.system, s.registry.list(), s.estimator);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// The single compaction seam. Prefers the strategy's optional async method
|
|
329
|
+
// (LLM summary) and always falls back to the sync strategy on failure — an
|
|
330
|
+
// async compactor must never be able to crash the loop.
|
|
331
|
+
async function compactStore(s: SessionInternal, signal: AbortSignal): Promise<void> {
|
|
332
|
+
const opts = { keepRecentTurns: s.keepRecentTurns };
|
|
333
|
+
if (s.compaction.compactAsync) {
|
|
334
|
+
try {
|
|
335
|
+
const messages = await s.compaction.compactAsync(s.store, opts, signal);
|
|
336
|
+
s.store.replace(0, s.store.messages.length, messages);
|
|
337
|
+
return;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if (signal.aborted) throw abortError(signal);
|
|
340
|
+
// fall through to sync mechanical compaction
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
s.store.replace(0, s.store.messages.length, s.compaction.compact(s.store, opts));
|
|
344
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Permission boundary. The kernel commits to consulting this handler before
|
|
2
|
+
// every tool execution; it never enforces its own policy.
|
|
3
|
+
|
|
4
|
+
import type { ToolCall } from "./types.ts";
|
|
5
|
+
import type { ExecutorDeps } from "./executor.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Only "deny" blocks execution. A handler that needs interactive approval
|
|
9
|
+
* (e.g. a CLI prompt) is expected to block until it resolves the decision
|
|
10
|
+
* internally and then return "allow" or "deny".
|
|
11
|
+
*/
|
|
12
|
+
export type Decision = "allow" | "deny";
|
|
13
|
+
|
|
14
|
+
export interface PermissionHandler {
|
|
15
|
+
check(call: ToolCall, deps: ExecutorDeps): Promise<Decision>;
|
|
16
|
+
/**
|
|
17
|
+
* Additive seam (minicode, bukan upstream): alasan deny terakhir untuk
|
|
18
|
+
* `call`, agar model bisa koreksi arah alih-alih retry buta sampai
|
|
19
|
+
* max_steps. Dipanggil kernel tepat setelah `check` mengembalikan "deny";
|
|
20
|
+
* return undefined/"" = pesan deny polos seperti dulu. Opsional — handler
|
|
21
|
+
* lama tanpa method ini tetap jalan tanpa perubahan perilaku.
|
|
22
|
+
*/
|
|
23
|
+
describeDenial?(call: ToolCall): Promise<string | undefined> | string | undefined;
|
|
24
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// The model contract. The kernel only knows these normalized events; every
|
|
2
|
+
// provider adapter (OpenAI-compatible, Anthropic, Gemini, local…) implements
|
|
3
|
+
// this one interface. Reasoning/thinking is an optional "extension" event and
|
|
4
|
+
// is never required.
|
|
5
|
+
|
|
6
|
+
import type { Message } from "./types.ts";
|
|
7
|
+
import type { ToolSchema } from "./tool.ts";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Why a provider stream ended. The kernel consults this to decide recovery:
|
|
11
|
+
* `length` may trigger compaction+retry, `error`/`abort` never retry.
|
|
12
|
+
*/
|
|
13
|
+
export type FinishReason = "stop" | "tool_calls" | "length" | "abort" | "error";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The normalized provider stream. Adapters translate their wire format into
|
|
17
|
+
* exactly these events; the kernel never sees provider-specific shapes. A
|
|
18
|
+
* well-formed stream always ends with a `finish` event.
|
|
19
|
+
*/
|
|
20
|
+
export type ProviderEvent =
|
|
21
|
+
| { type: "text"; text: string }
|
|
22
|
+
| { type: "tool_call"; id: string; name: string; args: unknown }
|
|
23
|
+
| { type: "finish"; reason: FinishReason }
|
|
24
|
+
| { type: "extension"; kind: string; data: unknown };
|
|
25
|
+
|
|
26
|
+
/** The per-request payload the kernel hands to a provider. */
|
|
27
|
+
export interface StreamRequest {
|
|
28
|
+
readonly messages: readonly Message[];
|
|
29
|
+
readonly tools?: readonly ToolSchema[];
|
|
30
|
+
readonly system?: string;
|
|
31
|
+
readonly model?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A model provider: normalized, stateless, and swappable. */
|
|
35
|
+
export interface ModelProvider {
|
|
36
|
+
readonly id: string;
|
|
37
|
+
readonly models: readonly string[];
|
|
38
|
+
stream(request: StreamRequest, signal: AbortSignal): AsyncIterable<ProviderEvent>;
|
|
39
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Provider-agnostic recovery. Adapters normalize provider-specific errors into
|
|
2
|
+
// ProviderError categories; this policy decides what the kernel does about them.
|
|
3
|
+
|
|
4
|
+
import type { ProviderError, RecoveryAction } from "./errors.ts";
|
|
5
|
+
|
|
6
|
+
export interface RecoveryPolicy {
|
|
7
|
+
onError(error: ProviderError, attempt: number): RecoveryAction;
|
|
8
|
+
onLength(compacted: boolean): RecoveryAction;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const maxProviderRetries = 3;
|
|
12
|
+
|
|
13
|
+
export const defaultRecoveryPolicy: RecoveryPolicy = {
|
|
14
|
+
onError(error, attempt) {
|
|
15
|
+
switch (error.category) {
|
|
16
|
+
case "auth":
|
|
17
|
+
case "invalid_request":
|
|
18
|
+
return { type: "throw" };
|
|
19
|
+
case "context_length_exceeded":
|
|
20
|
+
return { type: "force_compact_and_retry" };
|
|
21
|
+
default:
|
|
22
|
+
if (attempt > maxProviderRetries) return { type: "throw" };
|
|
23
|
+
return { type: "retry", delayMs: backoffDelay(attempt, error.retryAfterMs) };
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
onLength(compacted) {
|
|
27
|
+
return compacted ? { type: "throw" } : { type: "force_compact_and_retry" };
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function backoffDelay(attempt: number, retryAfter?: number): number {
|
|
32
|
+
if (retryAfter != null) return retryAfter;
|
|
33
|
+
return Math.min(1_000 * 2 ** (attempt - 1), 8_000);
|
|
34
|
+
}
|