xonecas.io
64875
Mc

mini-coder / commit 08b1a98

feat: todoWrite and todoRead tools

Also includes several fixes to headless mode.

xonecas2026-04-16 08b1a98b46d81dd0b8d480fb6f8902cc29a08cfc parent 6e02ac7

23 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+1−0
@@ -95,6 +95,7 @@
9595 - Before 1.0, prefer correct/simple semantics over speculative compatibility shims, but call out intentional breaking changes.
9696 - TUI changes need real terminal validation in `tmux`; passing tests is not enough.
9797 - Stay within the agreed TODO scope. Do not pull in adjacent items without discussion.
98+- Don't write tests that call real git commands
9899
99100 ## Testing strategy
100101
TODO.md+4−2
@@ -7,9 +7,11 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
77
88 ## Open items
99
10+- [ ] headless mode with --json should only output completed messages and not delta messages.
11+
1012 ## Forge comparison follow-ups (high-value gaps, highest priority first)
1113
12-- [ ] Add first-class todo tools plus prompt/UI integration so the agent can track and complete work explicitly instead of relying only on a `/tmp` file (`src/tools.ts`, `src/agent.ts`, `src/prompt.ts`, `src/ui/conversation.ts`)
14+- [x] Add first-class todo tools plus prompt/UI integration so the agent can track and complete work explicitly instead of relying only on a `/tmp` file (`src/tools.ts`, `src/agent.ts`, `src/prompt.ts`, `src/ui/conversation.ts`)
1315 - [ ] Add loop safeguards: retry policy, tool-failure/request budgets, and doom-loop detection/reminders (`src/agent.ts`, `src/submit.ts`, `src/prompt.ts`)
1416 - [ ] Add dedicated read/search tools so the model relies less on `shell` for code discovery (`src/tools.ts`, `src/prompt.ts`, `src/ui/conversation.ts`)
1517 - [ ] Add first-class delegation/subagent support instead of relying on shell-level `mc -p` delegation (`src/agent.ts`, `src/tools.ts`, `src/prompt.ts`, `src/headless.ts`)
@@ -24,7 +26,7 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
2426 - [ ] `/session` can switch sessions mid-run (`ui/commands.ts`, `ui/agent.ts`)
2527 - [ ] `shell` results are flattened into one text blob (`src/tools.ts`, `src/ui/conversation.ts`)
2628 - [ ] Steering meesages are implemented wrong, they appear in the UI at the end of the turn loop. Not at the next loop interation boundary... NOT CONFIRMED NEEDS DEBUGGING
27-- [ ] Custom XML parsing and frontmatter parsing are still in use (`skills.ts`, `prompt.ts`)
29+- [ ] Skills aren't xml safe and we should use a frontmatter parsing library (`skills.ts`, `prompt.ts`)
2830
2931 ## Plugin related (documented only, no plugin-related work is planned right now)
3032
spec.md+51−15
@@ -57,7 +57,7 @@ This replaces: `yoctocolors`, `yoctomarkdown`, `yoctoselect`, and all our custom
5757
5858 ## Tools
5959
60-Two built-in tools, plus a read-only image tool. Plugins may add more (see [Plugins](#plugins)).
60+Four built-in tools, plus a read-only image tool. Plugins may add more (see [Plugins](#plugins)).
6161
6262 ### `shell`
6363
@@ -85,6 +85,31 @@ Implementation details:
8585 - Returns a confirmation or error message — no diff output (the agent already knows what it wrote).
8686 - Encoding: reads and writes UTF-8. Preserves the file's existing line endings.
8787
88+### `todoWrite`
89+
90+Creates or updates the session todo list incrementally. Use it to track multi-step or non-trivial work, keep progress visible, and mark tasks complete explicitly.
91+
92+Implementation details:
93+
94+- Takes a `todos` array. Each item must include `content` and `status`.
95+- `content` is the exact matching key. If an item with the same content already exists, its status is updated in place. Otherwise a new item is appended.
96+- Allowed statuses: `pending`, `in_progress`, `completed`, `cancelled`.
97+- `cancelled` removes the matching item entirely.
98+- Items omitted from a call remain unchanged.
99+- Successful results return the full current todo-list snapshot in insertion order. Surviving items keep their relative order; newly added items are appended.
100+- Todo content must not be empty or whitespace-only and must stay within a small fixed length limit.
101+- Todo state is session-local and derived from the latest successful todo snapshot persisted in message history, so `/undo`, `/fork`, session reload, and session switching all restore the correct list automatically.
102+
103+### `todoRead`
104+
105+Returns the current session todo list.
106+
107+Implementation details:
108+
109+- Takes no arguments.
110+- Returns the full current todo-list snapshot, which may be empty.
111+- The returned snapshot uses the same shape as `todoWrite` success results.
112+
88113 ### `readImage`
89114
90115 Reads an image file and returns it as `ImageContent` (base64 + mimeType). This lets the model inspect screenshots, diagrams, or any image in the repo without the user explicitly attaching it.
@@ -209,21 +234,26 @@ The core runtime. Streaming is the default behavior throughout the turn: user-vi
209234 3. **Stream to LLM** — call `streamSimple(model, context, options)` from pi-ai. Iterate over the event stream:
210235 - `text_delta` / `thinking_delta` / `toolcall_delta` → update the in-progress assistant message and the UI incrementally (stream raw markdown text, show thinking if enabled, accumulate tool call arguments as they arrive).
211236 - `toolcall_end` → finalize the structured tool call in the in-progress `AssistantMessage`.
212- - `done` → append the `AssistantMessage` to history and DB. Update cumulative stats. If `stopReason` is `"toolUse"`, go to step 4. If `"stop"` or `"length"` and queued steering messages exist, go to step 5. Otherwise return to the input prompt.
237+ - `done` → append the `AssistantMessage` to history and DB. Update cumulative stats. If `stopReason` is `"toolUse"`, go to step 4. If `"stop"` or `"length"` and queued steering messages exist, go to step 6. If `"stop"` or `"length"` and incomplete todo items remain, go to step 5. Otherwise return to the input prompt.
213238 - `error` → display error in the log, return to the input prompt.
214239
215240 4. **Tool execution** — when the LLM requests tool calls:
216- - Execute each tool call. For `shell`: run the command, capture output, truncate if needed. For `edit`: perform the replacement. For `readImage`: read and base64-encode the file. For plugin tools: delegate to the plugin.
241+ - Execute each tool call. For `shell`: run the command, capture output, truncate if needed. For `edit`: perform the replacement. For `todoWrite`: apply the incremental todo changes and return the full current list. For `todoRead`: return the full current list. For `readImage`: read and base64-encode the file. For plugin tools: delegate to the plugin.
217242 - Each result becomes a `ToolResultMessage` appended to history and DB (same turn number).
218- - After all tool results are appended, if queued steering messages exist go to step 5; otherwise loop back to step 2 (re-stream with the updated context).
243+ - After all tool results are appended, if queued steering messages exist go to step 6; otherwise loop back to step 2 (re-stream with the updated context).
244+
245+5. **Todo reminders** — when the assistant tries to stop while incomplete todo items still exist:
246+ - Inject a model-visible reminder listing the current `pending` and `in_progress` items, then loop back to step 2.
247+ - Reminders are ephemeral: they are included in model context for the follow-up request but are not rendered in the conversation pane and are not persisted to the session DB.
248+ - If the exact same incomplete-todo set was already reminded during the current run, do not inject a duplicate reminder. In that case the turn ends normally instead of looping forever.
219249
220-5. **Steering messages** — if the user submits a model-visible message while an active run is already in progress, mini-coder queues it instead of dropping it or interrupting the current work.
250+6. **Steering messages** — if the user submits a model-visible message while an active run is already in progress, mini-coder queues it instead of dropping it or interrupting the current work.
221251 - Steering messages are consumed FIFO at the next model-request boundary: after the current assistant message is finalized and after any tool calls already requested by that assistant message have completed and their tool results have been appended.
222252 - When consumed, each steering message is appended to history and DB as a normal `UserMessage`, starting a new conversational turn.
223253 - After appending the next queued steering message, loop back to step 2 so the next `streamSimple(...)` call sees the updated history.
224254 - Submitting a steering message does not abort the current stream or running tool. Use `Escape` to interrupt immediately.
225255
226-6. **Interrupt** — if the user presses `Escape` during streaming with no overlay open:
256+7. **Interrupt** — if the user presses `Escape` during streaming with no overlay open:
227257 - Abort the stream via `AbortSignal`.
228258 - The partial `AssistantMessage` (with `stopReason: "aborted"`) is appended to history and DB as-is. This preserves context so the LLM knows what it was doing when interrupted.
229259 - Return to the input prompt with focus on the input. The user can continue the conversation or `/undo` the interrupted turn.
@@ -305,11 +335,13 @@ The current environment is:
305335
306336 ### Task management
307337
308-- Use the /tmp or equivalent temp directory to make a To-do list for your task.
309-- This to-do list is **extremly** helpful for breaking down your task into smaller less complex steps.
310-- Not using a to-do list may cause you to forget important steps, or loose focus of the user request, that would be unacceptable.
311-- Keep the to-do list up-to-date above all, mark your completions as soon as you verify them.
312-- A to-do item is only complete if verification was successful and thorough.
338+- Use `todoWrite` proactively for multi-step or non-trivial tasks.
339+- Capture new requirements in the todo list as soon as you understand them.
340+- Use `todoRead` when you need to inspect the current list before updating it or when the user asks for the current plan/status.
341+- Keep the todo list up-to-date above all; mark tasks `in_progress` before starting them and `completed` as soon as verification succeeds.
342+- A todo item is only complete if the requested work is actually finished and verified to the degree the task requires.
343+- Use `cancelled` to remove tasks that are no longer relevant.
344+- Skip todo tools for single trivial tasks and purely conversational/informational requests.
313345 - You have the option to delegate tasks to copies of yourself with `mc -p "subtask prompt"` in the shell.
314346 - Delegate when you are orchestarting a large to-do/plan execution.
315347 ```
@@ -526,16 +558,17 @@ Tool blocks share a common frame: a left border (`│`) plus a compact header pi
526558 - **Assistant messages**: streamed raw markdown rendered via cel-tui's `SyntaxHighlight` component on the default background so the log stays copy-friendly and preserves markdown markers. Thinking/reasoning content is collapsible (shown or hidden according to the user's persisted `/reasoning` preference; defaults to shown when no setting exists).
527559 - **Tool calls — shell**: rendered in the shared tool frame. The assistant tool call streams the command as it arrives. The command preview and shell tool result body use [verbose tool rendering](#verbose-tool-rendering). Shell tool results render the tool output content below a `shell <-` header.
528560 - **Tool calls — edit**: rendered in the shared tool frame. The in-progress tool-call preview shows the target path followed by the streamed `oldText` and `newText` bodies. Old text is styled as removed and new text as added, but the preview does not render literal `-`/`+` diff prefixes. The preview body uses [verbose tool rendering](#verbose-tool-rendering). Successful results render a compact confirmation block (`edit <-` plus the file path); errors render the returned error text.
561+- **Tool calls — todoWrite / todoRead**: rendered in the shared tool frame. Successful results render the full current todo list as a structured themed checklist with status markers (`[ ]`, `[~]`, `[x]`). This checklist is always shown in full and never truncated, regardless of `/verbose`. Errors render the returned error text.
529562 - **Tool calls — readImage**: rendered in the shared tool frame. The assistant tool call streams the path as it arrives. Successful results render a compact result block (`read image <-` plus the file path) rather than rendering the image itself.
530563 - **Tool calls — plugin tools**: rendered in the shared tool frame, prefixed with plugin/tool name when available.
531-- **UI messages**: internal app messages such as `/help` output, OAuth progress, `/fork` notices, and other session-local notices. They are rendered in the conversation log, persisted with the session, excluded from model context, and do not participate in conversational turn numbering.
564+- **UI messages**: internal app messages such as `/help` output, OAuth progress, `/fork` notices, and other session-local notices. They are rendered in the conversation log, persisted with the session, excluded from model context, and do not participate in conversational turn numbering. `/todo` output is also UI-only, but it renders using the same structured todo-checklist block as todo tool results instead of plain info text.
532565 - **Errors**: one-line summary, styled distinctly.
533566
534567 #### Verbose tool rendering
535568
536569 `/verbose` controls a single persisted UI preference for how tool-call previews and selected tool-result bodies are displayed in the conversation log.
537570
538-- Scope: shell tool-call bodies, shell tool-result bodies, edit tool-call preview bodies, and edit error results only. Successful edit results stay compact in both modes.
571+- Scope: shell tool-call bodies, shell tool-result bodies, edit tool-call preview bodies, and edit error results only. Successful edit results stay compact in both modes. Todo tool results ignore `/verbose` and always show the full current list.
539572 - Default: off when no saved setting exists.
540573 - Off: show as many trailing logical lines as fit within a fixed rendered-height preview, followed by `And X lines more` when earlier lines are hidden. The preview height stays stable for a given block, so wrapped long lines do not make the log jump while content streams.
541574 - On: show the full stored tool result or preview body.
@@ -727,7 +760,8 @@ add tests for undo_
727760 | `/fork` | Fork the current conversation into a new session. Copies the full message history, continues from here independently, and appends a UI-only `Forked session.` notice in the new session. The original session is preserved. …
728761 | `/undo` | Remove the last conversational turn from history: the most recent user message and all assistant/tool messages that followed in that turn. Persisted UI messages are not part of turns and are not removed by `/undo`. Context-only — does not revert filesystem changes. …
729762 | `/reasoning` | Toggle display of model thinking/reasoning content in the log. The new on/off state is persisted immediately and restored on launch. When no setting exists yet, reasoning defaults to shown. …
730-| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. …
763+| `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. Todo tool results always render in full. …
764+| `/todo` | Append the current session todo list to the conversation pane as a UI-only checklist block. The message is persisted with the session, excluded from model context, and does not create a session by itself when no session exists yet. …
731765 | `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. …
732766 | `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. …
733767 | `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately, and the selected effort is persisted immediately as the user's global default. The session record's `effort` field is not updated (it reflects the initial choice, like `/model`). …
@@ -754,7 +788,7 @@ Prompt source in headless mode:
754788 - If headless mode was selected because `stdout` is not a TTY but `stdin` is still interactive, startup fails with a clear error unless `-p` was provided. Headless mode does not fall back to an interactive prompt.
755789 - Empty or whitespace-only headless input is an error.
756790
757-Input parsing in headless mode reuses the same rules as the interactive input area for plain text, `/skill:name`, and standalone image-file paths. Interactive slash commands such as `/model`, `/session`, `/new`, `/fork`, `/undo`, `/login`, `/logout`, `/effort`, and `/help` are not available in headless mode and should fail clearly rather than attempting to open interactive UI.
791+Input parsing in headless mode reuses the same rules as the interactive input area for plain text, `/skill:name`, and standalone image-file paths. Interactive slash commands such as `/model`, `/session`, `/new`, `/fork`, `/undo`, `/login`, `/logout`, `/effort`, `/todo`, and `/help` are not available in headless mode and should fail clearly rather than attempting to open interactive UI.
758792
759793 ### Headless text output
760794
@@ -895,6 +929,8 @@ CREATE INDEX idx_prompt_history_created_at ON prompt_history(created_at, id);
895929
896930 **Messages as JSON blobs**: pi-ai's `Message` type (UserMessage, AssistantMessage, ToolResultMessage) is already serializable, and we also persist internal UI-only log entries in the same table. We store the full object as JSON in `data` rather than normalizing into columns. Session load returns the complete chronological log; model context construction filters out UI-only messages before replaying the remaining pi-ai messages into a pi-ai `Context`.
897931
932+**Todo state lives in message history**: there is no separate todo table. The current todo list is reconstructed from the latest successful persisted todo snapshot found in session messages. Because that snapshot rides along with normal message history, `/undo`, `/fork`, session reload, and session switching all restore the expected todo state automatically.
933+
898934 **Turn grouping**: the `turn` column groups only conversational messages. A turn is: one user message + the assistant messages and tool result messages produced after that user message until the next user message is consumed. Persisted UI messages are stored alongside them but have `turn = NULL`, so they remain visible in session history without becoming part of `/undo`. Queued steering messages submitted mid-run still start their own turn when they are consumed; tool results already requested b …
899935
900936 **Cumulative stats are computed, not stored**: the status bar's cumulative `in`, `out`, and `$cost` values are computed by summing `usage` from assistant messages on session load (deserialize all messages, filter for `role: "assistant"`, sum their `usage` fields). The message count per session is small (hundreds), so this is fast. No separate counters to keep in sync. During an active session, a running in-memory accumulator is updated after each assistant message to avoid re-scanning. `context% …
src/agent.test.ts+254−3
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import type {
77 AssistantMessage,
8+ Message,
89 Model,
910 Tool,
1011 Usage,
@@ -28,7 +29,16 @@ import {
2829 loadMessages,
2930 openDatabase,
3031 } from "./session.ts";
31-import { editTool, executeEdit, executeShell, shellTool } from "./tools.ts";
32+import {
33+ editTool,
34+ executeEdit,
35+ executeShell,
36+ executeTodoRead,
37+ executeTodoWrite,
38+ shellTool,
39+ todoReadTool,
40+ todoWriteTool,
41+} from "./tools.ts";
3242
3343 // ---------------------------------------------------------------------------
3444 // Helpers
@@ -54,6 +64,22 @@ function makeUser(text: string): UserMessage {
5464 return { role: "user", content: text, timestamp: Date.now() };
5565 }
5666
67+function makeTodoSnapshotMessage(
68+ todos: Array<{
69+ content: string;
70+ status: "pending" | "in_progress" | "completed";
71+ }>,
72+): Message {
73+ return {
74+ role: "toolResult",
75+ toolCallId: `todo-${Date.now()}`,
76+ toolName: "todoWrite",
77+ content: [{ type: "text", text: JSON.stringify({ todos }) }],
78+ isError: false,
79+ timestamp: Date.now(),
80+ };
81+}
82+
5783 const ZERO_USAGE: Usage = {
5884 input: 0,
5985 output: 0,
@@ -97,11 +123,13 @@ function expectLastEvent<TType extends AgentEvent["type"]>(
97123
98124 /** Built-in tool definitions for tests. */
99125 function builtinToolDefs(): Tool[] {
100- return [shellTool, editTool];
126+ return [shellTool, editTool, todoWriteTool, todoReadTool];
101127 }
102128
103129 /** Built-in tool handlers for tests. */
104-function builtinToolHandlers(): Map<string, ToolHandler> {
130+function builtinToolHandlers(
131+ messages: Message[] = [],
132+): Map<string, ToolHandler> {
105133 return new Map<string, ToolHandler>([
106134 [
107135 "shell",
@@ -123,6 +151,20 @@ function builtinToolHandlers(): Map<string, ToolHandler> {
123151 cwd,
124152 ),
125153 ],
154+ [
155+ "todoWrite",
156+ (args) =>
157+ executeTodoWrite(
158+ {
159+ todos: args.todos as Array<{
160+ content: string;
161+ status: "pending" | "in_progress" | "completed" | "cancelled";
162+ }>,
163+ },
164+ messages,
165+ ),
166+ ],
167+ ["todoRead", () => executeTodoRead(messages)],
126168 ]);
127169 }
128170
@@ -1512,6 +1554,215 @@ describe("agent loop", () => {
15121554 );
15131555 });
15141556
1557+ test("injects a todo reminder and re-prompts when pending todos remain", async () => {
1558+ faux.setResponses([
1559+ fauxAssistantMessage("All done."),
1560+ fauxAssistantMessage("I still need to finish the pending work."),
1561+ ]);
1562+
1563+ const session = createSession(db, { cwd: tmp });
1564+ const userMsg = makeUser("finish the task");
1565+ const turn = appendMessage(db, session.id, userMsg);
1566+ const messages: Message[] = [
1567+ makeTodoSnapshotMessage([
1568+ { content: "Run the test suite", status: "pending" },
1569+ { content: "Summarize the verified changes", status: "in_progress" },
1570+ ]),
1571+ userMsg,
1572+ ];
1573+
1574+ const result = await runAgentLoop({
1575+ db,
1576+ sessionId: session.id,
1577+ turn,
1578+ model: faux.getModel(),
1579+ systemPrompt: "Test",
1580+ tools: builtinToolDefs(),
1581+ toolHandlers: builtinToolHandlers(messages),
1582+ messages,
1583+ cwd: tmp,
1584+ });
1585+
1586+ expect(result.stopReason).toBe("stop");
1587+ expect(
1588+ result.messages.filter((message) => message.role === "assistant"),
1589+ ).toHaveLength(2);
1590+ const lastMessage = result.messages.at(-1);
1591+ if (!lastMessage || lastMessage.role !== "assistant") {
1592+ throw new Error("Expected a final assistant message");
1593+ }
1594+ expect(lastMessage.content).toEqual([
1595+ { type: "text", text: "I still need to finish the pending work." },
1596+ ]);
1597+ });
1598+
1599+ test("does not inject duplicate todo reminders for the same pending set", async () => {
1600+ faux.setResponses([
1601+ fauxAssistantMessage("All done."),
1602+ fauxAssistantMessage("All done again."),
1603+ ]);
1604+
1605+ const session = createSession(db, { cwd: tmp });
1606+ const userMsg = makeUser("finish the task");
1607+ const turn = appendMessage(db, session.id, userMsg);
1608+ const messages: Message[] = [
1609+ makeTodoSnapshotMessage([
1610+ { content: "Run the test suite", status: "pending" },
1611+ ]),
1612+ userMsg,
1613+ ];
1614+
1615+ const result = await runAgentLoop({
1616+ db,
1617+ sessionId: session.id,
1618+ turn,
1619+ model: faux.getModel(),
1620+ systemPrompt: "Test",
1621+ tools: builtinToolDefs(),
1622+ toolHandlers: builtinToolHandlers(messages),
1623+ messages,
1624+ cwd: tmp,
1625+ });
1626+
1627+ expect(result.stopReason).toBe("stop");
1628+ expect(
1629+ result.messages.filter((message) => message.role === "assistant"),
1630+ ).toHaveLength(2);
1631+ const lastMessage = result.messages.at(-1);
1632+ if (!lastMessage || lastMessage.role !== "assistant") {
1633+ throw new Error("Expected a final assistant message");
1634+ }
1635+ expect(lastMessage.content).toEqual([
1636+ { type: "text", text: "All done again." },
1637+ ]);
1638+ });
1639+
1640+ test("does not re-inject the same todo reminder after a queued steering message starts a new turn", async () => {
1641+ faux.setResponses([
1642+ fauxAssistantMessage("All done."),
1643+ fauxAssistantMessage("Still done."),
1644+ fauxAssistantMessage("Handled steering without a duplicate reminder."),
1645+ fauxAssistantMessage("Duplicate reminder fired."),
1646+ ]);
1647+
1648+ const session = createSession(db, { cwd: tmp });
1649+ const userMsg = makeUser("finish the task");
1650+ const turn = appendMessage(db, session.id, userMsg);
1651+ const messages: Message[] = [
1652+ makeTodoSnapshotMessage([
1653+ { content: "Run the test suite", status: "pending" },
1654+ ]),
1655+ userMsg,
1656+ ];
1657+ let dequeueCallCount = 0;
1658+
1659+ const result = await runAgentLoop({
1660+ db,
1661+ sessionId: session.id,
1662+ turn,
1663+ model: faux.getModel(),
1664+ systemPrompt: "Test",
1665+ tools: builtinToolDefs(),
1666+ toolHandlers: builtinToolHandlers(messages),
1667+ messages,
1668+ cwd: tmp,
1669+ takeQueuedUserMessage: () => {
1670+ dequeueCallCount += 1;
1671+ return dequeueCallCount === 2 ? makeUser("steer once") : null;
1672+ },
1673+ });
1674+
1675+ expect(result.stopReason).toBe("stop");
1676+ const assistantMessages = result.messages.filter(
1677+ (message): message is AssistantMessage => message.role === "assistant",
1678+ );
1679+ expect(assistantMessages).toHaveLength(3);
1680+ expect(assistantMessages.at(-1)?.content).toEqual([
1681+ {
1682+ type: "text",
1683+ text: "Handled steering without a duplicate reminder.",
1684+ },
1685+ ]);
1686+ });
1687+
1688+ test("does not re-inject the same todo reminder when the incomplete set is only reordered", async () => {
1689+ faux.setResponses([
1690+ fauxAssistantMessage("All done."),
1691+ fauxAssistantMessage(
1692+ [
1693+ fauxToolCall("todoWrite", {
1694+ todos: [
1695+ {
1696+ content: "Summarize the verified changes",
1697+ status: "in_progress",
1698+ },
1699+ { content: "Run the test suite", status: "pending" },
1700+ ],
1701+ }),
1702+ ],
1703+ { stopReason: "toolUse" },
1704+ ),
1705+ fauxAssistantMessage(
1706+ "Handled reordered todos without a duplicate reminder.",
1707+ ),
1708+ fauxAssistantMessage("Duplicate reminder fired."),
1709+ ]);
1710+
1711+ const session = createSession(db, { cwd: tmp });
1712+ const userMsg = makeUser("finish the task");
1713+ const turn = appendMessage(db, session.id, userMsg);
1714+ const messages: Message[] = [
1715+ makeTodoSnapshotMessage([
1716+ { content: "Run the test suite", status: "pending" },
1717+ { content: "Summarize the verified changes", status: "in_progress" },
1718+ ]),
1719+ userMsg,
1720+ ];
1721+ const reorderedTodoWriteHandler: ToolHandler = () => {
1722+ return {
1723+ content: [
1724+ {
1725+ type: "text",
1726+ text: JSON.stringify({
1727+ todos: [
1728+ {
1729+ content: "Summarize the verified changes",
1730+ status: "in_progress",
1731+ },
1732+ { content: "Run the test suite", status: "pending" },
1733+ ],
1734+ }),
1735+ },
1736+ ],
1737+ isError: false,
1738+ };
1739+ };
1740+
1741+ const result = await runAgentLoop({
1742+ db,
1743+ sessionId: session.id,
1744+ turn,
1745+ model: faux.getModel(),
1746+ systemPrompt: "Test",
1747+ tools: [todoWriteTool],
1748+ toolHandlers: new Map([[todoWriteTool.name, reorderedTodoWriteHandler]]),
1749+ messages,
1750+ cwd: tmp,
1751+ });
1752+
1753+ expect(result.stopReason).toBe("stop");
1754+ const assistantMessages = result.messages.filter(
1755+ (message): message is AssistantMessage => message.role === "assistant",
1756+ );
1757+ expect(assistantMessages).toHaveLength(3);
1758+ expect(assistantMessages.at(-1)?.content).toEqual([
1759+ {
1760+ type: "text",
1761+ text: "Handled reordered todos without a duplicate reminder.",
1762+ },
1763+ ]);
1764+ });
1765+
15151766 test("stopReason 'length' returns without looping", async () => {
15161767 faux.setResponses([
15171768 fauxAssistantMessage("Partial response that hit the token limit", {
src/agent.ts+206−60
@@ -22,7 +22,7 @@ import type {
2222 } from "@mariozechner/pi-ai";
2323 import { streamSimple } from "@mariozechner/pi-ai";
2424 import { appendMessage } from "./session.ts";
25-import type { ToolExecResult } from "./tools.ts";
25+import { getTodoItems, type ToolExecResult } from "./tools.ts";
2626
2727 // ---------------------------------------------------------------------------
2828 // Types
@@ -605,28 +605,111 @@ function appendToolResultMessage(
605605 onEvent?.({ type: "tool_result", message: toolResultMessage });
606606 }
607607
608-function finalizeStoppedAssistantMessage(
609- db: Database,
610- sessionId: string,
611- messages: Message[],
608+function getIncompleteTodos(messages: readonly Message[]) {
609+ return getTodoItems(messages).filter((todo) => todo.status !== "completed");
610+}
611+
612+function getTodoReminderSignature(
613+ todos: ReturnType<typeof getIncompleteTodos>,
614+): string {
615+ return JSON.stringify(
616+ [...todos].sort((left, right) => {
617+ const contentOrder = left.content.localeCompare(right.content);
618+ if (contentOrder !== 0) {
619+ return contentOrder;
620+ }
621+ return left.status.localeCompare(right.status);
622+ }),
623+ );
624+}
625+
626+function createTodoReminderMessage(
627+ messages: readonly Message[],
628+ remindedTodoSignatures: Set<string>,
629+): UserMessage | null {
630+ const incompleteTodos = getIncompleteTodos(messages);
631+ if (incompleteTodos.length === 0) {
632+ return null;
633+ }
634+
635+ const signature = getTodoReminderSignature(incompleteTodos);
636+ if (remindedTodoSignatures.has(signature)) {
637+ return null;
638+ }
639+ remindedTodoSignatures.add(signature);
640+
641+ const lines = [
642+ "You have pending todo items that must be completed before finishing the task:",
643+ "",
644+ ...incompleteTodos.map((todo) => {
645+ const status = todo.status === "in_progress" ? "IN_PROGRESS" : "PENDING";
646+ return `- [${status}] ${todo.content}`;
647+ }),
648+ "",
649+ "Please complete all pending items before finishing.",
650+ ];
651+
652+ return {
653+ role: "user",
654+ content: lines.join("\n"),
655+ timestamp: Date.now(),
656+ };
657+}
658+
659+interface StoppedAssistantResolution {
660+ /** Next turn number when a queued steering message was consumed. */
661+ nextTurn: number | null;
662+ /** Ephemeral context messages to include on the next model request. */
663+ pendingContextMessages: Message[];
664+ /** Final loop result when the turn should stop immediately. */
665+ finalResult: AgentLoopResult | null;
666+}
667+
668+function resolveStoppedAssistantMessage(
612669 assistantMessage: AssistantMessage,
613670 stopReason: "stop" | "length",
614- takeQueuedUserMessage: RunAgentOpts["takeQueuedUserMessage"],
615- onEvent: RunAgentOpts["onEvent"],
616-): AgentLoopResult | number {
671+ opts: Pick<
672+ RunAgentOpts,
673+ "db" | "sessionId" | "messages" | "takeQueuedUserMessage" | "onEvent"
674+ >,
675+ remindedTodoSignatures: Set<string>,
676+): StoppedAssistantResolution {
617677 const queuedTurn = consumeQueuedUserMessage(
618- db,
619- sessionId,
620- messages,
621- takeQueuedUserMessage,
622- onEvent,
678+ opts.db,
679+ opts.sessionId,
680+ opts.messages,
681+ opts.takeQueuedUserMessage,
682+ opts.onEvent,
623683 );
624684 if (queuedTurn !== null) {
625- return queuedTurn;
685+ return {
686+ nextTurn: queuedTurn,
687+ pendingContextMessages: [],
688+ finalResult: null,
689+ };
626690 }
627691
628- onEvent?.({ type: "done", message: assistantMessage });
629- return { messages, stopReason };
692+ const todoReminder = createTodoReminderMessage(
693+ opts.messages,
694+ remindedTodoSignatures,
695+ );
696+ if (todoReminder) {
697+ return {
698+ nextTurn: null,
699+ pendingContextMessages: [todoReminder],
700+ finalResult: null,
701+ };
702+ }
703+
704+ opts.onEvent?.({ type: "done", message: assistantMessage });
705+ return {
706+ nextTurn: null,
707+ pendingContextMessages: [],
708+ finalResult: {
709+ messages: opts.messages,
710+ stopReason,
711+ },
712+ };
630713 }
631714
632715 async function executeAssistantToolCalls(
@@ -671,6 +754,95 @@ async function executeAssistantToolCalls(
671754 return null;
672755 }
673756
757+interface AgentIterationOutcome {
758+ /** Final loop result when the run should stop immediately. */
759+ finalResult: AgentLoopResult | null;
760+ /** Next turn number when a queued steering message starts a new turn. */
761+ nextTurn: number;
762+ /** Ephemeral context messages for the next model request. */
763+ pendingContextMessages: Message[];
764+}
765+
766+async function resolveAgentIteration(
767+ assistantMessage: AssistantMessage,
768+ currentTurn: number,
769+ remindedTodoSignatures: Set<string>,
770+ opts: Pick<
771+ RunAgentOpts,
772+ | "db"
773+ | "sessionId"
774+ | "messages"
775+ | "toolHandlers"
776+ | "cwd"
777+ | "signal"
778+ | "onEvent"
779+ | "model"
780+ | "takeQueuedUserMessage"
781+ >,
782+): Promise<AgentIterationOutcome> {
783+ const stopResult = resolveLoopStopReason(
784+ assistantMessage,
785+ opts.messages,
786+ opts.onEvent,
787+ );
788+ if (stopResult) {
789+ return {
790+ finalResult: stopResult,
791+ nextTurn: currentTurn,
792+ pendingContextMessages: [],
793+ };
794+ }
795+
796+ if (
797+ assistantMessage.stopReason === "stop" ||
798+ assistantMessage.stopReason === "length"
799+ ) {
800+ const stopResolution = resolveStoppedAssistantMessage(
801+ assistantMessage,
802+ assistantMessage.stopReason,
803+ {
804+ db: opts.db,
805+ sessionId: opts.sessionId,
806+ messages: opts.messages,
807+ takeQueuedUserMessage: opts.takeQueuedUserMessage,
808+ onEvent: opts.onEvent,
809+ },
810+ remindedTodoSignatures,
811+ );
812+ return {
813+ finalResult: stopResolution.finalResult,
814+ nextTurn: stopResolution.nextTurn ?? currentTurn,
815+ pendingContextMessages: stopResolution.pendingContextMessages,
816+ };
817+ }
818+
819+ const toolStopResult = await executeAssistantToolCalls(
820+ assistantMessage,
821+ opts,
822+ currentTurn,
823+ );
824+ if (toolStopResult) {
825+ return {
826+ finalResult: toolStopResult,
827+ nextTurn: currentTurn,
828+ pendingContextMessages: [],
829+ };
830+ }
831+
832+ const queuedTurn = consumeQueuedUserMessage(
833+ opts.db,
834+ opts.sessionId,
835+ opts.messages,
836+ opts.takeQueuedUserMessage,
837+ opts.onEvent,
838+ );
839+ return {
840+ finalResult: null,
841+ nextTurn: queuedTurn ?? currentTurn,
842+ pendingContextMessages: [],
843+ };
844+}
845+
674846 // ---------------------------------------------------------------------------
675847 // Agent loop
676848 // ---------------------------------------------------------------------------
@@ -702,9 +874,18 @@ export async function runAgentLoop(
702874 takeQueuedUserMessage,
703875 } = opts;
704876 let currentTurn = turn;
877+ let pendingContextMessages: Message[] = [];
878+ const remindedTodoSignatures = new Set<string>();
705879
706880 while (true) {
707- const assistantMessage = await streamAssistantMessage(opts);
881+ const assistantMessage = await streamAssistantMessage({
882+ ...opts,
883+ messages:
884+ pendingContextMessages.length > 0
885+ ? [...messages, ...pendingContextMessages]
886+ : messages,
887+ });
888+ pendingContextMessages = [];
708889 appendAssistantMessage(
709890 db,
710891 sessionId,
@@ -714,37 +895,10 @@ export async function runAgentLoop(
714895 onEvent,
715896 );
716897
717- const stopResult = resolveLoopStopReason(
718- assistantMessage,
719- messages,
720- onEvent,
721- );
722- if (stopResult) {
723- return stopResult;
724- }
725-
726- if (
727- assistantMessage.stopReason === "stop" ||
728- assistantMessage.stopReason === "length"
729- ) {
730- const finalResult = finalizeStoppedAssistantMessage(
731- db,
732- sessionId,
733- messages,
734- assistantMessage,
735- assistantMessage.stopReason,
736- takeQueuedUserMessage,
737- onEvent,
738- );
739- if (typeof finalResult === "number") {
740- currentTurn = finalResult;
741- continue;
742- }
743- return finalResult;
744- }
745-
746- const toolStopResult = await executeAssistantToolCalls(
898+ const iterationOutcome = await resolveAgentIteration(
747899 assistantMessage,
900+ currentTurn,
901+ remindedTodoSignatures,
748902 {
749903 db,
750904 sessionId,
@@ -754,22 +908,14 @@ export async function runAgentLoop(
754908 signal,
755909 onEvent,
756910 model,
911+ takeQueuedUserMessage,
757912 },
758- currentTurn,
759913 );
760- if (toolStopResult) {
761- return toolStopResult;
914+ if (iterationOutcome.finalResult) {
915+ return iterationOutcome.finalResult;
762916 }
763917
764- const queuedTurn = consumeQueuedUserMessage(
765- db,
766- sessionId,
767- messages,
768- takeQueuedUserMessage,
769- onEvent,
770- );
771- if (queuedTurn !== null) {
772- currentTurn = queuedTurn;
773- }
918+ currentTurn = iterationOutcome.nextTurn;
919+ pendingContextMessages = iterationOutcome.pendingContextMessages;
774920 }
775921 }
src/headless.test.ts+11−0
@@ -163,6 +163,17 @@ describe("headless", () => {
163163 expect(listPromptHistory(state.db, 1)).toEqual([]);
164164 });
165165
166+ test("runHeadlessPrompt rejects /todo before creating a session", async () => {
167+ const state = createTestState();
168+
169+ await expect(runHeadlessPrompt(state, "/todo")).rejects.toThrow(
170+ "Headless mode does not support slash commands: /todo",
171+ );
172+
173+ expect(state.session).toBeNull();
174+ expect(listPromptHistory(state.db, 1)).toEqual([]);
175+ });
176+
166177 test("runHeadlessPrompt streams tool execution events for tool-use turns", async () => {
167178 faux.setResponses([
168179 fauxAssistantMessage(
src/index.test.ts+55−0
@@ -12,6 +12,7 @@ import {
1212 loadOAuthCredentials,
1313 loadPromptContext,
1414 reloadPromptContext,
15+ runHeadlessCli,
1516 } from "./index.ts";
1617 import type { LoadedPlugin } from "./plugins.ts";
1718 import { openDatabase } from "./session.ts";
@@ -162,6 +163,60 @@ test("bin/mc.ts reports headless command errors without a stack trace", async ()
162163 );
163164 });
164165
166+test("runHeadlessCli uses final-text mode by default in non-TTY environments", async () => {
167+ const state = createTestState();
168+ const calls: string[] = [];
169+
170+ const stopReason = await runHeadlessCli(
171+ state,
172+ { prompt: "fix the tests", json: false },
173+ { stdinIsTTY: false, stdoutIsTTY: false },
174+ {
175+ readStdin: async () => {
176+ throw new Error("stdin should not be read when a prompt was provided");
177+ },
178+ runJson: async () => {
179+ calls.push("json");
180+ return "stop";
181+ },
182+ runText: async (_state, rawPrompt) => {
183+ calls.push(`text:${rawPrompt}`);
184+ return "stop";
185+ },
186+ },
187+ );
188+
189+ expect(stopReason).toBe("stop");
190+ expect(calls).toEqual(["text:fix the tests"]);
191+});
192+
193+test("runHeadlessCli uses NDJSON mode only when --json was requested", async () => {
194+ const state = createTestState();
195+ const calls: string[] = [];
196+
197+ const stopReason = await runHeadlessCli(
198+ state,
199+ { prompt: "fix the tests", json: true },
200+ { stdinIsTTY: false, stdoutIsTTY: false },
201+ {
202+ readStdin: async () => {
203+ throw new Error("stdin should not be read when a prompt was provided");
204+ },
205+ runJson: async (_state, rawPrompt) => {
206+ calls.push(`json:${rawPrompt}`);
207+ return "stop";
208+ },
209+ runText: async () => {
210+ calls.push("text");
211+ return "stop";
212+ },
213+ },
214+ );
215+
216+ expect(stopReason).toBe("stop");
217+ expect(calls).toEqual(["json:fix the tests"]);
218+});
219+
165220 test("didOAuthCredentialsChange compares refreshed credentials structurally", () => {
166221 const current = {
167222 refresh: "refresh-token",
src/index.ts+76−9
@@ -25,9 +25,11 @@ import { getEnvApiKey, getModels, getProviders } from "@mariozechner/pi-ai";
2525 import { getOAuthApiKey, getOAuthProviders } from "@mariozechner/pi-ai/oauth";
2626 import type { ToolHandler } from "./agent.ts";
2727 import {
28+ type CliOptions,
2829 parseCliArgs,
2930 resolveHeadlessPrompt,
3031 shouldUseHeadlessMode,
32+ type TtyState,
3133 } from "./cli.ts";
3234 import { getErrorMessage } from "./errors.ts";
3335 import { type GitState, getGitState } from "./git.ts";
@@ -71,8 +73,12 @@ import {
7173 executeEdit,
7274 executeReadImage,
7375 executeShell,
76+ executeTodoRead,
77+ executeTodoWrite,
7478 readImageTool,
7579 shellTool,
80+ todoReadTool,
81+ todoWriteTool,
7682 } from "./tools.ts";
7783 import { resolveAppVersionLabel } from "./version.ts";
7884
@@ -382,11 +388,28 @@ const BUILTIN_HANDLERS: Record<string, ToolHandler> = {
382388 function buildTools(
383389 model: Model<string>,
384390 plugins: LoadedPlugin[],
391+ messages: AppState["messages"],
385392 ): { tools: Tool[]; toolHandlers: Map<string, ToolHandler> } {
386- const tools: Tool[] = [editTool, shellTool];
393+ const tools: Tool[] = [editTool, shellTool, todoWriteTool, todoReadTool];
387394 const toolHandlers = new Map<string, ToolHandler>([
388395 [editTool.name, BUILTIN_HANDLERS.edit!],
389396 [shellTool.name, BUILTIN_HANDLERS.shell!],
397+ [
398+ todoWriteTool.name,
399+ (args) =>
400+ executeTodoWrite(
401+ {
402+ todos: Array.isArray(args.todos)
403+ ? (args.todos as Array<{
404+ content: string;
405+ status: "pending" | "in_progress" | "completed" | "cancelled";
406+ }>)
407+ : [],
408+ },
409+ messages,
410+ ),
411+ ],
412+ [todoReadTool.name, () => executeTodoRead(messages)],
390413 ]);
391414
392415 // Conditionally register readImage for vision-capable models
@@ -696,7 +719,7 @@ export function buildToolList(state: AppState): {
696719 toolHandlers: Map<string, ToolHandler>;
697720 } {
698721 if (!state.model) return { tools: [], toolHandlers: new Map() };
699- return buildTools(state.model, state.plugins);
722+ return buildTools(state.model, state.plugins, state.messages);
700723 }
701724
702725 /**
@@ -763,6 +786,47 @@ export {
763786 saveOAuthCredentials,
764787 };
765788
789+// ---------------------------------------------------------------------------
790+// Headless CLI
791+// ---------------------------------------------------------------------------
792+
793+type HeadlessCliStopReason = "stop" | "length" | "error" | "aborted";
794+
795+/**
796+ * Run one headless CLI prompt using the output mode selected by the parsed CLI flags.
797+ *
798+ * Non-TTY detection only decides whether headless mode should run at all.
799+ * Once headless mode is selected, `--json` is the only switch that chooses
800+ * NDJSON streaming versus final-text output.
801+ *
802+ * @param state - Initialized application state for the run.
803+ * @param cli - Parsed CLI options.
804+ * @param tty - Current TTY availability.
805+ * @param deps - Injected I/O and runner callbacks.
806+ * @returns The terminal stop reason for the headless run.
807+ */
808+export async function runHeadlessCli(
809+ state: AppState,
810+ cli: CliOptions,
811+ tty: TtyState,
812+ deps: {
813+ readStdin: () => Promise<string>;
814+ runJson: (
815+ state: AppState,
816+ rawPrompt: string,
817+ ) => Promise<HeadlessCliStopReason>;
818+ runText: (
819+ state: AppState,
820+ rawPrompt: string,
821+ ) => Promise<HeadlessCliStopReason>;
822+ },
823+): Promise<HeadlessCliStopReason> {
824+ const rawPrompt = await resolveHeadlessPrompt(cli, tty, deps.readStdin);
825+ return cli.json
826+ ? deps.runJson(state, rawPrompt)
827+ : deps.runText(state, rawPrompt);
828+}
829+
766830 // ---------------------------------------------------------------------------
767831 // Main
768832 // ---------------------------------------------------------------------------
@@ -785,14 +849,17 @@ export async function main(): Promise<void> {
785849
786850 if (shouldUseHeadlessMode(cli, tty)) {
787851 try {
788- const rawPrompt = await resolveHeadlessPrompt(cli, tty, async () => {
789- return Bun.stdin.text();
852+ const stopReason = await runHeadlessCli(state, cli, tty, {
853+ readStdin: async () => Bun.stdin.text(),
Cut short: this commit's diff is over 1000 lines.
src/input.ts+1−0
Cut short: this commit's diff is over 1000 lines.
src/prompt.test.ts+6−0
Cut short: this commit's diff is over 1000 lines.
src/prompt.ts+7−5
Cut short: this commit's diff is over 1000 lines.
src/session.test.ts+24−1
Cut short: this commit's diff is over 1000 lines.
src/session.ts+56−8
Cut short: this commit's diff is over 1000 lines.
src/tools.test.ts+208−0
Cut short: this commit's diff is over 1000 lines.
src/tools.ts+241−2
Cut short: this commit's diff is over 1000 lines.
src/ui.test.ts+2−1
Cut short: this commit's diff is over 1000 lines.
src/ui.ts+35−8
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.test.ts+71−0
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.ts+13−0
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.test.ts+64−0
Cut short: this commit's diff is over 1000 lines.
src/ui/conversation.ts+102−3
Cut short: this commit's diff is over 1000 lines.
src/ui/help.test.ts+1−0
Cut short: this commit's diff is over 1000 lines.
src/ui/help.ts+1−0
Cut short: this commit's diff is over 1000 lines.