copilot-operator 0.1.44 → 0.1.46

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 (45) hide show
  1. package/dist/src/api/operator.controller.js +25 -1
  2. package/dist/src/api/operator.service.js +89 -16
  3. package/dist/src/api/server.js +6 -4
  4. package/dist/src/config/schema.js +21 -1
  5. package/dist/src/orchestrator/taskRunner.js +131 -23
  6. package/dist/src/plan/systemGuide.js +26 -2
  7. package/dist/src/session/checkpoint.js +91 -0
  8. package/dist/src/session/store.js +2 -0
  9. package/dist/src/transport/copilotTransport.js +92 -18
  10. package/dist/web/404.html +2 -2
  11. package/dist/web/_next/static/chunks/{549-1fe42544e4b72942.js → 549-8732dd2c1339bc5d.js} +1 -1
  12. package/dist/web/_next/static/chunks/867-7fb52be342fa64e5.js +1 -0
  13. package/dist/web/_next/static/chunks/app/defaults/page-614be29d185a2947.js +1 -0
  14. package/dist/web/_next/static/chunks/app/layout-485ce9395cb17998.js +1 -0
  15. package/dist/web/_next/static/chunks/app/page-ed6a5a2ff1b6285e.js +1 -0
  16. package/dist/web/_next/static/chunks/app/sessions/view/page-835d3533fdc63082.js +1 -0
  17. package/dist/web/_next/static/css/{eaec9cc6fe8aceb7.css → 70ceb261074b139c.css} +1 -1
  18. package/dist/web/appearance.html +2 -2
  19. package/dist/web/appearance.txt +10 -10
  20. package/dist/web/defaults.html +2 -2
  21. package/dist/web/defaults.txt +10 -10
  22. package/dist/web/history.html +2 -2
  23. package/dist/web/history.txt +10 -10
  24. package/dist/web/import.html +2 -2
  25. package/dist/web/import.txt +10 -10
  26. package/dist/web/index.html +2 -2
  27. package/dist/web/index.txt +10 -10
  28. package/dist/web/level1.html +2 -2
  29. package/dist/web/level1.txt +10 -10
  30. package/dist/web/presets.html +2 -2
  31. package/dist/web/presets.txt +10 -10
  32. package/dist/web/sessions/view.html +2 -2
  33. package/dist/web/sessions/view.txt +10 -10
  34. package/dist/web/sessions.html +2 -2
  35. package/dist/web/sessions.txt +10 -10
  36. package/dist/web/system.html +2 -2
  37. package/dist/web/system.txt +10 -10
  38. package/package.json +1 -1
  39. package/dist/web/_next/static/chunks/867-0f0f8c3bd37be31e.js +0 -1
  40. package/dist/web/_next/static/chunks/app/defaults/page-56134fbb8cc7554f.js +0 -1
  41. package/dist/web/_next/static/chunks/app/layout-12f138ee04d33c1e.js +0 -1
  42. package/dist/web/_next/static/chunks/app/page-09c6e2d42098f8d4.js +0 -1
  43. package/dist/web/_next/static/chunks/app/sessions/view/page-afc235a9171535d8.js +0 -1
  44. /package/dist/web/_next/static/{BX8Nw248DTY9xAfUu2pOH → uAYbk9CSKPZe3-jWXmPOP}/_buildManifest.js +0 -0
  45. /package/dist/web/_next/static/{BX8Nw248DTY9xAfUu2pOH → uAYbk9CSKPZe3-jWXmPOP}/_ssgManifest.js +0 -0
