okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
15.0 KiB278 linesraw
1/**
2 * Plans (the /plan command) and goal points, as the host sees them. Pure helpers plus a small store; the bridge drives them.
3 *
4 * A plan is a short numbered list the assistant wrote after looking around (the chat was in Plan mode: nothing could change). The
5 * person approves it, edits it, rejects it, or starts it as a goal whose steps are the plan's steps. A /goal whose text already has
6 * numbered points ("1. ... 2. ... 3. ...") is run the same way, so a point is a step and each one is reported.
7 *
8 * Plan shape (also what the page renders, notes-split-agent6.md):
9 *   { id, chatId, title, request, source: 'plan'|'goal', state, steps: [{ id, text, detail, state, summary }], createdAt, updatedAt, goalStarted }
10 *   plan.state:  proposed | approved | rejected | running | paused | done | stopped
11 *   step.state:  pending | running | done | failed | skipped
12 */
13
14import { randomUUID } from 'node:crypto';
15import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
16import { dirname } from 'node:path';
17
18export const MAX_STEPS = 12;
19const MAX_TEXT = 140;
20const MAX_DETAIL = 220;
21
22const clean = s => String(s ?? '').replace(/\*\*|__|`/g, '').replace(/\s+/g, ' ').trim();
23const clip = (s, n) => (s.length > n ? s.slice(0, n - 1).trimEnd() + '…' : s);
24
25/** "Write the file — one file, inline styles" into { text, detail }. */
26function splitStep(raw) {
27  const s = clean(raw).replace(/^(?:step\s*\d+\s*[:.\-]\s*)/i, '');
28  const at = s.search(/\s[—–]\s|\s-\s|:\s/);
29  const head = at > 8 ? s.slice(0, at) : s;
30  const rest = at > 8 ? s.slice(at).replace(/^\s*[—–:\-]\s*/, '') : '';
31  return { text: clip(head.replace(/[.;:]+$/, ''), MAX_TEXT), detail: clip(rest, MAX_DETAIL) };
32}
33
34/** The instruction a plan turn gets in front of the person's request. */
35export function planPrompt(task) {
36  return [
37    'Make a plan for the request below. Do not change anything: you may only look (read files, list folders, search).',
38    'When you have looked enough, end your reply with the plan as a numbered list: one short line per step, in the order they should be done.',
39    'Put a short heading line right before the list, like "## Pagoda page" (two to five words that name the plan).',
40    'You may add the reason after a dash. Use 3 to 8 steps. Write nothing after the list.',
41    '',
42    `Request: ${task}`,
43  ].join('\n');
44}
45
46/**
47 * The plan in a reply: its last run of numbered lines (at least two). Lines that follow a step and are indented or bulleted are that
48 * step's detail. Returns null when the reply holds no list, so the page shows the reply as it is and never a made-up plan.
49 */
50export function parsePlan(text, request = '') {
51  const lines = String(text ?? '').replace(/\r/g, '').split('\n');
52  const item = /^\s{0,3}(?:step\s+)?(\d{1,2})[.):]\s+(\S.*)$/i;
53  const runs = [];
54  let run = null;
55  lines.forEach((line, i) => {
56    const m = item.exec(line);
57    if (m) {
58      const n = Number(m[1]);
59      if (run && n === run.items.length + 1) { run.items.push({ raw: m[2], extra: [] }); run.end = i; return; }
60      if (n === 1) { run = { start: i, end: i, items: [{ raw: m[2], extra: [] }] }; runs.push(run); return; }
61      run = null; return;
62    }
63    if (run && /^\s+\S/.test(line)) { run.items.at(-1).extra.push(clean(line.replace(/^\s*[-*•]\s*/, ''))); run.end = i; return; }
64    if (run && /^\s*[-*•]\s+\S/.test(line)) { run.items.at(-1).extra.push(clean(line.replace(/^\s*[-*•]\s*/, ''))); run.end = i; return; }
65    if (run && line.trim() === '') return;
66    run = null;
67  });
68  const best = runs.filter(r => r.items.length >= 2).at(-1);
69  if (!best) return null;
70  const steps = best.items.slice(0, MAX_STEPS).map((it, k) => {
71    const { text: t, detail } = splitStep(it.raw);
72    const extra = clip(it.extra.join(' '), MAX_DETAIL);
73    return { id: `s${k + 1}`, text: t, detail: detail || extra, state: 'pending', summary: null };
74  }).filter(s => s.text);
75  if (steps.length < 2) return null;
76  let title = '';
77  for (let i = best.start - 1; i >= 0 && i >= best.start - 6; i--) {
78    const h = /^\s*#{1,6}\s+(.+?)\s*$/.exec(lines[i]);
79    if (h) { title = clean(h[1]); break; }
80  }
81  return { title: clip(title || clean(request) || 'Plan', 80), steps };
82}
83
84/** Numbered points inside a goal's own words ("1. a 2. b" on lines or in one line); at least two, counting up from 1. */
85export function parsePoints(objective) {
86  const text = String(objective ?? '').replace(/\r/g, '');
87  const found = [];
88  const re = /(?:^|\s)(\d{1,2})[.)]\s+/g;
89  let m; const marks = [];
90  while ((m = re.exec(text))) marks.push({ n: Number(m[1]), at: m.index, after: m.index + m[0].length });
91  let want = 1; let start = -1;
92  const seq = [];
93  for (const k of marks) {
94    if (k.n === want) { if (want === 1) start = seq.length; seq.push(k); want++; }
95    else if (k.n === 1) { seq.length = 0; seq.push(k); want = 2; }
96  }
97  if (seq.length < 2) return null;
98  seq.forEach((k, i) => found.push(clean(text.slice(k.after, i + 1 < seq.length ? seq[i + 1].at : undefined))));
99  const aim = clean(text.slice(0, seq[0].at)).replace(/[:\-–—]+$/, '').trim();
100  const steps = found.slice(0, MAX_STEPS).map((t, k) => {
101    const { text: s, detail } = splitStep(t);
102    return { id: `s${k + 1}`, text: s, detail, state: 'pending', summary: null };
103  }).filter(s => s.text);
104  if (steps.length < 2) return null;
105  return { title: clip(aim || steps[0].text, 80), steps };
106}
107
108/** A step that is about looking at the result in a browser or window: it must never hang or fail a whole run on a machine with no screen. */
109export const isViewStep = text => /\b(open|view|launch|preview|look at|check|confirm|verify)\b[^\n]{0,60}\b(browser|in chrome|in edge|in firefox|window|on screen)\b/i.test(String(text ?? ''));
110
111/** The goal the Harness runs for step `index` (0-based): one step, with the aim and the steps around it named. */
112export function stepObjective(plan, index) {
113  const n = plan.steps.length; const s = plan.steps[index];
114  const done = plan.steps.slice(0, index).map((x, i) => `${i + 1}. ${x.text}${x.summary ? ' (' + String(x.summary).slice(0, 100) + ')' : ''}`).join('; ');
115  return [
116    `Overall aim: ${plan.title}.`,
117    `You are on step ${index + 1} of ${n}: ${s.text}${s.detail ? ` (${s.detail})` : ''}.`,
118    done ? `Already done: ${done}.` : '',
119    plan.briefing ? String(plan.briefing) : '',
120    isViewStep(s.text) ? 'This step is about seeing the result. To show a local image, SVG, HTML page or PDF, use the present tool (a browser cannot open file:// addresses). Never wait for a program to close. If a person is at this computer and you start a browser, start it so the command returns at once (Windows: Start-Process; macOS: open; Linux: xdg-open) and say only that you started it, not that the page rendered. If there is no screen, check the page without a visible window: use the headless browser tool if you have one, otherwise read the file and its script for mistakes, and say in one plain sentence what you could and could not check. Then finish the step.' : '',
121    'Do only this step, check that it worked, and then finish the goal.',
122    index + 1 < n ? 'The next steps are handled separately: do not start them.' : '',
123  ].filter(Boolean).join(' ');
124}
125
126const WORD = { started: 'started', done: 'done', failed: "didn't finish", stopped: 'stopped', skipped: 'skipped' };
127/** One short friendly line for a step: "Write the roof — done" (no step counter: the owner removed it). */
128export function stepLine(index, total, text, state) {
129  return `${clip(clean(text), 90)} — ${WORD[state] ?? state}`;
130}
131
132/** The short summary of a step from the words it closed with: the first sentence, plain. */
133export function firstSentence(text, max = 140) {
134  const s = clean(String(text ?? '').replace(/^#+\s.*$/gm, '').replace(/^[-*]\s+/gm, ''));
135  if (!s) return null;
136  const m = /^(.{12,}?[.!?])(?:\s|$)/.exec(s);
137  return clip(m ? m[1] : s, max);
138}
139
140/**
141 * The short summary of a finished step: what it changed (from the tool cards: "Wrote pagoda.html, Changed style.css"), else the first
142 * sentence of its closing words when that reads as a result. A sentence about what is NOT done, or about later steps, is never a summary.
143 */
144export function stepSummary(cards, closing) {
145  const done = [];
146  for (const c of cards ?? []) {
147    const verb = /^(Wrote|Changed|Created|Edited|Deleted|Removed|Moved|Renamed)\b/.exec(String(c?.verb ?? ''))?.[1];
148    const target = String(c?.target ?? '').split(/[\\/]/).filter(Boolean).at(-1);
149    if (!verb || !target) continue;
150    const line = verb + ' ' + clip(target, 40);
151    if (!done.includes(line)) done.push(line);
152  }
153  if (done.length) return clip(done.slice(0, 3).join(', ') + (done.length > 3 ? ' and more' : ''), 140);
154  const s = firstSentence(closing);
155  return s && !/not done|not yet|remaining|handled separately|next steps?|later steps?|still (?:need|to)|todo/i.test(s) ? s : null;
156}
157
158/** The words a person sees for the plan, as one message the model can carry out (the plain Approve path). */
159export function planAsPrompt(plan) {
160  return ['Carry out this plan, step by step, and tell me briefly when each step is done.', '', plan.title ? `Plan: ${plan.title}` : '', ...plan.steps.map((s, i) => `${i + 1}. ${s.text}${s.detail ? ` (${s.detail})` : ''}`)].filter((l, i) => l !== '' || i === 1).join('\n');
161}
162
163/** A step list from the person's edit: texts only, validated and capped. Throws a plain sentence for an unusable list. */
164export function editedSteps(input, previous = []) {
165  if (!Array.isArray(input)) throw Object.assign(new Error('A plan needs a list of steps.'), { code: 'plan-steps' });
166  const steps = input.map((x, k) => {
167    const text = clip(clean(typeof x === 'string' ? x : x?.text), MAX_TEXT);
168    const detail = clip(clean(typeof x === 'string' ? '' : x?.detail), MAX_DETAIL);
169    const kept = previous.find(p => p.id === x?.id);
170    return text ? { id: kept?.id ?? `s${k + 1}`, text, detail, state: 'pending', summary: null } : null;
171  }).filter(Boolean).slice(0, MAX_STEPS);
172  if (!steps.length) throw Object.assign(new Error('A plan needs at least one step.'), { code: 'plan-steps' });
173  // ids must be unique and in order of the list
174  steps.forEach((s, i) => { s.id = `s${i + 1}`; });
175  return steps;
176}
177
178/** The latest plan of each chat, kept in memory and in one small file so a restart does not lose a proposal. */
179export class PlanStore {
180  constructor(file = null) {
181    this.file = file; this.plans = new Map();
182    if (file && existsSync(file)) {
183      try { for (const p of JSON.parse(readFileSync(file, 'utf8'))) if (p?.chatId) this.plans.set(p.chatId, p); } catch { /* a damaged file starts empty */ }
184    }
185  }
186  #save() {
187    if (!this.file) return;
188    try {
189      mkdirSync(dirname(this.file), { recursive: true });
190      const tmp = this.file + '.tmp';
191      writeFileSync(tmp, JSON.stringify([...this.plans.values()]));
192      renameSync(tmp, this.file);
193    } catch { /* the plan still lives in memory */ }
194  }
195  get(chatId) { return this.plans.get(chatId) ?? null; }
196  create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed', caution = null }) {
197    const now = new Date().toISOString();
198    const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false, ...(caution ? { caution } : {}) };
199    this.plans.set(chatId, plan); this.#save();
200    return plan;
201  }
202  update(chatId, fn) {
203    const plan = this.plans.get(chatId);
204    if (!plan) return null;
205    fn(plan); plan.updatedAt = new Date().toISOString();
206    this.#save();
207    return plan;
208  }
209  clear(chatId) { this.plans.delete(chatId); this.#save(); }
210}
211
212/** What the page gets: a copy with no host-only fields. */
213export const planView = plan => (plan ? JSON.parse(JSON.stringify(plan)) : null);
214
215// ---- /research ------------------------------------------------------------------------------------------------------------------
216
217/** The first research prompt: find and read pages, take notes. What the assistant writes here is not shown; the answer is written in a second step. */
218export function researchPrompt(topic) {
219  return [
220    `Research task: ${topic}`,
221    '',
222    'Do these steps in order. Do not skip a step.',
223    '1. Call web_search to find pages about the task.',
224    '2. Call web_fetch to open at least two of the pages you found, and read them. Do not rely on the search results alone.',
225    '3. When you have read them, reply with short notes: the facts you found, each with the web address of the page it came from.',
226  ].join('\n');
227}
228
229/** Sent when the assistant answered without opening pages. */
230export const RESEARCH_NUDGE = 'You have not opened enough pages yet. Call web_fetch now on at least two of the pages from your search, read them, then reply with short notes and the web address of each page.';
231
232/** The second research prompt: write the answer in the fixed shape. */
233export function researchWritePrompt(topic) {
234  return [
235    `Now write the final answer to the research task: ${topic}`,
236    'Use only what you read on the pages. Do not call any tool. Start your reply with the line "## Summary" and use exactly these three headings:',
237    '## Summary',
238    'Three to five sentences, in plain words. If the sources disagree or something could not be found, say so.',
239    '## Key findings',
240    '- One finding per line, each ending with its source number in square brackets, like [1].',
241    '## Sources',
242    '1. Page title - web address',
243    '2. Page title - web address',
244    'List only pages you opened.',
245  ].join('\n');
246}
247
248/** The numbered sources at the end of a research answer: [{ n, title, url }]. Empty when there are none. */
249export function parseSources(text) {
250  const lines = String(text ?? '').replace(/\r/g, '').split('\n');
251  const at = lines.map(l => /^\s{0,3}#{1,6}\s*sources\b/i.test(l) || /^\s*\*{0,2}sources\*{0,2}:?\s*$/i.test(l)).lastIndexOf(true);
252  if (at < 0) return linkSources(text);
253  const out = [];
254  for (const line of lines.slice(at + 1)) {
255    if (/^\s{0,3}#{1,6}\s/.test(line)) break;
256    const url = /(https?:\/\/[^\s)>\]"']+)/.exec(line)?.[1]?.replace(/[.,;]+$/, '');
257    if (!url) continue;
258    const md = /\[([^\]]+)\]\(https?:\/\//.exec(line);
259    const before = line.slice(0, line.indexOf(url)).replace(/^\s*(?:\d+[.)]|[-*•])\s*/, '').replace(/[\s\-–—:(<[]+$/, '').replace(/\*\*|`/g, '').trim();
260    const title = clean(md?.[1] ?? before) || (() => { try { return new URL(url).hostname; } catch { return url; } })();
261    if (!out.some(s => s.url === url)) out.push({ n: out.length + 1, title: clip(title, 120), url });
262  }
263  return out.slice(0, 20);
264}
265
266/** No Sources section: the pages the answer links to, in the order they appear, so the page can still list where it came from. */
267function linkSources(text) {
268  const out = [];
269  const re = /\[([^\]]{1,160})\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s)>\]"']+)/g;
270  let m;
271  while ((m = re.exec(String(text ?? ''))) && out.length < 8) {
272    const url = (m[2] ?? m[3]).replace(/[.,;]+$/, '');
273    if (out.some(x => x.url === url)) continue;
274    let host = url; try { host = new URL(url).hostname; } catch { /* keep the address */ }
275    out.push({ n: out.length + 1, title: clip(clean(m[1] ?? '') || host, 120), url });
276  }
277  return out;
278}