“The recipient's name in invitation emails has extra spaces at both ends. Please fix it and run the tests.” Suppose three functions in the project are named greeting, and the right one is inside a file over a thousand lines long. How does a coding agent get from that sentence to a change you can inspect? In late July I looked at how Cursor understands projects and reviews changes from the product side. In August I wanted to see how these steps connect in code.
On August 13 I searched for open-source coding agents and opened the repositories for Cline (an editor extension) and Gemini CLI (a terminal coding assistant, where CLI means command-line interface). I also read Ernest Chiang's list of command-line assistants, including Claude Code, AWS Q CLI, Codex CLI and Gemini CLI. 1 Gemini CLI published both terminal UI and tool execution code, a good comparison with Cline running in an editor.
In DeepWiki I browsed Cline's architecture and Gemini CLI's tool scheduling, then reopened my Q&A sessions about the two projects. 2 Both initial questions concerned memory and file modifications. Three follow-ups in the Cline conversation built on one another: can it change only a small part of a long file? How does it locate the lines? If the model must copy the exact original text, won't that fail frequently? 34
I tried two starting points. On August 21 I wrote tool registration and execution in Python so a program could find a tool by name, check arguments and call it. My TypeScript experiment starting on the 22nd began with opening a file and previewing changes from the terminal. On the 27th I saved both Q&A sessions and source excerpts in the project. 5
Architecture overview: who handles the email greeting fix from request to test result?
Follow one request through the UI, model, tools and executor
My first question in the Cline notes was:
“how agent loop works in cline? how memory is implemented and how to retreive and modify relavent code in agent loop? first answer does cline have agent mode?”3
Cline split interaction into Plan and Act at the time. In Plan it could read files, search and discuss a solution. After switching to Act it could edit code and run tools. That's the capability I was looking for when I asked whether it had an agent mode. 6
By “agent loop” I mean something the program repeats: send the task and gathered material (context) to the model, get a proposed next action, execute it and send back the result. The model's ability to advance depends on the loop receiving real feedback.
I submit the request through the UI. The model proposes searching for greeting. The search returns matching lines, which the model uses to select a file to open. The read result gives it the actual function, so it can propose an edit. I inspect the diff and confirm the write. The executor sends test output back to the model. If the tests fail, the next round starts with the error.
Conceptual diagram drawn for this article. Tools can be local code or connect to external services through Model Context Protocol (MCP). Execution failures, denials and test failures must also return to context as results. This is neither a historical UI screenshot nor a complete product architecture.
Who saves the task, finds code, checks permissions and logs the result?
The same example helps test whether the modules are divided sensibly. Here responsibilities follow the inputs and outputs of each step, drawing on the original design conversation and both sets of source notes. For instance, entering a filename in the terminal makes the UI pass a path to a read tool, which returns text. A table row might begin as one function, and several responsibilities can share a package. 734
| Owner | What it receives and produces in the email task |
|---|---|
| User interface | Accepts “fix the greeting,” displays progress and edit previews, returns confirmation or cancellation. |
| Task loop and prompting | Combines requirements, project instructions and tool descriptions into a model request. After a tool result, decides whether to send another round, await the user or finish. |
| Memory and context | Saves what was checked by task and retrieves messages, file excerpts and conventions needed for the next round. |
| Tool registration, permission and execution | Registry finds the named tool and expected arguments. Executor validates arguments, checks rules, calls the tool and receives its result. |
| Search, files and commands | Search returns hits, reads return current source, writes report actual outcomes, and tests return exit status and output. |
| Logs | Record which call read which file, whether it was approved and how tests exited. A person can follow call order to find the failing step. |
| Deep research | For questions needing external sources, extend search and reading into multiple verification rounds and retain provenance. Fixing this greeting starts with the project itself. |
How does an agent continue after the model requests a tool?
In the Cline excerpt from src/core/task/index.ts, initiateTaskLoop calls recursivelyMakeClineRequests unless canceled. One source comment is direct:
“we keep responding back to him with his tool's responses”3
In other words, keep feeding tool responses to the model. But don't reduce this code to “exit a while loop on attempt_completion.” The outer logic also handles didEndLoop, cancellation and prompts to continue when no tool was used. Source comments distinguish task interaction from loop exit. Follow the call chain to see how completion signals are handled.
How does an application give tools to the model and send results back?
While studying model integration, I also read OpenAI's text generation, function calling and streaming docs. Streaming lets applications receive output in parts. The search starting at client.chat.completions.create tools relates more directly to PromptPulse's model and MCP integration. Here I also use these materials to explain a common agent API mechanism: sending input, receiving tool calls and returning execution results. 8910
Using the Responses API, first see how a read connects to the next round.
The text generation docs show submitting content in input, setting behavior with instructions and reading the output. They specifically note:
“The
outputarray often has more than one item in it!”8
output_text is convenient for retrieving text, but an agent must also recognize tool calls and other items in output. Reading the first item's text doesn't mean the whole response has been handled. This means handling visible chat text separately from the structured output the runtime must interpret. 8
The docs state the execution step explicitly:
“Execute code on the application side with input from the tool call”9
For a code read, the app supplies a function name, description and argument schema. On receiving a function_call, validate the name and arguments, execute the local tool and return its result as function_call_output using the corresponding call_id. Subsequent requests also need the relevant conversation and model output. Sending only file contents without their call association isn't enough. 9
Suppose the model asks to read src/mail.ts. These two illustrative Responses API messages omit irrelevant fields. The first comes from the model and the app puts the second in its next request. arguments on the first line is a JSON string awaiting parsing. Only output on the second is text actually read from disk. 9
{"type":"function_call","name":"read_file","arguments":"{\"path\":\"src/mail.ts\"}","call_id":"call_mail"}
{"type":"function_call_output","call_id":"call_mail","output":"import { greeting } from './mail/greeting';"}
A response can contain several calls, and returning their results can generate more calls. This is the API-level connection in the agent loop. My ToolRegistry and ToolExecutor could handle its local execution. That's a correspondence in my design, not a class structure required by function calling.
When output streams in, how does the UI distinguish answers from tool requests?
In Gemini CLI a model can first say “I'll look at the email template” and then request a file read. How does the terminal distinguish them? In the August 13 source, Turn.run() converts text into Content events and function calls into ToolCallRequest events with name, arguments and call ID. In the UI, useGeminiStream appends text as it arrives and collects requests, handing them to the scheduler together when the stream ends. Only if no tools are pending and the current turn qualifies for a continuation check does the client use checkNextSpeaker to determine who speaks next. 41112
For example, the control flow below simplifies the Gemini CLI source. Events from the response must first be yielded so the UI can display them as they arrive. After the final event, the program still checks for pending tools. Loop detection, model switching and turn limits are omitted. 12
for await (const event of turn.run(request, signal)) {
yield event;
}
if (!turn.pendingToolCalls.length && signal && !signal.aborted) {
// 此分支才会询问下一轮该由模型还是用户发言
const next = await checkNextSpeaker(this.getChat(), this, signal);
// 若 next?.next_speaker === 'model',再发起一轮请求
}
The code structures differ, but both showed me that an agent loop needs to save state, execute actions, handle results and decide when to stop. A model response ending doesn't automatically finish the user's task. Asking the model to keep going cannot replace explicit exit conditions.
The streaming docs explain stream: true and server-sent events (SSE), and state:
“The Responses API uses semantic events for streaming.”10
The events have types. For example, response.output_text.delta can append visible text, response.completed marks one response complete, and errors need separate handling. Streaming solves progressive delivery of one response. The agent loop solves how to continue the task after receiving results. 10
Function arguments can also arrive in pieces. Accumulate them by call item, then parse, validate and execute once complete. Half a JSON object isn't a complete command. 9 Likewise one response.completed doesn't finish a programming task. The app still needs to check pending tools and task acceptance results.
Memory: how does an assistant resume yesterday's task after you reopen the editor?
“Memory” easily conflates several things. I divide it into three parts:
| Part | What it stores | Why it's needed |
|---|---|---|
| Current task runtime state | Conversation, tool results, current step, cancellation state | Maintain continuity during this execution |
| Long-term project instructions | Goals, conventions, technical choices and current progress | Avoid re-explaining all context on the next task |
| Code context needed this round | Search hits, file excerpts, relevant definitions and test output | Give the model real project evidence for its decisions |
How does Cline restore UI messages, model conversation and tool results?
Suppose I close the editor just after the assistant reads the email template. Reopening the old task requires Cline to restore two records: ui_messages.json stores displayed messages, and api_conversation_history.json stores the conversation sent to the model. Both are found by task ID. Selecting a historical task runs resumeTaskFromHistory(), which clears stale “continue?” prompts, loads both histories and context state, and then asks whether to continue. 13
const savedApiConversationHistory = await getSavedApiConversationHistory(context, this.taskId)
this.messageStateHandler.setApiConversationHistory(savedApiConversationHistory)
These two lines come from Cline's resume function before it displays the continuation prompt.13
Now I can add “only change the invitation email.” If the last old history item was a user message, Cline extracts it, combines it with the resume explanation and my new request as the next input, then reenters initiateTaskLoop. That's how it can discuss what it found last time. To know what yesterday's function looks like today, it still needs to reread the file. 13
Which project conventions should carry over into a new task?
Reopening an old task gives it yesterday's conversation. To carry “which tests to run after editing email templates” into a separate task, the app must retrieve the convention elsewhere. In the catgirl duty-roster example, the outgoing shift can hand over the whole logbook. As records grow, retrieve only those relevant to the question and include them in the current request. A coding agent likewise needs to decide where to write things and which to read this time.
Cline's Memory Bank documentation describes long-term materials this way:
“core files and optional context files, all in Markdown format.”3
projectbrief.md records scope, systemPatterns.md architecture and technical decisions, activeContext.md current work, and progress.md progress and known problems. This is a documentation convention requiring initialization, reading and maintenance. Putting Markdown files on disk alone doesn't automatically add their content to every model call.
Which information should the team share? Ernest Chiang puts project conventions in the repository's CLAUDE.md and personal preferences about Chinese/English typography in ~/.claude/CLAUDE.md. Coaching teams, he found installing the tool quick but documenting existing consensus took varying amounts of time. 14 For the email project, “which tests to run after a template change” belongs in the repository for the next developer. “Ask me directly when you're unsure” can travel between projects in my personal settings.
In “抓大放小,” Ernest Chiang wrote, “不同維度或是不同層次的需求,請切分成不同任務或對話。” Separate requirements at different levels or dimensions into different tasks or conversations. He also suggests splitting materials into small files and loading by task. 1 Editing an invitation greeting needs the template and tests. Redesigning the notification architecture calls for architecture conventions too. That raises an implementation question: once the files are split, who reads them into this request?
I saw a similar connection in Gemini CLI source. loadHierarchicalGeminiMemory loads hierarchical project instructions and the prompt builder appends nonempty userMemory to the base prompt. The documentation explains:
“These Markdown files contain instructions, guidelines, or context that you want the Gemini model to be aware of during your interactions.”4
To me, “give an agent memory” begins with what to save, when to retrieve it and how to put it in a request. Growing conversations need compression too, but summaries lose information. When editing code, reread the relevant files. An old summary cannot stand in for their current state.
OpenAI's text generation docs also say instructions applies only to the current request. When continuing with previous_response_id, prior instructions don't automatically carry over. 8 Preserving conversation state and continually supplying project rules need separate handling.
Gemini CLI's entry point for adding these instructions is getCoreSystemPrompt(userMemory) in packages/core/src/core/prompts.ts. If the project says “trim whitespace around names in invitation email greetings,” the loader must pass it to this function for the model to see it during the task. The simplified source below omits parts of the base prompt that vary by runtime environment. 15
const memory = userMemory?.trim();
return memory ? basePrompt + "\n\n---\n\n" + memory : basePrompt;
Retrieval: the assistant knows what to change, but which code should it read today?
Three functions share a name. Which should it open next?
Yesterday's record may contain a function name, but today the repository might contain another with the same name. Suppose tests, web UI and email each have a greeting function. Here's an illustrative project showing the selection I cared about. Cline's model could first request: 16
<search_files>
<path>src</path>
<regex>greeting</regex>
<file_pattern>*.ts</file_pattern>
</search_files>
search_files uses ripgrep, a text-pattern search tool, to return matches and surrounding code. Suppose it finds three definitions and a hit at the entry point for sending invitations:
// src/mail.ts
import { greeting } from './mail/greeting';
That import gives the model a verifiable reason to open src/mail.ts, check whether invitation sending really calls it, then use read_file on src/mail/greeting.ts. If it actually calls another template, follow that call instead. The search tool lists matches. The model decides what to read next from the task and returned code. Three definition locations alone can't answer which affects invitations. If the function name is unknown, Cline can use list_code_definition_names to list functions, classes and other definitions in top-level files of a directory and narrow the search. 16
In Gemini CLI the equivalent can start with search_file_content and {"pattern":"greeting","path":"src","include":"*.ts"}. Results include path, line number and matching line. The system prompt asks it to verify assumptions with read tools. Line numbers help open nearby code, but the edit tool must still verify what is there now. 15
Once the function is found, another kind of question may require a person. If a recipient name is all spaces, should the email say “friend” after trimming or omit the greeting? I'd first check existing templates, tests and project instructions and follow any established empty-name behavior. If none resolve it, show users both concrete effects and ask them to choose. In “說出心裡話,” Chiang suggests asking the assistant to propose several interpretations for discussion when requirements are unclear. The assistant can determine which code runs. The user decides what the recipient should see. 17
When does text search suffice, and when is an index worthwhile?
With a known function name or an exact phrase from the email, text search gives a verifiable lead. If all I recall is “the first letter sent to a new colleague” and the code says sendInvitation, searching those original words may fail. Cursor 1.2 used embedding-based semantic search, representing a question and code as numerical vectors, selecting candidates by similarity, then opening current files to verify. Retrieving material before giving it to the model for generation is retrieval-augmented generation (RAG). So I didn't build a vector database in the first round. I'd first see which tasks text search misses, then decide if maintaining an index for code chunks is worthwhile. Cursor indexing example · Built-in indexes in three assistants and connecting a Python retriever
Editing: once a function is found, how can you change just a few lines in a long file?
How do you describe a local edit?
In my second Cline question I narrowed the concern to output length. Even if it can read a long file, must it write the whole thing again to change a few lines?
“does cline support generating diff file and using patch? i think long files are not going to be handled well for llm because limit of context window, maybe diff files are better for this case?”3
If the model rewrites an entire long file every time, it consumes output tokens (the units models use to process text) and can more easily omit unrelated parts. But “use a diff” needs unpacking. How the model expresses an edit, how the program applies it and how the UI displays it are three separate problems. Below I call the difference between old and new text a diff and an applicable set of changes a patch.
| Method | What the model or caller provides | Program responsibility | Considerations |
|---|---|---|---|
| Whole-file write | Complete new contents | Create or overwrite a file | Expensive output for long files. All unchanged material must be preserved. |
| SEARCH/REPLACE | Old content and its replacement | Locate and replace the original | Stale or repeated text, whitespace and formatting affect matches |
| Unified diff/patch | Change hunks with context | Parse and apply the patch | Format, context and file version must match |
| Character-range edit | Start/end offsets and new text | Operate on a specific version of the string | Offsets depend on original text. Old positions cannot simply be reused. |
My third question was where line numbers come from. Insert a line at the beginning and every subsequent number changes. Once the invitation call leads to the right file, a freshly read passage can identify the edit location. The Cline version I saved used SEARCH/REPLACE blocks in replace_in_file, distinct from generating a file for the system patch command. This new example follows its format, rather than quoting project code: 3
------- SEARCH
export function greeting(name: string) {
return "Hello " + name;
}
=======
export function greeting(name: string) {
return `Hello ${name.trim()}`;
}
+++++++ REPLACE
The example assumes the entire old passage is present and context distinguishes the intended location. The model doesn't need an exact starting line. It supplies the text and the program locates it. Whole-file writes remain useful for short new files and major rewrites.
Local edits chiefly reduce the output needed to express a change. The model may still need a whole function, callers or relevant tests to understand it. Shortening output and reducing the context needed to understand code are separate things.
What happens when an exact match fails?
I asked another follow-up:
“will using sys prompts for exact content match have a high failure rate?”3
The excerpt from src/core/assistant-message/diff.ts showed that besides asking the model for accuracy, the program handles failures. First try an exact match, then a match ignoring leading and trailing whitespace per line, then matching first and last anchors of the block. Return an error if no suitable position is found. 3
The first step is ordinary string search. This line looks forward starting at the end of the previous edit block: 18
const exactIndex = originalContent.indexOf(currentSearchContent, lastProcessedIndex)
Supply only return name; and if two lines match, it hits the earlier one. Include the function signature in SEARCH for a chance to distinguish them.
Tolerance has a cost. Loosening matching raises the risk of changing a different similar passage. I think an editor needs to report location failures, ambiguous matches and actual edit results clearly to the model. After formatting or a user edit, subsequent edits should use current contents.
Cline's evals/diff-edits/README.md usefully defines what is evaluated. diffEditSuccess primarily measures whether edit blocks can be applied. It does not establish valid code or satisfaction of the user's semantic requirement. 3 Seeing fallback and evaluation code doesn't justify concluding the failure rate must be low.
The evaluation also defines its denominator. A valid attempt requires one replace_in_file call on the right file, potentially with multiple blocks. If the model chooses the wrong file, the tester samples again. A success rate under this evaluation answers “once the right file and tool call are selected, how many patches apply?” Wrong choices among the three greeting functions need separate counting. 19
I'd verify at least three things: whether the edit landed in the right place, whether the resulting code passes necessary checks, and whether behavior meets the requirement. A plausible-looking diff achieves only part of that.
How does the model learn the edit format, and what does it see if matching fails?
Prompt engineering became concrete here: explain available tools, argument formats, when local replacement fits, which version to use after an edit and how to continue after failure.
In my Cline questions I specifically asked where those prompts live. To trace “provide complete old lines for a local edit,” start with SYSTEM_PROMPT in src/core/prompts/system.ts. It receives the working directory and model capabilities, among other data, and selects model-specific templates such as model_prompts/claude4.ts. The general template covers replace_in_file arguments, markers and examples. The model generates text according to those rules. src/core/assistant-message/diff.ts matches it in the file. If matching fails, the executor reverts the preview and diffError in src/core/prompts/responses.ts returns original content and retry instructions. The next round now has the source needed to correct the mistake. 18
Where do a proposed edit, diff preview and final write actually happen?
My last question in both Q&A sessions was “how file read/write is done”. Following Cline's read_file shows the executor first checks path access and whether user confirmation is needed. After the read it records which files this task has viewed. When a model says “read this file,” the application process performs the actual open. 3
Gemini CLI clarified two other distinctions. For long text, offset and limit specify the start and maximum line count. For writes, write_file takes a path and full new contents, yet the UI can still diff old and new versions for confirmation. A diff preview establishes only that the application compared two versions. The model may have passed a complete file to the write tool.4
For example, to read lines 101–120 of a long file in the August 13 Gemini CLI, the arguments can look like this. The path field is absolute_path and offset is zero-based. 20
{"absolute_path":"/work/app/src/mail/greeting.ts","offset":100,"limit":20}
The same version can edit an existing function with replace using file_path, old_string and new_string. By default it expects one replacement. Set expected_replacements for several. For write_file, the ordinary interactive path works like this: 20
shouldConfirmExecutereads the original and compares it against proposed contents to generate a UI diff. The scheduler places the call inawaiting_approval.- Canceling ends this call. Approval schedules execution. If the user edited the proposal in the confirmation UI, the revised arguments are used.
executerevalidates arguments, prepares the contents and creates a parent directory if needed. The line below writes to disk. On success the tool reports the result to the model. Read/write errors are returned as errors. Automatically approved edits skip per-call questions. 20
fs.writeFileSync(params.file_path, fileContent, 'utf8');
Cline follows VS Code's editor save path. ToolExecutor builds candidate contents from old text and replacement blocks. Where confirmation is needed, denial invokes revertChanges(), approval proceeds through saveChanges(), and VS Code saves the edited document. If the user edited the preview or formatting ran on save, the next edit should use the actual saved contents. Hence Cline also prepares a tool response returning final text to the model. 21
Permissions: who decides whether a proposed file write or command can execute?
Between proposal and execution, when does the user get asked?
If the project instructions say to run npm test after editing the template, the model knows what command to propose. Before launching a process, the app must decide whether this call can proceed directly or needs my review first.
In June, while considering building an app with Claude Code's SDK, I asked how my UI could receive the approval request and return the user's decision when the command ran inside Claude Code. I described the interface at the time and a VS Code extension's implementation in this English article about command authorization.
In August I asked one step further: should the same command ask again next time? Claude Code writes reusable decisions into permission configuration, then evaluates tool arguments and working directory at runtime. For an example, see how Claude Code decides whether a tool call requires approval.
After a user approves, which directories and commands can the program access?
In the August Gemini CLI, run_shell_command extracts command names and consults an allowlist to decide whether confirmation is needed. Only at execution does it hand command and working directory to ShellExecutionService to launch a subprocess. “Allow” answers whether this command can start. What files the subprocess can see and whether it can use the network depend on its environment. 22
Even an approved test script might read a neighboring repository. “Only touch the current workspace” in a prompt lets the model consider the convention when proposing commands. Actual script access depends on process privileges, visible directories and execution isolation. Similarly, stopping a timed-out command requires a way for the executing program to interrupt its process.
Interface: how does someone follow progress, edit input and confirm diffs while the agent runs?
Which events display as text, and which await a decision?
During the greeting fix the UI receives three things: the model says “I'll look at the template,” search returns three hits, and the write tool asks for confirmation. Append the first to the response, display the second by call, and leave an actionable preview for the third. While waiting for me, the UI must remember which call is pending so “approve” reaches the right one. 1120
In VS Code the same decision is a sidebar button. Cline draws the sidebar in a Webview (a page embedded in the editor). The August version attaches a listener when the sidebar is ready, forwards incoming requests to an extension controller and returns results to the UI. That suggests a reading order: for a button that doesn't respond, check whether it sent a message. For a file that wasn't written, follow execution on the extension side. 23
From typing /open to a terminal file preview, how do UI and core divide work?
Suppose I've typed /open src/mail when a previous round returns a line of test output. It belongs in the results area. My path and cursor stay in the input area. Only on Enter does the UI pass the full path to the core. Show contents on success or identify the path that failed. Start with an editable file preview in Ink. Following the stack further, Gemini CLI's UI and core call methods within one process. See from TypeScript function calls to a Python subprocess.
Which path should work first in a homegrown version?
I initially asked which modules an assistant like Claude Code, Gemini CLI or Cline needs. I gave three examples: a command executor receiving and running commands, file search adding matching code to the task context, and memory storing task history. I also asked about advanced implementations at the time. The assistant read that as “how to orchestrate planning and action,” citing research systems like Magentic-One. That's an example of how a coordinator selects the next participant. To evaluate an entire coding agent, first agree whether you're comparing code location, applying edits or ultimately passing tests. I then asked for a module table we could discuss item by item: permission checks before tool calls, file I/O, deep research, prompt templates, terminal UI and logs, with development order based on dependencies. 7
Python route: why keep my own tool registry after adding MCP?
I asked the assistant to order development by dependency. It drafted Sprint 0 through Sprint 13. Applying them to the email example clarifies the reasoning behind several steps. 7
| Draft sprint | What can be tested | Why it comes here |
|---|---|---|
| 0: establish tool interface, registration and logs | Register a tool, give it input, inspect output and log | Define calls and results first for reuse by file writes and commands. |
| 1–2: connect the task loop, then add file search | First specify a file, confirm an edit and run tests. Then give only the task and let the agent find the file. | Verify edits and feedback first, then whether search chooses the right file. |
| 3–5: refine permissions, test feedback and version control | Deny a command or fail a test and observe continuation | Real tool calls, test output and diffs are now available to inspect. |
| 6–8: add task memory, prompt selection and deep research | Reopen a task with project conventions. Look up external questions and return sources. | These features must feed selected material back through an existing model-call path. |
| 9–10: isolate command processes and record executions | Limit a runaway test and find where it stalled on the timeline | Real test tasks give concrete resource constraints and failures to examine. |
| 11: connect external tool plugins | Connect an MCP server offering a new tool and call it under existing permissions | Tool registration and execution already work. This adds discovery and connection of external tools. |
| 12–13: integrate the editor and extend team permissions | Approve the same task from the editor and check repository/team rules apply | A new UI must rejoin the same run, and rules need a common enforcement point. |
External plugins weren't due until sprint 11, but sprint 0 required deciding where tools were registered. I first asked for a CLAUDE.md brief ready to hand to a coding assistant, then for an interface for future MCP plugins. The assistant changed the plan to building an MCP server first to expose example tools. I added, “i want the original tool registry”. If a tool is callable from both terminal and MCP, should each entry point register it and check permissions separately? I wanted the core to keep tools and rules. Each entry would submit the chosen tool and arguments and translate its result into the caller's format. 7
On August 21 I asked in the Python project's Cursor conversation:
“execute this plan, and if anything unclear ask me for advice”5
The Sprint 0 plan placed ToolRegistry and ToolExecutor in the core. MCP was a protocol adapter converting external messages into calls the core already understood. One design rule in the plan was:
“All calls (CLI, MCP, future WS/HTTP) go through
ToolExecutor→ which usesToolRegistry+rules.Policy. Protocols are adapters only.”24
See how that maps to code with echo, which simply returns a message unchanged. At startup ToolRegistry registers it by name. A separate Policy object stores its rules, including allowed origins cli and mcp. ToolExecutor receives both registry and policy. For a call it finds the tool, validates arguments, checks rules, executes and returns a result. If policy requires confirmation, it returns an authorization-required result before the tool runs. Both entry points find the same echo and rules. 24
Suppose the caller passes {"message":"hi"} to echo. The terminal entry labels the source cli, while MCPBridge.call_tool() labels it mcp. From the executor receiving an internal ToolCall to handing the internal ToolResult back to the entry point, both paths go through identical checks. 24
sequenceDiagram
participant Caller as 调用者
participant Entry as 本次入口(CLI 或 MCP)
participant Exec as ToolExecutor
participant Echo as echo 工具
Caller->>Entry: 调用 echo,消息为 hi
Entry->>Exec: ToolCall,带上来源 cli 或 mcp
Exec->>Exec: 向注册表取工具,校验参数,再向 Policy 查权限
alt 规则允许
Exec->>Echo: 调用工具
Echo-->>Exec: 成功结果,消息为 hi
else 规则拒绝
Note over Exec: 跳过工具,生成带原因的失败结果
end
Exec-->>Entry: ToolResult
alt 从 CLI 进入
Entry-->>Caller: 打印含 ok、result、error 等字段的 JSON
else 从 MCP 进入
Entry-->>Caller: 返回含 content 和 isError 的工具响应
end
Diagram adapted from the original design conversation's Call Flow and the Python prototype. One entry point is chosen per call and the result follows the return path.724
On success, terminal JSON contains "ok": true and "result": {"message": "hi"}. The MCP adapter puts the explanatory text Echoed: hi into content and sets isError: false. On denial it puts the reason in text and sets isError: true. That lets an external client call local tools. For my own assistant to discover and call tools from external services later, it needs the opposite, client-side flow. 24
echo can independently verify the entry point, checks and final result for one message. Reading and editing code and running tests still require those capabilities individually. Run records included missing dependencies and MCP adapter not available. An AI reply saying “implementation complete” cannot stand in for end-to-end verification. 5
Looking through the code later, I found a telling boundary. _execute_with_timeout() compares elapsed time only after tool.call() returns. It can report an overlong call but cannot interrupt one that never returns. A timeout in the function name still falls short of actual cancellation. 24
TypeScript route: why limit the first round to reading, editing, previewing and saving one file?
On the evening of August 22 I opened Gemini CLI's and Cline's package configs, then went back and forth between Gemini CLI's packages/cli and packages/core. 25 I originally imagined an Ink interface calling Python for code retrieval and asked how exactly UI and core pass input. With TypeScript and Ink I set a single-file first-round goal: open a file, see a proposed edit, then decide whether to write or discard it.
💡 Tip: A technique I use in vibe coding is to do and verify just one thing per round.
I came up with this while coding with an assistant in natural language. Pick one feature per round to implement, extend or refactor. For single-file editing I take one file from opening through saving, then read it back to verify the change. If code retrieval comes to mind halfway through, leave it for the next round. The conversation and code informing the assistant’s next step then serve the same goal. I spend less time re-explaining what this round should change, development is faster, and the purpose of each edit is clearer in commit history.26
I gave Cursor the Sprint 0 plan and asked:
“help me realise base functionalities”5
The plan narrowed the scope to:
“Read → Edit → Diff → Write (with backup)”.27
The directories are packages/cli and packages/core. The former owns Ink UI and command routing, the latter the workspace, file storage, edit operations and diffs. RAG retrieval, MCP tools, code execution and multi-file refactoring were later stages. That's an order for the experiment, not evidence that TypeScript suits agents better than Python.
The workspace's types.ts represents edit operations with these types:
export type EditOp =
| { kind: 'insert'; at: number; text: string }
| { kind: 'replace'; start: number; end: number; text: string };
Code excerpt from local packages/core/src/types.ts. This file belongs to an uncommitted workspace. The initial commit date cannot date the excerpt separately.27
PatchEngine checks for overlapping operations and applies them from highest position to lowest so earlier insertions don't invalidate later offsets. Offsets are JavaScript string indexes, that is UTF-16 code units, not bytes or necessarily user-visible character counts.
These types suit internal edit representation, but model output still needs translating into reliable operations. For SEARCH/REPLACE, locate the passage in the corresponding file version. Accepting numbers internally doesn't make the model able to calculate every offset reliably.
FileStore describes backing up the old file, writing a temporary file, syncing the file handle and replacing the target with rename. DiffService uses createTwoFilesPatch to generate a unified diff for display. Applying edits internally and displaying a diff to a person can be separate implementations. 27
How do you put first-round scope and acceptance criteria into CLAUDE.md?
I wanted a brief ready to hand directly to a coding assistant. The shortened versions below reorganize the two Sprint 0 plans. Each corresponds to one prototype and can serve as its own CLAUDE.md. 72427
Python version · Call one tool from two entry points
实现一个 echo 工具,接收字符串 message 并原样返回。先在核心登记工具和调用规则,
让执行器负责查找工具、校验参数、检查来源、执行并返回结果。
接上 CLI,再接 MCP 工具调用适配层。两个入口都把工具名、参数和来源交给同一执行器。
验收:分别从两个入口发送 {"message":"hello"},检查两边都能取回 hello。
把一个来源设为禁止,确认该入口返回拒绝且 echo 未执行,另一入口仍然成功。
再用缺少 message 的请求验证参数错误。交付可重复运行的测试与调用示例。
TypeScript version · Complete a single-file edit that can be discarded or saved
用 Ink 显示命令输入框和文件预览。先实现 /open 读取一个文本文件,
再在内存中对它应用一次局部编辑。/diff 显示原文与候选文本的实际差异。
/discard 丢弃候选修改;/write 经用户确认后备份并写入;/undo 恢复上一版。
验收:用临时目录里的邮件模板改一次称呼,预览时检查磁盘仍是原文。
分别走放弃和确认两条路径。确认后重新读取文件,核对新文本、备份和撤销结果。
本轮只交付单文件编辑。把接模型、检索和多文件修改留给后续迭代。
The TypeScript plan left cursor and selection behavior in the editor for the next round. Once single-file editing and preview work reliably, round four can let the model propose edits through the same confirmation and save path. Acceptance can then distinguish a wrong model proposal from a save button that never worked. 27
Returning to both prototypes: what was connected, and what remained a module or UI?
Those days I first had to get the UI running. The project used JavaScript's ESM format. What should execute TypeScript in development? With CLI and core in the same repository, where does Ink go? I compared tsx and ts-node and encountered compatibility issues between React types and Ink components.
Ink is used by packages/cli. If npm workspaces manage the packages, npm install ink -w ./packages/cli from the repository root records it in the CLI package's package.json. Physical installation is separate. npm can hoist a dependency satisfying several packages into an upper-level node_modules. If two packages need incompatible versions, one version may go in a subdirectory. Inspect each package.json to see which package depends directly on Ink. 28
React did not give the terminal input box its expected behavior automatically. I repeatedly worked on executing commands, recalling history with up/down arrows, moving the cursor left/right, deleting with backspace and opening and displaying files. “Provide a command input” is an easy plan item. In use, each key needs defined behavior. I compared that interaction in TypeScript and Rust in Ink versus Ratatui for terminal UIs.
On August 25 the entry point in branch commit 03bd8c1 showed only Hello CLI world. The next day I saved unfinished edits in a Git stash, a temporary workspace snapshot. In 92b0527 the entry point already connected sidebar, edit view, status bar, command input and diff dialog. Enter /diff and it opened the dialog, but passed Diff functionality coming soon.... That line marks the boundary precisely: the display was ready, but original text and proposed changes still had to be connected. 27
Undo showed a similar gap. Workspace FileStore held history in instance memory, while the command handler created a new instance on UI rerenders. Consecutive edits and undo required keeping that history across renders first. 27
The plan's “safe write” was not a verified guarantee either. Its path check used string startsWith, which treats sibling directories sharing the workspace prefix as matches. A real workspace restriction must handle directory boundaries and symbolic links. A temporary file and rename don't by themselves solve concurrent overwrites, permission preservation and crash recovery on every platform.
These details changed my definition of a minimum feature. A prototype can omit RAG and multiple agents and operate on one file, but the user's path from opening that file to confirming an edit has to work.
At this point I'd first express acceptance as a concrete task: give the agent a small project, have it find a specified function, read the implementation, propose a local edit, show the difference, write after confirmation and run a test verifying the behavior.
Each step has an inspectable result: which file version was read, where the edit matched, what was actually written, whether the test ran and what it returned. Failures have locations that distinguish retrieval, model output, editor or code problems.
The August prototypes each covered part of the path. Python left an execution framework for calling one tool from different entry points. TypeScript left file operation modules and a terminal UI that could open a diff dialog. Still missing was one end-to-end check: a model proposes an edit to a real file, a user sees the actual diff and confirms the write, and the test result returns to the model. That's the acceptance test I took away from the experiment.
References
Footnotes
-
Chiang, E. (2025, July 30). 我的 Anthropic Claude Code 學習筆記. Ernest Chiang. 「當前主要競爭者 (2025-08)」列出当时的命令行工具;引文见「抓大放小」第一条,按任务载入文件的建议见同条子项。 ↩ ↩2
-
DeepWiki. (n.d.). Cline: Architecture overview、Gemini CLI: Tool scheduling and execution [历史栏目路径]. 2025 年 8 月 13 日访问。栏目名按当时的访问路径保留;这两个地址后来分别显示 Quick Start Guide 和 Tool Registry and Discovery。当时保存的两组问答及所附源码见注 2、3。 ↩
-
DeepWiki. (n.d.). How agent loop works in Cline? How memory is implemented and how to retrieve and modify relevant code in agent loop? [AI 生成问答及所附源码、文档节选]. DeepWiki. 原问答链接。本地学习笔记
cline.md保存于 2025 年 8 月 27 日:文件创建时间 14:11:38,最后修改时间 14:38:19(北京时间)。问题引文分别位于首问、关于 diff/patch 的追问、关于精确匹配失败率的追问;源码注释引文位于 Cline contributors 的src/core/task/index.ts/initiateTaskLoop节选;Memory Bank 引文位于docs/prompting/cline-memory-bank.mdx/“Memory Bank Structure”。编辑机制依据所附src/core/assistant-message/diff.ts、src/core/prompts/system.ts;评测边界依据evals/diff-edits/README.md/“What We're Trying to Figure Out”。另见第 3、5、6 问的定位、提示词与读写工具节选。笔记未记录上游 commit。文中另引的 Cline 和 Gemini CLI 固定链接取自打开问答前已存在的 8 月 13 日提交,用于核对当日实现。 ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 -
DeepWiki. (n.d.). How agent loop works in Gemini CLI? How memory is implemented and how to retrieve and modify relevant code in agent loop? [AI 生成问答及所附源码、文档节选]. DeepWiki. 原问答链接。本地学习笔记
geminicli.md保存于 2025 年 8 月 27 日:文件创建时间 14:38:42,最后修改时间 14:47:30(北京时间)。循环、调度与 prompt 讨论依据 Google Gemini CLI contributors 的packages/core/src/core/client.ts、useGeminiStream、loadHierarchicalGeminiMemory和packages/core/src/core/prompts.ts保存节选;直接引文位于docs/cli/configuration.md/“Context Files (Hierarchical Instructional Context)”/“Purpose”。文件参数与预览见第 3 问所附docs/tools/file-system.md。 ↩ ↩2 ↩3 ↩4 ↩5 -
Cai, B. (2025, August 21–25). Open-vibe-coder 与 open-vibe-coder-js 开发对话 [私人对话记录]. Cursor,本地保存。Python 会话标题为 “Execute Sprint 0 plan and seek advice”,创建于 8 月 21 日 17:17,最后更新于 18:41;JS 会话创建于 8 月 22 日 18:18,最后更新于 8 月 25 日 16:15。均为北京时间。引文已与用户消息核对;这些是会话级时间,单条消息没有独立时间戳,故不将具体一句话强行定到某一天。8 月 25 日的 Git 提交另见注 5。 ↩ ↩2 ↩3 ↩4
-
Cline contributors. (2025, August 13). System prompt: Act and Plan modes [源代码]. GitHub. 两种模式与可用工具。 ↩
-
Cai, B. (2025, August 13–21). 编程助手模块与 Sprint 0 设计 [私人对话]. ChatGPT。直接引文见最后一次修订请求,此前依次讨论了模块清单、实现顺序、可交付的计划和 MCP 兼容性。 ↩ ↩2 ↩3 ↩4 ↩5 ↩6
-
OpenAI. (n.d.). Text generation [API documentation]. OpenAI Developers. 文档链接. Retrieved November 17, 2026. 直接引文位于首个响应
output示例后的说明段;instructions的延续范围见 “Message roles and instruction following”。这三篇 OpenAI 文档由我在本次整理中补充确认。随后提供的client.chat.completions.create tools检索路径,与 PromptPulse 的工具接入更直接对应;本文将其作为跨项目参考,不据此认定首次访问发生在八月。具体字段与引文核对的是本次访问内容,不将现有页面的模型名称、示例或全部功能回填为 2025 年 8 月的版本。 ↩ ↩2 ↩3 ↩4 -
OpenAI. (n.d.). Function calling [API documentation, Responses API mode]. OpenAI Developers. 文档链接. Retrieved November 17, 2026. 直接引文位于 “The tool calling flow” 第 3 步;调用与结果关联见 “Function tool example” 和 “Handling function calls”;参数分片与完成事件见 “Streaming”。历史查阅与本次页面核对的区别同注 6。 ↩ ↩2 ↩3 ↩4 ↩5
-
OpenAI. (n.d.). Streaming API responses [API documentation, Responses API mode]. OpenAI Developers. 文档链接. Retrieved November 17, 2026. 直接引文位于 “Enable streaming” 中关于语义事件的说明;事件分类另见 “Read the responses”。历史查阅与本次页面核对的区别同注 6。 ↩ ↩2 ↩3
-
Google Gemini CLI contributors. (2025, August 13). Turn and useGeminiStream [源代码]. GitHub. 文本与函数调用的分流、构造工具请求、界面收集与调度。 ↩ ↩2
-
Google Gemini CLI contributors. (2025, August 13). GeminiClient.sendMessageStream [源代码]. GitHub. 转发事件、检查待处理工具与决定下一轮。 ↩ ↩2
-
Cline contributors. (2025, August 13). Task history and resumption [源代码]. GitHub. 按任务保存的文件、恢复界面、对话并询问、合并末条消息、回到任务循环。 ↩ ↩2 ↩3
-
Chiang, E. (2025, July 30). 我的 Anthropic Claude Code 學習筆記. Ernest Chiang. 「管理 Claude 場景與記憶」中的项目与个人文件示例,以及「SDLC 軟體開發工作流程」中的团队辅导观察。 ↩
-
Google Gemini CLI contributors. (2025, August 13). Search tools and system instructions [源代码]. GitHub. 搜索参数与命中结构、搜索后验证、拼接项目说明。 ↩ ↩2
-
Cline contributors. (2025, August 13). Search and code definitions [源代码]. GitHub. 搜索工具参数、提取定义、执行文本搜索。 ↩ ↩2
-
Chiang, E. (2025, July 30). 我的 Anthropic Claude Code 學習筆記. Ernest Chiang. 「說出心裡話」,关于列出几种理解与缩小问题范围的建议。 ↩
-
Cline contributors. (2025, August 13). System prompts and diff editing [源代码]. GitHub. 模板选择、修改块规则、匹配及回退、成功和失败的反馈。 ↩ ↩2
-
Cline contributors. (2025, August 13). Diff edits evaluation [评测说明]. GitHub. 记录修改块的应用结果与有效尝试的取样条件。 ↩
-
Google Gemini CLI contributors. (2025, August 13). File tools and confirmation scheduling [源代码]. GitHub. 分段读取、局部替换参数、写入预览、取消或安排执行、校验与写盘。 ↩ ↩2 ↩3 ↩4
-
Cline contributors. (2025, August 13). File edit confirmation and saving [源代码]. GitHub. 构造候选文本、撤回或保存、保存文档、VS Code 保存入口。 ↩
-
Google Gemini CLI contributors. (2025, August 13). Shell tool and execution service [源代码]. GitHub. 确认命令、提交命令和工作目录、启动子进程。 ↩
-
Cline contributors. (2025, August 13). VscodeWebviewProvider [源代码]. GitHub. 侧栏就绪时监听消息、处理界面请求。 ↩
-
Cai, B. (2025, August). Open-vibe-coder:Sprint 0 工具框架计划与原型 [私人项目资料,含 AI 辅助生成内容]. 本地保存。计划引文位于
sprint-0.md/“Design rule”;实现核对文件为src/agent/tool_registry.py、rules.py、tool_executor.py、main.py、tools_builtin.py及src/adapters/mcp/bridge.py。开发背景由 8 月 21 日 Cursor 对话支持;当前目录没有可用 Git 历史,保存文件的具体修订不逐一赋予提交日期。2026-12-04 用现存原型核对了 CLI 和 MCP 适配层对同一条消息的成功返回,以及调用来源被拒绝时跳过工具的分支。 ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 -
Google Gemini CLI contributors. (n.d.). Gemini CLI packages [代码仓库]. GitHub. 仓库入口、子包目录、CLI 包清单、core 包清单、core 的 TypeScript 配置。Cline contributors. (n.d.). Cline extension manifest [代码仓库]. GitHub. 扩展的包清单。链接保留 2025 年 8 月 22 日打开的 main 分支地址,分支内容会更新。 ↩
-
Cai, B. (n.d.). TypeScript 终端界面与文件读写原型 [私人对话]. ChatGPT。单功能迭代要求见以 “change pf plan” 开头的用户消息。 ↩
-
Cai, B. (2025, August). Open-vibe-coder-js:文件操作 CLI 计划与原型 [私人项目资料,含 AI 辅助生成内容]. 本地 Git 与工作区。初始提交
03bd8c1,提交说明 “feat: :fire: start a new project”,作者时间为 2025 年 8 月 25 日 15:45:17 +0800。计划引文位于sprint-0.md/“Feature Definition”;类型与实现核对文件为packages/core/src/types.ts、patch.ts、filestore.ts、diff.ts、workspace.ts和packages/cli/src/hooks/useCommands.ts、index.tsx。另据 08-26 17:32:46 暂存快照92b0527的packages/cli/src/index.tsx第 34–42、44–78 行核对入口和占位预览;核心模块另据本地工作区。私人对话与项目资料不附公开访问链接。 ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 -
npm. (n.d.). npm install [CLI v10 documentation]. npm Docs.
workspace:选择执行命令的工作区、Algorithm:依赖的复用与嵌套。 ↩