copilot-operator 0.1.52 → 0.1.53

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 (57) hide show
  1. package/README.md +17 -1
  2. package/dist/src/api/operator.controller.js +35 -2
  3. package/dist/src/api/operator.service.js +83 -6
  4. package/dist/src/config/schema.js +32 -0
  5. package/dist/src/exec/policy.js +11 -1
  6. package/dist/src/exec/scriptFiles.js +108 -2
  7. package/dist/src/orchestrator/leadRunner.js +50 -4
  8. package/dist/src/orchestrator/review.js +9 -3
  9. package/dist/src/orchestrator/taskRunner.js +55 -3
  10. package/dist/src/plan/kerrigan.js +35 -4
  11. package/dist/src/plan/systemGuide.js +123 -4
  12. package/dist/src/session/compose.js +16 -4
  13. package/dist/src/session/store.js +3 -0
  14. package/dist/src/util/pacing.js +33 -2
  15. package/dist/src/vcs/git.js +11 -1
  16. package/dist/src/vcs/referenceGuard.js +299 -0
  17. package/dist/web/404.html +3 -2
  18. package/dist/web/_next/static/chunks/163.980c5145848efbdf.js +1 -0
  19. package/dist/web/_next/static/chunks/220.447d1d8624d4644c.js +1 -0
  20. package/dist/web/_next/static/chunks/500-34d01f8d8d73eb2c.js +1 -0
  21. package/dist/web/_next/static/chunks/548.c6dfd1cb270f3c93.js +1 -0
  22. package/dist/web/_next/static/chunks/584.fc9e061dd4069406.js +1 -0
  23. package/dist/web/_next/static/chunks/67.1a3ca07919abce27.js +1 -0
  24. package/dist/web/_next/static/chunks/714.5b2e291a430adc9c.js +1 -0
  25. package/dist/web/_next/static/chunks/747.157732b5b3f3c435.js +1 -0
  26. package/dist/web/_next/static/chunks/77.d478a6f2eafe31e3.js +1 -0
  27. package/dist/web/_next/static/chunks/921-b2219533c5a6e38f.js +1 -0
  28. package/dist/web/_next/static/chunks/app/defaults/page-b7e4e94a55e65806.js +1 -0
  29. package/dist/web/_next/static/chunks/app/layout-2b3718748721c1ac.js +1 -0
  30. package/dist/web/_next/static/chunks/app/page-59b9867b52914a6c.js +1 -0
  31. package/dist/web/_next/static/chunks/{webpack-77147e31d2125631.js → webpack-0c3cad1f3181d857.js} +1 -1
  32. package/dist/web/_next/static/css/06f314fa5fccd68d.css +1 -0
  33. package/dist/web/defaults.html +3 -2
  34. package/dist/web/defaults.txt +9 -9
  35. package/dist/web/index.html +3 -2
  36. package/dist/web/index.txt +9 -9
  37. package/dist/web/system.html +3 -2
  38. package/dist/web/system.txt +9 -9
  39. package/package.json +6 -2
  40. package/prompts/level1.md +32 -12
  41. package/prompts/review1.md +287 -286
  42. package/dist/web/_next/static/chunks/163.dbd7d36584d0bb37.js +0 -1
  43. package/dist/web/_next/static/chunks/220.35531b39410e1a9f.js +0 -1
  44. package/dist/web/_next/static/chunks/548.71ac96c94136659b.js +0 -1
  45. package/dist/web/_next/static/chunks/584.6df695c5b86a75aa.js +0 -1
  46. package/dist/web/_next/static/chunks/67.9ed79e2fbfb56f26.js +0 -1
  47. package/dist/web/_next/static/chunks/714.1e2338736a70b9c7.js +0 -1
  48. package/dist/web/_next/static/chunks/747.d2c1249d736dc03b.js +0 -1
  49. package/dist/web/_next/static/chunks/77.a200abef0f5b4a7f.js +0 -1
  50. package/dist/web/_next/static/chunks/808-bc7d7eac6d823291.js +0 -1
  51. package/dist/web/_next/static/chunks/921-dc5538cd779c6432.js +0 -1
  52. package/dist/web/_next/static/chunks/app/defaults/page-edd7534ca9ecf366.js +0 -1
  53. package/dist/web/_next/static/chunks/app/layout-8f99a164d76897a0.js +0 -1
  54. package/dist/web/_next/static/chunks/app/page-4bed816eda370d0c.js +0 -1
  55. package/dist/web/_next/static/css/3bea264adc472bc8.css +0 -1
  56. /package/dist/web/_next/static/{_1zhoDsMOPAH2xW702E5A → FGzV3mVZpXRCVjiw1diNu}/_buildManifest.js +0 -0
  57. /package/dist/web/_next/static/{_1zhoDsMOPAH2xW702E5A → FGzV3mVZpXRCVjiw1diNu}/_ssgManifest.js +0 -0
package/README.md CHANGED
@@ -419,10 +419,26 @@ same Copilot window, the lead asking you only what nobody else can decide. "Paus
419
419
  "Continue". The interface speaks nine languages (English, Bulgarian, German, Spanish, French,
420
420
  Portuguese, Japanese, Korean, Arabic), chosen from "Language". "Kerrigan" on the home screen hands out a persona to
421
421
  give another chat, which then helps you write tasks for this one (optional); she knows your projects,
422
- with the level 2 you write for each in Settings. See
422
+ with the level 2 you write for each in Settings. A project in Settings can be marked "For
423
+ reference only": the bot reads it and runs what only reads it, and whatever a command changes there
424
+ — files, branches, what is staged — is put back after that command, and the chat is told. See
423
425
  [`docs/ui.md`](docs/ui.md); the Sessions page, the task register and plans from JSON were removed
424
426
  on 2026-10-20.
425
427
 
