@nathanstephenson/flow 0.1.0

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 (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,366 @@
1
+ import { contextUsageLabel } from "../client/context-usage.js";
2
+ import { effortChoices, modelChoices } from "../client/model-choices.js";
3
+ import { answerLines, progressLabel, rowsFor, } from "../client/enquiry.js";
4
+ import { authorisationLabel, permissionChoices } from "../client/permission.js";
5
+ import { toolSummary } from "../client/tool-summary.js";
6
+ import { relativeTime } from "../client/relative-time.js";
7
+ import { scopeKindLabel } from "../client/scope-kind.js";
8
+ import { sessionLabel } from "../client/session-label.js";
9
+ export function renderFrame(ui, size) {
10
+ const width = Math.max(20, size.columns);
11
+ const height = Math.max(6, size.rows);
12
+ // Only ever one of the two: an Enquiry and a Permission Prompt are both a callback the CLI is
13
+ // blocked on, and the composer is locked to whichever is in hand. Concatenated rather than chosen
14
+ // between, so if the impossible happens the human can see both rather than one of them silently
15
+ // going missing behind a lockout.
16
+ const picker = [...enquiryLines(ui, width), ...permissionLines(ui, width)];
17
+ // The picker takes its rows off the transcript rather than replacing it, which is the difference
18
+ // between this and an Overlay. Bounded so a four-option Question on a short terminal still leaves
19
+ // something of the conversation visible.
20
+ const body = height - 3 - picker.length;
21
+ const lines = [header(ui, width)];
22
+ lines.push(...(ui.overlay.kind === "none" ? transcript(ui.view, width, body) : overlay(ui, width, body)));
23
+ lines.push(...picker);
24
+ lines.push(status(ui, width));
25
+ lines.push(promptLine(ui, width));
26
+ return lines;
27
+ }
28
+ function header(ui, width) {
29
+ const summary = ui.sessions.find((session) => session.id === ui.selected);
30
+ const model = ui.view.model?.label ?? ui.view.model?.id ?? "default model";
31
+ const effort = ui.view.effort && effortChoices(ui.view).length > 0 ? ` · ${ui.view.effort}` : "";
32
+ /*
33
+ * Where the next turn will land, beside what will run it.
34
+ *
35
+ * The web client draws this as a strip along the bottom of its composer, with the checkout named
36
+ * every time. Here it is one line shared with the model and the status, so only the notable case
37
+ * is spent width on: `scopeKindLabel` supplies the word either way, so the two clients cannot
38
+ * drift on *what* a Worktree is called — only on whether there is room to say it.
39
+ *
40
+ * Absent when the Scope is not a repository, the same signal the web client hides its control on.
41
+ */
42
+ const kind = ui.view.worktree ? ` · ${scopeKindLabel(ui.view)}` : "";
43
+ const branch = ui.view.branch ? ` · ${ui.view.branch.name}${kind}` : "";
44
+ const left = summary ? `${summary.backend} · ${sessionLabel(summary)}${branch}` : "no session";
45
+ const right = `${model}${effort} · ${ui.view.status}`;
46
+ return clip(pad(left, Math.max(0, width - right.length - 1)) + " " + right, width);
47
+ }
48
+ /**
49
+ * The Enquiry picker: the Question on screen, its Options, and where the cursor is.
50
+ *
51
+ * Empty when nothing is being asked, which is what keeps `renderFrame` free of a conditional — the
52
+ * rows are simply zero and the transcript gets its full height back.
53
+ *
54
+ * Numbers are a visible column, and that is the one thing this does that an arrow-driven list
55
+ * cannot: a row can be addressed without being travelled to. It is what "numbered picker" means, and
56
+ * it is why the digits are worth borrowing from the prompt line to get.
57
+ */
58
+ function enquiryLines(ui, width) {
59
+ const asking = ui.view.asking;
60
+ const state = ui.answering;
61
+ if (!asking || !state)
62
+ return [];
63
+ const question = asking.questions[state.index];
64
+ if (!question)
65
+ return [];
66
+ const rows = rowsFor(question, ui.input);
67
+ const progress = progressLabel(state, asking.questions);
68
+ const mode = question.multiSelect ? " (choose any)" : "";
69
+ const title = `${question.header}${progress ? ` (${progress})` : ""}${mode}`;
70
+ const lines = [rule(title, width), ...(asking.context ? wrap(asking.context, width) : []), ...wrap(question.question, width)];
71
+ rows.forEach((row, index) => {
72
+ const onCursor = index === state.cursor;
73
+ const cursor = onCursor ? ">" : " ";
74
+ // The box only where it means something. A single-select has exactly one answer at all times,
75
+ // so drawing an empty one beside every row would offer a choice that is not on offer.
76
+ const box = question.multiSelect ? ((state.chosen[state.index] ?? []).includes(row.label) ? "[x] " : "[ ] ") : "";
77
+ const head = `${cursor} ${index + 1} ${box}${row.label}`;
78
+ /*
79
+ * The row under the cursor gets its whole description, wrapped underneath; the rest get one
80
+ * clipped line.
81
+ *
82
+ * An Option's description is not a nicety the way a Skill's is in the `/` menu — it is the
83
+ * deciding information, and the model writes it long: a hundred characters saying what the
84
+ * trade-off is, with the trade-off itself at the end. Clipping every row to the width of a
85
+ * terminal reliably cuts off the half that decides it.
86
+ *
87
+ * So the one being considered is shown in full and the others stay scannable. The picker's
88
+ * height therefore changes as the cursor moves, which is the cost of this and is paid
89
+ * deliberately: what it buys is never having to choose between options whose descriptions have
90
+ * been cut in the same place.
91
+ */
92
+ if (!row.description) {
93
+ lines.push(clip(head, width));
94
+ return;
95
+ }
96
+ if (onCursor) {
97
+ lines.push(clip(head, width));
98
+ // Indented under the number, so the wrapped text reads as belonging to the row above it.
99
+ for (const line of wrap(row.description, Math.max(8, width - 6)))
100
+ lines.push(clip(` ${line}`, width));
101
+ return;
102
+ }
103
+ lines.push(ellipsised(`${head} ${row.description}`, width));
104
+ });
105
+ return lines;
106
+ }
107
+ /**
108
+ * The Permission Prompt picker: what wants to run, and the three things a human can do about it.
109
+ *
110
+ * Empty when nothing is waiting, which keeps `renderFrame` free of a conditional, exactly as
111
+ * `enquiryLines` does.
112
+ *
113
+ * What is being authorised is read off the `tool` Entry this prompt shares an id with, rather than
114
+ * carried on the prompt itself: `toolSummary` already précises a call's arguments for both
115
+ * front-ends, and a second description of the same call is a second thing to keep in step. The tool
116
+ * name alone would be the withholding `tool-summary.ts` exists to stop — "authorise Bash?" is not a
117
+ * question anyone can answer.
118
+ */
119
+ function permissionLines(ui, width) {
120
+ const authorising = ui.view.authorising;
121
+ if (!authorising)
122
+ return [];
123
+ const cursor = ui.deciding ?? 0;
124
+ const call = ui.view.entries.find((entry) => entry.kind === "tool" && entry.id === authorising.callId);
125
+ const summary = call ? toolSummary(call.input) : undefined;
126
+ const lines = [rule(`Authorise ${authorising.tool}?`, width)];
127
+ if (authorising.context)
128
+ lines.push(...wrap(authorising.context, width));
129
+ if (summary)
130
+ lines.push(...wrap(summary, width));
131
+ if (authorising.authorizationScope)
132
+ lines.push(...wrap(`Scope: ${authorising.authorizationScope}`, width));
133
+ permissionChoices(authorising.allowAlways).forEach((choice, index) => {
134
+ const onCursor = index === cursor;
135
+ const head = `${onCursor ? ">" : " "} ${index + 1} ${choice.label}`;
136
+ // The description in full on the cursor row and clipped elsewhere, the rule `enquiryLines`
137
+ // sets — and here the row it matters for is Always, whose description is the whole warning.
138
+ if (!onCursor) {
139
+ lines.push(ellipsised(`${head} ${choice.description}`, width));
140
+ return;
141
+ }
142
+ lines.push(clip(head, width));
143
+ for (const line of wrap(choice.description, Math.max(8, width - 6))) {
144
+ lines.push(clip(` ${line}`, width));
145
+ }
146
+ });
147
+ return lines;
148
+ }
149
+ /**
150
+ * The prompt line, and — while an Enquiry is open — the whole of how the lockout is stated.
151
+ *
152
+ * The TUI has no placeholder to put it in, so the sigil carries it: `?` rather than `>`, because a
153
+ * `>` over a box that cannot send a message tells exactly the lie the web client's placeholder is
154
+ * careful to refuse.
155
+ */
156
+ function promptLine(ui, width) {
157
+ // A Permission Prompt takes no text at all, so there is nothing to type and nothing to show
158
+ // typed. `!` rather than `?`: the difference between being asked something and being asked to
159
+ // allow something is the whole distinction between an Enquiry and this, and the sigil is the only
160
+ // place a terminal has to say it.
161
+ if (ui.view.authorising)
162
+ return clip(`! [1-${permissionChoices(ui.view.authorising.allowAlways).length} to decide]`, width);
163
+ if (!ui.view.asking)
164
+ return clip(`> ${ui.input}`, width);
165
+ return clip(ui.input === "" ? "? [type your own answer]" : `? ${ui.input}`, width);
166
+ }
167
+ function status(ui, width) {
168
+ const parts = [];
169
+ if (ui.view.queue.length > 0)
170
+ parts.push(`${ui.view.queue.length} queued`);
171
+ // Ahead of the reading it is about to change, and in place of it: a percentage that has not moved
172
+ // yet is the thing someone asking for a compaction is staring at.
173
+ if (ui.view.compacting)
174
+ parts.push("compacting…");
175
+ else {
176
+ const context = contextUsageLabel(ui.view.contextUsage);
177
+ if (context)
178
+ parts.push(context);
179
+ }
180
+ if (ui.notice)
181
+ parts.push(ui.notice);
182
+ // `^K` is listed only where it can be served, on the same rule the web client hides the menu item:
183
+ // an affordance a backend cannot honour is worse than no affordance at all.
184
+ const compact = ui.view.capabilities?.compaction ? " ^K compact" : "";
185
+ /*
186
+ * While an Enquiry is open the hints are replaced rather than added to, because most of them are
187
+ * no longer true: nothing here sends a message, and `^K` is refused. `esc abort` survives and is
188
+ * the one way out — the TUI has no Abort button to give Escape a second job, which is why it means
189
+ * abort here where on the web it means going back a Question.
190
+ */
191
+ parts.push(ui.view.authorising
192
+ ? `↑↓ choose 1-${permissionChoices(ui.view.authorising.allowAlways).length} pick enter decide esc deny`
193
+ : ui.view.asking
194
+ ? "↑↓ choose 1-9 pick enter answer esc abort"
195
+ : `^S sessions ^P models ^E effort ^G branches${compact} esc abort ^C quit`);
196
+ return clip(parts.join(" · "), width);
197
+ }
198
+ function transcript(view, width, height) {
199
+ const lines = view.entries.flatMap((entry) => entryLines(entry, width));
200
+ return padTo(lines.slice(-height), height, width);
201
+ }
202
+ function entryLines(entry, width) {
203
+ switch (entry.kind) {
204
+ case "user": {
205
+ const lines = wrap(`> ${entry.text}`, width);
206
+ // A terminal cannot show the image and cannot paste one either, so it says one is there and
207
+ // stops. Naming the count rather than each id, because an id is a filename this reader has no
208
+ // use for — what they need to know is that the model saw something they cannot.
209
+ const count = entry.attachments?.length ?? 0;
210
+ return count === 0 ? lines : [...lines, clip(` [${count} image${count === 1 ? "" : "s"}]`, width)];
211
+ }
212
+ case "assistant":
213
+ return wrap(entry.text, width);
214
+ case "thinking":
215
+ return wrap(`· ${entry.text}`, width);
216
+ case "tool": {
217
+ // The authorisation only where there is one — most rows have none, and a terminal that printed
218
+ // something for them would suggest a decision nobody was asked to make.
219
+ const authorised = authorisationLabel(entry.authorisation);
220
+ return [clip(` [${entry.status}] ${entry.name}${authorised ? ` — ${authorised}` : ""}`, width)];
221
+ }
222
+ case "subagent":
223
+ // Indented past a tool call: a Subagent is what one of those is doing, not another of them.
224
+ return [clip(` ⤷ [${entry.waitingOn ?? entry.status}] ${entry.name}`, width)];
225
+ case "background_call":
226
+ // Indented for the same reason, and for the same relationship: this is what the tool call
227
+ // above it is still doing. Its own glyph, because the row above says `complete` — that call
228
+ // handed back a receipt, and this is the work the receipt promised (ADR 0021).
229
+ return [clip(` ⟳ [${entry.status}] ${entry.tool}`, width)];
230
+ case "enquiry": {
231
+ // What was asked and what was chosen, which is the whole requirement of this row. The lines
232
+ // come from the shared module, so the terminal and the browser cannot disagree about what an
233
+ // answered Enquiry says — only about how it is drawn.
234
+ const head = clip(` [${entry.status}] asked ${entry.questions.length === 1 ? "a question" : `${entry.questions.length} questions`}`, width);
235
+ if (entry.status !== "answered")
236
+ return [head];
237
+ return [head, ...answerLines(entry.questions, entry.answers).map((line) => clip(` ${line}`, width))];
238
+ }
239
+ case "notice":
240
+ return wrap(`! ${entry.text}`, width);
241
+ case "marker":
242
+ return [rule(entry.text, width)];
243
+ }
244
+ }
245
+ /**
246
+ * A structural marker is a break in the Presentation Transcript rather than another line of text, so
247
+ * it gets a labelled rule — the same `──` vocabulary the Settled divider in the session list uses.
248
+ */
249
+ function rule(label, width) {
250
+ const dashes = Math.max(0, width - label.length - 4);
251
+ return clip(`── ${label} ${"─".repeat(dashes)}`, width);
252
+ }
253
+ function overlay(ui, width, height) {
254
+ if (ui.overlay.kind === "sessions") {
255
+ const cursor = ui.overlay.index;
256
+ const now = ui.now ?? Date.now();
257
+ const rows = [];
258
+ let openedSettled = false;
259
+ // list() sorts Settled last, so one divider separates the two groups. It is a label rather than
260
+ // a row: the cursor indexes into ui.sessions, and a selectable heading would shift every index.
261
+ for (const [index, session] of ui.sessions.entries()) {
262
+ if (session.status === "settled" && !openedSettled) {
263
+ openedSettled = true;
264
+ rows.push(clip(" ── settled ──", width));
265
+ }
266
+ // `restingAt`, which is also what the list is ordered by — a column showing one time while
267
+ // the rows are sorted by another reads as broken the first time they disagree.
268
+ const updated = relativeTime(session.restingAt, now);
269
+ rows.push(clip(`${index === cursor ? ">" : " "} ${session.status.padEnd(8)} ${session.backend.padEnd(7)} ${updated.padEnd(10)} ${sessionLabel(session)}`, width));
270
+ }
271
+ return padTo(["sessions (enter to switch, n for new, w for new in a worktree, s to settle, esc to close)", ...rows], height, width);
272
+ }
273
+ if (ui.overlay.kind === "branches") {
274
+ const { index, purpose, branches, head } = ui.overlay;
275
+ // Keep the cursor in view, the same way the model list does: a long-lived checkout accumulates
276
+ // branches the way the pi backend accumulates models.
277
+ const room = Math.max(1, height - 1);
278
+ const start = Math.max(0, Math.min(index - Math.floor(room / 2), branches.length - room));
279
+ const rows = [];
280
+ for (let cursor = start; cursor < Math.min(branches.length, start + room); cursor += 1) {
281
+ const name = branches[cursor];
282
+ if (name === undefined)
283
+ break;
284
+ const inForce = name === head ? " (in force)" : "";
285
+ rows.push(clip(`${cursor === index ? ">" : " "} ${name}${inForce}`, width));
286
+ }
287
+ const title = branches.length === 0
288
+ ? "no branches here"
289
+ : purpose === "switch"
290
+ ? "branches (enter to switch, esc to close)"
291
+ : "cut a worktree from (enter to start an Agent Session, esc to close)";
292
+ return padTo([title, ...rows], height, width);
293
+ }
294
+ if (ui.overlay.kind === "effort") {
295
+ const levels = effortChoices(ui.view);
296
+ const cursor = ui.overlay.index;
297
+ const rows = levels.map((level, index) => {
298
+ const inForce = level === ui.view.effort ? " (in force)" : "";
299
+ return clip(`${index === cursor ? ">" : " "} ${level}${inForce}`, width);
300
+ });
301
+ const title = levels.length > 0 ? "effort (enter to set, esc to close)" : "this model has no effort control";
302
+ return padTo([title, ...rows], height, width);
303
+ }
304
+ const choices = modelChoices(ui.view.capabilities);
305
+ const index = ui.overlay.kind === "models" ? ui.overlay.index : 0;
306
+ // Keep the cursor in view: the pi backend can offer hundreds of models.
307
+ const start = Math.max(0, Math.min(index - Math.floor((height - 2) / 2), choices.length - (height - 2)));
308
+ const rows = [];
309
+ let lastProvider;
310
+ for (let cursor = start; cursor < Math.min(choices.length, start + height - 2); cursor += 1) {
311
+ const choice = choices[cursor];
312
+ if (!choice)
313
+ break;
314
+ if (choice.provider !== lastProvider) {
315
+ rows.push(clip(` ${choice.provider}`, width));
316
+ lastProvider = choice.provider;
317
+ }
318
+ rows.push(clip(`${cursor === index ? ">" : " "} ${choice.model.label ?? choice.model.id}`, width));
319
+ }
320
+ return padTo([`models (${choices.length} across ${providerCount(choices)} providers)`, ...rows], height, width);
321
+ }
322
+ function providerCount(choices) {
323
+ return new Set(choices.map((choice) => choice.provider)).size;
324
+ }
325
+ function wrap(text, width) {
326
+ const out = [];
327
+ for (const paragraph of text.split("\n")) {
328
+ if (paragraph.length <= width) {
329
+ out.push(paragraph);
330
+ continue;
331
+ }
332
+ let rest = paragraph;
333
+ while (rest.length > width) {
334
+ const cut = rest.lastIndexOf(" ", width);
335
+ const at = cut > width / 2 ? cut : width;
336
+ out.push(rest.slice(0, at));
337
+ rest = rest.slice(at).trimStart();
338
+ }
339
+ if (rest)
340
+ out.push(rest);
341
+ }
342
+ return out;
343
+ }
344
+ function padTo(lines, height, width) {
345
+ const clipped = lines.slice(0, height).map((line) => clip(line, width));
346
+ while (clipped.length < height)
347
+ clipped.push("");
348
+ return clipped;
349
+ }
350
+ /**
351
+ * Clipped, but saying so.
352
+ *
353
+ * `clip` cuts silently, which is right for a header where the reader can see the shape of what is
354
+ * missing. It is wrong for an Option's description, where a sentence that stops mid-word is
355
+ * indistinguishable from one the model wrote that way — and the reader is being asked to choose on
356
+ * the strength of it.
357
+ */
358
+ function ellipsised(text, width) {
359
+ return text.length > width ? `${text.slice(0, Math.max(0, width - 1))}…` : text;
360
+ }
361
+ function clip(text, width) {
362
+ return text.length > width ? text.slice(0, width) : text;
363
+ }
364
+ function pad(text, width) {
365
+ return text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
366
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The shape of the embedded web assets: what the Session Host is entitled to assume about a manifest
3
+ * it is handed, and the contract src/web/manifest.ts is written against.
4
+ *
5
+ * The manifest itself is a build artifact and never appears under src/ — the binary build generates
6
+ * it and injects it in place of src/web/embedded.ts (ADR 0017), so nothing typechecks the bytes.
7
+ * These types are the whole of the agreement, and test/assets-embedding.test.ts is what holds the
8
+ * generator to them.
9
+ */
10
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The web client baked into this build, and the one place a build artifact enters the program.
3
+ *
4
+ * Empty here and replaced wholesale by scripts/build-binary.mjs at bundle time, because the single
5
+ * executable is the only build that can carry its assets — a SEA blob has no filesystem to read them
6
+ * from. A source run finds this empty and loads web/dist from disk instead (src/cli/main.ts), so
7
+ * both serve the same bytes by the same manifestOf(); only where they come from differs.
8
+ *
9
+ * Nothing generated is committed under src/ as a consequence, which is the whole point: the manifest
10
+ * is 2.5 MB that Vite content-hashes, so every branch touching web/ used to collide on it (ADR 0017).
11
+ */
12
+ export const EMBEDDED = {};
@@ -0,0 +1,70 @@
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { extname, join, posix, sep } from "node:path";
3
+ /**
4
+ * Turn a directory of Vite output into the manifest the Session Host serves from memory.
5
+ *
6
+ * One implementation with two callers, which is the point: scripts/build-binary.mjs runs it at bundle
7
+ * time to produce the manifest it injects, and src/cli/main.ts runs it at startup so a source run
8
+ * serves the same bytes the binary would. A second implementation is how the two would drift.
9
+ */
10
+ const CONTENT_TYPES = {
11
+ ".css": ["text/css", true],
12
+ ".html": ["text/html", true],
13
+ ".ico": ["image/x-icon", false],
14
+ ".js": ["text/javascript", true],
15
+ ".json": ["application/json", true],
16
+ ".png": ["image/png", false],
17
+ ".svg": ["image/svg+xml", true],
18
+ // The Shell's terminal emulator. It is fetched and handed to WebAssembly.compile(), so the type is
19
+ // not load-bearing the way it would be for instantiateStreaming — but the fallback would call it
20
+ // application/octet-stream, and being wrong in the manifest is how it gets served wrongly by the
21
+ // next thing that reads it.
22
+ ".wasm": ["application/wasm", false],
23
+ ".webp": ["image/webp", false],
24
+ ".woff2": ["font/woff2", false],
25
+ };
26
+ // Vite content-hashes everything but the Entry Document, and a hashed name may be cached forever.
27
+ // That is a fact about the build, so the judgement is made here — where the hashing is known —
28
+ // rather than in the Session Host.
29
+ const CONTENT_HASHED = /-[A-Za-z0-9_-]{8}\.[^.]+$/;
30
+ /** Raised when there is no build to serve, so a caller can say what to run rather than stack-trace. */
31
+ export class NoWebBuild extends Error {
32
+ }
33
+ /**
34
+ * The embedded manifest for a directory of Vite output, keyed by the URL path each file was emitted
35
+ * at. Throws `NoWebBuild` unless the directory exists and carries an Entry Document, because a
36
+ * manifest without one is a web client that cannot be opened.
37
+ */
38
+ export function manifestOf(dist) {
39
+ if (!statSync(dist, { throwIfNoEntry: false })?.isDirectory()) {
40
+ throw new NoWebBuild(`no web build at ${dist}`);
41
+ }
42
+ const manifest = {};
43
+ for (const relPath of walk(dist).sort()) {
44
+ const [type, isText] = CONTENT_TYPES[extname(relPath)] ?? ["application/octet-stream", false];
45
+ const bytes = readFileSync(join(dist, relPath.split("/").join(sep)));
46
+ manifest[`/${relPath}`] = {
47
+ type: isText ? `${type}; charset=utf-8` : type,
48
+ encoding: isText ? "utf8" : "base64",
49
+ immutable: CONTENT_HASHED.test(posix.basename(relPath)),
50
+ body: isText ? bytes.toString("utf8") : bytes.toString("base64"),
51
+ };
52
+ }
53
+ if (!manifest["/index.html"])
54
+ throw new NoWebBuild(`no index.html under ${dist}`);
55
+ return manifest;
56
+ }
57
+ /** Every file at or under `target`, as `/`-separated paths relative to it. */
58
+ function walk(target) {
59
+ const found = [];
60
+ const descend = (directory, prefix) => {
61
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
62
+ if (entry.isDirectory())
63
+ descend(join(directory, entry.name), `${prefix}${entry.name}/`);
64
+ else
65
+ found.push(`${prefix}${entry.name}`);
66
+ }
67
+ };
68
+ descend(target, "");
69
+ return found;
70
+ }
@@ -0,0 +1,65 @@
1
+ export class Decisions {
2
+ nodes = [{ variable: Infinity, choices: [] }, { variable: Infinity, choices: [] }];
3
+ unique = new Map();
4
+ cache = new Map();
5
+ outcome(variable, choice) {
6
+ return this.node(variable, Array.from({ length: 5 }, (_, index) => Number(index === choice)));
7
+ }
8
+ and(left, right) { return this.apply('and', left, right); }
9
+ or(left, right) { return this.apply('or', left, right); }
10
+ not(value) {
11
+ if (value < 2)
12
+ return 1 - value;
13
+ const key = `not:${value}`;
14
+ const cached = this.cache.get(key);
15
+ if (cached !== undefined)
16
+ return cached;
17
+ const node = this.nodes[value];
18
+ const result = this.node(node.variable, node.choices.map(choice => this.not(choice)));
19
+ this.cache.set(key, result);
20
+ return result;
21
+ }
22
+ implies(left, right) { return this.and(left, this.not(right)) === 0; }
23
+ node(variable, choices) {
24
+ if (choices.every(choice => choice === choices[0]))
25
+ return choices[0];
26
+ const key = `${variable}:${choices.join(',')}`;
27
+ const existing = this.unique.get(key);
28
+ if (existing !== undefined)
29
+ return existing;
30
+ const id = this.nodes.length;
31
+ this.nodes.push({ variable, choices });
32
+ this.unique.set(key, id);
33
+ return id;
34
+ }
35
+ apply(operator, left, right) {
36
+ if (left === right)
37
+ return left;
38
+ if (operator === 'and') {
39
+ if (left === 0 || right === 0)
40
+ return 0;
41
+ if (left === 1)
42
+ return right;
43
+ if (right === 1)
44
+ return left;
45
+ }
46
+ else {
47
+ if (left === 1 || right === 1)
48
+ return 1;
49
+ if (left === 0)
50
+ return right;
51
+ if (right === 0)
52
+ return left;
53
+ }
54
+ const key = `${operator}:${Math.min(left, right)}:${Math.max(left, right)}`;
55
+ const cached = this.cache.get(key);
56
+ if (cached !== undefined)
57
+ return cached;
58
+ const a = this.nodes[left];
59
+ const b = this.nodes[right];
60
+ const variable = Math.min(a.variable, b.variable);
61
+ const result = this.node(variable, Array.from({ length: 5 }, (_, index) => this.apply(operator, a.variable === variable ? a.choices[index] : left, b.variable === variable ? b.choices[index] : right)));
62
+ this.cache.set(key, result);
63
+ return result;
64
+ }
65
+ }
@@ -0,0 +1,132 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, realpathSync, statSync } from 'node:fs';
3
+ import { isAbsolute } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { parseValue, toTypeScript } from "./schema.js";
6
+ const environment = { PATH: '/usr/local/bin:/usr/bin:/bin', LANG: 'C.UTF-8' };
7
+ const dockerHost = 'unix:///var/run/docker.sock';
8
+ function probe(command, args) {
9
+ if (!isAbsolute(command))
10
+ return Promise.resolve(false);
11
+ return new Promise(resolve => {
12
+ const child = spawn(command, args, { env: environment, stdio: 'ignore' });
13
+ const timer = setTimeout(() => { child.kill('SIGKILL'); resolve(false); }, 5000);
14
+ child.once('error', () => { clearTimeout(timer); resolve(false); });
15
+ child.once('close', code => { clearTimeout(timer); resolve(code === 0); });
16
+ });
17
+ }
18
+ export async function createCodeExecutors(options) {
19
+ const sandbox = options.sandbox;
20
+ const docker = sandbox.enabled ? sandbox.dockerPath ?? '/usr/bin/docker' : '';
21
+ const dockerArgs = ['--host', dockerHost];
22
+ const [nodeAvailable, runtimeAvailable] = await Promise.all([
23
+ probe(options.nodePath, ['-e', 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)']),
24
+ !sandbox.enabled || (sandbox.available && probe(docker, [...dockerArgs, 'image', 'inspect', sandbox.image])),
25
+ ]);
26
+ function check(step) {
27
+ if (!['shell', 'typescript'].includes(step.kind))
28
+ throw new Error('Unsupported executor kind');
29
+ if (process.platform === 'win32')
30
+ throw new Error('Code executors require POSIX');
31
+ if (!isAbsolute(options.runtimePath) || !existsSync(options.runtimePath) || !statSync(options.runtimePath).isFile())
32
+ throw new Error('Workflow runtime bundle is unavailable; run build:workflow-runtime');
33
+ if (sandbox.enabled) {
34
+ if (!runtimeAvailable)
35
+ throw new Error('External sandbox is enabled but unavailable');
36
+ }
37
+ if (!nodeAvailable)
38
+ throw new Error('Host Node 22 or later runtime is unavailable');
39
+ if (step.secrets && Object.keys(step.secrets).length && !options.resolveSecret)
40
+ throw new Error('Secret resolver is unavailable');
41
+ if (step.kind === 'shell' && Object.keys(step.secrets ?? {}).some(name => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || /^(PATH|OUTPUT|ENV|BASH_ENV|SHELLOPTS|BASHOPTS|LD_.*|DYLD_.*|NODE_.*)$/.test(name)))
42
+ throw new Error('Unsafe Shell secret environment name');
43
+ }
44
+ const executor = {
45
+ check,
46
+ async execute(context) {
47
+ check(context.step);
48
+ context.signal.throwIfAborted();
49
+ const secrets = Object.create(null);
50
+ for (const [name, reference] of Object.entries(context.step.secrets ?? {})) {
51
+ secrets[name] = await options.resolveSecret(reference, context.signal);
52
+ context.signal.throwIfAborted();
53
+ }
54
+ const inputSchema = context.inputSchema ?? context.step.inputSchema;
55
+ try {
56
+ const output = await executeRuntime(context, secrets, inputSchema);
57
+ context.signal.throwIfAborted();
58
+ return context.step.kind === 'typescript' ? parseValue(context.step.outputSchema, output) : output;
59
+ }
60
+ catch (error) {
61
+ throw new Error(redact(error instanceof Error ? error.message : String(error), secrets));
62
+ }
63
+ },
64
+ };
65
+ async function executeRuntime(context, secrets, inputSchema) {
66
+ const scope = realpathSync(context.scope);
67
+ const name = `flow-workflow-${randomUUID()}`;
68
+ const args = sandbox.enabled ? [...dockerArgs, 'run', '--rm', '--log-driver=none', '--pull=never', '--name', name, '--init', '--interactive', '--read-only', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--pids-limit=64', '--ulimit=core=0', '--memory=256m', '--memory-swap=256m', '--cpus=1', '--user', `${process.getuid()}:${process.getgid()}`, '--network=host', '--mount', `type=bind,src=${scope},dst=/scope`, '--mount', `type=bind,src=${realpathSync(options.runtimePath)},dst=/runtime.cjs,readonly`, '--workdir=/scope', '--entrypoint=node', sandbox.image, '--max-old-space-size=128', '/runtime.cjs'] : ['--noprofile', '--norc', '-c', 'ulimit -c 0; exec "$@"', 'flow-workflow', options.nodePath, '--max-old-space-size=128', options.runtimePath];
69
+ if (sandbox.enabled && (scope.includes(',') || options.runtimePath.includes(',')))
70
+ throw new Error('Runtime mount paths cannot contain commas');
71
+ const timeout = Math.min(context.step.timeoutMs ?? 60_000, 2_147_000_000);
72
+ const request = JSON.stringify({ ...context.step, scope: sandbox.enabled ? '/scope' : scope, input: context.input, inputType: inputSchema ? toTypeScript(inputSchema) : 'unknown', outputType: context.step.kind === 'typescript' ? toTypeScript(context.step.outputSchema) : 'unknown', secrets, timeout });
73
+ context.signal.throwIfAborted();
74
+ const child = spawn(sandbox.enabled ? options.nodePath : '/bin/bash', sandbox.enabled ? ['--max-old-space-size=128', options.runtimePath, '--docker-supervisor'] : args, { env: environment, stdio: ['pipe', 'pipe', 'pipe'] });
75
+ let stdout = '', stderr = '', stopped = false;
76
+ let killTimer;
77
+ const abort = () => {
78
+ if (stopped)
79
+ return;
80
+ stopped = true;
81
+ child.stdin.end();
82
+ if (!sandbox.enabled)
83
+ killTimer = setTimeout(() => { child.kill('SIGKILL'); }, 5000);
84
+ };
85
+ context.signal.addEventListener('abort', abort, { once: true });
86
+ child.stdin.on('error', () => { });
87
+ child.stdin.write((sandbox.enabled ? JSON.stringify({ docker, args, name, request: JSON.parse(request) }) : request) + '\n');
88
+ const heartbeat = setInterval(() => { if (!stopped)
89
+ child.stdin.write('\n'); }, 500);
90
+ const deadline = setTimeout(abort, timeout + 1000);
91
+ for (const [stream, label] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']])
92
+ stream.setEncoding('utf8').on('data', (chunk) => {
93
+ if (label === 'stdout')
94
+ stdout += chunk.toString();
95
+ else
96
+ stderr += chunk.toString();
97
+ });
98
+ try {
99
+ const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
100
+ if (code !== 0)
101
+ throw new Error(`Workflow runtime exited (${code}): ${stderr.slice(0, 1000)}`);
102
+ const response = JSON.parse(stdout);
103
+ if (Object.hasOwn(response, 'error'))
104
+ throw new Error(redact(response.error, secrets));
105
+ if (stopped || context.signal.aborted)
106
+ throw new Error('Code execution stopped');
107
+ return redactValue(response.output, secrets);
108
+ }
109
+ finally {
110
+ clearInterval(heartbeat);
111
+ clearTimeout(deadline);
112
+ clearTimeout(killTimer);
113
+ context.signal.removeEventListener('abort', abort);
114
+ }
115
+ }
116
+ return { shell: executor, typescript: executor };
117
+ }
118
+ function redactValue(value, secrets) {
119
+ if (typeof value === 'string')
120
+ return redact(value, secrets);
121
+ if (Array.isArray(value))
122
+ return value.map(item => redactValue(item, secrets));
123
+ if (value && typeof value === 'object')
124
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redact(key, secrets), redactValue(item, secrets)]));
125
+ return value;
126
+ }
127
+ function redact(text, secrets) {
128
+ const patterns = Object.values(secrets).filter(Boolean).flatMap(value => [value, JSON.stringify(value).slice(1, -1), JSON.stringify(JSON.stringify(value).slice(1, -1)).slice(1, -1)]).sort((a, b) => b.length - a.length);
129
+ for (const value of patterns)
130
+ text = text.split(value).join('[REDACTED]');
131
+ return text;
132
+ }