@nathanstephenson/flow 0.1.10-beta.7 → 0.1.10-beta.9

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 (42) hide show
  1. package/build/backend-worker-chunks/{claude-THGSOTC2.mjs → claude-X57GT57M.mjs} +12 -4
  2. package/build/backend-worker-chunks/{pi-5LAWIJNE.mjs → pi-IZ3GX6HN.mjs} +5 -1
  3. package/build/backend-worker.mjs +7 -4
  4. package/dist/backend/claude/index.js +15 -4
  5. package/dist/backend/mcp.js +4 -1
  6. package/dist/backend/pi/index.js +6 -1
  7. package/dist/backend/worker/index.js +8 -3
  8. package/dist/build-id +1 -1
  9. package/dist/cli/bootstrap.js +1 -1
  10. package/dist/client/connection.js +46 -0
  11. package/dist/client/project-name.js +3 -1
  12. package/dist/client/reduce.js +1 -0
  13. package/dist/client/scope-kind.js +4 -0
  14. package/dist/daemon/changes.js +22 -12
  15. package/dist/daemon/git.js +10 -1
  16. package/dist/daemon/host.js +263 -47
  17. package/dist/daemon/pull-request.js +92 -34
  18. package/dist/daemon/repository.js +26 -9
  19. package/dist/daemon/runtime.js +2 -0
  20. package/dist/daemon/server.js +25 -0
  21. package/dist/daemon/stack.js +37 -3
  22. package/dist/daemon/tour.js +7 -1
  23. package/dist/daemon/workflow-environment.js +6 -4
  24. package/dist/daemon/workflow-executions.js +1 -1
  25. package/dist/isolation/filesystem.js +1 -1
  26. package/dist/protocol/spend.js +1 -1
  27. package/dist/protocol/stack.js +14 -1
  28. package/dist/workflows/executors.js +2 -1
  29. package/package.json +1 -1
  30. package/web/dist/assets/index-CHFNROUs.js +51 -0
  31. package/web/dist/assets/index-D9AneSPi.css +2 -0
  32. package/web/dist/assets/{select-C-BND5Jn.js → select-COVn-75j.js} +1 -1
  33. package/web/dist/assets/{settings-mcp-CBXZt_cf.js → settings-mcp-BHZwEeJF.js} +1 -1
  34. package/web/dist/assets/{settings-secrets-29ZG3w6p.js → settings-secrets-NGSRhEbU.js} +1 -1
  35. package/web/dist/assets/settings-workflows-uew3ONyO.js +23 -0
  36. package/web/dist/assets/{workflow-api-DkUjAZ4w.js → workflow-api-3z2Qqsmo.js} +1 -1
  37. package/web/dist/assets/{workflows-DdogjBu3.js → workflows-hcZXxss1.js} +14 -14
  38. package/web/dist/assets/{workflows-pane-B0dyuSuz.js → workflows-pane-DntY7Dcw.js} +1 -1
  39. package/web/dist/index.html +5 -5
  40. package/web/dist/assets/index-5E7qbtVD.js +0 -51
  41. package/web/dist/assets/index-BvkM2cWL.css +0 -2
  42. package/web/dist/assets/settings-workflows-CE11fxNj.js +0 -23
@@ -3,22 +3,24 @@ import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendI
3
3
  import { sessionToolSummary, sessionToolPage } from './session-tool-views.js';
4
4
  import { credentialKey } from './credential-redaction.js';
5
5
  import { randomUUID } from "node:crypto";
6
- import { copyFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
6
+ import { copyFileSync, existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
7
7
  import { isAbsolute, join, resolve } from "node:path";
8
8
  import { validateFilesystemScope } from "../isolation/filesystem.js";
9
- import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest, createPullRequest, editPullRequest, setPullRequestDraft, rerunPullRequestChecks, checkLog } from "./pull-request.js";
10
- import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
11
- import { changes, changesText, commitContext, diff } from "./changes.js";
9
+ import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest, createPullRequest, editPullRequest, setPullRequestDraft, rerunPullRequestChecks, checkLog, dropUnchangedBranch, fetchBranch, listPullRequests, projectPullRequest, projectTarget, pullRequestRange, remoteUrl, submitReview } from "./pull-request.js";
10
+ import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage, mergeableStack, stackMergeMethods } from "./stack.js";
11
+ import { changes, changesText, commitContext, diff, fileDiff, rangeChanges } from "./changes.js";
12
+ import { gh } from "./github.js";
13
+ import { resolveRepository } from "./repository.js";
12
14
  import { commit } from "./commit.js";
13
15
  import { push, pushState } from "./push.js";
14
16
  import { GitStates, readStatus } from "./git-state.js";
