dsh-anchored-gpt-patch 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 roc-20 and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,22 @@
1
+ dsh-anchored-gpt-patch
2
+ ======================
3
+
4
+ This project is an independent, community-built agent preset for DeepSeek
5
+ Harness (DSH).
6
+
7
+ - It is NOT an official DeepSeek product, and it is not affiliated with or
8
+ endorsed by DeepSeek.
9
+ - The two-phase "anchored bootstrap" design is forked from Jungod1121's
10
+ `dsh-anchored-standard` (MIT), which itself was inspired by the published
11
+ work of xiaobright (`xiaobright/dsh-anchored-standard`,
12
+ `xiaobright/modeltest`). The GPT Patch change — first-request anchors and
13
+ promoted catalog use the bundled OpenAI Codex `apply_patch` instead of
14
+ `edit`/`write` — was written for this fork.
15
+ - The preset composition follows the structure of the shipped
16
+ `standard`/`minimal` agent presets of the official
17
+ deepseek-ai/deepseek-harness repository, which is licensed under its own
18
+ terms.
19
+ - `preset/bin/apply_patch` is the OpenAI Codex patch-execution binary,
20
+ covered by its own license in `preset/bin/LICENSE-OpenAI-Codex.txt`.
21
+ It is redistributed here as the tool backend for the `apply_patch` preset
22
+ tool.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # dsh-anchored-gpt-patch
2
+
3
+ 锚定标准模式(GPT Patch):把 `anchored-standard` 的两阶段锚定拿过来,首轮和全量目录里的 `edit` / `write` 全部换成内置的 OpenAI Codex `apply_patch`。适合 GPT / Codex 模型。
4
+
5
+ > Forked from [`Jungod1121/dsh-anchored-standard`](https://github.com/Jungod1121/dsh-anchored-standard) (MIT, itself inspired by `xiaobright/dsh-anchored-standard`). Community project — not an official DeepSeek preset, not affiliated with or endorsed by DeepSeek.
6
+
7
+ ## 与上游的差别
8
+
9
+ | | 上游 `anchored-standard` | 本包 `anchored-gpt-patch` |
10
+ |---|---|---|
11
+ | 首轮 spec 锚定 | `bash + read + edit` | `bash + read + apply_patch` |
12
+ | 首轮 react 锚定 | `bash + read + write` | `bash + read + apply_patch` |
13
+ | 晋升后全量目录 | 全部 25 个 Standard 工具(含 `edit/write`) | 过滤掉 `edit`/`write`,文件改动只走 `apply_patch` |
14
+ | 工具后端 | 无 | 自带 `preset/bin/apply_patch` 二进制(见下) |
15
+ | UI | 无 | 建议同装 `dsh-apply-patch-ui`,把 `apply_patch` 调用渲染成 diff 卡 |
16
+
17
+ ## 安装
18
+
19
+ ```sh
20
+ dsh plugin --profile web add dsh-anchored-gpt-patch
21
+ dsh plugin --profile web add dsh-apply-patch-ui
22
+ ```
23
+
24
+ 重启 DeepSeek Harness,bundle 会把 preset 拷到 `$DSH_HOME/.agent-presets/anchored-gpt-patch/`(幂等:本地改过的文件不会被覆盖),然后新建空白会话选择 **锚定标准模式(GPT Patch)**。设为新会话默认:
25
+
26
+ ```yaml
27
+ # $DSH_HOME/settings.yaml
28
+ agent-presets:
29
+ default: anchored-gpt-patch
30
+ ```
31
+
32
+ ## 验证
33
+
34
+ 导出会话 JSONL,看 `request/header` 事件:首个 header 只有 `bash/read/apply_patch` 三件套,第一次 `tool/call` 之后恢复全量目录(不再含 `edit`/`write`)。
35
+
36
+ ## 当前限制
37
+
38
+ - `preset/bin/` 目前只带 Windows 的 `apply_patch.exe`,macOS / Linux 暂不支持(装得上但工具执行会失败)。
39
+ - `apply_patch` 二进制是 OpenAI Codex 的产物,遵循 `preset/bin/LICENSE-OpenAI-Codex.txt`,随包再分发。
40
+ - Harness 处在 developer preview,升级前先看上游 breaking changes。
41
+
42
+ ## 卸载
43
+
44
+ ```sh
45
+ dsh plugin --profile web remove dsh-anchored-gpt-patch
46
+ rm -rf "${DSH_HOME:-$HOME/.dsh}/.agent-presets/anchored-gpt-patch"
47
+ ```
48
+
49
+ ## 兼容性
50
+
51
+ 从 harness `0.1.1-rc.2` + `anchored-standard` 的 `0.1.0-rc.6` 验证基线 fork,实测以你本地为准。
52
+
53
+ ## License
54
+
55
+ MIT — [LICENSE](./LICENSE),第三方二进制见 [NOTICE](./NOTICE)。
@@ -0,0 +1,5 @@
1
+ # The `dsh-anchored-gpt-patch` bundle layer: one installer entry that copies the
2
+ # bundled preset into the user preset root on boot.
3
+ - insert:
4
+ - id: anchored-gpt-patch-installer
5
+ name: dsh-anchored-gpt-patch
package/index.js ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Installer for the `anchored-gpt-patch` agent preset.
3
+ *
4
+ * This bundle plugin copies the bundled preset (preset/agent.cordis.yml,
5
+ * preset/preset.yml, preset/tool-bootstrap.mjs, preset/apply-patch.mjs, plus
6
+ * the patch-execution backend under preset/bin/) into the user preset root
7
+ * `$DSH_HOME/.agent-presets/anchored-gpt-patch/` exactly once on boot, so
8
+ * `dsh plugin --profile web add dsh-anchored-gpt-patch`
9
+ * also makes the preset selectable in the session preset list.
10
+ *
11
+ * Forked from Jungod1121's `dsh-anchored-standard` installer (MIT).
12
+ * The GPT Patch difference: the preset replaces `edit`/`write` with the
13
+ * bundled OpenAI Codex `apply_patch` tool, so the binary backend must be
14
+ * installed alongside the preset sources.
15
+ *
16
+ * Idempotent and non-destructive:
17
+ * - a missing target file is written;
18
+ * - an identical target file is left untouched (no-op);
19
+ * - a DIFFERENT target file is left untouched with a one-time-ish warning,
20
+ * so a locally edited preset is never overwritten.
21
+ * Uninstalling this bundle never deletes the installed preset — delete the
22
+ * `anchored-gpt-patch` directory under the user preset root manually if you
23
+ * want it gone.
24
+ */
25
+
26
+ import { existsSync } from 'node:fs'
27
+ import { mkdir, readFile, writeFile, chmod } from 'node:fs/promises'
28
+ import { homedir } from 'node:os'
29
+ import { dirname, join } from 'node:path'
30
+ import { fileURLToPath } from 'node:url'
31
+
32
+ /** Cordis plugin name used by loader diagnostics. */
33
+ export const name = 'anchored-gpt-patch-installer'
34
+
35
+ const PRESET_ID = 'anchored-gpt-patch'
36
+ const PRESET_FILES = ['agent.cordis.yml', 'preset.yml', 'tool-bootstrap.mjs', 'apply-patch.mjs']
37
+ const BIN_FILES = ['bin/apply_patch.exe', 'bin/LICENSE-OpenAI-Codex.txt']
38
+
39
+ export async function apply(ctx) {
40
+ const log = {
41
+ info(message) {
42
+ try {
43
+ if (ctx.logger && typeof ctx.logger.info === 'function') ctx.logger.info(message)
44
+ } catch {
45
+ // logger unavailable — nothing to do
46
+ }
47
+ },
48
+ warn(message) {
49
+ try {
50
+ if (ctx.logger && typeof ctx.logger.warn === 'function') ctx.logger.warn(message)
51
+ } catch {
52
+ // logger unavailable — nothing to do
53
+ }
54
+ },
55
+ }
56
+
57
+ try {
58
+ const packageDir = dirname(fileURLToPath(import.meta.url))
59
+ const sourceDir = join(packageDir, 'preset')
60
+ const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
61
+ const targetDir = join(dshHome, '.agent-presets', PRESET_ID)
62
+
63
+ await mkdir(targetDir, { recursive: true })
64
+
65
+ let installed = 0
66
+ let kept = 0
67
+ for (const file of [...PRESET_FILES, ...BIN_FILES]) {
68
+ const source = join(sourceDir, file)
69
+ const target = join(targetDir, file)
70
+ const content = await readFile(source)
71
+ if (existsSync(target)) {
72
+ const existing = await readFile(target)
73
+ if (existing.equals(content)) continue
74
+ log.warn(`${name}: ${target} exists with different content; leaving it untouched`)
75
+ kept += 1
76
+ continue
77
+ }
78
+ await mkdir(dirname(target), { recursive: true })
79
+ await writeFile(target, content)
80
+ installed += 1
81
+ }
82
+
83
+ // POSIX users running a non-.exe backend keep exec permission when the
84
+ // backend is refreshed by this installer. Best-effort: never fail boot.
85
+ try {
86
+ const backend = join(targetDir, 'bin', 'apply_patch')
87
+ if (existsSync(backend)) await chmod(backend, 0o755)
88
+ } catch {
89
+ // ignore — Windows backends need no chmod
90
+ }
91
+
92
+ log.info(
93
+ installed > 0
94
+ ? `${name}: installed preset '${PRESET_ID}' (${installed} file(s)) at ${targetDir}`
95
+ : kept > 0
96
+ ? `${name}: preset '${PRESET_ID}' already present at ${targetDir} (${kept} locally edited file(s) kept untouched)`
97
+ : `${name}: preset '${PRESET_ID}' already present and up to date at ${targetDir}`,
98
+ )
99
+ log.info(`${name}: the '${PRESET_ID}' preset is now selectable for new sessions; set settings 'agent-presets.default' to make it the default.`)
100
+ } catch (error) {
101
+ // An installer failure must never take the bundle down with it.
102
+ log.warn(`${name}: preset install failed (plugin continues without it): ${String((error && error.message) || error)}`)
103
+ }
104
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "dsh-anchored-gpt-patch",
3
+ "version": "1.0.0",
4
+ "description": "Anchored Standard preset with GPT Patch mode: task-aware first-request anchors using the bundled OpenAI Codex apply_patch instead of edit/write. Built for GPT/Codex models.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js"
9
+ },
10
+ "files": [
11
+ "index.js",
12
+ "cordis.patch.yml",
13
+ "preset/",
14
+ "README.md",
15
+ "LICENSE",
16
+ "NOTICE"
17
+ ],
18
+ "dsh": {
19
+ "bundle": {
20
+ "patch": "./cordis.patch.yml"
21
+ }
22
+ },
23
+ "keywords": [
24
+ "dsh",
25
+ "deepseek-harness",
26
+ "dsh-plugin",
27
+ "agent-preset",
28
+ "anchored-standard",
29
+ "gpt-patch",
30
+ "apply-patch",
31
+ "openai-codex"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/roc-20/dsh-anchored-gpt-patch.git"
36
+ },
37
+ "homepage": "https://github.com/roc-20/dsh-anchored-gpt-patch#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/roc-20/dsh-anchored-gpt-patch/issues"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "license": "MIT"
45
+ }
@@ -0,0 +1,214 @@
1
+ # The `anchored-standard` user preset (v2): task-aware first-request anchors,
2
+ # then the full Standard tool catalog after the first durable tool call.
3
+ #
4
+ # Composition plan (verified on harness 0.1.0-rc.6):
5
+ # 1. `tool-bootstrap` classifies the session's FIRST user message into an
6
+ # anchor — spec (fix/maintain: Minimal persona + bash/read/edit), react
7
+ # (build/create: doer persona + bash/read/write), or weak (ambiguous:
8
+ # model self-picks + bash/read). `glob`/`grep` stay out of the bootstrap
9
+ # catalogs (measured trajectory boundary for V4 Pro).
10
+ # 2. On the first request the persona is the ONLY prompt section and
11
+ # runtime contexts are cleared — the cleanest possible opening.
12
+ # 3. After the first durable `tool/call`, every later request sees the
13
+ # full Standard catalog; the chosen persona stays constant and the
14
+ # remaining sections (plan-mode etc.) return. Nothing is injected
15
+ # after turn one (measured: anchors hurt Pro).
16
+ #
17
+ # This is a community preset. It is not an official DeepSeek preset and is not
18
+ # affiliated with or endorsed by DeepSeek. The upstream harness is a developer
19
+ # preview with breaking changes; review upstream changes before upgrading.
20
+
21
+ # ── identity ────────────────────────────────────────────────────────────────
22
+
23
+ # Fallback persona only: `tool-bootstrap` replaces the persona section on
24
+ # every assembly with the task-matched anchor persona (spec/react/weak).
25
+ # Keep this text byte-identical to the Minimal preset as the safe fallback.
26
+ - id: persona
27
+ name: '@deepseek-ai/dsh-persona'
28
+ config:
29
+ text: You are a helpful software engineer assistant.
30
+
31
+ - id: agent-instructions
32
+ name: '@deepseek-ai/dsh-agent-instructions'
33
+ config:
34
+ maxBytes: 65536
35
+
36
+ # ── shell ───────────────────────────────────────────────────────────────────
37
+
38
+ - id: tool-bash
39
+ name: '@deepseek-ai/dsh-tool-bash'
40
+ disabled: !!js process.platform === 'win32'
41
+
42
+ - id: tool-pwsh
43
+ name: '@deepseek-ai/dsh-tool-pwsh'
44
+ disabled: !!js process.platform !== 'win32'
45
+
46
+ # ── filesystem ──────────────────────────────────────────────────────────────
47
+
48
+ - id: tool-fs
49
+ name: '@deepseek-ai/dsh-tool-fs'
50
+
51
+ - id: tool-fs-search
52
+ name: '@deepseek-ai/dsh-tool-fs-search'
53
+ config:
54
+ sampleOverCapGlobResults: false
55
+
56
+ # ── background jobs ────────────────────────────────────────────────────────
57
+
58
+ - id: tool-jobs
59
+ name: '@deepseek-ai/dsh-tool-jobs'
60
+
61
+ # ── skills ──────────────────────────────────────────────────────────────────
62
+
63
+ - id: skill-filesystem
64
+ name: '@deepseek-ai/dsh-skill-filesystem'
65
+
66
+ - id: tool-skill
67
+ name: '@deepseek-ai/dsh-tool-skill'
68
+
69
+ # ── goals ───────────────────────────────────────────────────────────────────
70
+
71
+ - id: tool-goal
72
+ name: '@deepseek-ai/dsh-tool-goal'
73
+
74
+ # ── plan mode ───────────────────────────────────────────────────────────────
75
+
76
+ - id: planning
77
+ name: cordis:group
78
+ group: true
79
+ isolate:
80
+ planMode: true
81
+ config:
82
+ - id: plan-mode
83
+ name: '@deepseek-ai/dsh-plan-mode'
84
+ config:
85
+ section: |
86
+ You are in plan mode. Stay in plan mode until exit_plan_mode succeeds or the user switches the session mode. Imperative language to implement changes means plan the implementation, not execute it. A user's conversational agreement — including an answer confirming something you asked — approves nothing and does not end plan mode; fold the confirmed decision into the plan and submit it through exit_plan_mode.
87
+
88
+ Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery.
89
+
90
+ The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed to keep the tool catalog unchanged. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode.
91
+
92
+ Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out.
93
+
94
+ Make the plan decision-complete: state the goal and success criteria; group implementation changes by subsystem; identify public API, schema, and data-flow changes; cover edge cases, failure modes, tests, acceptance criteria, and explicit assumptions. Keep it concise enough to review but detailed enough that another engineer can implement it without making design decisions.
95
+
96
+ When ready, call exit_plan_mode with the complete plan markdown, starting with a # title. Make exit_plan_mode the only and final tool call in that assistant response: it presents the plan for approval, and implementation begins only in a later step after approval. Do not paste the final plan as a plain reply or ask "should I proceed?" through prose or ask_user_question. If review rejects it, incorporate the feedback and present again. If the review channel is unavailable or aborted, stay in plan mode and ask the user to switch modes manually; do not proceed with implementation.
97
+
98
+ # ── compaction ──────────────────────────────────────────────────────────────
99
+
100
+ - id: compaction
101
+ name: cordis:group
102
+ group: true
103
+ isolate:
104
+ compaction: true
105
+ toolResultPruner: true
106
+ config:
107
+ - id: compaction-basic
108
+ name: '@deepseek-ai/dsh-compaction-basic'
109
+
110
+ - id: command-compact
111
+ name: '@deepseek-ai/dsh-command-compact'
112
+
113
+ - id: tool-result-pruner
114
+ name: '@deepseek-ai/dsh-compaction-tool-result-pruner'
115
+ config:
116
+ thresholdChars: 8192
117
+ headChars: 4096
118
+ tailChars: 1024
119
+
120
+ # ── delegation and workflows ────────────────────────────────────────────────
121
+
122
+ - id: delegation
123
+ name: cordis:group
124
+ group: true
125
+ isolate:
126
+ workflowEngine: true
127
+ config:
128
+ - id: tool-subagent-control
129
+ name: '@deepseek-ai/dsh-tool-subagent-control'
130
+
131
+ - id: tool-subagent-list-agents
132
+ name: '@deepseek-ai/dsh-tool-subagent-control/list-agents'
133
+
134
+ - id: tool-subagent
135
+ name: '@deepseek-ai/dsh-tool-subagent'
136
+ config:
137
+ provider: spawn
138
+ toolName: subagent
139
+ backgroundMode: continuable
140
+ agentOptions:
141
+ provider: openai-codex
142
+ model: gpt-5.6-luna
143
+ maxTokens: 128000
144
+
145
+ - id: tool-subagent-fork
146
+ name: '@deepseek-ai/dsh-tool-subagent'
147
+ config:
148
+ provider: fork
149
+ toolName: subagent_fork
150
+ backgroundMode: continuable
151
+
152
+ - id: tool-subagent-codex
153
+ name: '@deepseek-ai/dsh-tool-subagent'
154
+ disabled: true
155
+ config:
156
+ provider: codex
157
+ toolName: subagent_codex
158
+ enableRunInBackground: false
159
+ maxDepth: provider-managed
160
+
161
+ - id: tool-subagent-claude-code
162
+ name: '@deepseek-ai/dsh-tool-subagent'
163
+ disabled: true
164
+ config:
165
+ provider: claude-code
166
+ toolName: subagent_claude_code
167
+ enableRunInBackground: false
168
+ maxDepth: provider-managed
169
+
170
+ - id: workflow-worker-thread
171
+ name: '@deepseek-ai/dsh-workflow-worker-thread'
172
+ config:
173
+ provider: spawn
174
+
175
+ - id: tool-workflow
176
+ name: '@deepseek-ai/dsh-tool-workflow'
177
+
178
+ - id: tool-ralph
179
+ name: '@deepseek-ai/dsh-tool-ralph'
180
+ config:
181
+ subagentProvider: spawn
182
+ maxRounds: 64
183
+
184
+ # ── remaining model-facing rows ─────────────────────────────────────────────
185
+
186
+ - id: tool-ask-user
187
+ name: '@deepseek-ai/dsh-tool-ask-user'
188
+
189
+ - id: tool-todo
190
+ name: '@deepseek-ai/dsh-tool-todo'
191
+ config:
192
+ allowParallelInProgress: true
193
+
194
+ - id: tool-web
195
+ name: '@deepseek-ai/dsh-tool-web'
196
+ config:
197
+ fetch: false
198
+ searchTimeoutMs: 60000
199
+
200
+ # ── bundled OpenAI Codex apply_patch ────────────────────────────────────────
201
+
202
+ - id: apply-patch
203
+ name: ./apply-patch.mjs
204
+
205
+ # ── anchored bootstrap (LAST: the final filter over the assembled catalog) ──
206
+
207
+ # Task-aware first-request anchors (v2): the first user message picks the
208
+ # anchor — spec (fix: bash+read+edit, Minimal persona), react (build:
209
+ # bash+read+write, doer persona), or weak (ambiguous: bash+read, model
210
+ # self-picks). After the session records its first durable `tool/call`,
211
+ # later step assemblies expose every Standard tool registered above while
212
+ # the chosen persona stays and the other prompt sections return.
213
+ - id: tool-bootstrap
214
+ name: ./tool-bootstrap.mjs
@@ -0,0 +1,234 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { readFile } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { fileURLToPath, pathToFileURL } from 'node:url'
5
+
6
+ const presetDir = path.dirname(fileURLToPath(import.meta.url))
7
+ const executable = path.join(presetDir, 'bin', 'apply_patch.exe')
8
+ const dshNodeModules = path.join(
9
+ process.env.APPDATA || '',
10
+ 'npm', 'node_modules', '@deepseek-ai', 'dsh', 'node_modules',
11
+ )
12
+ const { defineTool } = await import(pathToFileURL(path.join(
13
+ dshNodeModules, '@deepseek-ai', 'dsh-tools', 'lib', 'index.js',
14
+ )).href)
15
+ const { structuredPatch } = await import(pathToFileURL(path.join(
16
+ dshNodeModules, 'diff', 'libesm', 'index.js',
17
+ )).href)
18
+
19
+ export const name = 'bundled-codex-apply-patch'
20
+ export const inject = ['tools', 'systemPrompt']
21
+
22
+ function parsePatchOperations(input) {
23
+ const lines = input.replaceAll('\r\n', '\n').split('\n')
24
+ const operations = []
25
+ let index = 0
26
+ while (index < lines.length) {
27
+ const header = /^\*\*\* (Add|Update|Delete) File: (.+)$/.exec(lines[index])
28
+ if (!header) {
29
+ index += 1
30
+ continue
31
+ }
32
+ const kind = header[1].toLowerCase()
33
+ const sourcePath = header[2]
34
+ let end = index + 1
35
+ while (end < lines.length && !/^\*\*\* (?:Add|Update|Delete) File: /.test(lines[end]) && lines[end] !== '*** End Patch') end += 1
36
+ const block = lines.slice(index + 1, end)
37
+ const move = block.map((line) => /^\*\*\* Move to: (.+)$/.exec(line)).find(Boolean)
38
+ const targetPath = move?.[1] || sourcePath
39
+ const oldLines = []
40
+ const newLines = []
41
+ for (const line of block) {
42
+ if (line.startsWith('@@') || line === '*** End of File' || line.startsWith('*** Move to:')) continue
43
+ if (kind === 'add') {
44
+ if (line.startsWith('+')) newLines.push(line.slice(1))
45
+ } else if (line.startsWith(' ')) {
46
+ oldLines.push(line.slice(1))
47
+ newLines.push(line.slice(1))
48
+ } else if (line.startsWith('-')) oldLines.push(line.slice(1))
49
+ else if (line.startsWith('+')) newLines.push(line.slice(1))
50
+ }
51
+ operations.push({ kind, sourcePath, targetPath, oldLines, newLines })
52
+ index = end
53
+ }
54
+ return operations
55
+ }
56
+
57
+ function callDiffs(operations) {
58
+ return operations.map((operation) => {
59
+ if (operation.kind === 'add') return { path: operation.targetPath, oldText: null, newText: operation.newLines.join('\n') }
60
+ if (operation.kind === 'delete') return { path: operation.sourcePath, oldText: 'File will be deleted.', newText: '' }
61
+ if (operation.oldLines.length === 0 && operation.newLines.length === 0 && operation.sourcePath !== operation.targetPath) {
62
+ return { path: operation.targetPath, oldText: `Move from ${operation.sourcePath}`, newText: `Move to ${operation.targetPath}` }
63
+ }
64
+ return {
65
+ path: operation.targetPath,
66
+ oldText: operation.oldLines.length > 0 ? operation.oldLines.join('\n') : null,
67
+ newText: operation.newLines.join('\n'),
68
+ }
69
+ })
70
+ }
71
+
72
+ async function readUtf8(filePath) {
73
+ try {
74
+ return await readFile(filePath, 'utf8')
75
+ } catch (error) {
76
+ if (error?.code === 'ENOENT') return null
77
+ throw error
78
+ }
79
+ }
80
+
81
+ function computeHunkDiffs(filePath, before, after) {
82
+ if (before === null) return [{ path: filePath, oldText: null, newText: after }]
83
+ const patch = structuredPatch('', '', before, after, undefined, undefined, { context: 3 })
84
+ return patch.hunks.map((hunk) => {
85
+ const oldLines = []
86
+ const newLines = []
87
+ for (const line of hunk.lines) {
88
+ if (line.startsWith('\\')) continue
89
+ const text = line.slice(1)
90
+ if (line.startsWith('-')) oldLines.push(text)
91
+ else if (line.startsWith('+')) newLines.push(text)
92
+ else {
93
+ oldLines.push(text)
94
+ newLines.push(text)
95
+ }
96
+ }
97
+ return {
98
+ path: filePath,
99
+ oldText: oldLines.length > 0 ? oldLines.join('\n') : null,
100
+ newText: newLines.join('\n'),
101
+ }
102
+ })
103
+ }
104
+
105
+ function diffsFromMeta(meta) {
106
+ if (!meta || typeof meta !== 'object' || !Array.isArray(meta.diffs)) return undefined
107
+ const diffs = meta.diffs.filter((diff) => diff && typeof diff.path === 'string' && (diff.oldText === null || typeof diff.oldText === 'string') && typeof diff.newText === 'string')
108
+ return diffs.length > 0 ? diffs : undefined
109
+ }
110
+
111
+ function runPatch(input, cwd, signal) {
112
+ return new Promise((resolve, reject) => {
113
+ const child = spawn(executable, [], {
114
+ cwd,
115
+ windowsHide: true,
116
+ stdio: ['pipe', 'pipe', 'pipe'],
117
+ })
118
+ child.stdin.end(input)
119
+ const stdout = []
120
+ const stderr = []
121
+ let outputBytes = 0
122
+ const maxOutputBytes = 1024 * 1024
123
+ let settled = false
124
+
125
+ const fail = (error) => {
126
+ if (settled) return
127
+ settled = true
128
+ reject(error)
129
+ }
130
+ const collect = (target) => (chunk) => {
131
+ outputBytes += chunk.length
132
+ if (outputBytes > maxOutputBytes) {
133
+ child.kill()
134
+ fail(new Error('apply_patch output exceeded 1 MiB'))
135
+ return
136
+ }
137
+ target.push(chunk)
138
+ }
139
+ child.stdout.on('data', collect(stdout))
140
+ child.stderr.on('data', collect(stderr))
141
+
142
+ const abort = () => child.kill()
143
+ signal?.addEventListener('abort', abort, { once: true })
144
+ child.once('error', fail)
145
+ child.once('close', (code) => {
146
+ signal?.removeEventListener('abort', abort)
147
+ if (settled) return
148
+ const out = Buffer.concat(stdout).toString('utf8').trim()
149
+ const err = Buffer.concat(stderr).toString('utf8').trim()
150
+ if (signal?.aborted) return fail(new Error('apply_patch was canceled'))
151
+ if (code !== 0) return fail(new Error(err || out || `apply_patch exited with code ${code}`))
152
+ settled = true
153
+ resolve(out || 'Done!')
154
+ })
155
+ })
156
+ }
157
+
158
+ export function apply(ctx) {
159
+ ctx.systemPrompt.section({
160
+ name: 'tool:apply_patch',
161
+ order: 102,
162
+ text: 'Use apply_patch as the sole file-mutation tool. It does not require a prior read: when the conversation or available context already contains enough exact file context, apply the patch directly and avoid a redundant read. Read only when the target content is unknown, the patch context is uncertain, or a patch fails and must be refreshed. Send one complete Codex patch beginning with *** Begin Patch and ending with *** End Patch. It supports Add File, Update File, Delete File, and Move to operations. Use workspace-relative paths.',
163
+ })
164
+
165
+ ctx.tools.register(defineTool({
166
+ name: 'apply_patch',
167
+ description: 'Apply a Codex patch directly to files in the current workspace; no prior read is required when patch context is already known.',
168
+ parameters: {
169
+ input: {
170
+ type: 'string',
171
+ required: true,
172
+ description: 'Complete Codex patch text from *** Begin Patch through *** End Patch.',
173
+ },
174
+ },
175
+ output: {
176
+ schema: {
177
+ type: 'object',
178
+ additionalProperties: false,
179
+ properties: {
180
+ message: { type: 'string', required: true },
181
+ diffs: {
182
+ type: 'array',
183
+ required: true,
184
+ items: {
185
+ type: 'object',
186
+ additionalProperties: false,
187
+ properties: {
188
+ path: { type: 'string', required: true },
189
+ oldText: { required: true, oneOf: [{ type: 'string' }, { type: 'null' }] },
190
+ newText: { type: 'string', required: true },
191
+ },
192
+ },
193
+ },
194
+ },
195
+ },
196
+ render: (_args, value) => [{ type: 'text', text: value.message }],
197
+ presentationMeta: (_args, value) => ({ diffs: value.diffs }),
198
+ },
199
+ async execute(args, exec) {
200
+ if (!args.input.startsWith('*** Begin Patch') || !args.input.trimEnd().endsWith('*** End Patch')) {
201
+ throw new Error('input must be a complete Codex patch from *** Begin Patch through *** End Patch')
202
+ }
203
+ const cwd = exec.agent?.session.header.cwd
204
+ if (!cwd) throw new Error('apply_patch requires a session workspace')
205
+ const operations = parsePatchOperations(args.input)
206
+ if (operations.length === 0) throw new Error('apply_patch input contains no file operations')
207
+ const before = await Promise.all(operations.map((operation) => operation.kind === 'add'
208
+ ? null
209
+ : readUtf8(path.resolve(cwd, operation.sourcePath))))
210
+ const message = await runPatch(args.input, cwd, exec.signal)
211
+ const diffs = []
212
+ for (let index = 0; index < operations.length; index += 1) {
213
+ const operation = operations[index]
214
+ const after = operation.kind === 'delete' ? '' : (await readUtf8(path.resolve(cwd, operation.targetPath)) ?? '')
215
+ diffs.push(...computeHunkDiffs(operation.targetPath, before[index], after))
216
+ }
217
+ return { message, diffs }
218
+ },
219
+ presentCall(args) {
220
+ const diffs = callDiffs(parsePatchOperations(args.input))
221
+ return {
222
+ card: 'diff',
223
+ title: 'Apply patch',
224
+ diffs,
225
+ locations: diffs.map((diff) => ({ path: diff.path })),
226
+ }
227
+ },
228
+ presentResult(_args, result) {
229
+ if (result.isError) return undefined
230
+ const diffs = diffsFromMeta(result.meta)
231
+ return diffs ? { card: 'diff', title: 'Applied patch', diffs } : undefined
232
+ },
233
+ }))
234
+ }
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 OpenAI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Binary file
@@ -0,0 +1,3 @@
1
+ name: 锚定标准模式(GPT Patch)
2
+ description: 基于锚定标准模式,使用内置的 OpenAI Codex apply_patch 替代 edit;适合 GPT/Codex 模型。
3
+ order: 5
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Anchored tool bootstrap v2 — task-aware reasoning-mode anchors.
3
+ *
4
+ * Classifies the session's FIRST user message into one of three anchors and
5
+ * keeps the first model request on a small, task-matched tool surface:
6
+ *
7
+ * spec (fix / maintain / debug) → Minimal persona, bash + read + edit
8
+ * react (build / create / from 0) → doer persona, bash + read + write
9
+ * weak (ambiguous) → model self-picks; bash + read only
10
+ *
11
+ * After the session records its first durable `tool/call`, every later
12
+ * request sees the full preset catalog; the chosen persona stays constant,
13
+ * runtime contexts are cleared, and the remaining prompt sections (plan-mode
14
+ * etc.) come back. The mode derives from durable session events, so resume
15
+ * and reload preserve it.
16
+ *
17
+ * Design boundaries (measured evidence):
18
+ * - `glob` is a trajectory boundary for V4 Pro (xiaobright probes): a
19
+ * first-turn catalog with glob breaks the Minimal-like anchor. `grep` is
20
+ * unverified. Both stay out of the bootstrap catalogs.
21
+ * - `bash+edit` and `bash+write` both keep the Minimal-like anchor
22
+ * (xiaobright probes), so the spec/react catalogs use them.
23
+ * - Pro does NOT want post-anchor injected guidance (router-standard P24:
24
+ * anchors hurt Pro). Flash benefits from neutral persona + classify
25
+ * instruction (router-standard P11). Nothing is injected after turn one.
26
+ *
27
+ * Robustness: promotion is memoized per session; mode is memoized per
28
+ * session; a missing bootstrap tool degrades to the full catalog instead of
29
+ * throwing; any filter failure also degrades to the full catalog.
30
+ */
31
+
32
+ /** Cordis plugin name used by loader diagnostics. */
33
+ export const name = 'anchored-tool-bootstrap'
34
+
35
+ /** Prompt assembly must exist before this request filter can register. */
36
+ export const inject = ['systemPrompt']
37
+
38
+ /* ── task classifier (ported from router-standard, zero dependencies) ───── */
39
+
40
+ const REACT_RE = /(开发|创建|写一个|写个|生成|从零|做一个|做个|搞一个|游戏|网页|网站|构建|新项目|搭建|实现|做出|上线|落地|脚本|工具|应用|添加|新增|build|create|develop|generate|implement|make a|new project)/gi
41
+ const SPEC_RE = /(修复|修一下|修改|改一下|调整|完善|润色|排版|措辞|替换|删除|删掉|移除|去掉|清理|整理|调试|重构|维护|排查|报错|出错|崩溃|优化|审查|review|fix|debug|refactor|maintain|repair|broken|break|为什么|异常|故障|迁移|升级|兼容|edit|modify|tweak|adjust|update|polish|rename|delete|remove|cleanup)/gi
42
+
43
+ function countHits(regex, text) {
44
+ return [...String(text || '').matchAll(regex)].length
45
+ }
46
+
47
+ /** Classify a task text: clear keyword evidence picks spec/react; ambiguous
48
+ * or unmatched text returns 'weak' (the model decides per task). */
49
+ export function classifyTask(text) {
50
+ const react = countHits(REACT_RE, text)
51
+ const spec = countHits(SPEC_RE, text)
52
+ if (react > spec) return 'react'
53
+ if (spec > react) return 'spec'
54
+ return 'weak'
55
+ }
56
+
57
+ /** Unwrap the text of a durable user/message event (defensive shapes). */
58
+ export function extractText(data) {
59
+ if (!data) return ''
60
+ const payload = data && typeof data.message === 'object' && data.message !== null ? data.message : data
61
+ const content = Array.isArray(payload.content) ? payload.content : []
62
+ return content.map((c) => (typeof c === 'string' ? c : (c && c.text) || '')).join(' ')
63
+ }
64
+
65
+ /** Per-session mode derived from durable events (resume-safe). */
66
+ export function sessionMode(session) {
67
+ if (!session || !Array.isArray(session.events)) return 'weak'
68
+ const userMsg = session.events.find((event) => event && event.type === 'user/message')
69
+ return classifyTask(extractText(userMsg && userMsg.data))
70
+ }
71
+
72
+ /* ── personas ────────────────────────────────────────────────────────────── */
73
+
74
+ const PERSONA_SPEC = 'You are a helpful software engineer assistant.'
75
+
76
+ const PERSONA_REACT =
77
+ 'You are a hands-on software engineer who delivers working output fast.\n'
78
+ + 'Work directly: write or edit code, then verify it by reading and running. '
79
+ + 'Keep the loop tight — produce, verify, fix — and do not build test '
80
+ + 'harnesses, scaffolding, or ceremony the user did not ask for. '
81
+ + 'Finish with a usable deliverable and a short summary.'
82
+
83
+ /** Pro optimum (router-standard P11/P24): spec sentence + classify
84
+ * instruction, NO anchors. */
85
+ const PERSONA_WEAK_PRO =
86
+ 'You are a helpful software engineer assistant.\n'
87
+ + 'Before acting, decide the task type (build or fix) and adopt the matching '
88
+ + 'style: build → hands-on production; fix → inspect-and-plan.'
89
+
90
+ /** Flash optimum (router-standard P11/P23): neutral + classify + anchors. */
91
+ const PERSONA_WEAK_FLASH =
92
+ 'You are a helpful assistant.\n'
93
+ + 'Before acting, decide the task type (build or fix) and adopt the matching '
94
+ + 'style: build → hands-on production; fix → inspect-and-plan.\n'
95
+ + 'Before acting, briefly review what you have already done in this session '
96
+ + 'and continue from where you left off; do not repeat completed steps. '
97
+ + 'Do not run environment checks (echo, whoami, uname, node --version, date) '
98
+ + 'or exhaustive grep/glob scans.'
99
+
100
+ function isFlashModel(modelId) {
101
+ return typeof modelId === 'string' && /flash/i.test(modelId)
102
+ }
103
+
104
+ /** Persona for a mode; weak picks the model-specific internal-routing text. */
105
+ export function personaFor(mode, modelId) {
106
+ if (mode === 'react') return PERSONA_REACT
107
+ if (mode === 'spec') return PERSONA_SPEC
108
+ return isFlashModel(modelId) ? PERSONA_WEAK_FLASH : PERSONA_WEAK_PRO
109
+ }
110
+
111
+ /* ── first-turn core tools (shell added dynamically) ─────────────────────── */
112
+
113
+ /** Bootstrap catalogs per mode. `glob`/`grep` are deliberately absent
114
+ * (xiaobright boundary probes); edit/write are anchor-safe. */
115
+ export function coreFor(mode, shell) {
116
+ const common = [shell, 'read']
117
+ if (mode === 'spec') return [...common, 'apply_patch']
118
+ if (mode === 'react') return [...common, 'apply_patch']
119
+ return common // weak: conservative minimal anchor
120
+ }
121
+
122
+ /* ── prompt-section helpers ──────────────────────────────────────────────── */
123
+
124
+ /** Replace only the persona section, keeping everything else (plan-mode
125
+ * above all, which returns after promotion). */
126
+ export function applyPersona(sections, personaText) {
127
+ const rest = (sections || []).filter(
128
+ (section) => !section || (section.name !== 'persona' && !/persona/i.test(section.name) && section.name !== 'tool:edit' && section.name !== 'tool:write'),
129
+ )
130
+ return [{ name: 'anchored-persona', text: personaText, order: 0 }, ...rest]
131
+ }
132
+
133
+ /* ── plugin ──────────────────────────────────────────────────────────────── */
134
+
135
+ export function apply(ctx, config = {}) {
136
+ /** Sessions already promoted in this process. Promotion is append-only. */
137
+ const promoted = new Set()
138
+ /** Per-session resolved mode (append-only across the process lifetime). */
139
+ const modes = new Map()
140
+ /** First REAL user message text per session, captured from agent/pre-step
141
+ * (the in-memory session.events array may not contain the first
142
+ * user/message yet when the FIRST assembly runs — measured on rc.6). */
143
+ const firstTexts = new Map()
144
+ let warned = false
145
+ const warnOnce = (message) => {
146
+ if (warned) return
147
+ warned = true
148
+ try {
149
+ if (ctx.logger && typeof ctx.logger.warn === 'function') ctx.logger.warn(message)
150
+ } catch {
151
+ // Logger unavailable — the guard exists only to avoid spamming.
152
+ }
153
+ }
154
+
155
+ const messageText = (message) => {
156
+ if (!message) return ''
157
+ const content = Array.isArray(message.content) ? message.content : []
158
+ return content.map((c) => (typeof c === 'string' ? c : (c && c.text) || '')).join(' ')
159
+ }
160
+
161
+ /** Capture the first real user message of each session from the EARLIEST
162
+ * durable point — agent/inbox/inserted — which fires when the message
163
+ * enters the inbox, strictly before any prompt assembly. (Measured on
164
+ * rc.6: the FIRST assembly of a fresh session runs BEFORE agent/pre-step,
165
+ * so pre-step is too late for the first request.) */
166
+ ctx.on('agent/inbox/inserted', ({ agent, message }) => {
167
+ try {
168
+ const session = agent && agent.session
169
+ if (!session || firstTexts.has(session.id)) return
170
+ if (!message || !message.source || message.source.kind !== 'user') return
171
+ const text = messageText(message)
172
+ if (text.trim()) firstTexts.set(session.id, text)
173
+ } catch {
174
+ // Observation only.
175
+ }
176
+ })
177
+
178
+ /** Fallback capture point for sessions that never saw inbox/inserted. */
179
+ ctx.on('agent/pre-step', async (payload, next) => {
180
+ const decision = await next()
181
+ try {
182
+ const session = payload && payload.agent && payload.agent.session
183
+ if (!session || firstTexts.has(session.id)) return decision
184
+ const messages = Array.isArray(payload.messages) ? payload.messages : []
185
+ const first = messages.find((m) => m && m.source && m.source.kind === 'user')
186
+ if (first === undefined) return decision // system reminders do not classify
187
+ const text = messageText(first)
188
+ if (text.trim()) firstTexts.set(session.id, text)
189
+ } catch {
190
+ // Observation only — never disturb the step pipeline.
191
+ }
192
+ return decision
193
+ })
194
+
195
+ const resolveMode = (session) => {
196
+ if (modes.has(session.id)) return modes.get(session.id)
197
+ const cached = firstTexts.get(session.id)
198
+ const mode = cached !== undefined && cached.trim() !== ''
199
+ ? classifyTask(cached)
200
+ : sessionMode(session)
201
+ modes.set(session.id, mode)
202
+ return mode
203
+ }
204
+
205
+ const isPromoted = (session) => {
206
+ if (promoted.has(session.id)) return true
207
+ if (!Array.isArray(session.events)) return true
208
+ const hit = session.events.some((event) => event && event.type === 'tool/call')
209
+ if (hit) promoted.add(session.id)
210
+ return hit
211
+ }
212
+
213
+ ctx.on('system-prompt/assemble', async (assembly, context, next) => {
214
+ // Downstream errors propagate untouched; only this filter's own logic is guarded.
215
+ const assembled = await next()
216
+ try {
217
+ const agent = context && context.agent
218
+ const session = agent ? agent.session : undefined
219
+ if (session === undefined) return assembled
220
+ const mode = resolveMode(session)
221
+ const modelId = (agent.options && agent.options.model) || ''
222
+ const persona = personaFor(mode, modelId)
223
+
224
+ if (isPromoted(session)) {
225
+ // Promoted: full catalog; persona stays; contexts cleared; the other
226
+ // sections (plan-mode etc.) come back for the rest of the session.
227
+ return {
228
+ ...assembled,
229
+ sections: applyPersona(assembled.sections, persona),
230
+ contexts: [],
231
+ tools: (Array.isArray(assembled.tools) ? assembled.tools : []).filter((tool) => tool && tool.name !== 'edit' && tool.name !== 'write'),
232
+ }
233
+ }
234
+
235
+ const tools = Array.isArray(assembled.tools) ? assembled.tools : []
236
+ const available = new Set(tools.map((tool) => tool && tool.name))
237
+ const shell = available.has('bash') ? 'bash' : available.has('pwsh') ? 'pwsh' : undefined
238
+ if (shell === undefined) {
239
+ warnOnce(`${name}: no platform shell in the catalog — full catalog exposed`)
240
+ return assembled
241
+ }
242
+ const core = new Set(coreFor(mode, shell))
243
+
244
+ // First request: the cleanest possible opening (persona is the only
245
+ // section, contexts cleared — equivalent to a complete persona) plus
246
+ // the task-matched bootstrap catalog.
247
+ return {
248
+ ...assembled,
249
+ sections: [{ name: 'anchored-persona', text: persona, order: 0 }],
250
+ contexts: [],
251
+ tools: tools.filter((tool) => tool && core.has(tool.name)),
252
+ }
253
+ } catch (error) {
254
+ // A filter bug must never brick a session: degrade to the full catalog.
255
+ warnOnce(`${name}: bootstrap filter failed, exposing the full catalog: ${String((error && error.message) || error)}`)
256
+ return assembled
257
+ }
258
+ })
259
+ }