@goodandready/dsh-goal 0.1.7 → 0.1.9

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/README.md CHANGED
@@ -11,78 +11,124 @@
11
11
  <a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node-20%2B-f59e0b.svg?style=for-the-badge&labelColor=451a03" alt="Node version"></a>
12
12
  </p>
13
13
 
14
- <!-- Author Showcase Link -->
14
+ <!-- Обязательная кнопка перехода на витрину всех проектов -->
15
15
  <p align="center">
16
- <a href="https://goodandready.app/"><img src="https://img.shields.io/badge/All_Author_Projects-goodandready.app-ff4500.svg?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e" alt="GoodAndReady Showcase"></a>
16
+ <a href="https://goodandready.app/"><img src="https://img.shields.io/badge/Все_проекты_автора-goodandready.app-ff4500.svg?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e" alt="Все проекты автора"></a>
17
17
  </p>
18
18
 
19
19
  <p align="center">
20
20
  <a href="README.md"><b>🇬🇧 English</b></a> •
21
- <a href="docs/README.ru.md"><b>🇷🇺 Русский</b></a>
22
- <a href="docs/README.zh.md"><b>🇨🇳 中文说明</b></a>
21
+ <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
23
22
  </p>
24
23
 
24
+ <!-- Обязательный блок поддержки проекта: локализуй текст под язык README -->
25
+ <table align="center">
26
+ <tr>
27
+ <td align="center">
28
+ ⭐ <strong>If you like this plugin, please star it on GitHub</strong> — it shows me that the plugin is useful to you and motivates me to keep developing it.
29
+ <br><br>
30
+ 🐛 <strong>If you find a bug or would like to request a feature</strong>, open a GitHub issue in any language — I will review your proposal and implement useful suggestions in a future plugin version.
31
+ </td>
32
+ </tr>
33
+ </table>
34
+
25
35
  </div>
26
36
 
27
37
  ---
28
38
 
29
39
  ## ⚡ Overview & The Problem
30
40
 
31
- Complex engineering tasks require multi-step autonomy: decomposing high-level objectives into milestones, executing successive iterations without manual user re-prompting, and maintaining clear visibility into task progress.
41
+ Complex engineering tasks require multi-step autonomy: decomposing high-level objectives into sequential milestones, executing iterations without requiring manual user re-prompting, and maintaining clear visibility into task progress.
42
+
43
+ Without an autonomous tracking framework, agents can lose context across turns, stall in passive loops, or fail to notify users when complex workflows stall.
32
44
 
33
- **`@goodandready/dsh-goal`** brings autonomous goal execution to DeepSeek Harness via the `/goal` command:
34
- * 🎯 **Sticky Top Goal Banner**: Pinned status header with live timer (`• 2s`, `• 1m 45s`), active goal title, and interactive control buttons.
35
- * ⏸️ **Play / Pause / Cancel**: Instantly pause the autonomous loop or resume execution on demand.
36
- * 📋 **Milestone Breakdown Drawer**: Interactive checklist showing sub-tasks, percentage completion, and iteration logs.
37
- * 🤖 **Autonomous Agent Tools**: Provides `goal_set_milestones`, `goal_update_progress`, and `goal_finish` tools directly to the agent.
38
- * 🛡️ **Safety Guardrails**: Configurable `maxIterations` limit to prevent runaway loops.
45
+ **`@goodandready/dsh-goal`** introduces Goal Mode to DeepSeek Harness:
46
+ * 🎯 **Sticky Top Goal Banner**: Pinned header over composer dock with live elapsed timer (`• 2s`, `• 1m 45s`), real-time status badge (`RUNNING`, `PAUSED`, `COMPLETED`), active goal title, and control actions.
47
+ * ⏸️ **Play / Pause / Resume / Cancel**: Instantly pause the autonomous loop or resume execution on demand via buttons or `/goal` command.
48
+ * 📋 **Milestone Breakdown & ETA**: Interactive checklist showing sub-tasks, completion status (`pending`, `in_progress`, `completed`, `failed`), progress bar, and dynamic completion ETA.
49
+ * 🌐 **Multi-Language Auto-Detection (*Added in v0.1.9*)**: Prompt injection, autonomous follow-ups, and UI badges automatically follow the user's input language (English by default, Chinese, or Russian when entered in Cyrillic).
50
+ * 🔘 **Quick Launch Button (*Added in v0.1.8*)**: Fast goal launcher docked above the message input with instant objective prompt modal. Toggleable in settings.
51
+ * 📊 **Token Usage Tracking & Markdown Export (*Added in v0.1.7*)**: Accumulated prompt, completion, and total tokens tracked per session with one-click Markdown summary export.
52
+ * 🤖 **Autonomous Agent Contract**: Provides `goal_set_milestones`, `goal_update_progress`, and `goal_finish` tools directly to the agent.
53
+ * 🛡️ **Safety Guardrails**: Configurable `maxIterations` safety limit and Smart Progress Guard to catch and pause idle turns without progress.
54
+ * 🔔 **Web Audio Chimes**: Pleasant synthesized audio feedback on goal completion or failure via Web Audio API.
39
55
 
