@nathanstephenson/flow 0.1.10-beta.6 → 0.1.10-beta.8

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 (46) hide show
  1. package/README.md +5 -19
  2. package/dist/build-id +1 -1
  3. package/dist/cli/application.js +4 -37
  4. package/dist/cli/bootstrap.js +2 -2
  5. package/dist/cli/install-guard.js +1 -1
  6. package/dist/client/context-usage.js +2 -3
  7. package/dist/client/enquiry.js +0 -6
  8. package/dist/client/model-choices.js +1 -1
  9. package/dist/client/permission.js +1 -2
  10. package/dist/client/reduce.js +1 -0
  11. package/dist/client/relative-time.js +1 -1
  12. package/dist/client/scope-kind.js +2 -3
  13. package/dist/client/search.js +1 -1
  14. package/dist/client/status.js +1 -1
  15. package/dist/client/subagent-tree.js +1 -1
  16. package/dist/client/tool-chains.js +1 -1
  17. package/dist/client/tool-summary.js +2 -3
  18. package/dist/daemon/config-store.js +2 -0
  19. package/dist/daemon/config.js +32 -1
  20. package/dist/daemon/git.js +33 -2
  21. package/dist/daemon/host.js +27 -8
  22. package/dist/daemon/pull-request.js +3 -10
  23. package/dist/daemon/repository.js +11 -0
  24. package/dist/daemon/runtime.js +1 -1
  25. package/dist/daemon/server.js +2 -2
  26. package/dist/daemon/stack.js +37 -3
  27. package/dist/daemon/workflow-schedule-driver.js +5 -1
  28. package/dist/protocol/stack.js +14 -1
  29. package/dist/workflows/schedules.js +1 -0
  30. package/package.json +1 -1
  31. package/web/dist/assets/index-Cf28Ke0f.js +51 -0
  32. package/web/dist/assets/index-DBl7acBx.css +2 -0
  33. package/web/dist/assets/{switch-B00FEUA7.js → select-C-BND5Jn.js} +1 -1
  34. package/web/dist/assets/{settings-mcp-3cgqQB28.js → settings-mcp-DEU2AgQP.js} +1 -1
  35. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-29ZG3w6p.js} +1 -1
  36. package/web/dist/assets/{settings-workflows-Cutm8isB.js → settings-workflows-CS_5CtP9.js} +2 -2
  37. package/web/dist/assets/workflow-api-DkUjAZ4w.js +6 -0
  38. package/web/dist/assets/{workflows-D6oEUUhj.js → workflows-DOxarXng.js} +14 -14
  39. package/web/dist/assets/{workflows-pane-KIdSDKJB.js → workflows-pane-DlaP2y8m.js} +1 -1
  40. package/web/dist/index.html +5 -5
  41. package/dist/tui/app.js +0 -612
  42. package/dist/tui/keys.js +0 -90
  43. package/dist/tui/render.js +0 -417
  44. package/web/dist/assets/index-BhfJhrVJ.js +0 -51
  45. package/web/dist/assets/index-BvkM2cWL.css +0 -2
  46. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Flow
2
2
 
3
- Flow runs coding-agent sessions. You can watch and control them from a terminal or a browser.
3
+ Flow runs coding-agent sessions. You can watch and control them from a browser, or send one prompt from the CLI.
4
4
 
5
- - **Local mode (v1)** — a Session Host daemon runs on loopback. A TUI and a web UI are equal clients.
5
+ - **Local mode (v1)** — a Session Host daemon runs on loopback. The web UI is the client.
6
6
  - **Backends** — the Claude Agent SDK (on your own Claude subscription) and the pi SDK (for models
7
7
  that Claude does not serve). You choose the backend for each Agent Session.
8
8
 
@@ -46,7 +46,6 @@ flow serve
46
46
 
47
47
  `flow serve` stays in the foreground. It prints a web handoff URL
48
48
  (`http://127.0.0.1:PORT/auth?token=…`). Open that URL once in your browser.
49
- To use the terminal client, run `flow tui` in another terminal.
50
49
 
51
50
  To run the Session Host in the background:
52
51
 
@@ -88,7 +87,6 @@ Pi cache warming stays limited to active runs unless Pi's global `cacheWarming`
88
87
  | Command | Action |
89
88
  | --- | --- |
90
89
  | `flow serve [--port N] [--address HOST]` | Run the Session Host in the foreground. |
91
- | `flow tui [--scope DIR] [--backend claude\|pi\|fake]` | Open the terminal client. It connects to a running host, or starts its own. |
92
90
  | `flow list` | List Agent Sessions. |
93
91
  | `flow [--session ID] [--scope DIR] [--backend B] [--model M] [--effort L] "<prompt>"` | Send one prompt, then exit. |
