copilot-operator 0.1.96 → 0.1.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/src/api/apiLock.js +82 -0
  2. package/dist/src/api/main.js +5 -0
  3. package/dist/src/api/operator.controller.js +18 -4
  4. package/dist/src/api/operator.service.js +264 -51
  5. package/dist/src/api/server.js +10 -0
  6. package/dist/src/config/exportHome.js +1 -1
  7. package/dist/src/config/schema.js +13 -0
  8. package/dist/src/exec/policy.js +9 -18
  9. package/dist/src/plan/kerrigan.js +2 -2
  10. package/dist/src/plan/systemGuide.js +26 -26
  11. package/dist/src/queue/queue.js +7 -0
  12. package/dist/src/session/locatorFailures.js +10 -11
  13. package/dist/src/session/model.js +4 -0
  14. package/dist/src/session/store.js +47 -0
  15. package/dist/src/vcs/newBranch.js +6 -1
  16. package/dist/src/vcs/operatorGit.js +9 -10
  17. package/dist/web/404.html +2 -2
  18. package/dist/web/_next/static/chunks/1024-c0eee3ec374816d1.js +1 -0
  19. package/dist/web/_next/static/chunks/1077.4da389906036b1bb.js +1 -0
  20. package/dist/web/_next/static/chunks/1548.4aa3e42afe4542ab.js +1 -0
  21. package/dist/web/_next/static/chunks/2163.4c6ce20cf967756c.js +1 -0
  22. package/dist/web/_next/static/chunks/714.ffb1325246519f64.js +1 -0
  23. package/dist/web/_next/static/chunks/7220.f483b83c11525063.js +1 -0
  24. package/dist/web/_next/static/chunks/7921-946e538fe3f9630f.js +1 -0
  25. package/dist/web/_next/static/chunks/8124-967df691ec1bfeeb.js +1 -0
  26. package/dist/web/_next/static/chunks/8584.3301b056c97be517.js +1 -0
  27. package/dist/web/_next/static/chunks/9067.03cdfb01ebf6a35d.js +1 -0
  28. package/dist/web/_next/static/chunks/9747.fe06238bc42bd23d.js +1 -0
  29. package/dist/web/_next/static/chunks/app/{layout-2364903896c2c175.js → layout-7943a4391ad2f88f.js} +1 -1
  30. package/dist/web/_next/static/chunks/app/page-6ec948e0cf4b24f0.js +1 -0
  31. package/dist/web/_next/static/chunks/{webpack-3f144d13be3516c2.js → webpack-710628d673fa4afb.js} +1 -1
  32. package/dist/web/defaults.html +2 -2
  33. package/dist/web/defaults.txt +7 -7
  34. package/dist/web/index.html +3 -3
  35. package/dist/web/index.txt +8 -8
  36. package/dist/web/queue.html +2 -2
  37. package/dist/web/queue.txt +8 -8
  38. package/dist/web/settings.html +2 -2
  39. package/dist/web/settings.txt +8 -8
  40. package/dist/web/system.html +2 -2
  41. package/dist/web/system.txt +8 -8
  42. package/package.json +1 -1
  43. package/dist/web/_next/static/chunks/1024-214ded25b9048526.js +0 -1
  44. package/dist/web/_next/static/chunks/1077.161de82f740d47f0.js +0 -1
  45. package/dist/web/_next/static/chunks/1548.f2688468bf946e13.js +0 -1
  46. package/dist/web/_next/static/chunks/2163.b8ada3b7bde69f03.js +0 -1
  47. package/dist/web/_next/static/chunks/714.d1489788e598833b.js +0 -1
  48. package/dist/web/_next/static/chunks/7220.b85c8d105f394389.js +0 -1
  49. package/dist/web/_next/static/chunks/7921-00ebbcc6f65fbe35.js +0 -1
  50. package/dist/web/_next/static/chunks/8124-1dba8babfcfbc6e2.js +0 -1
  51. package/dist/web/_next/static/chunks/8584.a678bfced1cea938.js +0 -1
  52. package/dist/web/_next/static/chunks/9067.6da03ae052877b19.js +0 -1
  53. package/dist/web/_next/static/chunks/9747.ba29e64e97e8a15b.js +0 -1
  54. package/dist/web/_next/static/chunks/app/page-d031bf326e401246.js +0 -1
  55. /package/dist/web/_next/static/{kNfJ9jSwlboc-1sFBBfuI → D3ew46wEw5JXPsTVwZwFC}/_buildManifest.js +0 -0
  56. /package/dist/web/_next/static/{kNfJ9jSwlboc-1sFBBfuI → D3ew46wEw5JXPsTVwZwFC}/_ssgManifest.js +0 -0
@@ -22,15 +22,14 @@ import { chatbotFile } from '../session/chatbotFile.js';
22
22
  import { CHAT_LOCATOR_KEYS, locatorPrompt, resolveChatLocators } from '../transport/locators.js';
23
23
  import { LocatorMissing } from '../transport/copilotTransport.js';
24
24
  import { isStepKey, stepKey, stepPrompt } from '../transport/chatSteps.js';
25
- import { readFile } from 'node:fs/promises';
26
- import { join, resolve } from 'node:path';
25
+ import { basename, join, resolve } from 'node:path';
27
26
  import { chosenHome, defaultHome, installLayout } from '../config/layout.js';
28
27
  import { chooseHome, homeRefusal, movedFrom } from '../config/home.js';
29
- import { SessionStore, DEFAULT_VCS, DEFAULT_REVIEW, writeFileAtomically } from '../session/store.js';
30
- import { checkItems, emptyQueue, itemTitle, mergeItems, nextStep, parkAfterMs, parkedAnswerFrom, skippedBecause, statusOfTask, waitsByHand, MAX_PARK_AFTER_SEC, PARKED_WORDS } from '../queue/queue.js';
28
+ import { SessionStore, DEFAULT_VCS, DEFAULT_REVIEW, readStoreJson, StoreFileUnusable, writeFileAtomically } from '../session/store.js';
29
+ import { checkItems, emptyQueue, holdsChat, itemTitle, mergeItems, nextStep, parkAfterMs, parkedAnswerFrom, skippedBecause, statusOfTask, waitsByHand, MAX_PARK_AFTER_SEC, PARKED_WORDS } from '../queue/queue.js';
31
30
  import { branchStart, madeFromRemote, makeQueueBranch, refreshQueueBranch } from '../queue/queueBranch.js';
