@goodandready/dsh-goal 0.1.3 → 0.1.5
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/docs/design/DESIGN.md +7 -0
- package/lib/client.js +400 -213
- package/lib/command-handler.js +192 -189
- package/lib/goal-engine.js +255 -104
- package/lib/index.js +182 -78
- package/package.json +1 -1
package/lib/command-handler.js
CHANGED
|
@@ -1,189 +1,192 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { GoalState } from './goal-engine.js';
|
|
3
|
-
|
|
4
|
-
export const USAGE = 'Использование: /goal [<цель>|clear|pause|resume]';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Парсинг строки ввода для команды /goal
|
|
8
|
-
* @param {string} rawInput
|
|
9
|
-
* @returns {{ action: string, text?: string }}
|
|
10
|
-
*/
|
|
11
|
-
export function parseGoalInput(rawInput = '') {
|
|
12
|
-
const input = String(rawInput || '').trim();
|
|
13
|
-
if (!input) {
|
|
14
|
-
return { action: 'show' };
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
const lower = input.toLowerCase();
|
|
18
|
-
if (lower === 'clear') return { action: 'clear' };
|
|
19
|
-
if (lower === 'pause') return { action: 'pause' };
|
|
20
|
-
if (lower === 'resume') return { action: 'resume' };
|
|
21
|
-
|
|
22
|
-
return { action: 'start', text: input };
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Создание валидного identified сообщения пользователя для отправки агенту через followup
|
|
27
|
-
* @param {string} text
|
|
28
|
-
* @returns {Object}
|
|
29
|
-
*/
|
|
30
|
-
export function createGoalUserMessage(text) {
|
|
31
|
-
return {
|
|
32
|
-
id: randomUUID(),
|
|
33
|
-
role: 'user',
|
|
34
|
-
content: [{ type: 'text', text }],
|
|
35
|
-
source: { kind: 'user' },
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Формирование стартового промпта с жестким требованием составить план работ
|
|
41
|
-
* @param {string} goalText
|
|
42
|
-
* @returns {string}
|
|
43
|
-
*/
|
|
44
|
-
export function formatGoalStartPrompt(goalText) {
|
|
45
|
-
return `🎯 Активирован режим
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
*
|
|
55
|
-
* @param {
|
|
56
|
-
* @param {
|
|
57
|
-
* @
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
}
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { GoalState } from './goal-engine.js';
|
|
3
|
+
|
|
4
|
+
export const USAGE = 'Использование: /goal [<цель>|clear|pause|resume]';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Парсинг строки ввода для команды /goal
|
|
8
|
+
* @param {string} rawInput
|
|
9
|
+
* @returns {{ action: string, text?: string }}
|
|
10
|
+
*/
|
|
11
|
+
export function parseGoalInput(rawInput = '') {
|
|
12
|
+
const input = String(rawInput || '').trim();
|
|
13
|
+
if (!input) {
|
|
14
|
+
return { action: 'show' };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const lower = input.toLowerCase();
|
|
18
|
+
if (lower === 'clear') return { action: 'clear' };
|
|
19
|
+
if (lower === 'pause') return { action: 'pause' };
|
|
20
|
+
if (lower === 'resume') return { action: 'resume' };
|
|
21
|
+
|
|
22
|
+
return { action: 'start', text: input };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Создание валидного identified сообщения пользователя для отправки агенту через followup
|
|
27
|
+
* @param {string} text
|
|
28
|
+
* @returns {Object}
|
|
29
|
+
*/
|
|
30
|
+
export function createGoalUserMessage(text) {
|
|
31
|
+
return {
|
|
32
|
+
id: randomUUID(),
|
|
33
|
+
role: 'user',
|
|
34
|
+
content: [{ type: 'text', text }],
|
|
35
|
+
source: { kind: 'user' },
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Формирование стартового промпта с жестким требованием составить план работ
|
|
41
|
+
* @param {string} goalText
|
|
42
|
+
* @returns {string}
|
|
43
|
+
*/
|
|
44
|
+
export function formatGoalStartPrompt(goalText) {
|
|
45
|
+
return `🎯 Активирован режим цели (Goal Mode): "${goalText}"\n\n` +
|
|
46
|
+
`СТРОГИЙ КОНТРАКТ АВТОНОМНОГО РЕЖИМА:\n` +
|
|
47
|
+
`1. ОБЯЗАТЕЛЬНЫЙ ШАГ №1: Твоим ПЕРВЫМ действием ДО выполнения любой другой работы или ответа должен быть вызов инструмента goal_set_milestones с массивом из 3-7 конкретных, последовательных пунктов плана работ. Пользователь видит этот план в интерфейсе в реальном времени.\n` +
|
|
48
|
+
`2. ШАГ №2: После установки плана переходи к выполнению шагов. Перед началом работы над каждым шагом отметь его статус как in_progress через goal_update_progress(milestone_id, "in_progress").\n` +
|
|
49
|
+
`3. ШАГ №3: После успешного завершения шага отметь его статус как completed через goal_update_progress(milestone_id, "completed", "краткие итоги шага").\n` +
|
|
50
|
+
`4. ШАГ №4: Когда все пункты плана выполнены, вызови инструмент goal_finish(summary) с подробным резюме достигнутых результатов.`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Форматирование текстового ответа для UI и постановка/управление задачей агента
|
|
55
|
+
* @param {import('./goal-engine.js').GoalEngine} engine
|
|
56
|
+
* @param {{ action: string, text?: string }} parsed
|
|
57
|
+
* @param {Object} [config]
|
|
58
|
+
* @param {Object} [agent]
|
|
59
|
+
* @returns {{ kind: 'success' | 'error', text: string }}
|
|
60
|
+
*/
|
|
61
|
+
export function executeGoalSlashCommand(engine, parsed, config = {}, agent = null, sessionId = 'default') {
|
|
62
|
+
const sid = sessionId || 'default';
|
|
63
|
+
const snap = engine.getSnapshot(sid);
|
|
64
|
+
|
|
65
|
+
switch (parsed.action) {
|
|
66
|
+
case 'show': {
|
|
67
|
+
if (!snap.hasActiveGoal) {
|
|
68
|
+
return {
|
|
69
|
+
kind: 'success',
|
|
70
|
+
text: `🎯 Режим цели (Goal Mode): цель не установлена.\n${USAGE}`,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const milestonesInfo = snap.milestones.length > 0
|
|
75
|
+
? `\nПлан работ:\n` + snap.milestones.map((m, i) => ` ${i + 1}. [${m.status}] ${m.title}`).join('\n')
|
|
76
|
+
: '';
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
kind: 'success',
|
|
80
|
+
text: `🎯 Цель: «${snap.title}»\n` +
|
|
81
|
+
`Статус: ${snap.state}\n` +
|
|
82
|
+
`Время: ${snap.formattedElapsed}\n` +
|
|
83
|
+
`Итераций: ${snap.iterationsCount}/${snap.maxIterations}` +
|
|
84
|
+
milestonesInfo +
|
|
85
|
+
`\n\nКоманды: /goal pause, /goal resume, /goal clear, /goal <новая цель>`,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
case 'clear': {
|
|
90
|
+
if (!snap.hasActiveGoal) {
|
|
91
|
+
return {
|
|
92
|
+
kind: 'success',
|
|
93
|
+
text: 'Цель не была установлена.',
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
engine.clear(sid);
|
|
97
|
+
if (agent && typeof agent.cancel === 'function') {
|
|
98
|
+
try {
|
|
99
|
+
agent.cancel({ kind: 'user', reason: 'Goal cleared by user' });
|
|
100
|
+
} catch (err) {
|
|
101
|
+
console.warn('[dsh-goal] Failed to cancel agent on clear:', err);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
kind: 'success',
|
|
106
|
+
text: '🎯 Цель сброшена.',
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
case 'pause': {
|
|
111
|
+
if (!snap.hasActiveGoal) {
|
|
112
|
+
return {
|
|
113
|
+
kind: 'error',
|
|
114
|
+
text: `Нельзя приостановить: активная цель отсутствует.\n${USAGE}`,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
if (snap.state === GoalState.PAUSED) {
|
|
118
|
+
return {
|
|
119
|
+
kind: 'success',
|
|
120
|
+
text: '⏸ Цель уже на паузе.',
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
engine.pause('Пауза по команде пользователя (/goal pause)', sid);
|
|
124
|
+
if (agent && typeof agent.cancel === 'function') {
|
|
125
|
+
try {
|
|
126
|
+
agent.cancel({ kind: 'user', reason: 'Goal paused by user' });
|
|
127
|
+
} catch (err) {
|
|
128
|
+
console.warn('[dsh-goal] Failed to cancel agent on pause:', err);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
kind: 'success',
|
|
133
|
+
text: `⏸ Цель приостановлена: «${snap.title}». Работа агента остановлена. Используйте /goal resume или кнопку ▶️ для продолжения.`,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
case 'resume': {
|
|
138
|
+
if (!snap.hasActiveGoal) {
|
|
139
|
+
return {
|
|
140
|
+
kind: 'error',
|
|
141
|
+
text: `Нельзя возобновить: активная цель отсутствует.\n${USAGE}`,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
if (snap.state === GoalState.RUNNING) {
|
|
145
|
+
return {
|
|
146
|
+
kind: 'success',
|
|
147
|
+
text: '▶️ Цель уже выполняется.',
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
engine.resume(sid);
|
|
151
|
+
if (agent && typeof agent.followup === 'function') {
|
|
152
|
+
try {
|
|
153
|
+
const resumePrompt = `▶️ Цель возобновлена пользователем. Продолжай выполнение плана работ с того места, где остановился. Отмечай шаги через goal_update_progress.`;
|
|
154
|
+
agent.followup(createGoalUserMessage(resumePrompt));
|
|
155
|
+
} catch (err) {
|
|
156
|
+
console.warn('[dsh-goal] Failed to followup agent on resume:', err);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
kind: 'success',
|
|
161
|
+
text: `▶️ Цель возобновлена: «${snap.title}». Агент продолжает работу.`,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
case 'start': {
|
|
166
|
+
const maxIterations = config.maxIterations ?? snap.maxIterations ?? 25;
|
|
167
|
+
const newSnap = engine.startGoal(parsed.text, { maxIterations }, sid);
|
|
168
|
+
|
|
169
|
+
// Если команда вызвана в контексте агента, отправляем цель в очередь модели
|
|
170
|
+
if (agent && typeof agent.followup === 'function') {
|
|
171
|
+
try {
|
|
172
|
+
const userMsg = createGoalUserMessage(formatGoalStartPrompt(parsed.text));
|
|
173
|
+
agent.followup(userMsg);
|
|
174
|
+
} catch (err) {
|
|
175
|
+
console.warn('[dsh-goal] Failed to dispatch goal to agent followup:', err);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
kind: 'success',
|
|
181
|
+
text: `🎯 Активирована цель: «${newSnap.title}» (макс. ${newSnap.maxIterations} итераций).\n` +
|
|
182
|
+
`Для паузы: /goal pause | Для сброса: /goal clear`,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
default:
|
|
187
|
+
return {
|
|
188
|
+
kind: 'error',
|
|
189
|
+
text: `Неизвестная команда. ${USAGE}`,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
}
|