15
- import { TOUR_INSTRUCTIONS, TOUR_READ_TOOLS, tourInput, tourText } from "./tour.js";
17
+ import { TOUR_INSTRUCTIONS, TOUR_READ_TOOLS, pullRequestTourInput, tourInput, tourText } from "./tour.js";
16
18
  import { resolveDefaultBackend } from "../protocol/settings.js";
17
19
  import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
18
20
  import { deriveStatus, railGroupRank } from "../client/status.js";
19
21
  // `switchBranch` is aliased because this class has a method of that name: the method is the
20
22
  // Session Host's refusal-and-record wrapper, and the import is the git invocation it wraps.
21
- import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, updateSourceBranch, switchBranch as gitSwitchBranch, } from "./git.js";
23
+ import { addDetachedCheckout, createWorktree, refExists, removeDetachedCheckout, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, updateSourceBranch, switchBranch as gitSwitchBranch, } from "./git.js";
22
24
  import { SessionLog } from "./log.js";
23
25
  import { probeModels } from "./models.js";
24
26
  import { PiModelProbeCache } from "./pi-model-cache.js";
@@ -75,6 +77,7 @@ export class SessionHost {
75
77
  gitStates = new GitStates();
76
78
  closingScopes = new Set();
77
79
  tours = new Map();
80
+ pullRequestTours = new Map();
78
81
  refuseGitOperation(scope) {
79
82
  if (this.gitOperations.has(scopeKey(scope)))
80
83
  throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
@@ -115,7 +118,7 @@ export class SessionHost {
115
118
  }
116
119
  }
117
120
  async prepareStack(sessionId, action) {
118
- if (action !== "submit" && action !== "sync")
121
+ if (action !== "submit" && action !== "sync" && action !== "merge")
119
122
  throw new CommandRefused("Invalid Stack review action.");
120
123
  const record = this.record(sessionId);
121
124
  return this.withGitOperation(record.scope, async () => {
@@ -124,19 +127,28 @@ export class SessionHost {
124
127
  const status = await stackStatus(record.scope);
125
128
  if (!status.view)
126
129
  throw new Error(status.notice ?? "This branch is not in a stack.");
130
+ const fingerprint = await stackFingerprint(record.scope, status.view, action === "sync");
127
131
  const review = { token: randomUUID(), action, view: status.view };
128
- this.stackReviews.set(sessionId, { review, fingerprint: await stackFingerprint(record.scope, status.view, action === "sync"), expires: Date.now() + 15 * 60_000 });
132
+ if (action === "merge") {
133
+ review.view = await mergeableStack(record.scope);
134
+ review.mergeMethods = await stackMergeMethods(record.scope, review.view);
135
+ if (!review.mergeMethods.length)
136
+ throw new Error("You cannot merge pull requests in this repository.");
137
+ }
138
+ this.stackReviews.set(sessionId, { review, fingerprint, expires: Date.now() + 15 * 60_000 });
129
139
  return review;
130
140
  });
131
141
  }
132
142
  async changeStack(sessionId, input) {
133
143
  const record = this.record(sessionId);
134
144
  return this.withGitOperation(record.scope, async () => {
135
- if (input.action === "submit" || input.action === "sync") {
145
+ if (input.action === "submit" || input.action === "sync" || input.action === "merge") {
136
146
  const saved = this.stackReviews.get(sessionId);
137
147
  this.stackReviews.delete(sessionId);
138
148
  if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
139
149
  throw new Error("This Stack review expired. Review again.");
150
+ if (input.action === "merge" && !saved.review.mergeMethods?.includes(input.method))
151
+ throw new Error("This repository does not permit that merge method.");
140
152
  await cleanStack(record.scope);
141
153
  const status = await stackStatus(record.scope);
142
154
  if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
@@ -193,6 +205,42 @@ export class SessionHost {
193
205
  return status;
194
206
  });
195
207
  }
208
+ projectScope(project) {
209
+ if (typeof project !== "string" || !isRepository(project))
210
+ throw new CommandRefused(`${project} is not a git repository.`);
211
+ return project;
212
+ }
213
+ pullRequestPlace(target) {
214
+ if (target.project === undefined)
215
+ return { scope: this.record(target.sessionId).scope };
216
+ return { scope: this.projectScope(target.project), find: projectTarget };
217
+ }
218
+ /** Start an Agent Session in a Worktree on the head branch of a Pull Request, or focus the one already on it. */
219
+ async startPullRequestSession(project, ref) {
220
+ const scope = this.projectScope(project);
221
+ const pr = await this.readGit(() => projectTarget(scope, ref, gh));
222
+ const repository = await this.readGit(() => resolveRepository(scope, undefined, gh));
223
+ if (pr.state !== "OPEN")
224
+ throw new CommandRefused("This pull request is not open.");
225
+ if (pr.headRepository?.id !== repository.base.id)
226
+ throw new CommandRefused("This pull request comes from a fork. Flow can start an Agent Session only on a branch in the base repository.");
227
+ const existing = [...this.sessions.values()].find(record => record.lifecycle !== "ended" && scopeKey(record.worktree?.repo ?? record.scope) === scopeKey(scope) && !record.branch?.detached && record.branch?.name === pr.headRefName);
228
+ if (existing)
229
+ return existing.id;
230
+ if (await refExists(scope, pr.headRefName))
231
+ throw new CommandRefused(`The branch ${pr.headRefName} already exists in ${scope}. Start an Agent Session on it from the New Agent Session page.`);
232
+ const { remote } = await this.readGit(() => remoteUrl(scope, pr.repo));
233
+ if (!remote)
234
+ throw new CommandRefused(`No remote in ${scope} points to ${pr.repo}. Add one.`);
235
+ const fetched = await this.readGit(() => fetchBranch(scope, remote, pr.headRefName));
236
+ try {
237
+ return await this.create({ scope, worktree: { from: `${remote}/${pr.headRefName}`, branch: pr.headRefName } });
238
+ }
239
+ catch (error) {
240
+ await dropUnchangedBranch(scope, pr.headRefName, fetched);
241
+ throw error;
242
+ }
243
+ }
196
244
  gitScope(sessionId) {
197
245
  const scope = this.record(sessionId).scope;
198
246
  if (!isRepository(scope))
@@ -281,7 +329,7 @@ export class SessionHost {
281
329
  const session = record.session;
282
330
  if (!current())
283
331
  return;
284
- if (!session?.startWorkflowSubagent)
332
+ if (!session)
285
333
  throw new Error("This Backend Adapter cannot run a tour.");
286
334
  const log = record.log.since(0);
287
335
  const model = log.findLast(({ event }) => event.type === "model_changed")?.event;
@@ -290,22 +338,97 @@ export class SessionHost {
290
338
  const modelId = chosen?.modelId ?? (model?.type === "model_changed" ? model.model.id : record.modelId);
291
339
  if (!modelId)
292
340
  throw new Error("The Agent Session's model is unknown. Choose a Tour Model in Settings.");
293
- tour.handle = session.startWorkflowSubagent({
294
- id: tour.id, name: "Tour", instructions: TOUR_INSTRUCTIONS, input, modelId,
295
- effort: chosen?.effort ?? (effort?.type === "effort_changed" ? effort.effort : record.effort) ?? "off",
296
- permissionMode: "ask",
297
- emit: ({ event }) => {
298
- if (event.type === "permission" && event.state === "asked") {
299
- queueMicrotask(() => void tour.handle?.answerPermission(event.callId, TOUR_READ_TOOLS.includes(event.tool) ? "allow" : "deny").catch(() => undefined));
300
- }
301
- if (event.type === "enquiry" && event.state === "asked") {
302
- queueMicrotask(() => void tour.handle?.answerEnquiry(event.askId, event.questions.map(() => ["No human is available. Continue without an answer."])).catch(() => undefined));
303
- }
304
- if (event.type === "spend")
305
- this.workflowSpend(record.id, `tour:${tour.id}`, event.spend);
306
- },
341
+ const text = await this.writeTour(session, tour, input, modelId, chosen?.effort ?? (effort?.type === "effort_changed" ? effort.effort : record.effort) ?? "off", spend => this.workflowSpend(record.id, `tour:${tour.id}`, spend));
342
+ if (current())
343
+ tour.view = { state: "done", text, ...made };
344
+ }
345
+ catch (error) {
346
+ if (current())
347
+ tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
348
+ }
349
+ }
350
+ async writeTour(session, tour, input, modelId, effort, spent) {
351
+ if (!session.startWorkflowSubagent)
352
+ throw new Error("This Backend Adapter cannot run a tour.");
353
+ tour.handle = session.startWorkflowSubagent({
354
+ id: tour.id, name: "Tour", instructions: TOUR_INSTRUCTIONS, input, modelId, effort, permissionMode: "ask",
355
+ emit: ({ event }) => {
356
+ if (event.type === "permission" && event.state === "asked") {
357
+ queueMicrotask(() => void tour.handle?.answerPermission(event.callId, TOUR_READ_TOOLS.includes(event.tool) ? "allow" : "deny").catch(() => undefined));
358
+ }
359
+ if (event.type === "enquiry" && event.state === "asked") {
360
+ queueMicrotask(() => void tour.handle?.answerEnquiry(event.askId, event.questions.map(() => ["No human is available. Continue without an answer."])).catch(() => undefined));
361
+ }
362
+ if (event.type === "spend")
363
+ spent(event.spend);
364
+ },
365
+ });
366
+ return tourText(await tour.handle.done);
367
+ }
368
+ pullRequestTourKey(project, ref) {
369
+ return `${scopeKey(this.projectScope(project))}\0${ref?.repo}#${ref?.number}`;
370
+ }
371
+ pullRequestTour(project, ref) {
372
+ return this.pullRequestTours.get(this.pullRequestTourKey(project, ref))?.view ?? { state: "idle" };
373
+ }
374
+ startPullRequestTour(project, ref) {
375
+ const key = this.pullRequestTourKey(project, ref);
376
+ if (!this.store)
377
+ throw new CommandRefused("This Session Host keeps no state, so it cannot make a tour.");
378
+ this.dropPullRequestTour(key);
379
+ const tour = { id: randomUUID(), view: { state: "running" } };
380
+ this.pullRequestTours.set(key, tour);
381
+ tour.running = this.runPullRequestTour(project, ref, key, tour);
382
+ return tour.view;
383
+ }
384
+ cancelPullRequestTour(project, ref) {
385
+ this.dropPullRequestTour(this.pullRequestTourKey(project, ref));
386
+ return { state: "idle" };
387
+ }
388
+ dropPullRequestTour(key) {
389
+ const tour = this.pullRequestTours.get(key);
390
+ this.pullRequestTours.delete(key);
391
+ void tour?.handle?.cancel().catch(() => undefined);
392
+ }
393
+ /** A Tour with no Agent Session: a host Backend Session over a read-only checkout of the Pull Request head. */
394
+ async runPullRequestTour(project, ref, key, tour) {
395
+ const current = () => this.pullRequestTours.get(key) === tour;
396
+ let made;
397
+ let checkout;
398
+ let session;
399
+ try {
400
+ const range = await pullRequestRange(project, ref);
401
+ made = { branch: range.pr.headRefName, head: range.head, repo: range.pr.repo };
402
+ if (current())
403
+ tour.view = { state: "running", branch: made.branch, head: made.head };
404
+ const input = await pullRequestTourInput(project, range, { headRefName: range.pr.headRefName, baseRefName: range.pr.baseBranch });
405
+ const backendName = resolveDefaultBackend([...this.backends.keys()], this.defaultBackend?.());
406
+ if (backendName === undefined)
407
+ throw new Error("No backends available");
408
+ const chosen = this.tourModel?.(backendName);
409
+ const configured = chosen?.modelId ?? this.defaultModel?.(backendName);
410
+ let reported;
411
+ if (!current())
412
+ return;
413
+ checkout = join(this.store.worktreesRoot(), ".tours", tour.id);
414
+ const added = await addDetachedCheckout(project, range.head, checkout);
415
+ if (!added.ok) {
416
+ checkout = undefined;
417
+ throw new Error(added.failure.message);
418
+ }
419
+ if (!current())
420
+ return;
421
+ session = await this.backendFor(backendName).create({
422
+ scope: checkout, permissionMode: "ask", readOnly: this.readOnlyEnforcement(), ...(configured ? { modelId: configured } : {}),
423
+ emit: (event) => { if (event.type === "model_changed")
424
+ reported = event.model.id; },
307
425
  });
308
- const text = tourText(await tour.handle.done);
426
+ if (!current())
427
+ return;
428
+ const modelId = configured ?? reported;
429
+ if (!modelId)
430
+ throw new Error("The Default Backend reported no model. Choose a Tour Model in Settings.");
431
+ const text = await this.writeTour(session, tour, input, modelId, chosen?.effort ?? this.defaultEffort?.(backendName) ?? "off", spend => this.recordSpend("tour", tour.id, scopeKey(project), spend));
309
432
  if (current())
310
433
  tour.view = { state: "done", text, ...made };
311
434
  }
@@ -313,6 +436,14 @@ export class SessionHost {
313
436
  if (current())
314
437
  tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
315
438
  }
439
+ finally {
440
+ await session?.dispose().catch(() => undefined);
441
+ if (checkout)
442
+ await removeDetachedCheckout(project, checkout);
443
+ }
444
+ }
445
+ readOnlyEnforcement(isolationMode = this.filesystemIsolationMode()) {
446
+ return isolationMode === "bubblewrap" || (isolationMode === "sandbox" && this.sandboxSharing?.() !== "shared") ? "mounted" : "tools";
316
447
  }
317
448
  store;
318
449
  retention;
@@ -327,12 +458,15 @@ export class SessionHost {
327
458
  summaryModel;
328
459
  tourModel;
329
460
  closedListeners = new Set();
461
+ attentionListeners = new Set();
330
462
  backendFailures = new Set();
331
463
  keptListeners = new Set();
332
464
  filesystemIsolation;
333
465
  sandbox;
334
466
  sandboxSharing;
335
467
  updateSourceBranch;
468
+ projectRoot;
469
+ projectPaths;
336
470
  shared;
337
471
  mcpConnections;
338
472
  mcpAuth;
@@ -342,6 +476,8 @@ export class SessionHost {
342
476
  this.sandbox = options.sandboxSupport;
343
477
  this.sandboxSharing = options.sandboxSharing;
344
478
  this.updateSourceBranch = options.updateSourceBranch;
479
+ this.projectRoot = options.projectRoot;
480
+ this.projectPaths = options.projectPaths;
345
481
  this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
346
482
  this.mcpConnections = options.mcpConnections;
347
483
  this.mcpAuth = options.mcpAuth;
@@ -372,6 +508,10 @@ export class SessionHost {
372
508
  this.closedListeners.add(listener);
373
509
  return () => this.closedListeners.delete(listener);
374
510
  }
511
+ onAttentionRaised(listener) {
512
+ this.attentionListeners.add(listener);
513
+ return () => this.attentionListeners.delete(listener);
514
+ }
375
515
  announceClosed(sessionId) {
376
516
  for (const listener of this.closedListeners)
377
517
  listener(sessionId);
@@ -567,6 +707,9 @@ export class SessionHost {
567
707
  };
568
708
  if (reason !== "Input needed")
569
709
  record.latestOutcome = record.latestAttention;
710
+ for (const listener of this.attentionListeners) {
711
+ listener({ sessionId: record.id, title: record.title, reason, version, at });
712
+ }
570
713
  return { at, version };
571
714
  }
572
715
  /**
@@ -637,6 +780,7 @@ export class SessionHost {
637
780
  ...(record.branch ? { branch: record.branch } : {}),
638
781
  ...(git ? { git } : {}),
639
782
  ...(record.worktree ? { worktree: true } : {}),
783
+ ...(record.readOnly ? { readOnly: true } : {}),
640
784
  ...(record.session || existsSync(record.scope) ? {} : {
641
785
  scopeMissing: true,
642
786
  ...this.suggestion(record.scope),
@@ -666,6 +810,7 @@ export class SessionHost {
666
810
  async load() {
667
811
  if (!this.store)
668
812
  return;
813
+ rmSync(join(this.store.worktreesRoot(), ".tours"), { recursive: true, force: true });
669
814
  for (const id of await this.store.listSessionIds()) {
670
815
  const meta = this.store.readMeta(id);
671
816
  if (!meta || this.sessions.has(id))
@@ -712,6 +857,7 @@ export class SessionHost {
712
857
  branch: branchFrom(entries),
713
858
  branchGeneration: 0,
714
859
  worktree: meta.worktree,
860
+ ...(meta.readOnly ? { readOnly: true } : {}),
715
861
  ...(meta.scheduledOccurrenceId ? { scheduledOccurrenceId: meta.scheduledOccurrenceId } : {}),
716
862
  pendingBranchNote: undefined,
717
863
  capabilities: capabilitiesFrom(entries),
@@ -797,6 +943,13 @@ export class SessionHost {
797
943
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
798
944
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
799
945
  this.validatePermissionMode(backend.name, permissionMode);
946
+ if (options.readOnly) {
947
+ const root = this.projectRoot?.();
948
+ if (root === undefined || scopeKey(options.scope) !== scopeKey(root))
949
+ throw new CommandRefused("A Read-only Scope must be the Project Root.");
950
+ if (options.worktree)
951
+ throw new CommandRefused("A Read-only Scope cannot be a Worktree.");
952
+ }
800
953
  const cut = options.scheduled?.worktree || !options.worktree ? undefined : await this.cutWorktree(options.scope, options.worktree);
801
954
  const worktree = options.scheduled?.worktree ?? cut?.worktree;
802
955
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
@@ -839,6 +992,7 @@ export class SessionHost {
839
992
  branch: undefined,
840
993
  branchGeneration: 0,
841
994
  worktree,
995
+ ...(options.readOnly ? { readOnly: true } : {}),
842
996
  pendingBranchNote: undefined,
843
997
  capabilities: undefined,
844
998
  spend: undefined,
@@ -961,7 +1115,7 @@ export class SessionHost {
961
1115
  throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
962
1116
  if (!isRepository(repo))
963
1117
  throw new CommandRefused(`${repo} is not a git repository`);
964
- const updated = this.updateSourceBranch?.() ? await updateSourceBranch(repo, options.from) : undefined;
1118
+ const updated = this.updateSourceBranch?.() && await refExists(repo, options.from) ? await updateSourceBranch(repo, options.from) : undefined;
965
1119
  const created = await createWorktree({
966
1120
  repo,
967
1121
  from: options.from,
@@ -1012,6 +1166,8 @@ export class SessionHost {
1012
1166
  async relocate(sessionId, scope, repo) {
1013
1167
  const record = this.record(sessionId);
1014
1168
  const from = record.scope;
1169
+ if (record.readOnly)
1170
+ throw new CommandRefused("An Agent Session with a Read-only Scope cannot relocate.");
1015
1171
  if (record.session || record.reviving)
1016
1172
  throw new CommandRefused("This Agent Session is running. Only a stopped Agent Session can relocate.");
1017
1173
  if (existsSync(from))
@@ -1515,6 +1671,8 @@ export class SessionHost {
1515
1671
  throw new CommandRefused("Wait for the turn, the queued messages and the background work to finish, or abort them, before rewinding");
1516
1672
  }
1517
1673
  const files = restore !== "conversation";
1674
+ if (files && record.readOnly)
1675
+ throw new CommandRefused("This Agent Session has a Read-only Scope. Rewind only its conversation.");
1518
1676
  const conversation = restore !== "files";
1519
1677
  if (conversation && !session.capabilities.rewind)
1520
1678
  throw new CommandRefused(`${record.backendName} cannot rewind a Conversation Context`);
@@ -1568,6 +1726,7 @@ export class SessionHost {
1568
1726
  permissionMode: source.permissionMode,
1569
1727
  mcpConnectionIds: source.mcpConnectionIds ?? [],
1570
1728
  ...(worktree === undefined ? {} : { worktree }),
1729
+ ...(source.readOnly ? { readOnly: true } : {}),
1571
1730
  fork: { source, userMessageId, prefix: events.filter((entry) => entry.seq < at.seq) },
1572
1731
  });
1573
1732
  }
@@ -2293,6 +2452,8 @@ export class SessionHost {
2293
2452
  // that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
2294
2453
  // `SummaryModelSpare.dispose`.
2295
2454
  this.summarySpare.dispose();
2455
+ const tours = [...this.pullRequestTours.keys()].map(key => { const running = this.pullRequestTours.get(key)?.running; this.dropPullRequestTour(key); return running; });
2456
+ await Promise.allSettled(tours);
2296
2457
  const warm = [...this.skillSessions.values()];
2297
2458
  this.skillSessions.clear();
2298
2459
  await Promise.all(warm.map((held) => held.session.dispose().catch(() => { })));
@@ -2321,6 +2482,9 @@ export class SessionHost {
2321
2482
  throw new AggregateError(failures, "Backend Adapter shutdown failed");
2322
2483
  }
2323
2484
  async execute(command) {
2485
+ if (READ_ONLY_REFUSED.has(command.type) && "sessionId" in command && this.record(command.sessionId).readOnly) {
2486
+ throw new CommandRefused("This Agent Session has a Read-only Scope. It cannot change Git state or run a Tour.");
2487
+ }
2324
2488
  switch (command.type) {
2325
2489
  case "create":
2326
2490
  return await this.create({
@@ -2331,6 +2495,7 @@ export class SessionHost {
2331
2495
  ...(command.permissionMode === undefined ? {} : { permissionMode: command.permissionMode }),
2332
2496
  ...(command.mcpConnectionIds === undefined ? {} : { mcpConnectionIds: command.mcpConnectionIds }),
2333
2497
  ...(command.worktree === undefined ? {} : { worktree: command.worktree }),
2498
+ ...(command.readOnly ? { readOnly: true } : {}),
2334
2499
  });
2335
2500
  case "send":
2336
2501
  return await this.send(command.sessionId, command.text, command.when, command.attachments);
@@ -2358,24 +2523,62 @@ export class SessionHost {
2358
2523
  return await this.setEffort(command.sessionId, command.effort);
2359
2524
  case "pull_branch":
2360
2525
  return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
2361
- case "change_pull_request":
2362
- return await this.withGitOperation(this.record(command.sessionId).scope, () => this.afterPullRequestWrite(this.record(command.sessionId).scope, changePullRequest(this.record(command.sessionId).scope, command.action, command.input)));
2526
+ case "change_pull_request": {
2527
+ const { scope, find } = this.pullRequestPlace(command);
2528
+ const change = () => this.afterPullRequestWrite(scope, changePullRequest(scope, command.action, command.input, gh, find));
2529
+ return await (find ? this.readGit(change) : this.withGitOperation(scope, change));
2530
+ }
2363
2531
  case "pull_request": {
2532
+ if ("project" in command) {
2533
+ const scope = this.projectScope(command.project);
2534
+ return await this.readGit(() => projectPullRequest(scope, command.number));
2535
+ }
2364
2536
  const scope = this.record(command.sessionId).scope;
2365
2537
  return await this.readGit(() => pullRequest(scope, this.gitStates.pullRequestRef(scope)));
2366
2538
  }
2367
- case "comment_pull_request":
2368
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, commentPullRequest(this.record(command.sessionId).scope, command.input));
2369
- case "resolve_pull_request_thread":
2370
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, resolvePullRequestThread(this.record(command.sessionId).scope, command.input));
2371
- case "edit_pull_request":
2372
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, editPullRequest(this.record(command.sessionId).scope, command.input));
2373
- case "set_pull_request_draft":
2374
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, setPullRequestDraft(this.record(command.sessionId).scope, command.input));
2375
- case "rerun_pull_request_checks":
2376
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, rerunPullRequestChecks(this.record(command.sessionId).scope, command.input));
2377
- case "pull_request_check_log":
2378
- return await checkLog(this.record(command.sessionId).scope, command.pr, command.jobId);
2539
+ case "comment_pull_request": {
2540
+ const { scope, find } = this.pullRequestPlace(command);
2541
+ return await this.afterPullRequestWrite(scope, commentPullRequest(scope, command.input, gh, find));
2542
+ }
2543
+ case "resolve_pull_request_thread": {
2544
+ const { scope, find } = this.pullRequestPlace(command);
2545
+ return await this.afterPullRequestWrite(scope, resolvePullRequestThread(scope, command.input, gh, find));
2546
+ }
2547
+ case "edit_pull_request": {
2548
+ const { scope, find } = this.pullRequestPlace(command);
2549
+ return await this.afterPullRequestWrite(scope, editPullRequest(scope, command.input, gh, find));
2550
+ }
2551
+ case "set_pull_request_draft": {
2552
+ const { scope, find } = this.pullRequestPlace(command);
2553
+ return await this.afterPullRequestWrite(scope, setPullRequestDraft(scope, command.input, gh, find));
2554
+ }
2555
+ case "rerun_pull_request_checks": {
2556
+ const { scope, find } = this.pullRequestPlace(command);
2557
+ return await this.afterPullRequestWrite(scope, rerunPullRequestChecks(scope, command.input, gh, find));
2558
+ }
2559
+ case "pull_request_check_log": {
2560
+ const { scope, find } = this.pullRequestPlace(command);
2561
+ return await checkLog(scope, command.pr, command.jobId, gh, find);
2562
+ }
2563
+ case "submit_pull_request_review": {
2564
+ const { scope, find } = this.pullRequestPlace(command);
2565
+ return await this.afterPullRequestWrite(scope, submitReview(scope, command.input, gh, find));
2566
+ }
2567
+ case "project_pull_requests": {
2568
+ const scope = this.projectScope(command.project);
2569
+ const query = typeof command.query === "string" ? command.query.trim() : "";
2570
+ return await this.readGit(() => listPullRequests(scope, gh, query || undefined));
2571
+ }
2572
+ case "pull_request_changes":
2573
+ case "pull_request_diff": {
2574
+ const scope = this.projectScope(command.project);
2575
+ return await this.readGit(async () => {
2576
+ const range = await pullRequestRange(scope, command.pr);
2577
+ return command.type === "pull_request_diff" ? await fileDiff(scope, command.path, range.base, range.head) : await rangeChanges(scope, range.base, range.head);
2578
+ });
2579
+ }
2580
+ case "start_pull_request_session":
2581
+ return await this.startPullRequestSession(command.project, command.pr);
2379
2582
  case "stack_status":
2380
2583
  return await this.readStack(command.sessionId);
2381
2584
  case "prepare_stack":
@@ -2409,11 +2612,11 @@ export class SessionHost {
2409
2612
  case "suggest_git_text":
2410
2613
  return await this.suggestGitText(command.sessionId, command.kind, command.paths);
2411
2614
  case "start_tour":
2412
- return this.startTour(command.sessionId);
2615
+ return "project" in command ? this.startPullRequestTour(command.project, command.pr) : this.startTour(command.sessionId);
2413
2616
  case "tour":
2414
- return this.tour(command.sessionId);
2617
+ return "project" in command ? this.pullRequestTour(command.project, command.pr) : this.tour(command.sessionId);
2415
2618
  case "cancel_tour":
2416
- return this.cancelTour(command.sessionId);
2619
+ return "project" in command ? this.cancelPullRequestTour(command.project, command.pr) : this.cancelTour(command.sessionId);
2417
2620
  case "switch_branch":
2418
2621
  return await this.switchBranch(command.sessionId, command.branch);
2419
2622
  case "switch_scope_branch":
@@ -2507,6 +2710,7 @@ export class SessionHost {
2507
2710
  const mounts = [...this.backends.values()].flatMap(backend => backend.scheduledSandboxMounts?.(scope) ?? []);
2508
2711
  return { writable: mounts.flatMap(item => item.writable), readable: mounts.flatMap(item => item.readable) };
2509
2712
  }
2713
+ isReadOnly(sessionId) { return this.record(sessionId).readOnly === true; }
2510
2714
  sharedSandbox() { return this.sandboxSharing?.() === "shared" ? this.shared : undefined; }
2511
2715
  async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode(), signal) {
2512
2716
  signal?.throwIfAborted();
@@ -2525,7 +2729,7 @@ export class SessionHost {
2525
2729
  const { McpSession } = await import('../backend/mcp.js');
2526
2730
  const scope = this.workflowSession(id).scope;
2527
2731
  signal?.throwIfAborted();
2528
- return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
2732
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, undefined, undefined, this.isReadOnly(id));
2529
2733
  }
2530
2734
  /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
2531
2735
  async openWorkflowMcpAuthoring(scope, connectionId, isolationMode = this.filesystemIsolationMode(), expectedScopeIdentity) {
@@ -2533,7 +2737,7 @@ export class SessionHost {
2533
2737
  if (!connection)
2534
2738
  throw new Error('MCP connection removed. Refresh the workflow editor.');
2535
2739
  const { McpSession } = await import('../backend/mcp.js');
2536
- return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity);
2740
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity, undefined, true);
2537
2741
  }
2538
2742
  mcpStatus(id) {
2539
2743
  const record = this.sessions.get(id);
@@ -2644,7 +2848,11 @@ export class SessionHost {
2644
2848
  const { text, scope = source.scope, backend: name = source.backendName, modelId, effort, worktree } = sessionCreateInput.parse(input);
2645
2849
  if (!isAbsolute(scope))
2646
2850
  throw new CommandRefused('Scope must be an absolute directory');
2851
+ const readOnly = source.readOnly && !(this.projectPaths?.() ?? []).some(path => scopeKey(path) === scopeKey(scope));
2852
+ if (readOnly && scopeKey(scope) !== scopeKey(this.projectRoot?.() ?? scope))
2853
+ throw new CommandRefused('A read-only Agent Session can create Agent Sessions only in a Project or at the Project Root');
2647
2854
  const sessionId = await this.create({ scope, backend: name,
2855
+ ...(readOnly ? { readOnly: true } : {}),
2648
2856
  ...(modelId === undefined ? {} : { modelId }),
2649
2857
  ...(effort === undefined ? {} : { effort }),
2650
2858
  ...(worktree === undefined ? {} : { worktree: { from: worktree.from, ...(worktree.branch === undefined ? {} : { branch: worktree.branch }) } }),
@@ -2682,7 +2890,7 @@ export class SessionHost {
2682
2890
  const isolationMode = this.filesystemIsolationMode();
2683
2891
  const mcp = isolationMode === "sandbox"
2684
2892
  ? new SandboxMcpSession(selected, record.scope, oauth, this.resolveSecret)
2685
- : new McpSession(selected, record.scope, oauth, false, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
2893
+ : new McpSession(selected, record.scope, oauth, false, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, undefined, undefined, record.readOnly === true);
2686
2894
  record.mcp = mcp;
2687
2895
  const openingMcp = mcp.open();
2688
2896
  const autoCompaction = this.autoCompaction?.(backend.name);
@@ -2710,6 +2918,7 @@ export class SessionHost {
2710
2918
  throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).relayPermission(input, signal); },
2711
2919
  },
2712
2920
  scope: record.scope,
2921
+ ...(record.readOnly ? { readOnly: this.readOnlyEnforcement(isolationMode) } : {}),
2713
2922
  emit: (event) => {
2714
2923
  if (!attached || record.session === attached)
2715
2924
  this.onBackendEvent(record.id, event);
@@ -2949,7 +3158,8 @@ export class SessionHost {
2949
3158
  record.log.append({
2950
3159
  type: "user_message",
2951
3160
  id: messageId,
2952
- text: sent,
3161
+ text,
3162
+ ...(note === undefined ? {} : { note }),
2953
3163
  ...(attachments.length > 0 ? { attachments } : {}),
2954
3164
  ...(fromSessionId === undefined ? {} : { fromSessionId }),
2955
3165
  });
@@ -3297,6 +3507,7 @@ export class SessionHost {
3297
3507
  permissionMode: record.permissionMode,
3298
3508
  ...(record.initialEffortUnconfirmed ? { initialEffortUnconfirmed: true } : {}),
3299
3509
  ...(record.worktree === undefined ? {} : { worktree: record.worktree }),
3510
+ ...(record.readOnly ? { readOnly: true } : {}),
3300
3511
  };
3301
3512
  this.store.writeMeta(meta);
3302
3513
  }
@@ -3556,6 +3767,11 @@ function firstLine(text) {
3556
3767
  function errorMessage(error) {
3557
3768
  return error instanceof Error ? error.message : String(error);
3558
3769
  }
3770
+ const READ_ONLY_REFUSED = new Set([
3771
+ "switch_branch", "pull_branch", "change_pull_request", "comment_pull_request", "submit_pull_request_review", "resolve_pull_request_thread",
3772
+ "edit_pull_request", "set_pull_request_draft", "rerun_pull_request_checks", "prepare_stack", "change_stack",
3773
+ "assist_stack", "commit", "push", "create_pull_request", "start_tour",
3774
+ ]);
3559
3775
  function scopeKey(scope) {
3560
3776
  try {
3561
3777
  return realpathSync(scope);