copilot-operator 0.1.50 → 0.1.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +587 -574
  2. package/dist/src/api/operator.controller.js +119 -1023
  3. package/dist/src/api/operator.service.js +346 -2553
  4. package/dist/src/config/schema.js +13 -0
  5. package/dist/src/orchestrator/hold.js +49 -0
  6. package/dist/src/orchestrator/leadRunner.js +559 -0
  7. package/dist/src/orchestrator/taskRunner.js +211 -39
  8. package/dist/src/plan/kerrigan.js +232 -0
  9. package/dist/src/plan/systemGuide.js +758 -3757
  10. package/dist/src/protocol/leadSchema.js +156 -0
  11. package/dist/src/protocol/parser.js +1 -1
  12. package/dist/src/session/chatNotice.js +191 -0
  13. package/dist/src/session/checkpoint.js +19 -0
  14. package/dist/src/session/compose.js +1 -1
  15. package/dist/src/session/store.js +17 -126
  16. package/dist/src/session/workspace.js +52 -5
  17. package/dist/src/transport/chatTransport.js +1 -1
  18. package/dist/src/transport/copilotTransport.js +135 -1
  19. package/dist/web/404.html +13 -16
  20. package/dist/web/_next/static/_1zhoDsMOPAH2xW702E5A/_buildManifest.js +1 -0
  21. package/dist/web/_next/static/chunks/134-ddd50a7fbb536ec8.js +1 -0
  22. package/dist/web/_next/static/chunks/163.dbd7d36584d0bb37.js +1 -0
  23. package/dist/web/_next/static/chunks/220.35531b39410e1a9f.js +1 -0
  24. package/dist/web/_next/static/chunks/548.71ac96c94136659b.js +1 -0
  25. package/dist/web/_next/static/chunks/584.6df695c5b86a75aa.js +1 -0
  26. package/dist/web/_next/static/chunks/67.9ed79e2fbfb56f26.js +1 -0
  27. package/dist/web/_next/static/chunks/714.1e2338736a70b9c7.js +1 -0
  28. package/dist/web/_next/static/chunks/747.d2c1249d736dc03b.js +1 -0
  29. package/dist/web/_next/static/chunks/77.a200abef0f5b4a7f.js +1 -0
  30. package/dist/web/_next/static/chunks/808-bc7d7eac6d823291.js +1 -0
  31. package/dist/web/_next/static/chunks/921-dc5538cd779c6432.js +1 -0
  32. package/dist/web/_next/static/chunks/app/defaults/page-edd7534ca9ecf366.js +1 -0
  33. package/dist/web/_next/static/chunks/app/layout-8f99a164d76897a0.js +1 -0
  34. package/dist/web/_next/static/chunks/app/page-4bed816eda370d0c.js +1 -0
  35. package/dist/web/_next/static/chunks/app/system/page-1cf9e75e76da59ed.js +1 -0
  36. package/dist/web/_next/static/chunks/webpack-77147e31d2125631.js +1 -0
  37. package/dist/web/_next/static/css/3bea264adc472bc8.css +1 -0
  38. package/dist/web/defaults.html +13 -16
  39. package/dist/web/defaults.txt +22 -23
  40. package/dist/web/index.html +13 -16
  41. package/dist/web/index.txt +22 -23
  42. package/dist/web/system.html +13 -16
  43. package/dist/web/system.txt +22 -23
  44. package/package.json +5 -23
  45. package/prompts/lead1.md +116 -0
  46. package/dist/src/api/saveToDesktop.js +0 -157
  47. package/dist/src/plan/brief.js +0 -2003
  48. package/dist/src/plan/changes.js +0 -217
  49. package/dist/src/plan/script.js +0 -1014
  50. package/dist/src/session/debugExport.js +0 -165
  51. package/dist/src/session/exportRecord.js +0 -277
  52. package/dist/src/session/metrics.js +0 -95
  53. package/dist/src/vcs/prepareFromRemote.js +0 -288
  54. package/dist/src/vcs/remoteAuth.js +0 -117
  55. package/dist/src/vcs/startChoice.js +0 -367
  56. package/dist/src/vcs/syncCommand.js +0 -97
  57. package/dist/web/_next/static/chunks/197-f7c33a0114fc3db3.js +0 -1
  58. package/dist/web/_next/static/chunks/499-751e0be9d4f86e2d.js +0 -1
  59. package/dist/web/_next/static/chunks/534-56c68930a1a3c10f.js +0 -1
  60. package/dist/web/_next/static/chunks/549-c32dd718a1809d4d.js +0 -1
  61. package/dist/web/_next/static/chunks/699-9d031f8c145a0465.js +0 -1
  62. package/dist/web/_next/static/chunks/867-0e5d0d5472bf185f.js +0 -1
  63. package/dist/web/_next/static/chunks/app/appearance/page-a18019cdc395de3d.js +0 -1
  64. package/dist/web/_next/static/chunks/app/defaults/page-614be29d185a2947.js +0 -1
  65. package/dist/web/_next/static/chunks/app/history/page-95bab4c1b1ff9339.js +0 -1
  66. package/dist/web/_next/static/chunks/app/import/page-8ef75fc08638e75f.js +0 -1
  67. package/dist/web/_next/static/chunks/app/layout-a1314921eeba8ad5.js +0 -1
  68. package/dist/web/_next/static/chunks/app/level1/page-dd3ebf37d29dce4f.js +0 -1
  69. package/dist/web/_next/static/chunks/app/page-4d8f0851fe672925.js +0 -1
  70. package/dist/web/_next/static/chunks/app/presets/page-93ab518db67e52a2.js +0 -1
  71. package/dist/web/_next/static/chunks/app/sessions/page-28376d2e4a9b4738.js +0 -1
  72. package/dist/web/_next/static/chunks/app/sessions/view/page-adb64f8ba3d8c06e.js +0 -1
  73. package/dist/web/_next/static/chunks/app/system/page-227a259e383ca2a0.js +0 -1
  74. package/dist/web/_next/static/chunks/webpack-0f31b926d9a9c5a4.js +0 -1
  75. package/dist/web/_next/static/css/4335e4ce269ba1ea.css +0 -1
  76. package/dist/web/_next/static/z74_FBfnnXW5IJCHTgTH2/_buildManifest.js +0 -1
  77. package/dist/web/appearance.html +0 -16
  78. package/dist/web/appearance.txt +0 -26
  79. package/dist/web/history.html +0 -16
  80. package/dist/web/history.txt +0 -26
  81. package/dist/web/import.html +0 -16
  82. package/dist/web/import.txt +0 -26
  83. package/dist/web/level1.html +0 -16
  84. package/dist/web/level1.txt +0 -26
  85. package/dist/web/presets.html +0 -19
  86. package/dist/web/presets.txt +0 -26
  87. package/dist/web/sessions/view.html +0 -16
  88. package/dist/web/sessions/view.txt +0 -26
  89. package/dist/web/sessions.html +0 -16
  90. package/dist/web/sessions.txt +0 -26
  91. package/prompts/organisation.bg.md +0 -43
  92. package/prompts/organisation.en.md +0 -43
  93. package/prompts/persona.bg.md +0 -17
  94. package/prompts/persona.en.md +0 -17
  95. package/prompts/work.bg.md +0 -19
  96. package/prompts/work.en.md +0 -19
  97. /package/dist/web/_next/static/{z74_FBfnnXW5IJCHTgTH2 → _1zhoDsMOPAH2xW702E5A}/_ssgManifest.js +0 -0
@@ -14,24 +14,25 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
14
14
  */
15
15
  import { pageModelFor, sameModel } from '../transport/modelMatch.js';
16
16
  import { Injectable } from '@nestjs/common';
17
- import { readFile, readdir } from 'node:fs/promises';
18
17
  import { existsSync } from 'node:fs';
19
18
  import { join, resolve } from 'node:path';
20
19
  import { installLayout } from '../config/layout.js';
21
- import { SessionStore, DEFAULT_VCS, DEFAULT_REVIEW, applyDefaultProject, applyTaskPatch } from '../session/store.js';
20
+ import { SessionStore, DEFAULT_VCS, DEFAULT_REVIEW } from '../session/store.js';
22
21
  import { EventBus } from '../session/events.js';
23
- import { freshRetriesOfLatestRun, isContinuable, MAX_INSTRUCTION_CHARS, newId } from '../session/model.js';
24
- import { runSession, openBrowser, queuedToRun } from '../orchestrator/taskRunner.js';
25
- import { buildExport } from '../session/exportRecord.js';
26
- import { buildDebugExport } from '../session/debugExport.js';
27
- import { buildPlanExport, buildDomainExport, buildBotExport, buildBundleExport, exportFileName, exportMachine, runScope, taskAtAttempt, taskInRun, withTask, writeAttemptRecord } from '../session/exports.js';
22
+ import { MAX_INSTRUCTION_CHARS, newId } from '../session/model.js';
23
+ import { runSession, queuedToRun, failedWhileOpening } from '../orchestrator/taskRunner.js';
24
+ import { Hold } from '../orchestrator/hold.js';
25
+ import { exportFileName, exportMachine, writeAttemptRecord } from '../session/exports.js';
28
26
  import { suggestRunName } from '../session/runName.js';
29
27
  import { buildStory } from '../session/story.js';
30
28
  import { buildTaskExchange } from '../session/taskExchange.js';
29
+ import { chatNotice } from '../session/chatNotice.js';
30
+ import { kerriganFileName, kerriganPersona } from '../plan/kerrigan.js';
31
31
  import { workspaceCommit, workspaceGit, workspaceGitVersions } from '../session/workspaceGit.js';
32
32
  import { chatCode } from '../transport/chatSession.js';
33
- import { checkPlan } from '../plan/schema.js';
34
- import { planBrief } from '../plan/brief.js';
33
+ /** The folders the operator works in: the default new sessions start on, and the rest by name. */
34
+ /** The longest level 2 a project may have: Kerrigan carries each one whole. */
35
+ export const MAX_PROJECT_LEVEL2 = 8000;
35
36
  /**
36
37
  * A settings file or a policy lock that cannot be used: answered 409 with its own message on every route
37
38
  * (see `server.ts`), so a start passes it on rather than answering it as a start that did not happen.
@@ -48,61 +49,36 @@ function sameFolder(a, b) {
48
49
  const norm = (p) => p.trim().replace(/[\\/]+$/, '').replace(/\//g, '\\').toLowerCase();
49
50
  return a.trim() !== '' && norm(a) === norm(b);
50
51
  }
51
- import { composeLevel2, composePrompt, importPlan, personaBlock, plannedSessionSignature, taskSignature } from '../plan/importPlan.js';
52
- import { checkChanges, kerriganReport } from '../plan/changes.js';
53
- import { workspaceFile, workspaceFiles, workspaceInfo } from '../session/workspace.js';
52
+ import { saveWorkspaceFile, workspaceFile, workspaceFiles, workspaceInfo } from '../session/workspace.js';
54
53
  import { restoreCheckpoint } from '../session/checkpoint.js';
55
54
  import { readInterruption } from '../session/interruption.js';
56
- import { baseRefOf, branchAt, commitInterrupted, nextAttemptBranch, repoDirOf, trackedRepoOf, vcsPreflight, restorePoint, restorePreview, restoreToBase, revertTaskWork, undoThisPreview, sessionBranches, sessionBranchName } from '../vcs/taskVcs.js';
57
- import { branchExists, changedFilesBetween, commitsBetween, fileAt, freeBranchName, git, gitAvailable, localBranches, looksLikeRepo, plannedBranchName, repoUnusableReason } from '../vcs/git.js';
55
+ import { baseRefOf, commitInterrupted, nextAttemptBranch, repoDirOf, trackedRepoOf, sessionBranchName } from '../vcs/taskVcs.js';
56
+ import { changedFilesBetween, fileAt, git, repoUnusableReason } from '../vcs/git.js';
58
57
  import { makeAuthorizer } from '../exec/authorizer.js';
59
58
  import { pickFolder } from './folderPicker.js';
60
59
  import { findEdgeUsingProfile } from '../transport/profileLock.js';
61
- import { assessIsolation, readIsolationSignals, unattendedIsolationRefusal } from '../exec/isolation.js';
60
+ import { assessIsolation, readIsolationSignals } from '../exec/isolation.js';
62
61
  import { unattendedPrecondition } from '../exec/policy.js';
63
62
  import { createTransport } from '../transport/chatTransport.js';
64
63
  import { composeHandoff } from '../session/handoff.js';
65
- import { planSync } from '../vcs/syncCommand.js';
66
- import { planPrepare, prepareFromRemote } from '../vcs/prepareFromRemote.js';
67
- import { askpassProgram } from '../vcs/remoteAuth.js';
68
64
  import { appendRunLog, appendSessionLog, readRunLog } from '../session/runLog.js';
69
- import { applyStartChoice, fetchForStart, startOptions, withChoice } from '../vcs/startChoice.js';
70
65
  import { StartFailures, failureReport, refOf } from '../session/startFailure.js';
71
66
  import { formatTerminal, localTime, terminalLines, terminalLogFile } from '../log/terminal.js';
72
67
  import { redactSecrets } from '../exec/redaction.js';
73
68
  import { workingDirFor, isWorkingDirProblem } from '../exec/workDir.js';
74
- import { contractConflictsWithFixes, contractFixPatch, describeContractChange } from '../orchestrator/contract.js';
69
+ import { contractConflictsWithFixes } from '../orchestrator/contract.js';
75
70
  import { checkRefusalForOperator, lineRefusal } from '../orchestrator/taskRunner.js';
76
71
  import { preferredShell } from '../exec/shells.js';
77
72
  import { sessionRoots } from '../exec/confinement.js';
78
- import { dirtyPolicy, takeSnapshot } from '../vcs/snapshot.js';
79
- import { runVcsPreflight, runVcsPrepare } from '../vcs/runPreflight.js';
73
+ import { dirtyPolicy } from '../vcs/snapshot.js';
74
+ import { runVcsPreflight } from '../vcs/runPreflight.js';
80
75
  import { inputSettings, normalisePatterns } from '../vcs/inputs.js';
81
76
  import { coveredByArtifacts } from '../vcs/artifacts.js';
82
77
  import { botVersion } from '../config/version.js';
83
- import { computeMetrics } from '../session/metrics.js';
84
78
  import { resolveDesktopDir, desktopIsSynced } from '../context/desktopDir.js';
85
- import { saveAndReveal } from './saveToDesktop.js';
86
79
  import { settingsOf, SettingsUnusableError } from './settings.js';
87
80
  import { PolicyLockUnusableError } from '../config/lockedPolicy.js';
88
81
  import { chatDenyPatterns } from '../config/schema.js';
89
- /** Why a session set aside on the Sessions page does not run: one sentence for every start that refuses it. */
90
- /** The id of the task a change names by id, number or title; see `plan/changes.ts`. */
91
- function checkTaskRef(session, ref) {
92
- if (typeof ref === 'number' || /^\d+$/.test(String(ref)))
93
- return session.tasks[Number(ref) - 1]?.id;
94
- return (session.tasks.find((t) => t.id === ref) ?? session.tasks.find((t) => t.title === ref) ?? session.tasks.find((t) => t.title.toLowerCase() === String(ref).toLowerCase()))?.id;
95
- }
96
- /** Why this task cannot be undone now, or null: only a task that ran and is not running or queued. */
97
- function undoRefusalOf(task) {
98
- if (task.status === 'queued')
99
- return 'This task is queued and has not run since; there is nothing of it to undo.';
100
- if (task.status === 'running' || task.status === 'waiting-approval')
101
- return 'This task is running. Stop it first.';
102
- if (!task.startedAt)
103
- return 'This task has not run; there is nothing of it to undo.';
104
- return null;
105
- }
106
82
  const INACTIVE_REASON = 'the session is inactive; make it active on the Sessions page to run it';
107
83
  /**
108
84
  * Why the browser cannot be had now, said in terms of what was pressed. The sentences a start, a
@@ -120,27 +96,17 @@ function browserRefusal(held, ask) {
120
96
  }
121
97
  if (ask.kind === 'login')
122
98
  return loginWhileBusy;
123
- if (held.kind === 'batch') {
124
- if (ask.kind === 'models')
125
- return modelsWhileRunning;
126
- return ask.kind === 'batch' ? 'a batch is already running' : 'a batch of sessions is running';
127
- }
128
99
  if (held.kind === 'models') {
129
100
  return ask.kind === 'models'
130
101
  ? 'The model list is already being read.'
131
102
  : 'the model list is being read from the chat, which has the browser; start this once it has finished';
132
103
  }
133
- // A session running on its own.
104
+ // A conversation running.
134
105
  if (ask.kind === 'models')
135
106
  return modelsWhileRunning;
136
- if (ask.kind === 'run') {
137
- return ask.sessionId === held.sessionId
138
- ? 'already running'
139
- : 'another session is running, and the browser takes one run at a time; start this one once it has finished';
140
- }
141
- return ask.sessionIds.includes(held.sessionId)
142
- ? 'one of the selected sessions is already running on its own'
143
- : 'a session is running on its own, and the browser takes one run at a time; start the batch once it has finished';
107
+ return ask.sessionId === held.sessionId
108
+ ? 'already running'
109
+ : 'another conversation is running, and the browser takes one run at a time; start this one once it has finished';
144
110
  }
145
111
  /** A folder as compared: absolute, forward slashes, no trailing slash, and case folded as Windows does. */
