copilot-operator 0.1.75 → 0.1.81

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 (70) hide show
  1. package/dist/src/api/operator.controller.js +7 -4
  2. package/dist/src/api/operator.service.js +75 -26
  3. package/dist/src/api/server.js +3 -2
  4. package/dist/src/config/live.js +122 -0
  5. package/dist/src/exec/commandHeads.js +11 -2
  6. package/dist/src/exec/locations.js +194 -0
  7. package/dist/src/exec/network.js +3 -1
  8. package/dist/src/exec/scriptFiles.js +46 -21
  9. package/dist/src/exec/stops.js +147 -0
  10. package/dist/src/orchestrator/chosenAnswers.js +22 -0
  11. package/dist/src/orchestrator/handoff.js +37 -2
  12. package/dist/src/orchestrator/leadRunner.js +39 -22
  13. package/dist/src/orchestrator/taskRunner.js +129 -50
  14. package/dist/src/plan/kerrigan.js +2 -2
  15. package/dist/src/plan/systemGuide.js +38 -22
  16. package/dist/src/protocol/leadSchema.js +6 -1
  17. package/dist/src/protocol/replySchema.js +6 -0
  18. package/dist/src/queue/queue.js +6 -0
  19. package/dist/src/session/model.js +12 -0
  20. package/dist/src/util/pacing.js +6 -0
  21. package/dist/web/404.html +2 -2
  22. package/dist/web/_next/static/chunks/1024-17c74da39fb738c9.js +1 -0
  23. package/dist/web/_next/static/chunks/1077.89c88ca151fa06dd.js +1 -0
  24. package/dist/web/_next/static/chunks/1548.0b1ef8dbcd9208ea.js +1 -0
  25. package/dist/web/_next/static/chunks/2163.2847204ac3bdefd8.js +1 -0
  26. package/dist/web/_next/static/chunks/714.49218f1c7d549cd8.js +1 -0
  27. package/dist/web/_next/static/chunks/7220.6aa4247d697dda80.js +1 -0
  28. package/dist/web/_next/static/chunks/7921-8f8cb241fa524eae.js +1 -0
  29. package/dist/web/_next/static/chunks/8124-2f07cc63c1494443.js +1 -0
  30. package/dist/web/_next/static/chunks/8584.183614d44db3689b.js +1 -0
  31. package/dist/web/_next/static/chunks/895-9c1f0751920e6624.js +1 -0
  32. package/dist/web/_next/static/chunks/9067.6516feb0a44702b6.js +1 -0
  33. package/dist/web/_next/static/chunks/9747.fddf84fbe4cd50ca.js +1 -0
  34. package/dist/web/_next/static/chunks/app/layout-b8a1e0075a48b025.js +1 -0
  35. package/dist/web/_next/static/chunks/app/page-4a7cf5d83c000d73.js +1 -0
  36. package/dist/web/_next/static/chunks/app/queue/{page-82f724d0842f4870.js → page-317151444eda8115.js} +1 -1
  37. package/dist/web/_next/static/chunks/app/settings/page-e3909ef6c2d8e321.js +1 -0
  38. package/dist/web/_next/static/chunks/{webpack-f9f820c51a8952c8.js → webpack-864ad2757e758155.js} +1 -1
  39. package/dist/web/_next/static/css/0e586e29189e8783.css +1 -0
  40. package/dist/web/defaults.html +2 -2
  41. package/dist/web/defaults.txt +8 -8
  42. package/dist/web/index.html +3 -3
  43. package/dist/web/index.txt +9 -9
  44. package/dist/web/queue.html +2 -2
  45. package/dist/web/queue.txt +9 -9
  46. package/dist/web/settings.html +2 -2
  47. package/dist/web/settings.txt +9 -9
  48. package/dist/web/system.html +2 -2
  49. package/dist/web/system.txt +9 -9
  50. package/package.json +4 -3
  51. package/prompts/lead1.md +5 -2
  52. package/prompts/level1.md +8 -2
  53. package/dist/web/_next/static/chunks/1024-67625a65f58057ae.js +0 -1
  54. package/dist/web/_next/static/chunks/1077.14d6c828d8f71111.js +0 -1
  55. package/dist/web/_next/static/chunks/1548.2f75926c6e664f79.js +0 -1
  56. package/dist/web/_next/static/chunks/2163.f9f1ad4af05520cc.js +0 -1
  57. package/dist/web/_next/static/chunks/714.4507656685cb9337.js +0 -1
  58. package/dist/web/_next/static/chunks/7220.9bc9dd9f211b11e4.js +0 -1
  59. package/dist/web/_next/static/chunks/7921-9aaec581982b2329.js +0 -1
  60. package/dist/web/_next/static/chunks/8124-a39d85dff0db6600.js +0 -1
  61. package/dist/web/_next/static/chunks/8584.f2cb3ca81223d626.js +0 -1
  62. package/dist/web/_next/static/chunks/9067.a6cb3b9157a80921.js +0 -1
  63. package/dist/web/_next/static/chunks/9747.15aa40a046d54a2a.js +0 -1
  64. package/dist/web/_next/static/chunks/9929-2e0b1d006ebd5345.js +0 -1
  65. package/dist/web/_next/static/chunks/app/layout-52a2079ffa83c21f.js +0 -1
  66. package/dist/web/_next/static/chunks/app/page-80730838a81da226.js +0 -1
  67. package/dist/web/_next/static/chunks/app/settings/page-4f3c739287d7f32e.js +0 -1
  68. package/dist/web/_next/static/css/63b30b8e1a4aa500.css +0 -1
  69. /package/dist/web/_next/static/{9DmRzBb0M5BZ3dvVpbFMM → UJ2ArYHXgNEpx4W-ZdIgB}/_buildManifest.js +0 -0
  70. /package/dist/web/_next/static/{9DmRzBb0M5BZ3dvVpbFMM → UJ2ArYHXgNEpx4W-ZdIgB}/_ssgManifest.js +0 -0
