copilot-operator 0.1.97 → 0.1.99

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 (82) hide show
  1. package/dist/src/api/folderPicker.js +22 -22
  2. package/dist/src/api/operator.controller.js +21 -9
  3. package/dist/src/api/operator.service.js +233 -39
  4. package/dist/src/config/exportHome.js +51 -9
  5. package/dist/src/config/home.js +27 -11
  6. package/dist/src/exec/authorizer.js +11 -4
  7. package/dist/src/exec/commandHeads.js +25 -0
  8. package/dist/src/exec/confinement.js +50 -4
  9. package/dist/src/exec/network.js +11 -1
  10. package/dist/src/exec/npmScripts.js +33 -0
  11. package/dist/src/exec/policy.js +70 -6
  12. package/dist/src/exec/processes.js +24 -5
  13. package/dist/src/exec/programs.js +21 -0
  14. package/dist/src/exec/reportFile.js +2 -1
  15. package/dist/src/exec/runner.js +31 -9
  16. package/dist/src/exec/scriptFiles.js +133 -6
  17. package/dist/src/orchestrator/handoff.js +3 -3
  18. package/dist/src/orchestrator/kerriganRunner.js +14 -6
  19. package/dist/src/orchestrator/leadRunner.js +43 -23
  20. package/dist/src/orchestrator/review.js +66 -10
  21. package/dist/src/orchestrator/taskRunner.js +73 -14
  22. package/dist/src/plan/kerrigan.js +253 -253
  23. package/dist/src/plan/schema.js +3 -13
  24. package/dist/src/plan/systemGuide.js +2 -2
  25. package/dist/src/protocol/kerriganSchema.js +5 -1
  26. package/dist/src/protocol/replySchema.js +2 -2
  27. package/dist/src/queue/queue.js +86 -0
  28. package/dist/src/session/compose.js +14 -10
  29. package/dist/src/session/locatorFailures.js +27 -6
  30. package/dist/src/session/model.js +19 -0
  31. package/dist/src/session/workspace.js +20 -5
  32. package/dist/src/transport/copilotTransport.js +82 -62
  33. package/dist/src/util/zip.js +147 -44
  34. package/dist/src/vcs/newBranch.js +20 -3
  35. package/dist/src/vcs/referenceGuard.js +9 -4
  36. package/dist/web/404.html +2 -2
  37. package/dist/web/_next/static/chunks/1077.a4fe6ae48f3d3ff9.js +1 -0
  38. package/dist/web/_next/static/chunks/1548.765d6eed5325bd01.js +1 -0
  39. package/dist/web/_next/static/chunks/2163.e8d6c85412d5d411.js +1 -0
  40. package/dist/web/_next/static/chunks/{8124-967df691ec1bfeeb.js → 6240-8ba644c53ffab87d.js} +1 -1
  41. package/dist/web/_next/static/chunks/714.f2dcd6b41b58d1a7.js +1 -0
  42. package/dist/web/_next/static/chunks/7220.652a8a339c1e7401.js +1 -0
  43. package/dist/web/_next/static/chunks/7921-9cf1ece94fc89bb3.js +1 -0
  44. package/dist/web/_next/static/chunks/{8584.3301b056c97be517.js → 8584.7c438425140f1d8d.js} +1 -1
  45. package/dist/web/_next/static/chunks/9067.8c4e6a64620a45d9.js +1 -0
  46. package/dist/web/_next/static/chunks/9747.43d25bdff8737d09.js +1 -0
  47. package/dist/web/_next/static/chunks/app/{layout-7943a4391ad2f88f.js → layout-97259931ed97e20d.js} +1 -1
  48. package/dist/web/_next/static/chunks/app/page-26e4ea30eb076e6b.js +1 -0
  49. package/dist/web/_next/static/chunks/app/queue/page-7228e045f8ea10c4.js +1 -0
  50. package/dist/web/_next/static/chunks/app/settings/page-c915d61553e1025b.js +1 -0
  51. package/dist/web/_next/static/chunks/app/system/page-4d24f44eb9077fb7.js +1 -0
  52. package/dist/web/_next/static/chunks/{webpack-710628d673fa4afb.js → webpack-31db88c3d5781520.js} +1 -1
  53. package/dist/web/_next/static/css/{523d11041085f836.css → 87999096d96266fd.css} +1 -1
  54. package/dist/web/defaults.html +2 -2
  55. package/dist/web/defaults.txt +26 -25
  56. package/dist/web/index.html +3 -3
  57. package/dist/web/index.txt +26 -25
  58. package/dist/web/queue.html +2 -2
  59. package/dist/web/queue.txt +26 -25
  60. package/dist/web/settings.html +2 -2
  61. package/dist/web/settings.txt +26 -25
  62. package/dist/web/system.html +2 -2
  63. package/dist/web/system.txt +26 -25
  64. package/package.json +3 -2
  65. package/prompts/kerrigan1.md +2 -1
  66. package/prompts/lead1.md +2 -1
  67. package/prompts/level1.md +6 -1
  68. package/prompts/review1.md +7 -4
  69. package/dist/web/_next/static/chunks/1077.4da389906036b1bb.js +0 -1
  70. package/dist/web/_next/static/chunks/1548.4aa3e42afe4542ab.js +0 -1
  71. package/dist/web/_next/static/chunks/2163.4c6ce20cf967756c.js +0 -1
  72. package/dist/web/_next/static/chunks/714.ffb1325246519f64.js +0 -1
  73. package/dist/web/_next/static/chunks/7220.f483b83c11525063.js +0 -1
  74. package/dist/web/_next/static/chunks/7921-946e538fe3f9630f.js +0 -1
  75. package/dist/web/_next/static/chunks/9067.03cdfb01ebf6a35d.js +0 -1
  76. package/dist/web/_next/static/chunks/9747.fe06238bc42bd23d.js +0 -1
  77. package/dist/web/_next/static/chunks/app/page-6ec948e0cf4b24f0.js +0 -1
  78. package/dist/web/_next/static/chunks/app/queue/page-9cfc8f78d536cfb6.js +0 -1
  79. package/dist/web/_next/static/chunks/app/settings/page-9c2b961beb8b3dce.js +0 -1
  80. package/dist/web/_next/static/chunks/app/system/page-3466496814a70b62.js +0 -1
  81. /package/dist/web/_next/static/{D3ew46wEw5JXPsTVwZwFC → n8n-2FmbL8PhXulu4hTV5}/_buildManifest.js +0 -0
  82. /package/dist/web/_next/static/{D3ew46wEw5JXPsTVwZwFC → n8n-2FmbL8PhXulu4hTV5}/_ssgManifest.js +0 -0
