@goodandready/dsh-goal 0.1.3 → 0.1.4

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/lib/index.js CHANGED
@@ -1,489 +1,567 @@
1
- import path from 'node:path';
2
- import os from 'node:os';
3
- import z from '@deepseek-ai/schemastery';
4
- import { GoalEngine, GoalState, MilestoneStatus } from './goal-engine.js';
5
- import { parseGoalInput, executeGoalSlashCommand, createGoalUserMessage } from './command-handler.js';
6
-
7
- export const name = '@goodandready/dsh-goal';
8
- export const inject = ['webServer', 'settings'];
9
-
10
- const NS = 'dsh-goal';
11
-
12
- // Схема-функция: в rc.1 settings.register(NS, schema, { base }) ожидает
13
- // schemastery-схему вторым аргументом.
14
- // Issue #24: storagePath объявлен в схеме конфигурации плагина
15
- export const Config = z.object({
16
- maxIterations: z.number().default(25).description('Safety limit: max autonomous iterations per goal'),
17
- autoDrive: z.boolean().default(true).description('Automatically continue the loop after each turn'),
18
- enableSound: z.boolean().default(true).description('Play a sound when a goal completes'),
19
- storagePath: z.string().default('').description('Custom filesystem path for persistent state storage'),
20
- });
21
-
22
- export function apply(ctx, config = {}) {
23
- let settingsScope = null;
24
- let agentsService = null;
25
- const runningAgents = new Set();
26
- let lastActiveAgent = null;
27
-
28
- let currentSettings = {
29
- maxIterations: config?.maxIterations ?? 25,
30
- autoDrive: config?.autoDrive ?? true,
31
- enableSound: config?.enableSound ?? true,
32
- storagePath: config?.storagePath,
33
- };
34
-
35
- const defaultStorageDir = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
36
- const storagePath = currentSettings.storagePath !== undefined && currentSettings.storagePath !== null
37
- ? currentSettings.storagePath
38
- : path.join(defaultStorageDir, 'dsh-goal-state.json');
39
-
40
- const engine = new GoalEngine({
41
- defaultMaxIterations: currentSettings.maxIterations,
42
- autoDrive: currentSettings.autoDrive,
43
- enableSound: currentSettings.enableSound,
44
- storagePath,
45
- });
46
-
47
- // Динамическое внедрение сервиса agents для управления жизненным циклом
48
- ctx.inject(['agents'], (actx) => {
49
- agentsService = actx.agents;
50
- });
51
-
52
- // Отслеживание выполняющихся агентов через глобальное событие ядра DSH
53
- ctx.on?.('agent/status', ({ agent, status }) => {
54
- if (status === 'running') {
55
- runningAgents.add(agent);
56
- lastActiveAgent = agent;
57
- } else {
58
- runningAgents.delete(agent);
59
- }
60
- });
61
-
62
- const stopRunningAgents = () => {
63
- // 1. Отмена всех агентов, находящихся в активном выполнении
64
- for (const ag of runningAgents) {
65
- try {
66
- if (typeof ag.cancel === 'function') {
67
- ag.cancel({ kind: 'user' });
68
- }
69
- } catch (err) {
70
- console.warn('[dsh-goal] Failed to cancel running agent:', err);
71
- }
72
- }
73
- runningAgents.clear();
74
-
75
- // 2. Отмена последнего известного агента
76
- if (lastActiveAgent && lastActiveAgent.status === 'running' && typeof lastActiveAgent.cancel === 'function') {
77
- try {
78
- lastActiveAgent.cancel({ kind: 'user' });
79
- } catch (err) {
80
- console.warn('[dsh-goal] Failed to cancel lastActiveAgent:', err);
81
- }
82
- }
83
-
84
- // 3. Дополнительная проверка через agentsService.list()
85
- if (agentsService && typeof agentsService.list === 'function') {
86
- try {
87
- for (const ag of agentsService.list()) {
88
- if (ag && ag.status === 'running' && typeof ag.cancel === 'function') {
89
- try {
90
- ag.cancel({ kind: 'user' });
91
- } catch (_) {}
92
- }
93
- }
94
- } catch (err) {
95
- console.warn('[dsh-goal] Failed to cancel agents from list:', err);
96
- }
97
- }
98
- };
99
-
100
- const resumeActiveAgent = (promptText) => {
101
- const resumeMsg = createGoalUserMessage(
102
- promptText || '▶️ Цель возобновлена пользователем. Продолжай выполнение плана работ с того места, где остановился. Отмечай шаги через goal_update_progress.',
103
- );
104
- let target = null;
105
- if (lastActiveAgent && typeof lastActiveAgent.followup === 'function') {
106
- target = lastActiveAgent;
107
- } else if (agentsService && typeof agentsService.list === 'function') {
108
- const list = agentsService.list();
109
- if (list && list.length > 0) {
110
- target = list[list.length - 1];
111
- }
112
- }
113
-
114
- if (target && typeof target.followup === 'function') {
115
- try {
116
- target.followup(resumeMsg);
117
- lastActiveAgent = target;
118
- return true;
119
- } catch (err) {
120
- console.warn('[dsh-goal] Failed to resume agent:', err);
121
- }
122
- }
123
- return false;
124
- };
125
-
126
- // Issue #21: getConfig reads snap.value ONLY when status is 'ready' (or status is undefined in unit test mocks)
127
- const getConfig = () => {
128
- if (settingsScope) {
129
- const snap = typeof settingsScope.getSnapshot === 'function' ? settingsScope.getSnapshot() : null;
130
- if (snap) {
131
- if (snap.status === 'ready' || snap.status === undefined) {
132
- const live = snap.value || (typeof settingsScope.get === 'function' ? settingsScope.get() : null);
133
- if (live && typeof live === 'object') {
134
- return {
135
- maxIterations: typeof live.maxIterations === 'number' ? live.maxIterations : currentSettings.maxIterations,
136
- autoDrive: typeof live.autoDrive === 'boolean' ? live.autoDrive : currentSettings.autoDrive,
137
- enableSound: typeof live.enableSound === 'boolean' ? live.enableSound : currentSettings.enableSound,
138
- storagePath: typeof live.storagePath === 'string' ? live.storagePath : currentSettings.storagePath,
139
- };
140
- }
141
- }
142
- } else if (typeof settingsScope.get === 'function') {
143
- const live = settingsScope.get();
144
- if (live && typeof live === 'object') {
145
- return {
146
- maxIterations: typeof live.maxIterations === 'number' ? live.maxIterations : currentSettings.maxIterations,
147
- autoDrive: typeof live.autoDrive === 'boolean' ? live.autoDrive : currentSettings.autoDrive,
148
- enableSound: typeof live.enableSound === 'boolean' ? live.enableSound : currentSettings.enableSound,
149
- storagePath: typeof live.storagePath === 'string' ? live.storagePath : currentSettings.storagePath,
150
- };
151
- }
152
- }
153
- }
154
- return currentSettings;
155
- };
156
-
157
- const applySettings = () => {
158
- const live = getConfig();
159
- engine.updateConfig({
160
- defaultMaxIterations: live.maxIterations,
161
- autoDrive: live.autoDrive,
162
- enableSound: live.enableSound,
163
- });
164
- };
165
-
166
- // 1. Регистрация настроек плагина
167
- ctx.inject(['settings'], (sctx) => {
168
- try {
169
- const scope = sctx.settings?.register?.(NS, Config, { base: currentSettings });
170
- if (scope) {
171
- settingsScope = scope;
172
- applySettings();
173
- if (typeof scope.subscribe === 'function') {
174
- sctx.effect(() => {
175
- const off = scope.subscribe(() => {
176
- applySettings();
177
- });
178
- return () => {
179
- if (typeof off === 'function') off();
180
- settingsScope = null;
181
- };
182
- }, 'dsh-goal: settings subscription');
183
- }
184
- }
185
- } catch (err) {
186
- console.warn('[dsh-goal] Settings register skipped:', err.message);
187
- }
188
- });
189
-
190
- // 2. Регистрация слэш-команды /goal в чате
191
- ctx.inject(['commands'], (cctx) => {
192
- try {
193
- if (typeof cctx.commands?.register !== 'function') return;
194
-
195
- const unregister = cctx.commands.register({
196
- name: 'goal',
197
- description: 'Управление режимом цели (Goal Mode): активация, вехи, пауза, сброс',
198
- input: { hint: '[<цель>|clear|pause|resume]' },
199
- handler: async (invocation) => {
200
- if (invocation?.agent) {
201
- lastActiveAgent = invocation.agent;
202
- }
203
- const parsed = parseGoalInput(invocation?.rawInput);
204
- const liveConfig = getConfig();
205
- return executeGoalSlashCommand(engine, parsed, liveConfig, invocation?.agent);
206
- },
207
- });
208
-
209
- if (typeof unregister === 'function') {
210
- cctx.effect(() => () => unregister(), 'dsh-goal: /goal command unregister');
211
- }
212
- } catch (err) {
213
- console.warn('[dsh-goal] Commands register skipped:', err.message);
214
- }
215
- });
216
-
217
- // 3. Инжекция контекста цели в системный промпт (systemPrompt)
218
- ctx.inject(['systemPrompt'], (pctx) => {
219
- try {
220
- if (typeof pctx.systemPrompt?.section === 'function') {
221
- const order = typeof pctx.systemPrompt.getSectionOrder === 'function'
222
- ? (pctx.systemPrompt.getSectionOrder('TOOL_GOAL') || 600)
223
- : 600;
224
-
225
- const unregisterSection = pctx.systemPrompt.section({
226
- name: 'tool:dsh-goal',
227
- order,
228
- text: () => engine.getStatePromptInjection(),
229
- });
230
-
231
- if (typeof unregisterSection === 'function') {
232
- pctx.effect(() => () => unregisterSection(), 'dsh-goal: system prompt section');
233
- }
234
- }
235
- } catch (err) {
236
- console.warn('[dsh-goal] SystemPrompt section register skipped:', err.message);
237
- }
238
- });
239
-
240
- // 4. Регистрация инструментов для модели (tools)
241
- ctx.inject(['tools'], (tctx) => {
242
- if (!tctx.tools?.register) return;
243
-
244
- // Инструмент 1: Декомпозиция цели на вехи
245
- tctx.tools.register({
246
- name: 'goal_set_milestones',
247
- description: 'Break down the current active goal into a sequence of concrete milestones/sub-tasks.',
248
- parameters: {
249
- type: 'object',
250
- properties: {
251
- milestones: {
252
- type: 'array',
253
- items: { type: 'string' },
254
- description: 'List of milestone titles to accomplish.',
255
- },
256
- },
257
- required: ['milestones'],
258
- },
259
- handler: async ({ milestones }) => {
260
- const snap = engine.getSnapshot();
261
- if (!snap.hasActiveGoal) {
262
- return { error: 'No active goal currently set. Start a goal first.' };
263
- }
264
- engine.addMilestones(milestones);
265
- return {
266
- success: true,
267
- milestones: engine.getSnapshot().milestones,
268
- };
269
- },
270
- });
271
-
272
- // Инструмент 2: Обновление статуса вехи
273
- tctx.tools.register({
274
- name: 'goal_update_progress',
275
- description: 'Update the status of a specific goal milestone and optionally log progress notes.',
276
- parameters: {
277
- type: 'object',
278
- properties: {
279
- milestone_id: {
280
- type: 'string',
281
- description: 'The ID of the milestone (e.g. "m-1", "m-2").',
282
- },
283
- status: {
284
- type: 'string',
285
- enum: ['pending', 'in_progress', 'completed', 'failed'],
286
- description: 'New status for this milestone.',
287
- },
288
- notes: {
289
- type: 'string',
290
- description: 'Brief summary of what was accomplished or why it failed.',
291
- },
292
- },
293
- required: ['milestone_id', 'status'],
294
- },
295
- handler: async ({ milestone_id, status, notes }) => {
296
- const ok = engine.updateMilestone(milestone_id, status, notes);
297
- if (!ok) {
298
- return { error: `Milestone ${milestone_id} not found or no active goal.` };
299
- }
300
- return {
301
- success: true,
302
- snapshot: engine.getSnapshot(),
303
- };
304
- },
305
- });
306
-
307
- // Инструмент 3: Успешное завершение цели
308
- tctx.tools.register({
309
- name: 'goal_finish',
310
- description: 'Conclude the active goal successfully with a final summary and achievements.',
311
- parameters: {
312
- type: 'object',
313
- properties: {
314
- summary: {
315
- type: 'string',
316
- description: 'Final summary of the goal outcome and deliverables.',
317
- },
318
- },
319
- required: ['summary'],
320
- },
321
- handler: async ({ summary }) => {
322
- const snap = engine.completeGoal(summary);
323
- return {
324
- success: true,
325
- completed: true,
326
- summary,
327
- };
328
- },
329
- });
330
- });
331
-
332
- // 5. Регистрация HTTP REST API маршрутов
333
- ctx.effect(() => {
334
- if (!ctx.webServer?.register) return () => {};
335
-
336
- const unreg = ctx.webServer.register({
337
- kind: 'prefix',
338
- path: '/dsh-goal',
339
- handler: (req, res) => {
340
- const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
341
- const pathname = url.pathname;
342
-
343
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
344
-
345
- // GET /dsh-goal/state
346
- if (req.method === 'GET' && (pathname === '/dsh-goal/state' || pathname === '/dsh-goal/state/')) {
347
- res.statusCode = 200;
348
- return res.end(JSON.stringify(engine.getSnapshot()));
349
- }
350
-
351
- // POST /dsh-goal/action
352
- // Issue #22: CSRF & Same-Origin guard
353
- if (req.method === 'POST' && (pathname === '/dsh-goal/action' || pathname === '/dsh-goal/action/')) {
354
- const secFetchSite = req.headers['sec-fetch-site'];
355
- if (secFetchSite && secFetchSite !== 'same-origin' && secFetchSite !== 'same-site' && secFetchSite !== 'none') {
356
- res.statusCode = 403;
357
- return res.end(JSON.stringify({ error: 'Forbidden: cross-site requests are rejected' }));
358
- }
359
-
360
- const origin = req.headers.origin;
361
- const host = req.headers.host;
362
- if (origin && host) {
363
- try {
364
- const originHost = new URL(origin).host;
365
- if (originHost !== host) {
366
- res.statusCode = 403;
367
- return res.end(JSON.stringify({ error: 'Forbidden: origin mismatch' }));
368
- }
369
- } catch (_) {
370
- res.statusCode = 403;
371
- return res.end(JSON.stringify({ error: 'Forbidden: invalid origin' }));
372
- }
373
- }
374
-
375
- let body = '';
376
- req.on('data', (chunk) => { body += chunk; });
377
- req.on('end', () => {
378
- try {
379
- const data = JSON.parse(body || '{}');
380
- const { action, title, description, reason, milestoneId, status, notes } = data;
381
-
382
- let result = null;
383
- switch (action) {
384
- case 'start':
385
- result = engine.startGoal(title || 'Новая цель', {
386
- description,
387
- maxIterations: getConfig().maxIterations,
388
- });
389
- break;
390
- case 'pause':
391
- result = engine.pause(reason || 'Пауза по кнопке интерфейса');
392
- stopRunningAgents();
393
- break;
394
- case 'resume':
395
- result = engine.resume();
396
- resumeActiveAgent();
397
- break;
398
- case 'cancel':
399
- result = engine.cancel(reason || 'Отмена цели');
400
- stopRunningAgents();
401
- break;
402
- case 'clear':
403
- result = engine.clear();
404
- stopRunningAgents();
405
- break;
406
- case 'update_milestone':
407
- engine.updateMilestone(milestoneId, status, notes);
408
- result = engine.getSnapshot();
409
- break;
410
- default:
411
- res.statusCode = 400;
412
- return res.end(JSON.stringify({ error: `Unknown action: ${action}` }));
413
- }
414
-
415
- res.statusCode = 200;
416
- return res.end(JSON.stringify({ ok: true, state: result || engine.getSnapshot() }));
417
- } catch (parseErr) {
418
- res.statusCode = 400;
419
- return res.end(JSON.stringify({ error: parseErr.message }));
420
- }
421
- });
422
- return;
423
- }
424
-
425
- res.statusCode = 404;
426
- res.end(JSON.stringify({ error: 'Endpoint not found' }));
427
- },
428
- });
429
-
430
- return () => {
431
- if (typeof unreg === 'function') unreg();
432
- };
433
- }, 'dsh-goal: HTTP WebServer Routes');
434
-
435
- // 6. Подписка на события сессии (автономный цикл)
436
- ctx.effect(() => {
437
- // Подписка на завершение turn
438
- const onTurnEnd = (turn) => {
439
- const liveConfig = getConfig();
440
- if (!liveConfig.autoDrive) return; // Учитываем настройку autoDrive в рантайме
441
-
442
- const snap = engine.getSnapshot();
443
- if (snap.hasActiveGoal && snap.state === GoalState.RUNNING) {
444
- const canContinue = engine.incrementIteration();
445
- if (!canContinue) return;
446
-
447
- // Если turn не был прерван пользователем и цель ещё активна, отправляем следующий ход
448
- if (turn?.reason?.kind !== 'aborted') {
449
- setTimeout(() => {
450
- const currentSnap = engine.getSnapshot();
451
- if (currentSnap.hasActiveGoal && currentSnap.state === GoalState.RUNNING) {
452
- const promptMsg = createGoalUserMessage(
453
- 'Продолжай автономное выполнение цели согласно плану работ. Отмечай каждый выполненный шаг через goal_update_progress, а по завершении всех задач вызови goal_finish.',
454
- );
455
- let target = lastActiveAgent;
456
- if (!target && agentsService && typeof agentsService.list === 'function') {
457
- const list = agentsService.list();
458
- if (list && list.length > 0) target = list[list.length - 1];
459
- }
460
- if (target && typeof target.followup === 'function') {
461
- try {
462
- target.followup(promptMsg);
463
- } catch (err) {
464
- console.warn('[dsh-goal] Failed auto-drive followup:', err);
465
- }
466
- }
467
- }
468
- }, 300);
469
- }
470
- }
471
- };
472
-
473
- // Подписка на запрос подтверждения (approval/asked) -> автоматическая пауза
474
- const onApprovalAsked = () => {
475
- const snap = engine.getSnapshot();
476
- if (snap.hasActiveGoal && snap.state === GoalState.RUNNING) {
477
- engine.pause('Ожидание подтверждения действия оператором');
478
- }
479
- };
480
-
481
- ctx.on?.('turn/end', onTurnEnd);
482
- ctx.on?.('approval/asked', onApprovalAsked);
483
-
484
- return () => {
485
- ctx.off?.('turn/end', onTurnEnd);
486
- ctx.off?.('approval/asked', onApprovalAsked);
487
- };
488
- }, 'dsh-goal: Session & Turn Coordinator');
489
- }
1
+ import path from 'node:path';
2
+ import os from 'node:os';
3
+ import z from '@deepseek-ai/schemastery';
4
+ import { GoalEngine, GoalState, MilestoneStatus } from './goal-engine.js';
5
+ import { parseGoalInput, executeGoalSlashCommand, createGoalUserMessage } from './command-handler.js';
6
+
7
+ export const name = '@goodandready/dsh-goal';
8
+ export const inject = ['webServer', 'settings'];
9
+
10
+ const NS = 'dsh-goal';
11
+
12
+ function sessionIdOf(invocationOrReq, fallback = 'default') {
13
+ if (!invocationOrReq) return fallback;
14
+ try {
15
+ // 1. DSH invocation / event / turn
16
+ if (invocationOrReq.sessionId) return String(invocationOrReq.sessionId);
17
+ if (invocationOrReq.session) {
18
+ return String(invocationOrReq.session.id || invocationOrReq.session.header?.id || fallback);
19
+ }
20
+ if (invocationOrReq.data?.sessionId) return String(invocationOrReq.data.sessionId);
21
+ if (invocationOrReq.agent?.session) {
22
+ return String(invocationOrReq.agent.session.id || invocationOrReq.agent.session.header?.id || fallback);
23
+ }
24
+ // 2. HTTP Request (req)
25
+ if (invocationOrReq.headers) {
26
+ const headerSid = invocationOrReq.headers['x-dsh-session-id'];
27
+ if (headerSid) return String(headerSid);
28
+ if (invocationOrReq.url) {
29
+ const url = new URL(invocationOrReq.url, 'http://localhost');
30
+ const querySid = url.searchParams.get('sessionId') || url.searchParams.get('session');
31
+ if (querySid) return String(querySid);
32
+ }
33
+ }
34
+ } catch (_) {}
35
+ return fallback;
36
+ }
37
+
38
+ // Схема-функция: в rc.1 settings.register(NS, schema, { base }) ожидает
39
+ // schemastery-схему вторым аргументом.
40
+ // Issue #24: storagePath объявлен в схеме конфигурации плагина
41
+ export const Config = z.object({
42
+ maxIterations: z.number().default(25).description('Safety limit: max autonomous iterations per goal'),
43
+ autoDrive: z.boolean().default(true).description('Automatically continue the loop after each turn'),
44
+ enableSound: z.boolean().default(true).description('Play a sound when a goal completes'),
45
+ storagePath: z.string().default('').description('Custom filesystem path for persistent state storage'),
46
+ });
47
+
48
+ export function apply(ctx, config = {}) {
49
+ let settingsScope = null;
50
+ let agentsService = null;
51
+ const runningAgents = new Set();
52
+ const sessionAgents = new Map(); // sessionId -> agent
53
+ let lastActiveAgent = null;
54
+
55
+ let currentSettings = {
56
+ maxIterations: config?.maxIterations ?? 25,
57
+ autoDrive: config?.autoDrive ?? true,
58
+ enableSound: config?.enableSound ?? true,
59
+ storagePath: config?.storagePath,
60
+ };
61
+
62
+ const defaultStorageDir = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
63
+ const storagePath = currentSettings.storagePath !== undefined && currentSettings.storagePath !== null
64
+ ? currentSettings.storagePath
65
+ : path.join(defaultStorageDir, 'dsh-goal-state.json');
66
+
67
+ const engine = new GoalEngine({
68
+ defaultMaxIterations: currentSettings.maxIterations,
69
+ autoDrive: currentSettings.autoDrive,
70
+ enableSound: currentSettings.enableSound,
71
+ storagePath,
72
+ });
73
+
74
+ // Динамическое внедрение сервиса agents для управления жизненным циклом
75
+ ctx.inject(['agents'], (actx) => {
76
+ agentsService = actx.agents;
77
+ });
78
+
79
+ // Отслеживание выполняющихся агентов через глобальное событие ядра DSH
80
+ ctx.on?.('agent/status', ({ agent, status }) => {
81
+ if (status === 'running') {
82
+ runningAgents.add(agent);
83
+ lastActiveAgent = agent;
84
+ const sid = sessionIdOf(agent, null);
85
+ if (sid) {
86
+ sessionAgents.set(sid, agent);
87
+ }
88
+ } else {
89
+ runningAgents.delete(agent);
90
+ }
91
+ });
92
+
93
+ const stopRunningAgents = (sessionId = 'default') => {
94
+ const sid = sessionId || 'default';
95
+ const specificAgent = sessionAgents.get(sid);
96
+ if (specificAgent && typeof specificAgent.cancel === 'function') {
97
+ try {
98
+ specificAgent.cancel({ kind: 'user' });
99
+ } catch (err) {
100
+ console.warn('[dsh-goal] Failed to cancel specific agent for session:', err);
101
+ }
102
+ }
103
+
104
+ // Отмена всех подходящих агентов в runningAgents
105
+ for (const ag of runningAgents) {
106
+ try {
107
+ const agSid = sessionIdOf(ag, null);
108
+ if (!agSid || agSid === sid || sid === 'default') {
109
+ if (typeof ag.cancel === 'function') {
110
+ ag.cancel({ kind: 'user' });
111
+ }
112
+ }
113
+ } catch (err) {
114
+ console.warn('[dsh-goal] Failed to cancel running agent:', err);
115
+ }
116
+ }
117
+
118
+ if (lastActiveAgent && lastActiveAgent.status === 'running' && typeof lastActiveAgent.cancel === 'function') {
119
+ const lastSid = sessionIdOf(lastActiveAgent, null);
120
+ if (!lastSid || lastSid === sid || sid === 'default') {
121
+ try {
122
+ lastActiveAgent.cancel({ kind: 'user' });
123
+ } catch (err) {
124
+ console.warn('[dsh-goal] Failed to cancel lastActiveAgent:', err);
125
+ }
126
+ }
127
+ }
128
+ };
129
+
130
+ const resumeActiveAgent = (promptText, sessionId = 'default') => {
131
+ const sid = sessionId || 'default';
132
+ const resumeMsg = createGoalUserMessage(
133
+ promptText || '▶️ Цель возобновлена пользователем. Продолжай выполнение плана работ с того места, где остановился. Отмечай шаги через goal_update_progress.',
134
+ );
135
+ let target = sessionAgents.get(sid);
136
+ if (!target && lastActiveAgent && typeof lastActiveAgent.followup === 'function') {
137
+ const lastSid = sessionIdOf(lastActiveAgent, null);
138
+ if (!lastSid || lastSid === sid || sid === 'default') {
139
+ target = lastActiveAgent;
140
+ }
141
+ }
142
+ if (!target && agentsService && typeof agentsService.list === 'function') {
143
+ const list = agentsService.list();
144
+ if (list && list.length > 0) {
145
+ for (let i = list.length - 1; i >= 0; i--) {
146
+ const cand = list[i];
147
+ const candSid = sessionIdOf(cand, null);
148
+ if (candSid === sid) {
149
+ target = cand;
150
+ break;
151
+ }
152
+ }
153
+ if (!target && sid === 'default') {
154
+ target = list[list.length - 1];
155
+ }
156
+ }
157
+ }
158
+
159
+ if (target && typeof target.followup === 'function') {
160
+ try {
161
+ target.followup(resumeMsg);
162
+ lastActiveAgent = target;
163
+ sessionAgents.set(sid, target);
164
+ return true;
165
+ } catch (err) {
166
+ console.warn('[dsh-goal] Failed to resume agent:', err);
167
+ }
168
+ }
169
+ return false;
170
+ };
171
+
172
+ // Issue #21: getConfig reads snap.value ONLY when status is 'ready' (or status is undefined in unit test mocks)
173
+ const getConfig = () => {
174
+ if (settingsScope) {
175
+ const snap = typeof settingsScope.getSnapshot === 'function' ? settingsScope.getSnapshot() : null;
176
+ if (snap) {
177
+ if (snap.status === 'ready' || snap.status === undefined) {
178
+ const live = snap.value || (typeof settingsScope.get === 'function' ? settingsScope.get() : null);
179
+ if (live && typeof live === 'object') {
180
+ return {
181
+ maxIterations: typeof live.maxIterations === 'number' ? live.maxIterations : currentSettings.maxIterations,
182
+ autoDrive: typeof live.autoDrive === 'boolean' ? live.autoDrive : currentSettings.autoDrive,
183
+ enableSound: typeof live.enableSound === 'boolean' ? live.enableSound : currentSettings.enableSound,
184
+ storagePath: typeof live.storagePath === 'string' ? live.storagePath : currentSettings.storagePath,
185
+ };
186
+ }
187
+ }
188
+ } else if (typeof settingsScope.get === 'function') {
189
+ const live = settingsScope.get();
190
+ if (live && typeof live === 'object') {
191
+ return {
192
+ maxIterations: typeof live.maxIterations === 'number' ? live.maxIterations : currentSettings.maxIterations,
193
+ autoDrive: typeof live.autoDrive === 'boolean' ? live.autoDrive : currentSettings.autoDrive,
194
+ enableSound: typeof live.enableSound === 'boolean' ? live.enableSound : currentSettings.enableSound,
195
+ storagePath: typeof live.storagePath === 'string' ? live.storagePath : currentSettings.storagePath,
196
+ };
197
+ }
198
+ }
199
+ }
200
+ return currentSettings;
201
+ };
202
+
203
+ const applySettings = () => {
204
+ const live = getConfig();
205
+ engine.updateConfig({
206
+ defaultMaxIterations: live.maxIterations,
207
+ autoDrive: live.autoDrive,
208
+ enableSound: live.enableSound,
209
+ });
210
+ };
211
+
212
+ // 1. Регистрация настроек плагина
213
+ ctx.inject(['settings'], (sctx) => {
214
+ try {
215
+ const scope = sctx.settings?.register?.(NS, Config, { base: currentSettings });
216
+ if (scope) {
217
+ settingsScope = scope;
218
+ applySettings();
219
+ if (typeof scope.subscribe === 'function') {
220
+ sctx.effect(() => {
221
+ const off = scope.subscribe(() => {
222
+ applySettings();
223
+ });
224
+ return () => {
225
+ if (typeof off === 'function') off();
226
+ settingsScope = null;
227
+ };
228
+ }, 'dsh-goal: settings subscription');
229
+ }
230
+ }
231
+ } catch (err) {
232
+ console.warn('[dsh-goal] Settings register skipped:', err.message);
233
+ }
234
+ });
235
+
236
+ // 2. Регистрация слэш-команды /goal в чате
237
+ ctx.inject(['commands'], (cctx) => {
238
+ try {
239
+ if (typeof cctx.commands?.register !== 'function') return;
240
+
241
+ const unregister = cctx.commands.register({
242
+ name: 'goal',
243
+ description: 'Управление режимом цели (Goal Mode): активация, вехи, пауза, сброс',
244
+ input: { hint: '[<цель>|clear|pause|resume]' },
245
+ handler: async (invocation) => {
246
+ const sid = sessionIdOf(invocation, 'default');
247
+ if (invocation?.agent) {
248
+ lastActiveAgent = invocation.agent;
249
+ sessionAgents.set(sid, invocation.agent);
250
+ }
251
+ const parsed = parseGoalInput(invocation?.rawInput);
252
+ const liveConfig = getConfig();
253
+ return executeGoalSlashCommand(engine, parsed, liveConfig, invocation?.agent, sid);
254
+ },
255
+ });
256
+
257
+ if (typeof unregister === 'function') {
258
+ cctx.effect(() => () => unregister(), 'dsh-goal: /goal command unregister');
259
+ }
260
+ } catch (err) {
261
+ console.warn('[dsh-goal] Commands register skipped:', err.message);
262
+ }
263
+ });
264
+
265
+ // 3. Инжекция контекста цели в системный промпт (systemPrompt)
266
+ ctx.inject(['systemPrompt'], (pctx) => {
267
+ try {
268
+ if (typeof pctx.systemPrompt?.section === 'function') {
269
+ const order = typeof pctx.systemPrompt.getSectionOrder === 'function'
270
+ ? (pctx.systemPrompt.getSectionOrder('TOOL_GOAL') || 600)
271
+ : 600;
272
+
273
+ const unregisterSection = pctx.systemPrompt.section({
274
+ name: 'tool:dsh-goal',
275
+ order,
276
+ text: (sessionCtx) => {
277
+ const sid = sessionIdOf(sessionCtx, 'default');
278
+ return engine.getStatePromptInjection(sid);
279
+ },
280
+ });
281
+
282
+ if (typeof unregisterSection === 'function') {
283
+ pctx.effect(() => () => unregisterSection(), 'dsh-goal: system prompt section');
284
+ }
285
+ }
286
+ } catch (err) {
287
+ console.warn('[dsh-goal] SystemPrompt section register skipped:', err.message);
288
+ }
289
+ });
290
+
291
+ // 4. Регистрация инструментов для модели (tools)
292
+ ctx.inject(['tools'], (tctx) => {
293
+ if (!tctx.tools?.register) return;
294
+
295
+ // Инструмент 1: Декомпозиция цели на вехи
296
+ tctx.tools.register({
297
+ name: 'goal_set_milestones',
298
+ description: 'Break down the current active goal into a sequence of concrete milestones/sub-tasks.',
299
+ parameters: {
300
+ type: 'object',
301
+ properties: {
302
+ milestones: {
303
+ type: 'array',
304
+ items: { type: 'string' },
305
+ description: 'List of milestone titles to accomplish.',
306
+ },
307
+ },
308
+ required: ['milestones'],
309
+ },
310
+ handler: async ({ milestones }, toolCtx) => {
311
+ const sid = sessionIdOf(toolCtx, 'default');
312
+ const snap = engine.getSnapshot(sid);
313
+ if (!snap.hasActiveGoal) {
314
+ return { error: 'No active goal currently set. Start a goal first.' };
315
+ }
316
+ engine.addMilestones(milestones, true, sid);
317
+ return {
318
+ success: true,
319
+ milestones: engine.getSnapshot(sid).milestones,
320
+ };
321
+ },
322
+ });
323
+
324
+ // Инструмент 2: Обновление статуса вехи
325
+ tctx.tools.register({
326
+ name: 'goal_update_progress',
327
+ description: 'Update the status of a specific goal milestone and optionally log progress notes.',
328
+ parameters: {
329
+ type: 'object',
330
+ properties: {
331
+ milestone_id: {
332
+ type: 'string',
333
+ description: 'The ID of the milestone (e.g. "m-1", "m-2").',
334
+ },
335
+ status: {
336
+ type: 'string',
337
+ enum: ['pending', 'in_progress', 'completed', 'failed'],
338
+ description: 'New status for this milestone.',
339
+ },
340
+ notes: {
341
+ type: 'string',
342
+ description: 'Brief summary of what was accomplished or why it failed.',
343
+ },
344
+ },
345
+ required: ['milestone_id', 'status'],
346
+ },
347
+ handler: async ({ milestone_id, status, notes }, toolCtx) => {
348
+ const sid = sessionIdOf(toolCtx, 'default');
349
+ const ok = engine.updateMilestone(milestone_id, status, notes, sid);
350
+ if (!ok) {
351
+ return { error: `Milestone ${milestone_id} not found or no active goal.` };
352
+ }
353
+ return {
354
+ success: true,
355
+ snapshot: engine.getSnapshot(sid),
356
+ };
357
+ },
358
+ });
359
+
360
+ // Инструмент 3: Успешное завершение цели
361
+ tctx.tools.register({
362
+ name: 'goal_finish',
363
+ description: 'Conclude the active goal successfully with a final summary and achievements.',
364
+ parameters: {
365
+ type: 'object',
366
+ properties: {
367
+ summary: {
368
+ type: 'string',
369
+ description: 'Final summary of the goal outcome and deliverables.',
370
+ },
371
+ },
372
+ required: ['summary'],
373
+ },
374
+ handler: async ({ summary }, toolCtx) => {
375
+ const sid = sessionIdOf(toolCtx, 'default');
376
+ const snap = engine.completeGoal(summary, sid);
377
+ return {
378
+ success: true,
379
+ completed: true,
380
+ summary,
381
+ };
382
+ },
383
+ });
384
+ });
385
+
386
+ // 5. Регистрация HTTP REST API маршрутов
387
+ ctx.effect(() => {
388
+ if (!ctx.webServer?.register) return () => {};
389
+
390
+ const unreg = ctx.webServer.register({
391
+ kind: 'prefix',
392
+ path: '/dsh-goal',
393
+ handler: (req, res) => {
394
+ const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
395
+ const pathname = url.pathname;
396
+
397
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
398
+
399
+ // GET /dsh-goal/state
400
+ if (req.method === 'GET' && (pathname === '/dsh-goal/state' || pathname === '/dsh-goal/state/')) {
401
+ const sid = sessionIdOf(req, 'default');
402
+ res.statusCode = 200;
403
+ return res.end(JSON.stringify(engine.getSnapshot(sid)));
404
+ }
405
+
406
+ // POST /dsh-goal/action
407
+ // Issue #22: CSRF & Same-Origin guard
408
+ if (req.method === 'POST' && (pathname === '/dsh-goal/action' || pathname === '/dsh-goal/action/')) {
409
+ const secFetchSite = req.headers['sec-fetch-site'];
410
+ if (secFetchSite && secFetchSite !== 'same-origin' && secFetchSite !== 'same-site' && secFetchSite !== 'none') {
411
+ res.statusCode = 403;
412
+ return res.end(JSON.stringify({ error: 'Forbidden: cross-site requests are rejected' }));
413
+ }
414
+
415
+ const origin = req.headers.origin;
416
+ const host = req.headers.host;
417
+ if (origin && host) {
418
+ try {
419
+ const originHost = new URL(origin).host;
420
+ if (originHost !== host) {
421
+ res.statusCode = 403;
422
+ return res.end(JSON.stringify({ error: 'Forbidden: origin mismatch' }));
423
+ }
424
+ } catch (_) {
425
+ res.statusCode = 403;
426
+ return res.end(JSON.stringify({ error: 'Forbidden: invalid origin' }));
427
+ }
428
+ }
429
+
430
+ let body = '';
431
+ req.on('data', (chunk) => { body += chunk; });
432
+ req.on('end', () => {
433
+ try {
434
+ const data = JSON.parse(body || '{}');
435
+ const sid = data.sessionId || sessionIdOf(req, 'default');
436
+ const { action, title, description, reason, milestoneId, status, notes } = data;
437
+
438
+ let result = null;
439
+ switch (action) {
440
+ case 'start':
441
+ result = engine.startGoal(title || 'Новая цель', {
442
+ description,
443
+ maxIterations: getConfig().maxIterations,
444
+ }, sid);
445
+ break;
446
+ case 'pause':
447
+ result = engine.pause(reason || 'Пауза по кнопке интерфейса', sid);
448
+ stopRunningAgents(sid);
449
+ break;
450
+ case 'resume':
451
+ result = engine.resume(sid);
452
+ resumeActiveAgent(undefined, sid);
453
+ break;
454
+ case 'cancel':
455
+ result = engine.cancel(reason || 'Отмена цели', sid);
456
+ stopRunningAgents(sid);
457
+ break;
458
+ case 'clear':
459
+ result = engine.clear(sid);
460
+ stopRunningAgents(sid);
461
+ sessionAgents.delete(sid);
462
+ break;
463
+ case 'update_milestone':
464
+ engine.updateMilestone(milestoneId, status, notes, sid);
465
+ result = engine.getSnapshot(sid);
466
+ break;
467
+ default:
468
+ res.statusCode = 400;
469
+ return res.end(JSON.stringify({ error: `Unknown action: ${action}` }));
470
+ }
471
+
472
+ res.statusCode = 200;
473
+ return res.end(JSON.stringify({ ok: true, state: result || engine.getSnapshot(sid) }));
474
+ } catch (parseErr) {
475
+ res.statusCode = 400;
476
+ return res.end(JSON.stringify({ error: parseErr.message }));
477
+ }
478
+ });
479
+ return;
480
+ }
481
+
482
+ res.statusCode = 404;
483
+ res.end(JSON.stringify({ error: 'Endpoint not found' }));
484
+ },
485
+ });
486
+
487
+ return () => {
488
+ if (typeof unreg === 'function') unreg();
489
+ };
490
+ }, 'dsh-goal: HTTP WebServer Routes');
491
+
492
+ // 6. Подписка на события сессии (автономный цикл)
493
+ ctx.effect(() => {
494
+ // Подписка на завершение turn
495
+ const onTurnEnd = (turn) => {
496
+ const liveConfig = getConfig();
497
+ if (!liveConfig.autoDrive) return; // Учитываем настройку autoDrive в рантайме
498
+
499
+ const sid = sessionIdOf(turn, 'default');
500
+ const snap = engine.getSnapshot(sid);
501
+ if (snap.hasActiveGoal && snap.state === GoalState.RUNNING) {
502
+ // Проверяем причину завершения хода
503
+ if (turn?.reason?.kind === 'aborted' || turn?.reason?.kind === 'error' || turn?.error) {
504
+ return;
505
+ }
506
+
507
+ const canContinue = engine.incrementIteration(sid);
508
+ if (!canContinue) return;
509
+
510
+ setTimeout(() => {
511
+ const currentSnap = engine.getSnapshot(sid);
512
+ if (currentSnap.hasActiveGoal && currentSnap.state === GoalState.RUNNING) {
513
+ const promptMsg = createGoalUserMessage(
514
+ 'Продолжай автономное выполнение цели согласно плану работ. Отмечай каждый выполненный шаг через goal_update_progress, а по завершении всех задач вызови goal_finish.',
515
+ );
516
+ let target = sessionAgents.get(sid);
517
+ if (!target && lastActiveAgent && typeof lastActiveAgent.followup === 'function') {
518
+ const lastSid = sessionIdOf(lastActiveAgent, null);
519
+ if (!lastSid || lastSid === sid || sid === 'default') {
520
+ target = lastActiveAgent;
521
+ }
522
+ }
523
+ if (!target && agentsService && typeof agentsService.list === 'function') {
524
+ const list = agentsService.list();
525
+ if (list && list.length > 0) {
526
+ for (let i = list.length - 1; i >= 0; i--) {
527
+ const cand = list[i];
528
+ if (sessionIdOf(cand, null) === sid) {
529
+ target = cand;
530
+ break;
531
+ }
532
+ }
533
+ if (!target && sid === 'default') target = list[list.length - 1];
534
+ }
535
+ }
536
+
537
+ if (target && typeof target.followup === 'function' && target.status !== 'stopped') {
538
+ try {
539
+ target.followup(promptMsg);
540
+ sessionAgents.set(sid, target);
541
+ } catch (err) {
542
+ console.warn('[dsh-goal] Failed auto-drive followup:', err);
543
+ }
544
+ }
545
+ }
546
+ }, 300);
547
+ }
548
+ };
549
+
550
+ // Подписка на запрос подтверждения (approval/asked) -> автоматическая пауза
551
+ const onApprovalAsked = (event) => {
552
+ const sid = sessionIdOf(event, 'default');
553
+ const snap = engine.getSnapshot(sid);
554
+ if (snap.hasActiveGoal && snap.state === GoalState.RUNNING) {
555
+ engine.pause('Ожидание подтверждения действия оператором', sid);
556
+ }
557
+ };
558
+
559
+ ctx.on?.('turn/end', onTurnEnd);
560
+ ctx.on?.('approval/asked', onApprovalAsked);
561
+
562
+ return () => {
563
+ ctx.off?.('turn/end', onTurnEnd);
564
+ ctx.off?.('approval/asked', onApprovalAsked);
565
+ };
566
+ }, 'dsh-goal: Session & Turn Coordinator');
567
+ }