@@ -94,9 +94,9 @@ let OperatorController = class OperatorController {
94
94
  const scripts = { inForce: resolved.execution.scripts, writtenScripts: resolved.execution.writtenScripts };
95
95
  return { raw, defaults, resolved: resolved.resolved, picker, programs, scripts };
96
96
  }
97
+ /** Saved, and taken at once by the work going on where it can be (2026-11-03): the answer says what was, and what waits. */
97
98
  async saveSettings(body) {
98
- await this.ops.settings.save(body).catch(fail);
99
- return { ok: true };
99
+ return await this.ops.saveSettings(body).catch(fail);
100
100
  }
101
101
  // --- level 1 ----------------------------------------------------------------------------
102
102
  /** The contract the bot gives Copilot, as it ships: shown in Settings to read, changed only by an update of the bot. */
@@ -404,9 +404,12 @@ let OperatorController = class OperatorController {
404
404
  throw new BadRequestException('n, the subtask\'s number, is required');
405
405
  return this.ops.chatRetrySubtask(id, taskId, n, body?.fresh === true).catch(fail);
406
406
  }
407
- /** The lead's question (two chats): the operator's answer, as text. Stopping the task is `approvals/:id` with abort. */
407
+ /**
408
+ * A question of the chat or the lead: the operator's answer, as text; for one of several answers (2026-11-02), the
409
+ * ones chosen by their place in `chosen`, with any text besides. Stopping the task is `approvals/:id` with abort.
410
+ */
408
411
  answerQuestion(id, body) {
409
- const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '', body?.ran === false ? false : undefined, typeof body?.outcome === 'string' ? body.outcome : undefined);
412
+ const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '', body?.ran === false ? false : undefined, typeof body?.outcome === 'string' ? body.outcome : undefined, body?.chosen);
410
413
  if (!result.ok)
411
414
  throw new BadRequestException(result.problem);
412
415
  return result;
@@ -23,10 +23,11 @@ import { SessionStore, DEFAULT_VCS, DEFAULT_REVIEW, writeFileAtomically } from '
23
23
  import { checkItems, emptyQueue, itemTitle, mergeItems, nextStep, parkAfterMs, parkedAnswerFrom, skippedBecause, statusOfTask, waitsByHand, MAX_PARK_AFTER_SEC, PARKED_WORDS } from '../queue/queue.js';
24
24
  import { branchStart, makeQueueBranch, refreshQueueBranch } from '../queue/queueBranch.js';
25
25
  import { EventBus } from '../session/events.js';
26
- import { MAX_INSTRUCTION_CHARS, newId } from '../session/model.js';
26
+ import { MAX_INSTRUCTION_CHARS, newId, withProblemAt } from '../session/model.js';
27
27
  import { handoffOutcomeOf, handoffResultMessage } from '../orchestrator/handoff.js';
28
28
  import { runSession, queuedToRun, failedWhileOpening, pickerOptions } from '../orchestrator/taskRunner.js';
29
29
  import { Hold, WaitsFor } from '../orchestrator/hold.js';
30
+ import { chosenAnswer, chosenSaid } from '../orchestrator/chosenAnswers.js';
30
31
  import { exportFileName, exportMachine, writeAttemptRecord } from '../session/exports.js';
31
32
  import { suggestRunName } from '../session/runName.js';
32
33
  import { buildStory } from '../session/story.js';
@@ -36,8 +37,6 @@ import { kerriganFileName, kerriganPersona } from '../plan/kerrigan.js';
36
37
  import { branchChanges, gitCounts, workspaceCommit, workspaceGit, workspaceGitVersions } from '../session/workspaceGit.js';
37
38
  import { chatCode } from '../transport/chatSession.js';
38
39
  /** The folders the operator works in: the default new sessions start on, and the rest by name. */
39
- /** The longest level 2 a project may have: Kerrigan carries each one whole. */
40
- export const MAX_PROJECT_LEVEL2 = 8000;
41
40
  /** The longest name a conversation or a session may be given (2026-10-26). */
42
41
  export const MAX_SESSION_NAME = 120;