40
56
  ---
41
57
 
42
58
  ## 🏛️ Architecture
43
59
 
44
60
  ```mermaid
45
- graph TD
46
- subgraph Input ["User Interaction"]
61
+ graph LR
62
+ subgraph UserInterface ["User Interface & Interaction"]
47
63
  Cmd["Slash Command: /goal &lt;objective&gt;"]
48
- API["REST API: POST /dsh-goal/action"]
64
+ Dock["Sticky Goal Banner (conversation.input.dock)"]
65
+ Modal["Goal Details & Milestone Modal"]
66
+ QuickLaunch["Quick Launch Goal Button"]
49
67
  end
50
68
 
51
- subgraph GoalEngine ["Goal Lifecycle Engine (lib/index.js)"]
69
+ subgraph GoalEngineCore ["Goal Engine Core (lib/goal-engine.js)"]
52
70
  State["State Manager (IDLE, RUNNING, PAUSED, COMPLETED)"]
53
- Milestones["Milestone Tracker & Decomposition"]
54
- Disk["Persistence Store (~/.dsh/goal-state.json)"]
71
+ Milestones["Milestone Tracker & ETA Calculation"]
72
+ DiskStore["Persistence Store (goal-state.json)"]
73
+ LangDetector["detectLanguage (en, zh, ru)"]
55
74
  end
56
75
 
57
- subgraph AgentLoop ["Autonomous Agent Drive"]
76
+ subgraph AutonomousLoop ["Autonomous Drive & Turn Coordinator (lib/index.js)"]
77
+ TurnHook["ctx.on('turn/end') AutoDrive"]
78
+ Guard["Smart Progress Guard & Iteration Limiter"]
79
+ PromptInject["getStatePromptInjection"]
80
+ end
81
+
82
+ subgraph AgentTools ["Cordis Registered Tools"]
58
83
  ToolSet["goal_set_milestones"]
59
84
  ToolProgress["goal_update_progress"]
60
85
  ToolFinish["goal_finish"]
61
- LimitGuard{"maxIterations Guard"}
62
- end
63
-
64
- subgraph UI ["DSH Web Interface"]
65
- Banner["Sticky Top Goal Banner"]
66
- Timer["Live Elapsed Timer"]
67
- Drawer["Milestone Checklist Modal"]
68
- Settings["Settings Card (Schemastery)"]
69
86
  end
70
87
 
71
- Cmd --> GoalEngine
72
- API --> GoalEngine
73
- GoalEngine --> State
74
- State --> Disk
75
- State --> Banner
76
- State --> Drawer
77
- GoalEngine --> AgentLoop
78
- AgentLoop --> LimitGuard
79
- ToolSet --> GoalEngine
80
- ToolProgress --> GoalEngine
81
- ToolFinish --> GoalEngine
88
+ Cmd --> GoalEngineCore
89
+ Dock --> GoalEngineCore
90
+ QuickLaunch --> GoalEngineCore
91
+ GoalEngineCore --> DiskStore
92
+ GoalEngineCore --> AutonomousLoop
93
+ AutonomousLoop --> PromptInject
94
+ GoalEngineCore --> Modal
95
+ AgentTools --> GoalEngineCore
96
+ AutonomousLoop --> Guard
82
97
  ```
83
98
 
84
99
  ---
85
100
 
