@restregular/dsh-powerup 0.10.7 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -16,6 +16,9 @@
16
16
  * removed
17
17
  * POST /dsh-powerup/api/job-kill → stops one background job with an
18
18
  * optional human reason
19
+ * POST /dsh-powerup/api/progress → starts/polls/cancels a side-model
20
+ * task-progress summary (never writes
21
+ * to the session log or blocks the turn)
19
22
  * tool powerup_step_read → resolves a `dsh-step:` reference
20
23
  * copied from the Trajectory menu into
21
24
  * the raw session events it identifies
@@ -36,7 +39,17 @@ import { dirname, join, resolve as resolvePath, sep } from 'node:path';
36
39
  import { homedir } from 'node:os';
37
40
  import { defineTool } from '@deepseek-ai/dsh-tools';
38
41
  import { describeClose, describeRestart, requestRestart, requestShutdown } from './lib/restart.js';
42
+ import {
43
+ TASK_RESUME_FILE,
44
+ collectRunningTasks,
45
+ createResumeRecord,
46
+ mergeResumeQueue,
47
+ readResumeQueue,
48
+ replayPendingResumes,
49
+ stopUnfinishedTasks,
50
+ } from './lib/task-resume.js';
39
51
  import { createStepReadTool } from './lib/step-tool.js';
52
+ import { createProgressManager } from './lib/progress-manager.js';
40
53
 
41
54
  /** Prefix owned by this plugin. */
42
55
  const ROUTE = '/dsh-powerup/api';
@@ -60,6 +73,8 @@ const BODY_LIMIT = 16 * 1024;
60
73
  const STORE_DIR_NAME = 'dsh-powerup';
61
74
  const PROMPTS_FILE = 'prompts.json';
62
75
  const MASK_RULES_FILE = 'mask-rules.json';
76
+ /** Pending continuation prompts recorded by forced restart / close. */
77
+ const TASK_RESUME_FILE_NAME = TASK_RESUME_FILE;
63
78
  /** Legacy relative location inside a workspace, used only for migration. */
64
79
  const LEGACY_STORE_DIR = join('.dsh', 'dsh-powerup');
65
80
 
