@restregular/dsh-powerup 0.12.0 → 0.13.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/README.md +28 -1
- package/client.js +580 -45
- package/index.js +213 -7
- package/lib/direct-ask.js +115 -0
- package/lib/progress-manager.js +49 -7
- package/lib/progress-tool.js +13 -4
- package/lib/task-resume.js +20 -5
- package/package.json +3 -2
package/index.js
CHANGED
|
@@ -50,6 +50,7 @@ import {
|
|
|
50
50
|
} from './lib/task-resume.js';
|
|
51
51
|
import { createStepReadTool } from './lib/step-tool.js';
|
|
52
52
|
import { createProgressManager } from './lib/progress-manager.js';
|
|
53
|
+
import { buildAskPrompt, cleanAskText, directAsk } from './lib/direct-ask.js';
|
|
53
54
|
|
|
54
55
|
/** Prefix owned by this plugin. */
|
|
55
56
|
const ROUTE = '/dsh-powerup/api';
|
|
@@ -75,6 +76,10 @@ const PROMPTS_FILE = 'prompts.json';
|
|
|
75
76
|
const MASK_RULES_FILE = 'mask-rules.json';
|
|
76
77
|
/** Pending continuation prompts recorded by forced restart / close. */
|
|
77
78
|
const TASK_RESUME_FILE_NAME = TASK_RESUME_FILE;
|
|
79
|
+
/** Persisted progress-generation requirements (global + per workspace/session). */
|
|
80
|
+
const PROGRESS_REQUIREMENTS_FILE = 'progress-requirements.json';
|
|
81
|
+
/** Story of generated progress reports, kept on disk so refreshes never drop history. */
|
|
82
|
+
const PROGRESS_HISTORY_FILE = 'progress-history.json';
|
|
78
83
|
/** Legacy relative location inside a workspace, used only for migration. */
|
|
79
84
|
const LEGACY_STORE_DIR = join('.dsh', 'dsh-powerup');
|
|
80
85
|
|
|
@@ -173,14 +178,14 @@ function sendJson(res, payload, status = 200) {
|
|
|
173
178
|
* @param {import('node:http').IncomingMessage} req
|
|
174
179
|
* @returns {Promise<unknown>}
|
|
175
180
|
*/
|
|
176
|
-
async function readJsonBody(req) {
|
|
181
|
+
async function readJsonBody(req, limit = BODY_LIMIT) {
|
|
177
182
|
// Some callers (and older test doubles) send no stream at all.
|
|
178
183
|
if (req === null || typeof req !== 'object' || typeof req[Symbol.asyncIterator] !== 'function') return {};
|
|
179
184
|
const chunks = [];
|
|
180
185
|
let size = 0;
|
|
181
186
|
for await (const chunk of req) {
|
|
182
187
|
size += chunk.length;
|
|
183
|
-
if (size >
|
|
188
|
+
if (size > limit) throw new Error('body-too-large');
|
|
184
189
|
chunks.push(chunk);
|
|
185
190
|
}
|
|
186
191
|
if (size === 0) return {};
|
|
@@ -396,6 +401,17 @@ function promptStorePath() {
|
|
|
396
401
|
return storePath(PROMPTS_FILE);
|
|
397
402
|
}
|
|
398
403
|
|
|
404
|
+
/** Read one JSON object from disk; a missing or invalid file becomes an empty object. */
|
|
405
|
+
function readJsonObject(filePath) {
|
|
406
|
+
try {
|
|
407
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
408
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
409
|
+
} catch (error) {
|
|
410
|
+
if (error?.code === 'ENOENT') return {};
|
|
411
|
+
return {};
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
399
415
|
/** Read one JSON list from disk; a missing file is an empty list. */
|
|
400
416
|
function readJsonStore(filePath) {
|
|
401
417
|
try {
|
|
@@ -457,11 +473,121 @@ async function handle(req, res, ctx) {
|
|
|
457
473
|
|
|
458
474
|
const url = new URL(req.url ?? ROUTE, 'http://localhost');
|
|
459
475
|
const op = url.pathname.slice(ROUTE.length).replace(/^\/+/u, '') || url.searchParams.get('op') || '';
|
|
460
|
-
if (op !== '' && op !== 'restart' && op !== 'close' && op !== 'self-update' && op !== 'audit' && op !== 'job-kill' && op !== 'prompts' && op !== 'mask-rules' && op !== 'progress') {
|
|
476
|
+
if (op !== '' && op !== 'restart' && op !== 'close' && op !== 'self-update' && op !== 'audit' && op !== 'job-kill' && op !== 'prompts' && op !== 'mask-rules' && op !== 'progress' && op !== 'progress-requirements' && op !== 'progress-history' && op !== 'direct-ask') {
|
|
461
477
|
sendJson(res, { ok: false, error: 'not-found' }, 404);
|
|
462
478
|
return;
|
|
463
479
|
}
|
|
464
480
|
|
|
481
|
+
if (op === 'progress-requirements') {
|
|
482
|
+
const filePath = storePath(PROGRESS_REQUIREMENTS_FILE);
|
|
483
|
+
if (req.method === 'POST') {
|
|
484
|
+
try {
|
|
485
|
+
const body = await readJsonBody(req);
|
|
486
|
+
const requirements = body?.requirements !== null && typeof body?.requirements === 'object'
|
|
487
|
+
? body.requirements
|
|
488
|
+
: {};
|
|
489
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
490
|
+
writeFileSync(filePath, JSON.stringify(requirements, null, 2) + '\n', 'utf8');
|
|
491
|
+
sendJson(res, { ok: true, requirements });
|
|
492
|
+
} catch (error) {
|
|
493
|
+
sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
|
|
494
|
+
}
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (req.method !== 'GET') {
|
|
498
|
+
sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
try {
|
|
502
|
+
sendJson(res, { ok: true, requirements: readJsonObject(filePath) });
|
|
503
|
+
} catch (error) {
|
|
504
|
+
sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
|
|
505
|
+
}
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
if (op === 'progress-history') {
|
|
510
|
+
const filePath = storePath(PROGRESS_HISTORY_FILE);
|
|
511
|
+
if (req.method === 'GET') {
|
|
512
|
+
try {
|
|
513
|
+
const all = readJsonObject(filePath);
|
|
514
|
+
sendJson(res, { ok: true, records: all.records ?? {} });
|
|
515
|
+
} catch (error) {
|
|
516
|
+
sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
|
|
517
|
+
}
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
if (req.method === 'POST') {
|
|
521
|
+
try {
|
|
522
|
+
const body = await readJsonBody(req, 4 * 1024 * 1024);
|
|
523
|
+
const records = body?.records !== null && typeof body?.records === 'object' ? body.records : {};
|
|
524
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
525
|
+
writeFileSync(filePath, JSON.stringify({ records }, null, 2) + '\n', 'utf8');
|
|
526
|
+
sendJson(res, { ok: true, records });
|
|
527
|
+
} catch (error) {
|
|
528
|
+
sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
|
|
529
|
+
}
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
if (op === 'direct-ask') {
|
|
537
|
+
if (req.method !== 'POST') {
|
|
538
|
+
sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
let body;
|
|
542
|
+
try {
|
|
543
|
+
body = await readJsonBody(req, 4 * 1024 * 1024);
|
|
544
|
+
} catch (error) {
|
|
545
|
+
sendJson(res, { ok: false, error: String(error?.message ?? error) }, 400);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
|
|
549
|
+
const context = Array.isArray(body?.context) ? body.context : [];
|
|
550
|
+
const prompt = buildAskPrompt({ question: cleanAskText(body?.question), context });
|
|
551
|
+
if (prompt === '') {
|
|
552
|
+
sendJson(res, { ok: false, code: 'invalid-request', error: 'question is required' }, 400);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
const llm = ctx?.get?.('llm');
|
|
556
|
+
if (llm === null || typeof llm?.prepareCall !== 'function') {
|
|
557
|
+
sendJson(res, { ok: false, code: 'llm-unavailable', error: 'the llm service is unavailable' }, 503);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
// Prefer the current session's model; fall back to the default selection.
|
|
561
|
+
let route;
|
|
562
|
+
try {
|
|
563
|
+
const query = ctx?.get?.('sessionQuery');
|
|
564
|
+
if (sessionId !== '' && typeof query?.inspectSession === 'function') {
|
|
565
|
+
route = await query.inspectSession(sessionId, (session) => session?.requestHeader?.()?.config ?? undefined);
|
|
566
|
+
}
|
|
567
|
+
} catch {
|
|
568
|
+
/* fall through to default */
|
|
569
|
+
}
|
|
570
|
+
if (route === null || typeof route !== 'object' || typeof route.provider !== 'string') {
|
|
571
|
+
const defaults = ctx?.get?.('agentDefaultModel');
|
|
572
|
+
const selection = typeof defaults?.currentSelection === 'function' ? defaults.currentSelection() : undefined;
|
|
573
|
+
route = selection !== null && typeof selection === 'object' && typeof selection.provider === 'string'
|
|
574
|
+
? selection
|
|
575
|
+
: undefined;
|
|
576
|
+
}
|
|
577
|
+
const controller = new AbortController();
|
|
578
|
+
const timer = setTimeout(() => controller.abort(), 90_000);
|
|
579
|
+
timer.unref?.();
|
|
580
|
+
try {
|
|
581
|
+
const answer = await directAsk({ llm, route, prompt, signal: controller.signal });
|
|
582
|
+
sendJson(res, { ok: true, answer: answer.text, finish: answer.finish ?? null });
|
|
583
|
+
} catch (error) {
|
|
584
|
+
sendJson(res, { ok: false, code: error?.code ?? 'ask-failed', error: String(error?.message ?? error) }, 500);
|
|
585
|
+
} finally {
|
|
586
|
+
clearTimeout(timer);
|
|
587
|
+
}
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
|
|
465
591
|
if (op === 'progress') {
|
|
466
592
|
if (req.method !== 'POST') {
|
|
467
593
|
sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
|
|
@@ -479,18 +605,26 @@ async function handle(req, res, ctx) {
|
|
|
479
605
|
sendJson(res, { ok: false, code: 'invalid-request', error: 'sessionId is required' }, 400);
|
|
480
606
|
return;
|
|
481
607
|
}
|
|
482
|
-
const action = ['start', 'poll', 'cancel'].includes(body?.action) ? body.action : 'poll';
|
|
608
|
+
const action = ['start', 'poll', 'cancel', 'clear'].includes(body?.action) ? body.action : 'poll';
|
|
483
609
|
const manager = ctx?.__powerupProgress;
|
|
484
610
|
if (manager === undefined) {
|
|
485
611
|
sendJson(res, { ok: false, code: 'unavailable', error: 'progress service is not ready' }, 503);
|
|
486
612
|
return;
|
|
487
613
|
}
|
|
488
614
|
try {
|
|
615
|
+
// A one-off requirements override from the progress panel is kept for
|
|
616
|
+
// the next start; it does not modify the persisted layers.
|
|
617
|
+
if (typeof body?.requirements === 'string') {
|
|
618
|
+
ctx.__powerupProgressOverride = ctx.__powerupProgressOverride ?? {};
|
|
619
|
+
ctx.__powerupProgressOverride[sessionId] = body.requirements;
|
|
620
|
+
}
|
|
489
621
|
const view = action === 'start'
|
|
490
622
|
? manager.start(sessionId)
|
|
491
623
|
: action === 'cancel'
|
|
492
624
|
? manager.cancel(sessionId)
|
|
493
|
-
:
|
|
625
|
+
: action === 'clear'
|
|
626
|
+
? { ...manager.poll(sessionId), history: manager.clearHistory(sessionId) }
|
|
627
|
+
: manager.poll(sessionId);
|
|
494
628
|
sendJson(res, { ok: true, action, ...view });
|
|
495
629
|
} catch (error) {
|
|
496
630
|
sendJson(res, { ok: false, code: 'progress-failed', error: String(error?.message ?? error) }, 500);
|
|
@@ -641,7 +775,11 @@ async function handle(req, res, ctx) {
|
|
|
641
775
|
if (req.method === 'GET') {
|
|
642
776
|
// Expose unfinished work so the UI can gate the normal action and offer
|
|
643
777
|
// the forced variant. A runtime that cannot restart still reports tasks.
|
|
644
|
-
const tasks = collectRunningTasks({
|
|
778
|
+
const tasks = collectRunningTasks({
|
|
779
|
+
agents: ctx?.get?.('agents'),
|
|
780
|
+
jobs: ctx?.get?.('jobs'),
|
|
781
|
+
sessionTitle: ctx?.get?.('sessionTitle'),
|
|
782
|
+
});
|
|
645
783
|
sendJson(res, {
|
|
646
784
|
ok: true,
|
|
647
785
|
action,
|
|
@@ -664,7 +802,11 @@ async function handle(req, res, ctx) {
|
|
|
664
802
|
const force = body?.force === true;
|
|
665
803
|
const requested = body?.force === true || body?.resume === true || body?.action !== undefined;
|
|
666
804
|
const tasks = requested
|
|
667
|
-
? collectRunningTasks({
|
|
805
|
+
? collectRunningTasks({
|
|
806
|
+
agents: ctx?.get?.('agents'),
|
|
807
|
+
jobs: ctx?.get?.('jobs'),
|
|
808
|
+
sessionTitle: ctx?.get?.('sessionTitle'),
|
|
809
|
+
})
|
|
668
810
|
: [];
|
|
669
811
|
if (requested && tasks.length > 0 && !force) {
|
|
670
812
|
sendJson(res, {
|
|
@@ -762,6 +904,40 @@ export function apply(ctx) {
|
|
|
762
904
|
// The progress side call needs both `llm` and `sessionQuery`. Wait for them
|
|
763
905
|
// through inject so a late-provided service still creates the manager.
|
|
764
906
|
ctx.inject(['llm', 'sessionQuery'], (scope) => {
|
|
907
|
+
// Requirements are stored as { global, workspaces: {id: text}, sessions: {id: text} }.
|
|
908
|
+
// The active requirements for a session are the concatenation of the global,
|
|
909
|
+
// workspace and session layers; the UI may pass a one-off override too.
|
|
910
|
+
const requirementsFor = (sessionId, override) => {
|
|
911
|
+
const saved = readJsonObject(storePath(PROGRESS_REQUIREMENTS_FILE));
|
|
912
|
+
const parts = [];
|
|
913
|
+
if (typeof saved.global === 'string' && saved.global.trim() !== '') parts.push(saved.global.trim());
|
|
914
|
+
const workspaces = saved.workspaces !== null && typeof saved.workspaces === 'object' ? saved.workspaces : {};
|
|
915
|
+
const sessions = saved.sessions !== null && typeof saved.sessions === 'object' ? saved.sessions : {};
|
|
916
|
+
// Resolve the session's workspace id without activating an Agent.
|
|
917
|
+
let workspaceId = '';
|
|
918
|
+
try {
|
|
919
|
+
const registry = scope.get('workspaceRegistry');
|
|
920
|
+
const ws = typeof registry?.list === 'function' ? registry.list() : [];
|
|
921
|
+
for (const item of Array.isArray(ws) ? ws : []) {
|
|
922
|
+
if (Array.isArray(item?.sessionIds) && item.sessionIds.includes(sessionId)) {
|
|
923
|
+
workspaceId = typeof item.id === 'string' ? item.id : '';
|
|
924
|
+
break;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
} catch {
|
|
928
|
+
/* workspace layer is optional */
|
|
929
|
+
}
|
|
930
|
+
if (workspaceId !== '' && typeof workspaces[workspaceId] === 'string' && workspaces[workspaceId].trim() !== '') {
|
|
931
|
+
parts.push(workspaces[workspaceId].trim());
|
|
932
|
+
}
|
|
933
|
+
if (typeof sessions[sessionId] === 'string' && sessions[sessionId].trim() !== '') {
|
|
934
|
+
parts.push(sessions[sessionId].trim());
|
|
935
|
+
}
|
|
936
|
+
if (typeof override === 'string' && override.trim() !== '') parts.push(override.trim());
|
|
937
|
+
return parts.join('\n\n');
|
|
938
|
+
};
|
|
939
|
+
// Persist progress history to disk so it survives restarts and refreshes.
|
|
940
|
+
const historyPath = storePath(PROGRESS_HISTORY_FILE);
|
|
765
941
|
const manager = createProgressManager({
|
|
766
942
|
getLlm: () => scope.get('llm'),
|
|
767
943
|
getSessionQuery: () => scope.get('sessionQuery'),
|
|
@@ -773,8 +949,35 @@ export function apply(ctx) {
|
|
|
773
949
|
? selection
|
|
774
950
|
: undefined;
|
|
775
951
|
},
|
|
952
|
+
getRequirements: (sessionId) => requirementsFor(sessionId, ctx.__powerupProgressOverride?.[sessionId]),
|
|
953
|
+
onHistoryChange: (sessionId, history) => {
|
|
954
|
+
try {
|
|
955
|
+
const all = readJsonObject(historyPath);
|
|
956
|
+
const records = all.records !== null && typeof all.records === 'object' ? all.records : {};
|
|
957
|
+
records[sessionId] = history;
|
|
958
|
+
mkdirSync(dirname(historyPath), { recursive: true });
|
|
959
|
+
writeFileSync(historyPath, JSON.stringify({ records }, null, 2) + '\n', 'utf8');
|
|
960
|
+
} catch {
|
|
961
|
+
/* history is best-effort persistence */
|
|
962
|
+
}
|
|
963
|
+
},
|
|
776
964
|
});
|
|
965
|
+
// Load persisted history lazily when a session is first polled.
|
|
966
|
+
const originalPoll = manager.poll;
|
|
967
|
+
manager.poll = (sessionId) => {
|
|
968
|
+
if (!manager.__test.histories.has(sessionId)) {
|
|
969
|
+
try {
|
|
970
|
+
const all = readJsonObject(historyPath);
|
|
971
|
+
const records = all.records !== null && typeof all.records === 'object' ? all.records : {};
|
|
972
|
+
if (Array.isArray(records[sessionId])) manager.loadHistory(sessionId, records[sessionId]);
|
|
973
|
+
} catch {
|
|
974
|
+
/* ignore */
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
return originalPoll(sessionId);
|
|
978
|
+
};
|
|
777
979
|
ctx.__powerupProgress = manager;
|
|
980
|
+
ctx.__powerupProgressOverride = ctx.__powerupProgressOverride ?? {};
|
|
778
981
|
scope.effect(() => () => {
|
|
779
982
|
if (ctx.__powerupProgress === manager) ctx.__powerupProgress = undefined;
|
|
780
983
|
}, 'dsh-powerup: progress manager');
|
|
@@ -829,6 +1032,9 @@ export const __test = {
|
|
|
829
1032
|
MODULE_ID,
|
|
830
1033
|
STORE_DIR_NAME,
|
|
831
1034
|
TASK_RESUME_FILE_NAME,
|
|
1035
|
+
PROGRESS_REQUIREMENTS_FILE,
|
|
1036
|
+
PROGRESS_HISTORY_FILE,
|
|
832
1037
|
createProgressManager,
|
|
833
1038
|
cleanResumePrompt,
|
|
1039
|
+
readJsonObject,
|
|
834
1040
|
};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-powerup — a plain model question call, without an Agent.
|
|
3
|
+
*
|
|
4
|
+
* This is deliberately NOT an Agent turn: it uses `ctx.llm.prepareCall` +
|
|
5
|
+
* `call.stream` directly, so no systemPrompt sections, tools, skills, memory or
|
|
6
|
+
* background job machinery are involved. The caller supplies the text (and
|
|
7
|
+
* optionally text extracted from files); the answer is streamed back as plain
|
|
8
|
+
* text and is never written into any session log.
|
|
9
|
+
*
|
|
10
|
+
* Pure JS, no DSH imports at module load, so the offline suites can exercise it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Default instruction: keep the answer focused and tool-free. */
|
|
14
|
+
export const DIRECT_ASK_SYSTEM_PROMPT = [
|
|
15
|
+
'You are answering a single, direct question for the user.',
|
|
16
|
+
'Answer concisely and accurately in the same language as the question.',
|
|
17
|
+
'You have no tools, no skills, and no agent loop — do not pretend to run commands, browse, or modify files.',
|
|
18
|
+
'If the user included file excerpts, treat them as reference text only.',
|
|
19
|
+
].join('\n');
|
|
20
|
+
|
|
21
|
+
/** Upper bound for the question text sent to the model. */
|
|
22
|
+
export const DIRECT_ASK_INPUT_LIMIT = 24_000;
|
|
23
|
+
|
|
24
|
+
/** Default output cap for a one-shot answer. */
|
|
25
|
+
export const DIRECT_ASK_MAX_TOKENS = 2048;
|
|
26
|
+
|
|
27
|
+
/** Error with a stable machine code. */
|
|
28
|
+
export class DirectAskError extends Error {
|
|
29
|
+
constructor(code, message, options = {}) {
|
|
30
|
+
super(`${code}: ${message}`, options);
|
|
31
|
+
this.name = 'DirectAskError';
|
|
32
|
+
this.code = code;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Bound and clean arbitrary input text. */
|
|
37
|
+
export function cleanAskText(value, limit = DIRECT_ASK_INPUT_LIMIT) {
|
|
38
|
+
if (typeof value !== 'string') return '';
|
|
39
|
+
return value.replace(/\u0000/gu, '').trim().slice(0, limit);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Build the user message body from a question plus optional context blocks
|
|
44
|
+
* (e.g. file excerpts the user chose to attach).
|
|
45
|
+
* @param {{question: string, context?: Array<{name?: string, text: string}>}} input
|
|
46
|
+
* @returns {string}
|
|
47
|
+
*/
|
|
48
|
+
export function buildAskPrompt(input = {}) {
|
|
49
|
+
const question = cleanAskText(input.question);
|
|
50
|
+
const blocks = Array.isArray(input.context) ? input.context : [];
|
|
51
|
+
const parts = [];
|
|
52
|
+
for (const block of blocks) {
|
|
53
|
+
if (block === null || typeof block !== 'object') continue;
|
|
54
|
+
const text = cleanAskText(block.text, 12_000);
|
|
55
|
+
if (text === '') continue;
|
|
56
|
+
const name = typeof block.name === 'string' && block.name.trim() !== ''
|
|
57
|
+
? block.name.trim().slice(0, 200)
|
|
58
|
+
: 'attachment';
|
|
59
|
+
parts.push(`--- file: ${name} ---\n${text}`);
|
|
60
|
+
}
|
|
61
|
+
if (parts.length > 0) {
|
|
62
|
+
return `${parts.join('\n\n')}\n\n--- question ---\n${question}`;
|
|
63
|
+
}
|
|
64
|
+
return question;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Perform one direct model answer. No session log writes, no Agent activation.
|
|
69
|
+
*
|
|
70
|
+
* @param {object} options
|
|
71
|
+
* @param {object} options.llm Host `ctx.llm` service
|
|
72
|
+
* @param {{provider: string, model: string, reasoningEffort?: string}} options.route
|
|
73
|
+
* @param {string} options.prompt assembled prompt from {@link buildAskPrompt}
|
|
74
|
+
* @param {AbortSignal} [options.signal]
|
|
75
|
+
* @returns {Promise<{text: string, finish: string|undefined}>}
|
|
76
|
+
*/
|
|
77
|
+
export async function directAsk({ llm, route, prompt, signal, maxTokens }) {
|
|
78
|
+
if (llm === null || typeof llm !== 'object' || typeof llm.prepareCall !== 'function') {
|
|
79
|
+
throw new DirectAskError('LLM_UNAVAILABLE', 'the llm service is unavailable');
|
|
80
|
+
}
|
|
81
|
+
if (route === null || typeof route !== 'object' || typeof route.provider !== 'string' || typeof route.model !== 'string') {
|
|
82
|
+
throw new DirectAskError('NO_ROUTE', 'no provider/model route is available');
|
|
83
|
+
}
|
|
84
|
+
const question = cleanAskText(prompt);
|
|
85
|
+
if (question === '') throw new DirectAskError('EMPTY', 'the question is empty');
|
|
86
|
+
const config = {
|
|
87
|
+
provider: route.provider,
|
|
88
|
+
model: route.model,
|
|
89
|
+
...(typeof route.reasoningEffort === 'string' ? { reasoningEffort: route.reasoningEffort } : {}),
|
|
90
|
+
maxTokens: Number.isFinite(maxTokens) ? maxTokens : DIRECT_ASK_MAX_TOKENS,
|
|
91
|
+
};
|
|
92
|
+
const call = await llm.prepareCall(config, signal);
|
|
93
|
+
const options = {
|
|
94
|
+
...call.config,
|
|
95
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: question }] }],
|
|
96
|
+
system: DIRECT_ASK_SYSTEM_PROMPT,
|
|
97
|
+
purpose: 'powerup-direct-ask',
|
|
98
|
+
...(signal === undefined ? {} : { signal }),
|
|
99
|
+
};
|
|
100
|
+
let text = '';
|
|
101
|
+
let finish;
|
|
102
|
+
for await (const chunk of call.stream(options)) {
|
|
103
|
+
if (signal?.aborted) throw new DirectAskError('ABORTED', 'the direct ask was cancelled');
|
|
104
|
+
if (chunk === null || typeof chunk !== 'object') continue;
|
|
105
|
+
if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text;
|
|
106
|
+
else if (chunk.type === 'finish') finish = chunk.reason;
|
|
107
|
+
}
|
|
108
|
+
if (finish?.kind === 'error' || finish?.kind === 'aborted') {
|
|
109
|
+
throw new DirectAskError('LLM_FAILED', `the model call ${finish.kind ?? 'failed'}`);
|
|
110
|
+
}
|
|
111
|
+
if (finish?.kind === 'max-tokens') {
|
|
112
|
+
throw new DirectAskError('TRUNCATED', 'the model hit its token limit before finishing');
|
|
113
|
+
}
|
|
114
|
+
return { text, finish };
|
|
115
|
+
}
|
package/lib/progress-manager.js
CHANGED
|
@@ -4,6 +4,11 @@
|
|
|
4
4
|
* The manager is deliberately tiny and dependency-free: the Host injects the
|
|
5
5
|
* `llm`, `sessionQuery` and a route resolver, and the Client drives it through
|
|
6
6
|
* three verbs (start / poll / cancel). Nothing here writes to a session log.
|
|
7
|
+
*
|
|
8
|
+
* Reports are retained as a per-session history (newest first). A refresh adds
|
|
9
|
+
* a new entry instead of replacing the previous one — each report cost tokens
|
|
10
|
+
* and is a user-produced artifact, so it is never dropped silently. History is
|
|
11
|
+
* bounded and can be cleared explicitly through `clearHistory`.
|
|
7
12
|
*/
|
|
8
13
|
|
|
9
14
|
import {
|
|
@@ -14,6 +19,9 @@ import {
|
|
|
14
19
|
generateProgress,
|
|
15
20
|
} from './progress-tool.js';
|
|
16
21
|
|
|
22
|
+
/** Keep at most this many reports per session. */
|
|
23
|
+
const HISTORY_LIMIT = 30;
|
|
24
|
+
|
|
17
25
|
/** Cooperative deadline wrapper for one generation. */
|
|
18
26
|
function deadline(signal, ms) {
|
|
19
27
|
const controller = new AbortController();
|
|
@@ -30,7 +38,9 @@ function deadline(signal, ms) {
|
|
|
30
38
|
}
|
|
31
39
|
|
|
32
40
|
/**
|
|
33
|
-
* @param {{ getLlm: () => any, getSessionQuery: () => any, resolveRoute: (sessionId: string) => any,
|
|
41
|
+
* @param {{ getLlm: () => any, getSessionQuery: () => any, resolveRoute: (sessionId: string) => any,
|
|
42
|
+
* getRequirements?: (sessionId: string) => string, onHistoryChange?: (sessionId: string, history: object[]) => void,
|
|
43
|
+
* timeoutMs?: number }} options
|
|
34
44
|
*/
|
|
35
45
|
export function createProgressManager(options) {
|
|
36
46
|
if (options === null || typeof options !== 'object') throw new TypeError('createProgressManager requires options');
|
|
@@ -40,13 +50,17 @@ export function createProgressManager(options) {
|
|
|
40
50
|
if (typeof getLlm !== 'function' || typeof getSessionQuery !== 'function' || typeof resolveRoute !== 'function') {
|
|
41
51
|
throw new TypeError('createProgressManager needs getLlm, getSessionQuery and resolveRoute');
|
|
42
52
|
}
|
|
53
|
+
const getRequirements = typeof options.getRequirements === 'function' ? options.getRequirements : () => '';
|
|
54
|
+
const onHistoryChange = typeof options.onHistoryChange === 'function' ? options.onHistoryChange : () => {};
|
|
43
55
|
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 45_000;
|
|
44
56
|
|
|
45
57
|
/** @type {Map<string, {status:string, startedAt:number, updatedAt:number, report?:object, error?:string, controller?:AbortController}>} */
|
|
46
58
|
const states = new Map();
|
|
59
|
+
/** @type {Map<string, object[]>} newest-first report history */
|
|
60
|
+
const histories = new Map();
|
|
47
61
|
|
|
48
|
-
function
|
|
49
|
-
return
|
|
62
|
+
function historyOf(sessionId) {
|
|
63
|
+
return histories.get(sessionId) ?? [];
|
|
50
64
|
}
|
|
51
65
|
|
|
52
66
|
/** Return a client-safe view of a session's state. */
|
|
@@ -67,6 +81,23 @@ export function createProgressManager(options) {
|
|
|
67
81
|
return result;
|
|
68
82
|
}
|
|
69
83
|
|
|
84
|
+
function stateOf(sessionId) {
|
|
85
|
+
return states.get(sessionId) ?? { status: 'idle', startedAt: 0, updatedAt: Date.now() };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Replace a session's history (used when loading persisted history). */
|
|
89
|
+
function loadHistory(sessionId, records) {
|
|
90
|
+
histories.set(sessionId, Array.isArray(records) ? records.slice(0, HISTORY_LIMIT) : []);
|
|
91
|
+
return historyOf(sessionId);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Explicitly clear a session's history. */
|
|
95
|
+
function clearHistory(sessionId) {
|
|
96
|
+
histories.delete(sessionId);
|
|
97
|
+
onHistoryChange(sessionId, []);
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
|
|
70
101
|
function cancel(sessionId) {
|
|
71
102
|
const state = states.get(sessionId);
|
|
72
103
|
if (state?.controller !== undefined) {
|
|
@@ -77,7 +108,8 @@ export function createProgressManager(options) {
|
|
|
77
108
|
}
|
|
78
109
|
|
|
79
110
|
function start(sessionId) {
|
|
80
|
-
// Cancel any previous in-flight call before starting a fresh one
|
|
111
|
+
// Cancel any previous in-flight call before starting a fresh one, but keep
|
|
112
|
+
// the previous report in history — refreshing must not discard old work.
|
|
81
113
|
const previous = states.get(sessionId);
|
|
82
114
|
if (previous?.controller !== undefined) {
|
|
83
115
|
try { previous.controller.abort(new ProgressError('SUPERSEDED', 'a newer progress call replaced this one')); } catch { /* ignore */ }
|
|
@@ -110,9 +142,14 @@ export function createProgressManager(options) {
|
|
|
110
142
|
throw new ProgressError('NO_ROUTE', 'could not resolve a provider/model for this session');
|
|
111
143
|
}
|
|
112
144
|
const context = buildProgressContext(surface, {});
|
|
113
|
-
const
|
|
145
|
+
const requirements = getRequirements(sessionId);
|
|
146
|
+
const report = await generateProgress({ llm, route: resolved, context, requirements, signal: scope.signal });
|
|
114
147
|
const current = states.get(sessionId);
|
|
115
148
|
if (current?.controller !== controller) return; // superseded by a newer call
|
|
149
|
+
// Append to history, newest first, bounded.
|
|
150
|
+
const next = [report, ...historyOf(sessionId)].slice(0, HISTORY_LIMIT);
|
|
151
|
+
histories.set(sessionId, next);
|
|
152
|
+
onHistoryChange(sessionId, next);
|
|
116
153
|
states.set(sessionId, {
|
|
117
154
|
status: 'done',
|
|
118
155
|
startedAt,
|
|
@@ -139,9 +176,14 @@ export function createProgressManager(options) {
|
|
|
139
176
|
|
|
140
177
|
return {
|
|
141
178
|
start,
|
|
142
|
-
poll: (sessionId) =>
|
|
179
|
+
poll: (sessionId) => ({
|
|
180
|
+
...view(sessionId),
|
|
181
|
+
history: historyOf(sessionId),
|
|
182
|
+
}),
|
|
143
183
|
cancel,
|
|
184
|
+
loadHistory,
|
|
185
|
+
clearHistory,
|
|
144
186
|
/** Exposed for tests only. */
|
|
145
|
-
__test: { states, deadline },
|
|
187
|
+
__test: { states, histories, deadline, HISTORY_LIMIT },
|
|
146
188
|
};
|
|
147
189
|
}
|
package/lib/progress-tool.js
CHANGED
|
@@ -262,10 +262,11 @@ export function finishReport(text, finish) {
|
|
|
262
262
|
* @param {object} options.llm the Host `ctx.llm` service
|
|
263
263
|
* @param {{provider: string, model: string, reasoningEffort?: string, maxTokens?: number}} options.route
|
|
264
264
|
* @param {string} options.context compact transcript
|
|
265
|
+
* @param {string} [options.requirements] extra user-authored requirements appended to the system prompt
|
|
265
266
|
* @param {AbortSignal} [options.signal]
|
|
266
|
-
* @returns {Promise<object>} a normalized progress report
|
|
267
|
+
* @returns {Promise<object>} a normalized progress report (with `raw` = original model text)
|
|
267
268
|
*/
|
|
268
|
-
export async function generateProgress({ llm, route, context, signal }) {
|
|
269
|
+
export async function generateProgress({ llm, route, context, requirements, signal }) {
|
|
269
270
|
if (llm === null || typeof llm !== 'object' || typeof llm.prepareCall !== 'function') {
|
|
270
271
|
throw new ProgressError('LLM_UNAVAILABLE', 'the llm service is unavailable');
|
|
271
272
|
}
|
|
@@ -286,10 +287,13 @@ export async function generateProgress({ llm, route, context, signal }) {
|
|
|
286
287
|
'---',
|
|
287
288
|
'Return only the JSON progress object described in your instructions.',
|
|
288
289
|
].join('\n');
|
|
290
|
+
const extra = typeof requirements === 'string' && requirements.trim() !== ''
|
|
291
|
+
? `\n\nAdditional requirements from the user (follow them strictly):\n${requirements.trim()}`
|
|
292
|
+
: '';
|
|
289
293
|
const options = {
|
|
290
294
|
...call.config,
|
|
291
295
|
messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
|
|
292
|
-
system: PROGRESS_SYSTEM_PROMPT,
|
|
296
|
+
system: PROGRESS_SYSTEM_PROMPT + extra,
|
|
293
297
|
purpose: 'task-progress',
|
|
294
298
|
...(signal === undefined ? {} : { signal }),
|
|
295
299
|
};
|
|
@@ -304,5 +308,10 @@ export async function generateProgress({ llm, route, context, signal }) {
|
|
|
304
308
|
finish = chunk.reason;
|
|
305
309
|
}
|
|
306
310
|
}
|
|
307
|
-
|
|
311
|
+
const cleanedText = finishReport(text, finish);
|
|
312
|
+
const report = parseProgressReport(cleanedText);
|
|
313
|
+
// Keep the exact model output so the user can inspect it later. History is a
|
|
314
|
+
// user-produced artifact and must never be silently discarded.
|
|
315
|
+
report.raw = cleanedText;
|
|
316
|
+
return report;
|
|
308
317
|
}
|
package/lib/task-resume.js
CHANGED
|
@@ -43,12 +43,13 @@ export function cleanText(value, limit = TITLE_LIMIT) {
|
|
|
43
43
|
|
|
44
44
|
/**
|
|
45
45
|
* Collect unfinished work from live Host services.
|
|
46
|
-
* @param {{agents?: any, jobs?: any}} services
|
|
46
|
+
* @param {{agents?: any, jobs?: any, sessionTitle?: any}} services
|
|
47
47
|
* @returns {Array<{id: string, title: string, kind: 'agent'|'job', running: boolean}>}
|
|
48
48
|
*/
|
|
49
49
|
export function collectRunningTasks(services = {}) {
|
|
50
50
|
const tasks = [];
|
|
51
51
|
const agents = services.agents;
|
|
52
|
+
const sessionTitle = services.sessionTitle;
|
|
52
53
|
try {
|
|
53
54
|
const list = typeof agents?.list === 'function' ? agents.list() : [];
|
|
54
55
|
for (const agent of Array.isArray(list) ? list : []) {
|
|
@@ -59,7 +60,7 @@ export function collectRunningTasks(services = {}) {
|
|
|
59
60
|
if (typeof id !== 'string' || id === '') continue;
|
|
60
61
|
tasks.push({
|
|
61
62
|
id,
|
|
62
|
-
title: taskTitle(agent),
|
|
63
|
+
title: taskTitle(agent, sessionTitle),
|
|
63
64
|
kind: 'agent',
|
|
64
65
|
running: true,
|
|
65
66
|
});
|
|
@@ -91,10 +92,24 @@ export function collectRunningTasks(services = {}) {
|
|
|
91
92
|
}
|
|
92
93
|
|
|
93
94
|
/** Best-effort human label for one live Agent. */
|
|
94
|
-
function taskTitle(agent) {
|
|
95
|
+
function taskTitle(agent, sessionTitle) {
|
|
96
|
+
// The canonical title lives on the `sessionTitle` service, not on Session.
|
|
97
|
+
// `agent.session.title()` does not exist — using it silently yields 'session'.
|
|
98
|
+
if (sessionTitle !== null && typeof sessionTitle?.get === 'function' && agent.session !== undefined) {
|
|
99
|
+
try {
|
|
100
|
+
const snapshot = sessionTitle.get(agent.session);
|
|
101
|
+
const value = typeof snapshot === 'string'
|
|
102
|
+
? snapshot
|
|
103
|
+
: snapshot?.title ?? snapshot?.text;
|
|
104
|
+
if (typeof value === 'string' && value.trim() !== '') return cleanText(value);
|
|
105
|
+
} catch {
|
|
106
|
+
/* fall through */
|
|
107
|
+
}
|
|
108
|
+
}
|
|
95
109
|
try {
|
|
96
|
-
const
|
|
97
|
-
|
|
110
|
+
const header = agent.session?.header?.();
|
|
111
|
+
const value = typeof header === 'string' ? header : header?.title;
|
|
112
|
+
if (typeof value === 'string' && value.trim() !== '') return cleanText(value);
|
|
98
113
|
} catch {
|
|
99
114
|
/* fall through */
|
|
100
115
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@restregular/dsh-powerup",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
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",
|
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
"lib/progress-tool.js",
|
|
25
25
|
"lib/progress-manager.js",
|
|
26
26
|
"lib/task-resume.js",
|
|
27
|
+
"lib/direct-ask.js",
|
|
27
28
|
"locale/*.json",
|
|
28
29
|
"icon.svg",
|
|
29
30
|
"README.md",
|
|
@@ -97,7 +98,7 @@
|
|
|
97
98
|
"node": ">=22.13.0"
|
|
98
99
|
},
|
|
99
100
|
"scripts": {
|
|
100
|
-
"test": "node test/smoke.mjs && node test/host.mjs && node test/progress.mjs && node test/task-resume.mjs"
|
|
101
|
+
"test": "node test/smoke.mjs && node test/host.mjs && node test/progress.mjs && node test/task-resume.mjs && node test/direct-ask.mjs"
|
|
101
102
|
},
|
|
102
103
|
"license": "MIT",
|
|
103
104
|
"author": "RestRegular"
|