428
+ Skills keep your instructions for a kind of task that comes back — a new test, a new entity, a migration — in
429
+ Settings; a message starting with `/its-name` (or with the skill chosen under the chat's box) carries them to the
430
+ chat. The three panels move as in VS Code: drag the grip ⠿ in a panel's head onto another. Settings can also make
431
+ the bot pause between messages to Copilot, by a fixed or a random time.
432
+
433
+ **What runs, and how.** Every command the chat sends is given to PowerShell as text
434
+ (`pwsh -NoProfile -NonInteractive -Command "…"`); the bot writes no script to run it. A script file
435
+ — `.ps1`, `.cmd`, `.bat`, `.sh`, `.vbs` — runs only when it is the project's own: committed in its
436
+ repository, unchanged since, and committed before the work began. One the chat wrote, changed or
437
+ downloaded is refused however it is called, and nothing in `.cop-tmp` is run. The project's tools
438
+ go on as usual — `npm test`, `npm run build`, `dotnet test`, `node` starting the application.
439
+ Downloads wait for you even in an unattended run, `npm install` runs no install scripts, and the
440
+ package itself has none.
441
+
426
442
  ### Removing it from a machine
427
443
 
428
444
  Nothing is installed system-wide, nothing runs at start-up, no service and no scheduled task
@@ -263,6 +263,8 @@ let OperatorController = class OperatorController {
263
263
  ...(body.lead === true ? { lead: true } : {}),
264
264
  ...(typeof body.workerModel === 'string' && body.workerModel.trim() ? { workerModel: body.workerModel } : {}),
265
265
  ...(body.workerManualModel === true ? { workerManualModel: true } : {}),
266
+ // The skill chosen for this message (2026-10-21), by its name.
267
+ ...(typeof body.skill === 'string' && body.skill.trim() ? { skill: body.skill } : {}),
266
268
  })
267
269
  .catch(fail);
268
270
  }
