@nathanstephenson/flow 0.1.10-beta.8 → 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 (39) 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/scope-kind.js +4 -0
  13. package/dist/daemon/changes.js +22 -12
  14. package/dist/daemon/git.js +10 -1
  15. package/dist/daemon/host.js +248 -42
  16. package/dist/daemon/pull-request.js +90 -25
  17. package/dist/daemon/repository.js +15 -9
  18. package/dist/daemon/runtime.js +2 -0
  19. package/dist/daemon/server.js +25 -0
  20. package/dist/daemon/tour.js +7 -1
  21. package/dist/daemon/workflow-environment.js +6 -4
  22. package/dist/daemon/workflow-executions.js +1 -1
  23. package/dist/isolation/filesystem.js +1 -1
  24. package/dist/protocol/spend.js +1 -1
  25. package/dist/workflows/executors.js +2 -1
  26. package/package.json +1 -1
  27. package/web/dist/assets/index-CHFNROUs.js +51 -0
  28. package/web/dist/assets/index-D9AneSPi.css +2 -0
  29. package/web/dist/assets/{select-C-BND5Jn.js → select-COVn-75j.js} +1 -1
  30. package/web/dist/assets/{settings-mcp-DEU2AgQP.js → settings-mcp-BHZwEeJF.js} +1 -1
  31. package/web/dist/assets/{settings-secrets-29ZG3w6p.js → settings-secrets-NGSRhEbU.js} +1 -1
  32. package/web/dist/assets/settings-workflows-uew3ONyO.js +23 -0
  33. package/web/dist/assets/{workflow-api-DkUjAZ4w.js → workflow-api-3z2Qqsmo.js} +1 -1
  34. package/web/dist/assets/{workflows-DOxarXng.js → workflows-hcZXxss1.js} +2 -2
  35. package/web/dist/assets/{workflows-pane-DlaP2y8m.js → workflows-pane-DntY7Dcw.js} +1 -1
  36. package/web/dist/index.html +5 -5
  37. package/web/dist/assets/index-Cf28Ke0f.js +0 -51
  38. package/web/dist/assets/index-DBl7acBx.css +0 -2
  39. package/web/dist/assets/settings-workflows-CS_5CtP9.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";
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
10
  import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage, mergeableStack, stackMergeMethods } from "./stack.js";
11
- import { changes, changesText, commitContext, diff } from "./changes.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.");
@@ -202,6 +205,42 @@ export class SessionHost {
202
205
  return status;
203
206
  });
204
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
+ }
205
244
  gitScope(sessionId) {
206
245
  const scope = this.record(sessionId).scope;
207
246
  if (!isRepository(scope))
@@ -290,7 +329,7 @@ export class SessionHost {
290
329
  const session = record.session;
291
330
  if (!current())
292
331
  return;
293
- if (!session?.startWorkflowSubagent)
332
+ if (!session)
294
333
  throw new Error("This Backend Adapter cannot run a tour.");
295
334
  const log = record.log.since(0);
296
335
  const model = log.findLast(({ event }) => event.type === "model_changed")?.event;
@@ -299,22 +338,97 @@ export class SessionHost {
299
338
  const modelId = chosen?.modelId ?? (model?.type === "model_changed" ? model.model.id : record.modelId);
300
339
  if (!modelId)
301
340
  throw new Error("The Agent Session's model is unknown. Choose a Tour Model in Settings.");
302
- tour.handle = session.startWorkflowSubagent({
303
- id: tour.id, name: "Tour", instructions: TOUR_INSTRUCTIONS, input, modelId,
304
- effort: chosen?.effort ?? (effort?.type === "effort_changed" ? effort.effort : record.effort) ?? "off",
305
- permissionMode: "ask",
306
- emit: ({ event }) => {
307
- if (event.type === "permission" && event.state === "asked") {
308
- queueMicrotask(() => void tour.handle?.answerPermission(event.callId, TOUR_READ_TOOLS.includes(event.tool) ? "allow" : "deny").catch(() => undefined));
309
- }
310
- if (event.type === "enquiry" && event.state === "asked") {
311
- queueMicrotask(() => void tour.handle?.answerEnquiry(event.askId, event.questions.map(() => ["No human is available. Continue without an answer."])).catch(() => undefined));
312
- }
313
- if (event.type === "spend")
314
- this.workflowSpend(record.id, `tour:${tour.id}`, event.spend);
315
- },
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; },
316
425
  });
317
- 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));
318
432
  if (current())
319
433
  tour.view = { state: "done", text, ...made };
320
434
  }
