@nathanstephenson/flow 0.1.10-beta.5 → 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 (67) hide show
  1. package/README.md +5 -19
  2. package/build/backend-worker-chunks/{chunk-JOI2POLP.mjs → chunk-U73G6KK4.mjs} +18 -0
  3. package/build/backend-worker-chunks/{claude-GY27HBAY.mjs → claude-THGSOTC2.mjs} +7 -1
  4. package/build/backend-worker-chunks/{pi-JV6MWPW7.mjs → pi-5LAWIJNE.mjs} +82 -3
  5. package/build/backend-worker.mjs +7 -3
  6. package/dist/backend/claude/index.js +6 -0
  7. package/dist/backend/fake/index.js +6 -0
  8. package/dist/backend/pi/index.js +34 -2
  9. package/dist/backend/pi/plan-limits.js +41 -0
  10. package/dist/backend/plan-limits.js +17 -0
  11. package/dist/backend/worker/entry.js +4 -1
  12. package/dist/backend/worker/index.js +5 -0
  13. package/dist/backend/worker/protocol.js +2 -1
  14. package/dist/build-id +1 -1
  15. package/dist/cli/application.js +4 -37
  16. package/dist/cli/bootstrap.js +2 -2
  17. package/dist/cli/install-guard.js +1 -1
  18. package/dist/client/context-usage.js +3 -4
  19. package/dist/client/enquiry.js +0 -6
  20. package/dist/client/markdown.js +3 -2
  21. package/dist/client/model-choices.js +1 -1
  22. package/dist/client/permission.js +1 -2
  23. package/dist/client/relative-time.js +1 -1
  24. package/dist/client/scope-kind.js +2 -3
  25. package/dist/client/search.js +1 -1
  26. package/dist/client/status.js +1 -1
  27. package/dist/client/subagent-tree.js +1 -1
  28. package/dist/client/tool-chains.js +1 -1
  29. package/dist/client/tool-summary.js +2 -3
  30. package/dist/daemon/config-store.js +3 -0
  31. package/dist/daemon/config.js +63 -3
  32. package/dist/daemon/git.js +33 -2
  33. package/dist/daemon/github-image.js +18 -0
  34. package/dist/daemon/host.js +159 -9
  35. package/dist/daemon/runtime.js +2 -2
  36. package/dist/daemon/server.js +28 -2
  37. package/dist/daemon/skills.js +24 -0
  38. package/dist/daemon/spend-ledger.js +118 -0
  39. package/dist/daemon/summariser.js +11 -4
  40. package/dist/daemon/tour.js +42 -0
  41. package/dist/daemon/workflow-builder.js +3 -1
  42. package/dist/daemon/workflow-execution-resources.js +1 -1
  43. package/dist/daemon/workflow-routes.js +19 -0
  44. package/dist/daemon/workflow-schedule-driver.js +5 -1
  45. package/dist/daemon/workflow-schedules.js +6 -5
  46. package/dist/protocol/plan-limits.js +1 -0
  47. package/dist/protocol/spend.js +2 -0
  48. package/dist/workflows/scheduler.js +26 -14
  49. package/dist/workflows/schedules.js +1 -0
  50. package/dist/workflows/store.js +16 -2
  51. package/package.json +1 -1
  52. package/web/dist/assets/index-5E7qbtVD.js +51 -0
  53. package/web/dist/assets/index-BvkM2cWL.css +2 -0
  54. package/web/dist/assets/{switch-B00FEUA7.js → select-C-BND5Jn.js} +1 -1
  55. package/web/dist/assets/{settings-mcp-BwOPXAfH.js → settings-mcp-CBXZt_cf.js} +1 -1
  56. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-29ZG3w6p.js} +1 -1
  57. package/web/dist/assets/{settings-workflows-DocTa31_.js → settings-workflows-CE11fxNj.js} +2 -2
  58. package/web/dist/assets/workflow-api-DkUjAZ4w.js +6 -0
  59. package/web/dist/assets/{workflows-DJqUuGyg.js → workflows-DdogjBu3.js} +6 -6
  60. package/web/dist/assets/{workflows-pane-oM1fO_BC.js → workflows-pane-B0dyuSuz.js} +1 -1
  61. package/web/dist/index.html +5 -5
  62. package/dist/tui/app.js +0 -612
  63. package/dist/tui/keys.js +0 -90
  64. package/dist/tui/render.js +0 -417
  65. package/web/dist/assets/index-BqZ_iUmY.css +0 -2
  66. package/web/dist/assets/index-CxdSb7k0.js +0 -51
  67. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