101
+ ## ✨ Features & Module Breakdown
102
+
103
+ ### 1. `lib/goal-engine.js` — State Engine
104
+ Zero external dependency core managing session goals, milestone states, elapsed time calculations, ETA forecasts, token accumulators, and crash recovery hydration.
105
+ * **Auto Language Detection**: Automatically analyzes goal title and parameters (`detectLanguage`) to select English (`en`), Chinese (`zh`), or Russian (`ru`).
106
+ * **ETA Estimator**: Predicts remaining time based on average milestone velocity:
107
+ $$\text{ETA} = \frac{\text{elapsed}}{\text{completedMilestones}} \times \text{remainingMilestones}$$
108
+ * **Low-Latency State Serialization**: Synchronous debounced atomic file persistence to prevent data loss on crashes.
109
+
110
+ ### 2. `lib/command-handler.js` — Slash Commands
111
+ Handles `/goal` commands and subcommands:
112
+ * `/goal <objective>`: Starts a new autonomous goal.
113
+ * `/goal pause`: Pauses current goal and halts agent turn.
114
+ * `/goal resume`: Resumes execution and triggers agent continuation.
115
+ * `/goal clear`: Resets session goal to IDLE.
116
+ * `/goal`: Shows status, elapsed time, ETA, iterations, tokens, and active milestones.
117
+
118
+ ### 3. `lib/index.js` — DSH Cordis Lifecycle Coordinator
119
+ * Registers REST API endpoints (`GET /dsh-goal/state`, `POST /dsh-goal/action`, `GET /dsh-goal/events` SSE stream).
120
+ * Subscribes to `turn/end` for zero-latency turn-to-turn auto-drive using `setImmediate`.
121
+ * Listens to `approval/asked` to automatically pause goal when operator confirmation is needed.
122
+ * Registers agent tools: `goal_set_milestones`, `goal_update_progress`, `goal_finish`.
123
+
124
+ ### 4. `lib/client.js` — Frontend Web UI
125
+ * **Sticky Top Banner**: Mounts via slot `conversation.input.dock` with live timer, status badge, pause/resume, and details button.
126
+ * **Goal Details Modal**: Full milestone list, progress bar, token statistics, and 📋 Markdown Report Copy.
127
+ * **Quick Launch Button**: Floating launcher for rapid goal formulation without typing slash commands.
128
+ * **Plugin Settings Card**: Schemastery-backed settings UI registered via `settings.plugin.item`.
129
+
130
+ ---
131
+
86
132
  ## 📦 Installation
87
133
 
88
134
  ```bash
@@ -95,42 +141,70 @@ Restart your DeepSeek Harness instance and refresh the browser.
95
141
 
96
142
  ## 💬 Usage & Quick Start
97
143
 
98
- Start a goal directly in chat:
144
+ ### 1. Start a Goal via Chat
145
+ Simply enter the `/goal` slash command:
99
146
 
100
147
  ```text
101
- /goal Refactor the authentication middleware and add integration tests
148
+ /goal Refactor authentication middleware and cover with unit tests
102
149
  ```
103
150
 
104
- Or trigger via REST API:
151
+ The agent will immediately:
152
+ 1. Establish a structured milestone plan via `goal_set_milestones`.
153
+ 2. Advance through milestones, marking each `in_progress` and `completed` via `goal_update_progress`.
154
+ 3. Conclude with a full summary via `goal_finish`.
155
+
156
+ ### 2. Quick Launch Button
157
+ Click the **Start Goal** button directly above the message input box, type your objective, and click **Start Goal**.
158
+
159
+ ### 3. REST API Control
160
+ Control goals programmatically via HTTP:
105
161
 
106
162
  ```bash
163
+ # Start a goal
107
164
  curl -X POST http://localhost:3080/dsh-goal/action \
108
165
  -H "Content-Type: application/json" \
109
- -d '{"action":"start","title":"Optimize database queries"}'
166
+ -d '{"action":"start","title":"Implement automated backup pipeline"}'
167
+
168
+ # Pause
169
+ curl -X POST http://localhost:3080/dsh-goal/action \
170
+ -H "Content-Type: application/json" \
171
+ -d '{"action":"pause"}'
172
+
173
+ # Resume
174
+ curl -X POST http://localhost:3080/dsh-goal/action \
175
+ -H "Content-Type: application/json" \
176
+ -d '{"action":"resume"}'
177
+
178
+ # Inspect live state
179
+ curl http://localhost:3080/dsh-goal/state
110
180
  ```
111
181
 
112
182
  ---
113
183
 
114
184
  ## ⚙️ Configuration Reference (`settings.yaml`)
115
185
 
186
+ Configure settings in `settings.yaml` or through the **Settings → Plugins → Goal Mode** UI card:
187
+
116
188
  ```yaml
