@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,518 @@
1
+ import { effortChoices, modelChoices } from "../client/model-choices.js";
2
+ import { initialState, reduce } from "../client/reduce.js";
3
+ import { sessionLabel } from "../client/session-label.js";
4
+ import { canSettle } from "../client/status.js";
5
+ import { answersOf, canCommit, cursorAfterTyping, cursorClamped, isFinished, rowsFor, startAnswering, toggled, } from "../client/enquiry.js";
6
+ import { permissionChoices } from "../client/permission.js";
7
+ import { isPrintable, KEY, splitKeys } from "./keys.js";
8
+ import { renderFrame } from "./render.js";
9
+ export async function runTui(options) {
10
+ const stdin = options.stdin ?? process.stdin;
11
+ const stdout = options.stdout ?? process.stdout;
12
+ let sessions = await options.connection.listSessions();
13
+ let selected = sessions[0]?.id;
14
+ let view = initialState();
15
+ let input = "";
16
+ // Enquiries borrow the composer without consuming the normal message draft.
17
+ let enquiryInput = "";
18
+ let overlay = { kind: "none" };
19
+ /**
20
+ * Where the human is up to in the Enquiry on screen, and which Enquiry that is.
21
+ *
22
+ * The id is held beside the state rather than inferred, so a second Enquiry cannot inherit the
23
+ * first's cursor and half-filled answers — `view.asking` changing identity is the only signal that
24
+ * this is a different question, and comparing the id is how that is noticed.
25
+ */
26
+ let answering;
27
+ let answeringFor;
28
+ /** The cursor in the Permission Prompt picker, and which prompt it belongs to. See `answering`. */
29
+ let deciding;
30
+ let decidingFor;
31
+ let notice;
32
+ let unsubscribe;
33
+ const draw = () => {
34
+ const ui = {
35
+ sessions,
36
+ selected,
37
+ view,
38
+ input: view.asking ? enquiryInput : input,
39
+ overlay,
40
+ ...(answering === undefined ? {} : { answering }),
41
+ ...(deciding === undefined ? {} : { deciding }),
42
+ now: Date.now(),
43
+ ...(notice ? { notice } : {}),
44
+ };
45
+ const frame = renderFrame(ui, { columns: stdout.columns ?? 80, rows: stdout.rows ?? 24 });
46
+ stdout.write(`${frame.join("\r\n")}`);
47
+ };
48
+ const attach = (sessionId) => {
49
+ unsubscribe?.();
50
+ selected = sessionId;
51
+ view = initialState();
52
+ unsubscribe = options.connection.subscribe({
53
+ sessionId,
54
+ since: 0,
55
+ onEntry: (entry) => {
56
+ const previousAsk = view.asking?.askId;
57
+ view = reduce(view, entry);
58
+ if (view.asking?.askId !== previousAsk)
59
+ enquiryInput = "";
60
+ draw();
61
+ },
62
+ onError: (error) => {
63
+ notice = error.message;
64
+ draw();
65
+ },
66
+ });
67
+ draw();
68
+ };
69
+ const refreshSessions = async () => {
70
+ sessions = await options.connection.listSessions();
71
+ };
72
+ const newSession = async (worktree) => {
73
+ try {
74
+ const id = await options.connection.command({
75
+ type: "create",
76
+ scope: options.scope,
77
+ ...(options.backend === undefined ? {} : { backend: options.backend }),
78
+ ...(worktree === undefined ? {} : { worktree }),
79
+ });
80
+ await refreshSessions();
81
+ attach(id);
82
+ }
83
+ catch (error) {
84
+ // A worktree the host would not cut leaves no Agent Session at all, so there is nothing to
85
+ // attach to and the reason is all there is to say.
86
+ notice = error instanceof Error ? error.message : "could not start an Agent Session";
87
+ }
88
+ };
89
+ /** The Scope of an Agent Session, for asking git about it. */
90
+ const scopeOf = (sessionId) => sessions.find((session) => session.id === sessionId)?.scope;
91
+ /**
92
+ * Open the branch list, having asked for it first.
93
+ *
94
+ * Asked at the moment it is opened rather than held, because it changes outside Flow — the
95
+ * same reason `/api/branches` is a query. A Scope that is not a repository opens nothing and says
96
+ * so, which is this client's version of hiding the control.
97
+ */
98
+ const openBranches = async (purpose, scope) => {
99
+ if (scope === undefined)
100
+ return;
101
+ let list;
102
+ try {
103
+ list = await options.connection.branches(scope);
104
+ }
105
+ catch (error) {
106
+ notice = error instanceof Error ? error.message : "could not read branches";
107
+ return;
108
+ }
109
+ if (!list.repository) {
110
+ notice = `${scope} is not a git repository`;
111
+ return;
112
+ }
113
+ const head = list.head?.detached ? undefined : list.head?.name;
114
+ overlay = {
115
+ kind: "branches",
116
+ purpose,
117
+ branches: list.branches,
118
+ index: Math.max(0, head ? list.branches.indexOf(head) : 0),
119
+ ...(head === undefined ? {} : { head }),
120
+ };
121
+ };
122
+ if (selected)
123
+ attach(selected);
124
+ else
125
+ await newSession();
126
+ stdin.setRawMode?.(true);
127
+ stdin.resume();
128
+ stdin.setEncoding("utf8");
129
+ stdout.on("resize", draw);
130
+ await new Promise((resolve) => {
131
+ const finish = () => {
132
+ unsubscribe?.();
133
+ stdin.setRawMode?.(false);
134
+ stdin.pause();
135
+ stdout.write("");
136
+ resolve();
137
+ };
138
+ // Chunks are processed one at a time. handleKey is async, so without this a chunk arriving
139
+ // mid-walk would interleave with the previous one and keys would be applied out of order.
140
+ let pending = Promise.resolve();
141
+ stdin.on("data", (chunk) => {
142
+ pending = pending.then(async () => {
143
+ try {
144
+ for (const key of splitKeys(chunk)) {
145
+ if (await handleKey(key)) {
146
+ finish();
147
+ return;
148
+ }
149
+ }
150
+ }
151
+ catch (error) {
152
+ notice = error instanceof Error ? error.message : String(error);
153
+ draw();
154
+ }
155
+ });
156
+ });
157
+ });
158
+ /** Returns true when the app should exit. */
159
+ async function handleKey(key) {
160
+ if (key === KEY.ctrlC)
161
+ return true;
162
+ if (overlay.kind !== "none") {
163
+ await handleOverlayKey(key);
164
+ draw();
165
+ return false;
166
+ }
167
+ /*
168
+ * An open Enquiry takes the prompt line, and takes it *after* the overlay branch: an overlay
169
+ * opened before the question arrived must still be closable. Nothing below this runs while one
170
+ * is open, which is the lockout — no message is sent, and `^K` is refused rather than silently
171
+ * doing nothing.
172
+ */
173
+ if (view.asking) {
174
+ await handleEnquiryKey(key);
175
+ draw();
176
+ return false;
177
+ }
178
+ /*
179
+ * A Permission Prompt takes the prompt line on the same terms and in the same place — after the
180
+ * overlay branch, above everything else. Nothing below runs while one is open, which is the
181
+ * lockout: the turn is blocked on a callback, so there is nothing a message could reach.
182
+ */
183
+ if (view.authorising) {
184
+ await handlePermissionKey(key);
185
+ draw();
186
+ return false;
187
+ }
188
+ if (key === KEY.ctrlS) {
189
+ await refreshSessions();
190
+ const index = sessions.findIndex((session) => session.id === selected);
191
+ overlay = { kind: "sessions", index: Math.max(0, index) };
192
+ }
193
+ else if (key === KEY.ctrlP) {
194
+ overlay = { kind: "models", index: 0 };
195
+ }
196
+ else if (key === KEY.ctrlE) {
197
+ overlay = { kind: "effort", index: Math.max(0, effortChoices(view).indexOf(view.effort ?? "off")) };
198
+ }
199
+ else if (key === KEY.ctrlG) {
200
+ await openBranches("switch", scopeOf(selected));
201
+ }
202
+ else if (key === KEY.ctrlK) {
203
+ await compact();
204
+ }
205
+ else if (key === KEY.escape) {
206
+ if (selected)
207
+ await options.connection.command({ type: "abort", sessionId: selected });
208
+ }
209
+ else if (key === KEY.enter || key === KEY.newline) {
210
+ await submit();
211
+ }
212
+ else if (key === KEY.backspace || key === KEY.backspaceAlt) {
213
+ input = input.slice(0, -1);
214
+ }
215
+ else if (isPrintable(key)) {
216
+ input += key;
217
+ }
218
+ draw();
219
+ return false;
220
+ }
221
+ /**
222
+ * Drive the Enquiry picker.
223
+ *
224
+ * The order of these branches is the whole rule, and it is the terminal's statement of the one the
225
+ * web client's key module states for the editor: **the moment the box has a character in it, the
226
+ * picker borrows only the keys a prompt line never needed.** The digits and Space are ordinary
227
+ * characters as far as anyone typing is concerned, so they are claimed only while `input` is
228
+ * empty — and both branches sit above the `isPrintable` one that would otherwise swallow them.
229
+ *
230
+ * Escape still aborts, as the status line has always said. The web client gives Escape to "go back
231
+ * a Question" because it has an Abort button to spare; here there is no button, so abort keeps the
232
+ * key and there is no going back. That asymmetry is deliberate and is named in both files.
233
+ */
234
+ async function handleEnquiryKey(key) {
235
+ const asking = view.asking;
236
+ if (!asking)
237
+ return;
238
+ // Restarted whenever the Enquiry changes, so a second question cannot inherit the first's cursor.
239
+ if (!answering || answeringFor !== asking.askId) {
240
+ answering = startAnswering(asking.questions);
241
+ answeringFor = asking.askId;
242
+ }
243
+ const state = answering;
244
+ const question = asking.questions[state.index];
245
+ if (!question)
246
+ return;
247
+ const rows = rowsFor(question, enquiryInput);
248
+ const chosen = state.chosen[state.index] ?? [];
249
+ if (key === KEY.escape) {
250
+ if (selected)
251
+ await options.connection.command({ type: "abort", sessionId: selected });
252
+ return;
253
+ }
254
+ if (key === KEY.up || key === KEY.down) {
255
+ // Clamped, not wrapped: every list in this TUI clamps, and the web client's every list wraps.
256
+ // Each front-end keeps its own idiom rather than the two of them growing a third.
257
+ state.cursor = cursorClamped(state.cursor, key === KEY.up ? -1 : 1, rows.length);
258
+ return;
259
+ }
260
+ if (enquiryInput === "" && /^[1-9]$/.test(key)) {
261
+ const row = rows[Number(key) - 1];
262
+ if (!row)
263
+ return;
264
+ state.cursor = Number(key) - 1;
265
+ if (question.multiSelect)
266
+ state.chosen[state.index] = toggled(chosen, row.label);
267
+ else
268
+ await commitAnswer(asking.questions, state, [row.label]);
269
+ return;
270
+ }
271
+ if (enquiryInput === "" && key === " " && question.multiSelect) {
272
+ const row = rows[state.cursor];
273
+ if (row)
274
+ state.chosen[state.index] = toggled(chosen, row.label);
275
+ return;
276
+ }
277
+ if (key === KEY.enter || key === KEY.newline) {
278
+ const row = rows[state.cursor];
279
+ const answer = question.multiSelect ? chosen : row ? [row.label] : [];
280
+ if (!canCommit(question, answer)) {
281
+ notice = "choose at least one, or type your own answer";
282
+ return;
283
+ }
284
+ await commitAnswer(asking.questions, state, answer);
285
+ return;
286
+ }
287
+ const had = enquiryInput.trim() !== "";
288
+ if (key === KEY.backspace || key === KEY.backspaceAlt)
289
+ enquiryInput = enquiryInput.slice(0, -1);
290
+ else if (isPrintable(key))
291
+ enquiryInput += key;
292
+ else
293
+ return;
294
+ state.cursor = cursorAfterTyping(state.cursor, had, enquiryInput.trim() !== "", rowsFor(question, enquiryInput).length);
295
+ }
296
+ /**
297
+ * Record one Question's Answer and move on — sending the whole Enquiry once the last one is in.
298
+ *
299
+ * One command at the end rather than one per Question, because the backend holds a single promise
300
+ * for the whole tool call. The pacing is this front-end's; the wire sees one answer.
301
+ */
302
+ async function commitAnswer(questions, state, answer) {
303
+ state.chosen[state.index] = answer;
304
+ state.index += 1;
305
+ state.cursor = 0;
306
+ enquiryInput = "";
307
+ if (!isFinished(state, questions))
308
+ return;
309
+ const askId = answeringFor;
310
+ answering = undefined;
311
+ answeringFor = undefined;
312
+ if (!selected || !askId)
313
+ return;
314
+ try {
315
+ await options.connection.command({
316
+ type: "answer_enquiry",
317
+ sessionId: selected,
318
+ askId,
319
+ answers: answersOf(state, questions),
320
+ });
321
+ }
322
+ catch (error) {
323
+ notice = error instanceof Error ? error.message : String(error);
324
+ }
325
+ }
326
+ /**
327
+ * Drive the Permission Prompt picker.
328
+ *
329
+ * Simpler than its Enquiry counterpart by the whole of what made that one hard: nothing is typed
330
+ * here, so there is no box to hold characters and no rule about which keys the picker may borrow
331
+ * once it does. Digits and Enter are unconditionally the picker's.
332
+ *
333
+ * **Escape denies rather than aborting**, which is where this parts company with the Enquiry
334
+ * branch above. Aborting a turn to refuse one tool call is a sledgehammer — a denial is the answer
335
+ * the model can carry on from, and it is the whole reason a Deny is not an Abort. Someone wanting
336
+ * to stop the turn can press it again once the prompt is gone.
337
+ */
338
+ async function handlePermissionKey(key) {
339
+ const authorising = view.authorising;
340
+ if (!authorising)
341
+ return;
342
+ // Restarted whenever the prompt changes, so a second call cannot inherit the first's cursor —
343
+ // which matters more here than for an Enquiry, since a cursor left on Always would put the
344
+ // widest decision under an unsuspecting Enter.
345
+ if (deciding === undefined || decidingFor !== authorising.callId) {
346
+ deciding = 0;
347
+ decidingFor = authorising.callId;
348
+ }
349
+ const choices = permissionChoices(authorising.allowAlways);
350
+ if (key === KEY.escape) {
351
+ await commitDecision(authorising.callId, "deny");
352
+ return;
353
+ }
354
+ if (key === KEY.up || key === KEY.down) {
355
+ // Clamped, not wrapped: every list in this TUI clamps. See `handleEnquiryKey`.
356
+ deciding = cursorClamped(deciding, key === KEY.up ? -1 : 1, choices.length);
357
+ return;
358
+ }
359
+ if (/^[1-9]$/.test(key)) {
360
+ const choice = choices[Number(key) - 1];
361
+ if (!choice)
362
+ return;
363
+ deciding = Number(key) - 1;
364
+ await commitDecision(authorising.callId, choice.decision);
365
+ return;
366
+ }
367
+ if (key === KEY.enter || key === KEY.newline) {
368
+ const choice = choices[deciding];
369
+ if (choice)
370
+ await commitDecision(authorising.callId, choice.decision);
371
+ }
372
+ }
373
+ async function commitDecision(callId, decision) {
374
+ deciding = undefined;
375
+ decidingFor = undefined;
376
+ if (!selected)
377
+ return;
378
+ try {
379
+ await options.connection.command({ type: "answer_permission", sessionId: selected, callId, decision });
380
+ }
381
+ catch (error) {
382
+ notice = error instanceof Error ? error.message : String(error);
383
+ }
384
+ }
385
+ async function handleOverlayKey(key) {
386
+ // Snapshot the overlay: TypeScript cannot narrow a mutable closure variable across a guard.
387
+ const current = overlay;
388
+ if (current.kind === "none")
389
+ return;
390
+ if (key === KEY.escape) {
391
+ overlay = { kind: "none" };
392
+ return;
393
+ }
394
+ const length = current.kind === "sessions"
395
+ ? sessions.length
396
+ : current.kind === "effort"
397
+ ? effortChoices(view).length
398
+ : current.kind === "branches"
399
+ ? current.branches.length
400
+ : modelChoices(view.capabilities).length;
401
+ if (key === KEY.up) {
402
+ overlay = { ...current, index: Math.max(0, current.index - 1) };
403
+ return;
404
+ }
405
+ if (key === KEY.down) {
406
+ overlay = { ...current, index: Math.min(length - 1, current.index + 1) };
407
+ return;
408
+ }
409
+ if (key === "n" && current.kind === "sessions") {
410
+ overlay = { kind: "none" };
411
+ await newSession();
412
+ return;
413
+ }
414
+ if (key === "w" && current.kind === "sessions") {
415
+ // A worktree needs a branch to be cut from, and the TUI has no text entry outside the prompt
416
+ // line — so the base is picked from a list, and the new branch's name is derived by the host.
417
+ await openBranches("cut", options.scope);
418
+ return;
419
+ }
420
+ if (key === "s" && current.kind === "sessions") {
421
+ const chosen = sessions[current.index];
422
+ // A Settled Agent Session has nothing to Settle and an Ended one refuses, so offer neither.
423
+ if (!chosen || !canSettle(chosen.status))
424
+ return;
425
+ await options.connection.command({ type: "settle", sessionId: chosen.id });
426
+ await refreshSessions();
427
+ // Stay in the list rather than attaching. Settling is filing something away, not choosing
428
+ // what to work on next, and the settled session has just sunk to the bottom anyway.
429
+ overlay = { kind: "sessions", index: Math.min(current.index, Math.max(0, sessions.length - 1)) };
430
+ notice = `settled ${sessionLabel(chosen)}`;
431
+ return;
432
+ }
433
+ if (key !== KEY.enter && key !== KEY.newline)
434
+ return;
435
+ if (current.kind === "sessions") {
436
+ const chosen = sessions[current.index];
437
+ overlay = { kind: "none" };
438
+ if (chosen)
439
+ attach(chosen.id);
440
+ return;
441
+ }
442
+ if (current.kind === "branches") {
443
+ const branch = current.branches[current.index];
444
+ const { purpose } = current;
445
+ overlay = { kind: "none" };
446
+ if (!branch)
447
+ return;
448
+ if (purpose === "cut") {
449
+ await newSession({ from: branch });
450
+ return;
451
+ }
452
+ if (!selected)
453
+ return;
454
+ try {
455
+ await options.connection.command({ type: "switch_branch", sessionId: selected, branch });
456
+ notice = `branch → ${branch}`;
457
+ }
458
+ catch (error) {
459
+ // A refusal carries the reason — a turn in flight, or git's own words about a checkout it
460
+ // would not make — and it is the whole of what is worth showing.
461
+ notice = error instanceof Error ? error.message : `could not switch to ${branch}`;
462
+ }
463
+ return;
464
+ }
465
+ if (current.kind === "effort") {
466
+ const effort = effortChoices(view)[current.index];
467
+ overlay = { kind: "none" };
468
+ if (effort && selected) {
469
+ await options.connection.command({ type: "set_effort", sessionId: selected, effort });
470
+ notice = `effort → ${effort}`;
471
+ }
472
+ return;
473
+ }
474
+ const choice = modelChoices(view.capabilities)[current.index];
475
+ overlay = { kind: "none" };
476
+ if (choice && selected) {
477
+ await options.connection.command({ type: "set_model", sessionId: selected, modelId: choice.model.id });
478
+ notice = `model → ${choice.model.label ?? choice.model.id}`;
479
+ }
480
+ }
481
+ /**
482
+ * Ask the backend to compact the Conversation Context.
483
+ *
484
+ * The refusals live in the Session Host, not here — Dormant, Settled and mid-turn are all 409s
485
+ * with a sentence saying which — so this sends and reports whatever comes back rather than
486
+ * reimplementing that judgement against a `view` that can be a frame behind. The one thing it does
487
+ * check locally is the capability, because a backend that cannot compact at all should say so
488
+ * without a round trip.
489
+ */
490
+ async function compact() {
491
+ if (!selected)
492
+ return;
493
+ if (!view.capabilities?.compaction) {
494
+ notice = "this backend cannot compact";
495
+ return;
496
+ }
497
+ try {
498
+ await options.connection.command({ type: "compact", sessionId: selected });
499
+ notice = "compacting…";
500
+ }
501
+ catch (error) {
502
+ notice = error instanceof Error ? error.message : String(error);
503
+ }
504
+ }
505
+ async function submit() {
506
+ const text = input.trim();
507
+ if (!text || !selected)
508
+ return;
509
+ input = "";
510
+ // Always after_turn, never derived from our own status. The Session Host marks a turn in flight
511
+ // when it dispatches rather than when the backend reports turn_started, and only after_turn is
512
+ // guarded by that flag — so a client that believed itself idle on the strength of turn_started
513
+ // would prompt a busy backend and bypass the Steering Queue ADR 0002 exists to own. after_turn
514
+ // already means "queue if busy, else dispatch now", so it is identical in every other case.
515
+ // "now" stays in the protocol for a deliberate interrupt-and-steer, which is not this.
516
+ await options.connection.command({ type: "send", sessionId: selected, text, when: "after_turn" });
517
+ }
518
+ }
@@ -0,0 +1,54 @@
1
+ /** Terminal key sequences, named so the input handler reads as intent rather than escape codes. */
2
+ export const KEY = {
3
+ ctrlC: "\u0003",
4
+ ctrlE: "\u0005",
5
+ /**
6
+ * Branches.
7
+ *
8
+ * `^G` for git rather than the obvious `^B` for branch: `^B` is tmux's default prefix, and this
9
+ * is a client people run inside tmux.
10
+ *
11
+ * `^K` compacts the Conversation Context. A chord and not an unmodified key for the reason the
12
+ * web client keeps its Revive one click inside a menu: it asks the backend to summarise, and that
13
+ * spends tokens.
14
+ */
15
+ ctrlG: "\u0007",
16
+ ctrlK: "\u000b",
17
+ ctrlP: "\u0010",
18
+ ctrlS: "\u0013",
19
+ escape: "\u001b",
20
+ enter: "\r",
21
+ newline: "\n",
22
+ backspace: "\u007f",
23
+ backspaceAlt: "\b",
24
+ up: "\u001b[A",
25
+ down: "\u001b[B",
26
+ };
27
+ export function isPrintable(key) {
28
+ return key.length === 1 && key >= " " && key !== KEY.backspace;
29
+ }
30
+ /**
31
+ * Split a stdin chunk into individual keys.
32
+ *
33
+ * A chunk is not a keystroke: a paste arrives as one chunk of many characters, and an arrow key
34
+ * arrives as a three-byte escape sequence. Treating a chunk as one key silently drops both.
35
+ */
36
+ export function splitKeys(chunk) {
37
+ const keys = [];
38
+ let index = 0;
39
+ while (index < chunk.length) {
40
+ const char = chunk[index] ?? "";
41
+ if (char === "\u001b" && chunk[index + 1] === "[") {
42
+ // CSI sequence: ESC [ ... final byte in @-~
43
+ let end = index + 2;
44
+ while (end < chunk.length && !/[@-~]/.test(chunk[end] ?? ""))
45
+ end += 1;
46
+ keys.push(chunk.slice(index, end + 1));
47
+ index = end + 1;
48
+ continue;
49
+ }
50
+ keys.push(char);
51
+ index += 1;
52
+ }
53
+ return keys;
54
+ }