mini-coder 0.7.3 → 0.8.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/src/agent.ts CHANGED
@@ -1,287 +1,209 @@
1
1
  import {
2
+ type Api,
2
3
  type AssistantMessage,
3
- type Context,
4
- type ImageContent,
4
+ type JsonObject,
5
5
  type Message,
6
- streamSimple,
7
- type TextContent,
6
+ type Model,
7
+ type ModelThinkingLevel,
8
+ type Models,
9
+ type Tool,
8
10
  type ToolCall,
9
11
  type ToolResultMessage,
12
+ type UserMessage,
10
13
  } from "@earendil-works/pi-ai";
11
- import { getApiKey } from "./oauth";
12
- import { estimateTokens } from "./shared";
13
- import type {
14
- AgentContex,
15
- AgentEvent,
16
- AgentToolEvent,
17
- ToolAndRunner,
18
- } from "./types";
19
-
20
- // ### JetBrains Junie: Observation Masking
21
- // Published research found that **simply hiding old tool outputs** matched the quality of full LLM summarization with **zero extra compute**:
22
- // https://blog.jetbrains.com/research/2025/12/efficient-context-management/
23
- export function compactContext(messages: Message[]) {
24
- // TODO: Preserve SKILL.md contents, and exclude them from compaction.
25
- // Problem: How do we know? we need to check each message result againt it's arguments
26
- // and then find if by chance it has a read skill command... This is a mess. We we.
27
- // A better way would be to first add a read(path, lines, offset). And then we know
28
- // which files are read using it, and can match by path if it's a SKILL.md ending.
29
- const KEEP_OBSERVATIONS = 10;
30
-
31
- const toolResultIndices: number[] = [];
32
- for (let i = 0; i < messages.length; i++) {
33
- if (messages[i].role !== "toolResult") continue;
34
- const content = (messages[i] as ToolResultMessage).content;
35
- if (
36
- content.length === 1 &&
37
- content[0].type === "text" &&
38
- content[0].text.startsWith("Old environment output:")
39
- ) {
40
- continue;
41
- }
42
- toolResultIndices.push(i);
43
- }
44
-
45
- if (toolResultIndices.length <= KEEP_OBSERVATIONS) return;
46
-
47
- for (let i = 0; i < toolResultIndices.length - KEEP_OBSERVATIONS; i++) {
48
- const idx = toolResultIndices[i];
49
- const msg = messages[idx] as ToolResultMessage;
50
- let lines = 0;
51
- let images = 0;
52
- for (const c of msg.content) {
53
- if (c.type === "text") {
54
- lines += c.text.split(/\r?\n/).length;
55
- } else if (c.type === "image") {
56
- images++;
57
- }
58
- }
59
- let text = `Old environment output: (${lines} lines omitted)`;
60
- if (images > 0) {
61
- text += ` (${images} image${images > 1 ? "s" : ""} omitted)`;
62
- }
63
- msg.content = [{ type: "text", text }];
64
- }
14
+ import type { Session } from "./session.ts";
15
+ import { acceptsImages, executeTool, type ToolDetails, type ToolResult } from "./tools/index.ts";
16
+
17
+ export type Phase = "preparing" | "waitingModel" | "streaming" | "runningTool" | "pausing" | "idle";
18
+
19
+ export type AgentEvent =
20
+ | { type: "phase"; phase: Phase; detail?: string }
21
+ | { type: "text"; delta: string }
22
+ | { type: "reasoning"; delta: string }
23
+ | { type: "toolCallStart"; name: string }
24
+ | { type: "toolCall"; name: string; arguments: JsonObject }
25
+ | { type: "toolOutput"; chunk: string }
26
+ | { type: "toolResult"; name: string; text: string; isError: boolean }
27
+ | { type: "message"; message: AssistantMessage }
28
+ | { type: "error"; message: string }
29
+ | { type: "cancelled" }
30
+ | { type: "complete" };
31
+
32
+ interface Interaction {
33
+ isPauseRequested(): boolean;
34
+ clearPause(): void;
35
+ requestSteering(): Promise<string>;
65
36
  }
66
37
 
67
- export async function* streamAgent(
68
- agentCtx: AgentContex,
69
- ): AsyncGenerator<AgentEvent> {
70
- const llmCtx: Context = {
71
- systemPrompt: agentCtx.systemPrompt,
72
- tools: agentCtx.tools.map((t) => t.tool),
73
- messages: agentCtx.messages,
74
- };
75
-
76
- // Important for refreshing tokens.
77
- const apiKey = await getApiKey(agentCtx.options);
78
-
79
- // Main agent loop, continues until llm sends a response other than toolCall or has no tool calls.
80
- while (true) {
81
- const s = streamSimple(agentCtx.options.model, llmCtx, {
82
- reasoning: agentCtx.options.effort,
83
- signal: agentCtx.signal,
84
- apiKey,
85
- });
86
-
87
- let partial: AssistantMessage | null = null;
88
- let added = false;
89
-
90
- for await (const e of s) {
91
- switch (e.type) {
92
- case "start":
93
- partial = e.partial;
94
- llmCtx.messages.push(e.partial);
95
- added = true;
96
- yield { type: "message_start", partial };
97
- break;
98
-
99
- case "text_start":
100
- case "text_delta":
101
- case "text_end":
102
- case "thinking_start":
103
- case "thinking_delta":
104
- case "thinking_end":
105
- case "toolcall_start":
106
- case "toolcall_delta":
107
- case "toolcall_end": {
108
- if (partial) {
109
- partial = e.partial;
110
- llmCtx.messages[llmCtx.messages.length - 1] = partial;
111
- yield { type: "message_update", partial };
112
- }
38
+ export const NO_INTERACTION: Interaction = {
39
+ isPauseRequested: () => false,
40
+ clearPause: () => {},
41
+ requestSteering: async () => "",
42
+ };
43
+
44
+ /** What one turn needs, shared by both projections: the TUI and `--print`. */
45
+ export interface AgentOptions {
46
+ models: Models;
47
+ model: Model<Api>;
48
+ systemPrompt: string;
49
+ tools: Tool[];
50
+ thinkingEffort: ModelThinkingLevel;
51
+ session: Session;
52
+ }
113
53
 
114
- break;
115
- }
54
+ interface AgentRun extends AgentOptions {
55
+ messages: Message[];
56
+ signal: AbortSignal;
57
+ interaction: Interaction;
58
+ onEvent: (event: AgentEvent) => void;
59
+ }
116
60
 
117
- case "error": {
118
- const finalMessage = await s.result();
119
- if (added) {
120
- llmCtx.messages[llmCtx.messages.length - 1] = finalMessage;
121
- } else {
122
- llmCtx.messages.push(finalMessage);
123
- yield { type: "message_start", partial: { ...finalMessage } };
124
- }
61
+ export async function runAgentTurn(run: AgentRun): Promise<void> {
62
+ const { messages, session, signal, interaction, onEvent } = run;
125
63
 
126
- yield { type: "message_end", message: finalMessage };
127
- return;
128
- }
129
- }
64
+ /** Appends a user message the model reads at the next step boundary. */
65
+ const steer = (content: string): void => {
66
+ if (content === "") return;
67
+ const message: UserMessage = { role: "user", content, timestamp: Date.now() };
68
+ messages.push(message);
69
+ session.appendMessage(message);
70
+ };
130
71
 
131
- // Experiment: use this inside the inner loop for "running" compaction
132
- // after we are in the dumb zone.
133
- const estimate = estimateTokens(JSON.stringify(llmCtx));
134
- // 80k is the agreed uppon threshold to the DUMB ZONE
135
- if (estimate > 80000) compactContext(llmCtx.messages);
72
+ /**
73
+ * Returns the steering typed while paused, or ""; the caller decides where
74
+ * it lands, because a user message between an assistant turn and its tool
75
+ * results is rejected by the provider. Null once the turn has been aborted;
76
+ * every step boundary is a cancellation point.
77
+ */
78
+ const pauseStep = async (): Promise<string | null> => {
79
+ if (signal.aborted) return null;
80
+ if (interaction.isPauseRequested()) {
81
+ interaction.clearPause();
82
+ onEvent({ type: "phase", phase: "pausing" });
83
+ const steering = await interaction.requestSteering();
84
+ onEvent({ type: "phase", phase: "idle" });
85
+ if (signal.aborted) return null;
86
+ return steering;
136
87
  }
88
+ return "";
89
+ };
137
90
 
138
- const message = await s.result();
139
- if (added) {
140
- llmCtx.messages[llmCtx.messages.length - 1] = message;
141
- } else {
142
- llmCtx.messages.push(message);
143
- yield { type: "message_start", partial: { ...message } };
91
+ for (;;) {
92
+ const steering = await pauseStep();
93
+ if (steering === null) {
94
+ onEvent({ type: "cancelled" });
95
+ return;
144
96
  }
145
- yield { type: "message_end", message };
146
-
147
- const toolCalls = message.content.filter((c) => c.type === "toolCall");
97
+ steer(steering);
98
+
99
+ onEvent({ type: "phase", phase: "preparing" });
100
+ session.appendRequest({
101
+ provider: run.model.provider,
102
+ model: run.model.id,
103
+ api: run.model.api,
104
+ thinkingEffort: run.thinkingEffort,
105
+ systemPrompt: run.systemPrompt,
106
+ tools: run.tools,
107
+ });
148
108
 
149
- // Stop on errors or no tools to call.
150
- if (message.stopReason !== "toolUse" || toolCalls.length === 0) {
151
- break;
109
+ onEvent({ type: "phase", phase: "waitingModel" });
110
+ const context = { systemPrompt: run.systemPrompt, tools: run.tools, messages };
111
+ let stream;
112
+ try {
113
+ stream = run.models.streamSimple(run.model, context, {
114
+ reasoning: run.thinkingEffort === "off" ? undefined : run.thinkingEffort,
115
+ signal,
116
+ sessionId: session.id ?? undefined,
117
+ });
118
+ } catch (error) {
119
+ onEvent({ type: "error", message: (error as Error).message });
120
+ return;
152
121
  }
153
122
 
154
- const seenToolIds = new Map<string, number>();
155
- if (toolCalls.length > 0) {
156
- const ts = toolRunner(toolCalls, agentCtx.tools, agentCtx.signal);
157
-
158
- for await (const e of ts) {
159
- if (e.type === "tool_update") {
160
- // Update contex with update or add new.
161
- const existing = seenToolIds.get(e.partial.toolCallId);
162
- if (existing && existing >= 0) {
163
- const m = llmCtx.messages[existing];
164
- if (m.role === "toolResult") {
165
- llmCtx.messages[existing] = {
166
- ...m,
167
- content: [...m.content, ...e.partial.content],
168
- isError: e.partial.isError,
169
- };
170
- }
171
-
172
- yield {
173
- type: "tool_message_update",
174
- partial: e.partial,
175
- };
176
- } else {
177
- llmCtx.messages.push(e.partial);
178
- seenToolIds.set(e.partial.toolCallId, llmCtx.messages.length - 1);
179
-
180
- yield {
181
- type: "tool_message_start",
182
- partial: e.partial,
183
- };
184
- }
185
- } else if (e.type === "tool_result") {
186
- // Update context with full message and yield
187
- const idx = llmCtx.messages.findIndex(
188
- (m) =>
189
- m.role === "toolResult" && m.toolCallId === e.message.toolCallId,
190
- );
191
- if (idx >= 0) {
192
- llmCtx.messages[idx] = e.message;
193
- } else {
194
- llmCtx.messages.push(e.message);
195
- }
196
-
197
- yield {
198
- type: "tool_message_end",
199
- message: e.message,
200
- };
123
+ onEvent({ type: "phase", phase: "streaming" });
124
+ try {
125
+ for await (const event of stream) {
126
+ if (event.type === "text_delta") onEvent({ type: "text", delta: event.delta });
127
+ else if (event.type === "thinking_delta") onEvent({ type: "reasoning", delta: event.delta });
128
+ // The tool's name is known as soon as the call starts being written.
129
+ else if (event.type === "toolcall_start") {
130
+ const block = event.partial.content[event.contentIndex];
131
+ if (block.type === "toolCall") onEvent({ type: "toolCallStart", name: block.name });
132
+ } else if (event.type === "toolcall_end") {
133
+ onEvent({
134
+ type: "toolCall",
135
+ name: event.toolCall.name,
136
+ arguments: event.toolCall.arguments,
137
+ });
201
138
  }
202
139
  }
140
+ } catch (error) {
141
+ onEvent({ type: "error", message: (error as Error).message });
142
+ return;
203
143
  }
204
- }
205
- }
206
144
 
207
- // This should stay stateless, don't accumulate anything at this layer, just proxy
208
- // wrapped runners events.
209
- async function* toolRunner(
210
- toolCalls: ToolCall[],
211
- tools: ToolAndRunner[],
212
- signal?: AbortSignal,
213
- ): AsyncGenerator<AgentToolEvent> {
214
- for (const call of toolCalls) {
215
- const timestamp = Date.now();
216
- const tool = tools.find((t) => t.tool.name === call.name);
145
+ const assistant = await stream.result();
146
+ messages.push(assistant);
147
+ session.appendMessage(assistant);
148
+ onEvent({ type: "message", message: assistant });
217
149
 
218
- if (!tool) {
219
- yield {
220
- type: "tool_result",
221
- message: {
222
- role: "toolResult",
223
- toolCallId: call.id,
224
- toolName: call.name,
225
- content: [{ type: "text", text: "Error: Tool not found" }],
226
- isError: true,
227
- timestamp,
228
- },
229
- };
230
- continue;
150
+ if (assistant.stopReason === "aborted") {
151
+ onEvent({ type: "cancelled" });
152
+ return;
153
+ }
154
+ if (assistant.stopReason === "error") {
155
+ onEvent({ type: "error", message: assistant.errorMessage ?? "provider error" });
156
+ return;
231
157
  }
232
158
 
233
- try {
234
- for await (const e of tool.runner(call.arguments, signal)) {
235
- // yield deltas for output, full output on result.
236
- const content: TextContent = { type: "text", text: e.text };
237
-
238
- if (e.type === "output") {
239
- // handle deltas
240
- yield {
241
- type: "tool_update",
242
- partial: {
243
- role: "toolResult",
244
- toolCallId: call.id,
245
- toolName: call.name,
246
- content: [content],
247
- isError: false,
248
- timestamp,
249
- },
250
- };
251
- } else if (e.type === "result") {
252
- // handle final message, and check for images
253
- let img: ImageContent | null = null;
254
- if (e.image) {
255
- img = { ...e.image, type: "image" };
256
- }
159
+ const toolCalls = assistant.content.filter((block): block is ToolCall => block.type === "toolCall");
160
+ if (toolCalls.length === 0) {
161
+ onEvent({ type: "complete" });
162
+ return;
163
+ }
257
164
 
258
- yield {
259
- type: "tool_result",
260
- message: {
261
- role: "toolResult",
262
- toolCallId: call.id,
263
- toolName: call.name,
264
- content: img ? [content, img] : [content],
265
- isError: false,
266
- timestamp,
267
- },
268
- };
165
+ // Steering is held until every result of this assistant turn has landed:
166
+ // the provider rejects a user message between an assistant turn and its
167
+ // tool results.
168
+ const held: string[] = [];
169
+ for (const call of toolCalls) {
170
+ const steering = await pauseStep();
171
+ if (steering === null) {
172
+ onEvent({ type: "cancelled" });
173
+ return;
174
+ }
175
+ if (steering !== "") held.push(steering);
176
+ onEvent({ type: "phase", phase: "runningTool", detail: call.name });
177
+
178
+ const tool = run.tools.find((candidate) => candidate.name === call.name);
179
+ let result: ToolResult;
180
+ if (tool === undefined) {
181
+ result = { text: `unknown tool: ${call.name}`, isError: true };
182
+ } else {
183
+ try {
184
+ result = await executeTool(call, {
185
+ signal,
186
+ supportsImages: acceptsImages(run.model),
187
+ onOutput: (chunk) => onEvent({ type: "toolOutput", chunk }),
188
+ });
189
+ } catch (error) {
190
+ result = { text: (error as Error).message, isError: true };
269
191
  }
270
192
  }
271
- } catch (err) {
272
- // We don't validate arguments, so it's better to show the errors.
273
- const error = err instanceof Error ? err.message : "Unknown error";
274
- yield {
275
- type: "tool_result",
276
- message: {
277
- role: "toolResult",
278
- toolCallId: call.id,
279
- toolName: call.name,
280
- content: [{ type: "text", text: `Error: ${error}` }],
281
- isError: true,
282
- timestamp,
283
- },
193
+
194
+ const toolMessage: ToolResultMessage<ToolDetails> = {
195
+ role: "toolResult",
196
+ toolCallId: call.id,
197
+ toolName: call.name,
198
+ content: [{ type: "text", text: result.text }, ...(result.images ?? [])],
199
+ details: result.details,
200
+ isError: result.isError,
201
+ timestamp: Date.now(),
284
202
  };
203
+ messages.push(toolMessage);
204
+ session.appendMessage(toolMessage);
205
+ onEvent({ type: "toolResult", name: call.name, text: result.text, isError: result.isError });
285
206
  }
207
+ steer(held.join("\n"));
286
208
  }
287
209
  }
package/src/cli.ts ADDED
@@ -0,0 +1,101 @@
1
+ import process from "node:process";
2
+ import { clampThinkingLevel, type AssistantMessage, type Message, type UserMessage } from "@earendil-works/pi-ai";
3
+ import { loadConfig, resolveModel } from "./config.ts";
4
+ import { buildSystemPrompt } from "./prompt.ts";
5
+ import { acceptsImages, toolSchemas } from "./tools/index.ts";
6
+ import { Session } from "./session.ts";
7
+ import { NO_INTERACTION, runAgentTurn, type AgentOptions } from "./agent.ts";
8
+ import { runTui } from "./tui/tui.ts";
9
+
10
+ function parseArgs(argv: string[]): { print: string | null } {
11
+ let print: string | null = null;
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const match = /^(?:-p|--print)(?:=(.*))?$/.exec(argv[i]);
14
+ if (match === null) throw new Error(`unknown argument: ${argv[i]}`);
15
+ const value = match[1] ?? argv[++i];
16
+ if (value === undefined) throw new Error(`${argv[i - 1]} requires a prompt`);
17
+ print = value;
18
+ }
19
+ return { print };
20
+ }
21
+
22
+ async function runPrint(prompt: string, ctx: AgentOptions): Promise<number> {
23
+ const messages: Message[] = [];
24
+ const user: UserMessage = { role: "user", content: prompt, timestamp: Date.now() };
25
+ messages.push(user);
26
+ ctx.session.appendMessage(user);
27
+
28
+ const controller = new AbortController();
29
+ const onSignal = () => controller.abort();
30
+ process.on("SIGINT", onSignal);
31
+ process.on("SIGTERM", onSignal);
32
+
33
+ let failed = false;
34
+ let cancelled = false;
35
+ try {
36
+ await runAgentTurn({
37
+ ...ctx,
38
+ messages,
39
+ signal: controller.signal,
40
+ interaction: NO_INTERACTION,
41
+ onEvent: (event) => {
42
+ if (event.type === "toolCall") process.stderr.write(`[tool] ${event.name}\n`);
43
+ else if (event.type === "toolOutput") process.stderr.write(event.chunk);
44
+ else if (event.type === "error") {
45
+ failed = true;
46
+ process.stderr.write(`[error] ${event.message}\n`);
47
+ } else if (event.type === "cancelled") {
48
+ cancelled = true;
49
+ process.stderr.write("[cancelled]\n");
50
+ }
51
+ },
52
+ });
53
+ } catch (error) {
54
+ failed = true;
55
+ process.stderr.write(`[error] ${(error as Error).message}\n`);
56
+ } finally {
57
+ process.off("SIGINT", onSignal);
58
+ process.off("SIGTERM", onSignal);
59
+ ctx.session.close();
60
+ }
61
+
62
+ const last = messages.filter((message): message is AssistantMessage => message.role === "assistant").at(-1);
63
+ if (!failed && !cancelled && last !== undefined) {
64
+ const text = last.content
65
+ .filter((block) => block.type === "text")
66
+ .map((block) => block.text)
67
+ .join("");
68
+ if (text !== "") process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
69
+ }
70
+ return failed || cancelled ? 1 : 0;
71
+ }
72
+
73
+ async function main(): Promise<void> {
74
+ const args = parseArgs(process.argv.slice(2));
75
+ const config = loadConfig();
76
+ const { models, model } = resolveModel(config);
77
+ const session = new Session(config.sessionsDir, process.cwd());
78
+ const ctx: AgentOptions = {
79
+ models,
80
+ model,
81
+ systemPrompt: buildSystemPrompt(config),
82
+ tools: toolSchemas(config.tools, acceptsImages(model)),
83
+ thinkingEffort: clampThinkingLevel(model, config.thinkingEffort),
84
+ session,
85
+ };
86
+
87
+ if (args.print !== null) {
88
+ process.exitCode = await runPrint(args.print, ctx);
89
+ return;
90
+ }
91
+
92
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
93
+ throw new Error("interactive mode requires a TTY; use -p for non-interactive mode");
94
+ }
95
+ await runTui(ctx);
96
+ }
97
+
98
+ main().catch((error) => {
99
+ process.stderr.write(`${(error as Error).message}\n`);
100
+ process.exit(1);
101
+ });