117
189
  dsh-goal:
118
190
  maxIterations: 25
119
191
  autoDrive: true
120
192
  enableSound: true
193
+ showQuickLaunchButton: true
121
194
  ```
122
195
 
123
196
  | Parameter | Type | Default | Description |
124
197
  |:---|:---|:---|:---|
125
- | `maxIterations` | `number` | `25` | Safety limit: maximum autonomous iterations per goal |
198
+ | `maxIterations` | `number` | `25` | Safety limit: maximum autonomous turns per goal |
126
199
  | `autoDrive` | `boolean` | `true` | Keep the autonomous agent loop running between turns |
127
- | `enableSound` | `boolean` | `true` | Play completion audio chime when a goal finishes |
200
+ | `enableSound` | `boolean` | `true` | Play audio chime when a goal completes or fails |
201
+ | `showQuickLaunchButton` | `boolean` | `true` | Show the quick launch goal button above the composer dock |
128
202
 
129
203
  ---
130
204
 
131
205
  ## 🧪 Testing
132
206
 
133
- Run the automated test suite:
207
+ Run unit and integration tests:
134
208
 
135
209
  ```bash
136
210
  npm test
package/README.zh.md ADDED
@@ -0,0 +1,217 @@
1
+ # 📦 @goodandready/dsh-goal
2
+
3
+ <div align="center">
4
+
5
+ <h3>DeepSeek Harness 自主目标执行与多轮任务跟踪引擎</h3>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@goodandready/dsh-goal"><img src="https://img.shields.io/npm/v/@goodandready/dsh-goal.svg?style=for-the-badge&color=6366f1&labelColor=1e1b4b" alt="npm version"></a>
9
+ <a href="LICENSE"><img src="https://img.shields.io/github/license/GooDAnDReaDY/dsh-goal.svg?style=for-the-badge&color=10b981&labelColor=064e3b" alt="license"></a>
10
+ <a href="https://github.com/topics/dsh-plugin"><img src="https://img.shields.io/badge/DSH-Plugin-8b5cf6.svg?style=for-the-badge&labelColor=2e1065" alt="DSH Plugin"></a>
11
+ <a href="https://nodejs.org"><img src="https://img.shields.io/badge/Node-20%2B-f59e0b.svg?style=for-the-badge&labelColor=451a03" alt="Node version"></a>
12
+ </p>
13
+
14
+ <!-- Обязательная кнопка перехода на витрину всех проектов -->
15
+ <p align="center">
16
+ <a href="https://goodandready.app/"><img src="https://img.shields.io/badge/Все_проекты_автора-goodandready.app-ff4500.svg?style=for-the-badge&logo=rocket&logoColor=white&labelColor=1a1a2e" alt="Все проекты автора"></a>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <a href="README.md"><b>🇬🇧 English</b></a> •
21
+ <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
22
+ </p>
23
+
24
+ <!-- Обязательный блок поддержки проекта: локализуй текст под язык README -->
25
+ <table align="center">
26
+ <tr>
27
+ <td align="center">
28
+ ⭐ <strong>如果您喜欢这个插件,请在 GitHub 上为它点亮 Star</strong> — 这能让我知道插件对您有用,并鼓励我继续开发和维护它。
29
+ <br><br>
30
+ 🐛 <strong>如果您发现 Bug 或希望增加功能</strong>,请使用任意语言在 GitHub 上提交 Issue — 我会评估您的建议,并在后续版本中实现有价值的改进。
31
+ </td>
32
+ </tr>
33
+ </table>
34
+
35
+ </div>
36
+
37
+ ---
38
+
39
+ ## ⚡ 概述与解决的问题
40
+
41
+ 复杂的工程开发任务需要多步骤的自主推进:将高层目标分解为有序的里程碑、在各轮交互间无需用户重复提示即可持续执行,并保持清晰直观的进度可视化。
42
+
43
+ 如果缺乏目标跟踪框架,智能体容易在多轮对话中丢失上下文、陷入被动等待,或在遇到卡点时无法及时提醒用户。
44
+
45
+ **`@goodandready/dsh-goal`** 为 DeepSeek Harness 带来了完整的目标模式(Goal Mode):
46
+ * 🎯 **输入框上方常驻目标横幅**:顶部常驻状态条,配备实时计时器(`• 2s`、`• 1m 45s`)、状态徽章(`RUNNING`、`PAUSED`、`COMPLETED`)、当前目标名称与控制操作。
47
+ * ⏸️ **播放 / 暂停 / 恢复 / 取消**:可通过按钮或 `/goal` 命令随时暂停自主循环,或在需要时恢复执行。
48
+ * 📋 **里程碑拆解与 ETA 预测**:交互式清单抽屉,展示子任务状态(`pending`、`in_progress`、`completed`、`failed`)、进度百分比与动态预估剩余时间。
49
+ * 🌐 **多语言智能识别(v0.1.9 新增)**:提示词注入、自主轮次追问和 UI 状态徽章自动匹配用户输入语言(默认英语,支持中文和俄语)。
50
+ * 🔘 **快速启动按钮(v0.1.8 新增)**:常驻于输入框上方的启动按钮,支持弹窗一键制定目标,可在设置中自由开关。
51
+ * 📊 **Token 消耗统计与 Markdown 导出(v0.1.7 新增)**:实时累计提示词、生成词及总 Token 消耗,支持一键复制完整 Markdown 报告。
52
+ * 🤖 **智能体自主协作工具**:向智能体直接提供 `goal_set_milestones`、`goal_update_progress` 和 `goal_finish` 工具。
53
+ * 🛡️ **安全防护机制**:支持自定义最大迭代次数(`maxIterations`)以及智能卡顿检测(Smart Progress Guard)。
54
+ * 🔔 **Web Audio 提示音**:任务完成或失败时,通过 Web Audio API 播放舒缓的合成音效。
55
+
56
+ ---
57
+
58
+ ## 🏛️ 架构图
59
+
60
+ ```mermaid
61
+ graph LR
62
+ subgraph UserInterface ["用户界面与交互"]
63
+ Cmd["斜杠命令: /goal &lt;目标&gt;"]
64
+ Dock["常驻目标横幅 (conversation.input.dock)"]
65
+ Modal["目标详情与里程碑弹窗"]
66
+ QuickLaunch["快速启动目标按钮"]
67
+ end
68
+
69
+ subgraph GoalEngineCore ["目标引擎核心 (lib/goal-engine.js)"]
70
+ State["状态管理 (IDLE, RUNNING, PAUSED, COMPLETED)"]
71
+ Milestones["里程碑跟踪与 ETA 计算"]
72
+ DiskStore["状态持久化存储 (goal-state.json)"]
73
+ LangDetector["语言检测器 (en, zh, ru)"]
74
+ end
75
+
76
+ subgraph AutonomousLoop ["自主循环与轮次协调器 (lib/index.js)"]
77
+ TurnHook["ctx.on('turn/end') 自动推进"]
78
+ Guard["卡顿防守与最大迭代限制"]
79
+ PromptInject["getStatePromptInjection 提示词注入"]
80
+ end
81
+
82
+ subgraph AgentTools ["Cordis 注册工具"]
83
+ ToolSet["goal_set_milestones"]
84
+ ToolProgress["goal_update_progress"]
85
+ ToolFinish["goal_finish"]
86
+ end
87
+
88
+ Cmd --> GoalEngineCore
89
+ Dock --> GoalEngineCore
90
+ QuickLaunch --> GoalEngineCore
91
+ GoalEngineCore --> DiskStore
92
+ GoalEngineCore --> AutonomousLoop
93
+ AutonomousLoop --> PromptInject
94
+ GoalEngineCore --> Modal
95
+ AgentTools --> GoalEngineCore
96
+ AutonomousLoop --> Guard
97
+ ```
98
+
99
+ ---
100
+
101
+ ## ✨ 核心模块详解
102
+
103
+ ### 1. `lib/goal-engine.js` — 状态引擎
104
+ 纯 JavaScript 实现,零外部依赖,完整管理会话目标、里程碑状态、运行计时、ETA 预测、Token 累计与崩溃恢复水合。
105
+ * **语言自动识别**:根据目标文本自动选择英语 (`en`)、中文 (`zh`) 或俄语 (`ru`)。
106
+ * **ETA 预估计算**:基于已完成里程碑的平均耗时进行动态预估:
107
+ $$\text{ETA} = \frac{\text{已运行时间}}{\text{已完成里程碑数}} \times \text{剩余里程碑数}$$
108
+ * **原子防抖持久化**:采用安全的临时文件写入与重命名机制,避免进程中断导致数据损坏。
109
+
110
+ ### 2. `lib/command-handler.js` — 命令处理
111
+ 处理 `/goal` 斜杠命令及其子命令:
112
+ * `/goal <目标内容>`:启动新目标。
113
+ * `/goal pause`:暂停当前目标并中止智能体当前轮次。
114
+ * `/goal resume`:恢复执行并自动提示智能体继续。
115
+ * `/goal clear`:重置当前目标为 IDLE。
116
+ * `/goal`:展示状态、耗时、预估时间、迭代进度、Token 统计与里程碑列表。
117
+
118
+ ### 3. `lib/index.js` — DSH Cordis 生命周期管理
119
+ * 注册 HTTP REST API(`GET /dsh-goal/state`、`POST /dsh-goal/action` 及 `GET /dsh-goal/events` SSE 实时流)。
120
+ * 监听 `turn/end` 事件,通过 `setImmediate` 实现轮次间的极低延迟自动驱动。
121
+ * 监听 `approval/asked` 事件,在需要操作员审批时自动暂停。
122
+ * 为智能体注册专属工具:`goal_set_milestones`、`goal_update_progress`、`goal_finish`。
123
+
124
+ ### 4. `lib/client.js` — Web 前端界面
125
+ * **常驻目标横幅**:注入 `conversation.input.dock` 插槽,包含实时计时、状态徽章、暂停/恢复与详情按钮。
126
+ * **目标详情弹窗**:展示完整里程碑清单、进度条、Token 统计,并支持 📋 一键复制 Markdown 报告。
127
+ * **快速启动按钮**:输入框上方的便捷入口,免去手动输入命令的繁琐。
128
+ * **设置卡片**:基于 Schemastery 注册至 `settings.plugin.item` 的可视化设置面板。
129
+
130
+ ---
131
+
132
+ ## 📦 安装说明
133
+
134
+ ```bash
135
+ dsh plugin --profile web add @goodandready/dsh-goal
136
+ ```
137
+
138
+ 安装完成后重启 DeepSeek Harness 实例并刷新浏览器即可。
139
+
140
+ ---
141
+
142
+ ## 💬 使用指南
143
+
144
+ ### 1. 通过聊天输入启动目标
145
+ 在聊天输入框中直接输入 `/goal` 命令:
146
+
147
+ ```text
148
+ /goal 重构鉴权中间件并补充完整的单元测试
149
+ ```
150
+
151
+ 智能体将立即:
152
+ 1. 通过 `goal_set_milestones` 制定清晰的步骤规划;
153
+ 2. 逐项执行,并通过 `goal_update_progress` 标记 `in_progress` 与 `completed`;
154
+ 3. 全部完成后调用 `goal_finish` 输出最终总结。
155
+
156
+ ### 2. 快速启动按钮
157
+ 点击输入框上方的 **启动目标** 按钮,在弹出的窗口中输入任务描述并点击确认。
158
+
159
+ ### 3. 通过 REST API 控制
160
+ 也可以通过 HTTP 请求远程控制目标:
161
+
162
+ ```bash
163
+ # 启动目标
164
+ curl -X POST http://localhost:3080/dsh-goal/action \
165
+ -H "Content-Type: application/json" \
166
+ -d '{"action":"start","title":"实现自动化备份流水线"}'
167
+
168
+ # 暂停目标
169
+ curl -X POST http://localhost:3080/dsh-goal/action \
170
+ -H "Content-Type: application/json" \
171
+ -d '{"action":"pause"}'
172
+
173
+ # 恢复目标
174
+ curl -X POST http://localhost:3080/dsh-goal/action \
175
+ -H "Content-Type: application/json" \
176
+ -d '{"action":"resume"}'
177
+
178
+ # 查看实时状态
179
+ curl http://localhost:3080/dsh-goal/state
180
+ ```
181
+
182
+ ---
183
+
184
+ ## ⚙️ 配置说明 (`settings.yaml`)
185
+
186
+ 可在 `settings.yaml` 中配置,或在 **设置 → 插件 → 目标模式** 界面中调整:
187
+
188
+ ```yaml
189
+ dsh-goal:
190
+ maxIterations: 25
191
+ autoDrive: true
192
+ enableSound: true
193
+ showQuickLaunchButton: true
194
+ ```
195
+
196
+ | 参数项 | 类型 | 默认值 | 说明 |
197
+ |:---|:---|:---|:---|
198
+ | `maxIterations` | `number` | `25` | 安全限制:每个目标允许执行的最大自主轮次 |
199
+ | `autoDrive` | `boolean` | `true` | 是否在轮次之间自动保持循环执行 |
200
+ | `enableSound` | `boolean` | `true` | 目标完成或失败时是否播放提示音效 |
201
+ | `showQuickLaunchButton` | `boolean` | `true` | 是否在输入框上方常驻快速启动按钮 |
202
+
203
+ ---
204
+
205
+ ## 🧪 自动化测试
206
+
207
+ 运行单元与集成测试套件:
208
+
209
+ ```bash
210
+ npm test
211
+ ```
212
+
213
+ ---
214
+
215
+ ## 📄 开源许可
216
+
217
+ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
@@ -96,3 +96,23 @@
96
96
  - **Устойчивость SSE с Exponential Backoff**: На клиенте внедрена автоматическая схема повторного подключения `EventSource` с возрастающей задержкой (от 2s до 30s) и рандомизированным джиттером для защиты от шторма переподключений.
