minicode-ai 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/LICENSE +21 -21
- package/README.md +4 -0
- package/cli/args.ts +50 -2
- package/cli/commands/acp.ts +18 -3
- package/cli/commands/daemon.ts +114 -19
- package/cli/commands/exec.ts +95 -7
- package/cli/commands/mcp.ts +66 -5
- package/cli/commands/memory.ts +46 -14
- package/cli/commands.ts +5 -0
- package/cli/index.ts +30 -5
- package/cli/minicode.js +6 -0
- package/cli/setup.ts +365 -24
- package/cli/tui.ts +72 -27
- package/docs/TERMINAL_CONTRACT.md +91 -24
- package/docs/agents.md +2 -2
- package/docs/cli.md +1 -0
- package/docs/environment.md +1 -0
- package/docs/memory-sessions.md +5 -0
- package/package.json +3 -2
- package/src/app/session.ts +153 -35
- package/src/app/tool-layer.ts +67 -61
- package/src/daemon/approvals.ts +25 -1
- package/src/daemon/client.ts +51 -1
- package/src/daemon/control.ts +8 -0
- package/src/daemon/protocol.ts +47 -1
- package/src/daemon/server.ts +45 -9
- package/src/daemon/subscription.ts +25 -1
- package/src/daemon/telemetry.ts +4 -0
- package/src/hooks/run.ts +5 -1
- package/src/mcp/client.ts +349 -90
- package/src/mcp/http-transport.ts +7 -0
- package/src/mcp/transport.ts +5 -0
- package/src/memory/files.ts +69 -3
- package/src/memory/vector.ts +556 -160
- package/src/policy/approval-binding.ts +199 -0
- package/src/policy/context.ts +20 -1
- package/src/policy/executor.ts +44 -5
- package/src/policy/permission.ts +243 -26
- package/src/policy/tool-contract.ts +77 -0
- package/src/policy/usage.ts +3 -1
- package/src/policy/work-mode.ts +49 -1
- package/src/presentation/adapter.ts +157 -7
- package/src/presentation/events.ts +173 -1
- package/src/presentation/model.ts +37 -0
- package/src/presentation/projection.ts +107 -18
- package/src/presentation/reducer.ts +134 -10
- package/src/sandbox/os.ts +18 -1
- package/src/session/persistence.ts +153 -11
- package/src/task/store.ts +43 -3
- package/src/tools/memory.ts +70 -10
- package/src/tools/task.ts +7 -1
- package/src/tools/todo.ts +14 -4
- package/src/ui/approval/prompt.ts +52 -7
- package/src/ui/assistant/simple.ts +160 -57
- package/src/ui/contract.ts +46 -0
- package/src/ui/footer.ts +14 -5
- package/src/ui/i18n/en.ts +9 -0
- package/src/ui/i18n/id.ts +9 -0
- package/src/ui/render/collapse.ts +24 -52
- package/src/ui/render/detail.ts +14 -9
- package/src/ui/render/errors.ts +8 -0
- package/src/ui/render/reasoning.ts +13 -8
- package/src/ui/session-state.ts +243 -0
- package/src/ui/tui/app.ts +7 -3
- package/src/ui/tui/transcript.ts +271 -30
- 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
|
@@ -1,60 +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" }
|
|
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
60
|
| { type: "throw" };
|
|
@@ -1,74 +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
|
-
};
|
|
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
74
|
}
|
|
@@ -1,139 +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
|
-
// Optional handler diagnostic, surfaced so the model observes an
|
|
60
|
-
// actionable reason ("permission denied: <reason>"). Diagnostic-only:
|
|
61
|
-
// describeDenial must never fail the denial itself — hence the guard.
|
|
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
|
-
}
|
|
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
|
+
// Optional handler diagnostic, surfaced so the model observes an
|
|
60
|
+
// actionable reason ("permission denied: <reason>"). Diagnostic-only:
|
|
61
|
+
// describeDenial must never fail the denial itself — hence the guard.
|
|
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
|
+
}
|
|
@@ -1,32 +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
|
-
}
|
|
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
32
|
}
|