32
31
  import { EventBus } from '../session/events.js';
33
- import { isContinuable, MAX_INSTRUCTION_CHARS, newId, withProblemAt } from '../session/model.js';
32
+ import { isContinuable, parkedOver, MAX_INSTRUCTION_CHARS, newId, withProblemAt } from '../session/model.js';
34
33
  import { handoffOutcomeOf, handoffResultMessage } from '../orchestrator/handoff.js';
35
34
  import { runSession, queuedToRun, failedWhileOpening, pickerOptions } from '../orchestrator/taskRunner.js';
36
35
  import { Hold, WaitsFor } from '../orchestrator/hold.js';
@@ -78,6 +77,14 @@ const CARRIES_ON_AFTER = (what) => `${what}; it carries on from where it stopped
78
77
  /** A card answered after it went: by Kerrigan, another tab, or its work having ended (2026-11-18). */
79
78
  export const CARD_GONE = 'That card is not waiting any more: it was answered, or its work ended.';
80
79
  /** "Run this and the rest" where the run may not go on unasked: said, and the card kept (2026-11-18). */
80
+ /** How long a task of the queue waits for a sign-in Copilot asks for: as long as it takes, a week (2026-11-19). */
81
+ export const QUEUE_SIGN_IN_WAIT_SEC = 7 * 24 * 3600;
82
+ /** Said when "Sign in to Copilot" is pressed while a run's own window waits for the sign-in (2026-11-19). */
83
+ export const SIGN_IN_IN_THE_RUNS_WINDOW = 'The Copilot window the work opened is waiting for you to sign in: sign in there — it may be behind this one — and the work goes on by itself.';
84
+ /** Said when a set-aside task's card is pressed after the queue let go of it (2026-11-19). */
85
+ export const PARKED_RELEASED = 'Its card is closed now: "Continue" under its message carries it on in its own chat.';
86
+ /** Said when "Continue" is pressed on a message answered on its card in the queue (2026-11-19). */
87
+ export const PARKED_ANSWERED = "This message was answered on its card, and the queue carries it on with that answer: at the queue's next turn, or when the queue is run.";
81
88
  export const RUN_ALL_REFUSED = (why) => `"Run this and the rest" cannot be given here — ${why} Nothing was run: "Run" runs this step.`;
82
89
  /** Whether a folder is another, or inside it: Windows paths, as `sameFolder` reads them. */
83
90
  function folderInside(inner, outer) {
@@ -94,7 +101,7 @@ import { makeAuthorizer } from '../exec/authorizer.js';
94
101
  import { pickFolder } from './folderPicker.js';
95
102
  import { findEdgeUsingProfile, profileHolder } from '../transport/profileLock.js';
96
103
  import { assessIsolation, readIsolationSignals } from '../exec/isolation.js';
97
- import { unattendedPrecondition } from '../exec/policy.js';
104
+ import { unattendedBlock, unattendedPrecondition } from '../exec/policy.js';
98
105
  import { createTransport } from '../transport/chatTransport.js';
99
106
  import { composeHandoff } from '../session/handoff.js';
100
107
  import { appendRunLog, appendSessionLog, readRunLog } from '../session/runLog.js';
@@ -238,8 +245,19 @@ let OperatorService = class OperatorService {
238
245
  * opened again, a conversation lost, the program closed, are said.
239
246
  */
240
247
  stoppedByOperator = new Set();
248
+ /**
249
+ * Whether a conversation's latest message ended by the operator's own Stop, by its session: read by the queue, which
250
+ * only that stops (2026-11-19: a conversation lost, which ends a message stopped so that "Continue" is offered,
251
+ * stopped the whole queue left running).
252
+ */
253
+ endedByOperator = new Map();
241
254
  /** Where Git asks the operator for a password now, in its own window (2026-10-26): the step waits for it. */
242
255
  passwordAsked = new Map();
256
+ /**
257
+ * Where the Copilot window of a run waits for the operator to sign in (2026-11-19): said on the tab and in the chat,
258
+ * and "Sign in to Copilot" points to that window rather than refusing because of it.
259
+ */
260
+ signInAsked = new Map();
243
261
  followsActing = this.bus.subscribe('*', (e) => {
244
262
  if (e.type === 'acting' && e.data)
245
263
  this.acting.set(e.sessionId, e.data);
@@ -249,9 +267,13 @@ let OperatorService = class OperatorService {
249
267
  else if (e.type === 'browser:sign-in-required' || e.type === 'browser:verification-required') {
250
268
  // The Copilot window waits for the operator to sign in, or to show a person is there: not counted (2026-10-29).
251
269
  this.holdOf(e.sessionId)?.waitFor(`${e.type}:${e.sessionId}`);
270
+ if (e.type === 'browser:sign-in-required')
271
+ this.signInAsked.set(e.sessionId, e.at);
252
272
  }
253
273
  else if (e.type === 'browser:signed-in' || e.type === 'browser:verification-cleared') {
254
274
  this.holdOf(e.sessionId)?.waited(`${e.type === 'browser:signed-in' ? 'browser:sign-in-required' : 'browser:verification-required'}:${e.sessionId}`);
275
+ if (e.type === 'browser:signed-in')
276
+ this.signInAsked.delete(e.sessionId);
255
277
  }
256
278
  else if (e.type === 'password-window') {
257
279
  const open = e.data?.open === true;
@@ -275,12 +297,14 @@ let OperatorService = class OperatorService {
275
297
  else if (e.type === 'task-finished') {
276
298
  this.acting.delete(e.sessionId);
277
299
  this.passwordAsked.delete(e.sessionId);
300
+ this.signInAsked.delete(e.sessionId);
278
301
  for (const key of [`pw:${e.sessionId}`, `browser:sign-in-required:${e.sessionId}`, `browser:verification-required:${e.sessionId}`])
279
302
  this.holdOf(e.sessionId)?.waited(key);
280
303
  const status = e.data?.status;
281
304
  if (typeof status === 'string' && !this.workerLeads.has(e.sessionId)) {
282
305
  const byOperator = status === 'aborted' && this.stoppedByOperator.has(this.runKey(e.sessionId));
283
306
  this.lastOutcome = { status, at: e.at, sessionId: e.sessionId, ...(byOperator ? { byOperator: true } : {}) };
307
+ this.endedByOperator.set(e.sessionId, byOperator);
284
308
  }
285
309
  }
286
310
  });
@@ -421,8 +445,10 @@ let OperatorService = class OperatorService {
421
445
  await writeAttemptRecord(settled, ended, cfg.resolved.runsDir, exportMachine(cfg));
422
446
  }
423
447
  /** Runs the startup work now, so it does not wait for the first request. */
424
- bootstrap() {
425
- return this.init();
448
+ async bootstrap() {
449
+ await this.init();
450
+ // At once, not at the queue's first use (2026-11-19): a chat shows a set-aside task's card before the queue is read.
451
+ await this.recoverQueue().catch((e) => console.error('[queue] could not be recovered at the start:', e.message));
426
452
  }
427
453
  // --- level 1 --------------------------------------------------------------------------
428
454
  async getLevel1() {
@@ -1093,6 +1119,13 @@ let OperatorService = class OperatorService {
1093
1119
  */
1094
1120
  if (session.queueItem)
1095
1121
  runCfg.copilot = { ...runCfg.copilot, manualModel: false, leadManualModel: false, reviewManualModel: false, kerriganManualModel: false };
1122
+ /*
1123
+ * And a sign-in Copilot asks for is waited for as long as it takes (second bug hunt, 2026-11-19): a queue left
1124
+ * overnight whose account was signed out failed each task after fifteen minutes, skipping what depended on it, where
1125
+ * signed in in the morning it carries on by itself. The wait is not counted, and the run's Stop ends it.
1126
+ */
1127
+ if (session.queueItem)
1128
+ runCfg.copilot = { ...runCfg.copilot, signInTimeoutSec: Math.max(runCfg.copilot.signInTimeoutSec, QUEUE_SIGN_IN_WAIT_SEC) };
1096
1129
  const live = new LiveSettings(runCfg, session.kind === 'chat', loaded);
1097
1130
  const policy = { mode, ...stepRules(runCfg) };
1098
1131
  /*
@@ -1372,8 +1405,12 @@ let OperatorService = class OperatorService {
1372
1405
  ...(run?.hold?.held ? { paused: true } : {}),
1373
1406
  // Git asks for a password in its own window, and the work waits for it (2026-10-26).
1374
1407
  ...(this.passwordAsked.size > 0 ? { password: true } : {}),
1408
+ // Copilot's window waits for the operator to sign in (2026-11-19): the work goes on by itself once signed in.
1409
+ ...(this.signInAsked.size > 0 && this.running.size > 0 ? { signIn: true } : {}),
1375
1410
  // The queue still has its turn going, between one of its tasks and the next (2026-11-03): the work is not over.
1376
1411
  ...(this.queueLoop ? { queue: true } : {}),
1412
+ // Tasks of the queue set aside, waiting for the operator's answer on their cards (2026-11-19): the work is not over.
1413
+ ...(this.queueParked > 0 ? { parked: this.queueParked } : {}),
1377
1414
  // How the last message ended, while nothing runs: what the tab says until the operator has looked.
1378
1415
  ...(this.running.size === 0 && this.lastOutcome ? { last: { status: this.lastOutcome.status, at: this.lastOutcome.at, ...(this.lastOutcome.byOperator ? { byOperator: true } : {}) } } : {}),
1379
1416
  };
@@ -1523,14 +1560,28 @@ let OperatorService = class OperatorService {
1523
1560
  const busy = this.branchBusy();
1524
1561
  if (busy)
1525
1562
  throw new Error(busy);
1526
- return await createNewBranch(ws.dir, {
1563
+ const carry = input.carry === 'aside' || input.carry === 'commit' ? input.carry : 'take';
1564
+ /*
1565
+ * The work of a queue's task set aside on "the folder as it is" (2026-11-19): taken to the new branch, it carried on
1566
+ * without it, Copilot not told; put aside, nobody knew whose it was. Put aside, it is kept for that task and put back
1567
+ * when it carries on; taken along, refused, saying so; committed, it stays on the task's branch.
1568
+ */
1569
+ const onNow = ws.isRepo ? (await git(ws.dir, ['symbolic-ref', '--quiet', '--short', 'HEAD']).catch(() => null))?.stdout || null : null;
1570
+ const owners = await this.folderOwners(onNow);
1571
+ if (owners.length > 0 && carry === 'take' && (await git(ws.dir, ['status', '--porcelain']).catch(() => null))?.stdout.trim()) {
1572
+ throw new Error(`What is not committed here is the work of the queue's task "${itemTitle(owners[0].item)}", set aside while it waits for you: taken to the new branch, it would carry on without it. Put it aside instead — it is put back when that task carries on — or commit it, or answer the task's card first.`);
1573
+ }
1574
+ const made = await createNewBranch(ws.dir, {
1527
1575
  name: typeof input.name === 'string' ? input.name : '',
1528
- carry: input.carry === 'aside' || input.carry === 'commit' ? input.carry : 'take',
1576
+ carry,
1529
1577
  fingerprint: typeof input.fingerprint === 'string' ? input.fingerprint : '',
1530
1578
  ...(typeof input.message === 'string' && input.message.trim() ? { message: input.message.trim().slice(0, 2000) } : {}),
1531
1579
  // The saved branch under the bot's own prefix, as its other branches are.
1532
1580
  prefix: DEFAULT_VCS.branchPrefix,
1533
1581
  });
1582
+ if (made.ok && made.saved && owners.length > 0)
1583
+ await this.leftoversOf(onNow, '', made.saved.branch);
1584
+ return made;
1534
1585
  }
1535
1586
  /** The open folder's code, searched as VS Code's Search view does (2026-10-21, see `workspaceSearch.ts`). */
1536
1587
  async workspaceSearch(query, opts) {
@@ -1552,17 +1603,27 @@ let OperatorService = class OperatorService {
1552
1603
  throw new Error(ws.problem ?? 'No project folder is open.');
1553
1604
  return { dir: ws.dir, ...(await workspaceFiles(ws.dir)) };
1554
1605
  }
1555
- async workspaceFile(path) {
1606
+ async workspaceFile(path, dir) {
1556
1607
  const ws = await this.workspace();
1557
1608
  if (!ws.ok)
1558
1609
  throw new Error(ws.problem ?? 'No project folder is open.');
1610
+ this.sameOpenFolder(ws.dir, dir);
1559
1611
  return await workspaceFile(ws.dir, path);
1560
1612
  }
1613
+ /**
1614
+ * A file opened in one folder, read or saved after another was opened (second bug hunt, 2026-11-19): its path was
1615
+ * taken in the folder open now, and Ctrl+S wrote one folder's edit into the other's file of the same name. Refused.
1616
+ */
1617
+ sameOpenFolder(open, dir) {
1618
+ if (dir && !sameFolder(dir, open))
1619
+ throw new Error(`That file was opened in ${dir}, and the folder open now is ${open}: nothing was read or saved there. Open ${dir} again to save it.`);
1620
+ }
1561
1621
  /** The editor's text saved over a file of the open folder, over the version it was made on (see `saveWorkspaceFile`). */
1562
- async saveWorkspaceFile(path, text, base) {
1622
+ async saveWorkspaceFile(path, text, base, dir) {
1563
1623
  const ws = await this.workspace();
1564
1624
  if (!ws.ok)
1565
1625
  throw new Error(ws.problem ?? 'No project folder is open.');
1626
+ this.sameOpenFolder(ws.dir, dir);
1566
1627
  const saved = await saveWorkspaceFile(ws.dir, path, text, base);
1567
1628
  console.log(`[editor] saved ${saved.path} (${saved.size} bytes)`);
1568
1629
  return saved;
@@ -1819,22 +1880,30 @@ let OperatorService = class OperatorService {
1819
1880
  approvedAhead = new Map();
1820
1881
  /** Branches made for tasks of the queue, one edit of the list at a time. */
1821
1882
  branchTurn = Promise.resolve();
1822
- /** The queue as it is on disk; one that cannot be read is an empty one, said in the console. */
1883
+ /**
1884
+ * How many of the queue's tasks are set aside, waiting for the operator, as last read (2026-11-19): the work is not
1885
+ * over while one waits, and "Finished: aborted" — the queue's own stop to set it aside — was said instead.
1886
+ */
1887
+ queueParked = 0;
1888
+ /**
1889
+ * The queue as it is on disk: empty when it was never written. One that is there but cannot be read is refused, never
1890
+ * read as empty (2026-11-19: the next change wrote the empty queue over it, every task and card kept in it lost).
1891
+ */
1823
1892
  async readQueue() {
1824
- try {
1825
- const q = JSON.parse(await readFile(this.queueFile, 'utf8'));
1826
- return {
1827
- items: Array.isArray(q.items) ? q.items : [],
1828
- running: q.running === true,
1829
- updatedAt: q.updatedAt ?? '',
1830
- ...(typeof q.parkAfterSec === 'number' ? { parkAfterSec: q.parkAfterSec } : {}),
1831
- };
1832
- }
1833
- catch (e) {
1834
- if (e.code !== 'ENOENT')
1835
- console.error('[queue] data/queue.json could not be read:', e.message);
1893
+ const q = await readStoreJson(this.queueFile);
1894
+ if (q === undefined) {
1895
+ this.queueParked = 0;
1836
1896
  return emptyQueue();
1837
1897
  }
1898
+ if (!q || typeof q !== 'object' || Array.isArray(q))
1899
+ throw new StoreFileUnusable(this.queueFile, 'does not hold a queue');
1900
+ this.queueParked = Array.isArray(q.items) ? q.items.filter((x) => x?.status === 'parked').length : 0;
1901
+ return {
1902
+ items: Array.isArray(q.items) ? q.items : [],
1903
+ running: q.running === true,
1904
+ updatedAt: q.updatedAt ?? '',
1905
+ ...(typeof q.parkAfterSec === 'number' ? { parkAfterSec: q.parkAfterSec } : {}),
1906
+ };
1838
1907
  }
1839
1908
  /** Changes the queue in a turn of its own, so two changes never write over each other. */
1840
1909
  changeQueue(change) {
@@ -1844,6 +1913,7 @@ let OperatorService = class OperatorService {
1844
1913
  q.updatedAt = new Date().toISOString();
1845
1914
  delete q.busy;
1846
1915
  await writeFileAtomically(this.queueFile, JSON.stringify(q, null, 2));
1916
+ this.queueParked = q.items.filter((x) => x.status === 'parked').length;
1847
1917
  return q;
1848
1918
  };
1849
1919
  const done = this.queueTurn.then(run, run);
@@ -1857,22 +1927,38 @@ let OperatorService = class OperatorService {
1857
1927
  * were put, as said.
1858
1928
  */
1859
1929
  async leftoversOf(onBranch, except, saved) {
1860
- if (!onBranch)
1930
+ const owners = await this.folderOwners(onBranch, except);
1931
+ if (owners.length === 1) {
1932
+ const owner = owners[0].item.id;
1933
+ await this.changeQueue((x) => this.setQueueItem(x, owner, { setAside: [...(x.items.find((i) => i.id === owner)?.setAside ?? []), saved] }));
1861
1934
  return;
1935
+ }
1936
+ /*
1937
+ * Two or more such tasks (2026-11-19): whose each change is cannot be told, and nobody was told where the work went.
1938
+ * Each is told, in its chat, where it is kept; none has it put back, which would lay another's work on it.
1939
+ */
1940
+ for (const o of owners) {
1941
+ await this.store.addTaskNote(o.sessionId, o.taskId, `What was not committed in the folder on ${onBranch} — yours, or another set-aside task's of the queue that works there too — was put aside on the branch ${saved} while you waited. It is not put back by itself, since it cannot be told whose each change is: take back what is yours from there (git restore --source ${saved} -- <path>).`).catch(() => undefined);
1942
+ }
1943
+ }
1944
+ /**
1945
+ * The queue's tasks on "the folder as it is", set aside or carrying on at their next turn, whose work began on
1946
+ * `onBranch`: whose uncommitted changes the folder there holds.
1947
+ */
1948
+ async folderOwners(onBranch, except = '') {
1949
+ if (!onBranch)
1950
+ return [];
1862
1951
  const q = await this.readQueue();
1863
1952
  const owners = [];
1864
1953
  for (const x of q.items) {
1865
- if (x.id === except || x.branch !== 'folder' || !x.sessionId || !(x.status === 'parked' || (x.status === 'waiting' && x.resume)))
1954
+ if (x.id === except || x.branch !== 'folder' || !x.sessionId || !holdsChat(x))
1866
1955
  continue;
1867
1956
  const s = await this.store.getSession(x.sessionId);
1868
1957
  const t = s?.tasks.find((k) => k.parked && !k.parked.answer) ?? s?.tasks.at(-1);
1869
- if (s && !s.vcs?.enabled && t?.checkpoint?.branch === onBranch)
1870
- owners.push(x.id);
1958
+ if (s && t && !s.vcs?.enabled && t.checkpoint?.branch === onBranch)
1959
+ owners.push({ item: x, sessionId: s.id, taskId: t.id });
1871
1960
  }
1872
- if (owners.length !== 1)
1873
- return;
1874
- const owner = owners[0];
1875
- await this.changeQueue((x) => this.setQueueItem(x, owner, { setAside: [...(x.items.find((i) => i.id === owner)?.setAside ?? []), saved] }));
1961
+ return owners;
1876
1962
  }