@@ -315,10 +317,28 @@ let OperatorController = class OperatorController {
315
317
  /** Stores it. A field left out is kept; an empty `rootDir` clears the default. */
316
318
  setProject(body) {
317
319
  const text = (v) => (typeof v === 'string' ? v : undefined);
320
+ const flag = (v) => (typeof v === 'boolean' ? v : undefined);
318
321
  const others = Array.isArray(body?.others)
319
- ? body.others.map((o) => ({ name: String(o?.name ?? ''), rootDir: String(o?.rootDir ?? ''), ...(typeof o?.level2 === 'string' ? { level2: o.level2 } : {}) }))
322
+ ? body.others.map((o) => ({
323
+ name: String(o?.name ?? ''),
324
+ rootDir: String(o?.rootDir ?? ''),
325
+ ...(typeof o?.level2 === 'string' ? { level2: o.level2 } : {}),
326
+ ...(typeof o?.readOnly === 'boolean' ? { readOnly: o.readOnly } : {}),
327
+ }))
320
328
  : undefined;
321
- return this.ops.setProject({ rootDir: text(body?.rootDir), name: text(body?.name), level2: text(body?.level2), ...(others ? { others } : {}) }).catch(fail);
329
+ return this.ops
330
+ .setProject({ rootDir: text(body?.rootDir), name: text(body?.name), level2: text(body?.level2), readOnly: flag(body?.readOnly), ...(others ? { others } : {}) })
331
+ .catch(fail);
332
+ }
333
+ // --- skills (2026-10-21) ---------------------------------------------------------------------
334
+ skills() {
335
+ return this.ops.skills();
336
+ }
337
+ /** The whole list, as Settings show it: each skill's name, what it is for, its instructions and its project. */
338
+ setSkills(body = {}) {
339
+ if (!Array.isArray(body?.skills))
340
+ throw new BadRequestException('skills must be a list');
341
+ return this.ops.setSkills(body.skills).catch(fail);
322
342
  }
323
343
  // --- the model picker ---------------------------------------------------------------------
324
344
  /** The cached list. Returns null when the picker has never been read on this machine. */
@@ -626,6 +646,19 @@ __decorate([
626
646
  __metadata("design:paramtypes", [Object]),
627
647
  __metadata("design:returntype", Promise)
628
648
  ], OperatorController.prototype, "setProject", null);
649
+ __decorate([
650
+ Get('skills'),
651
+ __metadata("design:type", Function),
652
+ __metadata("design:paramtypes", []),
653
+ __metadata("design:returntype", Promise)
654
+ ], OperatorController.prototype, "skills", null);
655
+ __decorate([
656
+ Put('skills'),
657
+ __param(0, Body()),
658
+ __metadata("design:type", Function),
659
+ __metadata("design:paramtypes", [Object]),
660
+ __metadata("design:returntype", Promise)
661
+ ], OperatorController.prototype, "setSkills", null);
629
662
  __decorate([
630
663
  Get('models'),
631
664
  __metadata("design:type", Function),
@@ -33,6 +33,12 @@ import { chatCode } from '../transport/chatSession.js';
33
33
  /** The folders the operator works in: the default new sessions start on, and the rest by name. */
34
34
  /** The longest level 2 a project may have: Kerrigan carries each one whole. */
35
35
  export const MAX_PROJECT_LEVEL2 = 8000;
36
+ /** Its instructions: as long as a project's level 2, the longest text the opening carries besides the task. */
37
+ export const MAX_SKILL_TEXT = 8000;
38
+ export const MAX_SKILL_DESCRIPTION = 300;
39
+ export const MAX_SKILLS = 50;
40
+ /** What follows `/` at the start of a message: lowercase letters, digits and hyphens, 2 to 40 of them. */
41
+ export const SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,38}[a-z0-9]$/;
36
42
  /**
37
43
  * A settings file or a policy lock that cannot be used: answered 409 with its own message on every route
38
44
  * (see `server.ts`), so a start passes it on rather than answering it as a start that did not happen.
@@ -1073,11 +1079,15 @@ let OperatorService = class OperatorService {
1073
1079
  const cfg = await this.settings.load();
1074
1080
  const p = await this.project();
1075
1081
  const projects = [
1076
- ...(p.rootDir ? [{ name: p.name, rootDir: p.rootDir, ...(p.branch ? { branch: p.branch } : {}), level2: p.level2, chat: true }] : []),
1077
- ...p.others.map((o) => ({ name: o.name, rootDir: o.rootDir, ...(o.branch ? { branch: o.branch } : {}), level2: o.level2 })),
1082
+ ...(p.rootDir ? [{ name: p.name, rootDir: p.rootDir, ...(p.branch ? { branch: p.branch } : {}), level2: p.level2, chat: true, ...(p.readOnly ? { readOnly: true } : {}) }] : []),
1083
+ ...p.others.map((o) => ({ name: o.name, rootDir: o.rootDir, ...(o.branch ? { branch: o.branch } : {}), level2: o.level2, ...(o.readOnly ? { readOnly: true } : {}) })),
1078
1084
  ];
1085
+ // The skills, each with the name of the project it is for.
1086
+ const nameOf = (dir) => [{ name: p.name || p.rootDir, rootDir: p.rootDir }, ...p.others].find((x) => x.rootDir && sameFolder(x.rootDir, dir))?.name ?? dir;
1087
+ const skills = (await this.skills()).skills.map((k) => ({ name: k.name, description: k.description, ...(k.projectDir ? { project: nameOf(k.projectDir) } : {}) }));
1079
1088
  const text = kerriganPersona(lang, {
1080
1089
  version: botVersion(),
1090
+ skills,
1081
1091
  maxIterations: cfg.limits.maxIterations,
1082
1092
  maxRunMinutes: cfg.limits.maxRunMinutes,
1083
1093
  autoContinue: cfg.limits.autoContinue ?? 0,
@@ -1113,9 +1123,13 @@ let OperatorService = class OperatorService {
1113
1123
  let session = input.threadId ? await this.store.getSession(input.threadId) : null;
1114
1124
  if (input.threadId && (!session || session.kind !== 'chat'))
1115
1125
  throw new Error('That conversation is not there any more. Start a new one.');
1126
+ // The skill chosen for this message, as it reads now: the task keeps this copy whatever is edited later.
1127
+ const skill = input.skill?.trim() ? await this.skillFor(input.skill, session?.projectDir ?? (await this.workspace()).dir) : undefined;
1116
1128
  if (session) {
1117
1129
  const inFlight = session.tasks.find((t) => t.status === 'running' || t.status === 'waiting-approval');
1118
1130
  if (inFlight && this.running.has(session.id)) {
1131
+ if (skill)
1132
+ throw new Error(`A skill goes with a new message, and this one would be a note to the message at work. Send /${skill.name} when it has finished.`);
1119
1133
  await this.addTaskNote(session.id, inFlight.id, text);
1120
1134
  return { threadId: session.id, taskId: inFlight.id, noted: true, needsStart: false };
1121
1135
  }
@@ -1169,6 +1183,7 @@ let OperatorService = class OperatorService {
1169
1183
  title: text.split(/\r?\n/)[0].trim().slice(0, 80) || 'message',
1170
1184
  level2: '',
1171
1185
  prompt: text,
1186
+ ...(skill ? { skill: { name: skill.name, description: skill.description, text: skill.text } } : {}),
1172
1187
  });
1173
1188
  // The language the workbench is in, for what the chat's window says when the work has ended (`chatWindowNotice`).
1174
1189
  if (input.lang && session.lang !== input.lang) {
@@ -1186,6 +1201,64 @@ let OperatorService = class OperatorService {
1186
1201
  }
1187
1202
  return { threadId: session.id, taskId: task.id, needsStart: false };
1188
1203
  }
1204
+ // --- skills (2026-10-21) ----------------------------------------------------------------------------
1205
+ /** The skills in Settings, and how long their instructions may be. */
1206
+ async skills() {
1207
+ const cfg = await this.settings.load();
1208
+ return {
1209
+ skills: (cfg.skills ?? []).map((k) => ({ name: k.name, description: k.description ?? '', text: k.text ?? '', projectDir: k.projectDir ?? '' })),
1210
+ maxText: MAX_SKILL_TEXT,
1211
+ maxDescription: MAX_SKILL_DESCRIPTION,
1212
+ };
1213
+ }
1214
+ /**
1215
+ * Stores the list as given, held to the rules: a name to type after `/` — lowercase, digits and hyphens, each used
1216
+ * once — instructions that are there and not too long, a project that is one of Settings' or every project.
1217
+ */
1218
+ async setSkills(list) {
1219
+ if (!Array.isArray(list))
1220
+ throw new Error('The skills come as a list.');
1221
+ if (list.length > MAX_SKILLS)
1222
+ throw new Error(`There can be at most ${MAX_SKILLS} skills.`);
1223
+ const cfg = await this.settings.load();
1224
+ const folders = [cfg.project.rootDir, ...cfg.project.others.map((o) => o.rootDir)].filter((d) => d?.trim());
1225
+ const seen = new Set();
1226
+ const skills = list.map((k) => {
1227
+ const name = String(k?.name ?? '').trim().toLowerCase();
1228
+ if (!SKILL_NAME.test(name))
1229
+ throw new Error(`"${name || '(no name)'}" cannot be a skill's name: 2 to 40 lowercase letters, digits and hyphens, as typed after / — new-test, new-entity, db-migration.`);
1230
+ if (seen.has(name))
1231
+ throw new Error(`Two skills are named "${name}". The name is how a message calls one, so each needs its own.`);
1232
+ seen.add(name);
1233
+ const description = String(k?.description ?? '').trim();
1234
+ if (description.length > MAX_SKILL_DESCRIPTION)
1235
+ throw new Error(`What "${name}" is for is longer than ${MAX_SKILL_DESCRIPTION} characters; one line is enough.`);
1236
+ const text = String(k?.text ?? '');
1237
+ if (!text.trim())
1238
+ throw new Error(`The skill "${name}" has no instructions: write what the chat should know and do for this kind of task.`);
1239
+ if (text.length > MAX_SKILL_TEXT)
1240
+ throw new Error(`The instructions of "${name}" are longer than ${MAX_SKILL_TEXT.toLocaleString('en')} characters.`);
1241
+ const projectDir = String(k?.projectDir ?? '').trim();
1242
+ if (projectDir && !folders.some((f) => sameFolder(f, projectDir)))
1243
+ throw new Error(`The skill "${name}" is for ${projectDir}, which is not one of the projects in Settings.`);
1244
+ return { name, description, text, projectDir };
1245
+ });
1246
+ await this.settings.update((raw) => ({ ...raw, skills }));
1247
+ return await this.skills();
1248
+ }
1249
+ /** The skill a message calls, for the folder it works in: one for every project, or one for this one. */
1250
+ async skillFor(asked, dir) {
1251
+ const name = asked.trim().replace(/^\//, '').toLowerCase();
1252
+ const { skills } = await this.skills();
1253
+ const fits = skills.filter((k) => !k.projectDir || (dir && sameFolder(k.projectDir, dir)));
1254
+ const found = fits.find((k) => k.name === name);
1255
+ if (found)
1256
+ return found;
1257
+ const other = skills.find((k) => k.name === name);
1258
+ if (other)
1259
+ throw new Error(`The skill "${name}" is for ${other.projectDir}, not for the folder this chat works in.`);
1260
+ throw new Error(`There is no skill called "${name}"${fits.length > 0 ? `; there are ${fits.map((k) => k.name).join(', ')}` : ''}. Skills are written in Settings → Skills.`);
1261
+ }
1189
1262
  /**
1190
1263
  * Back to before a message of the chat (2026-10-17): the folder put back exactly as it was just before that
1191
1264
  * message ran — branch, commit, uncommitted changes — and that message and every one after it taken out of the
@@ -1751,7 +1824,7 @@ let OperatorService = class OperatorService {
1751
1824
  * The branch each folder is on now (operator, 2026-10-20: "show which branch is chosen"), read from git each
1752
1825
  * time, since the operator switches it by hand and the chat works on whatever is checked out.
1753
1826
  */
1754
- const entry = async (name, dir, level2) => {
1827
+ const entry = async (name, dir, level2, readOnly) => {
1755
1828
  const problem = dir ? repoUnusableReason(dir) : 'no folder';
1756
1829
  const branch = dir && problem === null ? await git(dir, ['rev-parse', '--abbrev-ref', 'HEAD']).catch(() => null) : null;
1757
1830
  return {
@@ -1761,10 +1834,11 @@ let OperatorService = class OperatorService {
1761
1834
  ...(dir && problem ? { repoProblem: problem } : {}),
1762
1835
  ...(branch?.ok && branch.stdout ? { branch: branch.stdout } : {}),
1763
1836
  level2,
1837
+ readOnly,
1764
1838
  };
1765
1839
  };
1766
- const main = await entry((cfg.project?.name ?? '').trim(), rootDir, cfg.project?.level2 ?? '');
1767
- const others = await Promise.all((cfg.project?.others ?? []).map((o) => entry(o.name, o.rootDir, o.level2 ?? '')));
1840
+ const main = await entry((cfg.project?.name ?? '').trim(), rootDir, cfg.project?.level2 ?? '', cfg.project?.readOnly === true);
1841
+ const others = await Promise.all((cfg.project?.others ?? []).map((o) => entry(o.name, o.rootDir, o.level2 ?? '', o.readOnly === true)));
1768
1842
  return { ...main, others };
1769
1843
  }
1770
1844
  /**
@@ -1784,6 +1858,7 @@ let OperatorService = class OperatorService {
1784
1858
  await this.settings.update((raw) => {
1785
1859
  const current = (raw.project ?? {});
1786
1860
  const rootDir = patch.rootDir !== undefined ? patch.rootDir.trim() : (current.rootDir ?? '').trim();
1861
+ const readOnly = patch.readOnly !== undefined ? patch.readOnly === true : current.readOnly === true;
1787
1862
  const name = patch.name !== undefined ? patch.name.trim() : (current.name ?? '').trim();
1788
1863
  const level2 = patch.level2 !== undefined ? patch.level2 : (current.level2 ?? '');
1789
1864
  // Each goes into Kerrigan whole, and she is pasted into a chat: bounded, so one project cannot crowd out the rest.
@@ -1803,6 +1878,8 @@ let OperatorService = class OperatorService {
1803
1878
  name: (o.name ?? '').trim(),
1804
1879
  rootDir: (o.rootDir ?? '').trim(),
1805
1880
  level2: o.level2 !== undefined ? o.level2 : (was?.level2 ?? ''),
1881
+ // Kept like the level 2 when the list comes without it: a page that does not know the box must not clear it.
1882
+ readOnly: o.readOnly !== undefined ? o.readOnly === true : was?.readOnly === true,
1806
1883
  };
1807
1884
  });
1808
1885
  const seen = new Set();
@@ -1822,7 +1899,7 @@ let OperatorService = class OperatorService {
1822
1899
  }
1823
1900
  // What the removed Desktop copies left in the stored project is dropped with the next save.
1824
1901
  const { mirror: _m, desktop: _d, mirrorToDesktop: _t, ...rest } = current;
1825
- return { ...raw, project: { ...rest, rootDir, name, level2, others } };
1902
+ return { ...raw, project: { ...rest, rootDir, name, level2, readOnly, others } };
1826
1903
  });
1827
1904
  return await this.project();
1828
1905
  }
@@ -314,6 +314,11 @@ export const RunConfigSchema = z.object({
314
314
  * saved or copied, so the chat she helps in knows the project; the bot sends it nowhere by itself.
315
315
  */
316
316
  level2: z.string().default(''),
317
+ /**
318
+ * For reference only (operator, 2026-10-21): the bot may read it and run what only reads, and nothing in it
319
+ * may change while it works. Whatever a step changes there is put back (see `vcs/referenceGuard.ts`).
320
+ */
321
+ readOnly: z.boolean().default(false),
317
322
  /**
318
323
  * The other folders this operator works in, each with a short name: a front end, a back
319
324
  * end, the test suite. They are not defaults — a new session still starts on `rootDir` —
@@ -328,15 +333,42 @@ export const RunConfigSchema = z.object({
328
333
  rootDir: z.string().trim().min(1),
329
334
  /** Its level 2, as the default project's `level2`. */
330
335
  level2: z.string().default(''),
336
+ /** For reference only, as the default project's `readOnly`. */
337
+ readOnly: z.boolean().default(false),
331
338
  }))
332
339
  .default([]),
333
340
  })
