@restregular/dsh-powerup 0.11.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/index.js CHANGED
@@ -39,8 +39,18 @@ import { dirname, join, resolve as resolvePath, sep } from 'node:path';
39
39
  import { homedir } from 'node:os';
40
40
  import { defineTool } from '@deepseek-ai/dsh-tools';
41
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';
42
51
  import { createStepReadTool } from './lib/step-tool.js';
43
52
  import { createProgressManager } from './lib/progress-manager.js';
53
+ import { buildAskPrompt, cleanAskText, directAsk } from './lib/direct-ask.js';
44
54
 
45
55
  /** Prefix owned by this plugin. */
46
56
  const ROUTE = '/dsh-powerup/api';
@@ -64,6 +74,12 @@ const BODY_LIMIT = 16 * 1024;
64
74
  const STORE_DIR_NAME = 'dsh-powerup';
65
75
  const PROMPTS_FILE = 'prompts.json';
66
76
  const MASK_RULES_FILE = 'mask-rules.json';
77
+ /** Pending continuation prompts recorded by forced restart / close. */
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';
67
83
  /** Legacy relative location inside a workspace, used only for migration. */
68
84
  const LEGACY_STORE_DIR = join('.dsh', 'dsh-powerup');
69
85
 
@@ -162,12 +178,14 @@ function sendJson(res, payload, status = 200) {
162
178
  * @param {import('node:http').IncomingMessage} req
163
179
  * @returns {Promise<unknown>}
164
180
  */
165
- async function readJsonBody(req) {
181
+ async function readJsonBody(req, limit = BODY_LIMIT) {
182
+ // Some callers (and older test doubles) send no stream at all.
183
+ if (req === null || typeof req !== 'object' || typeof req[Symbol.asyncIterator] !== 'function') return {};
166
184
  const chunks = [];
167
185
  let size = 0;
168
186
  for await (const chunk of req) {
169
187
  size += chunk.length;
170
- if (size > BODY_LIMIT) throw new Error('body-too-large');
188
+ if (size > limit) throw new Error('body-too-large');
171
189
  chunks.push(chunk);
172
190
  }
173
191
  if (size === 0) return {};
@@ -247,6 +265,12 @@ function normalizeStopReason(value) {
247
265
  * @param {unknown} value
248
266
  * @returns {string}
249
267
  */
268
+ /** Bound the optional resume prompt supplied by the UI. */
269
+ function cleanResumePrompt(value) {
270
+ if (typeof value !== 'string') return '';
271
+ return value.replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim().slice(0, 4000);
272
+ }
273
+
250
274
  function killReasonFor(value) {
251
275
  const reason = normalizeStopReason(value);
252
276
  return reason === '' ? HUMAN_KILL_REASON : `${HUMAN_KILL_REASON}: ${reason}`;
@@ -377,6 +401,17 @@ function promptStorePath() {
377
401
  return storePath(PROMPTS_FILE);
378
402
  }
379
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
+
380
415
  /** Read one JSON list from disk; a missing file is an empty list. */
381
416
  function readJsonStore(filePath) {
382
417
  try {
@@ -438,11 +473,121 @@ async function handle(req, res, ctx) {
438
473
 
439
474
  const url = new URL(req.url ?? ROUTE, 'http://localhost');
440
475
  const op = url.pathname.slice(ROUTE.length).replace(/^\/+/u, '') || url.searchParams.get('op') || '';
441
- 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') {
442
477
  sendJson(res, { ok: false, error: 'not-found' }, 404);
443
478
  return;
444
479
  }
445
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
+
446
591
  if (op === 'progress') {
447
592
  if (req.method !== 'POST') {
448
593
  sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
@@ -460,18 +605,26 @@ async function handle(req, res, ctx) {
460
605
  sendJson(res, { ok: false, code: 'invalid-request', error: 'sessionId is required' }, 400);
461
606
  return;
462
607
  }
463
- const action = ['start', 'poll', 'cancel'].includes(body?.action) ? body.action : 'poll';
608
+ const action = ['start', 'poll', 'cancel', 'clear'].includes(body?.action) ? body.action : 'poll';
464
609
  const manager = ctx?.__powerupProgress;
465
610
  if (manager === undefined) {
466
611
  sendJson(res, { ok: false, code: 'unavailable', error: 'progress service is not ready' }, 503);
467
612
  return;
468
613
  }
469
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
+ }
470
621
  const view = action === 'start'
471
622
  ? manager.start(sessionId)
472
623
  : action === 'cancel'
473
624
  ? manager.cancel(sessionId)
474
- : manager.poll(sessionId);
625
+ : action === 'clear'
626
+ ? { ...manager.poll(sessionId), history: manager.clearHistory(sessionId) }
627
+ : manager.poll(sessionId);
475
628
  sendJson(res, { ok: true, action, ...view });
476
629
  } catch (error) {
477
630
  sendJson(res, { ok: false, code: 'progress-failed', error: String(error?.message ?? error) }, 500);
@@ -618,14 +771,93 @@ async function handle(req, res, ctx) {
618
771
 
619
772
  if (op === '' || op === 'restart' || op === 'close') {
620
773
  const action = op === 'close' ? 'close' : 'restart';
774
+ const capability = action === 'close' ? describeClose() : describeRestart();
621
775
  if (req.method === 'GET') {
622
- sendJson(res, { ok: true, action, ...(action === 'close' ? describeClose() : describeRestart()) });
776
+ // Expose unfinished work so the UI can gate the normal action and offer
777
+ // the forced variant. A runtime that cannot restart still reports tasks.
778
+ const tasks = collectRunningTasks({
779
+ agents: ctx?.get?.('agents'),
780
+ jobs: ctx?.get?.('jobs'),
781
+ sessionTitle: ctx?.get?.('sessionTitle'),
782
+ });
783
+ sendJson(res, {
784
+ ok: true,
785
+ action,
786
+ ...capability,
787
+ runningTasks: tasks,
788
+ hasRunningTasks: tasks.length > 0,
789
+ });
623
790
  return;
624
791
  }
625
792
  if (req.method === 'POST') {
793
+ let body;
794
+ try {
795
+ body = await readJsonBody(req);
796
+ } catch (error) {
797
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 400);
798
+ return;
799
+ }
800
+ // A client that sends no body (older UI, plugin self-update flow) keeps
801
+ // the historical behaviour: scheduled directly, no task gate.
802
+ const force = body?.force === true;
803
+ const requested = body?.force === true || body?.resume === true || body?.action !== undefined;
804
+ const tasks = requested
805
+ ? collectRunningTasks({
806
+ agents: ctx?.get?.('agents'),
807
+ jobs: ctx?.get?.('jobs'),
808
+ sessionTitle: ctx?.get?.('sessionTitle'),
809
+ })
810
+ : [];
811
+ if (requested && tasks.length > 0 && !force) {
812
+ sendJson(res, {
813
+ ok: false,
814
+ code: 'tasks-running',
815
+ error: 'unfinished tasks are running; use force to stop them',
816
+ runningTasks: tasks,
817
+ }, 409);
818
+ return;
819
+ }
820
+ let stopped = { cancelledAgents: [], killedJobs: [], errors: [] };
821
+ let recorded = 0;
822
+ if (requested && tasks.length > 0 && force) {
823
+ stopped = stopUnfinishedTasks(
824
+ { agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') },
825
+ `dsh-powerup forced ${action}`,
826
+ );
827
+ if (body?.resume === true) {
828
+ try {
829
+ const filePath = storePath(TASK_RESUME_FILE_NAME);
830
+ const records = [];
831
+ const seen = new Set();
832
+ for (const task of tasks) {
833
+ if (task.kind !== 'agent' || seen.has(task.id)) continue;
834
+ seen.add(task.id);
835
+ records.push(createResumeRecord({
836
+ sessionId: task.id,
837
+ title: task.title,
838
+ prompt: cleanResumePrompt(body?.resumePrompt),
839
+ }, randomUUID));
840
+ }
841
+ if (records.length > 0) {
842
+ mkdirSync(dirname(filePath), { recursive: true });
843
+ const queue = mergeResumeQueue(readResumeQueue(filePath, readFileSync), records);
844
+ writeFileSync(filePath, JSON.stringify(queue, null, 2) + '\n', 'utf8');
845
+ recorded = records.length;
846
+ }
847
+ } catch (error) {
848
+ appendSelfUpdateLog(`task-resume: could not record resumes: ${String(error?.message ?? error)}`);
849
+ }
850
+ }
851
+ }
626
852
  try {
627
853
  const scheduled = action === 'close' ? requestShutdown() : requestRestart();
628
- sendJson(res, { ok: true, [action === 'close' ? 'closing' : 'restarting']: true, ...scheduled });
854
+ sendJson(res, {
855
+ ok: true,
856
+ [action === 'close' ? 'closing' : 'restarting']: true,
857
+ ...scheduled,
858
+ stopped,
859
+ recorded,
860
+ });
629
861
  } catch (error) {
630
862
  sendJson(res, { ok: false, code: error?.code, error: String(error?.message ?? error) }, 409);
631
863
  }
@@ -672,6 +904,40 @@ export function apply(ctx) {
672
904
  // The progress side call needs both `llm` and `sessionQuery`. Wait for them
673
905
  // through inject so a late-provided service still creates the manager.
674
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);
675
941
  const manager = createProgressManager({
676
942
  getLlm: () => scope.get('llm'),
677
943
  getSessionQuery: () => scope.get('sessionQuery'),
@@ -683,12 +949,62 @@ export function apply(ctx) {
683
949
  ? selection
684
950
  : undefined;
685
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
+ },
686
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
+ };
687
979
  ctx.__powerupProgress = manager;
980
+ ctx.__powerupProgressOverride = ctx.__powerupProgressOverride ?? {};
688
981
  scope.effect(() => () => {
689
982
  if (ctx.__powerupProgress === manager) ctx.__powerupProgress = undefined;
690
983
  }, 'dsh-powerup: progress manager');
691
984
  });
985
+ // Replay continuation prompts recorded by a forced restart/close once the
986
+ // application has fully started. `sessionController.prompt` resumes cold
987
+ // sessions internally, so no session needs to be opened by the user first.
988
+ ctx.inject(['sessionController'], (scope) => {
989
+ const controller = scope.get('sessionController');
990
+ if (controller === null || typeof controller?.prompt !== 'function') return;
991
+ const ready = ctx.appReady;
992
+ if (ready === null || typeof ready?.onReady !== 'function') return;
993
+ scope.effect(() => ready.onReady(() => {
994
+ void replayPendingResumes({
995
+ filePath: storePath(TASK_RESUME_FILE_NAME),
996
+ sessionController: controller,
997
+ readFile: readFileSync,
998
+ writeFile: writeFileSync,
999
+ mkdir: mkdirSync,
1000
+ dirname,
1001
+ randomUUID,
1002
+ logger: (line) => appendSelfUpdateLog(line),
1003
+ }).catch((error) => {
1004
+ appendSelfUpdateLog(`task-resume: uncaught ${String(error?.stack ?? error)}`);
1005
+ });
1006
+ }), 'dsh-powerup: resume tasks after restart');
1007
+ });
692
1008
  }
693
1009
 
694
1010
  /** Exported for tests only; the Host never reads this. */
@@ -715,5 +1031,10 @@ export const __test = {
715
1031
  ROUTE,
716
1032
  MODULE_ID,
717
1033
  STORE_DIR_NAME,
1034
+ TASK_RESUME_FILE_NAME,
1035
+ PROGRESS_REQUIREMENTS_FILE,
1036
+ PROGRESS_HISTORY_FILE,
718
1037
  createProgressManager,
1038
+ cleanResumePrompt,
1039
+ readJsonObject,
719
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
+ }
@@ -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, timeoutMs?: number }} options
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 stateOf(sessionId) {
49
- return states.get(sessionId) ?? { status: 'idle', startedAt: 0, updatedAt: Date.now() };
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 report = await generateProgress({ llm, route: resolved, context, signal: scope.signal });
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) => view(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
  }