@@ -322,6 +436,14 @@ export class SessionHost {
322
436
  if (current())
323
437
  tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
324
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";
325
447
  }
326
448
  store;
327
449
  retention;
@@ -336,12 +458,15 @@ export class SessionHost {
336
458
  summaryModel;
337
459
  tourModel;
338
460
  closedListeners = new Set();
461
+ attentionListeners = new Set();
339
462
  backendFailures = new Set();
340
463
  keptListeners = new Set();
341
464
  filesystemIsolation;
342
465
  sandbox;
343
466
  sandboxSharing;
344
467
  updateSourceBranch;
468
+ projectRoot;
469
+ projectPaths;
345
470
  shared;
346
471
  mcpConnections;
347
472
  mcpAuth;
@@ -351,6 +476,8 @@ export class SessionHost {
351
476
  this.sandbox = options.sandboxSupport;
352
477
  this.sandboxSharing = options.sandboxSharing;
353
478
  this.updateSourceBranch = options.updateSourceBranch;
479
+ this.projectRoot = options.projectRoot;
480
+ this.projectPaths = options.projectPaths;
354
481
  this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
355
482
  this.mcpConnections = options.mcpConnections;
356
483
  this.mcpAuth = options.mcpAuth;
@@ -381,6 +508,10 @@ export class SessionHost {
381
508
  this.closedListeners.add(listener);
382
509
  return () => this.closedListeners.delete(listener);
383
510
  }
511
+ onAttentionRaised(listener) {
512
+ this.attentionListeners.add(listener);
513
+ return () => this.attentionListeners.delete(listener);
514
+ }
384
515
  announceClosed(sessionId) {
385
516
  for (const listener of this.closedListeners)
386
517
  listener(sessionId);
@@ -576,6 +707,9 @@ export class SessionHost {
576
707
  };
577
708
  if (reason !== "Input needed")
578
709
  record.latestOutcome = record.latestAttention;
710
+ for (const listener of this.attentionListeners) {
711
+ listener({ sessionId: record.id, title: record.title, reason, version, at });
712
+ }
579
713
  return { at, version };
580
714
  }
581
715
  /**
@@ -646,6 +780,7 @@ export class SessionHost {
646
780
  ...(record.branch ? { branch: record.branch } : {}),
647
781
  ...(git ? { git } : {}),
648
782
  ...(record.worktree ? { worktree: true } : {}),
783
+ ...(record.readOnly ? { readOnly: true } : {}),
649
784
  ...(record.session || existsSync(record.scope) ? {} : {
650
785
  scopeMissing: true,
651
786
  ...this.suggestion(record.scope),
@@ -675,6 +810,7 @@ export class SessionHost {
675
810
  async load() {
676
811
  if (!this.store)
677
812
  return;
813
+ rmSync(join(this.store.worktreesRoot(), ".tours"), { recursive: true, force: true });
678
814
  for (const id of await this.store.listSessionIds()) {
679
815
  const meta = this.store.readMeta(id);
680
816
  if (!meta || this.sessions.has(id))
@@ -721,6 +857,7 @@ export class SessionHost {
721
857
  branch: branchFrom(entries),
722
858
  branchGeneration: 0,
723
859
  worktree: meta.worktree,
860
+ ...(meta.readOnly ? { readOnly: true } : {}),
724
861
  ...(meta.scheduledOccurrenceId ? { scheduledOccurrenceId: meta.scheduledOccurrenceId } : {}),
725
862
  pendingBranchNote: undefined,
726
863
  capabilities: capabilitiesFrom(entries),
@@ -806,6 +943,13 @@ export class SessionHost {
806
943
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
807
944
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
808
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
+ }
809
953
  const cut = options.scheduled?.worktree || !options.worktree ? undefined : await this.cutWorktree(options.scope, options.worktree);
810
954
  const worktree = options.scheduled?.worktree ?? cut?.worktree;
811
955
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
@@ -848,6 +992,7 @@ export class SessionHost {
848
992
  branch: undefined,
849
993
  branchGeneration: 0,
850
994
  worktree,
995
+ ...(options.readOnly ? { readOnly: true } : {}),
851
996
  pendingBranchNote: undefined,
852
997
  capabilities: undefined,
853
998
  spend: undefined,
@@ -970,7 +1115,7 @@ export class SessionHost {
970
1115
  throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
971
1116
  if (!isRepository(repo))
972
1117
  throw new CommandRefused(`${repo} is not a git repository`);
973
- 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;
974
1119
  const created = await createWorktree({
975
1120
  repo,
976
1121
  from: options.from,
@@ -1021,6 +1166,8 @@ export class SessionHost {
1021
1166
  async relocate(sessionId, scope, repo) {
1022
1167
  const record = this.record(sessionId);
1023
1168
  const from = record.scope;
1169
+ if (record.readOnly)
1170
+ throw new CommandRefused("An Agent Session with a Read-only Scope cannot relocate.");
1024
1171
  if (record.session || record.reviving)
1025
1172
  throw new CommandRefused("This Agent Session is running. Only a stopped Agent Session can relocate.");
1026
1173
  if (existsSync(from))
@@ -1524,6 +1671,8 @@ export class SessionHost {
1524
1671
  throw new CommandRefused("Wait for the turn, the queued messages and the background work to finish, or abort them, before rewinding");
1525
1672
  }
1526
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.");
1527
1676
  const conversation = restore !== "files";
1528
1677
  if (conversation && !session.capabilities.rewind)
1529
1678
  throw new CommandRefused(`${record.backendName} cannot rewind a Conversation Context`);
@@ -1577,6 +1726,7 @@ export class SessionHost {
1577
1726
  permissionMode: source.permissionMode,
1578
1727
  mcpConnectionIds: source.mcpConnectionIds ?? [],
1579
1728
  ...(worktree === undefined ? {} : { worktree }),
1729
+ ...(source.readOnly ? { readOnly: true } : {}),
1580
1730
  fork: { source, userMessageId, prefix: events.filter((entry) => entry.seq < at.seq) },
1581
1731
  });
1582
1732
  }
@@ -2302,6 +2452,8 @@ export class SessionHost {
2302
2452
  // that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
2303
2453
  // `SummaryModelSpare.dispose`.
2304
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);
2305
2457
  const warm = [...this.skillSessions.values()];
2306
2458
  this.skillSessions.clear();
2307
2459
  await Promise.all(warm.map((held) => held.session.dispose().catch(() => { })));
@@ -2330,6 +2482,9 @@ export class SessionHost {
2330
2482
  throw new AggregateError(failures, "Backend Adapter shutdown failed");
2331
2483
  }
2332
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
+ }
2333
2488
  switch (command.type) {
2334
2489
  case "create":
2335
2490
  return await this.create({
@@ -2340,6 +2495,7 @@ export class SessionHost {
2340
2495
  ...(command.permissionMode === undefined ? {} : { permissionMode: command.permissionMode }),
2341
2496
  ...(command.mcpConnectionIds === undefined ? {} : { mcpConnectionIds: command.mcpConnectionIds }),
2342
2497
  ...(command.worktree === undefined ? {} : { worktree: command.worktree }),
2498
+ ...(command.readOnly ? { readOnly: true } : {}),
2343
2499
  });
2344
2500
  case "send":
2345
2501
  return await this.send(command.sessionId, command.text, command.when, command.attachments);
@@ -2367,24 +2523,62 @@ export class SessionHost {
2367
2523
  return await this.setEffort(command.sessionId, command.effort);
2368
2524
  case "pull_branch":
2369
2525
  return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
2370
- case "change_pull_request":
2371
- 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
+ }
2372
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
+ }
2373
2536
  const scope = this.record(command.sessionId).scope;
2374
2537
  return await this.readGit(() => pullRequest(scope, this.gitStates.pullRequestRef(scope)));
2375
2538
  }
2376
- case "comment_pull_request":
2377
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, commentPullRequest(this.record(command.sessionId).scope, command.input));
2378
- case "resolve_pull_request_thread":
2379
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, resolvePullRequestThread(this.record(command.sessionId).scope, command.input));
2380
- case "edit_pull_request":
2381
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, editPullRequest(this.record(command.sessionId).scope, command.input));
2382
- case "set_pull_request_draft":
2383
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, setPullRequestDraft(this.record(command.sessionId).scope, command.input));
2384
- case "rerun_pull_request_checks":
2385
- return await this.afterPullRequestWrite(this.record(command.sessionId).scope, rerunPullRequestChecks(this.record(command.sessionId).scope, command.input));
2386
- case "pull_request_check_log":
2387
- 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);
2388
2582
  case "stack_status":
2389
2583
  return await this.readStack(command.sessionId);
2390
2584
  case "prepare_stack":
@@ -2418,11 +2612,11 @@ export class SessionHost {
2418
2612
  case "suggest_git_text":
2419
2613
  return await this.suggestGitText(command.sessionId, command.kind, command.paths);
2420
2614
  case "start_tour":
2421
- return this.startTour(command.sessionId);
2615
+ return "project" in command ? this.startPullRequestTour(command.project, command.pr) : this.startTour(command.sessionId);
2422
2616
  case "tour":
2423
- return this.tour(command.sessionId);
2617
+ return "project" in command ? this.pullRequestTour(command.project, command.pr) : this.tour(command.sessionId);
2424
2618
  case "cancel_tour":
2425
- return this.cancelTour(command.sessionId);
2619
+ return "project" in command ? this.cancelPullRequestTour(command.project, command.pr) : this.cancelTour(command.sessionId);
2426
2620
  case "switch_branch":
2427
2621
  return await this.switchBranch(command.sessionId, command.branch);
2428
2622
  case "switch_scope_branch":
@@ -2516,6 +2710,7 @@ export class SessionHost {
2516
2710
  const mounts = [...this.backends.values()].flatMap(backend => backend.scheduledSandboxMounts?.(scope) ?? []);
2517
2711
  return { writable: mounts.flatMap(item => item.writable), readable: mounts.flatMap(item => item.readable) };
2518
2712
  }
2713
+ isReadOnly(sessionId) { return this.record(sessionId).readOnly === true; }
2519
2714
  sharedSandbox() { return this.sandboxSharing?.() === "shared" ? this.shared : undefined; }
2520
2715
  async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode(), signal) {
2521
2716
  signal?.throwIfAborted();
@@ -2534,7 +2729,7 @@ export class SessionHost {
2534
2729
  const { McpSession } = await import('../backend/mcp.js');
2535
2730
  const scope = this.workflowSession(id).scope;
2536
2731
  signal?.throwIfAborted();
2537
- 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));
2538
2733
  }
2539
2734
  /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
2540
2735
  async openWorkflowMcpAuthoring(scope, connectionId, isolationMode = this.filesystemIsolationMode(), expectedScopeIdentity) {
@@ -2542,7 +2737,7 @@ export class SessionHost {
2542
2737
  if (!connection)
2543
2738
  throw new Error('MCP connection removed. Refresh the workflow editor.');
2544
2739
  const { McpSession } = await import('../backend/mcp.js');
2545
- 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);
2546
2741
  }
2547
2742
  mcpStatus(id) {
2548
2743
  const record = this.sessions.get(id);
@@ -2653,7 +2848,11 @@ export class SessionHost {
2653
2848
  const { text, scope = source.scope, backend: name = source.backendName, modelId, effort, worktree } = sessionCreateInput.parse(input);
2654
2849
  if (!isAbsolute(scope))
2655
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');
2656
2854
  const sessionId = await this.create({ scope, backend: name,
2855
+ ...(readOnly ? { readOnly: true } : {}),
2657
2856
  ...(modelId === undefined ? {} : { modelId }),
2658
2857
  ...(effort === undefined ? {} : { effort }),
2659
2858
  ...(worktree === undefined ? {} : { worktree: { from: worktree.from, ...(worktree.branch === undefined ? {} : { branch: worktree.branch }) } }),
@@ -2691,7 +2890,7 @@ export class SessionHost {
2691
2890
  const isolationMode = this.filesystemIsolationMode();
2692
2891
  const mcp = isolationMode === "sandbox"
2693
2892
  ? new SandboxMcpSession(selected, record.scope, oauth, this.resolveSecret)
2694
- : 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);
2695
2894
  record.mcp = mcp;
2696
2895
  const openingMcp = mcp.open();
2697
2896
  const autoCompaction = this.autoCompaction?.(backend.name);
@@ -2719,6 +2918,7 @@ export class SessionHost {
2719
2918
  throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).relayPermission(input, signal); },
2720
2919
  },
2721
2920
  scope: record.scope,
2921
+ ...(record.readOnly ? { readOnly: this.readOnlyEnforcement(isolationMode) } : {}),
2722
2922
  emit: (event) => {
2723
2923
  if (!attached || record.session === attached)
2724
2924
  this.onBackendEvent(record.id, event);
@@ -3307,6 +3507,7 @@ export class SessionHost {
3307
3507
  permissionMode: record.permissionMode,
3308
3508
  ...(record.initialEffortUnconfirmed ? { initialEffortUnconfirmed: true } : {}),
3309
3509
  ...(record.worktree === undefined ? {} : { worktree: record.worktree }),
3510
+ ...(record.readOnly ? { readOnly: true } : {}),
3310
3511
  };
3311
3512
  this.store.writeMeta(meta);
3312
3513
  }
@@ -3566,6 +3767,11 @@ function firstLine(text) {
3566
3767
  function errorMessage(error) {
3567
3768
  return error instanceof Error ? error.message : String(error);
3568
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
+ ]);
3569
3775
  function scopeKey(scope) {
3570
3776
  try {
3571
3777
  return realpathSync(scope);