copilot-operator 0.1.85 → 0.1.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/src/api/operator.controller.js +23 -0
  2. package/dist/src/api/operator.service.js +59 -2
  3. package/dist/src/config/schema.js +15 -0
  4. package/dist/src/orchestrator/kerriganRunner.js +3 -1
  5. package/dist/src/orchestrator/leadRunner.js +3 -1
  6. package/dist/src/orchestrator/taskRunner.js +56 -31
  7. package/dist/src/plan/systemGuide.js +35 -4
  8. package/dist/src/session/compose.js +5 -1
  9. package/dist/src/transport/chatTransport.js +6 -2
  10. package/dist/src/transport/copilotTransport.js +226 -11
  11. package/dist/src/transport/keptWindow.js +247 -0
  12. package/dist/src/transport/locators.js +14 -4
  13. package/dist/web/404.html +2 -2
  14. package/dist/web/_next/static/chunks/1077.26ca37faa3726fff.js +1 -0
  15. package/dist/web/_next/static/chunks/1548.f5790cd11a91309f.js +1 -0
  16. package/dist/web/_next/static/chunks/2163.aa9d9b82fcde6caa.js +1 -0
  17. package/dist/web/_next/static/chunks/714.b7dbce98ba0b59a8.js +1 -0
  18. package/dist/web/_next/static/chunks/7220.0ca53eefec5d01ea.js +1 -0
  19. package/dist/web/_next/static/chunks/7921-8f6503aba840928a.js +1 -0
  20. package/dist/web/_next/static/chunks/8584.9f3b058a8f67d3d7.js +1 -0
  21. package/dist/web/_next/static/chunks/9067.107f6164157e0aa1.js +1 -0
  22. package/dist/web/_next/static/chunks/9747.984a86f70f9cd973.js +1 -0
  23. package/dist/web/_next/static/chunks/app/page-b71841852e6b9ff5.js +1 -0
  24. package/dist/web/_next/static/chunks/app/settings/page-95069cb94d79e909.js +1 -0
  25. package/dist/web/_next/static/chunks/{webpack-13ccb80d7b7094ca.js → webpack-c015bbeb103c0856.js} +1 -1
  26. package/dist/web/_next/static/css/{6e2b8656501f0dd7.css → 0c5d6d5914aa3824.css} +1 -1
  27. package/dist/web/defaults.html +2 -2
  28. package/dist/web/defaults.txt +8 -8
  29. package/dist/web/index.html +3 -3
  30. package/dist/web/index.txt +9 -9
  31. package/dist/web/queue.html +2 -2
  32. package/dist/web/queue.txt +9 -9
  33. package/dist/web/settings.html +2 -2
  34. package/dist/web/settings.txt +9 -9
  35. package/dist/web/system.html +2 -2
  36. package/dist/web/system.txt +9 -9
  37. package/package.json +3 -2
  38. package/dist/web/_next/static/chunks/1077.06fe73b2c16f8f49.js +0 -1
  39. package/dist/web/_next/static/chunks/1548.b38c5d8d00ab2a72.js +0 -1
  40. package/dist/web/_next/static/chunks/2163.ba933c9a506302ca.js +0 -1
  41. package/dist/web/_next/static/chunks/714.575273a189d030fe.js +0 -1
  42. package/dist/web/_next/static/chunks/7220.988dfd28e00f407c.js +0 -1
  43. package/dist/web/_next/static/chunks/7921-65dd56d87144bd44.js +0 -1
  44. package/dist/web/_next/static/chunks/8584.2221587201bc2fa2.js +0 -1
  45. package/dist/web/_next/static/chunks/9067.8d94a08830c3d1da.js +0 -1
  46. package/dist/web/_next/static/chunks/9747.8671194406acd839.js +0 -1
  47. package/dist/web/_next/static/chunks/app/page-76139370c7ca3715.js +0 -1
  48. package/dist/web/_next/static/chunks/app/settings/page-116da78c83f0c5c9.js +0 -1
  49. /package/dist/web/_next/static/{aCQe1FDhYTj4zGeI5ueVq → hLBBsG7Kn4vd0p_J-47BJ}/_buildManifest.js +0 -0
  50. /package/dist/web/_next/static/{aCQe1FDhYTj4zGeI5ueVq → hLBBsG7Kn4vd0p_J-47BJ}/_ssgManifest.js +0 -0
@@ -440,6 +440,10 @@ let OperatorController = class OperatorController {
440
440
  throw new BadRequestException(result.problem);
441
441
  return result;
442
442
  }
443
+ /** "Continue" (2026-11-13): the last message of a conversation, stopped before it was done, carried on from where it got to. */
444
+ chatContinue(id, taskId) {
445
+ return this.ops.chatContinue(id, taskId).catch(fail);
446
+ }
443
447
  /** After a Stop (two chats, 2026-10-25): the stopped message carried on with one of its subtasks tried again first. */
