copilot-operator 0.1.68 → 0.1.70

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 +15 -2
  2. package/dist/src/api/operator.service.js +31 -10
  3. package/dist/src/api/server.js +10 -0
  4. package/dist/src/cli.js +2 -0
  5. package/dist/src/config/lockedPolicy.js +14 -0
  6. package/dist/src/config/schema.js +22 -0
  7. package/dist/src/exec/authorizer.js +45 -6
  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 +110 -7
  12. package/dist/src/exec/policyManifest.js +13 -0
  13. package/dist/src/exec/programs.js +6 -1
  14. package/dist/src/exec/redaction.js +17 -2
  15. package/dist/src/exec/scriptFiles.js +210 -32
  16. package/dist/src/exec/scriptKinds.js +86 -0
  17. package/dist/src/exec/stepEnv.js +9 -2
  18. package/dist/src/orchestrator/handoff.js +80 -29
  19. package/dist/src/orchestrator/leadRunner.js +5 -2
  20. package/dist/src/orchestrator/review.js +13 -3
  21. package/dist/src/orchestrator/taskRunner.js +105 -19
  22. package/dist/src/plan/kerrigan.js +4 -4
  23. package/dist/src/plan/systemGuide.js +93 -14
  24. package/dist/src/protocol/leadSchema.js +8 -1
  25. package/dist/src/protocol/replySchema.js +13 -3
  26. package/dist/src/protocol/reviewSchema.js +4 -1
  27. package/dist/src/queue/queue.js +8 -4
  28. package/dist/src/session/checkpoint.js +48 -0
  29. package/dist/src/session/compose.js +1 -1
  30. package/dist/src/session/story.js +14 -0
  31. package/dist/src/session/workspaceGit.js +64 -24
  32. package/dist/src/vcs/gitConfigGuard.js +126 -0
  33. package/dist/src/vcs/newBranch.js +7 -3
  34. package/dist/web/404.html +2 -2
  35. package/dist/web/_next/static/chunks/1024-67625a65f58057ae.js +1 -0
  36. package/dist/web/_next/static/chunks/1077.9fe1c0425bf51375.js +1 -0
  37. package/dist/web/_next/static/chunks/1548.cae3ba2196c8d52f.js +1 -0
  38. package/dist/web/_next/static/chunks/2163.5c9f8477d98b75a4.js +1 -0
  39. package/dist/web/_next/static/chunks/714.a0b32193f71e0e91.js +1 -0
  40. package/dist/web/_next/static/chunks/7220.5d6da026e0b34169.js +1 -0
  41. package/dist/web/_next/static/chunks/7921-0f7954cb5a9f697b.js +1 -0
  42. package/dist/web/_next/static/chunks/8124-a39d85dff0db6600.js +1 -0
  43. package/dist/web/_next/static/chunks/8584.6aa7ce56f7552f17.js +1 -0
  44. package/dist/web/_next/static/chunks/9067.2e4ba2e0e572f21e.js +1 -0
  45. package/dist/web/_next/static/chunks/9747.763da2026719a863.js +1 -0
  46. package/dist/web/_next/static/chunks/9929-2e0b1d006ebd5345.js +1 -0
  47. package/dist/web/_next/static/chunks/app/layout-52a2079ffa83c21f.js +1 -0
  48. package/dist/web/_next/static/chunks/app/page-44eac9d137f26dc5.js +1 -0
  49. package/dist/web/_next/static/chunks/app/queue/{page-fb49cb2d3dc6d14c.js → page-82f724d0842f4870.js} +1 -1
  50. package/dist/web/_next/static/chunks/app/settings/page-2df196e25cb7bfe1.js +1 -0
  51. package/dist/web/_next/static/chunks/{webpack-a3dd4e873378e9ae.js → webpack-950df0f512eef7ec.js} +1 -1
  52. package/dist/web/_next/static/css/cfe8ccb4adf3a311.css +1 -0
  53. package/dist/web/defaults.html +2 -2
  54. package/dist/web/defaults.txt +8 -8
  55. package/dist/web/index.html +3 -3
  56. package/dist/web/index.txt +9 -9
  57. package/dist/web/queue.html +2 -2
  58. package/dist/web/queue.txt +9 -9
  59. package/dist/web/settings.html +2 -2
  60. package/dist/web/settings.txt +9 -9
  61. package/dist/web/system.html +2 -2
  62. package/dist/web/system.txt +9 -9
  63. package/package.json +3 -2
  64. package/prompts/level1.md +25 -8
  65. package/dist/web/_next/static/chunks/1024-e4e596b184e05e91.js +0 -1
  66. package/dist/web/_next/static/chunks/1077.61be1f7b74828a4c.js +0 -1
  67. package/dist/web/_next/static/chunks/1548.a112748131a396ed.js +0 -1
  68. package/dist/web/_next/static/chunks/2163.581b2e067fe95eb3.js +0 -1
  69. package/dist/web/_next/static/chunks/6262-d074473db83ee798.js +0 -1
  70. package/dist/web/_next/static/chunks/714.5cc35e9440591fd9.js +0 -1
  71. package/dist/web/_next/static/chunks/7220.9313ff4ad7480f12.js +0 -1
  72. package/dist/web/_next/static/chunks/7921-19f36659bdea8d09.js +0 -1
  73. package/dist/web/_next/static/chunks/8124-1952612d3a681879.js +0 -1
  74. package/dist/web/_next/static/chunks/8584.5ff9e8c49bf9b259.js +0 -1
  75. package/dist/web/_next/static/chunks/9067.f0db4983b81a2df6.js +0 -1
  76. package/dist/web/_next/static/chunks/9747.0e0c54e5f8fab6c4.js +0 -1
  77. package/dist/web/_next/static/chunks/app/layout-5e0e7601702723bb.js +0 -1
  78. package/dist/web/_next/static/chunks/app/page-18954867735bf8c0.js +0 -1
  79. package/dist/web/_next/static/chunks/app/settings/page-7d120feb5af0ace9.js +0 -1
  80. package/dist/web/_next/static/css/45da8a97dbf20586.css +0 -1
  81. /package/dist/web/_next/static/{52rfiQXdaggycbuMIIw4K → DzoLjnxX5FvdxuPasWlnb}/_buildManifest.js +0 -0
  82. /package/dist/web/_next/static/{52rfiQXdaggycbuMIIw4K → DzoLjnxX5FvdxuPasWlnb}/_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);
