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.
Files changed (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,327 @@
1
+ // Session: configuration binding + lifecycle records. The loop lives in
2
+ // loop.ts; this module only composes the parts and exposes a minimal API.
3
+
4
+ import type { BudgetPolicy } from "./budget.ts";
5
+ import { defaultBudgetPolicy } from "./budget.ts";
6
+ import type { CompactionStrategy } from "./compact.ts";
7
+ import { mechanicalCompaction } from "./compact.ts";
8
+ import { AgentError, abortError } from "./errors.ts";
9
+ import type { AgentEvent, EventBus } from "./events.ts";
10
+ import { createEventBus } from "./events.ts";
11
+ import type { ToolExecutor } from "./executor.ts";
12
+ import { sequentialExecutor } from "./executor.ts";
13
+ import { ContextStore } from "./history.ts";
14
+ import type { PermissionHandler } from "./permission.ts";
15
+ import type { ModelProvider } from "./provider.ts";
16
+ import type { RecoveryPolicy } from "./recovery.ts";
17
+ import { defaultRecoveryPolicy } from "./recovery.ts";
18
+ import { executeTurn } from "./loop.ts";
19
+ import { snapshotState, snapshotTurnResult } from "./snapshot.ts";
20
+ import type { Tool, ToolRegistry } from "./tool.ts";
21
+ import { createToolRegistry } from "./tool.ts";
22
+ import type { TokenEstimator } from "./tokens.ts";
23
+ import { defaultTokenEstimator, estimateSessionContext } from "./tokens.ts";
24
+ import type { Message, ToolCall, ToolResult } from "./types.ts";
25
+
26
+ export const DEFAULT_MAX_STEPS = 50;
27
+ export const DEFAULT_CONTEXT_WINDOW_TOKENS = 128_000;
28
+ export const DEFAULT_TOOL_RESULT_MAX_TOKENS = 4_096;
29
+ export const DEFAULT_KEEP_RECENT_TURNS = 3;
30
+
31
+ export const DEFAULT_TIMEOUT_MS = 600_000;
32
+
33
+ export interface SessionConfig {
34
+ provider: ModelProvider;
35
+ permissions: PermissionHandler;
36
+ tools?: readonly Tool[];
37
+ system?: string;
38
+ model?: string;
39
+ cwd?: string;
40
+ /**
41
+ * Mode permission sesi, diteruskan ke ToolContext tiap turn agar tool
42
+ * (mis. delegate_task) bisa menyesuaikan perilaku. String atau getter
43
+ * live — getter disarankan bila mode bisa berubah saat runtime.
44
+ * Opsional; absen = perilaku lama (ctx.permissionMode undefined).
45
+ */
46
+ permissionMode?: string | (() => string);
47
+ /**
48
+ * Seed history untuk sesi baru (mis. resume dari storage). Messages akan
49
+ * di-append ke ContextStore saat createSession, jadi `session.state.history`
50
+ * langsung memuatnya dan turn berikutnya meneruskan konteks penuh.
51
+ */
52
+ initialMessages?: readonly Message[];
53
+ turnCount?: number;
54
+ stepCount?: number;
55
+ executor?: ToolExecutor;
56
+ budget?: BudgetPolicy;
57
+ estimator?: TokenEstimator;
58
+ compaction?: CompactionStrategy;
59
+ recovery?: RecoveryPolicy;
60
+ maxSteps?: number;
61
+ contextWindowTokens?: number;
62
+ toolResultMaxTokens?: number;
63
+ keepRecentTurns?: number;
64
+ /**
65
+ * Hard deadline for a single run() call, in milliseconds. When exceeded, the
66
+ * turn is aborted and run() rejects with AgentError("timeout") — even if the
67
+ * in-flight provider/tool ignores the abort signal. Defaults to
68
+ * DEFAULT_TIMEOUT_MS (10 minutes); set to Infinity to disable.
69
+ */
70
+ timeoutMs?: number;
71
+ /**
72
+ * Reports errors thrown by event listeners. Observer code must never be able
73
+ * to break a turn (lifecycle/executor events) nor trigger a spurious retry
74
+ * (provider streaming events): emit catches every handler error, reports it
75
+ * here, and continues. Defaults to console.error.
76
+ */
77
+ onHandlerError?: (error: unknown, event: AgentEvent) => void;
78
+ }
79
+
80
+ export interface SessionState {
81
+ readonly history: readonly Message[];
82
+ turnCount: number;
83
+ stepCount: number;
84
+ readonly model?: string;
85
+ }
86
+
87
+ export interface Execution {
88
+ readonly call: ToolCall;
89
+ readonly result: ToolResult;
90
+ }
91
+
92
+ export interface Step {
93
+ readonly index: number;
94
+ readonly toolCalls: readonly ToolCall[];
95
+ readonly results: readonly ToolResult[];
96
+ }
97
+
98
+ export interface TurnResult {
99
+ readonly steps: readonly Step[];
100
+ readonly finalText?: string;
101
+ readonly usage: { readonly turns: number; readonly steps: number };
102
+ }
103
+
104
+ export interface Session {
105
+ /**
106
+ * Point-in-time defensive snapshot of the committed session state.
107
+ *
108
+ * Each access deep-copies the committed history and counters, so a
109
+ * same-process caller that casts away the read-only types and mutates the
110
+ * result can never corrupt the kernel's state (the committed history that
111
+ * feeds the next turn) — the mutation touches only the caller's copy.
112
+ *
113
+ * Semantics: the returned value is a snapshot, not a live view. A reference
114
+ * held across a run stays frozen at the moment it was read; re-access
115
+ * `session.state` for fresh data. Committed state changes only when a turn
116
+ * completes successfully, and for change notification prefer the event bus
117
+ * (`turn:completed`, `step:completed`). Cost is O(history) per access, so
118
+ * read once per turn rather than polling.
119
+ */
120
+ readonly state: Readonly<SessionState>;
121
+ readonly events: EventBus;
122
+ /**
123
+ * Kontrak control-plane (Phase 6): angka konteks SAAT INI dari sumber
124
+ * kebenaran yang sama dengan pressure kernel (messages + system + tools,
125
+ * estimator sesi). Satu angka untuk driver/UI/budget — tanpa estimator
126
+ * duplikat. O(history) per akses (pola state snapshot); setiap akses
127
+ * menghitung ulang atas committed store.
128
+ */
129
+ readonly contextTokens: number;
130
+ run(input: string, opts?: { signal?: AbortSignal; model?: string }): Promise<TurnResult>;
131
+ abort(): void;
132
+ }
133
+
134
+ /** Internal handle consumed by loop.ts. Not part of the public surface. */
135
+ export interface SessionInternal {
136
+ readonly provider: ModelProvider;
137
+ readonly permissions: PermissionHandler;
138
+ readonly registry: ToolRegistry;
139
+ readonly executor: ToolExecutor;
140
+ readonly system?: string;
141
+ readonly model?: string;
142
+ readonly cwd?: string;
143
+ readonly permissionMode?: string | (() => string);
144
+ readonly budget: BudgetPolicy;
145
+ readonly estimator: TokenEstimator;
146
+ readonly compaction: CompactionStrategy;
147
+ readonly recovery: RecoveryPolicy;
148
+ readonly maxSteps: number;
149
+ readonly contextWindowTokens: number;
150
+ readonly toolResultMaxTokens: number;
151
+ readonly keepRecentTurns: number;
152
+ readonly timeoutMs: number;
153
+ readonly store: ContextStore;
154
+ readonly events: EventBus;
155
+ readonly state: SessionState;
156
+ }
157
+
158
+ interface SessionImpl extends SessionInternal {
159
+ sessionAbort: AbortController;
160
+ running: boolean;
161
+ }
162
+
163
+ export function createSession(config: SessionConfig): Session {
164
+ const store = new ContextStore();
165
+ if (config.initialMessages?.length) store.appendAll(config.initialMessages);
166
+ const events = createEventBus({ onHandlerError: config.onHandlerError });
167
+ const sessionAbort = new AbortController();
168
+ const state: SessionState = {
169
+ history: store.messages,
170
+ turnCount: config.turnCount ?? 0,
171
+ stepCount: config.stepCount ?? 0,
172
+ model: config.model,
173
+ };
174
+
175
+ const impl: SessionImpl = {
176
+ provider: config.provider,
177
+ permissions: config.permissions,
178
+ registry: createToolRegistry(config.tools ?? []),
179
+ executor: config.executor ?? sequentialExecutor(),
180
+ system: config.system,
181
+ model: config.model,
182
+ cwd: config.cwd,
183
+ permissionMode: config.permissionMode,
184
+ budget: config.budget ?? defaultBudgetPolicy,
185
+ estimator: config.estimator ?? defaultTokenEstimator,
186
+ compaction: config.compaction ?? mechanicalCompaction,
187
+ recovery: config.recovery ?? defaultRecoveryPolicy,
188
+ maxSteps: config.maxSteps ?? DEFAULT_MAX_STEPS,
189
+ contextWindowTokens: config.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS,
190
+ toolResultMaxTokens: config.toolResultMaxTokens ?? DEFAULT_TOOL_RESULT_MAX_TOKENS,
191
+ keepRecentTurns: config.keepRecentTurns ?? DEFAULT_KEEP_RECENT_TURNS,
192
+ timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
193
+ store,
194
+ events,
195
+ state,
196
+ sessionAbort,
197
+ running: false,
198
+ };
199
+
200
+ return {
201
+ // Public state crosses a host boundary, so it is a defensive snapshot per
202
+ // access (same policy as provider requests, tool ctx.state, and event
203
+ // payloads). The kernel keeps the raw object internally via `impl.state`.
204
+ get state() {
205
+ return snapshotState(state);
206
+ },
207
+ get events() {
208
+ return events;
209
+ },
210
+ // Kontrak (Phase 6): angka dari sumber kebenaran yang sama dengan loop —
211
+ // estimateSessionContext (tokens.ts), bukan estimator duplikat.
212
+ get contextTokens() {
213
+ return estimateSessionContext(store, config.system, impl.registry.list(), impl.estimator);
214
+ },
215
+ async run(input, opts) {
216
+ if (impl.running) throw new AgentError("busy", "session is already running");
217
+ impl.running = true;
218
+ const timeout = createTimeout(impl.timeoutMs);
219
+ const joined = joinSignals(impl.sessionAbort.signal, opts?.signal, timeout.signal);
220
+ const turnStore = new ContextStore();
221
+ turnStore.appendAll(store.messages);
222
+ const turnState: SessionState = {
223
+ history: turnStore.messages,
224
+ turnCount: state.turnCount,
225
+ stepCount: state.stepCount,
226
+ model: opts?.model ?? config.model,
227
+ };
228
+ const turnImpl: SessionInternal = {
229
+ ...impl,
230
+ store: turnStore,
231
+ state: turnState,
232
+ };
233
+ try {
234
+ const turn = executeTurn(turnImpl, input, joined.signal, opts?.model);
235
+ // The race guarantees run() rejects as soon as the joined signal
236
+ // aborts (user abort, session.abort, or timeout), even if the
237
+ // in-flight provider/tool ignores the signal. Any late work mutates
238
+ // only turnStore and is discarded.
239
+ const result = await withAbort(turn, joined.signal);
240
+ // A run is transactional with respect to model context: failed,
241
+ // aborted, or timed-out turns are discarded instead of leaving orphaned
242
+ // user messages or assistant tool_calls without matching tool results.
243
+ // Non-cooperative providers/tools may still settle after withTimeout
244
+ // rejects, but they mutate only this private turnStore.
245
+ store.replace(0, store.messages.length, turnStore.messages);
246
+ state.turnCount = turnState.turnCount;
247
+ state.stepCount = turnState.stepCount;
248
+ events.emit({ type: "turn:completed", result: snapshotTurnResult(result) });
249
+ return result;
250
+ } finally {
251
+ timeout.cancel();
252
+ joined.cleanup();
253
+ impl.running = false;
254
+ if (impl.sessionAbort.signal.aborted) impl.sessionAbort = new AbortController();
255
+ }
256
+ },
257
+ abort() {
258
+ if (impl.running) impl.sessionAbort.abort(new AgentError("aborted", "turn aborted"));
259
+ },
260
+ };
261
+ }
262
+
263
+ function joinSignals(...signals: Array<AbortSignal | undefined>): { signal: AbortSignal; cleanup(): void } {
264
+ const active = signals.filter((s): s is AbortSignal => s !== undefined);
265
+ if (active.length <= 1) {
266
+ return active[0] ? { signal: active[0], cleanup: noop } : { signal: new AbortController().signal, cleanup: noop };
267
+ }
268
+ const alreadyAborted = active.find((s) => s.aborted);
269
+ if (alreadyAborted) return { signal: alreadyAborted, cleanup: noop };
270
+ const controller = new AbortController();
271
+ const handlers: Array<[AbortSignal, () => void]> = active.map((s) => {
272
+ const onAbort = () => controller.abort(s.reason);
273
+ s.addEventListener("abort", onAbort, { once: true });
274
+ return [s, onAbort];
275
+ });
276
+ return {
277
+ signal: controller.signal,
278
+ cleanup() {
279
+ for (const [signal, onAbort] of handlers) signal.removeEventListener("abort", onAbort);
280
+ },
281
+ };
282
+ }
283
+
284
+ function noop(): void {}
285
+
286
+ interface Timeout {
287
+ readonly signal: AbortSignal;
288
+ cancel(): void;
289
+ }
290
+
291
+ function createTimeout(ms: number): Timeout {
292
+ const controller = new AbortController();
293
+ const error = new AgentError("timeout", `turn exceeded ${ms}ms`);
294
+ // setTimeout clamps a non-finite delay to 1ms in Node/Bun, so Infinity would
295
+ // abort the turn almost immediately instead of disabling the deadline.
296
+ const timer = Number.isFinite(ms) ? setTimeout(() => controller.abort(error), ms) : undefined;
297
+ return {
298
+ signal: controller.signal,
299
+ cancel: () => {
300
+ if (timer !== undefined) clearTimeout(timer);
301
+ },
302
+ };
303
+ }
304
+
305
+ function withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
306
+ if (signal.aborted) return Promise.reject(abortError(signal));
307
+ return new Promise((resolve, reject) => {
308
+ const onAbort = () => {
309
+ cleanup();
310
+ reject(abortError(signal));
311
+ };
312
+ signal.addEventListener("abort", onAbort, { once: true });
313
+ promise.then(
314
+ (value) => {
315
+ cleanup();
316
+ resolve(value);
317
+ },
318
+ (cause) => {
319
+ cleanup();
320
+ reject(cause);
321
+ },
322
+ );
323
+ function cleanup() {
324
+ signal.removeEventListener("abort", onAbort);
325
+ }
326
+ });
327
+ }
@@ -0,0 +1,142 @@
1
+ // Defensive snapshots for crossing host/provider/observer boundaries. The
2
+ // kernel keeps mutable buffers internally, but external adapters, tools,
3
+ // executors, and event listeners must not receive references that can corrupt
4
+ // runtime state or alter in-flight actions.
5
+
6
+ import type { Execution, SessionState, Step, TurnResult } from "./session.ts";
7
+ import type { ToolSchema } from "./tool.ts";
8
+ import type { AssistantMessage, Content, ContentPart, Message, ToolCall, ToolResult } from "./types.ts";
9
+
10
+ export function snapshotMessages(messages: readonly Message[]): Message[] {
11
+ return messages.map(snapshotMessage);
12
+ }
13
+
14
+ function snapshotMessage(message: Message): Message {
15
+ switch (message.role) {
16
+ case "user":
17
+ return { role: "user", content: snapshotContent(message.content) };
18
+ case "assistant":
19
+ return snapshotAssistant(message);
20
+ case "tool":
21
+ return snapshotToolResult(message);
22
+ }
23
+ }
24
+
25
+ export function snapshotToolCall(call: ToolCall): ToolCall {
26
+ return {
27
+ id: call.id,
28
+ name: call.name,
29
+ args: snapshotValue(call.args),
30
+ };
31
+ }
32
+
33
+ export function snapshotToolResult(result: ToolResult): ToolResult {
34
+ const out: ToolResult = {
35
+ role: "tool",
36
+ toolCallId: result.toolCallId,
37
+ name: result.name,
38
+ content: snapshotValue(result.content),
39
+ };
40
+ return result.isError === undefined ? out : { ...out, isError: result.isError };
41
+ }
42
+
43
+ export function snapshotToolSchemas(tools: readonly ToolSchema[]): ToolSchema[] {
44
+ return tools.map((toolSchema) => ({
45
+ name: toolSchema.name,
46
+ description: toolSchema.description,
47
+ parameters: snapshotValue(toolSchema.parameters),
48
+ }));
49
+ }
50
+
51
+ export function snapshotState(state: Readonly<SessionState>): SessionState {
52
+ return {
53
+ history: snapshotMessages(state.history),
54
+ turnCount: state.turnCount,
55
+ stepCount: state.stepCount,
56
+ model: state.model,
57
+ };
58
+ }
59
+
60
+ export function snapshotExecution(execution: Execution): Execution {
61
+ return {
62
+ call: snapshotToolCall(execution.call),
63
+ result: snapshotToolResult(execution.result),
64
+ };
65
+ }
66
+
67
+ export function snapshotStep(step: Step): Step {
68
+ return {
69
+ index: step.index,
70
+ toolCalls: step.toolCalls.map(snapshotToolCall),
71
+ results: step.results.map(snapshotToolResult),
72
+ };
73
+ }
74
+
75
+ export function snapshotTurnResult(result: TurnResult): TurnResult {
76
+ return {
77
+ finalText: result.finalText,
78
+ steps: result.steps.map(snapshotStep),
79
+ usage: { turns: result.usage.turns, steps: result.usage.steps },
80
+ };
81
+ }
82
+
83
+ function snapshotAssistant(message: AssistantMessage): AssistantMessage {
84
+ const base: AssistantMessage = {
85
+ role: "assistant",
86
+ content: snapshotContent(message.content),
87
+ };
88
+ const withReasoning = message.reasoning === undefined ? base : { ...base, reasoning: message.reasoning };
89
+ return message.toolCalls === undefined
90
+ ? withReasoning
91
+ : { ...withReasoning, toolCalls: message.toolCalls.map(snapshotToolCall) };
92
+ }
93
+
94
+ function snapshotContent(content: Content): Content {
95
+ if (typeof content === "string") return content;
96
+ return content.map(snapshotContentPart);
97
+ }
98
+
99
+ function snapshotContentPart(part: ContentPart): ContentPart {
100
+ switch (part.type) {
101
+ case "text":
102
+ return { type: "text", text: part.text };
103
+ case "image":
104
+ return { type: "image", mime: part.mime, data: part.data.slice() };
105
+ }
106
+ }
107
+
108
+ function snapshotValue<T>(value: T): T {
109
+ if (value instanceof Uint8Array) return value.slice() as T;
110
+ try {
111
+ return structuredClone(value);
112
+ } catch {
113
+ return clonePlainValue(value) as T;
114
+ }
115
+ }
116
+
117
+ function clonePlainValue(value: unknown, seen = new WeakMap<object, unknown>()): unknown {
118
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return value;
119
+ if (value instanceof Uint8Array) return value.slice();
120
+ if (typeof value === "function") return value;
121
+ const existing = seen.get(value);
122
+ if (existing) return existing;
123
+ if (Array.isArray(value)) {
124
+ const out: unknown[] = [];
125
+ seen.set(value, out);
126
+ for (const item of value) out.push(clonePlainValue(item, seen));
127
+ return out;
128
+ }
129
+ const proto = Object.getPrototypeOf(value);
130
+ if (proto !== Object.prototype && proto !== null) return value;
131
+ const out = Object.create(proto) as Record<string, unknown>;
132
+ seen.set(value, out);
133
+ for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
134
+ Object.defineProperty(out, key, {
135
+ value: clonePlainValue(child, seen),
136
+ enumerable: true,
137
+ writable: true,
138
+ configurable: true,
139
+ });
140
+ }
141
+ return out;
142
+ }
@@ -0,0 +1,111 @@
1
+ // Token estimation: an injectable policy. The kernel's default is a plain
2
+ // chars/4 heuristic — swap it per model without touching the kernel.
3
+ // Truncation in executor.ts must stay in the same unit as this heuristic, so
4
+ // the chars-per-token factor lives here as the single source of truth.
5
+
6
+ import type { ToolSchema } from "./tool.ts";
7
+ import type { Content, Message } from "./types.ts";
8
+
9
+ export const DEFAULT_CHARS_PER_TOKEN = 4;
10
+
11
+ export type TokenEstimator = (text: string) => number;
12
+
13
+ export const defaultTokenEstimator: TokenEstimator = (text) => Math.ceil(text.length / DEFAULT_CHARS_PER_TOKEN);
14
+
15
+ export function contentToText(content: Content): string {
16
+ if (typeof content === "string") return content;
17
+ return content.map((part) => (part.type === "text" ? part.text : `[image:${part.mime}]`)).join("\n");
18
+ }
19
+
20
+ /**
21
+ * Additive seam (minicode): estimasi token sadar-gambar. Gambar inline
22
+ * membawa byte base64 (~bytes/3 token) — placeholder `[image:mime]` lama
23
+ * membuat gambar 100k hanya ~15 token (tak terlihat budget → kompaksi tak
24
+ * jalan sampai konteks benar-benar jebol). Rumus sama dengan
25
+ * src/policy/context.ts estimateImageTokens agar laporan read_image dan
26
+ * budget konsisten.
27
+ */
28
+ export function estimateImageTokens(byteLength: number): number {
29
+ return Math.ceil(Math.ceil((byteLength * 4) / 3) / DEFAULT_CHARS_PER_TOKEN);
30
+ }
31
+
32
+ function estimateContent(content: Content, est: TokenEstimator): number {
33
+ if (typeof content === "string") return est(content);
34
+ let total = 0;
35
+ for (const part of content) {
36
+ if (part.type === "text") total += est(part.text);
37
+ else total += estimateImageTokens(part.data.byteLength);
38
+ }
39
+ return total;
40
+ }
41
+
42
+ /**
43
+ * JSON.stringify that never throws: cyclic values (possible only from hostile
44
+ * or buggy input) fall back to a plain string instead of leaking a raw
45
+ * TypeError through the kernel's deterministic error taxonomy.
46
+ */
47
+ export function safeStringify(value: unknown): string {
48
+ try {
49
+ return JSON.stringify(value) ?? String(value);
50
+ } catch {
51
+ return String(value);
52
+ }
53
+ }
54
+
55
+ export function estimateMessage(message: Message, est: TokenEstimator): number {
56
+ switch (message.role) {
57
+ case "user":
58
+ return estimateContent(message.content, est);
59
+ case "assistant":
60
+ return estimateContent(message.content, est) + est(safeStringify(message.toolCalls ?? [])) + est(message.reasoning ?? "");
61
+ case "tool": {
62
+ const c = message.content;
63
+ // Hasil tool biner (mis. gambar): JSON.stringify Uint8Array meledak
64
+ // jadi {"0":..} raksasa → tekanan palsu → kompaksi prematur. Estimasi
65
+ // sebagai gambar, bukan string JSON.
66
+ if (c instanceof Uint8Array) return estimateImageTokens(c.byteLength);
67
+ return est(typeof c === "string" ? c : safeStringify(c ?? null));
68
+ }
69
+ default:
70
+ return 0;
71
+ }
72
+ }
73
+
74
+ export function estimateMessages(messages: readonly Message[], est: TokenEstimator): number {
75
+ let total = 0;
76
+ for (const message of messages) total += estimateMessage(message, est);
77
+ return total;
78
+ }
79
+
80
+ /** The fixed per-request cost of the tool schemas sent with every call. */
81
+ export function estimateTools(tools: readonly ToolSchema[], est: TokenEstimator): number {
82
+ let total = 0;
83
+ for (const tool of tools) total += est(tool.name) + est(tool.description) + est(safeStringify(tool.parameters));
84
+ return total;
85
+ }
86
+
87
+ /** The fixed per-request cost of the system prompt. */
88
+ export function estimateSystem(system: string | undefined, est: TokenEstimator): number {
89
+ return system ? est(system) : 0;
90
+ }
91
+
92
+ /**
93
+ * Seam kontrak control-plane (Phase 6): SATU sumber angka konteks —
94
+ * messages + system + tools, semuanya yang dikirim per request. Dipakai
95
+ * loop (pressure) DAN Session getter (ekspos ke driver/UI/budget) sehingga
96
+ * tidak ada estimator duplikat untuk kebutuhan tampilan. Fungsi murni atas
97
+ * argumen — tidak ada ketergantungan SessionInternal (menghindari circular
98
+ * import session↔loop).
99
+ */
100
+ export function estimateSessionContext(
101
+ store: { messages: readonly Message[] },
102
+ system: string | undefined,
103
+ tools: readonly ToolSchema[],
104
+ est: TokenEstimator,
105
+ ): number {
106
+ return (
107
+ estimateMessages(store.messages, est) +
108
+ estimateSystem(system, est) +
109
+ estimateTools(tools, est)
110
+ );
111
+ }
@@ -0,0 +1,118 @@
1
+ // Tool abstraction: declarative schemas + deterministic argument validation.
2
+
3
+ import type { AgentEvent } from "./events.ts";
4
+ import type { SessionState } from "./session.ts";
5
+
6
+ export interface JSONSchema {
7
+ readonly type?: "object" | "string" | "number" | "integer" | "boolean" | "array" | "null";
8
+ readonly description?: string;
9
+ readonly properties?: Readonly<Record<string, JSONSchema>>;
10
+ readonly required?: readonly string[];
11
+ readonly items?: JSONSchema;
12
+ readonly enum?: readonly unknown[];
13
+ readonly additionalProperties?: boolean;
14
+ }
15
+
16
+ export interface ToolSchema {
17
+ readonly name: string;
18
+ readonly description: string;
19
+ readonly parameters: JSONSchema;
20
+ }
21
+
22
+ export interface ToolContext {
23
+ readonly signal: AbortSignal;
24
+ readonly state: Readonly<SessionState>;
25
+ readonly cwd?: string;
26
+ /**
27
+ * Mode permission sesi saat tool dipanggil (mis. "auto" | "plan").
28
+ * Opsional agar backward-compat; tool yang peduli (mis. delegate_task
29
+ * yang harus mengunci sub-agen saat parent read-only) membaca ini
30
+ * alih-alih menebak dari teks prompt. Di-resolve per turn dari
31
+ * SessionConfig (boleh string atau getter live agar Shift+Tab runtime
32
+ * ikut tercermin).
33
+ */
34
+ readonly permissionMode?: string;
35
+ emit(event: AgentEvent): void;
36
+ }
37
+
38
+ export interface Tool<P = unknown> extends ToolSchema {
39
+ execute(input: P, ctx: ToolContext): Promise<unknown>;
40
+ }
41
+
42
+ export type ArgsResult<A = unknown> = { ok: true; value: A } | { ok: false; message: string };
43
+
44
+ const error = (message: string): { ok: false; message: string } => ({ ok: false, message });
45
+
46
+ // Assignment via `out[key] = value` would treat "__proto__" as a setter and
47
+ // swap the result object's prototype (prototype pollution). defineProperty
48
+ // always creates an own property instead.
49
+ function setOwn(out: Record<string, unknown>, key: string, value: unknown): void {
50
+ Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true });
51
+ }
52
+
53
+ /** Deterministically validate `args` against a JSON schema (kernel built-in). */
54
+ export function validateArgs<A = unknown>(schema: JSONSchema, args: unknown): ArgsResult<A> {
55
+ if (schema.properties || schema.type === "object") {
56
+ if (typeof args !== "object" || args === null || Array.isArray(args)) return error("expected an object");
57
+ const record = args as Record<string, unknown>;
58
+ const out: Record<string, unknown> = {};
59
+ for (const key of schema.required ?? []) {
60
+ if (!(key in record)) return error(`missing required property: ${key}`);
61
+ }
62
+ for (const [key, value] of Object.entries(record)) {
63
+ const sub = schema.properties?.[key];
64
+ if (sub) {
65
+ const result = validateArgs(sub, value);
66
+ if (!result.ok) return error(`${key}: ${result.message}`);
67
+ setOwn(out, key, result.value);
68
+ } else if (schema.additionalProperties === false) {
69
+ return error(`unknown property: ${key}`);
70
+ } else {
71
+ setOwn(out, key, value);
72
+ }
73
+ }
74
+ return { ok: true, value: out as A };
75
+ }
76
+ if (schema.enum) {
77
+ if (!schema.enum.some((v) => Object.is(v, args))) return error("value not allowed");
78
+ return { ok: true, value: args as A };
79
+ }
80
+ switch (schema.type) {
81
+ case "string":
82
+ return typeof args === "string" ? { ok: true, value: args as A } : error("expected string");
83
+ case "number":
84
+ return typeof args === "number" && Number.isFinite(args) ? { ok: true, value: args as A } : error("expected number");
85
+ case "integer":
86
+ return typeof args === "number" && Number.isInteger(args) ? { ok: true, value: args as A } : error("expected integer");
87
+ case "boolean":
88
+ return typeof args === "boolean" ? { ok: true, value: args as A } : error("expected boolean");
89
+ case "null":
90
+ return args === null ? { ok: true, value: args as A } : error("expected null");
91
+ case "array": {
92
+ if (!Array.isArray(args)) return error("expected an array");
93
+ if (!schema.items) return { ok: true, value: args as A };
94
+ const out: unknown[] = [];
95
+ for (const item of args) {
96
+ const result = validateArgs(schema.items, item);
97
+ if (!result.ok) return error(result.message);
98
+ out.push(result.value);
99
+ }
100
+ return { ok: true, value: out as A };
101
+ }
102
+ default:
103
+ return { ok: true, value: args as A };
104
+ }
105
+ }
106
+
107
+ export interface ToolRegistry {
108
+ get(name: string): Tool | undefined;
109
+ list(): readonly Tool[];
110
+ }
111
+
112
+ export function createToolRegistry(tools: readonly Tool[]): ToolRegistry {
113
+ const map = new Map<string, Tool>(tools.map((tool) => [tool.name, tool]));
114
+ return {
115
+ get: (name) => map.get(name),
116
+ list: () => tools,
117
+ };
118
+ }