444
448
  chatRetrySubtask(id, taskId, body = {}) {
445
449
  const n = Number(body?.n);
@@ -527,6 +531,10 @@ let OperatorController = class OperatorController {
527
531
  setDefaultLeadModel(body) {
528
532
  return this.ops.setDefaultLeadModel(body?.model ?? '').catch(fail);
529
533
  }
534
+ /** The model Kerrigan's conversation starts on (2026-11-13). An empty name: the lead's, else the worker's. */
535
+ setDefaultKerriganModel(body) {
536
+ return this.ops.setDefaultKerriganModel(body?.model ?? '').catch(fail);
537
+ }
530
538
  /** The model of the independent review. An empty name means "the session's own". */
531
539
  setDefaultReviewModel(body) {
532
540
  return this.ops.setDefaultReviewModel(body?.model ?? '').catch(fail);
@@ -943,6 +951,14 @@ __decorate([
943
951
  __metadata("design:paramtypes", [String, Object]),
944
952
  __metadata("design:returntype", Object)
945
953
  ], OperatorController.prototype, "answerRetry", null);
954
+ __decorate([
955
+ Post('chat/:id/tasks/:taskId/continue'),
956
+ __param(0, Param('id')),
957
+ __param(1, Param('taskId')),
958
+ __metadata("design:type", Function),
959
+ __metadata("design:paramtypes", [String, String]),
960
+ __metadata("design:returntype", Promise)
961
+ ], OperatorController.prototype, "chatContinue", null);
946
962
  __decorate([
947
963
  Post('chat/:id/tasks/:taskId/retry-subtask'),
948
964
  __param(0, Param('id')),
@@ -1033,6 +1049,13 @@ __decorate([
1033
1049
  __metadata("design:paramtypes", [Object]),
1034
1050
  __metadata("design:returntype", Promise)
1035
1051
  ], OperatorController.prototype, "setDefaultLeadModel", null);
1052
+ __decorate([
1053
+ Put('models/kerrigan-default'),
1054
+ __param(0, Body()),
1055
+ __metadata("design:type", Function),
1056
+ __metadata("design:paramtypes", [Object]),
1057
+ __metadata("design:returntype", Promise)
1058
+ ], OperatorController.prototype, "setDefaultKerriganModel", null);
1036
1059
  __decorate([
1037
1060
  Put('models/review-default'),
1038
1061
  __param(0, Body()),
@@ -23,7 +23,7 @@ import { SessionStore, DEFAULT_VCS, DEFAULT_REVIEW, writeFileAtomically } from '
23
23
  import { checkItems, emptyQueue, itemTitle, mergeItems, nextStep, parkAfterMs, parkedAnswerFrom, skippedBecause, statusOfTask, waitsByHand, MAX_PARK_AFTER_SEC, PARKED_WORDS } from '../queue/queue.js';
24
24
  import { branchStart, makeQueueBranch, refreshQueueBranch } from '../queue/queueBranch.js';
25
25
  import { EventBus } from '../session/events.js';
26
- import { MAX_INSTRUCTION_CHARS, newId, withProblemAt } from '../session/model.js';
26
+ import { isContinuable, MAX_INSTRUCTION_CHARS, newId, withProblemAt } from '../session/model.js';
27
27
  import { handoffOutcomeOf, handoffResultMessage } from '../orchestrator/handoff.js';
28
28
  import { runSession, queuedToRun, failedWhileOpening, pickerOptions } from '../orchestrator/taskRunner.js';
29
29
  import { Hold, WaitsFor } from '../orchestrator/hold.js';
@@ -1053,6 +1053,8 @@ let OperatorService = class OperatorService {
1053
1053
  await this.setDefaultReviewModel(to);
1054
1054
  if (which === 'lead' && (now.defaultLeadModel ?? '').trim() === from)
1055
1055
  await this.setDefaultLeadModel(to);
1056
+ if (which === 'kerrigan' && (now.defaultKerriganModel ?? '').trim() === from)
1057
+ await this.setDefaultKerriganModel(to);
1056
1058
  },
1057
1059
  seen: async (options, current) => {
1058
1060
  await this.store.saveModels({ options, current: current ?? undefined, readAt: new Date().toISOString() });
@@ -2461,6 +2463,42 @@ let OperatorService = class OperatorService {
2461
2463
  const cfg = await this.settings.load();
2462
2464
  return await this.start(threadId, cfg.execution.mode);
2463
2465
  }
2466
+ /**
2467
+ * "Continue" under a message that stopped before it was done (operator, 2026-11-13: "for every stop" — a window closed
2468
+ * past the times it is opened again, Stop, the bot itself stopped or restarted, a limit): carried on in its conversation
2469
+ * from where it got to. The chat is told how it stopped and, for one that was stopped, which of its last commands ran,
2470
+ * with the end of what they printed, which was cut off and which never ran — read from its run folder — rather than
2471
+ * only that it was stopped, after which it ran its inspections again (live run, 2026-10-03). Only the last message of
2472
+ * a conversation: one the conversation has gone on past is not carried on in it. A chat Kerrigan directs is hers.
2473
+ */
2474
+ async chatContinue(threadId, taskId) {
2475
+ await this.init();
2476
+ const session = await this.store.getSession(threadId);
2477
+ if (!session || session.kind !== 'chat')
2478
+ throw new Error('That conversation is not there any more.');
2479
+ if (session.directedBy)
2480
+ throw new Error('Kerrigan directs this chat: carry her conversation on instead.');
2481
+ if (this.running.has(this.runKey(threadId)))
2482
+ throw new Error('The conversation is working: stop it first, or let it finish.');
2483
+ const task = session.tasks.find((t) => t.id === taskId);
2484
+ if (!task)
2485
+ throw new Error('That message is not in this conversation.');
2486
+ if (session.tasks.at(-1)?.id !== taskId)
2487
+ throw new Error('Only the last message of a conversation is carried on: the conversation has gone on past this one.');
2488
+ if (!isContinuable(task)) {
2489
+ throw new Error(task.status === 'done' ? 'This message is done.' : 'Only a message that stopped before it was done is carried on; write the next message instead.');
2490
+ }
2491
+ const cfg = await this.settings.load();
2492
+ const stoppedAt = task.status === 'aborted' && !task.interruption && task.runId ? await readInterruption(join(cfg.resolved.runsDir, task.runId)).catch(() => null) : null;
2493
+ const queued = await this.store.continueTask(threadId, taskId, stoppedAt);
2494
+ await appendSessionLog(cfg.resolved.runsDir, threadId, {
2495
+ type: 'continue',
2496
+ message: `"${queued.title}" carried on as attempt ${queued.attempt ?? 1}, from where it stopped: ${task.reason ?? task.status}`,
2497
+ data: { taskId, attempt: queued.attempt, was: task.status },
2498
+ }).catch(() => undefined);
2499
+ this.bus.publish({ sessionId: threadId, taskId, type: 'task-requeued', level: 'info', message: `"${queued.title}" carried on from where it stopped` });
2500
+ return await this.start(threadId, cfg.execution.mode);
2501
+ }
2464
2502
  answerQuestion(approvalId, text, ran, outcome, chosen, as) {
2465
2503
  const w = this.waiting.get(approvalId);
2466
2504
  if (!w?.resolveAnswer)
@@ -3076,7 +3114,10 @@ let OperatorService = class OperatorService {
3076
3114
  const defaultModel = cfg.copilot.defaultModel ?? '';
3077
3115
  const defaultReviewModel = cfg.copilot.defaultReviewModel ?? '';
3078
3116
  const defaultLeadModel = cfg.copilot.defaultLeadModel ?? '';
3079
- return cached ? { ...cached, defaultModel, defaultLeadModel, defaultReviewModel } : { defaultModel, defaultLeadModel, defaultReviewModel, options: [], readAt: null };
3117
+ const defaultKerriganModel = cfg.copilot.defaultKerriganModel ?? '';
3118
+ return cached
3119
+ ? { ...cached, defaultModel, defaultLeadModel, defaultKerriganModel, defaultReviewModel }
3120
+ : { defaultModel, defaultLeadModel, defaultKerriganModel, defaultReviewModel, options: [], readAt: null };
3080
3121
  }
3081
3122
  /**
3082
3123
  * Sets the model a new session's independent review starts on. An empty name clears it,
@@ -3095,6 +3136,18 @@ let OperatorService = class OperatorService {
3095
3136
  });
3096
3137
  return { defaultLeadModel: name.trim() };
3097
3138
  }
3139
+ /** Sets the model Kerrigan's conversation starts on (2026-11-13). An empty name: the lead's, else the worker's. */
3140
+ async setDefaultKerriganModel(name) {
3141
+ await this.init();
3142
+ await this.settings.update((raw) => ({ ...raw, copilot: { ...(raw.copilot ?? {}), defaultKerriganModel: name.trim() } }));
3143
+ this.bus.publish({
3144
+ sessionId: '*',
3145
+ type: 'default-kerrigan-model-changed',
3146
+ level: 'info',
3147
+ message: name.trim() ? `Kerrigan will start on ${name.trim()}` : "Kerrigan starts on the lead's model",
3148
+ });
3149
+ return { defaultKerriganModel: name.trim() };
3150
+ }
3098
3151
  async setDefaultReviewModel(name) {
3099
3152
  await this.init();
3100
3153
  await this.settings.update((raw) => ({ ...raw, copilot: { ...(raw.copilot ?? {}), defaultReviewModel: name.trim() } }));
@@ -3242,15 +3295,19 @@ let OperatorService = class OperatorService {
3242
3295
  const work = (saved.defaultModel ?? '').trim();
3243
3296
  const review = (saved.defaultReviewModel ?? '').trim();
3244
3297
  const lead = (saved.defaultLeadModel ?? '').trim();
3298
+ const kerrigan = (saved.defaultKerriganModel ?? '').trim();
3245
3299
  const workNow = work ? pageModelFor(work, options) : null;
3246
3300
  const reviewNow = review ? pageModelFor(review, options) : null;
3247
3301
  const leadNow = lead ? pageModelFor(lead, options) : null;
3302
+ const kerriganNow = kerrigan ? pageModelFor(kerrigan, options) : null;
3248
3303
  if (workNow && !sameModel(workNow.name, work))
3249
3304
  await this.setDefaultModel(workNow.name);
3250
3305
  if (reviewNow && !sameModel(reviewNow.name, review))
3251
3306
  await this.setDefaultReviewModel(reviewNow.name);
3252
3307
  if (leadNow && !sameModel(leadNow.name, lead))
3253
3308
  await this.setDefaultLeadModel(leadNow.name);
3309
+ if (kerriganNow && !sameModel(kerriganNow.name, kerrigan))
3310
+ await this.setDefaultKerriganModel(kerriganNow.name);
3254
3311
  return catalogue;
3255
3312
  }
3256
3313
  finally {
@@ -124,6 +124,12 @@ export const RunConfigSchema = z.object({
124
124
  * lead's conversation on whatever it is set to.
125
125
  */
126
126
  defaultLeadModel: z.string().default(''),
127
+ /**
128
+ * The model Kerrigan's own conversation starts on (operator, 2026-11-13: "add the section in Settings"). Empty, she
129
+ * starts on the lead's, else the worker's — as before she had one of her own. The chats she sends to are the
130
+ * worker's (and, with two chats, the lead's), not this.
131
+ */
132
+ defaultKerriganModel: z.string().default(''),
127
133
  /**
128
134
  * Choose the model by hand (operator's workaround, 2026-10-06): at the start of a run, and of a review's
129
135
  * conversation, the runner does not touch the picker; a card in the UI asks the operator to choose the
@@ -135,6 +141,8 @@ export const RunConfigSchema = z.object({
135
141
  /** The lead's and the review's models chosen by hand, each on its own (2026-10-23); absent, as `manualModel`. */
136
142
  leadManualModel: z.boolean().optional(),
137
143
  reviewManualModel: z.boolean().optional(),
144
+ /** Kerrigan's model chosen by hand (2026-11-13); absent, as the lead's (`leadManualModel`, then `manualModel`). */
145
+ kerriganManualModel: z.boolean().optional(),
138
146
  replyTimeoutSec: z.number().int().positive().default(900),
139
147
  signInTimeoutSec: z.number().int().positive().default(900),
140
148
  humanWaitSec: z.number().int().positive().default(900),
@@ -537,6 +545,13 @@ export const RunConfigSchema = z.object({
537
545
  * Zero turns it off.
538
546
  */
539
547
  autoContinue: z.number().int().min(0).max(20).default(3),
548
+ /*
549
+ * How many times the chat's Edge window, closed while a message is at work — its X pressed, by accident or not, or
550
+ * Edge ending — is opened again on its conversation for that message, and the work carried on there (operator,
551
+ * 2026-11-13; see `transport/keptWindow.ts`). Past it, the message stops and "Continue" carries it on. Zero: a
552
+ * window closed under the work stops the message, as before. Stop is the way to stop the work. Settings → limits.
553
+ */
554
+ reopenWindow: z.number().int().min(0).max(10).default(3),
540
555
  /*
541
556
  * The most subtasks the lead of a two-chat conversation may give its worker for one message (2026-10-20). Each
542
557
  * subtask is a task of the worker's, with the limits above; this bounds the whole. Settings → Execution.
@@ -25,6 +25,7 @@
25
25
  */
26
26
  import { appendFile, mkdir, writeFile } from 'node:fs/promises';
27
27
  import { ChatLost, isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
28
+ import { CLOSED_NOT_REOPENED } from '../transport/keptWindow.js';
28
29
  import { buildChatName, chatCode, savePointer } from '../transport/chatSession.js';
29
30
  import { RunLog } from '../log/runLog.js';
30
31
  import { gapFrom, Pacer } from '../util/pacing.js';
@@ -904,8 +905,9 @@ export async function runKerriganTask(transport, session, task, deps) {
904
905
  limitHit = { setting: 'replyTimeoutSec', value: e.seconds };
905
906
  return await finish('limit-reached', `replyTimeoutSec (${e.seconds}) reached: ${message}`);
906
907
  }
908
+ // Why, as the kept window says it (2026-11-13): not opened again by Settings, past the times allowed, or not found.
907
909
  if (e instanceof WindowClosed || transport.closedOutside())
908
- return await finish('aborted', 'the browser window was closed; nothing more was sent');
910
+ return await finish('aborted', e instanceof WindowClosed ? e.message : CLOSED_NOT_REOPENED);
909
911
  sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
910
912
  return await finish('failed', message);
911
913
  }
@@ -21,6 +21,7 @@
21
21
  */
22
22
  import { appendFile, mkdir, writeFile } from 'node:fs/promises';
23
23
  import { isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
24
+ import { CLOSED_NOT_REOPENED } from '../transport/keptWindow.js';
24
25
  import { buildChatName, chatCode, savePointer } from '../transport/chatSession.js';
25
26
  import { RunLog } from '../log/runLog.js';
26
27
  import { gapFrom, Pacer } from '../util/pacing.js';
@@ -922,8 +923,9 @@ export async function runLeadTask(transport, session, task, deps) {
922
923
  limitHit = { setting: 'replyTimeoutSec', value: e.seconds };
923
924
  return await finish('limit-reached', `replyTimeoutSec (${e.seconds}) reached: ${message}`);
924
925
  }
926
+ // Why, as the kept window says it (2026-11-13): not opened again by Settings, past the times allowed, or not found.
925
927
  if (e instanceof WindowClosed || transport.closedOutside())
926
- return await finish('aborted', 'the browser window was closed; nothing more was sent');
928
+ return await finish('aborted', e instanceof WindowClosed ? e.message : CLOSED_NOT_REOPENED);
927
929
  sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
928
930
  return await finish('failed', message);
929
931
  }
@@ -15,6 +15,7 @@ import { readFile, mkdir, writeFile, appendFile } from 'node:fs/promises';
15
15
  import { basename, join, resolve } from 'node:path';
16
16
  import { buttonShows, normModel } from '../transport/modelMatch.js';
17
17
  import { ChatLost, createTransport, isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
18
+ import { CLOSED_NOT_REOPENED } from '../transport/keptWindow.js';
18
19
  import { buildChatName, chatCode, loadPointer, savePointer } from '../transport/chatSession.js';
19
20
  import { parseReply, formatErrorMessage, findLikelyDamage, damageGuidance } from '../protocol/parser.js';
20
21
  import { resolveDeviations, describeDeviations, mergeDisputes, describeDisputes } from '../protocol/replySchema.js';
@@ -100,7 +101,8 @@ async function followPageModels(which, wanted, result, session, store, hooks, fr
100
101
  else {
101
102
  await hooks?.renamedDefault?.(which, wanted, result.matched).catch(() => undefined);
102
103
  }
103
- return `"${wanted}" is no longer offered under that name; the page offers it as "${result.matched}", which was chosen, and ${own ? "the session's" : 'Settings\''} ${which === 'model' ? 'model' : 'review model'} now says so`;
104
+ const what = which === 'review' ? 'review model' : own ? 'model' : which === 'lead' ? 'model for the lead' : which === 'kerrigan' ? 'model for Kerrigan' : 'model';
105
+ return `"${wanted}" is no longer offered under that name; the page offers it as "${result.matched}", which was chosen, and ${own ? "the session's" : 'Settings\''} ${what} now says so`;
104
106
  }
105
107
  /** Why a task that was reported as done is being closed as failed. */
106
108
  function checksFailedReason(outcomes) {
@@ -482,17 +484,26 @@ signal) {
482
484
  'error-banner': 'The chat reported a transient error; reloading the page.',
483
485
  'reply-files-ignored': 'The reply came with a file attached. It was not downloaded and will not be run: the runner takes only the text of a reply.',
484
486
  'model-menu-stuck': 'The model menu would not close — Escape, the menu button and a click outside all left it open. Close it in the Edge window; the run goes on.',
485
- 'window-closed': 'The Edge window was closed. A run in it stops; the next message opens a new one.',
487
+ 'window-closed': 'The Edge window was closed. While a message is at work it is opened again on its conversation, as many times as ' +
488
+ 'Settings allow (limits.reopenWindow); between messages, the next message opens a new one.',
489
+ // Opened again under the work (2026-11-13): see transport/keptWindow.ts.
490
+ 'window-reopening': `Opening Edge again on this conversation (${String(detail?.time ?? '?')} of ${String(detail?.of ?? '?')} for this message), so the work goes on there.`,
491
+ 'window-reopened': 'Back on this conversation in a new Edge window; the work goes on from where it was.',
492
+ 'window-not-reopened': `The window was not opened again: ${String(detail?.reason ?? '')}`,
493
+ 'reply-asked-again': 'The chat was writing its answer when the window was closed; it was asked to send that answer again.',
494
+ 'message-sent-again': 'The window was closed while a message was being sent; it was sent again, saying it is a copy.',
486
495
  // The window left its conversation while the work waited (2026-11-09): put back before anything is sent.
487
496
  'chat-left': `The Copilot window is no longer on this conversation (it shows ${String(detail?.found ?? 'another page')}). Going back to it before anything is sent.`,
488
497
  'chat-returned': `Back on this conversation${detail?.signedIn ? ', after the sign-in' : ''}${detail?.by === 'name' ? ', found by its name in the sidebar' : ''}. The work goes on there.`,
489
498
  'chat-lost': 'The conversation could not be opened again, by its address or by its name. Nothing was sent, and nothing went into another chat.',
499
+ // Copilot showed another of its pages, its home page, instead of the chat (2026-11-17): the chat opened from it.
500
+ 'chat-page-elsewhere': `Copilot showed its page ${String(detail?.found ?? '')} instead of the chat; opening the chat ${detail?.by === 'link' ? "by the page's own link to it" : `at ${String(detail?.to ?? '')}`}.`,
490
501
  };
491
502
  for (const id of new Set(speaker.alone ? [speaker.id] : [speaker.id, sessionId])) {
492
503
  bus.publish({
493
504
  sessionId: id,
494
505
  type: `browser:${event}`,
495
- level: event === 'chat-lost' ? 'error' : event === 'verification-required' || event === 'reply-files-ignored' || event === 'model-menu-stuck' || event === 'chat-left' ? 'warn' : 'info',
506
+ level: event === 'chat-lost' ? 'error' : ['verification-required', 'reply-files-ignored', 'model-menu-stuck', 'chat-left', 'window-closed', 'window-not-reopened', 'reply-asked-again', 'message-sent-again'].includes(event) ? 'warn' : 'info',
496
507
  // An event with no sentence of its own is named, not said as "undefined".
497
508
  message: spoken[event] ?? event.replace(/-/g, ' '),
498
509
  data: detail,
@@ -702,28 +713,25 @@ export async function openSessionTransport(cfg, session, bus, runsDir, signal) {
702
713
  }
703
714
  return transport;
704
715
  }
716
+ /** Which part of Settings a session's conversation takes its model from. */
717
+ export function modelPartOf(session) {
718
+ return session.kerrigan ? 'kerrigan' : session.lead ? 'lead' : 'model';
719
+ }
705
720
  /**
706
- * Puts the conversation on the model the session asks for, once per run.
707
- *
708
- * Applied here rather than per task because the picker belongs to the conversation, and a
709
- * failure is reported rather than raised: a model that is out of quota or has been withdrawn
710
- * should not throw away a queue of tasks. The run continues on whatever the chat is actually
711
- * set to, and the session records that, so the register shows which model did the work rather
712
- * than which one was asked for.
713
- */
714
- /**
715
- * The models a session runs on: its own, or else the ones chosen in Settings at this moment.
716
- * A session gets a model of its own from the plan or from its own picker; one that has none
717
- * follows Settings, so a model chosen there after the session was made still reaches it.
718
- */
719
- /**
720
- * The models a session runs on, and where each came from.
721
- *
722
- * The operator's choice on the session's page or the run panel first; then Settings; the plan's last.
723
- * Settings used to come after any model the session held, and a plan imported with a "model" — written
724
- * by another chat, often a model the picker no longer had — overrode what the operator chose in Settings
725
- * on every run (operator's rule, 2026-10-06: what is set in Settings outranks the same thing in the JSON).
721
+ * Settings' model for a part, with what stands in for it when none is chosen there: Kerrigan's, else the lead's; the
722
+ * lead's, else the worker's. `setting` names the one the name comes from, so a model the page renamed is followed there.
726
723
  */
724
+ export function settingsModelOf(part, copilot) {
725
+ const own = (x) => (x ?? '').trim();
726
+ if (part === 'kerrigan' && own(copilot.defaultKerriganModel))
727
+ return { model: own(copilot.defaultKerriganModel), setting: 'kerrigan' };
728
+ if (part !== 'model' && own(copilot.defaultLeadModel))
729
+ return { model: own(copilot.defaultLeadModel), setting: 'lead' };
730
+ return { model: own(copilot.defaultModel), setting: 'model' };
731
+ }
732
+ function settingsModelFor(session, cfg) {
733
+ return settingsModelOf(modelPartOf(session), cfg.copilot).model;
734
+ }
727
735
  export function effectiveModels(session, cfg) {
728
736
  const pick = (own, source, settings) => own && source === 'operator' ? [own, 'session'] : settings ? [settings, 'settings'] : own ? [own, 'plan'] : ['', 'none'];
729
737
  // Set by hand in the Copilot window: no name is asked for, neither the session's nor the one in Settings.
@@ -731,9 +739,11 @@ export function effectiveModels(session, cfg) {
731
739
  * Settings' model for the conversation's part (2026-10-23): the lead's for the lead of two chats — the worker's when
732
740
  * none is chosen for the lead, as before there were two — else the worker's.
733
741
  */
734
- // Kerrigan directs as the lead does (2026-11-12): her conversation takes Settings' model for the lead.
735
- const directs = !!session.lead || !!session.kerrigan;
736
- const fromSettings = ((directs ? cfg.copilot.defaultLeadModel?.trim() || cfg.copilot.defaultModel : cfg.copilot.defaultModel) ?? '').trim();
742
+ /*
743
+ * Kerrigan's conversation (2026-11-13): Settings' model for Kerrigan; none chosen there, the lead's, as it was from
744
+ * 2026-11-12 when she directed as the lead does; none for the lead either, the worker's.
745
+ */
746
+ const fromSettings = settingsModelFor(session, cfg);
737
747
  const [model, modelFrom] = session.manualModel ? ['', 'none'] : pick((session.model ?? '').trim(), session.modelSource, fromSettings);
738
748
  const [reviewModel, reviewModelFrom] = pick((session.review?.model ?? '').trim(), session.reviewModelSource, (cfg.copilot.defaultReviewModel ?? '').trim());
739
749
  return { model, reviewModel, modelFrom, reviewModelFrom };
@@ -744,8 +754,12 @@ export function effectiveModels(session, cfg) {
744
754
  * model and has none from Settings either — its picker shows "by hand" for that, and what it shows is what happens.
745
755
  */
746
756
  export function modelByHand(session, cfg) {
747
- // Settings' "by hand" for the conversation's part (2026-10-23): the lead's has its own, absent as the worker's; Kerrigan's is the lead's.
748
- const settingsSay = session.lead || session.kerrigan ? (cfg.copilot.leadManualModel ?? cfg.copilot.manualModel) : cfg.copilot.manualModel;
757
+ /*
758
+ * Settings' "by hand" for the conversation's part (2026-10-23): the lead's has its own, absent as the worker's.
759
+ * Kerrigan's has her own since 2026-11-13, absent as the lead's.
760
+ */
761
+ const lead = cfg.copilot.leadManualModel ?? cfg.copilot.manualModel;
762
+ const settingsSay = session.kerrigan ? (cfg.copilot.kerriganManualModel ?? lead) : session.lead ? lead : cfg.copilot.manualModel;
749
763
  if (settingsSay || session.manualModel)
750
764
  return true;
751
765
  return session.kind === 'chat' && !effectiveModels(session, cfg).model;
@@ -829,7 +843,8 @@ signal) {
829
843
  const hand = await withOperatorHand(transport, wanted, result, hooks, session.id, bus, false, asks);
830
844
  result = hand.result;
831
845
  const goOnAsItIs = hand.goOnAsItIs;
832
- const renamed = await followPageModels(session.lead ? 'lead' : 'model', wanted, result, session, store, hooks, modelFrom);
846
+ // Followed in the setting the name came from: a part with none of its own takes another's (see `settingsModelOf`).
847
+ const renamed = await followPageModels(settingsModelOf(modelPartOf(session), cfg.copilot).setting, wanted, result, session, store, hooks, modelFrom);
833
848
  if (renamed)
834
849
  bus.publish({ sessionId: session.id, type: 'model-renamed', level: 'warn', message: renamed, data: { asked: wanted, chosen: result.matched } });
835
850
  bus.publish({
@@ -3559,8 +3574,10 @@ export async function runTask(transport, session, task, deps) {
3559
3574
  * Edge left a crash report, which says it was not them.
3560
3575
  */
3561
3576
  if (transport.closedOutside() && !(await transport.recentCrash().catch(() => null))) {
3562
- sink.event('window-closed', { error: message }, 'the browser window was closed; nothing more is sent', 'warn');
3563
- return await finish('aborted', 'the browser window was closed; nothing more was sent');
3577
+ // Why, as the kept window says it (2026-11-13): not opened again by Settings, past the times allowed, or not found.
3578
+ const why = e instanceof WindowClosed ? e.message : CLOSED_NOT_REOPENED;
3579
+ sink.event('window-closed', { error: message, reopened: transport.reopenedTimes?.() ?? 0 }, why, 'warn');
3580
+ return await finish('aborted', why);
3564
3581
  }
3565
3582
  sink.event('task-error', { error: message, stack: e.stack }, message, 'error');
3566
3583
  await transport.dumpFailure(log.path('failures'), 'crash').catch(() => undefined);
@@ -3673,6 +3690,12 @@ export async function runSession(sessionId, deps) {
3673
3690
  let task = session.tasks.find((t) => t.id === queuedTask.id);
3674
3691
  if (!task || task.status !== 'queued')
3675
3692
  continue;
3693
+ /*
3694
+ * The window, closed under this message, is opened again on its conversation and the work goes on there (operator,
3695
+ * 2026-11-13: "if I close the browser by accident, carry the task on from where it got to"), up to the times
3696
+ * Settings allow for one message — its runs again in a fresh chat and on its own after a limit included.
3697
+ */
3698
+ chat.holdWindow?.(cfg.limits.reopenWindow ?? 3, deps.signal);
3676
3699
  /*
3677
3700
  * A task taken from the queue was started by the operator, never by the retry loop below, which
3678
3701
  * runs its own. A fresh-retry mark on it is left from a retry that was queued and never ran —
@@ -3889,6 +3912,8 @@ export async function runSession(sessionId, deps) {
3889
3912
  }
3890
3913
  }
3891
3914
  finally {
3915
+ // No message at work: a window closed from now on is the next message's to open. One being opened again is let finish.
3916
+ await transport?.releaseWindow?.().catch(() => undefined);
3892
3917
  // A borrowed window belongs to whoever opened it and stays open for the next session.
3893
3918
  if (!borrowed) {
3894
3919
  // The chat's, still open, is kept for its next message; one the operator closed is let go of.
@@ -1010,6 +1010,14 @@ export const SYSTEM_GUIDE = [
1010
1010
  doesEn: 'While it is paused: goes on with the work from where it held.',
1011
1011
  doesBg: 'Докато е на пауза: продължава работата оттам, където е задържана.',
1012
1012
  },
1013
+ {
1014
+ key: 'chat.carryOn',
1015
+ kind: 'button',
1016
+ en: 'Continue',
1017
+ bg: 'Продължи',
1018
+ doesEn: 'Under the last message of a conversation when it stopped before it was done — its window closed more times than Settings reopen it, Stop, the bot stopped or restarted, a limit: carries it on in the same conversation from where it got to; Copilot is told how it stopped and which of its last commands ran, with what they printed.',
1019
+ doesBg: 'Под последното съобщение на разговор, когато е спряло, преди да е готово — прозорецът му е затварян повече пъти, отколкото Настройките го отварят отново, „Стоп“, ботът е спрял или рестартиран, лимит: продължава го в същия разговор оттам, докъдето е стигнало; на Copilot се казва как е спряло и кои от последните му команди са минали, с изписаното от тях.',
1020
+ },
1013
1021
  {
1014
1022
  key: 'chat.stop',
1015
1023
  kind: 'button',
@@ -1079,8 +1087,8 @@ export const SYSTEM_GUIDE = [
1079
1087
  kind: 'note',
1080
1088
  en: 'Kerrigan\'s model',
1081
1089
  bg: 'Модел на Кериган',
1082
- doesEn: 'With Kerrigan directing: beside the first model, which is hers; none chosen, Settings\' model for the lead.',
1083
- doesBg: 'Когато Кериган води: до първия модел, който е неин; ако не е избран — моделът за ръководителя от Настройки.',
1090
+ doesEn: 'With Kerrigan directing: beside the first model, which is hers; none chosen, Settings\' model for Kerrigan, else the lead\'s, else the worker\'s.',
1091
+ doesBg: 'Когато Кериган води: до първия модел, който е неин; ако не е избран — моделът за Кериган от Настройки, иначе този за ръководителя, иначе този за изпълнителя.',
1084
1092
  },
1085
1093
  {
1086
1094
  key: 'chat.kerriganChatsModel',
@@ -2436,8 +2444,8 @@ export const SYSTEM_GUIDE = [
2436
2444
  kind: 'checkbox',
2437
2445
  en: 'Choose the model by hand at the start of each run',
2438
2446
  bg: 'Избирай модела ръчно в началото на всяко пускане',
2439
- doesEn: 'In each of the three sections, for that part: nothing is chosen for it; a card asks you to choose its model in the Copilot window and press "Ready". The lead\'s and the review\'s are as the worker\'s until set.',
2440
- doesBg: 'Във всяка от трите секции, за съответната част: нищо не се избира за нея; карта ви моли да изберете модела ѝ в прозореца на Copilot и да натиснете „Готово“. Тези на ръководителя и на рецензията са като на изпълнителя, докато не се зададат.',
2447
+ doesEn: 'In each of the four sections, for that part: nothing is chosen for it; a card asks you to choose its model in the Copilot window and press "Ready". The lead\'s and the review\'s are as the worker\'s until set; Kerrigan\'s is as the lead\'s.',
2448
+ doesBg: 'Във всяка от четирите секции, за съответната част: нищо не се избира за нея; карта ви моли да изберете модела ѝ в прозореца на Copilot и да натиснете „Готово“. Тези на ръководителя и на рецензията са като на изпълнителя, докато не се зададат; този на Кериган е като на ръководителя.',
2441
2449
  },
2442
2450
  {
2443
2451
  key: 'def.saving',
@@ -2464,6 +2472,21 @@ export const SYSTEM_GUIDE = [
2464
2472
  },
2465
2473
  ],
2466
2474
  },
2475
+ {
2476
+ headingKey: 'def.kerriganTitle',
2477
+ en: 'Model for Kerrigan',
2478
+ bg: 'Модел за Кериган',
2479
+ controls: [
2480
+ {
2481
+ key: 'def.kerriganTitle',
2482
+ kind: 'note',
2483
+ en: 'Model for Kerrigan',
2484
+ bg: 'Модел за Кериган',
2485
+ doesEn: 'The model Kerrigan\'s own conversation starts on, with "Kerrigan directs", unless one is chosen under the chat\'s box as "Kerrigan\'s model"; none chosen, the lead\'s, else the worker\'s. The chats she sends the work to take the worker\'s (and, with two chats, the lead\'s), not this. Best a strong reasoning model. Its picker and buttons are those of the worker\'s section; its "by hand" is as the lead\'s until set.',
2486
+ doesBg: 'Моделът, с който започва собственият разговор на Кериган при „Кериган води“, освен ако под полето на чата не е избран друг като „Модел на Кериган“; ако не е избран — този на ръководителя, иначе този на изпълнителя. Чатовете, на които тя праща работата, вземат модела на изпълнителя (а при два чата — и на ръководителя), не този. Най-добре силен модел за разсъждение. Менюто и бутоните му са като в секцията на изпълнителя; „ръчно“ е като при ръководителя, докато не се зададе.',
2487
+ },
2488
+ ],
2489
+ },
2467
2490
  {
2468
2491
  headingKey: 'def.reviewTitle',
2469
2492
  en: 'Model for the review',
@@ -2563,6 +2586,14 @@ export const SYSTEM_GUIDE = [
2563
2586
  doesEn: 'How many times a task stopped by a limit is carried on by itself.',
2564
2587
  doesBg: 'Колко пъти задача, спряна от ограничение, продължава сама.',
2565
2588
  },
2589
+ {
2590
+ key: 'exec.reopenWindow',
2591
+ kind: 'field',
2592
+ en: 'Open the closed Copilot window again',
2593
+ bg: 'Отваряй отново затворения прозорец на Copilot',
2594
+ doesEn: 'How many times, for one message, the Edge window with the Copilot chat — closed while the message is at work, its X pressed by accident or Edge ending — is opened again on the same conversation and the work carried on there (3 by default); past it the message stops and waits for "Continue". 0: closing the window stops the message. The Stop button stops the work.',
2595
+ doesBg: 'Колко пъти за едно съобщение прозорецът на Edge с чата на Copilot — затворен, докато съобщението е в работа, с X по случайност или спрял Edge — се отваря отново на същия разговор и работата продължава там (по подразбиране 3); над това съобщението спира и чака „Продължи“. 0: затварянето на прозореца спира съобщението. Работата се спира с бутона „Стоп“.',
2596
+ },
2566
2597
  {
2567
2598
  key: 'exec.minApproaches',
2568
2599
  kind: 'field',
@@ -103,7 +103,11 @@ export function whyItStopped(c) {
103
103
  }
104
104
  if (c.how === 'stopped') {
105
105
  const where = c.interruption ? `\n\n${describeInterruption(c.interruption).replace(/when the runner stopped/g, 'when it was stopped')}\n\n` : ' ';
106
- return `It was stopped by the operator before it finished — not because anything failed. The files are as you left them.${where}`.trimEnd();
106
+ // The window closed under it (2026-11-13): said as that, in the runner's own words, not as the operator's Stop.
107
+ const first = /browser window/.test(c.stoppedBecause ?? '')
108
+ ? `It stopped because the browser window this conversation is in was closed (${c.stoppedBecause}) — not because anything failed.`
109
+ : 'It was stopped by the operator before it finished — not because anything failed.';
110
+ return `${first} The files are as you left them.${where}`.trimEnd();
107
111
  }
108
112
  const why = c.stoppedBecause ? ` (${c.stoppedBecause})` : '';
109
113
  // Out of rounds of fixing: something did say no, and the chat needs to hear it was not waved through.
@@ -20,12 +20,16 @@
20
20
  * running in this process — a check script — can call `setTransportFactory`.
21
21
  */
22
22
  import { CopilotTransport } from './copilotTransport.js';
23
+ import { keptWindow } from './keptWindow.js';
23
24
  export { ReplyTimeoutError, isReplyTimeout, WindowClosed, ChatLost } from './copilotTransport.js';
24
25
  const realChat = (opts) => new CopilotTransport(opts);
25
26
  let factory = realChat;
26
- /** A chat for these options: the real Copilot window, unless a check has put a scripted one in. */
27
+ /**
28
+ * A chat for these options: the real Copilot window, unless a check has put a scripted one in — either way kept for the
29
+ * work by the same rules (see keptWindow.ts).
30
+ */
27
31
  export function createTransport(opts) {
28
- return factory(opts);
32
+ return keptWindow(factory, opts);
29
33
  }
30
34
  /** For checks only: every chat opened from now on comes from `f`. `null` puts the real one back. */
31
35
  export function setTransportFactory(f) {