copilot-operator 0.1.84 → 0.1.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/src/api/operator.controller.js +113 -0
  2. package/dist/src/api/operator.service.js +329 -32
  3. package/dist/src/config/schema.js +32 -0
  4. package/dist/src/orchestrator/cardText.js +91 -0
  5. package/dist/src/orchestrator/kerriganRunner.js +914 -0
  6. package/dist/src/orchestrator/leadRunner.js +25 -15
  7. package/dist/src/orchestrator/planMode.js +6 -4
  8. package/dist/src/orchestrator/taskRunner.js +93 -40
  9. package/dist/src/plan/kerrigan.js +109 -4
  10. package/dist/src/plan/systemGuide.js +227 -4
  11. package/dist/src/protocol/kerriganSchema.js +175 -0
  12. package/dist/src/session/compose.js +5 -1
  13. package/dist/src/session/store.js +9 -0
  14. package/dist/src/transport/chatTransport.js +6 -2
  15. package/dist/src/transport/copilotTransport.js +226 -11
  16. package/dist/src/transport/keptWindow.js +247 -0
  17. package/dist/src/transport/locators.js +14 -4
  18. package/dist/src/vcs/git.js +72 -2
  19. package/dist/src/vcs/operatorGit.js +409 -0
  20. package/dist/web/404.html +2 -2
  21. package/dist/web/_next/static/chunks/1077.26ca37faa3726fff.js +1 -0
  22. package/dist/web/_next/static/chunks/1548.f5790cd11a91309f.js +1 -0
  23. package/dist/web/_next/static/chunks/2163.aa9d9b82fcde6caa.js +1 -0
  24. package/dist/web/_next/static/chunks/714.b7dbce98ba0b59a8.js +1 -0
  25. package/dist/web/_next/static/chunks/7220.0ca53eefec5d01ea.js +1 -0
  26. package/dist/web/_next/static/chunks/7921-8f6503aba840928a.js +1 -0
  27. package/dist/web/_next/static/chunks/8124-1dba8babfcfbc6e2.js +1 -0
  28. package/dist/web/_next/static/chunks/8584.9f3b058a8f67d3d7.js +1 -0
  29. package/dist/web/_next/static/chunks/9067.107f6164157e0aa1.js +1 -0
  30. package/dist/web/_next/static/chunks/9747.984a86f70f9cd973.js +1 -0
  31. package/dist/web/_next/static/chunks/app/layout-127e5af1ebf21876.js +1 -0
  32. package/dist/web/_next/static/chunks/app/page-b71841852e6b9ff5.js +1 -0
  33. package/dist/web/_next/static/chunks/app/settings/page-95069cb94d79e909.js +1 -0
  34. package/dist/web/_next/static/chunks/webpack-c015bbeb103c0856.js +1 -0
  35. package/dist/web/_next/static/css/0c5d6d5914aa3824.css +1 -0
  36. package/dist/web/defaults.html +2 -2
  37. package/dist/web/defaults.txt +8 -8
  38. package/dist/web/index.html +3 -3
  39. package/dist/web/index.txt +9 -9
  40. package/dist/web/queue.html +2 -2
  41. package/dist/web/queue.txt +9 -9
  42. package/dist/web/settings.html +2 -2
  43. package/dist/web/settings.txt +9 -9
  44. package/dist/web/system.html +2 -2
  45. package/dist/web/system.txt +9 -9
  46. package/package.json +176 -173
  47. package/prompts/kerrigan1.md +169 -0
  48. package/prompts/lead1.md +4 -1
  49. package/prompts/level1.md +8 -1
  50. package/dist/web/_next/static/chunks/1077.e0136d293069ccb8.js +0 -1
  51. package/dist/web/_next/static/chunks/1548.5cc0c57b00c2e44f.js +0 -1
  52. package/dist/web/_next/static/chunks/2163.2af0979126ae613a.js +0 -1
  53. package/dist/web/_next/static/chunks/714.410e2b61aa8c72b7.js +0 -1
  54. package/dist/web/_next/static/chunks/7220.2c4e5173a060769f.js +0 -1
  55. package/dist/web/_next/static/chunks/7921-3d21f385338afdf9.js +0 -1
  56. package/dist/web/_next/static/chunks/8124-1dc34be1646970a8.js +0 -1
  57. package/dist/web/_next/static/chunks/8584.61650a59d2bfa54d.js +0 -1
  58. package/dist/web/_next/static/chunks/9067.553056fc9b6cf80e.js +0 -1
  59. package/dist/web/_next/static/chunks/9747.d5826524bf4b714d.js +0 -1
  60. package/dist/web/_next/static/chunks/app/layout-b8a1e0075a48b025.js +0 -1
  61. package/dist/web/_next/static/chunks/app/page-13147b69cf336831.js +0 -1
  62. package/dist/web/_next/static/chunks/app/settings/page-e3909ef6c2d8e321.js +0 -1
  63. package/dist/web/_next/static/chunks/webpack-19a2d7161f23b21d.js +0 -1
  64. package/dist/web/_next/static/css/f152f27d6afce55c.css +0 -1
  65. /package/dist/web/_next/static/{WU_J4Ke1d3xVfpW2acqqf → hLBBsG7Kn4vd0p_J-47BJ}/_buildManifest.js +0 -0
  66. /package/dist/web/_next/static/{WU_J4Ke1d3xVfpW2acqqf → hLBBsG7Kn4vd0p_J-47BJ}/_ssgManifest.js +0 -0
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Kerrigan's contract, as a schema (operator, 2026-11-12: "I paste Kerrigan into a chat, give her the task, she gives me
3
+ * the prompt and tells me plan mode, two chats, the reviewer, which skill; I run the bot; when it asks me something I
4
+ * take the question to her and do what she says; at the end she reads the result and goes on with a new prompt, in a
5
+ * new chat or the same — automate that").
6
+ *
7
+ * The prose she is given is `prompts/kerrigan1.md`; this is the enforcement. She runs nothing: every reply is one
8
+ * decision — a message to a chat with its settings, the answer to a card of the chat's, a question for the operator,
9
+ * her report, or a stop — and anything that does not validate here is sent back with the reason, as a chat's reply in
10
+ * the wrong shape is. Lenient where nothing runs on it, as the lead's: prose that came as an object or a list is read
11
+ * as the text it means.
12
+ */
13
+ import { z } from 'zod';
14
+ import { findJsonCandidates, stripCitations, stripLineNumbers } from './parser.js';
15
+ import { proseOfValue } from './leadSchema.js';
16
+ import { MIN_SUMMARY_CHARS } from './replySchema.js';
17
+ const prose = z.preprocess((v) => (v === undefined || v === null ? undefined : proseOfValue(v)), z.string().optional());
18
+ const proseList = z.preprocess((v) => v === undefined || v === null
19
+ ? []
20
+ : typeof v === 'string'
21
+ ? v.split(/\r?\n/).map((l) => l.replace(/^\s*(?:\d+[.)]|[-*•])\s+/, '').trim()).filter(Boolean)
22
+ : Array.isArray(v)
23
+ ? v.map((x) => proseOfValue(x)).filter((x) => x.trim() !== '')
24
+ : [proseOfValue(v)], z.array(z.string()));
25
+ /** A yes or no, as a chat may say it: true, "true", "yes", 1. */
26
+ const flag = z.preprocess((v) => {
27
+ if (typeof v === 'string')
28
+ return /^(true|yes|on|1)$/i.test(v.trim()) ? true : /^(false|no|off|0|)$/i.test(v.trim()) ? false : v;
29
+ if (typeof v === 'number')
30
+ return v !== 0;
31
+ return v;
32
+ }, z.boolean());
33
+ /** A number of an answer, as a chat may write it: 2, "2", "2." or "option 2". */
34
+ const number = z.preprocess((v) => {
35
+ if (typeof v === 'string') {
36
+ const m = /^\D*(\d+)/.exec(v.trim());
37
+ return m ? Number(m[1]) : v;
38
+ }
39
+ return v;
40
+ }, z.number().int().min(1).max(50));
41
+ export const RETRY_CHOICES = ['same', 'fresh', 'continue', 'restore', 'accept'];
42
+ export const KerriganReplySchema = z
43
+ .object({
44
+ /**
45
+ * `send` — a message to a chat (`prompt`), new or the one sent to last (`chat`), with its settings. `answer` — the card
46
+ * the runner put to her, answered: an option by its number (`option`), several (`options`), her own words (`text`),
47
+ * a plan approved or sent back (`decision`, `note`), or a subtask's retry (`choice`). `ask` — a question for the
48
+ * operator; to a card, leaving it to them (`why`, `suggestion`). `done` — her report (`report`). `blocked` — it
49
+ * cannot go on (`summary`, `needed`).
50
+ */
51
+ status: z.enum(['send', 'answer', 'ask', 'done', 'blocked'], {
52
+ message: 'status is one of "send", "answer", "ask", "done", "blocked". "continue", "delegate", "plan" and "handoff" are the chats\' and the lead\'s: ' +
53
+ 'what a chat is to do goes in a "send"; a card is answered with "answer"; a question for the person is "ask".',
54
+ }),
55
+ understanding: prose,
56
+ notes: prose,
57
+ /** Where she looked before she decided, as she names them. */
58
+ sources: proseList.default([]),
59
+ // send
60
+ chat: z.preprocess((v) => (typeof v === 'string' ? v.trim().toLowerCase() : v), z.enum(['new', 'same'], { message: 'chat is "new" or "same".' })).optional(),
61
+ title: prose,
62
+ prompt: prose,
63
+ planMode: flag.optional(),
64
+ twoChats: flag.optional(),
65
+ review: flag.optional(),
66
+ skill: z.preprocess((v) => (v === undefined || v === null ? undefined : String(v).trim().replace(/^\//, '')), z.string().optional()),
67
+ // answer
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()),
70
+ text: prose,
71
+ decision: z.preprocess((v) => (typeof v === 'string' ? v.trim().toLowerCase() : v), z.enum(['approve', 'revise'], { message: 'decision is "approve" or "revise".' })).optional(),
72
+ note: prose,
73
+ choice: z.preprocess((v) => (typeof v === 'string' ? v.trim().toLowerCase() : v), z.enum(RETRY_CHOICES, { message: `choice is one of ${RETRY_CHOICES.map((c) => `"${c}"`).join(', ')}.` })).optional(),
74
+ // ask
75
+ question: prose,
76
+ why: prose,
77
+ multiple: flag.default(false),
78
+ suggestion: prose,
79
+ // done / blocked
80
+ report: prose,
81
+ evidence: proseList.default([]),
82
+ summary: prose,
83
+ needed: prose,
84
+ })
85
+ .refine((r) => r.status !== 'send' || (r.prompt ?? '').trim().length >= 20, {
86
+ message: 'status "send" requires a "prompt": the message for the chat, in full — what to do, what it is for, the result and its form, and how it is known to be done.',
87
+ path: ['prompt'],
88
+ })
89
+ .refine((r) => r.status !== 'send' || !!r.chat, {
90
+ message: 'status "send" requires "chat": "new" for a new conversation, "same" for the one you sent to last.',
91
+ path: ['chat'],
92
+ })
93
+ .refine((r) => r.status !== 'done' || (r.report ?? '').trim().length >= MIN_SUMMARY_CHARS, {
94
+ message: 'status "done" requires a "report" for the person: what was done, what shows it, and what is left, in full.',
95
+ path: ['report'],
96
+ })
97
+ .refine((r) => r.status !== 'blocked' || (r.summary ?? '').trim().length >= MIN_SUMMARY_CHARS, {
98
+ message: 'status "blocked" requires a "summary": what was done and found, with its evidence.',
99
+ path: ['summary'],
100
+ })
101
+ .refine((r) => r.status !== 'blocked' || (r.needed ?? '').trim().length > 0, {
102
+ message: 'status "blocked" requires "needed": what would let the work go on.',
103
+ path: ['needed'],
104
+ });
105
+ /** Her reply, found, validated and cleaned of citation markers. */
106
+ export function parseKerriganReply(markdown) {
107
+ const candidates = findJsonCandidates(markdown);
108
+ if (candidates.length === 0) {
109
+ return { ok: false, reason: 'no-json-block', detail: 'The reply contained no fenced ```json block and no JSON object at all.' };
110
+ }
111
+ const errors = [];
112
+ const paths = new Set();
113
+ for (const raw of candidates) {
114
+ for (const text of [raw, stripLineNumbers(raw)]) {
115
+ let value;
116
+ try {
117
+ value = JSON.parse(text);
118
+ }
119
+ catch (e) {
120
+ errors.push(`JSON.parse failed: ${e.message}`);
121
+ continue;
122
+ }
123
+ const result = KerriganReplySchema.safeParse(value);
124
+ if (!result.success) {
125
+ errors.push(result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; '));
126
+ for (const i of result.error.issues)
127
+ paths.add(i.path.join('.') || '(root)');
128
+ continue;
129
+ }
130
+ const r = result.data;
131
+ const clean = (s) => stripCitations(s)?.trim() || undefined;
132
+ return {
133
+ ok: true,
134
+ reply: {
135
+ ...r,
136
+ understanding: clean(r.understanding),
137
+ notes: clean(r.notes),
138
+ prompt: clean(r.prompt),
139
+ title: clean(r.title),
140
+ text: clean(r.text),
141
+ note: clean(r.note),
142
+ question: clean(r.question),
143
+ why: clean(r.why),
144
+ suggestion: clean(r.suggestion),
145
+ report: clean(r.report),
146
+ summary: clean(r.summary),
147
+ needed: clean(r.needed),
148
+ },
149
+ json: text.trim(),
150
+ };
151
+ }
152
+ }
153
+ return { ok: false, reason: 'invalid-json', detail: errors.slice(0, 4).join(' | '), ...(paths.size > 0 ? { paths: [...paths] } : {}) };
154
+ }
155
+ const EXAMPLE = [
156
+ '```json',
157
+ '{"status": "send", "notes": "what you decided and why", "sources": ["the mail from …, 3 Nov"], "chat": "new", "title": "Fix the login test", "prompt": "the message for the chat, in full", "planMode": true, "twoChats": false, "review": true, "skill": ""}',
158
+ '```',
159
+ 'or {"status": "answer", "option": 1, "why": "…"} — or "options": [1, 3], or "text": "…"; for a plan {"status": "answer", "decision": "approve"} or "revise" with "note"; for a subtask {"status": "answer", "option": 1}',
160
+ 'or {"status": "ask", "question": "…", "why": "…", "options": ["…", "…"]} — to a card: {"status": "ask", "why": "…", "suggestion": "…"}',
161
+ 'or {"status": "done", "report": "what was done, what shows it, what is left", "evidence": ["…"]}',
162
+ 'or {"status": "blocked", "summary": "what was done and found", "needed": "what would let it go on"}',
163
+ ].join('\n');
164
+ /** The message that asks her for the same answer again, in the format. */
165
+ export function kerriganFormatErrorMessage(fail, attempt, maxAttempts) {
166
+ return [
167
+ `Your last reply did not match Kerrigan's format (format retry ${attempt} of ${maxAttempts}).`,
168
+ fail.reason === 'no-json-block' ? 'There was no fenced json code block in it.' : `The json block did not validate: ${fail.detail}`,
169
+ 'Only the format is wrong: nothing from that reply was acted on. Send the same answer again, reformatted, as exactly one fenced code block tagged json. For example:',
170
+ EXAMPLE,
171
+ ].join('\n');
172
+ }
173
+ /** A first reply without the assignment restated. */
174
+ export const KERRIGAN_UNDERSTANDING_FIRST = 'Before anything else, restate the person\'s assignment in "understanding": the goal, the result they want and its form, ' +
175
+ 'the constraints, and how it will be known to be done. Send your reply again with it; nothing from the last one was acted on.';
@@ -103,7 +103,11 @@ export function whyItStopped(c) {
103
103
  }
104
104
  if (c.how === 'stopped') {
105
105
  const where = c.interruption ? `\n\n${describeInterruption(c.interruption).replace(/when the runner stopped/g, 'when it was stopped')}\n\n` : ' ';
106
- return `It was stopped by the operator before it finished — not because anything failed. The files are as you left them.${where}`.trimEnd();
106
+ // The window closed under it (2026-11-13): said as that, in the runner's own words, not as the operator's Stop.
107
+ const first = /browser window/.test(c.stoppedBecause ?? '')
108
+ ? `It stopped because the browser window this conversation is in was closed (${c.stoppedBecause}) — not because anything failed.`
109
+ : 'It was stopped by the operator before it finished — not because anything failed.';
110
+ return `${first} The files are as you left them.${where}`.trimEnd();
107
111
  }
108
112
  const why = c.stoppedBecause ? ` (${c.stoppedBecause})` : '';
109
113
  // Out of rounds of fixing: something did say no, and the chat needs to hear it was not waved through.
@@ -120,6 +120,8 @@ export const TASK_FIELD_ON_RERUN = {
120
120
  // The lead's rounds belong to the attempt that made them (two chats, 2026-10-20); which lead a subtask serves, to the task.
121
121
  lead: 'archived',
122
122
  fromLead: 'kept',
123
+ kerrigan: 'archived',
124
+ fromKerrigan: 'kept',
123
125
  // The kind of task it is: every attempt is sent with the same skill.
124
126
  skill: 'kept',
125
127
  interruption: 'cleared',
@@ -225,6 +227,10 @@ export class SessionStore {
225
227
  async getLead1() {
226
228
  return { content: await readFile(join(dirname(this.defaultLevel1Path), 'lead1.md'), 'utf8') };
227
229
  }
230
+ /** Kerrigan's contract (2026-11-12), when she directs a conversation herself: `prompts/kerrigan1.md`. */
231
+ async getKerrigan1() {
232
+ return { content: await readFile(join(dirname(this.defaultLevel1Path), 'kerrigan1.md'), 'utf8') };
233
+ }
228
234
  // --- the model catalogue ----------------------------------------------------------------
229
235
  /** What the chat's picker offered when it was last read, or null if it never was. */
230
236
  async getModels() {
@@ -606,6 +612,8 @@ export class SessionStore {
606
612
  accepted: t.accepted,
607
613
  // Two chats: the lead's rounds and subtasks of this attempt (the next one counts its own from nothing).
608
614
  lead: t.lead,
615
+ // Kerrigan's rounds of this attempt (2026-11-12), as the lead's.
616
+ kerrigan: t.kerrigan,
609
617
  },
610
618
  ];
611
619
  // An edit is applied only after the old attempt has been put beyond its reach.
@@ -644,6 +652,7 @@ export class SessionStore {
644
652
  t.plan = undefined;
645
653
  t.accepted = undefined;
646
654
  t.lead = undefined;
655
+ t.kerrigan = undefined;
647
656
  t.scopeReverted = undefined;
648
657
  t.treeChanged = undefined;
649
658
  t.inputsRestored = undefined;
@@ -20,12 +20,16 @@
20
20
  * running in this process — a check script — can call `setTransportFactory`.
21
21
  */
22
22
  import { CopilotTransport } from './copilotTransport.js';
23
+ import { keptWindow } from './keptWindow.js';
23
24
  export { ReplyTimeoutError, isReplyTimeout, WindowClosed, ChatLost } from './copilotTransport.js';
24
25
  const realChat = (opts) => new CopilotTransport(opts);
25
26
  let factory = realChat;
26
- /** A chat for these options: the real Copilot window, unless a check has put a scripted one in. */
27
+ /**
28
+ * A chat for these options: the real Copilot window, unless a check has put a scripted one in — either way kept for the
29
+ * work by the same rules (see keptWindow.ts).
30
+ */
27
31
  export function createTransport(opts) {
28
- return factory(opts);
32
+ return keptWindow(factory, opts);
29
33
  }
30
34
  /** For checks only: every chat opened from now on comes from `f`. `null` puts the real one back. */
31
35
  export function setTransportFactory(f) {
@@ -38,7 +38,6 @@ export class ReplyTimeoutError extends Error {
38
38
  export function isReplyTimeout(e) {
39
39
  return e instanceof ReplyTimeoutError || (e instanceof Error && e.name === 'ReplyTimeoutError' && typeof e.seconds === 'number');
40
40
  }
41
- const ORIGIN = 'https://m365.cloud.microsoft';
42
41
  /**
43
42
  * Which Copilot an address is, by its host — not by whether the text appears anywhere in it: the
44
43
  * consumer Copilot and a sign-in page carry the work chat's address in their query (`ru=`,
@@ -62,6 +61,21 @@ export function surfaceOfUrl(url) {
62
61
  return 'work';
63
62
  return 'unknown';
64
63
  }
64
+ /** Whether an address is the work Copilot's chat — a new chat, a conversation, the list of chats — on either of its hosts. */
65
+ export function isWorkChatAddress(url) {
66
+ if (surfaceOfUrl(url) !== 'work')
67
+ return false;
68
+ const path = new URL(url).pathname.replace(/\/+$/, '');
69
+ return path === '/chat' || path.startsWith('/chat/');
70
+ }
71
+ /**
72
+ * Whether an address is another page of the work Copilot, not its chat: its home page
73
+ * (`copilot.cloud.microsoft/home?es=SSR&redirfrom=mcmToCcm`, where the work machine's start ended on 2026-11-17), or any
74
+ * other of its own. Signed in, then — a sign-in page is on Microsoft's sign-in host — and only away from the chat.
75
+ */
76
+ export function isCopilotOtherPage(url) {
77
+ return surfaceOfUrl(url) === 'work' && !isWorkChatAddress(url);
78
+ }
65
79
  /**
66
80
  * The operator's locators for a model, from the templates in force and where the list read from the page found it
67
81
  * (operator, 2026-10-24): a model of the main menu by the template for those; one in a provider's menu by the
@@ -140,6 +154,13 @@ export class WindowClosed extends Error {
140
154
  this.name = 'WindowClosed';
141
155
  }
142
156
  }
157
+ /** Said when a window closed under the work cannot be put back on its conversation: it had no address yet. */
158
+ export const NO_ADDRESS_YET = 'the browser window was closed before its conversation had an address, so it could not be found again; nothing more was sent';
159
+ /** How many times Edge is started again on the profile when a window is reopened, and the pause between (see `reopen`). */
160
+ const REOPEN_TRIES = 10;
161
+ const REOPEN_PAUSE_MS = 1_500;
162
+ /** How long the box is waited for on the work Copilot's host before the page is said not to be its chat. */
163
+ const SURFACE_WAIT_MS = 5_000;
143
164
  /**
144
165
  * The window had left the conversation the bot put it on, and could not be put back (operator, 2026-11-09; see
145
166
  * `ensureOnChat`): the conversation does not open again, or the sign-in the page asked for first was not done in time.
@@ -289,11 +310,22 @@ export class CopilotTransport {
289
310
  chatNames = new Map();
290
311
  /** How long a page is given to show the composer before it is taken to be asking for a sign-in. */
291
312
  firstLookMs = 15_000;
313
+ /**
314
+ * The host the chat was last found on, which the chat's addresses are opened on (2026-11-17): the address set in
315
+ * Settings when it is the work Copilot's, else the old host, until the chat is found on the new one. Going through
316
+ * the old host's redirect is what ended the work machine's start on Copilot's home page.
317
+ */
318
+ chatOrigin;
319
+ /** How long the box to write in must stay before the page is taken for the chat: one that showed on its way elsewhere is not. */
320
+ settleMs = 2_000;
321
+ /** How long another page of the work Copilot is given to turn into its chat on its own before the bot opens the chat. */
322
+ otherPageMs = 3_000;
292
323
  constructor(opts) {
293
324
  this.opts = opts;
294
325
  const { locators, problems } = resolvePickerLocators(opts.pickerLocators);
295
326
  this.locators = locators;
296
327
  this.locatorProblems = problems;
328
+ this.chatOrigin = surfaceOfUrl(opts.chatUrl) === 'work' ? new URL(opts.chatUrl).origin : Url.origin;
297
329
  }
298
330
  /** Says, once, which locators saved in Settings could not be used and why. */
299
331
  sayLocatorProblems() {
@@ -396,6 +428,41 @@ export class CopilotTransport {
396
428
  closedOutside() {
397
429
  return this.gone;
398
430
  }
431
+ /**
432
+ * The window again, after it was closed under the work (operator, 2026-11-13: "if I close the browser with the chat by
433
+ * accident, the bot should carry the task on from where it got to"). Edge is started again on the same profile, and
434
+ * the window put back on the conversation it was on: by its address, after a sign-in when the page asks for one, or by
435
+ * its name in the sidebar (see `ensureOnChat`). The Edge that was closed may still be on its way out and holding the
436
+ * profile, so the start is tried again for a while. A conversation that had no address yet — closed before its first
437
+ * answer — cannot be found again: `WindowClosed`, with the new window open on nothing. When and how often this is done
438
+ * is the runner's (`KeptWindow` in keptWindow.ts); this only does it.
439
+ */
440
+ async reopen(opts = {}) {
441
+ // What `close` leaves alone, kept: the conversation the window was on, and the names given to conversations.
442
+ const want = this.onChat;
443
+ await this.close();
444
+ for (let tries = 1;; tries += 1) {
445
+ try {
446
+ await this.open();
447
+ break;
448
+ }
449
+ catch (e) {
450
+ await this.close().catch(() => undefined);
451
+ const busy = /already running with this profile|already in use by copilot-operator/i.test(e.message);
452
+ if (!busy || tries >= REOPEN_TRIES || opts.signal?.aborted)
453
+ throw e;
454
+ await new Promise((r) => setTimeout(r, REOPEN_PAUSE_MS));
455
+ }
456
+ }
457
+ this.onChat = want;
458
+ if (!want || want === 'new')
459
+ throw new WindowClosed(NO_ADDRESS_YET);
460
+ await this.p.goto(this.chatAddress(Url.conversationPath(want.id)), { waitUntil: 'domcontentloaded' }).catch(() => undefined);
461
+ // On it, as nearly always: waited for until its box is there to write in. Elsewhere (a sign-in): `ensureOnChat`.
462
+ if (parseChatId(this.p.url()) === want.id)
463
+ await this.composerWithin(this.firstLookMs, opts.signal, 'stopped by the operator while the window was opened again');
464
+ return await this.ensureOnChat(opts);
465
+ }
399
466
  /**
400
467
  * A card over the chat's page with one button that takes it away (2026-10-19: "when the chat is done, let the
401
468
  * browser show a message — the task has finished — and an OK under it"). The window of the workbench's chat is
@@ -510,6 +577,115 @@ export class CopilotTransport {
510
577
  }
511
578
  }
512
579
  }
580
+ /** One of the chat's addresses (`Url.newChatPath`, `Url.conversationPath`) on the host the chat was last found on. */
581
+ chatAddress(path) {
582
+ return `${this.chatOrigin}${path}`;
583
+ }
584
+ /** Keeps the host the page is on when it is one of the chat's addresses: the chat's addresses are opened there from then on. */
585
+ learnChatOrigin() {
586
+ const url = this.p.url();
587
+ if (isWorkChatAddress(url))
588
+ this.chatOrigin = new URL(url).origin;
589
+ }
590
+ /** Whether the box to write in is still there, on the same page, after `settleMs`: one that showed on the way elsewhere is not. */
591
+ async boxStays() {
592
+ const at = whereIs(this.p.url());
593
+ await this.p.waitForTimeout(this.settleMs);
594
+ return whereIs(this.p.url()) === at && (await this.composer().isVisible().catch(() => false));
595
+ }
596
+ /**
597
+ * After the window was sent to the chat (`path`, one of its addresses): whether it got there. Operator, 2026-11-17:
598
+ * the start ended on "The page is not the Microsoft 365 Copilot chat" at
599
+ * `copilot.cloud.microsoft/home?es=SSR&redirfrom=mcmToCcm` — the box to write in had shown, and a few seconds later the
600
+ * page was Copilot's home page, with none, and the bot neither waited nor went to the chat from there.
601
+ *
602
+ * - `chat`: the box is there and stays (`boxStays`). The host it is on is the chat's from then on (`learnChatOrigin`).
603
+ * - `elsewhere`: the page is another of the work Copilot's own (`isCopilotOtherPage`), and stayed one after the chat
604
+ * was opened from it — by `path` on the page's own host, then, for a new chat, by the page's link to its chat. It
605
+ * is not a sign-in, and is not waited on as one.
606
+ * - `no-box`: anything else with no box within `firstLookMs` — a sign-in page, the consumer Copilot, a chat slow to
607
+ * load — left to the caller, as before.
608
+ *
609
+ * Looked at a second at a time, so a Stop ends it at once; another of Copilot's pages is given `otherPageMs` to turn
610
+ * into the chat on its own, not the whole first look.
611
+ */
612
+ async arrive(path, signal, stopped) {
613
+ for (let move = 0;; move += 1) {
614
+ const until = Date.now() + this.firstLookMs;
615
+ let otherSince = 0;
616
+ for (;;) {
617
+ if ((await this.composerWithin(Math.max(1, Math.min(1_000, until - Date.now())), signal, stopped)) && (await this.boxStays())) {
618
+ this.learnChatOrigin();
619
+ return 'chat';
620
+ }
621
+ const other = isCopilotOtherPage(this.p.url());
622
+ otherSince = other ? otherSince || Date.now() : 0;
623
+ if (other && Date.now() - otherSince >= this.otherPageMs)
624
+ break;
625
+ if (Date.now() >= until) {
626
+ if (other)
627
+ break;
628
+ return 'no-box';
629
+ }
630
+ }
631
+ if (move >= 2)
632
+ return 'elsewhere';
633
+ const found = whereIs(this.p.url());
634
+ if (move === 0) {
635
+ const to = `${new URL(this.p.url()).origin}${path}`;
636
+ this.emit('chat-page-elsewhere', { found, by: 'address', to: whereIs(to) });
637
+ await this.p.goto(to, { waitUntil: 'domcontentloaded' });
638
+ }
639
+ else {
640
+ // A conversation's address is the only way to it: a link to the chat would open a new one.
641
+ if (path !== Url.newChatPath)
642
+ return 'elsewhere';
643
+ const link = await this.chatLink();
644
+ if (!link)
645
+ return 'elsewhere';
646
+ this.emit('chat-page-elsewhere', { found, by: 'link', to: whereIs(link.href) });
647
+ await link.at.click({ timeout: 5_000 }).catch(() => undefined);
648
+ }
649
+ }
650
+ }
651
+ /**
652
+ * The page's own link to its chat, for another of Copilot's pages that the chat's address did not get past: an anchor
653
+ * on the page's host to `/chat`, shown, and opening in this window. Nothing else on the page is clicked.
654
+ */
655
+ async chatLink() {
656
+ const found = await this.p
657
+ .evaluate(() => {
658
+ const links = [...document.querySelectorAll('a[href]')];
659
+ const i = links.findIndex((a) => {
660
+ let u;
661
+ try {
662
+ u = new URL(a.href);
663
+ }
664
+ catch {
665
+ return false;
666
+ }
667
+ const box = a.getBoundingClientRect();
668
+ const shown = box.width > 0 && box.height > 0 && getComputedStyle(a).visibility !== 'hidden';
669
+ return u.origin === location.origin && u.pathname.replace(/\/+$/, '') === '/chat' && (!a.target || a.target === '_self') && shown;
670
+ });
671
+ return i < 0 ? null : { i, href: links[i].href };
672
+ })
673
+ .catch(() => null);
674
+ return found ? { at: this.p.locator('a[href]').nth(found.i), href: found.href } : null;
675
+ }
676
+ /**
677
+ * The error for a window that would not go to the chat from another of Copilot's pages (`arrive`'s `elsewhere`), with
678
+ * a picture of the page — a screenshot always, its HTML when Settings keep it — so the next look is at what it showed.
679
+ */
680
+ async notTheChat() {
681
+ const url = this.p.url();
682
+ const dir = join(this.opts.transportDir, '..', 'failures');
683
+ const tag = `not-the-chat-${Date.now()}`;
684
+ await this.dumpFailure(dir, tag).catch(() => undefined);
685
+ return new Error(`Copilot showed its page ${whereIs(url)} instead of the chat, and the chat did not open from there ` +
686
+ `(by its address on that host, nor by a link to it on the page). Nothing was sent. A picture of the page: ${join(dir, `${tag}.png`)}
687
+ Current URL: ${url}`);
688
+ }
513
689
  /**
514
690
  * Which Copilot we actually landed on.
515
691
  *
@@ -579,9 +755,17 @@ export class CopilotTransport {
579
755
  this.onChat = null;
580
756
  await this.p.goto(target.toString(), { waitUntil: 'domcontentloaded' });
581
757
  }
582
- /** Throws with an explanation when the profile is not on the work Copilot. */
758
+ /**
759
+ * Throws with an explanation when the profile is not on the work Copilot. On the work Copilot's host with no box to
760
+ * write in, the box is waited for a few seconds rather than looked for once (2026-11-17: the page was changing); a
761
+ * page that is still not the chat leaves a picture of itself, since its address alone does not say what it showed.
762
+ */
583
763
  async assertWorkSurface() {
584
- const where = await this.surface();
764
+ let where = await this.surface();
765
+ if (where === 'unknown' && surfaceOfUrl(this.p.url()) === 'work') {
766
+ await this.composerWithin(SURFACE_WAIT_MS, undefined, '');
767
+ where = await this.surface();
768
+ }
585
769
  if (where === 'work')
586
770
  return;
587
771
  const url = this.p.url();
@@ -592,7 +776,14 @@ export class CopilotTransport {
592
776
  'sign-in': 'The profile is signed out. Run "cop login".',
593
777
  unknown: 'The page is not the Microsoft 365 Copilot chat.',
594
778
  };
595
- throw new Error(`${explain[where] ?? explain.unknown}
779
+ let picture = '';
780
+ if (where === 'unknown') {
781
+ const dir = join(this.opts.transportDir, '..', 'failures');
782
+ const tag = `not-the-chat-${Date.now()}`;
783
+ await this.dumpFailure(dir, tag).catch(() => undefined);
784
+ picture = ` A picture of the page: ${join(dir, `${tag}.png`)}`;
785
+ }
786
+ throw new Error(`${explain[where] ?? explain.unknown}${picture}
596
787
  Current URL: ${url}`);
597
788
  }
598
789
  /**
@@ -694,29 +885,48 @@ Current URL: ${url}`);
694
885
  * ends the wait at once, rather than after the whole sign-in timeout, fifteen minutes by default (2026-10-17).
695
886
  */
696
887
  const stoppedHere = 'stopped by the operator while waiting for the sign-in';
697
- if (!(await this.composerWithin(this.firstLookMs, opts.signal, stoppedHere))) {
888
+ /*
889
+ * The chat; or another of Copilot's own pages, which the chat is opened from (2026-11-17: Copilot's home page, where
890
+ * the work machine's start ended); or a page asking for a sign-in, the only one waited on for the operator.
891
+ */
892
+ let at = await this.arrive(Url.newChatPath, opts.signal, stoppedHere);
893
+ if (at === 'no-box') {
698
894
  this.emit('sign-in-required', { url: this.p.url() });
699
895
  if (!(await this.composerWithin(this.opts.signInTimeoutMs, opts.signal, stoppedHere))) {
700
896
  throw new Error(`The sign-in was not completed within ${Math.round(this.opts.signInTimeoutMs / 1000)} s (Settings → copilot.signInTimeoutSec). ` +
701
897
  'Sign in in the open Edge window, then start again.');
702
898
  }
703
899
  this.emit('signed-in');
900
+ // A sign-in may come back to Copilot's home page rather than to its chat.
901
+ at = await this.arrive(Url.newChatPath, opts.signal, stoppedHere);
704
902
  }
903
+ if (at === 'elsewhere')
904
+ throw await this.notTheChat();
705
905
  await this.clearBlockers();
906
+ // The page may have moved on while the blockers were looked at, as the work machine's did: once more to the chat.
907
+ if ((await this.surface()) !== 'work' && (await this.arrive(Url.newChatPath, opts.signal, stoppedHere)) === 'elsewhere') {
908
+ throw await this.notTheChat();
909
+ }
706
910
  await this.assertWorkSurface();
707
911
  }
708
912
  async newChat() {
709
913
  this.onChat = null;
710
- await this.p.goto(Url.newChat, { waitUntil: 'domcontentloaded' });
711
- await this.composer().waitFor({ state: 'visible' });
914
+ await this.p.goto(this.chatAddress(Url.newChatPath), { waitUntil: 'domcontentloaded' });
915
+ // Another of Copilot's pages instead (2026-11-17): the chat opened from it, and said so when it would not.
916
+ if ((await this.arrive(Url.newChatPath, undefined, '')) === 'elsewhere')
917
+ throw await this.notTheChat();
918
+ // A chat slow to load: the rest of the minute it was always given (the page's default timeout).
919
+ await this.composer().waitFor({ state: 'visible', timeout: 45_000 });
712
920
  await this.dismissPopups();
713
921
  this.onChat = 'new';
714
922
  }
715
923
  /** Reopens a conversation by its id. Returns false when it no longer opens. */
716
924
  async openConversation(chatId) {
717
925
  this.onChat = null;
718
- await this.p.goto(Url.conversation(chatId), { waitUntil: 'domcontentloaded' });
719
- if (!(await this.isChatReady(20_000)))
926
+ const path = Url.conversationPath(chatId);
927
+ await this.p.goto(this.chatAddress(path), { waitUntil: 'domcontentloaded' });
928
+ const at = await this.arrive(path, undefined, '');
929
+ if (at === 'elsewhere' || (at === 'no-box' && !(await this.isChatReady(5_000))))
720
930
  return false;
721
931
  const there = parseChatId(this.p.url()) === chatId;
722
932
  if (there)
@@ -788,9 +998,14 @@ Current URL: ${url}`);
788
998
  this.emit('chat-left', { chatId: want.id, found: from });
789
999
  const stopped = 'stopped by the operator while waiting for the sign-in';
790
1000
  let signedIn = false;
1001
+ const path = Url.conversationPath(want.id);
791
1002
  for (let tries = 0; tries < 3; tries += 1) {
792
- await this.p.goto(Url.conversation(want.id), { waitUntil: 'domcontentloaded' });
793
- if (await this.composerWithin(this.firstLookMs, opts.signal, stopped)) {
1003
+ await this.p.goto(this.chatAddress(path), { waitUntil: 'domcontentloaded' });
1004
+ // Another of Copilot's pages, the conversation's address not getting past it (2026-11-17): by its name, not a sign-in.
1005
+ const at = await this.arrive(path, opts.signal, stopped);
1006
+ if (at === 'elsewhere')
1007
+ break;
1008
+ if (at === 'chat') {
794
1009
  if (parseChatId(this.p.url()) !== want.id)
795
1010
  break;
796
1011
  this.onChat = want;