copilot-operator 0.1.51 → 0.1.52

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 (64) hide show
  1. package/README.md +8 -3
  2. package/dist/src/api/operator.controller.js +32 -81
  3. package/dist/src/api/operator.service.js +166 -109
  4. package/dist/src/config/schema.js +13 -0
  5. package/dist/src/orchestrator/leadRunner.js +559 -0
  6. package/dist/src/orchestrator/taskRunner.js +55 -17
  7. package/dist/src/plan/kerrigan.js +172 -47
  8. package/dist/src/plan/systemGuide.js +443 -506
  9. package/dist/src/protocol/leadSchema.js +156 -0
  10. package/dist/src/protocol/parser.js +1 -1
  11. package/dist/src/session/chatNotice.js +115 -0
  12. package/dist/src/session/checkpoint.js +19 -0
  13. package/dist/src/session/compose.js +1 -1
  14. package/dist/src/session/store.js +18 -72
  15. package/dist/src/transport/copilotTransport.js +2 -0
  16. package/dist/web/404.html +13 -18
  17. package/dist/web/_next/static/_1zhoDsMOPAH2xW702E5A/_buildManifest.js +1 -0
  18. package/dist/web/_next/static/chunks/163.dbd7d36584d0bb37.js +1 -0
  19. package/dist/web/_next/static/chunks/220.35531b39410e1a9f.js +1 -0
  20. package/dist/web/_next/static/chunks/548.71ac96c94136659b.js +1 -0
  21. package/dist/web/_next/static/chunks/584.6df695c5b86a75aa.js +1 -0
  22. package/dist/web/_next/static/chunks/67.9ed79e2fbfb56f26.js +1 -0
  23. package/dist/web/_next/static/chunks/714.1e2338736a70b9c7.js +1 -0
  24. package/dist/web/_next/static/chunks/747.d2c1249d736dc03b.js +1 -0
  25. package/dist/web/_next/static/chunks/77.a200abef0f5b4a7f.js +1 -0
  26. package/dist/web/_next/static/chunks/808-bc7d7eac6d823291.js +1 -0
  27. package/dist/web/_next/static/chunks/921-dc5538cd779c6432.js +1 -0
  28. package/dist/web/_next/static/chunks/app/defaults/page-edd7534ca9ecf366.js +1 -0
  29. package/dist/web/_next/static/chunks/app/layout-8f99a164d76897a0.js +1 -0
  30. package/dist/web/_next/static/chunks/app/page-4bed816eda370d0c.js +1 -0
  31. package/dist/web/_next/static/chunks/app/system/page-1cf9e75e76da59ed.js +1 -0
  32. package/dist/web/_next/static/chunks/webpack-77147e31d2125631.js +1 -0
  33. package/dist/web/_next/static/css/3bea264adc472bc8.css +1 -0
  34. package/dist/web/defaults.html +13 -18
  35. package/dist/web/defaults.txt +9 -9
  36. package/dist/web/index.html +13 -18
  37. package/dist/web/index.txt +9 -9
  38. package/dist/web/system.html +13 -18
  39. package/dist/web/system.txt +9 -9
  40. package/package.json +4 -5
  41. package/prompts/lead1.md +116 -0
  42. package/dist/src/vcs/prepareFromRemote.js +0 -288
  43. package/dist/src/vcs/remoteAuth.js +0 -117
  44. package/dist/src/vcs/syncCommand.js +0 -97
  45. package/dist/web/_next/static/chunks/190-70555f20dd0da19b.js +0 -1
  46. package/dist/web/_next/static/chunks/643-e85d221d57900ed7.js +0 -1
  47. package/dist/web/_next/static/chunks/867-869900ec999e6345.js +0 -1
  48. package/dist/web/_next/static/chunks/app/appearance/page-cdef33c421397cbe.js +0 -1
  49. package/dist/web/_next/static/chunks/app/defaults/page-e0a2b8f9a41a94c4.js +0 -1
  50. package/dist/web/_next/static/chunks/app/layout-b4fc21e26e1bad95.js +0 -1
  51. package/dist/web/_next/static/chunks/app/level1/page-31b74cae86d960d8.js +0 -1
  52. package/dist/web/_next/static/chunks/app/page-1075921d44db3e4d.js +0 -1
  53. package/dist/web/_next/static/chunks/app/presets/page-f8abdd83cdf468f7.js +0 -1
  54. package/dist/web/_next/static/chunks/app/system/page-2a270bb885885821.js +0 -1
  55. package/dist/web/_next/static/chunks/webpack-0f31b926d9a9c5a4.js +0 -1
  56. package/dist/web/_next/static/css/8b14cb3cf0051138.css +0 -1
  57. package/dist/web/_next/static/eqTUTH_SJtBgNgq8Zzy3n/_buildManifest.js +0 -1
  58. package/dist/web/appearance.html +0 -18
  59. package/dist/web/appearance.txt +0 -25
  60. package/dist/web/level1.html +0 -18
  61. package/dist/web/level1.txt +0 -25
  62. package/dist/web/presets.html +0 -21
  63. package/dist/web/presets.txt +0 -25
  64. /package/dist/web/_next/static/{eqTUTH_SJtBgNgq8Zzy3n → _1zhoDsMOPAH2xW702E5A}/_ssgManifest.js +0 -0
