copilot-operator 0.1.69 → 0.1.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/src/api/operator.controller.js +6 -3
  2. package/dist/src/api/operator.service.js +58 -13
  3. package/dist/src/api/server.js +10 -0
  4. package/dist/src/cli.js +3 -0
  5. package/dist/src/config/lockedPolicy.js +14 -0
  6. package/dist/src/config/schema.js +29 -0
  7. package/dist/src/exec/authorizer.js +47 -8
  8. package/dist/src/exec/dangerous.js +1 -1
  9. package/dist/src/exec/npmScripts.js +180 -0
  10. package/dist/src/exec/platforms.js +45 -1
  11. package/dist/src/exec/policy.js +124 -9
  12. package/dist/src/exec/policyManifest.js +15 -0
  13. package/dist/src/exec/processes.js +8 -3
  14. package/dist/src/exec/programs.js +6 -1
  15. package/dist/src/exec/redaction.js +17 -2
  16. package/dist/src/exec/scriptFiles.js +230 -34
  17. package/dist/src/exec/scriptKinds.js +86 -0
  18. package/dist/src/exec/stepEnv.js +9 -2
  19. package/dist/src/orchestrator/handoff.js +80 -29
  20. package/dist/src/orchestrator/hold.js +83 -4
  21. package/dist/src/orchestrator/leadRunner.js +5 -2
  22. package/dist/src/orchestrator/review.js +13 -3
  23. package/dist/src/orchestrator/taskRunner.js +106 -19
  24. package/dist/src/plan/kerrigan.js +36 -15
  25. package/dist/src/plan/systemGuide.js +117 -22
  26. package/dist/src/protocol/leadSchema.js +8 -1
  27. package/dist/src/protocol/replySchema.js +13 -3
  28. package/dist/src/protocol/reviewSchema.js +4 -1
  29. package/dist/src/queue/queue.js +8 -4
  30. package/dist/src/session/checkpoint.js +48 -0
  31. package/dist/src/session/compose.js +1 -1
  32. package/dist/src/session/story.js +14 -0
  33. package/dist/src/vcs/gitConfigGuard.js +126 -0
  34. package/dist/src/vcs/newBranch.js +76 -13
  35. package/dist/web/404.html +2 -2
  36. package/dist/web/_next/static/chunks/1024-67625a65f58057ae.js +1 -0
  37. package/dist/web/_next/static/chunks/1077.14d6c828d8f71111.js +1 -0
  38. package/dist/web/_next/static/chunks/1548.2f75926c6e664f79.js +1 -0
  39. package/dist/web/_next/static/chunks/2163.f9f1ad4af05520cc.js +1 -0
  40. package/dist/web/_next/static/chunks/714.4507656685cb9337.js +1 -0
  41. package/dist/web/_next/static/chunks/7220.9bc9dd9f211b11e4.js +1 -0
  42. package/dist/web/_next/static/chunks/7921-9aaec581982b2329.js +1 -0
  43. package/dist/web/_next/static/chunks/8124-a39d85dff0db6600.js +1 -0
  44. package/dist/web/_next/static/chunks/8584.f2cb3ca81223d626.js +1 -0
  45. package/dist/web/_next/static/chunks/9067.a6cb3b9157a80921.js +1 -0
  46. package/dist/web/_next/static/chunks/9747.15aa40a046d54a2a.js +1 -0
  47. package/dist/web/_next/static/chunks/9929-2e0b1d006ebd5345.js +1 -0
  48. package/dist/web/_next/static/chunks/app/{layout-e23bb58f3ea117d5.js → layout-52a2079ffa83c21f.js} +1 -1
  49. package/dist/web/_next/static/chunks/app/page-80730838a81da226.js +1 -0
  50. package/dist/web/_next/static/chunks/app/queue/{page-fb49cb2d3dc6d14c.js → page-82f724d0842f4870.js} +1 -1
  51. package/dist/web/_next/static/chunks/app/settings/page-4f3c739287d7f32e.js +1 -0
  52. package/dist/web/_next/static/chunks/{webpack-77c6c045264c9213.js → webpack-f9f820c51a8952c8.js} +1 -1
  53. package/dist/web/_next/static/css/63b30b8e1a4aa500.css +1 -0
  54. package/dist/web/defaults.html +2 -2
  55. package/dist/web/defaults.txt +8 -8
  56. package/dist/web/index.html +3 -3
  57. package/dist/web/index.txt +9 -9
  58. package/dist/web/queue.html +2 -2
  59. package/dist/web/queue.txt +9 -9
  60. package/dist/web/settings.html +2 -2
  61. package/dist/web/settings.txt +9 -9
  62. package/dist/web/system.html +2 -2
  63. package/dist/web/system.txt +9 -9
  64. package/package.json +3 -2
  65. package/prompts/level1.md +50 -27
  66. package/dist/web/_next/static/chunks/1024-e4e596b184e05e91.js +0 -1
  67. package/dist/web/_next/static/chunks/1077.b3943e5b41c4bef4.js +0 -1
  68. package/dist/web/_next/static/chunks/1548.0ff0c0ece685ffe7.js +0 -1
  69. package/dist/web/_next/static/chunks/2163.9cfb1b06beaf5001.js +0 -1
  70. package/dist/web/_next/static/chunks/6262-d074473db83ee798.js +0 -1
  71. package/dist/web/_next/static/chunks/714.bee98f5a3db75882.js +0 -1
  72. package/dist/web/_next/static/chunks/7220.610988766a1104b7.js +0 -1
  73. package/dist/web/_next/static/chunks/7921-ac5793d5663674b2.js +0 -1
  74. package/dist/web/_next/static/chunks/8124-665327221384ba6e.js +0 -1
  75. package/dist/web/_next/static/chunks/8584.9220e445a8ce2265.js +0 -1
  76. package/dist/web/_next/static/chunks/9067.f05516f2f2a2e8f5.js +0 -1
  77. package/dist/web/_next/static/chunks/9747.e249434ff7e05f4f.js +0 -1
  78. package/dist/web/_next/static/chunks/app/page-fd49cf4fb6681d30.js +0 -1
  79. package/dist/web/_next/static/chunks/app/settings/page-7d120feb5af0ace9.js +0 -1
  80. package/dist/web/_next/static/css/52131c6d864daf3f.css +0 -1
  81. /package/dist/web/_next/static/{8i6gf0zoo-KiUKdzxsCJR → 9DmRzBb0M5BZ3dvVpbFMM}/_buildManifest.js +0 -0
  82. /package/dist/web/_next/static/{8i6gf0zoo-KiUKdzxsCJR → 9DmRzBb0M5BZ3dvVpbFMM}/_ssgManifest.js +0 -0
