copilot-operator 0.1.62 → 0.1.63

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 (46) hide show
  1. package/dist/src/api/operator.controller.js +31 -0
  2. package/dist/src/api/operator.service.js +75 -7
  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/systemGuide.js +119 -0
  8. package/dist/src/session/store.js +4 -0
  9. package/dist/web/404.html +2 -2
  10. package/dist/web/_next/static/chunks/1077.155f883ebfb223ae.js +1 -0
  11. package/dist/web/_next/static/chunks/1548.52fe19b2bb6dbe66.js +1 -0
  12. package/dist/web/_next/static/chunks/2163.51278cbd88674f1a.js +1 -0
  13. package/dist/web/_next/static/chunks/714.a3555e6b7e5f4339.js +1 -0
  14. package/dist/web/_next/static/chunks/7220.a7dcaec140695190.js +1 -0
  15. package/dist/web/_next/static/chunks/7921-b7eba39a21993047.js +1 -0
  16. package/dist/web/_next/static/chunks/8584.baf85c4394dc04eb.js +1 -0
  17. package/dist/web/_next/static/chunks/9067.2d7665cd257d7b47.js +1 -0
  18. package/dist/web/_next/static/chunks/9747.66a374501673612f.js +1 -0
  19. package/dist/web/_next/static/chunks/app/page-03f129240e06a07c.js +1 -0
  20. package/dist/web/_next/static/chunks/app/settings/page-9a83381087178f80.js +1 -0
  21. package/dist/web/_next/static/chunks/{webpack-4665fed2f4b06052.js → webpack-38c956574db7c7a6.js} +1 -1
  22. package/dist/web/_next/static/css/{5ec15fce93be8cbe.css → 2f2419505403ce07.css} +1 -1
  23. package/dist/web/defaults.html +2 -2
  24. package/dist/web/defaults.txt +8 -8
  25. package/dist/web/index.html +3 -3
  26. package/dist/web/index.txt +9 -9
  27. package/dist/web/queue.html +2 -2
  28. package/dist/web/queue.txt +9 -9
  29. package/dist/web/settings.html +2 -2
  30. package/dist/web/settings.txt +9 -9
  31. package/dist/web/system.html +2 -2
  32. package/dist/web/system.txt +9 -9
  33. package/package.json +3 -2
  34. package/dist/web/_next/static/chunks/1077.42a0502bfe3f2014.js +0 -1
  35. package/dist/web/_next/static/chunks/1548.dbf0648a1239382e.js +0 -1
  36. package/dist/web/_next/static/chunks/2163.dbdeebeb0c069d62.js +0 -1
  37. package/dist/web/_next/static/chunks/714.6472121643f99452.js +0 -1
  38. package/dist/web/_next/static/chunks/7220.391debd1191fc29a.js +0 -1
  39. package/dist/web/_next/static/chunks/7921-0549a0038e591e42.js +0 -1
  40. package/dist/web/_next/static/chunks/8584.4432f14f0cd88188.js +0 -1
  41. package/dist/web/_next/static/chunks/9067.841d6d2f4726f9c2.js +0 -1
  42. package/dist/web/_next/static/chunks/9747.1a7337320eccdc8a.js +0 -1
  43. package/dist/web/_next/static/chunks/app/page-ea0a60db75dac546.js +0 -1
  44. package/dist/web/_next/static/chunks/app/settings/page-1833ace66fc9eb0e.js +0 -1
  45. /package/dist/web/_next/static/{PJs9xZLAnUDPOFvGV0T_M → kxZRE1oIu_arurqhfP4mS}/_buildManifest.js +0 -0
  46. /package/dist/web/_next/static/{PJs9xZLAnUDPOFvGV0T_M → kxZRE1oIu_arurqhfP4mS}/_ssgManifest.js +0 -0
@@ -356,6 +356,20 @@ let OperatorController = class OperatorController {
356
356
  }
357
357
  return this.ops.decide(id, body.action);
358
358
  }