334
341
  .prefault({}),
342
+ /**
343
+ * Skills (operator, 2026-10-21: "a skill I can set and call for a certain task — information that belongs only to
344
+ * one task that comes back: adding a new automated test, a new entity, migrations of the database"): instructions
345
+ * for a kind of task, chosen under the chat's box or with `/its-name` at the start of a message, and sent to the
346
+ * chat with that message. `projectDir` is the project a skill is for; empty, every project. Kept loose here, so a
347
+ * hand-edited file still loads; the API holds what it saves to the rules (see `setSkills` in operator.service.ts).
348
+ */
349
+ skills: z
350
+ .array(z.object({
351
+ name: z.string().trim().min(1),
352
+ description: z.string().default(''),
353
+ text: z.string().default(''),
354
+ projectDir: z.string().default(''),
355
+ }))
356
+ .default([]),
335
357
  pacing: z
336
358
  .object({
337
359
  enabled: z.boolean().default(true),
338
360
  settleMs: z.number().int().nonnegative().default(1000),
339
361
  maxMessagesPerHour: z.number().int().positive().default(60),
362
+ /**
363
+ * A pause between two messages to Copilot (operator, 2026-10-21: "how often a message may be sent — one a minute,
364
+ * say: a message sent, the next no sooner than 60 seconds after"), and with `gapRandom` a time drawn anew each
365
+ * time between `gapSec` and `gapMaxSec` ("between 60 and 90"). Held across every conversation of the window,
366
+ * the lead's and the worker's alike (see `util/pacing.ts`).
367
+ */
368
+ gapEnabled: z.boolean().default(false),
369
+ gapSec: z.number().int().min(1).max(3600).default(60),
370
+ gapRandom: z.boolean().default(false),
371
+ gapMaxSec: z.number().int().min(1).max(3600).default(90),
340
372
  })
