minicode-ai 0.11.0 → 0.13.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/CHANGELOG.md +98 -0
- package/LICENSE +21 -21
- package/README.md +4 -4
- package/cli/args.ts +46 -0
- package/cli/commands/acp.ts +163 -10
- package/cli/commands/config.ts +33 -18
- package/cli/commands/daemon.ts +515 -0
- package/cli/commands/exec.ts +145 -53
- package/cli/commands/openwork.ts +986 -0
- package/cli/commands/sessions.ts +4 -1
- package/cli/commands/stats.ts +34 -4
- package/cli/commands.ts +217 -2
- package/cli/index.ts +146 -14
- package/cli/recovery-warning.ts +115 -0
- package/cli/router.ts +32 -1
- package/cli/setup.ts +2332 -171
- package/cli/tui.ts +113 -7
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
- package/docs/OUTPUT_EVENT_MODEL.md +289 -0
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
- package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
- package/docs/OUTPUT_UX_RULES.md +449 -0
- package/docs/PLAN_UIUX_V6.md +2 -2
- package/docs/README.md +4 -3
- package/docs/TERMINAL_CONTRACT.md +278 -66
- package/docs/architecture.md +89 -7
- package/docs/changelog.md +1 -1
- package/docs/choosing-mode.md +2 -2
- package/docs/cli.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +9 -2
- package/docs/environment.md +6 -2
- package/docs/exec.md +46 -5
- package/docs/memory-sessions.md +2 -0
- package/docs/policy-sandbox.md +1 -1
- package/docs/pricing-budget.md +1 -1
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +6 -2
- package/docs/security-model.md +1 -1
- package/docs/security.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal.md +9 -5
- package/docs/tools.md +1 -1
- package/package.json +35 -5
- package/src/app/session.ts +261 -15
- package/src/app/tool-layer.ts +94 -7
- package/src/daemon/approvals.ts +361 -0
- package/src/daemon/capability.ts +145 -0
- package/src/daemon/children.ts +142 -0
- package/src/daemon/client.ts +267 -0
- package/src/daemon/control.ts +350 -0
- package/src/daemon/discovery.ts +234 -0
- package/src/daemon/feed.ts +155 -0
- package/src/daemon/framing.ts +94 -0
- package/src/daemon/host.ts +316 -0
- package/src/daemon/protocol.ts +217 -0
- package/src/daemon/resource.ts +170 -0
- package/src/daemon/sanitize.ts +57 -0
- package/src/daemon/server.ts +627 -0
- package/src/daemon/store.ts +317 -0
- package/src/daemon/subscription.ts +270 -0
- package/src/daemon/telemetry.ts +81 -0
- package/src/hooks/run.ts +12 -1
- package/src/lib/atomic-write.ts +29 -3
- package/src/lib/db-path.ts +26 -0
- package/src/lib/keystore.ts +544 -42
- package/src/lib/net.ts +43 -1
- package/src/lib/safe-open.ts +116 -1
- package/src/lib/session-id.ts +15 -0
- package/src/lsp/client.ts +123 -5
- package/src/mcp/client.ts +139 -17
- package/src/mcp/server.ts +177 -50
- package/src/mcp/transport.ts +16 -19
- package/src/memory/vector.ts +770 -55
- package/src/policy/allowlist.ts +14 -2
- package/src/policy/bash-guard.ts +105 -10
- package/src/policy/compaction.ts +82 -5
- package/src/policy/consequence-engine.ts +220 -0
- package/src/policy/context.ts +132 -0
- package/src/policy/executor.ts +187 -121
- package/src/policy/no-progress.ts +559 -0
- package/src/policy/permission.ts +4 -8
- package/src/policy/pricing.ts +17 -3
- package/src/policy/scrub.ts +69 -2
- package/src/policy/tool-contract.ts +515 -0
- package/src/policy/usage.ts +310 -24
- package/src/policy/verifier.ts +6 -3
- package/src/policy/work-mode.ts +182 -0
- package/src/presentation/adapter.ts +533 -26
- package/src/presentation/events.ts +151 -0
- package/src/presentation/model.ts +180 -27
- package/src/presentation/projection.ts +858 -0
- package/src/presentation/reducer.ts +645 -310
- package/src/presentation/store.ts +12 -7
- package/src/providers/anthropic.ts +18 -10
- package/src/providers/responses.ts +17 -7
- package/src/runtime/capability.ts +409 -0
- package/src/runtime/child-execution.ts +274 -0
- package/src/runtime/composition.ts +958 -0
- package/src/runtime/dispatch.ts +591 -0
- package/src/runtime/execution-backend.ts +632 -0
- package/src/runtime/execution-events.ts +272 -0
- package/src/runtime/execution-id.ts +230 -0
- package/src/runtime/execution-journal.ts +926 -0
- package/src/runtime/execution-kernel.ts +456 -0
- package/src/runtime/execution-registry.ts +379 -0
- package/src/runtime/process-supervision.ts +276 -0
- package/src/runtime/production-execution.ts +551 -0
- package/src/runtime/production-runtime.ts +217 -0
- package/src/runtime/recovery-safety.ts +70 -0
- package/src/runtime/recovery.ts +477 -0
- package/src/runtime/runtime-capabilities.ts +179 -0
- package/src/runtime/runtime-diagnostics.ts +141 -0
- package/src/runtime/runtime-host.ts +365 -0
- package/src/runtime/runtime-status-facts.ts +222 -0
- package/src/runtime/runtime-status-provider.ts +74 -0
- package/src/runtime/runtime-status.ts +459 -0
- package/src/runtime/runtime-task-admission.ts +101 -0
- package/src/runtime/supervisor.ts +444 -0
- package/src/session/authority.ts +168 -0
- package/src/session/checkpoint.ts +88 -1
- package/src/session/context-adapter.ts +251 -0
- package/src/session/context-assembly.ts +242 -0
- package/src/session/context-identity.ts +389 -0
- package/src/session/context-projection.ts +248 -0
- package/src/session/context-selector.ts +500 -0
- package/src/session/cross-session-adoption.ts +249 -0
- package/src/session/full-history-fold.ts +171 -0
- package/src/session/identity.ts +192 -0
- package/src/session/journal.ts +805 -102
- package/src/session/open-work-intent.ts +732 -0
- package/src/session/open-work.ts +767 -0
- package/src/session/pending-tools.ts +94 -0
- package/src/session/persistence.ts +3569 -127
- package/src/session/runtime-header.ts +208 -0
- package/src/session/shadow-git.ts +13 -5
- package/src/session/verification.ts +1623 -0
- package/src/task/assignment.ts +136 -0
- package/src/task/autonomous-adapter.ts +168 -0
- package/src/task/autonomous-context.ts +630 -0
- package/src/task/autonomous-policy.ts +490 -0
- package/src/task/continuity.ts +179 -0
- package/src/task/execution-cancellation.ts +165 -0
- package/src/task/graph-validate.ts +379 -0
- package/src/task/graph.ts +305 -0
- package/src/task/identity.ts +230 -0
- package/src/task/model.ts +417 -0
- package/src/task/production-scheduler.ts +293 -0
- package/src/task/readiness.ts +229 -0
- package/src/task/scheduler-observability.ts +387 -0
- package/src/task/scheduler.ts +1197 -0
- package/src/task/scheduling-policy.ts +165 -0
- package/src/task/session-authority.ts +148 -0
- package/src/task/session-ownership.ts +211 -0
- package/src/task/store.ts +2887 -0
- package/src/task/sync.ts +343 -0
- package/src/task/trigger.ts +260 -0
- package/src/tools/bash.ts +377 -211
- package/src/tools/code_run.ts +1 -1
- package/src/tools/delete_file.ts +1 -1
- package/src/tools/edit.ts +33 -6
- package/src/tools/evidence.ts +30 -0
- package/src/tools/git.ts +4 -4
- package/src/tools/glob.ts +12 -3
- package/src/tools/grep.ts +1 -1
- package/src/tools/lsp.ts +4 -4
- package/src/tools/mcp_call.ts +11 -4
- package/src/tools/memory.ts +153 -18
- package/src/tools/move_file.ts +1 -1
- package/src/tools/patch.ts +1 -1
- package/src/tools/read_file.ts +1 -1
- package/src/tools/read_image.ts +1 -1
- package/src/tools/submit_result.ts +1 -1
- package/src/tools/task.ts +437 -41
- package/src/tools/todo.ts +662 -35
- package/src/tools/web_fetch.ts +4 -2
- package/src/tools/web_search.ts +9 -3
- package/src/tools/write_file.ts +1 -1
- package/src/ui/assistant/simple.ts +123 -50
- package/src/ui/assistant/turn-status.ts +17 -3
- package/src/ui/contract.ts +184 -0
- package/src/ui/footer.ts +54 -18
- package/src/ui/i18n/en.ts +62 -6
- package/src/ui/i18n/id.ts +62 -6
- package/src/ui/input/prompt-engine.ts +120 -25
- package/src/ui/render/errors.ts +39 -1
- package/src/ui/render/markdown-table.ts +455 -0
- package/src/ui/render/markdown.ts +22 -1
- package/src/ui/render/table-grid.ts +184 -0
- package/src/ui/render/table.ts +15 -76
- package/src/ui/runtime/screen.ts +7 -2
- package/src/ui/runtime/statusline.ts +25 -6
- package/src/ui/tui/app.ts +598 -133
- package/src/ui/tui/transcript.ts +531 -89
- package/vendor/minicore/VENDOR.md +1 -1
- package/vendor/minicore/src/core/budget.ts +25 -25
- package/vendor/minicore/src/core/compact.ts +75 -75
- package/vendor/minicore/src/core/errors.ts +59 -59
- package/vendor/minicore/src/core/events.ts +73 -73
- package/vendor/minicore/src/core/executor.ts +139 -139
- package/vendor/minicore/src/core/history.ts +31 -31
- package/vendor/minicore/src/core/index.ts +41 -41
- package/vendor/minicore/src/core/loop.ts +355 -355
- package/vendor/minicore/src/core/permission.ts +22 -22
- package/vendor/minicore/src/core/provider.ts +39 -39
- package/vendor/minicore/src/core/recovery.ts +35 -35
- package/vendor/minicore/src/core/session.ts +327 -327
- package/vendor/minicore/src/core/snapshot.ts +146 -146
- package/vendor/minicore/src/core/tokens.ts +107 -107
- package/vendor/minicore/src/core/tool.ts +115 -115
- package/vendor/minicore/src/core/types.ts +50 -50
- package/vendor/minicore/src/providers/openai-compat.ts +417 -417
- package/AGENTS.md +0 -45
- package/PLAN.md +0 -491
- package/docs/ARCHITECTURE.html +0 -1248
- package/docs/CONTROL-PLANE-MAP.md +0 -139
- package/docs/HARNESS.md +0 -150
- package/docs/SUMMARY.md +0 -52
- package/docs/UI_RENDER_PIPELINE.md +0 -165
- package/docs/USAGE.md +0 -11
|
@@ -1,355 +1,355 @@
|
|
|
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 the session permission mode for this turn's deps (a plain
|
|
14
|
-
* string or a live getter). Never throws — failure resolves to 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
|
-
// Two separate flags — policy-path and recovery-path compaction have
|
|
44
|
-
// different semantics. A single flag used to conflate them: a policy
|
|
45
|
-
// compaction burned the one recovery retry (though recovery was never
|
|
46
|
-
// tried), and vice versa. The recovery flag is ALWAYS set (a guard
|
|
47
|
-
// against an infinite loop: force_compact_and_retry is exempt from
|
|
48
|
-
// maxProviderRetries); the policy flag is set when a policy compaction
|
|
49
|
-
// is attempted (once per turn, guarding against per-step O(n) repeats).
|
|
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
|
-
// The reason distinguishes the trigger and whether compaction
|
|
69
|
-
// actually shrank the store (no-op = nothing evictable in messages;
|
|
70
|
-
// reporters must tell that apart from fixed system+schema overhead,
|
|
71
|
-
// which compaction never touches).
|
|
72
|
-
const reduced = s.store.messages.length < before;
|
|
73
|
-
s.events.emit({
|
|
74
|
-
type: "context:compacted",
|
|
75
|
-
reason: reduced ? `pressure:${pressure}` : `pressure:${pressure}:no-op`,
|
|
76
|
-
});
|
|
77
|
-
pressure = s.budget.evaluate({
|
|
78
|
-
usedTokens: contextTokens(s),
|
|
79
|
-
limitTokens: s.contextWindowTokens,
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
if (pressure === "critical" && compactedForBudget) {
|
|
83
|
-
throw new AgentError("budget_exceeded", "context window exceeded after compaction");
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Sample from the provider with deterministic recovery.
|
|
87
|
-
const toolCalls: ToolCall[] = [];
|
|
88
|
-
let text = "";
|
|
89
|
-
let reasoning = ""; // DeepSeek-style thinking content
|
|
90
|
-
let attempt = 0;
|
|
91
|
-
// The original ProviderError behind the current attempt (if any), kept so a
|
|
92
|
-
// terminal throw can carry it as `cause` — callers/CLI can then reach the
|
|
93
|
-
// provider category (auth, rate_limit, …) instead of only the message.
|
|
94
|
-
let providerError: ProviderError | undefined;
|
|
95
|
-
|
|
96
|
-
while (true) {
|
|
97
|
-
attempt++;
|
|
98
|
-
// Each attempt starts from a clean slate: a failed attempt must not leak
|
|
99
|
-
// its partial text or tool calls into the next one.
|
|
100
|
-
text = "";
|
|
101
|
-
reasoning = "";
|
|
102
|
-
toolCalls.length = 0;
|
|
103
|
-
providerError = undefined;
|
|
104
|
-
let action: RecoveryAction | null = null;
|
|
105
|
-
let errorMessage: string | undefined;
|
|
106
|
-
let completed: FinishReason | undefined;
|
|
107
|
-
try {
|
|
108
|
-
for await (const ev of s.provider.stream(buildRequest(s, modelOverride), signal)) {
|
|
109
|
-
if (signal.aborted) throw abortError(signal);
|
|
110
|
-
// Setelah finish: hanya `extension` (mis. usage/reasoning tail dari
|
|
111
|
-
// b.ai dll.) yang diterima — tidak boleh ada text/tool deltas baru,
|
|
112
|
-
// karena itu berarti output protokol rusak dan harus retryable error.
|
|
113
|
-
if (completed !== undefined) {
|
|
114
|
-
if (ev.type === "extension") {
|
|
115
|
-
s.events.emit({ type: "provider:extension", kind: ev.kind, data: ev.data });
|
|
116
|
-
continue;
|
|
117
|
-
}
|
|
118
|
-
throw new ProviderError("network", "provider stream emitted an event after finish");
|
|
119
|
-
}
|
|
120
|
-
switch (ev.type) {
|
|
121
|
-
case "text":
|
|
122
|
-
text += ev.text;
|
|
123
|
-
s.events.emit({ type: "provider:text", text: ev.text });
|
|
124
|
-
break;
|
|
125
|
-
case "extension":
|
|
126
|
-
s.events.emit({ type: "provider:extension", kind: ev.kind, data: ev.data });
|
|
127
|
-
if (ev.kind === "reasoning") reasoning += (ev.data as { text?: string }).text ?? "";
|
|
128
|
-
break;
|
|
129
|
-
case "tool_call":
|
|
130
|
-
toolCalls.push(snapshotToolCall({ id: ev.id, name: ev.name, args: ev.args }));
|
|
131
|
-
break;
|
|
132
|
-
case "finish":
|
|
133
|
-
completed = ev.reason;
|
|
134
|
-
break;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
if (signal.aborted) throw abortError(signal);
|
|
138
|
-
// A well-formed provider stream always ends with a finish event; a
|
|
139
|
-
// clean shutdown without one means the response was cut short, so treat
|
|
140
|
-
// it as a retryable provider error instead of silently accepting
|
|
141
|
-
// partial text or incomplete tool calls.
|
|
142
|
-
if (completed === undefined) {
|
|
143
|
-
throw new ProviderError("network", "stream ended without a finish reason");
|
|
144
|
-
}
|
|
145
|
-
if (completed === "length") {
|
|
146
|
-
errorMessage = "provider output reached length limit";
|
|
147
|
-
// onLength reads the RECOVERY flag — not the policy flag. A single
|
|
148
|
-
// flag used to let a policy compaction burn this recovery retry.
|
|
149
|
-
action = s.recovery.onLength(compactedForRecovery);
|
|
150
|
-
} else if (completed === "error") {
|
|
151
|
-
action = { type: "throw" };
|
|
152
|
-
errorMessage = "provider finished with error reason";
|
|
153
|
-
} else if (completed === "abort") {
|
|
154
|
-
action = { type: "throw" };
|
|
155
|
-
errorMessage = "provider aborted the stream";
|
|
156
|
-
}
|
|
157
|
-
} catch (error) {
|
|
158
|
-
const cause = toProviderError(error, signal);
|
|
159
|
-
providerError = cause;
|
|
160
|
-
s.events.emit({
|
|
161
|
-
type: "provider:extension",
|
|
162
|
-
kind: "error",
|
|
163
|
-
data: { category: cause.category, message: cause.message },
|
|
164
|
-
});
|
|
165
|
-
errorMessage = cause.message;
|
|
166
|
-
action = s.recovery.onError(cause, attempt);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
if (action === null) break;
|
|
170
|
-
switch (action.type) {
|
|
171
|
-
case "throw":
|
|
172
|
-
// `cause` is the original ProviderError when the throw came from a
|
|
173
|
-
// provider failure (category reachable by callers); it falls back to
|
|
174
|
-
// the recovery action for finish-reason throws (length/error/abort),
|
|
175
|
-
// which have no underlying ProviderError.
|
|
176
|
-
throw new AgentError("provider", errorMessage ?? "provider error", { cause: providerError ?? action });
|
|
177
|
-
case "force_compact_and_retry": {
|
|
178
|
-
if (compactedForRecovery)
|
|
179
|
-
throw new AgentError("budget_exceeded", errorMessage ?? "context too large", { cause: providerError ?? action });
|
|
180
|
-
await compactStore(s, signal);
|
|
181
|
-
// The recovery flag is ALWAYS set (even on no-op):
|
|
182
|
-
// force_compact_and_retry is exempt from maxProviderRetries, so a
|
|
183
|
-
// repeated no-op would otherwise loop forever.
|
|
184
|
-
compactedForRecovery = true;
|
|
185
|
-
s.events.emit({ type: "context:compacted", reason: "recovery" });
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
case "retry":
|
|
189
|
-
await delay(action.delayMs, signal);
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
// Dispatch.
|
|
195
|
-
if (signal.aborted) throw abortError(signal);
|
|
196
|
-
// Reasoning (DeepSeek-style thinking) disimpan di assistant message agar
|
|
197
|
-
// provider thinking-mode bisa menerima history (butuh reasoning_content).
|
|
198
|
-
const reasoningNote = reasoning.length ? { reasoning } : {};
|
|
199
|
-
if (toolCalls.length === 0) {
|
|
200
|
-
store.append({ role: "assistant", content: text, ...reasoningNote });
|
|
201
|
-
finalText = text || undefined;
|
|
202
|
-
break;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
const actionCalls = toolCalls.map(snapshotToolCall);
|
|
206
|
-
store.append({ role: "assistant", content: text, ...reasoningNote, toolCalls: actionCalls.map(snapshotToolCall) });
|
|
207
|
-
const started: Step = { index: stepIndex, toolCalls: actionCalls.map(snapshotToolCall), results: [] };
|
|
208
|
-
s.events.emit({ type: "step:started", step: snapshotStep(started) });
|
|
209
|
-
|
|
210
|
-
const deps: ExecutorDeps = {
|
|
211
|
-
registry: s.registry,
|
|
212
|
-
permissions: s.permissions,
|
|
213
|
-
events: s.events,
|
|
214
|
-
signal,
|
|
215
|
-
state: snapshotState(s.state),
|
|
216
|
-
maxResultTokens: s.toolResultMaxTokens,
|
|
217
|
-
cwd: s.cwd,
|
|
218
|
-
// Resolved per turn so a live getter reflects runtime mode changes
|
|
219
|
-
// in the next tool context. Failed resolution is undefined (safe).
|
|
220
|
-
permissionMode: resolvePermissionMode(s.permissionMode),
|
|
221
|
-
};
|
|
222
|
-
let rawResults: readonly ToolResult[];
|
|
223
|
-
try {
|
|
224
|
-
rawResults = await s.executor.execute(actionCalls.map(snapshotToolCall), deps);
|
|
225
|
-
} catch (error) {
|
|
226
|
-
if (signal.aborted) throw abortError(signal);
|
|
227
|
-
rawResults = actionCalls.map((call) =>
|
|
228
|
-
toolErrorResult(call, `executor error: ${error instanceof Error ? error.message : String(error)}`),
|
|
229
|
-
);
|
|
230
|
-
}
|
|
231
|
-
// The executor can outlive the turn when a tool ignores the abort signal
|
|
232
|
-
// and settles late. Never write those results back into the shared store
|
|
233
|
-
// after the turn has settled — a late result must not leak into the next
|
|
234
|
-
// run's history. (This is the only store mutation reachable across a
|
|
235
|
-
// suspension that can resolve after an abort; the other appends are
|
|
236
|
-
// synchronous relative to their awaits.)
|
|
237
|
-
if (signal.aborted) throw abortError(signal);
|
|
238
|
-
const results = pairToolResults(actionCalls, rawResults);
|
|
239
|
-
store.appendAll(results.map(snapshotToolResult));
|
|
240
|
-
|
|
241
|
-
const step: Step = {
|
|
242
|
-
index: stepIndex,
|
|
243
|
-
toolCalls: actionCalls.map(snapshotToolCall),
|
|
244
|
-
results: results.map(snapshotToolResult),
|
|
245
|
-
};
|
|
246
|
-
steps.push(step);
|
|
247
|
-
s.state.stepCount = stepIndex + 1;
|
|
248
|
-
s.events.emit({ type: "step:completed", step: snapshotStep(step) });
|
|
249
|
-
stepIndex++;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
const result: TurnResult = {
|
|
253
|
-
finalText,
|
|
254
|
-
steps,
|
|
255
|
-
usage: { turns: s.state.turnCount, steps: stepIndex },
|
|
256
|
-
};
|
|
257
|
-
s.state.stepCount = stepIndex;
|
|
258
|
-
return result;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
function buildRequest(s: SessionInternal, modelOverride?: string): StreamRequest {
|
|
262
|
-
const tools: ToolSchema[] = s.registry.list().map((tool) => ({
|
|
263
|
-
name: tool.name,
|
|
264
|
-
description: tool.description,
|
|
265
|
-
parameters: tool.parameters,
|
|
266
|
-
}));
|
|
267
|
-
return {
|
|
268
|
-
messages: snapshotMessages(s.store.messages),
|
|
269
|
-
tools: tools.length ? snapshotToolSchemas(tools) : undefined,
|
|
270
|
-
system: s.system,
|
|
271
|
-
model: modelOverride ?? s.model,
|
|
272
|
-
};
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
function pairToolResults(calls: readonly ToolCall[], results: readonly ToolResult[]): readonly ToolResult[] {
|
|
276
|
-
const byId = new Map<string, ToolResult[]>();
|
|
277
|
-
for (const result of results) {
|
|
278
|
-
const list = byId.get(result.toolCallId) ?? [];
|
|
279
|
-
list.push(result);
|
|
280
|
-
byId.set(result.toolCallId, list);
|
|
281
|
-
}
|
|
282
|
-
return calls.map((call) => {
|
|
283
|
-
const result = byId.get(call.id)?.shift();
|
|
284
|
-
if (!result) return toolErrorResult(call, `executor returned no result for tool call: ${call.id}`);
|
|
285
|
-
if (result.name !== call.name) {
|
|
286
|
-
return toolErrorResult(call, `executor returned result for "${result.name}" but call expected "${call.name}"`);
|
|
287
|
-
}
|
|
288
|
-
return snapshotToolResult(result);
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
function toolErrorResult(call: ToolCall, message: string): ToolResult {
|
|
293
|
-
return {
|
|
294
|
-
role: "tool",
|
|
295
|
-
toolCallId: call.id,
|
|
296
|
-
name: call.name,
|
|
297
|
-
content: message,
|
|
298
|
-
isError: true,
|
|
299
|
-
};
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
function toProviderError(error: unknown, signal: AbortSignal): ProviderError {
|
|
303
|
-
if (signal.aborted) throw abortError(signal);
|
|
304
|
-
if (error instanceof ProviderError) return error;
|
|
305
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
306
|
-
throw abortError(signal);
|
|
307
|
-
}
|
|
308
|
-
return new ProviderError("unknown", error instanceof Error ? error.message : String(error));
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
312
|
-
return new Promise((resolve, reject) => {
|
|
313
|
-
if (signal.aborted) {
|
|
314
|
-
reject(abortError(signal));
|
|
315
|
-
return;
|
|
316
|
-
}
|
|
317
|
-
const timer = setTimeout(() => {
|
|
318
|
-
cleanup();
|
|
319
|
-
resolve();
|
|
320
|
-
}, Math.max(0, ms));
|
|
321
|
-
const onAbort = () => {
|
|
322
|
-
clearTimeout(timer);
|
|
323
|
-
cleanup();
|
|
324
|
-
reject(abortError(signal));
|
|
325
|
-
};
|
|
326
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
327
|
-
function cleanup() {
|
|
328
|
-
signal.removeEventListener("abort", onAbort);
|
|
329
|
-
}
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
function contextTokens(s: SessionInternal): number {
|
|
334
|
-
// Single source in tokens.ts `estimateSessionContext` — shared by the
|
|
335
|
-
// loop and the Session getter so no duplicate estimator can drift.
|
|
336
|
-
return estimateSessionContext(s.store, s.system, s.registry.list(), s.estimator);
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
// The single compaction seam. Prefers the strategy's optional async method
|
|
340
|
-
// (LLM summary) and always falls back to the sync strategy on failure — an
|
|
341
|
-
// async compactor must never be able to crash the loop.
|
|
342
|
-
async function compactStore(s: SessionInternal, signal: AbortSignal): Promise<void> {
|
|
343
|
-
const opts = { keepRecentTurns: s.keepRecentTurns };
|
|
344
|
-
if (s.compaction.compactAsync) {
|
|
345
|
-
try {
|
|
346
|
-
const messages = await s.compaction.compactAsync(s.store, opts, signal);
|
|
347
|
-
s.store.replace(0, s.store.messages.length, messages);
|
|
348
|
-
return;
|
|
349
|
-
} catch (error) {
|
|
350
|
-
if (signal.aborted) throw abortError(signal);
|
|
351
|
-
// fall through to sync mechanical compaction
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
s.store.replace(0, s.store.messages.length, s.compaction.compact(s.store, opts));
|
|
355
|
-
}
|
|
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 the session permission mode for this turn's deps (a plain
|
|
14
|
+
* string or a live getter). Never throws — failure resolves to 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
|
+
// Two separate flags — policy-path and recovery-path compaction have
|
|
44
|
+
// different semantics. A single flag used to conflate them: a policy
|
|
45
|
+
// compaction burned the one recovery retry (though recovery was never
|
|
46
|
+
// tried), and vice versa. The recovery flag is ALWAYS set (a guard
|
|
47
|
+
// against an infinite loop: force_compact_and_retry is exempt from
|
|
48
|
+
// maxProviderRetries); the policy flag is set when a policy compaction
|
|
49
|
+
// is attempted (once per turn, guarding against per-step O(n) repeats).
|
|
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
|
+
// The reason distinguishes the trigger and whether compaction
|
|
69
|
+
// actually shrank the store (no-op = nothing evictable in messages;
|
|
70
|
+
// reporters must tell that apart from fixed system+schema overhead,
|
|
71
|
+
// which compaction never touches).
|
|
72
|
+
const reduced = s.store.messages.length < before;
|
|
73
|
+
s.events.emit({
|
|
74
|
+
type: "context:compacted",
|
|
75
|
+
reason: reduced ? `pressure:${pressure}` : `pressure:${pressure}:no-op`,
|
|
76
|
+
});
|
|
77
|
+
pressure = s.budget.evaluate({
|
|
78
|
+
usedTokens: contextTokens(s),
|
|
79
|
+
limitTokens: s.contextWindowTokens,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
if (pressure === "critical" && compactedForBudget) {
|
|
83
|
+
throw new AgentError("budget_exceeded", "context window exceeded after compaction");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Sample from the provider with deterministic recovery.
|
|
87
|
+
const toolCalls: ToolCall[] = [];
|
|
88
|
+
let text = "";
|
|
89
|
+
let reasoning = ""; // DeepSeek-style thinking content
|
|
90
|
+
let attempt = 0;
|
|
91
|
+
// The original ProviderError behind the current attempt (if any), kept so a
|
|
92
|
+
// terminal throw can carry it as `cause` — callers/CLI can then reach the
|
|
93
|
+
// provider category (auth, rate_limit, …) instead of only the message.
|
|
94
|
+
let providerError: ProviderError | undefined;
|
|
95
|
+
|
|
96
|
+
while (true) {
|
|
97
|
+
attempt++;
|
|
98
|
+
// Each attempt starts from a clean slate: a failed attempt must not leak
|
|
99
|
+
// its partial text or tool calls into the next one.
|
|
100
|
+
text = "";
|
|
101
|
+
reasoning = "";
|
|
102
|
+
toolCalls.length = 0;
|
|
103
|
+
providerError = undefined;
|
|
104
|
+
let action: RecoveryAction | null = null;
|
|
105
|
+
let errorMessage: string | undefined;
|
|
106
|
+
let completed: FinishReason | undefined;
|
|
107
|
+
try {
|
|
108
|
+
for await (const ev of s.provider.stream(buildRequest(s, modelOverride), signal)) {
|
|
109
|
+
if (signal.aborted) throw abortError(signal);
|
|
110
|
+
// Setelah finish: hanya `extension` (mis. usage/reasoning tail dari
|
|
111
|
+
// b.ai dll.) yang diterima — tidak boleh ada text/tool deltas baru,
|
|
112
|
+
// karena itu berarti output protokol rusak dan harus retryable error.
|
|
113
|
+
if (completed !== undefined) {
|
|
114
|
+
if (ev.type === "extension") {
|
|
115
|
+
s.events.emit({ type: "provider:extension", kind: ev.kind, data: ev.data });
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
throw new ProviderError("network", "provider stream emitted an event after finish");
|
|
119
|
+
}
|
|
120
|
+
switch (ev.type) {
|
|
121
|
+
case "text":
|
|
122
|
+
text += ev.text;
|
|
123
|
+
s.events.emit({ type: "provider:text", text: ev.text });
|
|
124
|
+
break;
|
|
125
|
+
case "extension":
|
|
126
|
+
s.events.emit({ type: "provider:extension", kind: ev.kind, data: ev.data });
|
|
127
|
+
if (ev.kind === "reasoning") reasoning += (ev.data as { text?: string }).text ?? "";
|
|
128
|
+
break;
|
|
129
|
+
case "tool_call":
|
|
130
|
+
toolCalls.push(snapshotToolCall({ id: ev.id, name: ev.name, args: ev.args }));
|
|
131
|
+
break;
|
|
132
|
+
case "finish":
|
|
133
|
+
completed = ev.reason;
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (signal.aborted) throw abortError(signal);
|
|
138
|
+
// A well-formed provider stream always ends with a finish event; a
|
|
139
|
+
// clean shutdown without one means the response was cut short, so treat
|
|
140
|
+
// it as a retryable provider error instead of silently accepting
|
|
141
|
+
// partial text or incomplete tool calls.
|
|
142
|
+
if (completed === undefined) {
|
|
143
|
+
throw new ProviderError("network", "stream ended without a finish reason");
|
|
144
|
+
}
|
|
145
|
+
if (completed === "length") {
|
|
146
|
+
errorMessage = "provider output reached length limit";
|
|
147
|
+
// onLength reads the RECOVERY flag — not the policy flag. A single
|
|
148
|
+
// flag used to let a policy compaction burn this recovery retry.
|
|
149
|
+
action = s.recovery.onLength(compactedForRecovery);
|
|
150
|
+
} else if (completed === "error") {
|
|
151
|
+
action = { type: "throw" };
|
|
152
|
+
errorMessage = "provider finished with error reason";
|
|
153
|
+
} else if (completed === "abort") {
|
|
154
|
+
action = { type: "throw" };
|
|
155
|
+
errorMessage = "provider aborted the stream";
|
|
156
|
+
}
|
|
157
|
+
} catch (error) {
|
|
158
|
+
const cause = toProviderError(error, signal);
|
|
159
|
+
providerError = cause;
|
|
160
|
+
s.events.emit({
|
|
161
|
+
type: "provider:extension",
|
|
162
|
+
kind: "error",
|
|
163
|
+
data: { category: cause.category, message: cause.message },
|
|
164
|
+
});
|
|
165
|
+
errorMessage = cause.message;
|
|
166
|
+
action = s.recovery.onError(cause, attempt);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (action === null) break;
|
|
170
|
+
switch (action.type) {
|
|
171
|
+
case "throw":
|
|
172
|
+
// `cause` is the original ProviderError when the throw came from a
|
|
173
|
+
// provider failure (category reachable by callers); it falls back to
|
|
174
|
+
// the recovery action for finish-reason throws (length/error/abort),
|
|
175
|
+
// which have no underlying ProviderError.
|
|
176
|
+
throw new AgentError("provider", errorMessage ?? "provider error", { cause: providerError ?? action });
|
|
177
|
+
case "force_compact_and_retry": {
|
|
178
|
+
if (compactedForRecovery)
|
|
179
|
+
throw new AgentError("budget_exceeded", errorMessage ?? "context too large", { cause: providerError ?? action });
|
|
180
|
+
await compactStore(s, signal);
|
|
181
|
+
// The recovery flag is ALWAYS set (even on no-op):
|
|
182
|
+
// force_compact_and_retry is exempt from maxProviderRetries, so a
|
|
183
|
+
// repeated no-op would otherwise loop forever.
|
|
184
|
+
compactedForRecovery = true;
|
|
185
|
+
s.events.emit({ type: "context:compacted", reason: "recovery" });
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
case "retry":
|
|
189
|
+
await delay(action.delayMs, signal);
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Dispatch.
|
|
195
|
+
if (signal.aborted) throw abortError(signal);
|
|
196
|
+
// Reasoning (DeepSeek-style thinking) disimpan di assistant message agar
|
|
197
|
+
// provider thinking-mode bisa menerima history (butuh reasoning_content).
|
|
198
|
+
const reasoningNote = reasoning.length ? { reasoning } : {};
|
|
199
|
+
if (toolCalls.length === 0) {
|
|
200
|
+
store.append({ role: "assistant", content: text, ...reasoningNote });
|
|
201
|
+
finalText = text || undefined;
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const actionCalls = toolCalls.map(snapshotToolCall);
|
|
206
|
+
store.append({ role: "assistant", content: text, ...reasoningNote, toolCalls: actionCalls.map(snapshotToolCall) });
|
|
207
|
+
const started: Step = { index: stepIndex, toolCalls: actionCalls.map(snapshotToolCall), results: [] };
|
|
208
|
+
s.events.emit({ type: "step:started", step: snapshotStep(started) });
|
|
209
|
+
|
|
210
|
+
const deps: ExecutorDeps = {
|
|
211
|
+
registry: s.registry,
|
|
212
|
+
permissions: s.permissions,
|
|
213
|
+
events: s.events,
|
|
214
|
+
signal,
|
|
215
|
+
state: snapshotState(s.state),
|
|
216
|
+
maxResultTokens: s.toolResultMaxTokens,
|
|
217
|
+
cwd: s.cwd,
|
|
218
|
+
// Resolved per turn so a live getter reflects runtime mode changes
|
|
219
|
+
// in the next tool context. Failed resolution is undefined (safe).
|
|
220
|
+
permissionMode: resolvePermissionMode(s.permissionMode),
|
|
221
|
+
};
|
|
222
|
+
let rawResults: readonly ToolResult[];
|
|
223
|
+
try {
|
|
224
|
+
rawResults = await s.executor.execute(actionCalls.map(snapshotToolCall), deps);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
if (signal.aborted) throw abortError(signal);
|
|
227
|
+
rawResults = actionCalls.map((call) =>
|
|
228
|
+
toolErrorResult(call, `executor error: ${error instanceof Error ? error.message : String(error)}`),
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
// The executor can outlive the turn when a tool ignores the abort signal
|
|
232
|
+
// and settles late. Never write those results back into the shared store
|
|
233
|
+
// after the turn has settled — a late result must not leak into the next
|
|
234
|
+
// run's history. (This is the only store mutation reachable across a
|
|
235
|
+
// suspension that can resolve after an abort; the other appends are
|
|
236
|
+
// synchronous relative to their awaits.)
|
|
237
|
+
if (signal.aborted) throw abortError(signal);
|
|
238
|
+
const results = pairToolResults(actionCalls, rawResults);
|
|
239
|
+
store.appendAll(results.map(snapshotToolResult));
|
|
240
|
+
|
|
241
|
+
const step: Step = {
|
|
242
|
+
index: stepIndex,
|
|
243
|
+
toolCalls: actionCalls.map(snapshotToolCall),
|
|
244
|
+
results: results.map(snapshotToolResult),
|
|
245
|
+
};
|
|
246
|
+
steps.push(step);
|
|
247
|
+
s.state.stepCount = stepIndex + 1;
|
|
248
|
+
s.events.emit({ type: "step:completed", step: snapshotStep(step) });
|
|
249
|
+
stepIndex++;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const result: TurnResult = {
|
|
253
|
+
finalText,
|
|
254
|
+
steps,
|
|
255
|
+
usage: { turns: s.state.turnCount, steps: stepIndex },
|
|
256
|
+
};
|
|
257
|
+
s.state.stepCount = stepIndex;
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function buildRequest(s: SessionInternal, modelOverride?: string): StreamRequest {
|
|
262
|
+
const tools: ToolSchema[] = s.registry.list().map((tool) => ({
|
|
263
|
+
name: tool.name,
|
|
264
|
+
description: tool.description,
|
|
265
|
+
parameters: tool.parameters,
|
|
266
|
+
}));
|
|
267
|
+
return {
|
|
268
|
+
messages: snapshotMessages(s.store.messages),
|
|
269
|
+
tools: tools.length ? snapshotToolSchemas(tools) : undefined,
|
|
270
|
+
system: s.system,
|
|
271
|
+
model: modelOverride ?? s.model,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function pairToolResults(calls: readonly ToolCall[], results: readonly ToolResult[]): readonly ToolResult[] {
|
|
276
|
+
const byId = new Map<string, ToolResult[]>();
|
|
277
|
+
for (const result of results) {
|
|
278
|
+
const list = byId.get(result.toolCallId) ?? [];
|
|
279
|
+
list.push(result);
|
|
280
|
+
byId.set(result.toolCallId, list);
|
|
281
|
+
}
|
|
282
|
+
return calls.map((call) => {
|
|
283
|
+
const result = byId.get(call.id)?.shift();
|
|
284
|
+
if (!result) return toolErrorResult(call, `executor returned no result for tool call: ${call.id}`);
|
|
285
|
+
if (result.name !== call.name) {
|
|
286
|
+
return toolErrorResult(call, `executor returned result for "${result.name}" but call expected "${call.name}"`);
|
|
287
|
+
}
|
|
288
|
+
return snapshotToolResult(result);
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function toolErrorResult(call: ToolCall, message: string): ToolResult {
|
|
293
|
+
return {
|
|
294
|
+
role: "tool",
|
|
295
|
+
toolCallId: call.id,
|
|
296
|
+
name: call.name,
|
|
297
|
+
content: message,
|
|
298
|
+
isError: true,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function toProviderError(error: unknown, signal: AbortSignal): ProviderError {
|
|
303
|
+
if (signal.aborted) throw abortError(signal);
|
|
304
|
+
if (error instanceof ProviderError) return error;
|
|
305
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
306
|
+
throw abortError(signal);
|
|
307
|
+
}
|
|
308
|
+
return new ProviderError("unknown", error instanceof Error ? error.message : String(error));
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
|
312
|
+
return new Promise((resolve, reject) => {
|
|
313
|
+
if (signal.aborted) {
|
|
314
|
+
reject(abortError(signal));
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const timer = setTimeout(() => {
|
|
318
|
+
cleanup();
|
|
319
|
+
resolve();
|
|
320
|
+
}, Math.max(0, ms));
|
|
321
|
+
const onAbort = () => {
|
|
322
|
+
clearTimeout(timer);
|
|
323
|
+
cleanup();
|
|
324
|
+
reject(abortError(signal));
|
|
325
|
+
};
|
|
326
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
327
|
+
function cleanup() {
|
|
328
|
+
signal.removeEventListener("abort", onAbort);
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function contextTokens(s: SessionInternal): number {
|
|
334
|
+
// Single source in tokens.ts `estimateSessionContext` — shared by the
|
|
335
|
+
// loop and the Session getter so no duplicate estimator can drift.
|
|
336
|
+
return estimateSessionContext(s.store, s.system, s.registry.list(), s.estimator);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// The single compaction seam. Prefers the strategy's optional async method
|
|
340
|
+
// (LLM summary) and always falls back to the sync strategy on failure — an
|
|
341
|
+
// async compactor must never be able to crash the loop.
|
|
342
|
+
async function compactStore(s: SessionInternal, signal: AbortSignal): Promise<void> {
|
|
343
|
+
const opts = { keepRecentTurns: s.keepRecentTurns };
|
|
344
|
+
if (s.compaction.compactAsync) {
|
|
345
|
+
try {
|
|
346
|
+
const messages = await s.compaction.compactAsync(s.store, opts, signal);
|
|
347
|
+
s.store.replace(0, s.store.messages.length, messages);
|
|
348
|
+
return;
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (signal.aborted) throw abortError(signal);
|
|
351
|
+
// fall through to sync mechanical compaction
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
s.store.replace(0, s.store.messages.length, s.compaction.compact(s.store, opts));
|
|
355
|
+
}
|