@@ -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("c0812b29-3bd1-4f02-be7b-5147006e3476", 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)
@@ -43,7 +42,7 @@ export function contextUsageDetail(usage) {
43
42
  * cent, and rounding that to `$0.00` would report free work. Anything at or above a cent reads in
44
43
  * the two places money is normally written.
45
44
  */
46
- function money(usd) {
45
+ export function money(usd) {
47
46
  if (usd >= 0.01)
48
47
  return `$${usd.toFixed(2)}`;
49
48
  if (usd === 0)
@@ -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
  *
@@ -156,12 +156,13 @@ function toImage(href, alt, raw, options) {
156
156
  if (!src || !/^https?:\/\//i.test(src))
157
157
  return { kind: "text", text: raw };
158
158
  const url = new URL(src);
159
- const blob = /^\/([^/]+)\/([^/]+)\/blob\/(.+)$/.exec(url.pathname);
159
+ const blob = /^\/([^/]+)\/([^/]+)\/(?:blob|raw)\/(.+)$/.exec(url.pathname);
160
160
  if (url.hostname === "github.com" && blob) {
161
161
  url.hostname = "raw.githubusercontent.com";
162
162
  url.pathname = `/${blob[1]}/${blob[2]}/${blob[3]}`;
163
163
  }
164
- return { kind: "image", src: url.href, alt };
164
+ const github = url.hostname === "raw.githubusercontent.com" || (url.hostname === "github.com" && url.pathname.startsWith("/user-attachments/assets/"));
165
+ return { kind: "image", src: options.imageProxy && github ? `${options.imageProxy}${encodeURIComponent(url.href)}` : url.href, alt };
165
166
  }
166
167
  function htmlImages(text, options) {
167
168
  const tags = text.match(/<img\b(?:[^"'<>]|"[^"]*"|'[^']*')*\/?>/gi);
@@ -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() {
@@ -131,6 +132,7 @@ export class ConfigStore {
131
132
  return { backend, ...summary };
132
133
  return providers?.summary?.backend === backend ? providers.summary : undefined;
133
134
  };
135
+ tourModel = (backend) => this.config.providers?.tours?.[backend];
134
136
  defaultPermissionMode = (backend) => this.config.providers?.permissionModes?.[backend];
135
137
  defaultEffort = (backend) => this.config.providers?.efforts?.[backend];
136
138
  /**
@@ -217,6 +219,7 @@ function settingsOf(config) {
217
219
  ...(config.filesystemIsolation === undefined ? {} : { filesystemIsolation: config.filesystemIsolation }),
218
220
  ...(config.sandboxSharing === undefined ? {} : { sandboxSharing: config.sandboxSharing }),
219
221
  ...(config.updateChannel === undefined ? {} : { updateChannel: config.updateChannel }),
222
+ ...(config.worktrees === undefined ? {} : { worktrees: config.worktrees }),
220
223
  // Omitted rather than defaulted when there is no Project Root, which is what
221
224
  // `Settings["projects"]` being optional means — see src/protocol/settings.ts.
222
225
  ...(config.projects === undefined ? {} : { projects: config.projects }),
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT, defaultFonts, } from "../protocol/fonts.js";
5
5
  import { DEFAULT_WORKFLOW_RUNTIME, formatDuration, parseDuration, } from "../protocol/settings.js";
6
+ import { EFFORT_ORDER } from "../backend/effort.js";
6
7
  export { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT };
7
8
  export { formatDuration, parseDuration };
8
9
  export const DEFAULT_SETTLED_RETENTION = 24 * 60 * 60 * 1000;
@@ -34,6 +35,7 @@ export function loadConfig(stateRoot) {
34
35
  const filesystemIsolation = readFilesystemIsolation(parsed, warnings);
35
36
  const sandboxSharing = readSandboxSharing(parsed, warnings);
36
37
  const updateChannel = readUpdateChannel(parsed, warnings);
38
+ const worktrees = readWorktrees(parsed, warnings);
37
39
  return {
38
40
  config: {
39
41
  retention,
@@ -43,6 +45,7 @@ export function loadConfig(stateRoot) {
43
45
  ...(updateChannel === undefined ? {} : { updateChannel }),
44
46
  mcp: readMcp(parsed, warnings),
45
47
  workflowRuntime: readWorkflowRuntime(parsed, warnings),
48
+ ...(worktrees === undefined ? {} : { worktrees }),
46
49
  ...(projects === undefined ? {} : { projects }),
47
50
  ...(permissions === undefined ? {} : { permissions }),
48
51
  ...(providers === undefined ? {} : { providers }),
@@ -144,6 +147,33 @@ function patchSandboxSharing(current, value) {
144
147
  throw new ConfigError('sandboxSharing must be "session" or "shared"');
145
148
  return value;
146
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
+ }
147
177
  const updateChannels = ["stable", "beta"];
148
178
  function readUpdateChannel(parsed, warnings) {
149
179
  const value = parsed?.updateChannel;
@@ -214,7 +244,7 @@ function parseProviders(parsed, warnings) {
214
244
  };
215
245
  }
216
246
  }
217
- for (const field of ["efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"]) {
247
+ for (const field of ["efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"]) {
218
248
  const entries = section[field];
219
249
  if (entries === undefined)
220
250
  continue;
@@ -442,19 +472,21 @@ export function applyPatch(current, patch) {
442
472
  throw new ConfigError("expected an object");
443
473
  }
444
474
  const body = patch;
445
- 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");
446
476
  const projects = patchProjects(current.projects, body.projects);
447
477
  const permissions = patchPermissions(current.permissions, body.permissions);
448
478
  const providers = patchProviders(current.providers, body.providers);
449
479
  const filesystemIsolation = patchFilesystemIsolation(current.filesystemIsolation, body.filesystemIsolation);
450
480
  const sandboxSharing = patchSandboxSharing(current.sandboxSharing, body.sandboxSharing);
451
481
  const updateChannel = patchUpdateChannel(current.updateChannel, body.updateChannel);
482
+ const worktrees = patchWorktrees(current.worktrees, body.worktrees);
452
483
  return {
453
484
  ...(filesystemIsolation === undefined ? {} : { filesystemIsolation }),
454
485
  ...(sandboxSharing === undefined ? {} : { sandboxSharing }),
455
486
  ...(updateChannel === undefined ? {} : { updateChannel }),
456
487
  mcp: body.mcp === undefined ? current.mcp ?? [] : parseMcp(body.mcp),
457
488
  workflowRuntime: patchWorkflowRuntime(current.workflowRuntime, body.workflowRuntime),
489
+ ...(worktrees === undefined ? {} : { worktrees }),
458
490
  retention: { settled: patchRetention(current.retention.settled, body.retention) },
459
491
  fonts: patchFonts(current.fonts, body.fonts),
460
492
  ...(projects === undefined ? {} : { projects }),
@@ -477,7 +509,7 @@ export function applyPatch(current, patch) {
477
509
  function patchProviders(current, patch) {
478
510
  if (patch === undefined)
479
511
  return current;
480
- refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"], "providers");
512
+ refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"], "providers");
481
513
  const next = {
482
514
  ...(current?.autoCompaction === undefined ? {} : { autoCompaction: { ...current.autoCompaction } }),
483
515
  ...(current?.compactionModels === undefined ? {} : { compactionModels: { ...current.compactionModels } }),
@@ -485,6 +517,7 @@ function patchProviders(current, patch) {
485
517
  ...(current?.efforts === undefined ? {} : { efforts: { ...current.efforts } }),
486
518
  ...(current?.permissionModes === undefined ? {} : { permissionModes: { ...current.permissionModes } }),
487
519
  ...(current?.summaries === undefined ? {} : { summaries: { ...current.summaries } }),
520
+ ...(current?.tours === undefined ? {} : { tours: { ...current.tours } }),
488
521
  ...(current?.defaults === undefined ? {} : { defaults: { ...current.defaults } }),
489
522
  ...(current?.summary === undefined ? {} : { summary: current.summary }),
490
523
  };
@@ -599,6 +632,33 @@ function patchProviders(current, patch) {
599
632
  };
600
633
  }
601
634
  }
635
+ if (patch.tours !== undefined) {
636
+ const entries = patch.tours;
637
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries))
638
+ throw new ConfigError("providers.tours must be an object");
639
+ const tours = { ...next.tours };
640
+ for (const [backend, value] of Object.entries(entries)) {
641
+ const field = `providers.tours.${backend}`;
642
+ if (value === null) {
643
+ delete tours[backend];
644
+ continue;
645
+ }
646
+ if (typeof value !== "object" || Array.isArray(value))
647
+ throw new ConfigError(`${field} must name a model and an effort`);
648
+ refuseUnknownKeys(value, ["modelId", "effort"], field);
649
+ const named = value;
650
+ const problem = checkModelId(named.modelId, `${field}.modelId`);
651
+ if (problem)
652
+ throw new ConfigError(problem);
653
+ if (!EFFORT_ORDER.includes(named.effort))
654
+ throw new ConfigError(`${field}.effort must be a valid effort`);
655
+ tours[backend] = { modelId: named.modelId.trim(), effort: named.effort };
656
+ }
657
+ if (Object.keys(tours).length)
658
+ next.tours = tours;
659
+ else
660
+ delete next.tours;
661
+ }
602
662
  if (patch.permissionModes !== undefined) {
603
663
  if (typeof patch.permissionModes !== "object" || patch.permissionModes === null || Array.isArray(patch.permissionModes))
604
664
  throw new ConfigError("providers.permissionModes must be an object");
@@ -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);
@@ -0,0 +1,18 @@
1
+ const TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
2
+ function isGithubImage(url) {
3
+ if (url.protocol !== "https:")
4
+ return false;
5
+ if (url.hostname === "raw.githubusercontent.com")
6
+ return /^\/[^/]+\/[^/]+\/.+/.test(url.pathname);
7
+ return url.hostname === "github.com" && /^\/user-attachments\/assets\/[0-9a-f-]+$/i.test(url.pathname);
8
+ }
9
+ export async function githubImage(href, token, fetcher = fetch) {
10
+ if (!URL.canParse(href) || !isGithubImage(new URL(href)))
11
+ return null;
12
+ const response = await fetcher(href, { headers: { authorization: `token ${(await token()).trim()}` } });
13
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim() ?? "";
14
+ if (response.ok && TYPES.has(type))
15
+ return response;
16
+ await response.body?.cancel();
17
+ return null;
18
+ }