1877
1963
  setQueueItem(q, id, patch) {
1878
1964
  const item = q.items.find((x) => x.id === id);
@@ -1892,6 +1978,17 @@ let OperatorService = class OperatorService {
1892
1978
  return;
1893
1979
  this.queueRecovered = true;
1894
1980
  const q = await this.readQueue();
1981
+ /*
1982
+ * The cards of set-aside tasks the queue does not hold any more (2026-11-19) — taken out, run again, the queue's file
1983
+ * lost, before this was looked after — closed, so their messages are carried on in their chats.
1984
+ */
1985
+ for (const s of await this.store.listSessions().catch(() => [])) {
1986
+ if (!s.queueItem || !s.tasks.some((t) => t.parked && !parkedOver(t.parked)))
1987
+ continue;
1988
+ const item = q.items.find((x) => x.id === s.queueItem);
1989
+ if (!item || item.sessionId !== s.id || !holdsChat(item))
1990
+ await this.releaseFromQueue(s.id, s.queueItem, undefined);
1991
+ }
1895
1992
  if (!q.running && !q.items.some((x) => x.status === 'running'))
1896
1993
  return;
1897
1994
  await this.changeQueue((x) => {
@@ -1909,6 +2006,31 @@ let OperatorService = class OperatorService {
1909
2006
  }
1910
2007
  });
1911
2008
  }
2009
+ /**
2010
+ * A chat the queue lets go of (2026-11-19): its set-aside task's card closed — "Continue" carries the message on there —
2011
+ * and, when the task had work put aside by a task after it, where that work is said in the chat, since nothing will
2012
+ * put it back now.
2013
+ */
2014
+ async releaseFromQueue(sessionId, itemId, setAside) {
2015
+ const s = await this.store.getSession(sessionId);
2016
+ if (!s || s.queueItem !== itemId)
2017
+ return;
2018
+ const open = s.tasks.find((t) => t.parked && !parkedOver(t.parked));
2019
+ if (open) {
2020
+ await this.store.updateSession(sessionId, (x) => {
2021
+ const t = x.tasks.find((y) => y.id === open.id);
2022
+ if (t?.parked && !parkedOver(t.parked))
2023
+ t.parked.answer = { kind: 'released', at: new Date().toISOString() };
2024
+ }).catch(() => undefined);
2025
+ this.bus.publish({ sessionId, taskId: open.id, type: 'queue-released', level: 'info', message: 'the queue does not hold this task any more: its card is closed, and "Continue" carries it on here' });
2026
+ }
2027
+ const last = open ?? s.tasks.at(-1);
2028
+ for (const saved of setAside ?? []) {
2029
+ if (last)
2030
+ await this.store.addTaskNote(sessionId, last.id, `What you had changed and not committed was put aside on the branch ${saved} while you waited, and the queue no longer puts it back. Take back what you need from there (git restore --source ${saved} -- <path>).`).catch(() => undefined);
2031
+ this.bus.publish({ sessionId, type: 'queue-put-back', level: 'warn', message: `what it had not committed is kept on ${saved}; the queue no longer puts it back`, data: { saved } });
2032
+ }
2033
+ }
1912
2034
  async queue() {
1913
2035
  await this.recoverQueue();
1914
2036
  return await this.withBusy(await this.readQueue());
@@ -1954,15 +2076,21 @@ let OperatorService = class OperatorService {
1954
2076
  throw new Error(`Task ${unknown + 1} is sent with the skill "${name}", which is not in Settings → Skills${skills.length > 0 ? `; there are ${skills.map((k) => k.name).join(', ')}` : ''}.`);
1955
2077
  }
1956
2078
  let problem;
2079
+ let letGo = [];
1957
2080
  const q = await this.changeQueue((x) => {
1958
2081
  const merged = mergeItems(x.items, checked.items);
1959
2082
  if ('problem' in merged)
1960
2083
  problem = merged.problem;
1961
- else
2084
+ else {
2085
+ letGo = x.items.filter((was) => holdsChat(was) && !merged.items.some((now) => now.id === was.id && now.sessionId === was.sessionId && holdsChat(now)));
1962
2086
  x.items = merged.items;
2087
+ }
1963
2088
  });
1964
2089
  if (problem)
1965
2090
  throw new Error(problem);
2091
+ // Taken out, run again or started over (2026-11-19): its chat's card closed, so its message is carried on there.
2092
+ for (const was of letGo)
2093
+ await this.releaseFromQueue(was.sessionId, was.id, was.setAside);
1966
2094
  return await this.withBusy(await this.makeQueueBranches(q));
1967
2095
  }
1968
2096
  /**
@@ -2136,16 +2264,24 @@ let OperatorService = class OperatorService {
2136
2264
  await this.recoverQueue();
2137
2265
  const q = await this.readQueue();
2138
2266
  const item = q.items.find((x) => x.id === itemId);
2139
- if (!item)
2140
- throw new Error('That task is not in the queue any more.');
2141
- if (item.status !== 'parked' || !item.sessionId)
2142
- throw new Error('That task is not waiting for an answer.');
2143
2267
  /*
2144
- * The card of another run of it (bug hunt 2026-11-18): a card left in the chat of an earlier run — stopped, run
2145
- * again, or a task removed whose id a new one took — answered the card the queue's task waits on now, unseen.
2268
+ * A card the queue does not hold any more (2026-11-19): its task taken out, run again or started over, or set aside
2269
+ * again in another chat. Every button failed, Stop included, and "Continue" was refused: the card is closed now, at
2270
+ * any press, and "Continue" carries its message on in its own chat. A Stop of it is simply taken.
2146
2271
  */
2147
- if (typeof input?.sessionId === 'string' && input.sessionId !== item.sessionId) {
2148
- throw new Error('That card is of another run of this task: what the task waits for now is on the queue\'s page.');
2272
+ const from = typeof input?.sessionId === 'string' ? input.sessionId : undefined;
2273
+ if (!item || item.status !== 'parked' || !item.sessionId || (from && from !== item.sessionId)) {
2274
+ const of = from ?? (item?.status === 'parked' ? undefined : item?.sessionId);
2275
+ if (of)
2276
+ await this.releaseFromQueue(of, itemId);
2277
+ if (input?.stop === true && of)
2278
+ return await this.queue();
2279
+ if (!item)
2280
+ throw new Error(`That task is not in the queue any more. ${PARKED_RELEASED}`);
2281
+ // The card of another run of it (bug hunt 2026-11-18): it answered the card the queue's task waits on now, unseen.
2282
+ if (from && item.sessionId && from !== item.sessionId)
2283
+ throw new Error(`That card is of another run of this task: what the task waits for now is on the queue's page. ${PARKED_RELEASED}`);
2284
+ throw new Error(`That task is not waiting for an answer. ${PARKED_RELEASED}`);
2149
2285
  }
2150
2286
  const s = await this.store.getSession(item.sessionId);
2151
2287
  const task = s?.tasks.find((t) => t.parked && !t.parked.answer);
@@ -2160,7 +2296,10 @@ let OperatorService = class OperatorService {
2160
2296
  t.parked.answer = { kind: 'stopped', at: new Date().toISOString() };
2161
2297
  }).catch(() => undefined);
2162
2298
  }
