@restregular/dsh-powerup 0.12.0 → 0.14.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
@@ -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 > BODY_LIMIT) throw new Error('body-too-large');
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,136 @@ 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
+ // Keep the flat list form; accept {requirements: [...]} or a bare array.
487
+ const list = Array.isArray(body?.requirements)
488
+ ? body.requirements
489
+ : Array.isArray(body) ? body : [];
490
+ const records = list.filter((r) => r !== null && typeof r === 'object')
491
+ .map((r) => ({
492
+ id: typeof r.id === 'string' && r.id !== '' ? r.id : `req-${randomUUID()}`,
493
+ title: typeof r.title === 'string' ? r.title : '',
494
+ text: typeof r.text === 'string' ? r.text : '',
495
+ workspaceId: typeof r.workspaceId === 'string' ? r.workspaceId : '',
496
+ enabled: r.enabled !== false,
497
+ }));
498
+ mkdirSync(dirname(filePath), { recursive: true });
499
+ writeFileSync(filePath, JSON.stringify(records, null, 2) + '\n', 'utf8');
500
+ sendJson(res, { ok: true, requirements: records });
501
+ } catch (error) {
502
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
503
+ }
504
+ return;
505
+ }
506
+ if (req.method !== 'GET') {
507
+ sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
508
+ return;
509
+ }
510
+ try {
511
+ let raw;
512
+ try { raw = JSON.parse(readFileSync(filePath, 'utf8')); } catch { raw = undefined; }
513
+ let records = [];
514
+ if (Array.isArray(raw)) records = raw;
515
+ else if (raw !== null && typeof raw === 'object' && Array.isArray(raw.records)) records = raw.records;
516
+ sendJson(res, { ok: true, requirements: records });
517
+ } catch (error) {
518
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
519
+ }
520
+ return;
521
+ }
522
+
523
+ if (op === 'progress-history') {
524
+ const filePath = storePath(PROGRESS_HISTORY_FILE);
525
+ if (req.method === 'GET') {
526
+ try {
527
+ const all = readJsonObject(filePath);
528
+ sendJson(res, { ok: true, records: all.records ?? {} });
529
+ } catch (error) {
530
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
531
+ }
532
+ return;
533
+ }
534
+ if (req.method === 'POST') {
535
+ try {
536
+ const body = await readJsonBody(req, 4 * 1024 * 1024);
537
+ const records = body?.records !== null && typeof body?.records === 'object' ? body.records : {};
538
+ mkdirSync(dirname(filePath), { recursive: true });
539
+ writeFileSync(filePath, JSON.stringify({ records }, null, 2) + '\n', 'utf8');
540
+ sendJson(res, { ok: true, records });
541
+ } catch (error) {
542
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 500);
543
+ }
544
+ return;
545
+ }
546
+ sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
547
+ return;
548
+ }
549
+
550
+ if (op === 'direct-ask') {
551
+ if (req.method !== 'POST') {
552
+ sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
553
+ return;
554
+ }
555
+ let body;
556
+ try {
557
+ body = await readJsonBody(req, 4 * 1024 * 1024);
558
+ } catch (error) {
559
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 400);
560
+ return;
561
+ }
562
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
563
+ const context = Array.isArray(body?.context) ? body.context : [];
564
+ const history = Array.isArray(body?.history) ? body.history : [];
565
+ const prompt = buildAskPrompt({ question: cleanAskText(body?.question), context });
566
+ if (prompt === '') {
567
+ sendJson(res, { ok: false, code: 'invalid-request', error: 'question is required' }, 400);
568
+ return;
569
+ }
570
+ const llm = ctx?.get?.('llm');
571
+ if (llm === null || typeof llm?.prepareCall !== 'function') {
572
+ sendJson(res, { ok: false, code: 'llm-unavailable', error: 'the llm service is unavailable' }, 503);
573
+ return;
574
+ }
575
+ // Prefer the current session's model; fall back to the default selection.
576
+ let route;
577
+ try {
578
+ const query = ctx?.get?.('sessionQuery');
579
+ if (sessionId !== '' && typeof query?.inspectSession === 'function') {
580
+ route = await query.inspectSession(sessionId, (session) => session?.requestHeader?.()?.config ?? undefined);
581
+ }
582
+ } catch {
583
+ /* fall through to default */
584
+ }
585
+ if (route === null || typeof route !== 'object' || typeof route.provider !== 'string') {
586
+ const defaults = ctx?.get?.('agentDefaultModel');
587
+ const selection = typeof defaults?.currentSelection === 'function' ? defaults.currentSelection() : undefined;
588
+ route = selection !== null && typeof selection === 'object' && typeof selection.provider === 'string'
589
+ ? selection
590
+ : undefined;
591
+ }
592
+ const controller = new AbortController();
593
+ const timer = setTimeout(() => controller.abort(), 90_000);
594
+ timer.unref?.();
595
+ try {
596
+ const answer = await directAsk({ llm, route, prompt, history, signal: controller.signal });
597
+ sendJson(res, { ok: true, answer: answer.text, finish: answer.finish ?? null });
598
+ } catch (error) {
599
+ sendJson(res, { ok: false, code: error?.code ?? 'ask-failed', error: String(error?.message ?? error) }, 500);
600
+ } finally {
601
+ clearTimeout(timer);
602
+ }
603
+ return;
604
+ }
605
+
465
606
  if (op === 'progress') {
466
607
  if (req.method !== 'POST') {
467
608
  sendJson(res, { ok: false, error: 'method-not-allowed' }, 405);
@@ -479,18 +620,26 @@ async function handle(req, res, ctx) {
479
620
  sendJson(res, { ok: false, code: 'invalid-request', error: 'sessionId is required' }, 400);
480
621
  return;
481
622
  }
482
- const action = ['start', 'poll', 'cancel'].includes(body?.action) ? body.action : 'poll';
623
+ const action = ['start', 'poll', 'cancel', 'clear'].includes(body?.action) ? body.action : 'poll';
483
624
  const manager = ctx?.__powerupProgress;
484
625
  if (manager === undefined) {
485
626
  sendJson(res, { ok: false, code: 'unavailable', error: 'progress service is not ready' }, 503);
486
627
  return;
487
628
  }
488
629
  try {
630
+ // A one-off requirements selection from the progress panel is kept for
631
+ // the next start; it does not modify the persisted records.
632
+ if (Array.isArray(body?.requirementIds)) {
633
+ ctx.__powerupProgressSelection = ctx.__powerupProgressSelection ?? {};
634
+ ctx.__powerupProgressSelection[sessionId] = body.requirementIds.map(String);
635
+ }
489
636
  const view = action === 'start'
490
637
  ? manager.start(sessionId)
491
638
  : action === 'cancel'
492
639
  ? manager.cancel(sessionId)
493
- : manager.poll(sessionId);
640
+ : action === 'clear'
641
+ ? { ...manager.poll(sessionId), history: manager.clearHistory(sessionId) }
642
+ : manager.poll(sessionId);
494
643
  sendJson(res, { ok: true, action, ...view });
495
644
  } catch (error) {
496
645
  sendJson(res, { ok: false, code: 'progress-failed', error: String(error?.message ?? error) }, 500);
@@ -641,7 +790,11 @@ async function handle(req, res, ctx) {
641
790
  if (req.method === 'GET') {
642
791
  // Expose unfinished work so the UI can gate the normal action and offer
643
792
  // the forced variant. A runtime that cannot restart still reports tasks.
644
- const tasks = collectRunningTasks({ agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') });
793
+ const tasks = collectRunningTasks({
794
+ agents: ctx?.get?.('agents'),
795
+ jobs: ctx?.get?.('jobs'),
796
+ sessionTitle: ctx?.get?.('sessionTitle'),
797
+ });
645
798
  sendJson(res, {
646
799
  ok: true,
647
800
  action,
@@ -664,7 +817,11 @@ async function handle(req, res, ctx) {
664
817
  const force = body?.force === true;
665
818
  const requested = body?.force === true || body?.resume === true || body?.action !== undefined;
666
819
  const tasks = requested
667
- ? collectRunningTasks({ agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') })
820
+ ? collectRunningTasks({
821
+ agents: ctx?.get?.('agents'),
822
+ jobs: ctx?.get?.('jobs'),
823
+ sessionTitle: ctx?.get?.('sessionTitle'),
824
+ })
668
825
  : [];
669
826
  if (requested && tasks.length > 0 && !force) {
670
827
  sendJson(res, {
@@ -762,6 +919,62 @@ export function apply(ctx) {
762
919
  // The progress side call needs both `llm` and `sessionQuery`. Wait for them
763
920
  // through inject so a late-provided service still creates the manager.
764
921
  ctx.inject(['llm', 'sessionQuery'], (scope) => {
922
+ // Requirements are a flat list of records: {id,title,text,workspaceId,enabled}.
923
+ // workspaceId '' = global. The panel sends the ids it wants; the Host only
924
+ // includes records visible to the session's workspace and explicitly picked.
925
+ const requirementsFor = (sessionId, selectedIds) => {
926
+ const file = storePath(PROGRESS_REQUIREMENTS_FILE);
927
+ let raw;
928
+ try {
929
+ raw = JSON.parse(readFileSync(file, 'utf8'));
930
+ } catch {
931
+ raw = undefined;
932
+ }
933
+ let all = [];
934
+ if (Array.isArray(raw)) all = raw;
935
+ else if (raw !== null && typeof raw === 'object' && Array.isArray(raw.records)) all = raw.records;
936
+ else if (raw !== null && typeof raw === 'object') {
937
+ // Legacy object form ({global, workspaces, sessions}) migrated on read.
938
+ const migrated = [];
939
+ if (typeof raw.global === 'string' && raw.global.trim() !== '') {
940
+ migrated.push({ id: 'legacy-global', title: '通用要求', text: raw.global, workspaceId: '', enabled: true });
941
+ }
942
+ const ws = raw.workspaces ?? {};
943
+ for (const [wid, text] of Object.entries(ws)) {
944
+ if (typeof text === 'string' && text.trim() !== '') {
945
+ migrated.push({ id: `legacy-ws-${wid}`, title: '工作区要求', text, workspaceId: wid, enabled: true });
946
+ }
947
+ }
948
+ all = migrated;
949
+ }
950
+ let workspaceId = '';
951
+ try {
952
+ const registry = scope.get('workspaceRegistry');
953
+ const list = typeof registry?.list === 'function' ? registry.list() : [];
954
+ for (const item of Array.isArray(list) ? list : []) {
955
+ if (Array.isArray(item?.sessionIds) && item.sessionIds.includes(sessionId)) {
956
+ workspaceId = typeof item.id === 'string' ? item.id : '';
957
+ break;
958
+ }
959
+ }
960
+ } catch {
961
+ /* workspace layer is optional */
962
+ }
963
+ const ids = Array.isArray(selectedIds) ? new Set(selectedIds.map(String)) : null;
964
+ const parts = [];
965
+ for (const record of all) {
966
+ if (record === null || typeof record !== 'object') continue;
967
+ if (record.enabled === false) continue;
968
+ if (typeof record.text !== 'string' || record.text.trim() === '') continue;
969
+ const wid = typeof record.workspaceId === 'string' ? record.workspaceId : '';
970
+ if (wid !== '' && wid !== workspaceId) continue; // workspace isolation
971
+ if (ids !== null && !ids.has(String(record.id))) continue; // panel selection
972
+ parts.push(record.text.trim());
973
+ }
974
+ return parts.join('\n\n');
975
+ };
976
+ // Persist progress history to disk so it survives restarts and refreshes.
977
+ const historyPath = storePath(PROGRESS_HISTORY_FILE);
765
978
  const manager = createProgressManager({
766
979
  getLlm: () => scope.get('llm'),
767
980
  getSessionQuery: () => scope.get('sessionQuery'),
@@ -773,8 +986,35 @@ export function apply(ctx) {
773
986
  ? selection
774
987
  : undefined;
775
988
  },
989
+ getRequirements: (sessionId) => requirementsFor(sessionId, ctx.__powerupProgressSelection?.[sessionId]),
990
+ onHistoryChange: (sessionId, history) => {
991
+ try {
992
+ const all = readJsonObject(historyPath);
993
+ const records = all.records !== null && typeof all.records === 'object' ? all.records : {};
994
+ records[sessionId] = history;
995
+ mkdirSync(dirname(historyPath), { recursive: true });
996
+ writeFileSync(historyPath, JSON.stringify({ records }, null, 2) + '\n', 'utf8');
997
+ } catch {
998
+ /* history is best-effort persistence */
999
+ }
1000
+ },
776
1001
  });
1002
+ // Load persisted history lazily when a session is first polled.
1003
+ const originalPoll = manager.poll;
1004
+ manager.poll = (sessionId) => {
1005
+ if (!manager.__test.histories.has(sessionId)) {
1006
+ try {
1007
+ const all = readJsonObject(historyPath);
1008
+ const records = all.records !== null && typeof all.records === 'object' ? all.records : {};
1009
+ if (Array.isArray(records[sessionId])) manager.loadHistory(sessionId, records[sessionId]);
1010
+ } catch {
1011
+ /* ignore */
1012
+ }
1013
+ }
1014
+ return originalPoll(sessionId);
1015
+ };
777
1016
  ctx.__powerupProgress = manager;
1017
+ ctx.__powerupProgressSelection = ctx.__powerupProgressSelection ?? {};
778
1018
  scope.effect(() => () => {
779
1019
  if (ctx.__powerupProgress === manager) ctx.__powerupProgress = undefined;
780
1020
  }, 'dsh-powerup: progress manager');
@@ -829,6 +1069,9 @@ export const __test = {
829
1069
  MODULE_ID,
830
1070
  STORE_DIR_NAME,
831
1071
  TASK_RESUME_FILE_NAME,
1072
+ PROGRESS_REQUIREMENTS_FILE,
1073
+ PROGRESS_HISTORY_FILE,
832
1074
  createProgressManager,
833
1075
  cleanResumePrompt,
1076
+ readJsonObject,
834
1077
  };
@@ -0,0 +1,126 @@
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 {Array<{role:'user'|'assistant', text:string}>} [options.history] prior turns for continuous Q&A
75
+ * @param {AbortSignal} [options.signal]
76
+ * @returns {Promise<{text: string, finish: string|undefined}>}
77
+ */
78
+ export async function directAsk({ llm, route, prompt, history, signal, maxTokens }) {
79
+ if (llm === null || typeof llm !== 'object' || typeof llm.prepareCall !== 'function') {
80
+ throw new DirectAskError('LLM_UNAVAILABLE', 'the llm service is unavailable');
81
+ }
82
+ if (route === null || typeof route !== 'object' || typeof route.provider !== 'string' || typeof route.model !== 'string') {
83
+ throw new DirectAskError('NO_ROUTE', 'no provider/model route is available');
84
+ }
85
+ const question = cleanAskText(prompt);
86
+ if (question === '') throw new DirectAskError('EMPTY', 'the question is empty');
87
+ const config = {
88
+ provider: route.provider,
89
+ model: route.model,
90
+ ...(typeof route.reasoningEffort === 'string' ? { reasoningEffort: route.reasoningEffort } : {}),
91
+ maxTokens: Number.isFinite(maxTokens) ? maxTokens : DIRECT_ASK_MAX_TOKENS,
92
+ };
93
+ const call = await llm.prepareCall(config, signal);
94
+ const messages = [];
95
+ for (const turn of Array.isArray(history) ? history : []) {
96
+ if (turn === null || typeof turn !== 'object') continue;
97
+ const role = turn.role === 'assistant' ? 'assistant' : turn.role === 'user' ? 'user' : null;
98
+ if (role === null) continue;
99
+ const text = cleanAskText(turn.text);
100
+ if (text === '') continue;
101
+ messages.push({ role, content: [{ type: 'text', text }] });
102
+ }
103
+ messages.push({ role: 'user', content: [{ type: 'text', text: question }] });
104
+ const options = {
105
+ ...call.config,
106
+ messages,
107
+ system: DIRECT_ASK_SYSTEM_PROMPT,
108
+ purpose: 'powerup-direct-ask',
109
+ ...(signal === undefined ? {} : { signal }),
110
+ };
111
+ let text = '';
112
+ let finish;
113
+ for await (const chunk of call.stream(options)) {
114
+ if (signal?.aborted) throw new DirectAskError('ABORTED', 'the direct ask was cancelled');
115
+ if (chunk === null || typeof chunk !== 'object') continue;
116
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text;
117
+ else if (chunk.type === 'finish') finish = chunk.reason;
118
+ }
119
+ if (finish?.kind === 'error' || finish?.kind === 'aborted') {
120
+ throw new DirectAskError('LLM_FAILED', `the model call ${finish.kind ?? 'failed'}`);
121
+ }
122
+ if (finish?.kind === 'max-tokens') {
123
+ throw new DirectAskError('TRUNCATED', 'the model hit its token limit before finishing');
124
+ }
125
+ return { text, finish };
126
+ }
@@ -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
  }
@@ -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
- return parseProgressReport(finishReport(text, finish));
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
  }