copilot-operator 0.1.84 → 0.1.85

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 (60) hide show
  1. package/dist/src/api/operator.controller.js +90 -0
  2. package/dist/src/api/operator.service.js +270 -30
  3. package/dist/src/config/schema.js +17 -0
  4. package/dist/src/orchestrator/cardText.js +91 -0
  5. package/dist/src/orchestrator/kerriganRunner.js +912 -0
  6. package/dist/src/orchestrator/leadRunner.js +22 -14
  7. package/dist/src/orchestrator/planMode.js +6 -4
  8. package/dist/src/orchestrator/taskRunner.js +42 -14
  9. package/dist/src/plan/kerrigan.js +109 -4
  10. package/dist/src/plan/systemGuide.js +194 -2
  11. package/dist/src/protocol/kerriganSchema.js +175 -0
  12. package/dist/src/session/store.js +9 -0
  13. package/dist/src/vcs/git.js +72 -2
  14. package/dist/src/vcs/operatorGit.js +409 -0
  15. package/dist/web/404.html +2 -2
  16. package/dist/web/_next/static/chunks/1077.06fe73b2c16f8f49.js +1 -0
  17. package/dist/web/_next/static/chunks/1548.b38c5d8d00ab2a72.js +1 -0
  18. package/dist/web/_next/static/chunks/{2163.2af0979126ae613a.js → 2163.ba933c9a506302ca.js} +1 -1
  19. package/dist/web/_next/static/chunks/714.575273a189d030fe.js +1 -0
  20. package/dist/web/_next/static/chunks/7220.988dfd28e00f407c.js +1 -0
  21. package/dist/web/_next/static/chunks/7921-65dd56d87144bd44.js +1 -0
  22. package/dist/web/_next/static/chunks/8124-1dba8babfcfbc6e2.js +1 -0
  23. package/dist/web/_next/static/chunks/8584.2221587201bc2fa2.js +1 -0
  24. package/dist/web/_next/static/chunks/9067.8d94a08830c3d1da.js +1 -0
  25. package/dist/web/_next/static/chunks/9747.8671194406acd839.js +1 -0
  26. package/dist/web/_next/static/chunks/app/layout-127e5af1ebf21876.js +1 -0
  27. package/dist/web/_next/static/chunks/app/page-76139370c7ca3715.js +1 -0
  28. package/dist/web/_next/static/chunks/app/settings/page-116da78c83f0c5c9.js +1 -0
  29. package/dist/web/_next/static/chunks/webpack-13ccb80d7b7094ca.js +1 -0
  30. package/dist/web/_next/static/css/6e2b8656501f0dd7.css +1 -0
  31. package/dist/web/defaults.html +2 -2
  32. package/dist/web/defaults.txt +8 -8
  33. package/dist/web/index.html +3 -3
  34. package/dist/web/index.txt +9 -9
  35. package/dist/web/queue.html +2 -2
  36. package/dist/web/queue.txt +9 -9
  37. package/dist/web/settings.html +2 -2
  38. package/dist/web/settings.txt +9 -9
  39. package/dist/web/system.html +2 -2
  40. package/dist/web/system.txt +9 -9
  41. package/package.json +175 -173
  42. package/prompts/kerrigan1.md +169 -0
  43. package/prompts/lead1.md +4 -1
  44. package/prompts/level1.md +8 -1
  45. package/dist/web/_next/static/chunks/1077.e0136d293069ccb8.js +0 -1
  46. package/dist/web/_next/static/chunks/1548.5cc0c57b00c2e44f.js +0 -1
  47. package/dist/web/_next/static/chunks/714.410e2b61aa8c72b7.js +0 -1
  48. package/dist/web/_next/static/chunks/7220.2c4e5173a060769f.js +0 -1
  49. package/dist/web/_next/static/chunks/7921-3d21f385338afdf9.js +0 -1
  50. package/dist/web/_next/static/chunks/8124-1dc34be1646970a8.js +0 -1
  51. package/dist/web/_next/static/chunks/8584.61650a59d2bfa54d.js +0 -1
  52. package/dist/web/_next/static/chunks/9067.553056fc9b6cf80e.js +0 -1
  53. package/dist/web/_next/static/chunks/9747.d5826524bf4b714d.js +0 -1
  54. package/dist/web/_next/static/chunks/app/layout-b8a1e0075a48b025.js +0 -1
  55. package/dist/web/_next/static/chunks/app/page-13147b69cf336831.js +0 -1
  56. package/dist/web/_next/static/chunks/app/settings/page-e3909ef6c2d8e321.js +0 -1
  57. package/dist/web/_next/static/chunks/webpack-19a2d7161f23b21d.js +0 -1
  58. package/dist/web/_next/static/css/f152f27d6afce55c.css +0 -1
  59. /package/dist/web/_next/static/{WU_J4Ke1d3xVfpW2acqqf → aCQe1FDhYTj4zGeI5ueVq}/_buildManifest.js +0 -0
  60. /package/dist/web/_next/static/{WU_J4Ke1d3xVfpW2acqqf → aCQe1FDhYTj4zGeI5ueVq}/_ssgManifest.js +0 -0