@@ -544,7 +544,23 @@ let OperatorController = class OperatorController {
544
544
  chatSend(body = {}) {
545
545
  if (typeof body?.text !== 'string' || !body.text.trim())
546
546
  throw new BadRequestException('text is required');
547
- return this.ops.chatSend({ text: body.text, ...(typeof body.threadId === 'string' && body.threadId ? { threadId: body.threadId } : {}) }).catch(fail);
547
+ return this.ops
548
+ .chatSend({
549
+ text: body.text,
550
+ ...(typeof body.threadId === 'string' && body.threadId ? { threadId: body.threadId } : {}),
551
+ ...(typeof body.model === 'string' && body.model.trim() ? { model: body.model } : {}),
552
+ ...(body.manualModel === true ? { manualModel: true } : {}),
553
+ })
554
+ .catch(fail);
555
+ }
556
+ /** Back to before a message: the folder as it was then, that message and the ones after it taken out. */
557
+ async chatRewind(id, body = {}) {
558
+ if (typeof body?.taskId !== 'string' || !body.taskId)
559
+ throw new BadRequestException('taskId is required');
560
+ const r = await this.ops.chatRewind(id, body.taskId).catch(fail);
561
+ if (!r.ok)
562
+ throw new BadRequestException(r.problem);
563
+ return r;
548
564
  }
549
565
  /** One folder of the session's repository at its branch (or the task's commit): read-only, for the workbench. */
550
566
  repoTree(id, path, task) {
@@ -1250,6 +1266,14 @@ __decorate([
1250
1266
  __metadata("design:paramtypes", [Object]),
1251
1267
  __metadata("design:returntype", Promise)
1252
1268
  ], OperatorController.prototype, "chatSend", null);
1269
+ __decorate([
1270
+ Post('chat/:id/rewind'),
1271
+ __param(0, Param('id')),
1272
+ __param(1, Body()),
1273
+ __metadata("design:type", Function),
1274
+ __metadata("design:paramtypes", [String, Object]),
1275
+ __metadata("design:returntype", Promise)
1276
+ ], OperatorController.prototype, "chatRewind", null);
1253
1277
  __decorate([
1254
1278
  Get('sessions/:id/repo/tree'),
1255
1279
  __param(0, Param('id')),
@@ -48,6 +48,7 @@ function sameFolder(a, b) {
48
48
  import { composeLevel2, composePrompt, importPlan, personaBlock, plannedSessionSignature, taskSignature } from '../plan/importPlan.js';
49
49
  import { checkChanges, kerriganReport } from '../plan/changes.js';
50
50
  import { workspaceFile, workspaceFiles, workspaceInfo } from '../session/workspace.js';
51
+ import { restoreCheckpoint } from '../session/checkpoint.js';
51
52
  import { readInterruption } from '../session/interruption.js';
52
53
  import { baseRefOf, branchAt, commitInterrupted, nextAttemptBranch, repoDirOf, trackedRepoOf, vcsPreflight, restorePoint, restorePreview, restoreToBase, revertTaskWork, undoThisPreview, sessionBranches, sessionBranchName } from '../vcs/taskVcs.js';
53
54
  import { branchExists, changedFilesBetween, commitsBetween, fileAt, freeBranchName, git, gitAvailable, localBranches, looksLikeRepo, plannedBranchName, repoUnusableReason } from '../vcs/git.js';
@@ -81,6 +82,7 @@ import { resolveDesktopDir, desktopIsSynced } from '../context/desktopDir.js';
81
82
  import { saveAndReveal } from './saveToDesktop.js';
82
83
  import { settingsOf, SettingsUnusableError } from './settings.js';
83
84
  import { PolicyLockUnusableError } from '../config/lockedPolicy.js';
85
+ import { chatDenyPatterns } from '../config/schema.js';
84
86
  /** Why a session set aside on the Sessions page does not run: one sentence for every start that refuses it. */
85
87
  /** The id of the task a change names by id, number or title; see `plan/changes.ts`. */
86
88
  function checkTaskRef(session, ref) {
@@ -427,6 +429,7 @@ let OperatorService = class OperatorService {
427
429
  throw new Error('This session is running; its status can be changed once it has stopped.');
428
430
  }
429
431
  return await this.store.updateSession(id, (s) => {
432
+ const before = { model: s.model, manualModel: s.manualModel };
430
433
  if (patch.name !== undefined)
431
434
  s.name = patch.name.trim() || s.name;
432
435
  if (patch.active === true)
@@ -441,6 +444,16 @@ let OperatorService = class OperatorService {
441
444
  // Chosen on the session's page: the operator's own word, which outranks Settings.
442
445
  s.modelSource = s.model ? 'operator' : undefined;
443
446
  }
447
+ if (typeof patch.manualModel === 'boolean') {
448
+ if (patch.manualModel)
449
+ s.manualModel = true;
450
+ else
451
+ delete s.manualModel;
452
+ }
453
+ // Another choice of model: what was set by hand in the conversation is not what is asked for any more.
454
+ if ((patch.model !== undefined || typeof patch.manualModel === 'boolean') && (s.model !== before.model || !!s.manualModel !== !!before.manualModel)) {
455
+ delete s.modelByHand;
456
+ }
444
457
  // The same for the group: clearing it gives this session its conversation back. It does
445
458
  // not move the conversation it is already in; that history is where it is.
446
459
  if (patch.conversationGroup !== undefined)
@@ -1301,7 +1314,9 @@ let OperatorService = class OperatorService {
1301
1314
  const queuedIds = queuedToRun(session, onlyTasks).map((t) => t.id);
1302
1315
  if (queuedIds.length === 0)
1303
1316
  return { started: false, reason: 'no queued tasks', done: Promise.resolve(idle) };
1304
- const cfg = await this.settings.load();
1317
+ const loaded = await this.settings.load();
1318
+ // A chat conversation's git is the operator's: switching branches and committing are allowed there (2026-10-17).
1319
+ const cfg = session.kind === 'chat' ? { ...loaded, execution: { ...loaded.execution, denyPatterns: chatDenyPatterns(loaded.execution.denyPatterns) } } : loaded;
1305
1320
  const policy = {
1306
1321
  mode,
1307
1322
  denyPatterns: cfg.execution.denyPatterns,
@@ -1475,8 +1490,9 @@ let OperatorService = class OperatorService {
1475
1490
  await this.store.updateSession(sessionId, (s) => {
1476
1491
  s.status = 'stopping';
1477
1492
  });
1478
- // The running step is cut off, not waited for: said as it is (live run 2026-10-03).
1479
- this.bus.publish({ sessionId, type: 'stop-requested', level: 'warn', message: 'stopping now: nothing more is sent, and a step still running is cut off' });
1493
+ // The running step is cut off, not waited for: said as it is (live run 2026-10-03). An answer the chat is writing
1494
+ // is waited for, so the conversation is left whole; the choice of model and the sign-in end at once (2026-10-17).
1495
+ this.bus.publish({ sessionId, type: 'stop-requested', level: 'warn', message: 'stopping now: nothing more is sent, a step still running is cut off, and an answer Copilot is writing is waited for first' });
1480
1496
  return { stopping: true };
1481
1497
  }
1482
1498
  // --- running several sessions in turn -------------------------------------------------
@@ -2302,18 +2318,20 @@ let OperatorService = class OperatorService {
2302
2318
  s.onFailure = 'continue';
2303
2319
  s.review = { enabled: false, model: '' };
2304
2320
  s.planMode = 'off';
2305
- s.vcs = ws.isRepo
2306
- ? {
2307
- ...(s.vcs ?? DEFAULT_VCS),
2308
- enabled: true,
2309
- repoDir: ws.dir,
2310
- branchMode: 'per-session',
2311
- // The operator's own uncommitted work is normal in an open folder: taken along as the conversation's
2312
- // starting snapshot, once they approve it, rather than refusing the first message.
2313
- dirtyWorktree: { policy: 'snapshot' },
2314
- }
2315
- : { ...(s.vcs ?? DEFAULT_VCS), enabled: false, repoDir: '' };
2321
+ /*
2322
+ * No version control of the bot's own (2026-10-17): no branch, no commit, no question about where the work
2323
+ * starts. The chat works on the branch the folder is on, with what is in it, as an IDE's chat does; each
2324
+ * message is photographed before it runs instead, so the operator can go back to before it.
2325
+ */
2326
+ s.vcs = { ...(s.vcs ?? DEFAULT_VCS), enabled: false, repoDir: '' };
2316
2327
  s.projectDir = ws.dir;
2328
+ // The model chosen in the chat for this conversation: the operator's word, which outranks Settings.
2329
+ if (input.manualModel)
2330
+ s.manualModel = true;
2331
+ else if (input.model?.trim()) {
2332
+ s.model = input.model.trim();
2333
+ s.modelSource = 'operator';
2334
+ }
2317
2335
  });
2318
2336
  this.bus.publish({ sessionId: session.id, type: 'chat-started', level: 'info', message: `a conversation in ${ws.dir}` });
2319
2337
  }
@@ -2322,8 +2340,63 @@ let OperatorService = class OperatorService {
2322
2340
  level2: '',
2323
2341
  prompt: text,
2324
2342
  });
2325
- const fresh = (await this.store.getSession(session.id));
2326
- return { threadId: fresh.id, taskId: task.id, needsStart: !fresh.vcsStart && !fresh.tasks.some((t) => t.startedAt) };
2343
+ // After going back, the conversation is told with this message: it still holds what was undone.
2344
+ const pending = (await this.store.getSession(session.id))?.rewindNote;
2345
+ if (pending) {
2346
+ await this.store.addTaskNote(session.id, task.id, pending);
2347
+ await this.store.updateSession(session.id, (s) => {
2348
+ s.rewindNote = undefined;
2349
+ });
2350
+ }
2351
+ return { threadId: session.id, taskId: task.id, needsStart: false };
2352
+ }
2353
+ /**
2354
+ * Back to before a message of the chat (2026-10-17): the folder put back exactly as it was just before that
2355
+ * message ran — branch, commit, uncommitted changes — and that message and every one after it taken out of the
2356
+ * conversation, because they did not happen. They stay on the record (`Session.rewound`), and the folder as it
2357
+ * was before going back is kept as a safety photograph. The Copilot conversation still holds them, so its next
2358
+ * message says what was undone. See `session/checkpoint.ts`.
2359
+ */
2360
+ async chatRewind(threadId, taskId) {
2361
+ await this.init();
2362
+ const session = await this.store.getSession(threadId);
2363
+ if (!session || session.kind !== 'chat')
2364
+ return { ok: false, problem: 'That conversation is not there any more.' };
2365
+ if (this.running.has(threadId) || session.status !== 'idle')
2366
+ return { ok: false, problem: 'The conversation is working. Stop it first, then go back.' };
2367
+ const at = session.tasks.findIndex((t) => t.id === taskId);
2368
+ if (at < 0)
2369
+ return { ok: false, problem: 'That message is not in the conversation.' };
2370
+ const task = session.tasks[at];
2371
+ // A message that never ran changed nothing: it is only taken out, with the ones after it.
2372
+ const firstRan = session.tasks.slice(at).find((t) => t.checkpoint);
2373
+ const dir = session.projectDir?.trim() || '';
2374
+ let safety;
2375
+ if (firstRan?.checkpoint) {
2376
+ const other = await this.runningIn(dir);
2377
+ if (other)
2378
+ return { ok: false, problem: `Session "${other.name}" is running in this folder. Stop it first.` };
2379
+ const done = await restoreCheckpoint(dir, firstRan.checkpoint);
2380
+ if (!done.ok)
2381
+ return { ok: false, problem: done.problem };
2382
+ safety = done.safety;
2383
+ }
2384
+ const removed = session.tasks.slice(at);
2385
+ const titles = removed.map((t) => `"${t.title}"`).join(', ');
2386
+ await this.store.updateSession(threadId, (s) => {
2387
+ s.tasks = s.tasks.slice(0, at);
2388
+ s.rewound = [...(s.rewound ?? []), { at: new Date().toISOString(), toBefore: taskId, safety: safety ?? '', tasks: removed }];
2389
+ s.rewindNote =
2390
+ `The operator went back to before the message "${task.title}": the folder is again exactly as it was then` +
2391
+ `${firstRan?.checkpoint ? ` (on ${firstRan.checkpoint.branch || 'commit ' + firstRan.checkpoint.head.slice(0, 8)})` : ''}, and that message and the ` +
2392
+ `${removed.length > 1 ? `${removed.length - 1} after it were` : 'ones after it were'} undone (${titles}). Forget what was done for them; ` +
2393
+ 'work from the folder as it is now.';
2394
+ });
2395
+ const message = `went back to before "${task.title}": ${removed.length} message(s) taken out${safety ? `, the folder as it was is kept as ${safety.slice(0, 8)}` : ''}`;
2396
+ const cfg = await this.settings.load();
2397
+ await appendSessionLog(cfg.resolved.runsDir, threadId, { type: 'chat-rewind', message, data: { taskId, removed: removed.map((t) => t.id), safety } }).catch(() => undefined);
2398
+ this.bus.publish({ sessionId: threadId, type: 'chat-rewind', level: 'info', message, data: { taskId, removed: removed.length, safety } });
2399
+ return { ok: true, message, text: task.prompt, ...(safety ? { safety } : {}) };
2327
2400
  }
2328
2401
  // --- the repository, read-only, for the workbench (2026-10-14) ------------------------------
2329
2402
  /**
@@ -111,14 +111,16 @@ export async function startApi(opts = {}) {
111
111
  /*
112
112
  * A page whose name is also a folder of pages: `/sessions` is `sessions.html`, and `sessions/` holds
113
113
  * `view.html` (2026-10-14, when the list moved there). The static server finds the folder first and
114
- * redirects to it, where there is no page; the page is served instead.
114
+ * redirects to it, where there is no page; the page is served instead. Named from the interface's own
115
+ * folder: a whole path is refused (404) when any folder in it starts with a dot, as one under
116
+ * `.claude\worktrees` or pnpm's `node_modules\.pnpm` does (2026-10-17).
115
117
  */
116
118
  const root = webDir;
117
119
  app.use((req, res, next) => {
118
120
  if ((req.method === 'GET' || req.method === 'HEAD') && /^\/[a-z0-9-]+$/i.test(req.path)) {
119
- const page = join(root, `${req.path.slice(1)}.html`);
120
- if (existsSync(page) && existsSync(join(root, req.path.slice(1)))) {
121
- res.sendFile(page);
121
+ const name = req.path.slice(1);
122
+ if (existsSync(join(root, `${name}.html`)) && existsSync(join(root, name))) {
123
+ res.sendFile(`${name}.html`, { root });
122
124
  return;
123
125
  }
124
126
  }
@@ -70,6 +70,24 @@ const GIT_SOMETIMES_WRITES = 'remote\\s+(?:add|remove|rm|rename|set-url|set-head
70
70
  'config\\s+(?:set|unset|rename-section|remove-section|edit)\\b|' +
71
71
  'reflog\\s+(?:delete|expire)|' +
72
72
  'notes\\s+(?:add|append|edit|remove|copy|prune)';
73
+ /** The two default patterns that refuse git writes, as they stand in `execution.denyPatterns`. */
74
+ export const GIT_WRITE_DENY = [
75
+ `\\bgit\\s+(?:${GIT_GLOBAL_OPTION}\\s+)*(?:${GIT_ALWAYS_WRITES})(?![\\w-])`,
76
+ `\\bgit\\s+(?:${GIT_GLOBAL_OPTION}\\s+)*(?:${GIT_SOMETIMES_WRITES})`,
77
+ ];
78
+ /**
79
+ * In the workbench's chat the git is the operator's (2026-10-17: "the program works on the branch I left; I may
80
+ * ask the bot to change it"): switching or making a branch, committing, staging, stashing, pulling and merging
81
+ * are theirs to ask for. Still refused there: what reaches the remote, rewrites history or throws work away —
82
+ * push, reset, rebase, clean, history filters, low-level ref and object surgery — and the settings ones.
83
+ */
84
+ const GIT_CHAT_WRITES = 'push|reset|rebase|clean|filter-branch|filter-repo|update-ref|update-index|gc|prune|repack|worktree|' +
85
+ 'submodule|init|clone|checkout-index|commit-tree|read-tree|prune-packed|update-server-info';
86
+ export function chatDenyPatterns(patterns) {
87
+ const [always] = GIT_WRITE_DENY;
88
+ // Only the default pattern is narrowed: a list the operator wrote themselves is kept as they wrote it.
89
+ return patterns.map((p) => (p === always ? `\\bgit\\s+(?:${GIT_GLOBAL_OPTION}\\s+)*(?:${GIT_CHAT_WRITES})(?![\\w-])` : p));
90
+ }
73
91
  export const RunConfigSchema = z.object({
74
92
  copilot: z
75
93
  .object({
@@ -101,8 +119,10 @@ export const RunConfigSchema = z.object({
101
119
  * Choose the model by hand (operator's workaround, 2026-10-06): at the start of a run, and of a review's
102
120
  * conversation, the runner does not touch the picker; a card in the UI asks the operator to choose the
103
121
  * model in the Copilot window and press "Ready". A conversation already on the model is not asked about.
122
+ * On by default since 2026-10-17 (operator: "leave the automatic choice for now; make it work with the
123
+ * user choosing it by hand, and test the bot itself"); off, the runner chooses the model itself.
104
124
  */
105
- manualModel: z.boolean().default(false),
125
+ manualModel: z.boolean().default(true),
106
126
  replyTimeoutSec: z.number().int().positive().default(900),
107
127
  signInTimeoutSec: z.number().int().positive().default(900),
108
128
  humanWaitSec: z.number().int().positive().default(900),
@@ -13,7 +13,7 @@
13
13
  import { createHash } from 'node:crypto';
14
14
  import { readFile, mkdir, writeFile, appendFile } from 'node:fs/promises';
15
15
  import { join, resolve } from 'node:path';
16
- import { buttonShows } from '../transport/modelMatch.js';
16
+ import { buttonShows, normModel } from '../transport/modelMatch.js';
17
17
  import { createTransport, isReplyTimeout } from '../transport/chatTransport.js';
18
18
  import { buildChatName, chatCode, loadPointer, savePointer } from '../transport/chatSession.js';
19
19
  import { parseReply, formatErrorMessage, findLikelyDamage, damageGuidance } from '../protocol/parser.js';
@@ -40,13 +40,14 @@ import { writeReport } from '../exec/reportFile.js';
40
40
  import { Pacer } from '../util/pacing.js';
41
41
  import { RunLog } from '../log/runLog.js';
42
42
  import { composeOpening, operatorNotesSection, readOnlyNote } from '../session/compose.js';
43
+ import { takeAfter, takeCheckpoint } from '../session/checkpoint.js';
43
44
  import { MIN_TRIED_APPROACHES } from '../protocol/replySchema.js';
44
45
  import { enforceScope, scopeMessage, scopeNote } from '../vcs/scope.js';
45
46
  import { PLAN_FIRST, PLAN_NOT_NOW, PLAN_NUDGE_AFTER, describePlan, planApprovedMessage, planFrom, planModeNote, planNudge, planReviseMessage } from './planMode.js';
46
47
  import { composeHandoff } from '../session/handoff.js';
47
48
  import { ProgressWatch } from './progress.js';
48
49
  import { contractConflicts, readsTreeClean } from './contract.js';
49
- import { treeFingerprint } from '../vcs/git.js';
50
+ import { commitFiles, treeFingerprint } from '../vcs/git.js';
50
51
  import { isContinuable } from '../session/model.js';
51
52
  import { prepareForTask, commitTaskResult, commitShortfall, repoDirOf, trackedRepoOf, whereLeft } from '../vcs/taskVcs.js';
52
53
  import { protectInputs, inputsMessage, inputsAtCommit, untrackedInputs, blobOfFile } from '../vcs/inputs.js';
@@ -312,7 +313,9 @@ export function speakFor(transport, sessionId) {
312
313
  if (speaker)
313
314
  speaker.id = sessionId;
314
315
  }
315
- export async function openBrowser(cfg, bus, transportDir, sessionId) {
316
+ export async function openBrowser(cfg, bus, transportDir, sessionId,
317
+ /** The run's Stop: a sign-in still awaited ends with it. */
318
+ signal) {
316
319
  const speaker = { id: sessionId };
317
320
  const transport = createTransport({
318
321
  profileDir: cfg.resolved.profileDir,
@@ -357,7 +360,7 @@ export async function openBrowser(cfg, bus, transportDir, sessionId) {
357
360
  */
358
361
  try {
359
362
  await transport.open();
360
- await transport.ensureSignedIn();
363
+ await transport.ensureSignedIn(undefined, { signal });
361
364
  }
362
365
  catch (e) {
363
366
  await transport.close().catch(() => undefined);
@@ -499,8 +502,8 @@ async function joinGroupConversation(store, session, bus) {
499
502
  return updated;
500
503
  }
501
504
  /** The old shape, kept for the terminal path: open a browser and enter the conversation. */
502
- export async function openSessionTransport(cfg, session, bus, runsDir) {
503
- const transport = await openBrowser(cfg, bus, join(runsDir, '_browser'), session.id);
505
+ export async function openSessionTransport(cfg, session, bus, runsDir, signal) {
506
+ const transport = await openBrowser(cfg, bus, join(runsDir, '_browser'), session.id, signal);
504
507
  await enterSessionConversation(transport, session, { closeOnFailure: true });
505
508
  return transport;
506
509
  }
@@ -528,14 +531,32 @@ export async function openSessionTransport(cfg, session, bus, runsDir) {
528
531
  */
529
532
  export function effectiveModels(session, cfg) {
530
533
  const pick = (own, source, settings) => own && source === 'operator' ? [own, 'session'] : settings ? [settings, 'settings'] : own ? [own, 'plan'] : ['', 'none'];
531
- const [model, modelFrom] = pick((session.model ?? '').trim(), session.modelSource, (cfg.copilot.defaultModel ?? '').trim());
534
+ // Set by hand in the Copilot window: no name is asked for, neither the session's nor the one in Settings.
535
+ const [model, modelFrom] = session.manualModel ? ['', 'none'] : pick((session.model ?? '').trim(), session.modelSource, (cfg.copilot.defaultModel ?? '').trim());
532
536
  const [reviewModel, reviewModelFrom] = pick((session.review?.model ?? '').trim(), session.reviewModelSource, (cfg.copilot.defaultReviewModel ?? '').trim());
533
537
  return { model, reviewModel, modelFrom, reviewModelFrom };
534
538
  }
535
- async function applySessionModel(transport, session, bus, cfg, store, hooks) {
539
+ /**
540
+ * Whether the model of this session's conversation is chosen by hand in the Copilot window: Settings say so for
541
+ * every run, the session says so ("Set the model by hand" in the chat's picker), or it is a chat that names no
542
+ * model and has none from Settings either — its picker shows "by hand" for that, and what it shows is what happens.
543
+ */
544
+ export function modelByHand(session, cfg) {
545
+ if (cfg.copilot.manualModel || session.manualModel)
546
+ return true;
547
+ return session.kind === 'chat' && !effectiveModels(session, cfg).model;
548
+ }
549
+ async function applySessionModel(transport, session, bus, cfg, store, hooks,
550
+ /** Whether the conversation was opened new for this run, rather than one the session already had. */
551
+ fresh = true,
552
+ /** The run's Stop: the picker's waits end with it, and nothing is sent. */
553
+ signal) {
554
+ const stopped = { refused: 'Stopped by the operator while the model was being chosen. Nothing was sent; the tasks stay queued.' };
555
+ if (signal?.aborted)
556
+ return stopped;
536
557
  const { model: wanted, modelFrom } = effectiveModels(session, cfg);
537
558
  const fromSettings = modelFrom === 'settings';
538
- const manual = !!cfg.copilot.manualModel && !!hooks?.askHelp;
559
+ const manual = modelByHand(session, cfg) && !!hooks?.askHelp;
539
560
  if (!wanted && !manual)
540
561
  return {};
541
562
  let result;
@@ -545,18 +566,42 @@ async function applySessionModel(transport, session, bus, cfg, store, hooks) {
545
566
  * on the model — the chat keeps its model — is not asked about; otherwise the card asks for it.
546
567
  */
547
568
  const shown = await transport.currentModel().catch(() => null);
569
+ /*
570
+ * The conversation is "on the model" when the operator set it by hand in it before, for the same name or for
571
+ * none: asked once, at its first run, not at every one (2026-10-17) — the picker button's text could not be
572
+ * relied on at work to say so. A new conversation is asked again, and so is another name asked for.
573
+ */
574
+ const setBefore = session.modelByHand;
575
+ if (!fresh && setBefore && normModel(setBefore.asked ?? '') === normModel(wanted)) {
576
+ bus.publish({ sessionId: session.id, type: 'model-kept-by-hand', level: 'info',
577
+ message: `model: set by hand in this conversation (the picker shows "${shown ?? 'nothing'}"); not asked again`,
578
+ data: { shown, setAt: setBefore.at, shownThen: setBefore.shown, asked: wanted } });
579
+ await store?.updateSession(session.id, (s) => { s.modelInUse = shown ?? undefined; }).catch(() => undefined);
580
+ return { current: shown ?? undefined };
581
+ }
582
+ const why = cfg.copilot.manualModel ? 'Settings ask for the model to be chosen by hand' : 'the session asks for the model to be set by hand';
548
583
  const hand = wanted && buttonShows(shown, wanted)
549
584
  ? { result: { ok: true, current: wanted, by: 'already' }, goOnAsItIs: false }
550
- : await withOperatorHand(transport, wanted, { ok: false, current: shown, reason: 'Settings ask for the model to be chosen by hand' }, hooks, session.id, bus, true);
585
+ : await withOperatorHand(transport, wanted, { ok: false, current: shown, reason: why }, hooks, session.id, bus, true);
551
586
  if (!wanted) {
552
587
  const now = await transport.currentModel().catch(() => null);
553
588
  if (hand.result.ok || hand.goOnAsItIs) {
554
- await store?.updateSession(session.id, (s) => { s.modelInUse = now ?? undefined; }).catch(() => undefined);
589
+ await store
590
+ ?.updateSession(session.id, (s) => {
591
+ s.modelInUse = now ?? undefined;
592
+ s.modelByHand = { at: new Date().toISOString(), shown: now };
593
+ })
594
+ .catch(() => undefined);
555
595
  return { current: now ?? undefined };
556
596
  }
557
597
  return { refused: 'The model was to be chosen by hand, and the operator stopped the run. Nothing was sent.' };
558
598
  }
559
599
  result = hand.result;
600
+ // Set by hand in this conversation: the next run that comes back to it is not asked again.
601
+ if (result.ok || hand.goOnAsItIs) {
602
+ const now = await transport.currentModel().catch(() => null);
603
+ await store?.updateSession(session.id, (s) => { s.modelByHand = { at: new Date().toISOString(), shown: now, asked: wanted }; }).catch(() => undefined);
604
+ }
560
605
  if (hand.goOnAsItIs) {
561
606
  bus.publish({ sessionId: session.id, type: 'model-selected', level: 'warn', message: `model: ${result.current ?? 'unknown'} (chosen by hand; not "${wanted}")`, data: { asked: wanted, current: result.current, ok: false, by: 'hand' } });
562
607
  return { current: result.current ?? undefined };
@@ -564,11 +609,16 @@ async function applySessionModel(transport, session, bus, cfg, store, hooks) {
564
609
  }
565
610
  else {
566
611
  const locator = await hooks?.locate?.(wanted).catch(() => undefined);
567
- result = await transport.selectModel(wanted, { locator }).catch((e) => ({
612
+ result = await transport.selectModel(wanted, { locator, signal }).catch((e) => ({
568
613
  ok: false,
569
614
  current: null,
570
615
  reason: e.message,
571
616
  }));
617
+ // Not put to the operator on a card: they asked for the run to stop.
618
+ if (signal?.aborted) {
619
+ bus.publish({ sessionId: session.id, type: 'model-not-selected', level: 'info', message: `stopped by the operator while "${wanted}" was being chosen; nothing was sent`, data: { asked: wanted, stopped: true } });
620
+ return stopped;
621
+ }
572
622
  }
573
623
  const hand = await withOperatorHand(transport, wanted, result, hooks, session.id, bus, false);
574
624
  result = hand.result;
@@ -651,6 +701,19 @@ async function withOperatorHand(transport, wanted, first, hooks, sessionId, bus,
651
701
  }
652
702
  return { result, goOnAsItIs: false };
653
703
  }
704
+ /**
705
+ * What a chat message is told about the folder (2026-10-17): it works on the operator's own branch, nothing is
706
+ * committed for it, and git is the operator's to ask for — unlike a task of the bot's sessions, where the runner
707
+ * owns the repository.
708
+ */
709
+ const CHAT_NOTE = [
710
+ '## Working in the operator\'s folder',
711
+ '',
712
+ 'This is the operator\'s chat in their own folder, on the branch it is on. Nothing is branched or committed for',
713
+ 'you, and the rule against git commands that change something does not hold here: when the operator asks, you',
714
+ 'may switch or create a branch, stage, commit, stash, pull or merge. Never push, reset, rebase or clean, and',
715
+ 'never rewrite history; the runner refuses those. The operator can put the folder back to before any message.',
716
+ ].join('\n');
654
717
  /** Runs one task to completion inside an already-open transport. */
655
718
  /** The approved plan a task works to: its own attempt's, else, for a continuation, the latest one before it. */
656
719
  function approvedPlanOf(task) {
@@ -889,11 +952,28 @@ export async function runTask(transport, session, task, deps) {
889
952
  }
890
953
  return check;
891
954
  };
955
+ /** A chat message's checkpoint and folder (2026-10-17), set where the task starts; read by `finish`. */
956
+ let chatCheckpoint = session.kind === 'chat' ? task.checkpoint : undefined;
957
+ const chatDir = session.kind === 'chat' ? session.projectDir?.trim() ?? '' : '';
892
958
  const finish = async (status, reason, summary, finalReply) => {
893
959
  // How it ended as reported; the runner's own checks below can still change it, and the final word is written at the end.
894
960
  await record(`ENDING: ${status.toUpperCase()}`, [summary ?? '', reason ? `Reason: ${reason}` : ''].filter(Boolean).join('\n\n') || '(no details)');
895
961
  // The net under the plan's own checks: whatever the task left running is stopped and named.
896
962
  await reap(processesBefore, 'the task');
963
+ /*
964
+ * A chat message: the folder photographed again after it, on top of its checkpoint, so what it changed is
965
+ * one commit's worth of files, shown under the message and in the changes view. Nothing is committed on the
966
+ * operator's branch.
967
+ */
968
+ if (chatCheckpoint && chatDir) {
969
+ const after = await takeAfter(chatDir, task.id, chatCheckpoint).catch((e) => ({ problem: e.message }));
970
+ if (!('problem' in after)) {
971
+ const files = await commitFiles(chatDir, after.commit).catch(() => []);
972
+ await setTask((t) => {
973
+ t.vcs = { baseCommit: chatCheckpoint.commit, commit: after.commit, files };
974
+ });
975
+ }
976
+ }
897
977
  /*
898
978
  * The operator's input files, once more before the commit: put back what the last round changed,
899
979
  * so it is not committed as the task's work. One that cannot be put back fails a done task. See
@@ -1139,6 +1219,23 @@ export async function runTask(transport, session, task, deps) {
1139
1219
  t.reviewChecks = reviewChecks;
1140
1220
  });
1141
1221
  sink.event('task-started', { runId, title: task.title }, `task "${task.title}" starting (run ${runId})`);
1222
+ /*
1223
+ * A chat message: the folder photographed before it first runs, so the operator can go back to before it
1224
+ * (2026-10-17). Kept from the first attempt: a message carried on goes back to where it began.
1225
+ */
1226
+ if (session.kind === 'chat' && !chatCheckpoint && chatDir) {
1227
+ const cp = await takeCheckpoint(chatDir, task.id).catch((e) => ({ problem: e.message }));
1228
+ if ('problem' in cp) {
1229
+ sink.event('chat-checkpoint-missing', { problem: cp.problem }, `no way back to before this message: ${cp.problem}`, 'warn');
1230
+ }
1231
+ else {
1232
+ chatCheckpoint = cp;
1233
+ await setTask((t) => {
1234
+ t.checkpoint = cp;
1235
+ });
1236
+ sink.event('chat-checkpoint', { commit: cp.commit, branch: cp.branch, head: cp.head }, `the folder before this message is kept as ${cp.commit.slice(0, 8)} (on ${cp.branch || cp.head.slice(0, 8)})`);
1237
+ }
1238
+ }
1142
1239
  {
1143
1240
  const sel = (await store.getSession(session.id))?.modelSelection;
1144
1241
  if (sel) {
@@ -1385,7 +1482,7 @@ export async function runTask(transport, session, task, deps) {
1385
1482
  * record would go on naming the model the session asked for. Applied again here, as the
1386
1483
  * fresh-chat retry in `runSession` does for the same reason.
1387
1484
  */
1388
- const modelNow = await applySessionModel(transport, session, bus, cfg, store, deps.models);
1485
+ const modelNow = await applySessionModel(transport, session, bus, cfg, store, deps.models, !chat, deps.signal);
1389
1486
  if (effectiveModels(session, cfg).model) {
1390
1487
  await store.updateSession(session.id, (s) => {
1391
1488
  s.modelInUse = modelNow.current;
@@ -1416,7 +1513,7 @@ export async function runTask(transport, session, task, deps) {
1416
1513
  // The operator's new prompt goes out whether or not the attempt it follows reached a conversation.
1417
1514
  ...(task.continuing?.instruction ? { instruction: { text: task.continuing.instruction, fromAttempt: task.continuing.fromAttempt, ended: task.continuing.ended } } : {}),
1418
1515
  workDirNote: workingDirNote(work),
1419
- vcsNote: prepared.note,
1516
+ vcsNote: session.kind === 'chat' ? CHAT_NOTE : prepared.note,
1420
1517
  // What is said about a commit is true only where one happens (live run 2026-10-03: promised with commits off).
1421
1518
  readOnlyNote: task.readOnly ? readOnlyNote(!!(session.vcs?.enabled && session.vcs.commitOnFinish !== false && trackedRepoOf(session)), artifactPatterns(session.vcs)) : undefined,
1422
1519
  scopeNote: [
@@ -1875,7 +1972,7 @@ export async function runTask(transport, session, task, deps) {
1875
1972
  }
1876
1973
  else {
1877
1974
  const reviewLocator = await deps.models?.locate?.(model).catch(() => undefined);
1878
- picked = await transport.selectModel(model, { locator: reviewLocator }).catch((e) => ({ ok: false, current: null, reason: e.message }));
1975
+ picked = await transport.selectModel(model, { locator: reviewLocator, signal }).catch((e) => ({ ok: false, current: null, reason: e.message }));
1879
1976
  }
1880
1977
  const renamed = await followPageModels('review', model, picked, session, store, deps.models, effectiveModels(session, cfg).reviewModelFrom);
1881
1978
  if (renamed)
@@ -2887,19 +2984,21 @@ export async function runSession(sessionId, deps) {
2887
2984
  }
2888
2985
  else {
2889
2986
  await deps.beforeBrowser?.();
2890
- transport = await openSessionTransport(cfg, session, bus, sessionRunsDir);
2987
+ transport = await openSessionTransport(cfg, session, bus, sessionRunsDir, deps.signal);
2891
2988
  }
2892
2989
  const chat = transport;
2893
2990
  // The picker belongs to the conversation, so the session's choice is applied once, here,
2894
- // before the first task goes out. What the chat ended up on is recorded either way.
2895
- const modelInUse = await applySessionModel(chat, session, bus, cfg, store, deps.models);
2991
+ // before the first task goes out. What the chat ended up on is recorded either way. A conversation
2992
+ // the session already had was reopened above; one it did not have was opened new.
2993
+ const modelInUse = await applySessionModel(chat, session, bus, cfg, store, deps.models, !session.chat, deps.signal);
2896
2994
  if (effectiveModels(session, cfg).model) {
2897
2995
  await store.updateSession(sessionId, (s) => {
2898
2996
  s.modelInUse = modelInUse.current;
2899
2997
  });
2900
2998
  }
2901
- // Refused before a task is marked started: its tasks stay queued, and the run says why.
2902
- if (modelInUse.refused)
2999
+ // Refused before a task is marked started: its tasks stay queued, and the run says why. Stopped, the loop
3000
+ // below ends before its first task.
3001
+ if (modelInUse.refused && !deps.signal?.aborted)
2903
3002
  throw new Error(modelInUse.refused);
2904
3003
  for (const queuedTask of queued) {
2905
3004
  if (deps.signal?.aborted)
@@ -3015,7 +3114,7 @@ export async function runSession(sessionId, deps) {
3015
3114
  * it was the model the session asked for. The review has always done this for its own
3016
3115
  * fresh conversations a few hundred lines up; this path simply never did.
3017
3116
  */
3018
- const freshModel = await applySessionModel(chat, session, bus, cfg, store, deps.models);
3117
+ const freshModel = await applySessionModel(chat, session, bus, cfg, store, deps.models, true, deps.signal);
3019
3118
  if (effectiveModels(session, cfg).model) {
3020
3119
  session = await store.updateSession(sessionId, (s) => {
3021
3120
  s.modelInUse = freshModel.current;
@@ -3079,8 +3178,17 @@ export async function runSession(sessionId, deps) {
3079
3178
  }
3080
3179
  }
3081
3180
  catch (e) {
3082
- bus.publish({ sessionId, type: 'session-error', level: 'error', message: e.message });
3083
- throw e;
3181
+ /*
3182
+ * Stopped while the browser was opening, the sign-in awaited or the model chosen: what the operator asked for,
3183
+ * not a failure. Said as a stop, and the tasks stay queued (2026-10-17).
3184
+ */
3185
+ if (deps.signal?.aborted && ran === 0) {
3186
+ bus.publish({ sessionId, type: 'session-stopped', level: 'info', message: `stopped by the operator before the first task was sent; the tasks stay queued (${e.message})` });
3187
+ }
3188
+ else {
3189
+ bus.publish({ sessionId, type: 'session-error', level: 'error', message: e.message });
3190
+ throw e;
3191
+ }
3084
3192
  }
3085
3193
  finally {
3086
3194
  // A borrowed window belongs to whoever opened it and stays open for the next session.
@@ -1273,6 +1273,30 @@ export const SYSTEM_GUIDE = [
1273
1273
  doesEn: 'The message: what to change or ask. Enter sends it, Shift+Enter starts a new line; while it works, what is written is added to what it is doing.',
1274
1274
  doesBg: 'Съобщението: какво да се промени или попита. Enter го изпраща, Shift+Enter започва нов ред; докато работи, написаното се добавя към това, което прави.',
1275
1275
  },
1276
+ {
1277
+ key: 'chat.model',
1278
+ kind: 'select',
1279
+ en: 'Model',
1280
+ bg: 'Модел',
1281
+ doesEn: 'The model of this conversation (or of the next one): "As in Settings" or one the chat\'s picker offered when last read; it is chosen in Copilot when the next message runs.',
1282
+ doesBg: 'Моделът на този разговор (или на следващия): „Както е в Настройки“ или някой, предложен от избора в чата при последното четене; избира се в Copilot, когато тръгне следващото съобщение.',
1283
+ },
1284
+ {
1285
+ key: 'chat.readModels',
1286
+ kind: 'button',
1287
+ en: 'Read the latest models from Copilot',
1288
+ bg: 'Прочети последните модели от Copilot',
1289
+ doesEn: 'The ↻ beside the model: reads the models Copilot\'s own picker offers now (the browser opens for a moment; not while a conversation works).',
1290
+ doesBg: '↻ до модела: прочита моделите, които изборът в Copilot предлага сега (браузърът се отваря за момент; не и докато разговор работи).',
1291
+ },
1292
+ {
1293
+ key: 'chat.rewind',
1294
+ kind: 'button',
1295
+ en: 'Go back to before this message',
1296
+ bg: 'Върни отпреди това съобщение',
1297
+ doesEn: 'The ↶ beside a message of yours: puts the folder back exactly as it was before that message — branch, files, uncommitted changes — and takes it and the messages after it out of the conversation; the folder as it was is kept in a safety copy, and the message goes back in the box.',
1298
+ doesBg: '↶ до твое съобщение: връща папката точно както беше преди него — клон, файлове, некомитнати промени — и маха него и следващите от разговора; папката, както е била, се пази като резервно копие, а съобщението се връща в полето.',
1299
+ },
1276
1300
  {
1277
1301
  key: 'chat.mode',
1278
1302
  kind: 'select',
@@ -1302,8 +1326,8 @@ export const SYSTEM_GUIDE = [
1302
1326
  kind: 'button',
1303
1327
  en: 'Send',
1304
1328
  bg: 'Изпрати',
1305
- doesEn: 'Sends the message: the first one of a conversation asks where the work starts (the start window), later ones go on where it is.',
1306
- doesBg: 'Изпраща съобщението: първото в разговора пита откъде да започне работата (прозорецът за начало), следващите продължават, където е.',
1329
+ doesEn: 'Sends the message and starts it on the branch the folder is on; nothing is asked about branches.',
1330
+ doesBg: 'Изпраща съобщението и го пуска на клона, на който е папката; нищо не се пита за клонове.',
1307
1331
  },
1308
1332
  {
1309
1333
  key: 'chat.sendNote',