wave-agent-sdk 0.19.8 → 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.
Files changed (95) hide show
  1. package/builtin/plugins/sdd/.wave-plugin/plugin.json +8 -0
  2. package/builtin/plugins/sdd/hooks/hooks.json +14 -0
  3. package/builtin/plugins/sdd/scripts/session-start.js +24 -0
  4. package/builtin/plugins/sdd/scripts/spec-count.js +77 -0
  5. package/builtin/plugins/sdd/skills/specify/SKILL.md +47 -0
  6. package/builtin/plugins/sdd/skills/specify/templates/spec-template.md +47 -0
  7. package/builtin/skills/settings/ENV.md +15 -9
  8. package/builtin/skills/settings/HOOKS.md +27 -2
  9. package/dist/agent.d.ts +1 -0
  10. package/dist/agent.js +26 -12
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +1 -0
  13. package/dist/managers/aiManager.d.ts +25 -0
  14. package/dist/managers/aiManager.js +172 -51
  15. package/dist/managers/backgroundTaskManager.d.ts +6 -0
  16. package/dist/managers/backgroundTaskManager.js +11 -0
  17. package/dist/managers/bangManager.d.ts +6 -0
  18. package/dist/managers/bangManager.js +11 -0
  19. package/dist/managers/hookManager.d.ts +8 -2
  20. package/dist/managers/hookManager.js +14 -4
  21. package/dist/managers/mcpManager.d.ts +18 -4
  22. package/dist/managers/mcpManager.js +40 -18
  23. package/dist/managers/permissionManager.d.ts +7 -0
  24. package/dist/managers/permissionManager.js +102 -142
  25. package/dist/managers/pluginManager.d.ts +7 -0
  26. package/dist/managers/pluginManager.js +31 -0
  27. package/dist/managers/toolManager.js +5 -0
  28. package/dist/prompts/index.d.ts +12 -1
  29. package/dist/prompts/index.js +133 -45
  30. package/dist/services/aiService.d.ts +1 -17
  31. package/dist/services/aiService.js +3 -85
  32. package/dist/services/configurationService.d.ts +21 -2
  33. package/dist/services/configurationService.js +72 -23
  34. package/dist/services/initializationService.js +14 -4
  35. package/dist/services/interactionService.js +35 -7
  36. package/dist/services/remoteSettingsService.d.ts +12 -0
  37. package/dist/services/remoteSettingsService.js +15 -1
  38. package/dist/services/session.d.ts +3 -1
  39. package/dist/services/session.js +12 -4
  40. package/dist/services/taskManager.d.ts +1 -0
  41. package/dist/services/taskManager.js +41 -6
  42. package/dist/tools/bashTool.js +1 -0
  43. package/dist/tools/editTool.js +24 -10
  44. package/dist/tools/enterWorktreeTool.js +14 -3
  45. package/dist/tools/exitWorktreeTool.js +11 -10
  46. package/dist/tools/grepTool.js +8 -2
  47. package/dist/tools/types.d.ts +7 -0
  48. package/dist/tools/writeTool.js +36 -0
  49. package/dist/types/config.d.ts +2 -0
  50. package/dist/types/hooks.d.ts +2 -2
  51. package/dist/utils/bashParser.d.ts +25 -0
  52. package/dist/utils/bashParser.js +103 -0
  53. package/dist/utils/configPaths.d.ts +4 -0
  54. package/dist/utils/configPaths.js +6 -0
  55. package/dist/utils/containerSetup.js +1 -1
  56. package/dist/utils/fileSearch.js +4 -2
  57. package/dist/utils/openaiClient.js +2 -1
  58. package/dist/utils/pathEncoder.js +7 -2
  59. package/dist/utils/worktreeUtils.d.ts +17 -0
  60. package/dist/utils/worktreeUtils.js +339 -1
  61. package/package.json +1 -1
  62. package/src/agent.ts +26 -12
  63. package/src/index.ts +1 -0
  64. package/src/managers/aiManager.ts +238 -66
  65. package/src/managers/backgroundTaskManager.ts +15 -0
  66. package/src/managers/bangManager.ts +15 -0
  67. package/src/managers/hookManager.ts +20 -5
  68. package/src/managers/mcpManager.ts +60 -18
  69. package/src/managers/permissionManager.ts +116 -168
  70. package/src/managers/pluginManager.ts +29 -0
  71. package/src/managers/toolManager.ts +7 -0
  72. package/src/prompts/index.ts +144 -37
  73. package/src/services/aiService.ts +9 -128
  74. package/src/services/configurationService.ts +84 -23
  75. package/src/services/initializationService.ts +17 -4
  76. package/src/services/interactionService.ts +49 -6
  77. package/src/services/remoteSettingsService.ts +16 -1
  78. package/src/services/session.ts +18 -4
  79. package/src/services/taskManager.ts +56 -8
  80. package/src/tools/bashTool.ts +1 -0
  81. package/src/tools/editTool.ts +29 -11
  82. package/src/tools/enterWorktreeTool.ts +19 -2
  83. package/src/tools/exitWorktreeTool.ts +15 -12
  84. package/src/tools/grepTool.ts +11 -2
  85. package/src/tools/types.ts +7 -0
  86. package/src/tools/writeTool.ts +43 -0
  87. package/src/types/config.ts +2 -0
  88. package/src/types/hooks.ts +2 -2
  89. package/src/utils/bashParser.ts +106 -0
  90. package/src/utils/configPaths.ts +7 -0
  91. package/src/utils/containerSetup.ts +3 -1
  92. package/src/utils/fileSearch.ts +6 -2
  93. package/src/utils/openaiClient.ts +2 -0
  94. package/src/utils/pathEncoder.ts +7 -2
  95. package/src/utils/worktreeUtils.ts +401 -1