@@ -0,0 +1,912 @@
1
+ /**
2
+ * Kerrigan directs (operator, 2026-11-12): "I copy Kerrigan into a chat — the project's description, the skills, all of
3
+ * it set in Settings. She says she is Kerrigan, give her the tasks. I give her the task and we start: she gives me a
4
+ * prompt for the bot and says whether plan mode, two chats, the reviewer, which skill. I do that by hand and start the
5
+ * bot. When the bot asks me something, I take its question with its answers to her, and she tells me what to press and
6
+ * what to add; the bot goes on. At the end she reads the result; if there is a problem she goes on with a new prompt,
7
+ * for a new chat or the same one — she decides. I give the task; from there she very rarely needs me." And, the same
8
+ * day: "not that it never asks — fewer questions: have it look in the internal sources first, mail, chats,
9
+ * transcripts, shared files, the code, the Azure CLI."
10
+ *
11
+ * So a message of such a conversation is run here. The conversation is hers: she is given her contract
12
+ * (`prompts/kerrigan1.md`) and the facts of this machine (`kerriganBrief`), then the person's task, and every reply of
13
+ * hers is one decision in the shape `protocol/kerriganSchema.ts` holds it to. A message she writes for a chat becomes a
14
+ * task of a chat of its own (`Session.directedBy`), a conversation in the same Copilot window, run as any chat message
15
+ * is — by `runTask`, or by `runLeadTask` when she asked for two chats — with its plan mode, review and skill as she
16
+ * chose. The chats are conversations of the list: the person can open one and follow it as it works.
17
+ *
18
+ * The chat's cards that are hers (the person's choice, 2026-11-12: "questions, plans, retries; the commands as Settings
19
+ * say") go to her while it waits: the window goes to her conversation, she answers — or leaves the card to the person,
20
+ * with why and what she would choose — and goes back to the chat's before the card is answered, so the chat goes on
21
+ * where it was. The person may answer a card first; theirs is taken, hers is not. Commands, platform access, scripts
22
+ * handed over, passwords, sign-ins and models chosen by hand never come to her. When the chat's work on her message has
23
+ * ended, its result goes to her: how it ended, the summary, the commands and their exit codes, the files, the review.
24
+ * She goes on, or delivers her report, which is the message's summary.
25
+ */
26
+ import { appendFile, mkdir, writeFile } from 'node:fs/promises';
27
+ import { ChatLost, isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
28
+ import { buildChatName, chatCode, savePointer } from '../transport/chatSession.js';
29
+ import { RunLog } from '../log/runLog.js';
30
+ import { gapFrom, Pacer } from '../util/pacing.js';
31
+ import { takeAfter, takeCheckpoint } from '../session/checkpoint.js';
32
+ import { commitFiles } from '../vcs/git.js';
33
+ import { buildTaskExchange } from '../session/taskExchange.js';
34
+ import { redactSecrets } from '../exec/redaction.js';
35
+ import { operatorNotesSection } from '../session/compose.js';
36
+ import { KERRIGAN_UNDERSTANDING_FIRST, kerriganFormatErrorMessage, parseKerriganReply } from '../protocol/kerriganSchema.js';
37
+ import { cardCopyText, endingCopyText } from './cardText.js';
38
+ import { chosenSaid } from './chosenAnswers.js';
39
+ import { runLeadTask } from './leadRunner.js';
40
+ import { applySessionModel, enterSessionConversation, holdsWhilePaused, limitsMessageLength, redactsMessages, runTask, Sink, speakFor, spokenFor, staysOnItsChat, StoppedSend, } from './taskRunner.js';
41
+ import { DEFAULT_VCS } from '../session/store.js';
42
+ const RETRY_WORDS = {
43
+ same: 'try it again in the same worker\'s conversation',
44
+ fresh: 'try it again in a new worker conversation',
45
+ continue: 'carry on from the folder as it is',
46
+ restore: 'put the folder back to how it was when the subtask began, and try again',
47
+ accept: 'go back to the lead with what was done',
48
+ };
49
+ /** How a chat's work on a message ended, in a few words. */
50
+ function endedAs(status) {
51
+ switch (status) {
52
+ case 'done':
53
+ return 'done — the chat says it is finished';
54
+ case 'blocked':
55
+ return 'blocked — the chat could not take it further';
56
+ case 'failed':
57
+ return 'failed — the run itself failed';
58
+ case 'aborted':
59
+ return 'stopped';
60
+ case 'limit-reached':
61
+ return 'limit-reached — a limit of Settings stopped it; it can be carried on in the same chat';
62
+ default:
63
+ return String(status);
64
+ }
65
+ }
66
+ /**
67
+ * The window, while she has it for a card: the chat whose card it is waits for it before it goes on, should the person
68
+ * answer the card while she still writes.
69
+ */
70
+ class WindowLease {
71
+ held = null;
72
+ take() {
73
+ let release;
74
+ const done = new Promise((resolve) => {
75
+ release = resolve;
76
+ });
77
+ this.held = { done, release };
78
+ }
79
+ release() {
80
+ const held = this.held;
81
+ this.held = null;
82
+ held?.release();
83
+ }
84
+ /** Resolves once nobody holds the window; at once on Stop. */
85
+ async free(signal) {
86
+ while (this.held && !signal?.aborted) {
87
+ const held = this.held;
88
+ await new Promise((resolve) => {
89
+ void held.done.then(resolve);
90
+ signal?.addEventListener('abort', () => resolve(), { once: true });
91
+ });
92
+ }
93
+ }
94
+ }
95
+ /** Her reply was not one that could be acted on, past the retries Settings allow. */
96
+ class FormatLimit extends Error {
97
+ }
98
+ /** The most of a chat message's exchange she is sent, as characters of its JSON; the rest is cut, and said so. */
99
+ export const MAX_EXCHANGE_CHARS = 2_000_000;
100
+ /** A text fenced with more backticks than any run in it, so it is shown as it is. */
101
+ function fenced(text) {
102
+ const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((x) => x.length));
103
+ const f = '`'.repeat(Math.max(3, longest + 1));
104
+ return `${f}text\n${text.trim()}\n${f}`;
105
+ }
106
+ /** The opening: the person's task, with what the runner tells her about it. */
107
+ export function kerriganTaskMessage(task, n, facts, again) {
108
+ return [
109
+ again
110
+ ? 'A new task from the person, in this same conversation. Your contract and the facts you were given at the start still apply unchanged: the same format, the same rules. Restate this task in "understanding" in your first reply to it.'
111
+ : '',
112
+ task.continuing
113
+ ? `The person asks you to carry on with this task (message ${n} of this conversation), which stopped before it was done${task.continuing.stoppedBecause ? `: ${task.continuing.stoppedBecause}` : ''}. What was done is above, in this conversation; the folder is as it was left.`
114
+ : `The person's task (message ${n} of this conversation):`,
115
+ '',
116
+ task.prompt.trim(),
117
+ '',
118
+ /*
119
+ * The skill the task is for (2026-11-12: "the information Kerrigan needs for the task is loaded: we already know it is
120
+ * for such a skill"): its instructions whole, as the bot sends them with each message of its kind.
121
+ */
122
+ ...(task.skill
123
+ ? [
124
+ `The task is for the skill \`${task.skill.name}\`${task.skill.description ? ` (${task.skill.description})` : ''}: send every message of its kind with \`"skill": "${task.skill.name}"\`, and write in it only what is particular to the message — the skill's instructions go with it. Its instructions, as the bot sends them, so you know its phases, the result it leads to and what it needs:`,
125
+ '',
126
+ fenced(task.skill.text),
127
+ '',
128
+ ]
129
+ : []),
130
+ `You may send at most ${facts.maxSends} message(s) to chats for it.`,
131
+ facts.chat
132
+ ? `A chat of yours is there to carry on: "${facts.chat.name}"${facts.chat.title ? `, which worked last on "${facts.chat.title}"` : ''} — "same" sends to it.`
133
+ : 'No chat of yours is there yet: your first message goes to a "new" one.',
134
+ '',
135
+ 'Find out what you can first (your contract, "Where to look"), then reply in your format.',
136
+ ]
137
+ .filter((line, i) => i > 0 || line)
138
+ .join('\n');
139
+ }
140
+ export async function runKerriganTask(transport, session, task, deps) {
141
+ const { cfg, store, bus, signal } = deps;
142
+ const attempt = task.attempt ?? 1;
143
+ const runId = task.runId ?? `${session.id}-${task.id}${attempt > 1 ? `-a${attempt}` : ''}`;
144
+ const log = new RunLog(runId, cfg.resolved.runsDir);
145
+ const sink = new Sink(log, bus, session.id, task.id);
146
+ const taskLogPath = log.path('task-log.txt');
147
+ await mkdir(log.path('replies'), { recursive: true });
148
+ await mkdir(log.path('messages'), { recursive: true });
149
+ const record = async (heading, body) => {
150
+ await appendFile(taskLogPath, `\n${'='.repeat(78)}\n${heading}\n${'='.repeat(78)}\n${body.trimEnd()}\n`, 'utf8').catch(() => undefined);
151
+ };
152
+ const setTask = async (mutate) => {
153
+ await store.updateTask(session.id, task.id, mutate);
154
+ };
155
+ const actingNow = async (actor, more = {}) => {
156
+ const acting = { actor, since: new Date().toISOString(), ...more };
157
+ await setTask((t) => {
158
+ t.acting = acting;
159
+ });
160
+ sink.event('acting', acting, `at work now: ${actor === 'kerrigan' ? 'Kerrigan' : actor}`);
161
+ };
162
+ const maxSends = () => Math.max(1, cfg.limits.maxKerriganSends ?? 6);
163
+ const k = { rounds: [], sent: 0, maxSends: maxSends(), messages: 0, chats: [] };
164
+ const save = async () => {
165
+ const copy = JSON.parse(JSON.stringify(k));
166
+ await setTask((t) => {
167
+ t.kerrigan = copy;
168
+ t.iterations = copy.rounds.length;
169
+ });
170
+ };
171
+ const startedAt = Date.now();
172
+ await setTask((t) => {
173
+ t.status = 'running';
174
+ t.runId = runId;
175
+ t.runGroup = deps.runGroup;
176
+ t.startedAt = new Date().toISOString();
177
+ t.kerrigan = { rounds: [], sent: 0, maxSends: maxSends(), messages: 0, chats: [] };
178
+ });
179
+ await writeFile(taskLogPath, `TASK: ${task.title}\nSESSION: ${session.name} (${session.id})\nRUN: ${runId}\nSTARTED: ${new Date().toISOString()}\nMODE: Kerrigan directs\n`, 'utf8');
180
+ sink.event('task-started', { runId, title: task.title, kerrigan: true }, `task "${task.title}" starting, directed by Kerrigan (run ${runId})`);
181
+ await actingNow('kerrigan');
182
+ // The folder before the message, for "go back" and for what the whole of it changed.
183
+ const chatDir = session.projectDir?.trim() ?? '';
184
+ let checkpoint = task.checkpoint;
185
+ if (!checkpoint && chatDir) {
186
+ const cp = await takeCheckpoint(chatDir, task.id).catch((e) => ({ problem: e.message }));
187
+ if ('problem' in cp)
188
+ sink.event('chat-checkpoint-missing', { problem: cp.problem }, `no way back to before this message: ${cp.problem}`, 'warn');
189
+ else {
190
+ checkpoint = cp;
191
+ await setTask((t) => {
192
+ t.checkpoint = cp;
193
+ });
194
+ 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)})`);
195
+ }
196
+ }
197
+ const pacer = new Pacer({
198
+ enabled: cfg.pacing.enabled,
199
+ settleMs: cfg.pacing.settleMs,
200
+ maxMessagesPerHour: cfg.pacing.maxMessagesPerHour,
201
+ gapMs: gapFrom(cfg.pacing),
202
+ signal,
203
+ onGap: (ms) => sink.event('pacing-gap', { ms, kerrigan: true }, `the next message to Kerrigan waits ${Math.ceil(ms / 1000)} s: Settings ask for a pause between messages`),
204
+ });
205
+ const unlive = deps.live?.onChange(() => pacer.retune({ enabled: cfg.pacing.enabled, settleMs: cfg.pacing.settleMs, maxMessagesPerHour: cfg.pacing.maxMessagesPerHour, gapMs: gapFrom(cfg.pacing) })) ?? (() => undefined);
206
+ let limitHit;
207
+ const holdHere = async () => {
208
+ const hold = deps.hold;
209
+ if (!hold?.held || signal?.aborted)
210
+ return false;
211
+ const from = Date.now();
212
+ sink.event('task-paused', { before: 'message', kerrigan: true }, 'paused by the operator: nothing more is sent to Kerrigan until Continue');
213
+ await hold.until(signal);
214
+ const stopped = !!signal?.aborted;
215
+ sink.event('task-resumed', { heldMs: Date.now() - from, stopped }, stopped ? 'stopped while paused' : 'continued by the operator');
216
+ return stopped;
217
+ };
218
+ // Each message into her own conversation, the window put back on it when it has left it (2026-11-09).
219
+ const herChat = redactsMessages(limitsMessageLength(holdsWhilePaused(staysOnItsChat(transport, signal), holdHere), {
220
+ get max() {
221
+ return cfg.limits.maxMessageChars;
222
+ },
223
+ dir: log.path('messages'),
224
+ onLong: ({ chars, max, file }) => sink.event('message-long', { chars, max, file, kerrigan: true }, `a message to Kerrigan of ${chars} characters is over the ${max} sent as text: its beginning is sent, the whole of it attached as ${file}`, 'warn'),
225
+ }), {
226
+ patterns: cfg.report.redactPatterns,
227
+ onRedacted: (hits) => sink.event('message-redacted', { redactions: hits, kerrigan: true }, `secrets taken out of a message to Kerrigan before it was sent: ${hits.map((h) => `${h.name} ×${h.count}`).join(', ')}`, 'warn'),
228
+ });
229
+ let replies = 0;
230
+ /**
231
+ * One message to her, and her reply. `files`: attached — the whole exchange of a chat's message with its result
232
+ * (2026-11-12: "I copy the whole JSON, or the one message, and send it to Kerrigan"); one that cannot be attached, the
233
+ * message goes without it, saying so.
234
+ */
235
+ const tell = async (text, files = []) => {
236
+ await pacer.throttleSend();
237
+ // The person's notes written while the work goes on ("Add to it") go to her with her next message.
238
+ const notes = await store.takeUnsentNotes(session.id, task.id).catch(() => []);
239
+ const message = notes.length > 0 ? `${text}\n\n${operatorNotesSection(notes, true)}` : text;
240
+ if (notes.length > 0)
241
+ sink.event('operator-note-sent', { notes: notes.length, with: 'kerrigan' }, `${notes.length} note(s) from the operator go to Kerrigan`);
242
+ let before;
243
+ try {
244
+ before = await herChat.sendAndConfirm(message, files);
245
+ }
246
+ catch (e) {
247
+ if (files.length === 0 || e instanceof StoppedSend || e instanceof ChatLost || e instanceof WindowClosed || signal?.aborted)
248
+ throw e;
249
+ sink.event('kerrigan-attach-failed', { files, error: e.message }, `the exchange could not be attached to the message to Kerrigan; it goes without it: ${e.message}`, 'warn');
250
+ before = await herChat.sendAndConfirm(`${message}\n\n(The whole exchange of the message could not be attached: ${e.message}. Judge from the above.)`);
251
+ }
252
+ k.messages += 1;
253
+ await save();
254
+ await writeFile(log.path('messages', `${String(k.messages).padStart(2, '0')}.md`), message, 'utf8').catch(() => undefined);
255
+ sink.event('message-sent', { n: k.messages, chars: message.length, kerrigan: true, chatId: session.chat?.chatId ?? null }, `message ${k.messages} sent to Kerrigan (${message.length} chars)`);
256
+ await record(`TO KERRIGAN (${k.messages})`, message);
257
+ const reply = await herChat.waitForReply(before);
258
+ replies += 1;
259
+ await writeFile(log.path('replies', `${String(replies).padStart(2, '0')}-kerrigan.md`), reply.markdown, 'utf8').catch(() => undefined);
260
+ await record(`FROM KERRIGAN (${replies})`, reply.markdown);
261
+ await pacer.settle();
262
+ await registerHerChat();
263
+ return reply.markdown;
264
+ };
265
+ /** Her conversation, put on record and named once it exists. */
266
+ const registerHerChat = async () => {
267
+ if (session.chat)
268
+ return;
269
+ const chatId = await transport.currentChatId().catch(() => null);
270
+ if (!chatId)
271
+ return;
272
+ const asked = buildChatName(chatCode(session.id), session.name);
273
+ const saved = await transport.nameChat(chatId, asked).catch(() => false);
274
+ const chat = {
275
+ chatId,
276
+ url: `${cfg.copilot.url.replace(/\/chat.*$/, '')}/chat/conversation/${chatId}?es=SSR`,
277
+ name: saved || asked,
278
+ ...(saved !== false ? {} : { named: false }),
279
+ runId,
280
+ createdAt: new Date().toISOString(),
281
+ };
282
+ session.chat = chat;
283
+ await store.updateSession(session.id, (s) => {
284
+ s.chat = chat;
285
+ });
286
+ await savePointer(log.path('chat.json'), chat).catch(() => undefined);
287
+ };
288
+ const maxFormat = () => Math.max(0, cfg.limits.maxFormatRetries ?? 2);
289
+ /**
290
+ * Her reply to `text`, in her format and one that can be acted on here (`fits`): asked again with the reason when it is
291
+ * not, up to Settings' retries.
292
+ */
293
+ const askHer = async (text, fits, files = []) => {
294
+ let markdown = await tell(text, files);
295
+ let retries = 0;
296
+ for (;;) {
297
+ const parsed = parseKerriganReply(markdown);
298
+ const problem = parsed.ok ? await fits(parsed.reply) : null;
299
+ if (parsed.ok && !problem)
300
+ return parsed.reply;
301
+ retries += 1;
302
+ const detail = parsed.ok ? problem : parsed.detail;
303
+ if (retries > maxFormat())
304
+ throw new FormatLimit(detail);
305
+ sink.event('kerrigan-format-retry', { detail, retry: retries }, `Kerrigan's reply could not be acted on, asked again (${retries} of ${maxFormat()}): ${detail}`, 'warn');
306
+ markdown = await tell(parsed.ok ? `${problem}\n\nNothing from your last reply was acted on. Send it again, in your format (retry ${retries} of ${maxFormat()}).` : kerriganFormatErrorMessage(parsed, retries, maxFormat()));
307
+ }
308
+ };
309
+ /** Back in her conversation, on her model, the window speaking for her. */
310
+ const toHer = async () => {
311
+ speakFor(transport, session.id);
312
+ const now = ((await store.getSession(session.id)) ?? session);
313
+ await enterSessionConversation(transport, now, { closeOnFailure: false });
314
+ const back = await applySessionModel(transport, now, bus, cfg, store, deps.models, false, signal);
315
+ if (back.refused && !signal?.aborted)
316
+ throw new Error(`Kerrigan's conversation could not be put on its model again: ${back.refused}`);
317
+ };
318
+ /** The chat she sent to last: in this message, or in an earlier one of this conversation. */
319
+ let lastChat = null;
320
+ let lastTitle = '';
321
+ {
322
+ const earlier = [...session.tasks].reverse().find((x) => x.id !== task.id && (x.kerrigan?.chats.length ?? 0) > 0);
323
+ const id = earlier?.kerrigan?.chats.at(-1);
324
+ const found = id ? await store.getSession(id) : null;
325
+ if (found) {
326
+ lastChat = found;
327
+ lastTitle = [...(earlier.kerrigan.rounds)].reverse().find((r) => r.send?.sessionId === id)?.send?.title ?? '';
328
+ }
329
+ }
330
+ const lease = new WindowLease();
331
+ /** Who is at work in the chat of hers at work now, for the line under her message. */
332
+ let actorNow = 'worker';
333
+ /** Her rounds of cards, one at a time. */
334
+ let cards = Promise.resolve();
335
+ const chatName = async (sessionId) => {
336
+ const s = await store.getSession(sessionId);
337
+ const top = s?.workerOf ? await store.getSession(s.workerOf) : s;
338
+ return (top?.name ?? sessionId).replace(/^chat: /, '');
339
+ };
340
+ /**
341
+ * The card, as she is told it: what its "Copy all" gives (operator, 2026-11-12: "where she is needed, 'Copy all', or
342
+ * 'Copy' where there is none"), and how to answer it in her format.
343
+ */
344
+ const cardMessage = async (c) => {
345
+ const name = await chatName(c.ask.sessionId);
346
+ const copy = c.kind === 'question'
347
+ ? cardCopyText({ actor: c.ask.actor ?? 'worker', question: { text: c.ask.question, ...(c.ask.why ? { why: c.ask.why } : {}), options: c.ask.options, ...(c.ask.commands ? { commands: c.ask.commands } : {}), ...(c.ask.multiple ? { multiple: true } : {}) } })
348
+ : c.kind === 'plan'
349
+ ? cardCopyText({ actor: c.ask.actor ?? 'plan', plan: { title: c.ask.title, plan: c.ask.plan } })
350
+ : cardCopyText({ actor: 'lead', retry: c.ask.retry });
351
+ const how = c.kind === 'question'
352
+ ? `Answer it with status "answer" — "option", the number of one of the answers offered${c.ask.multiple ? ', "options", the numbers of the ones you choose,' : ''} or "text" in your own words — and "why". An answer that runs a command does not run it by your word: it is asked about as the person's Settings say.`
353
+ : c.kind === 'plan'
354
+ ? 'Approve it with status "answer" and "decision": "approve" (a "note" beside it if you like), or send it back with "decision": "revise" and a "note" that says what to change.'
355
+ : 'Answer it with status "answer" and "option", the number of one of the answers offered, and "why".';
356
+ return [
357
+ `A card of the chat "${name}" waits for an answer. What its "Copy all" gives:`,
358
+ '',
359
+ '---',
360
+ copy ?? '',
361
+ '---',
362
+ '',
363
+ how,
364
+ 'Or leave it to the person with status "ask", "why" and "suggestion".',
365
+ ].join('\n');
366
+ };
367
+ /** Whether her reply answers this card, and the answer it gives; or why not. */
368
+ const answerOf = (c, r) => {
369
+ const why = (r.why ?? r.notes ?? '').trim();
370
+ if (c.kind === 'question') {
371
+ const opts = c.ask.options;
372
+ const many = (r.options ?? []).map((x) => (typeof x === 'number' ? x : Number(/\d+/.exec(String(x))?.[0] ?? NaN)));
373
+ if (r.option !== undefined) {
374
+ if (r.option < 1 || r.option > opts.length)
375
+ return { problem: `"option" is the number of one of the card's answers, 1 to ${opts.length}.` };
376
+ const text = opts[r.option - 1];
377
+ return { said: text, give: () => c.card.answer({ text }, why) };
378
+ }
379
+ if (many.length > 0) {
380
+ if (!c.ask.multiple)
381
+ return { problem: 'This question takes one answer: give "option", or "text".' };
382
+ if (many.some((x) => !Number.isInteger(x) || x < 1 || x > opts.length))
383
+ return { problem: `"options" are numbers of the card's answers, 1 to ${opts.length}.` };
384
+ const chosen = [...new Set(many)].map((x) => x - 1);
385
+ const text = (r.text ?? '').trim();
386
+ return { said: chosenSaid({ chosen: chosen.map((x) => opts[x]), ...(text ? { written: text } : {}) }), give: () => c.card.answer({ text, chosen }, why) };
387
+ }
388
+ const text = (r.text ?? '').trim();
389
+ if (!text)
390
+ return { problem: opts.length > 0 ? 'Answer the question with "option" (the number of one of its answers), "options" when more than one may be chosen, or "text" in your own words.' : 'Answer the question in "text".' };
391
+ return { said: text, give: () => c.card.answer({ text }, why) };
392
+ }
393
+ if (c.kind === 'plan') {
394
+ if (!r.decision)
395
+ return { problem: 'Answer the plan with "decision": "approve", or "revise" with a "note".' };
396
+ const note = (r.note ?? '').trim();
397
+ if (r.decision === 'revise' && !note)
398
+ return { problem: '"decision": "revise" needs a "note" that says what to change in the plan.' };
399
+ return { said: r.decision === 'approve' ? `approved${note ? ` — ${note}` : ''}` : `another plan asked for: ${note}`, give: () => c.card.answer({ decision: r.decision, ...(note ? { note } : {}) }, why) };
400
+ }
401
+ const choices = c.ask.retry.choices;
402
+ // By its number among the answers offered, as "Copy all" numbers them, or by its word.
403
+ const byNumber = r.option !== undefined ? choices[r.option - 1] : undefined;
404
+ if (r.option !== undefined && !byNumber)
405
+ return { problem: `"option" is the number of one of the answers offered, 1 to ${choices.length}.` };
406
+ if (!byNumber && (!r.choice || !choices.includes(r.choice)))
407
+ return { problem: `Answer with "option", the number of one of the answers offered, 1 to ${choices.length}.` };
408
+ const choice = (byNumber ?? r.choice);
409
+ return { said: `${choice} — ${RETRY_WORDS[choice]}`, give: () => c.card.answer(choice, why) };
410
+ };
411
+ /** A card the chat put up, answered by her in the person's place, or left to them; the chat's conversation given back. */
412
+ const answerCard = async (c) => {
413
+ if (signal?.aborted || !c.card.open())
414
+ return;
415
+ c.card.mark({ state: 'thinking', at: new Date().toISOString() });
416
+ lease.take();
417
+ const speaker = spokenFor(transport);
418
+ const round = {
419
+ status: 'answer',
420
+ at: new Date().toISOString(),
421
+ card: {
422
+ id: c.card.id,
423
+ kind: c.kind,
424
+ sessionId: c.ask.sessionId,
425
+ taskId: c.ask.taskId,
426
+ ...(c.kind !== 'retry' && c.ask.actor ? { actor: c.ask.actor } : {}),
427
+ text: c.kind === 'question' ? c.ask.question : c.kind === 'plan' ? `The plan of "${c.ask.title}" (version ${c.ask.plan.version})` : `Subtask ${c.ask.retry.n} ("${c.ask.retry.title}") did not finish: ${c.ask.retry.reason || c.ask.retry.category}`,
428
+ ...(c.kind === 'question' && c.ask.options.length > 0 ? { options: c.ask.options } : {}),
429
+ },
430
+ };
431
+ k.rounds.push(round);
432
+ await save();
433
+ sink.event('kerrigan-card', { card: c.card.id, kind: c.kind }, `a card of the chat goes to Kerrigan: ${round.card.text}`);
434
+ let give = null;
435
+ try {
436
+ await actingNow('kerrigan');
437
+ await toHer();
438
+ const message = await cardMessage(c);
439
+ const r = await askHer(message, (x) => {
440
+ if (x.status !== 'answer' && x.status !== 'ask')
441
+ return 'A card is waiting: answer it with status "answer", or leave it to the person with status "ask", "why" and "suggestion".';
442
+ if (x.status === 'ask')
443
+ return (x.why ?? '').trim() ? null : 'Leaving a card to the person needs "why": what makes it theirs alone, and what you looked at.';
444
+ const a = answerOf(c, x);
445
+ return 'problem' in a ? a.problem : null;
446
+ });
447
+ round.status = r.status;
448
+ if (r.notes)
449
+ round.notes = r.notes;
450
+ if (r.sources.length > 0)
451
+ round.sources = r.sources;
452
+ if (r.status === 'answer') {
453
+ const a = answerOf(c, r);
454
+ round.card.answer = a.said;
455
+ give = a.give;
456
+ }
457
+ else {
458
+ round.card.yours = { why: r.why, ...(r.suggestion ? { suggestion: r.suggestion } : {}) };
459
+ c.card.mark({ state: 'yours', at: new Date().toISOString(), why: r.why, ...(r.suggestion ? { suggestion: r.suggestion } : {}) });
460
+ sink.event('kerrigan-left-card', { card: c.card.id }, `Kerrigan leaves the card to the operator: ${r.why}`, 'warn');
461
+ }
462
+ }
463
+ catch (e) {
464
+ const why = e instanceof FormatLimit ? `her replies could not be acted on (${e.message})` : e.message;
465
+ round.status = 'ask';
466
+ round.card.yours = { why: `Kerrigan could not answer it: ${why}` };
467
+ if (!signal?.aborted)
468
+ c.card.mark({ state: 'yours', at: new Date().toISOString(), why: round.card.yours.why });
469
+ sink.event('kerrigan-card-failed', { card: c.card.id, error: why }, `Kerrigan could not answer the card; it is left to the operator: ${why}`, 'warn');
470
+ }
471
+ // The chat's conversation given back before the chat goes on, whoever answers the card.
472
+ try {
473
+ if (!signal?.aborted) {
474
+ const theirs = (await store.getSession(c.ask.sessionId));
475
+ if (theirs) {
476
+ speakFor(transport, speaker ?? theirs.id);
477
+ await enterSessionConversation(transport, theirs, { closeOnFailure: false });
478
+ await applySessionModel(transport, theirs, bus, cfg, store, deps.models, false, signal);
479
+ }
480
+ }
481
+ }
482
+ catch (e) {
483
+ sink.event('kerrigan-return-failed', { card: c.card.id, error: e.message }, `the window could not be put back on the chat's conversation: ${e.message}`, 'warn');
484
+ }
485
+ if (give) {
486
+ const done = give();
487
+ round.card.by = done.ok ? 'kerrigan' : 'operator';
488
+ if (!done.ok) {
489
+ delete round.card.answer;
490
+ sink.event('kerrigan-too-late', { card: c.card.id }, 'the operator answered the card before Kerrigan did: theirs is taken');
491
+ }
492
+ else
493
+ sink.event('kerrigan-answered', { card: c.card.id, answer: round.card.answer }, `Kerrigan answered the card: ${round.card.answer}`);
494
+ }
495
+ else if (!c.card.open())
496
+ round.card.by = 'operator';
497
+ await save();
498
+ lease.release();
499
+ await actingNow(actorNow).catch(() => undefined);
500
+ };
501
+ const cardToHer = (c) => {
502
+ cards = cards.then(() => answerCard(c)).catch((e) => {
503
+ lease.release();
504
+ sink.event('kerrigan-card-failed', { error: e.message }, `a card could not be put to Kerrigan: ${e.message}`, 'warn');
505
+ });
506
+ };
507
+ /**
508
+ * A card that went to her and was answered by the person — before her, or after she left it to them: on her record as
509
+ * theirs, with their answer.
510
+ */
511
+ const answeredByPerson = async (id, answer) => {
512
+ const round = [...k.rounds].reverse().find((r) => r.card?.id === id);
513
+ if (!round?.card || round.card.by === 'kerrigan')
514
+ return;
515
+ round.card.by = 'operator';
516
+ if (answer !== null)
517
+ round.card.answer = answer;
518
+ else
519
+ delete round.card.answer;
520
+ await save();
521
+ };
522
+ /** The deps a chat of hers runs with: its cards that are hers go to her; its worker is its own. */
523
+ const chatDeps = (chatId) => ({
524
+ ...deps,
525
+ directed: true,
526
+ kerrigan: undefined,
527
+ onWorker: (workerId, parent) => deps.onWorker?.(workerId, parent ?? chatId),
528
+ ...(deps.askQuestion
529
+ ? {
530
+ askQuestion: async (ask) => {
531
+ // Commands handed over to run are the person's, never hers.
532
+ if (ask.handoff)
533
+ return await deps.askQuestion(ask);
534
+ let id = '';
535
+ const got = await deps.askQuestion({
536
+ ...ask,
537
+ onCard: (card) => {
538
+ id = card.id;
539
+ cardToHer({ kind: 'question', ask, card });
540
+ },
541
+ });
542
+ await lease.free(signal);
543
+ if (id && got !== 'stop' && got.by !== 'kerrigan')
544
+ await answeredByPerson(id, got.answer);
545
+ return got;
546
+ },
547
+ }
548
+ : {}),
549
+ ...(deps.approvePlan
550
+ ? {
551
+ approvePlan: async (ask) => {
552
+ let id = '';
553
+ const got = await deps.approvePlan({
554
+ ...ask,
555
+ onCard: (card) => {
556
+ id = card.id;
557
+ cardToHer({ kind: 'plan', ask, card });
558
+ },
559
+ });
560
+ await lease.free(signal);
561
+ if (id && got.decision !== 'stop' && got.by !== 'kerrigan')
562
+ await answeredByPerson(id, got.decision === 'approve' ? `approved${got.note ? ` — ${got.note}` : ''}` : `another plan asked for: ${got.note ?? ''}`);
563
+ return got;
564
+ },
565
+ }
566
+ : {}),
567
+ ...(deps.askSubtaskRetry
568
+ ? {
569
+ askSubtaskRetry: async (ask) => {
570
+ let id = '';
571
+ let hers = false;
572
+ const got = await deps.askSubtaskRetry({
573
+ ...ask,
574
+ onCard: (card) => {
575
+ id = card.id;
576
+ // Her answer is told apart by the card itself: a retry's choice says nothing of who chose it.
577
+ const answer = card.answer.bind(card);
578
+ card.answer = (a, why) => {
579
+ const done = answer(a, why);
580
+ if (done.ok)
581
+ hers = true;
582
+ return done;
583
+ };
584
+ cardToHer({ kind: 'retry', ask, card });
585
+ },
586
+ });
587
+ await lease.free(signal);
588
+ if (id && got !== 'stop' && !hers)
589
+ await answeredByPerson(id, `${got} — ${RETRY_WORDS[got]}`);
590
+ return got;
591
+ },
592
+ }
593
+ : {}),
594
+ });
595
+ /** A chat for her message: a new one with the settings she chose, or the one she sent to last, set as she chose now. */
596
+ const chatFor = async (r, n) => {
597
+ const planMode = r.planMode ? 'approve' : 'off';
598
+ if (r.chat === 'same' && lastChat) {
599
+ return await store.updateSession(lastChat.id, (s) => {
600
+ s.planMode = planMode;
601
+ if (!s.lead)
602
+ s.review = { ...(s.review ?? { model: '' }), enabled: !!r.review };
603
+ });
604
+ }
605
+ const title = (r.title ?? '').trim() || r.prompt.split(/\r?\n/)[0].trim().slice(0, 60);
606
+ const made = await store.createSession(`Kerrigan ${n}: ${title}`.slice(0, 120), session.projectDir ?? '');
607
+ const own = (await store.getSession(session.id))?.kerrigan ?? {};
608
+ return await store.updateSession(made.id, (s) => {
609
+ s.kind = 'chat';
610
+ s.directedBy = session.id;
611
+ s.onFailure = 'continue';
612
+ // No version control of its own, as the chat has none: it works on the branch the folder is on (see `chatSend`).
613
+ s.vcs = { ...(s.vcs ?? DEFAULT_VCS), enabled: false, repoDir: '' };
614
+ s.projectDir = session.projectDir ?? '';
615
+ s.planMode = planMode;
616
+ s.review = { enabled: !!r.review && !r.twoChats, model: '' };
617
+ // The model of her chats, as chosen under the chat's box; none, Settings'. With two chats it is the worker's, and the
618
+ // lead's is Settings' model for the lead.
619
+ if (r.twoChats) {
620
+ s.lead = {
621
+ ...(own.chatManualModel ? { workerManualModel: true } : {}),
622
+ ...(!own.chatManualModel && own.chatModel?.trim() ? { workerModel: own.chatModel.trim() } : {}),
623
+ };
624
+ }
625
+ else if (own.chatManualModel)
626
+ s.manualModel = true;
627
+ else if (own.chatModel?.trim()) {
628
+ s.model = own.chatModel.trim();
629
+ s.modelSource = 'operator';
630
+ }
631
+ if (session.lang)
632
+ s.lang = session.lang;
633
+ });
634
+ };
635
+ /** Why a "send" cannot be carried out as it stands, or null. */
636
+ const sendProblem = async (r) => {
637
+ if (r.chat === 'same' && !lastChat)
638
+ return 'There is no chat of yours to carry on yet: send to a "new" one.';
639
+ if (r.chat === 'same' && lastChat && !!r.twoChats !== !!lastChat.lead) {
640
+ return `"twoChats" is set when a chat begins: the chat you sent to last is ${lastChat.lead ? 'one of two chats' : 'one chat'}. Send with "twoChats": ${!!lastChat.lead}, or to a "new" chat.`;
641
+ }
642
+ const skill = (r.skill ?? '').trim();
643
+ if (skill && !(await deps.kerrigan?.skill(skill, chatDir)))
644
+ return `There is no skill called "${skill}" for this folder: use one of the facts' list, or "".`;
645
+ return null;
646
+ };
647
+ /** Her message to a chat, carried out there to its end; the result, as she is told it. */
648
+ const sendToChat = async (r, round) => {
649
+ k.sent += 1;
650
+ const n = k.sent;
651
+ const chat = await chatFor(r, n);
652
+ const title = (r.title ?? '').trim() || r.prompt.split(/\r?\n/)[0].trim().slice(0, 80);
653
+ const skill = (r.skill ?? '').trim() ? await deps.kerrigan?.skill(r.skill.trim(), chatDir) : null;
654
+ const made = await store.addTask(chat.id, { title, level2: '', prompt: r.prompt, ...(skill ? { skill } : {}) });
655
+ await store.updateTask(chat.id, made.id, (t) => {
656
+ t.fromKerrigan = { sessionId: session.id, taskId: task.id, n };
657
+ });
658
+ if (!k.chats.includes(chat.id))
659
+ k.chats.push(chat.id);
660
+ round.send = {
661
+ n,
662
+ title,
663
+ prompt: r.prompt,
664
+ chat: r.chat === 'same' && lastChat ? 'same' : 'new',
665
+ planMode: !!r.planMode,
666
+ twoChats: !!chat.lead,
667
+ review: !!chat.review?.enabled,
668
+ ...(skill ? { skill: skill.name } : {}),
669
+ sessionId: chat.id,
670
+ taskId: made.id,
671
+ status: 'running',
672
+ };
673
+ await save();
674
+ sink.event('kerrigan-sent', { n, sessionId: chat.id, taskId: made.id, chat: round.send.chat, planMode: round.send.planMode, twoChats: round.send.twoChats, review: round.send.review, skill: skill?.name ?? null }, `Kerrigan's message ${n} goes to the chat "${chat.name}": ${title}`);
675
+ deps.onWorker?.(chat.id, session.id);
676
+ actorNow = chat.lead ? 'lead' : chat.planMode === 'approve' ? 'plan' : 'worker';
677
+ await actingNow(actorNow);
678
+ speakFor(transport, chat.id);
679
+ const fresh = !chat.chat;
680
+ await enterSessionConversation(transport, chat, { closeOnFailure: false });
681
+ const model = await applySessionModel(transport, chat, bus, cfg, store, deps.models, fresh, signal);
682
+ if (model.refused) {
683
+ speakFor(transport, session.id);
684
+ if (signal?.aborted)
685
+ return 'stopped';
686
+ throw new Error(`The chat's conversation could not be put on its model: ${model.refused}`);
687
+ }
688
+ const current = (await store.getSession(chat.id));
689
+ const its = current.tasks.find((x) => x.id === made.id);
690
+ const out = current.lead ? await runLeadTask(transport, current, its, chatDeps(chat.id)) : await runTask(transport, current, its, chatDeps(chat.id));
691
+ // A card she was still on when the chat ended: her round of it is let finish before her conversation is used again.
692
+ await cards;
693
+ speakFor(transport, session.id);
694
+ if (transport.closedOutside())
695
+ throw new WindowClosed();
696
+ lastChat = (await store.getSession(chat.id)) ?? chat;
697
+ lastTitle = title;
698
+ const ended = lastChat.tasks.find((x) => x.id === made.id);
699
+ round.send.status = ended?.status ?? out.status;
700
+ const summary = (ended?.summary ?? out.summary ?? '').trim();
701
+ if (summary)
702
+ round.send.summary = summary.slice(0, 4000);
703
+ await save();
704
+ sink.event('kerrigan-result', { n, status: out.status }, `the chat's work on Kerrigan's message ${n} ended: ${out.status}`);
705
+ if (signal?.aborted)
706
+ return 'stopped';
707
+ await actingNow('kerrigan');
708
+ // The whole exchange only when Settings say so (2026-11-12); by default she is given what "Copy" gives.
709
+ const file = cfg.execution.kerriganResult === 'exchange' ? await exchangeOf(chat.id, made.id, n) : null;
710
+ await toHer();
711
+ const name = file ? file.replace(/^.*[\\/]/, '') : undefined;
712
+ return { text: await resultOf(lastChat, made.id, out, n, title, name), files: file ? [file] : [] };
713
+ };
714
+ /**
715
+ * The whole exchange of a chat's message, as its "JSON" button gives it (`taskExchange.ts`): every message, every reply,
716
+ * every command with all it printed. Written out for her, secrets taken out first, as every report is.
717
+ */
718
+ const exchangeOf = async (chatId, taskId, n) => {
719
+ const s = await store.getSession(chatId);
720
+ const t = s?.tasks.find((x) => x.id === taskId);
721
+ if (!s || !t)
722
+ return null;
723
+ try {
724
+ let text = redactSecrets(JSON.stringify(await buildTaskExchange(cfg.resolved.runsDir, s, t), null, 2), cfg.report.redactPatterns);
725
+ if (text.length > MAX_EXCHANGE_CHARS)
726
+ text = `${text.slice(0, MAX_EXCHANGE_CHARS)}\n… (cut here: the whole of it is ${text.length} characters)`;
727
+ // As text: the chat window takes a .txt as the reports go; it is JSON, and she is told so.
728
+ const file = log.path('messages', `exchange-of-message-${n}.txt`);
729
+ await writeFile(file, text, 'utf8');
730
+ return file;
731
+ }
732
+ catch (e) {
733
+ sink.event('kerrigan-exchange-missing', { n, error: e.message }, `the exchange of Kerrigan's message ${n} could not be written out: ${e.message}`, 'warn');
734
+ return null;
735
+ }
736
+ };
737
+ /**
738
+ * The result of her message, as she is told it: how it ended, and what "Copy" under its ending gives — the chat's
739
+ * summary of what was done, tried and how it went (operator, 2026-11-12: "the last message must be enough, just
740
+ * copied") — with the whole exchange attached when Settings say so.
741
+ */
742
+ const resultOf = async (chat, taskId, out, n, title, attached) => {
743
+ const t = chat.tasks.find((x) => x.id === taskId);
744
+ const status = t?.status ?? out.status;
745
+ const copied = endingCopyText({ status, summary: t?.summary ?? out.summary, reason: t?.reason ?? out.reason });
746
+ const lines = [
747
+ `The result of your message ${n} ("${title}") in the chat "${chat.name.replace(/^chat: /, '')}": ${endedAs(status)}.`,
748
+ '',
749
+ 'What "Copy" under its ending gives:',
750
+ '',
751
+ '---',
752
+ copied || '(it gave no summary)',
753
+ '---',
754
+ ];
755
+ if (attached)
756
+ lines.push('', `Attached, \`${attached}\`: the whole exchange of this message, as JSON — every message the chat was sent, every reply of its, every command with all it printed. Read it where the summary above is not enough.`);
757
+ lines.push('', `Messages to chats left: ${Math.max(0, k.maxSends - k.sent)} of ${k.maxSends}.`, 'Reply in your format: the next message (send), your report (done), a question for the person (ask), or blocked.');
758
+ return lines.join('\n');
759
+ };
760
+ const finish = async (status, reason, summary) => {
761
+ // What the whole of the message changed: the folder against its photograph from before it.
762
+ let vcs;
763
+ if (checkpoint && chatDir) {
764
+ const after = await takeAfter(chatDir, task.id, checkpoint).catch((e) => ({ problem: e.message }));
765
+ if (!('problem' in after))
766
+ vcs = { baseCommit: checkpoint.commit, commit: after.commit, files: await commitFiles(chatDir, after.commit).catch(() => []) };
767
+ }
768
+ await save();
769
+ await setTask((t) => {
770
+ if (vcs)
771
+ t.vcs = vcs;
772
+ t.status = status;
773
+ delete t.acting;
774
+ t.finishedAt = new Date().toISOString();
775
+ const held = deps.hold?.pausedSince(startedAt) ?? 0;
776
+ if (held > 0)
777
+ t.pausedMs = held;
778
+ t.summary = summary;
779
+ t.reason = reason;
780
+ t.logFile = 'task-log.txt';
781
+ if (limitHit)
782
+ t.limit = limitHit;
783
+ });
784
+ await record(`TASK ${status.toUpperCase()}`, [summary ?? '', reason ? `Reason: ${reason}` : ''].filter(Boolean).join('\n\n') || '(no details)');
785
+ sink.event('task-finished', { status, reason, iterations: k.rounds.length, sent: k.sent, kerrigan: true }, `task "${task.title}" ${status}${reason ? `: ${reason}` : ''}`);
786
+ unlive();
787
+ await log.close();
788
+ return { status, iterations: k.rounds.length, summary, reason };
789
+ };
790
+ try {
791
+ const n = session.tasks.findIndex((x) => x.id === task.id) + 1;
792
+ if (!session.contractSent) {
793
+ const contract = (await store.getKerrigan1()).content.trim();
794
+ const brief = (await deps.kerrigan?.brief()) ?? '';
795
+ const opening = brief ? `${contract}\n\n---\n\n${brief}` : contract;
796
+ await setTask((t) => {
797
+ t.firstMessage = opening;
798
+ });
799
+ if (signal?.aborted)
800
+ return await finish('aborted', 'stopped before anything was sent to Kerrigan');
801
+ // Her acknowledgement is not read: what she does begins with the task.
802
+ await tell(opening);
803
+ session.contractSent = true;
804
+ await store.updateSession(session.id, (s) => {
805
+ s.contractSent = true;
806
+ });
807
+ }
808
+ const opening = kerriganTaskMessage(task, n || 1, { maxSends: maxSends(), ...(lastChat ? { chat: { name: lastChat.name.replace(/^chat: /, ''), ...(lastTitle ? { title: lastTitle } : {}) } } : {}) }, k.messages === 0 && !!session.chat);
809
+ await record('THE TASK', opening);
810
+ if (signal?.aborted)
811
+ return await finish('aborted', 'stopped before the task was sent to Kerrigan');
812
+ /** Her next decision in the work: not an answer to a card, which only a card takes. */
813
+ let understood = !!task.continuing;
814
+ const decides = async (x) => {
815
+ if (x.status === 'answer')
816
+ return 'No card is waiting for an answer now: reply with "send", "ask", "done" or "blocked".';
817
+ if (!understood && !x.understanding)
818
+ return KERRIGAN_UNDERSTANDING_FIRST;
819
+ if (x.status === 'ask' && (x.question ?? '').trim().length < 10)
820
+ return 'status "ask" needs a "question" for the person: what only they can decide, said in full, with "why" and "options".';
821
+ if (x.status === 'send')
822
+ return await sendProblem(x);
823
+ return null;
824
+ };
825
+ let r = await askHer(opening, decides);
826
+ const maxRounds = () => Math.max(1, cfg.limits.maxIterations);
827
+ for (;;) {
828
+ understood = true;
829
+ if (signal?.aborted)
830
+ return await finish('aborted', 'stopped by the operator');
831
+ if (k.rounds.length >= maxRounds()) {
832
+ limitHit = { setting: 'maxIterations', value: maxRounds() };
833
+ return await finish('limit-reached', `maxIterations (${maxRounds()}) reached: Kerrigan's replies`);
834
+ }
835
+ const round = {
836
+ status: r.status,
837
+ at: new Date().toISOString(),
838
+ ...(r.understanding ? { understanding: r.understanding } : {}),
839
+ ...(r.notes ? { notes: r.notes } : {}),
840
+ ...(r.sources.length > 0 ? { sources: r.sources } : {}),
841
+ };
842
+ k.rounds.push(round);
843
+ await save();
844
+ sink.event('kerrigan-reply', { round: k.rounds.length, status: r.status }, `Kerrigan: ${r.status}${r.title ? ` — ${r.title}` : ''}`);
845
+ switch (r.status) {
846
+ case 'send': {
847
+ if (k.sent >= k.maxSends) {
848
+ r = await askHer(`You have sent the ${k.maxSends} message(s) to chats you may for this task. Deliver what you have now — status "done" with your report, what is missing said plainly — or "blocked".`, async (x) => (x.status === 'send' ? 'No message to a chat is left: reply "done" or "blocked".' : await decides(x)));
849
+ break;
850
+ }
851
+ const ran = await sendToChat(r, round);
852
+ if (ran === 'stopped')
853
+ return await finish('aborted', 'stopped by the operator');
854
+ r = await askHer(ran.text, decides, ran.files);
855
+ break;
856
+ }
857
+ case 'ask': {
858
+ round.question = { text: r.question, ...(r.why ? { why: r.why } : {}), options: r.options?.map(String) ?? [], ...(r.multiple ? { multiple: true } : {}) };
859
+ await save();
860
+ if (!deps.askQuestion) {
861
+ r = await askHer('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.', decides);
862
+ break;
863
+ }
864
+ sink.event('kerrigan-question', { question: r.question }, `Kerrigan asks the operator: ${r.question}`, 'warn');
865
+ const options = (r.options ?? []).map(String).filter((o) => o.trim());
866
+ const got = await deps.askQuestion({ sessionId: session.id, taskId: task.id, question: r.question, ...(r.why ? { why: r.why } : {}), options, ...(r.multiple && options.length >= 2 ? { multiple: true } : {}), actor: 'kerrigan' });
867
+ if (got === 'stop' || signal?.aborted)
868
+ return await finish('aborted', 'the operator stopped the task at Kerrigan\'s question');
869
+ round.question.answer = got.answer;
870
+ await save();
871
+ sink.event('kerrigan-question-answered', {}, 'the operator answered Kerrigan');
872
+ await actingNow('kerrigan');
873
+ const said = got.chosen ? `The person answered your question, ${chosenSaid({ chosen: got.chosen, ...(got.written ? { written: got.written } : {}) })}` : `The person answers your question:\n\n${got.answer.trim()}`;
874
+ r = await askHer(`${said}\n\nGo on in your format. Messages to chats left: ${Math.max(0, k.maxSends - k.sent)} of ${k.maxSends}.`, decides);
875
+ break;
876
+ }
877
+ case 'done': {
878
+ round.report = r.report;
879
+ if (r.evidence.length > 0)
880
+ round.evidence = r.evidence;
881
+ return await finish('done', undefined, r.report);
882
+ }
883
+ case 'blocked': {
884
+ round.report = r.summary;
885
+ round.needed = r.needed;
886
+ return await finish('blocked', `Kerrigan could not take it further: ${r.needed ?? ''}`.trim(), r.summary);
887
+ }
888
+ case 'answer':
889
+ // Refused by `decides` before it gets here.
890
+ r = await askHer('No card is waiting for an answer now: reply with "send", "ask", "done" or "blocked".', decides);
891
+ break;
892
+ }
893
+ }
894
+ }
895
+ catch (e) {
896
+ const message = e.message;
897
+ if (e instanceof StoppedSend || signal?.aborted)
898
+ return await finish('aborted', 'stopped by the operator; nothing more was sent');
899
+ if (e instanceof FormatLimit) {
900
+ limitHit = { setting: 'maxFormatRetries', value: maxFormat() };
901
+ return await finish('limit-reached', `maxFormatRetries (${maxFormat()}) reached: Kerrigan's replies could not be acted on (${message})`);
902
+ }
903
+ if (isReplyTimeout(e)) {
904
+ limitHit = { setting: 'replyTimeoutSec', value: e.seconds };
905
+ return await finish('limit-reached', `replyTimeoutSec (${e.seconds}) reached: ${message}`);
906
+ }
907
+ if (e instanceof WindowClosed || transport.closedOutside())
908
+ return await finish('aborted', 'the browser window was closed; nothing more was sent');
909
+ sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
910
+ return await finish('failed', message);
911
+ }
912
+ }