copilot-operator 0.1.66 → 0.1.68

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 (61) hide show
  1. package/dist/src/api/operator.controller.js +9 -2
  2. package/dist/src/api/operator.service.js +23 -7
  3. package/dist/src/cli.js +1 -0
  4. package/dist/src/config/schema.js +7 -0
  5. package/dist/src/exec/authorizer.js +26 -6
  6. package/dist/src/exec/commandHeads.js +30 -6
  7. package/dist/src/exec/platforms.js +13 -2
  8. package/dist/src/exec/policy.js +32 -5
  9. package/dist/src/exec/policyManifest.js +9 -0
  10. package/dist/src/exec/readOnly.js +158 -0
  11. package/dist/src/exec/scriptFiles.js +91 -9
  12. package/dist/src/orchestrator/handoff.js +79 -0
  13. package/dist/src/orchestrator/taskRunner.js +43 -2
  14. package/dist/src/plan/kerrigan.js +5 -1
  15. package/dist/src/plan/systemGuide.js +95 -0
  16. package/dist/src/protocol/parser.js +2 -2
  17. package/dist/src/protocol/replySchema.js +23 -2
  18. package/dist/src/queue/queue.js +6 -0
  19. package/dist/web/404.html +2 -2
  20. package/dist/web/_next/static/chunks/1024-e4e596b184e05e91.js +1 -0
  21. package/dist/web/_next/static/chunks/1077.61be1f7b74828a4c.js +1 -0
  22. package/dist/web/_next/static/chunks/1548.a112748131a396ed.js +1 -0
  23. package/dist/web/_next/static/chunks/2163.581b2e067fe95eb3.js +1 -0
  24. package/dist/web/_next/static/chunks/714.5cc35e9440591fd9.js +1 -0
  25. package/dist/web/_next/static/chunks/7220.9313ff4ad7480f12.js +1 -0
  26. package/dist/web/_next/static/chunks/7921-19f36659bdea8d09.js +1 -0
  27. package/dist/web/_next/static/chunks/8124-1952612d3a681879.js +1 -0
  28. package/dist/web/_next/static/chunks/8584.5ff9e8c49bf9b259.js +1 -0
  29. package/dist/web/_next/static/chunks/9067.f0db4983b81a2df6.js +1 -0
  30. package/dist/web/_next/static/chunks/9747.0e0c54e5f8fab6c4.js +1 -0
  31. package/dist/web/_next/static/chunks/app/page-18954867735bf8c0.js +1 -0
  32. package/dist/web/_next/static/chunks/app/settings/page-7d120feb5af0ace9.js +1 -0
  33. package/dist/web/_next/static/chunks/{webpack-5ea108bc2e386c55.js → webpack-a3dd4e873378e9ae.js} +1 -1
  34. package/dist/web/_next/static/css/{a112074f3d1a8a07.css → 45da8a97dbf20586.css} +1 -1
  35. package/dist/web/defaults.html +2 -2
  36. package/dist/web/defaults.txt +8 -8
  37. package/dist/web/index.html +3 -3
  38. package/dist/web/index.txt +9 -9
  39. package/dist/web/queue.html +2 -2
  40. package/dist/web/queue.txt +9 -9
  41. package/dist/web/settings.html +2 -2
  42. package/dist/web/settings.txt +9 -9
  43. package/dist/web/system.html +2 -2
  44. package/dist/web/system.txt +9 -9
  45. package/package.json +4 -2
  46. package/prompts/level1.md +53 -14
  47. package/dist/web/_next/static/chunks/1024-444e9060299d04ba.js +0 -1
  48. package/dist/web/_next/static/chunks/1077.b88b069535f7008e.js +0 -1
  49. package/dist/web/_next/static/chunks/1548.9e01803e48173ea9.js +0 -1
  50. package/dist/web/_next/static/chunks/2163.018cd5f719ae4b3d.js +0 -1
  51. package/dist/web/_next/static/chunks/714.281f68f85df26013.js +0 -1
  52. package/dist/web/_next/static/chunks/7220.3bd10a3e4e053e0c.js +0 -1
  53. package/dist/web/_next/static/chunks/7921-1c173d00d23b3589.js +0 -1
  54. package/dist/web/_next/static/chunks/8124-bb544c96a7c0e7e3.js +0 -1
  55. package/dist/web/_next/static/chunks/8584.c7cd52c2e7075bcb.js +0 -1
  56. package/dist/web/_next/static/chunks/9067.feaf894390db1a88.js +0 -1
  57. package/dist/web/_next/static/chunks/9747.7cee8a2d8301f25c.js +0 -1
  58. package/dist/web/_next/static/chunks/app/page-95379244849623fc.js +0 -1
  59. package/dist/web/_next/static/chunks/app/settings/page-9a83381087178f80.js +0 -1
  60. /package/dist/web/_next/static/{BbWvNQTsh3pH7ZN_RKR60 → 52rfiQXdaggycbuMIIw4K}/_buildManifest.js +0 -0
  61. /package/dist/web/_next/static/{BbWvNQTsh3pH7ZN_RKR60 → 52rfiQXdaggycbuMIIw4K}/_ssgManifest.js +0 -0
@@ -31,6 +31,7 @@
31
31
  import { existsSync, readFileSync, statSync } from 'node:fs';
32
32
  import { dirname, isAbsolute, relative, resolve } from 'node:path';
33
33
  import { gitSync, RUNNER_EMAIL } from '../vcs/git.js';
34
+ import { scanCommandHeads } from './commandHeads.js';
34
35
  /** Larger than this is not a step's script; it is not read, and running it is refused. */
35
36
  const MAX_SCRIPT_BYTES = 256 * 1024;
36
37
  /** Paths of PowerShell scripts this command line runs, as written. */