@@ -159,6 +174,8 @@ function sendJson(res, payload, status = 200) {
159
174
  * @returns {Promise<unknown>}
160
175
  */
161
176
  async function readJsonBody(req) {
177
+ // Some callers (and older test doubles) send no stream at all.
178
+ if (req === null || typeof req !== 'object' || typeof req[Symbol.asyncIterator] !== 'function') return {};
162
179
  const chunks = [];
163
180
  let size = 0;
164
181
  for await (const chunk of req) {
@@ -243,6 +260,12 @@ function normalizeStopReason(value) {
243
260
  * @param {unknown} value
244
261
  * @returns {string}
245
262
  */
263
+ /** Bound the optional resume prompt supplied by the UI. */
264
+ function cleanResumePrompt(value) {
265
+ if (typeof value !== 'string') return '';
266
+ return value.replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim().slice(0, 4000);
267
+ }
268
+
246
269
  function killReasonFor(value) {
247
270
  const reason = normalizeStopReason(value);
248
271
  return reason === '' ? HUMAN_KILL_REASON : `${HUMAN_KILL_REASON}: ${reason}`;
@@ -434,11 +457,47 @@ async function handle(req, res, ctx) {
434
457
 
435
458
  const url = new URL(req.url ?? ROUTE, 'http://localhost');
436
459
  const op = url.pathname.slice(ROUTE.length).replace(/^\/+/u, '') || url.searchParams.get('op') || '';
437
- if (op !== '' && op !== 'restart' && op !== 'close' && op !== 'self-update' && op !== 'audit' && op !== 'job-kill' && op !== 'prompts' && op !== 'mask-rules') {
460
+ if (op !== '' && op !== 'restart' && op !== 'close' && op !== 'self-update' && op !== 'audit' && op !== 'job-kill' && op !== 'prompts' && op !== 'mask-rules' && op !== 'progress') {
438
461
  sendJson(res, { ok: false, error: 'not-found' }, 404);
439
462
  return;
440
463
  }
441
464
 
465
+ if (op === 'progress') {
466
+ if (req.method !== 'POST') {
467
+ sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
468
+ return;
469
+ }
470
+ let body;
471
+ try {
472
+ body = await readJsonBody(req);
473
+ } catch (error) {
474
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 400);
475
+ return;
476
+ }
477
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
478
+ if (sessionId === '') {
479
+ sendJson(res, { ok: false, code: 'invalid-request', error: 'sessionId is required' }, 400);
480
+ return;
481
+ }
482
+ const action = ['start', 'poll', 'cancel'].includes(body?.action) ? body.action : 'poll';
483
+ const manager = ctx?.__powerupProgress;
484
+ if (manager === undefined) {
485
+ sendJson(res, { ok: false, code: 'unavailable', error: 'progress service is not ready' }, 503);
486
+ return;
487
+ }
488
+ try {
489
+ const view = action === 'start'
490
+ ? manager.start(sessionId)
491
+ : action === 'cancel'
492
+ ? manager.cancel(sessionId)
493
+ : manager.poll(sessionId);
494
+ sendJson(res, { ok: true, action, ...view });
495
+ } catch (error) {
496
+ sendJson(res, { ok: false, code: 'progress-failed', error: String(error?.message ?? error) }, 500);
497
+ }
498
+ return;
499
+ }
500
+
442
501
  if (op === 'mask-rules') {
443
502
  const filePath = storePath(MASK_RULES_FILE);
444
503
  if (req.method === 'POST') {
@@ -578,14 +637,85 @@ async function handle(req, res, ctx) {
578
637
 
579
638
  if (op === '' || op === 'restart' || op === 'close') {
580
639
  const action = op === 'close' ? 'close' : 'restart';
640
+ const capability = action === 'close' ? describeClose() : describeRestart();
581
641
  if (req.method === 'GET') {
582
- sendJson(res, { ok: true, action, ...(action === 'close' ? describeClose() : describeRestart()) });
642
+ // Expose unfinished work so the UI can gate the normal action and offer
643
+ // the forced variant. A runtime that cannot restart still reports tasks.
644
+ const tasks = collectRunningTasks({ agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') });
645
+ sendJson(res, {
646
+ ok: true,
647
+ action,
648
+ ...capability,
649
+ runningTasks: tasks,
650
+ hasRunningTasks: tasks.length > 0,
651
+ });
583
652
  return;
584
653
  }
585
654
  if (req.method === 'POST') {
655
+ let body;
656
+ try {
657
+ body = await readJsonBody(req);
658
+ } catch (error) {
659
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 400);
660
+ return;
661
+ }
662
+ // A client that sends no body (older UI, plugin self-update flow) keeps
663
+ // the historical behaviour: scheduled directly, no task gate.
664
+ const force = body?.force === true;
665
+ const requested = body?.force === true || body?.resume === true || body?.action !== undefined;
666
+ const tasks = requested
667
+ ? collectRunningTasks({ agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') })
668
+ : [];
669
+ if (requested && tasks.length > 0 && !force) {
670
+ sendJson(res, {
671
+ ok: false,
672
+ code: 'tasks-running',
673
+ error: 'unfinished tasks are running; use force to stop them',
674
+ runningTasks: tasks,
675
+ }, 409);
676
+ return;
677
+ }
678
+ let stopped = { cancelledAgents: [], killedJobs: [], errors: [] };
679
+ let recorded = 0;
680
+ if (requested && tasks.length > 0 && force) {
681
+ stopped = stopUnfinishedTasks(
682
+ { agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') },
683
+ `dsh-powerup forced ${action}`,
684
+ );
685
+ if (body?.resume === true) {
686
+ try {
687
+ const filePath = storePath(TASK_RESUME_FILE_NAME);
688
+ const records = [];
689
+ const seen = new Set();
690
+ for (const task of tasks) {
691
+ if (task.kind !== 'agent' || seen.has(task.id)) continue;
692
+ seen.add(task.id);
693
+ records.push(createResumeRecord({
694
+ sessionId: task.id,
695
+ title: task.title,
696
+ prompt: cleanResumePrompt(body?.resumePrompt),
697
+ }, randomUUID));
698
+ }
699
+ if (records.length > 0) {
700
+ mkdirSync(dirname(filePath), { recursive: true });
701
+ const queue = mergeResumeQueue(readResumeQueue(filePath, readFileSync), records);
702
+ writeFileSync(filePath, JSON.stringify(queue, null, 2) + '\n', 'utf8');
703
+ recorded = records.length;
704
+ }
705
+ } catch (error) {
706
+ appendSelfUpdateLog(`task-resume: could not record resumes: ${String(error?.message ?? error)}`);
707
+ }
708
+ }
709
+ }
586
710
  try {
587
711
  const scheduled = action === 'close' ? requestShutdown() : requestRestart();
588
- sendJson(res, { ok: true, [action === 'close' ? 'closing' : 'restarting']: true, ...scheduled });
712
+ sendJson(res, {
713
+ ok: true,
714
+ [action === 'close' ? 'closing' : 'restarting']: true,
715
+ ...scheduled,
716
+ stopped,
717
+ recorded,
718
+ });
589
719
  } catch (error) {
590
720
  sendJson(res, { ok: false, code: error?.code, error: String(error?.message ?? error) }, 409);
591
721
  }
@@ -629,6 +759,49 @@ export function apply(ctx) {
629
759
  'dsh-powerup: step reference reader',
630
760
  );
631
761
  });
762
+ // The progress side call needs both `llm` and `sessionQuery`. Wait for them
763
+ // through inject so a late-provided service still creates the manager.
764
+ ctx.inject(['llm', 'sessionQuery'], (scope) => {
765
+ const manager = createProgressManager({
766
+ getLlm: () => scope.get('llm'),
767
+ getSessionQuery: () => scope.get('sessionQuery'),
768
+ resolveRoute: (sessionId) => {
769
+ // Fall back to the default model when a session has no captured header.
770
+ const defaults = scope.get('agentDefaultModel');
771
+ const selection = typeof defaults?.currentSelection === 'function' ? defaults.currentSelection() : undefined;
772
+ return selection !== undefined && typeof selection.provider === 'string'
773
+ ? selection
774
+ : undefined;
775
+ },
776
+ });
777
+ ctx.__powerupProgress = manager;
778
+ scope.effect(() => () => {
779
+ if (ctx.__powerupProgress === manager) ctx.__powerupProgress = undefined;
780
+ }, 'dsh-powerup: progress manager');
781
+ });
782
+ // Replay continuation prompts recorded by a forced restart/close once the
783
+ // application has fully started. `sessionController.prompt` resumes cold
784
+ // sessions internally, so no session needs to be opened by the user first.
785
+ ctx.inject(['sessionController'], (scope) => {
786
+ const controller = scope.get('sessionController');
787
+ if (controller === null || typeof controller?.prompt !== 'function') return;
788
+ const ready = ctx.appReady;
789
+ if (ready === null || typeof ready?.onReady !== 'function') return;
790
+ scope.effect(() => ready.onReady(() => {
791
+ void replayPendingResumes({
792
+ filePath: storePath(TASK_RESUME_FILE_NAME),
793
+ sessionController: controller,
794
+ readFile: readFileSync,
795
+ writeFile: writeFileSync,
796
+ mkdir: mkdirSync,
797
+ dirname,
798
+ randomUUID,
799
+ logger: (line) => appendSelfUpdateLog(line),
800
+ }).catch((error) => {
801
+ appendSelfUpdateLog(`task-resume: uncaught ${String(error?.stack ?? error)}`);
802
+ });
803
+ }), 'dsh-powerup: resume tasks after restart');
804
+ });
632
805
  }
633
806
 
634
807
  /** Exported for tests only; the Host never reads this. */
@@ -655,4 +828,7 @@ export const __test = {
655
828
  ROUTE,
656
829
  MODULE_ID,
657
830
  STORE_DIR_NAME,
831
+ TASK_RESUME_FILE_NAME,
832
+ createProgressManager,
833
+ cleanResumePrompt,
658
834
  };
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Per-session state machine for Power-Up's task-progress side call.
3
+ *
4
+ * The manager is deliberately tiny and dependency-free: the Host injects the
5
+ * `llm`, `sessionQuery` and a route resolver, and the Client drives it through
6
+ * three verbs (start / poll / cancel). Nothing here writes to a session log.
7
+ */
8
+
9
+ import {
10
+ PROGRESS_CACHE_TTL_MS,
11
+ PROGRESS_STALE_MS,
12
+ ProgressError,
13
+ buildProgressContext,
14
+ generateProgress,
15
+ } from './progress-tool.js';
16
+
17
+ /** Cooperative deadline wrapper for one generation. */
18
+ function deadline(signal, ms) {
19
+ const controller = new AbortController();
20
+ const onAbort = () => controller.abort(signal?.reason);
21
+ if (signal?.aborted) controller.abort(signal.reason);
22
+ else signal?.addEventListener?.('abort', onAbort, { once: true });
23
+ const timer = setTimeout(() => controller.abort(new ProgressError('TIMEOUT', 'the progress call timed out')), ms);
24
+ timer.unref?.();
25
+ const dispose = () => {
26
+ clearTimeout(timer);
27
+ signal?.removeEventListener?.('abort', onAbort);
28
+ };
29
+ return { signal: controller.signal, dispose };
30
+ }
31
+
32
+ /**
33
+ * @param {{ getLlm: () => any, getSessionQuery: () => any, resolveRoute: (sessionId: string) => any, timeoutMs?: number }} options
34
+ */
35
+ export function createProgressManager(options) {
36
+ if (options === null || typeof options !== 'object') throw new TypeError('createProgressManager requires options');
37
+ const getLlm = options.getLlm;
38
+ const getSessionQuery = options.getSessionQuery;
39
+ const resolveRoute = options.resolveRoute;
40
+ if (typeof getLlm !== 'function' || typeof getSessionQuery !== 'function' || typeof resolveRoute !== 'function') {
41
+ throw new TypeError('createProgressManager needs getLlm, getSessionQuery and resolveRoute');
42
+ }
43
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 45_000;
44
+
45
+ /** @type {Map<string, {status:string, startedAt:number, updatedAt:number, report?:object, error?:string, controller?:AbortController}>} */
46
+ const states = new Map();
47
+
48
+ function stateOf(sessionId) {
49
+ return states.get(sessionId) ?? { status: 'idle', startedAt: 0, updatedAt: Date.now() };
50
+ }
51
+
52
+ /** Return a client-safe view of a session's state. */
53
+ function view(sessionId) {
54
+ const state = stateOf(sessionId);
55
+ const result = {
56
+ status: state.status,
57
+ updatedAt: state.updatedAt,
58
+ startedAt: state.startedAt,
59
+ stale: false,
60
+ };
61
+ if (state.report !== undefined) result.report = state.report;
62
+ if (state.error !== undefined) result.error = state.error;
63
+ if (state.status === 'done') result.stale = Date.now() - state.updatedAt > PROGRESS_STALE_MS;
64
+ if (state.status === 'idle' && Date.now() - state.updatedAt > PROGRESS_CACHE_TTL_MS) {
65
+ result.status = 'expired';
66
+ }
67
+ return result;
68
+ }
69
+
70
+ function cancel(sessionId) {
71
+ const state = states.get(sessionId);
72
+ if (state?.controller !== undefined) {
73
+ try { state.controller.abort(new ProgressError('CANCELLED', 'the progress call was cancelled')); } catch { /* ignore */ }
74
+ }
75
+ states.set(sessionId, { ...state, status: 'idle', controller: undefined, updatedAt: Date.now() });
76
+ return view(sessionId);
77
+ }
78
+
79
+ function start(sessionId) {
80
+ // Cancel any previous in-flight call before starting a fresh one.
81
+ const previous = states.get(sessionId);
82
+ if (previous?.controller !== undefined) {
83
+ try { previous.controller.abort(new ProgressError('SUPERSEDED', 'a newer progress call replaced this one')); } catch { /* ignore */ }
84
+ }
85
+ const controller = new AbortController();
86
+ const startedAt = Date.now();
87
+ states.set(sessionId, { status: 'running', startedAt, updatedAt: startedAt, controller });
88
+
89
+ const scope = deadline(controller.signal, timeoutMs);
90
+ (async () => {
91
+ try {
92
+ const llm = getLlm();
93
+ const query = getSessionQuery();
94
+ const route = resolveRoute(sessionId);
95
+ if (query === null || typeof query !== 'object') {
96
+ throw new ProgressError('QUERY_UNAVAILABLE', 'the sessionQuery service is unavailable');
97
+ }
98
+ const [config, surface] = await Promise.all([
99
+ typeof query.inspectSession === 'function'
100
+ ? query.inspectSession(sessionId, (session) => session?.requestHeader?.()?.config ?? undefined, scope.signal)
101
+ : Promise.resolve(undefined),
102
+ typeof query.readSurface === 'function'
103
+ ? query.readSurface(sessionId)
104
+ : Promise.resolve({ events: [] }),
105
+ ]);
106
+ const resolved = (config !== undefined && typeof config?.provider === 'string' && typeof config?.model === 'string')
107
+ ? config
108
+ : (typeof route === 'object' && route !== null ? route : undefined);
109
+ if (resolved === undefined || typeof resolved.provider !== 'string' || typeof resolved.model !== 'string') {
110
+ throw new ProgressError('NO_ROUTE', 'could not resolve a provider/model for this session');
111
+ }
112
+ const context = buildProgressContext(surface, {});
113
+ const report = await generateProgress({ llm, route: resolved, context, signal: scope.signal });
114
+ const current = states.get(sessionId);
115
+ if (current?.controller !== controller) return; // superseded by a newer call
116
+ states.set(sessionId, {
117
+ status: 'done',
118
+ startedAt,
119
+ updatedAt: Date.now(),
120
+ report,
121
+ });
122
+ } catch (error) {
123
+ const current = states.get(sessionId);
124
+ if (current?.controller !== controller) return;
125
+ if (scope.signal.aborted && !(error instanceof ProgressError)) return; // cancelled silently
126
+ states.set(sessionId, {
127
+ status: 'error',
128
+ startedAt,
129
+ updatedAt: Date.now(),
130
+ error: String(error?.message ?? error),
131
+ });
132
+ } finally {
133
+ scope.dispose();
134
+ }
135
+ })().catch(() => { /* never let a side call crash the Host */ });
136
+
137
+ return view(sessionId);
138
+ }
139
+
140
+ return {
141
+ start,
142
+ poll: (sessionId) => view(sessionId),
143
+ cancel,
144
+ /** Exposed for tests only. */
145
+ __test: { states, deadline },
146
+ };
147
+ }