341
373
  .prefault({}),
342
374
  limits: z
@@ -5,7 +5,7 @@ import { inlineCodeRefusal, programRefusal } from './programs.js';
5
5
  import { unattendedIsolationRefusal } from './isolation.js';
6
6
  import { confinementRefusal } from './confinement.js';
7
7
  import { botSelfRefusal, networkFetchReason, networkFetchRefusal } from './network.js';
8
- import { scriptFileRefusal } from './scriptFiles.js';
8
+ import { ownScriptRefusal, scriptFileRefusal } from './scriptFiles.js';
9
9
  export function describeStep(step) {
10
10
  // The shell it will really be read by, not the one this file used to assume: a line in the
11
11
  // log that names an interpreter the machine has not got explains the wrong failure.
@@ -173,6 +173,16 @@ export function unattendedPrecondition(cfg) {
173
173
  * decision when it is refused without asking anyone.
174
174
  */
175
175
  export function staticCheck(step, cfg, env = process.env, confinement) {
176
+ /*
177
+ * Only the project's own scripts, and nothing from .cop-tmp (operator, 2026-10-21): a script the chat wrote is not
178
+ * run, however it is called. First, so the chat is told that, and not the older advice of the shared gate to write
179
+ * a script in one step and run it in the next. See `scriptFiles.ts`.
180
+ */
181
+ if (confinement) {
182
+ const own = ownScriptRefusal(step.cmd, confinement.cwd, confinement.workStartedAt);
183
+ if (own)
184
+ return { action: 'skip', reason: own };
185
+ }
176
186
  // Screened against the shell that will actually read it: the traps in `shellExecuteTrap.ts`
177
187
  // are shell-specific, so screening for one interpreter and running in another finds nothing.
178
188
  const reason = commandRefusal(step.cmd, effectiveShell(step.shell), cfg.denyPatterns, cfg.allowedPrograms, env, confinement);
@@ -18,9 +18,19 @@
18
18
  * Covered: PowerShell scripts given to `-File`, dot-sourced, or called with `&` or by path. Not
19
19
  * covered, and stated so: a `.js`, `.py` or `.cs` file a project's own tools run. Those are the
20
20
  * project's code, and this runner has never claimed to read it; the boundary there is isolation.
21
+ *
22
+ * And since 2026-10-21, for the chat's steps, a third rule (`ownScriptRefusal`): only the project's own scripts run
23
+ * at all. The operator: "I do not want the project to run scripts downloaded from the internet, or ones it created
24
+ * itself — everything is dynamic, not from files", then "that is for scripts from the internet; the ones that are
25
+ * part of it and needed stay", and "npm and the like of course; I mean only scripts from files, not whether the bot
26
+ * runs the tests or the back end". What the chat writes comes from Copilot, a service on the internet, so a script
27
+ * it wrote is a script from the internet. A script file a step runs must therefore be the project's own: committed
28
+ * in its repository, unchanged since, last committed by someone other than the runner and before the work began;
29
+ * nothing is run from `.cop-tmp`. What a step does it says in the step itself, which may be several lines.
21
30
  */
22
- import { readFileSync, statSync } from 'node:fs';
23
- import { isAbsolute, resolve } from 'node:path';
31
+ import { existsSync, readFileSync, statSync } from 'node:fs';
32
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
33
+ import { gitSync, RUNNER_EMAIL } from '../vcs/git.js';
24
34
  /** Larger than this is not a step's script; it is not read, and running it is refused. */
25
35
  const MAX_SCRIPT_BYTES = 256 * 1024;
26
36
  /** Paths of PowerShell scripts this command line runs, as written. */
@@ -79,3 +89,99 @@ export function scriptFileRefusal(command, cwd, screen) {
79
89
  }
80
90
  return null;
81
91
  }
92
+ /** The folder for scratch files (`vcs/artifacts.ts` keeps it out of every commit); nothing in it is run. */
93
+ const SCRATCH = '.cop-tmp';
94
+ /** A program that runs a file it is given: the shells, the scripting runtimes, the TypeScript runners. */
95
+ const RUNS_A_FILE = String.raw `(?:node|nodejs|python3?|py|pwsh|powershell|cmd|tsx|ts-node|deno|bun|ruby|perl|php|cscript|wscript|bash|sh|java|dotnet|npx|vitest|jest|mocha)`;
96
+ /**
97
+ * The script files a command line runs — PowerShell's `.ps1` and `.psm1`, cmd's `.cmd` and `.bat`, bash's `.sh`,
98
+ * Windows Script Host's `.vbs`, `.wsf` and the rest — as full paths:
99
+ * given to `-File`, dot-sourced, called with `&` or by a path, passed to `cmd /c`, started with Start-Process, or
100
+ * imported as a module. A bare name counts only when that file is in the folder, where cmd and Start-Process look
101
+ * first; otherwise it is a program found on PATH — `npm.cmd`, `npx.cmd` — and not one of the project's files.
102
+ */
103
+ export function shellScriptsRun(command, cwd) {
104
+ const named = new Set(scriptPathsRun(command));
105
+ const patterns = [
106
+ /(?:^|[|;&(\n{]\s*)(?:[.&]\s+)?(?:"([^"]+\.(?:ps1|psm1|cmd|bat))"|'([^']+\.(?:ps1|psm1|cmd|bat))'|(\S+\.(?:ps1|psm1|cmd|bat)))(?=\s|$)/gi,
107
+ /\bcmd(?:\.exe)?\b[^|;\n]*?\s\/[ck]\s+(?:"([^"]+\.(?:cmd|bat))"|'([^']+\.(?:cmd|bat))'|(\S+\.(?:cmd|bat)))/gi,
108
+ /\b(?:Start-Process|saps)\b[^|;\n]*?(?:"([^"]+\.(?:ps1|cmd|bat))"|'([^']+\.(?:ps1|cmd|bat))'|([^\s'",]+\.(?:ps1|cmd|bat)))/gi,
109
+ /\b(?:Import-Module|ipmo)\b[^|;\n]*?(?:"([^"]+\.psm1)"|'([^']+\.psm1)'|(\S+\.psm1))/gi,
110
+ // A shell script for bash and its kin (Git Bash, WSL), by a path or given to the shell.
111
+ /(?:^|[|;&(\n{]\s*)(?:"([^"]+\.(?:sh|bash|zsh))"|'([^']+\.(?:sh|bash|zsh))'|(\S+\.(?:sh|bash|zsh)))(?=\s|$)/gi,
112
+ /\b(?:bash|sh|zsh|ksh|dash|wsl)(?:\.exe)?\b[^|;\n]*?\s(?:"([^"]+\.(?:sh|bash|zsh))"|'([^']+\.(?:sh|bash|zsh))'|(\S+\.(?:sh|bash|zsh)))/gi,
113
+ // Windows Script Host's scripts.
114
+ /\b(?:wscript|cscript)(?:\.exe)?\b[^|;\n]*?\s(?:"([^"]+\.(?:vbs|vbe|js|jse|wsf|wsh))"|'([^']+\.(?:vbs|vbe|js|jse|wsf|wsh))'|(\S+\.(?:vbs|vbe|js|jse|wsf|wsh)))/gi,
115
+ /(?:^|[|;&(\n{]\s*)(?:[.&]\s+)?(?:"([^"]+\.(?:vbs|vbe|wsf|wsh|hta))"|'([^']+\.(?:vbs|vbe|wsf|wsh|hta))'|(\S+\.(?:vbs|vbe|wsf|wsh|hta)))(?=\s|$)/gi,
116
+ ];
117
+ for (const re of patterns) {
118
+ for (const m of command.matchAll(re)) {
119
+ const p = (m[1] ?? m[2] ?? m[3] ?? '').trim();
120
+ if (p)
121
+ named.add(p);
122
+ }
123
+ }
124
+ const files = new Set();
125
+ for (const p of named) {
126
+ const full = isAbsolute(p) ? p : resolve(cwd, p);
127
+ if (!/[\\/]/.test(p) && !existsSync(full))
128
+ continue;
129
+ files.add(full);
130
+ }
131
+ return [...files];
132
+ }
133
+ /** Whether a path lies in the scratch folder, at any depth. */
134
+ const inScratch = (path) => path.split(/[\\/]+/).some((part) => part.toLowerCase() === SCRATCH);
135
+ /**
136
+ * Why a script is not one of the project's own, or null when it is: in its repository, committed, unchanged since,
137
+ * last committed by someone other than the runner and, when `since` is known, before the work began.
138
+ */
139
+ export function notTheProjects(file, since) {
140
+ if (inScratch(file))
141
+ return `it is in ${SCRATCH}, the folder for scratch files, and nothing there is run`;
142
+ if (!existsSync(file))
143
+ return 'it does not exist';
144
+ const top = gitSync(dirname(file), ['rev-parse', '--show-toplevel']);
145
+ if (!top.ok || !top.stdout)
146
+ return 'it is not in a git repository, so nothing tells it apart from a script written during the work';
147
+ const rel = relative(top.stdout, file);
148
+ const path = rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel.replace(/\\/g, '/') : file;
149
+ if (!gitSync(top.stdout, ['ls-files', '--error-unmatch', '--', path]).ok)
150
+ return 'it is not committed in its repository';
151
+ const diff = gitSync(top.stdout, ['diff', '--quiet', 'HEAD', '--', path]);
152
+ if (diff.code === 1)
153
+ return 'it was changed since it was last committed';
154
+ if (!diff.ok)
155
+ return `git could not compare it with its last commit${diff.stderr ? ` (${diff.stderr.split('\n')[0]})` : ''}`;
156
+ const last = gitSync(top.stdout, ['log', '-1', '--format=%ae%x09%ct', '--', path]);
157
+ const [email = '', time = ''] = last.stdout.split('\t');
158
+ if (email.trim().toLowerCase() === RUNNER_EMAIL)
159
+ return 'its last commit was made by copilot-operator, so it was written during the work';
160
+ const began = since ? Date.parse(since) : NaN;
161
+ if (Number.isFinite(began) && Number(time) * 1000 >= began - 1000)
162
+ return 'it was committed after this work began, so it was written during the work';
163
+ return null;
164
+ }
165
+ /**
166
+ * 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.
169
+ */
170
+ export function ownScriptRefusal(command, cwd, since) {
171
+ // 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
+ 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
+ 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.';
177
+ for (const file of shellScriptsRun(command, cwd)) {
178
+ const reason = notTheProjects(file, since);
179
+ if (reason)
180
+ return why(file, reason);
181
+ }
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.');
185
+ }
186
+ return null;
187
+ }
@@ -23,7 +23,7 @@ import { appendFile, mkdir, writeFile } from 'node:fs/promises';
23
23
  import { isReplyTimeout, WindowClosed } from '../transport/chatTransport.js';