97
97
  - **Строгая REST валидация и Enum Guard**: Обработчик `POST /dsh-goal/action` валидирует непустой `title` при старте цели и проверяет допустимость статуса вехи по `MilestoneStatus` enum, возвращая внятный HTTP 400 Bad Request / 404 Not Found.
98
98
  - **Безопасность файловой системы**: `GoalEngine.writeStateToDiskSync()` гарантированно создаёт отсутствующие родительские директории через `fs.mkdirSync(dir, { recursive: true })` перед созданием временного файла и атомарным переименованием.
99
+
100
+ ### Решение 9: Интеллектуальная оценка времени (ETA), аналитика токенов, кнопка быстрого запуска цели и экспорт отчетов в Markdown
101
+
102
+ **Контекст:**
103
+ После стабилизации сессионной изоляции и SSE-потока пользователям требовалась наглядная оценка оставшегося времени работы над целью, понимание расхода токенов за цикл, удобный запуск цели без ручного ввода команды `/goal` и возможность мгновенно экспортировать структурированный итоговый отчёт в markdown-формате.
104
+
105
+ **Принятые решения:**
106
+ 1. **Расчет оставшегося времени (ETA projection):**
107
+ - Метод `getEstimatedRemainingSeconds(sid)` рассчитывает среднее время на выполнение завершенных вех `elapsed / completedCount` и умножает на количество оставшихся шагов.
108
+ - В верхнем баннере и модальном окне отображается живое время работы с прогнозом: `⏱ 45s (ETA ~2m)`.
109
+ 2. **Аналитика расхода токенов (Token Usage Analytics):**
110
+ - Накопление счетчиков `promptTokens`, `completionTokens`, `totalTokens` на каждом завершении хода `turn/end` через `engine.addTokenUsage(usage, sid)`.
111
+ - В модальном окне деталей в сетку характеристик добавлен блок «Токены» с подсказкой при наведении с детальным расщеплением.
112
+ 3. **Кнопка быстрого запуска цели (Quick Launch button):**
113
+ - Когда цель не активна, в `conversation.input.dock` отображается компактная кнопка с иконкой 🎯.
114
+ - По клику открывается модальное окно с полем ввода для немедленной постановки задачи агенту без ручного ввода слэш-команд.
115
+ - В карточке настроек добавлен переключатель `showQuickLaunchButton` с возможностью сброса к дефолту.
116
+ 4. **Экспорт отчета в Markdown (One-click Markdown Export):**
117
+ - Для выполненной цели модальное окно предоставляет кнопку «📋 Скопировать отчёт в Markdown».
118
+ - Генерирует отчет с заголовком, статусом, длительностью, итерациями, расходом токенов, резюме результатов и таблицей вех.