@@ -162,26 +163,107 @@ export function notTheProjects(file, since) {
162
163
  return 'it was committed after this work began, so it was written during the work';
163
164
  return null;
164
165
  }
166
+ /** The runtimes a file of code is given to, by the program's name. */
167
+ const CODE_RUNTIMES = new Set(['node', 'nodejs', 'tsx', 'ts-node', 'ts-node-esm', 'python', 'python3', 'pythonw', 'py', 'deno', 'bun', 'ruby', 'perl', 'php']);
168
+ /** What a package runner starts that runs a file of code: `npx ts-node x.ts`, `npx tsx x.ts`. */
169
+ const RUN_THROUGH = new Set(['npx', 'pnpx', 'bunx']);
170
+ const CODE_FILE = /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx|py|pyw|rb|pl|php)$/i;
171
+ /**
172
+ * The files of code a line gives straight to a runtime (2026-10-26): `node tools/x.js`, `npx ts-node tools/x.ts`,
173
+ * `tsx x.ts`, `python x.py`, `deno run x.ts`, as full paths. The first argument that is not a switch is the file; a
174
+ * line whose first one is not a file of code (`node --version`, `python -m pytest`) gives none. The project's test
175
+ * runners are not this (operator, 2026-10-26: "tests as before"): `node --test` is left alone, as are `npm test`,
176
+ * `npx playwright test` and the rest, which are not runtimes given a file.
177
+ */
178
+ export function codeFilesRun(command, cwd, shell) {
179
+ const files = new Set();
180
+ for (const call of scanCommandHeads(command, shell ?? 'pwsh').calls) {
181
+ let program = call.head.replace(/^.*[\\/]/, '').replace(/\.(?:exe|cmd)$/i, '').toLowerCase();
182
+ let args = call.args;
183
+ if (RUN_THROUGH.has(program)) {
184
+ const first = args.findIndex((a) => !a.literal.startsWith('-'));
185
+ if (first < 0)
186
+ continue;
187
+ program = args[first].literal.toLowerCase();
188
+ args = args.slice(first + 1);
189
+ }
190
+ if (!CODE_RUNTIMES.has(program))
191
+ continue;
192
+ if (args.some((a) => /^--test\b/.test(a.literal)))
193
+ continue;
194
+ const rest = (program === 'deno' || program === 'bun') && args[0]?.literal === 'run' ? args.slice(1) : args;
195
+ const file = rest.find((a) => !a.literal.startsWith('-'));
196
+ if (!file || file.dynamic || !CODE_FILE.test(file.literal))
197
+ continue;
198
+ files.add(isAbsolute(file.literal) ? file.literal : resolve(cwd, file.literal));
199
+ }
200
+ return [...files];
201
+ }
202
+ /**
203
+ * Why a file of code was written during this work, or null when it was the project's before the work began: added
204
+ * to the repository by someone else before then, or, not committed, made on disk before then. A file of the project
205
+ * changed by the work is still the project's — the application started after a change is the work, run the way the
206
+ * project runs it; a file that was not there is a script the work wrote.
207
+ */
208
+ export function writtenDuringTheWork(file, since) {
209
+ if (!existsSync(file))
210
+ return null;
211
+ const began = since ? Date.parse(since) : NaN;
212
+ const top = gitSync(dirname(file), ['rev-parse', '--show-toplevel']);
213
+ if (top.ok && top.stdout) {
214
+ const rel = relative(top.stdout, file);
215
+ const path = rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel.replace(/\\/g, '/') : file;
216
+ const added = gitSync(top.stdout, ['log', '--diff-filter=A', '--format=%ae%x09%ct', '-1', '--', path]);
217
+ if (added.ok && added.stdout.trim()) {
218
+ const [email = '', time = ''] = added.stdout.trim().split('\t');
219
+ if (email.trim().toLowerCase() === RUNNER_EMAIL)
220
+ return 'it was added by copilot-operator, so it was written during the work';
221
+ if (Number.isFinite(began) && Number(time) * 1000 >= began - 1000)
222
+ return 'it was added after this work began';
223
+ return null;
224
+ }
225
+ }
226
+ if (!Number.isFinite(began))
227
+ return 'it is not committed, and nothing tells when it was written';
228
+ let born = NaN;
229
+ try {
230
+ born = statSync(file).birthtimeMs;
231
+ }
232
+ catch {
233
+ /* unreadable: the runtime will say so */
234
+ }
235
+ return Number.isFinite(born) && born >= began - 1000 ? 'it was made after this work began and is not committed' : null;
236
+ }
165
237
  /**
166
238
  * Why a chat's step must not run a script, or null: a shell script that is not one of the project's own (see
167
- * `notTheProjects`), or any file in `.cop-tmp` given to a program that runs it. Only for the chat's steps, the
168
- * implementer's and the reviewer's: the operator's own checks are theirs to point at whatever they choose.
239
+ * `notTheProjects`), a file of code written during the work given to a runtime (see `writtenDuringTheWork`), or any
240
+ * file in `.cop-tmp` given to a program that runs it. Every one of them is the operator's to run (2026-10-26), and the
241
+ * chat is told to hand it over. Only for the chat's steps, the implementer's and the reviewer's: the operator's own
242
+ * checks are theirs to point at whatever they choose.
169
243
  */