@@ -90,7 +90,9 @@ let OperatorController = class OperatorController {
90
90
  * be set to read only, and the list in force, which a policy lock may have narrowed.
91
91
  */
92
92
  const programs = { platforms: platformTools(), readOnly: readOnlyCapable(), inForce: resolved.execution.allowedPrograms };
93
- return { raw, defaults, resolved: resolved.resolved, picker, programs };
93
+ // The scripts the bot may run, as in force (2026-10-27): a lock may have emptied the boxes for its own.
94
+ const scripts = { inForce: resolved.execution.scripts, writtenScripts: resolved.execution.writtenScripts };
95
+ return { raw, defaults, resolved: resolved.resolved, picker, programs, scripts };
94
96
  }
95
97
  async saveSettings(body) {
96
98
  await this.ops.settings.save(body).catch(fail);
@@ -285,7 +287,8 @@ let OperatorController = class OperatorController {
285
287
  /**
286
288
  * A new branch from main, from the chat (2026-10-26): what it would start from — `fetch` true fetches the remote's
287
289
  * main first, through Git's own password window when it asks — and then the branch made, the uncommitted changes
288
- * taken to it (`carry: take`) or put aside (`carry: aside`), after checking the folder is what the preview read.
290
+ * taken to it (`carry: take`), put aside (`carry: aside`) or committed on the branch it is on (`carry: commit`, with
291
+ * `message`), after checking the folder is what the preview read.
289
292
  */
290
293
  newBranchPreview(body = {}) {
291
294
  return this.ops.newBranchPreview(body?.fetch !== false).catch(fail);
@@ -403,7 +406,7 @@ let OperatorController = class OperatorController {
403
406
  }
404
407
  /** The lead's question (two chats): the operator's answer, as text. Stopping the task is `approvals/:id` with abort. */
405
408
  answerQuestion(id, body) {
406
- const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '', body?.ran === false ? false : undefined);
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);
407
410
  if (!result.ok)
408
411
  throw new BadRequestException(result.problem);
409
412
  return result;
@@ -24,9 +24,9 @@ import { checkItems, emptyQueue, itemTitle, mergeItems, nextStep, parkAfterMs, p
24
24
  import { branchStart, makeQueueBranch, refreshQueueBranch } from '../queue/queueBranch.js';
25
25
  import { EventBus } from '../session/events.js';
26
26
  import { MAX_INSTRUCTION_CHARS, newId } from '../session/model.js';
27
- import { handoffResultMessage } from '../orchestrator/handoff.js';
27
+ import { handoffOutcomeOf, handoffResultMessage } from '../orchestrator/handoff.js';
28
28
  import { runSession, queuedToRun, failedWhileOpening, pickerOptions } from '../orchestrator/taskRunner.js';
29
- import { Hold } from '../orchestrator/hold.js';
29
+ import { Hold, WaitsFor } from '../orchestrator/hold.js';
30
30
  import { exportFileName, exportMachine, writeAttemptRecord } from '../session/exports.js';
31
31
  import { suggestRunName } from '../session/runName.js';
32
32
  import { buildStory } from '../session/story.js';
@@ -165,12 +165,24 @@ let OperatorService = class OperatorService {
165
165
  followsActing = this.bus.subscribe('*', (e) => {
166
166
  if (e.type === 'acting' && e.data)
167
167
  this.acting.set(e.sessionId, e.data);
168
+ else if (e.type === 'browser:sign-in-required' || e.type === 'browser:verification-required') {
169
+ // The Copilot window waits for the operator to sign in, or to show a person is there: not counted (2026-10-29).
170
+ this.holdOf(e.sessionId)?.waitFor(`${e.type}:${e.sessionId}`);
171
+ }
172
+ else if (e.type === 'browser:signed-in' || e.type === 'browser:verification-cleared') {
173
+ this.holdOf(e.sessionId)?.waited(`${e.type === 'browser:signed-in' ? 'browser:sign-in-required' : 'browser:verification-required'}:${e.sessionId}`);
174
+ }
168
175
  else if (e.type === 'password-window') {
169
176
  const open = e.data?.open === true;
170
177
  if (open)
171
178
  this.passwordAsked.set(e.sessionId, e.at);
172
179
  else
173
180
  this.passwordAsked.delete(e.sessionId);
181
+ // Git's own window waits for the operator's password: not counted either (2026-10-29).
182
+ if (open)
183
+ this.holdOf(e.sessionId)?.waitFor(`pw:${e.sessionId}`);
184
+ else
185
+ this.holdOf(e.sessionId)?.waited(`pw:${e.sessionId}`);
174
186
  // In the queue, a password nobody types sets the task aside, as an unanswered card does (2026-10-26).
175
187
  if (open) {
176
188
  const step = Number(e.data?.id) || 0;
@@ -182,12 +194,29 @@ let OperatorService = class OperatorService {
182
194
  else if (e.type === 'task-finished') {
183
195
  this.acting.delete(e.sessionId);
184
196
  this.passwordAsked.delete(e.sessionId);
197
+ for (const key of [`pw:${e.sessionId}`, `browser:sign-in-required:${e.sessionId}`, `browser:verification-required:${e.sessionId}`])
198
+ this.holdOf(e.sessionId)?.waited(key);
185
199
  const status = e.data?.status;
186
200
  if (typeof status === 'string' && !this.workerLeads.has(e.sessionId))
187
201
  this.lastOutcome = { status, at: e.at, sessionId: e.sessionId };
188
202
  }
189
203
  });
190
- waiting = new Map();
204
+ /**
205
+ * What waits for the operator: every card, by its id. Each one put here starts a wait on its run's clock and its going
206
+ * — answered, set aside, stopped — ends it, so a task's minutes, and its limit, leave out the time it waited
207
+ * (operator, 2026-10-29: "while the bot waits for the user to type something or answer, it must not count").
208
+ */
209
+ waiting = new WaitsFor((id, w, begins) => {
210
+ const hold = this.holdOf(w.approval.sessionId);
211
+ if (begins)
212
+ hold?.waitFor(`card:${id}`);
213
+ else
214
+ hold?.waited(`card:${id}`);
215
+ });
216
+ /** The clock of the run a session's work belongs to: its own, or its lead's for a worker. */
217
+ holdOf(sessionId) {
218
+ return this.running.get(this.runKey(sessionId))?.hold;
219
+ }
191
220
  /**
192
221
  * The workers of the two-chat mode, by the session of the lead they work for (2026-10-20). A worker's steps and cards
193
222
  * carry its own session's id, while the run, its mode and its Stop are the lead's: they are looked up through this.
@@ -849,6 +878,9 @@ let OperatorService = class OperatorService {
849
878
  networkFetch: cfg.execution.networkFetch,
850
879
  platformAccess: cfg.execution.questions === 'agree' ? 'allow' : 'ask',
851
880
  readOnlyPrograms: cfg.execution.readOnlyPrograms,
881
+ runWithoutAsking: cfg.execution.runWithoutAsking,
882
+ scripts: cfg.execution.scripts,
883
+ writtenScripts: cfg.execution.writtenScripts,
852
884
  };
853
885
  /*
854
886
  * An unattended run that cannot legally execute anything is stopped here, where the operator
@@ -1151,7 +1183,7 @@ let OperatorService = class OperatorService {
1151
1183
  throw new Error(busy);
1152
1184
  return await planNewBranch(ws.dir, { fetch, askpass: fetch ? await askpassProgram() : null });
1153
1185
  }
1154
- /** The branch made and checked out, the uncommitted changes taken to it or put aside, as the operator chose. */
1186
+ /** The branch made and checked out, the uncommitted changes taken to it, put aside or committed where they are, as the operator chose. */
1155
1187
  async newBranchCreate(input) {
1156
1188
  const ws = await this.workspace();
1157
1189
  if (!ws.ok)
@@ -1161,8 +1193,9 @@ let OperatorService = class OperatorService {
1161
1193
  throw new Error(busy);
1162
1194
  return await createNewBranch(ws.dir, {
1163
1195
  name: typeof input.name === 'string' ? input.name : '',
1164
- carry: input.carry === 'aside' ? 'aside' : 'take',
1196
+ carry: input.carry === 'aside' || input.carry === 'commit' ? input.carry : 'take',
1165
1197
  fingerprint: typeof input.fingerprint === 'string' ? input.fingerprint : '',
1198
+ ...(typeof input.message === 'string' && input.message.trim() ? { message: input.message.trim().slice(0, 2000) } : {}),
1166
1199
  // The saved branch under the bot's own prefix, as its other branches are.
1167
1200
  prefix: DEFAULT_VCS.branchPrefix,
1168
1201
  });
@@ -1884,7 +1917,7 @@ let OperatorService = class OperatorService {
1884
1917
  }
1885
1918
  else if (a.kind === 'question') {
1886
1919
  const handed = p.approval.question?.handoff;
1887
- note = handed ? handoffResultMessage(handed, a.ran !== false, a.answer) : `You asked: ${p.approval.question?.text ?? ''}\n\nThe operator answers: ${a.answer}`;
1920
+ note = handed ? handoffResultMessage(handed, handoffOutcomeOf(a.outcome, a.ran), a.answer) : `You asked: ${p.approval.question?.text ?? ''}\n\nThe operator answers: ${a.answer}`;
1888
1921
  }
1889
1922
  else if (a.kind === 'retry' && p.approval.retry) {
1890
1923
  const r = p.approval.retry;
@@ -2174,18 +2207,24 @@ let OperatorService = class OperatorService {
2174
2207
  const cfg = await this.settings.load();
2175
2208
  return await this.start(threadId, cfg.execution.mode);
2176
2209
  }
2177
- answerQuestion(approvalId, text, ran) {
2210
+ answerQuestion(approvalId, text, ran, outcome) {
2178
2211
  const w = this.waiting.get(approvalId);
2179
2212
  if (!w?.resolveAnswer)
2180
2213
  return { ok: false, problem: 'No question of the lead is waiting under that id.' };
2181
- // Commands handed over (2026-10-26): what they printed, or that the operator did not run them, with a word or none.
2214
+ /*
2215
+ * Commands handed over (2026-10-26): what they printed; sent back for a correction, which needs what to correct
2216
+ * (2026-10-27); or that the operator will not run them, with a word or none.
2217
+ */
2182
2218
  const handed = !!w.approval.question?.handoff;
2183
- if (handed && ran !== false && !text.trim())
2219
+ const how = handoffOutcomeOf(outcome, ran);
2220
+ if (handed && how === 'ran' && !text.trim())
2184
2221
  return { ok: false, problem: 'Paste what the commands printed first.' };
2222
+ if (handed && how === 'revise' && !text.trim())
2223
+ return { ok: false, problem: 'Say what to correct first.' };
2185
2224
  if (!handed && !text.trim())
2186
2225
  return { ok: false, problem: 'Write the answer first.' };
2187
2226
  this.waiting.delete(approvalId);
2188
- w.resolveAnswer(handed ? { answer: text.trim(), ran: ran !== false } : { answer: text.trim() });
2227
+ w.resolveAnswer(handed ? { answer: text.trim(), ran: how === 'ran', outcome: how } : { answer: text.trim() });
2189
2228
  this.bus.publish({ sessionId: w.approval.sessionId, taskId: w.approval.taskId, type: 'approval-decided', level: 'info',
2190
2229
  message: 'the operator answered the lead', data: { approvalId, question: true } });
2191
2230
  return { ok: true };
@@ -2315,8 +2354,12 @@ let OperatorService = class OperatorService {
2315
2354
  for (const [id, w] of this.waiting) {
2316
2355
  if (this.runKey(w.approval.sessionId) !== sessionId)
2317
2356
  continue;
2318
- // A fetch waits for its own answer: "run the rest without asking" is not an answer to it; nor is a question.
2319
- if (w.approval.network || w.approval.model || w.approval.question || w.approval.plan)
2357
+ // A fetch waits for its own answer: "run the rest without asking" is not an answer to it; nor is a question, nor
2358
+ // a platform reached with the operator's access, a read-only program's unclear line, a subtask's retry, or a
2359
+ // script the bot wrote that Settings put to the operator first (audit, 2026-10-27: these were let go).
2360
+ if (w.approval.network || w.approval.model || w.approval.question || w.approval.plan || w.approval.platform || w.approval.readOnly || w.approval.retry)
2361
+ continue;
2362
+ if (w.approval.scripts && run.policy.writtenScripts !== 'run')
2320
2363
  continue;
2321
2364
  this.waiting.delete(id);
2322
2365
  w.resolve({ action: 'run' });
@@ -2339,7 +2382,8 @@ let OperatorService = class OperatorService {
2339
2382
  // This is checked per step rather than captured once, which is what makes the switch
2340
2383
  // take effect from the very next step instead of the next run. A held step is the
2341
2384
  // exception: it is asked about in an unattended run too, which is the point of holding it.
2342
- if (!held && this.running.get(this.runKey(ctx.sessionId ?? ''))?.mode === 'unattended') {
2385
+ const forTheOperator = !!(held?.network || held?.platform || held?.readOnly || (held?.scripts && policy.writtenScripts !== 'run'));
2386
+ if (!forTheOperator && this.running.get(this.runKey(ctx.sessionId ?? ''))?.mode === 'unattended') {
2343
2387
  resolvePromise({ action: 'run' });
2344
2388
  return;
2345
2389
  }
@@ -2363,6 +2407,7 @@ let OperatorService = class OperatorService {
2363
2407
  ...(held?.network ? { network: held.network } : {}),
2364
2408
  ...(held?.platform ? { platform: held.platform } : {}),
2365
2409
  ...(held?.readOnly ? { readOnly: held.readOnly } : {}),
2410
+ ...(held?.scripts ? { scripts: held.scripts } : {}),
2366
2411
  };
2367
2412
  this.waiting.set(approval.id, { approval, resolve: resolvePromise });
2368
2413
  this.parkLater(approval);
@@ -163,6 +163,16 @@ export async function startApi(opts = {}) {
163
163
  await app.close();
164
164
  throw new Error(`copilot-operator api will not start: ${runsAcl.reason}`);
165
165
  }
166
+ /*
167
+ * The browser profile holds the signed-in Microsoft 365 session. In %LOCALAPPDATA% it is the operator's alone; in a
168
+ * home chosen elsewhere (`C:\Projects\bot`) it took that folder's permissions, which on a drive's own folders let
169
+ * every local account change it (audit, 2026-10-27). Narrowed as data/ and runs/ are — said, not refused, when it
170
+ * cannot be, so the bot still starts.
171
+ */
172
+ await mkdir(cfg.resolved.profileDir, { recursive: true }).catch(() => undefined);
173
+ const profileAcl = secureDataDir(cfg.resolved.profileDir);
174
+ if (!profileAcl.ok)
175
+ console.warn(` warning: the browser profile (${cfg.resolved.profileDir}) could not be made the operator's alone: ${profileAcl.reason}`);
166
176
  for (const [name, dir] of [['data', dataDir], ['runs', cfg.resolved.runsDir]]) {
167
177
  if (/onedrive/i.test(dir) || /^\\\\/.test(dir)) {
168
178
  console.warn(` warning: the ${name} folder (${dir}) is under OneDrive or on a network share; keep the bot's records on a local disk (COP_DATA_DIR, runsDir)`);
package/dist/src/cli.js CHANGED
@@ -502,6 +502,9 @@ program
502
502
  networkFetch: cfg.execution.networkFetch,
503
503
  platformAccess: cfg.execution.questions === 'agree' ? 'allow' : 'ask',
504
504
  readOnlyPrograms: cfg.execution.readOnlyPrograms,
505
+ runWithoutAsking: cfg.execution.runWithoutAsking,
506
+ scripts: cfg.execution.scripts,
507
+ writtenScripts: cfg.execution.writtenScripts,
505
508
  };
506
509
  const authorizer = cfg.execution.mode === 'unattended'
507
510
  ? unattendedAuthorizer(policy)
@@ -16,6 +16,9 @@
16
16
  * the gate switched off, because empty means "no allowlist" and that is
17
17
  * the one direction a lock must never permit.
18
18
  * denyPatterns a floor: merged in, so a lock pattern cannot be deleted locally.
19
+ * writtenScripts a ceiling on the scripts the bot wrote (2026-10-27): `never` empties every kind's box for
20
+ * them, so the operator runs each one; `ask` puts each on a card first, even in a run
21
+ * without asking; `run` changes nothing.
19
22
  *
20
23
  * The runner never writes this file. There is no API route that edits it and no UI that shows it
21
24
  * as editable; it is placed by whoever administers the machine, and on a machine that has none
@@ -28,6 +31,7 @@
28
31
  import { z } from 'zod';
29
32
  import { join } from 'node:path';
30
33
  import { readHandWritten } from './handWritten.js';
34
+ import { SCRIPT_KINDS } from '../exec/scriptKinds.js';
31
35
  export const POLICY_LOCK_FILE = 'policy.lock.json';
32
36
  export const PolicyLockSchema = z
33
37
  .object({
@@ -43,6 +47,8 @@ export const PolicyLockSchema = z
43
47
  */
44
48
  allowDesktopMirror: z.boolean().optional(),
45
49
  allowEnvFiles: z.boolean().optional(),
50
+ /** A ceiling on the scripts the bot wrote during the work: never run by it, asked about first, or as Settings say. */
51
+ writtenScripts: z.enum(['never', 'ask', 'run']).optional(),
46
52
  /** A ceiling on `execution.passEnv`: the only variables a step may be given beyond the fixed set. */
47
53
  passEnv: z.array(z.string()).optional(),
48
54
  /** What `npm run update` must insist on: signed commits, and one remote no flag can override. */
@@ -110,6 +116,14 @@ export function applyPolicyLock(policy, lock) {
110
116
  next.passEnv = kept;
111
117
  }
112
118
  }
119
+ if (lock.writtenScripts === 'never' && next.scripts && SCRIPT_KINDS.some((k) => next.scripts[k].written)) {
120
+ next.scripts = Object.fromEntries(SCRIPT_KINDS.map((k) => [k, { ...next.scripts[k], written: false }]));
121
+ changes.push('scripts written by the bot are not run by it (the lock): each is handed to the operator');
122
+ }
123
+ if ((lock.writtenScripts === 'ask' || lock.writtenScripts === 'never') && next.writtenScripts === 'run') {
124
+ next.writtenScripts = 'ask';
125
+ changes.push('scripts written by the bot are asked about first, in every mode (the lock)');
126
+ }
113
127
  return { policy: next, outcome: { applied: true, changes, maxMode: lock.maxMode } };
114
128
  }
115
129
  /**
@@ -6,6 +6,7 @@
6
6
  * commands denied.
7
7
  */
8
8
  import { z } from 'zod';
9
+ import { SCRIPT_KINDS } from '../exec/scriptKinds.js';
9
10
  import { parse as parseYaml } from 'yaml';
10
11
  import { readHandWritten } from './handWritten.js';
11
12
  import { applyPolicyLock, readPolicyLocks } from './lockedPolicy.js';
@@ -88,6 +89,8 @@ export function chatDenyPatterns(patterns) {
88
89
  // Only the default pattern is narrowed: a list the operator wrote themselves is kept as they wrote it.
89
90
  return patterns.map((p) => (p === always ? `\\bgit\\s+(?:${GIT_GLOBAL_OPTION}\\s+)*(?:${GIT_CHAT_WRITES})(?![\\w-])` : p));
90
91
  }
92
+ /** One kind's two boxes: the project's own scripts, and the bot's (2026-10-27). */
93
+ const ScriptRuleSchema = z.object({ own: z.boolean().default(true), written: z.boolean().default(false) }).prefault({});
91
94
  export const RunConfigSchema = z.object({
92
95
  copilot: z
93
96
  .object({
@@ -304,6 +307,28 @@ export const RunConfigSchema = z.object({
304
307
  * named here are ignored.
305
308
  */
306
309
  readOnlyPrograms: z.array(z.string()).default([]),
310
+ /**
311
+ * Programs on the list that reach a platform with the operator's access, set to run without asking (operator,
312
+ * 2026-10-28: "az asks for permission again, although it is on the list of allowed commands"): their commands run
313
+ * as any other step's, changes included — no card. The refused techniques, the folders and the network hold still
314
+ * apply. A program set to read only is not one of these.
315
+ */
316
+ runWithoutAsking: z.array(z.string()).default([]),
317
+ /**
318
+ * Which scripts may run (operator, 2026-10-27: "whether I allow npm, ts files, ps1 files … only for scripts that
319
+ * are already there, and another box for scripts the bot created"). For each kind (`exec/scriptKinds.ts`): `own`,
320
+ * the project's, there before the work began; `written`, the bot's, written during the work. A kind whose box is
321
+ * empty is not run: the chat hands it to the operator. The defaults are the rule as it was: the project's run,
322
+ * the bot's do not.
323
+ */
324
+ scripts: z
325
+ .object(Object.fromEntries(SCRIPT_KINDS.map((k) => [k, ScriptRuleSchema])))
326
+ .prefault({}),
327
+ /**
328
+ * A script the bot wrote, its box ticked, in a run without asking (2026-10-27): `ask` puts it on a card with its
329
+ * text first; `run` runs it as any other step. A run that asks before every command asks about these too.
330
+ */
331
+ writtenScripts: z.enum(['ask', 'run']).default('ask'),
307
332
  denyPatterns: z
308
333
  .array(z.string())
309
334
  .default([
@@ -560,6 +585,8 @@ export async function resolveConfig(cfg, configPath, baseDir) {
560
585
  denyPatterns: cfg.execution.denyPatterns,
561
586
  isolation: cfg.execution.isolation,
562
587
  passEnv: cfg.execution.passEnv,
588
+ scripts: cfg.execution.scripts,
589
+ writtenScripts: cfg.execution.writtenScripts,
563
590
  };
564
591
  const outcome = { applied: false, changes: [] };
565
592
  for (const lock of locks) {
@@ -579,6 +606,8 @@ export async function resolveConfig(cfg, configPath, baseDir) {
579
606
  denyPatterns: policy.denyPatterns,
580
607
  isolation: policy.isolation ?? cfg.execution.isolation,
581
608
  passEnv: policy.passEnv ?? cfg.execution.passEnv,
609
+ scripts: policy.scripts ?? cfg.execution.scripts,
610
+ writtenScripts: policy.writtenScripts ?? cfg.execution.writtenScripts,
582
611
  },
583
612
  configPath,
584
613
  baseDir,
@@ -1,9 +1,12 @@
1
1
  import { staticCheck, describeStep } from './policy.js';
2
2
  import { networkFetchReason, networkFetchRefusal } from './network.js';
3
- import { scriptNetworkReason } from './policy.js';
3
+ import { notHeldFor, scriptNetworkReason } from './policy.js';
4
4
  import { platformOf, platformReason } from './platforms.js';
5
5
  import { readOnlyUnclearRefusal, readOnlyVerdict } from './readOnly.js';
6
+ import { scriptText, writtenScriptsLetRun } from './scriptFiles.js';
7
+ import { effectiveShell } from './shells.js';
6
8
  import { createInterface } from 'node:readline/promises';
9
+ import { relative } from 'node:path';
7
10
  import { stdin, stdout } from 'node:process';
8
11
  /**
9
12
  * Runs the static rules, then, unless unattended, asks the human through `ask`.
@@ -23,16 +26,36 @@ import { stdin, stdout } from 'node:process';
23
26
  * without asking" — a Stop that landed between the runner's own look at the signal and this answer
24
27
  * let one more step run.
25
28
  */
26
- export function makeAuthorizer(cfg, ask, signal) {
29
+ export function makeAuthorizer(cfg, askPerson, signal) {
27
30
  return {
28
31
  async authorize(step, ctx) {
29
32
  if (signal?.aborted)
30
33
  return { action: 'abort', reason: 'stopped by the operator', by: 'operator' };
31
- const blocked = staticCheck(step, cfg, undefined, ctx.confinement);
34
+ const blocked = staticCheck(step, cfg, undefined, ctx.confinement, ctx.actor);
32
35
  if (blocked)
33
36
  return blocked;
37
+ /*
38
+ * Asked, and the run gone over to running without asking meanwhile ("run the rest without asking"): the rules of a
39
+ * run nobody watches are put to the step before it runs (audit, 2026-10-27) — it was checked as a watched one.
40
+ */
41
+ const ask = async (s, c, held) => {
42
+ const decided = await askPerson(s, c, held);
43
+ return decided.action === 'run' && cfg.mode === 'unattended' ? (staticCheck(s, cfg, undefined, c.confinement, c.actor) ?? decided) : decided;
44
+ };
34
45
  const cwd = ctx.confinement?.cwd;
35
- const network = networkFetchReason(step.cmd, cwd) ?? (cwd ? scriptNetworkReason(step.cmd, cwd) : null);
46
+ // Scripts the bot wrote that the operator's boxes let run (2026-10-27): what is in them goes on the card.
47
+ const scripts = ctx.confinement && cfg.scripts
48
+ ? writtenScriptsLetRun(step.cmd, ctx.confinement.cwd, ctx.confinement.workStartedAt, effectiveShell(step.shell), cfg.scripts).map((r) => {
49
+ const read = scriptText(r);
50
+ const path = relative(ctx.confinement.cwd, r.file) || r.file;
51
+ return { path, kind: r.kind, ...('problem' in read ? { problem: read.problem } : { text: read.text, ...(read.cut ? { cut: true } : {}) }), ...(r.script ? { script: r.script.name } : {}) };
52
+ })
53
+ : [];
54
+ // A fetch inside one is held as one on the line is (a `.ps1`'s is found by `scriptNetworkReason`).
55
+ const network = networkFetchReason(step.cmd, cwd) ??
56
+ (cwd ? scriptNetworkReason(step.cmd, cwd) : null) ??
57
+ scripts.map((x) => (x.text !== undefined && x.kind !== 'ps1' ? networkFetchReason(x.text, cwd) : null)).find(Boolean) ??
58
+ null;
36
59
  /*
37
60
  * A platform reached with the operator's access (2026-10-23): asked in every mode, unless Settings agree to it. A
38
61
  * program set to read only (2026-10-26) is not asked about when the line only reads with it; when it cannot be
@@ -44,8 +67,12 @@ export function makeAuthorizer(cfg, ask, signal) {
44
67
  ? (platformReason(step.cmd, step.shell) ?? platformOf(unclear.program) ?? unclear.program)
45
68
  : cfg.platformAccess === 'allow'
46
69
  ? null
47
- : platformReason(step.cmd, step.shell, reading?.kind === 'reads' ? new Set(reading.programs) : undefined);
48
- const held = { ...(platform ? { platform } : {}), ...(unclear ? { readOnly: unclear.why, readOnlyProgram: unclear.program } : {}) };
70
+ : platformReason(step.cmd, step.shell, notHeldFor(cfg, reading?.kind === 'reads' ? reading.programs : []));
71
+ const held = {
72
+ ...(platform ? { platform } : {}),
73
+ ...(unclear ? { readOnly: unclear.why, readOnlyProgram: unclear.program } : {}),
74
+ ...(scripts.length ? { scripts } : {}),
75
+ };
49
76
  if (network) {
50
77
  if (cfg.mode === 'unattended' && cfg.networkFetch === 'refuse')
51
78
  return { action: 'skip', reason: networkFetchRefusal(network) };
@@ -55,12 +82,18 @@ export function makeAuthorizer(cfg, ask, signal) {
55
82
  }
56
83
  if (platform)
57
84
  return await ask(step, ctx, held);
58
- if (cfg.mode === 'unattended')
85
+ // The bot's scripts: on a card with their text, unless Settings run them without asking (2026-10-27).
86
+ if (scripts.length && !(cfg.mode === 'unattended' && cfg.writtenScripts === 'run'))
87
+ return await ask(step, ctx, held);
88
+ if (cfg.mode === 'unattended' || ctx.chosen)
59
89
  return { action: 'run' };
60
90
  return await ask(step, ctx);
61
91
  },
62
92
  };
63
93
  }
94
+ /** What the chat is told when a script the bot wrote waits for the operator's word and nobody is there to give it. */
95
+ export const WRITTEN_NOBODY = 'refused: this runs a script written during this work, which the operator\'s Settings put to them first, and this run has nobody to ask. ' +
96
+ 'Put what it does in the step itself — a command may be several lines — or end blocked and say in "needed" what the operator has to run.';
64
97
  /** What the chat is told when a command to a platform was held and nobody was there to allow it. */
65
98
  export function platformRefusal(platform) {
66
99
  return (`refused: this command reaches ${platform} with the operator's access, which only the operator may allow, and this run has ` +
@@ -77,6 +110,10 @@ export function terminalAuthorizer(cfg, print) {
77
110
  print(` held: it reaches ${held.platform} with your access`);
78
111
  if (held?.readOnly)
79
112
  print(` held: ${held.readOnlyProgram ?? 'the program'} is set to read only, and this could not be read as only reading (${held.readOnly})`);
113
+ for (const x of held?.scripts ?? []) {
114
+ print(` it runs ${x.script ? `the script "${x.script}" of ${x.path}` : x.path}, written by the bot during this work:`);
115
+ print(x.text !== undefined ? x.text.split('\n').map((l) => ` | ${l}`).join('\n') : ` (${x.problem})`);
116
+ }
80
117
  const rl = createInterface({ input: stdin, output: stdout });
81
118
  try {
82
119
  const answer = (await rl.question(' [Enter] run [s] skip [q] abort > ')).trim().toLowerCase();
@@ -107,5 +144,7 @@ export function unattendedAuthorizer(cfg) {
107
144
  ? { action: 'skip', reason: readOnlyUnclearRefusal(held.readOnlyProgram ?? 'the program', held.readOnly) }
108
145
  : held?.platform
109
146
  ? { action: 'skip', reason: platformRefusal(held.platform) }
110
- : { action: 'run' });
147
+ : held?.scripts
148
+ ? { action: 'skip', reason: WRITTEN_NOBODY }
149
+ : { action: 'run' });
111
150
  }
@@ -159,7 +159,7 @@ export const DANGEROUS_TECHNIQUES = [
159
159
  * — which goes to the chat. Git asks for what it needs by itself: `git push`, `git fetch`, `git pull` and
160
160
  * `git clone` are not touched by this.
161
161
  */
162
- pattern: /\b(?:git|ssh)-askpass\b|\b(?:GIT_ASKPASS|SSH_ASKPASS(?:_REQUIRE)?|GIT_SSH_COMMAND|GIT_SSH|GCM_[A-Z_]+)\b|\bcore\.(?:askpass|sshCommand)\b|\bcredential\.(?:helper|[\w.-]*\.helper)\b|\bgit-credential(?:-[\w-]+)?\b|\bgit(?:\.exe)?(?:\s+-[-\w.=]+(?:\s+[^\s-][^\s]*)?)*\s+credential(?:-[\w-]+)?\b/i,
162
+ pattern: /\b(?:git|ssh)-askpass\b|\b(?:GIT_ASKPASS|SSH_ASKPASS(?:_REQUIRE)?|GIT_SSH_COMMAND|GIT_SSH|GCM_[A-Z_]+|GIT_TRACE_REDACT|GIT_CURL_VERBOSE|GIT_TRACE_CURL(?:_NO_DATA)?)\b|\bcore\.(?:askpass|sshCommand)\b|\bcredential\.(?:helper|[\w.-]*\.helper)\b|\bgit-credential(?:-[\w-]+)?\b|\bgit(?:\.exe)?(?:\s+-[-\w.=]+(?:\s+[^\s-][^\s]*)?)*\s+credential(?:-[\w-]+)?\b/i,
163
163
  why: 'the password Git asks for goes from its own window straight to git; a step that runs that window, a credential helper or git\'s password settings itself could catch what the operator types. Run git itself — push, fetch, pull, clone — and Git asks for what it needs in its own window.',
164
164
  },
165
165
  {
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The scripts of package.json a command line runs (2026-10-27): `npm run build`, `npm test`, `pnpm lint`, `yarn dev`.
3
+ *
4
+ * The operator: "whether I allow npm … scripts that are already there, and another box for scripts the bot created".
5
+ * A script of package.json is a command line someone wrote into the project; one the bot added or changed is a script
6
+ * the bot wrote, as much as a `.ps1` is, and it used to run unread. So each one a line runs is told apart here: the
7
+ * project's, the same as it was in the last commit before the work began; or the work's, added or changed since.
8
+ *
9
+ * Read only from what the line says: which runner, which script, in which folder (`--prefix`, `-C`, `--dir`, `--cwd`)
10
+ * and which workspace (`-w`, `--workspace`; `--workspaces`, `-r`, `--filter` for all of them). A name the line builds
11
+ * at run time cannot be told and is taken as written during the work.
12
+ */
13
+ import { existsSync, readFileSync, statSync } from 'node:fs';
14
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
15
+ import { gitSync } from '../vcs/git.js';
16
+ import { scanCommandHeads } from './commandHeads.js';
17
+ const RUNNERS = new Set(['npm', 'pnpm', 'yarn', 'bun']);
18
+ /** The runners' own commands, which a bare word after them is before it is a script's name (pnpm, yarn and bun run a script by its name alone). */
19
+ const OWN_COMMANDS = new Set([
20
+ 'add', 'audit', 'bin', 'cache', 'ci', 'config', 'create', 'dedupe', 'deploy', 'dlx', 'doctor', 'env', 'exec', 'explain', 'fetch', 'help',
21
+ 'i', 'import', 'info', 'init', 'install', 'link', 'list', 'login', 'logout', 'ls', 'node', 'outdated', 'pack', 'patch', 'pm', 'prune', 'publish',
22
+ 'rebuild', 'remove', 'rm', 'root', 'run', 'run-script', 'server', 'set', 'setup', 'store', 'tag', 'test', 't', 'unlink', 'up', 'update',
23
+ 'upgrade', 'version', 'why', 'workspace', 'workspaces',
24
+ ]);
25
+ /** Switches that take the next word as their value. */
26
+ const TAKES_VALUE = /^(?:--prefix|-C|--dir|--cwd|-w|--workspace|--filter|-F|--userconfig|--cache|--registry|--loglevel|--script-shell|--reporter)$/;
27
+ const readScripts = (text) => {
28
+ if (text === null)
29
+ return null;
30
+ try {
31
+ const value = JSON.parse(text.replace(/^/, ''));
32
+ const out = {};
33
+ for (const [k, v] of Object.entries(value.scripts ?? {}))
34
+ if (typeof v === 'string')
35
+ out[k] = v;
36
+ return out;
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ };
42
+ const scriptsOnDisk = (pkg) => {
43
+ try {
44
+ return readScripts(readFileSync(pkg, 'utf8'));
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ };
50
+ /** Every package.json under a folder, the git-ignored ones (node_modules) left out. */
51
+ function workspacePackages(dir) {
52
+ const listed = gitSync(dir, ['ls-files', '-co', '--exclude-standard', '--', 'package.json', '**/package.json']);
53
+ const found = listed.ok ? listed.stdout.split('\n').filter((p) => p && !/(^|\/)node_modules\//.test(p)).map((p) => resolve(dir, p)) : [];
54
+ if (existsSync(join(dir, 'package.json')) && !found.some((p) => p === join(dir, 'package.json')))
55
+ found.unshift(join(dir, 'package.json'));
56
+ return found;
57
+ }
58
+ /** The scripts of package.json this line runs, with the package.json each one is in. */
59
+ export function packageScriptsRun(command, cwd, shell) {
60
+ const out = [];
61
+ for (const call of scanCommandHeads(command, shell ?? 'pwsh').calls) {
62
+ const runner = call.head.replace(/^.*[\\/]/, '').replace(/\.(?:exe|cmd|ps1)$/i, '').toLowerCase();
63
+ if (!RUNNERS.has(runner))
64
+ continue;
65
+ let folder;
66
+ let workspace;
67
+ let everyWorkspace = false;
68
+ const words = [];
69
+ for (let i = 0; i < call.args.length; i++) {
70
+ const a = call.args[i];
71
+ const [flag, inline] = a.literal.startsWith('-') && a.literal.includes('=') ? [a.literal.slice(0, a.literal.indexOf('=')), a.literal.slice(a.literal.indexOf('=') + 1)] : [a.literal, undefined];
72
+ if (flag === '--')
73
+ break;
74
+ if (flag.startsWith('-')) {
75
+ const value = inline ?? (TAKES_VALUE.test(flag) ? call.args[++i]?.literal : undefined);
76
+ if (flag === '--prefix' || flag === '-C' || flag === '--dir' || flag === '--cwd')
77
+ folder = value;
78
+ else if (flag === '-w' || flag === '--workspace')
79
+ workspace = value;
80
+ else if (flag === '--workspaces' || flag === '-ws' || flag === '-r' || flag === '--recursive' || flag === '--filter' || flag === '-F')
81
+ everyWorkspace = true;
82
+ continue;
83
+ }
84
+ words.push(a);
85
+ }
86
+ const base = resolve(cwd, folder ?? '.');
87
+ const packages = () => {
88
+ if (everyWorkspace)
89
+ return workspacePackages(base);
90
+ if (workspace) {
91
+ const own = resolve(base, workspace, 'package.json');
92
+ return existsSync(own) ? [own] : workspacePackages(base);
93
+ }
94
+ return [join(base, 'package.json')];
95
+ };
96
+ const sub = words[0];
97
+ if (!sub)
98
+ continue;
99
+ const verb = sub.literal.toLowerCase();
100
+ let name;
101
+ let implicit = false;
102
+ if (verb === 'run' || verb === 'run-script' || verb === 'rum' || verb === 'urn')
103
+ name = words[1];
104
+ else if (runner !== 'bun' && (verb === 'test' || verb === 't' || verb === 'tst'))
105
+ name = { literal: 'test', dynamic: false };
106
+ else if (verb === 'start' || verb === 'stop' || verb === 'restart')
107
+ name = { literal: verb, dynamic: false };
108
+ else if (runner !== 'npm' && !OWN_COMMANDS.has(verb)) {
109
+ // `pnpm lint`, `yarn dev`, `bun dev`: a script only when package.json has one by that name.
110
+ name = sub;
111
+ implicit = true;
112
+ }
113
+ if (!name)
114
+ continue;
115
+ // `bun run x.ts` is a file of code, not a script: see `codeFilesRun`.
116
+ if (runner === 'bun' && /[\\/]|\.[cm]?[jt]sx?$/i.test(name.literal))
117
+ continue;
118
+ for (const pkg of packages()) {
119
+ if (name.dynamic) {
120
+ out.push({ pkg, name: name.literal, command: null, dynamic: true });
121
+ continue;
122
+ }
123
+ const scripts = scriptsOnDisk(pkg);
124
+ // npm is given npm_config_ignore_scripts (`stepEnv.ts`), which leaves pre- and post- scripts out; yarn and bun run them.
125
+ const names = runner === 'yarn' || runner === 'bun' ? [`pre${name.literal}`, name.literal, `post${name.literal}`] : [name.literal];
126
+ for (const n of names) {
127
+ const cmd = scripts?.[n] ?? null;
128
+ if (cmd === null && (n !== name.literal || implicit))
129
+ continue;
130
+ out.push({ pkg, name: n, command: cmd });
131
+ }
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+ /** Whether a line writes package.json's scripts itself: `npm pkg set scripts.x=…`, `npm set-script`, or the file written. */
137
+ export function writesPackageScripts(command) {
138
+ return (/\b(?:npm|pnpm)(?:\.cmd)?\s+(?:pkg\s+set\b[^|;\n]*\bscripts\.|set-script\b)/i.test(command) ||
139
+ /\b(Set-Content|Add-Content|Out-File|New-Item|Copy-Item|Move-Item|Tee-Object|sc|ac|cp|copy|mv|move|tee)\b[^|;\n]*package\.json\b|>\s*["']?[^\s"']*package\.json\b/i.test(command));
140
+ }
141
+ /**
142
+ * Why a script of package.json was written during the work, or null when it is the project's: the same as in the last
143
+ * commit before the work began. A package.json git does not know is the project's when it was made before then (and
144
+ * its scripts cannot be told apart further). `sameLine`: the line itself writes package.json's scripts.
145
+ */
146
+ export function packageScriptWritten(run, since, sameLine) {
147
+ if (run.dynamic)
148
+ return 'its name is decided when the line runs, so nothing tells whose it is';
149
+ if (run.command === null)
150
+ return sameLine ? 'this same line writes it into package.json' : null;
151
+ const began = since ? Date.parse(since) : NaN;
152
+ const top = gitSync(dirname(run.pkg), ['rev-parse', '--show-toplevel']);
153
+ if (top.ok && top.stdout) {
154
+ const rel = relative(top.stdout, run.pkg);
155
+ const path = rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel.replace(/\\/g, '/') : null;
156
+ const known = path !== null && gitSync(top.stdout, ['log', '-1', '--format=%H', '--', path]).stdout.trim() !== '';
157
+ if (path && known) {
158
+ const at = Number.isFinite(began) ? gitSync(top.stdout, ['rev-list', '-1', `--before=@${Math.floor(began / 1000)}`, 'HEAD']) : gitSync(top.stdout, ['rev-parse', 'HEAD']);
159
+ const commit = at.ok ? at.stdout.trim() : '';
160
+ if (!commit)
161
+ return 'package.json had no commit before this work began';
162
+ const then = gitSync(top.stdout, ['show', `${commit}:${path}`]);
163
+ const before = then.ok ? readScripts(then.stdout) : {};
164
+ const was = before?.[run.name];
165
+ if (was === run.command)
166
+ return null;
167
+ return was === undefined ? 'it was added to package.json during this work' : 'it was changed in package.json during this work';
168
+ }
169
+ }
170
+ if (!Number.isFinite(began))
171
+ return null;
172
+ let born = NaN;
173
+ try {
174
+ born = statSync(run.pkg).birthtimeMs;
175
+ }
176
+ catch {
177
+ /* not there: npm says so */
178
+ }
179
+ return Number.isFinite(born) && born >= began - 1000 ? 'package.json was made during this work and is not committed' : null;
180
+ }