146
112
  function normaliseDir(dir) {
@@ -148,84 +114,10 @@ function normaliseDir(dir) {
148
114
  return '';
149
115
  return resolve(dir.trim()).replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
150
116
  }
151
- /** The repository a planned session will work in, read the way `repoDirOf` reads an imported one. */
152
- function plannedRepoDir(session) {
153
- return session.vcs?.repoDir?.trim() || session.projectDir?.trim() || session.mirror?.rootDir?.trim() || '';
154
- }
155
- /**
156
- * The branches a planned session will make by name when it runs, as `prepareForTask` names them.
157
- *
158
- * None with version control off, and none when it carries on an existing branch, which makes
159
- * nothing. In per-session mode the one `branchName`; in per-task mode the branch each task names,
160
- * since `branchName` is ignored there. A branch named for the session's id is not known before the
161
- * import, and is not one a plan can ask to carry on.
162
- */
163
- function branchesMadeBy(session) {
164
- const vcs = session.vcs;
165
- if (!vcs || vcs.enabled === false || vcs.startFrom === 'existing-branch' || vcs.existingBranch?.trim())
166
- return [];
167
- const prefix = vcs.branchPrefix?.trim() || 'cop/';
168
- if (vcs.branchMode === 'per-session')
169
- return vcs.branchName?.trim() ? [plannedBranchName(vcs.branchName, prefix)] : [];
170
- return session.tasks.flatMap((t) => (t.vcs?.branch?.trim() ? [plannedBranchName(t.vcs.branch, prefix)] : []));
171
- }
172
- /**
173
- * The one restore each repository gets when a run starts again from a task: the rule, in one place,
174
- * for the preview and for the restore itself, which used to keep a copy each and drifted apart.
175
- *
176
- * One per repository, keyed on the folder as compared rather than on the path as written or on the
177
- * session: three sessions working in one repository must not take it back three times to three
178
- * different commits. The earliest affected task that ran is the one that decides, because that is
179
- * the state the whole re-run starts from.
180
- *
181
- * A repository whose affected tasks never ran has nothing to go back to: the run never touched it.
182
- * Taking "no base commit recorded" as a refusal blocked "run again from here" for every plan whose
183
- * later sessions had not started yet — which is the usual shape of a run that stopped in the middle.
184
- *
185
- * A session that carries on an existing branch cannot be taken back: its run checks that branch out
186
- * again before the first task, so a restore branch would be left the moment it was made, and going
187
- * back on the branch itself would take a reset, which this tool never does. That holds for every
188
- * session of the repository the run reached, not only the one that decides where it goes back to:
189
- * a later one carrying on a branch would run its tasks again on top of what they did the first
190
- * time, which is not "the code goes back first" either. So the repository's restore carries the
191
- * problem of the first such session, and the preview and the restart refuse before anything moves.
192
- */
193
- function restoreTargets(tasks) {
194
- const byRepo = new Map();
195
- for (const { session, task } of tasks) {
196
- if (!session.vcs?.enabled || !task.startedAt)
197
- continue;
198
- const dir = repoDirOf(session);
199
- const key = normaliseDir(dir);
200
- if (!key)
201
- continue;
202
- const target = byRepo.get(key) ?? { dir, session, task };
203
- byRepo.set(key, target);
204
- const existing = session.vcs.startFrom === 'existing-branch' ? (session.vcs.existingBranch ?? '').trim() : '';
205
- if (existing && !target.problem) {
206
- target.problem =
207
- `"${session.name}" carries on the existing branch ${existing}, and its run checks that branch out again, so the code ` +
208
- `would not stay back; going back on ${existing} itself would take a reset, which this tool never does. ` +
209
- `Queue its tasks again with "Run again" on each, which carries on ${existing} as it is, or move that branch yourself first.`;
210
- }
211
- }
212
- return [...byRepo.values()];
213
- }
214
117
  /** Whether two folders, as `normaliseDir` gives them, are one folder or one is inside the other. */
215
118
  function overlaps(a, b) {
216
119
  return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
217
120
  }
218
- /**
219
- * The reason a restart stopped, with what it had already done by then.
220
- *
221
- * A repository taken back and tasks queued again stay so when a later step refuses — nothing here
222
- * undoes them — and the reason is the one thing the page shows. Said only in the result, they were
223
- * left for the operator to find in git and in the queue.
224
- */
225
- function afterMoves(reason, restored, requeued) {
226
- const done = [...restored.map((r) => `taken back ${r}`), ...(requeued > 0 ? [`${requeued} task(s) queued again`] : [])];
227
- return done.length > 0 ? `${reason} Already done, and left as it is: ${done.join('; ')}.` : reason;
228
- }
229
121
  let OperatorService = class OperatorService {
230
122
  /** Where this install keeps its prompts and its records. See `config/layout.ts`. */
231
123
  layout = installLayout();
@@ -238,8 +130,15 @@ let OperatorService = class OperatorService {
238
130
  startFailures = new StartFailures();
239
131
  running = new Map();
240
132
  waiting = new Map();
241
- /** The batch in progress, or the last one that finished. At most one ever exists. */
242
- batch = null;
133
+ /**
134
+ * The workers of the two-chat mode, by the session of the lead they work for (2026-10-20). A worker's steps and cards
135
+ * carry its own session's id, while the run, its mode and its Stop are the lead's: they are looked up through this.
136
+ */
137
+ workerLeads = new Map();
138
+ /** The session whose run a session's steps belong to: its own, or its lead's for a worker. */
139
+ runKey(sessionId) {
140
+ return this.running.has(sessionId) ? sessionId : (this.workerLeads.get(sessionId) ?? sessionId);
141
+ }
243
142
  ready = null;
244
143
  /**
245
144
  * What has the browser now: one session's run, a batch, or a read of the model list.
@@ -256,6 +155,17 @@ let OperatorService = class OperatorService {
256
155
  * refused. See `claimBrowser`.
257
156
  */
258
157
  browser = null;
158
+ /**
159
+ * The workbench chat's window, left open when the work on a message has ended (2026-10-19: "when the work on one
160
+ * chat message is done, the browser is not to close, so that if the work goes on with another message it is open
161
+ * already"). Given to the chat's next message, in this conversation or a new one, so it does not open again.
162
+ *
163
+ * Not a claim on the browser (`browser`): nothing is using it. Whatever takes the browser next and is not a message
164
+ * of the chat — a session's run, a batch, signing in, reading the models — closes it first (`closeChatWindow`),
165
+ * since the profile takes one window. The operator closes it with its X whenever they like; that is found when it
166
+ * is next wanted (`keptChatWindow`), and it is closed when the program is.
167
+ */
168
+ chatWindow = null;
259
169
  /**
260
170
  * One-time startup work, run lazily on the first request that needs the store.
261
171
  *
@@ -327,68 +237,11 @@ let OperatorService = class OperatorService {
327
237
  await this.init();
328
238
  return await this.store.getLevel1();
329
239
  }
330
- async setLevel1(content) {
331
- await this.init();
332
- await this.store.setLevel1(content);
333
- }
334
- async resetLevel1() {
335
- await this.init();
336
- await this.store.resetLevel1();
337
- return await this.store.getLevel1();
338
- }
339
- // --- the organisation's part of the plan persona -------------------------------------
340
- async getContext(kind, lang) {
341
- await this.init();
342
- return await this.store.getContext(kind, lang === 'bg' ? 'bg' : 'en');
343
- }
344
- async setContext(kind, content) {
345
- await this.init();
346
- await this.store.setContext(kind, content);
347
- }
348
- async resetContext(kind, lang) {
349
- await this.init();
350
- await this.store.resetContext(kind);
351
- return await this.store.getContext(kind, lang === 'bg' ? 'bg' : 'en');
352
- }
353
- // --- level 2 presets ------------------------------------------------------------------
354
- async listPresets() {
355
- await this.init();
356
- return await this.store.listPresets();
357
- }
358
- async savePreset(name, content) {
359
- await this.init();
360
- return await this.store.savePreset(name, content);
361
- }
362
- async deletePreset(name) {
363
- await this.init();
364
- await this.store.deletePreset(name);
365
- }
366
- // --- named personas for the import page -----------------------------------------------
367
- async listPersonas() {
368
- await this.init();
369
- return await this.store.listPersonas();
370
- }
371
- async savePersona(name, content) {
372
- await this.init();
373
- return await this.store.savePersona(name, content);
374
- }
375
- async deletePersona(name) {
376
- await this.init();
377
- await this.store.deletePersona(name);
378
- }
379
240
  // --- sessions and tasks ---------------------------------------------------------------
380
- /** The operator's order for the sessions list, top to bottom. See `SessionStore.reorderSessions`. */
381
- async reorderSessions(ids) {
382
- await this.init();
383
- if (!Array.isArray(ids) || ids.some((x) => typeof x !== 'string'))
384
- throw new Error('ids must be a list of session ids.');
385
- await this.store.reorderSessions(ids);
386
- return await this.listSessions();
387
- }
388
241
  async listSessions() {
389
242
  await this.init();
390
243
  const all = await this.store.listSessions();
391
- return all.map((s) => ({ ...s, running: this.running.has(s.id) }));
244
+ return all.map((s) => ({ ...s, running: this.running.has(s.id), paused: this.running.get(s.id)?.hold.held ?? false }));
392
245
  }
393
246
  async getSession(id) {
394
247
  await this.init();
@@ -396,42 +249,14 @@ let OperatorService = class OperatorService {
396
249
  if (!s)
397
250
  return null;
398
251
  const pending = [...this.waiting.values()].filter((w) => w.approval.sessionId === id).map((w) => w.approval);
399
- return { ...s, running: this.running.has(id), pending, runMode: this.running.get(id)?.mode };
400
- }
401
- async createSession(name, folder) {
402
- await this.init();
403
- // Read before the session is made: a settings file that cannot be read refuses the request,
404
- // and a refusal must leave nothing behind, or each retry adds a session with no project.
405
- const cfg = await this.settings.load();
406
- const session = await this.store.createSession(name, folder ?? '');
407
- /*
408
- * The models are not written onto a new session. A session with no model of its own uses the
409
- * one chosen in Settings at the time it runs (see `effectiveModels` in taskRunner.ts), so
410
- * choosing a model there reaches every such session, the ones created before it included.
411
- * It used to be copied here, which meant a model chosen after an import reached nothing.
412
- */
413
- const projectDir = (cfg.project?.rootDir ?? '').trim();
414
- return await this.store.updateSession(session.id, (s) => {
415
- /*
416
- * A folder given here is the session's repository too, in the shape a session made on the
417
- * Project page's folder has: both fields, one folder. Left empty, every reader that follows
418
- * `repoDirOf` found the folder, but the review read `vcs.repoDir` itself, and was told there
419
- * was no repository and no changed files for work committed in that folder. The review asks
420
- * `trackedRepoOf` now, so a session saved with `repoDir` empty is read right as well; this
421
- * keeps the record saying what the session works in.
422
- */
423
- if (s.projectDir.trim() && s.vcs && !s.vcs.repoDir.trim())
424
- s.vcs.repoDir = s.projectDir;
425
- // The same rule an import applies, for a session given no folder; see `applyDefaultProject`.
426
- applyDefaultProject(s, projectDir);
427
- });
252
+ return { ...s, running: this.running.has(id), paused: this.running.get(id)?.hold.held ?? false, pending, runMode: this.running.get(id)?.mode };
428
253
  }
429
254
  async updateSession(id, patch) {
430
255
  await this.init();
431
256
  if (patch.active !== undefined && this.running.has(id)) {
432
257
  throw new Error('This session is running; its status can be changed once it has stopped.');
433
258
  }
434
- return await this.store.updateSession(id, (s) => {
259
+ const updated = await this.store.updateSession(id, (s) => {
435
260
  const before = { model: s.model, manualModel: s.manualModel };
436
261
  if (patch.name !== undefined)
437
262
  s.name = patch.name.trim() || s.name;
@@ -457,6 +282,12 @@ let OperatorService = class OperatorService {
457
282
  if ((patch.model !== undefined || typeof patch.manualModel === 'boolean') && (s.model !== before.model || !!s.manualModel !== !!before.manualModel)) {
458
283
  delete s.modelByHand;
459
284
  }
285
+ // The worker's model (two chats), kept on the lead's session and given to its worker below.
286
+ if (s.lead && (patch.workerModel !== undefined || typeof patch.workerManualModel === 'boolean')) {
287
+ const manual = typeof patch.workerManualModel === 'boolean' ? patch.workerManualModel : !!s.lead.workerManualModel;
288
+ const model = patch.workerModel !== undefined ? patch.workerModel.trim() : (s.lead.workerModel ?? '');
289
+ s.lead = { ...s.lead, workerManualModel: manual || undefined, workerModel: manual ? undefined : model || undefined };
290
+ }
460
291
  // The same for the group: clearing it gives this session its conversation back. It does
461
292
  // not move the conversation it is already in; that history is where it is.
462
293
  if (patch.conversationGroup !== undefined)
@@ -558,53 +389,19 @@ let OperatorService = class OperatorService {
558
389
  s.vcs = merged;
559
390
  }
560
391
  });
561
- }
562
- async deleteSession(id) {
563
- await this.init();
564
- if (this.running.has(id))
565
- throw new Error('Stop the session before deleting it.');
566
- await this.store.deleteSession(id);
567
- }
568
- async addTask(sessionId, input) {
569
- await this.init();
570
- if (!input.prompt?.trim())
571
- throw new Error('A task needs a prompt.');
572
- return await this.store.addTask(sessionId, input);
573
- }
574
- /**
575
- * Edits a queued task, including the names it carries into git.
576
- *
577
- * Everything an imported plan can set, the form can change: a task that arrived as JSON is
578
- * the same object as one typed in by hand, and the moment the two diverge is the moment an
579
- * import becomes a thing you cannot correct without editing a file.
580
- */
581
- async updateTask(sessionId, taskId, patch) {
582
- await this.init();
583
- let before;
584
- const task = await this.store.updateTask(sessionId, taskId, (t) => {
585
- if (t.status !== 'queued')
586
- throw new Error('Only a queued task can be edited.');
587
- before = structuredClone(t);
588
- applyTaskPatch(t, patch);
589
- });
590
- /*
591
- * On record with the operator's other actions: a check or the prompt changed after the import is a
592
- * different contract from the plan's, and the export showed only the new one (live run 2026-10-04).
593
- */
594
- const changed = Object.keys(patch).filter((k) => JSON.stringify(before?.[k]) !== JSON.stringify(task[k]));
595
- if (changed.length > 0) {
596
- const cfg = await this.settings.load();
597
- await appendSessionLog(cfg.resolved.runsDir, sessionId, {
598
- type: 'task-edited',
599
- message: `"${task.title}" edited while queued: ${changed.join(', ')} changed`,
600
- data: { taskId, changed, before: Object.fromEntries(changed.map((k) => [k, before?.[k] ?? null])) },
601
- }).catch(() => undefined);
392
+ // The worker's model (two chats): given to the worker's session too, which asks again for one chosen by hand.
393
+ const workerId = updated.lead?.workerSessionId;
394
+ if (workerId && (patch.workerModel !== undefined || typeof patch.workerManualModel === 'boolean')) {
395
+ await this.store
396
+ .updateSession(workerId, (w) => {
397
+ w.manualModel = updated.lead?.workerManualModel ? true : undefined;
398
+ w.model = updated.lead?.workerManualModel ? undefined : updated.lead?.workerModel;
399
+ w.modelSource = w.model ? 'operator' : undefined;
400
+ delete w.modelByHand;
401
+ })
402
+ .catch(() => undefined);
602
403
  }
603
- return task;
604
- }
605
- async deleteTask(sessionId, taskId) {
606
- await this.init();
607
- await this.store.deleteTask(sessionId, taskId);
404
+ return updated;
608
405
  }
609
406
  /**
610
407
  * A note to the chat about a task (2026-10-14): queued, running or waiting, it goes out with the task's
@@ -619,116 +416,6 @@ let OperatorService = class OperatorService {
619
416
  data: { length: text.trim().length, running } });
620
417
  return task;
621
418
  }
622
- /** The operator accepts a task as done that did not end so (2026-10-14). */
623
- async acceptTask(sessionId, taskId, note) {
624
- await this.init();
625
- if (this.running.has(sessionId)) {
626
- const now = (await this.store.getSession(sessionId))?.tasks.find((t) => t.id === taskId);
627
- if (now && ['running', 'waiting-approval'].includes(now.status))
628
- throw new Error('This task is running. Stop it first.');
629
- }
630
- const task = await this.store.acceptTask(sessionId, taskId, note);
631
- const message = `"${task.title}" accepted as done by the operator (it had ended ${task.accepted?.was})${task.accepted?.note ? `: ${task.accepted.note}` : ''}`;
632
- this.bus.publish({ sessionId, taskId, type: 'task-accepted', level: 'info', message, data: { was: task.accepted?.was } });
633
- const cfg = await this.settings.load();
634
- await appendSessionLog(cfg.resolved.runsDir, sessionId, { type: 'accept', message, data: { taskId, was: task.accepted?.was } }).catch(() => undefined);
635
- return task;
636
- }
637
- /**
638
- * Puts a finished task back in the queue, keeping the record of what it already did.
639
- *
640
- * An optional patch is how a finished task is edited: the attempt that ran is archived with
641
- * the text it ran with, and only then is the new text applied. Editing in place would leave
642
- * the old attempt's summary sitting under a question that was never asked.
643
- */
644
- /** "Continue" on a task that stopped before it finished — a limit from the settings, the bot stopping, the operator: same chat, same branch, fresh count. */
645
- async continueTask(sessionId, taskId,
646
- /**
647
- * The operator's new prompt: what carries a task that failed on from where it got to, in its chat and
648
- * on its branch (2026-10-13); optional with any other Continue. See `TaskContinuation.instruction`.
649
- */
650
- instruction) {
651
- await this.init();
652
- /*
653
- * An attempt the operator stopped: which of its last steps ran, and what they printed, read from its
654
- * run folder, so "Continue" can tell the chat. Without it the chat was told only that it had been
655
- * stopped, and ran its inspection steps again (live run 2026-10-03).
656
- */
657
- const before = (await this.store.getSession(sessionId))?.tasks.find((t) => t.id === taskId);
658
- const cfg = await this.settings.load();
659
- const stoppedAt = before?.status === 'aborted' && !before.interruption && before.runId ? await readInterruption(join(cfg.resolved.runsDir, before.runId)).catch(() => null) : null;
660
- const task = await this.store.continueTask(sessionId, taskId, stoppedAt, instruction);
661
- const after = task.continuing?.how === 'failed' ? ` after it ended ${task.continuing.ended?.status ?? 'failed'}` : '';
662
- const withPrompt = task.continuing?.instruction ? ', with a new prompt' : '';
663
- await appendSessionLog(cfg.resolved.runsDir, sessionId, {
664
- type: 'continue',
665
- message: `"${task.title}" queued to continue as attempt ${task.attempt ?? 1}${after}${withPrompt}`,
666
- data: { taskId, attempt: task.attempt, ...(task.continuing?.instruction ? { instruction: task.continuing.instruction } : {}) },
667
- }).catch(() => undefined);
668
- this.bus.publish({
669
- sessionId,
670
- taskId,
671
- type: 'task-requeued',
672
- level: 'info',
673
- message: `"${task.title}" is queued to continue where it ${after ? 'ended' : 'stopped'}${after}${withPrompt} (attempt ${task.attempt ?? 1})`,
674
- data: { attempt: task.attempt, continuing: true, ...(task.continuing?.instruction ? { instruction: true } : {}) },
675
- });
676
- return task;
677
- }
678
- async rerunTask(sessionId, taskId, patch = {},
679
- /**
680
- * A new prompt for a task that ended done builds on what it did: the next attempt works on
681
- * that attempt's branch. Only for a done task — a failed attempt's work is what is being
682
- * replaced, so a re-run of one starts again from where the task first started.
683
- */
684
- opts = {}) {
685
- await this.init();
686
- const before = (await this.store.getSession(sessionId))?.tasks.find((t) => t.id === taskId);
687
- const buildsOn = opts.buildOnFinished && before?.status === 'done' ? { fromAttempt: before.attempt ?? 1 } : undefined;
688
- /*
689
- * A new prompt is a new change: the plan's commit subject was written for the old one, and two
690
- * different commits went out under it (live run 2026-10-03). Dropped unless the edit names one.
691
- */
692
- // A correction added to the old prompt is not a new change, and keeps the subject (live run 2026-10-04).
693
- const appended = !!before && !!patch.prompt && patch.prompt.trim().startsWith(before.prompt.trim().split('\n### Expected result')[0].trim());
694
- if (patch.prompt?.trim() && before && patch.prompt.trim() !== before.prompt.trim() && !appended && before.vcsPlan?.commitMessage && !patch.vcsPlan?.commitMessage) {
695
- patch = { ...patch, vcsPlan: { ...before.vcsPlan, ...(patch.vcsPlan ?? {}), commitMessage: undefined } };
696
- }
697
- const task = await this.store.rerunTask(sessionId, taskId, patch, undefined, buildsOn);
698
- {
699
- const cfg = await this.settings.load();
700
- const changed = Object.keys(patch).filter((k) => patch[k] !== undefined);
701
- await appendSessionLog(cfg.resolved.runsDir, sessionId, { type: 'rerun', message: `"${task.title}" queued again as attempt ${task.attempt ?? 1}${buildsOn ? `, building on attempt ${buildsOn.fromAttempt}` : ''}${changed.length > 0 ? `, with ${changed.join(', ')} changed` : ''}`, data: { taskId, attempt: task.attempt, changed, ...(buildsOn ? { buildsOn } : {}) } }).catch(() => undefined);
702
- }
703
- this.bus.publish({
704
- sessionId,
705
- taskId,
706
- type: 'task-requeued',
707
- level: 'info',
708
- message: buildsOn
709
- ? `"${task.title}" is queued again with a new prompt that builds on attempt ${buildsOn.fromAttempt} (attempt ${task.attempt ?? 1})`
710
- : `"${task.title}" is queued again (attempt ${task.attempt ?? 1})`,
711
- data: { attempt: task.attempt, ...(buildsOn ? { buildsOn } : {}) },
712
- });
713
- return task;
714
- }
715
- /**
716
- * The consolidated text log of a task, or null when it has not produced one.
717
- *
718
- * `runId` asks for one particular attempt. It is checked against the run ids this task
719
- * actually owns, so the parameter cannot be used to read another task's folder, or any
720
- * other folder on the machine.
721
- */
722
- async taskLog(sessionId, taskId, runId) {
723
- const cfg = await this.settings.load();
724
- const s = await this.store.getSession(sessionId);
725
- const t = s?.tasks.find((x) => x.id === taskId);
726
- const chosen = resolveRunId(t, runId);
727
- if (!chosen)
728
- return null;
729
- const path = join(cfg.resolved.runsDir, chosen, 'task-log.txt');
730
- return existsSync(path) ? await readFile(path, 'utf8') : null;
731
- }
732
419
  /**
733
420
  * The story of one attempt, assembled from its run folder: what was sent, what the chat
734
421
  * answered, what ran with its output, the review rounds, how it ended. Read while it runs
@@ -821,173 +508,6 @@ let OperatorService = class OperatorService {
821
508
  return { problem: 'The session has no repository folder set.' };
822
509
  return { dir, base: vcs.baseCommit, commit: vcs.commit, branch: vcs.branch };
823
510
  }
824
- async taskFiles(sessionId, taskId, runId) {
825
- const cfg = await this.settings.load();
826
- const s = await this.store.getSession(sessionId);
827
- const t = s?.tasks.find((x) => x.id === taskId);
828
- const empty = { reports: [], artifacts: [], replies: [] };
829
- const chosen = resolveRunId(t, runId);
830
- if (!chosen)
831
- return empty;
832
- const base = join(cfg.resolved.runsDir, chosen);
833
- const ls = async (sub) => (await readdir(join(base, sub)).catch(() => [])).filter((n) => !n.startsWith('_')).sort();
834
- return { reports: await ls('reports'), artifacts: await ls('artifacts'), replies: await ls('replies') };
835
- }
836
- async taskFile(sessionId, taskId, kind, name, runId) {
837
- if (name.includes('..') || name.includes('/') || name.includes('\\'))
838
- return null;
839
- const cfg = await this.settings.load();
840
- const s = await this.store.getSession(sessionId);
841
- const t = s?.tasks.find((x) => x.id === taskId);
842
- const chosen = resolveRunId(t, runId);
843
- if (!chosen)
844
- return null;
845
- const path = join(cfg.resolved.runsDir, chosen, kind, name);
846
- return existsSync(path) ? await readFile(path, 'utf8') : null;
847
- }
848
- /**
849
- * The same log, written to the Desktop and shown in Explorer instead of to the browser.
850
- *
851
- * What the operator does with a log is hand it to the chat that orchestrates the effort, so
852
- * the useful end of the journey is a file under the cursor, not a page in a tab. The reading
853
- * is delegated to `taskLog` rather than repeated here: that method already decides which run
854
- * folder this task is allowed to open, and a second copy of that decision is a second place
855
- * for it to be got wrong.
856
- */
857
- async saveTaskLog(sessionId, taskId, runId) {
858
- const text = await this.taskLog(sessionId, taskId, runId);
859
- if (text === null)
860
- return null;
861
- return await saveAndReveal(text, await this.namingFor(sessionId, taskId, runId));
862
- }
863
- /** One of a task's own files, saved and revealed the same way. They are logs by another name. */
864
- async saveTaskFile(sessionId, taskId, kind, name, runId) {
865
- const text = await this.taskFile(sessionId, taskId, kind, name, runId);
866
- if (text === null)
867
- return null;
868
- return await saveAndReveal(text, { ...(await this.namingFor(sessionId, taskId, runId)), file: name });
869
- }
870
- /**
871
- * What a saved file is named after.
872
- *
873
- * An earlier attempt is named from its own snapshot rather than from the task as it stands
874
- * now: a task can be edited between attempts, and a file called after today's title would
875
- * claim the old log answered a question it was never asked.
876
- */
877
- async namingFor(sessionId, taskId, runId) {
878
- const s = await this.store.getSession(sessionId);
879
- const t = s?.tasks.find((x) => x.id === taskId);
880
- const chosen = resolveRunId(t, runId);
881
- const earlier = chosen && t && chosen !== t.runId ? (t.attempts ?? []).findIndex((a) => a.runId === chosen) : -1;
882
- const attempt = earlier >= 0 ? earlier + 1 : (t?.attempt ?? 1);
883
- return {
884
- session: s?.name ?? sessionId,
885
- task: (earlier >= 0 ? t?.attempts?.[earlier]?.title : t?.title) ?? taskId,
886
- // A task that has only ever run once has nothing to be told apart from.
887
- attempt: attempt > 1 ? attempt : undefined,
888
- };
889
- }
890
- /**
891
- * The record of selected tasks as one downloadable document.
892
- *
893
- * `taskIds` empty means every task of the session that has actually run. A queued task has
894
- * nothing to say yet, and silently including it would put an empty section in a document
895
- * someone is about to send to a colleague.
896
- */
897
- async exportTasks(sessionId, taskIds, variant) {
898
- await this.init();
899
- const session = await this.store.getSession(sessionId);
900
- if (!session)
901
- throw new Error('No such session.');
902
- const wanted = taskIds.length > 0 ? session.tasks.filter((t) => taskIds.includes(t.id)) : session.tasks;
903
- const tasks = wanted.filter((t) => t.status !== 'queued');
904
- if (tasks.length === 0) {
905
- throw new Error('None of the selected tasks has run yet, so there is nothing to export.');
906
- }
907
- const cfg = await this.settings.load();
908
- return await buildExport({ session, tasks, variant, runsDir: cfg.resolved.runsDir });
909
- }
910
- /**
911
- * Everything that happened across a set of sessions, as one JSON document.
912
- *
913
- * Given no ids it exports the sessions of the last batch, because the commonest moment for
914
- * wanting this is right after a run of several went wrong and the operator wants to hand the
915
- * whole thing to somebody who was not watching.
916
- */
917
- async debugExport(sessionIds) {
918
- await this.init();
919
- const wanted = sessionIds.map((x) => x.trim()).filter(Boolean);
920
- const ids = wanted.length > 0 ? wanted : (this.batch?.sessions ?? []).map((s) => s.sessionId);
921
- if (ids.length === 0) {
922
- throw new Error('No sessions were named, and no batch has run in this process to fall back on.');
923
- }
924
- const sessions = [];
925
- for (const id of ids) {
926
- const session = await this.store.getSession(id);
927
- if (session)
928
- sessions.push(session);
929
- }
930
- if (sessions.length === 0)
931
- throw new Error('None of those sessions exists any more.');
932
- const cfg = await this.settings.load();
933
- return await buildDebugExport({ sessions, runsDir: cfg.resolved.runsDir, cwd: cfg.resolved.cwd });
934
- }
935
- /**
936
- * One of the three JSON views (plan, domain, bot) of one task, one session or one run.
937
- *
938
- * A run is everything that one press of a start button set off, across sessions: the tasks
939
- * stamped with its id, and the sessions that were part of it even where a task never got its
940
- * turn. The file is named after the run's own name when it has one, because a file called
941
- * `run-r-abc123` is not something anyone can find again.
942
- */
943
- async exportView(kind, where) {
944
- await this.init();
945
- let scope;
946
- if (where.runId) {
947
- const runId = where.runId;
948
- const all = await this.store.listSessions();
949
- const sessions = all
950
- .filter((s) => s.runGroup?.id === runId || s.tasks.some((t) => t.runGroup?.id === runId || t.attempts?.some((a) => a.runGroup?.id === runId)))
951
- .sort((a, b) => (a.runGroup?.id === runId ? (a.runGroup.order ?? 0) : 0) - (b.runGroup?.id === runId ? (b.runGroup.order ?? 0) : 0));
952
- if (sessions.length === 0)
953
- throw new Error(`No session took part in run ${runId}.`);
954
- /*
955
- * The run's name and start, from a session's own record of the run — or, once a later run has
956
- * replaced that record, from a task that ran in it, which carries both. Without the second,
957
- * the earlier run's file was called "run-" with nothing after it, the kind of name nobody
958
- * finds again.
959
- */
960
- const group = sessions.map((s) => s.runGroup).find((g) => g?.id === runId) ??
961
- sessions.flatMap((s) => s.tasks.map((t) => taskInRun(t, runId)?.runGroup)).find((g) => g?.id === runId);
962
- const name = group?.name?.trim() || `run-${(group?.startedAt ?? '').slice(0, 16).replace(/[:T]/g, '-')}`;
963
- // Each task as it ended in this run, not as it is now; see `runScope`.
964
- scope = runScope(sessions, runId, name);
965
- }
966
- else if (where.sessionId) {
967
- const session = await this.store.getSession(where.sessionId);
968
- if (!session)
969
- throw new Error('No such session.');
970
- if (where.taskId) {
971
- const task = session.tasks.find((t) => t.id === where.taskId);
972
- if (!task)
973
- throw new Error('No such task.');
974
- scope = { sessions: [session], taskFilter: (_s, t) => t.id === task.id, label: `${session.name}-${task.title}` };
975
- }
976
- else {
977
- scope = { sessions: [session], label: session.name };
978
- }
979
- }
980
- else {
981
- throw new Error('Name a run, a session or a task.');
982
- }
983
- const cfg = await this.settings.load();
984
- const document = kind === 'plan'
985
- ? buildPlanExport(scope)
986
- : kind === 'domain'
987
- ? await buildDomainExport(scope, cfg.resolved.runsDir)
988
- : await buildBotExport(scope, cfg.resolved.runsDir, exportMachine(cfg));
989
- return { fileName: exportFileName(kind, scope.label), content: JSON.stringify(document, null, 2) };
990
- }
991
511
  /**
992
512
  * Everything that passed between the bot and Copilot for one task — every message sent, every reply, every
993
513
  * command with its whole output — every attempt of it and nothing of the tasks around it (2026-10-18: one JSON per
@@ -1005,60 +525,6 @@ let OperatorService = class OperatorService {
1005
525
  const label = `${chatCode(session.id)}-${String(session.tasks.indexOf(task) + 1).padStart(2, '0')}-${task.title}`;
1006
526
  return { fileName: exportFileName('exchange', label), content: JSON.stringify(document, null, 2) };
1007
527
  }
1008
- /**
1009
- * All three views of a set of tasks the operator picked by hand, in one file.
1010
- *
1011
- * The pairs carry their session because a selection spans runs and sessions — that is the
1012
- * point of it — so a task id on its own would not say which session's task it is. Unknown
1013
- * pairs are dropped rather than refused: a register left open while a session is deleted
1014
- * elsewhere should still hand over the tasks that are still there, and the document says
1015
- * which ones it holds.
1016
- */
1017
- async exportBundle(pairs) {
1018
- await this.init();
1019
- if (pairs.length === 0)
1020
- throw new Error('Choose at least one task.');
1021
- const wanted = new Map();
1022
- for (const { sessionId, taskId } of pairs) {
1023
- const set = wanted.get(sessionId) ?? new Set();
1024
- set.add(taskId);
1025
- wanted.set(sessionId, set);
1026
- }
1027
- /*
1028
- * A pair may name one attempt of its task — the button beside an earlier attempt does. That
1029
- * task is then exported as it stood for that attempt (`taskAtAttempt`): its text, its outcome,
1030
- * its run folder, and only the attempts before it.
1031
- */
1032
- const sessions = [];
1033
- for (const sessionId of wanted.keys()) {
1034
- let session = await this.store.getSession(sessionId);
1035
- if (!session)
1036
- continue;
1037
- for (const pair of pairs.filter((x) => x.sessionId === sessionId && x.attempt !== undefined)) {
1038
- const task = session.tasks.find((t) => t.id === pair.taskId);
1039
- const asItWas = task ? taskAtAttempt(task, pair.attempt) : null;
1040
- if (task && !asItWas)
1041
- throw new Error(`"${task.title}" has no attempt ${pair.attempt}.`);
1042
- if (asItWas)
1043
- session = withTask(session, asItWas);
1044
- }
1045
- sessions.push(session);
1046
- }
1047
- const found = sessions.flatMap((s) => s.tasks.filter((t) => wanted.get(s.id)?.has(t.id)));
1048
- if (found.length === 0)
1049
- throw new Error('None of the chosen tasks still exists.');
1050
- // Named after what was chosen rather than after a run, because a selection is not a run: it
1051
- // may be one task of one, or a task from each of three.
1052
- const one = pairs.length === 1 ? pairs[0] : undefined;
1053
- const label = found.length === 1 && sessions.length === 1
1054
- ? `${sessions[0].name}-${found[0].title}${one?.attempt !== undefined ? `-attempt-${one.attempt}` : ''}`
1055
- : sessions.length === 1
1056
- ? `${sessions[0].name}-${found.length}-tasks`
1057
- : `${found.length}-tasks-${sessions.length}-sessions`;
1058
- const cfg = await this.settings.load();
1059
- const document = await buildBundleExport({ sessions, taskFilter: (s, t) => !!wanted.get(s.id)?.has(t.id), label }, cfg.resolved.runsDir, exportMachine(cfg));
1060
- return { fileName: exportFileName('bundle', label), content: JSON.stringify(document, null, 2) };
1061
- }
1062
528
  // --- running --------------------------------------------------------------------------
1063
529
  isRunning(sessionId) {
1064
530
  return this.running.has(sessionId);
@@ -1079,38 +545,77 @@ let OperatorService = class OperatorService {
1079
545
  if (this.browser === holder)
1080
546
  this.browser = null;
1081
547
  }
548
+ /** The window the chat left open, if it is still there; one the operator closed with its X is let go of. */
549
+ async keptChatWindow() {
550
+ const window = this.chatWindow;
551
+ if (!window)
552
+ return undefined;
553
+ if (window.isOpen())
554
+ return window;
555
+ this.chatWindow = null;
556
+ await window.close().catch(() => undefined);
557
+ return undefined;
558
+ }
559
+ keepChatWindow(window) {
560
+ // One at a time, as the profile allows: an earlier one still held is closed rather than lost open.
561
+ const earlier = this.chatWindow;
562
+ this.chatWindow = window;
563
+ if (earlier && earlier !== window)
564
+ void earlier.close().catch(() => undefined);
565
+ }
566
+ /** Closes the window the chat left open, before something else takes the browser. Said on the console. */
567
+ async closeChatWindow(why) {
568
+ const window = this.chatWindow;
569
+ if (!window)
570
+ return;
571
+ this.chatWindow = null;
572
+ if (window.isOpen())
573
+ console.log(`[chat] the window the chat left open is closed: ${why}`);
574
+ await window.close().catch(() => undefined);
575
+ }
576
+ /** The card in the chat's window once the work on a message has ended (see `session/chatNotice.ts`). */
577
+ async chatWindowNotice(sessionId, tally) {
578
+ const window = this.chatWindow;
579
+ if (!window?.isOpen())
580
+ return;
581
+ const s = await this.store.getSession(sessionId);
582
+ if (!s)
583
+ return;
584
+ const ids = new Set(s.runGroup?.taskIds ?? []);
585
+ const tasks = s.tasks.filter((t) => ids.has(t.id)).map((t) => ({ title: t.title, status: t.status, reason: t.reason, summary: t.summary }));
586
+ if (tasks.length === 0)
587
+ return;
588
+ // Refused at its turn, nothing of it began: said as a start that could not happen, not as a stop.
589
+ await window.showNotice(chatNotice(s.lang || 'en', tasks, tally.error ?? tally.refused)).catch(() => undefined);
590
+ }
591
+ /** The program is closing: so is the window the chat left open. */
592
+ async onModuleDestroy() {
593
+ await this.closeChatWindow('the program is closing');
594
+ }
1082
595
  /**
1083
596
  * Starts the session's queued tasks in the background. Returns immediately; progress
1084
597
  * arrives on the event stream. One run at a time, of this session or any other.
1085
598
  */
1086
- async start(sessionId, mode = 'confirm', name,
1087
- /** Where the session starts, as chosen in the start window: see `vcs/startChoice.ts`. Absent keeps its settings. */
1088
- starts) {
599
+ async start(sessionId, mode = 'confirm') {
1089
600
  const pressedAt = new Date().toISOString();
1090
601
  // One conversation at a time is not a policy, it is the browser profile: a second run
1091
602
  // does not get a second browser, it gets an error about a closed one. Whatever has the
1092
- // browser now — a batch, another session, a read of the models — the start is refused where
603
+ // browser now — another conversation, a read of the models, the sign-in — the start is refused where
1093
604
  // the reason can still be read, rather than three minutes later in a stack trace.
1094
605
  const claim = this.claimBrowser({ kind: 'run', sessionId });
1095
606
  if ('refused' in claim)
1096
607
  return await this.notStarted({ stage: 'refused', message: claim.refused, sessionIds: [sessionId], pressedAt });
1097
608
  let runId;
1098
609
  try {
1099
- // A run nobody named is named after what it is a run of, rather than left to show up in the
1100
- // register as "Unnamed run" beside five others of the same description.
1101
- // Set aside on the Sessions page: said first, before the preflight judges a session that will not run.
610
+ // Set aside: said first, before the preflight judges a session that will not run.
1102
611
  if ((await this.store.getSession(sessionId))?.active === false) {
1103
612
  this.releaseBrowser(claim.holder);
1104
613
  return await this.notStarted({ stage: 'refused', message: INACTIVE_REASON, sessionIds: [sessionId], pressedAt });
1105
614
  }
1106
- const chosenName = name?.trim() || (await this.suggestRunName([sessionId]));
615
+ // Named after what it is a run of.
616
+ const chosenName = await this.suggestRunName([sessionId]);
1107
617
  const runGroup = { id: newId('r-'), startedAt: new Date().toISOString(), sessions: 1, name: chosenName };
1108
618
  runId = runGroup.id;
1109
- /*
1110
- * What refuses this start whatever branch is chosen, asked before the choice moves anything: a local
1111
- * branch made or brought up to its remote, and the session's settings, stayed changed after a start
1112
- * refused for an unattended run this machine does not allow (review of 2026-10-13).
1113
- */
1114
619
  const before = await this.store.getSession(sessionId);
1115
620
  const earlyRefusal = !before ? 'no such session' : queuedToRun(before).length === 0 ? 'no queued tasks' : await this.unattendedRefusal(mode);
1116
621
  if (earlyRefusal) {
@@ -1118,14 +623,6 @@ let OperatorService = class OperatorService {
1118
623
  // No run log for a session that does not exist: the id is the caller's, and may be anything.
1119
624
  return await this.notStarted({ stage: 'refused', message: earlyRefusal, sessionIds: [sessionId], pressedAt, ...(before ? { runId } : {}) });
1120
625
  }
1121
- // The branch the session starts from, as the start window chose it, before the preflight judges it.
1122
- const unusable = await this.applyStartChoices(runGroup.id, [sessionId], starts);
1123
- if (unusable) {
1124
- this.releaseBrowser(claim.holder);
1125
- return await this.notStarted({ stage: 'branch', message: unusable, sessionIds: [sessionId], pressedAt, runId });
1126
- }
1127
- // A run of one is still a run, and it records the same thing a batch does, so that going
1128
- // back and starting again from a task works the same whether one session was started or six.
1129
626
  // Recorded by `beginRun` once the start is accepted, not here: see `recordOnSession`.
1130
627
  // Version control first, before anything opens the browser: see `vcs/runPreflight.ts`.
1131
628
  const notReady = await this.runPreflight(runGroup.id, [sessionId]);
@@ -1133,14 +630,20 @@ let OperatorService = class OperatorService {
1133
630
  this.releaseBrowser(claim.holder);
1134
631
  return await this.notStarted({ stage: 'preflight', message: notReady, sessionIds: [sessionId], pressedAt, runId });
1135
632
  }
1136
- const begun = await this.beginRun(sessionId, mode, undefined, runGroup, undefined, { recordOnSession: true, pressedAt });
633
+ // A message of the chat is given the window the last one left open, while it is still there (see `chatWindow`).
634
+ const chat = before?.kind === 'chat';
635
+ const lent = chat ? await this.keptChatWindow() : undefined;
636
+ const begun = await this.beginRun(sessionId, mode, lent, runGroup, undefined, { recordOnSession: true, pressedAt, chatWindow: chat });
1137
637
  if (!begun.started) {
1138
638
  this.releaseBrowser(claim.holder);
1139
639
  return await this.notStarted({ stage: 'refused', message: begun.reason ?? 'not started', sessionIds: [sessionId], pressedAt, runId });
1140
640
  }
1141
641
  // The window closes before the run's promise settles (see `runSession`), so the browser is
1142
- // free again exactly when it is.
1143
- void begun.done.finally(() => this.releaseBrowser(claim.holder));
642
+ // free again exactly when it is. The chat's stays open, and says in it that the work has ended.
643
+ void begun.done
644
+ .then((tally) => (chat ? this.chatWindowNotice(sessionId, tally) : undefined))
645
+ .catch(() => undefined)
646
+ .finally(() => this.releaseBrowser(claim.holder));
1144
647
  return { started: true };
1145
648
  }
1146
649
  catch (e) {
@@ -1182,88 +685,6 @@ let OperatorService = class OperatorService {
1182
685
  }
1183
686
  return { started: false, reason: f.message, failure: refOf(recorded) };
1184
687
  }
1185
- /**
1186
- * Writes the start window's choices onto the sessions of a run, or says why one cannot be used.
1187
- *
1188
- * Every choice is checked first, with nothing moved (`dry`), so a choice that cannot be used for one
1189
- * session leaves every other session and every branch as it was; then each is written, and a local
1190
- * branch made from, or brought up to, its remote one where the choice was to work on it. A session
1191
- * whose start is fixed keeps it. Recorded in the run's log and the session's.
1192
- */
1193
- async applyStartChoices(runId, sessionIds, starts) {
1194
- if (!starts || typeof starts !== 'object')
1195
- return null;
1196
- const wanted = sessionIds.filter((id) => starts[id]);
1197
- if (wanted.length === 0)
1198
- return null;
1199
- for (const id of wanted) {
1200
- const s = await this.store.getSession(id);
1201
- if (!s)
1202
- continue;
1203
- if (this.running.has(id))
1204
- return `"${s.name}" is running; its start cannot be changed now.`;
1205
- const checked = await applyStartChoice(s, starts[id], { dry: true });
1206
- if (!checked.ok)
1207
- return `"${s.name}": ${checked.problem}`;
1208
- }
1209
- const cfg = await this.settings.load();
1210
- const entries = [];
1211
- for (const id of wanted) {
1212
- const s = await this.store.getSession(id);
1213
- if (!s)
1214
- continue;
1215
- const done = await applyStartChoice(s, starts[id]);
1216
- if (!done.ok)
1217
- return `"${s.name}": ${done.problem}`;
1218
- if (!done.applied)
1219
- continue;
1220
- const applied = done.applied;
1221
- await this.store.updateSession(id, (x) => {
1222
- if (!x.vcs)
1223
- return;
1224
- x.vcs = withChoice(x.vcs, applied.vcs);
1225
- if (applied.clearStart) {
1226
- x.vcsBaseCommit = undefined;
1227
- x.vcsStart = undefined;
1228
- }
1229
- // Chosen again after the session ran: a re-run starts from it too, and a per-session line goes on under a new name.
1230
- if (applied.restart) {
1231
- x.startRechosenAt = new Date().toISOString();
1232
- if (applied.restart.freshBranch) {
1233
- x.vcs.branchName = applied.restart.freshBranch;
1234
- x.vcs.branchNameExact = true;
1235
- }
1236
- }
1237
- });
1238
- const message = `${applied.said}${applied.note ? `; ${applied.note}` : ''}${applied.clearStart && !applied.restart ? '; the start prepared before (a starting snapshot) no longer applies' : ''}`;
1239
- entries.push({ at: new Date().toISOString(), type: 'start-chosen', message, data: { session: id, choice: starts[id], ...(applied.note ? { note: applied.note } : {}) } });
1240
- this.bus.publish({ sessionId: id, type: 'start-chosen', level: 'info', message, data: { runId, choice: starts[id] } });
1241
- await appendSessionLog(cfg.resolved.runsDir, id, { type: 'start-chosen', message, data: { runId, choice: starts[id] } }).catch(() => undefined);
1242
- }
1243
- await appendRunLog(cfg.resolved.runsDir, runId, entries).catch(() => undefined);
1244
- return null;
1245
- }
1246
- /** The start window's question for these sessions: their starts and the branches of their repositories. */
1247
- async startChoices(sessionIds) {
1248
- await this.init();
1249
- const sessions = [];
1250
- for (const id of [...new Set(sessionIds.map((x) => x.trim()).filter(Boolean))]) {
1251
- const s = await this.store.getSession(id);
1252
- if (s)
1253
- sessions.push(s);
1254
- }
1255
- return await startOptions(sessions);
1256
- }
1257
- /**
1258
- * Fetches branches of a remote for the start window, where the operator is looking — so through Git's
1259
- * own password window when the remote asks (see `vcs/remoteAuth.ts`). Only for a folder this bot works
1260
- * in; only remote-tracking branches move.
1261
- */
1262
- async startFetch(dir, remote, branches) {
1263
- await this.init();
1264
- await this.knownProjectFolder(dir, 'it is not fetched from here');
1265
- return await fetchForStart(resolve(dir.trim()), remote.trim(), branches, await askpassProgram());
1266
- }
1267
688
  /** The starts that did not get as far as a first task, newest first: see `session/startFailure.ts`. */
1268
689
  recentStartFailures(unansweredOnly) {
1269
690
  return this.startFailures.recent({ unansweredOnly }).slice(0, 10).map(refOf);
@@ -1305,16 +726,12 @@ let OperatorService = class OperatorService {
1305
726
  return { fileName: `copilot-operator-terminal-${fileStamp(new Date().toISOString())}.txt`, content: redactSecrets(`${head}${formatTerminal(lines)}\n`, cfg.report.redactPatterns) };
1306
727
  }
1307
728
  /**
1308
- * The same thing `start` does, but it also hands back a promise that settles when the run
1309
- * is over and says how it went.
1310
- *
1311
- * A batch needs that promise and a single session does not, which is the only difference
1312
- * between the two callers. The sessions of a batch still run one at a time through here,
1313
- * and they have to: the browser profile is single-writer, so two conversations at once is
1314
- * not slower, it is a failure with a message about a closed browser.
729
+ * Begins the run `start` asked for, and hands back a promise that settles when it is over and says how it went.
730
+ * One at a time: the browser profile is single-writer, so two conversations at once is not slower, it is a
731
+ * failure with a message about a closed browser.
1315
732
  */
1316
733
  async beginRun(sessionId, mode,
1317
- /** A browser that is already open. A batch passes its own; a single run opens one. */
734
+ /** A browser that is already open: the one the chat left open (see `chatWindow`); otherwise the run opens one. */
1318
735
  transport,
1319
736
  /** The press of a start button this belongs to, stamped onto every task it reaches. */
1320
737
  runGroup,
@@ -1371,7 +788,13 @@ let OperatorService = class OperatorService {
1371
788
  */
1372
789
  const authorizer = this.webAuthorizer(policy, controller.signal);
1373
790
  const startedAt = new Date().toISOString();
1374
- this.running.set(sessionId, { controller, startedAt, mode, policy });
791
+ const hold = new Hold();
792
+ this.running.set(sessionId, { controller, startedAt, mode, policy, hold });
793
+ {
794
+ const asLead = await this.store.getSession(sessionId);
795
+ if (asLead?.lead?.workerSessionId)
796
+ this.workerLeads.set(asLead.lead.workerSessionId, sessionId);
797
+ }
1375
798
  this.bus.publish({ sessionId, type: 'run-requested', level: 'info', message: `starting in ${mode} mode` });
1376
799
  // Said at the start of every run, in both modes, because it is the one fact about this tool a
1377
800
  // data-protection team needs and the one an operator forgets: the reports leave the machine.
@@ -1391,9 +814,6 @@ let OperatorService = class OperatorService {
1391
814
  bus: this.bus,
1392
815
  authorizer,
1393
816
  signal: controller.signal,
1394
- // Read between tasks, so the one in flight finishes properly first. The batch that owns
1395
- // this run answers it, because a pause is about the whole run and not about this session.
1396
- shouldPause: how.shouldPause,
1397
817
  // The mode as it is now, not as it was: "run the rest without asking" changes it mid-run,
1398
818
  // and the policy.json of a later task must say so.
1399
819
  currentMode: () => this.running.get(sessionId)?.mode ?? mode,
@@ -1413,7 +833,17 @@ let OperatorService = class OperatorService {
1413
833
  }
1414
834
  return refused;
1415
835
  },
1416
- ...(transport || !runGroup ? {} : { beforeBrowser: () => this.browserRequested(runGroup.id, [sessionId]) }),
836
+ // Opening a window of its own: the one the chat left open goes first, since the profile takes one.
837
+ ...(transport
838
+ ? {}
839
+ : {
840
+ beforeBrowser: async () => {
841
+ await this.closeChatWindow('another run needs the browser');
842
+ if (runGroup)
843
+ await this.browserRequested(runGroup.id, [sessionId]);
844
+ },
845
+ }),
846
+ ...(how.chatWindow ? { chatWindow: { keep: (window) => this.keepChatWindow(window) } } : {}),
1417
847
  // The page is the source of the model names: Settings and the saved list follow it (see `ModelHooks`).
1418
848
  models: {
1419
849
  locate: async (name) => (await this.store.getModels())?.options.find((o) => sameModel(o.name, name))?.locator,
@@ -1431,6 +861,10 @@ let OperatorService = class OperatorService {
1431
861
  },
1432
862
  // Plan mode `approve`: the plan is put to the operator on the approvals card.
1433
863
  approvePlan: (ask) => this.askPlanApproval(ask, controller.signal),
864
+ // The two-chat mode (2026-10-20): the lead's questions, and the worker the run speaks for too.
865
+ askQuestion: (ask) => this.askLeadQuestion(ask, controller.signal),
866
+ onWorker: (workerId) => this.workerLeads.set(workerId, sessionId),
867
+ hold,
1434
868
  })
1435
869
  .then(async (outcome) => {
1436
870
  const tally = { ...(await this.tally(sessionId, queuedIds)), paused: outcome.paused, ...(outcome.refused ? { refused: outcome.refused } : {}) };
@@ -1450,18 +884,18 @@ let OperatorService = class OperatorService {
1450
884
  // Not when the operator stopped it: that is an answer, not a failure to show.
1451
885
  if (tally.ran === 0 && !controller.signal.aborted) {
1452
886
  console.error('[start] the run ended before its first task:', e.stack ?? e.message);
1453
- await this.notStarted({ stage: how.laterInRun ? 'at-turn' : 'run', message: e.message, sessionIds: [sessionId], pressedAt: how.pressedAt ?? startedAt, ...(runGroup ? { runId: runGroup.id } : {}), answered: false });
887
+ await this.notStarted({ stage: failedWhileOpening(e) ? 'browser' : 'run', message: e.message, sessionIds: [sessionId], pressedAt: how.pressedAt ?? startedAt, ...(runGroup ? { runId: runGroup.id } : {}), answered: false });
1454
888
  }
1455
889
  return tally;
1456
890
  })
1457
891
  .finally(() => {
1458
- this.running.delete(sessionId);
1459
892
  for (const [id, w] of this.waiting) {
1460
- if (w.approval.sessionId === sessionId) {
893
+ if (this.runKey(w.approval.sessionId) === sessionId) {
1461
894
  w.resolve({ action: 'abort', reason: 'the run ended' });
1462
895
  this.waiting.delete(id);
1463
896
  }
1464
897
  }
898
+ this.running.delete(sessionId);
1465
899
  });
1466
900
  return { started: true, done };
1467
901
  }
@@ -1496,13 +930,33 @@ let OperatorService = class OperatorService {
1496
930
  return tally;
1497
931
  }
1498
932
  /** Asks the run to stop after the current step. Pending approvals are aborted at once. */
933
+ /**
934
+ * "Pause" on the chat (operator, 2026-10-20): the running work holds at its next message to Copilot or its next
935
+ * command, and the button becomes "Continue". A reply being written and a command running are let finish.
936
+ */
937
+ pause(sessionId) {
938
+ const r = this.running.get(sessionId);
939
+ if (!r)
940
+ throw new Error('Nothing of this conversation is running, so there is nothing to pause.');
941
+ if (r.hold.pause()) {
942
+ this.bus.publish({ sessionId, type: 'pause-asked', level: 'info', message: 'paused by the operator: the work holds at its next message or command, until Continue' });
943
+ }
944
+ return { paused: true };
945
+ }
946
+ /** "Continue": the paused work goes on from where it held. A run that has ended meanwhile has nothing to go on with. */
947
+ resume(sessionId) {
948
+ const r = this.running.get(sessionId);
949
+ if (r?.hold.resume())
950
+ this.bus.publish({ sessionId, type: 'resume-asked', level: 'info', message: 'continued by the operator' });
951
+ return { paused: false };
952
+ }
1499
953
  async stop(sessionId) {
1500
954
  const r = this.running.get(sessionId);
1501
955
  if (!r)
1502
956
  return { stopping: false };
1503
957
  r.controller.abort();
1504
958
  for (const [id, w] of this.waiting) {
1505
- if (w.approval.sessionId === sessionId) {
959
+ if (this.runKey(w.approval.sessionId) === sessionId) {
1506
960
  w.resolve({ action: 'abort', reason: 'stopped by the operator', by: 'operator' });
1507
961
  this.waiting.delete(id);
1508
962
  }
@@ -1529,12 +983,8 @@ let OperatorService = class OperatorService {
1529
983
  * A run being started — its version control checked before the browser opens — is not running yet
1530
984
  * and not idle either: `starting` says so, so "nothing is happening" is not read in that moment.
1531
985
  */
1532
- const starting = this.running.size === 0 && !this.batch?.running && (this.browser?.kind === 'run' || this.browser?.kind === 'batch');
1533
- return { running: this.running.size > 0, sessions: this.running.size, batch: this.batch?.running === true, starting };
1534
- }
1535
- /** The batch in progress, or the last one that ran, or null if none ever has. */
1536
- batchState() {
1537
- return this.batch ? { ...this.batch, sessions: this.batch.sessions.map((s) => ({ ...s })) } : null;
986
+ const starting = this.running.size === 0 && this.browser?.kind === 'run';
987
+ return { running: this.running.size > 0, sessions: this.running.size, starting };
1538
988
  }
1539
989
  /**
1540
990
  * Runs the queued tasks of several sessions, one session after another.
@@ -1551,112 +1001,6 @@ let OperatorService = class OperatorService {
1551
1001
  async suggestRunName(sessionIds, about) {
1552
1002
  return suggestRunName(await this.store.listSessions(), sessionIds, about);
1553
1003
  }
1554
- async startBatch(sessionIds, mode = 'confirm', onFailure = 'stop', model,
1555
- /**
1556
- * The model the independent review runs on, for every session in this run.
1557
- *
1558
- * Separate from `model` because they are separate decisions, and the interesting case is
1559
- * precisely when they differ: a review is worth most when it is not the same mind that did
1560
- * the work, and a run panel that could only set one model made that the hard path.
1561
- */
1562
- reviewModel,
1563
- /** What to call the run. Offered from the plan's name; empty means it goes by its id. */
1564
- name,
1565
- /**
1566
- * The queued tasks to run, when not every queued task of those sessions: what the operator
1567
- * ticked in the register. A session none of whose chosen tasks is queued is skipped; the
1568
- * tasks nobody chose stay queued exactly as they were. Absent means every queued task.
1569
- */
1570
- taskIds,
1571
- /** Where each session starts, as chosen in the start window: see `vcs/startChoice.ts`. Absent keeps their settings. */
1572
- starts) {
1573
- const pressedAt = new Date().toISOString();
1574
- const wanted = [...new Set(sessionIds.map((s) => s.trim()).filter(Boolean))];
1575
- // Before anything is waited for (see `browser`): a second batch, a session running on its own
1576
- // — one of these or any other — and a read of the models all have the browser already.
1577
- const claim = this.claimBrowser({ kind: 'batch', sessionIds: wanted });
1578
- if ('refused' in claim)
1579
- return await this.notStarted({ stage: 'refused', message: claim.refused, sessionIds: wanted, pressedAt });
1580
- return await this.startBatchHolding(claim.holder, wanted, mode, onFailure, model, reviewModel, name, taskIds, { starts, pressedAt });
1581
- }
1582
- /**
1583
- * `startBatch` for a caller that has claimed the browser already, and the claim with it: handed on
1584
- * to the batch once it is under way (`runBatch` gives it back), and given back here on every
1585
- * refusal. "Run again from here" claims it before it moves anything and starts through this, so
1586
- * one claim covers the restore, the requeue and the run.
1587
- */
1588
- async startBatchHolding(holder, wanted, mode, onFailure, model, reviewModel, name, taskIds, how = {}) {
1589
- const onlyTasks = taskIds && taskIds.length > 0 ? new Set(taskIds.map((t) => t.trim()).filter(Boolean)) : undefined;
1590
- const pressedAt = how.pressedAt ?? new Date().toISOString();
1591
- let handedOn = false;
1592
- // The batch's id first, so the preflight is recorded under the run it decides about.
1593
- const batchId = newId('b-');
1594
- const refuse = (stage, message, runId) => this.notStarted({ stage, message, sessionIds: wanted, pressedAt, ...(runId ? { runId } : {}) });
1595
- try {
1596
- await this.init();
1597
- if (wanted.length === 0)
1598
- return await refuse('refused', 'no sessions were selected');
1599
- // Version control first, before anything opens the browser: see `vcs/runPreflight.ts`.
1600
- /*
1601
- * Sessions set aside on the Sessions page are left out before the preflight: judged there, an inactive
1602
- * session's contradiction or version-control problem was the answer to the press — and could refuse
1603
- * the whole batch — although it would never have run (review of 2026-10-09). `prepareBatch` records
1604
- * them as skipped, with the reason.
1605
- */
1606
- const active = [];
1607
- const inactive = [];
1608
- for (const id of wanted) {
1609
- const s = await this.store.getSession(id);
1610
- if (s?.active === false)
1611
- inactive.push(s.name);
1612
- else
1613
- active.push(id);
1614
- }
1615
- if (active.length === 0)
1616
- return await refuse('refused', `${inactive.map((n) => `"${n}"`).join(', ')}: ${INACTIVE_REASON}`);
1617
- /*
1618
- * What refuses the batch whatever branch is chosen, asked before the choices move anything (review of
1619
- * 2026-10-13): nothing queued among the chosen tasks, an unattended run this machine does not allow.
1620
- */
1621
- let anyQueued = false;
1622
- for (const id of active) {
1623
- const s = await this.store.getSession(id);
1624
- if (s && queuedToRun(s, onlyTasks).length > 0)
1625
- anyQueued = true;
1626
- }
1627
- if (!anyQueued)
1628
- return await refuse('refused', 'none of the selected sessions has a queued task', batchId);
1629
- const blockedEarly = await this.unattendedRefusal(mode);
1630
- if (blockedEarly)
1631
- return await refuse('refused', blockedEarly, batchId);
1632
- // The branch each session starts from, as the start window chose it, before the preflight judges it.
1633
- const unusable = await this.applyStartChoices(batchId, active, how.starts);
1634
- if (unusable)
1635
- return await refuse('branch', unusable, batchId);
1636
- const notReady = await this.runPreflight(batchId, active, onlyTasks);
1637
- if (notReady)
1638
- return await refuse('preflight', notReady, batchId);
1639
- const begun = await this.prepareBatch(wanted, onlyTasks, mode, onFailure, model, reviewModel, name, batchId);
1640
- if (!begun.batch)
1641
- return await refuse('refused', begun.reason, batchId);
1642
- begun.batch.pressedAt = pressedAt;
1643
- this.batch = begun.batch;
1644
- handedOn = true;
1645
- void this.runBatch(begun.batch, holder);
1646
- return { started: true, batch: this.batchState() };
1647
- }
1648
- catch (e) {
1649
- if (unusableConfig(e))
1650
- throw e;
1651
- // Said with the error itself, and on record with the console of those moments, rather than as a bare 400.
1652
- console.error('[start] the run could not be started:', e.stack ?? e.message);
1653
- return await refuse('error', e.message, batchId);
1654
- }
1655
- finally {
1656
- if (!handedOn)
1657
- this.releaseBrowser(holder);
1658
- }
1659
- }
1660
1004
  /**
1661
1005
  * Why a batch in this mode may not begin on this machine now, or null when it may: the entrance
1662
1006
  * rule (`unattendedPrecondition`) asked of the settings as they are at this moment. One place, for
@@ -1671,611 +1015,7 @@ let OperatorService = class OperatorService {
1671
1015
  lockedToConfirm: cfg.policyLock?.maxMode === 'confirm',
1672
1016
  });
1673
1017
  }
1674
- /**
1675
- * Everything `startBatch` decides before the batch exists: which sessions it has work in, whether
1676
- * an unattended run may begin, and the models the run panel chose. A refusal comes back as the
1677
- * reason; nothing is started here.
1678
- */
1679
- async prepareBatch(wanted, onlyTasks, mode, onFailure, model, reviewModel, name,
1680
- /** The id its preflight was recorded under; a new one when there was none. */
1681
- id = newId('b-')) {
1682
- // Worked out here rather than asked of the operator again: every way into this — the run
1683
- // panel, continuing after a failure, "Run again from here" — either has a field they may
1684
- // have left empty or has no field at all.
1685
- const chosenName = name?.trim() || (await this.suggestRunName(wanted));
1686
- const sessions = [];
1687
- for (const id of wanted) {
1688
- const s = await this.store.getSession(id);
1689
- if (!s) {
1690
- sessions.push({ sessionId: id, name: id, state: 'skipped', ran: 0, failed: 0, reason: 'no such session' });
1691
- continue;
1692
- }
1693
- /*
1694
- * Set aside on the Sessions page: left out here, before the browser opens, with the reason `start`
1695
- * gives. Let through, the batch said "started", opened the browser, and only then skipped it — a
1696
- * "Run" that reported success and ran nothing.
1697
- */
1698
- if (s.active === false) {
1699
- sessions.push({ sessionId: id, name: s.name, state: 'skipped', ran: 0, failed: 0, reason: INACTIVE_REASON });
1700
- continue;
1701
- }
1702
- const queued = queuedToRun(s, onlyTasks).length;
1703
- sessions.push(queued === 0
1704
- ? { sessionId: id, name: s.name, state: 'skipped', ran: 0, failed: 0, reason: onlyTasks ? 'none of its chosen tasks is queued' : 'nothing queued' }
1705
- : { sessionId: id, name: s.name, state: 'waiting', ran: 0, failed: 0 });
1706
- }
1707
- if (!sessions.some((s) => s.state === 'waiting')) {
1708
- const inactive = sessions.filter((s) => s.reason === INACTIVE_REASON);
1709
- return {
1710
- reason: inactive.length > 0 ? `${inactive.map((s) => `"${s.name}"`).join(', ')}: ${INACTIVE_REASON}` : 'none of the selected sessions has a queued task',
1711
- };
1712
- }
1713
- /*
1714
- * The same entrance rule `start` has, asked here too and for the same reason: before a browser
1715
- * is opened. It was missing, and the rule was only met inside the loop, per session, after the
1716
- * window was already up — so on a machine with no isolation the operator pressed the run
1717
- * button, watched Edge open, begin loading the chat and close again, and was told nothing: the
1718
- * session was quietly skipped with the reason held in a batch state nobody was looking at. Asked
1719
- * here, the refusal is the answer to the press, shown under the button that caused it.
1720
- */
1721
- const blocked = await this.unattendedRefusal(mode);
1722
- if (blocked)
1723
- return { reason: blocked };
1724
- // One model for the whole run, chosen here rather than opened on every session first. It
1725
- // is written onto the sessions instead of being held for the run, so what the session says
1726
- // it will use and what it used are the same thing afterwards — including for anyone who
1727
- // opens one of them tomorrow and wonders which model produced that summary.
1728
- const wantedModel = model?.trim();
1729
- const wantedReviewModel = reviewModel?.trim();
1730
- if (wantedModel || wantedReviewModel) {
1731
- /*
1732
- * The panel starts on the models chosen in Settings. A session that follows Settings and is
1733
- * run on exactly that model is left following it, so choosing another model in Settings
1734
- * later still reaches it; only a different choice, or a session with a model of its own,
1735
- * is written.
1736
- */
1737
- const settingsNow = await this.settings.load();
1738
- const followModel = (settingsNow.copilot.defaultModel ?? '').trim();
1739
- const followReview = (settingsNow.copilot.defaultReviewModel ?? '').trim();
1740
- for (const entry of sessions) {
1741
- if (entry.state !== 'waiting')
1742
- continue;
1743
- await this.store.updateSession(entry.sessionId, (s) => {
1744
- if (wantedModel && (s.model?.trim() || wantedModel !== followModel)) {
1745
- s.model = wantedModel;
1746
- s.modelSource = 'operator';
1747
- }
1748
- // Only the model is set here, never whether the review happens: a run panel is about
1749
- // this run, and silently switching a session's review on or off from it would be a
1750
- // change to the session that outlives the run.
1751
- if (wantedReviewModel && (s.review?.model?.trim() || wantedReviewModel !== followReview)) {
1752
- s.review = { ...DEFAULT_REVIEW, ...s.review, model: wantedReviewModel };
1753
- s.reviewModelSource = 'operator';
1754
- }
1755
- });
1756
- }
1757
- }
1758
- return {
1759
- batch: {
1760
- id,
1761
- startedAt: new Date().toISOString(),
1762
- name: chosenName,
1763
- ...(onlyTasks ? { onlyTasks: [...onlyTasks] } : {}),
1764
- mode,
1765
- onFailure,
1766
- stopping: false,
1767
- pausing: false,
1768
- running: true,
1769
- sessions,
1770
- },
1771
- };
1772
- }
1773
- /** Stops the session that is running now and leaves the rest of the batch unstarted. */
1774
- /**
1775
- * Holds the run after the task that is running, and lets that task finish first.
1776
- *
1777
- * Not a stop: the task in flight runs its checks, is reviewed and commits, exactly as it would
1778
- * have. What is held is the queue behind it, and the sessions after this one, both of which
1779
- * stay as they are — so continuing is the same act it always was, and the button for it is the
1780
- * one already on the register.
1781
- *
1782
- * It does not release the browser early either. The run ends when the current task does, and
1783
- * the window closes with it, because the Edge profile is single-writer and a run that sat
1784
- * holding it would stop every other session from doing anything at all.
1785
- */
1786
- async pauseBatch() {
1787
- const batch = this.batch;
1788
- if (!batch?.running || batch.stopping)
1789
- return { pausing: false };
1790
- batch.pausing = true;
1791
- this.bus.publish({
1792
- sessionId: batch.sessions.find((s) => s.state === 'running')?.sessionId ?? batch.id,
1793
- type: 'batch-pausing',
1794
- level: 'info',
1795
- message: 'pausing: the task that is running will finish, and the rest of the queue stays as it is',
1796
- data: { batchId: batch.id },
1797
- });
1798
- return { pausing: true };
1799
- }
1800
- /** Takes the hold off a run that has not ended yet, so the queue carries on where it was. */
1801
- async resumeBatch() {
1802
- const batch = this.batch;
1803
- if (!batch?.running || !batch.pausing)
1804
- return { pausing: false };
1805
- batch.pausing = false;
1806
- this.bus.publish({
1807
- sessionId: batch.sessions.find((s) => s.state === 'running')?.sessionId ?? batch.id,
1808
- type: 'batch-resumed',
1809
- level: 'info',
1810
- message: 'the hold is off; the queue carries on',
1811
- data: { batchId: batch.id },
1812
- });
1813
- return { pausing: false };
1814
- }
1815
- async stopBatch() {
1816
- const batch = this.batch;
1817
- if (!batch?.running)
1818
- return { stopping: false };
1819
- batch.stopping = true;
1820
- const current = batch.sessions.find((s) => s.state === 'running');
1821
- if (current)
1822
- await this.stop(current.sessionId);
1823
- return { stopping: true };
1824
- }
1825
- /**
1826
- * Runs a batch that has just been started, and ends what only the batch may end: its hold and
1827
- * its claim on the browser. Both are let go here, once, however the loop came out — finished,
1828
- * stopped, failed, or never able to open its window.
1829
- */
1830
- async runBatch(batch, holder) {
1831
- try {
1832
- await this.batchLoop(batch);
1833
- }
1834
- finally {
1835
- // A pause holds this batch's queue and nothing after it. Left on, it read as "pausing" on a
1836
- // batch that had ended, and it was what every later run read, so each stopped before its
1837
- // first task (see `shouldPause` in `beginRun`).
1838
- batch.pausing = false;
1839
- // The batch's window is closed by now, in the loop's own ending.
1840
- this.releaseBrowser(holder);
1841
- }
1842
- }
1843
- /**
1844
- * The batch loop. Nothing here runs in parallel, on purpose: see `beginRun`.
1845
- *
1846
- * Each session is judged by the tasks it was given. A session that ran everything without a
1847
- * failure is `done`; one with a failed task is `failed`; one the operator stopped, or one
1848
- * whose chain stopped early with no failure of its own, is `stopped`.
1849
- */
1850
- async batchLoop(batch) {
1851
- /*
1852
- * One browser for the whole batch.
1853
- *
1854
- * Every session used to open its own window and close it again: a fresh launch, a fresh
1855
- * sign-in check and a fresh grab at the profile lock, several times over, for a machine
1856
- * that can only have one of them open at a time anyway. The window is opened here, handed
1857
- * to each session in turn, and closed when the last one is done — so between sessions the
1858
- * only thing that changes is which conversation is on screen.
1859
- */
1860
- let browser = null;
1861
- try {
1862
- const cfg = await this.settings.load();
1863
- await this.browserRequested(batch.id, batch.sessions.filter((x) => x.state === 'waiting').map((x) => x.sessionId));
1864
- browser = await openBrowser(cfg, this.bus, join(cfg.resolved.runsDir, '_browser'), batch.id);
1865
- this.bus.publish({
1866
- sessionId: batch.sessions[0]?.sessionId ?? batch.id,
1867
- type: 'batch-browser-open',
1868
- level: 'info',
1869
- message: `one browser window for all ${batch.sessions.length} session(s) in this run`,
1870
- data: { batchId: batch.id },
1871
- });
1872
- }
1873
- catch (e) {
1874
- // Without a window nothing can run, and saying so once is better than failing every
1875
- // session in turn with the same message.
1876
- for (const entry of batch.sessions) {
1877
- if (entry.state === 'waiting') {
1878
- entry.state = 'failed';
1879
- entry.reason = `the browser could not be opened: ${e.message}`;
1880
- }
1881
- }
1882
- batch.running = false;
1883
- batch.finishedAt = new Date().toISOString();
1884
- this.bus.publish({
1885
- sessionId: batch.id,
1886
- type: 'batch-error',
1887
- level: 'error',
1888
- message: `the browser could not be opened: ${e.message}`,
1889
- });
1890
- /*
1891
- * The run had been accepted, so the press was answered "started": this is shown on every page
1892
- * until it is closed, with what the console printed (2026-10-13). The stack is printed for it.
1893
- */
1894
- console.error('[start] the browser could not be opened:', e.stack ?? e.message);
1895
- await this.notStarted({
1896
- stage: 'browser',
1897
- message: `the browser could not be opened: ${e.message}`,
1898
- sessionIds: batch.sessions.map((x) => x.sessionId),
1899
- pressedAt: batch.pressedAt ?? batch.startedAt,
1900
- runId: batch.id,
1901
- answered: false,
1902
- });
1903
- return;
1904
- }
1905
- try {
1906
- /*
1907
- * One group for the whole batch, made before the loop rather than per session.
1908
- *
1909
- * That is the entire point of it: the register can then draw one line around everything
1910
- * this press of the button set off, across sessions, which is the question a list of
1911
- * tasks sorted by time cannot answer.
1912
- */
1913
- const runGroup = {
1914
- id: batch.id,
1915
- startedAt: batch.startedAt,
1916
- sessions: batch.sessions.filter((s) => s.state === 'waiting').length,
1917
- ...(batch.name ? { name: batch.name } : {}),
1918
- };
1919
- /*
1920
- * The same run, recorded on each session, with what it was asked to do.
1921
- *
1922
- * Written before the first session starts and for every session including the ones the
1923
- * run may never reach, because that is precisely the case it exists for: a failure in
1924
- * session one leaves sessions two and three with no tasks stamped and no way to know
1925
- * they were ever part of this. Going back afterwards and running the rest again needs
1926
- * the whole list, and this is the only place it is still true.
1927
- */
1928
- let order = 0;
1929
- for (const entry of batch.sessions) {
1930
- if (entry.state !== 'waiting')
1931
- continue;
1932
- const at = order;
1933
- order += 1;
1934
- await this.store.updateSession(entry.sessionId, (s) => {
1935
- s.runGroup = {
1936
- ...runGroup,
1937
- order: at,
1938
- // What this run was asked to do: the chosen tasks, when some were chosen.
1939
- taskIds: queuedToRun(s, batch.onlyTasks).map((t) => t.id),
1940
- mode: batch.mode,
1941
- onFailure: batch.onFailure,
1942
- };
1943
- });
1944
- }
1945
- for (const entry of batch.sessions) {
1946
- if (entry.state !== 'waiting')
1947
- continue;
1948
- if (batch.stopping) {
1949
- entry.state = 'skipped';
1950
- entry.reason = 'the batch was stopped before this session started';
1951
- continue;
1952
- }
1953
- // A hold applies to the sessions that have not started as well as to the queue inside
1954
- // the one that has. They are left exactly as they were, which is what makes continuing
1955
- // afterwards the same act as continuing after anything else.
1956
- if (batch.pausing) {
1957
- entry.state = 'skipped';
1958
- entry.reason = 'the run was paused before this session started; its tasks are still queued';
1959
- continue;
1960
- }
1961
- entry.state = 'running';
1962
- this.bus.publish({
1963
- sessionId: entry.sessionId,
1964
- type: 'batch-session-started',
1965
- level: 'info',
1966
- message: `starting as part of a batch of ${batch.sessions.length} session(s), in ${batch.mode} mode`,
1967
- data: { batchId: batch.id },
1968
- });
1969
- // In the batch's mode as it is now: "run the rest without asking" in an earlier session
1970
- // switched the batch with it (see `setRunMode`). The hold is this batch's own.
1971
- const begun = await this.beginRun(entry.sessionId, batch.mode, browser, runGroup, batch.onlyTasks ? new Set(batch.onlyTasks) : undefined, {
1972
- shouldPause: () => batch.pausing,
1973
- laterInRun: batch.sessions.some((x) => x.ran > 0),
1974
- });
1975
- if (!begun.started) {
1976
- entry.state = 'skipped';
1977
- entry.reason = begun.reason;
1978
- continue;
1979
- }
1980
- const tally = await begun.done;
1981
- entry.ran = tally.ran;
1982
- entry.failed = tally.failed;
1983
- if (tally.refused) {
1984
- // Refused at its turn, before anything of it ran: not a failure of its tasks, which stay queued.
1985
- entry.state = 'skipped';
1986
- entry.reason = tally.refused;
1987
- }
1988
- else if (tally.error) {
1989
- entry.state = 'failed';
1990
- entry.reason = tally.error;
1991
- }
1992
- else if (tally.failed > 0) {
1993
- entry.state = 'failed';
1994
- entry.reason = `${tally.failed} task(s) did not finish: ${tally.failedTitles.join(', ')}`;
1995
- }
1996
- else if ((tally.stopped ?? 0) > 0) {
1997
- entry.state = 'stopped';
1998
- // The task cut short is counted as what it is: "after 0 task(s)" beside ran 1 read as if nothing ran (live run 2026-10-04).
1999
- const finished = tally.ran - (tally.stopped ?? 0);
2000
- entry.reason = `stopped by the operator: ${tally.stopped} task(s) cut short${finished > 0 ? `, after ${finished} that finished` : ''}; ${tally.leftQueued} still queued`;
2001
- }
2002
- else if (tally.paused) {
2003
- entry.state = 'stopped';
2004
- entry.reason = `paused after ${tally.ran} task(s); ${tally.leftQueued} still queued`;
2005
- }
2006
- else if (batch.stopping || tally.leftQueued > 0) {
2007
- entry.state = 'stopped';
2008
- entry.reason = `${tally.leftQueued} task(s) never started`;
2009
- }
2010
- else {
2011
- entry.state = 'done';
2012
- }
2013
- this.bus.publish({
2014
- sessionId: entry.sessionId,
2015
- type: 'batch-session-finished',
2016
- level: entry.state === 'failed' || tally.refused ? 'warn' : 'info',
2017
- message: tally.refused ? 'this session was refused at its turn inside the batch; its tasks stay queued' : `this session ended ${entry.state} inside the batch`,
2018
- data: { batchId: batch.id, ran: entry.ran, failed: entry.failed },
2019
- });
2020
- // A session refused at its turn breaks a chain as a failed one does.
2021
- if ((entry.state === 'failed' || tally.refused) && batch.onFailure === 'stop') {
2022
- batch.stopping = true;
2023
- this.bus.publish({
2024
- sessionId: entry.sessionId,
2025
- type: 'batch-stopped-early',
2026
- level: 'warn',
2027
- message: 'the batch is set to stop on a failure, so the sessions after this one stay as they are',
2028
- data: { batchId: batch.id },
2029
- });
2030
- }
2031
- }
2032
- }
2033
- catch (e) {
2034
- // Nothing above is expected to throw: a failing run resolves rather than rejects. If
2035
- // something does, the batch has to end here and say so, because this promise is not
2036
- // awaited anywhere and an escaping rejection would take the whole API process down.
2037
- const current = batch.sessions.find((s) => s.state === 'running');
2038
- if (current) {
2039
- current.state = 'failed';
2040
- current.reason = e.message;
2041
- }
2042
- this.bus.publish({
2043
- sessionId: current?.sessionId ?? batch.id,
2044
- type: 'batch-error',
2045
- level: 'error',
2046
- message: e.message,
2047
- });
2048
- }
2049
- finally {
2050
- for (const entry of batch.sessions) {
2051
- if (entry.state === 'waiting' || entry.state === 'running') {
2052
- entry.state = 'skipped';
2053
- entry.reason ??= 'the batch ended before this session ran';
2054
- }
2055
- }
2056
- // The window outlived every session in the batch; it does not outlive the batch.
2057
- await browser?.close().catch(() => undefined);
2058
- batch.running = false;
2059
- batch.finishedAt = new Date().toISOString();
2060
- }
2061
- }
2062
1018
  // --- plans ----------------------------------------------------------------------------
2063
- /** The brief the operator hands to a chat model, in the language the interface is in. */
2064
- /**
2065
- * The persona, assembled: the software part (fixed, this project's), the machine's projects
2066
- * by path, and the organisation's part (the operator's, edited on the plan page). Returned
2067
- * whole for copying and in parts for showing, so the page can say which is which.
2068
- */
2069
- async planBrief(opts) {
2070
- // The machine's projects go into the brief by absolute path, so a plan across a front
2071
- // end, a back end and a test suite is written with the folders that exist rather than
2072
- // with three paths the chat model had to ask for and the operator typed from memory.
2073
- const lang = opts.lang === 'bg' ? 'bg' : 'en';
2074
- const project = await this.project();
2075
- const projects = [
2076
- ...(project.rootDir ? [{ name: project.name, rootDir: project.rootDir, repo: project.repoOk, isDefault: true }] : []),
2077
- ...project.others.map((o) => ({ name: o.name, rootDir: o.rootDir, repo: o.repoOk, isDefault: false })),
2078
- ];
2079
- const [organisation, persona, work] = await Promise.all([
2080
- this.getContext('organisation', lang),
2081
- this.getContext('persona', lang),
2082
- this.getContext('work', lang),
2083
- ]);
2084
- /*
2085
- * Whether a run with nobody watching can start here, asked of the same rule the runner applies
2086
- * at the entrance — so the brief cannot tell Kerrigan the unattended button works while the run
2087
- * refuses it, which is exactly what the first test of her did.
2088
- */
2089
- const cfg = await this.settings.load();
2090
- const unattendedRule = { mode: 'unattended', allowedPrograms: cfg.execution.allowedPrograms, isolation: cfg.execution.isolation, lockedToConfirm: cfg.policyLock?.maxMode === 'confirm' };
2091
- /*
2092
- * Which of its refusals it is, asked in the order the rule asks them: the lock, then isolation,
2093
- * then the allowlist. Anything that was not isolation used to be told as an empty allowlist, so
2094
- * under a policy lock the brief sent the operator to fill in a list that was already full.
2095
- */
2096
- const unattendedBlocked = !unattendedPrecondition(unattendedRule)
2097
- ? undefined
2098
- : unattendedRule.lockedToConfirm
2099
- ? 'lock'
2100
- : unattendedIsolationRefusal('unattended', cfg.execution.isolation)
2101
- ? 'isolation'
2102
- : 'allowlist';
2103
- return {
2104
- text: planBrief({
2105
- lang,
2106
- projects,
2107
- organisation: organisation.content,
2108
- organisationExample: organisation.example,
2109
- persona: persona.content,
2110
- personaExample: persona.example,
2111
- work: work.content,
2112
- workExample: work.example,
2113
- unattendedBlocked,
2114
- }),
2115
- software: planBrief({ lang, projects }),
2116
- organisation: organisation.content,
2117
- customised: organisation.customised,
2118
- example: organisation.example,
2119
- persona: persona.content,
2120
- personaCustomised: persona.customised,
2121
- personaExample: persona.example,
2122
- work: work.content,
2123
- workCustomised: work.customised,
2124
- workExample: work.example,
2125
- };
2126
- }
2127
- /**
2128
- * Reads a pasted plan and says what it means, or what is wrong with it.
2129
- *
2130
- * A valid plan is also checked against what the store already holds, because the most
2131
- * likely mistake with this page is not a malformed document: it is pressing the button
2132
- * twice, or pasting the plan that is already imported instead of the corrected one. That is
2133
- * reported, not refused — importing the same work twice is a thing people legitimately do.
2134
- */
2135
- async checkPlan(text) {
2136
- await this.init();
2137
- const check = checkPlan(text ?? '');
2138
- if (!check.ok)
2139
- return { ...check, duplicates: [] };
2140
- /*
2141
- * A plan can ask for version control in a folder that is not a repository on this machine.
2142
- * The document is not wrong; this machine is not ready for it. It is refused all the same,
2143
- * and the message says which of the two it is, because importing it would create sessions
2144
- * that claim a way back they do not have.
2145
- */
2146
- const repoIssues = [];
2147
- check.plan.sessions.forEach((session, i) => {
2148
- if (session.vcs?.enabled === false) {
2149
- // Without version control the project folder must still be there (live run 2026-10-03: not looked at).
2150
- const folder = (session.projectDir ?? '').trim();
2151
- if (folder && !existsSync(folder))
2152
- repoIssues.push({ path: `sessions[${i}].projectDir`, message: `${folder} does not exist. Name the session's project folder, or create it.` });
2153
- return;
2154
- }
2155
- const dir = plannedRepoDir(session);
2156
- const reason = repoUnusableReason(dir);
2157
- if (reason)
2158
- repoIssues.push({ path: `sessions[${i}].vcs.repoDir`, message: reason });
2159
- else if (!dir) {
2160
- repoIssues.push({
2161
- path: `sessions[${i}].vcs.repoDir`,
2162
- message: 'This session asks for version control but names no repository. Give it the absolute path of a git ' +
2163
- 'repository, or set "enabled": false for it.',
2164
- });
2165
- }
2166
- });
2167
- if (repoIssues.length > 0)
2168
- return { ok: false, issues: repoIssues, warnings: check.warnings, duplicates: [] };
2169
- /*
2170
- * A branch to carry on must be there to carry on — unless a session before it in this same plan
2171
- * is the one that makes it, in this same repository. Refused now, with the branches that are
2172
- * there, rather than at the first run with a task refused.
2173
- *
2174
- * The repository is part of the question. A branch is a branch of one repository, and the name
2175
- * alone let a branch an earlier session makes somewhere else count here: the plan was accepted,
2176
- * and the session failed at its first task with "no such local branch" — the failure this check
2177
- * exists to bring forward.
2178
- */
2179
- for (const [i, session] of check.plan.sessions.entries()) {
2180
- const wanted = session.vcs?.enabled === false ? '' : (session.vcs?.existingBranch ?? '').trim();
2181
- if (!wanted)
2182
- continue;
2183
- const dir = plannedRepoDir(session);
2184
- const here = normaliseDir(dir);
2185
- const madeEarlier = check.plan.sessions
2186
- .slice(0, i)
2187
- .some((e) => normaliseDir(plannedRepoDir(e)) === here && branchesMadeBy(e).includes(wanted));
2188
- if (madeEarlier || (await branchExists(dir, wanted)))
2189
- continue;
2190
- const have = await localBranches(dir);
2191
- repoIssues.push({
2192
- path: `sessions[${i}].vcs.existingBranch`,
2193
- message: `${dir} has no local branch "${wanted}" to carry on. ` +
2194
- (have.length > 0 ? `Its branches: ${have.slice(0, 20).join(', ')}.` : 'It has no branches yet.') +
2195
- ' Give the exact name, or use startFrom "branch" to start a new one.',
2196
- });
2197
- }
2198
- if (repoIssues.length > 0)
2199
- return { ok: false, issues: repoIssues, warnings: check.warnings, duplicates: [] };
2200
- /*
2201
- * A check the runner refuses for its own command line under these Settings: every start of its task
2202
- * is refused for it, so it is said here, at the check, and not only at the start (live run 2026-10-04:
2203
- * "check" said ok and the first start was refused). A warning, since the Settings may be changed.
2204
- */
2205
- const cfg = await this.settings.load();
2206
- const shell = preferredShell(cfg.execution.defaultShell);
2207
- const others = [cfg.project.rootDir, ...cfg.project.others.map((o) => o.rootDir)];
2208
- const lineWarnings = [];
2209
- check.plan.sessions.forEach((session, i) => {
2210
- const cwd = (session.vcs?.enabled === false ? '' : plannedRepoDir(session)) || (session.projectDir ?? '').trim() || cfg.resolved.cwd;
2211
- const roots = sessionRoots(cwd, others);
2212
- session.tasks.forEach((task, j) => {
2213
- for (const c of task.checks ?? []) {
2214
- const run = c.run?.trim();
2215
- if (!run)
2216
- continue;
2217
- const why = lineRefusal(run, c.shell ?? shell, c.cwd ? resolve(cwd, c.cwd) : cwd, cfg.execution, roots);
2218
- if (why)
2219
- lineWarnings.push(`sessions[${i}].tasks[${j}] ("${task.title}"): the check "${c.name}" is refused by the runner for its own command line, so the task cannot start until it is changed: ${checkRefusalForOperator(why)}.`);
2220
- }
2221
- });
2222
- });
2223
- return { ...check, warnings: [...check.warnings, ...lineWarnings], duplicates: await this.findDuplicates(check.plan) };
2224
- }
2225
- /**
2226
- * Sessions the store already holds that this plan would create again, task for task.
2227
- *
2228
- * Matched on the name and on the text that would actually be sent, in order. Not on the
2229
- * level 2, the model or the branch names: those are edited on a session after an import, and
2230
- * a session whose instructions were tightened by hand is still the same session this plan
2231
- * describes.
2232
- */
2233
- async findDuplicates(plan) {
2234
- const existing = await this.store.listSessions();
2235
- const out = [];
2236
- for (const planned of plan.sessions) {
2237
- const wanted = plannedSessionSignature(planned);
2238
- const match = existing.find((s) => s.name.trim().toLowerCase() === planned.name.trim().toLowerCase() &&
2239
- s.tasks.length === planned.tasks.length &&
2240
- s.tasks.map((t) => taskSignature(t)).join('\u0001') === wanted);
2241
- if (match) {
2242
- out.push({ name: match.name, sessionId: match.id, createdAt: match.createdAt, tasks: match.tasks.length });
2243
- }
2244
- }
2245
- return out;
2246
- }
2247
- /**
2248
- * Validates a plan and creates everything in it. Nothing is started.
2249
- *
2250
- * A plan that does not validate is refused as a whole rather than imported in part: half a
2251
- * plan in the session list is harder to recognise, and harder to undo, than none of it.
2252
- */
2253
- async importPlan(text) {
2254
- await this.init();
2255
- const check = await this.checkPlan(text);
2256
- if (!check.ok)
2257
- return { ok: false, check };
2258
- const cfg = await this.settings.load();
2259
- /*
2260
- * The persona in force right now is the one this import carries. Read here, once, and written
2261
- * into every task, so a session keeps the approach it was created with: changing the field
2262
- * afterwards changes the next import, not work already queued. The content does not depend on
2263
- * the language asked for; only the shipped example does.
2264
- */
2265
- const persona = (await this.getContext('persona', 'en')).content;
2266
- // No default models passed: a session the plan gives no model follows Settings at run time.
2267
- // The default project is passed, so a session the plan gives no folder works where one made
2268
- // on the Sessions page would, and not in execution.cwd.
2269
- const result = await importPlan(this.store, check.plan, '', '', persona, (cfg.project?.rootDir ?? '').trim());
2270
- return {
2271
- ok: true,
2272
- result: { ...result, warnings: [...check.warnings, ...result.warnings] },
2273
- summary: check.summary,
2274
- // The sessions this import has just made a second copy of, reported after the fact for
2275
- // the same reason it is reported before: so nobody has to notice it in a list.
2276
- duplicates: check.duplicates,
2277
- };
2278
- }
2279
1019
  // --- the workspace and its chat (2026-10-17, "like Windsurf") ------------------------------
2280
1020
  /** The project folder the workbench has open: Settings → the default project. */
2281
1021
  async workspace() {
@@ -2295,6 +1035,15 @@ let OperatorService = class OperatorService {
2295
1035
  throw new Error(ws.problem ?? 'No project folder is open.');
2296
1036
  return await workspaceFile(ws.dir, path);
2297
1037
  }
1038
+ /** The editor's text saved over a file of the open folder, over the version it was made on (see `saveWorkspaceFile`). */
1039
+ async saveWorkspaceFile(path, text, base) {
1040
+ const ws = await this.workspace();
1041
+ if (!ws.ok)
1042
+ throw new Error(ws.problem ?? 'No project folder is open.');
1043
+ const saved = await saveWorkspaceFile(ws.dir, path, text, base);
1044
+ console.log(`[editor] saved ${saved.path} (${saved.size} bytes)`);
1045
+ return saved;
1046
+ }
2298
1047
  /** The open folder's git, as an IDE's Source Control view shows it (see `workspaceGit.ts`). Read-only. */
2299
1048
  async workspaceGit() {
2300
1049
  const ws = await this.workspace();
@@ -2314,18 +1063,43 @@ let OperatorService = class OperatorService {
2314
1063
  throw new Error(ws.problem ?? 'No project folder is open.');
2315
1064
  return await workspaceGitVersions(ws.dir, area, path, commit);
2316
1065
  }
1066
+ /**
1067
+ * Kerrigan (2026-10-20): the persona the operator may give to a chat of their own, in the language asked for, with
1068
+ * this machine's limits in it and the projects of Settings — each one's folder, its branch now, and the level 2 the
1069
+ * operator wrote for it. Nothing is sent anywhere: the page saves it or copies it. See `plan/kerrigan.ts`; in a
1070
+ * language she is not written out in, the page fills in the names of the controls (`filled: false`).
1071
+ */
1072
+ async kerrigan(lang) {
1073
+ const cfg = await this.settings.load();
1074
+ const p = await this.project();
1075
+ const projects = [
1076
+ ...(p.rootDir ? [{ name: p.name, rootDir: p.rootDir, ...(p.branch ? { branch: p.branch } : {}), level2: p.level2, chat: true }] : []),
1077
+ ...p.others.map((o) => ({ name: o.name, rootDir: o.rootDir, ...(o.branch ? { branch: o.branch } : {}), level2: o.level2 })),
1078
+ ];
1079
+ const text = kerriganPersona(lang, {
1080
+ version: botVersion(),
1081
+ maxIterations: cfg.limits.maxIterations,
1082
+ maxRunMinutes: cfg.limits.maxRunMinutes,
1083
+ autoContinue: cfg.limits.autoContinue ?? 0,
1084
+ maxReviewRounds: cfg.limits.maxReviewRounds ?? 2,
1085
+ maxSubtasks: cfg.limits.maxSubtasks ?? 20,
1086
+ projects,
1087
+ });
1088
+ return { lang, fileName: kerriganFileName(lang), text, filled: lang === 'en' || lang === 'bg' };
1089
+ }
2317
1090
  /** The chat's conversations, newest first. */
2318
1091
  async chatThreads() {
2319
1092
  await this.init();
2320
1093
  return (await this.store.listSessions())
2321
- .filter((s) => s.kind === 'chat')
1094
+ // A worker's session (two chats) is not a conversation of the list: it is shown under its lead's messages.
1095
+ .filter((s) => s.kind === 'chat' && !s.workerOf)
2322
1096
  .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
2323
1097
  .map((s) => ({ id: s.id, name: s.name, createdAt: s.createdAt, status: s.status, turns: s.tasks.length, running: this.running.has(s.id), repoDir: s.vcs?.repoDir || s.projectDir }));
2324
1098
  }
2325
1099
  /**
2326
1100
  * A message written in the chat. With no conversation yet, one is made in the open project folder: a session of
2327
- * kind `chat`, one branch for all of it, no independent review, plan mode off, so each message is answered as
2328
- * it would be in an IDE's chat. The message becomes a task of it, queued; the caller starts it (the start window
1101
+ * kind `chat`, one branch for all of it, reviewed by a conversation of its own unless "Review" under the box is
1102
+ * unticked (2026-10-20), plan mode as chosen there, so each message is answered as it would be in an IDE's chat. The message becomes a task of it, queued; the caller starts it (the start window
2329
1103
  * the first time, where the work starts being asked once). While the conversation is working, the message is a
2330
1104
  * note to the task in flight, which the chat gets with its next report.
2331
1105
  */
@@ -2355,8 +1129,14 @@ let OperatorService = class OperatorService {
2355
1129
  session = await this.store.updateSession(created.id, (s) => {
2356
1130
  s.kind = 'chat';
2357
1131
  s.onFailure = 'continue';
2358
- s.review = { enabled: false, model: '' };
2359
- s.planMode = 'off';
1132
+ /*
1133
+ * The review as chosen under the box (operator, 2026-10-20): the box is on unless unticked, and the page always
1134
+ * says which. A second conversation checks the work when it says it is done, and sends back what it finds; it
1135
+ * was off for the chat from 2026-10-17. Asked for without the box — the API on its own, a script — it stays off.
1136
+ */
1137
+ s.review = { enabled: input.review === true, model: '' };
1138
+ // Plan mode as chosen under the box (2026-10-20, "as in Claude Code"): the plan first, approved by the operator.
1139
+ s.planMode = input.planMode ? 'approve' : 'off';
2360
1140
  /*
2361
1141
  * No version control of the bot's own (2026-10-17): no branch, no commit, no question about where the work
2362
1142
  * starts. The chat works on the branch the folder is on, with what is in it, as an IDE's chat does; each
@@ -2364,6 +1144,17 @@ let OperatorService = class OperatorService {
2364
1144
  */
2365
1145
  s.vcs = { ...(s.vcs ?? DEFAULT_VCS), enabled: false, repoDir: '' };
2366
1146
  s.projectDir = ws.dir;
1147
+ /*
1148
+ * Two chats (operator, 2026-10-20): this conversation is the lead's, and a worker carries out its subtasks. The
1149
+ * lead judges the worker's reports, so there is no review of its own.
1150
+ */
1151
+ if (input.lead) {
1152
+ s.lead = {
1153
+ ...(input.workerManualModel ? { workerManualModel: true } : {}),
1154
+ ...(!input.workerManualModel && input.workerModel?.trim() ? { workerModel: input.workerModel.trim() } : {}),
1155
+ };
1156
+ s.review = { enabled: false, model: '' };
1157
+ }
2367
1158
  // The model chosen in the chat for this conversation: the operator's word, which outranks Settings.
2368
1159
  if (input.manualModel)
2369
1160
  s.manualModel = true;
@@ -2379,6 +1170,12 @@ let OperatorService = class OperatorService {
2379
1170
  level2: '',
2380
1171
  prompt: text,
2381
1172
  });
1173
+ // The language the workbench is in, for what the chat's window says when the work has ended (`chatWindowNotice`).
1174
+ if (input.lang && session.lang !== input.lang) {
1175
+ await this.store.updateSession(session.id, (s) => {
1176
+ s.lang = input.lang;
1177
+ });
1178
+ }
2382
1179
  // After going back, the conversation is told with this message: it still holds what was undone.
2383
1180
  const pending = (await this.store.getSession(session.id))?.rewindNote;
2384
1181
  if (pending) {
@@ -2438,193 +1235,7 @@ let OperatorService = class OperatorService {
2438
1235
  return { ok: true, message, text: task.prompt, ...(safety ? { safety } : {}) };
2439
1236
  }
2440
1237
  // --- the repository, read-only, for the workbench (2026-10-14) ------------------------------
2441
- /**
2442
- * Where a session's work is in its repository: the session's branch in per-session mode, the task's own
2443
- * branch when one is named, else what is checked out. Read-only; nothing here moves anything.
2444
- */
2445
- async repoRefOf(sessionId, taskId) {
2446
- await this.init();
2447
- const session = await this.store.getSession(sessionId);
2448
- if (!session)
2449
- throw new Error('No such session.');
2450
- const dir = repoDirOf(session);
2451
- if (!dir || !looksLikeRepo(dir))
2452
- throw new Error('This session has no repository to show.');
2453
- const task = taskId ? session.tasks.find((t) => t.id === taskId) : undefined;
2454
- const candidates = [
2455
- ...(task?.vcs?.commit ? [task.vcs.commit] : []),
2456
- ...(session.vcs?.enabled && session.vcs.branchMode === 'per-session' ? [sessionBranchName(session)] : []),
2457
- 'HEAD',
2458
- ];
2459
- for (const ref of candidates) {
2460
- const r = await git(dir, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
2461
- if (r.ok && r.stdout)
2462
- return { dir, ref: r.stdout, label: ref === 'HEAD' ? 'HEAD' : ref.length >= 40 ? ref.slice(0, 8) : ref };
2463
- }
2464
- throw new Error('The repository has no commit to show yet.');
2465
- }
2466
- /** One folder of the repository at that point: its folders and files, folders first. */
2467
- async repoTree(sessionId, path = '', taskId) {
2468
- const clean = path.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
2469
- if (clean.split('/').some((p) => p === '..'))
2470
- throw new Error('That path is not inside the repository.');
2471
- const { dir, ref, label } = await this.repoRefOf(sessionId, taskId);
2472
- const r = await git(dir, ['ls-tree', '-l', clean ? `${ref}:${clean}` : ref]);
2473
- if (!r.ok)
2474
- throw new Error(clean ? `There is no folder ${clean} there.` : 'The repository could not be read.');
2475
- const entries = r.stdout
2476
- .split('\n')
2477
- .filter(Boolean)
2478
- .map((line) => {
2479
- const [meta, name] = line.split('\t');
2480
- const [, type, , size] = (meta ?? '').split(/\s+/);
2481
- return { name: name ?? '', path: clean ? `${clean}/${name}` : (name ?? ''), type: type === 'tree' ? 'dir' : 'file', ...(type === 'blob' && size && size !== '-' ? { size: Number(size) } : {}) };
2482
- })
2483
- .filter((e) => e.name)
2484
- .sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'dir' ? -1 : 1));
2485
- return { ref, label, path: clean, entries };
2486
- }
2487
- /** One file of the repository at that point, as text; a binary or very large file is said to be one. */
2488
- async repoFile(sessionId, path, taskId) {
2489
- const clean = path.replace(/\\/g, '/').replace(/^\/+/, '');
2490
- if (!clean || clean.split('/').some((p) => p === '..'))
2491
- throw new Error('That path is not inside the repository.');
2492
- const { dir, ref, label } = await this.repoRefOf(sessionId, taskId);
2493
- const got = await fileAt(dir, ref, clean, 2 * 1024 * 1024);
2494
- if (!got.bytes && !got.tooLarge)
2495
- throw new Error(`There is no file ${clean} there.`);
2496
- const binary = !!got.bytes && got.bytes.subarray(0, 8000).includes(0);
2497
- return { ref, label, path: clean, text: got.bytes && !binary ? got.bytes.toString('utf8').replace(/^/, '') : null, binary, tooLarge: got.tooLarge };
2498
- }
2499
- /** The commits on the session's line, newest first, each with the task that made it when one did. */
2500
- async repoLog(sessionId, limit = 60) {
2501
- const { dir, ref, label } = await this.repoRefOf(sessionId);
2502
- const session = (await this.store.getSession(sessionId));
2503
- const r = await git(dir, ['log', `-${Math.max(1, Math.min(limit, 300))}`, '--format=%H%x09%an%x09%aI%x09%s', ref]);
2504
- const byCommit = new Map();
2505
- for (const t of session.tasks) {
2506
- for (const v of [t.vcs, ...(t.attempts ?? []).map((a) => a.vcs)])
2507
- if (v?.commit)
2508
- byCommit.set(v.commit, t);
2509
- }
2510
- const commits = (r.ok ? r.stdout.split('\n').filter(Boolean) : []).map((line) => {
2511
- const [sha = '', author = '', at = '', subject = ''] = line.split('\t');
2512
- const task = byCommit.get(sha);
2513
- return { sha, subject, author, at, ...(task ? { taskId: task.id, taskTitle: task.title } : {}) };
2514
- });
2515
- return { ref, label, commits };
2516
- }
2517
1238
  // --- Kerrigan: what happened, and her changes to existing work (2026-10-14) ---------------------
2518
- /** What happened in these sessions (all, when none are named), for Kerrigan, with the operator's note. */
2519
- async kerriganReport(opts = {}) {
2520
- await this.init();
2521
- const all = await this.store.listSessions();
2522
- const wanted = (opts.sessionIds ?? []).filter(Boolean);
2523
- const taskIds = (opts.taskIds ?? []).filter(Boolean);
2524
- const sessions = all.filter((s) => (wanted.length > 0 ? wanted.includes(s.id) : taskIds.length > 0 ? s.tasks.some((t) => taskIds.includes(t.id)) : true));
2525
- if (sessions.length === 0)
2526
- throw new Error('None of these sessions exists.');
2527
- if ((opts.note ?? '').length > MAX_INSTRUCTION_CHARS)
2528
- throw new Error(`The note is ${(opts.note ?? '').length} characters; it can be at most ${MAX_INSTRUCTION_CHARS}.`);
2529
- return { text: kerriganReport(sessions, { note: opts.note, taskIds }), sessions: sessions.length };
2530
- }
2531
- /** Kerrigan's answer read against the sessions as they are now; nothing is changed. */
2532
- async checkChanges(text) {
2533
- await this.init();
2534
- return checkChanges(text ?? '', await this.store.listSessions());
2535
- }
2536
- /**
2537
- * Applies Kerrigan's changes one by one, through the paths the buttons use, and stops at the first that is
2538
- * refused, saying which were done. Nothing is started.
2539
- */
2540
- async applyChanges(text) {
2541
- const check = await this.checkChanges(text);
2542
- if (!check.ok)
2543
- return { ok: false, check, applied: [] };
2544
- const cfg = await this.settings.load();
2545
- const persona = (await this.getContext('persona', 'en')).content;
2546
- const applied = [];
2547
- for (const r of check.changes) {
2548
- const c = r.change;
2549
- try {
2550
- switch (c.op) {
2551
- case 'addTask': {
2552
- const session = await this.store.getSession(r.sessionId);
2553
- if (!session)
2554
- throw new Error('The session is gone.');
2555
- const afterId = c.after !== undefined ? checkTaskRef(session, c.after) : undefined;
2556
- const reference = afterId ? session.tasks.find((t) => t.id === afterId) : session.tasks.at(-1);
2557
- const level2 = c.task.level2.trim()
2558
- ? composeLevel2({ level2: '', goal: '' }, c.task, persona)
2559
- : (reference?.level2 ?? personaBlock(persona));
2560
- const added = await this.store.addTask(r.sessionId, {
2561
- title: c.task.title,
2562
- level2,
2563
- prompt: composePrompt(c.task),
2564
- vcsPlan: c.task.vcs,
2565
- checks: c.task.checks,
2566
- reviewEnabled: c.task.review,
2567
- readOnly: c.task.readOnly || undefined,
2568
- scope: c.task.scope.length > 0 ? c.task.scope : undefined,
2569
- outputs: c.task.outputs.length > 0 ? c.task.outputs : undefined,
2570
- });
2571
- if (afterId) {
2572
- await this.store.updateSession(r.sessionId, (s) => {
2573
- const from = s.tasks.findIndex((t) => t.id === added.id);
2574
- const [moved] = s.tasks.splice(from, 1);
2575
- s.tasks.splice(s.tasks.findIndex((t) => t.id === afterId) + 1, 0, moved);
2576
- });
2577
- }
2578
- break;
2579
- }
2580
- case 'editTask':
2581
- await this.updateTask(r.sessionId, r.taskId, {
2582
- ...(c.title ? { title: c.title } : {}),
2583
- ...(c.prompt ? { prompt: c.prompt } : {}),
2584
- ...(c.checks ? { checks: c.checks } : {}),
2585
- ...(c.scope ? { scope: c.scope } : {}),
2586
- });
2587
- break;
2588
- case 'removeTask':
2589
- await this.deleteTask(r.sessionId, r.taskId);
2590
- break;
2591
- case 'continue':
2592
- await this.continueTask(r.sessionId, r.taskId, c.instruction);
2593
- break;
2594
- case 'newPrompt':
2595
- await this.rerunTask(r.sessionId, r.taskId, { prompt: c.prompt }, { buildOnFinished: true });
2596
- break;
2597
- case 'runAgain':
2598
- await this.rerunTask(r.sessionId, r.taskId, c.prompt ? { prompt: c.prompt } : {});
2599
- break;
2600
- case 'undo': {
2601
- const done = await this.undoTask(r.sessionId, r.taskId, c.how);
2602
- if (!done.ok)
2603
- throw new Error(done.problem ?? 'it could not be undone');
2604
- break;
2605
- }
2606
- case 'accept':
2607
- await this.acceptTask(r.sessionId, r.taskId, c.note);
2608
- break;
2609
- case 'note':
2610
- await this.addTaskNote(r.sessionId, r.taskId, c.text);
2611
- break;
2612
- }
2613
- applied.push({ index: r.index, says: r.says });
2614
- await appendSessionLog(cfg.resolved.runsDir, r.sessionId, { type: 'kerrigan-change', message: r.says, data: { op: c.op, ...(r.taskId ? { taskId: r.taskId } : {}) } }).catch(() => undefined);
2615
- this.bus.publish({ sessionId: r.sessionId, ...(r.taskId ? { taskId: r.taskId } : {}), type: 'kerrigan-change', level: 'info', message: `from Kerrigan's answer: ${r.says}` });
2616
- }
2617
- catch (e) {
2618
- return {
2619
- ok: false,
2620
- applied,
2621
- failedAt: r.index,
2622
- problem: `Change ${r.index + 1} (${r.says}) was refused: ${e.message}${applied.length > 0 ? ` The ${applied.length} before it were made.` : ' Nothing was changed.'}`,
2623
- };
2624
- }
2625
- }
2626
- return { ok: true, applied };
2627
- }
2628
1239
  // --- approvals ------------------------------------------------------------------------
2629
1240
  /**
2630
1241
  * Asks the operator to choose the model in the Copilot window, when the runner could not (operator's
@@ -2642,9 +1253,9 @@ let OperatorService = class OperatorService {
2642
1253
  sessionId: ask.sessionId,
2643
1254
  taskId: '',
2644
1255
  stepId: 0,
2645
- description: ask.asked ? `Choose "${ask.asked}" in the Copilot window` : 'Choose the model in the Copilot window',
1256
+ description: `${ask.asked ? `Choose "${ask.asked}" in the Copilot window` : 'Choose the model in the Copilot window'}${ask.review ? ' for the review' : ask.role ? ` for the ${ask.role}` : ''}`,
2646
1257
  createdAt: new Date().toISOString(),
2647
- model: { asked: ask.asked, shown: ask.shown, why: ask.why, tries: ask.tries, ...(ask.manual ? { manual: true } : {}) },
1258
+ model: { asked: ask.asked, shown: ask.shown, why: ask.why, tries: ask.tries, ...(ask.manual ? { manual: true } : {}), ...(ask.review ? { review: true } : {}), ...(ask.role ? { role: ask.role } : {}) },
2648
1259
  };
2649
1260
  this.waiting.set(approval.id, {
2650
1261
  approval,
@@ -2654,6 +1265,49 @@ let OperatorService = class OperatorService {
2654
1265
  message: `choose "${ask.asked}" in the Copilot window, then answer on the card`, data: { approvalId: approval.id, model: approval.model } });
2655
1266
  });
2656
1267
  }
1268
+ /**
1269
+ * The lead's question for the operator (two chats, 2026-10-20): what only a person can decide, on a card in the
1270
+ * conversation, waiting in every mode — an unattended run included, since nobody else can answer it — until it is
1271
+ * answered or the task is stopped.
1272
+ */
1273
+ askLeadQuestion(ask, signal) {
1274
+ return new Promise((resolveAnswer) => {
1275
+ if (signal.aborted) {
1276
+ resolveAnswer('stop');
1277
+ return;
1278
+ }
1279
+ const approval = {
1280
+ id: newId('a-'),
1281
+ sessionId: ask.sessionId,
1282
+ taskId: ask.taskId,
1283
+ stepId: 0,
1284
+ description: `The lead asks: ${ask.question}`,
1285
+ createdAt: new Date().toISOString(),
1286
+ question: { text: ask.question, ...(ask.why ? { why: ask.why } : {}), options: ask.options },
1287
+ };
1288
+ this.waiting.set(approval.id, {
1289
+ approval,
1290
+ // A stop, the end of the run, "abort" on the card: the task stops at the question.
1291
+ resolve: () => resolveAnswer('stop'),
1292
+ resolveAnswer,
1293
+ });
1294
+ this.bus.publish({ sessionId: ask.sessionId, taskId: ask.taskId, type: 'approval-requested', level: 'warn',
1295
+ message: `the lead asks the operator: ${ask.question}`, data: { approvalId: approval.id, question: approval.question } });
1296
+ });
1297
+ }
1298
+ /** The operator's answer to the lead's question. */
1299
+ answerQuestion(approvalId, text) {
1300
+ const w = this.waiting.get(approvalId);
1301
+ if (!w?.resolveAnswer)
1302
+ return { ok: false, problem: 'No question of the lead is waiting under that id.' };
1303
+ if (!text.trim())
1304
+ return { ok: false, problem: 'Write the answer first.' };
1305
+ this.waiting.delete(approvalId);
1306
+ w.resolveAnswer({ answer: text.trim() });
1307
+ this.bus.publish({ sessionId: w.approval.sessionId, taskId: w.approval.taskId, type: 'approval-decided', level: 'info',
1308
+ message: 'the operator answered the lead', data: { approvalId, question: true } });
1309
+ return { ok: true };
1310
+ }
2657
1311
  /**
2658
1312
  * A task's plan, put to the operator (plan mode `approve`, in a run that asks before each command): it
2659
1313
  * waits on the approvals card, on every page, until it is approved, sent back for another, or the task
@@ -2702,8 +1356,9 @@ let OperatorService = class OperatorService {
2702
1356
  message: `plan: ${action}${text ? ' (with a note)' : ''}`, data: { approvalId, action, plan: true } });
2703
1357
  return { ok: true };
2704
1358
  }
1359
+ /** What waits for the operator; of one session, its worker's included (two chats: they are asked in its conversation). */
2705
1360
  pendingApprovals(sessionId) {
2706
- return [...this.waiting.values()].map((w) => w.approval).filter((a) => !sessionId || a.sessionId === sessionId);
1361
+ return [...this.waiting.values()].map((w) => w.approval).filter((a) => !sessionId || a.sessionId === sessionId || this.workerLeads.get(a.sessionId) === sessionId);
2707
1362
  }
2708
1363
  /**
2709
1364
  * Answers one pending approval.
@@ -2719,7 +1374,7 @@ let OperatorService = class OperatorService {
2719
1374
  return { ok: false };
2720
1375
  this.waiting.delete(approvalId);
2721
1376
  if (action === 'run-all')
2722
- this.setRunMode(w.approval.sessionId, 'unattended');
1377
+ this.setRunMode(this.runKey(w.approval.sessionId), 'unattended');
2723
1378
  const decision = action === 'run' || action === 'run-all'
2724
1379
  ? { action: 'run' }
2725
1380
  : action === 'skip'
@@ -2762,33 +1417,21 @@ let OperatorService = class OperatorService {
2762
1417
  * one would read.
2763
1418
  */
2764
1419
  run.policy.mode = mode;
2765
- /*
2766
- * A batch is one run. The dialog behind "run the rest without asking" says "until this run
2767
- * ends", and the run the operator started is the batch: the switch used to reach only the
2768
- * session on screen, and the next session started in the batch's old mode and asked again. So
2769
- * the sessions the batch has not reached yet start in the mode it is switched to — and back,
2770
- * when the asking is switched on again. Each still meets the unattended precondition as it
2771
- * starts (see `beginRun`), under the settings of that moment, and the run recorded on it
2772
- * (`Session.runGroup`) keeps the mode it was started in.
2773
- */
2774
- const batch = this.batch?.running && this.batch.sessions.some((e) => e.sessionId === sessionId && e.state === 'running') ? this.batch : null;
2775
- if (batch)
2776
- batch.mode = mode;
2777
1420
  this.bus.publish({
2778
1421
  sessionId,
2779
1422
  type: 'run-mode-changed',
2780
1423
  level: mode === 'unattended' ? 'warn' : 'info',
2781
1424
  message: mode === 'unattended'
2782
- ? `the rest of this run${batch ? ', the sessions of the batch after this one included,' : ''} will execute without asking; denied patterns are still refused`
2783
- : `every further step${batch ? ', in this session and the ones of the batch after it,' : ''} will be shown for approval again`,
2784
- data: { mode, ...(batch ? { batchId: batch.id } : {}) },
1425
+ ? 'the rest of this run will execute without asking; denied patterns are still refused'
1426
+ : 'every further step will be shown for approval again',
1427
+ data: { mode },
2785
1428
  });
2786
1429
  if (mode === 'unattended') {
2787
1430
  for (const [id, w] of this.waiting) {
2788
- if (w.approval.sessionId !== sessionId)
1431
+ if (this.runKey(w.approval.sessionId) !== sessionId)
2789
1432
  continue;
2790
- // A fetch waits for its own answer: "run the rest without asking" is not an answer to it.
2791
- if (w.approval.network || w.approval.model)
1433
+ // A fetch waits for its own answer: "run the rest without asking" is not an answer to it; nor is a question.
1434
+ if (w.approval.network || w.approval.model || w.approval.question || w.approval.plan)
2792
1435
  continue;
2793
1436
  this.waiting.delete(id);
2794
1437
  w.resolve({ action: 'run' });
@@ -2811,7 +1454,7 @@ let OperatorService = class OperatorService {
2811
1454
  // This is checked per step rather than captured once, which is what makes the switch
2812
1455
  // take effect from the very next step instead of the next run. A held step is the
2813
1456
  // exception: it is asked about in an unattended run too, which is the point of holding it.
2814
- if (!held && this.running.get(ctx.sessionId ?? '')?.mode === 'unattended') {
1457
+ if (!held && this.running.get(this.runKey(ctx.sessionId ?? ''))?.mode === 'unattended') {
2815
1458
  resolvePromise({ action: 'run' });
2816
1459
  return;
2817
1460
  }
@@ -2836,24 +1479,7 @@ let OperatorService = class OperatorService {
2836
1479
  recentEvents(sessionId) {
2837
1480
  return this.bus.recent(sessionId);
2838
1481
  }
2839
- subscribe(sessionId, handler) {
2840
- return this.bus.subscribe(sessionId, handler);
2841
- }
2842
1482
  // --- version control ----------------------------------------------------------------------
2843
- /**
2844
- * Version control for the sessions of a run, one group per repository, with what can be done about
2845
- * it from the run screen. See `vcs/runPreflight.ts`. Only sessions that have something queued count.
2846
- */
2847
- async runVcs(sessionIds, onlyTasks) {
2848
- await this.init();
2849
- const sessions = [];
2850
- for (const id of sessionIds) {
2851
- const s = await this.store.getSession(id);
2852
- if (s && queuedToRun(s, onlyTasks).length > 0)
2853
- sessions.push(s);
2854
- }
2855
- return await runVcsPreflight(sessions, () => this.store.listSessions());
2856
- }
2857
1483
  /**
2858
1484
  * The run's version control preflight: why the run may not start, said before anything opens the
2859
1485
  * browser, creates a task attempt or emits `task-started`; null when it may.
@@ -2950,6 +1576,20 @@ let OperatorService = class OperatorService {
2950
1576
  await appendRunLog(cfg.resolved.runsDir, runId, log).catch(() => undefined);
2951
1577
  return reason;
2952
1578
  }
1579
+ /**
1580
+ * Version control for the sessions of a run, one group per repository, with what can be done about
1581
+ * it from the run screen. See `vcs/runPreflight.ts`. Only sessions that have something queued count.
1582
+ */
1583
+ async runVcs(sessionIds, onlyTasks) {
1584
+ await this.init();
1585
+ const sessions = [];
1586
+ for (const id of sessionIds) {
1587
+ const s = await this.store.getSession(id);
1588
+ if (s && queuedToRun(s, onlyTasks).length > 0)
1589
+ sessions.push(s);
1590
+ }
1591
+ return await runVcsPreflight(sessions, () => this.store.listSessions());
1592
+ }
2953
1593
  /**
2954
1594
  * Why the session's next task cannot start because it contradicts itself — read-only and scoped, or
2955
1595
  * a file check that needs a change the task may not make — or null. The part of the contract that
@@ -3008,87 +1648,6 @@ let OperatorService = class OperatorService {
3008
1648
  }
3009
1649
  return conflicts;
3010
1650
  }
3011
- /**
3012
- * How a task contradicts itself, asked by a page: a task that ended `contract-conflict`, or a queued
3013
- * one a run refused to start for it. Changes nothing.
3014
- */
3015
- async contractCheck(sessionId, taskId) {
3016
- await this.init();
3017
- const session = await this.store.getSession(sessionId);
3018
- if (!session)
3019
- throw new Error('No such session.');
3020
- const task = session.tasks.find((t) => t.id === taskId);
3021
- if (!task)
3022
- throw new Error('No such task.');
3023
- return { conflicts: await this.contractFor(session, task) };
3024
- }
3025
- /**
3026
- * Applies the chosen way out of each contradiction and puts the task back in the queue.
3027
- *
3028
- * `choices` holds one entry per contradiction `contractCheck` names, in its order: the index of the
3029
- * fix taken, or -1 to leave that one as it is. Judged again here rather than trusted from the page,
3030
- * and refused when the contradictions are no longer the ones the operator chose from — an edit in
3031
- * another tab, a check that passes now. A queued task is edited in place; one that has run is queued
3032
- * again with the change, its attempt kept on the record as any re-run keeps it. Nothing starts.
3033
- */
3034
- async applyContractFix(sessionId, taskId, choices,
3035
- /** The contradictions the choices were made from, as the page was shown them. */
3036
- expect) {
3037
- await this.init();
3038
- const session = await this.store.getSession(sessionId);
3039
- if (!session)
3040
- throw new Error('No such session.');
3041
- const task = session.tasks.find((t) => t.id === taskId);
3042
- if (!task)
3043
- throw new Error('No such task.');
3044
- if (task.status === 'running' || task.status === 'waiting-approval')
3045
- throw new Error('This task is running. Stop the session first.');
3046
- const conflicts = await this.contractFor(session, task);
3047
- // The same ones, not only as many: a fix chosen for one contradiction must not be applied to another.
3048
- const same = Array.isArray(expect) ? expect.length === conflicts.length && expect.every((x, i) => x === conflicts[i].text) : true;
3049
- if (!Array.isArray(choices) || choices.length !== conflicts.length || !same) {
3050
- throw new Error(`The task's contradictions are not the ones shown (${conflicts.length} now). Look again before applying a fix.`);
3051
- }
3052
- const chosen = conflicts.flatMap((c, i) => {
3053
- const at = choices[i] ?? -1;
3054
- if (at === -1)
3055
- return [];
3056
- const fix = Number.isInteger(at) ? c.fixes[at] : undefined;
3057
- if (!fix)
3058
- throw new Error(`There is no fix number ${at} for "${c.text}".`);
3059
- return [fix];
3060
- });
3061
- if (chosen.length === 0)
3062
- throw new Error('No fix was chosen.');
3063
- const patch = contractFixPatch(task, chosen);
3064
- const applied = describeContractChange(task, patch);
3065
- // Judged on the task as it was read: one edited meanwhile, in another tab, is not overwritten with a patch made from the old one.
3066
- const contract = (t) => JSON.stringify([t?.status, !!t?.readOnly, t?.scope ?? [], t?.checks ?? []]);
3067
- const meanwhile = (await this.store.getSession(sessionId))?.tasks.find((t) => t.id === taskId);
3068
- if (contract(meanwhile) !== contract(task))
3069
- throw new Error('The task was changed while its contradictions were being judged. Look again before applying a fix.');
3070
- const updated = task.status === 'queued' ? await this.updateTask(sessionId, taskId, patch) : await this.rerunTask(sessionId, taskId, patch);
3071
- const after = await this.store.getSession(sessionId);
3072
- const now = after?.tasks.find((t) => t.id === taskId) ?? updated;
3073
- const remaining = after ? await this.contractFor(after, now) : [];
3074
- const cfg = await this.settings.load();
3075
- await appendSessionLog(cfg.resolved.runsDir, sessionId, {
3076
- type: 'contract-fixed',
3077
- message: `"${now.title}": ${applied.join('; ')}${remaining.length > 0 ? `; ${remaining.length} contradiction(s) left` : ''}`,
3078
- data: { taskId, applied: chosen, remaining: remaining.map((c) => c.text) },
3079
- }).catch(() => undefined);
3080
- this.bus.publish({
3081
- sessionId,
3082
- taskId,
3083
- type: 'contract-fixed',
3084
- level: 'info',
3085
- message: remaining.length === 0
3086
- ? `"${now.title}" changed so it no longer contradicts itself: ${applied.join('; ')}`
3087
- : `"${now.title}" changed (${applied.join('; ')}), and it still contradicts itself in ${remaining.length} way(s)`,
3088
- data: { applied: chosen, remaining: remaining.length },
3089
- });
3090
- return { task: now, applied, remaining };
3091
- }
3092
1651
  /**
3093
1652
  * Where the next task's file checks can be judged before the run: see `ContractTree`. The folder holds
3094
1653
  * the task's tree only when nothing is still to happen to it first — no update from a remote, no
@@ -3155,239 +1714,6 @@ let OperatorService = class OperatorService {
3155
1714
  this.bus.publish({ sessionId: id, type: entry.type, level: 'info', message: entry.message, data: { runId, ...entry.data } });
3156
1715
  await appendRunLog(cfg.resolved.runsDir, runId, [entry]).catch(() => undefined);
3157
1716
  }
3158
- /** One action of "Prepare version control for this run". Refused while anything runs in that repository. */
3159
- async runVcsPrepare(sessionIds, repoDir, action, choices) {
3160
- await this.init();
3161
- if (this.batch?.running)
3162
- return { ok: false, problem: 'A run is going. Stop it before preparing version control.' };
3163
- const other = await this.runningIn(repoDir);
3164
- if (other)
3165
- return { ok: false, problem: `Session "${other.name}" is running in this repository. Stop it first.` };
3166
- const sessions = [];
3167
- for (const id of sessionIds) {
3168
- const s = await this.store.getSession(id);
3169
- if (s && queuedToRun(s).length > 0)
3170
- sessions.push(s);
3171
- }
3172
- const done = await runVcsPrepare(sessions, repoDir, action, choices && typeof choices === 'object' ? choices : {}, this.bus, async (id, mutate) => void (await this.store.updateSession(id, mutate)), () => this.store.listSessions());
3173
- // Kept on every session the action was for, with what it did: see `appendSessionLog`.
3174
- if (done.ok && action !== 'review-inputs') {
3175
- const cfg = await this.settings.load();
3176
- for (const s of sessions.filter((x) => normaliseDir(repoDirOf(x)) === normaliseDir(repoDir))) {
3177
- const message = `run screen: "${action}" in ${repoDir}: ${done.result}`;
3178
- await appendSessionLog(cfg.resolved.runsDir, s.id, { type: 'run-screen-action', message, data: { action, repoDir, before: { startFrom: s.vcs?.startFrom, baseBranch: s.vcs?.baseBranch } } }).catch(() => undefined);
3179
- this.bus.publish({ sessionId: s.id, type: 'run-screen-action', level: 'info', message, data: { action, repoDir } });
3180
- }
3181
- }
3182
- return done.ok ? { ok: true, result: done.result } : { ok: false, problem: done.problem };
3183
- }
3184
- /** Whether version control can do its job in this session, asked before a run. */
3185
- async vcsStatus(sessionId) {
3186
- await this.init();
3187
- const session = await this.store.getSession(sessionId);
3188
- if (!session)
3189
- throw new Error('No such session.');
3190
- const git = await gitAvailable();
3191
- if (!git)
3192
- return { ok: false, repoDir: '', problem: "git is not installed, or not on this machine's PATH.", git: null };
3193
- // `branch` is where HEAD is; `work` is where the session's work is. After a per-task run
3194
- // those differ, and the second is the one the operator is asking about.
3195
- const preflight = await vcsPreflight(session, () => this.store.listSessions());
3196
- // The local branches, so "carry on an existing branch" can offer them rather than be typed blind.
3197
- const branches = preflight.repoDir ? await localBranches(preflight.repoDir) : [];
3198
- return { ...preflight, git, work: sessionBranches(session), branches };
3199
- }
3200
- /**
3201
- * The operator's approval of the starting snapshot: their uncommitted changes become the commit the
3202
- * session starts from, each file taken or left out as they chose on the list. See `vcs/snapshot.ts`.
3203
- * Refused while anything could be working in the repository, as a restore is: it changes branches.
3204
- */
3205
- async vcsSnapshot(sessionId, choices) {
3206
- await this.init();
3207
- const session = await this.store.getSession(sessionId);
3208
- if (!session)
3209
- throw new Error('No such session.');
3210
- const refused = await this.restoreRefusal(session);
3211
- if (refused)
3212
- return { ok: false, problem: refused };
3213
- const taken = await takeSnapshot(session, { approved: true, choices: choices && typeof choices === 'object' ? choices : {} }, this.bus, async (mutate) => void (await this.store.updateSession(sessionId, mutate)), () => this.store.listSessions());
3214
- return taken.ok ? { ok: true, branch: taken.start.branch, commit: taken.start.commit } : { ok: false, problem: taken.problem };
3215
- }
3216
- /**
3217
- * What going back to before a task would do, and then doing it.
3218
- *
3219
- * Two calls rather than one because the operator has to read the consequence before they
3220
- * agree to it: which commits the restored branch will not have, and which branch keeps them.
3221
- */
3222
- async restorePreview(sessionId, taskId) {
3223
- await this.init();
3224
- const session = await this.store.getSession(sessionId);
3225
- if (!session)
3226
- throw new Error('No such session.');
3227
- const task = session.tasks.find((t) => t.id === taskId);
3228
- if (!task)
3229
- throw new Error('No such task.');
3230
- const preview = await restorePreview(session, task);
3231
- // Said in the preview too, so the dialog refuses before the operator agrees to anything,
3232
- // rather than showing what would happen and refusing when they say yes.
3233
- const refused = await this.restoreRefusal(session);
3234
- return refused ? { ...preview, ok: false, problem: refused } : preview;
3235
- }
3236
- /**
3237
- * What undoing this task would do, both ways (operator's request, 2026-10-14): "Undo only this task" — its
3238
- * work taken out of the session's line, what came after it kept — and "Go back to before this task" — the
3239
- * line put back at its start, it and the tasks after it queued again, nothing started. See `undoTask`.
3240
- */
3241
- async undoPreview(sessionId, taskId) {
3242
- await this.init();
3243
- const session = await this.store.getSession(sessionId);
3244
- if (!session)
3245
- throw new Error('No such session.');
3246
- const task = session.tasks.find((t) => t.id === taskId);
3247
- if (!task)
3248
- throw new Error('No such task.');
3249
- const notYet = undoRefusalOf(task);
3250
- const refused = notYet ?? (await this.restoreRefusal(session));
3251
- const own = await undoThisPreview(session, task);
3252
- const back = await this.restartPlan(sessionId, taskId);
3253
- return {
3254
- this: refused ? { ...own, ok: false, problem: refused } : own,
3255
- back: refused ? { ...back, ok: false, problem: refused } : back,
3256
- ...(refused ? { problem: refused } : {}),
3257
- };
3258
- }
3259
- /**
3260
- * Undoes a task that ran. `this`: its work is taken out of the session's line by a revert (per-session),
3261
- * or the folder is put back at its start (per-task); the task goes back to the queue. `back`: "Run again
3262
- * from here" without the run — the line goes back to the task's start and it and the tasks after it are
3263
- * queued. Nothing is started and nothing in git is deleted: the old branch or the reverted commits stay.
3264
- */
3265
- async undoTask(sessionId, taskId, how) {
3266
- await this.init();
3267
- const session = await this.store.getSession(sessionId);
3268
- if (!session)
3269
- throw new Error('No such session.');
3270
- const task = session.tasks.find((t) => t.id === taskId);
3271
- if (!task)
3272
- throw new Error('No such task.');
3273
- const notYet = undoRefusalOf(task);
3274
- if (notYet)
3275
- return { ok: false, problem: notYet };
3276
- const refused = await this.restoreRefusal(session);
3277
- if (refused)
3278
- return { ok: false, problem: refused };
3279
- const cfg = await this.settings.load();
3280
- const at = new Date().toISOString();
3281
- if (how === 'back') {
3282
- const plan = await this.restartPlan(sessionId, taskId);
3283
- const r = await this.restartFrom(sessionId, taskId, { restore: true, start: false });
3284
- if (r.reason && r.requeued === 0)
3285
- return { ok: false, problem: r.reason };
3286
- for (const t of plan.tasks.filter((x) => !x.alreadyQueued)) {
3287
- await this.store
3288
- .updateSession(t.sessionId, (s) => {
3289
- const last = s.tasks.find((x) => x.id === t.taskId)?.attempts?.at(-1);
3290
- if (last)
3291
- last.undone = { how: 'back', at, ...(r.restored[0] ? { branch: r.restored[0] } : {}), ...(t.taskId !== taskId ? { byTask: taskId } : {}) };
3292
- })
3293
- .catch(() => undefined);
3294
- }
3295
- const message = `went back to before "${task.title}": ${r.requeued} task(s) queued again${r.restored.length > 0 ? `, the code on ${r.restored.join(', ')}` : ''}; nothing was started`;
3296
- await appendSessionLog(cfg.resolved.runsDir, sessionId, { type: 'undo', message, data: { taskId, how, requeued: r.requeued, restored: r.restored } }).catch(() => undefined);
3297
- this.bus.publish({ sessionId, taskId, type: 'task-undone', level: 'info', message, data: { how, requeued: r.requeued } });
3298
- return { ok: true, message, requeued: r.requeued };
3299
- }
3300
- let done = {};
3301
- if (session.vcs?.enabled && session.vcs.branchMode === 'per-task') {
3302
- const preview = await undoThisPreview(session, task);
3303
- if (!preview.ok)
3304
- return { ok: false, problem: preview.problem };
3305
- if (!preview.nothing) {
3306
- const back = await restoreToBase(session, task, this.bus);
3307
- if (!back.ok)
3308
- return { ok: false, problem: back.problem };
3309
- done = { branch: back.branch };
3310
- }
3311
- else
3312
- done = { nothing: preview.nothing };
3313
- }
3314
- else {
3315
- const r = await revertTaskWork(session, task, this.bus);
3316
- if (!r.ok)
3317
- return { ok: false, problem: r.problem };
3318
- done = { commit: r.commit, branch: r.branch, nothing: r.nothing };
3319
- }
3320
- await this.store.rerunTask(sessionId, taskId, {});
3321
- await this.store.updateSession(sessionId, (s) => {
3322
- const last = s.tasks.find((x) => x.id === taskId)?.attempts?.at(-1);
3323
- if (last)
3324
- last.undone = { how: 'this', at, ...(done.commit ? { commit: done.commit } : {}), ...(done.branch ? { branch: done.branch } : {}) };
3325
- });
3326
- const message = done.commit
3327
- ? `took the work of "${task.title}" out of ${done.branch} in ${done.commit.slice(0, 8)}; the task is queued again, nothing was started`
3328
- : done.branch
3329
- ? `put the folder back as it was before "${task.title}", on ${done.branch}; its own branch is kept, the task is queued again`
3330
- : `${done.nothing ?? 'nothing in git to take out'} The task is queued again.`;
3331
- await appendSessionLog(cfg.resolved.runsDir, sessionId, { type: 'undo', message, data: { taskId, how, ...done } }).catch(() => undefined);
3332
- this.bus.publish({ sessionId, taskId, type: 'task-undone', level: 'info', message, data: { how, ...done } });
3333
- return { ok: true, message, requeued: 1 };
3334
- }
3335
- async restore(sessionId, taskId) {
3336
- await this.init();
3337
- const session = await this.store.getSession(sessionId);
3338
- if (!session)
3339
- throw new Error('No such session.');
3340
- const task = session.tasks.find((t) => t.id === taskId);
3341
- if (!task)
3342
- throw new Error('No such task.');
3343
- const refused = await this.restoreRefusal(session);
3344
- if (refused)
3345
- return { ok: false, problem: refused };
3346
- const done = await restoreToBase(session, task, this.bus);
3347
- // On record with the operator's other actions: it made a branch and moved the checkout (live run 2026-10-04).
3348
- if (done.ok) {
3349
- const cfg = await this.settings.load();
3350
- await appendSessionLog(cfg.resolved.runsDir, session.id, { type: 'restore', message: `restored the code as it was before "${task.title}" on ${done.branch} at ${(done.commit ?? '').slice(0, 8)}`, data: { taskId, branch: done.branch, commit: done.commit, leftBehind: done.leftBehind, keptOn: done.keptOn } }).catch(() => undefined);
3351
- }
3352
- /*
3353
- * In per-session mode the session's one branch is where its next task goes, so a Restore moves the
3354
- * session onto the restore branch, as "Run again from here" does. Without that the next run checked
3355
- * the old session branch out again and the restore did not hold (live run 2026-10-03).
3356
- */
3357
- if (done.ok && done.branch && session.vcs?.branchMode === 'per-session' && session.vcs.startFrom !== 'existing-branch') {
3358
- const left = sessionBranchName(session);
3359
- await this.store.updateSession(session.id, (s) => {
3360
- if (s.vcs) {
3361
- s.vcs.branchName = done.branch;
3362
- s.vcs.branchNameExact = true;
3363
- }
3364
- });
3365
- this.bus.publish({ sessionId: session.id, taskId: task.id, type: 'vcs-session-branch', level: 'info',
3366
- message: `the session carries on from ${done.branch}, the code as it was before "${task.title}"; ${left} keeps the work that came after`,
3367
- data: { branch: done.branch, left } });
3368
- }
3369
- return done;
3370
- }
3371
- /**
3372
- * Why the repository of this session cannot be moved to another branch now, or null when it can.
3373
- *
3374
- * Anything that may be working in that folder at this moment: the session itself, a batch (which
3375
- * may reach a session in it next), and any other session running there on its own. Only the first
3376
- * two used to be asked, so a restore checked out a branch under another session in the middle of
3377
- * its task — and that session then found its repository moved, and left its work uncommitted.
3378
- * Version control being off for the other session does not make it safe: its commands still run
3379
- * in that folder.
3380
- */
3381
- async restoreRefusal(session) {
3382
- if (this.running.has(session.id))
3383
- return 'This session is running. Stop it before moving the repository to another branch.';
3384
- if (this.batch?.running)
3385
- return 'A batch is running. Stop it before moving the repository to another branch.';
3386
- const other = await this.runningIn(repoDirOf(session));
3387
- return other
3388
- ? `Session "${other.name}" is running in this repository. Stop it before moving the repository to another branch.`
3389
- : null;
3390
- }
3391
1717
  /**
3392
1718
  * A session running right now whose commands run in this folder, inside it, or in a folder around it.
3393
1719
  *
@@ -3411,474 +1737,6 @@ let OperatorService = class OperatorService {
3411
1737
  }
3412
1738
  return undefined;
3413
1739
  }
3414
- /**
3415
- * Everything one run was asked to do, from a given task onward, in the order it would run.
3416
- *
3417
- * The run's own record on each session is what makes this answerable. Tasks are stamped when
3418
- * they start, so after a failure the tasks that never ran carry nothing and the sessions that
3419
- * were never reached carry nothing either — asking the tasks would return the half of the run
3420
- * that already happened, which is the opposite of what is wanted.
3421
- */
3422
- async affectedByRestart(session, task) {
3423
- const group = session.runGroup;
3424
- /** The tasks a session was asked to do in that run, in its own order, falling back to all. */
3425
- const askedOf = (s) => {
3426
- const ids = s.runGroup?.id === group?.id ? (s.runGroup?.taskIds ?? []) : [];
3427
- return ids.length > 0 ? s.tasks.filter((t) => ids.includes(t.id)) : s.tasks;
3428
- };
3429
- if (!group) {
3430
- // No run on record — an older session, or one whose tasks were started by hand. Then the
3431
- // honest scope is this session alone, from this task onward.
3432
- const from = session.tasks.findIndex((t) => t.id === task.id);
3433
- return { sessions: [session], tasks: session.tasks.slice(Math.max(0, from)).map((t) => ({ session, task: t })) };
3434
- }
3435
- const all = await this.store.listSessions();
3436
- const inRun = all.filter((s) => s.runGroup?.id === group.id).sort((a, b) => (a.runGroup?.order ?? 0) - (b.runGroup?.order ?? 0));
3437
- const out = [];
3438
- const sessions = [];
3439
- for (const s of inRun) {
3440
- // Sessions the run had already finished with are none of this restart's business.
3441
- if ((s.runGroup?.order ?? 0) < (group.order ?? 0))
3442
- continue;
3443
- const mine = s.id === session.id;
3444
- /*
3445
- * The session the task is in starts from that task; every session after it starts from
3446
- * the top, because it was either never reached or its work is downstream of this one.
3447
- *
3448
- * The pivot is looked for in what the run was asked to do, and then in the session's own
3449
- * list. The second lookup is not redundant: a task added since the run is not in the
3450
- * run's list, and skipping its session because of that would quietly drop the very
3451
- * session the operator pressed the button on.
3452
- */
3453
- let scope = askedOf(s);
3454
- let start = 0;
3455
- if (mine) {
3456
- start = scope.findIndex((t) => t.id === task.id);
3457
- if (start < 0) {
3458
- scope = s.tasks;
3459
- start = scope.findIndex((t) => t.id === task.id);
3460
- if (start < 0)
3461
- continue;
3462
- }
3463
- }
3464
- const slice = scope.slice(start);
3465
- if (slice.length === 0)
3466
- continue;
3467
- sessions.push(s);
3468
- for (const t of slice)
3469
- out.push({ session: s, task: t });
3470
- }
3471
- return { sessions, tasks: out, group };
3472
- }
3473
- /** What starting again from this task would re-queue, and what it would do to the code. */
3474
- async restartPlan(sessionId, taskId) {
3475
- await this.init();
3476
- const session = await this.store.getSession(sessionId);
3477
- if (!session)
3478
- throw new Error('No such session.');
3479
- const task = session.tasks.find((t) => t.id === taskId);
3480
- if (!task)
3481
- throw new Error('No such task.');
3482
- const { sessions, tasks, group } = await this.affectedByRestart(session, task);
3483
- const from = { sessionId: session.id, sessionName: session.name, taskId: task.id, title: task.title, status: task.status };
3484
- const plan = {
3485
- ok: tasks.length > 0,
3486
- problem: tasks.length === 0 ? 'There is nothing to run again from this task.' : undefined,
3487
- runId: group?.id,
3488
- runStartedAt: group?.startedAt,
3489
- from,
3490
- tasks: tasks.map(({ session: s, task: t }) => ({
3491
- sessionId: s.id,
3492
- sessionName: s.name,
3493
- taskId: t.id,
3494
- title: t.title,
3495
- status: t.status,
3496
- alreadyQueued: t.status === 'queued',
3497
- })),
3498
- sessions: sessions.map((s) => ({ id: s.id, name: s.name, tasks: tasks.filter((x) => x.session.id === s.id).length })),
3499
- restores: [],
3500
- /*
3501
- * Nothing on record says a run with no record of its own ever went unattended, and taken for
3502
- * one, it was refused on every machine that refuses unattended runs, the default among them:
3503
- * the dialog has no other mode to offer, so its button could never do anything for such a task.
3504
- */
3505
- mode: group?.mode ?? 'confirm',
3506
- onFailure: group?.onFailure ?? session.onFailure ?? 'stop',
3507
- };
3508
- // Asked of the machine as it is now, as `restartFrom` will ask it; see `unattendedRefused`.
3509
- if (plan.mode === 'unattended')
3510
- plan.unattendedRefused = (await this.unattendedRefusal('unattended')) ?? undefined;
3511
- // The sessions in the order the run had them: the order `rerunFromRestore` moves them in.
3512
- const inOrder = [...new Map(tasks.map(({ session: s }) => [s.id, s])).values()];
3513
- for (const target of restoreTargets(tasks)) {
3514
- const preview = await restorePreview(target.session, target.task);
3515
- // What would stop the restore itself, asked here as well, so the dialog says it before the
3516
- // operator agrees rather than after.
3517
- const refused = target.problem ?? (await this.restoreRefusal(target.session));
3518
- /*
3519
- * What the restart moves besides the first session's line: each later per-session session in this
3520
- * repository that ran goes onto a new branch, and its own commits stay on the branch it leaves. By
3521
- * the conditions `rerunFromRestore` applies when it does it, so the list is what will happen.
3522
- */
3523
- const listed = new Set(preview.leftBehind);
3524
- const here = normaliseDir(target.dir);
3525
- const laterSessions = [];
3526
- for (const s of inOrder.slice(inOrder.findIndex((x) => x.id === target.session.id) + 1)) {
3527
- if (!s.vcs?.enabled || s.vcs.branchMode !== 'per-session' || s.vcs.startFrom === 'existing-branch')
3528
- continue;
3529
- if (!s.vcsBaseCommit || normaliseDir(repoDirOf(s)) !== here)
3530
- continue;
3531
- const first = tasks.find((x) => x.session.id === s.id && x.task.startedAt)?.task;
3532
- if (!first)
3533
- continue;
3534
- const branch = sessionBranchName(s);
3535
- const from = (s.vcsStart?.kind === 'branch' ? restorePoint(s, first) : undefined) ?? s.vcsBaseCommit;
3536
- const commits = (await commitsBetween(target.dir, from, branch).catch(() => [])).filter((c) => !listed.has(c));
3537
- commits.forEach((c) => listed.add(c));
3538
- laterSessions.push({ sessionName: s.name, branch, commits });
3539
- }
3540
- plan.restores.push({
3541
- repoDir: preview.repoDir || target.dir,
3542
- ok: preview.ok && !refused,
3543
- problem: refused ?? preview.problem,
3544
- forTask: target.task.title,
3545
- baseCommit: preview.baseCommit,
3546
- branchName: preview.branchName,
3547
- leftBehind: preview.leftBehind,
3548
- keptOn: preview.keptOn,
3549
- ...(laterSessions.length > 0 ? { laterSessions } : {}),
3550
- });
3551
- }
3552
- /*
3553
- * The plan is "ok" only when the restart it describes can happen: a refused restore refuses the
3554
- * restart, as `restartFrom` does and the dialog says, so a caller reading only `ok` is not told
3555
- * otherwise (live run 2026-10-04: ok true beside its only restore refused).
3556
- */
3557
- const refusedRestores = plan.restores.filter((r) => !r.ok);
3558
- if (plan.ok && refusedRestores.length > 0) {
3559
- plan.ok = false;
3560
- plan.problem = refusedRestores.map((r) => `${r.repoDir}: ${r.problem ?? 'the restore cannot be made'}`).join(' ');
3561
- }
3562
- /*
3563
- * A session set aside on the Sessions page would not run, and the run is refused at its start for it:
3564
- * said here, before anything moves, as the other entrance rules are (review of 2026-10-09: the
3565
- * repositories were taken back and the tasks queued, and only then was the run refused).
3566
- */
3567
- const inactive = sessions.filter((s) => s.active === false);
3568
- if (inactive.length > 0) {
3569
- plan.ok = false;
3570
- plan.inactive = true;
3571
- plan.problem = `${inactive.map((s) => `"${s.name}"`).join(', ')}: ${INACTIVE_REASON}`;
3572
- }
3573
- return plan;
3574
- }
3575
- /**
3576
- * Put the code back, queue the task and everything after it, and start the run again.
3577
- *
3578
- * The order matters and is not negotiable: restore first, then queue, then start. Queueing
3579
- * before restoring would leave a window in which a run could pick up a task against a tree
3580
- * that has not moved yet, and starting before queueing would run an empty batch.
3581
- *
3582
- * `restore` can be turned off, for the case where the repository is already where it should
3583
- * be, or where version control was never on. `start` can be turned off to do the first two
3584
- * and stop there, leaving a queue and an untouched Start button — the same shape an import
3585
- * has, and the same reason: the moment before a run is the one worth being able to stop at.
3586
- */
3587
- async restartFrom(sessionId, taskId, opts = {}) {
3588
- await this.init();
3589
- const idle = { started: false, requeued: 0, restored: [] };
3590
- if (this.batch?.running)
3591
- return { ...idle, reason: 'A run is in progress. Stop it first.' };
3592
- const plan = await this.restartPlan(sessionId, taskId);
3593
- // A session set aside stops it whatever is asked: its run would be refused after everything moved.
3594
- if (plan.inactive)
3595
- return { ...idle, reason: plan.problem };
3596
- // A refused restore stops the restart only when the restore is asked for: `restore: false` queues without one.
3597
- const onlyRestoreRefused = plan.tasks.length > 0 && plan.restores.some((r) => !r.ok);
3598
- if (!plan.ok && !(opts.restore === false && onlyRestoreRefused))
3599
- return { ...idle, reason: plan.problem };
3600
- if (plan.sessions.some((s) => this.running.has(s.id))) {
3601
- return { ...idle, reason: 'One of these sessions is running on its own. Stop it first.' };
3602
- }
3603
- /*
3604
- * Claimed before anything is moved, and held until the run it ends in has the browser: that run
3605
- * needs it, and another session running on its own, or a read of the models, may have it. Found
3606
- * out only at the start, the repositories were already taken back and the tasks queued, with
3607
- * nothing to run them; and only looked at here, the browser could still be taken by a start that
3608
- * came in while the repositories were being taken back, to the same end. Given back on every way
3609
- * out that does not start the run.
3610
- */
3611
- const ids = plan.sessions.map((s) => s.id);
3612
- if (opts.start === false)
3613
- return await this.restartMoves(sessionId, taskId, plan, opts);
3614
- /*
3615
- * The run's entrance rule, asked before anything moves, for the same reason as the browser
3616
- * below. Asked only when the batch began, a machine that no longer lets this run go unattended
3617
- * (a policy lock added since, isolation no longer accepted) took the repositories back and
3618
- * queued the tasks, and only then refused the run they were moved for. The plan says so first
3619
- * (`unattendedRefused`), so the dialog asks for the run step by step instead.
3620
- */
3621
- const blocked = await this.unattendedRefusal(opts.mode ?? plan.mode);
3622
- if (blocked)
3623
- return { ...idle, reason: blocked };
3624
- const claim = this.claimBrowser({ kind: 'batch', sessionIds: ids });
3625
- if ('refused' in claim)
3626
- return { ...idle, reason: claim.refused };
3627
- let handedOn = false;
3628
- try {
3629
- const moved = await this.restartMoves(sessionId, taskId, plan, opts);
3630
- if (moved.reason !== undefined)
3631
- return moved;
3632
- // Named after the task it goes back to, which is the one thing this run is about and the
3633
- // only thing a heading could usefully say. There is no field to type into on a task card,
3634
- // so leaving it to the operator meant leaving it blank every time.
3635
- const runName = await this.suggestRunName(ids, plan.from.title);
3636
- // From here the claim is the batch's to give back, whichever way its start goes.
3637
- handedOn = true;
3638
- /*
3639
- * Exactly the tasks the preview listed, which are the tasks the run was asked to do from this
3640
- * one on. Started with none named, the batch took every queued task of these sessions, so a
3641
- * task the run never chose — queued beside it, or added since — was sent to the chat as well.
3642
- */
3643
- const taskIds = plan.tasks.map((x) => x.taskId);
3644
- const started = await this.startBatchHolding(claim.holder, ids, opts.mode ?? plan.mode, opts.onFailure ?? plan.onFailure, undefined, undefined, runName, taskIds);
3645
- // A start refused now leaves the moves in place, and says so with its reason.
3646
- const reason = started.started || started.reason === undefined ? started.reason : afterMoves(started.reason, moved.restored, moved.requeued);
3647
- return { started: started.started, reason, requeued: moved.requeued, restored: moved.restored, batch: started.batch };
3648
- }
3649
- finally {
3650
- if (!handedOn)
3651
- this.releaseBrowser(claim.holder);
3652
- }
3653
- }
3654
- /**
3655
- * What `restartFrom` moves before its run starts: the repositories taken back, then the tasks
3656
- * queued again. A refusal, and "prepared, not started", come back with their reason; with none,
3657
- * everything is in place for the run.
3658
- */
3659
- async restartMoves(sessionId, taskId, plan, opts) {
3660
- const idle = { started: false, requeued: 0, restored: [] };
3661
- const restored = [];
3662
- if (opts.restore !== false) {
3663
- for (const entry of plan.restores) {
3664
- if (!entry.ok)
3665
- return { ...idle, reason: `${entry.repoDir}: ${entry.problem ?? 'the restore could not be prepared.'}` };
3666
- }
3667
- /*
3668
- * Re-read each repository's own pivot and do it for real. The preview above is what the
3669
- * operator agreed to; this is the same choice (`restoreTargets`), one step further. It was
3670
- * worked out a second time here, by a copy of the rule that had not been given the preview's
3671
- * "never started" skip, so a run whose later repository was never reached failed on it after
3672
- * the first repository had already been moved — and queued nothing.
3673
- *
3674
- * A refusal part-way still says what was already moved, in the result and in its reason (the
3675
- * one thing the page shows): a repository taken back is the operator's to know about, whatever
3676
- * happened after it.
3677
- */
3678
- const session = (await this.store.getSession(sessionId));
3679
- const task = session.tasks.find((t) => t.id === taskId);
3680
- const { tasks } = await this.affectedByRestart(session, task);
3681
- for (const target of restoreTargets(tasks)) {
3682
- // Asked again at the moment of moving: a session may have started in this folder since.
3683
- const refused = target.problem ?? (await this.restoreRefusal(target.session));
3684
- if (refused)
3685
- return { ...idle, restored, reason: afterMoves(`${target.dir}: ${refused}`, restored, 0) };
3686
- const done = await restoreToBase(target.session, target.task, this.bus);
3687
- if (!done.ok || !done.branch) {
3688
- return { ...idle, restored, reason: afterMoves(`${target.dir}: ${done.problem ?? 'the restore failed.'}`, restored, 0) };
3689
- }
3690
- restored.push(`${target.dir} -> ${done.branch}`);
3691
- await this.rerunFromRestore(target, done.branch, tasks);
3692
- }
3693
- }
3694
- let requeued = 0;
3695
- for (const t of plan.tasks) {
3696
- if (t.alreadyQueued)
3697
- continue;
3698
- try {
3699
- await this.store.rerunTask(t.sessionId, t.taskId);
3700
- requeued += 1;
3701
- }
3702
- catch (e) {
3703
- // One task refusing to be queued again must not leave the rest half-reset with no
3704
- // explanation, so it stops here and says which one and why — and what was done before it.
3705
- return { ...idle, restored, requeued, reason: afterMoves(`"${t.title}" could not be queued again: ${e.message}`, restored, requeued) };
3706
- }
3707
- }
3708
- this.bus.publish({
3709
- sessionId,
3710
- taskId,
3711
- type: 'run-restarted',
3712
- level: 'info',
3713
- message: `${opts.start === false ? 'prepared to start again' : 'starting again'} from "${plan.from.title}": ${plan.tasks.length} task(s) in ${plan.sessions.length} session(s)` +
3714
- (restored.length > 0 ? `, after taking ${restored.length} repository(ies) back` : '') +
3715
- (opts.start === false ? '; press a run button to start' : ''),
3716
- data: { requeued, restored },
3717
- });
3718
- if (opts.start === false)
3719
- return { started: false, reason: 'prepared, not started', requeued, restored };
3720
- return { started: false, requeued, restored };
3721
- }
3722
- /**
3723
- * Makes a restore hold for the run that follows it.
3724
- *
3725
- * The restore puts the repository on a new branch at the pivot task's starting commit, and the
3726
- * re-run then puts each session on its own branch. In per-task mode that is right: a re-run cuts
3727
- * a fresh branch from where the task first started, which is the restore commit. In per-session
3728
- * mode it undid the restore: the session's one branch was checked out again, with the failed
3729
- * attempt's commit still on it, so the attempt that was to start from the code as it was began on
3730
- * the work it was meant to replace, and committed it a second time. So the pivot's session now
3731
- * works on the restore branch — the code as it was before that task, with the tasks before it —
3732
- * and its old branch keeps the attempt that failed, as the confirmation says.
3733
- *
3734
- * A per-session session after it in the same repository that this run reached has the same
3735
- * problem whatever it started from: its one branch carries what its tasks did in this run, and
3736
- * checked out again it would start them over on their own first attempt. So it gets a branch of
3737
- * its own, and the old one keeps what it did. Where that branch starts depends on where the
3738
- * session began. From a named branch: where its first task in this run began, as a restore of
3739
- * that task would go back to, and the session's start stays as recorded. From where the
3740
- * repository was, or from the session before it: that start was work this run is now redoing, so
3741
- * it is forgotten, to be worked out again when the session is reached (for a `previous-session`
3742
- * chain, from the work done again), and the branch is cut from that. A session the run never
3743
- * reached holds nothing of this run and is left alone.
3744
- *
3745
- * A later per-task session is left as it is. From a named branch that is right: each re-run is
3746
- * cut from where its task first started, that branch's commit. Chained on this run's work it is
3747
- * not, and is not solved here: its tasks first started on the work being redone, so their re-runs
3748
- * are cut from it again. Telling that apart from an operator's new "Start from", whose re-runs go
3749
- * back to where each task first started on purpose (see `updateSession`), needs the restart
3750
- * written on the session, and the session's record has no field for it.
3751
- */
3752
- async rerunFromRestore(target, branch, tasks) {
3753
- if (target.session.vcs?.branchMode === 'per-session') {
3754
- const left = sessionBranchName(target.session);
3755
- // The restore branch exists by this name, so the name is kept as it is (see `branchNameExact`).
3756
- await this.store.updateSession(target.session.id, (s) => {
3757
- if (s.vcs) {
3758
- s.vcs.branchName = branch;
3759
- s.vcs.branchNameExact = true;
3760
- }
3761
- });
3762
- this.bus.publish({
3763
- sessionId: target.session.id,
3764
- taskId: target.task.id,
3765
- type: 'vcs-session-branch',
3766
- level: 'info',
3767
- message: `the session carries on from ${branch}, the code as it was before "${target.task.title}"; ${left} keeps the work that came after`,
3768
- data: { branch, left },
3769
- });
3770
- }
3771
- const here = normaliseDir(target.dir);
3772
- const inOrder = [...new Map(tasks.map(({ session }) => [session.id, session])).values()];
3773
- const later = inOrder.slice(inOrder.findIndex((s) => s.id === target.session.id) + 1);
3774
- for (const s of later) {
3775
- // One that carries on an existing branch never gets here: `restoreTargets` refuses the restart.
3776
- if (!s.vcs?.enabled || s.vcs.branchMode !== 'per-session' || s.vcs.startFrom === 'existing-branch')
3777
- continue;
3778
- // No base recorded: version control never got as far as making its branch.
3779
- if (!s.vcsBaseCommit || normaliseDir(repoDirOf(s)) !== here)
3780
- continue;
3781
- const first = tasks.find((x) => x.session.id === s.id && x.task.startedAt)?.task;
3782
- if (!first)
3783
- continue;
3784
- const left = sessionBranchName(s);
3785
- const fresh = await freeBranchName(target.dir, left);
3786
- // No record of the start is read as chained, the reading that cannot bring undone work back.
3787
- const chained = s.vcsStart?.kind !== 'branch';
3788
- const at = chained ? undefined : restorePoint(s, first);
3789
- if (at) {
3790
- const made = await branchAt(target.dir, fresh, at);
3791
- // Not made: left to the run, which cuts it from the session's start when it is reached.
3792
- if (!made.ok) {
3793
- this.bus.publish({ sessionId: s.id, type: 'vcs-problem', level: 'warn', message: `${fresh} could not be made at ${at.slice(0, 8)}: ${made.problem}` });
3794
- }
3795
- }
3796
- await this.store.updateSession(s.id, (x) => {
3797
- if (chained) {
3798
- x.vcsBaseCommit = undefined;
3799
- x.vcsStart = undefined;
3800
- }
3801
- if (x.vcs) {
3802
- x.vcs.branchName = fresh;
3803
- x.vcs.branchNameExact = true;
3804
- }
3805
- });
3806
- this.bus.publish({
3807
- sessionId: s.id,
3808
- type: 'vcs-session-branch',
3809
- level: 'info',
3810
- message: chained
3811
- ? `the session began from work this run is doing again, so it starts again when it is reached, on a new branch ${fresh}; ${left} keeps what it did before`
3812
- : `the session starts its tasks again on a new branch ${fresh}, from where "${first.title}" began; ${left} keeps what it did before`,
3813
- data: { branch: fresh, left },
3814
- });
3815
- }
3816
- }
3817
- /** Why a folder cannot be used for version control, or null when it can. */
3818
- repoProblem(dir) {
3819
- return repoUnusableReason(dir);
3820
- }
3821
- /**
3822
- * What bringing a project back to its remote's main branch would lose, and the command that does
3823
- * it — for the operator to run. See `vcs/syncCommand.ts`; nothing here writes.
3824
- *
3825
- * Only for a folder this bot already works in: a project in Settings or the repository of a
3826
- * session. The answer lists file names and commit subjects, and a local page asking about any
3827
- * folder on the disk is not a question this API should answer.
3828
- */
3829
- async syncPlan(dir) {
3830
- await this.init();
3831
- await this.knownProjectFolder(dir, 'no command is offered for it');
3832
- return await planSync(resolve(dir.trim()));
3833
- }
3834
- /** Throws unless the folder is a project in Settings or the repository of a session. */
3835
- async knownProjectFolder(dir, otherwise) {
3836
- const wanted = normaliseDir(dir);
3837
- const cfg = await this.settings.load();
3838
- const known = new Set([cfg.project?.rootDir ?? '', ...(cfg.project?.others ?? []).map((o) => o.rootDir), ...(await this.store.listSessions()).flatMap((s) => [s.vcs?.repoDir ?? '', s.projectDir ?? ''])]
3839
- .filter((d) => d.trim())
3840
- .map(normaliseDir));
3841
- if (!wanted || !known.has(wanted)) {
3842
- throw new Error(`That folder is not one of the projects in Settings or the repository of a session, so ${otherwise}.`);
3843
- }
3844
- }
3845
- /**
3846
- * "Prepare the folder from the remote main branch", first half: fetches and says what would be
3847
- * kept where and what the folder would be. See `vcs/prepareFromRemote.ts`.
3848
- */
3849
- async preparePreview(dir, fetch = true) {
3850
- await this.init();
3851
- await this.knownProjectFolder(dir, 'it is not prepared from here');
3852
- // The operator pressed the button and is looking: the remote may ask for a password through Git's own window.
3853
- return await planPrepare(resolve(dir.trim()), { fetch, askpass: fetch ? await askpassProgram() : null });
3854
- }
3855
- /**
3856
- * The second half: does it, if the folder is still what the preview showed. Refused while anything
3857
- * runs, or is being started, in that folder or one around it: it moves the checkout.
3858
- */
3859
- async prepareProject(dir, fingerprint, names = {}) {
3860
- await this.init();
3861
- await this.knownProjectFolder(dir, 'it is not prepared from here');
3862
- if (this.batch?.running)
3863
- return { ok: false, problem: 'A run is going. Stop it before preparing the folder; nothing was changed.' };
3864
- if (this.browser?.kind === 'run' || this.browser?.kind === 'batch')
3865
- return { ok: false, problem: 'A run is being started. Wait for it, or stop it, before preparing the folder; nothing was changed.' };
3866
- const other = await this.runningIn(dir);
3867
- if (other)
3868
- return { ok: false, problem: `Session "${other.name}" is running in this folder. Stop it before preparing the folder; nothing was changed.` };
3869
- const done = await prepareFromRemote(resolve(dir.trim()), String(fingerprint ?? ''), { names });
3870
- // Kept on every session working in that folder: it moved the checkout and made saved branches.
3871
- if (done.ok) {
3872
- const cfg = await this.settings.load();
3873
- const here = normaliseDir(dir);
3874
- for (const s of (await this.store.listSessions()).filter((x) => normaliseDir(repoDirOf(x)) === here)) {
3875
- const message = `the folder was prepared from ${done.target}: ${done.result}`;
3876
- await appendSessionLog(cfg.resolved.runsDir, s.id, { type: 'folder-prepared', message, data: { target: done.target, commit: done.commit, branch: done.branch, saved: done.saved, removedFromFolder: done.removedFromFolder } }).catch(() => undefined);
3877
- this.bus.publish({ sessionId: s.id, type: 'folder-prepared', level: 'info', message, data: { target: done.target, commit: done.commit, saved: done.saved } });
3878
- }
3879
- }
3880
- return done;
3881
- }
3882
1740
  // --- the project being worked on ---------------------------------------------------------
3883
1741
  /**
3884
1742
  * The folder new sessions start pointed at, and whether it can carry version control.
@@ -3889,18 +1747,25 @@ let OperatorService = class OperatorService {
3889
1747
  async project() {
3890
1748
  const cfg = await this.settings.load();
3891
1749
  const rootDir = (cfg.project?.rootDir ?? '').trim();
3892
- const problem = repoUnusableReason(rootDir);
3893
- const others = (cfg.project?.others ?? []).map((o) => {
3894
- const p = repoUnusableReason(o.rootDir);
3895
- return { name: o.name, rootDir: o.rootDir, repoOk: p === null, ...(p ? { repoProblem: p } : {}) };
3896
- });
3897
- return {
3898
- rootDir,
3899
- name: (cfg.project?.name ?? '').trim(),
3900
- repoOk: rootDir !== '' && problem === null,
3901
- ...(problem ? { repoProblem: problem } : {}),
3902
- others,
1750
+ /*
1751
+ * The branch each folder is on now (operator, 2026-10-20: "show which branch is chosen"), read from git each
1752
+ * time, since the operator switches it by hand and the chat works on whatever is checked out.
1753
+ */
1754
+ const entry = async (name, dir, level2) => {
1755
+ const problem = dir ? repoUnusableReason(dir) : 'no folder';
1756
+ const branch = dir && problem === null ? await git(dir, ['rev-parse', '--abbrev-ref', 'HEAD']).catch(() => null) : null;
1757
+ return {
1758
+ name,
1759
+ rootDir: dir,
1760
+ repoOk: dir !== '' && problem === null,
1761
+ ...(dir && problem ? { repoProblem: problem } : {}),
1762
+ ...(branch?.ok && branch.stdout ? { branch: branch.stdout } : {}),
1763
+ level2,
1764
+ };
3903
1765
  };
1766
+ const main = await entry((cfg.project?.name ?? '').trim(), rootDir, cfg.project?.level2 ?? '');
1767
+ const others = await Promise.all((cfg.project?.others ?? []).map((o) => entry(o.name, o.rootDir, o.level2 ?? '')));
1768
+ return { ...main, others };
3904
1769
  }
3905
1770
  /**
3906
1771
  * Stores the project folder and the other folders the operator works in. A field left out
@@ -3920,12 +1785,26 @@ let OperatorService = class OperatorService {
3920
1785
  const current = (raw.project ?? {});
3921
1786
  const rootDir = patch.rootDir !== undefined ? patch.rootDir.trim() : (current.rootDir ?? '').trim();
3922
1787
  const name = patch.name !== undefined ? patch.name.trim() : (current.name ?? '').trim();
1788
+ const level2 = patch.level2 !== undefined ? patch.level2 : (current.level2 ?? '');
1789
+ // Each goes into Kerrigan whole, and she is pasted into a chat: bounded, so one project cannot crowd out the rest.
1790
+ const tooLong = [{ name: name || rootDir, level2 }, ...(patch.others ?? [])].find((o) => (o.level2 ?? '').length > MAX_PROJECT_LEVEL2);
1791
+ if (tooLong)
1792
+ throw new Error(`The level 2 of "${tooLong.name}" is longer than ${MAX_PROJECT_LEVEL2.toLocaleString('en')} characters; keep it to what a chat needs to know about the project.`);
3923
1793
  if (rootDir && !existsSync(rootDir))
3924
1794
  throw new Error(`The folder ${rootDir} does not exist on this machine.`);
3925
- const others = (patch.others ?? current.others ?? []).map((o) => ({
3926
- name: (o.name ?? '').trim(),
3927
- rootDir: (o.rootDir ?? '').trim(),
3928
- }));
1795
+ /*
1796
+ * A project's level 2 is kept with it when the list comes without one — renamed or moved, or saved by a page that
1797
+ * does not know the field — matched by its folder, then by its name.
1798
+ */
1799
+ const before = current.others ?? [];
1800
+ const others = (patch.others ?? before).map((o) => {
1801
+ const was = before.find((b) => sameFolder(b.rootDir ?? '', o.rootDir ?? '')) ?? before.find((b) => (b.name ?? '').trim() === (o.name ?? '').trim());
1802
+ return {
1803
+ name: (o.name ?? '').trim(),
1804
+ rootDir: (o.rootDir ?? '').trim(),
1805
+ level2: o.level2 !== undefined ? o.level2 : (was?.level2 ?? ''),
1806
+ };
1807
+ });
3929
1808
  const seen = new Set();
3930
1809
  for (const o of others) {
3931
1810
  if (!o.name)
@@ -3943,7 +1822,7 @@ let OperatorService = class OperatorService {
3943
1822
  }
3944
1823
  // What the removed Desktop copies left in the stored project is dropped with the next save.
3945
1824
  const { mirror: _m, desktop: _d, mirrorToDesktop: _t, ...rest } = current;
3946
- return { ...raw, project: { ...rest, rootDir, name, others } };
1825
+ return { ...raw, project: { ...rest, rootDir, name, level2, others } };
3947
1826
  });
3948
1827
  return await this.project();
3949
1828
  }
@@ -4044,6 +1923,7 @@ let OperatorService = class OperatorService {
4044
1923
  humanWaitMs: cfg.copilot.signInTimeoutSec * 1000,
4045
1924
  keepFailurePage: cfg.copilot.keepFailurePage,
4046
1925
  });
1926
+ await this.closeChatWindow('signing in needs the browser');
4047
1927
  await transport.open();
4048
1928
  if (upn) {
4049
1929
  await transport.signOut();
@@ -4100,6 +1980,7 @@ let OperatorService = class OperatorService {
4100
1980
  humanWaitMs: cfg.copilot.humanWaitSec * 1000,
4101
1981
  keepFailurePage: cfg.copilot.keepFailurePage,
4102
1982
  });
1983
+ await this.closeChatWindow('reading the models needs the browser');
4103
1984
  await transport.open();
4104
1985
  await transport.ensureSignedIn();
4105
1986
  const { options, current, note } = await transport.listModels();
@@ -4123,94 +2004,6 @@ let OperatorService = class OperatorService {
4123
2004
  }
4124
2005
  }
4125
2006
  // --- the registry ---------------------------------------------------------------------
4126
- /**
4127
- * Every task of every session in one flat list, newest session first and, inside a session,
4128
- * in the order the tasks run. The page splits it into what is done, what is running and
4129
- * what is still ahead; doing the flattening here keeps that split honest, because the
4130
- * queue position is only knowable from the session's own list.
4131
- */
4132
- /** How well the bot is doing, added up from every task on record. See `session/metrics.ts`. */
4133
- async metrics() {
4134
- await this.init();
4135
- return computeMetrics(await this.store.listSessions());
4136
- }
4137
- async taskRegistry() {
4138
- await this.init();
4139
- const sessions = await this.store.listSessions();
4140
- const out = [];
4141
- for (const s of sessions) {
4142
- let queueSeen = 0;
4143
- s.tasks.forEach((t, i) => {
4144
- if (t.status === 'queued')
4145
- queueSeen += 1;
4146
- const started = t.startedAt ? Date.parse(t.startedAt) : undefined;
4147
- const finished = t.finishedAt ? Date.parse(t.finishedAt) : undefined;
4148
- out.push({
4149
- sessionId: s.id,
4150
- sessionName: s.name,
4151
- sessionStatus: s.status,
4152
- sessionOnFailure: s.onFailure === 'continue' ? 'continue' : 'stop',
4153
- sessionRunOrder: s.runGroup?.order,
4154
- sessionRunning: this.running.has(s.id),
4155
- chatUrl: s.chat?.url,
4156
- taskId: t.id,
4157
- title: t.title,
4158
- status: t.status,
4159
- position: i + 1,
4160
- queuePosition: t.status === 'queued' ? queueSeen : undefined,
4161
- createdAt: t.createdAt,
4162
- startedAt: t.startedAt,
4163
- finishedAt: t.finishedAt,
4164
- durationMs: started && finished ? finished - started : undefined,
4165
- iterations: t.iterations,
4166
- summary: t.summary,
4167
- reason: t.reason,
4168
- runId: t.runId,
4169
- runGroup: t.runGroup,
4170
- review: t.review
4171
- ? { verdict: t.review.verdict, findings: t.review.findings?.length ?? 0, stepsRun: t.review.stepsRun }
4172
- : undefined,
4173
- deviations: t.deviations?.length || undefined,
4174
- disputes: t.disputes?.length || undefined,
4175
- readOnly: t.readOnly || undefined,
4176
- scope: t.scope?.length ? t.scope : undefined,
4177
- stopCode: t.stopCode,
4178
- limit: t.limit,
4179
- continuable: isContinuable(t) || undefined,
4180
- branch: t.vcs?.branch,
4181
- commit: t.vcs?.commit,
4182
- vcsProblem: t.vcs?.problem,
4183
- sessionInactive: s.active === false || undefined,
4184
- autoRetries: freshRetriesOfLatestRun(t) || undefined,
4185
- attempt: t.attempt,
4186
- changedFiles: t.vcs?.commit && t.vcs.baseCommit ? (t.vcs.files?.length ?? 0) : undefined,
4187
- interrupted: t.status === 'aborted' && !!t.interruption ? true : undefined,
4188
- attempts: (t.attempts ?? []).map((a, n) => {
4189
- const from = a.startedAt ? Date.parse(a.startedAt) : undefined;
4190
- const to = a.finishedAt ? Date.parse(a.finishedAt) : undefined;
4191
- return {
4192
- attempt: n + 1,
4193
- status: a.status,
4194
- startedAt: a.startedAt,
4195
- finishedAt: a.finishedAt,
4196
- durationMs: from && to ? to - from : undefined,
4197
- iterations: a.iterations,
4198
- summary: a.summary,
4199
- reason: a.reason,
4200
- runId: a.runId,
4201
- branch: a.vcs?.branch,
4202
- // Why the runner stopped this attempt, whether it was a fresh-chat retry, and its commit (live run 2026-10-03).
4203
- stopCode: a.stopCode,
4204
- freshRetry: a.freshRetry,
4205
- commit: a.vcs?.commit,
4206
- changedFiles: a.vcs?.commit && a.vcs.baseCommit ? (a.vcs.files?.length ?? 0) : undefined,
4207
- };
4208
- }),
4209
- });
4210
- });
4211
- }
4212
- return out;
4213
- }
4214
2007
  // --- environment ----------------------------------------------------------------------
4215
2008
  /** Opens the machine's own folder dialog and reports what was picked. */
4216
2009
  async browseFolder(start) {
@@ -4233,7 +2026,7 @@ let OperatorService = class OperatorService {
4233
2026
  * on that profile *by the runner*, and the warning "close this Edge window, a run would
4234
2027
  * fail" was shown in exactly the moment it was false. The page says which it is.
4235
2028
  */
4236
- botRunning: this.running.size > 0 || this.batch?.running === true,
2029
+ botRunning: this.running.size > 0,
4237
2030
  desktop: resolveDesktopDir(),
4238
2031
  desktopSynced: desktopIsSynced(),
4239
2032
  cwd: cfg.resolved.cwd,