@@ -297,6 +299,10 @@ let OperatorController = class OperatorController {
297
299
  workspaceBranch(base) {
298
300
  return this.ops.workspaceBranch(base || undefined).catch(fail);
299
301
  }
302
+ /** The two numbers on the Git button: files not committed, and files on this branch against `base`. Read-only. */
303
+ workspaceGitCounts(base) {
304
+ return this.ops.workspaceGitCounts(base || undefined).catch(fail);
305
+ }
300
306
  workspaceCommit(sha) {
301
307
  if (!sha)
302
308
  throw new BadRequestException('sha is required');
@@ -399,7 +405,7 @@ let OperatorController = class OperatorController {
399
405
  }
400
406
  /** The lead's question (two chats): the operator's answer, as text. Stopping the task is `approvals/:id` with abort. */
401
407
  answerQuestion(id, body) {
402
- const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '', body?.ran === false ? false : undefined);
408
+ const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '', body?.ran === false ? false : undefined, typeof body?.outcome === 'string' ? body.outcome : undefined);
403
409
  if (!result.ok)
404
410
  throw new BadRequestException(result.problem);
405
411
  return result;
@@ -736,6 +742,13 @@ __decorate([
736
742
  __metadata("design:paramtypes", [String]),
737
743
  __metadata("design:returntype", Promise)
738
744
  ], OperatorController.prototype, "workspaceBranch", null);
745
+ __decorate([
746
+ Get('workspace/git/counts'),
747
+ __param(0, Query('base')),
748
+ __metadata("design:type", Function),
749
+ __metadata("design:paramtypes", [String]),
750
+ __metadata("design:returntype", Promise)
751
+ ], OperatorController.prototype, "workspaceGitCounts", null);
739
752
  __decorate([
740
753
  Get('workspace/git/commit'),
741
754
  __param(0, Query('sha')),
@@ -24,7 +24,7 @@ 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
29
  import { Hold } from '../orchestrator/hold.js';
30
30
  import { exportFileName, exportMachine, writeAttemptRecord } from '../session/exports.js';
@@ -33,7 +33,7 @@ import { buildStory } from '../session/story.js';
33
33
  import { buildTaskExchange } from '../session/taskExchange.js';
34
34
  import { chatNotice } from '../session/chatNotice.js';
35
35
  import { kerriganFileName, kerriganPersona } from '../plan/kerrigan.js';
36
- import { branchChanges, workspaceCommit, workspaceGit, workspaceGitVersions } from '../session/workspaceGit.js';
36
+ import { branchChanges, gitCounts, workspaceCommit, workspaceGit, workspaceGitVersions } from '../session/workspaceGit.js';
37
37
  import { chatCode } from '../transport/chatSession.js';
38
38
  /** The folders the operator works in: the default new sessions start on, and the rest by name. */
39
39
  /** The longest level 2 a project may have: Kerrigan carries each one whole. */
@@ -849,6 +849,8 @@ let OperatorService = class OperatorService {
849
849
  networkFetch: cfg.execution.networkFetch,
850
850
  platformAccess: cfg.execution.questions === 'agree' ? 'allow' : 'ask',
851
851
  readOnlyPrograms: cfg.execution.readOnlyPrograms,
852
+ scripts: cfg.execution.scripts,
853
+ writtenScripts: cfg.execution.writtenScripts,
852
854
  };
853
855
  /*
854
856
  * An unattended run that cannot legally execute anything is stopped here, where the operator
@@ -1216,6 +1218,13 @@ let OperatorService = class OperatorService {
1216
1218
  throw new Error(ws.problem ?? 'No project folder is open.');
1217
1219
  return await branchChanges(ws.dir, base);
1218
1220
  }
1221
+ /** The two numbers on the Git button: files not committed, and files on this branch against `base` (see `gitCounts`). */
1222
+ async workspaceGitCounts(base) {
1223
+ const ws = await this.workspace();
1224
+ if (!ws.ok)
1225
+ return { isRepo: false, uncommitted: 0, branch: null };
1226
+ return await gitCounts(ws.dir, base);
1227
+ }
1219
1228
  async workspaceCommit(sha) {
1220
1229
  const ws = await this.workspace();
1221
1230
  if (!ws.ok)
@@ -1877,7 +1886,7 @@ let OperatorService = class OperatorService {
1877
1886
  }
1878
1887
  else if (a.kind === 'question') {
1879
1888
  const handed = p.approval.question?.handoff;
1880
- note = handed ? handoffResultMessage(handed, a.ran !== false, a.answer) : `You asked: ${p.approval.question?.text ?? ''}\n\nThe operator answers: ${a.answer}`;
1889
+ note = handed ? handoffResultMessage(handed, handoffOutcomeOf(a.outcome, a.ran), a.answer) : `You asked: ${p.approval.question?.text ?? ''}\n\nThe operator answers: ${a.answer}`;
1881
1890
  }
1882
1891
  else if (a.kind === 'retry' && p.approval.retry) {
1883
1892
  const r = p.approval.retry;
@@ -2167,18 +2176,24 @@ let OperatorService = class OperatorService {
2167
2176
  const cfg = await this.settings.load();
2168
2177
  return await this.start(threadId, cfg.execution.mode);
2169
2178
  }
2170
- answerQuestion(approvalId, text, ran) {
2179
+ answerQuestion(approvalId, text, ran, outcome) {
2171
2180
  const w = this.waiting.get(approvalId);
2172
2181
  if (!w?.resolveAnswer)
2173
2182
  return { ok: false, problem: 'No question of the lead is waiting under that id.' };
2174
- // Commands handed over (2026-10-26): what they printed, or that the operator did not run them, with a word or none.
2183
+ /*
2184
+ * Commands handed over (2026-10-26): what they printed; sent back for a correction, which needs what to correct
2185
+ * (2026-10-27); or that the operator will not run them, with a word or none.
2186
+ */
2175
2187
  const handed = !!w.approval.question?.handoff;
2176
- if (handed && ran !== false && !text.trim())
2188
+ const how = handoffOutcomeOf(outcome, ran);
2189
+ if (handed && how === 'ran' && !text.trim())
2177
2190
  return { ok: false, problem: 'Paste what the commands printed first.' };
2191
+ if (handed && how === 'revise' && !text.trim())
2192
+ return { ok: false, problem: 'Say what to correct first.' };
2178
2193
  if (!handed && !text.trim())
2179
2194
  return { ok: false, problem: 'Write the answer first.' };
2180
2195
  this.waiting.delete(approvalId);
2181
- w.resolveAnswer(handed ? { answer: text.trim(), ran: ran !== false } : { answer: text.trim() });
2196
+ w.resolveAnswer(handed ? { answer: text.trim(), ran: how === 'ran', outcome: how } : { answer: text.trim() });
2182
2197
  this.bus.publish({ sessionId: w.approval.sessionId, taskId: w.approval.taskId, type: 'approval-decided', level: 'info',
2183
2198
  message: 'the operator answered the lead', data: { approvalId, question: true } });
2184
2199
  return { ok: true };
@@ -2308,8 +2323,12 @@ let OperatorService = class OperatorService {
2308
2323
  for (const [id, w] of this.waiting) {
2309
2324
  if (this.runKey(w.approval.sessionId) !== sessionId)
2310
2325
  continue;
2311
- // A fetch waits for its own answer: "run the rest without asking" is not an answer to it; nor is a question.
2312
- if (w.approval.network || w.approval.model || w.approval.question || w.approval.plan)
2326
+ // A fetch waits for its own answer: "run the rest without asking" is not an answer to it; nor is a question, nor
2327
+ // a platform reached with the operator's access, a read-only program's unclear line, a subtask's retry, or a
2328
+ // script the bot wrote that Settings put to the operator first (audit, 2026-10-27: these were let go).
2329
+ if (w.approval.network || w.approval.model || w.approval.question || w.approval.plan || w.approval.platform || w.approval.readOnly || w.approval.retry)
2330
+ continue;
2331
+ if (w.approval.scripts && run.policy.writtenScripts !== 'run')
2313
2332
  continue;
2314
2333
  this.waiting.delete(id);
2315
2334
  w.resolve({ action: 'run' });
@@ -2332,7 +2351,8 @@ let OperatorService = class OperatorService {
2332
2351
  // This is checked per step rather than captured once, which is what makes the switch
2333
2352
  // take effect from the very next step instead of the next run. A held step is the
2334
2353
  // exception: it is asked about in an unattended run too, which is the point of holding it.
2335
- if (!held && this.running.get(this.runKey(ctx.sessionId ?? ''))?.mode === 'unattended') {
2354
+ const forTheOperator = !!(held?.network || held?.platform || held?.readOnly || (held?.scripts && policy.writtenScripts !== 'run'));
2355
+ if (!forTheOperator && this.running.get(this.runKey(ctx.sessionId ?? ''))?.mode === 'unattended') {
2336
2356
  resolvePromise({ action: 'run' });
2337
2357
  return;
2338
2358
  }
@@ -2356,6 +2376,7 @@ let OperatorService = class OperatorService {
2356
2376
  ...(held?.network ? { network: held.network } : {}),
2357
2377
  ...(held?.platform ? { platform: held.platform } : {}),
2358
2378
  ...(held?.readOnly ? { readOnly: held.readOnly } : {}),
2379
+ ...(held?.scripts ? { scripts: held.scripts } : {}),
2359
2380
  };
2360
2381
  this.waiting.set(approval.id, { approval, resolve: resolvePromise });
2361
2382
  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,8 @@ program
502
502
  networkFetch: cfg.execution.networkFetch,
503
503
  platformAccess: cfg.execution.questions === 'agree' ? 'allow' : 'ask',
504
504
  readOnlyPrograms: cfg.execution.readOnlyPrograms,
505
+ scripts: cfg.execution.scripts,
506
+ writtenScripts: cfg.execution.writtenScripts,
505
507
  };
506
508
  const authorizer = cfg.execution.mode === 'unattended'
507
509
  ? 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,21 @@ export const RunConfigSchema = z.object({
304
307
  * named here are ignored.
305
308
  */
306
309
  readOnlyPrograms: z.array(z.string()).default([]),
310
+ /**
311
+ * Which scripts may run (operator, 2026-10-27: "whether I allow npm, ts files, ps1 files … only for scripts that
312
+ * are already there, and another box for scripts the bot created"). For each kind (`exec/scriptKinds.ts`): `own`,
313
+ * the project's, there before the work began; `written`, the bot's, written during the work. A kind whose box is
314
+ * empty is not run: the chat hands it to the operator. The defaults are the rule as it was: the project's run,
315
+ * the bot's do not.
316
+ */
317
+ scripts: z
318
+ .object(Object.fromEntries(SCRIPT_KINDS.map((k) => [k, ScriptRuleSchema])))
319
+ .prefault({}),
320
+ /**
321
+ * A script the bot wrote, its box ticked, in a run without asking (2026-10-27): `ask` puts it on a card with its
322
+ * text first; `run` runs it as any other step. A run that asks before every command asks about these too.
323
+ */
324
+ writtenScripts: z.enum(['ask', 'run']).default('ask'),
307
325
  denyPatterns: z
308
326
  .array(z.string())
309
327
  .default([
@@ -560,6 +578,8 @@ export async function resolveConfig(cfg, configPath, baseDir) {
560
578
  denyPatterns: cfg.execution.denyPatterns,
561
579
  isolation: cfg.execution.isolation,
562
580
  passEnv: cfg.execution.passEnv,
581
+ scripts: cfg.execution.scripts,
582
+ writtenScripts: cfg.execution.writtenScripts,
563
583
  };
564
584
  const outcome = { applied: false, changes: [] };
565
585
  for (const lock of locks) {
@@ -579,6 +599,8 @@ export async function resolveConfig(cfg, configPath, baseDir) {
579
599
  denyPatterns: policy.denyPatterns,
580
600
  isolation: policy.isolation ?? cfg.execution.isolation,
581
601
  passEnv: policy.passEnv ?? cfg.execution.passEnv,
602
+ scripts: policy.scripts ?? cfg.execution.scripts,
603
+ writtenScripts: policy.writtenScripts ?? cfg.execution.writtenScripts,
582
604
  },
583
605
  configPath,
584
606
  baseDir,
@@ -3,7 +3,10 @@ import { networkFetchReason, networkFetchRefusal } from './network.js';
3
3
  import { 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
@@ -45,7 +68,11 @@ export function makeAuthorizer(cfg, ask, signal) {
45
68
  : cfg.platformAccess === 'allow'
46
69
  ? null
47
70
  : 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 } : {}) };
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
+ }
@@ -8,7 +8,8 @@
8
8
  * Read by the programs a line starts (`commandHeads`, as the shell reads it), not by words anywhere in it: a file
9
9
  * that mentions `az` is not a command to Azure.
10
10
  */
11
- import { commandHeads, externalProgram } from './programs.js';
11
+ import { commandHeads, externalProgram, startProcessTargets } from './programs.js';
12
+ import { scanCommandHeads } from './commandHeads.js';
12
13
  /** Platform command-line tools, by the program's name. */
13
14
  const TOOLS = {
14
15
  az: 'Azure (az)',
@@ -91,8 +92,51 @@ export function platformReason(command, shell, reading) {
91
92
  if (pattern.test(bare) || pattern.test(bare.toLowerCase()))
92
93
  return name;
93
94
  }
95
+ /*
96
+ * What a package runner or Start-Process starts (audit, 2026-10-27): `npx vercel deploy`, `npm exec -- vercel`,
97
+ * `pnpm dlx netlify deploy`, `Start-Process gh -ArgumentList …` reach the platform as the program itself does.
98
+ */
99
+ for (const program of startedPrograms(command, shell)) {
100
+ if (reading?.has(program))
101
+ continue;
102
+ if (TOOLS[program])
103
+ return TOOLS[program];
104
+ }
94
105
  for (const [pattern, name] of REGISTRIES)
95
106
  if (pattern.test(command))
96
107
  return name;
97
108
  return null;
98
109
  }
110
+ const RUNNERS = { npx: null, pnpx: null, bunx: null, npm: new Set(['exec', 'x']), pnpm: new Set(['exec', 'dlx']), yarn: new Set(['exec', 'dlx']) };
111
+ /** The programs a package runner and Start-Process are given to start, by name. */
112
+ function startedPrograms(command, shell) {
113
+ const out = [];
114
+ const name = (word) => word.replace(/^.*[\\/]/, '').replace(/^['"]|['"]$/g, '').replace(/\.(?:exe|cmd|ps1)$/i, '').replace(/@[^@/]*$/, '').toLowerCase();
115
+ for (const call of scanCommandHeads(command, shell ?? 'pwsh').calls) {
116
+ const runner = name(call.head);
117
+ if (!(runner in RUNNERS))
118
+ continue;
119
+ let args = call.args.map((a) => a.literal);
120
+ const words = RUNNERS[runner];
121
+ if (words) {
122
+ if (!words.has((args[0] ?? '').toLowerCase()))
123
+ continue;
124
+ args = args.slice(1);
125
+ }
126
+ for (let i = 0; i < args.length; i++) {
127
+ const a = args[i];
128
+ if (a === '--')
129
+ continue;
130
+ if (a.startsWith('-')) {
131
+ if (/^(?:-p|--package)$/.test(a))
132
+ out.push(name(args[++i] ?? ''));
133
+ continue;
134
+ }
135
+ out.push(name(a));
136
+ break;
137
+ }
138
+ }
139
+ for (const target of startProcessTargets(command))
140
+ out.push(name(target));
141
+ return out.filter(Boolean);
142
+ }