@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10

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 (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -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.
@@ -11,17 +11,20 @@
11
11
  * between the Project's own checkout and a Worktree cut from it, so that is the one named.
12
12
  */
13
13
  export function scopeKindLabel(scope) {
14
+ if (scope.readOnly)
15
+ return "Read-only Project Root";
14
16
  return scope.worktree ? "Worktree" : "Project checkout";
15
17
  }
16
18
  /**
17
19
  * Why the checkout is a label and never a control.
18
20
  *
19
21
  * 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.
22
+ * change from here — a different directory is a different Agent Session. Exported as prose so the web
23
+ * client can say it as a tooltip.
23
24
  */
24
25
  export function scopeKindHint(scope) {
26
+ if (scope.readOnly)
27
+ return "The Project Root, read-only. This Agent Session can read it but not write to it, for its whole life.";
25
28
  return scope.worktree
26
29
  ? "A worktree the Session Host made for this Agent Session. It is bound to it for its whole life."
27
30
  : "The Project's own checkout. This Agent Session is bound to it for its whole life.";
@@ -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",
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Which Subagent spawned which, read from `producer` on each Subagent Entry.
3
+ *
4
+ * The transcript stays flat (ADR 0015), so the tree exists only here, built over keys at paint time.
5
+ * DOM-free so every front-end shares one rule.
6
+ */
7
+ const SUBAGENT_PREFIX = "subagent:";
8
+ /** The key of the Entry a Subagent's own row uses, given the id its rows are attributed to. */
9
+ export function subagentKey(subagentId) {
10
+ return `${SUBAGENT_PREFIX}${subagentId}`;
11
+ }
12
+ /** The Subagent a row belongs to, or undefined for the Agent Session's own work. */
13
+ export function producerKey(entry) {
14
+ return "producer" in entry && entry.producer ? subagentKey(entry.producer.subagentId) : undefined;
15
+ }
16
+ /**
17
+ * Every Subagent key mapped to its parent's key, undefined at the root.
18
+ *
19
+ * A parent missing from the transcript maps to the root, so a row is never lost.
20
+ */
21
+ export function subagentParents(keys, getEntry) {
22
+ const subagents = keys.filter((key) => key.startsWith(SUBAGENT_PREFIX) && getEntry(key)?.kind === "subagent");
23
+ const known = new Set(subagents);
24
+ return new Map(subagents.map((key) => {
25
+ const parent = producerKey(getEntry(key));
26
+ return [key, parent !== undefined && known.has(parent) ? parent : undefined];
27
+ }));
28
+ }
29
+ /** How many Subagents are in the chain from `key` up to the root, `key` included. 0 for the Agent Session. */
30
+ export function depthOf(parents, key) {
31
+ let depth = 0;
32
+ const seen = new Set();
33
+ for (let at = key; at !== undefined && !seen.has(at); at = parents.get(at)) {
34
+ seen.add(at);
35
+ if (parents.has(at))
36
+ depth++;
37
+ }
38
+ return depth;
39
+ }
40
+ /** Whether `key` is `ancestor` or sits anywhere below it. */
41
+ export function isWithin(parents, key, ancestor) {
42
+ const seen = new Set();
43
+ for (let at = key; at !== undefined && !seen.has(at); at = parents.get(at)) {
44
+ if (at === ancestor)
45
+ return true;
46
+ seen.add(at);
47
+ }
48
+ return false;
49
+ }
@@ -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
@@ -13,17 +12,18 @@
13
12
  const MAX = 60;
14
13
  /**
15
14
  * Ordered, because a tool's input usually carries several of these and the first is the one the
16
- * question is about: a Bash call's `command` before its `description`, a Grep's `pattern` before the
17
- * directory it searched.
15
+ * question is about: the `description` a model wrote for a call before the `command` or `prompt` it
16
+ * describes, a Grep's `pattern` before the directory it searched.
18
17
  *
19
18
  * Keyed on the shape of the arguments rather than on the tool's name, because the name is the part
20
19
  * that varies: Claude's `Edit` and a pi tool that edits a file are not called the same thing, while
21
20
  * `file_path` means the same in both. An unrecognised tool with a recognisable argument still reads.
22
21
  */
23
22
  const ARGUMENTS = [
23
+ { key: "description", shape: "text" },
24
24
  { key: "command", shape: "text" },
25
- // Ahead of `description` and `prompt`, which an AskUserQuestion call does not carry but a future
26
- // asking tool might. Keyed on the argument rather than the tool's name, which is this list's rule.
25
+ // Ahead of `prompt`, which an AskUserQuestion call does not carry but a future asking tool might.
26
+ // Keyed on the argument rather than the tool's name, which is this list's rule.
27
27
  { key: "questions", shape: "questions" },
28
28
  { key: "file_path", shape: "path" },
29
29
  { key: "notebook_path", shape: "path" },
@@ -31,36 +31,46 @@ const ARGUMENTS = [
31
31
  { key: "url", shape: "text" },
32
32
  { key: "query", shape: "text" },
33
33
  { key: "path", shape: "path" },
34
- { key: "description", shape: "text" },
35
34
  { key: "prompt", shape: "text" },
36
35
  ];
36
+ const MAIN_ARGUMENTS = ARGUMENTS.filter(({ key }) => key !== "description");
37
37
  /**
38
38
  * Returns undefined when there is nothing worth saying, so a caller renders the tool's name alone
39
39
  * rather than a padded blank. `input` is `unknown` on the wire (`events.ts` — a Backend Adapter
40
40
  * passes its backend's arguments through), so every access is narrowed rather than trusted.
41
41
  */
42
42
  export function toolSummary(input) {
43
+ return summarise(input, MAX);
44
+ }
45
+ /**
46
+ * The first argument after `description`, unclipped — the command or prompt the description
47
+ * stands for — for a card that has room to wrap it.
48
+ */
49
+ export function fullToolSummary(input) {
50
+ return summarise(input, Infinity, MAIN_ARGUMENTS);
51
+ }
52
+ function summarise(input, max, args = ARGUMENTS) {
43
53
  if (!input || typeof input !== "object")
44
54
  return undefined;
45
55
  const record = input;
46
- for (const argument of ARGUMENTS) {
56
+ for (const argument of args) {
47
57
  const value = record[argument.key];
48
58
  if (argument.shape === "questions") {
49
- const asked = clipQuestions(value);
59
+ const asked = clipQuestions(value, max);
50
60
  if (asked !== undefined)
51
61
  return asked;
52
62
  continue;
53
63
  }
54
64
  if (typeof value !== "string" || value.trim() === "")
55
65
  continue;
56
- return argument.shape === "path" ? clipPath(value.trim()) : clipText(value);
66
+ return argument.shape === "path" ? clipPath(value.trim(), max) : clipText(value, max);
57
67
  }
58
68
  // The fallback: a tool nobody here has heard of, whose input is a single string, is describing
59
69
  // itself with that string. Two or more and there is no way to know which one matters, so say
60
70
  // nothing rather than pick.
61
71
  const strings = Object.values(record).filter((value) => typeof value === "string");
62
72
  const only = strings.length === 1 ? strings[0] : undefined;
63
- return only && only.trim() !== "" ? clipText(only) : undefined;
73
+ return only && only.trim() !== "" ? clipText(only, max) : undefined;
64
74
  }
65
75
  /**
66
76
  * The first question asked, and how many others came with it.
@@ -72,7 +82,7 @@ export function toolSummary(input) {
72
82
  * The front-ends suppress this row where an Enquiry Entry stands beside it, so what this actually
73
83
  * serves is the case where one does not: a Subagent's Enquiry, seen from the Agents tab.
74
84
  */
75
- function clipQuestions(value) {
85
+ function clipQuestions(value, max) {
76
86
  if (!Array.isArray(value) || value.length === 0)
77
87
  return undefined;
78
88
  const first = value[0];
@@ -84,15 +94,15 @@ function clipQuestions(value) {
84
94
  const rest = value.length - 1;
85
95
  // Clipped after the count is appended, not before, so the whole précis obeys MAX rather than
86
96
  // MAX-plus-however-long-the-suffix-turned-out-to-be.
87
- return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked);
97
+ return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked, max);
88
98
  }
89
99
  /** Whitespace collapsed so a heredoc or a multi-line prompt still occupies one line. */
90
- function clipText(value) {
100
+ function clipText(value, max) {
91
101
  const text = value.replace(/\s+/g, " ").trim();
92
- return text.length <= MAX ? text : `${text.slice(0, MAX - 1)}…`;
102
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
93
103
  }
94
- function clipPath(path) {
104
+ function clipPath(path, max) {
95
105
  // The tail of a path is what identifies the file; the leading directories are what a reader can
96
106
  // afford to lose, which is the opposite of how everything else here truncates.
97
- return path.length <= MAX ? path : `…${path.slice(-(MAX - 1))}`;
107
+ return path.length <= max ? path : `…${path.slice(-(max - 1))}`;
98
108
  }
@@ -0,0 +1,128 @@
1
+ import { lstat, readFile, readlink } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { head, run, GIT_READ_TIMEOUT_MS } from "./git.js";
4
+ import { gh } from "./github.js";
5
+ import { git, localRepository, resolveRepository } from "./repository.js";
6
+ import { readStatus } from "./git-state.js";
7
+ import { localStack, localStacks, stackParent } from "./stack-metadata.js";
8
+ const SIDE_LIMIT = 250_000;
9
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
10
+ async function files(scope) {
11
+ return (await readStatus(scope)).files;
12
+ }
13
+ async function baseRef(scope, remote, branch, preferLocal) {
14
+ const refs = [`refs/heads/${branch}`, `refs/remotes/${remote}/${branch}`];
15
+ for (const ref of preferLocal ? refs : refs.reverse()) {
16
+ if ((await run(scope, ["rev-parse", "--verify", "--quiet", ref], GIT_READ_TIMEOUT_MS)).ok)
17
+ return ref;
18
+ }
19
+ return undefined;
20
+ }
21
+ async function rangeFiles(scope, base, to) {
22
+ const raw = (await git(scope, ["diff", "--name-status", "-z", "--no-renames", `${base}...${to}`, "--"])).split("\0").filter(Boolean);
23
+ const files = [];
24
+ for (let index = 0; index < raw.length; index += 2)
25
+ files.push({ status: raw[index], path: raw[index + 1] });
26
+ return files;
27
+ }
28
+ async function rangeCommits(scope, base, to) {
29
+ return (await git(scope, ["log", "--format=%h %s", `${base}..${to}`, "--"])).trim().split("\n").filter(Boolean);
30
+ }
31
+ export async function rangeChanges(scope, base, to) {
32
+ return { files: await rangeFiles(scope, base, to), commits: await rangeCommits(scope, base, to) };
33
+ }
34
+ async function branchBase(scope, pullRequestBase, github) {
35
+ const current = await head(scope);
36
+ const branch = current.ok && !current.value.detached ? current.value.name : undefined;
37
+ const repository = await resolveRepository(scope, branch, github);
38
+ const stack = branch === undefined ? undefined : await localStack(scope, branch);
39
+ const parent = stack && stackParent(stack, branch);
40
+ const name = (branch === undefined ? undefined : pullRequestBase?.(branch)) ?? parent ?? repository.base.defaultBranch;
41
+ const ref = await baseRef(scope, repository.remote, name, name === parent);
42
+ if (!ref)
43
+ throw new Error(`The base branch ${name} is not known locally. Fetch ${name} from ${repository.remote} to show the branch changes.`);
44
+ return ref;
45
+ }
46
+ export async function changes(scope, view, pullRequestBase, github = gh) {
47
+ if (view !== "branch")
48
+ return { files: await files(scope), commits: [] };
49
+ const base = await branchBase(scope, pullRequestBase, github);
50
+ return { ...await rangeChanges(scope, base, "HEAD"), base: base.replace(/^refs\/(heads|remotes)\//, "") };
51
+ }
52
+ function added(path, content) {
53
+ const lines = content.match(/[^\n]*\n|[^\n]+$/g) ?? [];
54
+ const hunk = lines.length === 0 ? "" : `@@ -0,0 +1,${lines.length} @@\n${lines.map(line => `+${line}`).join("")}${content.endsWith("\n") ? "" : "\n\\n"}`;
55
+ return `--- /dev/null\n+++ b/${path}\n${hunk}`;
56
+ }
57
+ async function untracked(scope, path) {
58
+ const full = resolve(scope, path);
59
+ const stat = await lstat(full);
60
+ if (stat.isSymbolicLink())
61
+ return { text: added(path, await readlink(full)) };
62
+ if (!stat.isFile())
63
+ return { binary: true };
64
+ if (stat.size > SIDE_LIMIT)
65
+ return { tooLarge: true };
66
+ const content = await readFile(full);
67
+ if (content.includes(0))
68
+ return { binary: true };
69
+ return { text: added(path, content.toString("utf8")) };
70
+ }
71
+ async function blobSize(scope, object) {
72
+ const size = await run(scope, ["cat-file", "-s", object], GIT_READ_TIMEOUT_MS);
73
+ return size.ok ? Number(size.value) : 0;
74
+ }
75
+ export async function diff(scope, view, path, pullRequestBase, github = gh) {
76
+ return fileDiff(scope, path, view === "branch" ? await branchBase(scope, pullRequestBase, github) : undefined, "HEAD");
77
+ }
78
+ export async function fileDiff(scope, path, base, to) {
79
+ const listed = base ? await rangeFiles(scope, base, to) : await files(scope);
80
+ const file = listed.find(item => item.path === path);
81
+ if (!file)
82
+ throw new Error("This file is not in the list of changes. Read the list again.");
83
+ if (file.status === "??")
84
+ return untracked(scope, path);
85
+ const from = base ? (await git(scope, ["merge-base", base, to])).trim() : (await run(scope, ["rev-parse", "--verify", "--quiet", "HEAD"], GIT_READ_TIMEOUT_MS)).ok ? "HEAD" : EMPTY_TREE;
86
+ const oldSize = await blobSize(scope, `${from}:${path}`);
87
+ const newSize = base ? await blobSize(scope, `${to}:${path}`) : (await lstat(resolve(scope, path)).catch(() => undefined))?.size ?? 0;
88
+ if (oldSize > SIDE_LIMIT || newSize > SIDE_LIMIT)
89
+ return { tooLarge: true };
90
+ const range = base ? [from, to] : [from];
91
+ const numstat = await git(scope, ["--literal-pathspecs", "diff", "--numstat", ...range, "--", path]);
92
+ if (numstat.startsWith("-\t-\t"))
93
+ return { binary: true };
94
+ return { text: await git(scope, ["--literal-pathspecs", "diff", "--no-color", "--no-ext-diff", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", ...range, "--", path]) };
95
+ }
96
+ export async function canNameBranch(scope, branch, remote, pullRequest) {
97
+ if (pullRequest)
98
+ return false;
99
+ if ((await localStacks(scope)).some(stack => stack.trunk.branch === branch || stack.branches.some(item => item.branch === branch)))
100
+ return false;
101
+ return !(await run(scope, ["show-ref", "--verify", "--quiet", `refs/remotes/${remote}/${branch}`], GIT_READ_TIMEOUT_MS)).ok;
102
+ }
103
+ export async function commitContext(scope, branch, pullRequest) {
104
+ const repository = await localRepository(scope, branch).catch(() => undefined);
105
+ const defaultBranch = repository?.defaultBranches[0];
106
+ const canRename = Boolean(branch && repository?.github && defaultBranch && !repository.defaultBranches.includes(branch) && await canNameBranch(scope, branch, repository.remote, pullRequest(branch)));
107
+ return { ...(branch ? { branch } : {}), ...(defaultBranch ? { defaultBranch } : {}), canRename };
108
+ }
109
+ export async function changesText(scope, view, paths, pullRequestBase, github = gh) {
110
+ return textOf(await changes(scope, view, pullRequestBase, github), paths, path => diff(scope, view, path, pullRequestBase, github));
111
+ }
112
+ export async function rangeText(scope, base, to) {
113
+ return textOf(await rangeChanges(scope, base, to), undefined, path => fileDiff(scope, path, base, to));
114
+ }
115
+ async function textOf(listed, paths, read) {
116
+ let text = listed.commits.length > 0 ? `Commits:\n${listed.commits.join("\n")}\n` : "";
117
+ for (const file of listed.files) {
118
+ if (paths && !paths.includes(file.path))
119
+ continue;
120
+ if (text.length > 24_000) {
121
+ text += `${file.status} ${file.path}: diff left out, read the file\n`;
122
+ continue;
123
+ }
124
+ const shown = await read(file.path);
125
+ text += "text" in shown ? shown.text : `${file.status} ${file.path}: no text diff\n`;
126
+ }
127
+ return text;
128
+ }
@@ -0,0 +1,84 @@
1
+ import { access } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { run, GIT_READ_TIMEOUT_MS } from "./git.js";
4
+ import { canNameBranch } from "./changes.js";
5
+ import { readStatus } from "./git-state.js";
6
+ import { gh } from "./github.js";
7
+ import { remoteHead } from "./push.js";
8
+ import { git, localRepository, resolvePullRequest, resolveRepository } from "./repository.js";
9
+ async function refuseOperation(scope) {
10
+ if ((await readStatus(scope)).files.some(file => file.status.includes("U") || ["AA", "DD"].includes(file.status)))
11
+ throw new Error("Resolve the merge conflicts before you commit.");
12
+ for (const operation of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"]) {
13
+ if ((await run(scope, ["rev-parse", "--verify", "-q", operation], GIT_READ_TIMEOUT_MS)).ok)
14
+ throw new Error("Finish the current Git operation before you commit.");
15
+ }
16
+ for (const operation of ["rebase-merge", "rebase-apply", "sequencer"]) {
17
+ const path = (await git(scope, ["rev-parse", "--git-path", operation])).trim();
18
+ if (await access(resolve(scope, path)).then(() => true, () => false))
19
+ throw new Error("Finish the current Git operation before you commit.");
20
+ }
21
+ }
22
+ async function refuseBranchName(scope, name, repository) {
23
+ if (name.startsWith("-") || name.includes("@{") || repository?.defaultBranches.includes(name))
24
+ throw new Error(`${name} is not a valid new branch name.`);
25
+ await git(scope, ["check-ref-format", "--branch", name]);
26
+ if ((await run(scope, ["show-ref", "--verify", "--quiet", `refs/heads/${name}`], GIT_READ_TIMEOUT_MS)).ok)
27
+ throw new Error(`The branch ${name} already exists. Enter a new name.`);
28
+ if (repository && await remoteHead(scope, repository.remote, name))
29
+ throw new Error(`The branch ${name} already exists on ${repository.remote}. Enter a new name.`);
30
+ }
31
+ async function renameAllowed(scope, branch, repository, github) {
32
+ if (!repository?.github)
33
+ return false;
34
+ const pullRequest = await resolvePullRequest(scope, await resolveRepository(scope, branch, github), branch, github);
35
+ return await canNameBranch(scope, branch, repository.remote, pullRequest !== undefined) && !await remoteHead(scope, repository.remote, branch);
36
+ }
37
+ export async function commit(scope, input, github = gh) {
38
+ if (typeof input.message !== "string" || !input.message.trim())
39
+ throw new Error("Enter a commit message.");
40
+ if (!Array.isArray(input.paths) || input.paths.length === 0 || input.paths.some(path => typeof path !== "string"))
41
+ throw new Error("Select at least one file to commit.");
42
+ await refuseOperation(scope);
43
+ const reviewed = await readStatus(scope);
44
+ const changed = "The changes changed after the list was read. Read the list again.";
45
+ if (reviewed.fingerprint !== input.fingerprint)
46
+ throw new Error(changed);
47
+ const paths = new Set(input.paths);
48
+ if ([...paths].some(path => !reviewed.files.some(file => file.path === path)))
49
+ throw new Error("A selected file is not in the list of changes. Read the list again.");
50
+ const branch = reviewed.local.branch;
51
+ const repository = await localRepository(scope, branch);
52
+ if (repository?.github && repository.defaultBranches.length === 0)
53
+ throw new Error(`The default branch of ${repository.remote} is not known. Refresh when GitHub answers, or run git remote set-head ${repository.remote} --auto.`);
54
+ const creating = branch === undefined || repository?.defaultBranches.includes(branch) === true;
55
+ const name = typeof input.branch === "string" ? input.branch.trim() : "";
56
+ if (creating && (!name || name === branch))
57
+ throw new Error(branch ? `${branch} is the default branch. Enter a new branch name.` : "HEAD is detached. Enter a new branch name.");
58
+ if (name && name !== branch) {
59
+ await refuseBranchName(scope, name, repository);
60
+ if (!creating && !await renameAllowed(scope, branch, repository, github))
61
+ throw new Error(`${branch} has a pull request, a remote branch or a stack registration, so it cannot be renamed.`);
62
+ await git(scope, creating ? ["switch", "--quiet", "-c", name] : ["branch", "-m", name], true);
63
+ }
64
+ if ((await readStatus(scope)).fingerprint !== input.fingerprint)
65
+ throw new Error(name && name !== branch ? `The branch ${name} is ready, but the changes changed. Read the list again.` : changed);
66
+ const untracked = reviewed.files.filter(file => file.status === "??" && paths.has(file.path)).map(file => file.path);
67
+ try {
68
+ if (untracked.length > 0)
69
+ await git(scope, ["--literal-pathspecs", "add", "--intent-to-add", "--", ...untracked], true);
70
+ await git(scope, ["--literal-pathspecs", "commit", "--quiet", "-m", input.message, "--", ...paths], true);
71
+ }
72
+ catch (error) {
73
+ if (untracked.length > 0)
74
+ await run(scope, ["--literal-pathspecs", "rm", "--cached", "--quiet", "--ignore-unmatch", "--", ...untracked], GIT_READ_TIMEOUT_MS);
75
+ throw error;
76
+ }
77
+ const [created, ...parents] = (await git(scope, ["rev-list", "--parents", "-n", "1", "HEAD"])).trim().split(" ");
78
+ if (parents.join(" ") !== (reviewed.local.head ?? ""))
79
+ throw new Error(`Commit ${created.slice(0, 7)} was created, but its parent is not the commit that was read. Review the commit before you push.`);
80
+ const committed = (await git(scope, ["diff-tree", "-r", "-z", "--name-only", "--no-renames", "--no-commit-id", "--root", "HEAD"])).split("\0").filter(Boolean);
81
+ if (committed.length !== paths.size || committed.some(path => !paths.has(path)))
82
+ throw new Error(`Commit ${created.slice(0, 7)} was created, but it does not contain exactly the selected files. Review the commit before you push.`);
83
+ return created;
84
+ }
@@ -1,9 +1,9 @@
1
1
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { applyPatch, formatDuration, loadConfig, } from "./config.js";
4
- import { DEFAULT_WORKFLOW_RUNTIME } from "../protocol/settings.js";
5
- import { detectFilesystemIsolationSupport, } from "../isolation/support.js";
6
- import { detectSandboxSupport } from "../isolation/sandbox.js";
4
+ import { DEFAULT_WORKFLOW_RUNTIME } from '../protocol/settings.js';
5
+ import { detectFilesystemIsolationSupport, } from '../isolation/support.js';
6
+ import { detectSandboxSupport } from '../isolation/sandbox.js';
7
7
  import { expandHome } from "./projects.js";
8
8
  import { defaultStateRoot } from "./store.js";
9
9
  /**
@@ -62,7 +62,9 @@ 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";
67
+ dictation = () => this.config.dictation ?? {};
66
68
  /** The current Config, in the file's own units. Cheap: held in memory, not re-read. */
67
69
  current() {
68
70
  return this.config;
@@ -131,6 +133,7 @@ export class ConfigStore {
131
133
  return { backend, ...summary };
132
134
  return providers?.summary?.backend === backend ? providers.summary : undefined;
133
135
  };
136
+ tourModel = (backend) => this.config.providers?.tours?.[backend];
134
137
  defaultPermissionMode = (backend) => this.config.providers?.permissionModes?.[backend];
135
138
  defaultEffort = (backend) => this.config.providers?.efforts?.[backend];
136
139
  /**
@@ -217,6 +220,8 @@ function settingsOf(config) {
217
220
  ...(config.filesystemIsolation === undefined ? {} : { filesystemIsolation: config.filesystemIsolation }),
218
221
  ...(config.sandboxSharing === undefined ? {} : { sandboxSharing: config.sandboxSharing }),
219
222
  ...(config.updateChannel === undefined ? {} : { updateChannel: config.updateChannel }),
223
+ ...(config.worktrees === undefined ? {} : { worktrees: config.worktrees }),
224
+ ...(config.dictation === undefined ? {} : { dictation: config.dictation }),
220
225
  // Omitted rather than defaulted when there is no Project Root, which is what
221
226
  // `Settings["projects"]` being optional means — see src/protocol/settings.ts.
222
227
  ...(config.projects === undefined ? {} : { projects: config.projects }),