359
+ /** A subtask that failed for a technical reason (two chats, 2026-10-25): one of its card's choices. */
360
+ answerRetry(id, body) {
361
+ const result = this.ops.answerRetry(id, typeof body?.choice === 'string' ? body.choice : '');
362
+ if (!result.ok)
363
+ throw new BadRequestException(result.problem);
364
+ return result;
365
+ }
366
+ /** After a Stop (two chats, 2026-10-25): the stopped message carried on with one of its subtasks tried again first. */
367
+ chatRetrySubtask(id, taskId, body = {}) {
368
+ const n = Number(body?.n);
369
+ if (!Number.isInteger(n) || n < 1)
370
+ throw new BadRequestException('n, the subtask\'s number, is required');
371
+ return this.ops.chatRetrySubtask(id, taskId, n, body?.fresh === true).catch(fail);
372
+ }
359
373
  /** The lead's question (two chats): the operator's answer, as text. Stopping the task is `approvals/:id` with abort. */
360
374
  answerQuestion(id, body) {
361
375
  const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '');
@@ -757,6 +771,23 @@ __decorate([
757
771
  __metadata("design:paramtypes", [String, Object]),
758
772
  __metadata("design:returntype", Object)
759
773
  ], OperatorController.prototype, "decide", null);
774
+ __decorate([
775
+ Post('approvals/:id/retry'),
776
+ __param(0, Param('id')),
777
+ __param(1, Body()),
778
+ __metadata("design:type", Function),
779
+ __metadata("design:paramtypes", [String, Object]),
780
+ __metadata("design:returntype", Object)
781
+ ], OperatorController.prototype, "answerRetry", null);
782
+ __decorate([
783
+ Post('chat/:id/tasks/:taskId/retry-subtask'),
784
+ __param(0, Param('id')),
785
+ __param(1, Param('taskId')),
786
+ __param(2, Body()),
787
+ __metadata("design:type", Function),
788
+ __metadata("design:paramtypes", [String, String, Object]),
789
+ __metadata("design:returntype", Promise)
790
+ ], OperatorController.prototype, "chatRetrySubtask", null);
760
791
  __decorate([
761
792
  Post('approvals/:id/answer'),
762
793
  __param(0, Param('id')),
@@ -36,8 +36,11 @@ import { chatCode } from '../transport/chatSession.js';
36
36
  /** The folders the operator works in: the default new sessions start on, and the rest by name. */
37
37
  /** The longest level 2 a project may have: Kerrigan carries each one whole. */
38
38
  export const MAX_PROJECT_LEVEL2 = 8000;
39
- /** Its instructions: as long as a project's level 2, the longest text the opening carries besides the task. */
40
- export const MAX_SKILL_TEXT = 8000;
39
+ /*
40
+ * Its instructions have no limit of their own (operator, 2026-10-25: "remove the limit; say how many characters there
41
+ * are instead"): the message they go with is held to Settings' `limits.maxMessageChars` like every other — longer, its
42
+ * beginning goes as text and the whole of it attached.
43
+ */
41
44
  export const MAX_SKILL_DESCRIPTION = 300;
42
45
  export const MAX_SKILLS = 50;
43
46
  /** What follows `/` at the start of a message: lowercase letters, digits and hyphens, 2 to 40 of them. */
@@ -919,6 +922,7 @@ let OperatorService = class OperatorService {
919
922
  approvePlan: (ask) => this.askPlanApproval(ask, controller.signal),
920
923
  // The two-chat mode (2026-10-20): the lead's questions, and the worker the run speaks for too.
921
924
  askQuestion: (ask) => this.askLeadQuestion(ask, controller.signal),
925
+ askSubtaskRetry: (ask) => this.askSubtaskRetry(ask, controller.signal),
922
926
  onWorker: (workerId) => this.workerLeads.set(workerId, sessionId),
923
927
  hold,
924
928
  })
@@ -1507,18 +1511,17 @@ let OperatorService = class OperatorService {
1507
1511
  return { status, ...(status !== 'done' ? { why: task?.reason ?? `it ended ${task?.status ?? 'without a record'}` } : {}), sessionId };
1508
1512
  }
1509
1513
  // --- skills (2026-10-21) ----------------------------------------------------------------------------
1510
- /** The skills in Settings, and how long their instructions may be. */
1514
+ /** The skills in Settings, and how long what each is for may be. */
1511
1515
  async skills() {
1512
1516
  const cfg = await this.settings.load();
1513
1517
  return {
1514
1518
  skills: (cfg.skills ?? []).map((k) => ({ name: k.name, description: k.description ?? '', text: k.text ?? '', projectDir: k.projectDir ?? '' })),
1515
- maxText: MAX_SKILL_TEXT,
1516
1519
  maxDescription: MAX_SKILL_DESCRIPTION,
1517
1520
  };
1518
1521
  }
1519
1522
  /**
1520
1523
  * Stores the list as given, held to the rules: a name to type after `/` — lowercase, digits and hyphens, each used
1521
- * once — instructions that are there and not too long, a project that is one of Settings' or every project.
1524
+ * once — instructions that are there, of any length, a project that is one of Settings' or every project.
1522
1525
  */
1523
1526
  async setSkills(list) {
1524
1527
  if (!Array.isArray(list))
@@ -1541,8 +1544,6 @@ let OperatorService = class OperatorService {
1541
1544
  const text = String(k?.text ?? '');
1542
1545
  if (!text.trim())
1543
1546
  throw new Error(`The skill "${name}" has no instructions: write what the chat should know and do for this kind of task.`);
1544
- if (text.length > MAX_SKILL_TEXT)
1545
- throw new Error(`The instructions of "${name}" are longer than ${MAX_SKILL_TEXT.toLocaleString('en')} characters.`);
1546
1547
  const projectDir = String(k?.projectDir ?? '').trim();
1547
1548
  if (projectDir && !folders.some((f) => sameFolder(f, projectDir)))
1548
1549
  throw new Error(`The skill "${name}" is for ${projectDir}, which is not one of the projects in Settings.`);
@@ -1677,6 +1678,73 @@ let OperatorService = class OperatorService {
1677
1678
  });
1678
1679
  }
1679
1680
  /** The operator's answer to the lead's question. */
1681
+ /**
1682
+ * A subtask of two chats that failed for a technical reason, put to the operator (2026-10-25): a card under the subtask
1683
+ * with why, which attempt it was, what it left, and the choices; it waits until one is chosen, or the task is stopped.
1684
+ * Answered with `answerRetry`; "abort" on the card, a Stop or the end of the run stop the task.
1685
+ */
1686
+ askSubtaskRetry(ask, signal) {
1687
+ return new Promise((resolveRetry) => {
1688
+ if (signal.aborted) {
1689
+ resolveRetry('stop');
1690
+ return;
1691
+ }
1692
+ const approval = {
1693
+ id: newId('a-'),
1694
+ sessionId: ask.sessionId,
1695
+ taskId: ask.taskId,
1696
+ stepId: 0,
1697
+ description: `Subtask ${ask.retry.n} (${ask.retry.title}) did not finish, attempt ${ask.retry.attempt} of ${ask.retry.maxAttempts}: ${ask.retry.reason || ask.retry.category}`,
1698
+ createdAt: new Date().toISOString(),
1699
+ actor: 'lead',
1700
+ retry: ask.retry,
1701
+ };
1702
+ this.waiting.set(approval.id, { approval, resolve: () => resolveRetry('stop'), resolveRetry });
1703
+ this.bus.publish({ sessionId: ask.sessionId, taskId: ask.taskId, type: 'approval-requested', level: 'warn',
1704
+ message: `subtask ${ask.retry.n} did not finish (attempt ${ask.retry.attempt} of ${ask.retry.maxAttempts}): the operator is asked what to do`, data: { approvalId: approval.id, retry: ask.retry } });
1705
+ });
1706
+ }
1707
+ /** The operator's choice for a subtask that failed for a technical reason: one of the card's own. */
1708
+ answerRetry(approvalId, choice) {
1709
+ const w = this.waiting.get(approvalId);
1710
+ if (!w?.resolveRetry || !w.approval.retry)
1711
+ return { ok: false, problem: 'No subtask is waiting for a choice under that id.' };
1712
+ if (!w.approval.retry.choices.includes(choice))
1713
+ return { ok: false, problem: `"${choice}" is not one of this card's choices: ${w.approval.retry.choices.join(', ')}.` };
1714
+ this.waiting.delete(approvalId);
1715
+ w.resolveRetry(choice);
1716
+ this.bus.publish({ sessionId: w.approval.sessionId, taskId: w.approval.taskId, type: 'approval-decided', level: 'info',
1717
+ message: `the operator chose for subtask ${w.approval.retry.n}: ${choice}`, data: { approvalId, retry: choice } });
1718
+ return { ok: true };
1719
+ }
1720
+ /**
1721
+ * Two chats, after a Stop (2026-10-25): "do not start a task again by itself after Stop; when the operator carries on in
1722
+ * the same conversation, let a chosen failed subtask be tried again, with the plan and the reports kept". The message
1723
+ * is carried on with that subtask first (`TaskContinuation.retrySubtask`), then the lead goes on; the run is started
1724
+ * as a message of the chat is.
1725
+ */
1726
+ async chatRetrySubtask(threadId, taskId, n, fresh) {
1727
+ await this.init();
1728
+ const session = await this.store.getSession(threadId);
1729
+ if (!session || session.kind !== 'chat')
1730
+ throw new Error('That conversation is not there any more.');
1731
+ if (this.running.has(threadId))
1732
+ throw new Error('The conversation is working: stop it first, or let it finish.');
1733
+ const task = session.tasks.find((t) => t.id === taskId);
1734
+ if (!task?.lead)
1735
+ throw new Error('That message is not one of two chats.');
1736
+ if (task.status !== 'aborted')
1737
+ throw new Error('Only a message that was stopped has a subtask to try again: the others carry on by themselves, or end.');
1738
+ const sub = [...task.lead.rounds].reverse().find((r) => r.subtask?.n === n)?.subtask;
1739
+ if (!sub)
1740
+ throw new Error(`The message has no subtask ${n}.`);
1741
+ const last = sub.attempts?.at(-1);
1742
+ if (last?.status === 'done')
1743
+ throw new Error(`Subtask ${n} was done; it is not done again.`);
1744
+ await this.store.rerunTask(threadId, taskId, {}, { fromAttempt: task.attempt ?? 1, stoppedBecause: task.reason, how: 'stopped', retrySubtask: { n, ...(fresh ? { fresh: true } : {}) } });
1745
+ const cfg = await this.settings.load();
1746
+ return await this.start(threadId, cfg.execution.mode);
1747
+ }
1680
1748
  answerQuestion(approvalId, text) {
1681
1749
  const w = this.waiting.get(approvalId);
1682
1750
  if (!w?.resolveAnswer)
@@ -498,6 +498,16 @@ export const RunConfigSchema = z.object({
498
498
  * subtask is a task of the worker's, with the limits above; this bounds the whole. Settings → Execution.
499
499
  */
500
500
  maxSubtasks: z.number().int().min(1).max(100).default(20),
501
+ /*
502
+ * A subtask of two chats that failed for a technical reason (operator's specification, 2026-10-25; see
503
+ * `orchestrator/subtaskRetry.ts`): `ask` puts it to the operator on a card; `same` tries it again in the same
504
+ * worker's conversation, `fresh` in a new one — by themselves only for a proven, temporary fault of the chat; `lead`
505
+ * gives the lead the report, as before. At most `subtaskRetries` times more (0 to 3), `subtaskRetryWaitSec` apart.
506
+ * Settings → "Retrying an interrupted subtask". Only for two chats.
507
+ */
508
+ subtaskRetryMode: z.enum(['ask', 'same', 'fresh', 'lead']).default('ask'),
509
+ subtaskRetries: z.number().int().min(0).max(3).default(2),
510
+ subtaskRetryWaitSec: z.number().int().min(0).max(600).default(15),
501
511
  /*
502
512
  * How many genuinely different approaches the chat must have tried before it may end a task
503
513
  * "blocked". The reply format's own floor is 2 (replySchema.ts); this raises it. A "blocked"
@@ -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': {