@@ -0,0 +1,8 @@
1
+ {
2
+ "name": "sdd",
3
+ "description": "Spec-first workflow: specify skill, SessionStart guidance, and spec-count validation.",
4
+ "version": "1.0.0",
5
+ "author": {
6
+ "name": "Wave Team"
7
+ }
8
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "node \"${WAVE_PLUGIN_ROOT}/scripts/session-start.js\""
9
+ }
10
+ ]
11
+ }
12
+ ]
13
+ }
14
+ }
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart hook for the sdd built-in plugin.
3
+ // Emits the spec-first workflow guidance as additionalContext (JSON form),
4
+ // resolving the absolute path to the plugin's spec-count validator so the
5
+ // agent can run it from its bash tool (which does not carry WAVE_PLUGIN_ROOT).
6
+ import path from "node:path";
7
+
8
+ const root =
9
+ process.env.WAVE_PLUGIN_ROOT ||
10
+ path.dirname(new URL("..", import.meta.url).pathname);
11
+ const specCount = `node ${JSON.stringify(path.join(root, "scripts", "spec-count.js"))}`;
12
+
13
+ const guidance = [
14
+ "Spec-First Workflow(规格优先工作流):",
15
+ "- 需求增加或变更时,优先更新 spec:先更新对应规格说明(新增用户故事、验收场景),待用户确认 spec 后再实现代码。spec 是功能设计的权威来源,不是 changelog。",
16
+ "- 边界模糊时也先写 spec 草稿请用户确认,不要直接改代码。",
17
+ "- 规格编写技能(specify)由 AI 自动触发:对话中涉及新需求或需求变更时主动创建或更新规格文件,不需要用户手动调用(不出现在斜杠命令列表中)。",
18
+ `- 新增或修改 spec 后运行校验:${specCount}(自动检测 docs/specs/,否则 specs/,否则退出)。`,
19
+ ].join("\n");
20
+
21
+ // JSON form → parsed as hookSpecificOutput.additionalContext by the hook manager.
22
+ console.log(
23
+ JSON.stringify({ hookSpecificOutput: { additionalContext: guidance } }),
24
+ );
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ // Generic, self-contained spec validator. Counts user stories and acceptance
3
+ // scenarios under the project's specs directory and warns on missing sections.
4
+ // Detects the specs dir: prefers docs/specs/, else specs/, else exits gracefully.
5
+ // No dependency on any project's VitePress/docs-site modules.
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+
9
+ function detectSpecsDir() {
10
+ for (const dir of ["docs/specs", "specs"]) {
11
+ const resolved = path.resolve(process.cwd(), dir);
12
+ if (fs.existsSync(resolved)) return resolved;
13
+ }
14
+ return null;
15
+ }
16
+
17
+ function walk(dir, out = []) {
18
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
19
+ const fullPath = path.join(dir, entry.name);
20
+ if (entry.isDirectory()) walk(fullPath, out);
21
+ else if (entry.isFile() && entry.name.endsWith(".md")) out.push(fullPath);
22
+ }
23
+ return out;
24
+ }
25
+
26
+ function countUserStories(content) {
27
+ const m = content.match(/^### 用户故事[::]/gm);
28
+ return m ? m.length : 0;
29
+ }
30
+
31
+ function countAcceptanceScenarios(content) {
32
+ const m = content.match(/^\d+\.\s+\*\*假设\*\*/gm);
33
+ return m ? m.length : 0;
34
+ }
35
+
36
+ const specsDir = detectSpecsDir();
37
+ if (!specsDir) {
38
+ console.log("未找到规格目录(docs/specs/ 或 specs/),跳过校验。");
39
+ process.exit(0);
40
+ }
41
+
42
+ const files = walk(specsDir).sort();
43
+ const totals = { specs: 0, us: 0, ac: 0 };
44
+ const warnings = [];
45
+
46
+ // index.md is conventionally a directory listing page, not a spec — skip it.
47
+ const specFiles = files.filter(
48
+ (fp) => path.basename(fp).toLowerCase() !== "index.md",
49
+ );
50
+
51
+ for (const fp of specFiles) {
52
+ const content = fs.readFileSync(fp, "utf-8");
53
+ const usCount = countUserStories(content);
54
+ const acCount = countAcceptanceScenarios(content);
55
+ const rel = path.relative(process.cwd(), fp);
56
+ totals.specs++;
57
+ totals.us += usCount;
58
+ totals.ac += acCount;
59
+ if (!content.match(/^## 用户场景与测试/m))
60
+ warnings.push(`${rel}: 缺少 "## 用户场景与测试" 章节`);
61
+ if (usCount === 0)
62
+ warnings.push(`${rel}: 未找到用户故事(期望 \`### 用户故事:\`)`);
63
+ if (acCount === 0)
64
+ warnings.push(
65
+ `${rel}: 未找到验收场景(期望 \`N. **假设** … **当** … **则** …\`)`,
66
+ );
67
+ console.log(`${rel} 用户故事: ${usCount} 验收场景: ${acCount}`);
68
+ }
69
+
70
+ console.log("---");
71
+ console.log(
72
+ `规格: ${totals.specs} 用户故事: ${totals.us} 验收场景: ${totals.ac}`,
73
+ );
74
+ if (warnings.length) {
75
+ for (const w of warnings) console.warn(`⚠ ${w}`);
76
+ console.warn(`⚠ ${warnings.length} 条模板警告——见上方。`);
77
+ }
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: specify
3
+ description: 根据自然语言描述创建或更新功能规格说明,生成包含用户故事与验收场景的规格文件。
4
+ user-invocable: false
5
+ ---
6
+
7
+ ## 用户输入
8
+
9
+ ```text
10
+ $ARGUMENTS
11
+ ```
12
+
13
+ ## 流程
14
+
15
+ 本技能由 AI 在会话中自动触发(不占用手动斜杠命令)。触发时机:用户提出新的需求、修改需求或涉及功能边界时,若对应规格尚未创建或已过期,则主动创建或更新规格说明。$ARGUMENTS 通常为空——需求描述直接来自对话上下文,不要让用户重复。
16
+
17
+ 根据对话中的功能描述,执行以下步骤:
18
+
19
+ 1. **确定规格文件路径**:
20
+ - **确定规格根目录**:优先复用项目中已有的规格目录——若 `docs/specs/` 存在则用之,否则若 `specs/` 存在则用之,否则默认 `specs/`(并在完成报告中说明所选目录,便于用户纠正)。
21
+ - **选择分组**:若规格目录下已有分组子目录,沿用其既有分组约定;否则默认扁平结构(直接放在规格根目录下)。
22
+ - 根据功能描述生成 2-4 个词的 slug(小写、连字符、保留缩写词),与组内已有文件名不冲突
23
+ - 规格文件路径:`<规格根目录>/<分组>/<slug>.md`(无分组时为 `<规格根目录>/<slug>.md`)
24
+
25
+ 2. **加载模板** `${WAVE_SKILL_DIR}/templates/spec-template.md`,了解必需章节。
26
+
27
+ 3. **编写规格说明**:
28
+ - 解析用户描述,提取关键概念:角色、操作、数据、约束
29
+ - 对于不明确的部分,根据上下文和行业标准做出合理推断
30
+ - 仅在关键决策处标记 `[待澄清:具体问题]`(最多 3 处)
31
+ - 填写 frontmatter(`name` 为功能中文名、`description` 为一句话简述、`order` 为控制组内排序的数字)
32
+ - 填写「用户场景与测试」章节,包含按优先级排序的用户故事(P1、P2、P3...),每个故事以「作为…,我希望…,以便…」描述,附 `**为什么是这个优先级**` 与 `**独立测试**`(不适用的可省略)
33
+ - 为每个用户故事编写可测试的验收场景(**假设** … **当** … **则** …)
34
+ - 写入规格文件,替换所有占位符
35
+
36
+ 4. **如果存在 `[待澄清]` 标记**(最多 3 处):
37
+ - 将每个标记作为问题展示,附带建议答案
38
+ - 等待用户回复后更新规格文件
39
+
40
+ 5. 报告完成,输出规格文件路径。
41
+
42
+ ## 指南
43
+
44
+ - 关注用户**需要什麼**和**为什么**,而非如何实现
45
+ - 不包含实现细节(不涉及技术栈、API、代码结构)
46
+ - 每个验收场景必须可测试、无歧义
47
+ - 删除不适用的可选章节(不要留 "N/A")
@@ -0,0 +1,47 @@
1
+ ---
2
+ name: "[功能名称]"
3
+ description: "[一句话简短描述]"
4
+ order: [数字,控制组内排序]
5
+ ---
6
+
7
+ # 功能规格说明:[功能名称]
8
+
9
+ **创建日期**:[日期]
10
+
11
+ ## 用户场景与测试 *(必填)*
12
+
13
+ ### 用户故事:[简要标题](优先级:P1)
14
+
15
+ 作为[角色],我希望[操作],以便[价值/目的]。
16
+
17
+ **为什么是这个优先级**:[解释其价值以及为何具有此优先级]
18
+
19
+ **独立测试**:[描述如何独立测试——例如,"可以通过 [具体操作] 进行完整测试,并交付 [具体价值]"]
20
+
21
+ **验收场景**:
22
+
23
+ 1. **假设** [初始状态],**当** [操作],**则** [预期结果]
24
+ 2. **假设** [初始状态],**当** [操作],**则** [预期结果]
25
+
26
+ ---
27
+
28
+ ### 用户故事:[简要标题](优先级:P2)
29
+
30
+ 作为[角色],我希望[操作],以便[价值/目的]。
31
+
32
+ **为什么是这个优先级**:[解释其价值以及为何具有此优先级]
33
+
34
+ **独立测试**:[描述如何独立测试]
35
+
36
+ **验收场景**:
37
+
38
+ 1. **假设** [初始状态],**当** [操作],**则** [预期结果]
39
+
40
+ ---
41
+
42
+ [根据需要添加更多用户故事,每个都分配优先级]
43
+
44
+ ### 边界情况
45
+
46
+ - **[问题?]** [答案/处理方式]
47
+ - **[问题?]** [答案/处理方式]
@@ -17,13 +17,13 @@ Environment variables are configured in the `env` field of `settings.json`. It i
17
17
 
18
18
  ## Supported `WAVE_*` Environment Variables
19
19
 
20
- Wave uses several environment variables to control its core functionality.
20
+ Wave uses several environment variables to control its core functionality. Variables marked **OS env only** are read from the OS environment (or constructor / stdio `initialize` params) and are **NOT** read from settings.json `env` — set them in your shell, not in the `env` field.
21
21
 
22
22
  | Variable | Description | Default |
23
23
  | :--- | :--- | :--- |
24
24
  | `WAVE_API_KEY` | API key for the AI gateway. | - |
25
25
  | `WAVE_BASE_URL` | Base URL for the AI gateway. | - |
26
- | `WAVE_SERVER_URL` | Server URL for SSO authentication. | `https://codechat.codewave.163.com` |
26
+ | `WAVE_SERVER_URL` | Server URL for SSO authentication. **OS env only** — set via OS env or `options.serverUrl`; not read from settings.json `env` (avoids a startup 401 race). | `https://codechat.codewave.163.com` |
27
27
  | `WAVE_CUSTOM_HEADERS` | Custom HTTP headers for the AI gateway. Newline-separated `Key: Value` pairs (e.g., `"X-Foo: bar\nAuthorization: Bearer xxx"`). | - |
28
28
  | `WAVE_MODEL` | The primary AI model to use for the agent. | `gemini-3-flash` |
29
29
  | `WAVE_FAST_MODEL` | The fast AI model to use for quick tasks. | `gemini-2.5-flash` |
@@ -32,23 +32,29 @@ Wave uses several environment variables to control its core functionality.
32
32
  | `WAVE_DISABLE_AUTO_MEMORY` | Set to `1` or `true` to disable the auto-memory feature. | `false` |
33
33
  | `WAVE_AUTO_MEMORY_FREQUENCY` | Auto memory update frequency. `1` = every turn, `2` = every 2 turns, etc. | `1` |
34
34
  | `WAVE_TASK_LIST_ID` | Explicitly set the task list ID for the session. | (Session ID) |
35
- | `WAVE_PLUGIN_GIT_TIMEOUT_MS` | Timeout in milliseconds for git operations when installing plugins. | `300000` |
35
+ | `WAVE_PLUGIN_GIT_TIMEOUT_MS` | Timeout in milliseconds for git operations when installing plugins. **OS env only** (infrastructure). | `300000` |
36
36
 
37
37
  ## Configuration Scopes
38
38
 
39
- Environment variables can be set in different scopes, with the following precedence (highest to lowest):
39
+ Environment variables can be set in different scopes. Wave merges scopes from lowest to highest priority and stores the result in the agent's **per-session environment snapshot**. The snapshot takes priority over OS environment variables but is **NOT written to `process.env`** — this keeps multiple sessions in one `wave --stdio` process from polluting each other.
40
+
41
+ Precedence (highest to lowest):
40
42
 
41
43
  1. **Local Scope**: `.wave/settings.local.json` (Local overrides, ignored by git)
42
44
  2. **Project Scope**: `.wave/settings.json` (Project-specific settings, shared via git)
43
45
  3. **User Scope**: `~/.wave/settings.json` (Global settings for all projects)
44
- 4. **System Environment**: Variables set in your shell (e.g., `export WAVE_API_KEY=...`)
46
+ 4. **System Environment**: Variables set in your shell (e.g., `export WAVE_API_KEY=...`). Used as a fallback when a key is absent from the settings snapshot.
47
+
48
+ > Settings `env` shadows (does not mutate) OS env: a key set in both settings.json `env` and the OS environment resolves to the settings value for that session, while the OS value remains untouched and visible to unrelated processes.
45
49
 
46
50
  ## Custom Environment Variables
47
51
 
48
- You can also define custom environment variables in the `env` field. These variables will be available to:
52
+ You can also define custom environment variables in the `env` field. These variables are stored in the session's environment snapshot and will be available to:
53
+
54
+ - **Hooks**: Any shell command executed as a hook will have these variables in its environment (merged on top of OS env).
55
+ - **Tools**: Tools like `Bash` will have access to these variables (merged on top of OS env).
49
56
 
50
- - **Hooks**: Any shell command executed as a hook will have these variables in its environment.
51
- - **Tools**: Tools like `Bash` will have access to these variables.
57
+ In `wave --stdio` mode one process hosts multiple sessions; each session keeps its own snapshot, so sessions with different `env` do not pollute each other (no "last session wins").
52
58
 
53
59
  Example:
54
60
  ```json
@@ -62,7 +68,7 @@ Example:
62
68
 
63
69
  ## Live Reload
64
70
 
65
- Environment variables configured in `settings.json` support **live reload**. When you modify the `env` field in any `settings.json` file (user, project, or local scope), the changes take effect immediately without requiring a Wave session restart.
71
+ Environment variables configured in `settings.json` support **live reload**. When you modify the `env` field in any `settings.json` file (user, project, or local scope), the changes take effect immediately without requiring a Wave session restart — the session's environment snapshot is refreshed and subsequent resolve calls / subprocess spawns use the new values.
66
72
 
67
73
  ## Best Practices
68
74
 
@@ -13,7 +13,7 @@ Wave supports the following hook events:
13
13
  - `Stop`: Triggered when Wave finishes its response cycle (no more tool calls).
14
14
  - `SubagentStop`: Triggered when a subagent finishes its response cycle.
15
15
  - `WorktreeCreate`: Triggered when a new worktree is created.
16
- - `WorktreeRemove`: Triggered when a worktree is removed (e.g., via ExitWorktree with `action: "remove"`). Non-blocking. The hook receives `worktree_path` in the JSON input. Useful for cleanup tasks (e.g., `docker compose -p $(basename "$worktree_path") down`) after worktree deletion.
16
+ - `WorktreeRemove`: Triggered before a worktree is removed (e.g., via ExitWorktree with `action: "remove"`). Non-blocking. Fires **before** the worktree directory is deleted so hooks can still read files inside it. The hook receives `worktree_path` in the JSON input. Useful for cleanup tasks (e.g., `docker compose -p $(basename "$worktree_path") down`).
17
17
  - `CwdChanged`: Triggered when the working directory changes (e.g., entering/exiting a worktree). Non-blocking.
18
18
  - `SessionStart`: Triggered during session initialization. Hooks can inject `additionalContext` and `initialUserMessage` via stdout.
19
19
  - `SessionEnd`: Triggered during agent destruction (fire-and-forget, non-blocking). Useful for cleanup, resource teardown, and analytics.
@@ -79,7 +79,7 @@ Wave provides detailed context to hook processes via `stdin` as a JSON object. T
79
79
  - `user_prompt`: (UserPromptSubmit) The text submitted by the user.
80
80
  - `subagent_type`: (If executed by a subagent) The type of the subagent.
81
81
  - `name`: (WorktreeCreate) The name of the new worktree.
82
- - `worktree_path`: (WorktreeRemove) The absolute path to the removed worktree.
82
+ - `worktree_path`: (WorktreeRemove) The absolute path of the worktree about to be removed. Derive the worktree name with `basename "$worktree_path"`.
83
83
  - `old_cwd`: (CwdChanged) The previous working directory.
84
84
  - `new_cwd`: (CwdChanged) The new working directory.
85
85
  - `compact_instructions`: (PreCompact) Custom instructions for the compaction, if any.
@@ -165,6 +165,31 @@ SessionEnd hooks receive `end_source` in the JSON input indicating how the sessi
165
165
  }
166
166
  ```
167
167
 
168
+ ## WorktreeRemove Hooks
169
+
170
+ `WorktreeRemove` hooks fire **before** the worktree directory is deleted, so they can still read files inside it. They are non-blocking (Notification type): the hook never replaces `git worktree remove` itself. Useful for cleaning up external resources that were provisioned for the worktree (databases, containers, etc.).
171
+
172
+ ### Input
173
+ WorktreeRemove hooks receive `worktree_path` in the JSON input (alongside the common fields `session_id`, `transcript_path`, `cwd`, `hook_event_name`). The worktree name can be derived via `basename "$worktree_path"`.
174
+
175
+ ### Example Configuration
176
+ ```json
177
+ {
178
+ "hooks": {
179
+ "WorktreeRemove": [
180
+ {
181
+ "hooks": [
182
+ {
183
+ "command": "worktree_path=$(jq -r '.worktree_path') && docker compose -p \"$(basename \"$worktree_path\")\" down || true",
184
+ "description": "Tear down the worktree's docker compose project before removal"
185
+ }
186
+ ]
187
+ }
188
+ ]
189
+ }
190
+ }
191
+ ```
192
+
168
193
  ## Live Reload
169
194
 
170
195
  Hook configurations support **live reload**. When you modify hooks in `settings.json`, the changes take effect immediately without restarting Wave.
package/dist/agent.d.ts CHANGED
@@ -24,6 +24,7 @@ export declare class Agent {
24
24
  private reversionManager;
25
25
  private messageQueue;
26
26
  private dispatchPromise;
27
+ private isAborting;
27
28
  private memoryRuleManager;
28
29
  private liveConfigManager;
29
30
  private taskManager;
package/dist/agent.js CHANGED
@@ -14,7 +14,10 @@ import { remoteSettingsService } from "./services/remoteSettingsService.js";
14
14
  export class Agent {
15
15
  // Dynamic configuration getter methods
16
16
  getGatewayConfig() {
17
- return this.configurationService.resolveGatewayConfig();
17
+ return {
18
+ ...this.configurationService.resolveGatewayConfig(),
19
+ sessionId: this.messageManager.getSessionId(),
20
+ };
18
21
  }
19
22
  getModelConfig() {
20
23
  return this.configurationService.resolveModelConfig(undefined, undefined, undefined, this.getPermissionMode());
@@ -52,6 +55,7 @@ export class Agent {
52
55
  constructor(options) {
53
56
  this.bangManager = null;
54
57
  this.dispatchPromise = null; // Track current dispatch for teardown
58
+ this.isAborting = false; // Guard: prevents tryDispatch from firing during abortMessage
55
59
  this.sessionStartTime = Date.now();
56
60
  const { logger, workdir, systemPrompt, stream = true } = options;
57
61
  // Set working directory early as we need it for loading configuration
@@ -278,6 +282,8 @@ export class Agent {
278
282
  * onLoadingChange(false), and onCommandRunningChange(false).
279
283
  */
280
284
  tryDispatch() {
285
+ if (this.isAborting)
286
+ return; // Suppress dispatch during abort to prevent queued notifications from being dispatched as a side-effect
281
287
  if (this.messageQueue.state !== "idle")
282
288
  return;
283
289
  if (!this.messageQueue.hasPending())
@@ -632,17 +638,25 @@ export class Agent {
632
638
  }
633
639
  /** Unified interrupt method, interrupts both AI messages and command execution */
634
640
  abortMessage() {
635
- if (this.aiManager.isLoading || this.isCommandRunning) {
636
- // Clear user-facing queue items first to prevent processQueuedMessage
637
- // from dequeuing when abortAIMessage triggers onLoadingChange(false).
638
- // Notifications are preserved so background task results aren't lost.
639
- this.messageQueue.clear();
640
- this.options.callbacks?.onQueuedMessagesChange?.(this.queuedMessages);
641
+ // Guard: prevent tryDispatch (triggered by abortAIMessage → setIsLoading(false))
642
+ // from dispatching preserved notifications as a new AI turn during the abort.
643
+ this.isAborting = true;
644
+ try {
645
+ if (this.aiManager.isLoading || this.isCommandRunning) {
646
+ // Clear user-facing queue items first to prevent processQueuedMessage
647
+ // from dequeuing when abortAIMessage triggers onLoadingChange(false).
648
+ // Notifications are preserved so background task results aren't lost.
649
+ this.messageQueue.clear();
650
+ this.options.callbacks?.onQueuedMessagesChange?.(this.queuedMessages);
651
+ }
652
+ this.messageQueue.transitionTo("idle"); // Reset state on abort
653
+ this.abortAIMessage(); // This will abort tools including Agent tool (subagents)
654
+ this.abortBashCommand();
655
+ this.abortSlashCommand();
656
+ }
657
+ finally {
658
+ this.isAborting = false;
641
659
  }
642
- this.messageQueue.transitionTo("idle"); // Reset state on abort
643
- this.abortAIMessage(); // This will abort tools including Agent tool (subagents)
644
- this.abortBashCommand();
645
- this.abortSlashCommand();
646
660
  }
647
661
  /** Interrupt bash command execution */
648
662
  abortBashCommand() {
@@ -691,7 +705,7 @@ export class Agent {
691
705
  transcriptPath,
692
706
  cwd: this.workdir,
693
707
  worktreePath,
694
- env: Object.fromEntries(Object.entries(process.env).filter((e) => e[1] !== undefined)),
708
+ env: Object.fromEntries(Object.entries(this.configurationService.getMergedEnv()).filter((e) => e[1] !== undefined)),
695
709
  });
696
710
  // Process results via messageManager (may not be visible during shutdown)
697
711
  this.hookManager.processHookResults("WorktreeRemove", hookResults, this.messageManager);
package/dist/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export * from "./utils/tokenCalculation.js";
22
22
  export * from "./utils/gitUtils.js";
23
23
  export * from "./utils/nameGenerator.js";
24
24
  export * from "./utils/worktreeSession.js";
25
+ export * from "./utils/worktreeUtils.js";
25
26
  export { loadMergedWaveConfig } from "./services/configurationService.js";
26
27
  export * from "./types/index.js";
27
28
  export * from "./tools/buildTool.js";
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ export * from "./utils/tokenCalculation.js";
26
26
  export * from "./utils/gitUtils.js";
27
27
  export * from "./utils/nameGenerator.js";
28
28
  export * from "./utils/worktreeSession.js";
29
+ export * from "./utils/worktreeUtils.js";
29
30
  export { loadMergedWaveConfig } from "./services/configurationService.js";
30
31
  export * from "./types/index.js";
31
32
  // Export tool building utilities
@@ -53,6 +53,14 @@ export declare class AIManager {
53
53
  private get permissionManager();
54
54
  private get planManager();
55
55
  private get configurationService();
56
+ /**
57
+ * OS env merged with the per-session env snapshot. Falls back to process.env
58
+ * when ConfigurationService is absent or its getMergedEnv is missing (e.g. in
59
+ * unit tests with partial mocks), so hook-context env construction never
60
+ * throws. Use this (not the non-null `configurationService` getter) when
61
+ * building hook context env.
62
+ */
63
+ private get mergedEnv();
56
64
  getGatewayConfig(): GatewayConfig;
57
65
  getModelConfig(): ModelConfig;
58
66
  getMaxInputTokens(): number;
@@ -103,6 +111,23 @@ export declare class AIManager {
103
111
  customInstructions?: string;
104
112
  abortSignal?: AbortSignal;
105
113
  }): Promise<void>;
114
+ /**
115
+ * Build the system prompt used by the main agent loop. Extracted so the
116
+ * compaction fork can mirror it exactly — the forked request prefix must
117
+ * match the main conversation's for the prompt cache to be reused.
118
+ */
119
+ private buildMainSystemPrompt;
120
+ private resolveFilteredTools;
121
+ /**
122
+ * Fork-path compaction: run a bounded agent loop over a copy of the
123
+ * conversation using the same system prompt, tools, model, and generation
124
+ * params as the main loop, so the forked request prefix matches exactly
125
+ * and the prompt cache is reused. Tool calls are denied locally (the model
126
+ * is told to summarize, not act) and their rejections are fed back for
127
+ * another turn. Returns undefined content when the model never produces
128
+ * text; the caller treats that as a compaction failure.
129
+ */
130
+ private runCompactFork;
106
131
  /**
107
132
  * Build post-compact context restoration content.
108
133
  * Restores file reads, working directory, plan mode, skills, and background tasks.