170
- export function ownScriptRefusal(command, cwd, since) {
244
+ export function ownScriptRefusal(command, cwd, since, shell) {
171
245
  // A file of code in it, given to a program that runs files — not its output written there (`node x.js > .cop-tmp\out.txt`).
172
246
  const scratch = new RegExp(String.raw `\b${RUNS_A_FILE}(?:\.exe|\.cmd)?\b[^|;\n]*?(?:^|[\s'"=(,:])(?:\.[\\/])?(?:[^\s'"|;]*[\\/])?\.cop-tmp[\\/][^\s'"|;]*\.(?:ps1|psm1|cmd|bat|js|mjs|cjs|jsx|ts|mts|cts|tsx|py|rb|pl|php|vbs|vbe|wsf|sh|jar|dll|exe|csx)\b`, 'i');
173
247
  const why = (file, reason) => `refused: ${relative(cwd, file) || file} is not one of the project's own scripts — ${reason}. A script written or ` +
174
- 'changed during the work is not run, nor anything in .cop-tmp (the operator\'s rule). Put what it does in the ' +
175
- 'step itself: a command may be several lines. If the script is meant to be part of the project, say so in "notes", ' +
176
- 'and the operator can commit it.';
248
+ 'changed during the work is run by the operator, not by the runner, nor is anything in .cop-tmp (the operator\'s rule). ' +
249
+ HAND_IT_OVER;
250
+ if (scratch.test(command)) {
251
+ return 'refused: this runs a file in .cop-tmp, the folder for scratch files — the runner runs nothing there (the operator\'s rule). ' + HAND_IT_OVER;
252
+ }
177
253
  for (const file of shellScriptsRun(command, cwd)) {
178
254
  const reason = notTheProjects(file, since);
179
255
  if (reason)
180
256
  return why(file, reason);
181
257
  }
182
- if (scratch.test(command)) {
183
- return ('refused: this runs a file in .cop-tmp, the folder for scratch files — nothing there is run (the operator\'s rule). ' +
184
- 'Put what it does in the step itself: a command may be several lines.');
258
+ for (const file of codeFilesRun(command, cwd, shell)) {
259
+ const reason = writtenDuringTheWork(file, since);
260
+ if (reason) {
261
+ return (`refused: ${relative(cwd, file) || file} is a script written during this work — ${reason} — and such a script is run by ` +
262
+ 'the operator, not by the runner (the operator\'s rule). ' + HAND_IT_OVER + ' The project\'s tests run as steps, as before.');
263
+ }
185
264
  }
186
265
  return null;
187
266
  }
267
+ /** What the chat is told to do instead (2026-10-26). */
268
+ const HAND_IT_OVER = 'Put what it does in the step itself — a command may be several lines — or hand it to the operator with status "handoff": ' +
269
+ 'the commands, the folder, what they should see and the script; the operator runs it and you get what it printed.';
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Commands the operator runs themselves (operator, 2026-10-26: "the script is made, but the user runs it; the bot gives
3
+ * the commands for the user to run and the result it expects"). The runner never runs a script written during the
4
+ * work (`exec/scriptFiles.ts`); the chat hands it over with `"status": "handoff"` and the operator gets a card: the
5
+ * lines in order, the folder, what should be seen, and the script files they run, read from disk with their SHA-256,
6
+ * so what the operator reads is what they run. A line the runner would refuse outright is marked on the card: the
7
+ * card is not a way round the rules, and the operator is told so before running it in their own terminal.
8
+ *
9
+ * What the operator sends back goes to the chat in the same words wherever it was answered: on the card in the
10
+ * conversation, or on a queue task's card answered after it was set aside.
11
+ */
12
+ import { createHash } from 'node:crypto';
13
+ import { existsSync, readFileSync, statSync } from 'node:fs';
14
+ import { isAbsolute, relative, resolve } from 'node:path';
15
+ import { dangerousRefusal } from '../exec/dangerous.js';
16
+ import { botSelfRefusal } from '../exec/network.js';
17
+ import { matchDenyPattern } from '../exec/policy.js';
18
+ /** The most of one script shown on the card; its hash is of all of it. */
19
+ const MAX_SHOWN_BYTES = 64 * 1024;
20
+ /** A script larger than this is not read for the card at all. */
21
+ const MAX_READ_BYTES = 4 * 1024 * 1024;
22
+ const inside = (roots, path) => roots.some((root) => {
23
+ const rel = relative(root, path);
24
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
25
+ });
26
+ /** The card for a handoff: the folder resolved in the project, each script read with its hash, the lines the runner refuses. */
27
+ export function handoffCard(h, cwd, roots, denyPatterns) {
28
+ const folder = resolve(cwd, h.cwd ?? '.');
29
+ const files = h.files.map((f) => {
30
+ const full = resolve(folder, f);
31
+ const path = relative(cwd, full).replace(/\\/g, '/') || f;
32
+ if (!inside(roots, full))
33
+ return { path: f, problem: 'outside the project' };
34
+ if (!existsSync(full))
35
+ return { path, problem: 'not there' };
36
+ try {
37
+ const size = statSync(full).size;
38
+ if (size > MAX_READ_BYTES)
39
+ return { path, problem: `too large to show (${Math.round(size / 1024)} KB)` };
40
+ const bytes = readFileSync(full);
41
+ const text = bytes.subarray(0, MAX_SHOWN_BYTES).toString('utf8');
42
+ return { path, sha256: createHash('sha256').update(bytes).digest('hex'), text, ...(bytes.length > MAX_SHOWN_BYTES ? { cut: true } : {}) };
43
+ }
44
+ catch (e) {
45
+ return { path, problem: e.message };
46
+ }
47
+ });
48
+ const warnings = [];
49
+ h.commands.forEach((line, i) => {
50
+ const deny = matchDenyPattern(line, denyPatterns);
51
+ const why = dangerousRefusal(line) ?? botSelfRefusal(line) ?? (deny ? `refused: matches deny pattern /${deny}/` : null);
52
+ if (why)
53
+ warnings.push(`${i + 1}: ${why.replace(/^refused:\s*/, '')}`);
54
+ });
55
+ return {
56
+ commands: h.commands,
57
+ cwd: folder,
58
+ expect: h.expect,
59
+ files,
60
+ ...(inside(roots, folder) ? {} : { outside: true }),
61
+ ...(warnings.length ? { warnings } : {}),
62
+ };
63
+ }
64
+ /** What the chat is told of the commands it handed over: what they printed when the operator ran them, or that they did not. */
65
+ export function handoffResultMessage(h, ran, text) {
66
+ const lines = h.commands.map((c) => ` ${c}`).join('\n');
67
+ const said = text.trim();
68
+ if (!ran) {
69
+ return (`The operator did not run the commands you handed over:\n${lines}\n\n${said ? `They say: ${said}\n\n` : ''}` +
70
+ 'Go on with the work without them, or end blocked and say in "needed" what has to be run.');
71
+ }
72
+ const fence = said.includes('```') ? '~~~~' : '```';
73
+ return (`The operator ran the commands you handed over, themselves:\n${lines}\n\n` +
74
+ `What it printed, as they gave it:\n\n${fence}\n${said || '(nothing)'}\n${fence}\n\n` +
75
+ `You expected: ${h.expect}\n\nCompare the two and go on with the work from here, in the same format.`);
76
+ }
77
+ /** What the chat is told when nobody is there to run them: the terminal's run, or one with nobody to ask. */
78
+ export const HANDOFF_NOBODY = 'Nobody is here to run the commands you handed over: this run has nobody to ask. Go on with the work without them, ' +
79
+ 'or end blocked and say in "needed" what the operator has to run and what it should show.';
@@ -35,8 +35,9 @@ import { describeCrash } from '../transport/edgeCrash.js';
35
35
  import { runReview, findingsMessage, deliverableFor } from './review.js';
36
36
  import { allAboutTheTask, isRepeat, findingId } from '../protocol/reviewSchema.js';
37
37
  import { repoState, workingTreePaths } from '../vcs/git.js';
38
- import { describeStep, checkCommandRefusal, commandRefusal, staticCheck } from '../exec/policy.js';
38
+ import { describeStep, checkAccessRefusal, checkCommandRefusal, commandRefusal, staticCheck } from '../exec/policy.js';
39
39
  import { networkFetchReason } from '../exec/network.js';
40
+ import { handoffCard, handoffResultMessage, HANDOFF_NOBODY } from './handoff.js';
40
41
  import { collectPolicyManifest, describePolicyManifest } from '../exec/policyManifest.js';
41
42
  import { assessIsolation, readIsolationSignals } from '../exec/isolation.js';
42
43
  import { confinementRefusal, isWithin, sessionRoots } from '../exec/confinement.js';
@@ -129,8 +130,9 @@ export function checkRefusalForOperator(why) {
129
130
  return text;
130
131
  }
131
132
  export function lineRefusal(command, shell, cwd, cfg, roots) {
132
- return (commandRefusal(command, shell, cfg.denyPatterns, cfg.allowedPrograms) ??
133
+ return (commandRefusal(command, shell, cfg.denyPatterns, cfg.allowedPrograms, process.env, undefined, cfg.readOnlyPrograms ?? []) ??
133
134
  confinementRefusal(command, { roots, cwd }) ??
135
+ checkAccessRefusal(command, shell, cfg) ??
134
136
  (PACKAGE_RUNNER.test(command) ? null : networkFetchReason(command, cwd)));
135
137
  }
136
138
  /**
@@ -1551,6 +1553,7 @@ export async function runTask(transport, session, task, deps) {
1551
1553
  mode: deps.currentMode?.() ?? cfg.execution.mode,
1552
1554
  networkFetch: cfg.execution.networkFetch,
1553
1555
  allowedPrograms: cfg.execution.allowedPrograms,
1556
+ readOnlyPrograms: cfg.execution.readOnlyPrograms,
1554
1557
  denyPatterns: cfg.execution.denyPatterns,
1555
1558
  cwd: work.cwd,
1556
1559
  lock: cfg.policyLock,
@@ -2675,6 +2678,44 @@ export async function runTask(transport, session, task, deps) {
2675
2678
  * what the reply said, at greater length and one message later. The reason carries the
2676
2679
  * approaches that were tried, and that is what the register shows.
2677
2680
  */
2681
+ /*
2682
+ * Commands the operator runs themselves (operator, 2026-10-26: "the script is made, but the user runs it; the bot
2683
+ * gives the commands for the user to run and the result it expects"). Never answered for the operator, Settings'
2684
+ * agreement or not: only their own run of it has anything to say. With nobody to ask, the chat is told so. What
2685
+ * they printed, or that they did not run it, goes back, and the work goes on.
2686
+ */
2687
+ if (reply.status === 'handoff' && reply.handoff) {
2688
+ const card = handoffCard(reply.handoff, work.cwd, confinement.roots, cfg.execution.denyPatterns);
2689
+ const why = reply.handoff.why?.trim() || 'Run these commands yourself, and send what they print.';
2690
+ let message = HANDOFF_NOBODY;
2691
+ await record('HANDOFF', `${why}\n\nin ${card.cwd}:\n${card.commands.join('\n')}\n\nexpected: ${card.expect}${card.files.length ? `\n\nscripts: ${card.files.map((f) => `${f.path}${f.sha256 ? ` (sha256 ${f.sha256})` : f.problem ? ` (${f.problem})` : ''}`).join(', ')}` : ''}`);
2692
+ if (deps.askQuestion) {
2693
+ sink.event('handoff-asked', { commands: card.commands, cwd: card.cwd, files: card.files.map((f) => ({ path: f.path, sha256: f.sha256 })) }, `the chat hands the operator commands to run themselves: ${card.commands.join(' ; ')}`, 'warn');
2694
+ await setTask((t) => {
2695
+ t.status = 'waiting-approval';
2696
+ });
2697
+ const got = await deps.askQuestion({ sessionId: session.id, taskId: task.id, question: why, options: [], handoff: card, actor: planning ? 'plan' : 'worker' });
2698
+ await setTask((t) => {
2699
+ t.status = 'running';
2700
+ });
2701
+ if (got === 'stop' || signal?.aborted)
2702
+ return await finish('aborted', 'stopped by the operator at the commands handed over', undefined, lastMarkdown);
2703
+ const ran = got.ran !== false;
2704
+ sink.event('handoff-answered', { ran }, ran ? 'the operator ran the commands and sent what they printed' : 'the operator did not run the commands');
2705
+ message = handoffResultMessage(card, ran, got.answer);
2706
+ }
2707
+ else {
2708
+ sink.event('handoff-nobody', { commands: card.commands }, 'the chat handed over commands to run, and nobody is here to run them', 'warn');
2709
+ }
2710
+ await record('HANDOFF RESULT', message);
2711
+ await pacer.throttleSend();
2712
+ const before = await transport.sendAndConfirm(message);
2713
+ const next = await transport.waitForReply(before);
2714
+ await saveReply('handoff', next);
2715
+ lastMarkdown = next.markdown;
2716
+ await pacer.settle();
2717
+ continue;
2718
+ }
2678
2719
  /*
2679
2720
  * A question only the operator can answer (operator, 2026-10-23: "answers to click, not only a text field; when the
2680
2721
  * chat proposes a command for the user to run by hand, a button behind it, and the bot runs it"): put to the
@@ -165,6 +165,8 @@ You are **Kerrigan**. You help the person talking to you get their work done wit
165
165
  - copilot-operator **runs those commands on the machine, in the project folder**, and sends back what they printed. Round after round, until Copilot says the task is **done** (with a summary of what it did), or **blocked** (with what it tried and what it needs), or a limit is reached.
166
166
  - Copilot learns the project only through those commands: it lists files, reads them, runs the build and the tests. It is not sent the files themselves, and it knows nothing about the project that the task does not say and the commands cannot find.
167
167
  - The person chooses how commands run in Settings, under ${Q('exec.startMode')} (not in the chat): ${Q('exec.startModeAsk')} (they press ${Q('chat.askRun')}, ${Q('chat.askRunAll')} or ${Q('chat.askSkip')} on a card that says who asks) or ${Q('exec.startModeAuto')}. A list of forbidden commands applies either way; pushing to a remote is refused; nothing needs administrator rights. A command that reaches a platform with the person's own access — Azure, AWS, GitHub, Jira, publishing a package and the like — waits on a card even in a run without asking, unless ${Q('exec.questions')} in Settings is set to agree with what the bot proposes; so do the questions the chat or the lead asks, with their answers to click. Once one answer on a card is pressed, the card's other answers and its text box turn off and the one pressed stays marked until the card goes; only when the answer did not reach the program do they come back on, with the reason on the card.
168
+ - The programs a command may start are listed in Settings, under "Programs the bot may start": the person adds one by its name (${Q('prog.add')}, ${Q('prog.addButton')}) and takes one off with its ✕; a command that starts a program not on the list is refused, and the chat is told why. A program that reaches a platform with their access is set to ${Q('prog.modeAsk')}, or, for az, to ${Q('prog.modeReadOnly')}: az's commands that only look (list, show, query) then run without a card, the ones that create, change, delete, sign in or out, or show a secret are refused, and one the program cannot read waits on a card. The person signs in themselves, with az login in their own terminal; the program uses that sign-in and never sees the password. The program reads the command line and a script could go round it, so for a guarantee they sign in with an account that has only the Reader role in Azure, and Azure itself refuses every change.
169
+ - A script Copilot writes during the work — a diagnostic, a reproduction, a small tool — is never run by the program (the person's rule): Copilot hands it over on a card, "Run this yourself", with the commands in order (and Copy), the folder, what should be seen, and each script with its SHA-256 to read first. The person runs them in their own terminal, pastes what they printed and presses ${Q('ho.send')}, or presses ${Q('ho.notRun')}; the card waits for them even when Settings agree with what the bot proposes. The project's tests, the build and the application run as steps, as before.
168
170
  - The model: ${Q('chat.model')} under the chat's box. When it is to be chosen by hand (the default), a card asks the person to choose the model in the Copilot window and press ${Q('approval.manualReady')}.
169
171
  - ${Q('chat.planMode')} (a choice under the chat's box): Copilot first looks at the project with read-only commands and proposes a plan — what is there, how it means to do it, the stages, the files, how it will show it works — and nothing is changed until the person approves the plan (${Q('pm.approve')}), asks for another (${Q('pm.revise')}), or stops.
170
172
  - ${Q('chat.review')} (under the chat's box, on unless unticked): when Copilot says the work is done, a conversation of its own reviews it — reads the changes, runs the checks — and sends back what it finds, up to ${n(rounds)} round(s) of fixing. When the model is chosen by hand, the card for the review's model says it is the review's: a different, stronger model than the one that did the work catches more mistakes.
@@ -246,7 +248,9 @@ function bgText(f) {
246
248
  - Човекът пише задание в чата, за **папката на проекта**, отворена там. Програмата го изпраща на **Microsoft 365 Copilot** (служебен акаунт) в прозорец на Edge, който отваря и държи отворен между съобщенията; когато работата по съобщение свърши, карта в този прозорец го казва, с бутон „ОК“. Copilot не може сам да пипа машината: отговаря с **команди на PowerShell**, в определен вид JSON.
247
249
  - copilot-operator **изпълнява тези команди на машината, в папката на проекта**, и връща какво са изписали. Кръг след кръг, докато Copilot каже, че заданието е **готово** (с обобщение на направеното), или **блокирано** (с какво е опитал и какво му трябва), или се стигне ограничение.
248
250
  - Copilot опознава проекта само чрез тези команди: изброява файлове, чете ги, пуска компилацията и тестовете. Самите файлове не му се изпращат и той не знае за проекта нищо, което заданието не казва и командите не могат да намерят.
249
- - Човекът избира как се изпълняват командите в Настройки, при ${Q('exec.startMode')} (не в чата): ${Q('exec.startModeAsk')} (натиска ${Q('chat.askRun')}, ${Q('chat.askRunAll')} или ${Q('chat.askSkip')} на карта, на която пише кой иска) или ${Q('exec.startModeAuto')}. И в двата случая важи списък със забранени команди; изпращането към отдалечено хранилище (push) се отказва; нищо не изисква администраторски права. Команда, която достъпва платформа със собствения достъп на човека — Azure, AWS, GitHub, Jira, публикуване на пакет и подобни, — чака на карта дори при пускане без питане, освен ако ${Q('exec.questions')} в Настройки не е настроено да се съгласява с това, което предлага ботът; същото важи за въпросите на чата или на ръководителя, с отговори за избор.
251
+ - Човекът избира как се изпълняват командите в Настройки, при ${Q('exec.startMode')} (не в чата): ${Q('exec.startModeAsk')} (натиска ${Q('chat.askRun')}, ${Q('chat.askRunAll')} или ${Q('chat.askSkip')} на карта, на която пише кой иска) или ${Q('exec.startModeAuto')}. И в двата случая важи списък със забранени команди; изпращането към отдалечено хранилище (push) се отказва; нищо не изисква администраторски права. Команда, която достъпва платформа със собствения достъп на човека — Azure, AWS, GitHub, Jira, публикуване на пакет и подобни, — чака на карта дори при пускане без питане, освен ако ${Q('exec.questions')} в Настройки не е настроено да се съгласява с това, което предлага ботът; същото важи за въпросите на чата или на ръководителя, с отговори за избор. Щом се натисне един отговор на карта, другите отговори и полето за текст на картата се изключват, а натиснатият остава отбелязан, докато картата изчезне; включват се отново само ако отговорът не е стигнал до програмата, с причината на картата.
252
+ - Програмите, които командата може да пуска, са изброени в Настройки, при „Програми, които ботът може да пуска“: човекът добавя програма по името ѝ (${Q('prog.add')}, ${Q('prog.addButton')}) и маха програма с нейното ✕; команда, която пуска програма извън списъка, се отказва и на чата се казва защо. Програма, която достъпва платформа с неговия достъп, е на ${Q('prog.modeAsk')} или, за az, на ${Q('prog.modeReadOnly')}: тогава командите на az, които само гледат (list, show, query), се изпълняват без карта, тези, които създават, променят, трият, влизат или излизат, или показват тайна, се отказват, а такава, която програмата не може да разчете, чака на карта. Човекът влиза сам, с az login в собствения си терминал; програмата ползва този вход и никога не вижда паролата. Програмата чете командния ред и скрипт би могъл да го заобиколи, затова за гаранция той влиза с акаунт, който има само ролята Reader в Azure, и тогава самият Azure отказва всяка промяна.
253
+ - Скрипт, който Copilot пише по време на работата — диагностика, възпроизвеждане, малък инструмент, — програмата никога не го пуска (правилото на човека): Copilot го предава на карта „Пуснете го сами“ с командите по ред (и „Копирай“), папката, какво трябва да се види и всеки скрипт с неговия SHA-256, за да се прочете първо. Човекът ги пуска в собствения си терминал, поставя какво са изписали и натиска ${Q('ho.send')} или натиска ${Q('ho.notRun')}; картата чака него, дори когато Настройки се съгласяват с това, което предлага ботът. Тестовете на проекта, компилацията и приложението се пускат като стъпки, както досега.
250
254
  - Моделът: ${Q('chat.model')} под полето на чата. Когато се избира ръчно (по подразбиране), карта моли човека да избере модела в прозореца на Copilot и да натисне ${Q('approval.manualReady')}.
251
255
  - ${Q('chat.planMode')} (избор под полето на чата): Copilot първо разглежда проекта само с команди, които четат, и предлага план — какво има, как смята да го направи, етапите, файловете, как ще покаже, че работи, — и нищо не се променя, докато човекът не одобри плана (${Q('pm.approve')}), не поиска друг (${Q('pm.revise')}) или не спре.
252
256
  - ${Q('chat.review')} (под полето на чата, включена, освен ако не я изключат): когато Copilot каже, че работата е готова, отделен разговор я преглежда — чете промените, пуска проверките — и връща каквото открие, до ${n(rounds)} кръга поправка. Когато моделът се избира ръчно, картата за модела на рецензията казва, че е за нея: модел, различен и по-силен от този, с който е работено, хваща повече грешки.
@@ -1050,6 +1050,38 @@ export const SYSTEM_GUIDE = [
1050
1050
  doesEn: 'Sends your answer to the lead, and the work goes on.',
1051
1051
  doesBg: 'Изпраща отговора ви на ръководителя и работата продължава.',
1052
1052
  },
1053
+ {
1054
+ key: 'ho.output',
1055
+ kind: 'field',
1056
+ en: 'What it printed',
1057
+ bg: 'Какво изписа',
1058
+ doesEn: 'On the card "Run this yourself", where the chat hands over a script it wrote with the commands, the folder and what should be seen (the bot never runs such a script): paste here what the commands printed in your own terminal.',
1059
+ doesBg: 'На картата „Пуснете го сами“, където чатът предава написан от него скрипт с командите, папката и какво трябва да се види (ботът никога не пуска такъв скрипт): поставете тук какво изписаха командите в собствения ви терминал.',
1060
+ },
1061
+ {
1062
+ key: 'ho.send',
1063
+ kind: 'button',
1064
+ en: 'Send what it printed',
1065
+ bg: 'Изпрати какво изписа',
1066
+ doesEn: 'Sends what you pasted to the chat, beside what it expected, and the work goes on.',
1067
+ doesBg: 'Изпраща поставеното на чата, до това, което е очаквал, и работата продължава.',
1068
+ },
1069
+ {
1070
+ key: 'ho.notRun',
1071
+ kind: 'button',
1072
+ en: 'I did not run it',
1073
+ bg: 'Не го пуснах',
1074
+ doesEn: 'Tells the chat you did not run the commands, with what you wrote as the reason; it goes on without them or ends blocked.',
1075
+ doesBg: 'Казва на чата, че не сте пуснали командите, с написаното като причина; той продължава без тях или приключва като блокиран.',
1076
+ },
1077
+ {
1078
+ key: 'approval.openChat',
1079
+ kind: 'link',
1080
+ en: 'Open the chat ({name})',
1081
+ bg: 'Отвори чата ({name})',
1082
+ doesEn: 'On the card at the top of another page, for a question of the chat\'s or commands handed over: opens the chat, where it is answered.',
1083
+ doesBg: 'На картата най-горе на друга страница, за въпрос на чата или предадени команди: отваря чата, където се отговаря.',
1084
+ },
1053
1085
  {
1054
1086
  key: 'lead.stop',
1055
1087
  kind: 'button',
@@ -2588,6 +2620,69 @@ export const SYSTEM_GUIDE = [
2588
2620
  },
2589
2621
  ],
2590
2622
  },
2623
+ {
2624
+ headingKey: 'prog.title',
2625
+ en: 'Programs the bot may start',
2626
+ bg: 'Програми, които ботът може да пуска',
2627
+ controls: [
2628
+ {
2629
+ key: 'prog.platforms',
2630
+ kind: 'note',
2631
+ en: 'Programs that reach a platform with your access',
2632
+ bg: 'Програми, които достъпват платформа с вашия достъп',
2633
+ doesEn: 'The programs on the list that reach a platform with the operator\'s access (Azure, AWS, GitHub…), each with how the bot may use it and its ✕ to take it off.',
2634
+ doesBg: 'Програмите от списъка, които достъпват платформа с достъпа на оператора (Azure, AWS, GitHub…), всяка с начина, по който ботът може да я ползва, и ✕, за да се махне.',
2635
+ },
2636
+ {
2637
+ key: 'prog.modeAsk',
2638
+ kind: 'select',
2639
+ en: 'Ask me each time',
2640
+ bg: 'Питай ме всеки път',
2641
+ doesEn: 'Every command of that program waits on a card for the operator, in every run.',
2642
+ doesBg: 'Всяка команда на тази програма чака на карта за оператора, при всяко пускане.',
2643
+ },
2644
+ {
2645
+ key: 'prog.modeReadOnly',
2646
+ kind: 'select',
2647
+ en: 'Only for reference (read only)',
2648
+ bg: 'Само за справка (само четене)',
2649
+ doesEn: 'Only where the bot can read the program\'s commands (az today): those that only look — list, show, query — run without asking; one that creates, changes, deletes, signs in or out, or shows a secret is refused, and one it cannot read waits on a card. The operator signs in with az login in their own terminal; the bot never sees the password.',
2650
+ doesBg: 'Само където ботът може да разчете командите на програмата (днес az): тези, които само гледат — list, show, query — се изпълняват без питане; команда, която създава, променя, трие, влиза или излиза, или показва тайна, се отказва, а такава, която не може да разчете, чака на карта. Операторът влиза с az login в собствения си терминал; ботът никога не вижда паролата.',
2651
+ },
2652
+ {
2653
+ key: 'prog.others',
2654
+ kind: 'note',
2655
+ en: 'Other programs',
2656
+ bg: 'Други програми',
2657
+ doesEn: 'The other programs a command may start, each with its ✕ to take it off; the last one cannot be taken off.',
2658
+ doesBg: 'Другите програми, които командата може да пуска, всяка с ✕, за да се махне; последната не може да се махне.',
2659
+ },
2660
+ {
2661
+ key: 'prog.add',
2662
+ kind: 'field',
2663
+ en: 'Add a program',
2664
+ bg: 'Добави програма',
2665
+ doesEn: 'The name of a program to add, as a terminal takes it, without a folder: az, gh, kubectl. One that can be read only for reference is added so.',
2666
+ doesBg: 'Името на програма за добавяне, както го приема терминалът, без папка: az, gh, kubectl. Програма, която може да е само за справка, се добавя така.',
2667
+ },
2668
+ {
2669
+ key: 'prog.addButton',
2670
+ kind: 'button',
2671
+ en: 'Add',
2672
+ bg: 'Добави',
2673
+ doesEn: 'Adds the program written beside it to the list.',
2674
+ doesBg: 'Добавя написаната до него програма в списъка.',
2675
+ },
2676
+ {
2677
+ key: 'prog.restore',
2678
+ kind: 'button',
2679
+ en: 'Put back the defaults',
2680
+ bg: 'Върни подразбиращите се',
2681
+ doesEn: 'Puts back the list the bot comes with, after asking; the programs added are taken off.',
2682
+ doesBg: 'Връща списъка, с който идва ботът, след като попита; добавените програми се махат.',
2683
+ },
2684
+ ],
2685
+ },
2591
2686
  ],
2592
2687
  },
2593
2688
  {
@@ -233,8 +233,8 @@ export function parseReply(markdown, opts) {
233
233
  // model that writes "Край" under an explanation of why it cannot finish has ended the
234
234
  // task, not completed it, and reading that as `done` would file a failure as a success.
235
235
  const blocked = reply.status === 'blocked';
236
- // A plan waits for its approval, a question for its answer: the stop word in either does not end the task.
237
- const plan = reply.status === 'plan' || reply.status === 'ask';
236
+ // A plan waits for its approval, a question for its answer, a handoff for the operator's run: the stop word in none of them ends the task.
237
+ const plan = reply.status === 'plan' || reply.status === 'ask' || reply.status === 'handoff';
238
238
  return {
239
239
  ok: true,
240
240
  reply: { ...reply, steps },
@@ -115,6 +115,21 @@ export const OptionSchema = z.preprocess((v) => (typeof v === 'string' ? { answe
115
115
  run: z.string().trim().min(1).optional(),
116
116
  shell: ShellSchema.optional(),
117
117
  }));
118
+ /**
119
+ * Commands the operator runs themselves (operator, 2026-10-26: "the script is made, but the user runs it; the bot gives
120
+ * the commands for the user to run and the result it expects"): a script written during the work is never run by the
121
+ * runner (`scriptFiles.ts`), so the chat hands it over — the lines in order, the folder, what should be seen, and the
122
+ * script files they run, which the card shows with their SHA-256 so the operator reads what they run.
123
+ */
124
+ export const HandoffSchema = z.object({
125
+ why: z.string().trim().min(1).optional(),
126
+ /** The folder the commands are typed in, relative to the project; the project itself when left out. */
127
+ cwd: z.string().trim().min(1).optional(),
128
+ commands: z.array(z.preprocess(asText, z.string().trim().min(1))).min(1, 'handoff.commands needs at least one command for the operator to run.'),
129
+ expect: z.string().trim().min(5, 'handoff.expect must say what the operator should see when it works.'),
130
+ /** The script files the commands run, relative to the project. */
131
+ files: z.array(z.preprocess(asText, z.string().trim().min(1))).default([]),
132
+ });
118
133
  export const ReplySchema = z
119
134
  .object({
120
135
  /**
@@ -134,13 +149,15 @@ export const ReplySchema = z
134
149
  * `plan` — in plan mode only: here is the plan, made from what I read; no steps with it, and no change
135
150
  * made yet. See `PlanSchema`.
136
151
  */
137
- status: z.enum(['continue', 'done', 'blocked', 'plan', 'ask']),
152
+ status: z.enum(['continue', 'done', 'blocked', 'plan', 'ask', 'handoff']),
138
153
  /** Required when `status` is `plan`. */
139
154
  plan: PlanSchema.optional(),
140
155
  /** `ask` — a question only the operator can answer (2026-10-23): the question, why, and the answers to click. */
141
156
  question: z.string().optional(),
142
157
  why: z.string().optional(),
143
158
  options: z.array(OptionSchema).default([]),
159
+ /** `handoff` — a script written during the work, for the operator to run themselves (2026-10-26). */
160
+ handoff: HandoffSchema.optional(),
144
161
  steps: z.array(StepSchema).default([]),
145
162
  notes: z.string().optional(),
146
163
  /**
@@ -172,12 +189,16 @@ export const ReplySchema = z
172
189
  'Send at least one step, or set status to "done" or "blocked".',
173
190
  })
174
191
  .refine((r) => r.status === 'continue' || r.steps.length === 0, {
175
- message: 'status "done", "blocked", "plan" and "ask" cannot carry steps: "done" and "blocked" end the task, "plan" waits for the plan to be approved and "ask" for the operator\'s answer (a command for an answer goes in its "run"). ' +
192
+ message: 'status "done", "blocked", "plan", "ask" and "handoff" cannot carry steps: "done" and "blocked" end the task, "plan" waits for the plan to be approved, "ask" for the operator\'s answer (a command for an answer goes in its "run") and "handoff" for what the operator\'s own run of its commands printed. ' +
176
193
  'Send the steps with status "continue".',
177
194
  })
178
195
  .refine((r) => r.status !== 'ask' || ((r.question ?? '').trim().length >= 5 && r.options.length >= 2), {
179
196
  message: 'status "ask" requires a "question" for the operator and at least two "options", your recommended one first: ' +
180
197
  '[{ "answer": "what the operator clicks" }, { "answer": "...", "run": "a command the runner runs if this is chosen" }].',
198
+ })
199
+ .refine((r) => r.status !== 'handoff' || !!r.handoff, {
200
+ message: 'status "handoff" requires a "handoff" object: { "why": what it is for, "cwd": the folder, relative to the project, ' +
201
+ '"commands": [the exact lines the operator types, in order], "expect": what they should see when it works, "files": [the scripts they run] }.',
181
202
  })
182
203
  .refine((r) => r.status !== 'plan' || !!r.plan, {
183
204
  message: 'status "plan" requires a "plan" object: { "existing": what is already there, "approach": how, "steps": [the stages], ' +
@@ -214,6 +214,12 @@ export function parkedAnswerFrom(p, input) {
214
214
  return text(input.note) ? { kind: 'plan', decision: 'revise', note: text(input.note) } : { problem: 'Say what to change in the plan.' };
215
215
  return { problem: 'A plan is approved, or sent back for another.' };
216
216
  case 'question':
217
+ // Commands handed over (2026-10-26): what they printed, or that the operator did not run them, with a word or none.
218
+ if (p.approval.question?.handoff) {
219
+ if (input.ran === false)
220
+ return { kind: 'question', answer: text(input.answer), ran: false };
221
+ return text(input.answer) ? { kind: 'question', answer: text(input.answer), ran: true } : { problem: 'Paste what the commands printed first.' };
222
+ }
217
223
  return text(input.answer) ? { kind: 'question', answer: text(input.answer) } : { problem: 'Write the answer first.' };
218
224
  case 'retry': {
219
225
  const choices = p.approval.retry?.choices ?? [];