94
92
  | `flow update [--force]` | Update Flow. See [Updating Flow](#updating-flow). |
@@ -102,11 +100,7 @@ flow --session <id> "What word did I ask you to remember?" # → marmalade
102
100
  flow list
103
101
  ```
104
102
 
105
- Scope rules:
106
-
107
- - `flow tui` without `--scope` uses the Project Root from `config.json`. If there is no Project
108
- Root, it uses the current directory.
109
- - A one-shot prompt always uses the current directory, unless `--scope` names a different one.
103
+ A one-shot prompt always uses the current directory, unless `--scope` names a different one.
110
104
 
111
105
  ### Agent Sessions survive restarts
112
106
 
@@ -122,15 +116,7 @@ Creation and messaging use the existing permission policy and can incur Spend. A
122
116
  another Agent Session's human prompts. Use a fresh Worktree for concurrent edits, and inspect for
123
117
  results rather than assuming delivery means completion.
124
118
 
125
- ### TUI keys
126
-
127
- | Key | Action |
128
- | --- | --- |
129
- | `^S` | Sessions |
130
- | `^P` | Models (grouped by provider) |
131
- | `^E` | Effort |
132
- | `esc` | Abort |
133
- | `^C` | Quit |
119
+ ### Messages during a turn
134
120
 
135
121
  If you type while the agent works, Flow queues the message. It does not interrupt the agent.
136
122
  Steering is a deliberate action.
@@ -172,7 +158,7 @@ Each state root permits one Session Host.
172
158
  flow update
173
159
  ```
174
160
 
175
- Before you update, close all CLI and TUI clients. Stop other Session Hosts that use this
161
+ Before you update, close all CLI clients. Stop other Session Hosts that use this
176
162
  installation. Updates are never automatic. [docs/updating.md](docs/updating.md) gives the
177
163
  requirements, the browser update, systemd setup and the repair procedure.
178
164
 
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- 607b7e81-c593-4a74-86cb-83029e6da64f
1
+ d55666c9-014a-4615-bc06-84cd0d47d46e
@@ -4,7 +4,6 @@ import { getHostStatus, launchBackground, requestHostStop, requireRestartable, w
4
4
  import { readHost, oidcFingerprint } from '../daemon/ownership.js';
5
5
  import { startRuntime } from '../daemon/runtime.js';
6
6
  import { join, resolve } from "node:path";
7
- import { ConfigStore } from "../daemon/config-store.js";
8
7
  import { embeddedWorkflowRuntime } from '../workflows/runtime-asset.js';
9
8
  import { fileURLToPath } from 'node:url';
10
9
  import { getAsset, isSea } from 'node:sea';
@@ -15,20 +14,17 @@ import { connect } from "../client/connection.js";
15
14
  import { answerLines } from "../client/enquiry.js";
16
15
  import { authorisationLabel } from "../client/permission.js";
17
16
  import { initialState, reduce } from "../client/reduce.js";
18
- import { runTui } from "../tui/app.js";
19
17
  import { updateUnsupportedReason } from './install-guard.js';
20
18
  let webUpdateSupport;
21
19
  const USAGE = `usage:
22
20
  flow --version print the installed version
23
21
  flow update [--force] update a private global npm installation
24
- flow tui [--scope DIR] [--backend claude|pi|fake] interactive terminal client
25
22
  flow serve [--port N] [--address HOST] run the Session Host in the foreground
26
23
  flow serve start|status|stop|restart [--force] control a background Session Host
27
24
  flow list list Agent Sessions
28
25
  flow [--session ID] [--scope DIR] [--backend B] [--model M] [--effort L] "<prompt>"
29
26
  one prompt, then exit
30
27
 
31
- tui without --scope uses the Project Root from config.json, else this directory.
32
28
  A one-shot prompt always uses this directory unless --scope names another.`;
33
29
  function installedVersion() {
34
30
  return JSON.parse(isSea() ? getAsset('package.json', 'utf8') : readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
@@ -108,20 +104,6 @@ async function main() {
108
104
  await stop();
109
105
  return 0;
110
106
  }
111
- if (command === "tui") {
112
- const { connection, stop } = await clientConnection();
113
- try {
114
- await runTui({
115
- connection,
116
- scope: values.scope ?? configuredScope() ?? process.cwd(),
117
- ...(values.backend === undefined ? {} : { backend: values.backend }),
118
- });
119
- }
120
- finally {
121
- await stop();
122
- }
123
- return 0;
124
- }
125
107
  if (command === "list") {
126
108
  const { connection, stop } = await clientConnection();
127
109
  try {
@@ -141,21 +123,6 @@ async function main() {
141
123
  }
142
124
  return await oneShot(prompt, values);
143
125
  }
144
- /**
145
- * The Project Root, for a client that named no Scope.
146
- *
147
- * Read straight off disk rather than asked of the daemon, because the TUI may be talking to one it
148
- * did not start, and `/api/config`'s `scope` falls back to *that process's* working directory —
149
- * which is not this reader's. Only the configured root is a safe answer to borrow; the fallback to
150
- * `process.cwd()` has to happen here, where the cwd is the right one.
151
- *
152
- * A one-time read rather than a read-through, and that does not contradict ADR 0009: an Agent
153
- * Session's Scope is fixed for its whole life, so this value is consumed the moment it is asked for
154
- * and there is no later one for it to go stale against.
155
- */
156
- function configuredScope() {
157
- return new ConfigStore().projectRoot();
158
- }
159
126
  /** Build a Session Host with every Backend Adapter registered and prior sessions loaded. */
160
127
  const LOOPBACK = "127.0.0.1";
161
128
  async function startHost(port, address, mode = 'embedded') {
@@ -236,11 +203,11 @@ async function oneShot(prompt, values) {
236
203
  * worst of the three things that could happen, because it looks like a slow model rather
237
204
  * than like a question. Aborting ends the turn, which prints the `aborted` row below and
238
205
  * gets the transcript written; the Agent Session is left Dormant like any other, so `--session`
239
- * can pick it up in the TUI or the web client, where it *can* be answered.
206
+ * can pick it up in the web client, where it *can* be answered.
240
207
  */
241
208
  if (entry.event.type === "enquiry" && entry.event.state === "asked") {
242
209
  console.log(" ? the model asked a question, and this runner has no way to answer it");
243
- console.log(` ? resume with: --session ${sessionId} (or open it in the TUI)`);
210
+ console.log(` ? resume with: --session ${sessionId} (or open it in the web UI)`);
244
211
  void connection.command({ type: "abort", sessionId });
245
212
  }
246
213
  /*
@@ -267,7 +234,7 @@ async function oneShot(prompt, values) {
267
234
  const { tool, callId } = state.authorising;
268
235
  refused = callId;
269
236
  console.log(` ! ${tool} needs authorising, and this runner has no way to ask; refusing it`);
270
- console.log(` ! authorise it with: --session ${sessionId} (or open it in the TUI)`);
237
+ console.log(` ! authorise it with: --session ${sessionId} (or open it in the web UI)`);
271
238
  // Rejection swallowed rather than dropped: `--session` resumes a live Agent Session, and a
272
239
  // call decided in another client between the reducer seeing it and this landing comes back
273
240
  // as a refusal. There is nothing to do about that — the prompt is settled either way — and
@@ -325,7 +292,7 @@ function format(entry) {
325
292
  case "enquiry": {
326
293
  // This runner takes no input, so an Enquiry it sees is one it aborts (see `oneShot`) — what
327
294
  // reaches here is therefore `aborted`, and what it prints is what was asked and went
328
- // unanswered. The TUI and the web client are where one can actually be answered.
295
+ // unanswered. The web client is where one can actually be answered.
329
296
  const asked = answerLines(entry.questions, entry.answers).join("; ");
330
297
  return ` ? [${entry.status}] ${asked}`;
331
298
  }
@@ -342,7 +342,7 @@ function installation(slot) {
342
342
  if (!active.some((other) => other.id === lease.id && other.pid === process.pid && other.root === lease.root)) throw new Error("Update process has no installation lease");
343
343
  const selected = host && active.find((other) => other.pid === host.pid && other.root === lease.root);
344
344
  if (systemdArgs && selected && JSON.stringify(selected.args) !== JSON.stringify(systemdArgs)) throw new Error("Configured systemd hostArgs do not match the running Session Host; correct systemd-update.json before updating");
345
- if (active.some((other) => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && (systemdArgs ? JSON.stringify(other.args) === JSON.stringify(systemdArgs) : other.args.includes("--background-host"))))) throw new Error("Stop all other Flow hosts and CLI/TUI clients using this installation first");
345
+ if (active.some((other) => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && (systemdArgs ? JSON.stringify(other.args) === JSON.stringify(systemdArgs) : other.args.includes("--background-host"))))) throw new Error("Stop all other Flow hosts and CLI clients using this installation first");
346
346
  if (host && !active.some((other) => other.pid === host.pid && other.root === lease.root)) throw new Error("Stop all pre-guard Flow processes before updating");
347
347
  save(barrier);
348
348
  });
@@ -889,7 +889,7 @@ async function bootstrap() {
889
889
  if (!managed) throw new Error("Missing systemd update configuration");
890
890
  await assertSystemdOwner(managed, managed.updater, process.pid);
891
891
  }
892
- const lease = await install.register("607b7e81-c593-4a74-86cb-83029e6da64f", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
892
+ const lease = await install.register("d55666c9-014a-4615-bc06-84cd0d47d46e", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
893
893
  delete process.env.FLOW_UPDATE_CAPABILITY;
894
894
  process.on("exit", lease.release);
895
895
  if (args[0] === "update") {
@@ -272,7 +272,7 @@ export function installation(slot) {
272
272
  if (systemdArgs && selected && JSON.stringify(selected.args) !== JSON.stringify(systemdArgs))
273
273
  throw new Error('Configured systemd hostArgs do not match the running Session Host; correct systemd-update.json before updating');
274
274
  if (active.some(other => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && (systemdArgs ? JSON.stringify(other.args) === JSON.stringify(systemdArgs) : other.args.includes('--background-host')))))
275
- throw new Error('Stop all other Flow hosts and CLI/TUI clients using this installation first');
275
+ throw new Error('Stop all other Flow hosts and CLI clients using this installation first');
276
276
  if (host && !active.some(other => other.pid === host.pid && other.root === lease.root))
277
277
  throw new Error('Stop all pre-guard Flow processes before updating');
278
278
  save(barrier);
@@ -1,9 +1,8 @@
1
1
  /**
2
2
  * How much of the Conversation Context is spent, as one short chrome label.
3
3
  *
4
- * The two front-ends had drifted on the wording — the TUI said `context 12%` and the web UI said
5
- * `12% context` for the same numbers. The TUI's wording wins because it reads as a label rather than
6
- * as a sentence fragment, and because it is the one with tests.
4
+ * `context 12%` rather than `12% context`, because it reads as a label rather than as a sentence
5
+ * fragment.
7
6
  */
8
7
  export function contextUsageLabel(usage) {
9
8
  if (!usage)
@@ -25,12 +25,6 @@ export function cursorAfter(current, delta, rows) {
25
25
  return 0;
26
26
  return (((current + delta) % rows) + rows) % rows;
27
27
  }
28
- /** Where the cursor lands after moving by `delta`, clamped — the TUI's idiom, as every list there clamps. */
29
- export function cursorClamped(current, delta, rows) {
30
- if (rows <= 0)
31
- return 0;
32
- return Math.min(rows - 1, Math.max(0, current + delta));
33
- }
34
28
  /**
35
29
  * Where the cursor goes when the box gains or loses its first character.
36
30
  *
@@ -8,7 +8,7 @@ export function modelChoices(capabilities) {
8
8
  * `Capabilities` is how a model list arrives inside an Agent Session, and `GET /api/models` is how
9
9
  * it arrives before there is one (ADR 0020) — the New Agent Session view reads the second. Only
10
10
  * `.models` was ever used here, so taking the list is the whole of the generalisation, and
11
- * `modelChoices` keeps its signature so the TUI is untouched.
11
+ * `modelChoices` keeps its signature.
12
12
  */
13
13
  export function modelChoicesOf(models) {
14
14
  if (!models)
@@ -27,8 +27,7 @@ export const PERMISSION_CHOICES = [
27
27
  description: "Run it, and never ask again in any Agent Session. Revocable in Settings.",
28
28
  },
29
29
  ];
30
- // Permission controls are rendered and navigated on every TUI key event. Keep the fixed narrowed
31
- // view beside the source choices rather than allocating and scanning the same list in that hot path.
30
+ // The fixed narrowed view, kept beside the source choices rather than sliced on every render.
32
31
  const ONE_SHOT_PERMISSION_CHOICES = PERMISSION_CHOICES.slice(0, 2);
33
32
  /** The same shared controls, narrowed for requests whose scope can never become standing. */
34
33
  export function permissionChoices(allowAlways) {
@@ -117,6 +117,7 @@ function applyEvent(state, event, at) {
117
117
  ...(event.fromSessionId === undefined
118
118
  ? { text: event.text }
119
119
  : { text: event.text.slice(event.text.indexOf("\n") + 1), fromSessionId: event.fromSessionId }),
120
+ ...(event.note === undefined ? {} : { note: event.note }),
120
121
  ...(event.attachments === undefined ? {} : { attachments: event.attachments }),
121
122
  at,
122
123
  }),
@@ -2,7 +2,7 @@
2
2
  * How long ago something happened, for the "last updated" badge both front-ends show.
3
3
  *
4
4
  * Shared with the browser the same way the reducer is: types only, so stripping leaves standalone
5
- * ESM. The TUI and the web UI must agree about what "2h" means, and the only way to guarantee that
5
+ * ESM. Every front-end must agree about what "2h" means, and the only way to guarantee that
6
6
  * is for there to be one implementation.
7
7
  *
8
8
  * `now` is a parameter rather than a call to the clock so a frame renders the same way twice.
@@ -17,9 +17,8 @@ export function scopeKindLabel(scope) {
17
17
  * Why the checkout is a label and never a control.
18
18
  *
19
19
  * A Scope is fixed for an Agent Session's whole life, so there is no version of this someone could
20
- * change from here — a different directory is a different Agent Session. Exported as prose because
21
- * both front-ends want to say it: the web client as a tooltip, and it is the reason the TUI's
22
- * branch overlay offers no way to move between checkouts.
20
+ * change from here — a different directory is a different Agent Session. Exported as prose so the web
21
+ * client can say it as a tooltip.
23
22
  */
24
23
  export function scopeKindHint(scope) {
25
24
  return scope.worktree
@@ -4,7 +4,7 @@ import { editDiff } from "./diff.js";
4
4
  *
5
5
  * DOM-free deliberately rather than incidentally: `highlightSegments` returns segments and not
6
6
  * nodes, which is what keeps this module compiling under the root config's `lib: ["ES2023"]`, and so
7
- * what lets the TUI match the way the web UI matches instead of growing a second rule.
7
+ * what lets another front-end match the way the web UI matches instead of growing a second rule.
8
8
  *
9
9
  * Case-insensitive substring, and nothing else. No regex (a reader typing `(` into a filter box does
10
10
  * not mean a group) and no fuzzy matching (which finds things nobody asked for and hides the reason).
@@ -33,7 +33,7 @@ export function deriveStatus(of) {
33
33
  export function occupied(status) {
34
34
  return status === "running" || status === "awaiting";
35
35
  }
36
- export const RAIL_GROUPS = [
36
+ const RAIL_GROUPS = [
37
37
  "needs-input",
38
38
  "unread",
39
39
  "working",
@@ -2,7 +2,7 @@
2
2
  * Which Subagent spawned which, read from `producer` on each Subagent Entry.
3
3
  *
4
4
  * The transcript stays flat (ADR 0015), so the tree exists only here, built over keys at paint time.
5
- * DOM-free so the web client and the TUI share one rule.
5
+ * DOM-free so every front-end shares one rule.
6
6
  */
7
7
  const SUBAGENT_PREFIX = "subagent:";
8
8
  /** The key of the Entry a Subagent's own row uses, given the id its rows are attributed to. */
@@ -11,7 +11,7 @@
11
11
  * Keys alone answer this, the way `ownKeys` answers its own question: a tool Entry's key is
12
12
  * `tool:<id>` (`entryKey`), so no Entry is read and nothing here touches the DOM. Kept in
13
13
  * `src/client/` beside `diff.ts` and `tool-summary.ts` rather than in the web client's presentation
14
- * folder, because the TUI draws this same transcript and should not have to re-derive the rule.
14
+ * folder, because another front-end that draws this same transcript should not have to re-derive the rule.
15
15
  *
16
16
  * The caller passes the keys a reader can actually see — after `ownKeys`, after any search filter,
17
17
  * after the tail window — because a grouping can only honestly describe the list it was given.
@@ -2,9 +2,8 @@
2
2
  * A one-line précis of a tool call's arguments.
3
3
  *
4
4
  * A collapsed tool call that says only `[complete] Edit` withholds the one thing a reader wants —
5
- * which file, which command, which pattern. The TUI prints exactly that today (`render.ts:79`), so
6
- * this lives beside the reducer and stays DOM-free: it returns a string, and both front-ends can
7
- * print a string.
5
+ * which file, which command, which pattern. This lives beside the reducer and stays DOM-free: it
6
+ * returns a string, and any front-end can print a string.
8
7
  */
9
8
  /**
10
9
  * About a line in a narrow terminal, which is the tighter of the two front-ends. A précis that needs
@@ -62,6 +62,7 @@ export class ConfigStore {
62
62
  sandboxSupport = () => this.sandbox;
63
63
  /** Read when a sandbox-mode Backend Session starts. */
64
64
  sandboxSharing = () => this.config.sandboxSharing ?? "session";
65
+ updateSourceBranch = () => this.config.worktrees?.updateSource === true;
65
66
  updateChannel = () => this.config.updateChannel ?? "stable";
66
67
  /** The current Config, in the file's own units. Cheap: held in memory, not re-read. */
67
68
  current() {
@@ -218,6 +219,7 @@ function settingsOf(config) {
218
219
  ...(config.filesystemIsolation === undefined ? {} : { filesystemIsolation: config.filesystemIsolation }),
219
220
  ...(config.sandboxSharing === undefined ? {} : { sandboxSharing: config.sandboxSharing }),
220
221
  ...(config.updateChannel === undefined ? {} : { updateChannel: config.updateChannel }),
222
+ ...(config.worktrees === undefined ? {} : { worktrees: config.worktrees }),
221
223
  // Omitted rather than defaulted when there is no Project Root, which is what
222
224
  // `Settings["projects"]` being optional means — see src/protocol/settings.ts.
223
225
  ...(config.projects === undefined ? {} : { projects: config.projects }),
@@ -35,6 +35,7 @@ export function loadConfig(stateRoot) {
35
35
  const filesystemIsolation = readFilesystemIsolation(parsed, warnings);
36
36
  const sandboxSharing = readSandboxSharing(parsed, warnings);
37
37
  const updateChannel = readUpdateChannel(parsed, warnings);
38
+ const worktrees = readWorktrees(parsed, warnings);
38
39
  return {
39
40
  config: {
40
41
  retention,
@@ -44,6 +45,7 @@ export function loadConfig(stateRoot) {
44
45
  ...(updateChannel === undefined ? {} : { updateChannel }),
45
46
  mcp: readMcp(parsed, warnings),
46
47
  workflowRuntime: readWorkflowRuntime(parsed, warnings),
48
+ ...(worktrees === undefined ? {} : { worktrees }),
47
49
  ...(projects === undefined ? {} : { projects }),
48
50
  ...(permissions === undefined ? {} : { permissions }),
49
51
  ...(providers === undefined ? {} : { providers }),
@@ -145,6 +147,33 @@ function patchSandboxSharing(current, value) {
145
147
  throw new ConfigError('sandboxSharing must be "session" or "shared"');
146
148
  return value;
147
149
  }
150
+ const worktreeKeys = ["always", "updateSource"];
151
+ function readWorktrees(parsed, warnings) {
152
+ try {
153
+ return patchWorktrees(undefined, parsed?.worktrees);
154
+ }
155
+ catch (error) {
156
+ warnings.push(`${error.message}; using defaults`);
157
+ return undefined;
158
+ }
159
+ }
160
+ function patchWorktrees(current, value) {
161
+ if (value === undefined)
162
+ return current;
163
+ if (typeof value !== "object" || value === null || Array.isArray(value))
164
+ throw new ConfigError("worktrees must be an object");
165
+ refuseUnknownKeys(value, worktreeKeys, "worktrees");
166
+ const next = { ...current };
167
+ for (const key of worktreeKeys) {
168
+ const flag = value[key];
169
+ if (flag === undefined)
170
+ continue;
171
+ if (typeof flag !== "boolean")
172
+ throw new ConfigError(`worktrees.${key} must be true or false`);
173
+ next[key] = flag;
174
+ }
175
+ return next;
176
+ }
148
177
  const updateChannels = ["stable", "beta"];
149
178
  function readUpdateChannel(parsed, warnings) {
150
179
  const value = parsed?.updateChannel;
@@ -443,19 +472,21 @@ export function applyPatch(current, patch) {
443
472
  throw new ConfigError("expected an object");
444
473
  }
445
474
  const body = patch;
446
- refuseUnknownKeys(body, ["retention", "fonts", "projects", "permissions", "providers", "workflowRuntime", "mcp", "filesystemIsolation", "sandboxSharing", "updateChannel"], "config");
475
+ refuseUnknownKeys(body, ["retention", "fonts", "projects", "permissions", "providers", "workflowRuntime", "mcp", "filesystemIsolation", "sandboxSharing", "updateChannel", "worktrees"], "config");
447
476
  const projects = patchProjects(current.projects, body.projects);
448
477
  const permissions = patchPermissions(current.permissions, body.permissions);
449
478
  const providers = patchProviders(current.providers, body.providers);
450
479
  const filesystemIsolation = patchFilesystemIsolation(current.filesystemIsolation, body.filesystemIsolation);
451
480
  const sandboxSharing = patchSandboxSharing(current.sandboxSharing, body.sandboxSharing);
452
481
  const updateChannel = patchUpdateChannel(current.updateChannel, body.updateChannel);
482
+ const worktrees = patchWorktrees(current.worktrees, body.worktrees);
453
483
  return {
454
484
  ...(filesystemIsolation === undefined ? {} : { filesystemIsolation }),
455
485
  ...(sandboxSharing === undefined ? {} : { sandboxSharing }),
456
486
  ...(updateChannel === undefined ? {} : { updateChannel }),
457
487
  mcp: body.mcp === undefined ? current.mcp ?? [] : parseMcp(body.mcp),
458
488
  workflowRuntime: patchWorkflowRuntime(current.workflowRuntime, body.workflowRuntime),
489
+ ...(worktrees === undefined ? {} : { worktrees }),
459
490
  retention: { settled: patchRetention(current.retention.settled, body.retention) },
460
491
  fonts: patchFonts(current.fonts, body.fonts),
461
492
  ...(projects === undefined ? {} : { projects }),
@@ -237,8 +237,7 @@ function candidate(base, attempt) {
237
237
  *
238
238
  * A name the reader supplied is never bumped. Someone who typed a name and got a different one has
239
239
  * been ignored, so an existing ref is a failure carrying git's own conclusion; bumping exists only
240
- * for the derived name, and only because the TUI never types and would otherwise be stuck on the
241
- * second worktree of the day.
240
+ * for the derived name, which would otherwise be stuck on the second worktree of the day.
242
241
  */
243
242
  export async function planWorktree(options) {
244
243
  const { repo, from, under } = options;
@@ -297,6 +296,38 @@ export async function createWorktree(options) {
297
296
  return added;
298
297
  return { ok: true, value: planned.value };
299
298
  }
299
+ /**
300
+ * Fast-forward the Source Branch `branch` in the Project `repo` to its upstream.
301
+ *
302
+ * Only a fast-forward: git refuses a diverged branch, and refuses to move a branch that is
303
+ * checked out in a linked worktree, so nothing local is ever lost.
304
+ */
305
+ export async function updateSourceBranch(repo, branch) {
306
+ const upstream = await run(repo, ["rev-parse", "--symbolic-full-name", `${branch}@{upstream}`], GIT_READ_TIMEOUT_MS);
307
+ if (!upstream.ok)
308
+ return upstream;
309
+ const remote = await run(repo, ["config", "--get", `branch.${branch}.remote`], GIT_READ_TIMEOUT_MS);
310
+ if (!remote.ok)
311
+ return remote;
312
+ const fetched = await run(repo, ["fetch", "--quiet", remote.value.trim()], GIT_WRITE_TIMEOUT_MS);
313
+ if (!fetched.ok)
314
+ return fetched;
315
+ const target = upstream.value.trim();
316
+ const contained = await run(repo, ["merge-base", "--is-ancestor", target, `refs/heads/${branch}`], GIT_READ_TIMEOUT_MS);
317
+ if (contained.ok)
318
+ return { ok: true, value: undefined };
319
+ if (contained.failure.code !== 1)
320
+ return contained;
321
+ const current = await head(repo);
322
+ if (!current.ok)
323
+ return current;
324
+ const updated = !current.value.detached && current.value.name === branch
325
+ ? await run(repo, ["merge", "--ff-only", "--quiet", target], GIT_WRITE_TIMEOUT_MS)
326
+ : await run(repo, ["fetch", ".", `${target}:refs/heads/${branch}`], GIT_WRITE_TIMEOUT_MS);
327
+ if (!updated.ok)
328
+ return updated;
329
+ return { ok: true, value: undefined };
330
+ }
300
331
  export async function removeMergedBranch(repo, branch, from) {
301
332
  if (from === undefined) {
302
333
  const target = await head(repo);
@@ -7,7 +7,7 @@ import { copyFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
7
7
  import { isAbsolute, join, resolve } from "node:path";
8
8
  import { validateFilesystemScope } from "../isolation/filesystem.js";
9
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";
10
+ import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage, mergeableStack, stackMergeMethods } from "./stack.js";
11
11
  import { changes, changesText, commitContext, diff } from "./changes.js";
12
12
  import { commit } from "./commit.js";
13
13
  import { push, pushState } from "./push.js";
@@ -18,7 +18,7 @@ import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_AT
18
18
  import { deriveStatus, railGroupRank } from "../client/status.js";
19
19
  // `switchBranch` is aliased because this class has a method of that name: the method is the
20
20
  // 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, switchBranch as gitSwitchBranch, } from "./git.js";
21
+ import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, updateSourceBranch, switchBranch as gitSwitchBranch, } from "./git.js";
22
22
  import { SessionLog } from "./log.js";
23
23
  import { probeModels } from "./models.js";
24
24
  import { PiModelProbeCache } from "./pi-model-cache.js";
@@ -115,7 +115,7 @@ export class SessionHost {
115
115
  }
116
116
  }
117
117
  async prepareStack(sessionId, action) {
118
- if (action !== "submit" && action !== "sync")
118
+ if (action !== "submit" && action !== "sync" && action !== "merge")
119
119
  throw new CommandRefused("Invalid Stack review action.");
120
120
  const record = this.record(sessionId);
121
121
  return this.withGitOperation(record.scope, async () => {
@@ -124,19 +124,28 @@ export class SessionHost {
124
124
  const status = await stackStatus(record.scope);
125
125
  if (!status.view)
126
126
  throw new Error(status.notice ?? "This branch is not in a stack.");
127
+ const fingerprint = await stackFingerprint(record.scope, status.view, action === "sync");
127
128
  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 });
129
+ if (action === "merge") {
130
+ review.view = await mergeableStack(record.scope);
131
+ review.mergeMethods = await stackMergeMethods(record.scope, review.view);
132
+ if (!review.mergeMethods.length)
133
+ throw new Error("You cannot merge pull requests in this repository.");
134
+ }
135
+ this.stackReviews.set(sessionId, { review, fingerprint, expires: Date.now() + 15 * 60_000 });
129
136
  return review;
130
137
  });
131
138
  }
132
139
  async changeStack(sessionId, input) {
133
140
  const record = this.record(sessionId);
134
141
  return this.withGitOperation(record.scope, async () => {
135
- if (input.action === "submit" || input.action === "sync") {
142
+ if (input.action === "submit" || input.action === "sync" || input.action === "merge") {
136
143
  const saved = this.stackReviews.get(sessionId);
137
144
  this.stackReviews.delete(sessionId);
138
145
  if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
139
146
  throw new Error("This Stack review expired. Review again.");
147
+ if (input.action === "merge" && !saved.review.mergeMethods?.includes(input.method))
148
+ throw new Error("This repository does not permit that merge method.");
140
149
  await cleanStack(record.scope);
141
150
  const status = await stackStatus(record.scope);
142
151
  if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
@@ -332,6 +341,7 @@ export class SessionHost {
332
341
  filesystemIsolation;
333
342
  sandbox;
334
343
  sandboxSharing;
344
+ updateSourceBranch;
335
345
  shared;
336
346
  mcpConnections;
337
347
  mcpAuth;
@@ -340,6 +350,7 @@ export class SessionHost {
340
350
  this.filesystemIsolation = options.filesystemIsolationMode;
341
351
  this.sandbox = options.sandboxSupport;
342
352
  this.sandboxSharing = options.sandboxSharing;
353
+ this.updateSourceBranch = options.updateSourceBranch;
343
354
  this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
344
355
  this.mcpConnections = options.mcpConnections;
345
356
  this.mcpAuth = options.mcpAuth;
@@ -795,7 +806,8 @@ export class SessionHost {
795
806
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
796
807
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
797
808
  this.validatePermissionMode(backend.name, permissionMode);
798
- const worktree = options.scheduled?.worktree ?? (options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined);
809
+ const cut = options.scheduled?.worktree || !options.worktree ? undefined : await this.cutWorktree(options.scope, options.worktree);
810
+ const worktree = options.scheduled?.worktree ?? cut?.worktree;
799
811
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
800
812
  // exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
801
813
  // that is not there.
@@ -892,6 +904,8 @@ export class SessionHost {
892
904
  if (options.fork)
893
905
  this.appendForkPrefix(record, options.fork.source.id, options.fork.userMessageId, options.fork.prefix);
894
906
  this.flushBuffered(record);
907
+ if (cut?.warning)
908
+ record.log.append({ type: "notice", level: "warn", text: cut.warning });
895
909
  // After session_started, never before: the transcript has to open with it (see `buffered`).
896
910
  await this.refreshBranch(record);
897
911
  /*
@@ -956,6 +970,7 @@ export class SessionHost {
956
970
  throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
957
971
  if (!isRepository(repo))
958
972
  throw new CommandRefused(`${repo} is not a git repository`);
973
+ const updated = this.updateSourceBranch?.() ? await updateSourceBranch(repo, options.from) : undefined;
959
974
  const created = await createWorktree({
960
975
  repo,
961
976
  from: options.from,
@@ -964,7 +979,10 @@ export class SessionHost {
964
979
  });
965
980
  if (!created.ok)
966
981
  throw new CommandRefused(created.failure.message);
967
- return { path: created.value.path, repo, branch: created.value.branch };
982
+ return {
983
+ worktree: { path: created.value.path, repo, branch: created.value.branch },
984
+ ...(updated?.ok === false ? { warning: `Source Branch ${options.from} was not updated, so the Worktree was cut from the local branch: ${updated.failure.message}` } : {}),
985
+ };
968
986
  }
969
987
  /** Attach a fresh Backend Session to a Dormant Agent Session, continuing the same transcript. */
970
988
  async revive(sessionId) {
@@ -2940,7 +2958,8 @@ export class SessionHost {
2940
2958
  record.log.append({
2941
2959
  type: "user_message",
2942
2960
  id: messageId,
2943
- text: sent,
2961
+ text,
2962
+ ...(note === undefined ? {} : { note }),
2944
2963
  ...(attachments.length > 0 ? { attachments } : {}),
2945
2964
  ...(fromSessionId === undefined ? {} : { fromSessionId }),
2946
2965
  });
@@ -1,5 +1,5 @@
1
1
  import { api, connection, gh, page } from "./github.js";
2
- import { githubRepository, localRepository, resolvePullRequest, resolveRepository } from "./repository.js";
2
+ import { githubRepository, localRepository, mergeMethods, mergeSettingsFields, resolvePullRequest, resolveRepository, writers } from "./repository.js";
3
3
  import { cleanStack } from "./stack.js";
4
4
  import { pushTarget, remoteHead } from "./push.js";
5
5
  import { localStack, stackParent } from "./stack-metadata.js";
@@ -8,8 +8,7 @@ const commentFields = "id author{login} body url createdAt";
8
8
  const threadFields = "id path line isOutdated isResolved viewerCanReply viewerCanResolve viewerCanUnresolve";
9
9
  const threadCommentFields = `${commentFields} diffHunk`;
10
10
  const checkFields = "... on CheckRun{name status conclusion detailsUrl} ... on StatusContext{context state targetUrl}";
11
- const detailsQuery = `query($id:ID!){node(id:$id){... on PullRequest{id number url title body state isDraft reviewDecision updatedAt author{login} headRefName headRefOid headRepository{id nameWithOwner} baseRefName mergeable mergeStateStatus locked repository{isArchived viewerPermission mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed} comments(first:100){nodes{${commentFields}} ${page}} reviews(first:100){nodes{${commentFields} state} ${page}} reviewThreads(first:100){nodes{${threadFields} comments(first:100){nodes{${threadCommentFields}} ${page}}} ${page}} commits(last:1){nodes{commit{statusCheckRollup{id contexts(first:100){nodes{${checkFields}} ${page}}}}}}}}}`;
12
- const writers = ["ADMIN", "MAINTAIN", "WRITE"];
11
+ const detailsQuery = `query($id:ID!){node(id:$id){... on PullRequest{id number url title body state isDraft reviewDecision updatedAt author{login} headRefName headRefOid headRepository{id nameWithOwner} baseRefName mergeable mergeStateStatus locked repository{${mergeSettingsFields}} comments(first:100){nodes{${commentFields}} ${page}} reviews(first:100){nodes{${commentFields} state} ${page}} reviewThreads(first:100){nodes{${threadFields} comments(first:100){nodes{${threadCommentFields}} ${page}}} ${page}} commits(last:1){nodes{commit{statusCheckRollup{id contexts(first:100){nodes{${checkFields}} ${page}}}}}}}}}`;
13
12
  const comment = (value) => ({ ...value, author: value.author?.login ?? "[deleted]" });
14
13
  function check(node) {
15
14
  const url = node.detailsUrl || node.targetUrl || "";
@@ -28,14 +27,8 @@ async function details(scope, ref, github) {
28
27
  threads.push({ ...thread, diffHunk: all[0]?.diffHunk ?? "", comments: all.map(comment) });
29
28
  }
30
29
  const rollup = commits.nodes[0]?.commit.statusCheckRollup;
31
- const writer = !repository.isArchived && writers.includes(repository.viewerPermission ?? "");
32
- const mergeMethods = !writer ? [] : [
33
- ...(repository.mergeCommitAllowed ? ["MERGE"] : []),
34
- ...(repository.squashMergeAllowed ? ["SQUASH"] : []),
35
- ...(repository.rebaseMergeAllowed ? ["REBASE"] : []),
36
- ];
37
30
  return { headRepositoryId: headRepository?.id, pr: {
38
- ...fields, repo: ref.repo, author: author?.login ?? "[deleted]", mergeMethods,
31
+ ...fields, repo: ref.repo, author: author?.login ?? "[deleted]", mergeMethods: mergeMethods(repository),
39
32
  ...(headRepository ? { headRepository: headRepository.nameWithOwner } : {}),
40
33
  viewerCanComment: !repository.isArchived && (!locked || writers.includes(repository.viewerPermission ?? "")),
41
34
  comments: (await connection(scope, github, comments, id, "PullRequest", "comments", commentFields)).map(comment),