@@ -0,0 +1,559 @@
1
+ /**
2
+ * The two-chat mode (operator, 2026-10-20): "chat A takes the whole, complex task — it breaks it into steps, checks
3
+ * that it understands it, plans, and directs; chat B carries out the small technical tasks — reads files, runs tests,
4
+ * debugs, whatever it takes — and reports back to A. One LLM controls the process at a high level and knows what is to
5
+ * be achieved; the other does the separate technical tasks. The browser is not closed between the two chats."
6
+ *
7
+ * So a message of such a conversation is run here, not by `runTask`. The conversation of the chat's session is the
8
+ * lead's (A): it is given the lead's contract (`prompts/lead1.md`) and the assignment, and every reply of it is one
9
+ * decision in the shape `protocol/leadSchema.ts` holds it to — a subtask for the worker, the plan, a question for the
10
+ * operator, the result, or a stop. The worker (B) is a session of its own (`Session.workerOf`), made at the first
11
+ * subtask, with a conversation of its own in the same Copilot window; each subtask is a task of it, run by `runTask`
12
+ * as any chat message is, with everything that comes with that — commands asked about or not, Pause, Stop, the
13
+ * checkpoint of the folder, the limits. The window goes from one conversation to the other and back (as the review's
14
+ * does); it is never closed between them. The worker keeps its conversation across subtasks, so what it learnt of
15
+ * the project stays with it, unless the lead asks for a fresh one.
16
+ *
17
+ * What the operator sees is the lead's record on the message (`Task.lead`): its understanding of the assignment, its
18
+ * notes, its plan, the subtasks with the worker's commands under each, its questions with their answers, and the
19
+ * result, which is the message's summary. The folder is photographed before the message and after it, so its changes
20
+ * are shown and "go back" works for the whole of it.
21
+ */
22
+ import { appendFile, mkdir, writeFile } from 'node:fs/promises';
23
+ import { isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
24
+ import { buildChatName, chatCode, savePointer } from '../transport/chatSession.js';
25
+ import { RunLog } from '../log/runLog.js';
26
+ import { Pacer } from '../util/pacing.js';
27
+ import { takeAfter, takeCheckpoint } from '../session/checkpoint.js';
28
+ import { commitFiles } from '../vcs/git.js';
29
+ import { buildStory } from '../session/story.js';
30
+ import { operatorNotesSection, whyItStopped } from '../session/compose.js';
31
+ import { describeDeviations } from '../protocol/replySchema.js';
32
+ import { leadFormatErrorMessage, parseLeadReply, UNDERSTANDING_FIRST } from '../protocol/leadSchema.js';
33
+ import { describePlan, planFrom } from './planMode.js';
34
+ import { applySessionModel, enterSessionConversation, holdsWhilePaused, runTask, Sink, speakFor, StoppedSend } from './taskRunner.js';
35
+ import { DEFAULT_VCS } from '../session/store.js';
36
+ /** The assignment as the lead is given it: the operator's message, and what the runner tells it about the work. */
37
+ export function assignmentMessage(task, n, facts, again) {
38
+ return [
39
+ again
40
+ ? 'New assignment in this same conversation. The lead\'s contract you were given at the start still applies unchanged: the same format, the same rules. Restate this assignment in "understanding" in your first reply to it.'
41
+ : '',
42
+ `## Assignment ${n}: ${task.title.trim() || 'untitled'}`,
43
+ '',
44
+ task.prompt.trim(),
45
+ '',
46
+ '## What the runner tells you',
47
+ '',
48
+ `- The project folder, where the worker's commands run: ${facts.workDir || '(none is open)'}.`,
49
+ `- You may give the worker at most ${facts.maxSubtasks} subtask(s) for this assignment. Each subtask may take the worker up to ${facts.maxIterations} messages and ${facts.maxRunMinutes} minutes.`,
50
+ facts.planApproval
51
+ ? '- The operator approves plans: when you send "plan", the work waits for their answer.'
52
+ : '- Plans are not put to the operator here: send "plan" all the same, so it is on record; the work goes on at once.',
53
+ '- Reply in the lead\'s format.',
54
+ ]
55
+ .filter((l, i) => l !== '' || i > 0)
56
+ .join('\n')
57
+ .trim();
58
+ }
59
+ /**
60
+ * "Continue" on a message of the lead's that stopped before its result (a limit, Stop, the bot closed): in the same
61
+ * conversation, told why it stopped, to carry on from where the work got to — the subtasks and their reports are above
62
+ * it — rather than to start the assignment again.
63
+ */
64
+ export function continuationMessage(task, n, facts) {
65
+ const instruction = task.continuing?.instruction?.trim();
66
+ return [
67
+ `Continue assignment ${n}: ${task.title.trim() || 'untitled'}, in this same conversation. ${task.continuing ? whyItStopped(task.continuing) : ''}`.trim(),
68
+ '',
69
+ 'Do not start over: the subtasks so far and the worker\'s reports are above in this conversation. Say in "notes" where the work got to, and carry on from there in the lead\'s format.',
70
+ ...(instruction ? ['', 'The operator adds this, which wins where it and the assignment disagree:', '', instruction] : []),
71
+ '',
72
+ `You may give the worker up to ${facts.maxSubtasks} more subtask(s) for it.`,
73
+ ].join('\n');
74
+ }
75
+ /** A subtask, as the worker is given it: a task of its own, written so that someone who knows nothing else can do it. */
76
+ export function subtaskPrompt(sub, n) {
77
+ return [
78
+ `This task comes from the lead of the work, not straight from the operator: it is subtask ${n} of a larger assignment. Your closing summary is your report to the lead — put in it exactly what the lead asks for under "Report back", with the evidence (commands, their output, files and lines), not only your conclusions.`,
79
+ '',
80
+ `## Goal`,
81
+ sub.goal.trim(),
82
+ ...(sub.context.trim() ? ['', '## What you need to know', sub.context.trim()] : []),
83
+ ...(sub.steps.length > 0 ? ['', '## How to go about it', ...sub.steps.map((s, i) => `${i + 1}. ${s}`)] : []),
84
+ '',
85
+ '## Report back',
86
+ sub.report.trim(),
87
+ ...(sub.doneWhen.trim() ? ['', '## Done when', sub.doneWhen.trim()] : []),
88
+ ...(sub.readOnly ? ['', 'This subtask changes nothing: read, run and diagnose, but do not create, change or delete a file.'] : []),
89
+ ].join('\n');
90
+ }
91
+ /** How a subtask ended, in the report's words. */
92
+ function endedAs(status) {
93
+ switch (status) {
94
+ case 'done':
95
+ return 'done';
96
+ case 'blocked':
97
+ return 'blocked — the worker could not finish it';
98
+ case 'limit-reached':
99
+ return 'stopped at a limit of the settings, unfinished';
100
+ case 'aborted':
101
+ return 'stopped';
102
+ default:
103
+ return 'failed';
104
+ }
105
+ }
106
+ /** What the lead is told when it has no subtask left. */
107
+ export function noSubtasksLeft(max) {
108
+ return [
109
+ `No subtask is left: all ${max} of this assignment have been used. Do not send "delegate" again.`,
110
+ 'Deliver what the work has found (status "done", with what is missing said plainly in "answer"), or stop (status "blocked", with what would let it go on in "needed").',
111
+ ].join('\n');
112
+ }
113
+ /** The plan, as the lead is told it was approved. */
114
+ export function leadPlanApproved(approval, left) {
115
+ return [
116
+ approval.by === 'operator' ? 'The operator approved your plan.' : 'Your plan is on record; the operator is not asked about plans in this conversation.',
117
+ ...(approval.note?.trim() ? ['', 'With this from the operator, which wins where it and the plan disagree:', '', approval.note.trim()] : []),
118
+ '',
119
+ `Carry it out now: give the worker the first subtask of it (status "delegate"). Subtasks left: ${left}.`,
120
+ ].join('\n');
121
+ }
122
+ /** The operator asked the lead for another plan. */
123
+ export function leadPlanRevise(comment, version) {
124
+ return [
125
+ `The operator read version ${version} of your plan and asks for another. What to change:`,
126
+ '',
127
+ comment.trim(),
128
+ '',
129
+ 'Send the whole revised plan (status "plan"), not only what changed. You may give the worker a subtask first if you need to find something out for it.',
130
+ ].join('\n');
131
+ }
132
+ /** The operator's answer to the lead's question. */
133
+ export function operatorAnswerMessage(answer, left) {
134
+ return ['The operator answers your question:', '', answer.trim(), '', `Go on in the lead's format. Subtasks left: ${left}.`].join('\n');
135
+ }
136
+ /** Nobody can answer the lead's question (a run with no page to ask on). */
137
+ export const NOBODY_TO_ASK = 'Nobody can answer a question in this run: decide it yourself, the way that keeps the most options open, say the assumption in "notes", and go on.';
138
+ export async function runLeadTask(transport, session, task, deps) {
139
+ const { cfg, store, bus, signal } = deps;
140
+ const attempt = task.attempt ?? 1;
141
+ const runId = task.runId ?? `${session.id}-${task.id}${attempt > 1 ? `-a${attempt}` : ''}`;
142
+ const log = new RunLog(runId, cfg.resolved.runsDir);
143
+ const sink = new Sink(log, bus, session.id, task.id);
144
+ const taskLogPath = log.path('task-log.txt');
145
+ await mkdir(log.path('replies'), { recursive: true });
146
+ await mkdir(log.path('messages'), { recursive: true });
147
+ const record = async (heading, body) => {
148
+ await appendFile(taskLogPath, `\n${'='.repeat(78)}\n${heading}\n${'='.repeat(78)}\n${body.trimEnd()}\n`, 'utf8').catch(() => undefined);
149
+ };
150
+ const setTask = async (mutate) => {
151
+ await store.updateTask(session.id, task.id, mutate);
152
+ };
153
+ const max = Math.max(1, cfg.limits.maxSubtasks ?? 20);
154
+ const lead = { rounds: [], subtasks: 0, maxSubtasks: max };
155
+ const saveLead = async () => {
156
+ const copy = JSON.parse(JSON.stringify(lead));
157
+ await setTask((t) => {
158
+ t.lead = copy;
159
+ t.iterations = copy.rounds.length;
160
+ });
161
+ };
162
+ await setTask((t) => {
163
+ t.status = 'running';
164
+ t.runId = runId;
165
+ t.runGroup = deps.runGroup;
166
+ t.startedAt = new Date().toISOString();
167
+ t.lead = { rounds: [], subtasks: 0, maxSubtasks: max };
168
+ });
169
+ await writeFile(taskLogPath, `TASK: ${task.title}\nSESSION: ${session.name} (${session.id})\nRUN: ${runId}\nSTARTED: ${new Date().toISOString()}\nMODE: lead and worker\n`, 'utf8');
170
+ sink.event('task-started', { runId, title: task.title, lead: true }, `task "${task.title}" starting with a lead and a worker (run ${runId})`);
171
+ // The folder before the message, for "go back" and for what the whole of it changed.
172
+ const chatDir = session.projectDir?.trim() ?? '';
173
+ let checkpoint = task.checkpoint;
174
+ if (!checkpoint && chatDir) {
175
+ const cp = await takeCheckpoint(chatDir, task.id).catch((e) => ({ problem: e.message }));
176
+ if ('problem' in cp)
177
+ sink.event('chat-checkpoint-missing', { problem: cp.problem }, `no way back to before this message: ${cp.problem}`, 'warn');
178
+ else {
179
+ checkpoint = cp;
180
+ await setTask((t) => {
181
+ t.checkpoint = cp;
182
+ });
183
+ sink.event('chat-checkpoint', { commit: cp.commit, branch: cp.branch, head: cp.head }, `the folder before this message is kept as ${cp.commit.slice(0, 8)} (on ${cp.branch || cp.head.slice(0, 8)})`);
184
+ }
185
+ }
186
+ const pacer = new Pacer({ enabled: cfg.pacing.enabled, settleMs: cfg.pacing.settleMs, maxMessagesPerHour: cfg.pacing.maxMessagesPerHour });
187
+ let limitHit;
188
+ /*
189
+ * Paused (see `Hold`): the lead's next message waits, as the worker's do in `runTask`. True when the run was stopped
190
+ * while it was held.
191
+ */
192
+ const holdHere = async () => {
193
+ const hold = deps.hold;
194
+ if (!hold?.held || signal?.aborted)
195
+ return false;
196
+ const from = Date.now();
197
+ sink.event('task-paused', { before: 'message', lead: true }, 'paused by the operator: nothing more is sent to the lead until Continue');
198
+ await hold.until(signal);
199
+ const stopped = !!signal?.aborted;
200
+ sink.event('task-resumed', { heldMs: Date.now() - from, stopped }, stopped ? 'stopped while paused' : 'continued by the operator');
201
+ return stopped;
202
+ };
203
+ const leadChat = holdsWhilePaused(transport, holdHere);
204
+ let sent = 0;
205
+ let replies = 0;
206
+ /** One message to the lead, and its reply. */
207
+ const tell = async (text) => {
208
+ await pacer.throttleSend();
209
+ // The operator's notes written while the work goes on ("Add to it") go to the lead with its next message.
210
+ const notes = await store.takeUnsentNotes(session.id, task.id).catch(() => []);
211
+ const message = notes.length > 0 ? `${text}\n\n${operatorNotesSection(notes, true)}` : text;
212
+ if (notes.length > 0)
213
+ sink.event('operator-note-sent', { notes: notes.length, with: 'lead' }, `${notes.length} note(s) from the operator go to the lead`);
214
+ const before = await leadChat.sendAndConfirm(message);
215
+ sent += 1;
216
+ await writeFile(log.path('messages', `${String(sent).padStart(2, '0')}.md`), message, 'utf8').catch(() => undefined);
217
+ sink.event('message-sent', { n: sent, chars: message.length, lead: true, chatId: session.chat?.chatId ?? null }, `message ${sent} sent to the lead (${message.length} chars)`);
218
+ await record(`TO THE LEAD (${sent})`, message);
219
+ const reply = await leadChat.waitForReply(before);
220
+ replies += 1;
221
+ await writeFile(log.path('replies', `${String(replies).padStart(2, '0')}-lead.md`), reply.markdown, 'utf8').catch(() => undefined);
222
+ await record(`FROM THE LEAD (${replies})`, reply.markdown);
223
+ await pacer.settle();
224
+ await registerLeadChat();
225
+ return reply.markdown;
226
+ };
227
+ /** The lead's conversation, put on record and named once it exists. */
228
+ const registerLeadChat = async () => {
229
+ if (session.chat)
230
+ return;
231
+ const chatId = await transport.currentChatId().catch(() => null);
232
+ if (!chatId)
233
+ return;
234
+ const asked = buildChatName(chatCode(session.id), session.name);
235
+ const saved = await transport.nameChat(chatId, asked).catch(() => false);
236
+ const chat = {
237
+ chatId,
238
+ url: `${cfg.copilot.url.replace(/\/chat.*$/, '')}/chat/conversation/${chatId}?es=SSR`,
239
+ name: saved || asked,
240
+ ...(saved !== false ? {} : { named: false }),
241
+ runId,
242
+ createdAt: new Date().toISOString(),
243
+ };
244
+ session.chat = chat;
245
+ await store.updateSession(session.id, (s) => {
246
+ s.chat = chat;
247
+ });
248
+ await savePointer(log.path('chat.json'), chat).catch(() => undefined);
249
+ sink.event('chat-registered', { ...chat, lead: true }, `the lead's chat: ${chat.name}`);
250
+ };
251
+ const finish = async (status, reason, summary) => {
252
+ // What the whole of the message changed: the folder against its photograph from before it.
253
+ let vcs;
254
+ if (checkpoint && chatDir) {
255
+ const after = await takeAfter(chatDir, task.id, checkpoint).catch((e) => ({ problem: e.message }));
256
+ if (!('problem' in after))
257
+ vcs = { baseCommit: checkpoint.commit, commit: after.commit, files: await commitFiles(chatDir, after.commit).catch(() => []) };
258
+ }
259
+ await saveLead();
260
+ await setTask((t) => {
261
+ if (vcs)
262
+ t.vcs = vcs;
263
+ t.status = status;
264
+ t.finishedAt = new Date().toISOString();
265
+ t.summary = summary;
266
+ t.reason = reason;
267
+ t.logFile = 'task-log.txt';
268
+ if (limitHit)
269
+ t.limit = limitHit;
270
+ });
271
+ await record(`TASK ${status.toUpperCase()}`, [summary ?? '', reason ? `Reason: ${reason}` : ''].filter(Boolean).join('\n\n') || '(no details)');
272
+ sink.event('task-finished', { status, reason, iterations: lead.rounds.length, subtasks: lead.subtasks, lead: true }, `task "${task.title}" ${status}${reason ? `: ${reason}` : ''}`);
273
+ await log.close();
274
+ return { status, iterations: lead.rounds.length, summary, reason };
275
+ };
276
+ /** The worker's session: made at the first subtask, with the chat's folder and the worker's model. */
277
+ const workerSession = async () => {
278
+ const now = await store.getSession(session.id);
279
+ const id = now?.lead?.workerSessionId;
280
+ const existing = id ? await store.getSession(id) : null;
281
+ if (existing) {
282
+ deps.onWorker?.(existing.id);
283
+ lead.workerSessionId = existing.id;
284
+ return existing;
285
+ }
286
+ const made = await store.createSession(`worker: ${session.name.replace(/^chat: /, '')}`, session.projectDir ?? '');
287
+ const lead2 = now?.lead ?? {};
288
+ const worker = await store.updateSession(made.id, (s) => {
289
+ s.kind = 'chat';
290
+ s.workerOf = session.id;
291
+ s.onFailure = 'continue';
292
+ /*
293
+ * No version control of its own, as the chat has none (2026-10-17): the worker works on the branch the folder is
294
+ * on, and each subtask is photographed instead. A session is made with it on, and the first worker made a branch
295
+ * of the operator's repository and committed on it (found by the check, 2026-10-20).
296
+ */
297
+ s.vcs = { ...(s.vcs ?? DEFAULT_VCS), enabled: false, repoDir: '' };
298
+ s.projectDir = session.projectDir ?? '';
299
+ // The lead judges the worker's reports; there is no review of its own.
300
+ s.review = { enabled: false, model: '' };
301
+ s.planMode = 'off';
302
+ /*
303
+ * The worker's model as chosen under the chat's box; with none chosen, the lead's — by hand when the lead's is.
304
+ * A worker with no model of its own would be asked about by hand on every conversation that named one.
305
+ */
306
+ const own = lead2.workerModel?.trim();
307
+ if (lead2.workerManualModel || (!own && now?.manualModel))
308
+ s.manualModel = true;
309
+ else if (own || now?.model?.trim()) {
310
+ s.model = own || now?.model?.trim();
311
+ s.modelSource = 'operator';
312
+ }
313
+ if (session.lang)
314
+ s.lang = session.lang;
315
+ });
316
+ await store.updateSession(session.id, (s) => {
317
+ s.lead = { ...(s.lead ?? {}), workerSessionId: worker.id };
318
+ });
319
+ lead.workerSessionId = worker.id;
320
+ deps.onWorker?.(worker.id);
321
+ sink.event('worker-made', { workerSessionId: worker.id }, 'a worker for the lead\'s subtasks');
322
+ return worker;
323
+ };
324
+ /** The worker's report of a subtask, as the lead is given it. */
325
+ const reportOf = async (workerId, taskId, out, n, title) => {
326
+ const w = await store.getSession(workerId);
327
+ const t = w?.tasks.find((x) => x.id === taskId);
328
+ const story = t?.runId ? await buildStory(cfg.resolved.runsDir, t.runId, t, false).catch(() => null) : null;
329
+ const steps = (story?.entries ?? []).flatMap((e) => (e.kind === 'step' ? [e] : e.kind === 'review' ? e.entries.filter((x) => x.kind === 'step') : []));
330
+ const commands = steps.slice(-25).map((s) => `- \`${s.command.replace(/\s+/g, ' ').slice(0, 160)}\` → ${s.exitCode ?? s.outcome ?? '?'}`);
331
+ const files = (t?.vcs?.files ?? []).map((f) => f.path);
332
+ return [
333
+ `Report of subtask ${n} (${title}): ${endedAs(out.status)}.`,
334
+ '',
335
+ '### The worker\'s report',
336
+ (t?.summary ?? out.summary ?? '').trim() || '(the worker gave no summary)',
337
+ ...(out.status !== 'done' && (t?.reason ?? out.reason) ? ['', `### Why it ended so`, (t?.reason ?? out.reason ?? '').trim()] : []),
338
+ ...(commands.length > 0 ? ['', `### The commands it ran, and their exit codes${steps.length > 25 ? ` (the last 25 of ${steps.length})` : ''}`, ...commands] : ['', 'It ran no command.']),
339
+ '',
340
+ files.length > 0 ? `Files it changed: ${files.join(', ')}.` : 'It changed no file.',
341
+ ...((t?.deviations?.length ?? 0) > 0 ? ['', describeDeviations(t.deviations)] : []),
342
+ '',
343
+ `Subtasks left: ${max - lead.subtasks} of ${max}.`,
344
+ 'Reply in the lead\'s format: the next subtask, the plan, a question for the operator, or the result.',
345
+ ].join('\n');
346
+ };
347
+ /** One subtask: to the worker's conversation, carried out there as a task, and back to the lead with its report. */
348
+ const runSubtask = async (sub, round) => {
349
+ lead.subtasks += 1;
350
+ const n = lead.subtasks;
351
+ let worker = await workerSession();
352
+ if (sub.freshWorker && worker.chat) {
353
+ worker = await store.updateSession(worker.id, (s) => {
354
+ s.chat = undefined;
355
+ s.contractSent = false;
356
+ s.modelByHand = undefined;
357
+ });
358
+ sink.event('worker-fresh', { n }, `subtask ${n} goes to a fresh worker conversation`);
359
+ }
360
+ const made = await store.addTask(worker.id, { title: `${n}. ${sub.title}`, level2: '', prompt: subtaskPrompt(sub, n), reviewEnabled: false, readOnly: sub.readOnly });
361
+ await store.updateTask(worker.id, made.id, (t) => {
362
+ t.fromLead = { sessionId: session.id, taskId: task.id, n };
363
+ });
364
+ round.subtask = { n, taskId: made.id, title: sub.title, ...(sub.readOnly ? { readOnly: true } : {}), ...(sub.freshWorker ? { fresh: true } : {}) };
365
+ await saveLead();
366
+ sink.event('subtask-given', { n, taskId: made.id, title: sub.title, readOnly: sub.readOnly, fresh: sub.freshWorker }, `subtask ${n} to the worker: ${sub.title}`);
367
+ // To the worker's conversation, in the same window.
368
+ speakFor(transport, worker.id);
369
+ const fresh = !worker.chat;
370
+ await enterSessionConversation(transport, worker, { closeOnFailure: false });
371
+ const model = await applySessionModel(transport, worker, bus, cfg, store, deps.models, fresh, signal);
372
+ if (model.refused) {
373
+ speakFor(transport, session.id);
374
+ if (signal?.aborted)
375
+ return 'stopped';
376
+ throw new Error(`The worker's conversation could not be put on its model: ${model.refused}`);
377
+ }
378
+ const current = (await store.getSession(worker.id));
379
+ const subtask = current.tasks.find((x) => x.id === made.id);
380
+ const out = await runTask(transport, current, subtask, { ...deps, approvePlan: undefined });
381
+ speakFor(transport, session.id);
382
+ if (transport.closedOutside())
383
+ throw new WindowClosed();
384
+ if (signal?.aborted)
385
+ return 'stopped';
386
+ sink.event('subtask-ended', { n, status: out.status }, `subtask ${n} ${out.status}`);
387
+ // Back to the lead's conversation.
388
+ const leadNow = (await store.getSession(session.id));
389
+ await enterSessionConversation(transport, leadNow, { closeOnFailure: false });
390
+ const back = await applySessionModel(transport, leadNow, bus, cfg, store, deps.models, false, signal);
391
+ if (back.refused) {
392
+ if (signal?.aborted)
393
+ return 'stopped';
394
+ throw new Error(`The lead's conversation could not be put on its model again: ${back.refused}`);
395
+ }
396
+ return { report: await reportOf(worker.id, made.id, out, n, sub.title) };
397
+ };
398
+ try {
399
+ const facts = {
400
+ workDir: chatDir,
401
+ maxSubtasks: max,
402
+ maxIterations: cfg.limits.maxIterations,
403
+ maxRunMinutes: cfg.limits.maxRunMinutes,
404
+ planApproval: session.planMode === 'approve' && !!deps.approvePlan,
405
+ };
406
+ const n = session.tasks.findIndex((x) => x.id === task.id) + 1;
407
+ const contract = (await store.getLead1()).content.trim();
408
+ // Carried on in its own conversation: told why it stopped, and to go on from there (see `continuationMessage`).
409
+ const carryingOn = !!task.continuing && !!session.contractSent;
410
+ const assignment = carryingOn ? continuationMessage(task, n || 1, facts) : assignmentMessage(task, n || 1, facts, !!session.contractSent);
411
+ await setTask((t) => {
412
+ t.firstMessage = session.contractSent ? assignment : `${contract}\n\n---\n\n${assignment}`;
413
+ });
414
+ await record('OPENING MESSAGE', session.contractSent ? assignment : `${contract}\n\n---\n\n${assignment}`);
415
+ if (signal?.aborted)
416
+ return await finish('aborted', 'stopped before the assignment was sent');
417
+ let markdown;
418
+ if (!session.contractSent) {
419
+ await tell(contract);
420
+ session.contractSent = true;
421
+ await store.updateSession(session.id, (s) => {
422
+ s.contractSent = true;
423
+ });
424
+ }
425
+ markdown = await tell(assignment);
426
+ const maxFormat = Math.max(0, cfg.limits.maxFormatRetries ?? 2);
427
+ let formatRetries = 0;
428
+ // A message carried on was restated when it began: its first reply now need not do it again.
429
+ let understood = carryingOn;
430
+ let planVersion = 0;
431
+ let revisions = [];
432
+ const maxRounds = Math.max(1, cfg.limits.maxIterations);
433
+ for (;;) {
434
+ if (signal?.aborted)
435
+ return await finish('aborted', 'stopped by the operator');
436
+ if (lead.rounds.length >= maxRounds) {
437
+ limitHit = { setting: 'maxIterations', value: maxRounds };
438
+ return await finish('limit-reached', `maxIterations (${maxRounds}) reached: the lead's replies`);
439
+ }
440
+ const parsed = parseLeadReply(markdown);
441
+ if (!parsed.ok) {
442
+ formatRetries += 1;
443
+ if (formatRetries > maxFormat) {
444
+ limitHit = { setting: 'maxFormatRetries', value: maxFormat };
445
+ return await finish('limit-reached', `maxFormatRetries (${maxFormat}) reached: the lead's replies did not match its format (${parsed.detail})`);
446
+ }
447
+ sink.event('lead-format-retry', { reason: parsed.reason, detail: parsed.detail, retry: formatRetries }, `the lead's reply did not match its format, asked again (${formatRetries} of ${maxFormat})`, 'warn');
448
+ markdown = await tell(leadFormatErrorMessage(parsed, formatRetries, maxFormat));
449
+ continue;
450
+ }
451
+ const r = parsed.reply;
452
+ if (!understood && !r.understanding) {
453
+ formatRetries += 1;
454
+ if (formatRetries > maxFormat) {
455
+ limitHit = { setting: 'maxFormatRetries', value: maxFormat };
456
+ return await finish('limit-reached', `maxFormatRetries (${maxFormat}) reached: the lead did not restate the assignment`);
457
+ }
458
+ markdown = await tell(UNDERSTANDING_FIRST);
459
+ continue;
460
+ }
461
+ formatRetries = 0;
462
+ understood = true;
463
+ const round = {
464
+ n: lead.rounds.length + 1,
465
+ at: new Date().toISOString(),
466
+ status: r.status,
467
+ ...(r.understanding ? { understanding: r.understanding } : {}),
468
+ ...(r.notes ? { notes: r.notes } : {}),
469
+ };
470
+ lead.rounds.push(round);
471
+ await saveLead();
472
+ sink.event('lead-reply', { round: round.n, status: r.status }, `the lead: ${r.status}${r.subtask ? ` — ${r.subtask.title}` : ''}`);
473
+ switch (r.status) {
474
+ case 'delegate': {
475
+ if (lead.subtasks >= max) {
476
+ markdown = await tell(noSubtasksLeft(max));
477
+ break;
478
+ }
479
+ const ran = await runSubtask(r.subtask, round);
480
+ if (ran === 'stopped')
481
+ return await finish('aborted', 'stopped by the operator');
482
+ markdown = await tell(ran.report);
483
+ break;
484
+ }
485
+ case 'plan': {
486
+ planVersion += 1;
487
+ const plan = planFrom(r.plan, planVersion, revisions);
488
+ await setTask((t) => {
489
+ t.plan = plan;
490
+ });
491
+ await record(`THE LEAD'S PLAN (version ${planVersion})`, describePlan(plan));
492
+ let approved;
493
+ if (facts.planApproval && deps.approvePlan) {
494
+ const answer = await deps.approvePlan({ sessionId: session.id, taskId: task.id, title: task.title, plan });
495
+ if (answer.decision === 'stop' || signal?.aborted)
496
+ return await finish('aborted', 'the operator stopped the task at the lead\'s plan');
497
+ if (answer.decision === 'revise') {
498
+ revisions = [...(revisions ?? []), { version: planVersion, comment: answer.note ?? '', at: new Date().toISOString() }];
499
+ await setTask((t) => {
500
+ if (t.plan)
501
+ t.plan.revisions = revisions;
502
+ });
503
+ markdown = await tell(leadPlanRevise(answer.note ?? '', planVersion));
504
+ break;
505
+ }
506
+ approved = { by: 'operator', at: new Date().toISOString(), ...(answer.note?.trim() ? { note: answer.note.trim() } : {}) };
507
+ }
508
+ else {
509
+ approved = { by: 'auto', at: new Date().toISOString(), why: 'plans are not put to the operator in this conversation' };
510
+ }
511
+ await setTask((t) => {
512
+ if (t.plan)
513
+ t.plan.approved = approved;
514
+ });
515
+ markdown = await tell(leadPlanApproved(approved, max - lead.subtasks));
516
+ break;
517
+ }
518
+ case 'ask': {
519
+ round.question = { text: r.question, ...(r.why ? { why: r.why } : {}), ...(r.options.length > 0 ? { options: r.options } : {}) };
520
+ await saveLead();
521
+ if (!deps.askQuestion) {
522
+ markdown = await tell(NOBODY_TO_ASK);
523
+ break;
524
+ }
525
+ sink.event('lead-question', { round: round.n, question: r.question }, `the lead asks the operator: ${r.question}`, 'warn');
526
+ const got = await deps.askQuestion({ sessionId: session.id, taskId: task.id, question: r.question, ...(r.why ? { why: r.why } : {}), options: r.options });
527
+ if (got === 'stop' || signal?.aborted)
528
+ return await finish('aborted', 'the operator stopped the task at the lead\'s question');
529
+ round.question.answer = got.answer;
530
+ round.question.at = new Date().toISOString();
531
+ await saveLead();
532
+ sink.event('lead-question-answered', { round: round.n }, 'the operator answered the lead');
533
+ markdown = await tell(operatorAnswerMessage(got.answer, max - lead.subtasks));
534
+ break;
535
+ }
536
+ case 'done': {
537
+ lead.evidence = r.evidence;
538
+ return await finish('done', undefined, r.answer);
539
+ }
540
+ case 'blocked': {
541
+ return await finish('blocked', `the lead could not take it further: ${r.needed ?? ''}`.trim(), r.summary);
542
+ }
543
+ }
544
+ }
545
+ }
546
+ catch (e) {
547
+ const message = e.message;
548
+ if (e instanceof StoppedSend || signal?.aborted)
549
+ return await finish('aborted', 'stopped by the operator; nothing more was sent');
550
+ if (isReplyTimeout(e)) {
551
+ limitHit = { setting: 'replyTimeoutSec', value: e.seconds };
552
+ return await finish('limit-reached', `replyTimeoutSec (${e.seconds}) reached: ${message}`);
553
+ }
554
+ if (e instanceof WindowClosed || transport.closedOutside())
555
+ return await finish('aborted', 'the browser window was closed; nothing more was sent');
556
+ sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
557
+ return await finish('failed', message);
558
+ }
559
+ }