43
42
  /*
@@ -100,6 +99,25 @@ import { createZip } from '../util/zip.js';
100
99
  import { settingsOf, SettingsUnusableError } from './settings.js';
101
100
  import { PolicyLockUnusableError } from '../config/lockedPolicy.js';
102
101
  import { chatDenyPatterns } from '../config/schema.js';
102
+ import { LiveSettings, mergedChange } from '../config/live.js';
103
+ /**
104
+ * The rules each step of a run is judged by, from its settings: at the start, and again when a save changes them while
105
+ * it goes on (2026-11-03). The mode is not among them: it is the start's, and "run the rest without asking" changes it.
106
+ */
107
+ function stepRules(cfg) {
108
+ return {
109
+ denyPatterns: cfg.execution.denyPatterns,
110
+ allowedPrograms: cfg.execution.allowedPrograms,
111
+ isolation: cfg.execution.isolation,
112
+ lockedToConfirm: cfg.policyLock?.maxMode === 'confirm',
113
+ networkFetch: cfg.execution.networkFetch,
114
+ platformAccess: cfg.execution.questions === 'agree' ? 'allow' : 'ask',
115
+ readOnlyPrograms: cfg.execution.readOnlyPrograms,
116
+ runWithoutAsking: cfg.execution.runWithoutAsking,
117
+ scripts: cfg.execution.scripts,
118
+ writtenScripts: cfg.execution.writtenScripts,
119
+ };
120
+ }
103
121
  const INACTIVE_REASON = 'the session is inactive; make it active on the Sessions page to run it';
