copilot-operator 0.1.50 → 0.1.51
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.
- package/README.md +582 -574
- package/dist/src/api/operator.controller.js +77 -932
- package/dist/src/api/operator.service.js +197 -2461
- package/dist/src/orchestrator/hold.js +49 -0
- package/dist/src/orchestrator/taskRunner.js +157 -23
- package/dist/src/plan/kerrigan.js +107 -0
- package/dist/src/plan/systemGuide.js +438 -3374
- package/dist/src/session/chatNotice.js +76 -0
- package/dist/src/session/store.js +2 -57
- package/dist/src/session/workspace.js +52 -5
- package/dist/src/transport/chatTransport.js +1 -1
- package/dist/src/transport/copilotTransport.js +133 -1
- package/dist/web/404.html +5 -3
- package/dist/web/_next/static/chunks/134-ddd50a7fbb536ec8.js +1 -0
- package/dist/web/_next/static/chunks/190-70555f20dd0da19b.js +1 -0
- package/dist/web/_next/static/chunks/643-e85d221d57900ed7.js +1 -0
- package/dist/web/_next/static/chunks/867-869900ec999e6345.js +1 -0
- package/dist/web/_next/static/chunks/app/appearance/page-cdef33c421397cbe.js +1 -0
- package/dist/web/_next/static/chunks/app/defaults/page-e0a2b8f9a41a94c4.js +1 -0
- package/dist/web/_next/static/chunks/app/layout-b4fc21e26e1bad95.js +1 -0
- package/dist/web/_next/static/chunks/app/level1/page-31b74cae86d960d8.js +1 -0
- package/dist/web/_next/static/chunks/app/page-1075921d44db3e4d.js +1 -0
- package/dist/web/_next/static/chunks/app/presets/page-f8abdd83cdf468f7.js +1 -0
- package/dist/web/_next/static/chunks/app/system/page-2a270bb885885821.js +1 -0
- package/dist/web/_next/static/css/8b14cb3cf0051138.css +1 -0
- package/dist/web/_next/static/eqTUTH_SJtBgNgq8Zzy3n/_buildManifest.js +1 -0
- package/dist/web/appearance.html +5 -3
- package/dist/web/appearance.txt +22 -23
- package/dist/web/defaults.html +5 -3
- package/dist/web/defaults.txt +22 -23
- package/dist/web/index.html +5 -3
- package/dist/web/index.txt +22 -23
- package/dist/web/level1.html +5 -3
- package/dist/web/level1.txt +22 -23
- package/dist/web/presets.html +6 -4
- package/dist/web/presets.txt +22 -23
- package/dist/web/system.html +5 -3
- package/dist/web/system.txt +22 -23
- package/package.json +3 -20
- package/dist/src/api/saveToDesktop.js +0 -157
- package/dist/src/plan/brief.js +0 -2003
- package/dist/src/plan/changes.js +0 -217
- package/dist/src/plan/script.js +0 -1014
- package/dist/src/session/debugExport.js +0 -165
- package/dist/src/session/exportRecord.js +0 -277
- package/dist/src/session/metrics.js +0 -95
- package/dist/src/vcs/startChoice.js +0 -367
- package/dist/web/_next/static/chunks/197-f7c33a0114fc3db3.js +0 -1
- package/dist/web/_next/static/chunks/499-751e0be9d4f86e2d.js +0 -1
- package/dist/web/_next/static/chunks/534-56c68930a1a3c10f.js +0 -1
- package/dist/web/_next/static/chunks/549-c32dd718a1809d4d.js +0 -1
- package/dist/web/_next/static/chunks/699-9d031f8c145a0465.js +0 -1
- package/dist/web/_next/static/chunks/867-0e5d0d5472bf185f.js +0 -1
- package/dist/web/_next/static/chunks/app/appearance/page-a18019cdc395de3d.js +0 -1
- package/dist/web/_next/static/chunks/app/defaults/page-614be29d185a2947.js +0 -1
- package/dist/web/_next/static/chunks/app/history/page-95bab4c1b1ff9339.js +0 -1
- package/dist/web/_next/static/chunks/app/import/page-8ef75fc08638e75f.js +0 -1
- package/dist/web/_next/static/chunks/app/layout-a1314921eeba8ad5.js +0 -1
- package/dist/web/_next/static/chunks/app/level1/page-dd3ebf37d29dce4f.js +0 -1
- package/dist/web/_next/static/chunks/app/page-4d8f0851fe672925.js +0 -1
- package/dist/web/_next/static/chunks/app/presets/page-93ab518db67e52a2.js +0 -1
- package/dist/web/_next/static/chunks/app/sessions/page-28376d2e4a9b4738.js +0 -1
- package/dist/web/_next/static/chunks/app/sessions/view/page-adb64f8ba3d8c06e.js +0 -1
- package/dist/web/_next/static/chunks/app/system/page-227a259e383ca2a0.js +0 -1
- package/dist/web/_next/static/css/4335e4ce269ba1ea.css +0 -1
- package/dist/web/_next/static/z74_FBfnnXW5IJCHTgTH2/_buildManifest.js +0 -1
- package/dist/web/history.html +0 -16
- package/dist/web/history.txt +0 -26
- package/dist/web/import.html +0 -16
- package/dist/web/import.txt +0 -26
- package/dist/web/sessions/view.html +0 -16
- package/dist/web/sessions/view.txt +0 -26
- package/dist/web/sessions.html +0 -16
- package/dist/web/sessions.txt +0 -26
- package/prompts/organisation.bg.md +0 -43
- package/prompts/organisation.en.md +0 -43
- package/prompts/persona.bg.md +0 -17
- package/prompts/persona.en.md +0 -17
- package/prompts/work.bg.md +0 -19
- package/prompts/work.en.md +0 -19
- /package/dist/web/_next/static/{z74_FBfnnXW5IJCHTgTH2 → eqTUTH_SJtBgNgq8Zzy3n}/_ssgManifest.js +0 -0
|
@@ -14,24 +14,22 @@ 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
|
|
20
|
+
import { SessionStore, DEFAULT_VCS, DEFAULT_REVIEW } from '../session/store.js';
|
|
22
21
|
import { EventBus } from '../session/events.js';
|
|
23
|
-
import {
|
|
24
|
-
import { runSession,
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
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';
|
|
35
33
|
/**
|
|
36
34
|
* A settings file or a policy lock that cannot be used: answered 409 with its own message on every route
|
|
37
35
|
* (see `server.ts`), so a start passes it on rather than answering it as a start that did not happen.
|
|
@@ -48,61 +46,38 @@ function sameFolder(a, b) {
|
|
|
48
46
|
const norm = (p) => p.trim().replace(/[\\/]+$/, '').replace(/\//g, '\\').toLowerCase();
|
|
49
47
|
return a.trim() !== '' && norm(a) === norm(b);
|
|
50
48
|
}
|
|
51
|
-
import {
|
|
52
|
-
import { checkChanges, kerriganReport } from '../plan/changes.js';
|
|
53
|
-
import { workspaceFile, workspaceFiles, workspaceInfo } from '../session/workspace.js';
|
|
49
|
+
import { saveWorkspaceFile, workspaceFile, workspaceFiles, workspaceInfo } from '../session/workspace.js';
|
|
54
50
|
import { restoreCheckpoint } from '../session/checkpoint.js';
|
|
55
51
|
import { readInterruption } from '../session/interruption.js';
|
|
56
|
-
import { baseRefOf,
|
|
57
|
-
import {
|
|
52
|
+
import { baseRefOf, commitInterrupted, nextAttemptBranch, repoDirOf, trackedRepoOf, sessionBranchName } from '../vcs/taskVcs.js';
|
|
53
|
+
import { changedFilesBetween, fileAt, git, repoUnusableReason } from '../vcs/git.js';
|
|
58
54
|
import { makeAuthorizer } from '../exec/authorizer.js';
|
|
59
55
|
import { pickFolder } from './folderPicker.js';
|
|
60
56
|
import { findEdgeUsingProfile } from '../transport/profileLock.js';
|
|
61
|
-
import { assessIsolation, readIsolationSignals
|
|
57
|
+
import { assessIsolation, readIsolationSignals } from '../exec/isolation.js';
|
|
62
58
|
import { unattendedPrecondition } from '../exec/policy.js';
|
|
63
59
|
import { createTransport } from '../transport/chatTransport.js';
|
|
64
60
|
import { composeHandoff } from '../session/handoff.js';
|
|
65
|
-
import { planSync } from '../vcs/syncCommand.js';
|
|
66
61
|
import { planPrepare, prepareFromRemote } from '../vcs/prepareFromRemote.js';
|
|
67
62
|
import { askpassProgram } from '../vcs/remoteAuth.js';
|
|
68
63
|
import { appendRunLog, appendSessionLog, readRunLog } from '../session/runLog.js';
|
|
69
|
-
import { applyStartChoice, fetchForStart, startOptions, withChoice } from '../vcs/startChoice.js';
|
|
70
64
|
import { StartFailures, failureReport, refOf } from '../session/startFailure.js';
|
|
71
65
|
import { formatTerminal, localTime, terminalLines, terminalLogFile } from '../log/terminal.js';
|
|
72
66
|
import { redactSecrets } from '../exec/redaction.js';
|
|
73
67
|
import { workingDirFor, isWorkingDirProblem } from '../exec/workDir.js';
|
|
74
|
-
import { contractConflictsWithFixes
|
|
68
|
+
import { contractConflictsWithFixes } from '../orchestrator/contract.js';
|
|
75
69
|
import { checkRefusalForOperator, lineRefusal } from '../orchestrator/taskRunner.js';
|
|
76
70
|
import { preferredShell } from '../exec/shells.js';
|
|
77
71
|
import { sessionRoots } from '../exec/confinement.js';
|
|
78
|
-
import { dirtyPolicy
|
|
79
|
-
import { runVcsPreflight
|
|
72
|
+
import { dirtyPolicy } from '../vcs/snapshot.js';
|
|
73
|
+
import { runVcsPreflight } from '../vcs/runPreflight.js';
|
|
80
74
|
import { inputSettings, normalisePatterns } from '../vcs/inputs.js';
|
|
81
75
|
import { coveredByArtifacts } from '../vcs/artifacts.js';
|
|
82
76
|
import { botVersion } from '../config/version.js';
|
|
83
|
-
import { computeMetrics } from '../session/metrics.js';
|
|
84
77
|
import { resolveDesktopDir, desktopIsSynced } from '../context/desktopDir.js';
|
|
85
|
-
import { saveAndReveal } from './saveToDesktop.js';
|
|
86
78
|
import { settingsOf, SettingsUnusableError } from './settings.js';
|
|
87
79
|
import { PolicyLockUnusableError } from '../config/lockedPolicy.js';
|
|
88
80
|
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
81
|
const INACTIVE_REASON = 'the session is inactive; make it active on the Sessions page to run it';
|
|
107
82
|
/**
|
|
108
83
|
* Why the browser cannot be had now, said in terms of what was pressed. The sentences a start, a
|
|
@@ -120,27 +95,17 @@ function browserRefusal(held, ask) {
|
|
|
120
95
|
}
|
|
121
96
|
if (ask.kind === 'login')
|
|
122
97
|
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
98
|
if (held.kind === 'models') {
|
|
129
99
|
return ask.kind === 'models'
|
|
130
100
|
? 'The model list is already being read.'
|
|
131
101
|
: 'the model list is being read from the chat, which has the browser; start this once it has finished';
|
|
132
102
|
}
|
|
133
|
-
// A
|
|
103
|
+
// A conversation running.
|
|
134
104
|
if (ask.kind === 'models')
|
|
135
105
|
return modelsWhileRunning;
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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';
|
|
106
|
+
return ask.sessionId === held.sessionId
|
|
107
|
+
? 'already running'
|
|
108
|
+
: 'another conversation is running, and the browser takes one run at a time; start this one once it has finished';
|
|
144
109
|
}
|
|
145
110
|
/** A folder as compared: absolute, forward slashes, no trailing slash, and case folded as Windows does. */
|
|
146
111
|
function normaliseDir(dir) {
|
|
@@ -148,84 +113,10 @@ function normaliseDir(dir) {
|
|
|
148
113
|
return '';
|
|
149
114
|
return resolve(dir.trim()).replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
|
|
150
115
|
}
|
|
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
116
|
/** Whether two folders, as `normaliseDir` gives them, are one folder or one is inside the other. */
|
|
215
117
|
function overlaps(a, b) {
|
|
216
118
|
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
217
119
|
}
|
|
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
120
|
let OperatorService = class OperatorService {
|
|
230
121
|
/** Where this install keeps its prompts and its records. See `config/layout.ts`. */
|
|
231
122
|
layout = installLayout();
|
|
@@ -238,8 +129,6 @@ let OperatorService = class OperatorService {
|
|
|
238
129
|
startFailures = new StartFailures();
|
|
239
130
|
running = new Map();
|
|
240
131
|
waiting = new Map();
|
|
241
|
-
/** The batch in progress, or the last one that finished. At most one ever exists. */
|
|
242
|
-
batch = null;
|
|
243
132
|
ready = null;
|
|
244
133
|
/**
|
|
245
134
|
* What has the browser now: one session's run, a batch, or a read of the model list.
|
|
@@ -256,6 +145,17 @@ let OperatorService = class OperatorService {
|
|
|
256
145
|
* refused. See `claimBrowser`.
|
|
257
146
|
*/
|
|
258
147
|
browser = null;
|
|
148
|
+
/**
|
|
149
|
+
* The workbench chat's window, left open when the work on a message has ended (2026-10-19: "when the work on one
|
|
150
|
+
* chat message is done, the browser is not to close, so that if the work goes on with another message it is open
|
|
151
|
+
* already"). Given to the chat's next message, in this conversation or a new one, so it does not open again.
|
|
152
|
+
*
|
|
153
|
+
* Not a claim on the browser (`browser`): nothing is using it. Whatever takes the browser next and is not a message
|
|
154
|
+
* of the chat — a session's run, a batch, signing in, reading the models — closes it first (`closeChatWindow`),
|
|
155
|
+
* since the profile takes one window. The operator closes it with its X whenever they like; that is found when it
|
|
156
|
+
* is next wanted (`keptChatWindow`), and it is closed when the program is.
|
|
157
|
+
*/
|
|
158
|
+
chatWindow = null;
|
|
259
159
|
/**
|
|
260
160
|
* One-time startup work, run lazily on the first request that needs the store.
|
|
261
161
|
*
|
|
@@ -337,19 +237,6 @@ let OperatorService = class OperatorService {
|
|
|
337
237
|
return await this.store.getLevel1();
|
|
338
238
|
}
|
|
339
239
|
// --- 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
240
|
// --- level 2 presets ------------------------------------------------------------------
|
|
354
241
|
async listPresets() {
|
|
355
242
|
await this.init();
|
|
@@ -364,31 +251,11 @@ let OperatorService = class OperatorService {
|
|
|
364
251
|
await this.store.deletePreset(name);
|
|
365
252
|
}
|
|
366
253
|
// --- 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
254
|
// --- 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
255
|
async listSessions() {
|
|
389
256
|
await this.init();
|
|
390
257
|
const all = await this.store.listSessions();
|
|
391
|
-
return all.map((s) => ({ ...s, running: this.running.has(s.id) }));
|
|
258
|
+
return all.map((s) => ({ ...s, running: this.running.has(s.id), paused: this.running.get(s.id)?.hold.held ?? false }));
|
|
392
259
|
}
|
|
393
260
|
async getSession(id) {
|
|
394
261
|
await this.init();
|
|
@@ -396,35 +263,7 @@ let OperatorService = class OperatorService {
|
|
|
396
263
|
if (!s)
|
|
397
264
|
return null;
|
|
398
265
|
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
|
-
});
|
|
266
|
+
return { ...s, running: this.running.has(id), paused: this.running.get(id)?.hold.held ?? false, pending, runMode: this.running.get(id)?.mode };
|
|
428
267
|
}
|
|
429
268
|
async updateSession(id, patch) {
|
|
430
269
|
await this.init();
|
|
@@ -559,53 +398,6 @@ let OperatorService = class OperatorService {
|
|
|
559
398
|
}
|
|
560
399
|
});
|
|
561
400
|
}
|
|
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);
|
|
602
|
-
}
|
|
603
|
-
return task;
|
|
604
|
-
}
|
|
605
|
-
async deleteTask(sessionId, taskId) {
|
|
606
|
-
await this.init();
|
|
607
|
-
await this.store.deleteTask(sessionId, taskId);
|
|
608
|
-
}
|
|
609
401
|
/**
|
|
610
402
|
* A note to the chat about a task (2026-10-14): queued, running or waiting, it goes out with the task's
|
|
611
403
|
* next message — at once, in effect, for a task that is running. See `Task.notes`.
|
|
@@ -619,116 +411,6 @@ let OperatorService = class OperatorService {
|
|
|
619
411
|
data: { length: text.trim().length, running } });
|
|
620
412
|
return task;
|
|
621
413
|
}
|
|
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
414
|
/**
|
|
733
415
|
* The story of one attempt, assembled from its run folder: what was sent, what the chat
|
|
734
416
|
* answered, what ran with its output, the review rounds, how it ended. Read while it runs
|
|
@@ -821,173 +503,6 @@ let OperatorService = class OperatorService {
|
|
|
821
503
|
return { problem: 'The session has no repository folder set.' };
|
|
822
504
|
return { dir, base: vcs.baseCommit, commit: vcs.commit, branch: vcs.branch };
|
|
823
505
|
}
|
|
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
506
|
/**
|
|
992
507
|
* Everything that passed between the bot and Copilot for one task — every message sent, every reply, every
|
|
993
508
|
* command with its whole output — every attempt of it and nothing of the tasks around it (2026-10-18: one JSON per
|
|
@@ -1005,60 +520,6 @@ let OperatorService = class OperatorService {
|
|
|
1005
520
|
const label = `${chatCode(session.id)}-${String(session.tasks.indexOf(task) + 1).padStart(2, '0')}-${task.title}`;
|
|
1006
521
|
return { fileName: exportFileName('exchange', label), content: JSON.stringify(document, null, 2) };
|
|
1007
522
|
}
|
|
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
523
|
// --- running --------------------------------------------------------------------------
|
|
1063
524
|
isRunning(sessionId) {
|
|
1064
525
|
return this.running.has(sessionId);
|
|
@@ -1079,38 +540,77 @@ let OperatorService = class OperatorService {
|
|
|
1079
540
|
if (this.browser === holder)
|
|
1080
541
|
this.browser = null;
|
|
1081
542
|
}
|
|
543
|
+
/** The window the chat left open, if it is still there; one the operator closed with its X is let go of. */
|
|
544
|
+
async keptChatWindow() {
|
|
545
|
+
const window = this.chatWindow;
|
|
546
|
+
if (!window)
|
|
547
|
+
return undefined;
|
|
548
|
+
if (window.isOpen())
|
|
549
|
+
return window;
|
|
550
|
+
this.chatWindow = null;
|
|
551
|
+
await window.close().catch(() => undefined);
|
|
552
|
+
return undefined;
|
|
553
|
+
}
|
|
554
|
+
keepChatWindow(window) {
|
|
555
|
+
// One at a time, as the profile allows: an earlier one still held is closed rather than lost open.
|
|
556
|
+
const earlier = this.chatWindow;
|
|
557
|
+
this.chatWindow = window;
|
|
558
|
+
if (earlier && earlier !== window)
|
|
559
|
+
void earlier.close().catch(() => undefined);
|
|
560
|
+
}
|
|
561
|
+
/** Closes the window the chat left open, before something else takes the browser. Said on the console. */
|
|
562
|
+
async closeChatWindow(why) {
|
|
563
|
+
const window = this.chatWindow;
|
|
564
|
+
if (!window)
|
|
565
|
+
return;
|
|
566
|
+
this.chatWindow = null;
|
|
567
|
+
if (window.isOpen())
|
|
568
|
+
console.log(`[chat] the window the chat left open is closed: ${why}`);
|
|
569
|
+
await window.close().catch(() => undefined);
|
|
570
|
+
}
|
|
571
|
+
/** The card in the chat's window once the work on a message has ended (see `session/chatNotice.ts`). */
|
|
572
|
+
async chatWindowNotice(sessionId, tally) {
|
|
573
|
+
const window = this.chatWindow;
|
|
574
|
+
if (!window?.isOpen())
|
|
575
|
+
return;
|
|
576
|
+
const s = await this.store.getSession(sessionId);
|
|
577
|
+
if (!s)
|
|
578
|
+
return;
|
|
579
|
+
const ids = new Set(s.runGroup?.taskIds ?? []);
|
|
580
|
+
const tasks = s.tasks.filter((t) => ids.has(t.id)).map((t) => ({ title: t.title, status: t.status, reason: t.reason, summary: t.summary }));
|
|
581
|
+
if (tasks.length === 0)
|
|
582
|
+
return;
|
|
583
|
+
// Refused at its turn, nothing of it began: said as a start that could not happen, not as a stop.
|
|
584
|
+
await window.showNotice(chatNotice(s.lang === 'bg' ? 'bg' : 'en', tasks, tally.error ?? tally.refused)).catch(() => undefined);
|
|
585
|
+
}
|
|
586
|
+
/** The program is closing: so is the window the chat left open. */
|
|
587
|
+
async onModuleDestroy() {
|
|
588
|
+
await this.closeChatWindow('the program is closing');
|
|
589
|
+
}
|
|
1082
590
|
/**
|
|
1083
591
|
* Starts the session's queued tasks in the background. Returns immediately; progress
|
|
1084
592
|
* arrives on the event stream. One run at a time, of this session or any other.
|
|
1085
593
|
*/
|
|
1086
|
-
async start(sessionId, mode = 'confirm'
|
|
1087
|
-
/** Where the session starts, as chosen in the start window: see `vcs/startChoice.ts`. Absent keeps its settings. */
|
|
1088
|
-
starts) {
|
|
594
|
+
async start(sessionId, mode = 'confirm') {
|
|
1089
595
|
const pressedAt = new Date().toISOString();
|
|
1090
596
|
// One conversation at a time is not a policy, it is the browser profile: a second run
|
|
1091
597
|
// does not get a second browser, it gets an error about a closed one. Whatever has the
|
|
1092
|
-
// browser now —
|
|
598
|
+
// browser now — another conversation, a read of the models, the sign-in — the start is refused where
|
|
1093
599
|
// the reason can still be read, rather than three minutes later in a stack trace.
|
|
1094
600
|
const claim = this.claimBrowser({ kind: 'run', sessionId });
|
|
1095
601
|
if ('refused' in claim)
|
|
1096
602
|
return await this.notStarted({ stage: 'refused', message: claim.refused, sessionIds: [sessionId], pressedAt });
|
|
1097
603
|
let runId;
|
|
1098
604
|
try {
|
|
1099
|
-
//
|
|
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.
|
|
605
|
+
// Set aside: said first, before the preflight judges a session that will not run.
|
|
1102
606
|
if ((await this.store.getSession(sessionId))?.active === false) {
|
|
1103
607
|
this.releaseBrowser(claim.holder);
|
|
1104
608
|
return await this.notStarted({ stage: 'refused', message: INACTIVE_REASON, sessionIds: [sessionId], pressedAt });
|
|
1105
609
|
}
|
|
1106
|
-
|
|
610
|
+
// Named after what it is a run of.
|
|
611
|
+
const chosenName = await this.suggestRunName([sessionId]);
|
|
1107
612
|
const runGroup = { id: newId('r-'), startedAt: new Date().toISOString(), sessions: 1, name: chosenName };
|
|
1108
613
|
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
614
|
const before = await this.store.getSession(sessionId);
|
|
1115
615
|
const earlyRefusal = !before ? 'no such session' : queuedToRun(before).length === 0 ? 'no queued tasks' : await this.unattendedRefusal(mode);
|
|
1116
616
|
if (earlyRefusal) {
|
|
@@ -1118,14 +618,6 @@ let OperatorService = class OperatorService {
|
|
|
1118
618
|
// No run log for a session that does not exist: the id is the caller's, and may be anything.
|
|
1119
619
|
return await this.notStarted({ stage: 'refused', message: earlyRefusal, sessionIds: [sessionId], pressedAt, ...(before ? { runId } : {}) });
|
|
1120
620
|
}
|
|
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
621
|
// Recorded by `beginRun` once the start is accepted, not here: see `recordOnSession`.
|
|
1130
622
|
// Version control first, before anything opens the browser: see `vcs/runPreflight.ts`.
|
|
1131
623
|
const notReady = await this.runPreflight(runGroup.id, [sessionId]);
|
|
@@ -1133,14 +625,20 @@ let OperatorService = class OperatorService {
|
|
|
1133
625
|
this.releaseBrowser(claim.holder);
|
|
1134
626
|
return await this.notStarted({ stage: 'preflight', message: notReady, sessionIds: [sessionId], pressedAt, runId });
|
|
1135
627
|
}
|
|
1136
|
-
|
|
628
|
+
// A message of the chat is given the window the last one left open, while it is still there (see `chatWindow`).
|
|
629
|
+
const chat = before?.kind === 'chat';
|
|
630
|
+
const lent = chat ? await this.keptChatWindow() : undefined;
|
|
631
|
+
const begun = await this.beginRun(sessionId, mode, lent, runGroup, undefined, { recordOnSession: true, pressedAt, chatWindow: chat });
|
|
1137
632
|
if (!begun.started) {
|
|
1138
633
|
this.releaseBrowser(claim.holder);
|
|
1139
634
|
return await this.notStarted({ stage: 'refused', message: begun.reason ?? 'not started', sessionIds: [sessionId], pressedAt, runId });
|
|
1140
635
|
}
|
|
1141
636
|
// 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
|
|
637
|
+
// free again exactly when it is. The chat's stays open, and says in it that the work has ended.
|
|
638
|
+
void begun.done
|
|
639
|
+
.then((tally) => (chat ? this.chatWindowNotice(sessionId, tally) : undefined))
|
|
640
|
+
.catch(() => undefined)
|
|
641
|
+
.finally(() => this.releaseBrowser(claim.holder));
|
|
1144
642
|
return { started: true };
|
|
1145
643
|
}
|
|
1146
644
|
catch (e) {
|
|
@@ -1182,88 +680,6 @@ let OperatorService = class OperatorService {
|
|
|
1182
680
|
}
|
|
1183
681
|
return { started: false, reason: f.message, failure: refOf(recorded) };
|
|
1184
682
|
}
|
|
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
683
|
/** The starts that did not get as far as a first task, newest first: see `session/startFailure.ts`. */
|
|
1268
684
|
recentStartFailures(unansweredOnly) {
|
|
1269
685
|
return this.startFailures.recent({ unansweredOnly }).slice(0, 10).map(refOf);
|
|
@@ -1305,16 +721,12 @@ let OperatorService = class OperatorService {
|
|
|
1305
721
|
return { fileName: `copilot-operator-terminal-${fileStamp(new Date().toISOString())}.txt`, content: redactSecrets(`${head}${formatTerminal(lines)}\n`, cfg.report.redactPatterns) };
|
|
1306
722
|
}
|
|
1307
723
|
/**
|
|
1308
|
-
*
|
|
1309
|
-
* is
|
|
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.
|
|
724
|
+
* Begins the run `start` asked for, and hands back a promise that settles when it is over and says how it went.
|
|
725
|
+
* One at a time: the browser profile is single-writer, so two conversations at once is not slower, it is a
|
|
726
|
+
* failure with a message about a closed browser.
|
|
1315
727
|
*/
|
|
1316
728
|
async beginRun(sessionId, mode,
|
|
1317
|
-
/** A browser that is already open
|
|
729
|
+
/** A browser that is already open: the one the chat left open (see `chatWindow`); otherwise the run opens one. */
|
|
1318
730
|
transport,
|
|
1319
731
|
/** The press of a start button this belongs to, stamped onto every task it reaches. */
|
|
1320
732
|
runGroup,
|
|
@@ -1371,7 +783,8 @@ let OperatorService = class OperatorService {
|
|
|
1371
783
|
*/
|
|
1372
784
|
const authorizer = this.webAuthorizer(policy, controller.signal);
|
|
1373
785
|
const startedAt = new Date().toISOString();
|
|
1374
|
-
|
|
786
|
+
const hold = new Hold();
|
|
787
|
+
this.running.set(sessionId, { controller, startedAt, mode, policy, hold });
|
|
1375
788
|
this.bus.publish({ sessionId, type: 'run-requested', level: 'info', message: `starting in ${mode} mode` });
|
|
1376
789
|
// Said at the start of every run, in both modes, because it is the one fact about this tool a
|
|
1377
790
|
// data-protection team needs and the one an operator forgets: the reports leave the machine.
|
|
@@ -1391,9 +804,6 @@ let OperatorService = class OperatorService {
|
|
|
1391
804
|
bus: this.bus,
|
|
1392
805
|
authorizer,
|
|
1393
806
|
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
807
|
// The mode as it is now, not as it was: "run the rest without asking" changes it mid-run,
|
|
1398
808
|
// and the policy.json of a later task must say so.
|
|
1399
809
|
currentMode: () => this.running.get(sessionId)?.mode ?? mode,
|
|
@@ -1413,7 +823,17 @@ let OperatorService = class OperatorService {
|
|
|
1413
823
|
}
|
|
1414
824
|
return refused;
|
|
1415
825
|
},
|
|
1416
|
-
|
|
826
|
+
// Opening a window of its own: the one the chat left open goes first, since the profile takes one.
|
|
827
|
+
...(transport
|
|
828
|
+
? {}
|
|
829
|
+
: {
|
|
830
|
+
beforeBrowser: async () => {
|
|
831
|
+
await this.closeChatWindow('another run needs the browser');
|
|
832
|
+
if (runGroup)
|
|
833
|
+
await this.browserRequested(runGroup.id, [sessionId]);
|
|
834
|
+
},
|
|
835
|
+
}),
|
|
836
|
+
...(how.chatWindow ? { chatWindow: { keep: (window) => this.keepChatWindow(window) } } : {}),
|
|
1417
837
|
// The page is the source of the model names: Settings and the saved list follow it (see `ModelHooks`).
|
|
1418
838
|
models: {
|
|
1419
839
|
locate: async (name) => (await this.store.getModels())?.options.find((o) => sameModel(o.name, name))?.locator,
|
|
@@ -1431,6 +851,7 @@ let OperatorService = class OperatorService {
|
|
|
1431
851
|
},
|
|
1432
852
|
// Plan mode `approve`: the plan is put to the operator on the approvals card.
|
|
1433
853
|
approvePlan: (ask) => this.askPlanApproval(ask, controller.signal),
|
|
854
|
+
hold,
|
|
1434
855
|
})
|
|
1435
856
|
.then(async (outcome) => {
|
|
1436
857
|
const tally = { ...(await this.tally(sessionId, queuedIds)), paused: outcome.paused, ...(outcome.refused ? { refused: outcome.refused } : {}) };
|
|
@@ -1450,7 +871,7 @@ let OperatorService = class OperatorService {
|
|
|
1450
871
|
// Not when the operator stopped it: that is an answer, not a failure to show.
|
|
1451
872
|
if (tally.ran === 0 && !controller.signal.aborted) {
|
|
1452
873
|
console.error('[start] the run ended before its first task:', e.stack ?? e.message);
|
|
1453
|
-
await this.notStarted({ stage:
|
|
874
|
+
await this.notStarted({ stage: failedWhileOpening(e) ? 'browser' : 'run', message: e.message, sessionIds: [sessionId], pressedAt: how.pressedAt ?? startedAt, ...(runGroup ? { runId: runGroup.id } : {}), answered: false });
|
|
1454
875
|
}
|
|
1455
876
|
return tally;
|
|
1456
877
|
})
|
|
@@ -1496,6 +917,26 @@ let OperatorService = class OperatorService {
|
|
|
1496
917
|
return tally;
|
|
1497
918
|
}
|
|
1498
919
|
/** Asks the run to stop after the current step. Pending approvals are aborted at once. */
|
|
920
|
+
/**
|
|
921
|
+
* "Pause" on the chat (operator, 2026-10-20): the running work holds at its next message to Copilot or its next
|
|
922
|
+
* command, and the button becomes "Continue". A reply being written and a command running are let finish.
|
|
923
|
+
*/
|
|
924
|
+
pause(sessionId) {
|
|
925
|
+
const r = this.running.get(sessionId);
|
|
926
|
+
if (!r)
|
|
927
|
+
throw new Error('Nothing of this conversation is running, so there is nothing to pause.');
|
|
928
|
+
if (r.hold.pause()) {
|
|
929
|
+
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' });
|
|
930
|
+
}
|
|
931
|
+
return { paused: true };
|
|
932
|
+
}
|
|
933
|
+
/** "Continue": the paused work goes on from where it held. A run that has ended meanwhile has nothing to go on with. */
|
|
934
|
+
resume(sessionId) {
|
|
935
|
+
const r = this.running.get(sessionId);
|
|
936
|
+
if (r?.hold.resume())
|
|
937
|
+
this.bus.publish({ sessionId, type: 'resume-asked', level: 'info', message: 'continued by the operator' });
|
|
938
|
+
return { paused: false };
|
|
939
|
+
}
|
|
1499
940
|
async stop(sessionId) {
|
|
1500
941
|
const r = this.running.get(sessionId);
|
|
1501
942
|
if (!r)
|
|
@@ -1529,12 +970,8 @@ let OperatorService = class OperatorService {
|
|
|
1529
970
|
* A run being started — its version control checked before the browser opens — is not running yet
|
|
1530
971
|
* and not idle either: `starting` says so, so "nothing is happening" is not read in that moment.
|
|
1531
972
|
*/
|
|
1532
|
-
const starting = this.running.size === 0 &&
|
|
1533
|
-
return { running: this.running.size > 0, sessions: this.running.size,
|
|
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;
|
|
973
|
+
const starting = this.running.size === 0 && this.browser?.kind === 'run';
|
|
974
|
+
return { running: this.running.size > 0, sessions: this.running.size, starting };
|
|
1538
975
|
}
|
|
1539
976
|
/**
|
|
1540
977
|
* Runs the queued tasks of several sessions, one session after another.
|
|
@@ -1551,731 +988,21 @@ let OperatorService = class OperatorService {
|
|
|
1551
988
|
async suggestRunName(sessionIds, about) {
|
|
1552
989
|
return suggestRunName(await this.store.listSessions(), sessionIds, about);
|
|
1553
990
|
}
|
|
1554
|
-
async startBatch(sessionIds, mode = 'confirm', onFailure = 'stop', model,
|
|
1555
991
|
/**
|
|
1556
|
-
*
|
|
1557
|
-
*
|
|
1558
|
-
*
|
|
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.
|
|
992
|
+
* Why a batch in this mode may not begin on this machine now, or null when it may: the entrance
|
|
993
|
+
* rule (`unattendedPrecondition`) asked of the settings as they are at this moment. One place, for
|
|
994
|
+
* the batch and for "Run again from here", which has to ask it before it moves anything.
|
|
1569
995
|
*/
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
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
|
-
/**
|
|
1661
|
-
* Why a batch in this mode may not begin on this machine now, or null when it may: the entrance
|
|
1662
|
-
* rule (`unattendedPrecondition`) asked of the settings as they are at this moment. One place, for
|
|
1663
|
-
* the batch and for "Run again from here", which has to ask it before it moves anything.
|
|
1664
|
-
*/
|
|
1665
|
-
async unattendedRefusal(mode) {
|
|
1666
|
-
const cfg = await this.settings.load();
|
|
1667
|
-
return unattendedPrecondition({
|
|
1668
|
-
mode,
|
|
1669
|
-
allowedPrograms: cfg.execution.allowedPrograms,
|
|
1670
|
-
isolation: cfg.execution.isolation,
|
|
1671
|
-
lockedToConfirm: cfg.policyLock?.maxMode === 'confirm',
|
|
1672
|
-
});
|
|
1673
|
-
}
|
|
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
|
-
}
|
|
996
|
+
async unattendedRefusal(mode) {
|
|
997
|
+
const cfg = await this.settings.load();
|
|
998
|
+
return unattendedPrecondition({
|
|
999
|
+
mode,
|
|
1000
|
+
allowedPrograms: cfg.execution.allowedPrograms,
|
|
1001
|
+
isolation: cfg.execution.isolation,
|
|
1002
|
+
lockedToConfirm: cfg.policyLock?.maxMode === 'confirm',
|
|
1003
|
+
});
|
|
2061
1004
|
}
|
|
2062
1005
|
// --- 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
1006
|
// --- the workspace and its chat (2026-10-17, "like Windsurf") ------------------------------
|
|
2280
1007
|
/** The project folder the workbench has open: Settings → the default project. */
|
|
2281
1008
|
async workspace() {
|
|
@@ -2295,6 +1022,15 @@ let OperatorService = class OperatorService {
|
|
|
2295
1022
|
throw new Error(ws.problem ?? 'No project folder is open.');
|
|
2296
1023
|
return await workspaceFile(ws.dir, path);
|
|
2297
1024
|
}
|
|
1025
|
+
/** The editor's text saved over a file of the open folder, over the version it was made on (see `saveWorkspaceFile`). */
|
|
1026
|
+
async saveWorkspaceFile(path, text, base) {
|
|
1027
|
+
const ws = await this.workspace();
|
|
1028
|
+
if (!ws.ok)
|
|
1029
|
+
throw new Error(ws.problem ?? 'No project folder is open.');
|
|
1030
|
+
const saved = await saveWorkspaceFile(ws.dir, path, text, base);
|
|
1031
|
+
console.log(`[editor] saved ${saved.path} (${saved.size} bytes)`);
|
|
1032
|
+
return saved;
|
|
1033
|
+
}
|
|
2298
1034
|
/** The open folder's git, as an IDE's Source Control view shows it (see `workspaceGit.ts`). Read-only. */
|
|
2299
1035
|
async workspaceGit() {
|
|
2300
1036
|
const ws = await this.workspace();
|
|
@@ -2314,6 +1050,20 @@ let OperatorService = class OperatorService {
|
|
|
2314
1050
|
throw new Error(ws.problem ?? 'No project folder is open.');
|
|
2315
1051
|
return await workspaceGitVersions(ws.dir, area, path, commit);
|
|
2316
1052
|
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Kerrigan (2026-10-20): the persona the operator may give to a chat of their own, in the language asked for, with
|
|
1055
|
+
* this machine's limits in it. Nothing is sent anywhere: the page saves it or copies it. See `plan/kerrigan.ts`.
|
|
1056
|
+
*/
|
|
1057
|
+
async kerrigan(lang) {
|
|
1058
|
+
const cfg = await this.settings.load();
|
|
1059
|
+
const text = kerriganPersona(lang, {
|
|
1060
|
+
version: botVersion(),
|
|
1061
|
+
maxIterations: cfg.limits.maxIterations,
|
|
1062
|
+
maxRunMinutes: cfg.limits.maxRunMinutes,
|
|
1063
|
+
autoContinue: cfg.limits.autoContinue ?? 0,
|
|
1064
|
+
});
|
|
1065
|
+
return { lang, fileName: kerriganFileName(lang), text };
|
|
1066
|
+
}
|
|
2317
1067
|
/** The chat's conversations, newest first. */
|
|
2318
1068
|
async chatThreads() {
|
|
2319
1069
|
await this.init();
|
|
@@ -2356,7 +1106,8 @@ let OperatorService = class OperatorService {
|
|
|
2356
1106
|
s.kind = 'chat';
|
|
2357
1107
|
s.onFailure = 'continue';
|
|
2358
1108
|
s.review = { enabled: false, model: '' };
|
|
2359
|
-
|
|
1109
|
+
// Plan mode as chosen under the box (2026-10-20, "as in Claude Code"): the plan first, approved by the operator.
|
|
1110
|
+
s.planMode = input.planMode ? 'approve' : 'off';
|
|
2360
1111
|
/*
|
|
2361
1112
|
* No version control of the bot's own (2026-10-17): no branch, no commit, no question about where the work
|
|
2362
1113
|
* starts. The chat works on the branch the folder is on, with what is in it, as an IDE's chat does; each
|
|
@@ -2379,6 +1130,12 @@ let OperatorService = class OperatorService {
|
|
|
2379
1130
|
level2: '',
|
|
2380
1131
|
prompt: text,
|
|
2381
1132
|
});
|
|
1133
|
+
// The language the workbench is in, for what the chat's window says when the work has ended (`chatWindowNotice`).
|
|
1134
|
+
if (input.lang && session.lang !== input.lang) {
|
|
1135
|
+
await this.store.updateSession(session.id, (s) => {
|
|
1136
|
+
s.lang = input.lang;
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
2382
1139
|
// After going back, the conversation is told with this message: it still holds what was undone.
|
|
2383
1140
|
const pending = (await this.store.getSession(session.id))?.rewindNote;
|
|
2384
1141
|
if (pending) {
|
|
@@ -2438,193 +1195,7 @@ let OperatorService = class OperatorService {
|
|
|
2438
1195
|
return { ok: true, message, text: task.prompt, ...(safety ? { safety } : {}) };
|
|
2439
1196
|
}
|
|
2440
1197
|
// --- 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
1198
|
// --- 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
1199
|
// --- approvals ------------------------------------------------------------------------
|
|
2629
1200
|
/**
|
|
2630
1201
|
* Asks the operator to choose the model in the Copilot window, when the runner could not (operator's
|
|
@@ -2762,26 +1333,14 @@ let OperatorService = class OperatorService {
|
|
|
2762
1333
|
* one would read.
|
|
2763
1334
|
*/
|
|
2764
1335
|
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
1336
|
this.bus.publish({
|
|
2778
1337
|
sessionId,
|
|
2779
1338
|
type: 'run-mode-changed',
|
|
2780
1339
|
level: mode === 'unattended' ? 'warn' : 'info',
|
|
2781
1340
|
message: mode === 'unattended'
|
|
2782
|
-
?
|
|
2783
|
-
:
|
|
2784
|
-
data: { mode
|
|
1341
|
+
? 'the rest of this run will execute without asking; denied patterns are still refused'
|
|
1342
|
+
: 'every further step will be shown for approval again',
|
|
1343
|
+
data: { mode },
|
|
2785
1344
|
});
|
|
2786
1345
|
if (mode === 'unattended') {
|
|
2787
1346
|
for (const [id, w] of this.waiting) {
|
|
@@ -2836,24 +1395,7 @@ let OperatorService = class OperatorService {
|
|
|
2836
1395
|
recentEvents(sessionId) {
|
|
2837
1396
|
return this.bus.recent(sessionId);
|
|
2838
1397
|
}
|
|
2839
|
-
subscribe(sessionId, handler) {
|
|
2840
|
-
return this.bus.subscribe(sessionId, handler);
|
|
2841
|
-
}
|
|
2842
1398
|
// --- 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
1399
|
/**
|
|
2858
1400
|
* The run's version control preflight: why the run may not start, said before anything opens the
|
|
2859
1401
|
* browser, creates a task attempt or emits `task-started`; null when it may.
|
|
@@ -2950,6 +1492,20 @@ let OperatorService = class OperatorService {
|
|
|
2950
1492
|
await appendRunLog(cfg.resolved.runsDir, runId, log).catch(() => undefined);
|
|
2951
1493
|
return reason;
|
|
2952
1494
|
}
|
|
1495
|
+
/**
|
|
1496
|
+
* Version control for the sessions of a run, one group per repository, with what can be done about
|
|
1497
|
+
* it from the run screen. See `vcs/runPreflight.ts`. Only sessions that have something queued count.
|
|
1498
|
+
*/
|
|
1499
|
+
async runVcs(sessionIds, onlyTasks) {
|
|
1500
|
+
await this.init();
|
|
1501
|
+
const sessions = [];
|
|
1502
|
+
for (const id of sessionIds) {
|
|
1503
|
+
const s = await this.store.getSession(id);
|
|
1504
|
+
if (s && queuedToRun(s, onlyTasks).length > 0)
|
|
1505
|
+
sessions.push(s);
|
|
1506
|
+
}
|
|
1507
|
+
return await runVcsPreflight(sessions, () => this.store.listSessions());
|
|
1508
|
+
}
|
|
2953
1509
|
/**
|
|
2954
1510
|
* Why the session's next task cannot start because it contradicts itself — read-only and scoped, or
|
|
2955
1511
|
* a file check that needs a change the task may not make — or null. The part of the contract that
|
|
@@ -3008,87 +1564,6 @@ let OperatorService = class OperatorService {
|
|
|
3008
1564
|
}
|
|
3009
1565
|
return conflicts;
|
|
3010
1566
|
}
|
|
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
1567
|
/**
|
|
3093
1568
|
* Where the next task's file checks can be judged before the run: see `ContractTree`. The folder holds
|
|
3094
1569
|
* the task's tree only when nothing is still to happen to it first — no update from a remote, no
|
|
@@ -3155,239 +1630,6 @@ let OperatorService = class OperatorService {
|
|
|
3155
1630
|
this.bus.publish({ sessionId: id, type: entry.type, level: 'info', message: entry.message, data: { runId, ...entry.data } });
|
|
3156
1631
|
await appendRunLog(cfg.resolved.runsDir, runId, [entry]).catch(() => undefined);
|
|
3157
1632
|
}
|
|
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
1633
|
/**
|
|
3392
1634
|
* A session running right now whose commands run in this folder, inside it, or in a folder around it.
|
|
3393
1635
|
*
|
|
@@ -3411,426 +1653,6 @@ let OperatorService = class OperatorService {
|
|
|
3411
1653
|
}
|
|
3412
1654
|
return undefined;
|
|
3413
1655
|
}
|
|
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
1656
|
/** Throws unless the folder is a project in Settings or the repository of a session. */
|
|
3835
1657
|
async knownProjectFolder(dir, otherwise) {
|
|
3836
1658
|
const wanted = normaliseDir(dir);
|
|
@@ -3859,9 +1681,9 @@ let OperatorService = class OperatorService {
|
|
|
3859
1681
|
async prepareProject(dir, fingerprint, names = {}) {
|
|
3860
1682
|
await this.init();
|
|
3861
1683
|
await this.knownProjectFolder(dir, 'it is not prepared from here');
|
|
3862
|
-
if (this.
|
|
1684
|
+
if (this.running.size > 0)
|
|
3863
1685
|
return { ok: false, problem: 'A run is going. Stop it before preparing the folder; nothing was changed.' };
|
|
3864
|
-
if (this.browser?.kind === 'run'
|
|
1686
|
+
if (this.browser?.kind === 'run')
|
|
3865
1687
|
return { ok: false, problem: 'A run is being started. Wait for it, or stop it, before preparing the folder; nothing was changed.' };
|
|
3866
1688
|
const other = await this.runningIn(dir);
|
|
3867
1689
|
if (other)
|
|
@@ -4044,6 +1866,7 @@ let OperatorService = class OperatorService {
|
|
|
4044
1866
|
humanWaitMs: cfg.copilot.signInTimeoutSec * 1000,
|
|
4045
1867
|
keepFailurePage: cfg.copilot.keepFailurePage,
|
|
4046
1868
|
});
|
|
1869
|
+
await this.closeChatWindow('signing in needs the browser');
|
|
4047
1870
|
await transport.open();
|
|
4048
1871
|
if (upn) {
|
|
4049
1872
|
await transport.signOut();
|
|
@@ -4100,6 +1923,7 @@ let OperatorService = class OperatorService {
|
|
|
4100
1923
|
humanWaitMs: cfg.copilot.humanWaitSec * 1000,
|
|
4101
1924
|
keepFailurePage: cfg.copilot.keepFailurePage,
|
|
4102
1925
|
});
|
|
1926
|
+
await this.closeChatWindow('reading the models needs the browser');
|
|
4103
1927
|
await transport.open();
|
|
4104
1928
|
await transport.ensureSignedIn();
|
|
4105
1929
|
const { options, current, note } = await transport.listModels();
|
|
@@ -4123,94 +1947,6 @@ let OperatorService = class OperatorService {
|
|
|
4123
1947
|
}
|
|
4124
1948
|
}
|
|
4125
1949
|
// --- 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
1950
|
// --- environment ----------------------------------------------------------------------
|
|
4215
1951
|
/** Opens the machine's own folder dialog and reports what was picked. */
|
|
4216
1952
|
async browseFolder(start) {
|
|
@@ -4233,7 +1969,7 @@ let OperatorService = class OperatorService {
|
|
|
4233
1969
|
* on that profile *by the runner*, and the warning "close this Edge window, a run would
|
|
4234
1970
|
* fail" was shown in exactly the moment it was false. The page says which it is.
|
|
4235
1971
|
*/
|
|
4236
|
-
botRunning: this.running.size > 0
|
|
1972
|
+
botRunning: this.running.size > 0,
|
|
4237
1973
|
desktop: resolveDesktopDir(),
|
|
4238
1974
|
desktopSynced: desktopIsSynced(),
|
|
4239
1975
|
cwd: cfg.resolved.cwd,
|