okami.mom/strata

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

Niko1221Merge branch 'f-split-agent8' into f-split-vision788e0b731

main
22.0 KiB332 linesraw
1/**
2 * Time-skip = /plan + /goal + a smart subagent fork at the step that matters most (notes-split-agent8.md, item 11).
3 *
4 *   1. The request is dissected into a plan with steps (the same read-only plan turn as /plan), in a COPY of the project folder (A).
5 *   2. One short question picks the lever: the single step where stopping, checking the results so far and improving or diverting
6 *      matters most for the final result (with its reason; a fixed rule when the answer is unusable).
7 *   3. Agent A runs the plan as a goal, step by step, all the way: RESULT A.
8 *   4. When A has finished the step before the lever, the host copies A to B and a read-only helper writes an improvement plan from the
9 *      plan, A's results so far and the lever's reason. Agent B gets that plan (and .timeskip/context.md as its attachment) and finishes
10 *      its own improved path in B: RESULT B. With one model slot B starts when A is done and the person is told so.
11 *   5. A and B are compared side by side; the person keeps one (Keep A / Keep B), with a rollback copy.
12 * The person's own folder is never touched until Keep.
13 */
14
15import { randomUUID } from 'node:crypto';
16import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
17import { dirname, join, relative, resolve, sep } from 'node:path';
18import { diffRun, runImagePath, isNoisePath } from './timeskip.mjs';
19import { isViewStep } from './agent/plan.mjs';
20
21/** The note both agents carry on every step: the work is in a copy, unattended, on whatever machine this is. */
22export const UNATTENDED = 'This work runs in a copy of the folder with nobody watching. Never open a visible window and never wait for a program to close. To check a web page use the headless browser tool if you have one; otherwise read the file and say plainly what you could not check. A check that cannot be done here is noted in one sentence and the step is finished.';
23
24const SKIP = new Set(['.git', '.strata', '.timeskip', 'node_modules', '__pycache__']);
25const TERMINAL = new Set(['completed', 'failed', 'cancelled', 'interrupted']);
26
27/** Copy a project folder for a trial, without dependency/VCS folders. */
28export function copyProject(from, to) {
29  mkdirSync(to, { recursive: true });
30  cpSync(from, to, { recursive: true, force: true, filter: src => !SKIP.has(src.split(sep).pop()) || resolve(src) === resolve(from) });
31}
32
33/** The question that picks the lever. */
34export function leverPrompt(request, steps) {
35  return [
36    'Below is a plan for a request. Find the ONE biggest lever in it: the single step where stopping, checking the results so far and improving or changing direction would matter most for the quality of the final result.',
37    'Rules: never step 1 (nothing exists yet to check); prefer the step right after the first real result exists and before the expensive or hard-to-undo part; choose exactly one step.',
38    '',
39    `Request: ${request}`,
40    'Plan:',
41    ...steps.map((s, i) => `${i + 1}. ${s.text}${s.detail ? ` (${s.detail})` : ''}`),
42    '',
43    'Answer with only this JSON on one line, no other words: {"step": <number>, "why": "<one short plain sentence: why checking here matters most>"}',
44  ].join('\n');
45}
46
47/** The model's answer as { step, why }, or null. The step is 1-based and must be inside the plan and not the first. */
48export function parseLever(text, total) {
49  const m = /\{[^{}]*"step"[^{}]*\}/s.exec(String(text ?? ''));
50  if (!m) return null;
51  try {
52    const j = JSON.parse(m[0]);
53    const step = Number(j.step);
54    if (!Number.isInteger(step) || step < 2 || step > total) return null;
55    const why = String(j.why ?? '').replace(/\s+/g, ' ').trim().slice(0, 220);
56    return { step, why: why || 'This is where the results so far are worth checking.' };
57  } catch { return null; }
58}
59
60/** A fixed rule for the lever when the model's answer cannot be used: the step after the first step that makes something. */
61export function defaultLever(steps) {
62  const n = steps.length;
63  const making = steps.findIndex((s, i) => i >= 1 && /\b(write|create|build|draw|implement|generate|make|design|code|add)\b/i.test(s.text));
64  let step = making >= 0 ? Math.min(n, making + 2) : Math.ceil(n / 2) + 1;
65  step = Math.max(2, Math.min(n, step));
66  return { step, why: 'Chosen by a default rule (the answer from the model could not be used): the first results exist after the step before it.', defaulted: true };
67}
68
69/** The improvement plan request for B: what is done, what the lever is, and what to write. */
70export function improvementPrompt({ request, steps, lever, doneSummaries }) {
71  return [
72    'You are improving work that is already in progress in this folder. Read .timeskip/context.md and the files first (you may only look, not change anything).',
73    `Original request: ${request}`,
74    'Original plan:',
75    ...steps.map((s, i) => `${i + 1}. ${s.text}`),
76    `Steps 1 to ${lever.step - 1} are done in this folder${doneSummaries.length ? ': ' + doneSummaries.join(' ') : '.'}`,
77    `Step ${lever.step} ("${steps[lever.step - 1]?.text}") is the checkpoint, chosen because: ${lever.why}`,
78    '',
79    'Write an IMPROVEMENT PLAN: the numbered steps that should now finish the work, improving or changing direction wherever the results so far show a better way. 2 to 8 short steps. Put a short heading line before the list.',
80  ].join('\n');
81}
82
83const stepObjectiveBriefing = ctx => ctx;
84
85export function createForkTimeskip({ agent, dir, notify = () => {}, now = Date.now, stepTimeoutMs = 15 * 60_000 }) {
86  mkdirSync(dir, { recursive: true });
87  const runs = new Map();     // id -> internal run
88
89  const pub = r => ({
90    id: r.id, kind: 'fork', phase: r.phase, workspace: r.workspace, prompt: r.prompt, startedAt: r.startedAt / 1000, finishedAt: r.finishedAt ? r.finishedAt / 1000 : null,
91    attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: r.phase === 'completed' && !!r.b?.root,
92    error: r.error, plan: r.plan, lever: r.lever, a: r.a, b: r.b, labels: { original: 'A', updated: 'B' }, activity: r.activity,
93  });
94  const saveFile = r => join(dir, r.id, 'run.json');
95  const persist = r => { try { mkdirSync(join(dir, r.id), { recursive: true }); const tmp = saveFile(r) + '.tmp'; writeFileSync(tmp, JSON.stringify(pub(r))); renameSync(tmp, saveFile(r)); } catch { /* memory only */ } };
96  let lastSent = new Map();
97  const announce = r => {
98    persist(r);
99    const view = { id: r.id, phase: r.phase, activity: r.activity, plan: r.plan, lever: r.lever, a: r.a, b: r.b };
100    const key = JSON.stringify(view);
101    if (lastSent.get(r.id) !== key) { lastSent.set(r.id, key); notify('timeskip', JSON.parse(key)); }
102  };
103  const say = (r, code, text, args = {}) => { r.activity = { code, text, args }; announce(r); };
104  // The page's older phase names keep working (queued/checkpointing/generating/checking/completed); the new fields say the rest.
105  const setPhase = (r, phase) => { r.phase = phase; announce(r); };
106
107  async function ask(r, chatId, line, ws, choice, thinking, mode = 'plan') {
108    let text = '';
109    await agent.runTurn({ chatId, message: line, workspacePath: ws, choice, mode, thinking, onFrame: f => { if (f.type === 'delta') text += f.text; } });
110    return text;
111  }
112
113  /**
114   * One plan step in its own session: tried twice if it ends early; stopped when it takes longer than `stepTimeoutMs` (a small model that keeps
115   * debugging one step must not hold the whole version for an hour). A step that cannot finish (too long, or a look-in-a-browser step on a machine
116   * with no screen) is left as it is with a plain note and the next step goes on; any other step that fails ends the version.
117   * Returns 'done' | 'skipped' | 'failed' | 'stopped'.
118   */
119  async function runOneStep(r, { tag, chat, planId, plan, at, root, choice, thinking, onFrame }) {
120    let finished = false, timedOut = false;
121    for (let attempt = 0; attempt < 2 && !finished && !timedOut && !r.stopping; attempt++) {
122      if (attempt) { agent.reopenPlan(chat); say(r, tag + '-retry', `${tag.toUpperCase()}, trying step ${at + 1} again…`, { step: at + 1 }); }
123      agent.resetSession(chat);
124      const turn = agent.planGoal({ chatId: chat, planId, once: true, workspacePath: root, mode: 'bypass', choice, thinking, onFrame });
125      let timer;
126      const raced = await Promise.race([turn.then(() => 'ended'), new Promise(res => { timer = setTimeout(() => res('timeout'), stepTimeoutMs); timer.unref?.(); })]);
127      clearTimeout(timer);
128      if (raced === 'timeout') { timedOut = true; try { await agent.stop(chat, { waitMs: 15_000 }); } catch { /* ending anyway */ } await turn.catch(() => {}); }
129      if (r.stopping) return 'stopped';
130      finished = agent.planState(chat)?.steps[at]?.state === 'done';
131    }
132    if (finished) return 'done';
133    if (timedOut || isViewStep(plan.steps[at].text)) {
134      agent.skipStep(chat, at, timedOut ? 'This step took too long, so it was left as it is.' : 'Could not look at the page here; the files were checked instead.');
135      say(r, tag + '-skip', timedOut ? `${tag.toUpperCase()}, step ${at + 1} took too long and was left as it is.` : `${tag.toUpperCase()}, step ${at + 1} (viewing the page) was skipped on this machine.`, { step: at + 1 });
136      return 'skipped';
137    }
138    return 'failed';
139  }
140
141  async function runFlow(r, { choice, thinking, slots }) {
142    const aChat = `ts:${r.id}:A`, bChat = `ts:${r.id}:B`, leverChat = `ts:${r.id}:lever`;
143    r.chats = [aChat, bChat, leverChat];
144    const stopped = () => r.stopping;
145    try {
146      // 1. plan
147      setPhase(r, 'checkpointing'); say(r, 'planning', 'Planning the work…');
148      copyProject(r.workspace, r.a.root);
149      await agent.planCommand({ chatId: aChat, line: r.prompt, workspacePath: r.a.root, choice, thinking, mode: 'plan', onFrame: f => { if (f.type === 'status' && f.text) say(r, 'planning', f.text, f.args ?? {}); } });
150      if (stopped()) return;
151      const plan = agent.planState(aChat);
152      if (!plan || plan.steps.length < 2) throw new Error('The assistant could not split this request into steps. Describe the steps you want, or use /goal instead.');
153      agent.setPlanBriefing(aChat, UNATTENDED);
154      agent.planControl({ chatId: aChat, planId: plan.id, action: 'approve' });
155      r.plan = { id: plan.id, title: plan.title, steps: plan.steps.map(s => ({ id: s.id, text: s.text, detail: s.detail })) };
156      announce(r);
157      // 2. the lever
158      say(r, 'choosing-lever', 'Choosing the step that matters most…');
159      let lever = null;
160      if (plan.steps.length >= 3) {
161        try { const said = await ask(r, leverChat, leverPrompt(r.prompt, plan.steps), r.a.root, choice, 'Low'); if (process.env.TS_DEBUG) console.log('lever said:', JSON.stringify(said).slice(0, 300)); lever = parseLever(said, plan.steps.length); } catch (e) { lever = null; if (process.env.TS_DEBUG) console.log('lever failed', e.message); }
162        if (stopped()) return;
163        lever ??= defaultLever(plan.steps);
164      }
165      r.lever = lever ? { step: lever.step, total: plan.steps.length, text: plan.steps[lever.step - 1].text, why: lever.why, defaulted: !!lever.defaulted } : null;
166      if (!r.lever) { r.b = { state: 'none', note: 'This plan is too short to be worth forking: only A runs.' }; }
167      announce(r);
168
169      // 3. A runs all the way; B forks when A has finished the step before the lever
170      let bDone = null;
171      const doneSummaries = [];
172      const startB = async () => {
173        r.b.state = 'planning'; r.b.waiting = false; say(r, 'b-planning', 'B: planning the improved path…');
174        await agent.planCommand({ chatId: bChat, line: improvementPrompt({ request: r.prompt, steps: plan.steps, lever, doneSummaries }), workspacePath: r.b.root, choice, thinking, mode: 'plan', onFrame: () => {} });
175        if (stopped()) return;
176        const bp = agent.planState(bChat);
177        if (!bp || bp.steps.length < 2) { r.b.state = 'failed'; r.b.note = 'The improvement plan could not be written, so only A is shown.'; announce(r); return; }
178        agent.setPlanBriefing(bChat, UNATTENDED + ' This work continues from a first attempt that is already in this folder; its notes are in .timeskip/context.md (read them first). Improve on it where it is weak instead of starting over.');
179        agent.planControl({ chatId: bChat, planId: bp.id, action: 'approve' });
180        r.b.plan = bp.steps.map(s => ({ id: s.id, text: s.text }));
181        r.b.state = 'running'; r.b.total = bp.steps.length; announce(r);
182        for (let at = 0; at < bp.steps.length && !stopped(); at++) {
183          const res = await runOneStep(r, { tag: 'b', chat: bChat, planId: bp.id, plan: bp, at, root: r.b.root, choice, thinking,
184            onFrame: f => {
185              if (f.type === 'error') r.b.note = String(f.message ?? '').slice(0, 240);
186              if (f.type === 'goal' && f.goal?.blocked) r.b.note = String(f.goal.blocked).slice(0, 240);
187              if (f.type === 'plan-step') { r.b.step = f.index; r.b.total = f.total; r.b.text = f.text; r.b.line = f.line; say(r, 'b-step', `B, ${f.line}`, { step: f.index, steps: f.total }); }
188            } });
189          if (res === 'stopped') return;
190          if (res === 'failed') break;
191        }
192        const end = agent.planState(bChat);
193        r.b.state = end?.steps.every(x => ['done', 'skipped'].includes(x.state)) ? 'done' : 'failed';
194        if (r.b.state === 'done') r.b.note = end.steps.some(x => x.state === 'skipped') ? 'A step that could not finish was left as it is.' : null;
195        if (r.b.state === 'failed') r.b.note = stopped() ? 'Stopped.' : 'B did not finish, so only A is shown.';
196        announce(r);
197      };
198      let forked = false;
199      const forkNow = () => {
200        if (forked || !r.lever) return;
201        forked = true;
202        copyProject(r.a.root, r.b.root);
203        mkdirSync(join(r.b.root, '.timeskip'), { recursive: true });
204        writeFileSync(join(r.b.root, '.timeskip', 'context.md'), [
205          `# Work so far (copied from the first attempt, A)`, '', `Request: ${r.prompt}`, '', 'Plan:', ...plan.steps.map((s, i) => `${i + 1}. ${s.text}`), '',
206          `Steps 1 to ${lever.step - 1} are done in this folder.`, ...r.a.summaries.map(s => `- ${s}`), '', `Checkpoint step ${lever.step}: ${plan.steps[lever.step - 1].text}`, `Why this step: ${lever.why}`, ''].join('\n'));
207        r.b = { ...r.b, root: r.b.root, state: 'waiting', waiting: slots < 2, step: 0, total: 0 };
208        doneSummaries.push(...r.a.summaries);
209        announce(r);
210        if (slots >= 2) bDone = startB();
211      };
212      r.b ??= {};
213      if (r.lever) { r.b = { state: 'pending', root: join(dir, r.id, 'B'), waiting: slots < 2 }; }
214      r.a.state = 'running'; r.a.total = plan.steps.length; setPhase(r, 'generating'); announce(r);
215      // Each step is its own turn in its own agent session (the folder carries the work from step to step): a small model window never fills up
216      // across a long plan. The fork happens between two steps, so B gets exactly the files of the finished steps.
217      for (let at = 0; at < plan.steps.length && !stopped(); at++) {
218        const res = await runOneStep(r, { tag: 'a', chat: aChat, planId: plan.id, plan, at, root: r.a.root, choice, thinking,
219          onFrame: f => {
220            if (f.type === 'error') r.a.note = String(f.message ?? '').slice(0, 240);
221            if (f.type === 'goal' && f.goal) r.a.goal = { phase: f.goal.phase, blocked: f.goal.blocked ?? null, round: f.goal.round };
222            if (f.type === 'plan-step') {
223              r.a.step = f.index; r.a.total = f.total; r.a.text = f.text; r.a.line = f.line;
224              if (f.state === 'done') r.a.summaries.push(`${f.index}. ${f.text}${f.summary ? ': ' + f.summary : ''}`);
225              say(r, 'a-step', `A, ${f.line}`, { step: f.index, steps: f.total });
226            }
227          } });
228        if (res === 'stopped') return;
229        if (res === 'failed') break;
230        if (r.lever && at + 1 === r.lever.step - 1) { try { forkNow(); } catch (e) { r.b = { ...r.b, state: 'failed', note: 'B could not be prepared, so only A is shown.' }; } }
231      }
232      if (stopped()) return;
233      const aEnd = agent.planState(aChat);
234      r.a.state = aEnd?.steps.every(x => ['done', 'skipped'].includes(x.state)) ? 'done' : 'failed';
235      announce(r);
236      if (r.a.state !== 'done') throw new Error('A did not finish the plan' + (r.a.note ? ' (' + r.a.note + ')' : r.a.goal?.blocked ? ' (' + r.a.goal.blocked + ')' : '') + ', so there is nothing to compare. Your files were not changed.');
237      if (r.lever && !forked) { forkNow(); }
238      if (r.lever && slots < 2 && r.b.state === 'waiting') { say(r, 'b-waiting', 'A is done. B starts now (one model slot: B waited for A).'); bDone = startB(); }
239      if (bDone) await bDone.catch(e => { r.b.state = 'failed'; r.b.note = 'B stopped: ' + String(e.message ?? e).slice(0, 160); });
240      if (stopped()) return;
241      setPhase(r, 'checking'); say(r, 'comparing', 'Comparing A and B…');
242      r.finishedAt = now();
243      r.activity = r.b?.state === 'done' ? { code: 'ready', text: 'Both versions are ready. Compare A and B, then keep the one you like.', args: {} } : { code: 'ready', text: 'The result is ready.' + (r.b?.note ? ' ' + r.b.note : ''), args: {} };
244      setPhase(r, 'completed');
245    } catch (e) {
246      if (stopped()) return;
247      r.error = String(e.message ?? e).slice(0, 400); r.finishedAt = now(); r.activity = null; setPhase(r, 'failed');
248    } finally {
249      for (const c of r.chats) { try { agent.forget?.(c); } catch { /* best effort */ } }
250    }
251  }
252
253  return {
254    /** Start a run; resolves at once with the first snapshot. */
255    start({ prompt, workspace, chatId = null, choice, thinking = 'Low', slots = 1 }) {
256      const id = randomUUID().replaceAll('-', '');
257      const r = { id, chatId, prompt: String(prompt ?? '').trim().slice(0, 4000), workspace: resolve(workspace), phase: 'queued', startedAt: now(), finishedAt: null, error: null, plan: null, lever: null, b: null, activity: { code: 'planning', text: 'Planning the work…', args: {} }, stopping: false,
258        a: { state: 'pending', root: join(dir, id, 'A'), step: 0, total: 0, summaries: [] }, chats: [] };
259      runs.set(id, r);
260      announce(r);
261      r.done = runFlow(r, { choice, thinking, slots });
262      return pub(r);
263    },
264    has: id => runs.has(String(id)),
265    status: id => { const r = runs.get(String(id)); return r ? pub(r) : null; },
266    list: () => [...runs.values()].map(pub),
267    byChat: chatId => [...runs.values()].find(r => r.chatId === chatId && !TERMINAL.has(r.phase))?.id ?? null,
268    async stop(id) {
269      const r = runs.get(String(id)); if (!r) return false;
270      if (TERMINAL.has(r.phase)) return false;
271      r.stopping = true;
272      await Promise.allSettled((r.chats ?? []).map(c => agent.stop(c, { waitMs: 8000 })));
273      r.finishedAt = now(); r.activity = null; r.phase = 'cancelled'; if (r.a) r.a.state = r.a.state === 'done' ? 'done' : 'stopped'; if (r.b?.state && r.b.state !== 'done') r.b.state = 'stopped';
274      announce(r);
275      try { await r.done; } catch { /* ended */ }
276      try { rmSync(join(dir, r.id), { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ }
277      return true;
278    },
279    /** A against B (or the original against A when there was no fork). */
280    files(id) {
281      const r = runs.get(String(id)); if (!r || !TERMINAL.has(r.phase) || r.phase === 'cancelled') return null;
282      return diffRun(recordOf(r));
283    },
284    image(id, rel, version) { const r = runs.get(String(id)); return r ? imageOf(r, rel, version) : null; },
285    /** Keep A or B: copy what differs into the person's folder, keeping the replaced files for "put the original back". */
286    apply({ id, which = 'b', restore = false }) {
287      const r = runs.get(String(id));
288      if (!r) throw new Error('No such Time-skip run.');
289      const back = join(dir, r.id, 'rollback');
290      if (restore) {
291        if (!existsSync(back)) throw new Error('There is nothing to put back.');
292        cpSync(back, r.workspace, { recursive: true, force: true });
293        for (const rel of readIndex(back).created) { try { rmSync(join(r.workspace, rel), { force: true }); } catch { /* gone */ } }
294        rmSync(back, { recursive: true, force: true });
295        return { restored: true };
296      }
297      if (r.phase !== 'completed') throw new Error('This run has not finished.');
298      const from = which === 'a' ? r.a.root : (r.b?.root && r.b.state === 'done' ? r.b.root : null);
299      if (!from) throw new Error('B is not available: only A can be kept.');
300      if (existsSync(back)) throw new Error('A result is already in your files. Put the original back first.');
301      mkdirSync(back, { recursive: true });
302      const created = []; let copied = 0;
303      for (const rel of walk(from)) {
304        if (isNoisePath(rel)) continue;
305        const src = join(from, rel), dst = join(r.workspace, rel);
306        if (existsSync(dst) && Buffer.compare(readFileSync(src), readFileSync(dst)) === 0) continue;
307        if (existsSync(dst)) { mkdirSync(dirname(join(back, rel)), { recursive: true }); cpSync(dst, join(back, rel)); } else created.push(rel);
308        mkdirSync(dirname(dst), { recursive: true }); cpSync(src, dst); copied += 1;
309      }
310      writeFileSync(join(back, '.index.json'), JSON.stringify({ created }));
311      return { applied: which, files: copied };
312    },
313  };
314
315  function recordOf(r) {
316    if (r.b?.root && r.b.state === 'done') return { checkpoints: [{ id: 'cp-a', label: 'baseline', path: r.a.root }, { id: 'cp-b', label: 'b', path: r.b.root }], selected_checkpoint: 'cp-b', attempts: [] };
317    return { checkpoints: [{ id: 'cp-orig', label: 'baseline', path: r.workspace }], selected_checkpoint: 'cp-orig', attempts: [{ index: 1, path: r.a.root }] };
318  }
319  function imageOf(r, rel, version) { return runImagePath(recordOf(r), rel, version); }
320}
321
322function* walkGen(root, base = root) {
323  let entries; try { entries = readdirSync(root, { withFileTypes: true }); } catch { return; }
324  for (const e of entries) {
325    const full = join(root, e.name);
326    if (e.isDirectory()) { if (!SKIP.has(e.name)) yield* walkGen(full, base); }
327    else if (e.isFile()) yield relative(base, full).split(sep).join('/');
328  }
329}
330const walk = root => [...walkGen(root)];
331function readIndex(back) { try { return JSON.parse(readFileSync(join(back, '.index.json'), 'utf8')); } catch { return { created: [] }; } }
332void stepObjectiveBriefing; void statSync;