104
122
  /**
105
123
  * Why the browser cannot be had now, said in terms of what was pressed. The sentences a start, a
@@ -301,7 +319,7 @@ let OperatorService = class OperatorService {
301
319
  if (interruption)
302
320
  t.interruption = interruption;
303
321
  if (vcs?.commit) {
304
- t.vcs = vcs;
322
+ t.vcs = withProblemAt(t.vcs, vcs);
305
323
  t.reason = `${t.reason ?? ''} What it had changed is committed on ${vcs.branch} as ${vcs.commit?.slice(0, 8)}.`.trim();
306
324
  }
307
325
  // The same fixed-shape ending a task the runner finished gets; the steps the bot never
@@ -868,20 +886,10 @@ let OperatorService = class OperatorService {
868
886
  const loaded = await this.settings.load();
869
887
  // A chat conversation's git is the operator's: switching branches and committing are allowed there (2026-10-17).
870
888
  const cfg = session.kind === 'chat' ? { ...loaded, execution: { ...loaded.execution, denyPatterns: chatDenyPatterns(loaded.execution.denyPatterns) } } : loaded;
871
- const policy = {
872
- mode,
873
- denyPatterns: cfg.execution.denyPatterns,
874
- allowedPrograms: cfg.execution.allowedPrograms,
875
- isolation: cfg.execution.isolation,
876
- lockedToConfirm: cfg.policyLock?.maxMode === 'confirm',
877
- // Read once per run like the rest of the policy: a change in Settings applies from the next start.
878
- networkFetch: cfg.execution.networkFetch,
879
- platformAccess: cfg.execution.questions === 'agree' ? 'allow' : 'ask',
880
- readOnlyPrograms: cfg.execution.readOnlyPrograms,
881
- runWithoutAsking: cfg.execution.runWithoutAsking,
882
- scripts: cfg.execution.scripts,
883
- writtenScripts: cfg.execution.writtenScripts,
884
- };
889
+ // The run's own settings; a save while it goes on changes them in place (`saveSettings`), and these rules with them.
890
+ const runCfg = { ...cfg, execution: { ...cfg.execution, mode } };
891
+ const live = new LiveSettings(runCfg, session.kind === 'chat', loaded);
892
+ const policy = { mode, ...stepRules(runCfg) };
885
893
  /*
886
894
  * An unattended run that cannot legally execute anything is stopped here, where the operator
887
895
  * is looking, rather than starting and returning every step refused. The step gate holds the
@@ -908,7 +916,7 @@ let OperatorService = class OperatorService {
908
916
  const authorizer = this.webAuthorizer(policy, controller.signal);
909
917
  const startedAt = new Date().toISOString();
910
918
  const hold = new Hold();
911
- this.running.set(sessionId, { controller, startedAt, mode, policy, hold });
919
+ this.running.set(sessionId, { controller, startedAt, mode, policy, hold, live });
912
920
  // Who was at work in a run of it that ended without saying so is not who is at work in this one.
913
921
  this.acting.delete(sessionId);
914
922
  {
@@ -930,7 +938,8 @@ let OperatorService = class OperatorService {
930
938
  'tenant; secret-shaped strings are redacted first',
931
939
  });
932
940
  const done = runSession(sessionId, {
933
- cfg: { ...cfg, execution: { ...cfg.execution, mode } },
941
+ cfg: runCfg,
942
+ live,
934
943
  store: this.store,
935
944
  bus: this.bus,
936
945
  authorizer,
@@ -1119,6 +1128,8 @@ let OperatorService = class OperatorService {
1119
1128
  ...(run?.hold?.held ? { paused: true } : {}),
1120
1129
  // Git asks for a password in its own window, and the work waits for it (2026-10-26).
1121
1130
  ...(this.passwordAsked.size > 0 ? { password: true } : {}),
1131
+ // The queue still has its turn going, between one of its tasks and the next (2026-11-03): the work is not over.
1132
+ ...(this.queueLoop ? { queue: true } : {}),
1122
1133
  // How the last message ended, while nothing runs: what the tab says until the operator has looked.
1123
1134
  ...(this.running.size === 0 && this.lastOutcome ? { last: { status: this.lastOutcome.status, at: this.lastOutcome.at } } : {}),
1124
1135
  };
@@ -1917,7 +1928,15 @@ let OperatorService = class OperatorService {
1917
1928
  }
1918
1929
  else if (a.kind === 'question') {
1919
1930
  const handed = p.approval.question?.handoff;
1920
- note = handed ? handoffResultMessage(handed, handoffOutcomeOf(a.outcome, a.ran), a.answer) : `You asked: ${p.approval.question?.text ?? ''}\n\nThe operator answers: ${a.answer}`;
1931
+ const q = p.approval.question;
1932
+ const asked = `You asked: ${q?.text ?? ''}\n\n`;
1933
+ // An answer chosen that carries a command (2026-11-02): the card says it runs it, so the chat is told to.
1934
+ const run = q && !a.chosen ? q.commands?.[q.options.indexOf(a.answer)] : undefined;
1935
+ note = handed
1936
+ ? handoffResultMessage(handed, handoffOutcomeOf(a.outcome, a.ran), a.answer)
1937
+ : a.chosen
1938
+ ? `${asked}The operator answered your question, ${chosenSaid({ chosen: a.chosen, ...(a.written ? { written: a.written } : {}) })}`
1939
+ : `${asked}The operator answers: ${a.answer}${run ? `\n\nThat answer carries a command: send \`${run}\` as your next step.` : ''}`;
1921
1940
  }
1922
1941
  else if (a.kind === 'retry' && p.approval.retry) {
1923
1942
  const r = p.approval.retry;
@@ -2124,6 +2143,7 @@ let OperatorService = class OperatorService {
2124
2143
  ...(ask.why ? { why: ask.why } : {}),
2125
2144
  options: ask.options,
2126
2145
  ...(ask.commands?.some(Boolean) ? { commands: ask.commands } : {}),
2146
+ ...(ask.multiple ? { multiple: true } : {}),
2127
2147
  ...(ask.handoff ? { handoff: ask.handoff } : {}),
2128
2148
  },
2129
2149
  };
@@ -2207,10 +2227,21 @@ let OperatorService = class OperatorService {
2207
2227
  const cfg = await this.settings.load();
2208
2228
  return await this.start(threadId, cfg.execution.mode);
2209
2229
  }
2210
- answerQuestion(approvalId, text, ran, outcome) {
2230
+ answerQuestion(approvalId, text, ran, outcome, chosen) {
2211
2231
  const w = this.waiting.get(approvalId);
2212
2232
  if (!w?.resolveAnswer)
2213
2233
  return { ok: false, problem: 'No question of the lead is waiting under that id.' };
2234
+ // A question of several answers (2026-11-02): the ones chosen, by their place, and what was written besides.
2235
+ if (chosen !== undefined && w.approval.question && !w.approval.question.handoff) {
2236
+ const many = chosenAnswer(w.approval.question, chosen, text);
2237
+ if ('problem' in many)
2238
+ return { ok: false, problem: many.problem };
2239
+ this.waiting.delete(approvalId);
2240
+ w.resolveAnswer(many);
2241
+ this.bus.publish({ sessionId: w.approval.sessionId, taskId: w.approval.taskId, type: 'approval-decided', level: 'info',
2242
+ message: `the operator chose ${many.chosen.length} of the answers`, data: { approvalId, question: true } });
2243
+ return { ok: true };
2244
+ }
2214
2245
  /*
2215
2246
  * Commands handed over (2026-10-26): what they printed; sent back for a correction, which needs what to correct
2216
2247
  * (2026-10-27); or that the operator will not run them, with a word or none.
@@ -2722,6 +2753,26 @@ let OperatorService = class OperatorService {
2722
2753
  * folder that is not there, a name used twice, and the default listed again among the others
2723
2754
  * — each of those would be a setting that looks filled in and points nowhere.
2724
2755
  */
