thincoder 0.12.80 → 0.12.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +115 -74
- package/README.md +90 -39
- package/package.json +2 -2
- package/src/acp/bridge.mjs +19 -61
- package/src/acp/buffered-edit.mjs +217 -0
- package/src/acp/handlers-session.mjs +34 -3
- package/src/acp/handlers-slots.mjs +8 -7
- package/src/acp/read-data.mjs +4 -4
- package/src/acp/resource-link.mjs +1 -1
- package/src/cli/make-agent.mjs +3 -3
- package/src/command-interactive.mjs +3 -1
- package/src/tui/agent-turn.mjs +14 -3
- package/src/tui/cmd-advisor.mjs +1 -1
- package/src/tui/cmd-config.mjs +27 -4
- package/src/tui/cmd-eng.mjs +49 -84
- package/src/tui/cmd-mcp.mjs +1 -1
- package/src/tui/cmd-new.mjs +7 -1
- package/src/tui/cmd-session.mjs +2 -2
- package/src/tui/cmd-timers.mjs +2 -2
- package/src/tui/index.mjs +31 -2
- package/src/tui/lifecycle-records.mjs +12 -1
- package/src/tui/model-picker.mjs +27 -37
- package/src/tui/provider-admin.mjs +3 -2
- package/src/tui/provider-entries.mjs +92 -0
- package/src/tui/render-loop.mjs +30 -4
- package/src/tui/slash-commands.mjs +6 -2
- package/src/tui/status-line.mjs +22 -11
- package/src/tui/timer-watch.mjs +61 -0
- package/src/tui/tui-state.mjs +1 -1
package/README.md
CHANGED
|
@@ -4,12 +4,13 @@
|
|
|
4
4
|
|
|
5
5
|
**A "thin" AI coding agent: pure `.mjs`, no build step, zero third-party dependencies, native Node.js.**
|
|
6
6
|
|
|
7
|
-
The "Thin" in ThinCoder doesn't mean "feature-poor"
|
|
8
|
-
While every AI agent races to be "all-powerful", ThinCoder plays the opposite card: **restraint, precision, no filler**.
|
|
9
|
-
Its persona is a geek engineer of few words who cuts to the bone: give it a complex requirement, get back a clean implementation.
|
|
7
|
+
The "Thin" in ThinCoder doesn't mean "feature-poor". It means **sharp thinking, straight to the point** — like a blade.
|
|
10
8
|
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
While every AI agent races to be "all-powerful", ThinCoder plays the opposite card: **restraint, precision, no filler**. Its persona is a geek engineer of few words who cuts to the bone — give it a complex requirement, get back a clean implementation.
|
|
10
|
+
|
|
11
|
+
Design philosophy (the entire meaning of the name): if the Node standard library can do it, no third-party dependency is allowed.
|
|
12
|
+
|
|
13
|
+
So `node_modules` holds no third-party packages — only the first-party `@thincoder/core` shared core, a local link in development and resolved from the npm registry for releases.
|
|
13
14
|
|
|
14
15
|
## Features
|
|
15
16
|
|
|
@@ -17,18 +18,26 @@ resolved from the npm registry for releases).
|
|
|
17
18
|
- **Checkpoint system**: auto-snapshot before every user task, `list`/`create`/`rewind` tools for the model, single-file restore — rewinding itself is reversible (pre-rewind state auto-saved)
|
|
18
19
|
- **Codebase understanding** ⭐0.5.0: `repo_outline` (dependency outline, auto-injected at startup), `code_search` (source FTS5 + vectors + JSDoc extraction), `doc_search` (docs chunked by ## headings) — background indexing, auto-incremental updates on file writes, three tools
|
|
19
20
|
guided by "structure → intent → details"
|
|
20
|
-
- **Model adaptation** ⭐: top-tier only, latest only. Built-in flagship models from twenty-five providers — DeepSeek / Kimi / Kimi For Coding / GLM / GLM Coding Plan (智谱 Coding) / Qwen / Qwen Token Plan / MiMo (小米) / MiMo Token Plan (小米套餐) / MiniMax / OpenAI / Claude / Gemini / Gemini (OpenAI-compatible — same key)
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
- **Model adaptation** ⭐: top-tier only, latest only. Built-in flagship models from twenty-five providers — DeepSeek / Kimi / Kimi For Coding / GLM / GLM Coding Plan (智谱 Coding) / Qwen / Qwen Token Plan / MiMo (小米) / MiMo Token Plan (小米套餐) / MiniMax / OpenAI / Claude / Gemini / Gemini (OpenAI-compatible — same key).
|
|
22
|
+
|
|
23
|
+
Further presets: Grok / Mistral / Volcengine Ark (豆包) / Hunyuan (腾讯混元) / Tencent TokenHub (腾讯混元网关) / Huawei Cloud MaaS (华为云 MaaS) / SiliconFlow (硅基流动) / OpenRouter / Groq / OpenCode Go (same key for both protocol sides: OpenAI-compatible + Anthropic Messages).
|
|
24
|
+
|
|
25
|
+
No legacy model compatibility. Context windows are auto-matched.
|
|
26
|
+
|
|
27
|
+
The same deep adaptation covers truncation-resume protocols (prefix/partial), thinking-mode APIs (thinking.type / reasoning_effort), reasoning_content echo strategies (reasoningEcho), output limits and temperature range clamping.
|
|
23
28
|
- **Toolset**: `read` / `write` / `edit` / `bash` / `glob` (supports `**`) / `grep` / `websearch` / `ls` / `fetch` + `read_image` (image/video paste) + three retrieval tools + MCP — all zero-dependency, file tools confined to the working directory
|
|
24
29
|
- **Memory system**: three layers (personal/project/team), FTS5 + vector RRF hybrid retrieval, git-friendly markdown format
|
|
25
30
|
- **Two-phase tool scheduling**: permission prompts serialized, read-only tools parallelized, side-effect tools serialized
|
|
26
31
|
- **Session persistence** ⭐0.5.0: unlimited archive slots, `/session` to switch anytime, tool results visible after restore. Process-level isolation — multiple instances in the same directory each get their own session slot
|
|
27
32
|
- **Concurrent subagents**: five roles — `explore`/`plan`/`coder`/`eng-coder`/`eng-designer` — dispatched in parallel, streaming output visible, reports land in the conversation; per-subagent model override (`subagent` tool `model` arg or `agent.subagentModel` config — e.g.
|
|
28
33
|
discuss with `glm-5.2`, let `deepseek-v4-flash` implement)
|
|
29
|
-
- **Multi-model consultation 会诊 + 飞刀 (escalate)** ⭐0.12.30: `consult_start`/`consult_stop` run several configured models in parallel as independent read-only consultants (each with its own TUI activity card, `main_history` access to the failure trail); when every model settles
|
|
30
|
-
|
|
31
|
-
|
|
34
|
+
- **Multi-model consultation 会诊 + 飞刀 (escalate)** ⭐0.12.30: `consult_start`/`consult_stop` run several configured models in parallel as independent read-only consultants (each with its own TUI activity card, `main_history` access to the failure trail); when every model settles.
|
|
35
|
+
|
|
36
|
+
The full verdict digest is then delivered automatically (R17 — consult_check retired).
|
|
37
|
+
|
|
38
|
+
`escalate` flies in a stronger model for a single expert implementation run with full write access. It is default-async since R17, so the post-op report arrives automatically with its mutations merged.
|
|
39
|
+
|
|
40
|
+
Candidate pool = `agent.consultModels` ([{ provider, model, effort? }], up to 5); budgets via `agent.consultTurns` / `agent.consultTimeoutMs`.
|
|
32
41
|
- **Plan Mode**: read-only exploration + design, implement after user approval
|
|
33
42
|
- **AUTO mode**: `/auto` full authorization, no confirmations on long tasks
|
|
34
43
|
- **Task tracking**: `task` tool breaks down multi-step work, status bar ✓n/m live progress, auto-filters completed items
|
|
@@ -77,10 +86,15 @@ npm install -g thincoder
|
|
|
77
86
|
thincoder
|
|
78
87
|
```
|
|
79
88
|
|
|
80
|
-
First launch walks you through a setup wizard: arrow keys to pick a provider (built-in presets or a custom endpoint) → enter API key → optionally enter an embedding key (SiliconFlow, enables vector memory search, skippable) → arrow keys to pick a model
|
|
81
|
-
files. Adjust anytime with `/model` (add/remove providers, set keys, custom endpoints) or `/config embedkey`. `chat`/`distill` also offer in-place interactive setup when no key is configured in a terminal (in pipes/CI they exit with an error and instructions).
|
|
89
|
+
First launch walks you through a setup wizard: arrow keys to pick a provider (built-in presets or a custom endpoint) → enter API key → optionally enter an embedding key (SiliconFlow, enables vector memory search, skippable) → arrow keys to pick a model.
|
|
82
90
|
|
|
83
|
-
|
|
91
|
+
Nothing is hand-edited in config files. Adjust any of it later with `/model` (add/remove providers, set keys, custom endpoints) or `/config embedkey`.
|
|
92
|
+
|
|
93
|
+
`chat`/`distill` also offer in-place interactive setup when no key is configured in a terminal; in pipes/CI they exit with an error and instructions.
|
|
94
|
+
|
|
95
|
+
Any OpenAI-compatible endpoint works without a built-in preset: pick **add provider → custom** in `/model` (name + baseURL + model), or hand-write the entry in `providers[]`.
|
|
96
|
+
|
|
97
|
+
Regional endpoint variants work the same way — Huawei Cloud MaaS, for example, is `https://api-ap-southeast-1.modelarts-maas.com/openai/v1`.
|
|
84
98
|
|
|
85
99
|
You can also hand-write `~/.thincoder/config.json` (see "Configuration" below), then:
|
|
86
100
|
|
|
@@ -107,14 +121,23 @@ thincoder upgrade
|
|
|
107
121
|
|
|
108
122
|
Running from source: replace `thincoder` above with `node bin/thincoder.mjs`.
|
|
109
123
|
|
|
110
|
-
Slash commands in the TUI
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
124
|
+
Slash commands in the TUI cover the whole loop. `/help` prints help, and `/model` opens a two-level picker (provider first, then model) that also adds or removes providers, sets keys and edits custom endpoints; `/model <provider>:<name>` switches directly.
|
|
125
|
+
|
|
126
|
+
Subagents get the same treatment. `/submodel` picks their models per type, from global plus the explore/plan/coder/eng-coder/eng-designer slots, or takes `/submodel <type> <provider:model>` directly.
|
|
127
|
+
|
|
128
|
+
`/shell` opens a platform-aware picker over the available shells — pick Git Bash/pwsh, or pass `/shell "C:\Program Files\Git\bin\bash.exe"`, or `/shell reset`. It also fixes win11 cmd encoding/command issues.
|
|
129
|
+
|
|
130
|
+
`/think` toggles thinking mode and reasoning effort. `/config` views configuration, and with no argument opens the interactive menu (default model, embedding key, proxy), while `/config embedkey` sets the embedding key directly.
|
|
131
|
+
|
|
132
|
+
`/session` lists and switches archived sessions; `/reindex` rebuilds the index; `/extract` pulls knowledge from the current session; `/restore` restores a checkpoint; `/clear` and `/exit` do what they say.
|
|
133
|
+
|
|
134
|
+
High-frequency commands support abbreviations: `/h` `/x` `/m` `/p` `/t` `/c` `/n`. Typing `/` shows live matching hints in the status bar, and the model picker supports search/filter — type to narrow down results.
|
|
115
135
|
|
|
116
|
-
Configuration comes exclusively from `~/.thincoder/config.json` — the single source of truth.
|
|
117
|
-
|
|
136
|
+
Configuration comes exclusively from `~/.thincoder/config.json` — the single source of truth.
|
|
137
|
+
|
|
138
|
+
Sensitive value fields — a provider's `apiKey` or `websearch.apiKey`, for instance — may hold a `${env:VAR}` reference, resolved at use time, when the value is taken from the environment variable.
|
|
139
|
+
|
|
140
|
+
There is no environment-variable-only configuration channel and no env-only override.
|
|
118
141
|
|
|
119
142
|
> **Kimi note**: Kimi has **two separate platforms with non-interchangeable API keys** — Moonshot (`https://api.moonshot.cn/v1`, keys `sk-...`, platform.moonshot.cn) and **Kimi For Coding** (`https://api.kimi.com/coding/v1`, keys `sk-kimi-...`, platform.kimi.com, model ID `k3`).
|
|
120
143
|
> Use the `kimi` preset for Moonshot and `kimi-code` for Kimi For Coding — putting one platform's key on the other's endpoint fails with 401 (a hint is appended when the key/baseURL look mismatched).
|
|
@@ -204,7 +227,7 @@ src/
|
|
|
204
227
|
tui.mjs re-export shim → src/tui/index.mjs
|
|
205
228
|
upgrade.mjs version check and self-upgrade
|
|
206
229
|
test/ suite entry (npm test) — integration set; unit tests = batch-local files (docs/batches/) — current state: ../docs/core/design/TESTING.md §2.3
|
|
207
|
-
scripts/ repo-side scripts — release check,
|
|
230
|
+
scripts/ repo-side scripts — release check, syntax/endpoint probes,
|
|
208
231
|
real-environment verification (compaction, team sync)
|
|
209
232
|
```
|
|
210
233
|
|
|
@@ -233,6 +256,26 @@ Code conventions: pure `.mjs`, no semicolons, no third-party npm dependencies al
|
|
|
233
256
|
|
|
234
257
|
## Changelog
|
|
235
258
|
|
|
259
|
+
### 0.12.81 (2026-11)
|
|
260
|
+
- **Core `^0.11.1`** — ssh file transfer (`put` / `get`, single file, classic SCP by default); the write gate now reaches `ssh` (`get` only); task-book action tables carry a reason column; SSE first-chunk / mid-stream split; ledger contract unified on one sentence.
|
|
261
|
+
- `ledger/count`: the boundary follows the caller `cwd` (cross-project read face).
|
|
262
|
+
- Turn-cap card reports both the segment and the cumulative count; the stale `(limit)` line is gone.
|
|
263
|
+
|
|
264
|
+
### 0.12.80 (2026-10)
|
|
265
|
+
- **Core `^0.10.13`** — model requests carry a product identity header (`ThinCoder/<surface>/<version>`).
|
|
266
|
+
|
|
267
|
+
### 0.12.79 (2026-10)
|
|
268
|
+
- **Core `^0.10.12`** — ledger root errors are surfaced instead of silently returning an empty set; batch creation names the project under multi-root workspaces.
|
|
269
|
+
|
|
270
|
+
### 0.12.78 (2026-10)
|
|
271
|
+
- `modelContext` duplicate keys no longer error — two spellings that normalise to the same model are treated as one entry.
|
|
272
|
+
|
|
273
|
+
### 0.12.77 (2026-10)
|
|
274
|
+
- **Core `^0.10.10`** — prompt face rewritten (one rule per line), new "check the docs before acting" section; subagents gain the read-only `manifest` face.
|
|
275
|
+
|
|
276
|
+
### 0.12.76 (2026-10)
|
|
277
|
+
- Network tools reuse the DeepSeek key from `providers[]` (`websearch` / `fetch`), zero new config.
|
|
278
|
+
|
|
236
279
|
### 0.12.75 (2026-10)
|
|
237
280
|
- **Core `^0.10.8`** — builtin `doc_check` (document-discipline machine check as a product tool: anchors + line width, report-only) and ledger root derivation (single read/write criterion) ride in with the core.
|
|
238
281
|
- Prompt-face corrections: Chinese = design docs / English = code split landed; runtime face doc-reference removal; online-verification guidance; S1/S2 tuning.
|
|
@@ -324,10 +367,10 @@ Chinese output on win11.
|
|
|
324
367
|
|
|
325
368
|
### 0.12.9 (2026-08)
|
|
326
369
|
- **Prompt-system quality pass (both CLI and VS Code extension, byte-identical sync):**
|
|
327
|
-
- **Advisor-after-code rule moved from system
|
|
328
|
-
-
|
|
370
|
+
- **Advisor-after-code rule moved from the `system` prompt to the `discipline` prompt** — engineering mode no longer receives the conflicting "call advisor after changing code" instruction (its review-timing rules say do not call unprompted). Standard mode behavior unchanged.
|
|
371
|
+
- **`engineering` prompt delivery-review semantics unified** — the mandatory-flow step and the state table now both say: eng-coder self-reviews inside the subagent; the architect verifies against acceptance criteria and re-reviews only when asked or when the delivery looks wrong.
|
|
329
372
|
(Previously the step forced a parent-side advisor code review that the hard rules contradicted.)
|
|
330
|
-
- **checkpoint description aligned with actual auto-snapshot triggers
|
|
373
|
+
- **checkpoint description aligned with actual auto-snapshot triggers**.
|
|
331
374
|
- **advisor round budget wording fixed** — prompts advertise a 30-round budget; the mechanical hard cap is 100 rounds (loop guard). Both layers are now named explicitly.
|
|
332
375
|
|
|
333
376
|
### 0.12.8 (2026-08)
|
|
@@ -340,9 +383,11 @@ only; expanded blocks are exempt from the consecutive-dim folding so nothing fol
|
|
|
340
383
|
- **Fix: wide tables misaligned in narrow terminals** — a many-column table that still exceeded the terminal width after column shrinking (e.g. 8 columns at 40 cols) wrapped at the terminal and misaligned. Table rows are now clipped with an ellipsis instead of ever exceeding the width.
|
|
341
384
|
|
|
342
385
|
### 0.12.6 (2026-08)
|
|
343
|
-
- **Checkpoint v2 — full-file-copy snapshots** — snapshots now store complete copies of changed files (tracked + untracked) instead of a git diff patch: rollback works even after commits happened post-snapshot. New `versions` checkpoint action lists a file's historical copies
|
|
344
|
-
|
|
345
|
-
|
|
386
|
+
- **Checkpoint v2 — full-file-copy snapshots** — snapshots now store complete copies of changed files (tracked + untracked) instead of a git diff patch: rollback works even after commits happened post-snapshot. New `versions` checkpoint action lists a file's historical copies.
|
|
387
|
+
|
|
388
|
+
That listing spans snapshots by time, size or content hash, and a specific version can be restored from it.
|
|
389
|
+
|
|
390
|
+
**Full rollback is disabled** — as dangerous as a working-tree reset, since it silently discards post-snapshot work. Oversized files (>5MB) are skipped with an explicit notice, and files created after a snapshot are never deleted by a restore.
|
|
346
391
|
- **Git destructive-command protection** — `checkout --` / `restore` / `reset --hard` / `clean -f` (including bypass variants like `checkout HEAD -- .`) auto-snapshot every uncommitted file **before** running, then execute without blocking — a model rollback can no longer destroy
|
|
347
392
|
uncommitted work. Snapshot triggers slimmed to: destructive-git guard, pre-restore, manual.
|
|
348
393
|
- **Fix: bash no longer hangs on background processes** — `start /b`, `&`, `nohup` children that hold the output pipe no longer stall the tool until timeout (resolves after a short grace with a notice).
|
|
@@ -354,9 +399,13 @@ with click-to-expand — folding now has real objects in everyday sessions.
|
|
|
354
399
|
- **Fix: inline code styling** — markdown code spans now render with underline instead of reverse video (less harsh on the eyes)
|
|
355
400
|
|
|
356
401
|
### 0.12.4 (2026-08)
|
|
357
|
-
- **Context compaction unified spec** — CLI/VS Code now share one compaction semantics (`docs/design/CONTEXT-COMPACTION.md`): window-adaptive tail size (`max(10, ctx/100K×30)`, ≤40% of history), measured prompt-token baseline preferred, pure-estimation path includes system+tools
|
|
358
|
-
|
|
359
|
-
|
|
402
|
+
- **Context compaction unified spec** — CLI/VS Code now share one compaction semantics (`docs/core/design/CONTEXT-COMPACTION.md`): window-adaptive tail size (`max(10, ctx/100K×30)`, ≤40% of history), measured prompt-token baseline preferred, pure-estimation path includes system+tools overhead.
|
|
403
|
+
|
|
404
|
+
Head/tail tool-call pairing is protected on both sides, and the fallback runs in 3 tiers: LLM summary → deterministic truncation after 3 failures → per-message shrink.
|
|
405
|
+
|
|
406
|
+
Compaction summaries stay silent to the frontend — nothing streams into the conversation — and task re-injection is deduplicated.
|
|
407
|
+
|
|
408
|
+
Unknown model names now warn once instead of silently degrading to the 128K default.
|
|
360
409
|
- **Kimi For Coding support** — new `kimi-code` preset (`api.kimi.com/coding/v1`, model `k3`, platform.kimi.com, `sk-kimi-` keys — NOT interchangeable with Moonshot); `MODEL_SPECS` gains the `k3` alias (1M context / multimodal / partialMode / reasoningEcho); 401 errors hint at
|
|
361
410
|
the two-platform key mismatch; README documents the split
|
|
362
411
|
- **Ctrl+C double-confirm** — idle-state first Ctrl+C only warns (3s window), second press exits; picker-cancel and in-flight abort semantics unchanged
|
|
@@ -385,7 +434,7 @@ intelligently reclaimed via `isProcessAlive()` check
|
|
|
385
434
|
- **Interactive slash command UX** — `/advisor`, `/think`, `/config`, `/mcp` now use persistent menu loops with live state feedback. Toggle, change settings, and see results without re-entering the command. Cursor position is remembered across menu cycles. `/plan` and `/auto` now
|
|
386
435
|
show immediate local feedback (`❯ Plan: ON/OFF`).
|
|
387
436
|
- **User-level AGENTS.md** — `~/.thincoder/AGENTS.md` is now loaded alongside the project-level `AGENTS.md`. User-level preferences (language, style, format) apply across all projects; project-level rules take priority.
|
|
388
|
-
- **Skill subdirectory format** — `.thincoder/skills/` now supports the standard `
|
|
437
|
+
- **Skill subdirectory format** — `.thincoder/skills/` now supports the standard one-directory-per-skill convention: each skill sits in its own directory holding a `SKILL.md` (Claude Code / Cursor compatible). Flat `.md` files remain fully backward-compatible. Subdirectories take priority when both formats exist with the same name.
|
|
389
438
|
- **MCP stdio `env` field** — `env` key in MCP stdio server config is now merged into the child process environment. Enables MCP servers requiring custom environment variables (e.g. `deveco-mcp`).
|
|
390
439
|
- **Project-level `.mcp.json`** — `.mcp.json` in the project root is auto-loaded at startup (standard MCP client convention). Servers defined here are merged with `config.json` servers — `config.json` takes priority for same-named entries.
|
|
391
440
|
- **Cleaner conversations** — Removed redundant `[System reminder: ...]` injections from `/advisor`, `/plan`, `/auto`, and `/think` toggles. All feedback is now local TUI output, not conversation noise.
|
|
@@ -403,7 +452,7 @@ limits output to 50KB, enforces 30s timeout, and blocks private IPs in fetch. Sc
|
|
|
403
452
|
- **Lifecycle Hooks** — `PreToolUse` / `PostToolUse` / `PostToolUseFailure` / `Stop` events. User-defined shell commands in config, with per-tool regex matching, timeout control, and `block`/`allow`/`notify` actions. Implemented in `thincoder-core/hooks.mjs`, integrated into tool dispatch.
|
|
404
453
|
- **Built-in Skills (5)** — `pdf-create`, `xlsx-create`, `frontend-design`, `code-review`, `api-design` ship with the installation. Each is a standalone markdown instruction file using zero-dependency approaches (Chrome headless for PDF, PowerShell for Excel, etc.).
|
|
405
454
|
- **Conversation message folding** — Long tool result blocks (>8 consecutive dim lines) auto-collapse to first 2 lines + "… N more lines — Enter to expand". `/fold on|off` toggles globally.
|
|
406
|
-
- **Tree-shaped tasks** — `checklist` tool now supports hierarchical task IDs (`T1`, `T1.1`, `T1.2.1`) with auto-assigned numbering. `add` accepts `parent` parameter for subtree positioning. Indentation-based persistence in
|
|
455
|
+
- **Tree-shaped tasks** — `checklist` tool now supports hierarchical task IDs (`T1`, `T1.1`, `T1.2.1`) with auto-assigned numbering. `add` accepts `parent` parameter for subtree positioning. Indentation-based persistence in the checklist file.
|
|
407
456
|
- **AI-native MCP config** — `/mcp add` picker now includes "Describe with AI" option. Describe a server in natural language → model generates config JSON → preview + confirm → save and connect.
|
|
408
457
|
- **Goal judge model** — `goal complete` now runs an independent LLM check: goal criteria + recent agent activity → judge model verifies YES/NO. Prevents false completion claims during autonomous work.
|
|
409
458
|
- **`/undo` command** — Tracks up to 50 write/edit/delete operations in `agent._undoStack`. `/undo` opens a picker showing each operation's file and original content size. Select to revert.
|
|
@@ -437,17 +486,19 @@ extensions, Office add-ins, Program Files)
|
|
|
437
486
|
- **Refactor: `embed-config.mjs`** — simplified to only read API key via `resolveEmbedKey()`, base URL and model are fixed constants; VSCode SecretStorage dependency removed
|
|
438
487
|
|
|
439
488
|
### 0.8.11 (2026-07)
|
|
440
|
-
- **Feat**: `checklist` tool — persistent project task tracking in `.thincoder
|
|
489
|
+
- **Feat**: `checklist` tool — persistent project task tracking in a checklist file under `.thincoder/`. Add/mark/list items, auto-archive done items to a separate done file. Injected at session start (pending + in_progress only)
|
|
441
490
|
- **Feat**: updated prompts — four-step workflow (requirements→design→development→testing), three-step debugging strategy (logs→docs→binary search), working checklist discipline
|
|
442
|
-
- **Feat**: methodology docs — `
|
|
491
|
+
- **Feat**: methodology docs — `METHODOLOGY.md` rebuilt, `PHILOSOPHY.md` expanded with worldview #6 (official docs over guessing)
|
|
443
492
|
- **Bugfix**: vision guard — `read_image` now refuses non-vision models before reading the file, the agent loop injects a system reminder instead of image parts for text-only models, and `stripImagesForTextModel` sanitizes image parts at send time (history untouched, restored
|
|
444
493
|
when switching back to a vision model). Previously a single image in history made text-only APIs (e.g. DeepSeek) reject EVERY subsequent request with 400, bricking the conversation
|
|
445
494
|
- **Improvement**: silent `catch {}` blocks now log to stderr (checkpoint file copies, MCP notify/close, session incremental save, clipboard paste, provider picker, team-memory rebase abort, tool dispatch) — failures are visible for debugging instead of disappearing
|
|
446
495
|
|
|
447
496
|
### 0.8.10 (2026-07)
|
|
448
|
-
- **Bugfix**: pasted text now lands in the active TUI text target — the API key prompt when adding a provider via `/model` (and any free-text `askQuestion`) now accepts paste correctly. Previously, bracketed-paste injection in the terminal was always written to the main input
|
|
449
|
-
|
|
450
|
-
|
|
497
|
+
- **Bugfix**: pasted text now lands in the active TUI text target — the API key prompt when adding a provider via `/model` (and any free-text `askQuestion`) now accepts paste correctly. Previously, bracketed-paste injection in the terminal was always written to the main input box.
|
|
498
|
+
|
|
499
|
+
Pasting into a question prompt therefore appeared as "nothing happened", and the text was orphaned into the input box after the question closed.
|
|
500
|
+
|
|
501
|
+
Both bracketed-paste (Windows Terminal / most modern terminals) and Ctrl+V-as-key-event (legacy conhost) now route through a single `insertPastedText` helper. It targets the question answer, the options-list (ignored), or the main input box as appropriate.
|
|
451
502
|
|
|
452
503
|
### 0.8.9 (2026-07)
|
|
453
504
|
- **Bugfix**: `wizardProviderItems` was defined inside `createWizard()` but not included in the return statement, causing key-handler to crash with `TypeError` during provider selection on first launch (/ new config)
|
|
@@ -458,7 +509,7 @@ box, so pasting into a question prompt appeared as "nothing happened" and orphan
|
|
|
458
509
|
- **Feat**: auto update check on startup + `/upgrade` command
|
|
459
510
|
|
|
460
511
|
### 0.8.3 (2026-07)
|
|
461
|
-
- **Output panels**: tools with `outputPanel` flag stream to scrolled panel, auto-collapse to summary on completion (bash, long tool results)(机制已于 2026-08-30 废除——D6 清理,见 AGENT-LOOP.md)
|
|
512
|
+
- **Output panels**: tools with `outputPanel` flag stream to scrolled panel, auto-collapse to summary on completion (bash, long tool results)(机制已于 2026-08-30 废除——D6 清理,见 docs/core/design/AGENT-LOOP.md)
|
|
462
513
|
- **Checkpoint enhancements**: `cat` for file preview from snapshots, per-file rewind, auto-recover on apply failure, escape-hatch hints on errors
|
|
463
514
|
- **Bash safety**: `checkpoint-before-destructive` discipline rule; bash guard guides checkpoint instead of just commit/stash
|
|
464
515
|
- **Code review fixes**: output friendliness, readability, English-only strings, TUI polish
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "thincoder",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.82",
|
|
4
4
|
"description": "Thin coding agent - zero third-party dependencies, no build step, Node.js native. Sharp code, zero bloat.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"node": ">=24"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@thincoder/core": "^0.
|
|
23
|
+
"@thincoder/core": "^0.11.2"
|
|
24
24
|
},
|
|
25
25
|
"files": [
|
|
26
26
|
"bin/",
|
package/src/acp/bridge.mjs
CHANGED
|
@@ -23,8 +23,14 @@
|
|
|
23
23
|
* End-of-turn is NOT a notification: `session/prompt` resolves with
|
|
24
24
|
* `{ stopReason: "end_turn" }` (kimi session.ts parity).
|
|
25
25
|
*/
|
|
26
|
-
import { detectDanger
|
|
27
|
-
import {
|
|
26
|
+
import { detectDanger } from "@thincoder/core/tools/shared.mjs"
|
|
27
|
+
import { hasLineParams } from "@thincoder/core/tools/edit-diff.mjs"
|
|
28
|
+
// 行号锚护栏(EDIT-HELPERS §3):桥不经 writeThroughPath ⇒ 判据与记账都得在桥面接(§4)。
|
|
29
|
+
// 判据 / 拒文 = 核单源(住 `buffered-edit.mjs`);记账 = 写缓冲成功后 recordWrite,键 = resolveInCwd 后的绝对路径。
|
|
30
|
+
import { recordWrite } from "@thincoder/core/tools/write-path.mjs"
|
|
31
|
+
// IDE 缓冲编辑面(2026-11-05 拆档族):`absOf` ∥ `editSingle` ∥ `editBatch` 三件住同目录兄弟档,
|
|
32
|
+
// 本档按工厂造一次、把四个 IO 缝递进去——判据 ∥ 回执零变。
|
|
33
|
+
import { makeBufferedEditFace } from "./buffered-edit.mjs"
|
|
28
34
|
// 第 27 批 §12.3①/③:relay 前缀文法单一权威(模块直连——不自持正则副本)。
|
|
29
35
|
import { parseRelayPath } from "@thincoder/core/agent/relay-prefix.mjs"
|
|
30
36
|
// 批 1 CORE-DEFECT-FIXES B3:onWait 相位值域 + 文案单源(本面仅日志——PROVIDER.md §6.20)
|
|
@@ -132,8 +138,9 @@ export function buildAcpCallbacks({ sessionId, agent, notify, request, log = ()
|
|
|
132
138
|
|
|
133
139
|
// §15.1(TOOLS.md)D15.7 委派:edit 判定/应用单一权威 = 本地 computeEditEntry
|
|
134
140
|
// (edit-diff.mjs——校验→判定序→应用:行级 LCS、零重叠→替换即删、replace_all 字面替换全部)。
|
|
135
|
-
//
|
|
136
|
-
//
|
|
141
|
+
// 编辑链本体(读缓冲 → 行号锚护栏 → 纯函数判定 → 写回 → 记账)2026-11-05 外移 `./buffered-edit.mjs`:
|
|
142
|
+
// 那三件原是本函数体内的闭包,改装成工厂注入四个 IO 缝(本文件的 `readBuffer` / `writeBuffer` /
|
|
143
|
+
// `pathOf` + `agent`)——链体逐字搬家,错误文本仍经抛错原样透传(NF15.6b / AC15.10)。
|
|
137
144
|
|
|
138
145
|
// 不变量(§11.7-2):**任何** fs/* 反向 RPC 发出前必过客户端能力位——守卫住在本函数内
|
|
139
146
|
// (防御面:路由分支先判,守卫兜底,漏判不发静默超时)。
|
|
@@ -154,61 +161,9 @@ export function buildAcpCallbacks({ sessionId, agent, notify, request, log = ()
|
|
|
154
161
|
throw new Error(`fs/write_text_file failed: ${e.message}`)
|
|
155
162
|
}
|
|
156
163
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
const editSingle = async (p, args) => {
|
|
161
|
-
const raw = await readBuffer(p)
|
|
162
|
-
const content = normalizeEOL(raw)
|
|
163
|
-
const out = computeEditEntry(content, args, { path: p })
|
|
164
|
-
await writeBuffer(p, joinWithEol(normalizeEOL(out.updated).split("\n"), raw))
|
|
165
|
-
return `OK: edited ${p} via IDE (${out.occurrences} occurrence(s))${out.note ? ` — ${out.note}` : ""}`
|
|
166
|
-
}
|
|
167
|
-
/** 数组形态(D15.7):守卫与文案单源 = 本地 edit-diff(assertEditsContainer / assertEditEntries /
|
|
168
|
-
* validateEditEntry——EDIT.md §8 D-7:核 edit-batch 与桥同调用、桥零字面副本)→
|
|
169
|
-
* 读全部涉及文件缓冲(同文件去重——一次读)→ 逐条 computeEditEntry(EDIT_ABORT_PREFIX——批量
|
|
170
|
-
* 原子前缀;同文件条目按数组序串行累积——第二条基于第一条结果)→ 全部通过 → 逐文件写回
|
|
171
|
-
* 一次(判失败 → 零写;写失败 → 同本地 edit-batch 既有原子语义)。 */
|
|
172
|
-
/** ACP batch-edit 通道——与 EDIT.md:#796 汇总行体系**无关**。
|
|
173
|
-
* 桥面 `outcomes.map(...).join("\\n")` 自持逐条文字行,不经 `applyEditBatch`/`diffLines`/offload;
|
|
174
|
-
* 距 64K offload 阈值远 + 不含 diff 结构 ⇒ 不在 offload 盲区范围。**判定:非 #796 射程(#908)**。
|
|
175
|
-
*/
|
|
176
|
-
const editBatch = async (args) => {
|
|
177
|
-
const edits = args.edits
|
|
178
|
-
assertEditsContainer(edits)
|
|
179
|
-
assertEditArgsExclusive(args)
|
|
180
|
-
assertEditEntries(edits)
|
|
181
|
-
const groups = new Map() // path → { path, raw, content, edits }
|
|
182
|
-
for (const e of edits) {
|
|
183
|
-
// 2026-09-05 用户裁定(CLI parity——本地 edit-batch 同句):条目自带 path 优先;
|
|
184
|
-
// 缺省回退顶层 path(pathOf——path/filePath 别名同单形态)
|
|
185
|
-
const p = e.path ?? pathOf(args)
|
|
186
|
-
if (!p) throw new Error(EDIT_ENTRY_NO_PATH)
|
|
187
|
-
validateEditEntry(e, { label: editEntryLabel(p), rich: false })
|
|
188
|
-
let g = groups.get(p)
|
|
189
|
-
if (!g) {
|
|
190
|
-
g = { path: p, raw: "", content: "", edits: [] }
|
|
191
|
-
groups.set(p, g)
|
|
192
|
-
}
|
|
193
|
-
g.edits.push(e)
|
|
194
|
-
}
|
|
195
|
-
for (const g of groups.values()) {
|
|
196
|
-
g.raw = await readBuffer(g.path)
|
|
197
|
-
g.content = normalizeEOL(g.raw)
|
|
198
|
-
}
|
|
199
|
-
const outcomes = []
|
|
200
|
-
for (const g of groups.values()) {
|
|
201
|
-
for (const e of g.edits) {
|
|
202
|
-
const out = computeEditEntry(g.content, e, { path: g.path, abortPrefix: EDIT_ABORT_PREFIX })
|
|
203
|
-
outcomes.push({ g, out })
|
|
204
|
-
g.content = out.updated // 同文件串行累积
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
for (const g of groups.values()) {
|
|
208
|
-
await writeBuffer(g.path, joinWithEol(normalizeEOL(g.content).split("\n"), g.raw))
|
|
209
|
-
}
|
|
210
|
-
return outcomes.map((o) => `OK: edited ${o.g.path} via IDE (${o.out.occurrences} occurrence(s))${o.out.note ? ` — ${o.out.note}` : ""}`).join("\n")
|
|
211
|
-
}
|
|
164
|
+
// 编辑面三件(`absOf` ∥ `editSingle` ∥ `editBatch`):判据与回执住 `./buffered-edit.mjs`,本处只把四个
|
|
165
|
+
// 常量闭包当作 IO 缝递进去(唯一调用点就在本作用域内,实参恒在)。
|
|
166
|
+
const { absOf, editSingle, editBatch } = makeBufferedEditFace({ agent, readBuffer, writeBuffer, pathOf })
|
|
212
167
|
|
|
213
168
|
const callbacks = {
|
|
214
169
|
onToken: (text) => {
|
|
@@ -334,8 +289,8 @@ export function buildAcpCallbacks({ sessionId, agent, notify, request, log = ()
|
|
|
334
289
|
/**
|
|
335
290
|
* fs reverse-RPC router (dispatch.mjs toolRouter, M2) — 能力位 + 工具形态双判(§11.4):
|
|
336
291
|
* - write → fs/write_text_file (full content, no read-back) — 需 clientCaps.fs.writeTextFile
|
|
337
|
-
* - edit → fs/read_text_file → computeEditEntry(本地权威——单/数组形态)→ fs/write_text_file
|
|
338
|
-
* (§15.1 D15.7
|
|
292
|
+
* - edit → fs/read_text_file → 行号锚护栏 → computeEditEntry(本地权威——单/数组形态)→ fs/write_text_file
|
|
293
|
+
* (§15.1 D15.7 委派——双通道同语义;数组=原子批量——帧 R1–R4 同核,写回成功后同记账)
|
|
339
294
|
* — 需 readTextFile ∧ writeTextFile(读回是 edit 桥的必要前提)
|
|
340
295
|
* - apply_patch → local (unified-diff application is not routed in M2)
|
|
341
296
|
* - delete, reads → local
|
|
@@ -351,6 +306,9 @@ export function buildAcpCallbacks({ sessionId, agent, notify, request, log = ()
|
|
|
351
306
|
const content = args.content
|
|
352
307
|
try {
|
|
353
308
|
await request("fs/write_text_file", { sessionId, path, content }, { timeoutMs: 30000 })
|
|
309
|
+
// 全文重写也是「我们写的」——与核 writeTool 同型记账(§3 第 3 行:之后任何行号形拒)。
|
|
310
|
+
// 不记这一格,同一份漂移就成了「本地拒、IDE 缓冲放」。
|
|
311
|
+
recordWrite(absOf(path), { type: "write", startLine: 1, shift: 0 })
|
|
354
312
|
return { handled: true, result: `OK: wrote ${path} via IDE` }
|
|
355
313
|
} catch (e) {
|
|
356
314
|
return { handled: true, result: `Error: fs/write_text_file failed: ${e.message}` }
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* buffered-edit.mjs — IDE 缓冲编辑面(读缓冲 → 行号锚护栏 → 纯函数判定 → 写回 → 记账)。
|
|
3
|
+
*
|
|
4
|
+
* 2026-11-05 拆档族从 `bridge.mjs` 外移:`absOf` / `editSingle` / `editBatch` 三者原是
|
|
5
|
+
* `buildAcpCallbacks` 体内的闭包,依赖四个同作用域闭包(`agent` ∥ `readBuffer` ∥ `writeBuffer` ∥
|
|
6
|
+
* `pathOf`)——裸搬会把 `request` 与 sessionId 一并带走,故改为**工厂形注入**:IO 缝由调用方给,
|
|
7
|
+
* 链体逐字搬家。
|
|
8
|
+
*
|
|
9
|
+
* 判据与回执:edit 判定/应用单一权威仍是本地 `edit-diff.mjs` 的 `computeEditEntry` /
|
|
10
|
+
* `planEditEntries` / `applyPlannedEntries`——本档零字面副本;行号锚护栏的判据与拒文仍是核单源
|
|
11
|
+
* `write-path.mjs`;批级回执的两件文案单源 `edit-receipt.mjs`(与核同调、零字面副本);
|
|
12
|
+
* 记账键 = `resolveInCwd` 后的绝对路径(与核同一键)。
|
|
13
|
+
*
|
|
14
|
+
* **批量口径与核批面同一**(`docs/core/design/EDIT.md` §2「匹配与应用」):逐条成败、逐档一次写回、批内零回滚。
|
|
15
|
+
*
|
|
16
|
+
* 依赖单向:`本档 ← bridge.mjs`(本档不 import `bridge.mjs`)。
|
|
17
|
+
*/
|
|
18
|
+
import { normalizeEOL, joinWithEol, resolveInCwd } from "@thincoder/core/tools/shared.mjs"
|
|
19
|
+
import { computeEditEntry, validateEditEntry, assertEditArgsExclusive, assertEditsContainer, hasLineParams, planEditEntries, applyPlannedEntries, deleteTarget, EDIT_ENTRY_NO_PATH, editEntryLabel, editsEntryError } from "@thincoder/core/tools/edit-diff.mjs"
|
|
20
|
+
// 行号锚护栏(`EDIT-HELPERS.md` §3「行号锚」):桥不经 writeThroughPath ⇒ 判据与记账都得在桥面接(同节)。
|
|
21
|
+
// 判据 / 拒文 = 核单源;记账 = 写缓冲成功后桥自 recordWrite,键 = resolveInCwd 后的绝对路径。
|
|
22
|
+
import { recordWrite, lineAnchorVerdict, lineAnchorRefusal } from "@thincoder/core/tools/write-path.mjs"
|
|
23
|
+
// 批级回执两件文案(逐条失败行 ∥ 末行汇总)单源 = edit-receipt.mjs(`EDIT-HELPERS.md` §4「批量帧」):
|
|
24
|
+
// 核批面与桥面同调用——两工具一副骨架,改一处就同时改到另一处。
|
|
25
|
+
import { editEntryFailureLine, editBatchSummary } from "@thincoder/core/tools/edit-receipt.mjs"
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 造一个 IDE 缓冲编辑面。
|
|
29
|
+
* @param {{ agent: object, readBuffer: (p: string) => Promise<string>,
|
|
30
|
+
* writeBuffer: (p: string, content: string) => Promise<void>,
|
|
31
|
+
* pathOf: (args: object) => string|null }} deps
|
|
32
|
+
* `agent` = 会话的活引用(取 `cwd`);`readBuffer` / `writeBuffer` = 客户端 fs 反向 RPC 的两件闭包
|
|
33
|
+
* (各带自己的能力位守卫——本档只 issue);`pathOf` = `args.path ?? args.filePath` 的取值闭包
|
|
34
|
+
* (数组形态里条目缺 path 时回落到顶层 path 的判据靠它)。
|
|
35
|
+
* @returns {{ absOf: (p: string) => string, editSingle: Function, editBatch: Function }}
|
|
36
|
+
*/
|
|
37
|
+
export function makeBufferedEditFace({ agent, readBuffer, writeBuffer, pathOf }) {
|
|
38
|
+
/** 记账键(`EDIT-HELPERS.md` §3「行号锚」):与核同一键 = `resolveInCwd` 后的绝对路径——键不一致则核与桥各记一条、
|
|
39
|
+
* 互相看不见,护栏对另一条通道等于零。 */
|
|
40
|
+
const absOf = (p) => resolveInCwd({ cwd: agent?.cwd ?? process.cwd() }, p)
|
|
41
|
+
/** 单形态:读 IDE 缓冲 → 行号锚护栏判定 → computeEditEntry(rich——同本地 runSingleEdit)→
|
|
42
|
+
* 写回 → 记账。EOL 权威(F1):判定/应用在 normalizeEOL 后的 LF 域;写回
|
|
43
|
+
* joinWithEol 按原文首换行恢复(LF 域判定——CRLF 域写回——与本地 edit 工具同判同恢复)。 */
|
|
44
|
+
const editSingle = async (p, args) => {
|
|
45
|
+
const raw = await readBuffer(p)
|
|
46
|
+
const content = normalizeEOL(raw)
|
|
47
|
+
const abs = absOf(p)
|
|
48
|
+
// 行号锚护栏(`EDIT-HELPERS.md` §3「行号锚」):行号形才需判——内容形态是位置无关寻址,没有可漂移的锚。
|
|
49
|
+
// 形态校验先于护栏(与核 runSingleEdit 同序):缺 endLine / 与 old_string 互斥报自己的句。
|
|
50
|
+
if (hasLineParams(args)) {
|
|
51
|
+
validateEditEntry(args, { rich: true })
|
|
52
|
+
const startLine = args.line ?? args.startLine
|
|
53
|
+
const endLine = args.line ?? args.endLine
|
|
54
|
+
if (lineAnchorVerdict(abs, startLine, endLine)) throw new Error(lineAnchorRefusal(abs, startLine, endLine))
|
|
55
|
+
}
|
|
56
|
+
const out = computeEditEntry(content, args, { path: p, absPath: abs })
|
|
57
|
+
await writeBuffer(p, joinWithEol(normalizeEOL(out.updated).split("\n"), raw))
|
|
58
|
+
// 缓冲写回**成功之后**记账(快照对同一坐标系有效——缓冲与盘面可能不同步,行号语义跟的是缓冲)
|
|
59
|
+
recordWrite(abs, { type: "edit", startLine: out.editStartLine, shift: out.lineShift })
|
|
60
|
+
// 单形态回执说真话(EDIT.md §3「写与桥」):路由门要求单形态的 `new_string` 是字符串,而空串也是字符串
|
|
61
|
+
// ⇒ 行号形 + 空串改后确实走到这里,且它的结局是一次删除——继续印 `OK: edited` 就是把删除
|
|
62
|
+
// 说成替换。两路同一措辞:`Deleted <line N|lines N-M> of <path>`(行号段 = 同一 `deleteTarget`)。
|
|
63
|
+
return out.deleted
|
|
64
|
+
? `Deleted ${deleteTarget(out)} of ${p}`
|
|
65
|
+
: `OK: edited ${p} via IDE (${out.occurrences} occurrence(s))${out.note ? ` — ${out.note}` : ""}`
|
|
66
|
+
}
|
|
67
|
+
/** 数组形态:与核批面同一条六段流水线(EDIT.md §2「匹配与应用」)——
|
|
68
|
+
* ① 容器守卫整批拒 → ② 分组(非对象条目 ∥ 缺 path ∥ 条目校验不过 ⇒ 该条失败、不进组)→
|
|
69
|
+
* ③ 逐档读缓冲(读不到连坐该档)→ ④ 行号锚护栏逐条判(命中只废那一条)→
|
|
70
|
+
* ⑤ 帧排 + `onEntryError:"collect"` 累积(重叠两条互指、各得一行)→
|
|
71
|
+
* ⑥ 有 ≥1 条成功的档写缓冲一次并记合并快照;零成功的档不写不记账,写缓冲抛错只连坐该档。
|
|
72
|
+
*
|
|
73
|
+
* **两段结构保留、不拆**:`readBuffer` / `writeBuffer` 指 IDE 文档缓冲(传输事实),不是暂存区;
|
|
74
|
+
* 变的是第一段的身份——从「全过才写的闸」变成逐条判定点。桥的 IO 缝与消息契约字段零改。
|
|
75
|
+
*
|
|
76
|
+
* 回执三形(EDIT.md §2「匹配与应用」):成功行保持桥面现措辞;失败行与末行与核同一构造器;末行汇总行桥面
|
|
77
|
+
* 照写——它的数字(条目总数 / 成功条数 / 已写档数与路径)全在内存里,没有宿主能力依据可以挡它。
|
|
78
|
+
* 桥面不写的三样仍是 diff ∥ 语法检查 ∥ 写入点上下文(它们都读盘面内容或起外部进程)。
|
|
79
|
+
*
|
|
80
|
+
* ACP batch-edit 通道**不进 offload 面**:回执自持逐条文字行,不含 diff 结构。
|
|
81
|
+
*/
|
|
82
|
+
const editBatch = async (args) => {
|
|
83
|
+
const edits = args.edits
|
|
84
|
+
assertEditsContainer(edits) // ① 容器成形错 = 整批拒(经 toolRouter catch 渲染 `Error: <msg>`)
|
|
85
|
+
assertEditArgsExclusive(args)
|
|
86
|
+
const total = edits.length
|
|
87
|
+
// 每条一个结局:{ ok:true, g, out } ∥ { ok:false, reason }。回执只在全部写回之后组装——
|
|
88
|
+
// 档级写失败要把该档已算成的条改判为失败(「该档写不成就整档不成」)。
|
|
89
|
+
const state = new Array(total)
|
|
90
|
+
const fail = (i, reason) => { state[i] = { ok: false, reason } }
|
|
91
|
+
const groups = new Map() // abs → 每档一条流水线
|
|
92
|
+
|
|
93
|
+
// ② 分组(同核批面判据):非对象条目 = **该条**成形错(文案单源 editsEntryError(i)),不进组
|
|
94
|
+
for (let i = 0; i < total; i++) {
|
|
95
|
+
const e = edits[i]
|
|
96
|
+
if (e === null || typeof e !== "object" || Array.isArray(e)) { fail(i, editsEntryError(i)); continue }
|
|
97
|
+
// 2026-09-05 用户裁定(CLI parity——本地 edit-batch 同句):条目自带 path 优先;
|
|
98
|
+
// 缺省回退顶层 path(pathOf——path/filePath 别名同单形态)
|
|
99
|
+
const p = e.path || pathOf(args) // 同核 edit-batch 的兜底判(`||` 而非 `??`——空串也回落顶层)
|
|
100
|
+
if (!p) { fail(i, EDIT_ENTRY_NO_PATH); continue }
|
|
101
|
+
try {
|
|
102
|
+
// 成形错 ∥ 空串 ∥ 互斥 ∥ 行号非法:都只废这一条(scope:"batch" ⇒ 文本不带写盘结论)
|
|
103
|
+
validateEditEntry(e, { label: editEntryLabel(p), scope: "batch" })
|
|
104
|
+
} catch (err) {
|
|
105
|
+
fail(i, err.message)
|
|
106
|
+
continue
|
|
107
|
+
}
|
|
108
|
+
const abs = absOf(p)
|
|
109
|
+
let g = groups.get(abs)
|
|
110
|
+
if (!g) {
|
|
111
|
+
g = { abs, path: p, raw: "", content: "", readError: null, entries: [], idx: [], written: false }
|
|
112
|
+
groups.set(abs, g)
|
|
113
|
+
}
|
|
114
|
+
g.entries.push(e)
|
|
115
|
+
g.idx.push(i) // 条目在 `edits` 数组里的原始下标——回显按它回位(`EDIT-HELPERS.md` §4「批量帧」)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ③ 逐档读一次缓冲(读不到 ⇒ 该档所有条失败——原因取读错误原文)
|
|
119
|
+
for (const g of groups.values()) {
|
|
120
|
+
try {
|
|
121
|
+
g.raw = await readBuffer(g.path)
|
|
122
|
+
g.content = normalizeEOL(g.raw)
|
|
123
|
+
} catch (err) {
|
|
124
|
+
g.readError = err.message
|
|
125
|
+
for (const i of g.idx) fail(i, g.readError)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ④ 行号锚护栏(判定点同核:批前快照逐条判——命中只废那一条,零写不是它的后果)
|
|
130
|
+
// 组内不逐条再判:组内漂移由 R2(降序应用)自己算得出来,逐条再判会用同一份快照判出与 R2 相反的结果。
|
|
131
|
+
for (const g of groups.values()) {
|
|
132
|
+
if (g.readError) continue
|
|
133
|
+
const keep = []
|
|
134
|
+
const keepIdx = []
|
|
135
|
+
g.entries.forEach((e, k) => {
|
|
136
|
+
if (hasLineParams(e)) {
|
|
137
|
+
const startLine = e.line ?? e.startLine
|
|
138
|
+
const endLine = e.line ?? e.endLine
|
|
139
|
+
if (lineAnchorVerdict(g.abs, startLine, endLine)) {
|
|
140
|
+
fail(g.idx[k], lineAnchorRefusal(g.abs, startLine, endLine))
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
keep.push(e)
|
|
145
|
+
keepIdx.push(g.idx[k])
|
|
146
|
+
})
|
|
147
|
+
g.entries = keep
|
|
148
|
+
g.idx = keepIdx
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ⑤ 帧排 + 逐条累积(帧单源 = edit-diff 的两个零 IO 纯函数;`onEntryError:"collect"` + `scope:"batch"`
|
|
152
|
+
// 与核批面同组实参——桥只做「读缓冲 → 应用计划 → 写缓冲」)
|
|
153
|
+
const planned = [] // { g, results, idx }——待写档
|
|
154
|
+
for (const g of groups.values()) {
|
|
155
|
+
if (g.readError || g.entries.length === 0) continue
|
|
156
|
+
const plan = planEditEntries(g.entries, g.path)
|
|
157
|
+
const rejected = new Set(plan.rejections.map((r) => r.index))
|
|
158
|
+
for (const r of plan.rejections) fail(g.idx[r.index], r.reason) // 重叠:两条互指,各得一行
|
|
159
|
+
const pos = new Map() // 组内下标 → 存活序下标
|
|
160
|
+
const liveE = []
|
|
161
|
+
const liveIdx = []
|
|
162
|
+
g.entries.forEach((e, k) => {
|
|
163
|
+
if (rejected.has(k)) return
|
|
164
|
+
pos.set(k, liveE.length)
|
|
165
|
+
liveE.push(e)
|
|
166
|
+
liveIdx.push(g.idx[k])
|
|
167
|
+
})
|
|
168
|
+
if (liveE.length === 0) continue
|
|
169
|
+
const order = plan.order.filter((k) => !rejected.has(k)).map((k) => pos.get(k))
|
|
170
|
+
const applied = applyPlannedEntries(g.content, liveE, order, { path: g.path, scope: "batch", onEntryError: "collect" })
|
|
171
|
+
g.content = applied.content
|
|
172
|
+
for (const f of applied.failures) fail(liveIdx[f.index], f.reason)
|
|
173
|
+
planned.push({ g, results: applied.results, idx: liveIdx })
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ⑥ 逐档一次写回(该档有 ≥1 条成功才写;零条成功 ⇒ 不写、也不记账)
|
|
177
|
+
// recordWrite 每档一条合并快照:startLine = 已应用条受影响行的最小值、shift = 已应用条净漂移之和
|
|
178
|
+
// (失败条没有可记的漂移)。零条成功的档不记账,否则护栏会拿一条没有对应写盘的快照放行/拒绝。
|
|
179
|
+
for (const { g, results, idx } of planned) {
|
|
180
|
+
const okPos = []
|
|
181
|
+
results.forEach((r, k) => { if (r) okPos.push(k) })
|
|
182
|
+
if (okPos.length === 0) continue
|
|
183
|
+
const startLine = Math.min(...okPos.map((k) => results[k].editStartLine))
|
|
184
|
+
const shift = okPos.reduce((n, k) => n + results[k].lineShift, 0)
|
|
185
|
+
try {
|
|
186
|
+
await writeBuffer(g.path, joinWithEol(normalizeEOL(g.content).split("\n"), g.raw))
|
|
187
|
+
} catch (err) {
|
|
188
|
+
// 写缓冲抛错只连坐该档:已有自己失败原因的条目保留自己那一句——它讲的是另一件事。
|
|
189
|
+
for (const k of idx) if (!state[k]) fail(k, err.message)
|
|
190
|
+
continue
|
|
191
|
+
}
|
|
192
|
+
// 缓冲写回**成功之后**记账:快照对同一坐标系有效(行号语义跟的是缓冲)
|
|
193
|
+
recordWrite(g.abs, { type: "edit", startLine, shift })
|
|
194
|
+
g.written = true
|
|
195
|
+
okPos.forEach((k) => { state[idx[k]] = { ok: true, g, out: results[k] } })
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ⑦ 回执:逐条一行、按调用序回原位(成 = 桥面成功形;败 = `edits[<i>] — failed: <原因原文>`)+ 末行汇总
|
|
199
|
+
const lines = new Array(total)
|
|
200
|
+
let appliedCount = 0
|
|
201
|
+
for (let i = 0; i < total; i++) {
|
|
202
|
+
const s = state[i]
|
|
203
|
+
if (!s) throw new Error(`editBatch: entry ${i} produced no outcome — internal invariant break, not a bad input`)
|
|
204
|
+
if (!s.ok) { lines[i] = editEntryFailureLine(`edits[${i}]`, s.reason); continue }
|
|
205
|
+
appliedCount++
|
|
206
|
+
// 删行条目写 `Deleted <line N|lines N-M> of <path> via IDE`,行号段取同一 `deleteTarget`;
|
|
207
|
+
// 替换条目写确认形。两形是模型区分「删了行」与「换了内容」的两条线索。
|
|
208
|
+
lines[i] = s.out.deleted
|
|
209
|
+
? `Deleted ${deleteTarget(s.out)} of ${s.g.path} via IDE`
|
|
210
|
+
: `OK: edited ${s.g.path} via IDE (${s.out.occurrences} occurrence(s))${s.out.note ? ` — ${s.out.note}` : ""}`
|
|
211
|
+
}
|
|
212
|
+
const written = [...groups.values()].filter((g) => g.written).map((g) => g.path)
|
|
213
|
+
lines.push(editBatchSummary({ tool: "edit batch", applied: appliedCount, total, unit: "entries", filesWritten: written }))
|
|
214
|
+
return lines.join("\n")
|
|
215
|
+
}
|
|
216
|
+
return { absOf, editSingle, editBatch }
|
|
217
|
+
}
|