2163
- return await this.withBusy(await this.changeQueue((x) => this.setQueueItem(x, itemId, { status: 'stopped', why: 'stopped by the operator at its card', waitsFor: undefined })));
2299
+ // Its work put aside by a task after it is not put back now (2026-11-19): where it is, said in its chat.
2300
+ if (item.setAside?.length)
2301
+ await this.releaseFromQueue(item.sessionId, itemId, item.setAside);
2302
+ return await this.withBusy(await this.changeQueue((x) => this.setQueueItem(x, itemId, { status: 'stopped', why: 'stopped by the operator at its card', waitsFor: undefined, setAside: undefined })));
2164
2303
  }
2165
2304
  if (!s || !task?.parked)
2166
2305
  throw new Error('What that task waited for is not on its record any more; run it again.');
@@ -2237,7 +2376,7 @@ let OperatorService = class OperatorService {
2237
2376
  let carryOn = false;
2238
2377
  if (item.resume && item.sessionId) {
2239
2378
  const s0 = await this.store.getSession(item.sessionId);
2240
- const answered = s0?.tasks.find((t) => t.parked?.answer && t.parked.answer.kind !== 'stopped');
2379
+ const answered = s0?.tasks.find((t) => t.parked?.answer && !parkedOver(t.parked));
2241
2380
  const last = s0?.tasks.at(-1);
2242
2381
  if (!s0 || !last)
2243
2382
  return { status: 'failed', why: 'its chat is not there any more; run it again' };
@@ -2253,14 +2392,15 @@ let OperatorService = class OperatorService {
2253
2392
  const aside = await setAsideUncommitted(ws.dir, `the queue's task "${itemTitle(item)}" carries on on ${began}, where it began, and the folder held changes left on ${onNow ?? 'a detached HEAD'}`);
2254
2393
  if (aside && 'problem' in aside)
2255
2394
  return { status: 'failed', why: `what was not committed in the folder could not be put aside before it: ${aside.problem}`, sessionId: s0.id };
2395
+ // Kept for whose it is first (2026-11-19): a switch that failed after it said nothing of where it went.
2396
+ if (aside && 'saved' in aside)
2397
+ await this.leftoversOf(onNow, item.id, aside.saved);
2256
2398
  const back = await git(ws.dir, ['switch', began]);
2257
2399
  if (!back.ok)
2258
- return { status: 'failed', why: `it could not be put back on ${began}, where it began: ${(back.stderr || back.stdout).trim().slice(0, 300)}`, sessionId: s0.id };
2400
+ return { status: 'failed', why: `it could not be put back on ${began}, where it began: ${(back.stderr || back.stdout).trim().slice(0, 300)}${aside ? `; what was not committed in the folder is kept on ${aside.saved}, not pushed` : ''}`, sessionId: s0.id };
2259
2401
  this.bus.publish({ sessionId: s0.id, type: 'queue-back-on-branch', level: 'info',
2260
2402
  message: `back on ${began}, where it began, before it carries on (the folder was on ${onNow ?? 'a detached HEAD'})${aside ? `; what was not committed there is kept on ${aside.saved}, not pushed` : ''}`,
2261
2403
  data: { branch: began, was: onNow, ...(aside ? { saved: aside.saved } : {}) } });
2262
- if (aside && 'saved' in aside)
2263
- await this.leftoversOf(onNow, item.id, aside.saved);
2264
2404
  }
2265
2405
  }
2266
2406
  // Its own work, put aside by a task after it on a branch of its own (2026-11-18): put back before it carries on.
@@ -2419,7 +2559,14 @@ let OperatorService = class OperatorService {
2419
2559
  if ((asked || !(await stillRunning())) && task && (task.status === 'queued' || isContinuable(task))) {
2420
2560
  return { status: 'waiting', resume: true, why: CARRIES_ON_AFTER('the queue was stopped while it ran'), sessionId };
2421
2561
  }
2422
- const status = statusOfTask(task?.status);
2562
+ const byOperator = this.endedByOperator.get(sessionId) === true;
2563
+ this.endedByOperator.delete(sessionId);
2564
+ /*
2565
+ * Stopped by nobody — its conversation lost, its window closed past the times it is opened again (2026-11-19): it
2566
+ * ended stopped so that its chat offers "Continue", but only the operator's Stop stops the queue. It failed: what
2567
+ * depends on it is skipped, the others run, and its chat carries it on when the operator chooses.
2568
+ */
2569
+ const status = task?.status === 'aborted' && !byOperator ? 'failed' : statusOfTask(task?.status);
2423
2570
  return { status, ...(status !== 'done' ? { why: task?.reason ?? `it ended ${task?.status ?? 'without a record'}` } : {}), sessionId };
2424
2571
  }
2425
2572
  /**
@@ -2431,10 +2578,10 @@ let OperatorService = class OperatorService {
2431
2578
  async resumeParked(sessionId, dir) {
2432
2579
  const s = await this.store.getSession(sessionId);
2433
2580
  // Not one stopped at its card (2026-11-18): that is an answer that does not carry it on.
2434
- const task = s?.tasks.find((t) => t.parked?.answer && t.parked.answer.kind !== 'stopped');
2581
+ const task = s?.tasks.find((t) => t.parked?.answer && !parkedOver(t.parked));
2435
2582
  const p = task?.parked;
2436
2583
  const a = p?.answer;
2437
- if (!s || !task || !p || !a || a.kind === 'stopped')
2584
+ if (!s || !task || !p || !a || a.kind === 'stopped' || a.kind === 'released')
2438
2585
  return { problem: 'its answer is not on its record any more; run it again' };
2439
2586
  const continuing = { fromAttempt: task.attempt ?? 1, stoppedBecause: task.reason, how: 'parked', parkedFor: p.kind };
2440
2587
  let note = '';
@@ -2838,6 +2985,12 @@ let OperatorService = class OperatorService {
2838
2985
  // A queue task set aside is answered on its card (2026-11-18): carried on here, its queue entry lost what it waited for.
2839
2986
  if (task.parked && !task.parked.answer)
2840
2987
  throw new Error('This message waits for an answer on its card in the queue: answer it there, and the queue carries it on.');
2988
+ /*
2989
+ * Answered on its card, the queue carries it on with the answer (2026-11-19): carried on here instead, the answer was
2990
+ * filed under the attempt before and lost — a plan approved was asked for again, a question's answer never sent.
2991
+ */
2992
+ if (!parkedOver(task.parked))
2993
+ throw new Error(PARKED_ANSWERED);
2841
2994
  const busy = this.browserBusyFor(threadId);
2842
2995
  if (busy)
2843
2996
  throw new Error(busy);
@@ -2960,7 +3113,26 @@ let OperatorService = class OperatorService {
2960
3113
  /** What waits for the operator; of one session, its worker's included (two chats: they are asked in its conversation). */
2961
3114
  pendingApprovals(sessionId) {
2962
3115
  // Kerrigan's (2026-11-12): the cards of the chats she directs, and of their workers, are shown in hers too.
2963
- return [...this.waiting.values()].map((w) => w.approval).filter((a) => !sessionId || this.under(a.sessionId, sessionId));
3116
+ return [...this.waiting.values()]
3117
+ .map((w) => w.approval)
3118
+ .filter((a) => !sessionId || this.under(a.sessionId, sessionId))
3119
+ .map((a) => {
3120
+ const off = this.runAllOff(a);
3121
+ return off ? { ...a, runAllOff: off } : a;
3122
+ });
3123
+ }
3124
+ /**
3125
+ * What keeps "Run this and the rest" from this command's card, read as the card is shown (2026-11-19): under the
3126
+ * default Settings — no isolation — it was offered on every card and refused at every press. Only a command's card
3127
+ * has it, and not one that downloads or reaches a platform, which is asked about in every run anyway.
3128
+ */
3129
+ runAllOff(a) {
3130
+ if (a.plan || a.question || a.retry || a.model || a.network || a.platform)
3131
+ return undefined;
3132
+ const run = this.running.get(this.runKey(a.sessionId));
3133
+ if (!run || run.mode === 'unattended')
3134
+ return undefined;
3135
+ return unattendedBlock(run.policy) ?? undefined;
2964
3136
  }
2965
3137
  /**
2966
3138
  * Answers one pending approval.
@@ -3394,6 +3566,44 @@ let OperatorService = class OperatorService {
3394
3566
  * The repository check travels with it because the two questions are always asked together:
3395
3567
  * somewhere to work, and whether that somewhere can be branched and committed.
3396
3568
  */
3569
+ /**
3570
+ * "Open a folder" in the workbench (second bug hunt, 2026-11-19): the folder becomes the project. It kept the name,
3571
+ * the level 2 and "for reference only" of the one before — a folder opened to work in was then for reference only,
3572
+ * every change put back, and Kerrigan given another project's notes. One of the other projects comes with its own,
3573
+ * and the one before takes its place among them; any other folder comes with what it had when it was the project
3574
+ * before, or with nothing, and the one before is remembered with its own.
3575
+ */
3576
+ async openProjectFolder(dir) {
3577
+ const target = dir.trim();
3578
+ if (!target || !existsSync(target))
3579
+ throw new Error(`The folder ${target || '(none)'} does not exist on this machine.`);
3580
+ await this.settings.update((raw) => {
3581
+ const current = (raw.project ?? {});
3582
+ const was = { rootDir: (current.rootDir ?? '').trim(), name: (current.name ?? '').trim(), level2: current.level2 ?? '', readOnly: current.readOnly === true };
3583
+ if (was.rootDir && sameFolder(was.rootDir, target))
3584
+ return raw;
3585
+ const others = (current.others ?? []);
3586
+ let earlier = (current.earlier ?? []).filter((e) => e.rootDir && !sameFolder(e.rootDir, target) && !(was.rootDir && sameFolder(e.rootDir, was.rootDir)));
3587
+ const i = others.findIndex((o) => o.rootDir && sameFolder(o.rootDir, target));
3588
+ let next;
3589
+ let nextOthers = others;
3590
+ if (i >= 0) {
3591
+ const o = others[i];
3592
+ next = { rootDir: o.rootDir, name: o.name ?? '', level2: o.level2 ?? '', readOnly: o.readOnly === true };
3593
+ nextOthers = was.rootDir
3594
+ ? others.map((x, j) => (j === i ? { name: was.name || basename(was.rootDir) || was.rootDir, rootDir: was.rootDir, level2: was.level2, readOnly: was.readOnly } : x))
3595
+ : others.filter((_, j) => j !== i);
3596
+ }
3597
+ else {
3598
+ const before = (current.earlier ?? []).find((e) => e.rootDir && sameFolder(e.rootDir, target));
3599
+ next = { rootDir: target, name: before?.name ?? '', level2: before?.level2 ?? '', readOnly: before?.readOnly === true };
3600
+ if (was.rootDir && (was.name || was.level2.trim() || was.readOnly))
3601
+ earlier = [was, ...earlier].slice(0, 20);
3602
+ }
3603
+ return { ...raw, project: { ...current, ...next, others: nextOthers, earlier } };
3604
+ });
3605
+ return await this.project();
3606
+ }
3397
3607
  async project() {
3398
3608
  const cfg = await this.settings.load();
3399
3609
  const rootDir = (cfg.project?.rootDir ?? '').trim();
@@ -3615,6 +3825,9 @@ let OperatorService = class OperatorService {
3615
3825
  if (upn && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(upn)) {
3616
3826
  throw new Error(`"${upn}" is not an account address. Give the work or school address, for example name@company.com, or leave it empty.`);
3617
3827
  }
3828
+ // The run's own window waits for exactly that (2026-11-19): it was refused "once the run has finished", which never came.
3829
+ if (this.signInAsked.size > 0 && this.running.size > 0)
3830
+ throw new Error(SIGN_IN_IN_THE_RUNS_WINDOW);
3618
3831
  const claim = this.claimBrowser({ kind: 'login' });
3619
3832
  if ('refused' in claim)
3620
3833
  throw new Error(claim.refused);
@@ -24,6 +24,7 @@ import { existsSync } from 'node:fs';
24
24
  import { installLayout } from '../config/layout.js';
25
25
  import { moveLegacyHome } from '../config/home.js';
26
26
  import { captureTerminal } from '../log/terminal.js';
27
+ import { acquireApiLock } from './apiLock.js';
27
28
  /**
28
29
  * A settings file, or a policy lock, that cannot be used, answered the same way on every route: 409,
29
30
  * with the message that names the file and says what to do (see `SettingsUnusableError` and
@@ -149,6 +150,15 @@ export async function startApi(opts = {}) {
149
150
  await app.close();
150
151
  throw e;
151
152
  });
153
+ /*
154
+ * The records are this process's, or another copilot-operator runs on them and this one does not start (second bug
155
+ * hunt, 2026-11-19): started anyway, it put the other's work to rest below — its task marked stopped, its queue
156
+ * stopped — and the two wrote the same files. Before the port and before anything is recovered.
157
+ */
158
+ await acquireApiLock(dataDir, PORT).catch(async (e) => {
159
+ await app.close().catch(() => undefined);
160
+ throw e;
161
+ });
152
162
  // A port that cannot be taken (in use, or reserved by Windows: EACCES) closes what was opened, so a caller can try another.
153
163
  await app.listen(PORT, '127.0.0.1').catch(async (e) => {
154
164
  await app.close().catch(() => undefined);
@@ -8,7 +8,7 @@
8
8
  import { readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import { join, relative } from 'node:path';
10
10
  /** Files of the data folder never exported, by name: this machine's key and the API's own bookkeeping. */
11
- const NEVER = new Set(['api-token', 'dev-pids.json', '.cop-lock.json']);
11
+ const NEVER = new Set(['api-token', 'dev-pids.json', '.cop-lock.json', 'api.lock.json']);
12
12
  function filesUnder(dir) {
13
13
  const out = [];
14
14
  const walk = (d) => {
@@ -456,6 +456,19 @@ export const RunConfigSchema = z.object({
456
456
  readOnly: z.boolean().default(false),
457
457
  }))
458
458
  .default([]),
459
+ /**
460
+ * Folders that were the project before "Open a folder" put another in their place (2026-11-19), with their name,
461
+ * level 2 and "for reference only", given back when one is opened again. Only remembered: the chat works in none
462
+ * of them.
463
+ */
464
+ earlier: z
465
+ .array(z.object({
466
+ rootDir: z.string().trim().min(1),
467
+ name: z.string().trim().default(''),
468
+ level2: z.string().default(''),
469
+ readOnly: z.boolean().default(false),
470
+ }))
471
+ .default([]),
459
472
  })
460
473
  .prefault({}),
461
474
  /**