2756
+ /**
2757
+ * Settings saved from their page (operator, 2026-11-03: "when I change a setting, if it can be, let it take effect at
2758
+ * once, even while a task is running"). Each run at work takes what can change under a message into its own settings
2759
+ * at once — the rules its steps are judged by with them — and the answer says, for the page to show, what did and
2760
+ * what waits for the next message or the next chat window. See `config/live.ts`.
2761
+ */
2762
+ async saveSettings(body) {
2763
+ const saved = await this.settings.save(body);
2764
+ const changes = [];
2765
+ for (const run of this.running.values()) {
2766
+ changes.push(run.live.take(saved));
2767
+ Object.assign(run.policy, stepRules(run.live.cfg));
2768
+ // A lock that holds runs to asking now holds this one too, whatever it started as.
2769
+ if (run.policy.lockedToConfirm && run.mode === 'unattended') {
2770
+ run.mode = 'confirm';
2771
+ run.policy.mode = 'confirm';
2772
+ }
2773
+ }
2774
+ return { ok: true, running: this.running.size, ...mergedChange(changes) };
2775
+ }
2725
2776
  async setProject(patch) {
2726
2777
  // Worked out from the file in its turn (see `Settings.update`), so a model chosen at the same
2727
2778
  // moment is kept, and a refusal below leaves the file as it was.
@@ -2731,10 +2782,8 @@ let OperatorService = class OperatorService {
2731
2782
  const readOnly = patch.readOnly !== undefined ? patch.readOnly === true : current.readOnly === true;
2732
2783
  const name = patch.name !== undefined ? patch.name.trim() : (current.name ?? '').trim();
2733
2784
  const level2 = patch.level2 !== undefined ? patch.level2 : (current.level2 ?? '');
2734
- // Each goes into Kerrigan whole, and she is pasted into a chat: bounded, so one project cannot crowd out the rest.
2735
- const tooLong = [{ name: name || rootDir, level2 }, ...(patch.others ?? [])].find((o) => (o.level2 ?? '').length > MAX_PROJECT_LEVEL2);
2736
- if (tooLong)
2737
- throw new Error(`The level 2 of "${tooLong.name}" is longer than ${MAX_PROJECT_LEVEL2.toLocaleString('en')} characters; keep it to what a chat needs to know about the project.`);
2785
+ // No limit to its length (operator, 2026-11-03: "remove the limit, so it can take megabytes if need be"): each goes
2786
+ // into Kerrigan whole, and only the size of a request (`server.ts`) bounds it.
2738
2787
  if (rootDir && !existsSync(rootDir))
2739
2788
  throw new Error(`The folder ${rootDir} does not exist on this machine.`);
2740
2789
  /*
@@ -59,8 +59,9 @@ export async function startApi(opts = {}) {
59
59
  captureTerminal();
60
60
  const app = await NestFactory.create(AppModule, { logger: opts.quiet ? ['error', 'warn'] : ['error', 'warn', 'log'] });
61
61
  // A plan pasted from a chat carries every task's text at once, which the 100 KB default
62
- // refuses with a message about entity size that says nothing about plans.
63
- app.useBodyParser('json', { limit: '5mb' });
62
+ // refuses with a message about entity size that says nothing about plans; and a project's
63
+ // level 2 has no limit of its own (2026-11-03), so a save may carry megabytes of it.
64
+ app.useBodyParser('json', { limit: '50mb' });
64
65
  app.enableCors({
65
66
  origin: [WEB_ORIGIN, WEB_ORIGIN.replace('localhost', '127.0.0.1')],
66
67
  /*
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Settings saved while a message is at work (operator, 2026-11-03: "when I change a setting in Settings, if it can be,
3
+ * let it take effect at once, even while a task is running"). A run read its settings once, when it started, so a
4
+ * program added to "Programs the bot may start" after a step was refused for it was refused again until the next
5
+ * message. Now each run keeps its settings in one object (`LiveSettings.cfg`) and takes into it, in place, what can
6
+ * change under a message without breaking it:
7
+ *
8
+ * - at once (`now`): the rules each step is judged by — the programs, the scripts, the ones set to read only, those
9
+ * run without asking, downloads, the deny patterns, isolation, the variables a step is given, and Settings'
10
+ * agreement with the bot — the time a command may take, the limits, the pauses, the reports and their redaction.
11
+ * Each is read where it is used, so the next step, the next reply or the next message goes by the new value;
12
+ * - from the next message (`next`): what a message is built on when it starts — the models, plan mode, the shell and
13
+ * folder a step runs in by default, the project and its folders, the skills, the contract's stop word, the mode a
14
+ * start takes, and the lead's number of subtasks, which its assignment states;
15
+ * - when the chat window opens again (`window`): the chat's address, its browser and the waits and locators the
16
+ * window was opened with; it is kept open between messages.
17
+ *
18
+ * A step that is running, and a card already put to the operator, go on as they began. The locked policy, when there is
19
+ * one, is in what was saved (`loadConfigObject`), so it is taken with the rest and still wins.
20
+ */
21
+ import { chatDenyPatterns } from './schema.js';
22
+ /** Taken at once, by section; `*` is every field of it. */
23
+ const NOW = {
24
+ execution: [
25
+ 'networkFetch', 'questions', 'commandTimeoutSec', 'idleTimeoutSec', 'longCommandTimeoutSec', 'longIdleTimeoutSec',
26
+ 'maxStepTimeoutSec', 'isolation', 'passEnv', 'allowedPrograms', 'readOnlyPrograms', 'runWithoutAsking', 'scripts',
27
+ 'writtenScripts', 'denyPatterns',
28
+ ],
29
+ limits: '*',
30
+ pacing: '*',
31
+ report: '*',
32
+ };
33
+ /** Of a section taken whole, what a message is told when it starts: the lead's number of subtasks is its assignment's. */
34
+ const NOT_NOW = {
35
+ limits: ['maxSubtasks'],
36
+ };
37
+ /** What the chat window was opened with. */
38
+ const WINDOW = {
39
+ copilot: ['url', 'profileDir', 'channel', 'headless', 'replyTimeoutSec', 'signInTimeoutSec', 'humanWaitSec', 'keepFailurePage', 'pickerLocators', 'pickerSteps'],
40
+ };
41
+ /** The sections a run compares; the rest (where the bot keeps its records) is read when the bot starts. */
42
+ const SECTIONS = ['copilot', 'task', 'execution', 'report', 'project', 'skills', 'pacing', 'limits'];
43
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
44
+ function classOf(section, key) {
45
+ if (NOT_NOW[section]?.includes(key))
46
+ return 'next';
47
+ const now = NOW[section];
48
+ if (now === '*' || now?.includes(key))
49
+ return 'now';
50
+ return WINDOW[section]?.includes(key) ? 'window' : 'next';
51
+ }
52
+ /** One run's settings, and those who hear when a save changes what it goes by. */
53
+ export class LiveSettings {
54
+ cfg;
55
+ chat;
56
+ listeners = new Set();
57
+ /** The settings as last saved, so a save names what it changed, not what an earlier one did. */
58
+ last;
59
+ /**
60
+ * `cfg`: the run's own; `chat`: a conversation of the workbench's chat, whose deny patterns leave its git to the
61
+ * operator; `loaded`: the settings the run was made from, before that.
62
+ */
63
+ constructor(cfg, chat, loaded = cfg) {
64
+ this.cfg = cfg;
65
+ this.chat = chat;
66
+ this.last = JSON.parse(JSON.stringify(loaded));
67
+ }
68
+ /** Hears every save that changes something this run takes at once. */
69
+ onChange(fn) {
70
+ this.listeners.add(fn);
71
+ return () => this.listeners.delete(fn);
72
+ }
73
+ /**
74
+ * Takes what was saved: the fields this run takes at once go into `cfg`, in place, so every part of the run holding
75
+ * it reads them; the rest is only named. Those who listen hear of it when anything was taken.
76
+ */
77
+ take(saved) {
78
+ const change = { now: [], next: [], window: [] };
79
+ const target = this.cfg;
80
+ const source = saved;
81
+ for (const section of SECTIONS) {
82
+ const before = this.last[section] ?? {};
83
+ const from = source[section];
84
+ if (!from || typeof from !== 'object')
85
+ continue;
86
+ for (const key of new Set([...Object.keys(before), ...Object.keys(from)])) {
87
+ if (same(before[key], from[key]))
88
+ continue;
89
+ const kind = classOf(section, key);
90
+ change[kind].push(`${section}.${key}`);
91
+ if (kind !== 'now' || !target[section])
92
+ continue;
93
+ const value = from[key];
94
+ target[section][key] = section === 'execution' && key === 'denyPatterns' && this.chat && Array.isArray(value) ? chatDenyPatterns(value) : value;
95
+ }
96
+ }
97
+ this.last = JSON.parse(JSON.stringify(saved));
98
+ if (change.now.length > 0) {
99
+ this.cfg.policyLock = saved.policyLock;
100
+ for (const fn of this.listeners) {
101
+ try {
102
+ fn(change);
103
+ }
104
+ catch {
105
+ // One that cannot hear it does not keep it from the others.
106
+ }
107
+ }
108
+ }
109
+ return change;
110
+ }
111
+ }
112
+ /** The names of several runs' changes together, each once. */
113
+ export function mergedChange(changes) {
114
+ const out = { now: [], next: [], window: [] };
115
+ for (const c of changes) {
116
+ for (const k of ['now', 'next', 'window'])
117
+ for (const name of c[k])
118
+ if (!out[k].includes(name))
119
+ out[k].push(name);
120
+ }
121
+ return out;
122
+ }
@@ -77,12 +77,18 @@ class PowerShellScan {
77
77
  calls = [];
78
78
  uncertain;
79
79
  depth = 0;
80
+ exits = 0;
80
81
  constructor(s) {
81
82
  this.s = s;
82
83
  }
83
84
  run() {
84
85
  this.statements(0, null);
85
- return this.uncertain ? { heads: this.heads, calls: this.calls, uncertain: this.uncertain } : { heads: this.heads, calls: this.calls };
86
+ return {
87
+ heads: this.heads,
88
+ calls: this.calls,
89
+ ...(this.uncertain ? { uncertain: this.uncertain } : {}),
90
+ ...(this.exits ? { exits: this.exits } : {}),
91
+ };
86
92
  }
87
93
  /** A literal head: recorded, with the invocation its arguments are read into. */
88
94
  record(head) {
@@ -231,8 +237,11 @@ class PowerShellScan {
231
237
  return this.typeDefinition(word.end);
232
238
  if (PIPELINE_KEYWORDS.has(lower))
233
239
  return this.element(word.end);
234
- if (BLOCK_KEYWORDS.has(lower))
240
+ if (BLOCK_KEYWORDS.has(lower)) {
241
+ if (lower === 'exit')
242
+ this.exits += 1;
235
243
  return this.keywordRest(word.end);
244
+ }
236
245
  }
237
246
  if (word.dynamic)
238
247
  this.fail(`the command "${word.literal}" is built from a variable, so which program it starts is known only when it runs`);
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The folder each part of a line runs in (2026-11-03). `Push-Location 'rules-engine'; .\switch-env.ps1 qa` runs the
3
+ * script of `rules-engine`, and the scripts a line runs (`scriptFiles.ts`) were looked for in the folder the line
4
+ * started in: the project's own committed script was "not one of the project's own — it does not exist", the chat was
5
+ * told to hand it over, and the card of commands handed over could not show it.
6
+ *
7
+ * So a line is read statement by statement, as the shell runs it, and a statement that changes the folder — `cd`,
8
+ * `Set-Location`, `Push-Location` and `Pop-Location`, by their aliases too, and cmd's `cd /d`, `pushd` and `popd` —
9
+ * changes it for what follows. Only a folder written out is followed: one chosen at run time (`cd $dir`, `cd ~`,
10
+ * `cd %X%`) leaves the folder as it was, which is what every reader here did before, and a script then looked for in
11
+ * the wrong folder is not found and not run. A change inside a block or a condition is not followed either.
12
+ */
13
+ import { resolve } from 'node:path';
14
+ /** Where the top-level statements of a PowerShell line start and end. */
15
+ function powerShellStatements(s) {
16
+ const out = [];
17
+ let start = 0;
18
+ let depth = 0;
19
+ const cut = (end, next) => {
20
+ if (end > start)
21
+ out.push([start, end]);
22
+ start = next;
23
+ };
24
+ for (let i = 0; i < s.length; i++) {
25
+ const c = s[i];
26
+ if (c === '`') {
27
+ i += 1;
28
+ continue;
29
+ }
30
+ if (c === "'" || c === '‘' || c === '’') {
31
+ // '' inside a single-quoted string is a quote.
32
+ for (i += 1; i < s.length; i++) {
33
+ if (s[i] === "'" || s[i] === '‘' || s[i] === '’') {
34
+ if (s[i + 1] === "'")
35
+ i += 1;
36
+ else
37
+ break;
38
+ }
39
+ }
40
+ continue;
41
+ }
42
+ if (c === '"' || c === '“' || c === '”') {
43
+ for (i += 1; i < s.length; i++) {
44
+ if (s[i] === '`')
45
+ i += 1;
46
+ else if (s[i] === '"' || s[i] === '“' || s[i] === '”') {
47
+ if (s[i + 1] === '"')
48
+ i += 1;
49
+ else
50
+ break;
51
+ }
52
+ }
53
+ continue;
54
+ }
55
+ if (c === '@' && (s[i + 1] === "'" || s[i + 1] === '"') && (s[i + 2] === '\n' || (s[i + 2] === '\r' && s[i + 3] === '\n'))) {
56
+ const close = s.indexOf(`\n${s[i + 1]}@`, i + 2);
57
+ i = close < 0 ? s.length : close + 2;
58
+ continue;
59
+ }
60
+ if (c === '<' && s[i + 1] === '#') {
61
+ const close = s.indexOf('#>', i + 2);
62
+ i = close < 0 ? s.length : close + 1;
63
+ continue;
64
+ }
65
+ if (c === '#' && (i === 0 || /\s/.test(s[i - 1]))) {
66
+ const nl = s.indexOf('\n', i);
67
+ i = nl < 0 ? s.length : nl - 1;
68
+ continue;
69
+ }
70
+ if (c === '(' || c === '{' || c === '[')
71
+ depth += 1;
72
+ else if (c === ')' || c === '}' || c === ']')
73
+ depth = Math.max(0, depth - 1);
74
+ else if (depth === 0 && (c === ';' || c === '\n'))
75
+ cut(i, i + 1);
76
+ else if (depth === 0 && (c === '&' || c === '|') && s[i + 1] === c) {
77
+ cut(i, i + 2);
78
+ i += 1;
79
+ }
80
+ }
81
+ cut(s.length, s.length);
82
+ return out;
83
+ }
84
+ /** Where cmd's commands start and end: `&`, `&&`, `||` and newlines, outside quotes and brackets. */
85
+ function cmdStatements(s) {
86
+ const out = [];
87
+ let start = 0;
88
+ let depth = 0;
89
+ let quoted = false;
90
+ const cut = (end, next) => {
91
+ if (end > start)
92
+ out.push([start, end]);
93
+ start = next;
94
+ };
95
+ for (let i = 0; i < s.length; i++) {
96
+ const c = s[i];
97
+ if (c === '^' && !quoted) {
98
+ i += 1;
99
+ continue;
100
+ }
101
+ if (c === '"')
102
+ quoted = !quoted;
103
+ if (quoted)
104
+ continue;
105
+ if (c === '(')
106
+ depth += 1;
107
+ else if (c === ')')
108
+ depth = Math.max(0, depth - 1);
109
+ else if (depth === 0 && c === '\n')
110
+ cut(i, i + 1);
111
+ else if (depth === 0 && (c === '&' || c === '|') && s[i + 1] === c) {
112
+ cut(i, i + 2);
113
+ i += 1;
114
+ }
115
+ else if (depth === 0 && c === '&')
116
+ cut(i, i + 1);
117
+ }
118
+ cut(s.length, s.length);
119
+ return out;
120
+ }
121
+ /** A folder written out in full, its quotes taken off; null for one chosen at run time. */
122
+ function literalFolder(arg, cmd) {
123
+ let a = arg.trim();
124
+ const q = a[0];
125
+ if (q === '"' || (!cmd && q === "'")) {
126
+ if (a.length < 2 || a[a.length - 1] !== q)
127
+ return null;
128
+ a = a.slice(1, -1);
129
+ if (q === "'")
130
+ a = a.replace(/''/g, "'");
131
+ }
132
+ else if (!cmd && /\s/.test(a)) {
133
+ return null;
134
+ }
135
+ if (!a || a === '-' || a === '+' || a.startsWith('~'))
136
+ return null;
137
+ if (cmd ? /[%!]/.test(a) : /[$`(){}@]/.test(a) || (q === '"' && /[$`]/.test(a)))
138
+ return null;
139
+ // A PowerShell drive other than a file system's (`HKLM:`, `Env:`): not a folder.
140
+ if (/^[A-Za-z]{2,}:/.test(a))
141
+ return null;
142
+ return a;
143
+ }
144
+ /** What a statement does to the folder, when it does anything a reader can follow. */
145
+ function moveOf(statement, cmd) {
146
+ const s = statement.trim();
147
+ if (cmd) {
148
+ if (/^popd$/i.test(s))
149
+ return { pop: true };
150
+ const m = /^(cd|chdir|pushd)(?:\s+\/d)?\s+(.+)$/i.exec(s);
151
+ if (!m)
152
+ return null;
153
+ const to = literalFolder(m[2], true);
154
+ if (to === null)
155
+ return null;
156
+ return m[1].toLowerCase() === 'pushd' ? { push: to } : { to };
157
+ }
158
+ if (/^(?:Pop-Location|popd)$/i.test(s))
159
+ return { pop: true };
160
+ const m = /^(Set-Location|sl|cd|chdir|Push-Location|pushd)(?:\s+-(?:Path|LiteralPath)(?::)?)?\s+(.+)$/i.exec(s);
161
+ if (!m)
162
+ return null;
163
+ const to = literalFolder(m[2], false);
164
+ if (to === null)
165
+ return null;
166
+ return /^(?:Push-Location|pushd)$/i.test(m[1]) ? { push: to } : { to };
167
+ }
168
+ /**
169
+ * The line cut where it changes folder, each stretch with the folder it runs in. A line that changes none is one
170
+ * stretch, in `cwd`: what every reader here was given before.
171
+ */
172
+ export function foldersAlong(command, cwd, shell) {
173
+ const cmd = shell === 'cmd';
174
+ const statements = cmd ? cmdStatements(command) : powerShellStatements(command);
175
+ const out = [];
176
+ const stack = [];
177
+ let folder = cwd;
178
+ let from = 0;
179
+ for (const [start, end] of statements) {
180
+ const move = moveOf(command.slice(start, end), cmd);
181
+ if (!move)
182
+ continue;
183
+ const next = 'pop' in move ? (stack.pop() ?? folder) : resolve(folder, 'to' in move ? move.to : move.push);
184
+ if ('push' in move)
185
+ stack.push(folder);
186
+ if (next === folder)
187
+ continue;
188
+ out.push({ text: command.slice(from, end), cwd: folder });
189
+ folder = next;
190
+ from = end;
191
+ }
192
+ out.push({ text: command.slice(from), cwd: folder });
193
+ return out.filter((s, i) => i === out.length - 1 || s.text.trim());
194
+ }
@@ -51,6 +51,7 @@
51
51
  */
52
52
  import { existsSync } from 'node:fs';
53
53
  import { dirname, join, resolve } from 'node:path';
54
+ import { stopsTheBot } from './stops.js';
54
55
  import { botRootDir } from './workDir.js';
55
56
  import { chosenHome, defaultHome, installLayout } from '../config/layout.js';
56
57
  const FETCHERS = [
@@ -279,6 +280,7 @@ export function networkFetchReason(command, cwd) {
279
280
  * that approves its steps. Found on 2026-09-27: with the token in its environment, a step could call
280
281
  * `127.0.0.1:4000` and answer its own held download. The token is no longer passed (`stepEnv.ts`);
281
282
  * this refuses the attempt as well, so a step that goes looking gets a reason instead of a 401.
283
+ * And a line that stops the processes the bot runs as, by their name or its port (`stops.ts`, 2026-11-03).
282
284
  */
283
285
  export function botSelfRefusal(command, ports = botPorts(), root = botRootDir(), homes = botHomeFolders()) {
284
286
  const port = `(?:${ports.map((p) => String(Math.trunc(p))).join('|')})`;
@@ -316,7 +318,7 @@ export function botSelfRefusal(command, ports = botPorts(), root = botRootDir(),
316
318
  return ('refused: this reaches the bot itself — its API, its web page or its key. A task works on its own project; ' +
317
319
  'the bot that runs it is not part of the work. Use a different port for a server the task starts.');
318
320
  }
319
- return null;
321
+ return stopsTheBot(command, ports);
320
322
  }
321
323
  /** A path or a command as compared here: one backslash for any run of slashes, lower case. */
322
324
  function foldPath(text) {