@echo-agent/coding 0.6.0 → 0.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@echo-agent/coding",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Echo's coding agent: file, search, shell and web tools, its own identity and conduct. Installs the `echo-coding` command. Requires Bun.",
@@ -8,9 +8,9 @@
8
8
  "echo-coding": "./bin/echo-coding.ts"
9
9
  },
10
10
  "dependencies": {
11
- "@echo-agent/base": "0.6.0",
12
- "@echo-agent/core": "0.6.0",
13
- "@echo-agent/tui": "0.6.0"
11
+ "@echo-agent/base": "0.7.0",
12
+ "@echo-agent/core": "0.7.0",
13
+ "@echo-agent/tui": "0.7.0"
14
14
  },
15
15
  "devDependencies": {
16
16
  "@types/bun": "latest",
package/src/agent.ts CHANGED
@@ -26,8 +26,8 @@
26
26
 
27
27
  import { DEFAULT_MAX_ITERATIONS, type AssembleContext } from "@echo-agent/core"; // 执行预算的唯一出处(identity 读它)
28
28
  import { definePromptPack, type ExtensionEntry } from "@echo-agent/core/extension";
29
- import type { CredentialStore, PermissionPolicy as CorePermissionPolicy, PromptSection, Skill } from "@echo-agent/core";
30
- import { makeBashTool, makeShellTools } from "./tools/bash.ts";
29
+ import type { CredentialStore, PermissionPolicy as CorePermissionPolicy, PromptSection, Skill, ThinkingLevel } from "@echo-agent/core";
30
+ import { detectShellEnvironment, makeBashTool, makeShellTools } from "./tools/bash.ts";
31
31
  import { makeFsTools } from "./tools/fs.ts";
32
32
  import { makeSearchTools } from "./tools/search.ts";
33
33
  import { makeWebTools } from "./tools/web.ts";
@@ -37,7 +37,10 @@ import { permissionPolicyFor, type PermissionPolicy } from "./permission.ts";
37
37
  import { codingConductSection, codingIdentitySection, shellToolsSection, workspaceToolsSection } from "./prompt.ts";
38
38
 
39
39
  export type CodingPresetOptions = {
40
- /** 权限策略;false = 全放行(评测/CI)。缺省「读随便,动手先问」——没配裁决人时动手会被拒。 */
40
+ /**
41
+ * 权限策略;false = 不装策略、全放行(出厂 echo-coding 就是这一档,见 `cli.ts`)。不给 = `DEFAULT_PERMISSION`
42
+ * (`permission.ts`:bash / write_file / edit_file 先问)——没配裁决人时这三件会被拒。
43
+ */
41
44
  permission?: PermissionPolicy | false;
42
45
  /**
43
46
  * 已经扫好的 skill。**本函数不扫盘**——它是同步的一份配置,读盘是调用方的事
@@ -45,6 +48,8 @@ export type CodingPresetOptions = {
45
48
  */
46
49
  skills?: Skill[];
47
50
  maxIterations?: number;
51
+ /** 思考档位。缺省 {@link CODING_DEFAULT_THINKING};给了就用给的(`"off"` 照样是关)。 */
52
+ thinkingLevel?: ThinkingLevel;
48
53
  /**
49
54
  * 凭据来源:`web_search` 从这里读搜索服务的 key(`brave`),排在环境变量 `BRAVE_API_KEY` 之后。
50
55
  * 不给 = 只认环境变量(评测、低层装配)。宿主给的是与模型 key 同一个 store(`PresetForm.credentials`)。
@@ -65,6 +70,7 @@ export type CodingPreset = {
65
70
  // 自己另定一份「更严格」的类型只会在 spread 进 `createEcho()` 时打架。
66
71
  skills?: Skill[];
67
72
  maxIterations?: number;
73
+ thinkingLevel?: ThinkingLevel;
68
74
  };
69
75
  extensions: readonly ExtensionEntry[];
70
76
  };
@@ -72,6 +78,13 @@ export type CodingPreset = {
72
78
  /** 缺省模型的**唯一**出处:identity 与调用方都读它,不各手抄一份(review 五轮 #3)。 */
73
79
  export const CODING_DEFAULT_MODEL = { provider: "kimi", model: "kimi-k3" } as const;
74
80
 
81
+ /**
82
+ * 缺省思考档(2026-11-03 拍板,`docs/decisions/implemented/2026-11-03-coding-default-thinking-medium.md`):
83
+ * core 新建 agent 缺省 `"off"`,能真关思考的模型(DeepSeek、Kimi K2.6)一起来就不思考,管道形态又没有档位可切。
84
+ * coding 要多步推理,缺省开 medium(codex 的缺省 reasoning effort 也是 medium);各家怎么映射见模型目录的 `thinkingLevelMap`。
85
+ */
86
+ const CODING_DEFAULT_THINKING: ThinkingLevel = "medium";
87
+
75
88
  /** 产品的身份 + 编码纪律,一条 prompt pack。 */
76
89
  const ECHO_CODING_PROMPT = definePromptPack("echo:coding");
77
90
 
@@ -110,9 +123,15 @@ const AGENT_BUILTIN_TOOLS = [
110
123
  // 「这个产品自己带什么」——把容器的选择写进产品身份,换个宿主就对不上了。
111
124
  ] as const;
112
125
 
113
- /** 产品自己出的四段(identity / conduct:coding / tool:workspace / tool:shell),按 order 排。 */
126
+ /**
127
+ * 产品自己出的四段(identity / conduct:coding / tool:workspace / tool:shell),按 order 排。
128
+ * `tool:shell` 末尾那句运行环境与 `echo:shell` 装配时取的是同一个来源(`detectShellEnvironment`),
129
+ * 所以 digest 随机器的平台与 bash 版本变——同一台机器上两次调用仍相等。
130
+ */
114
131
  function productSections(): PromptSection[] {
115
- return [codingIdentitySection(), codingConductSection(), workspaceToolsSection(), shellToolsSection()].sort((a, b) => a.order - b.order);
132
+ return [codingIdentitySection(), codingConductSection(), workspaceToolsSection(), shellToolsSection(detectShellEnvironment())].sort(
133
+ (a, b) => a.order - b.order,
134
+ );
116
135
  }
117
136
 
118
137
  /** digest 用的固定装配上下文:产品四段都不引用变量,所以值无关紧要,只求确定。 */
@@ -159,6 +178,7 @@ export function codingPreset(opts: CodingPresetOptions = {}): CodingPreset {
159
178
  ...(opts.permission !== false ? { permission: permissionPolicyFor(opts.permission) } : {}),
160
179
  ...(opts.skills !== undefined && opts.skills.length > 0 ? { skills: opts.skills } : {}),
161
180
  ...(opts.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),
181
+ thinkingLevel: opts.thinkingLevel ?? CODING_DEFAULT_THINKING,
162
182
  },
163
183
  extensions: [
164
184
  // 产品的身份与编码纪律
package/src/cli.ts CHANGED
@@ -7,11 +7,11 @@
7
7
  // 装配、收摊全在 base 的 `mainFor()` 里,这里一行都不复制;交互形态起哪个壳由本文件挑
8
8
  // (`terminalShell`),装配层不写死。
9
9
  //
10
- // **权限:缺省全放行**(2026-09-01 用户拍板,两种形态都是)。`permission: false` = 不装策略,
10
+ // **权限:出厂的 echo-coding 全放行**(2026-09-01 用户拍板,两种形态都是)。这里传 `permission: false` = 不装策略,
11
11
  // bash / write_file / edit_file 不问直接跑。理由:这是用户自己在自己的仓库里开的 coding agent,
12
- // 每一步都问只会让人按到麻木;管道形态更是没人可问。要「动手先问」的策略仍在
13
- // `permission.ts`(`DEFAULT_PERMISSION` + `responder: "host"`,壳会摆出来问 y/n),
14
- // 评测或别的宿主可以自己传——本产品不缺省开它。
12
+ // 每一步都问只会让人按到麻木;管道形态更是没人可问。
13
+ // `permission.ts` 的 `DEFAULT_PERMISSION`(三件先问的黑名单)**不是这条命令的行为**:它只在嵌入方调 `codingPreset()`
14
+ // 而不传 `permission` 时生效(评测、别的宿主);要在交互壳里问 y/n,再给 `responder: "host"`。
15
15
 
16
16
  import { readFileSync } from "node:fs";
17
17
  import { conductEntry, mainFor, retainRecentDays, type Product } from "@echo-agent/base";
package/src/extensions.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  // 复制一份实现就是复制一份将来会漏修的地方。
13
13
 
14
14
  import { AgentBackgroundService, AgentPrompt, AgentRuntimeService, AgentTools, defineExtension, defineToolPack, registerAll } from "@echo-agent/core/extension";
15
- import { makeShellTools } from "./tools/bash.ts";
15
+ import { detectShellEnvironment, makeShellTools } from "./tools/bash.ts";
16
16
  import { makeWorktreeTools } from "./tools/worktree.ts";
17
17
  import { shellToolsSection } from "./prompt.ts";
18
18
 
@@ -79,12 +79,14 @@ export const ECHO_SHELL = defineExtension({
79
79
  const prompt = ctx.get(AgentPrompt);
80
80
  // bash + job_output / job_stop:同一张后台任务表(`agent.background`),一起装、一起撤
81
81
  const tools = makeShellTools({ background: ctx.get(AgentBackgroundService) });
82
+ // 运行环境(平台、bash 版本)装配时取一次,写进段里;不是每轮现问
83
+ const section = shellToolsSection(detectShellEnvironment());
82
84
  void ctx.effect({
83
85
  // 与 `defineToolPack` 同一档:工具面每轮都可能变,声明得比实际需要强会挡住热重载
84
86
  boundary: "turn",
85
87
  // 工具与它们的习惯段(`tool:shell`)同一个 effect:一起装、一起撤。
86
88
  // 中途撞名要把已注册的撤回去——半组工具在、半组不在,比整组不在更难排查(`registerAll`,与内建同一份)
87
- start: () => registerAll([...tools.map((tool) => () => registry.register(tool)), () => prompt.section(shellToolsSection())]),
89
+ start: () => registerAll([...tools.map((tool) => () => registry.register(tool)), () => prompt.section(section)]),
88
90
  });
89
91
  },
90
92
  });
package/src/permission.ts CHANGED
@@ -36,7 +36,11 @@ export type PermissionPolicy = {
36
36
  };
37
37
 
38
38
  /**
39
- * 缺省策略:读随便;**bash / write_file / edit_file 先问**,其余放行——与 Claude Code 的缺省一个精神。
39
+ * `codingPreset()` 的缺省策略:读随便;**bash / write_file / edit_file 先问**,其余放行——与 Claude Code 的缺省一个精神。
40
+ *
41
+ * **适用范围**:只在嵌入方调 `codingPreset()` 而不传 `permission` 时生效(评测、别的宿主)。出厂的 `echo-coding`
42
+ * 命令不用它——`cli.ts` 的 `ECHO_CODING` 传 `permission: false`,全放行(2026-09-01 用户拍板,理由写在那里)。
43
+ *
40
44
  * 这是一张黑名单而不是白名单(2026-09-09 拍板,`docs/decisions/implemented/2026-09-09-default-permission-blacklist.md`):
41
45
  * 「其余」里也有动东西的,各有各的不问的理由——worktree_enter 开的是新分支与新目录,可逆;worktree_exit 的删除
42
46
  * 由 git 自己挡(有未提交改动就拒,分支保留);web_fetch / web_search 出网不问(2026-09-03 拍板);core 内建的
package/src/prompt.ts CHANGED
@@ -4,10 +4,12 @@
4
4
  // 由拥有这些工具的 extension(`echo:workspace` / `echo:shell`)注册:工具在段在,工具卸段走
5
5
  // 单工具的语义(参数、上限)只在各工具的 description;这里只写 description 装不下的「几个工具怎么选」。
6
6
  // 文本是模型逐字读的资产,全英文;改动这里 = 改被测行为(`codingAgentIdentity()` 的 digest 会变)。
7
- // `tool:shell` 里的 120 s、`background: true`、非零退出码走 error,都是 `tools/bash.ts` 的**真实行为**——
8
- // 行为变了这段跟着改,不许两边说的不一样。
7
+ // `tool:shell` 里的 120 s、`background: true`、非零退出码走 error、没有 TTY 且 stdin 已关、git 的编辑器与分页器关掉、
8
+ // `&` 起的后台进程在主进程退出后不再收输出,都是 `tools/bash.ts` 的**真实行为**——行为变了这段跟着改,不许两边说的不一样。
9
+ // 段末那句运行环境(平台、bash 版本)由 `echo:shell` 装配时取一次(`detectShellEnvironment`),不是每轮现问。
9
10
 
10
11
  import { PROMPT_ORDER, type PromptSection } from "@echo-agent/core";
12
+ import type { ShellEnvironment } from "./tools/bash.ts";
11
13
 
12
14
  export const CODING_IDENTITY =
13
15
  "You are Echo Coding, a coding agent working inside the user's repository. You read, change, and verify code on the user's behalf, and you work for one user across many sessions.";
@@ -18,13 +20,32 @@ export const CODING_CONDUCT = `# Working in code
18
20
  - Change only what the task requires. No drive-by refactors, no speculative abstractions, no compatibility shims for code you can simply change.
19
21
  - A change is done when you have run the checks that prove it: the tests, the type check, or the command the user relies on. If you could not run them, say so.
20
22
  - Do not commit, push, or publish unless the user asks.
23
+ - Uncommitted changes may be the user's own work in progress. Run \`git status\` before any git command that rewrites the working tree or history, and never throw away changes you did not make: no \`git reset --hard\`, \`git checkout -- .\`, \`git restore .\`, \`git clean -f\`, \`git stash drop\` or \`git push --force\` unless the user asks for exactly that.
21
24
  - Add a comment only for a constraint the code cannot show; do not restate the code.`;
22
25
 
23
26
  export const WORKSPACE_TOOLS = `# Files
24
- The six file tools (read_file, write_file, edit_file, list_dir, glob, grep) are confined to the workspace: relative paths resolve from its root, and a path that leads outside it, directly or through a symlink, is refused. bash is not confined. See a directory's entries with list_dir, find files with glob, and search contents with grep (a directory or a single file) rather than running ls, find or rg through bash. edit_file and write_file refuse a file you have not read with read_file in this session, or that changed on disk since you read it: read it (again) first. Change an existing file with edit_file (exact, unique match; replace_all for a rename); use write_file only to create a file or rewrite it entirely.`;
27
+ The six file tools (read_file, write_file, edit_file, list_dir, glob, grep) are confined to the workspace: relative paths resolve from its root, and a path that leads outside it, directly or through a symlink, is refused. bash is not confined. See a directory's entries with list_dir, find files with glob, and search contents with grep (a directory or a single file) rather than running ls, find or rg through bash. When several reads or searches do not depend on each other's results, make those calls together in one reply: read_file, list_dir, glob and grep run in parallel. edit_file and write_file refuse a file you have not read with read_file in this session, or that changed on disk since you read it: read it (again) first. Change an existing file with edit_file (exact, unique match; replace_all for a rename); use write_file only to create a file or rewrite it entirely.`;
25
28
 
26
29
  export const SHELL_TOOLS = `# Shell
27
- The working directory carries over between bash calls (it starts at the workspace root and cd persists; the reply tells you when it changed); shell variables and functions do not, so set them in the same call that uses them. Commands time out after 120 s by default; for long-running processes (servers, watchers) pass background: true and keep working — read the job's output with job_output, stop it with job_stop, and you are notified when it ends. A non-zero exit code comes back as an error with the output; read it before deciding the command worked. Today's date is not in your context; run \`date\` when it matters.`;
30
+ Use bash to run programs: builds, tests, git, package managers, scripts. Read, change and search files in the workspace with read_file, edit_file / write_file, grep and glob, not with cat, head, sed, awk, echo, a heredoc redirected into a file, find or rg: a shell write skips the check that you have read the current version of the file. Commands run without a terminal and stdin is closed, so anything that prompts or opens an editor fails or hangs: pass non-interactive flags (git commit -m, --yes, --no-edit); git's editor and pager are turned off. The working directory carries over between bash calls (it starts at the workspace root and cd persists; the reply tells you when it changed); shell variables and functions do not, so set them in the same call that uses them. Commands time out after 120 s by default; for long-running processes (servers, watchers) pass background: true and keep working — read the job's output with job_output, stop it with job_stop, and you are notified when it ends. Do not start them with a trailing &: the call returns once the command itself exits, and whatever the process prints after that is lost. A non-zero exit code comes back as an error with the output; read it before deciding the command worked. Today's date is not in your context; run \`date\` when it matters.`;
31
+
32
+ /** 段末那句运行环境。macOS 上最常踩的是 BSD 工具链与系统自带的 bash 3.2,点名说。 */
33
+ export function shellEnvironmentText(env: ShellEnvironment): string {
34
+ const bash = env.bashVersion === null ? "bash" : `bash ${env.bashVersion}`;
35
+ const old =
36
+ env.bashVersion !== null && Number.parseInt(env.bashVersion, 10) < 4
37
+ ? " bash 3 has no `mapfile` / `readarray`, no associative arrays and no `${var,,}` case conversion."
38
+ : "";
39
+ if (env.platform === "darwin") {
40
+ return (
41
+ `Commands run with ${bash} on macOS. The command-line tools are the BSD versions, not GNU: \`sed -i\` takes a suffix argument ` +
42
+ "(`sed -i '' …`), `grep -P` does not exist, and `date`, `stat`, `find` and `xargs` take BSD flags." +
43
+ old
44
+ );
45
+ }
46
+ if (env.platform === "linux") return `Commands run with ${bash} on Linux (GNU command-line tools).${old}`;
47
+ return `Commands run with ${bash} on ${env.platform}.${old}`;
48
+ }
28
49
 
29
50
  export function codingIdentitySection(): PromptSection {
30
51
  return { name: "identity", order: PROMPT_ORDER.identity, render: () => CODING_IDENTITY };
@@ -38,6 +59,8 @@ export function workspaceToolsSection(): PromptSection {
38
59
  return { name: "tool:workspace", order: PROMPT_ORDER.tools, render: () => WORKSPACE_TOOLS };
39
60
  }
40
61
 
41
- export function shellToolsSection(): PromptSection {
42
- return { name: "tool:shell", order: PROMPT_ORDER.tools + 1, render: () => SHELL_TOOLS };
62
+ /** `env` 由调用方取好传进来(`echo:shell` 装配时 / identity 现取),段本身不跑命令。 */
63
+ export function shellToolsSection(env: ShellEnvironment): PromptSection {
64
+ const text = `${SHELL_TOOLS}\n${shellEnvironmentText(env)}`;
65
+ return { name: "tool:shell", order: PROMPT_ORDER.tools + 1, render: () => text };
43
66
  }
package/src/tools/bash.ts CHANGED
@@ -8,10 +8,29 @@
8
8
  // 结果「以后作为通知送达」,模型中途看不到输出、也停不掉——「跑起来看日志再改」这条最常见的循环走不通。
9
9
 
10
10
  import { getBackground, killBackground, listBackground, startBackground } from "@echo-agent/core/background";
11
- import { spawn, type ChildProcess } from "node:child_process";
11
+ import { spawn, spawnSync, type ChildProcess } from "node:child_process";
12
12
  import { existsSync } from "node:fs";
13
13
  import { toolError, toolOk, type AgentBackground, type AgentToolResult, type ModelTool } from "@echo-agent/core";
14
14
 
15
+ /** 命令跑在什么环境里:`tool:shell` 段据此写明平台与 bash 版本(macOS 的 BSD 工具链、bash 3.2 的缺口)。 */
16
+ export type ShellEnvironment = { platform: NodeJS.Platform; bashVersion: string | null };
17
+
18
+ /**
19
+ * 取一次运行环境:平台读 `process.platform`,bash 版本问一次 `bash` 自己(`$BASH_VERSION` 去掉括号后缀)。
20
+ * 装配时调(`echo:shell` 的 apply),不是每轮——段在 run 之间不变,前缀缓存才接得上。问不出来版本 = null。
21
+ */
22
+ export function detectShellEnvironment(): ShellEnvironment {
23
+ let bashVersion: string | null = null;
24
+ try {
25
+ const r = spawnSync("bash", ["-c", 'printf %s "$BASH_VERSION"'], { encoding: "utf8", timeout: 2_000, stdio: ["ignore", "pipe", "ignore"] });
26
+ const v = /^\d+(\.\d+)*/.exec(r.stdout ?? "")?.[0];
27
+ if (r.status === 0 && v !== undefined) bashVersion = v;
28
+ } catch {
29
+ // 没有 bash:段里只写平台
30
+ }
31
+ return { platform: process.platform, bashVersion };
32
+ }
33
+
15
34
  /**
16
35
  * 前台命令最多收这么多字符(2026-11-02):不再在这里截到 30,000 丢掉后半——报错多在末尾。
17
36
  * 收全了交给 core:超过内联上限时全文外存、对话里只留头尾预览(`@echo-agent/core` 的工具结果外存)。
@@ -25,10 +44,37 @@ const JOB_TAIL_DEFAULT = 4_000;
25
44
  /**
26
45
  * 工作目录跨调用保留(2026-09-03,照 Claude Code:cd 保留、shell 变量不保留)。
27
46
  * 每次前台命令包一层——命令跑完打印 `$PWD` 标记再以原退出码退出;解析到的目录就是下一次的起点(后台命令也从那里起)。
28
- * 标记用 RS(0x1e)包着,普通输出里不会出现;它只在末尾几百字节里找,输出再长也截不掉它。
47
+ * 标记用 RS(0x1e)包着,普通输出里不会出现。找**最后一个**标记、不要求它在末尾:`cmd &` 起的后台进程可能在标记之后
48
+ * 还写了几行。正文被截断时标记在截断点之后,另在末尾几百字节里留了一份。
29
49
  */
30
50
  const CWD_TAIL_KEEP = 512;
31
- const CWD_MARK_RE = /\u001e__ECHO_CWD__([^\u001e]*)\u001e\n?$/;
51
+ const CWD_MARK = "\u001e__ECHO_CWD__";
52
+
53
+ /**
54
+ * 主 shell 退出之后等输出管道关的时间:管道里剩下的输出读完就关(通常几毫秒);关不上说明命令起的后台进程
55
+ * (`cmd &`)还攥着它——那就不等了,收尾返回已有输出并说明,后台进程不杀。窗口在有输出到达时顺延(主进程退出前
56
+ * 写进管道的最后一截还在路上),但总共不超过 `DRAIN_MAX_MS`,一直在写的后台进程拖不住这一次调用。
57
+ */
58
+ // 500 而不是 100(2026-11-09):慢机器上起一个子进程就要一两百毫秒(macOS CI 实测 `(sleep 0.02; echo late) &` 的输出
59
+ // 连着两次赶不上 100 ms),刚起的后台子进程写完的那几行会被当成「攥着输出」丢掉。只有留了后台进程的那次调用多等,封顶仍是 DRAIN_MAX_MS
60
+ const DRAIN_IDLE_MS = 500;
61
+ const DRAIN_MAX_MS = 1_000;
62
+
63
+ /**
64
+ * 子进程的环境:继承父进程(`bash -c`,不读 profile),再关掉会等人的东西——没有 TTY、stdin 已关,
65
+ * 编辑器 / 分页器 / 凭据提示只会挂到超时、什么也不输出。取舍照 codex 给子进程设的非交互变量:
66
+ * - `GIT_EDITOR=true`:commit / merge / rebase --continue 不开编辑器——带着现成的消息走,没有消息就因空消息中止;
67
+ * - `GIT_PAGER` / `PAGER` / `GH_PAGER` = `cat`:输出直接出来,不进分页器;
68
+ * - `GIT_TERMINAL_PROMPT=0`:要账号密码时直接失败,不等输入。
69
+ * `EDITOR` / `VISUAL` 不动:git 先认 `GIT_EDITOR`,别的程序要编辑器时失败比被换成 `true` 静默「编辑成功」更好懂。
70
+ */
71
+ const NON_INTERACTIVE_ENV = {
72
+ GIT_EDITOR: "true",
73
+ GIT_PAGER: "cat",
74
+ PAGER: "cat",
75
+ GH_PAGER: "cat",
76
+ GIT_TERMINAL_PROMPT: "0",
77
+ } as const;
32
78
 
33
79
  export type BashDeps = {
34
80
  /** 给了才支持 background: true(接 agent.background);job_output / job_stop 也读同一张表。 */
@@ -68,10 +114,13 @@ export function makeBashTool(
68
114
  name: "bash",
69
115
  label: "跑命令",
70
116
  description:
71
- "Run one bash command and return stdout and stderr (merged). The working directory carries over between calls " +
72
- "(it starts at the workspace root; cd persists), shell variables and functions do not. " +
117
+ "Run one bash command (bash -c, not a login shell; it inherits this process's environment) and return stdout and stderr (merged). " +
118
+ "There is no terminal and stdin is closed: use non-interactive flags (git commit -m, --yes); git's editor and pager are turned off. " +
119
+ "The working directory carries over between calls (it starts at the workspace root; cd persists), shell variables and functions do not. " +
73
120
  "Times out after 120 s by default; for long-running work (dev servers, watchers) pass background: true — " +
74
- "read its output with job_output, stop it with job_stop, and you are notified when it ends.",
121
+ "read its output with job_output, stop it with job_stop, and you are notified when it ends. Do not use a trailing & for that: " +
122
+ "the call returns once the command exits and the background process's later output is lost. " +
123
+ "For files in the workspace use read_file, edit_file / write_file, grep and glob instead of cat, sed, echo >, find or rg.",
75
124
  parameters: {
76
125
  type: "object",
77
126
  properties: {
@@ -137,9 +186,33 @@ function withCwdMarker(command: string): string {
137
186
  /**
138
187
  * 起 shell 时自成一个进程组(detached):杀的时候按组杀({@link killTree})。
139
188
  * 不然 `sleep 10`、dev server 这类由 bash 再起的子进程会活过 bash,攥着输出管道不放——超时/中止要等它自己结束,job_stop 也留孤儿。
189
+ *
190
+ * `bash -c`,不是登录 shell:登录 shell 会读 profile,macOS 上 `path_helper` 还会把系统目录排到 PATH 前面,
191
+ * 用户装的 git / ruby / node 就变成了系统那一份。命令看到的环境与启动 echo-coding 的那个 shell 一致。
192
+ * `PWD` 例外,设成本次的起点:继承来的是父进程的目录,bash 发现它不指向当前目录就改用物理路径——
193
+ * 工作区经软链时(macOS 的 `/var` → `/private/var`)`$PWD` 成了展开后的路径,第一条命令就被当成「cd 过了」。
140
194
  */
141
195
  function spawnShell(command: string, cwd: string): ChildProcess {
142
- return spawn("bash", ["-lc", command], { cwd, stdio: ["ignore", "pipe", "pipe"], detached: true });
196
+ return spawn("bash", ["-c", command], {
197
+ cwd,
198
+ stdio: ["ignore", "pipe", "pipe"],
199
+ detached: true,
200
+ env: { ...process.env, ...NON_INTERACTIVE_ENV, PWD: cwd },
201
+ });
202
+ }
203
+
204
+ /** 输出里摘掉最后一个 cwd 标记(连同它前后各一个换行),返回标记里的目录。没有标记 = 命令没跑到末尾(exec / 被杀 / 语法错)。 */
205
+ function takeCwdMarker(text: string): { cwd?: string; body: string } {
206
+ const at = text.lastIndexOf(CWD_MARK);
207
+ if (at < 0) return { body: text };
208
+ const end = text.indexOf("\u001e", at + CWD_MARK.length);
209
+ if (end < 0) return { body: text };
210
+ const before = text.slice(0, at);
211
+ const after = text.slice(end + 1);
212
+ return {
213
+ cwd: text.slice(at + CWD_MARK.length, end),
214
+ body: (before.endsWith("\n") ? before.slice(0, -1) : before) + (after.startsWith("\n") ? after.slice(1) : after),
215
+ };
143
216
  }
144
217
 
145
218
  function killTree(child: ChildProcess): void {
@@ -228,11 +301,24 @@ function runForeground(
228
301
  }
229
302
  out += chunk;
230
303
  };
304
+ // 主 shell 退出之后的排空窗口(见 `DRAIN_IDLE_MS`):有输出到达就顺延,总长封顶
305
+ let exited = false;
306
+ let exitCode: number | null = null;
307
+ let drainIdle: ReturnType<typeof setTimeout> | undefined;
308
+ let drainMax: ReturnType<typeof setTimeout> | undefined;
309
+ const armDrain = (): void => {
310
+ clearTimeout(drainIdle);
311
+ drainIdle = setTimeout(() => finish(exitCode, { held: true }), DRAIN_IDLE_MS);
312
+ };
231
313
  // 每条流一只流式 decoder:跨 chunk 的多字节字符不再被解成替换符(review 2026-09-07:此前逐块 toString)
232
314
  const outDec = new TextDecoder();
233
315
  const errDec = new TextDecoder();
234
- child.stdout!.on("data", (d: Buffer) => append(outDec.decode(d, { stream: true })));
235
- child.stderr!.on("data", (d: Buffer) => append(errDec.decode(d, { stream: true })));
316
+ const onData = (dec: TextDecoder) => (d: Buffer): void => {
317
+ append(dec.decode(d, { stream: true }));
318
+ if (exited) armDrain();
319
+ };
320
+ child.stdout!.on("data", onData(outDec));
321
+ child.stderr!.on("data", onData(errDec));
236
322
 
237
323
  let timedOut = false;
238
324
  const timer = setTimeout(() => {
@@ -244,20 +330,35 @@ function runForeground(
244
330
  };
245
331
  signal?.addEventListener("abort", onAbort, { once: true });
246
332
 
247
- const finish = (code: number | null, spawnError?: string): void => {
333
+ let settled = false;
334
+ const finish = (code: number | null, how: { spawnError?: string; held?: boolean } = {}): void => {
335
+ if (settled) return;
336
+ settled = true;
248
337
  clearTimeout(timer);
338
+ clearTimeout(drainIdle);
339
+ clearTimeout(drainMax);
249
340
  signal?.removeEventListener("abort", onAbort);
341
+ if (how.held === true) {
342
+ // 后台进程还攥着管道:我们这头不读了。进程本身不杀——它是命令有意起的
343
+ child.stdout?.destroy();
344
+ child.stderr?.destroy();
345
+ }
250
346
  append(outDec.decode()); // 冲残余
251
347
  append(errDec.decode());
252
- // 先把 cwd 标记摘出来(在 tail 里),再从正文里剥掉——正文没被截断时标记就在正文末尾
253
- const marked = CWD_MARK_RE.exec(tail);
254
- const newCwd = marked?.[1];
255
- const body = marked === null ? out : out.replace(CWD_MARK_RE, "").replace(/\n$/, "");
348
+ // cwd 标记:正文里有就从正文摘(连同它前后各一个换行);正文被截断、标记落在截断点之后,就从末尾那份里找
349
+ const taken = takeCwdMarker(out);
350
+ const newCwd = taken.cwd ?? takeCwdMarker(tail).cwd;
351
+ const body = taken.body;
256
352
  let text = body.slice(0, CAPTURE_CAP);
257
353
  if (truncated || body.length > CAPTURE_CAP) text += `\n…[output truncated: over ${CAPTURE_CAP} characters]`;
354
+ if (how.held === true) {
355
+ text +=
356
+ "\n(a background process started by this command is still running and holding the output; what it prints from now on is not captured. " +
357
+ "Use background: true for long-running processes.)";
358
+ }
258
359
  const withCwd = (r: AgentToolResult): AgentToolResult & { cwd?: string } => (newCwd === undefined ? r : { ...r, cwd: newCwd });
259
- if (spawnError !== undefined) {
260
- resolvePromise(toolError(`The command could not start: ${spawnError}`));
360
+ if (how.spawnError !== undefined) {
361
+ resolvePromise(toolError(`The command could not start: ${how.spawnError}`));
261
362
  } else if (timedOut) {
262
363
  resolvePromise(toolError(`Timed out after ${timeoutMs} ms and was killed. Output:\n${text}`));
263
364
  } else if (signal?.aborted === true) {
@@ -269,7 +370,15 @@ function runForeground(
269
370
  resolvePromise(withCwd(toolOk(text === "" ? "(no output)" : text, { exitCode: 0 })));
270
371
  }
271
372
  };
272
- child.on("error", (e) => finish(null, String(e)));
273
- child.on("close", (code) => finish(code));
373
+ child.on("error", (e) => finish(null, { spawnError: String(e) }));
374
+ child.on("exit", (code) => {
375
+ // 命令本身结束了:超时不再适用(剩下的只可能是它起的后台进程),进入排空窗口
376
+ exited = true;
377
+ exitCode = code;
378
+ clearTimeout(timer);
379
+ armDrain();
380
+ drainMax = setTimeout(() => finish(code, { held: true }), DRAIN_MAX_MS);
381
+ });
382
+ child.on("close", (code) => finish(code ?? exitCode));
274
383
  });
275
384
  }