copilot-operator 0.1.62 → 0.1.64

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.
Files changed (50) hide show
  1. package/dist/src/api/operator.controller.js +36 -3
  2. package/dist/src/api/operator.service.js +142 -14
  3. package/dist/src/config/schema.js +10 -0
  4. package/dist/src/orchestrator/leadRunner.js +268 -30
  5. package/dist/src/orchestrator/subtaskRetry.js +152 -0
  6. package/dist/src/orchestrator/taskRunner.js +8 -0
  7. package/dist/src/plan/kerrigan.js +31 -4
  8. package/dist/src/plan/systemGuide.js +185 -2
  9. package/dist/src/queue/queue.js +8 -2
  10. package/dist/src/session/store.js +4 -0
  11. package/dist/web/404.html +2 -2
  12. package/dist/web/_next/static/chunks/1077.32bfff8490ea3d67.js +1 -0
  13. package/dist/web/_next/static/chunks/1548.2bbbbb4759fd5073.js +1 -0
  14. package/dist/web/_next/static/chunks/2163.147b0ca65a65d5dd.js +1 -0
  15. package/dist/web/_next/static/chunks/714.16070ca6426f260c.js +1 -0
  16. package/dist/web/_next/static/chunks/7220.f71047baa16e6be0.js +1 -0
  17. package/dist/web/_next/static/chunks/7921-90ed63bfdf7162f3.js +1 -0
  18. package/dist/web/_next/static/chunks/8584.abc09920f03375b1.js +1 -0
  19. package/dist/web/_next/static/chunks/9067.538dec4d8ec0b04e.js +1 -0
  20. package/dist/web/_next/static/chunks/9747.9d15583d6ebafba3.js +1 -0
  21. package/dist/web/_next/static/chunks/app/page-185efe80d6e8dd05.js +1 -0
  22. package/dist/web/_next/static/chunks/app/queue/page-d4155eb6ab172c03.js +1 -0
  23. package/dist/web/_next/static/chunks/app/settings/page-9a83381087178f80.js +1 -0
  24. package/dist/web/_next/static/chunks/{webpack-4665fed2f4b06052.js → webpack-d85f02ecd2903252.js} +1 -1
  25. package/dist/web/_next/static/css/{5ec15fce93be8cbe.css → d107848da2f006af.css} +1 -1
  26. package/dist/web/defaults.html +2 -2
  27. package/dist/web/defaults.txt +8 -8
  28. package/dist/web/index.html +3 -3
  29. package/dist/web/index.txt +9 -9
  30. package/dist/web/queue.html +2 -2
  31. package/dist/web/queue.txt +9 -9
  32. package/dist/web/settings.html +2 -2
  33. package/dist/web/settings.txt +9 -9
  34. package/dist/web/system.html +2 -2
  35. package/dist/web/system.txt +9 -9
  36. package/package.json +3 -2
  37. package/dist/web/_next/static/chunks/1077.42a0502bfe3f2014.js +0 -1
  38. package/dist/web/_next/static/chunks/1548.dbf0648a1239382e.js +0 -1
  39. package/dist/web/_next/static/chunks/2163.dbdeebeb0c069d62.js +0 -1
  40. package/dist/web/_next/static/chunks/714.6472121643f99452.js +0 -1
  41. package/dist/web/_next/static/chunks/7220.391debd1191fc29a.js +0 -1
  42. package/dist/web/_next/static/chunks/7921-0549a0038e591e42.js +0 -1
  43. package/dist/web/_next/static/chunks/8584.4432f14f0cd88188.js +0 -1
  44. package/dist/web/_next/static/chunks/9067.841d6d2f4726f9c2.js +0 -1
  45. package/dist/web/_next/static/chunks/9747.1a7337320eccdc8a.js +0 -1
  46. package/dist/web/_next/static/chunks/app/page-ea0a60db75dac546.js +0 -1
  47. package/dist/web/_next/static/chunks/app/queue/page-f86936d39121ade8.js +0 -1
  48. package/dist/web/_next/static/chunks/app/settings/page-1833ace66fc9eb0e.js +0 -1
  49. /package/dist/web/_next/static/{PJs9xZLAnUDPOFvGV0T_M → vU04zVwJyicqgtWQsApuV}/_buildManifest.js +0 -0
  50. /package/dist/web/_next/static/{PJs9xZLAnUDPOFvGV0T_M → vU04zVwJyicqgtWQsApuV}/_ssgManifest.js +0 -0
@@ -24,7 +24,7 @@ import { isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
24
24
  import { buildChatName, chatCode, savePointer } from '../transport/chatSession.js';
25
25
  import { RunLog } from '../log/runLog.js';
26
26
  import { gapFrom, Pacer } from '../util/pacing.js';
27
- import { takeAfter, takeCheckpoint } from '../session/checkpoint.js';
27
+ import { restoreCheckpoint, takeAfter, takeCheckpoint } from '../session/checkpoint.js';
28
28
  import { commitFiles } from '../vcs/git.js';
29
29
  import { buildStory } from '../session/story.js';
30
30
  import { operatorNotesSection, whyItStopped } from '../session/compose.js';
@@ -32,6 +32,7 @@ import { describeDeviations } from '../protocol/replySchema.js';
32
32
  import { leadFormatErrorMessage, parseLeadReply, UNDERSTANDING_FIRST } from '../protocol/leadSchema.js';
33
33
  import { describePlan, planFrom } from './planMode.js';
34
34
  import { closeLedger, describeLedger, nextLedger } from './leadLedger.js';
35
+ import { classifySubtaskEnd, describeAttempts, FAILURE_WORDS, retryMessage, retryPlan, sanitizedReason, sideEffectsOf, stepFacts, stepsOf } from './subtaskRetry.js';
35
36
  import { ACTOR_WORDS, applySessionModel, enterSessionConversation, holdsWhilePaused, limitsMessageLength, runTask, Sink, speakFor, StoppedSend } from './taskRunner.js';
36
37
  import { DEFAULT_VCS } from '../session/store.js';
37
38
  /** The assignment as the lead is given it: the operator's message, and what the runner tells it about the work. */
@@ -106,6 +107,16 @@ export function subtaskPrompt(sub, n) {
106
107
  ...(sub.readOnly ? ['', 'This subtask changes nothing: read, run and diagnose, but do not create, change or delete a file.'] : []),
107
108
  ].join('\n');
108
109
  }