24
24
  import { buildChatName, chatCode, savePointer } from '../transport/chatSession.js';
25
25
  import { RunLog } from '../log/runLog.js';
26
- import { Pacer } from '../util/pacing.js';
26
+ import { gapFrom, Pacer } from '../util/pacing.js';
27
27
  import { takeAfter, takeCheckpoint } from '../session/checkpoint.js';
28
28
  import { commitFiles } from '../vcs/git.js';
29
29
  import { buildStory } from '../session/story.js';
@@ -43,6 +43,18 @@ export function assignmentMessage(task, n, facts, again) {
43
43
  '',
44
44
  task.prompt.trim(),
45
45
  '',
46
+ // The operator's skill for this kind of work (2026-10-21): the lead plans by it, and every subtask carries it to the worker.
47
+ ...(task.skill?.text.trim()
48
+ ? [
49
+ `## Skill: ${task.skill.name}`,
50
+ '',
51
+ ...(task.skill.description.trim() ? [`For: ${task.skill.description.trim()}`, ''] : []),
52
+ 'The operator\'s instructions for this kind of work. Plan and judge the work by them; the worker is given them with every subtask.',
53
+ '',
54
+ task.skill.text.trim(),
55
+ '',
56
+ ]
57
+ : []),
46
58
  '## What the runner tells you',
47
59
  '',
48
60
  `- The project folder, where the worker's commands run: ${facts.workDir || '(none is open)'}.`,
@@ -50,6 +62,11 @@ export function assignmentMessage(task, n, facts, again) {
50
62
  facts.planApproval
51
63
  ? '- The operator approves plans: when you send "plan", the work waits for their answer.'
52
64
  : '- Plans are not put to the operator here: send "plan" all the same, so it is on record; the work goes on at once.',
65
+ ...((facts.reference?.length ?? 0) > 0
66
+ ? [
67
+ `- For reference only, changed by nothing: ${facts.reference.map((p) => `${p.name} (${p.dir})`).join(', ')}. The worker may read them and run what only reads; whatever it changes there is put back. Plan no change in them; if the result needs one, say so to the operator.`,
68
+ ]
69
+ : []),
53
70
  '- Reply in the lead\'s format.',
54
71
  ]
55
72
  .filter((l, i) => l !== '' || i > 0)
@@ -183,7 +200,14 @@ export async function runLeadTask(transport, session, task, deps) {
183
200
  sink.event('chat-checkpoint', { commit: cp.commit, branch: cp.branch, head: cp.head }, `the folder before this message is kept as ${cp.commit.slice(0, 8)} (on ${cp.branch || cp.head.slice(0, 8)})`);
184
201
  }
185
202
  }