@@ -170,22 +170,12 @@ const VcsInput = z
170
170
  * model of its own, so a check it cannot decide by running something and comparing is a check
171
171
  * it would have to take on trust — which is the thing the check exists to replace.
172
172
  */
173
+ /** What a check expects, as a plan, a skill and a reviewer's finding write it. */
174
+ export const CHECK_EXPECTS = ['exit-zero', 'exit-nonzero', 'output-contains', 'output-omits', 'output-matches', 'file-exists', 'file-missing', 'file-contains'];
173
175
  export const CheckInput = z
174
176
  .object({
175
177
  name: z.string().trim().min(3, 'A check needs a name saying what it is checking.'),
176
- expect: z.enum([
177
- 'exit-zero',
178
- 'exit-nonzero',
179
- 'output-contains',
180
- 'output-omits',
181
- 'output-matches',
182
- 'file-exists',
183
- 'file-missing',
184
- 'file-contains',
185
- ], {
186
- error: 'expect must be one of: exit-zero, exit-nonzero, output-contains, output-omits, output-matches, ' +
187
- 'file-exists, file-missing, file-contains.',
188
- }),
178
+ expect: z.enum(CHECK_EXPECTS, { error: `expect must be one of: ${CHECK_EXPECTS.join(', ')}.` }),
189
179
  run: z.string().trim().optional(),
190
180
  /**
191
181
  * The shell to run it in. Left out is the usual answer and the better one.
@@ -3521,8 +3521,8 @@ export const SYSTEM_GUIDE = [
3521
3521
  kind: 'button',
3522
3522
  en: 'Change…',
3523
3523
  bg: 'Смени…',
3524
- doesEn: 'Opens a field for another folder (and the machine\'s folder dialog), with a checkbox to copy what is there now — settings, conversations, logs, the Edge profile — and the button that uses it. Nothing in the new folder is overwritten; it takes effect when the bot is started again. Not offered for a clone or when COP_HOME sets the folder, and refused while work is going on.',
3525
- doesBg: 'Отваря поле за друга папка (и прозореца за избор на папка), с отметка да се копира каквото има сега — настройки, разговори, логове, профилът на Edge — и бутона, който я ползва. Нищо в новата папка не се презаписва; важи, когато ботът се пусне отново. Не се предлага за клонинг или когато COP_HOME задава папката, и се отказва, докато върви работа.',
3524
+ doesEn: 'Opens a field for another folder (and the machine\'s folder dialog), with a checkbox to copy what is there now — settings, conversations, logs, the Edge profile — and the button that uses it. What the new folder has already is put aside beside it (<folder>.before-<when>), not used; it takes effect when the bot is started again. Not offered for a clone or when COP_HOME sets the folder, and refused while work is going on.',
3525
+ doesBg: 'Отваря поле за друга папка (и прозореца за избор на папка), с отметка да се копира каквото има сега — настройки, разговори, логове, профилът на Edge — и бутона, който я ползва. Каквото новата папка вече има, отива встрани до нея (<папка>.before-<кога>) и не се ползва; важи, когато ботът се пусне отново. Не се предлага за клонинг или когато COP_HOME задава папката, и се отказва, докато върви работа.',
3526
3526
  },
3527
3527
  {
3528
3528
  key: 'sys.homeReset',
@@ -66,7 +66,11 @@ export const KerriganReplySchema = z
66
66
  skill: z.preprocess((v) => (v === undefined || v === null ? undefined : String(v).trim().replace(/^\//, '')), z.string().optional()),
67
67
  // answer
68
68
  option: number.optional(),
69
- options: z.preprocess((v) => (v === undefined || v === null ? undefined : Array.isArray(v) ? v : [v]), z.array(z.union([number, z.string()])).optional()),
69
+ /*
70
+ * The numbers of the answers chosen (status "answer", read by number there), or the answers she offers the person
71
+ * (status "ask"): kept as written (third hunt, 2026-11-20). Read as numbers here, "Use Node 20" became 20 on the card.
72
+ */
73
+ options: z.preprocess((v) => (v === undefined || v === null ? undefined : Array.isArray(v) ? v : [v]), z.array(z.union([z.number(), z.string()])).optional()),
70
74
  text: prose,
71
75
  decision: z.preprocess((v) => (typeof v === 'string' ? v.trim().toLowerCase() : v), z.enum(['approve', 'revise'], { message: 'decision is "approve" or "revise".' })).optional(),
72
76
  note: prose,
@@ -21,8 +21,8 @@ const CommandStep = z.object({
21
21
  */
22
22
  type: z.literal('command', {
23
23
  error: 'this runner has no file steps: it never fetches or runs a file the chat provides. Every step is ' +
24
- 'a `command`. For something too long for one line, write the file with Set-Content in one command ' +
25
- 'step and run it with its interpreter in the next.',
24
+ 'a `command`. For something too long for one line, put it in the command itself: a command may be ' +
25
+ 'several lines. Never write a script only to run it.',
26
26
  }),
27
27
  shell: ShellSchema.optional(),
28
28
  cmd: z.string().min(1),
@@ -141,6 +141,92 @@ export function mergeItems(current, edited) {
141
141
  });
142
142
  return { items };
143
143
  }
144
+ /**
145
+ * An edit a page made on the list it had read (`seen`), put onto the queue as it is now (second bug hunt, 2026-11-19).
146
+ * The page sends the whole list, and a list read before a change — a second tab, or a page that had not read again yet —
147
+ * dropped a task added since, put back one taken out since (to run again), and undid an edit made elsewhere. What this
148
+ * page changed is taken; what it did not touch stays as the queue has it now:
149
+ * - a task added since stays, after the tasks it came after;
150
+ * - one taken out since stays out;
151
+ * - a field this page did not change keeps the queue's value, so an edit made elsewhere is not undone;
152
+ * - the order is this page's when it moved something, else the queue's.
153
+ * A new task whose id was given meanwhile to another gets one of its own.
154
+ */
155
+ export function rebaseEdit(current, seen, edited) {
156
+ const saw = new Map(seen.map((x) => [x.id, x]));
157
+ const now = new Map(current.map((x) => [x.id, x]));
158
+ const taken = new Set([...current.map((x) => x.id), ...seen.map((x) => x.id)]);
159
+ const renamed = new Map();
160
+ const kept = new Map();
161
+ const fresh = [];
162
+ const pageOrder = [];
163
+ for (const e of edited) {
164
+ const was = saw.get(e.id);
165
+ if (!was) {
166
+ let id = e.id;
167
+ while (taken.has(id))
168
+ id = `${id}x`;
169
+ taken.add(id);
170
+ if (id !== e.id)
171
+ renamed.set(e.id, id);
172
+ const dependsOn = e.dependsOn.map((d) => renamed.get(d) ?? d);
173
+ fresh.push({ ...e, id, dependsOn });
174
+ pageOrder.push(id);
175
+ continue;
176
+ }
177
+ const is = now.get(e.id);
178
+ if (!is)
179
+ continue;
180
+ const out = { id: e.id };
181
+ for (const key of GIVEN) {
182
+ if (key === 'id')
183
+ continue;
184
+ const v = asSaid(e[key]) === asSaid(was[key]) ? is[key] : e[key];
185
+ if (v !== undefined)
186
+ out[key] = v;
187
+ }
188
+ if (e.status)
189
+ out.status = e.status;
190
+ kept.set(e.id, out);
191
+ pageOrder.push(e.id);
192
+ }
193
+ const knownOnPage = pageOrder.filter((id) => kept.has(id));
194
+ const moved = knownOnPage.join('\n') !== seen.map((x) => x.id).filter((id) => kept.has(id)).join('\n');
195
+ const since = current.filter((x) => !saw.has(x.id));
196
+ let order;
197
+ if (moved) {
198
+ order = [...pageOrder];
199
+ // After every task it came after: one added at the end stays at the end.
200
+ for (const x of since) {
201
+ const i = current.indexOf(x);
202
+ const at = Math.max(0, ...current.slice(0, i).map((o) => order.indexOf(o.id) + 1));
203
+ order.splice(at, 0, x.id);
204
+ }
205
+ }
206
+ else {
207
+ order = [...current.filter((x) => kept.has(x.id) || !saw.has(x.id)).map((x) => x.id), ...fresh.map((x) => x.id)];
208
+ }
209
+ const byId = new Map([...kept, ...fresh.map((x) => [x.id, x]), ...since.map((x) => [x.id, asGiven(x)])]);
210
+ // What a task depends on is a task before it that is still there.
211
+ const before = new Set();
212
+ return order.map((id) => {
213
+ const x = byId.get(id);
214
+ const dependsOn = x.dependsOn.filter((d) => before.has(d));
215
+ before.add(id);
216
+ return dependsOn.length === x.dependsOn.length ? x : { ...x, dependsOn };
217
+ });
218
+ }
219
+ /**
220
+ * Whether an edit leaves a task carrying on in its own chat, as `mergeItems` keeps it: one that carries on, with nothing
221
+ * of what it does changed. It goes on as it was given there, its skill sent with it already, so a skill taken out of
222
+ * Settings since is not its concern (second bug hunt, 2026-11-19: it blocked every edit of the queue).
223
+ */
224
+ export function carriesOn(was, edit) {
225
+ if (!was.resume || was.status !== 'waiting')
226
+ return false;
227
+ const given = asGiven(edit);
228
+ return !WHAT_IT_DOES.some((key) => asSaid(was[key]) !== asSaid(given[key]));
229
+ }
144
230
  /** What the operator gives a task, apart from what its runs give it. */
145
231
  const GIVEN = ['id', 'name', 'prompt', 'model', 'dependsOn', 'branch', 'review', 'reviewModel', 'lead', 'workerModel', 'skill', 'plan'];
146
232
  /** Of what is given, what the task's chat is told: an edit of it starts over a task that carries on. */
@@ -86,20 +86,24 @@ const PARKED_FOR = {
86
86
  model: 'for the operator to choose the model by hand',
87
87
  password: 'for a password Git asked for in its own window',
88
88
  };
89
- export function whyItStopped(c) {
89
+ /**
90
+ * `committed`: whether what the task had changed was committed for it — not in the operator's chat, where nothing is
91
+ * branched or committed (third hunt, 2026-11-20: "what had changed is committed on this branch" was said there, beside
92
+ * the note that nothing is).
93
+ */
94
+ export function whyItStopped(c, committed = true) {
95
+ const kept = committed ? ', and what had changed is committed on this branch.' : '.';
90
96
  if (c.how === 'failed')
91
97
  return describeEnding(c.fromAttempt, c.ended, c.stoppedBecause);
92
98
  if (c.how === 'interrupted') {
93
99
  const where = c.interruption ? `\n\n${describeInterruption(c.interruption)}\n\n` : ' ';
94
100
  return ('The runner stopped unexpectedly while this task was in progress — the program was closed, the machine went off or it ' +
95
- 'crashed; nothing you did failed — and it has now started again. The files are as your work left them, and what had ' +
96
- `changed is committed on this branch.${where}`.trimEnd());
101
+ `crashed; nothing you did failed — and it has now started again. The files are as your work left them${kept}${where}`.trimEnd());
97
102
  }
98
103
  if (c.how === 'parked') {
99
104
  const what = c.parkedFor ? PARKED_FOR[c.parkedFor] : 'for the operator';
100
105
  return (`It waited ${what}, and was set aside so that the queue's other tasks could run while nobody was there — not because ` +
101
- 'anything failed. The operator has answered now: the answer is below. The files are as you left them, and what had ' +
102
- 'changed is committed on this branch.');
106
+ `anything failed. The operator has answered now: the answer is below. The files are as you left them${kept}`);
103
107
  }
104
108
  if (c.how === 'stopped') {
105
109
  const where = c.interruption ? `\n\n${describeInterruption(c.interruption).replace(/when the runner stopped/g, 'when it was stopped')}\n\n` : ' ';
@@ -169,10 +173,10 @@ export function composeOpening(input) {
169
173
  * operator approved — but plan first, as the plan-mode note says, and nothing changes until the plan is approved.
170
174
  */
171
175
  if (input.planNote) {
172
- const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation. ${whyItStopped(input.continuing)} ` +
176
+ const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation. ${whyItStopped(input.continuing, !input.noCommits)} ` +
173
177
  `Its plan was not approved yet, so the work does not go on from where it stopped: plan first, as below — look at ` +
174
178
  `what is there now, changing nothing — and send the plan for approval. Step numbering restarts at 1.\n\n` +
175
- `${input.planNote}\n\n` +
179
+ // The plan-mode note once, with the runner's notes below (second bug hunt, 2026-11-19: it was sent twice).
176
180
  (instruction ? `${instructionSection(instruction.text)}\n\n` : '') +
177
181
  `${runnerBlock(input)}`.trimEnd();
178
182
  return { messages: [message], firstMessage: message };
@@ -183,7 +187,7 @@ export function composeOpening(input) {
183
187
  */
184
188
  if (input.continuing.how === 'failed' && instruction) {
185
189
  const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation, with a new instruction from the operator.\n\n` +
186
- `${whyItStopped(input.continuing)}\n\n` +
190
+ `${whyItStopped(input.continuing, !input.noCommits)}\n\n` +
187
191
  `The files are as that attempt left them, and what it changed is in your working tree. Do not start over: look at ` +
188
192
  `what is there first, keep what is right, and do what the instruction below says. The assignment is the one you ` +
189
193
  `were given above, with the instruction added to it. Verify the result as for any task. Step numbering restarts at 1.\n\n` +
@@ -192,7 +196,7 @@ export function composeOpening(input) {
192
196
  return { messages: [message], firstMessage: message };
193
197
  }
194
198
  const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation. ` +
195
- `${whyItStopped(input.continuing)} ` +
199
+ `${whyItStopped(input.continuing, !input.noCommits)} ` +
196
200
  `Do not start over and do not repeat work that is done: start from ` +
197
201
  `your plan, say in \`notes\` which stages are done and which one you are on, and carry on. ` +
198
202
  (instruction
@@ -202,7 +206,7 @@ export function composeOpening(input) {
202
206
  return { messages: [message], firstMessage: message };
203
207
  }
204
208
  const continuationLine = input.continuing
205
- ? `\n\nThis continues an earlier attempt at this task. ${whyItStopped(input.continuing)}` +
209
+ ? `\n\nThis continues an earlier attempt at this task. ${whyItStopped(input.continuing, !input.noCommits)}` +
206
210
  (input.continuing.how === 'failed'
207
211
  ? `\n\nWhat that attempt changed is in your working tree. Look at it before changing anything, keep what is right, and do what the instruction below says.`
208
212
  : ` Look at what is already done before changing anything, and carry on from there.`) +
@@ -4,7 +4,8 @@
4
4
  * each. Kept in the data folder, so a failure seen before a restart is still shown; read by the banner on every page
5
5
  * and by Settings, where the locator's field is in red, until the locator is changed there or the operator closes it.
6
6
  */
7
- import { readStoreJson, writeFileAtomically } from './store.js';
7
+ import { rename } from 'node:fs/promises';
8
+ import { readStoreJson, StoreFileUnusable, writeFileAtomically } from './store.js';
8
9
  import { CHAT_LOCATOR_KEYS } from '../transport/locators.js';
9
10
  import { isStepKey } from '../transport/chatSteps.js';
10
11
  const isKey = (k) => typeof k === 'string' && (CHAT_LOCATOR_KEYS.includes(k) || isStepKey(k));
@@ -26,6 +27,25 @@ export class LocatorFailures {
26
27
  return [];
27
28
  return raw.filter((f) => !!f && typeof f === 'object' && isKey(f.key) && typeof f.locator === 'string' && typeof f.at === 'string');
28
29
  }
30
+ /**
31
+ * As kept, or — the file there but not readable, after a power cut say — the file moved aside beside itself and the
32
+ * list begun again (third hunt, 2026-11-20): refused, every failure after it was dropped without a word, and the banner,
33
+ * the red field and the file for a chatbot were gone for good. These are notices, kept since; nothing of the operator's
34
+ * is lost, and where the old one went is said.
35
+ */
36
+ async readOrPutAside() {
37
+ try {
38
+ return await this.read();
39
+ }
40
+ catch (e) {
41
+ if (!(e instanceof StoreFileUnusable))
42
+ throw e;
43
+ const aside = `${this.file}.unreadable-${new Date().toISOString().replace(/[:.]/g, '-')}`;
44
+ await rename(this.file, aside);
45
+ console.error(`[locators] ${this.file} could not be read; moved to ${aside}, and the list begun again`);
46
+ return [];
47
+ }
48
+ }
29
49
  async get(key) {
30
50
  return (await this.list()).find((f) => f.key === key) ?? null;
31
51
  }
@@ -33,12 +53,13 @@ export class LocatorFailures {
33
53
  async record(failure) {
34
54
  await this.change((all) => [failure, ...all.filter((f) => f.key !== failure.key)]);
35
55
  }
36
- /** Closed by the operator. True when there was one. */
37
- async dismiss(key) {
56
+ /** Closed by the operator, or found after all; with `locator`, only while it is the one kept. True when there was one. */
57
+ async dismiss(key, locator) {
38
58
  let had = false;
59
+ const goes = (f) => f.key === key && (locator === undefined || f.locator === locator);
39
60
  await this.change((all) => {
40
- had = all.some((f) => f.key === key);
41
- return all.filter((f) => f.key !== key);
61
+ had = all.some(goes);
62
+ return all.filter((f) => !goes(f));
42
63
  });
43
64
  return had;
44
65
  }
@@ -49,7 +70,7 @@ export class LocatorFailures {
49
70
  */
50
71
  async change(edit) {
51
72
  const run = async () => {
52
- await writeFileAtomically(this.file, async () => JSON.stringify(edit(await this.read()), null, 2));
73
+ await writeFileAtomically(this.file, async () => JSON.stringify(edit(await this.readOrPutAside()), null, 2));
53
74
  };
54
75
  const done = this.queue.then(run, run);
55
76
  this.queue = done.catch(() => undefined);
@@ -12,6 +12,25 @@ export function tidyVcsPlan(plan) {
12
12
  return undefined;
13
13
  return { ...(branch ? { branch } : {}), ...(commitMessage ? { commitMessage } : {}) };
14
14
  }
15
+ /**
16
+ * The approved plan a task works to: its own attempt's, else, carried on, the latest one approved in the conversation it
17
+ * carries on — back through the attempts it continues, to the one that began that conversation. Not one before it
18
+ * (second bug hunt, 2026-11-19): a plan approved before a retry in a fresh conversation was taken by a message carried
19
+ * on after that retry, and it went to the work on a plan its conversation never saw.
20
+ */
21
+ export function approvedPlanOf(task) {
22
+ if (task.plan?.approved)
23
+ return task.plan;
24
+ if (!task.continuing)
25
+ return undefined;
26
+ for (const a of [...(task.attempts ?? [])].reverse()) {
27
+ if (a.plan?.approved)
28
+ return a.plan;
29
+ if (!a.continuing || a.freshRetry)
30
+ return undefined;
31
+ }
32
+ return undefined;
33
+ }
15
34
  /** Whether a set-aside task's card is over — stopped, or let go of by the queue — so that "Continue" carries it on. */
16
35
  export function parkedOver(parked) {
17
36
  return !parked || parked.answer?.kind === 'stopped' || parked.answer?.kind === 'released';
@@ -6,8 +6,8 @@
6
6
  */
7
7
  import { createHash } from 'node:crypto';
8
8
  import { existsSync, statSync } from 'node:fs';
9
- import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
10
- import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
+ import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';
10
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
11
11
  import { git, looksLikeRepo, repoState } from '../vcs/git.js';
12
12
  import { moveOver } from './store.js';
13
13
  export async function workspaceInfo(dir, name = '') {
@@ -71,12 +71,18 @@ function insideFolder(dir, path) {
71
71
  function versionOf(bytes) {
72
72
  return createHash('sha256').update(bytes).digest('hex').slice(0, 20);
73
73
  }
74
+ /**
75
+ * Said when the file is not on disk (any more): deleted or renamed under the editor (second bug hunt, 2026-11-19), which
76
+ * the page says, keeping the edit and offering to save it there again.
77
+ */
78
+ export const GONE_FROM_DISK = 'gone-from-disk';
79
+ const gone = (clean) => Object.assign(new Error(`There is no file ${clean} in the project folder.`), { code: GONE_FROM_DISK });
74
80
  /** One file of the folder as it is on disk, as text; a binary or very large one is said to be one. */
75
81
  export async function workspaceFile(dir, path, maxBytes = MAX_EDIT_BYTES) {
76
82
  const { clean, full } = insideFolder(dir, path);
77
83
  const st = await stat(full).catch(() => null);
78
84
  if (!st?.isFile())
79
- throw new Error(`There is no file ${clean} in the project folder.`);
85
+ throw gone(clean);
80
86
  if (st.size > maxBytes)
81
87
  return { path: clean, text: null, binary: false, tooLarge: true, size: st.size };
82
88
  const bytes = await readFile(full);
@@ -112,12 +118,21 @@ export const CHANGED_ON_DISK = 'changed-on-disk';
112
118
  * is there already and is text; and only over the version the edit was made on (`base`), so a change the chat made to
113
119
  * it meanwhile is not overwritten without the operator knowing — without `base` it is saved whatever is there. The
114
120
  * file keeps its own line endings and its byte-order mark: the editor works in LF, and a CRLF file stays CRLF.
121
+ * `again`: a file deleted or renamed under the editor, saved where it was with the editor's text (2026-11-19).
115
122
  */
116
- export async function saveWorkspaceFile(dir, path, text, base) {
123
+ export async function saveWorkspaceFile(dir, path, text, base, again = false) {
117
124
  const { clean, full } = insideFolder(dir, path);
118
125
  const st = await stat(full).catch(() => null);
126
+ if (!st && again) {
127
+ const bytes = Buffer.from(text.replace(/\r\n/g, '\n'), 'utf8');
128
+ if (bytes.length > MAX_EDIT_BYTES)
129
+ throw new Error(`The text is too large to save (${bytes.length} bytes).`);
130
+ await mkdir(dirname(full), { recursive: true });
131
+ await writeFile(full, bytes, { flag: 'wx' });
132
+ return { path: clean, version: versionOf(bytes), size: bytes.length };
133
+ }
119
134
  if (!st?.isFile())
120
- throw new Error(`There is no file ${clean} in the project folder.`);
135
+ throw gone(clean);
121
136
  if (st.size > MAX_EDIT_BYTES)
122
137
  throw new Error(`${clean} is too large to edit here.`);
123
138
  const before = await readFile(full);
@@ -218,65 +218,65 @@ const NOTICE_ID = 'copilot-operator-notice';
218
218
  * impossible — the runner notes it before the click and waits for it to move, so a copy that
219
219
  * did not happen reads as a failure rather than as the previous answer.
220
220
  */
221
- export const CLIPBOARD_GUARD = `(() => {
222
- const state = { text: '', seq: 0 };
223
- try {
224
- Object.defineProperty(window, '__copClipboard', { value: state, enumerable: false });
225
- } catch (e) {
226
- window.__copClipboard = state;
227
- }
228
-
229
- const remember = (text) => {
230
- if (typeof text !== 'string' || text.length === 0) return;
231
- state.text = text;
232
- state.seq += 1;
233
- };
234
-
235
- const clip = navigator.clipboard;
236
- if (clip) {
237
- try {
238
- Object.defineProperty(clip, 'writeText', {
239
- configurable: true,
240
- writable: true,
241
- value: (text) => {
242
- remember(String(text));
243
- return Promise.resolve();
244
- },
245
- });
246
- } catch (e) { /* a frame that will not let its clipboard be replaced reads as a failure later */ }
247
-
248
- try {
249
- Object.defineProperty(clip, 'write', {
250
- configurable: true,
251
- writable: true,
252
- value: async (items) => {
253
- for (const item of items || []) {
254
- try {
255
- if (item && item.types && item.types.indexOf('text/plain') >= 0) {
256
- remember(await (await item.getType('text/plain')).text());
257
- }
258
- } catch (e) { /* one unreadable item is not a reason to drop the rest */ }
259
- }
260
- },
261
- });
262
- } catch (e) { /* as above */ }
263
- }
264
-
265
- // The old way: select text in a hidden field, then execCommand('copy'). The selection is
266
- // exactly the text being copied, so it is taken and the command is never run.
267
- try {
268
- const realExec = document.execCommand.bind(document);
269
- document.execCommand = (command, ...rest) => {
270
- if (String(command).toLowerCase() === 'copy') {
271
- const selected = String(window.getSelection() || '');
272
- if (selected.length > 0) {
273
- remember(selected);
274
- return true;
275
- }
276
- }
277
- return realExec(command, ...rest);
278
- };
279
- } catch (e) { /* as above */ }
221
+ export const CLIPBOARD_GUARD = `(() => {
222
+ const state = { text: '', seq: 0 };
223
+ try {
224
+ Object.defineProperty(window, '__copClipboard', { value: state, enumerable: false });
225
+ } catch (e) {
226
+ window.__copClipboard = state;
227
+ }
228
+
229
+ const remember = (text) => {
230
+ if (typeof text !== 'string' || text.length === 0) return;
231
+ state.text = text;
232
+ state.seq += 1;
233
+ };
234
+
235
+ const clip = navigator.clipboard;
236
+ if (clip) {
237
+ try {
238
+ Object.defineProperty(clip, 'writeText', {
239
+ configurable: true,
240
+ writable: true,
241
+ value: (text) => {
242
+ remember(String(text));
243
+ return Promise.resolve();
244
+ },
245
+ });
246
+ } catch (e) { /* a frame that will not let its clipboard be replaced reads as a failure later */ }
247
+
248
+ try {
249
+ Object.defineProperty(clip, 'write', {
250
+ configurable: true,
251
+ writable: true,
252
+ value: async (items) => {
253
+ for (const item of items || []) {
254
+ try {
255
+ if (item && item.types && item.types.indexOf('text/plain') >= 0) {
256
+ remember(await (await item.getType('text/plain')).text());
257
+ }
258
+ } catch (e) { /* one unreadable item is not a reason to drop the rest */ }
259
+ }
260
+ },
261
+ });
262
+ } catch (e) { /* as above */ }
263
+ }
264
+
265
+ // The old way: select text in a hidden field, then execCommand('copy'). The selection is
266
+ // exactly the text being copied, so it is taken and the command is never run.
267
+ try {
268
+ const realExec = document.execCommand.bind(document);
269
+ document.execCommand = (command, ...rest) => {
270
+ if (String(command).toLowerCase() === 'copy') {
271
+ const selected = String(window.getSelection() || '');
272
+ if (selected.length > 0) {
273
+ remember(selected);
274
+ return true;
275
+ }
276
+ }
277
+ return realExec(command, ...rest);
278
+ };
279
+ } catch (e) { /* as above */ }
280
280
  })();`;
281
281
  /**
282
282
  * A locator of the chat that found nothing where the bot needed it (operator, 2026-11-17: "a mechanism that detects
@@ -1064,7 +1064,7 @@ export class CopilotTransport {
1064
1064
  // Most likely the box itself (2026-11-17: Copilot's chat was at /home, its box changed): said as the box's locator.
1065
1065
  return await this.locatorMissing('composer', `on ${whereIs(url)}, which did not turn into the chat`, {
1066
1066
  message: (files) => `Copilot showed its page ${whereIs(url)} instead of the chat, and the chat did not open from there ` +
1067
- `(by its address on that host, nor by a link to it on the page). Nothing was sent. ${files} ${this.composerHint()}
1067
+ `(by its address on that host, nor by a link to it on the page). Nothing was sent. ${files} ${this.composerHint()}
1068
1068
  Current URL: ${url}`,
1069
1069
  });
1070
1070
  }
@@ -1160,10 +1160,10 @@ Current URL: ${url}`,
1160
1160
  unknown: 'The page is not the Microsoft 365 Copilot chat.',
1161
1161
  };
1162
1162
  if (where === 'unknown') {
1163
- throw await this.locatorMissing('composer', `on ${whereIs(url)}`, { message: (files) => `${explain.unknown} ${files} ${this.composerHint()}
1163
+ throw await this.locatorMissing('composer', `on ${whereIs(url)}`, { message: (files) => `${explain.unknown} ${files} ${this.composerHint()}
1164
1164
  Current URL: ${url}` });
1165
1165
  }
1166
- throw new Error(`${explain[where] ?? explain.unknown}
1166
+ throw new Error(`${explain[where] ?? explain.unknown}
1167
1167
  Current URL: ${url}`);
1168
1168
  }
1169
1169
  /**
@@ -1256,6 +1256,12 @@ Current URL: ${url}`);
1256
1256
  * Opens the chat and, if the tenant has signed us out, waits for the human. The bot never
1257
1257
  * types credentials; it only waits for the composer to appear.
1258
1258
  */
1259
+ /**
1260
+ * `boxNotWaited`: for a reading that only looks — the models, "Check the locators" — a box not found on Copilot's own
1261
+ * chat page, no sign-in page in sight, is said at once as the box's locator, not waited on for the whole sign-in time
1262
+ * (second bug hunt, 2026-11-19: the operator, at Settings, waited fifteen minutes with nothing said). A sign-in page is
1263
+ * still waited on.
1264
+ */
1259
1265
  async ensureSignedIn(url = this.opts.chatUrl, opts = {}) {
1260
1266
  // A box locator saved in Settings that cannot be used: said once, before the box is looked for with the default.
1261
1267
  for (const problem of this.chatLocatorProblems.splice(0))
@@ -1284,8 +1290,14 @@ Current URL: ${url}`);
1284
1290
  */
1285
1291
  const firstLook = Math.min(this.boxSuspectMs, this.opts.signInTimeoutMs);
1286
1292
  const soon = await this.composerWithin(firstLook, opts.signal, stoppedHere);
1293
+ if (!soon && opts.boxNotWaited && isWorkChatAddress(this.p.url())) {
1294
+ this.warned.add('composer');
1295
+ throw await this.locatorMissing('composer', `on ${whereIs(this.p.url())}, Copilot's own chat page and not a sign-in page, for ${Math.round(firstLook / 1000)} s`);
1296
+ }
1297
+ let suspected = false;
1287
1298
  if (!soon && isWorkChatAddress(this.p.url()) && !this.warned.has('composer')) {
1288
1299
  this.warned.add('composer');
1300
+ suspected = true;
1289
1301
  await this.locatorMissing('composer', `on ${whereIs(this.p.url())}, Copilot's own chat page and not a sign-in page, for ${Math.round(firstLook / 1000)} s: if you are signed in, the box's locator is the one to fix (the bot goes on waiting for a sign-in meanwhile)`, { stopped: false }).catch(() => undefined);
1290
1302
  }
1291
1303
  if (!soon && !(await this.composerWithin(Math.max(1, this.opts.signInTimeoutMs - firstLook), opts.signal, stoppedHere))) {
@@ -1295,6 +1307,14 @@ Current URL: ${url}`);
1295
1307
  ? ` If you were signed in, the box to write in was not found on Copilot's chat page: fix "Box to write in" in Settings → "The chat's locators" (its notice has the file for a chatbot). In force: ${this.chatLocators.composer}`
1296
1308
  : ''));
1297
1309
  }
1310
+ /*
1311
+ * Found after all, once the sign-in was done (second bug hunt, 2026-11-19): the box's locator was not at fault, and
1312
+ * the red field and the banner it had been given stayed, saying so.
1313
+ */
1314
+ if (suspected) {
1315
+ this.warned.delete('composer');
1316
+ this.emit('locator-found', { key: 'composer', locator: this.chatLocators.composer });
1317
+ }
1298
1318
  this.emit('signed-in');
1299
1319
  // A sign-in may come back to Copilot's home page rather than to its chat.
1300
1320
  at = await this.arrive(Url.newChatPath, opts.signal, stoppedHere);