110
+ function givenOf(sub) {
111
+ return { title: sub.title, readOnly: sub.readOnly, fresh: sub.freshWorker, prompt: (n) => subtaskPrompt(sub, n) };
112
+ }
113
+ /**
114
+ * What the lead is told when it carries on after a Stop and the operator had one subtask tried again first (2026-10-25):
115
+ * the usual "continue", then that subtask's report under its own number.
116
+ */
117
+ export function afterStopRetryMessage(continuation, n, report) {
118
+ return [continuation, '', `Before you go on: the operator had subtask ${n} tried again after the Stop, under its own number — it is not a new subtask. Its report:`, '', report].join('\n');
119
+ }
109
120
  /** How a subtask ended, in the report's words. */
110
121
  function endedAs(status) {
111
122
  switch (status) {
@@ -177,6 +188,11 @@ export async function runLeadTask(transport, session, task, deps) {
177
188
  sink.event('acting', acting, `at work now: ${ACTOR_WORDS[actor]}${more.subtask ? ` (subtask ${more.subtask})` : ''}`);
178
189
  };
179
190
  const max = Math.max(1, cfg.limits.maxSubtasks ?? 20);
191
+ /*
192
+ * The most subtasks this attempt may have given in all: `max`, and as many again as the attempt before had given when a
193
+ * subtask is tried again after a Stop, its record carried on (2026-10-25).
194
+ */
195
+ let limit = max;
180
196
  const lead = { rounds: [], subtasks: 0, maxSubtasks: max };
181
197
  const saveLead = async () => {
182
198
  const copy = JSON.parse(JSON.stringify(lead));
@@ -375,16 +391,20 @@ export async function runLeadTask(transport, session, task, deps) {
375
391
  sink.event('worker-made', { workerSessionId: worker.id }, 'a worker for the lead\'s subtasks');
376
392
  return worker;
377
393
  };
378
- /** The worker's report of a subtask, as the lead is given it. */
379
- const reportOf = async (workerId, taskId, out, n, title) => {
394
+ /** The worker's report of a subtask, as the lead is given it: its last attempt's, with how the earlier ones went. */
395
+ const reportOf = async (workerId, taskId, out, n, title, tries) => {
380
396
  const w = await store.getSession(workerId);
381
397
  const t = w?.tasks.find((x) => x.id === taskId);
382
- const story = t?.runId ? await buildStory(cfg.resolved.runsDir, t.runId, t, false).catch(() => null) : null;
383
- const steps = (story?.entries ?? []).flatMap((e) => (e.kind === 'step' ? [e] : e.kind === 'review' ? e.entries.filter((x) => x.kind === 'step') : []));
398
+ const steps = await stepsOfTask(t);
384
399
  const commands = steps.slice(-25).map((s) => `- \`${s.command.replace(/\s+/g, ' ').slice(0, 160)}\` → ${s.exitCode ?? s.outcome ?? '?'}`);
385
400
  const files = (t?.vcs?.files ?? []).map((f) => f.path);
401
+ const last = tries?.attempts.at(-1);
402
+ const attempts = tries ? describeAttempts(tries.attempts, tries.maxAttempts) : '';
386
403
  return [
387
404
  `Report of subtask ${n} (${title}): ${endedAs(out.status)}.`,
405
+ // Which kind of ending it was (2026-10-25), and the attempts, when it was tried more than once.
406
+ ...(last?.category ? ['', `It ended for this reason: ${FAILURE_WORDS[last.category]}.`] : []),
407
+ ...(attempts ? ['', attempts] : []),
388
408
  '',
389
409
  '### The worker\'s report',
390
410
  (t?.summary ?? out.summary ?? '').trim() || '(the worker gave no summary)',
@@ -394,42 +414,79 @@ export async function runLeadTask(transport, session, task, deps) {
394
414
  files.length > 0 ? `Files it changed: ${files.join(', ')}.` : 'It changed no file.',
395
415
  ...((t?.deviations?.length ?? 0) > 0 ? ['', describeDeviations(t.deviations)] : []),
396
416
  '',
397
- `Subtasks left: ${max - lead.subtasks} of ${max}.`,
417
+ `Subtasks left: ${limit - lead.subtasks} of ${limit}.`,
398
418
  // Its own list, as it sent it last, to send again with the next subtask (2026-10-21).
399
- ...(lead.ledger ? ['', describeLedger(lead.ledger, lead.subtasks, max)] : []),
419
+ ...(lead.ledger ? ['', describeLedger(lead.ledger, lead.subtasks, limit)] : []),
400
420
  'Reply in the lead\'s format: the next subtask, the plan, a question for the operator, or the result.',
401
421
  ].join('\n');
402
422
  };
403
- /** One subtask: to the worker's conversation, carried out there as a task, and back to the lead with its report. */
404
- const runSubtask = async (sub, round) => {
405
- lead.subtasks += 1;
406
- const n = lead.subtasks;
423
+ /** The steps of a worker's task, as its run folder has them. */
424
+ const stepsOfTask = async (t) => {
425
+ const story = t?.runId ? await buildStory(cfg.resolved.runsDir, t.runId, t, false).catch(() => null) : null;
426
+ return stepsOf(story?.entries ?? []);
427
+ };
428
+ /*
429
+ * Trying a subtask again (operator's specification, 2026-10-25; see `subtaskRetry.ts`): as Settings say, at most so
430
+ * many times more, so far apart. Only for two chats.
431
+ */
432
+ const retrying = {
433
+ mode: (cfg.limits.subtaskRetryMode ?? 'ask'),
434
+ maxAttempts: 1 + Math.max(0, Math.min(3, cfg.limits.subtaskRetries ?? 2)),
435
+ waitMs: Math.max(0, cfg.limits.subtaskRetryWaitSec ?? 15) * 1000,
436
+ };
437
+ /** A pause the run's Stop ends. */
438
+ const pauseFor = (ms) => new Promise((resolve) => {
439
+ if (ms <= 0 || signal?.aborted)
440
+ return resolve();
441
+ const timer = setTimeout(resolve, ms);
442
+ signal?.addEventListener('abort', () => {
443
+ clearTimeout(timer);
444
+ resolve();
445
+ }, { once: true });
446
+ });
447
+ /** What the subtasks done before this one reported, for a fresh worker's conversation, which has not seen them. */
448
+ const predecessors = (before) => lead.rounds.flatMap((r) => r.subtask && r.subtask.n < before && r.subtask.report && (r.subtask.attempts?.at(-1)?.status ?? 'done') === 'done' ? [{ n: r.subtask.n, title: r.subtask.title, report: r.subtask.report }] : []);
449
+ /** One attempt at a subtask: a task of the worker's, in its conversation (a fresh one when asked), carried out there. */
450
+ const runAttempt = async (given, n, attempt, prompt, fresh) => {
407
451
  let worker = await workerSession();
408
- if (sub.freshWorker && worker.chat) {
452
+ if (fresh && worker.chat) {
409
453
  worker = await store.updateSession(worker.id, (s) => {
410
454
  s.chat = undefined;
411
455
  s.contractSent = false;
412
456
  s.modelByHand = undefined;
413
457
  });
414
- sink.event('worker-fresh', { n }, `subtask ${n} goes to a fresh worker conversation`);
458
+ sink.event('worker-fresh', { n, attempt }, `subtask ${n}${attempt > 1 ? `, attempt ${attempt},` : ''} goes to a fresh worker conversation`);
415
459
  }
416
- const made = await store.addTask(worker.id, { title: `${n}. ${sub.title}`, level2: '', prompt: subtaskPrompt(sub, n), reviewEnabled: false, readOnly: sub.readOnly, ...(task.skill ? { skill: task.skill } : {}) });
460
+ const made = await store.addTask(worker.id, {
461
+ title: attempt > 1 ? `${n}. ${given.title} (attempt ${attempt})` : `${n}. ${given.title}`,
462
+ level2: '',
463
+ prompt,
464
+ reviewEnabled: false,
465
+ readOnly: given.readOnly,
466
+ ...(task.skill ? { skill: task.skill } : {}),
467
+ });
417
468
  await store.updateTask(worker.id, made.id, (t) => {
418
469
  t.fromLead = { sessionId: session.id, taskId: task.id, n };
419
470
  });
420
- round.subtask = { n, taskId: made.id, title: sub.title, ...(sub.readOnly ? { readOnly: true } : {}), ...(sub.freshWorker ? { fresh: true } : {}) };
471
+ // The attempt at work is the subtask's task the chat shows, from its first command.
472
+ const sub = currentRound.subtask;
473
+ sub.taskId = made.id;
474
+ sub.attempts = [
475
+ ...(sub.attempts ?? []).filter((a) => a.attempt !== attempt),
476
+ { attempt, taskId: made.id, status: 'running', startedAt: new Date().toISOString(), commands: { started: 0, completed: 0 }, repoChanged: null, ...(fresh ? { fresh: true } : {}) },
477
+ ];
421
478
  await saveLead();
422
- sink.event('subtask-given', { n, taskId: made.id, title: sub.title, readOnly: sub.readOnly, fresh: sub.freshWorker }, `subtask ${n} to the worker: ${sub.title}`);
479
+ sink.event(attempt > 1 ? 'subtask-retried' : 'subtask-given', { n, taskId: made.id, title: given.title, attempt, readOnly: given.readOnly, fresh }, attempt > 1 ? `subtask ${n} tried again, attempt ${attempt} of ${sub.maxAttempts}: ${given.title}` : `subtask ${n} to the worker: ${given.title}`);
423
480
  await actingNow('worker', { subtask: n });
424
481
  // To the worker's conversation, in the same window.
425
482
  speakFor(transport, worker.id);
426
- const fresh = !worker.chat;
483
+ const freshChat = !worker.chat;
427
484
  await enterSessionConversation(transport, worker, { closeOnFailure: false });
428
- const model = await applySessionModel(transport, worker, bus, cfg, store, deps.models, fresh, signal);
485
+ const model = await applySessionModel(transport, worker, bus, cfg, store, deps.models, freshChat, signal);
429
486
  if (model.refused) {
430
487
  speakFor(transport, session.id);
431
488
  if (signal?.aborted)
432
- return 'stopped';
489
+ return { stopped: true, taskId: made.id };
433
490
  throw new Error(`The worker's conversation could not be put on its model: ${model.refused}`);
434
491
  }
435
492
  const current = (await store.getSession(worker.id));
@@ -454,8 +511,150 @@ export async function runLeadTask(transport, session, task, deps) {
454
511
  if (transport.closedOutside())
455
512
  throw new WindowClosed();
456
513
  if (signal?.aborted)
457
- return 'stopped';
458
- sink.event('subtask-ended', { n, status: out.status }, `subtask ${n} ${out.status}`);
514
+ return { stopped: true, taskId: made.id };
515
+ sink.event('subtask-ended', { n, status: out.status, attempt }, `subtask ${n}${attempt > 1 ? ` (attempt ${attempt})` : ''} ${out.status}`);
516
+ const done = ((await store.getSession(worker.id))?.tasks.find((x) => x.id === made.id) ?? subtask);
517
+ return { out, done, workerId: worker.id };
518
+ };
519
+ /** The round whose subtask is being worked: an attempt writes itself on it. */
520
+ let currentRound = null;
521
+ /**
522
+ * One subtask, to its end: tried, and tried again when it failed for a technical reason and Settings, or the operator
523
+ * on its card, say so (2026-10-25) — under the same number, never counted as another subtask, each attempt on record —
524
+ * then back to the lead with the report of its last attempt and how the others went. `resume`: after a Stop, the
525
+ * subtask the operator chose to try again, with the attempts it already had, carried on from the folder as it is.
526
+ */
527
+ const runSubtask = async (given, round, resume) => {
528
+ let n;
529
+ if (resume)
530
+ n = resume.n;
531
+ else {
532
+ lead.subtasks += 1;
533
+ n = lead.subtasks;
534
+ }
535
+ const firstPrompt = resume ? resume.firstPrompt : given.prompt(n);
536
+ round.subtask = {
537
+ n,
538
+ taskId: resume?.from.taskId ?? '',
539
+ title: given.title,
540
+ ...(given.readOnly ? { readOnly: true } : {}),
541
+ ...(given.fresh ? { fresh: true } : {}),
542
+ attempts: [...(resume?.from.attempts ?? [])],
543
+ maxAttempts: Math.max(retrying.maxAttempts, (resume?.from.attempts?.length ?? 0) + 1),
544
+ };
545
+ currentRound = round;
546
+ const sub = round.subtask;
547
+ await saveLead();
548
+ let attempt = (sub.attempts?.length ?? 0) + 1;
549
+ let how = resume ? { fresh: resume.fresh, continued: true, restored: false, by: 'after-stop' } : { fresh: given.fresh, continued: false, restored: false };
550
+ // What the attempt before left, for the next one's message: what finished, what was cut off, what changed so far.
551
+ let previous;
552
+ let changedSoFar = [];
553
+ if (resume && resume.from.attempts?.length) {
554
+ const last = resume.from.attempts.at(-1);
555
+ const w = lead.workerSessionId ? await store.getSession(lead.workerSessionId) : null;
556
+ const lastTask = w?.tasks.find((x) => x.id === last.taskId);
557
+ const facts = stepFacts(await stepsOfTask(lastTask));
558
+ previous = { why: last.reason ? `${FAILURE_WORDS[last.category ?? 'USER_STOPPED']}: ${last.reason}` : FAILURE_WORDS[last.category ?? 'USER_STOPPED'], done: facts.done, cutOff: facts.cutOff };
559
+ changedSoFar = [...new Set(resume.from.attempts.flatMap((a) => (w?.tasks.find((x) => x.id === a.taskId)?.vcs?.files ?? []).map((f) => f.path)))];
560
+ }
561
+ let ended;
562
+ for (;;) {
563
+ const prompt = attempt === 1 || !previous
564
+ ? firstPrompt
565
+ : retryMessage(firstPrompt, { n, attempt, maxAttempts: sub.maxAttempts, why: previous.why, continued: how.continued, restored: how.restored, fresh: how.fresh, done: previous.done, cutOff: previous.cutOff, changed: changedSoFar, predecessors: predecessors(n) });
566
+ let one;
567
+ try {
568
+ one = await runAttempt(given, n, attempt, prompt, how.fresh);
569
+ }
570
+ catch (e) {
571
+ // Its record closed, not left "running": the window closed by the operator, or the chat failing under the lead.
572
+ const open = sub.attempts?.find((a) => a.attempt === attempt && a.status === 'running');
573
+ if (open) {
574
+ const theirs = e instanceof WindowClosed || e instanceof StoppedSend || !!signal?.aborted;
575
+ Object.assign(open, { status: theirs ? 'aborted' : 'failed', category: theirs ? 'USER_STOPPED' : 'TRANSIENT_CHAT_FAILURE', reason: sanitizedReason(e.message), endedAt: new Date().toISOString() });
576
+ await saveLead().catch(() => undefined);
577
+ }
578
+ throw e;
579
+ }
580
+ const mark = sub.attempts.find((a) => a.attempt === attempt);
581
+ Object.assign(mark, { ...(how.continued && attempt > 1 ? { continued: true } : {}), ...(how.restored ? { restored: true } : {}), ...(attempt > 1 ? { retryOf: attempt - 1 } : {}), ...(how.by ? { by: how.by } : {}) });
582
+ if ('stopped' in one) {
583
+ Object.assign(mark, { status: 'aborted', category: 'USER_STOPPED', reason: 'stopped by the operator', endedAt: new Date().toISOString() });
584
+ await saveLead();
585
+ return 'stopped';
586
+ }
587
+ ended = one;
588
+ const facts = stepFacts(await stepsOfTask(one.done));
589
+ const category = classifySubtaskEnd(one.done);
590
+ const side = sideEffectsOf(one.done, facts);
591
+ const workerNow = await store.getSession(one.workerId);
592
+ Object.assign(mark, {
593
+ status: one.done.status,
594
+ ...(category ? { category: category !== 'TASK_EVIDENCE_FAILURE' && category !== 'USER_STOPPED' && side.state === 'unknown' ? 'UNKNOWN_SIDE_EFFECT_STATE' : category } : {}),
595
+ ...(category ? { reason: sanitizedReason(one.done.reason ?? one.out.reason) } : {}),
596
+ ...(workerNow?.chat?.chatId ? { chatId: workerNow.chat.chatId } : {}),
597
+ endedAt: new Date().toISOString(),
598
+ commands: { started: facts.started, completed: facts.completed },
599
+ repoChanged: one.done.vcs?.commit ? side.changed.length > 0 : null,
600
+ sideEffects: side.state,
601
+ });
602
+ changedSoFar = [...new Set([...changedSoFar, ...side.changed])];
603
+ await saveLead();
604
+ const plan = retryPlan({ category, sideEffects: side.state, mode: retrying.mode, attempt, maxAttempts: sub.maxAttempts, canAsk: !!deps.askSubtaskRetry });
605
+ if (category && category !== 'TASK_EVIDENCE_FAILURE') {
606
+ sink.event('subtask-attempt-failed', { n, attempt, category: mark.category, sideEffects: side.state, plan: plan.do }, `subtask ${n}, attempt ${attempt} of ${sub.maxAttempts}: ${FAILURE_WORDS[mark.category]} (${side.why})${plan.do === 'lead' ? ` — to the lead: ${plan.why}` : ''}`, 'warn');
607
+ }
608
+ if (plan.do === 'lead')
609
+ break;
610
+ let choice;
611
+ let by;
612
+ if (plan.do === 'ask') {
613
+ const got = await deps.askSubtaskRetry({
614
+ sessionId: one.workerId,
615
+ taskId: one.done.id,
616
+ retry: { n, title: given.title, attempt, maxAttempts: sub.maxAttempts, category: plan.category, reason: mark.reason ?? '', sideEffects: side.state, changed: side.changed, choices: plan.choices },
617
+ });
618
+ if (got === 'stop' || signal?.aborted)
619
+ return 'stopped';
620
+ if (got === 'accept') {
621
+ sink.event('subtask-retry-declined', { n, attempt }, `subtask ${n}: the operator takes it as failed; the lead decides`);
622
+ break;
623
+ }
624
+ choice = got;
625
+ by = 'operator';
626
+ }
627
+ else {
628
+ choice = plan.choice;
629
+ by = 'settings';
630
+ }
631
+ /*
632
+ * What the next attempt starts from. Put back to the subtask's start only at the operator's word — never by itself;
633
+ * carried on from the folder as it is when something changed, the commands that finished not to be run again.
634
+ */
635
+ let restored = false;
636
+ if (choice === 'restore') {
637
+ const firstTask = (await store.getSession(one.workerId))?.tasks.find((x) => x.id === sub.attempts[0].taskId);
638
+ const cp = firstTask?.checkpoint;
639
+ const back = cp && chatDir ? await restoreCheckpoint(chatDir, cp) : { ok: false, problem: 'the subtask\'s start was not photographed' };
640
+ if (!back.ok) {
641
+ sink.event('subtask-restore-failed', { n, problem: back.problem }, `subtask ${n}: the folder could not be put back to the subtask's start (${back.problem}); the lead decides`, 'error');
642
+ break;
643
+ }
644
+ restored = true;
645
+ changedSoFar = [];
646
+ sink.event('subtask-restored', { n, safety: back.safety }, `subtask ${n}: the folder put back to how it was when the subtask began, at the operator's word (what it was is kept as ${back.safety.slice(0, 8)})`);
647
+ }
648
+ how = { fresh: choice === 'fresh', continued: !restored && (choice === 'continue' || side.state === 'changed'), restored, by };
649
+ previous = { why: `${FAILURE_WORDS[mark.category ?? 'TRANSIENT_CHAT_FAILURE']}${mark.reason ? `: ${mark.reason}` : ''}`, done: facts.done, cutOff: facts.cutOff };
650
+ if (retrying.waitMs > 0) {
651
+ sink.event('subtask-retry-wait', { n, ms: retrying.waitMs }, `subtask ${n} is tried again in ${Math.round(retrying.waitMs / 1000)} s`);
652
+ await pauseFor(retrying.waitMs);
653
+ if (signal?.aborted)
654
+ return 'stopped';
655
+ }
656
+ attempt += 1;
657
+ }
459
658
  await actingNow('lead');
460
659
  // Back to the lead's conversation.
461
660
  const leadNow = (await store.getSession(session.id));
@@ -466,7 +665,11 @@ export async function runLeadTask(transport, session, task, deps) {
466
665
  return 'stopped';
467
666
  throw new Error(`The lead's conversation could not be put on its model again: ${back.refused}`);
468
667
  }
469
- return { report: await reportOf(worker.id, made.id, out, n, sub.title) };
668
+ const report = await reportOf(ended.workerId, ended.done.id, ended.out, n, given.title, { attempts: sub.attempts, maxAttempts: sub.maxAttempts });
669
+ // Kept with the subtask: what a fresh worker trying a later one is told was done before it.
670
+ sub.report = report.slice(0, 6000);
671
+ await saveLead();
672
+ return { report };
470
673
  };
471
674
  try {
472
675
  const facts = {
@@ -499,7 +702,42 @@ export async function runLeadTask(transport, session, task, deps) {
499
702
  s.contractSent = true;
500
703
  });
501
704
  }
502
- markdown = await tell(assignment);
705
+ /*
706
+ * After a Stop, the subtask the operator chose to try again (2026-10-25): first, under its own number, on the record
707
+ * the stopped attempt left — its rounds, its list of subtasks, the subtasks given, its worker — carried on from the
708
+ * folder as it is; then the lead is told to carry on, with that subtask's report.
709
+ */
710
+ const retryFirst = carryingOn ? task.continuing?.retrySubtask : undefined;
711
+ const before = retryFirst ? task.attempts?.at(-1)?.lead : undefined;
712
+ const from = before && retryFirst ? [...before.rounds].reverse().find((r) => r.subtask?.n === retryFirst.n)?.subtask : undefined;
713
+ if (retryFirst && before && from) {
714
+ lead.rounds = JSON.parse(JSON.stringify(before.rounds));
715
+ lead.subtasks = before.subtasks;
716
+ if (before.ledger)
717
+ lead.ledger = before.ledger;
718
+ if (before.workerSessionId)
719
+ lead.workerSessionId = before.workerSessionId;
720
+ limit = before.subtasks + max;
721
+ lead.maxSubtasks = limit;
722
+ const w = before.workerSessionId ? await store.getSession(before.workerSessionId) : null;
723
+ const firstId = from.attempts?.[0]?.taskId ?? from.taskId;
724
+ const firstTask = w?.tasks.find((x) => x.id === firstId);
725
+ // A subtask from before there were attempts: its one attempt, as its task had it.
726
+ const attempts = from.attempts?.length
727
+ ? from.attempts
728
+ : [{ attempt: 1, taskId: from.taskId, status: firstTask?.status ?? 'aborted', category: 'USER_STOPPED', reason: 'stopped by the operator', commands: { started: 0, completed: 0 }, repoChanged: null }];
729
+ const round = { n: lead.rounds.length + 1, at: new Date().toISOString(), status: 'delegate', notes: `Subtask ${retryFirst.n} tried again after the Stop, at the operator's word.` };
730
+ lead.rounds.push(round);
731
+ await saveLead();
732
+ sink.event('subtask-retry-after-stop', { n: retryFirst.n, fresh: !!retryFirst.fresh }, `subtask ${retryFirst.n} is tried again after the Stop, at the operator's word${retryFirst.fresh ? ', by a fresh worker' : ''}`);
733
+ const ran = await runSubtask({ title: from.title, readOnly: !!from.readOnly, fresh: !!retryFirst.fresh, prompt: () => firstTask?.prompt ?? '' }, round, { n: retryFirst.n, fresh: !!retryFirst.fresh, from: { ...from, attempts }, firstPrompt: firstTask?.prompt ?? '' });
734
+ if (ran === 'stopped')
735
+ return await finish('aborted', 'stopped by the operator');
736
+ markdown = await tell(afterStopRetryMessage(assignment, retryFirst.n, ran.report));
737
+ }
738
+ else {
739
+ markdown = await tell(assignment);
740
+ }
503
741
  const maxFormat = Math.max(0, cfg.limits.maxFormatRetries ?? 2);
504
742
  let formatRetries = 0;
505
743
  // A message carried on was restated when it began: its first reply now need not do it again.
@@ -546,7 +784,7 @@ export async function runLeadTask(transport, session, task, deps) {
546
784
  };
547
785
  lead.rounds.push(round);
548
786
  // Its list of subtasks, as this reply sends it (2026-10-21); the subtask given now is the running one.
549
- const giving = r.status === 'delegate' && r.subtask && lead.subtasks < max ? { title: r.subtask.title, n: lead.subtasks + 1 } : undefined;
787
+ const giving = r.status === 'delegate' && r.subtask && lead.subtasks < limit ? { title: r.subtask.title, n: lead.subtasks + 1 } : undefined;
550
788
  const listed = nextLedger(lead.ledger, r.todo, round.at, giving);
551
789
  lead.ledger = listed.ledger;
552
790
  if (listed.change) {
@@ -560,11 +798,11 @@ export async function runLeadTask(transport, session, task, deps) {
560
798
  sink.event('lead-reply', { round: round.n, status: r.status }, `the lead: ${r.status}${r.subtask ? ` — ${r.subtask.title}` : ''}`);
561
799
  switch (r.status) {
562
800
  case 'delegate': {
563
- if (lead.subtasks >= max) {
564
- markdown = await tell(noSubtasksLeft(max));
801
+ if (lead.subtasks >= limit) {
802
+ markdown = await tell(noSubtasksLeft(limit));
565
803
  break;
566
804
  }
567
- const ran = await runSubtask(r.subtask, round);
805
+ const ran = await runSubtask(givenOf(r.subtask), round);
568
806
  if (ran === 'stopped')
569
807
  return await finish('aborted', 'stopped by the operator');
570
808
  markdown = await tell(ran.report);
@@ -600,7 +838,7 @@ export async function runLeadTask(transport, session, task, deps) {
600
838
  if (t.plan)
601
839
  t.plan.approved = approved;
602
840
  });
603
- markdown = await tell(leadPlanApproved(approved, max - lead.subtasks));
841
+ markdown = await tell(leadPlanApproved(approved, limit - lead.subtasks));
604
842
  break;
605
843
  }
606
844
  case 'ask': {
@@ -616,7 +854,7 @@ export async function runLeadTask(transport, session, task, deps) {
616
854
  round.question.at = new Date().toISOString();
617
855
  await saveLead();
618
856
  sink.event('question-agreed', { round: round.n, question: r.question, answer: agreed }, `the lead asked: ${r.question} — answered as it recommends (Settings agree with what the bot proposes): ${agreed}`);
619
- markdown = await tell(operatorAnswerMessage(agreed, max - lead.subtasks));
857
+ markdown = await tell(operatorAnswerMessage(agreed, limit - lead.subtasks));
620
858
  break;
621
859
  }
622
860
  if (!deps.askQuestion) {
@@ -631,7 +869,7 @@ export async function runLeadTask(transport, session, task, deps) {
631
869
  round.question.at = new Date().toISOString();
632
870
  await saveLead();
633
871
  sink.event('lead-question-answered', { round: round.n }, 'the operator answered the lead');
634
- markdown = await tell(operatorAnswerMessage(got.answer, max - lead.subtasks));
872
+ markdown = await tell(operatorAnswerMessage(got.answer, limit - lead.subtasks));
635
873
  break;
636
874
  }
637
875
  case 'done': {
@@ -0,0 +1,152 @@
1
+ /** The steps of an attempt's story, its review's included. */
2
+ export function stepsOf(entries) {
3
+ return entries.flatMap((e) => (e.kind === 'step' ? [e] : e.kind === 'review' ? e.entries.filter((x) => x.kind === 'step') : []));
4
+ }
5
+ /** A command that began: one refused, or that the shell could not start, never did. */
6
+ const BEGAN = (s) => s.outcome !== undefined && s.outcome !== 'refused' && s.outcome !== 'spawn-error';
7
+ /** A command cut off while it ran. */
8
+ const CUT = (s) => s.outcome === 'aborted' || s.outcome === 'hard-timeout' || s.outcome === 'idle-timeout';
9
+ export function stepFacts(steps) {
10
+ const began = steps.filter(BEGAN);
11
+ return {
12
+ started: began.length,
13
+ completed: began.filter((s) => s.outcome === 'completed').length,
14
+ cutOff: began.filter(CUT).map((s) => s.command),
15
+ done: began.filter((s) => s.outcome === 'completed').map((s) => ({ command: s.command, ...(s.exitCode !== undefined ? { exitCode: s.exitCode } : {}) })),
16
+ };
17
+ }
18
+ /**
19
+ * How an attempt ended, as a category, or null when it ended done. Read from what the runner recorded, never from the
20
+ * words of a reason: a Stop or the window closed (`aborted`); the shell missing (`stopCode: environment`); the chat's
21
+ * answers out of their format however often it was asked again, or an answer that never came (the limits on those); a
22
+ * fault of the chat or the browser under the work (`failure: transport`). Anything else is the work's own end — a
23
+ * check or a test that fails, a blocker, a refused command, a limit of rounds or minutes — which the lead decides on.
24
+ */
25
+ export function classifySubtaskEnd(task, opts = {}) {
26
+ if (task.status === 'done')
27
+ return null;
28
+ if (opts.stopped || task.status === 'aborted')
29
+ return 'USER_STOPPED';
30
+ if (task.stopCode === 'environment' || task.failure?.kind === 'shell')
31
+ return 'COMMAND_INFRASTRUCTURE_FAILURE';
32
+ if (task.stopCode === 'format-repair-exhausted' || task.limit?.setting === 'maxFormatRetries')
33
+ return 'TRANSIENT_CHAT_FAILURE';
34
+ if (task.limit?.setting === 'replyTimeoutSec')
35
+ return 'TRANSIENT_CHAT_FAILURE';
36
+ if (task.failure?.kind === 'transport')
37
+ return 'TRANSIENT_CHAT_FAILURE';
38
+ return 'TASK_EVIDENCE_FAILURE';
39
+ }
40
+ /** Whether a category is a fault of the means, which may be tried again: the chat's, or the commands' runner. */
41
+ export function isTechnical(category) {
42
+ return category === 'TRANSIENT_CHAT_FAILURE' || category === 'COMMAND_INFRASTRUCTURE_FAILURE' || category === 'UNKNOWN_SIDE_EFFECT_STATE';
43
+ }
44
+ /**
45
+ * What an attempt left behind. The folder is compared with its photograph from the attempt's start (the chat's
46
+ * checkpoint, and the photograph after it): nothing changed and nothing cut off is `none`, safe to run again as it was;
47
+ * changes made by commands that finished are `changed`, to be carried on from, those commands not run again; a command
48
+ * cut off while it ran (a read-only subtask's apart, whose changes are put back), or a folder that could not be
49
+ * compared, is `unknown`, which the operator decides on.
50
+ */
51
+ export function sideEffectsOf(task, steps) {
52
+ const changed = (task.vcs?.files ?? []).map((f) => f.path);
53
+ if (steps.started === 0 && changed.length === 0)
54
+ return { state: 'none', changed, why: 'no command ran, and nothing in the folder changed' };
55
+ if (steps.cutOff.length > 0 && !task.readOnly) {
56
+ return { state: 'unknown', changed, why: `a command was cut off while it ran, so what it did is not known: ${steps.cutOff.slice(0, 3).map((c) => `\`${c.replace(/\s+/g, ' ').slice(0, 120)}\``).join(', ')}` };
57
+ }
58
+ if (!task.checkpoint || !task.vcs?.commit)
59
+ return { state: 'unknown', changed, why: 'the folder could not be compared with how it was when the subtask began' };
60
+ if (changed.length > 0)
61
+ return { state: 'changed', changed, why: `commands that finished changed ${changed.length} file(s)` };
62
+ return { state: 'none', changed, why: 'nothing in the folder changed' };
63
+ }
64
+ /**
65
+ * What to do after an attempt, by its category, what it left, Settings and the attempts left. Tried again by itself
66
+ * only for a proven, temporary fault of the chat (`TRANSIENT_CHAT_FAILURE`) with Settings saying so: one of the
67
+ * commands' runner is put to the operator, as is anything after which the folder is not known; without anybody to ask,
68
+ * the lead decides, as it did before there were attempts.
69
+ */
70
+ export function retryPlan(input) {
71
+ const { category, sideEffects, mode, attempt, maxAttempts, canAsk } = input;
72
+ if (!category)
73
+ return { do: 'lead', why: 'it ended done' };
74
+ if (category === 'USER_STOPPED')
75
+ return { do: 'lead', why: 'the operator stopped it; it is not started again by itself' };
76
+ if (category === 'TASK_EVIDENCE_FAILURE')
77
+ return { do: 'lead', why: 'the work itself ended so; the lead decides what comes next' };
78
+ if (attempt >= maxAttempts)
79
+ return { do: 'lead', why: `all ${maxAttempts} attempt(s) were used` };
80
+ if (mode === 'lead')
81
+ return { do: 'lead', why: 'Settings leave it to the lead' };
82
+ if (sideEffects === 'unknown') {
83
+ return canAsk ? { do: 'ask', choices: ['continue', 'restore', 'accept'], category: 'UNKNOWN_SIDE_EFFECT_STATE' } : { do: 'lead', why: 'what it changed is not known, and nobody is here to decide' };
84
+ }
85
+ if (mode === 'ask' || category === 'COMMAND_INFRASTRUCTURE_FAILURE') {
86
+ return canAsk ? { do: 'ask', choices: ['same', 'fresh', 'accept'], category } : { do: 'lead', why: mode === 'ask' ? 'nobody is here to ask' : 'the commands could not be run, which is not proven temporary' };
87
+ }
88
+ return { do: 'retry', choice: mode, continued: sideEffects === 'changed' };
89
+ }
90
+ /** What a category is, in the words the lead and the record use. */
91
+ export const FAILURE_WORDS = {
92
+ TRANSIENT_CHAT_FAILURE: 'a temporary failure of the chat or the browser',
93
+ COMMAND_INFRASTRUCTURE_FAILURE: 'the commands could not be run',
94
+ TASK_EVIDENCE_FAILURE: 'the work itself',
95
+ USER_STOPPED: 'stopped by the operator',
96
+ UNKNOWN_SIDE_EFFECT_STATE: 'interrupted after a possible change',
97
+ };
98
+ /** A reason for the record: one line, no longer than it needs, nothing of the machine's secrets. */
99
+ export function sanitizedReason(reason) {
100
+ return (reason ?? '')
101
+ .replace(/\r?\n[\s\S]*$/, '')
102
+ .replace(/(token|password|secret|key)=\S+/gi, '$1=…')
103
+ .replace(/[A-Za-z]:\\Users\\[^\\\s]+\\AppData\\Local\\copilot-operator\\edge-profile\S*/gi, '(the bot\'s Edge profile)')
104
+ .trim()
105
+ .slice(0, 300);
106
+ }
107
+ /**
108
+ * The message an attempt after the first is given (the lead's subtask as it was, `prompt`, then this): which attempt it
109
+ * is and why, and what it starts from — the folder put back to the subtask's start; or the folder as the last attempt
110
+ * left it, with what finished there, not to be run again; or, in a fresh conversation, the reports of the subtasks done
111
+ * before it, which it has not seen. Never to redo the assignment's other subtasks; the report as the lead asked for it.
112
+ */
113
+ export function retryMessage(prompt, input) {
114
+ const cmd = (c) => `\`${c.replace(/\s+/g, ' ').slice(0, 160)}\``;
115
+ return [
116
+ prompt,
117
+ '',
118
+ `## Attempt ${input.attempt} of ${input.maxAttempts} at subtask ${input.n}`,
119
+ '',
120
+ `The attempt before this one did not end: ${input.why}. This is the same subtask, given again — not a new one.`,
121
+ '',
122
+ ...(input.restored
123
+ ? ['The folder was put back to how it was when the subtask began, at the operator\'s word: start it from the beginning.', '']
124
+ : input.continued
125
+ ? [
126
+ 'Carry on from the folder as the last attempt left it: what it did is there. Do not run again the commands that finished; check what they left instead, and do what is still missing.',
127
+ ...(input.changed.length > 0 ? ['', `Files changed so far in this subtask: ${input.changed.slice(0, 40).join(', ')}${input.changed.length > 40 ? ` and ${input.changed.length - 40} more` : ''}.`] : []),
128
+ ...(input.done.length > 0 ? ['', 'Commands that finished in the last attempt — do not run them again:', ...input.done.slice(-25).map((d) => `- ${cmd(d.command)}${d.exitCode !== undefined ? ` → exit ${d.exitCode}` : ''}`)] : []),
129
+ ...(input.cutOff.length > 0 ? ['', 'Cut off while they ran, so what they did is not known — look before you run them again:', ...input.cutOff.slice(-10).map((c) => `- ${cmd(c)}`)] : []),
130
+ '',
131
+ ]
132
+ : ['Nothing in the folder changed in the last attempt: do the subtask as it is given above.', '']),
133
+ ...(input.fresh && input.predecessors.length > 0
134
+ ? [
135
+ 'This is a fresh conversation. What the subtasks done before this one reported, for what you need of it:',
136
+ '',
137
+ ...input.predecessors.slice(-6).flatMap((p) => [`### Subtask ${p.n}: ${p.title}`, p.report.trim().slice(0, 1500), '']),
138
+ ]
139
+ : []),
140
+ 'Do only this subtask: the assignment\'s other subtasks are not yours, and the ones done are not to be done again. Report back exactly as asked under "Report back" above.',
141
+ ].join('\n');
142
+ }
143
+ /** How a subtask's attempts went, for the lead's report: the last's ending, and the earlier ones in a line each. */
144
+ export function describeAttempts(attempts, maxAttempts) {
145
+ if (attempts.length <= 1)
146
+ return '';
147
+ const last = attempts.at(-1);
148
+ return [
149
+ last.status === 'done' ? `It was done at attempt ${last.attempt} of ${maxAttempts}.` : `It ended at attempt ${last.attempt} of ${maxAttempts}.`,
150
+ ...attempts.slice(0, -1).map((a) => `- Attempt ${a.attempt}: ${a.status}${a.category ? ` (${FAILURE_WORDS[a.category]})` : ''}${a.reason ? ` — ${a.reason}` : ''}.`),
151
+ ].join('\n');
152
+ }
@@ -3294,6 +3294,14 @@ export async function runTask(transport, session, task, deps) {
3294
3294
  * says so, with the process that died and where the report is.
3295
3295
  */
3296
3296
  const crash = /has been closed/i.test(message) ? await transport.recentCrash().catch(() => null) : null;
3297
+ /*
3298
+ * A fault of the means, not of the work (2026-10-25): what ended it here is the chat, the browser or the runner's own
3299
+ * dealing with them, never a check or the chat's report. A subtask of two chats reads it to say whether it may be
3300
+ * tried again (`classifySubtaskEnd`).
3301
+ */
3302
+ await setTask((t) => {
3303
+ t.failure = { kind: 'transport', detail: (crash ? `${describeCrash(crash)}. Then: ${message}` : message).slice(0, 400) };
3304
+ }).catch(() => undefined);
3297
3305
  return await finish('failed', crash ? `${describeCrash(crash)}. Then: ${message}` : message);
3298
3306
  }
3299
3307
  }