186
- const pacer = new Pacer({ enabled: cfg.pacing.enabled, settleMs: cfg.pacing.settleMs, maxMessagesPerHour: cfg.pacing.maxMessagesPerHour });
203
+ const pacer = new Pacer({
204
+ enabled: cfg.pacing.enabled,
205
+ settleMs: cfg.pacing.settleMs,
206
+ maxMessagesPerHour: cfg.pacing.maxMessagesPerHour,
207
+ gapMs: gapFrom(cfg.pacing),
208
+ signal,
209
+ onGap: (ms) => sink.event('pacing-gap', { ms, lead: true }, `the next message to the lead waits ${Math.ceil(ms / 1000)} s: Settings ask for a pause between messages`),
210
+ });
187
211
  let limitHit;
188
212
  /*
189
213
  * Paused (see `Hold`): the lead's next message waits, as the worker's do in `runTask`. True when the run was stopped
@@ -213,6 +237,9 @@ export async function runLeadTask(transport, session, task, deps) {
213
237
  sink.event('operator-note-sent', { notes: notes.length, with: 'lead' }, `${notes.length} note(s) from the operator go to the lead`);
214
238
  const before = await leadChat.sendAndConfirm(message);
215
239
  sent += 1;
240
+ // Counted for the operator, with the worker's (2026-10-21): shown under the message and in the status bar.
241
+ lead.messages = { lead: sent, worker: lead.messages?.worker ?? 0 };
242
+ await saveLead();
216
243
  await writeFile(log.path('messages', `${String(sent).padStart(2, '0')}.md`), message, 'utf8').catch(() => undefined);
217
244
  sink.event('message-sent', { n: sent, chars: message.length, lead: true, chatId: session.chat?.chatId ?? null }, `message ${sent} sent to the lead (${message.length} chars)`);
218
245
  await record(`TO THE LEAD (${sent})`, message);
@@ -357,7 +384,7 @@ export async function runLeadTask(transport, session, task, deps) {
357
384
  });
358
385
  sink.event('worker-fresh', { n }, `subtask ${n} goes to a fresh worker conversation`);
359
386
  }
360
- const made = await store.addTask(worker.id, { title: `${n}. ${sub.title}`, level2: '', prompt: subtaskPrompt(sub, n), reviewEnabled: false, readOnly: sub.readOnly });
387
+ const made = await store.addTask(worker.id, { title: `${n}. ${sub.title}`, level2: '', prompt: subtaskPrompt(sub, n), reviewEnabled: false, readOnly: sub.readOnly, ...(task.skill ? { skill: task.skill } : {}) });
361
388
  await store.updateTask(worker.id, made.id, (t) => {
362
389
  t.fromLead = { sessionId: session.id, taskId: task.id, n };
363
390
  });
@@ -377,7 +404,22 @@ export async function runLeadTask(transport, session, task, deps) {
377
404
  }
378
405
  const current = (await store.getSession(worker.id));
379
406
  const subtask = current.tasks.find((x) => x.id === made.id);
380
- const out = await runTask(transport, current, subtask, { ...deps, approvePlan: undefined });
407
+ // Every message the worker's task sends is counted as the worker's, as it goes.
408
+ const counted = new Proxy(transport, {
409
+ get(target, key) {
410
+ if (key === 'sendAndConfirm') {
411
+ return async (...args) => {
412
+ const r = await target.sendAndConfirm(...args);
413
+ lead.messages = { lead: lead.messages?.lead ?? sent, worker: (lead.messages?.worker ?? 0) + 1 };
414
+ await saveLead();
415
+ return r;
416
+ };
417
+ }
418
+ const value = Reflect.get(target, key, target);
419
+ return typeof value === 'function' ? value.bind(target) : value;
420
+ },
421
+ });
422
+ const out = await runTask(counted, current, subtask, { ...deps, approvePlan: undefined });
381
423
  speakFor(transport, session.id);
382
424
  if (transport.closedOutside())
383
425
  throw new WindowClosed();
@@ -402,6 +444,10 @@ export async function runLeadTask(transport, session, task, deps) {
402
444
  maxIterations: cfg.limits.maxIterations,
403
445
  maxRunMinutes: cfg.limits.maxRunMinutes,
404
446
  planApproval: session.planMode === 'approve' && !!deps.approvePlan,
447
+ reference: [
448
+ ...(cfg.project.readOnly && cfg.project.rootDir ? [{ name: cfg.project.name || cfg.project.rootDir, dir: cfg.project.rootDir }] : []),
449
+ ...cfg.project.others.filter((o) => o.readOnly).map((o) => ({ name: o.name, dir: o.rootDir })),
450
+ ],
405
451
  };
406
452
  const n = session.tasks.findIndex((x) => x.id === task.id) + 1;
407
453
  const contract = (await store.getLead1()).content.trim();
@@ -261,8 +261,8 @@ export async function runReview(transport, session, task, deps) {
261
261
  // The machine's shells, when they are not what the contract's example assumes — the same note
262
262
  // the implementer's conversation opens with, for a conversation working to the same example.
263
263
  const machineNote = shellNote(undefined, defaultShell);
264
- let before = await transport.sendAndConfirm(machineNote ? `${contract}
265
-
264
+ let before = await transport.sendAndConfirm(machineNote ? `${contract}
265
+
266
266
  ${machineNote}` : contract);
267
267
  await transport.waitForReply(before);
268
268
  await pacer.throttleSend();
@@ -471,7 +471,7 @@ ${machineNote}` : contract);
471
471
  sessionId: session.id,
472
472
  taskId: task.id,
473
473
  iteration: iterations,
474
- confinement: { roots: deps.roots, cwd: deps.cwd },
474
+ confinement: { roots: deps.roots, cwd: deps.cwd, workStartedAt: deps.workStartedAt },
475
475
  });
476
476
  if (decision.action !== 'run') {
477
477
  results.push(refused(step.id, decision.reason, step.cmd, step.shell, decision.by === 'operator' ? 'operator' : 'runner'));
@@ -510,10 +510,16 @@ ${machineNote}` : contract);
510
510
  }, { signal, tracker: deps.tracker });
511
511
  stepsRun += 1;
512
512
  results.push(result);
513
+ const touched = deps.afterStep ? await deps.afterStep().catch(() => null) : null;
514
+ if (touched)
515
+ result.stderr = `${result.stderr}${result.stderr && !result.stderr.endsWith('\n') ? '\n' : ''}[runner] ${touched}\n`;
513
516
  deps.event('review-step-finished', { round, id: step.id, outcome: result.outcome, exitCode: result.exitCode, shell: result.shell, requestedShell: result.requestedShell ?? null, shellPath: result.shellPath ?? '' }, `review step ${step.id}: ${result.outcome}, exit ${result.exitCode}, ${(result.durationMs / 1000).toFixed(1)}s`);
514
517
  // Stopped while it ran: no step after it is started, and the report waits below.
515
518
  if (signal?.aborted)
516
519
  break;
520
+ // A project for reference only was changed and put back: the rest of the round is not run.
521
+ if (touched)
522
+ break;
517
523
  await pacer.settle();
518
524
  }
519
525
  const report = await writeReport(results, {