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

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/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/relative-time.js +1 -1
  11. package/dist/client/scope-kind.js +2 -3
  12. package/dist/client/search.js +1 -1
  13. package/dist/client/status.js +1 -1
  14. package/dist/client/subagent-tree.js +1 -1
  15. package/dist/client/tool-chains.js +1 -1
  16. package/dist/client/tool-summary.js +2 -3
  17. package/dist/daemon/config-store.js +2 -0
  18. package/dist/daemon/config.js +32 -1
  19. package/dist/daemon/git.js +33 -2
  20. package/dist/daemon/host.js +12 -3
  21. package/dist/daemon/runtime.js +1 -1
  22. package/dist/daemon/server.js +2 -2
  23. package/dist/daemon/workflow-schedule-driver.js +5 -1
  24. package/dist/workflows/schedules.js +1 -0
  25. package/package.json +1 -1
  26. package/web/dist/assets/index-5E7qbtVD.js +51 -0
  27. package/web/dist/assets/{switch-B00FEUA7.js → select-C-BND5Jn.js} +1 -1
  28. package/web/dist/assets/{settings-mcp-3cgqQB28.js → settings-mcp-CBXZt_cf.js} +1 -1
  29. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-29ZG3w6p.js} +1 -1
  30. package/web/dist/assets/{settings-workflows-Cutm8isB.js → settings-workflows-CE11fxNj.js} +2 -2
  31. package/web/dist/assets/workflow-api-DkUjAZ4w.js +6 -0
  32. package/web/dist/assets/{workflows-D6oEUUhj.js → workflows-DdogjBu3.js} +5 -5
  33. package/web/dist/assets/{workflows-pane-KIdSDKJB.js → workflows-pane-B0dyuSuz.js} +1 -1
  34. package/web/dist/index.html +4 -4
  35. package/dist/tui/app.js +0 -612
  36. package/dist/tui/keys.js +0 -90
  37. package/dist/tui/render.js +0 -417
  38. package/web/dist/assets/index-BhfJhrVJ.js +0 -51
  39. 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
