@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.
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Power-Up task-progress side call.
3
+ *
4
+ * A session's progress is summarized by a SEPARATE model call that never enters
5
+ * the conversation log and never touches the running agent's turn or abort
6
+ * signal. The Host reads the session's recent surface messages, resolves the
7
+ * same provider/model the session last used, asks the model for a structured
8
+ * JSON progress report, and caches the latest report in memory for the Client
9
+ * panel to poll.
10
+ *
11
+ * Everything in this module is plain JS so it can be exercised by the offline
12
+ * tests without a DSH installation. It never imports `@deepseek-ai/*` at module
13
+ * load; the Host passes the `llm` service in at call time.
14
+ */
15
+
16
+ /** Default cooperative deadline for one side call. */
17
+ export const PROGRESS_TIMEOUT_MS = 45_000;
18
+
19
+ /** Upper bound on characters of session text fed into the side call. */
20
+ export const PROGRESS_CONTEXT_LIMIT = 24_000;
21
+
22
+ /** Max output tokens for the summary. */
23
+ export const PROGRESS_MAX_TOKENS = 900;
24
+
25
+ /** Number of recent surface messages considered. */
26
+ export const PROGRESS_MESSAGE_LIMIT = 60;
27
+
28
+ /** Cache TTL for a finished report, in milliseconds. */
29
+ export const PROGRESS_CACHE_TTL_MS = 5 * 60_000;
30
+
31
+ /** Report is considered stale for the overlay after this long. */
32
+ export const PROGRESS_STALE_MS = 60_000;
33
+
34
+ /** The JSON schema modes the model may choose from. */
35
+ export const PROGRESS_MODES = ['checklist', 'phases', 'milestones', 'tree'];
36
+
37
+ /**
38
+ * The single instruction sent to the side model. It deliberately lets the
39
+ * model choose a structure that fits the task instead of forcing one shape.
40
+ */
41
+ export const PROGRESS_SYSTEM_PROMPT = [
42
+ 'You are a task-progress reporter embedded in DeepSeek Harness.',
43
+ 'You will be given a compact transcript of a work session that is still in progress.',
44
+ 'Produce ONE JSON object and nothing else — no prose, no markdown fences.',
45
+ 'Pick the structure that best fits the task and set "mode" accordingly:',
46
+ ' - "checklist": a to-do list with discrete steps. Use "steps": [{"title","status","detail"}], status one of pending|in-progress|done|blocked.',
47
+ ' - "phases": ordered work phases. Use "phases": [{"name","status","detail","steps"?:[{"title","status"}]}].',
48
+ ' - "milestones": goal-oriented milestones. Use "milestones": [{"name","status","detail","criteria"?}].',
49
+ ' - "tree": hierarchical subtasks (e.g. subagents or nested work). Use "root": {"title","status","children"?:[...]}.',
50
+ 'Every mode also requires: "title" (short), "summary" (1-2 sentences), "percent" (integer 0-100), "blockers" (string array).',
51
+ 'You MAY add a "display" field to show extra information the user will see directly in the panel.',
52
+ '"display" is an array of blocks. Each block is either',
53
+ ' {"kind":"text","text":"..."} (plain text, line breaks preserved), or',
54
+ ' {"kind":"kv","items":[{"label":"...","value":"..."}]}, or',
55
+ ' {"kind":"callout","tone":"info"|"warn"|"success","text":"..."}, or',
56
+ ' {"kind":"bars","items":[{"label":"...","value":0-100}]}, or',
57
+ ' {"kind":"code","language":"...","text":"..."}.',
58
+ 'Keep "display" concise and genuinely useful; omit it when the structured fields already say everything.',
59
+ 'Be honest: if work has not started, say so; never invent progress. Base the report only on the transcript.',
60
+ ].join('\n');
61
+
62
+ /** Error with a stable machine code. */
63
+ export class ProgressError extends Error {
64
+ constructor(code, message, options = {}) {
65
+ super(`${code}: ${message}`);
66
+ this.name = 'ProgressError';
67
+ this.code = code;
68
+ if (options.cause !== undefined) this.cause = options.cause;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Accept either a live Session or a SessionSurfaceSnapshot and return a compact
74
+ * transcript of recent user/assistant text (tool names noted, arguments dropped).
75
+ * @param {object} session
76
+ * @param {{provider: string, model: string, maxTokens?: number}} route
77
+ * @returns {string}
78
+ */
79
+ export function buildProgressContext(session, options = {}) {
80
+ const limit = Number.isFinite(options.limit) ? options.limit : PROGRESS_CONTEXT_LIMIT;
81
+ const messageLimit = Number.isFinite(options.messageLimit) ? options.messageLimit : PROGRESS_MESSAGE_LIMIT;
82
+ const events = Array.isArray(session?.events) ? session.events : [];
83
+ const chunks = [];
84
+ let used = 0;
85
+ const selected = events.length > messageLimit ? events.slice(-messageLimit) : events;
86
+ for (const event of selected) {
87
+ if (event === null || typeof event !== 'object') continue;
88
+ let role = '';
89
+ let message = null;
90
+ if (event.type === 'user/message') {
91
+ role = 'User';
92
+ message = event.data;
93
+ } else if (event.type === 'assistant/message') {
94
+ role = 'Assistant';
95
+ message = event.data?.message;
96
+ } else if (event.role === 'user' || event.role === 'assistant') {
97
+ role = event.role === 'user' ? 'User' : 'Assistant';
98
+ message = event;
99
+ }
100
+ if (message === null || typeof message !== 'object') continue;
101
+ const parts = [];
102
+ for (const block of Array.isArray(message.content) ? message.content : []) {
103
+ if (block === null || typeof block !== 'object') continue;
104
+ if (block.type === 'text' && typeof block.text === 'string') {
105
+ parts.push(block.text.trim());
106
+ } else if (block.type === 'tool-call') {
107
+ const name = typeof block.name === 'string' ? block.name : 'tool';
108
+ parts.push(`[called ${name}]`);
109
+ } else if (block.type === 'tool-result') {
110
+ parts.push('[tool result]');
111
+ }
112
+ }
113
+ const text = parts.filter(Boolean).join('\n').trim();
114
+ if (text === '') continue;
115
+ const line = `${role}: ${text}`;
116
+ if (used + line.length > limit) break;
117
+ chunks.push(line);
118
+ used += line.length;
119
+ }
120
+ return chunks.join('\n\n').slice(0, limit);
121
+ }
122
+
123
+ /**
124
+ * Strip accidental markdown fences and parse the model text as one JSON object.
125
+ * @param {string} text
126
+ * @returns {object}
127
+ */
128
+ export function parseProgressReport(text) {
129
+ if (typeof text !== 'string' || text.trim() === '') {
130
+ throw new ProgressError('EMPTY', 'the model returned an empty progress report');
131
+ }
132
+ let cleaned = text.trim();
133
+ const fence = cleaned.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/iu);
134
+ if (fence !== null) cleaned = fence[1].trim();
135
+ let value;
136
+ try {
137
+ value = JSON.parse(cleaned);
138
+ } catch (error) {
139
+ throw new ProgressError('INVALID_JSON', 'the model did not return valid JSON', { cause: error });
140
+ }
141
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
142
+ throw new ProgressError('INVALID_SHAPE', 'the progress report must be a JSON object');
143
+ }
144
+ return normalizeProgressReport(value);
145
+ }
146
+
147
+ /**
148
+ * Normalize/validate a parsed report into a stable shape for the UI. Unknown
149
+ * fields are dropped, missing fields get safe defaults, and the mode is checked
150
+ * against the declared set.
151
+ * @param {object} value
152
+ * @returns {object}
153
+ */
154
+ export function normalizeProgressReport(value) {
155
+ const mode = PROGRESS_MODES.includes(value?.mode) ? value.mode : 'checklist';
156
+ const statusOf = (x) => ['pending', 'in-progress', 'done', 'blocked'].includes(x) ? x : 'pending';
157
+ const text = (x, max = 4000) => typeof x === 'string' ? x.trim().slice(0, max) : '';
158
+ const list = (x) => Array.isArray(x) ? x.filter((v) => v !== null && typeof v === 'object') : [];
159
+ const listStrings = (x) => Array.isArray(x) ? x : [];
160
+
161
+ const steps = list(value.steps).map((s) => ({
162
+ title: text(s.title, 240),
163
+ status: statusOf(s.status),
164
+ detail: text(s.detail, 1200),
165
+ })).filter((s) => s.title !== '');
166
+ const phases = list(value.phases).map((p) => ({
167
+ name: text(p.name, 240),
168
+ status: statusOf(p.status),
169
+ detail: text(p.detail, 1200),
170
+ steps: list(p.steps).map((s) => ({
171
+ title: text(s.title, 240),
172
+ status: statusOf(s.status),
173
+ })).filter((s) => s.title !== ''),
174
+ })).filter((p) => p.name !== '');
175
+ const milestones = list(value.milestones).map((m) => ({
176
+ name: text(m.name, 240),
177
+ status: statusOf(m.status),
178
+ detail: text(m.detail, 1200),
179
+ criteria: text(m.criteria, 600),
180
+ })).filter((m) => m.name !== '');
181
+ const normalizeNode = (node, depth = 0) => {
182
+ if (depth > 6 || node === null || typeof node !== 'object') return null;
183
+ return {
184
+ title: text(node.title ?? node.name, 240),
185
+ status: statusOf(node.status),
186
+ detail: text(node.detail, 800),
187
+ children: list(node.children).map((c) => normalizeNode(c, depth + 1)).filter(Boolean),
188
+ };
189
+ };
190
+ const tree = normalizeNode(value.root) ?? normalizeNode(value.tree) ?? null;
191
+
192
+ const display = list(value.display).map((block) => {
193
+ if (block.kind === 'text') return { kind: 'text', text: text(block.text, 8000) };
194
+ if (block.kind === 'kv') {
195
+ return {
196
+ kind: 'kv',
197
+ items: list(block.items).map((item) => ({
198
+ label: text(item.label, 160),
199
+ value: text(item.value, 1200),
200
+ })).filter((item) => item.label !== ''),
201
+ };
202
+ }
203
+ if (block.kind === 'callout') {
204
+ return {
205
+ kind: 'callout',
206
+ tone: ['info', 'warn', 'success'].includes(block.tone) ? block.tone : 'info',
207
+ text: text(block.text, 2000),
208
+ };
209
+ }
210
+ if (block.kind === 'bars') {
211
+ return {
212
+ kind: 'bars',
213
+ items: list(block.items).map((item) => ({
214
+ label: text(item.label, 160),
215
+ value: Math.max(0, Math.min(100, Math.round(Number(item.value) || 0))),
216
+ })).filter((item) => item.label !== ''),
217
+ };
218
+ }
219
+ if (block.kind === 'code') {
220
+ return { kind: 'code', language: text(block.language, 40), text: text(block.text, 8000) };
221
+ }
222
+ return null;
223
+ }).filter(Boolean);
224
+
225
+ const percentRaw = Number(value.percent);
226
+ return {
227
+ mode,
228
+ title: text(value.title, 240) || 'Task progress',
229
+ summary: text(value.summary, 2400),
230
+ percent: Number.isFinite(percentRaw) ? Math.max(0, Math.min(100, Math.round(percentRaw))) : 0,
231
+ blockers: listStrings(value.blockers).map((b) => text(b, 600)).filter(Boolean),
232
+ steps,
233
+ phases,
234
+ milestones,
235
+ tree,
236
+ display,
237
+ updatedAt: Date.now(),
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Assemble accumulated text chunks and check the terminal finish reason.
243
+ * @param {string} text
244
+ * @param {{kind: string} | undefined} finish
245
+ * @returns {string}
246
+ */
247
+ export function finishReport(text, finish) {
248
+ if (finish?.kind === 'error' || finish?.kind === 'aborted') {
249
+ throw new ProgressError('LLM_FAILED', `the side model call ${finish.kind ?? 'failed'}`);
250
+ }
251
+ if (finish?.kind === 'max-tokens') {
252
+ throw new ProgressError('TRUNCATED', 'the side model hit its token limit before finishing');
253
+ }
254
+ return text;
255
+ }
256
+
257
+ /**
258
+ * Perform the side call. The caller supplies the `llm` service, the route, the
259
+ * transcript and its own AbortSignal; this function writes nothing durable.
260
+ *
261
+ * @param {object} options
262
+ * @param {object} options.llm the Host `ctx.llm` service
263
+ * @param {{provider: string, model: string, reasoningEffort?: string, maxTokens?: number}} options.route
264
+ * @param {string} options.context compact transcript
265
+ * @param {AbortSignal} [options.signal]
266
+ * @returns {Promise<object>} a normalized progress report
267
+ */
268
+ export async function generateProgress({ llm, route, context, signal }) {
269
+ if (llm === null || typeof llm !== 'object' || typeof llm.prepareCall !== 'function') {
270
+ throw new ProgressError('LLM_UNAVAILABLE', 'the llm service is unavailable');
271
+ }
272
+ if (route === null || typeof route !== 'object' || typeof route.provider !== 'string' || typeof route.model !== 'string') {
273
+ throw new ProgressError('NO_ROUTE', 'no provider/model route is available for this session');
274
+ }
275
+ const config = {
276
+ provider: route.provider,
277
+ model: route.model,
278
+ ...(typeof route.reasoningEffort === 'string' ? { reasoningEffort: route.reasoningEffort } : {}),
279
+ maxTokens: Number.isFinite(route.maxTokens) ? route.maxTokens : PROGRESS_MAX_TOKENS,
280
+ };
281
+ const call = await llm.prepareCall(config, signal);
282
+ const prompt = [
283
+ 'Session transcript (may be truncated):',
284
+ '---',
285
+ context || '(no recent user or assistant text)',
286
+ '---',
287
+ 'Return only the JSON progress object described in your instructions.',
288
+ ].join('\n');
289
+ const options = {
290
+ ...call.config,
291
+ messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
292
+ system: PROGRESS_SYSTEM_PROMPT,
293
+ purpose: 'task-progress',
294
+ ...(signal === undefined ? {} : { signal }),
295
+ };
296
+ let text = '';
297
+ let finish;
298
+ for await (const chunk of call.stream(options)) {
299
+ if (signal?.aborted) throw new ProgressError('ABORTED', 'the progress call was cancelled');
300
+ if (chunk === null || typeof chunk !== 'object') continue;
301
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
302
+ text += chunk.text;
303
+ } else if (chunk.type === 'finish') {
304
+ finish = chunk.reason;
305
+ }
306
+ }
307
+ return parseProgressReport(finishReport(text, finish));
308
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * dsh-powerup — task-aware restart / shutdown helpers.
3
+ *
4
+ * Plain JS, dependency-free so the offline suites can exercise it. The Host
5
+ * passes live services in at call time; nothing here imports `@deepseek-ai/*`
6
+ * at module load.
7
+ *
8
+ * Two responsibilities:
9
+ * 1. Snapshot unfinished work (live running Agents plus running background
10
+ * jobs) so a restart/close request can refuse the normal path.
11
+ * 2. Persist a small "pending resume" queue to disk when a forced restart /
12
+ * close is requested with `resume: true`, and replay it on the next
13
+ * successful application startup by sending each session a continuation
14
+ * prompt through `sessionController.prompt` (which resumes cold sessions).
15
+ */
16
+
17
+ /** Central store file name, next to prompts.json / mask-rules.json. */
18
+ export const TASK_RESUME_FILE = 'task-resume.json';
19
+
20
+ /** Default continuation prompt; the user sees it as a real user message. */
21
+ export const DEFAULT_RESUME_PROMPT = '继续之前未完成的任务。';
22
+
23
+ /** Max number of records kept in the queue, so a corrupt file cannot explode startup. */
24
+ const MAX_RECORDS = 500;
25
+
26
+ /** Max characters kept for a session title in the queue. */
27
+ const TITLE_LIMIT = 200;
28
+
29
+ /**
30
+ * Clamp arbitrary text to a single line of bounded length (control chars gone).
31
+ * @param {unknown} value
32
+ * @param {number} [limit]
33
+ * @returns {string}
34
+ */
35
+ export function cleanText(value, limit = TITLE_LIMIT) {
36
+ if (typeof value !== 'string') return '';
37
+ return value
38
+ .replace(/[\u0000-\u001f\u007f]+/gu, ' ')
39
+ .replace(/\s+/gu, ' ')
40
+ .trim()
41
+ .slice(0, limit);
42
+ }
43
+
44
+ /**
45
+ * Collect unfinished work from live Host services.
46
+ * @param {{agents?: any, jobs?: any}} services
47
+ * @returns {Array<{id: string, title: string, kind: 'agent'|'job', running: boolean}>}
48
+ */
49
+ export function collectRunningTasks(services = {}) {
50
+ const tasks = [];
51
+ const agents = services.agents;
52
+ try {
53
+ const list = typeof agents?.list === 'function' ? agents.list() : [];
54
+ for (const agent of Array.isArray(list) ? list : []) {
55
+ if (agent === null || typeof agent !== 'object') continue;
56
+ // Cold sessions are never `running`; only the live driver knows.
57
+ if (agent.status !== 'running') continue;
58
+ const id = typeof agent.id === 'string' ? agent.id : agent.session?.id;
59
+ if (typeof id !== 'string' || id === '') continue;
60
+ tasks.push({
61
+ id,
62
+ title: taskTitle(agent),
63
+ kind: 'agent',
64
+ running: true,
65
+ });
66
+ }
67
+ } catch {
68
+ /* A service that is still warming up contributes no tasks. */
69
+ }
70
+ const jobs = services.jobs;
71
+ try {
72
+ const list = typeof jobs?.list === 'function' ? jobs.list() : [];
73
+ for (const job of Array.isArray(list) ? list : []) {
74
+ if (job === null || typeof job !== 'object') continue;
75
+ if (job.status !== 'running') continue;
76
+ const id = typeof job.id === 'string' ? job.id : '';
77
+ if (id === '') continue;
78
+ // Avoid duplicating the same work when a job view carries its owner.
79
+ if (tasks.some((task) => task.id === id)) continue;
80
+ tasks.push({
81
+ id,
82
+ title: cleanText(job.title ?? job.kind ?? 'background job', TITLE_LIMIT),
83
+ kind: 'job',
84
+ running: true,
85
+ });
86
+ }
87
+ } catch {
88
+ /* Optional service. */
89
+ }
90
+ return tasks.slice(0, MAX_RECORDS);
91
+ }
92
+
93
+ /** Best-effort human label for one live Agent. */
94
+ function taskTitle(agent) {
95
+ try {
96
+ const title = agent.session?.title?.();
97
+ if (typeof title === 'string' && title.trim() !== '') return cleanText(title);
98
+ } catch {
99
+ /* fall through */
100
+ }
101
+ return 'session';
102
+ }
103
+
104
+ /**
105
+ * Read the pending-resume queue from a JSON file.
106
+ * @param {string} filePath
107
+ * @returns {Array<object>}
108
+ */
109
+ export function readResumeQueue(filePath, readFile) {
110
+ try {
111
+ const parsed = JSON.parse(readFile(filePath, 'utf8'));
112
+ if (!Array.isArray(parsed)) return [];
113
+ return parsed.filter((record) => record !== null && typeof record === 'object'
114
+ && typeof record.sessionId === 'string' && record.sessionId !== '').slice(0, MAX_RECORDS);
115
+ } catch (error) {
116
+ if (error?.code === 'ENOENT') return [];
117
+ return [];
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Build one resume record.
123
+ * @param {{sessionId: string, title?: string, prompt?: string, forcedAt?: number}} input
124
+ * @returns {{sessionId: string, requestId: string, title: string, prompt: string, createdAt: number}}
125
+ */
126
+ export function createResumeRecord(input, randomUUID) {
127
+ const sessionId = typeof input?.sessionId === 'string' ? input.sessionId : '';
128
+ if (sessionId === '') throw new TypeError('sessionId is required');
129
+ const prompt = cleanText(input.prompt, 4000) || DEFAULT_RESUME_PROMPT;
130
+ return {
131
+ sessionId,
132
+ requestId: typeof randomUUID === 'function' ? randomUUID() : `resume-${Date.now()}-${Math.random().toString(36).slice(2)}`,
133
+ title: cleanText(input.title),
134
+ prompt,
135
+ createdAt: Number.isFinite(input.forcedAt) ? input.forcedAt : Date.now(),
136
+ };
137
+ }
138
+
139
+ /**
140
+ * Append resume records to the queue, deduplicated by sessionId.
141
+ * @param {Array<object>} queue
142
+ * @param {Array<object>} records
143
+ * @returns {Array<object>}
144
+ */
145
+ export function mergeResumeQueue(queue, records) {
146
+ const merged = Array.isArray(queue) ? queue.slice() : [];
147
+ const seen = new Set(merged.map((record) => record.sessionId));
148
+ for (const record of Array.isArray(records) ? records : []) {
149
+ if (record === null || typeof record !== 'object') continue;
150
+ if (typeof record.sessionId !== 'string' || record.sessionId === '') continue;
151
+ if (seen.has(record.sessionId)) continue;
152
+ seen.add(record.sessionId);
153
+ merged.push(record);
154
+ }
155
+ return merged.slice(-MAX_RECORDS);
156
+ }
157
+
158
+ /**
159
+ * Cancel each running live Agent and kill each running job. Best effort: the
160
+ * restart proceeds even if one cancellation fails.
161
+ * @param {{agents?: any, jobs?: any}} services
162
+ * @param {string} [reason]
163
+ * @returns {{cancelledAgents: string[], killedJobs: string[], errors: string[]}}
164
+ */
165
+ export function stopUnfinishedTasks(services = {}, reason = 'dsh-powerup forced app action') {
166
+ const result = { cancelledAgents: [], killedJobs: [], errors: [] };
167
+ const agents = services.agents;
168
+ try {
169
+ const list = typeof agents?.list === 'function' ? agents.list() : [];
170
+ for (const agent of Array.isArray(list) ? list : []) {
171
+ if (agent?.status !== 'running') continue;
172
+ const id = typeof agent.id === 'string' ? agent.id : agent.session?.id;
173
+ try {
174
+ if (typeof agent.cancel !== 'function') continue;
175
+ agent.cancel({ kind: 'user', reason }, { keepInbox: false });
176
+ if (typeof id === 'string' && id !== '') result.cancelledAgents.push(id);
177
+ } catch (error) {
178
+ result.errors.push(`agent ${id ?? '?'}: ${String(error?.message ?? error)}`);
179
+ }
180
+ }
181
+ } catch (error) {
182
+ result.errors.push(`agents: ${String(error?.message ?? error)}`);
183
+ }
184
+ const jobs = services.jobs;
185
+ try {
186
+ const list = typeof jobs?.list === 'function' ? jobs.list() : [];
187
+ for (const job of Array.isArray(list) ? list : []) {
188
+ if (job?.status !== 'running') continue;
189
+ const id = typeof job.id === 'string' ? job.id : '';
190
+ if (id === '') continue;
191
+ try {
192
+ const owner = typeof job.sessionId === 'string' ? job.sessionId : typeof job.owner === 'string' ? job.owner : undefined;
193
+ jobs.kill(id, owner, reason);
194
+ result.killedJobs.push(id);
195
+ } catch (error) {
196
+ result.errors.push(`job ${id}: ${String(error?.message ?? error)}`);
197
+ }
198
+ }
199
+ } catch (error) {
200
+ result.errors.push(`jobs: ${String(error?.message ?? error)}`);
201
+ }
202
+ return result;
203
+ }
204
+
205
+ /**
206
+ * Replay pending resumes once startup is committed. Each prompt is sent
207
+ * through `sessionController.prompt`, which resumes a cold session internally.
208
+ * A record is removed from the queue only after its prompt is accepted.
209
+ *
210
+ * @param {{sessionController?: any, readFile: Function, writeFile: Function, mkdir: Function, dirname: Function, randomUUID: Function, logger?: Function}} deps
211
+ * @returns {Promise<{delivered: string[], failed: Array<{sessionId: string, error: string}>, remaining: number}>}
212
+ */
213
+ export async function replayPendingResumes(deps) {
214
+ const { readFile, writeFile, mkdir, dirname, randomUUID } = deps;
215
+ const filePath = deps.filePath;
216
+ const queue = readResumeQueue(filePath, readFile);
217
+ if (queue.length === 0) return { delivered: [], failed: [], remaining: 0 };
218
+
219
+ const result = { delivered: [], failed: [], remaining: 0 };
220
+ const pending = [];
221
+ const controller = deps.sessionController;
222
+
223
+ for (const record of queue) {
224
+ if (controller === null || typeof controller?.prompt !== 'function') {
225
+ pending.push(record);
226
+ continue;
227
+ }
228
+ const signal = deps.signal ?? new AbortController().signal;
229
+ try {
230
+ await controller.prompt({
231
+ requestId: randomUUID(),
232
+ sessionId: record.sessionId,
233
+ mode: 'queue',
234
+ content: [{ type: 'text', text: record.prompt || DEFAULT_RESUME_PROMPT }],
235
+ }, signal);
236
+ result.delivered.push(record.sessionId);
237
+ } catch (error) {
238
+ result.failed.push({ sessionId: record.sessionId, error: String(error?.message ?? error) });
239
+ pending.push(record);
240
+ if (typeof deps.logger === 'function') {
241
+ deps.logger(`[dsh-powerup] resume prompt failed for ${record.sessionId}: ${String(error?.message ?? error)}`);
242
+ }
243
+ }
244
+ }
245
+
246
+ result.remaining = pending.length;
247
+ try {
248
+ mkdir(dirname(filePath), { recursive: true });
249
+ writeFile(filePath, JSON.stringify(pending, null, 2) + '\n', 'utf8');
250
+ } catch (error) {
251
+ if (typeof deps.logger === 'function') {
252
+ deps.logger(`[dsh-powerup] could not persist resume queue: ${String(error?.message ?? error)}`);
253
+ }
254
+ }
255
+ return result;
256
+ }
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Power-Up",
4
- "description": "Independently toggleable upgrades for DeepSeek Harness on the Power-Up page: trajectory context menu and step references, job stop reasons, one-click plugin install, sidebar icon grid and back-to-top, session switching and locating, workspace prompts, plus conversation rendering enhancements (regex reply masking) and dual send buttons (queued/interrupt)."
4
+ "description": "Independently toggleable upgrades for DeepSeek Harness on the Power-Up page: trajectory context menu and step references, job stop reasons, one-click plugin install, sidebar icon grid and back-to-top, session switching and locating, workspace prompts, non-blocking model-generated structured task progress, plus conversation rendering enhancements (regex reply masking) and dual send buttons (queued/interrupt)."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Power-Up",
4
- "description": "为 DeepSeek Harness 提供一组可在 Power-Up 页面独立开关的增强:轨迹右键菜单与步骤引用、后台任务停止原因、插件一键安装、侧边栏图标网格与回到顶部、会话切换与定位、工作区提示词,以及会话内容渲染增强(回复内容正则屏蔽)和双发送按钮(等待/插话)。"
4
+ "description": "为 DeepSeek Harness 提供一组可在 Power-Up 页面独立开关的增强:轨迹右键菜单与步骤引用、后台任务停止原因、插件一键安装、侧边栏图标网格与回到顶部、会话切换与定位、工作区提示词、旁路模型生成的结构化任务进度,以及会话内容渲染增强(回复内容正则屏蔽)和双发送按钮(等待/插话)。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@restregular/dsh-powerup",
3
- "version": "0.10.7",
4
- "description": "为 DeepSeek Harness 提供一组可选的小型增强:轨迹右键菜单与步骤引用、后台任务停止原因、插件一键安装、侧边栏图标网格、会话切换、定位当前会话、工作区提示词;所有功能均可在 Power-Up 页面独立开关。 · Opt-in upgrades for DeepSeek Harness: Trajectory context menu and step references, job stop reasons, one-click plugin install, an adaptive sidebar launcher, session switching, locating the current session, and workspace prompts — each toggled independently on the Power-Up page.",
3
+ "version": "0.12.0",
4
+ "description": "为 DeepSeek Harness 提供一组可选的小型增强:轨迹右键菜单与步骤引用、后台任务停止原因、插件一键安装、侧边栏图标网格、会话切换、定位当前会话、工作区提示词、旁路模型生成的结构化任务进度;所有功能均可在 Power-Up 页面独立开关。 · Opt-in upgrades for DeepSeek Harness: Trajectory context menu and step references, job stop reasons, one-click plugin install, an adaptive sidebar launcher, session switching, locating the current session, workspace prompts, and non-blocking model-generated structured task progress — each toggled independently on the Power-Up page.",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",
7
7
  "main": "index.js",
@@ -21,6 +21,9 @@
21
21
  "lib/restart-helper.cjs",
22
22
  "lib/step-reference.js",
23
23
  "lib/step-tool.js",
24
+ "lib/progress-tool.js",
25
+ "lib/progress-manager.js",
26
+ "lib/task-resume.js",
24
27
  "locale/*.json",
25
28
  "icon.svg",
26
29
  "README.md",
@@ -81,7 +84,10 @@
81
84
  "close",
82
85
  "session-switch",
83
86
  "workspace",
84
- "locate"
87
+ "locate",
88
+ "task-progress",
89
+ "side-llm",
90
+ "visualization"
85
91
  ],
86
92
  "publishConfig": {
87
93
  "access": "public",
@@ -91,7 +97,7 @@
91
97
  "node": ">=22.13.0"
92
98
  },
93
99
  "scripts": {
94
- "test": "node test/smoke.mjs && node test/host.mjs"
100
+ "test": "node test/smoke.mjs && node test/host.mjs && node test/progress.mjs && node test/task-resume.mjs"
95
101
  },
96
102
  "license": "MIT",
97
103
  "author": "RestRegular"