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,76 @@
|
|
|
1
|
+
// Compaction: a deterministic, LLM-free strategy. Replaces old turns with a
|
|
2
|
+
// bounded summary while preserving the recent tail verbatim. It never splits
|
|
3
|
+
// an assistant tool_call message from its following tool results.
|
|
4
|
+
|
|
5
|
+
import type { ContextStore } from "./history.ts";
|
|
6
|
+
import type { Message } from "./types.ts";
|
|
7
|
+
import { contentToText, safeStringify } from "./tokens.ts";
|
|
8
|
+
|
|
9
|
+
export interface CompactionStrategy {
|
|
10
|
+
readonly kind: string;
|
|
11
|
+
compact(store: ContextStore, opts: { keepRecentTurns: number }): readonly Message[];
|
|
12
|
+
/**
|
|
13
|
+
* Optional async compaction. If present, the loop prefers this over `compact`
|
|
14
|
+
* (sync). Must return the new messages array (or same if no compaction needed).
|
|
15
|
+
* The loop expects this to respect `signal` (abort → reject). If it throws,
|
|
16
|
+
* the loop falls back to `compact` (sync mechanical) — never crash the loop.
|
|
17
|
+
* The signal is the turn's abort signal (user abort, session.abort, timeout).
|
|
18
|
+
*/
|
|
19
|
+
compactAsync?(store: ContextStore, opts: { keepRecentTurns: number }, signal: AbortSignal): Promise<readonly Message[]>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const mechanicalCompaction: CompactionStrategy = {
|
|
23
|
+
kind: "mechanical",
|
|
24
|
+
compact(store, { keepRecentTurns }) {
|
|
25
|
+
const messages = store.messages;
|
|
26
|
+
let kept = 0;
|
|
27
|
+
let turns = 0;
|
|
28
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
29
|
+
kept++;
|
|
30
|
+
if (messages[i]!.role === "user") turns++;
|
|
31
|
+
if (turns >= keepRecentTurns) break;
|
|
32
|
+
}
|
|
33
|
+
// Never leave a tool result dangling: extend the kept region across a
|
|
34
|
+
// tool's call batch (assistant → tool results) so results stay paired.
|
|
35
|
+
while (kept < messages.length) {
|
|
36
|
+
const cut = messages.length - kept;
|
|
37
|
+
const firstKept = messages[cut]!;
|
|
38
|
+
const prev = messages[cut - 1];
|
|
39
|
+
const extendsPair =
|
|
40
|
+
firstKept.role === "tool" &&
|
|
41
|
+
prev !== undefined &&
|
|
42
|
+
(prev.role === "tool" || (prev.role === "assistant" && prev.toolCalls !== undefined && prev.toolCalls.length > 0));
|
|
43
|
+
if (extendsPair) kept++;
|
|
44
|
+
else break;
|
|
45
|
+
}
|
|
46
|
+
if (kept >= messages.length) return messages;
|
|
47
|
+
const prefix = messages.slice(0, messages.length - kept);
|
|
48
|
+
const summary: Message = {
|
|
49
|
+
role: "user",
|
|
50
|
+
content: `Previous context:\n${prefix.map(compactLine).join("\n")}`,
|
|
51
|
+
};
|
|
52
|
+
return [summary, ...messages.slice(-kept)];
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function compactLine(message: Message): string {
|
|
57
|
+
switch (message.role) {
|
|
58
|
+
case "user":
|
|
59
|
+
return `- user: ${head(contentToText(message.content), 400)}`;
|
|
60
|
+
case "assistant": {
|
|
61
|
+
const calls = (message.toolCalls ?? [])
|
|
62
|
+
.map((call) => `${call.name}(${head(safeStringify(call.args), 80)})`)
|
|
63
|
+
.join(", ");
|
|
64
|
+
return `- assistant${calls ? ` [calls: ${calls}]` : ""}: ${head(contentToText(message.content), 400)}`;
|
|
65
|
+
}
|
|
66
|
+
case "tool":
|
|
67
|
+
if (message.isError) return `- tool(${message.name}): ${head(String(message.content), 200)}`;
|
|
68
|
+
return `- tool(${message.name}): <result omitted>`;
|
|
69
|
+
default:
|
|
70
|
+
return "";
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function head(text: string, max: number): string {
|
|
75
|
+
return text.length <= max ? text : `${text.slice(0, max)}…`;
|
|
76
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Provider-agnostic error taxonomy and recovery actions.
|
|
2
|
+
|
|
3
|
+
/** The deterministic reasons a kernel `run()` can settle with. */
|
|
4
|
+
export type AgentErrorKind =
|
|
5
|
+
| "busy"
|
|
6
|
+
| "aborted"
|
|
7
|
+
| "timeout"
|
|
8
|
+
| "max_steps_exceeded"
|
|
9
|
+
| "budget_exceeded"
|
|
10
|
+
| "provider";
|
|
11
|
+
|
|
12
|
+
/** Kernel-side failure, always carrying a `kind` from `AgentErrorKind`. */
|
|
13
|
+
export class AgentError extends Error {
|
|
14
|
+
readonly name = "AgentError";
|
|
15
|
+
constructor(
|
|
16
|
+
readonly kind: AgentErrorKind,
|
|
17
|
+
message: string,
|
|
18
|
+
options?: { cause?: unknown },
|
|
19
|
+
) {
|
|
20
|
+
super(message, options);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Turn an aborted signal into the AgentError it carries. When the kernel
|
|
26
|
+
* aborts a signal with a reason (e.g. a timeout), that reason is preserved so
|
|
27
|
+
* callers can distinguish "timed out" from "user aborted".
|
|
28
|
+
*/
|
|
29
|
+
export function abortError(signal: AbortSignal): AgentError {
|
|
30
|
+
return signal.reason instanceof AgentError ? signal.reason : new AgentError("aborted", "turn aborted");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Normalized provider failure categories produced by adapters. */
|
|
34
|
+
export type ProviderErrorCategory =
|
|
35
|
+
| "rate_limit"
|
|
36
|
+
| "network"
|
|
37
|
+
| "server"
|
|
38
|
+
| "auth"
|
|
39
|
+
| "invalid_request"
|
|
40
|
+
| "context_length_exceeded"
|
|
41
|
+
| "unknown";
|
|
42
|
+
|
|
43
|
+
/** Provider-side failure, normalized by an adapter into a category. */
|
|
44
|
+
export class ProviderError extends Error {
|
|
45
|
+
readonly name = "ProviderError";
|
|
46
|
+
constructor(
|
|
47
|
+
readonly category: ProviderErrorCategory,
|
|
48
|
+
message: string,
|
|
49
|
+
readonly retryAfterMs?: number,
|
|
50
|
+
cause?: unknown,
|
|
51
|
+
) {
|
|
52
|
+
super(message, { cause });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** What the recovery policy tells the loop to do after a provider failure. */
|
|
57
|
+
export type RecoveryAction =
|
|
58
|
+
| { type: "retry"; delayMs: number }
|
|
59
|
+
| { type: "force_compact_and_retry" }
|
|
60
|
+
| { type: "throw" };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Typed event bus for observability and lifecycles.
|
|
2
|
+
|
|
3
|
+
import type { Execution, Step, TurnResult } from "./session.ts";
|
|
4
|
+
|
|
5
|
+
export type AgentEvent =
|
|
6
|
+
| { type: "turn:started"; turn: number }
|
|
7
|
+
| { type: "turn:completed"; result: TurnResult }
|
|
8
|
+
| { type: "step:started"; step: Step }
|
|
9
|
+
| { type: "step:completed"; step: Step }
|
|
10
|
+
| { type: "execution:started"; execution: Execution }
|
|
11
|
+
| { type: "execution:completed"; execution: Execution }
|
|
12
|
+
| { type: "provider:text"; text: string }
|
|
13
|
+
| { type: "provider:extension"; kind: string; data: unknown }
|
|
14
|
+
| { type: "context:compacted"; reason: string };
|
|
15
|
+
|
|
16
|
+
export type AgentEventType = AgentEvent["type"];
|
|
17
|
+
|
|
18
|
+
export interface EventBus {
|
|
19
|
+
on<const T extends AgentEventType | "*">(
|
|
20
|
+
type: T,
|
|
21
|
+
handler: T extends "*" ? (event: AgentEvent) => void : (event: Extract<AgentEvent, { type: T }>) => void,
|
|
22
|
+
): () => void;
|
|
23
|
+
emit(event: AgentEvent): void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface EventBusOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Reports errors thrown by event listeners. Observers must never be able to
|
|
29
|
+
* break the agent: emit catches every handler, reports the failure here, and
|
|
30
|
+
* continues with the remaining listeners. Defaults to console.error.
|
|
31
|
+
*/
|
|
32
|
+
onHandlerError?: (error: unknown, event: AgentEvent) => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function createEventBus(options?: EventBusOptions): EventBus {
|
|
36
|
+
const handlers = new Map<string, Set<(event: AgentEvent) => void>>();
|
|
37
|
+
const report =
|
|
38
|
+
options?.onHandlerError ??
|
|
39
|
+
((error: unknown, event: AgentEvent) => {
|
|
40
|
+
console.error(`event handler for "${event.type}" failed`, error);
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
on(type, handler) {
|
|
44
|
+
const wrapped = handler as (event: AgentEvent) => void;
|
|
45
|
+
const set = handlers.get(type) ?? new Set<(event: AgentEvent) => void>();
|
|
46
|
+
set.add(wrapped);
|
|
47
|
+
handlers.set(type, set);
|
|
48
|
+
return () => {
|
|
49
|
+
set.delete(wrapped);
|
|
50
|
+
};
|
|
51
|
+
},
|
|
52
|
+
emit(event) {
|
|
53
|
+
// Per-handler isolation: a crashing observer (UI, logging, metrics) must
|
|
54
|
+
// neither kill the turn nor escape into surrounding try/catches (which
|
|
55
|
+
// used to turn listener crashes into spurious retries). The error is
|
|
56
|
+
// reported and the remaining listeners still run.
|
|
57
|
+
const run = (handler: (event: AgentEvent) => void) => {
|
|
58
|
+
try {
|
|
59
|
+
handler(event);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
try {
|
|
62
|
+
report(error, event);
|
|
63
|
+
} catch {
|
|
64
|
+
// The reporter itself must not be able to break the emit.
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const set = handlers.get(event.type);
|
|
69
|
+
if (set) for (const handler of set) run(handler);
|
|
70
|
+
const all = handlers.get("*");
|
|
71
|
+
if (all) for (const handler of all) run(handler);
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Tool executor boundary. The kernel ships a sequential strategy; a parallel
|
|
2
|
+
// strategy can be added later by implementing the same interface, without
|
|
3
|
+
// changing the kernel. Each call runs the same deterministic pipeline:
|
|
4
|
+
// resolve → permission → validate → execute → normalize/truncate.
|
|
5
|
+
|
|
6
|
+
import { validateArgs } from "./tool.ts";
|
|
7
|
+
import type { ToolRegistry } from "./tool.ts";
|
|
8
|
+
import type { PermissionHandler } from "./permission.ts";
|
|
9
|
+
import type { EventBus } from "./events.ts";
|
|
10
|
+
import type { SessionState } from "./session.ts";
|
|
11
|
+
import type { Execution } from "./session.ts";
|
|
12
|
+
import type { ToolCall, ToolResult } from "./types.ts";
|
|
13
|
+
import { DEFAULT_CHARS_PER_TOKEN } from "./tokens.ts";
|
|
14
|
+
import { abortError } from "./errors.ts";
|
|
15
|
+
import { snapshotExecution, snapshotState, snapshotToolCall } from "./snapshot.ts";
|
|
16
|
+
|
|
17
|
+
export interface ExecutorDeps {
|
|
18
|
+
readonly registry: ToolRegistry;
|
|
19
|
+
readonly permissions: PermissionHandler;
|
|
20
|
+
readonly events: EventBus;
|
|
21
|
+
readonly signal: AbortSignal;
|
|
22
|
+
readonly state: Readonly<SessionState>;
|
|
23
|
+
readonly maxResultTokens: number;
|
|
24
|
+
readonly cwd?: string;
|
|
25
|
+
readonly permissionMode?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ToolExecutor {
|
|
29
|
+
execute(calls: readonly ToolCall[], deps: ExecutorDeps): Promise<readonly ToolResult[]>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const errorResult = (call: ToolCall, message: string): ToolResult => ({
|
|
33
|
+
role: "tool",
|
|
34
|
+
toolCallId: call.id,
|
|
35
|
+
name: call.name,
|
|
36
|
+
content: message,
|
|
37
|
+
isError: true,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
export async function runCall(call: ToolCall, deps: ExecutorDeps): Promise<ToolResult> {
|
|
41
|
+
throwIfAborted(deps.signal);
|
|
42
|
+
const safeCall = snapshotToolCall(call);
|
|
43
|
+
const tool = deps.registry.get(safeCall.name);
|
|
44
|
+
if (!tool) return errorResult(safeCall, `unknown tool: ${safeCall.name}`);
|
|
45
|
+
|
|
46
|
+
// The permission handler is user/policy code and may throw. Treat a crash
|
|
47
|
+
// exactly like a tool error: a deterministic error result (observation),
|
|
48
|
+
// never a raw rejection that escapes run() without an error taxonomy.
|
|
49
|
+
let decision: Awaited<ReturnType<PermissionHandler["check"]>>;
|
|
50
|
+
const permissionDeps: ExecutorDeps = { ...deps, state: snapshotState(deps.state) };
|
|
51
|
+
try {
|
|
52
|
+
decision = await deps.permissions.check(snapshotToolCall(safeCall), permissionDeps);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
throwIfAborted(deps.signal);
|
|
55
|
+
return errorResult(safeCall, `permission error: ${error instanceof Error ? error.message : String(error)}`);
|
|
56
|
+
}
|
|
57
|
+
throwIfAborted(deps.signal);
|
|
58
|
+
if (decision === "deny") {
|
|
59
|
+
// Additive seam (minicode): alasan deny opsional dari handler agar
|
|
60
|
+
// observasi model actionable ("permission denied: bash-guard: ...").
|
|
61
|
+
// describeDenial tak boleh menggagalkan denial itu sendiri — bungkus.
|
|
62
|
+
let suffix = "";
|
|
63
|
+
try {
|
|
64
|
+
const r = await deps.permissions.describeDenial?.(snapshotToolCall(safeCall));
|
|
65
|
+
if (typeof r === "string" && r.trim()) suffix = `: ${r.trim().slice(0, 160)}`;
|
|
66
|
+
} catch {
|
|
67
|
+
/* reason is diagnostic-only; the denial stands */
|
|
68
|
+
}
|
|
69
|
+
return errorResult(safeCall, `permission denied${suffix}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const parsed = validateArgs(tool.parameters, safeCall.args);
|
|
73
|
+
if (!parsed.ok) return errorResult(safeCall, `invalid arguments: ${parsed.message}`);
|
|
74
|
+
throwIfAborted(deps.signal);
|
|
75
|
+
|
|
76
|
+
const ctx = {
|
|
77
|
+
signal: deps.signal,
|
|
78
|
+
state: snapshotState(deps.state),
|
|
79
|
+
emit: deps.events.emit,
|
|
80
|
+
cwd: deps.cwd,
|
|
81
|
+
permissionMode: deps.permissionMode,
|
|
82
|
+
};
|
|
83
|
+
// Started and completed events carry separate result objects so listeners
|
|
84
|
+
// that retain the execution reference never observe later mutation.
|
|
85
|
+
const started: Execution = { call: safeCall, result: { role: "tool", toolCallId: safeCall.id, name: safeCall.name, content: "" } };
|
|
86
|
+
deps.events.emit({ type: "execution:started", execution: snapshotExecution(started) });
|
|
87
|
+
let result: ToolResult;
|
|
88
|
+
try {
|
|
89
|
+
const content = await tool.execute(parsed.value, ctx);
|
|
90
|
+
throwIfAborted(deps.signal);
|
|
91
|
+
result = { role: "tool", toolCallId: safeCall.id, name: safeCall.name, content: serializeContent(content, deps.maxResultTokens) };
|
|
92
|
+
} catch (error) {
|
|
93
|
+
throwIfAborted(deps.signal);
|
|
94
|
+
result = {
|
|
95
|
+
role: "tool",
|
|
96
|
+
toolCallId: safeCall.id,
|
|
97
|
+
name: safeCall.name,
|
|
98
|
+
content: error instanceof Error ? error.message : String(error),
|
|
99
|
+
isError: true,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
deps.events.emit({ type: "execution:completed", execution: snapshotExecution({ call: safeCall, result }) });
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function sequentialExecutor(): ToolExecutor {
|
|
107
|
+
return {
|
|
108
|
+
async execute(calls, deps) {
|
|
109
|
+
const results: ToolResult[] = [];
|
|
110
|
+
for (const call of calls) {
|
|
111
|
+
throwIfAborted(deps.signal);
|
|
112
|
+
results.push(await runCall(call, deps));
|
|
113
|
+
}
|
|
114
|
+
return results;
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function throwIfAborted(signal: AbortSignal): void {
|
|
120
|
+
if (signal.aborted) throw abortError(signal);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function serializeContent(value: unknown, maxTokens: number): unknown {
|
|
124
|
+
if (value instanceof Uint8Array) return value;
|
|
125
|
+
let text: string;
|
|
126
|
+
if (typeof value === "string") text = value;
|
|
127
|
+
else {
|
|
128
|
+
try {
|
|
129
|
+
text = JSON.stringify(value, null, 2) ?? String(value);
|
|
130
|
+
} catch {
|
|
131
|
+
text = String(value);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const maxChars = maxTokens * DEFAULT_CHARS_PER_TOKEN;
|
|
135
|
+
if (text.length <= maxChars) return text;
|
|
136
|
+
const headLen = Math.max(0, Math.floor(maxChars * 0.7));
|
|
137
|
+
const tailLen = Math.max(0, maxChars - headLen - 12);
|
|
138
|
+
return `${text.slice(0, headLen)}\n…[truncated]…\n${text.slice(-tailLen)}`;
|
|
139
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Context storage: an append-only, transformable message buffer.
|
|
2
|
+
// Storage only — token policy and compaction are separate modules.
|
|
3
|
+
|
|
4
|
+
import type { Message } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The kernel's context buffer. Append-only in normal operation; `replace` is
|
|
8
|
+
* the single seam for compaction. `messages` exposes the live buffer typed as
|
|
9
|
+
* read-only — mutating it via a cast would corrupt the kernel's history, so
|
|
10
|
+
* treat it as immutable.
|
|
11
|
+
*/
|
|
12
|
+
export class ContextStore {
|
|
13
|
+
#messages: Message[] = [];
|
|
14
|
+
|
|
15
|
+
/** Live view of the buffer. Read-only by type; never cast and mutate. */
|
|
16
|
+
get messages(): readonly Message[] {
|
|
17
|
+
return this.#messages;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
append(message: Message): void {
|
|
21
|
+
this.#messages.push(message);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
appendAll(messages: readonly Message[]): void {
|
|
25
|
+
this.#messages.push(...messages);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Replace `deleteCount` messages starting at `start` with `replacement`. */
|
|
29
|
+
replace(start: number, deleteCount: number, replacement: readonly Message[]): void {
|
|
30
|
+
this.#messages.splice(start, deleteCount, ...replacement);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// MiniCore — public surface. Everything the kernel exposes intentionally.
|
|
2
|
+
// Providers, tools, memory, UI, and storage live outside this file.
|
|
3
|
+
|
|
4
|
+
export type { Message, UserMessage, AssistantMessage, ToolResult, ToolCall, Content, ContentPart } from "./types.ts";
|
|
5
|
+
export { AgentError, ProviderError, abortError } from "./errors.ts";
|
|
6
|
+
export type { AgentErrorKind, ProviderErrorCategory, RecoveryAction } from "./errors.ts";
|
|
7
|
+
export type { ModelProvider, StreamRequest, ProviderEvent, FinishReason } from "./provider.ts";
|
|
8
|
+
export type { Tool, ToolSchema, JSONSchema, ToolContext, ToolRegistry, ArgsResult } from "./tool.ts";
|
|
9
|
+
export { validateArgs, createToolRegistry } from "./tool.ts";
|
|
10
|
+
export type { ToolExecutor, ExecutorDeps } from "./executor.ts";
|
|
11
|
+
export { runCall, sequentialExecutor } from "./executor.ts";
|
|
12
|
+
export type { PermissionHandler, Decision } from "./permission.ts";
|
|
13
|
+
export type { TokenEstimator } from "./tokens.ts";
|
|
14
|
+
export {
|
|
15
|
+
defaultTokenEstimator,
|
|
16
|
+
estimateImageTokens,
|
|
17
|
+
estimateMessage,
|
|
18
|
+
estimateMessages,
|
|
19
|
+
estimateTools,
|
|
20
|
+
estimateSystem,
|
|
21
|
+
estimateSessionContext,
|
|
22
|
+
contentToText,
|
|
23
|
+
DEFAULT_CHARS_PER_TOKEN,
|
|
24
|
+
} from "./tokens.ts";
|
|
25
|
+
export type { BudgetPolicy, BudgetState, PressureLevel } from "./budget.ts";
|
|
26
|
+
export { defaultBudgetPolicy } from "./budget.ts";
|
|
27
|
+
export type { CompactionStrategy } from "./compact.ts";
|
|
28
|
+
export { mechanicalCompaction } from "./compact.ts";
|
|
29
|
+
export type { RecoveryPolicy } from "./recovery.ts";
|
|
30
|
+
export { defaultRecoveryPolicy, maxProviderRetries } from "./recovery.ts";
|
|
31
|
+
export type { AgentEvent, AgentEventType, EventBus, EventBusOptions } from "./events.ts";
|
|
32
|
+
export { createEventBus } from "./events.ts";
|
|
33
|
+
export { ContextStore } from "./history.ts";
|
|
34
|
+
export type { Session, SessionConfig, SessionState, TurnResult, Step, Execution } from "./session.ts";
|
|
35
|
+
export {
|
|
36
|
+
createSession,
|
|
37
|
+
DEFAULT_MAX_STEPS,
|
|
38
|
+
DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
39
|
+
DEFAULT_TOOL_RESULT_MAX_TOKENS,
|
|
40
|
+
DEFAULT_KEEP_RECENT_TURNS,
|
|
41
|
+
DEFAULT_TIMEOUT_MS,
|
|
42
|
+
} from "./session.ts";
|