+ 8ab6f68e-a8d0-4e4f-a520-68e8a0b6b031
@@ -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("8ab6f68e-a8d0-4e4f-a520-68e8a0b6b031", 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) {
@@ -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);
@@ -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";
@@ -332,6 +332,7 @@ export class SessionHost {
332
332
  filesystemIsolation;
333
333
  sandbox;
334
334
  sandboxSharing;
335
+ updateSourceBranch;
335
336
  shared;
336
337
  mcpConnections;
337
338
  mcpAuth;
@@ -340,6 +341,7 @@ export class SessionHost {
340
341
  this.filesystemIsolation = options.filesystemIsolationMode;
341
342
  this.sandbox = options.sandboxSupport;
342
343
  this.sandboxSharing = options.sandboxSharing;
344
+ this.updateSourceBranch = options.updateSourceBranch;
343
345
  this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
344
346
  this.mcpConnections = options.mcpConnections;
345
347
  this.mcpAuth = options.mcpAuth;
@@ -795,7 +797,8 @@ export class SessionHost {
795
797
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
796
798
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
797
799
  this.validatePermissionMode(backend.name, permissionMode);
798
- const worktree = options.scheduled?.worktree ?? (options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined);
800
+ const cut = options.scheduled?.worktree || !options.worktree ? undefined : await this.cutWorktree(options.scope, options.worktree);
801
+ const worktree = options.scheduled?.worktree ?? cut?.worktree;
799
802
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
800
803
  // exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
801
804
  // that is not there.
@@ -892,6 +895,8 @@ export class SessionHost {
892
895
  if (options.fork)
893
896
  this.appendForkPrefix(record, options.fork.source.id, options.fork.userMessageId, options.fork.prefix);
894
897
  this.flushBuffered(record);
898
+ if (cut?.warning)
899
+ record.log.append({ type: "notice", level: "warn", text: cut.warning });
895
900
  // After session_started, never before: the transcript has to open with it (see `buffered`).
896
901
  await this.refreshBranch(record);
897
902
  /*
@@ -956,6 +961,7 @@ export class SessionHost {
956
961
  throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
957
962
  if (!isRepository(repo))
958
963
  throw new CommandRefused(`${repo} is not a git repository`);
964
+ const updated = this.updateSourceBranch?.() ? await updateSourceBranch(repo, options.from) : undefined;
959
965
  const created = await createWorktree({
960
966
  repo,
961
967
  from: options.from,
@@ -964,7 +970,10 @@ export class SessionHost {
964
970
  });
965
971
  if (!created.ok)
966
972
  throw new CommandRefused(created.failure.message);
967
- return { path: created.value.path, repo, branch: created.value.branch };
973
+ return {
974
+ worktree: { path: created.value.path, repo, branch: created.value.branch },
975
+ ...(updated?.ok === false ? { warning: `Source Branch ${options.from} was not updated, so the Worktree was cut from the local branch: ${updated.failure.message}` } : {}),
976
+ };
968
977
  }
969
978
  /** Attach a fresh Backend Session to a Dormant Agent Session, continuing the same transcript. */
970
979
  async revive(sessionId) {
@@ -49,7 +49,7 @@ export async function startRuntime(options) {
49
49
  store, resolveSecret: name => secrets.resolve(name), retention: config.retention,
50
50
  mcpConnections: config.mcpConnections, mcpAuth,
51
51
  filesystemIsolationMode: config.filesystemIsolationMode, sandboxSupport: config.sandboxSupport,
52
- sandboxSharing: config.sandboxSharing, projectRoot: config.projectRoot,
52
+ sandboxSharing: config.sandboxSharing, updateSourceBranch: config.updateSourceBranch, projectRoot: config.projectRoot,
53
53
  standingAuthorisations: config.standingAuthorisations, allowTool: config.allowTool,
54
54
  defaultBackend: config.defaultBackend, defaultModel: config.defaultModel,
55
55
  defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel, tourModel: config.tourModel,
@@ -959,7 +959,7 @@ function streamEvents(response, host, sessionId, since, oidc, browserSessionId)
959
959
  detachAuth?.();
960
960
  });
961
961
  }
962
- /** Bearer access is deliberately independent of OIDC so remote CLI/TUI clients keep working. */
962
+ /** Bearer access is deliberately independent of OIDC so remote CLI clients keep working. */
963
963
  async function authenticateRequest(request, options) {
964
964
  if (tokenMatches(options.token, presentedBearer(request)))
965
965
  return { kind: "bearer" };
@@ -1021,7 +1021,7 @@ a{display:inline-flex;align-items:center;justify-content:center;width:100%;heigh
1021
1021
  response.end(html);
1022
1022
  }
1023
1023
  /**
1024
- * Same-origin only. A request with no Origin header is a non-browser client (the TUI, curl), which
1024
+ * Same-origin only. A request with no Origin header is a non-browser client (the CLI, curl), which
1025
1025
  * a hostile page cannot forge on the user's behalf, so it is not what this check defends against.
1026
1026
  */
1027
1027
  function originAllowed(request, publicAppUrl) {
@@ -7,7 +7,7 @@ import { ScheduledExecutionStarted } from './workflow-schedules.js';
7
7
  import { resolveWorkflowCalls } from '../workflows/calls.js';
8
8
  import { ScheduleValidationError } from '../workflows/schedule-errors.js';
9
9
  import { includedProjects } from './projects.js';
10
- import { isClean, localBranches, planWorktree, removeMergedBranch, removeWorktree, run, GIT_WRITE_TIMEOUT_MS } from './git.js';
10
+ import { isClean, localBranches, planWorktree, removeMergedBranch, removeWorktree, run, updateSourceBranch, GIT_WRITE_TIMEOUT_MS } from './git.js';
11
11
  export function scheduleDriver(options) {
12
12
  const { host, config, workflows, executions, schedules, transcripts } = options;
13
13
  const repositories = new Map();
@@ -164,6 +164,10 @@ export function scheduleDriver(options) {
164
164
  const provision = previous.catch(() => { }).then(async () => {
165
165
  signal?.throwIfAborted();
166
166
  const from = occurrence.settings.worktree.from;
167
+ if (config.updateSourceBranch() && !(await updateSourceBranch(repo, from)).ok) {
168
+ occurrence = { ...occurrence, warning: 'Source Branch not updated; cut from the local branch.' };
169
+ }
170
+ signal?.throwIfAborted();
167
171
  const planned = await planWorktree({ repo, from, branch: `flow/schedule-${occurrence.id}`, under: transcripts.worktreesRoot() });
168
172
  if (!planned.ok)
169
173
  throw new Error('Could not plan worktree');
@@ -44,6 +44,7 @@ export const occurrenceValidator = z.object({
44
44
  createdAt: timestamp, finishedAt: timestamp.optional(), sessionId: storageId.optional(), association: z.enum(['pending', 'attached', 'failed']).optional(), executionId: storageId.optional(),
45
45
  scope: z.string().min(1).optional(), worktree: z.object({ path: z.string(), repo: z.string(), branch: z.string() }).strict().optional(),
46
46
  outcome: z.string().max(2000).optional(),
47
+ warning: z.string().max(2000).optional(),
47
48
  }).strict().superRefine((value, context) => {
48
49
  if (value.id !== occurrenceId(value.scheduleId, value.activation, value.scheduledAt))
49
50
  context.addIssue({ code: 'custom', message: 'Invalid occurrence identity' });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathanstephenson/flow",
3
- "version": "0.1.10-beta.6",
3
+ "version": "0.1.10-beta.7",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",