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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +5 -19
  2. package/dist/build-id +1 -1
  3. package/dist/cli/application.js +4 -37
  4. package/dist/cli/bootstrap.js +2 -2
  5. package/dist/cli/install-guard.js +1 -1
  6. package/dist/client/context-usage.js +2 -3
  7. package/dist/client/enquiry.js +0 -6
  8. package/dist/client/model-choices.js +1 -1
  9. package/dist/client/permission.js +1 -2
  10. package/dist/client/relative-time.js +1 -1
  11. package/dist/client/scope-kind.js +2 -3
  12. package/dist/client/search.js +1 -1
  13. package/dist/client/status.js +1 -1
  14. package/dist/client/subagent-tree.js +1 -1
  15. package/dist/client/tool-chains.js +1 -1
  16. package/dist/client/tool-summary.js +2 -3
  17. package/dist/daemon/config-store.js +2 -0
  18. package/dist/daemon/config.js +32 -1
  19. package/dist/daemon/git.js +33 -2
  20. package/dist/daemon/host.js +12 -3
  21. package/dist/daemon/runtime.js +1 -1
  22. package/dist/daemon/server.js +2 -2
  23. package/dist/daemon/workflow-schedule-driver.js +5 -1
  24. package/dist/workflows/schedules.js +1 -0
  25. package/package.json +1 -1
  26. package/web/dist/assets/index-5E7qbtVD.js +51 -0
  27. package/web/dist/assets/{switch-B00FEUA7.js → select-C-BND5Jn.js} +1 -1
  28. package/web/dist/assets/{settings-mcp-3cgqQB28.js → settings-mcp-CBXZt_cf.js} +1 -1
  29. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-29ZG3w6p.js} +1 -1
  30. package/web/dist/assets/{settings-workflows-Cutm8isB.js → settings-workflows-CE11fxNj.js} +2 -2
  31. package/web/dist/assets/workflow-api-DkUjAZ4w.js +6 -0
  32. package/web/dist/assets/{workflows-D6oEUUhj.js → workflows-DdogjBu3.js} +5 -5
  33. package/web/dist/assets/{workflows-pane-KIdSDKJB.js → workflows-pane-B0dyuSuz.js} +1 -1
  34. package/web/dist/index.html +4 -4
  35. package/dist/tui/app.js +0 -612
  36. package/dist/tui/keys.js +0 -90
  37. package/dist/tui/render.js +0 -417
  38. package/web/dist/assets/index-BhfJhrVJ.js +0 -51
  39. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
@@ -1 +1 @@
1
- import{a as e}from"./rolldown-runtime-B0Z9INg1.js";import{Pn as t,kr as n,n as r,t as i,wr as a}from"./workflow-api-BfExddae.js";import{C as o,S as s,_t as c,d as l,ht as u,pt as d,u as f,x as p}from"./workflows-D6oEUUhj.js";import{a as m,c as h,n as g,r as _,s as v}from"./switch-B00FEUA7.js";import{t as y}from"./index-BhfJhrVJ.js";var b=e(n(),1),x=a();function S({sessionId:e,placement:n=`right`,mobileNavigation:a}){let S=i(`/api/workflows`),C=`/api/sessions/${encodeURIComponent(e)}/workflows`,w=i(C),[T,E]=(0,b.useState)(()=>c(e)),[D,O]=(0,b.useState)(T?.workflowId??``),[k,A]=(0,b.useState)(T?.input??{}),[j,M]=(0,b.useState)(``),[N,P]=(0,b.useState)(T?.error??``),[F,I]=(0,b.useState)(!1),[L,R]=(0,b.useState)(T!==void 0),z=i(j?`${C}/${j}`:void 0,1e3),{sessions:B}=d(),V=B.find(t=>t.id===e),H=S.data?.workflows.find(e=>e.id===D),U=z.data?.execution,W=!!(z.data?.enquiries.length||z.data?.permissions.length),G=[...w.data?.executions??[]].sort((e,t)=>t.startedAt-e.startedAt);(0,b.useEffect)(()=>{let t=c(e);E(t),O(t?.workflowId??``),A(t?.input??{}),M(``),P(t?.error??``),R(t!==void 0)},[e]),(0,b.useEffect)(()=>{if(j||!G.length)return;let e=G.find(e=>e.status===`running`||e.status===`recovery-required`);M((e??G[0]).id)},[j,w.data]);let K=``;try{H&&(s(H),o(H.inputSchema,k))}catch(e){K=p(e)}let q=H&&V&&H.backend!==V.backend,J=async(t,n)=>{I(!0);try{let i=await r(t,`POST`,n);i.execution&&(M(i.execution.id),R(!1),t===C&&(u(e),E(void 0))),P(`Request accepted`)}catch(e){P(p(e))}finally{I(!1)}};return(0,x.jsxs)(`section`,{className:`workflow-panel grid grid-cols-[minmax(0,1fr)] content-start gap-3 overflow-auto p-3 text-sm`,children:[(0,x.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,x.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workflows`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`,onClick:()=>R(e=>!e),children:L?`Close`:`New workflow`})]}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Independent of parent chat. Steps share this Scope.`}),(S.error||w.error||z.error||N)&&(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:N||S.error||w.error||z.error}),T&&(0,x.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3`,role:`alert`,children:[(0,x.jsx)(`p`,{className:`font-medium`,children:`Workflow did not start`}),(0,x.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`This Agent Session was kept. Review the preserved inputs below and retry here; retrying will not create another Agent Session.`})]}),L&&!w.data?.occupied&&(0,x.jsx)(`section`,{"aria-label":`New workflow`,children:(0,x.jsxs)(`div`,{className:`grid gap-3 pt-2`,children:[(0,x.jsxs)(g,{value:D,onValueChange:e=>{if(e===null)return;O(e);let t=S.data?.workflows.find(t=>t.id===e);A(t?l(t.inputSchema):{})},children:[(0,x.jsx)(v,{className:`w-full`,"aria-label":`Workflow`,children:(0,x.jsx)(h,{children:H?.name??`Select workflow`})}),(0,x.jsxs)(_,{children:[(0,x.jsx)(m,{value:``,children:`Select workflow`}),S.data?.workflows.map(e=>(0,x.jsx)(m,{value:e.id,children:e.name},e.id))]})]}),H&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(f,{schema:H.inputSchema,value:k,onChange:A}),q&&(0,x.jsxs)(`p`,{role:`alert`,children:[`This workflow requires Backend Adapter `,H.backend,`.`,` `,(0,x.jsx)(`a`,{className:`underline`,href:`#/new/${encodeURIComponent(H.backend)}`,children:`Create a matching Agent Session`}),`.`]}),K&&(0,x.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono text-xs text-destructive`,role:`alert`,children:K}),(0,x.jsx)(t,{size:`sm`,className:`justify-self-start`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`||!!K||!!q,onClick:()=>void J(C,{workflowId:D,input:k,...T?{launchId:T.launchId,nameSession:!0}:{}}),children:T?`Retry workflow`:`Start workflow`})]})]})}),(0,x.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,x.jsx)(`span`,{className:`text-sm font-medium`,children:`Execution history`}),(0,x.jsxs)(g,{items:[{value:``,label:`Select execution`},...G.map(e=>({value:e.id,label:`${e.name} · ${e.status.replaceAll(`-`,` `)} · ${new Date(e.startedAt).toLocaleString()}${e.testStepId?` · step test`:``}`}))],disabled:F,value:j,onValueChange:e=>{e!==null&&(M(e),a?.onBack())},children:[(0,x.jsx)(v,{className:`w-full`,"aria-label":`Execution history`,children:(0,x.jsx)(h,{})}),(0,x.jsxs)(_,{children:[(0,x.jsx)(m,{value:``,children:`Select execution`}),G.map(e=>(0,x.jsxs)(m,{value:e.id,children:[e.name,` · `,e.status.replaceAll(`-`,` `),` · `,new Date(e.startedAt).toLocaleString(),e.testStepId?` · step test`:``]},e.id))]})]})]}),U&&(0,x.jsxs)(x.Fragment,{children:[[`running`,`recovery-required`].includes(U.status)&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Cancel stops work; it does not undo changes.`}),(0,x.jsx)(t,{size:`sm`,variant:`destructive`,className:`justify-self-start`,disabled:F,onClick:()=>void J(`${C}/${j}/cancel`),children:`Cancel execution`})]}),U.status===`recovery-required`&&(0,x.jsx)(`p`,{children:`Ask the parent in chat to diagnose and recover this execution.`}),W&&(0,x.jsxs)(`section`,{"aria-label":`Workflow input actions`,className:`grid gap-2`,children:[(0,x.jsx)(`h4`,{className:`font-medium`,children:`Input requested in parent chat`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The parent relays one request at a time using the normal composer controls. This pane stays on the execution so management actions remain available.`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:V?.status===`dormant`||V?.status===`settled`?`Revive the parent manually to continue. The request will remain pending here.`:V?.status===`running`||V?.status===`awaiting`?`The request is queued behind the parent’s current turn.`:`The parent is preparing the next request.`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,className:`justify-self-start`,onClick:()=>document.querySelector(`[data-pane] [data-composer-input]`)?.focus(),children:`Go to parent chat`})]}),z.data&&(0,x.jsx)(y,{view:z.data,detailBase:`${C}/${j}`,transcriptBase:`${C}/${j}`,placement:n,mobileNavigation:a},`${e}/${j}`)]})]})}export{S as default};
1
+ import{a as e}from"./rolldown-runtime-B0Z9INg1.js";import{Pn as t,kr as n,n as r,t as i,wr as a}from"./workflow-api-DkUjAZ4w.js";import{C as o,S as s,_t as c,d as l,ht as u,pt as d,u as f,x as p}from"./workflows-DdogjBu3.js";import{i as m,n as h,o as g,s as _,t as v}from"./select-C-BND5Jn.js";import{t as y}from"./index-5E7qbtVD.js";var b=e(n(),1),x=a();function S({sessionId:e,placement:n=`right`,mobileNavigation:a}){let S=i(`/api/workflows`),C=`/api/sessions/${encodeURIComponent(e)}/workflows`,w=i(C),[T,E]=(0,b.useState)(()=>c(e)),[D,O]=(0,b.useState)(T?.workflowId??``),[k,A]=(0,b.useState)(T?.input??{}),[j,M]=(0,b.useState)(``),[N,P]=(0,b.useState)(T?.error??``),[F,I]=(0,b.useState)(!1),[L,R]=(0,b.useState)(T!==void 0),z=i(j?`${C}/${j}`:void 0,1e3),{sessions:B}=d(),V=B.find(t=>t.id===e),H=S.data?.workflows.find(e=>e.id===D),U=z.data?.execution,W=!!(z.data?.enquiries.length||z.data?.permissions.length),G=[...w.data?.executions??[]].sort((e,t)=>t.startedAt-e.startedAt);(0,b.useEffect)(()=>{let t=c(e);E(t),O(t?.workflowId??``),A(t?.input??{}),M(``),P(t?.error??``),R(t!==void 0)},[e]),(0,b.useEffect)(()=>{if(j||!G.length)return;let e=G.find(e=>e.status===`running`||e.status===`recovery-required`);M((e??G[0]).id)},[j,w.data]);let K=``;try{H&&(s(H),o(H.inputSchema,k))}catch(e){K=p(e)}let q=H&&V&&H.backend!==V.backend,J=async(t,n)=>{I(!0);try{let i=await r(t,`POST`,n);i.execution&&(M(i.execution.id),R(!1),t===C&&(u(e),E(void 0))),P(`Request accepted`)}catch(e){P(p(e))}finally{I(!1)}};return(0,x.jsxs)(`section`,{className:`workflow-panel grid grid-cols-[minmax(0,1fr)] content-start gap-3 overflow-auto p-3 text-sm`,children:[(0,x.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,x.jsx)(`h2`,{className:`text-sm font-semibold`,children:`Workflows`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`,onClick:()=>R(e=>!e),children:L?`Close`:`New workflow`})]}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Independent of parent chat. Steps share this Scope.`}),(S.error||w.error||z.error||N)&&(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:N||S.error||w.error||z.error}),T&&(0,x.jsxs)(`div`,{className:`rounded-lg border border-destructive/40 bg-destructive/5 p-3`,role:`alert`,children:[(0,x.jsx)(`p`,{className:`font-medium`,children:`Workflow did not start`}),(0,x.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`This Agent Session was kept. Review the preserved inputs below and retry here; retrying will not create another Agent Session.`})]}),L&&!w.data?.occupied&&(0,x.jsx)(`section`,{"aria-label":`New workflow`,children:(0,x.jsxs)(`div`,{className:`grid gap-3 pt-2`,children:[(0,x.jsxs)(v,{value:D,onValueChange:e=>{if(e===null)return;O(e);let t=S.data?.workflows.find(t=>t.id===e);A(t?l(t.inputSchema):{})},children:[(0,x.jsx)(g,{className:`w-full`,"aria-label":`Workflow`,children:(0,x.jsx)(_,{children:H?.name??`Select workflow`})}),(0,x.jsxs)(h,{children:[(0,x.jsx)(m,{value:``,children:`Select workflow`}),S.data?.workflows.map(e=>(0,x.jsx)(m,{value:e.id,children:e.name},e.id))]})]}),H&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(f,{schema:H.inputSchema,value:k,onChange:A}),q&&(0,x.jsxs)(`p`,{role:`alert`,children:[`This workflow requires Backend Adapter `,H.backend,`.`,` `,(0,x.jsx)(`a`,{className:`underline`,href:`#/new/${encodeURIComponent(H.backend)}`,children:`Create a matching Agent Session`}),`.`]}),K&&(0,x.jsx)(`pre`,{className:`whitespace-pre-wrap break-words font-mono text-xs text-destructive`,role:`alert`,children:K}),(0,x.jsx)(t,{size:`sm`,className:`justify-self-start`,disabled:F||!w.data||w.data.occupied||V?.status===`ended`||!!K||!!q,onClick:()=>void J(C,{workflowId:D,input:k,...T?{launchId:T.launchId,nameSession:!0}:{}}),children:T?`Retry workflow`:`Start workflow`})]})]})}),(0,x.jsxs)(`label`,{className:`flex flex-col gap-1`,children:[(0,x.jsx)(`span`,{className:`text-sm font-medium`,children:`Execution history`}),(0,x.jsxs)(v,{items:[{value:``,label:`Select execution`},...G.map(e=>({value:e.id,label:`${e.name} · ${e.status.replaceAll(`-`,` `)} · ${new Date(e.startedAt).toLocaleString()}${e.testStepId?` · step test`:``}`}))],disabled:F,value:j,onValueChange:e=>{e!==null&&(M(e),a?.onBack())},children:[(0,x.jsx)(g,{className:`w-full`,"aria-label":`Execution history`,children:(0,x.jsx)(_,{})}),(0,x.jsxs)(h,{children:[(0,x.jsx)(m,{value:``,children:`Select execution`}),G.map(e=>(0,x.jsxs)(m,{value:e.id,children:[e.name,` · `,e.status.replaceAll(`-`,` `),` · `,new Date(e.startedAt).toLocaleString(),e.testStepId?` · step test`:``]},e.id))]})]})]}),U&&(0,x.jsxs)(x.Fragment,{children:[[`running`,`recovery-required`].includes(U.status)&&(0,x.jsxs)(x.Fragment,{children:[(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Cancel stops work; it does not undo changes.`}),(0,x.jsx)(t,{size:`sm`,variant:`destructive`,className:`justify-self-start`,disabled:F,onClick:()=>void J(`${C}/${j}/cancel`),children:`Cancel execution`})]}),U.status===`recovery-required`&&(0,x.jsx)(`p`,{children:`Ask the parent in chat to diagnose and recover this execution.`}),W&&(0,x.jsxs)(`section`,{"aria-label":`Workflow input actions`,className:`grid gap-2`,children:[(0,x.jsx)(`h4`,{className:`font-medium`,children:`Input requested in parent chat`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`The parent relays one request at a time using the normal composer controls. This pane stays on the execution so management actions remain available.`}),(0,x.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:V?.status===`dormant`||V?.status===`settled`?`Revive the parent manually to continue. The request will remain pending here.`:V?.status===`running`||V?.status===`awaiting`?`The request is queued behind the parent’s current turn.`:`The parent is preparing the next request.`}),(0,x.jsx)(t,{size:`sm`,variant:`outline`,className:`justify-self-start`,onClick:()=>document.querySelector(`[data-pane] [data-composer-input]`)?.focus(),children:`Go to parent chat`})]}),z.data&&(0,x.jsx)(y,{view:z.data,detailBase:`${C}/${j}`,transcriptBase:`${C}/${j}`,placement:n,mobileNavigation:a},`${e}/${j}`)]})]})}export{S as default};
@@ -26,11 +26,11 @@
26
26
  document.documentElement.style.colorScheme = "light";
27
27
  }
28
28
  </script>
29
- <script type="module" crossorigin src="/assets/index-BhfJhrVJ.js"></script>
29
+ <script type="module" crossorigin src="/assets/index-5E7qbtVD.js"></script>
30
30
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-B0Z9INg1.js">
31
- <link rel="modulepreload" crossorigin href="/assets/workflow-api-BfExddae.js">
32
- <link rel="modulepreload" crossorigin href="/assets/switch-B00FEUA7.js">
33
- <link rel="modulepreload" crossorigin href="/assets/workflows-D6oEUUhj.js">
31
+ <link rel="modulepreload" crossorigin href="/assets/workflow-api-DkUjAZ4w.js">
32
+ <link rel="modulepreload" crossorigin href="/assets/select-C-BND5Jn.js">
33
+ <link rel="modulepreload" crossorigin href="/assets/workflows-DdogjBu3.js">
34
34
  <link rel="stylesheet" crossorigin href="/assets/workflows-Bb90N0XJ.css">
35
35
  <link rel="stylesheet" crossorigin href="/assets/index-BvkM2cWL.css">
36
36
  </head>
package/dist/tui/app.js DELETED
@@ -1,612 +0,0 @@
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, KeySplitter, KEY } 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
- // Assume focus until a terminal answers DECSET 1004 with an event. Terminals that do not support
34
- // focus reporting ignore the mode and retain the documented fallback; supporting ones stop a
35
- // background window from consuming attention.
36
- let focused = true;
37
- let stopped = false;
38
- let refreshGeneration = 0;
39
- const acknowledged = new Map();
40
- const draw = () => {
41
- const ui = {
42
- sessions,
43
- selected,
44
- view,
45
- input: view.asking ? enquiryInput : input,
46
- overlay,
47
- ...(answering === undefined ? {} : { answering }),
48
- ...(deciding === undefined ? {} : { deciding }),
49
- now: Date.now(),
50
- ...(notice ? { notice } : {}),
51
- };
52
- const frame = renderFrame(ui, { columns: stdout.columns ?? 80, rows: stdout.rows ?? 24 });
53
- stdout.write(`${frame.join("\r\n")}`);
54
- };
55
- const refreshSessions = async () => {
56
- const generation = ++refreshGeneration;
57
- const next = await options.connection.listSessions();
58
- // Polling, focus events, commands, and overlays may all refresh concurrently. Only the newest
59
- // issued request may publish; otherwise a slow old response can restore stale inbox ordering.
60
- if (generation !== refreshGeneration)
61
- return;
62
- // A list refresh may move the cursor into another attention group. Preserve what it addressed
63
- // by identity; headings never enter the selectable sessions array.
64
- const cursorId = overlay.kind === "sessions" ? sessions[overlay.index]?.id : undefined;
65
- sessions = next;
66
- if (overlay.kind === "sessions" && cursorId) {
67
- const moved = sessions.findIndex((session) => session.id === cursorId);
68
- overlay = { kind: "sessions", index: moved < 0 ? Math.min(overlay.index, Math.max(0, sessions.length - 1)) : moved };
69
- }
70
- };
71
- const acknowledgeVisible = async () => {
72
- if (!focused || !selected || overlay.kind !== "none")
73
- return;
74
- const summary = sessions.find((session) => session.id === selected);
75
- const attention = summary?.attention;
76
- if (!attention || view.lastSeq < attention.observedSeq || (acknowledged.get(selected) ?? -1) >= attention.version)
77
- return;
78
- acknowledged.set(selected, attention.version);
79
- try {
80
- await options.connection.command({ type: "acknowledge", sessionId: selected, throughVersion: attention.version });
81
- }
82
- catch (error) {
83
- if (acknowledged.get(selected) === attention.version)
84
- acknowledged.delete(selected);
85
- throw error;
86
- }
87
- };
88
- const attach = (sessionId) => {
89
- unsubscribe?.();
90
- selected = sessionId;
91
- view = initialState();
92
- unsubscribe = options.connection.subscribe({
93
- sessionId,
94
- since: 0,
95
- onEntry: (entry) => {
96
- const previousAsk = view.asking?.askId;
97
- view = reduce(view, entry);
98
- if (view.asking?.askId !== previousAsk)
99
- enquiryInput = "";
100
- draw();
101
- // The transcript has been drawn at its tail. The summary's exact version makes a delayed
102
- // command harmless if newer output lands before it reaches the host.
103
- void acknowledgeVisible().catch(() => { });
104
- },
105
- onError: (error) => {
106
- notice = error.message;
107
- draw();
108
- },
109
- });
110
- draw();
111
- void acknowledgeVisible().catch(() => { });
112
- };
113
- const newSession = async (worktree) => {
114
- try {
115
- const id = await options.connection.command({
116
- type: "create",
117
- scope: options.scope,
118
- ...(options.backend === undefined ? {} : { backend: options.backend }),
119
- ...(worktree === undefined ? {} : { worktree }),
120
- });
121
- await refreshSessions();
122
- attach(id);
123
- }
124
- catch (error) {
125
- // A worktree the host would not cut leaves no Agent Session at all, so there is nothing to
126
- // attach to and the reason is all there is to say.
127
- notice = error instanceof Error ? error.message : "could not start an Agent Session";
128
- }
129
- };
130
- /** The Scope of an Agent Session, for asking git about it. */
131
- const scopeOf = (sessionId) => sessions.find((session) => session.id === sessionId)?.scope;
132
- /**
133
- * Open the branch list, having asked for it first.
134
- *
135
- * Asked at the moment it is opened rather than held, because it changes outside Flow — the
136
- * same reason `/api/branches` is a query. A Scope that is not a repository opens nothing and says
137
- * so, which is this client's version of hiding the control.
138
- */
139
- const openBranches = async (purpose, scope) => {
140
- if (scope === undefined)
141
- return;
142
- let list;
143
- try {
144
- list = await options.connection.branches(scope);
145
- }
146
- catch (error) {
147
- notice = error instanceof Error ? error.message : "could not read branches";
148
- return;
149
- }
150
- if (!list.repository) {
151
- notice = `${scope} is not a git repository`;
152
- return;
153
- }
154
- const head = list.head?.detached ? undefined : list.head?.name;
155
- overlay = {
156
- kind: "branches",
157
- purpose,
158
- branches: list.branches,
159
- index: Math.max(0, head ? list.branches.indexOf(head) : 0),
160
- ...(head === undefined ? {} : { head }),
161
- };
162
- };
163
- if (selected)
164
- attach(selected);
165
- else
166
- await newSession();
167
- stdin.setRawMode?.(true);
168
- stdin.resume();
169
- stdin.setEncoding("utf8");
170
- // Ask terminals that support it to report ESC [ I / ESC [ O. Unsupported terminals ignore this
171
- // mode, in which case `focused` deliberately remains true.
172
- if (stdin.isTTY)
173
- stdout.write("\u001b[?1004h");
174
- stdout.on("resize", draw);
175
- let refreshTimer;
176
- function schedulePoll() {
177
- if (!stopped)
178
- refreshTimer = setTimeout(() => void poll(), 2_000);
179
- }
180
- async function poll() {
181
- try {
182
- await refreshSessions();
183
- if (!stopped) {
184
- draw();
185
- await acknowledgeVisible();
186
- }
187
- }
188
- catch { }
189
- schedulePoll();
190
- }
191
- schedulePoll();
192
- await new Promise((resolve) => {
193
- const finish = () => {
194
- if (stopped)
195
- return;
196
- stopped = true;
197
- refreshGeneration++;
198
- if (refreshTimer)
199
- clearTimeout(refreshTimer);
200
- unsubscribe?.();
201
- if (stdin.isTTY)
202
- stdout.write("\u001b[?1004l");
203
- stdin.setRawMode?.(false);
204
- stdin.pause();
205
- stdout.write("");
206
- resolve();
207
- };
208
- // Chunks are processed one at a time. handleKey is async, so without this a chunk arriving
209
- // mid-walk would interleave with the previous one and keys would be applied out of order.
210
- let pending = Promise.resolve();
211
- const processKeys = (received) => {
212
- // Focus is terminal state, not a queued command. Record the whole received batch before
213
- // awaiting any key: a slow refresh must see a subsequent focus-out immediately, and an
214
- // older queued focus-in must never restore focus after it.
215
- for (const key of received) {
216
- if (key === KEY.focusOut)
217
- focused = false;
218
- else if (key === KEY.focusIn)
219
- focused = true;
220
- }
221
- pending = pending.then(async () => {
222
- try {
223
- for (const key of received) {
224
- if (await handleKey(key)) {
225
- finish();
226
- return;
227
- }
228
- }
229
- }
230
- catch (error) {
231
- notice = error instanceof Error ? error.message : String(error);
232
- draw();
233
- }
234
- });
235
- };
236
- const keys = new KeySplitter(processKeys);
237
- stdin.on("data", (chunk) => processKeys(keys.push(chunk)));
238
- });
239
- /** Returns true when the app should exit. */
240
- async function handleKey(key) {
241
- if (key === KEY.ctrlC)
242
- return true;
243
- if (key === KEY.focusOut)
244
- return false;
245
- if (key === KEY.focusIn) {
246
- // Pull the shared boundary immediately. The stream may already have rendered output while the
247
- // terminal was unfocused, and waiting for the next interval would leave it falsely unread.
248
- await refreshSessions();
249
- draw();
250
- void acknowledgeVisible().catch(() => { });
251
- return false;
252
- }
253
- if (overlay.kind !== "none") {
254
- await handleOverlayKey(key);
255
- draw();
256
- // Escape has just made the transcript visible. Any other overlay action leaves this guarded
257
- // by overlay.kind, so it cannot acknowledge through an obscuring picker.
258
- void acknowledgeVisible().catch(() => { });
259
- return false;
260
- }
261
- /*
262
- * An open Enquiry takes the prompt line, and takes it *after* the overlay branch: an overlay
263
- * opened before the question arrived must still be closable. Nothing below this runs while one
264
- * is open, which is the lockout — no message is sent, and `^K` is refused rather than silently
265
- * doing nothing.
266
- */
267
- if (view.asking) {
268
- await handleEnquiryKey(key);
269
- draw();
270
- return false;
271
- }
272
- /*
273
- * A Permission Prompt takes the prompt line on the same terms and in the same place — after the
274
- * overlay branch, above everything else. Nothing below runs while one is open, which is the
275
- * lockout: the turn is blocked on a callback, so there is nothing a message could reach.
276
- */
277
- if (view.authorising) {
278
- await handlePermissionKey(key);
279
- draw();
280
- return false;
281
- }
282
- if (key === KEY.ctrlS) {
283
- await refreshSessions();
284
- const index = sessions.findIndex((session) => session.id === selected);
285
- overlay = { kind: "sessions", index: Math.max(0, index) };
286
- }
287
- else if (key === KEY.ctrlP) {
288
- overlay = { kind: "models", index: 0 };
289
- }
290
- else if (key === KEY.ctrlE) {
291
- overlay = { kind: "effort", index: Math.max(0, effortChoices(view).indexOf(view.effort ?? "off")) };
292
- }
293
- else if (key === KEY.ctrlG) {
294
- await openBranches("switch", scopeOf(selected));
295
- }
296
- else if (key === KEY.ctrlK) {
297
- await compact();
298
- }
299
- else if (key === KEY.escape) {
300
- if (selected)
301
- await options.connection.command({ type: "abort", sessionId: selected });
302
- }
303
- else if (key === KEY.enter || key === KEY.newline) {
304
- await submit();
305
- }
306
- else if (key === KEY.backspace || key === KEY.backspaceAlt) {
307
- input = input.slice(0, -1);
308
- }
309
- else if (isPrintable(key)) {
310
- input += key;
311
- }
312
- draw();
313
- return false;
314
- }
315
- /**
316
- * Drive the Enquiry picker.
317
- *
318
- * The order of these branches is the whole rule, and it is the terminal's statement of the one the
319
- * web client's key module states for the editor: **the moment the box has a character in it, the
320
- * picker borrows only the keys a prompt line never needed.** The digits and Space are ordinary
321
- * characters as far as anyone typing is concerned, so they are claimed only while `input` is
322
- * empty — and both branches sit above the `isPrintable` one that would otherwise swallow them.
323
- *
324
- * Escape still aborts, as the status line has always said. The web client gives Escape to "go back
325
- * a Question" because it has an Abort button to spare; here there is no button, so abort keeps the
326
- * key and there is no going back. That asymmetry is deliberate and is named in both files.
327
- */
328
- async function handleEnquiryKey(key) {
329
- const asking = view.asking;
330
- if (!asking)
331
- return;
332
- // Restarted whenever the Enquiry changes, so a second question cannot inherit the first's cursor.
333
- if (!answering || answeringFor !== asking.askId) {
334
- answering = startAnswering(asking.questions);
335
- answeringFor = asking.askId;
336
- }
337
- const state = answering;
338
- const question = asking.questions[state.index];
339
- if (!question)
340
- return;
341
- const rows = rowsFor(question, enquiryInput);
342
- const chosen = state.chosen[state.index] ?? [];
343
- if (key === KEY.escape) {
344
- if (selected)
345
- await options.connection.command({ type: "abort", sessionId: selected });
346
- return;
347
- }
348
- if (key === KEY.up || key === KEY.down) {
349
- // Clamped, not wrapped: every list in this TUI clamps, and the web client's every list wraps.
350
- // Each front-end keeps its own idiom rather than the two of them growing a third.
351
- state.cursor = cursorClamped(state.cursor, key === KEY.up ? -1 : 1, rows.length);
352
- return;
353
- }
354
- if (enquiryInput === "" && /^[1-9]$/.test(key)) {
355
- const row = rows[Number(key) - 1];
356
- if (!row)
357
- return;
358
- state.cursor = Number(key) - 1;
359
- if (question.multiSelect)
360
- state.chosen[state.index] = toggled(chosen, row.label);
361
- else
362
- await commitAnswer(asking.questions, state, [row.label]);
363
- return;
364
- }
365
- if (enquiryInput === "" && key === " " && question.multiSelect) {
366
- const row = rows[state.cursor];
367
- if (row)
368
- state.chosen[state.index] = toggled(chosen, row.label);
369
- return;
370
- }
371
- if (key === KEY.enter || key === KEY.newline) {
372
- const row = rows[state.cursor];
373
- const answer = question.multiSelect ? chosen : row ? [row.label] : [];
374
- if (!canCommit(question, answer)) {
375
- notice = "choose at least one, or type your own answer";
376
- return;
377
- }
378
- await commitAnswer(asking.questions, state, answer);
379
- return;
380
- }
381
- const had = enquiryInput.trim() !== "";
382
- if (key === KEY.backspace || key === KEY.backspaceAlt)
383
- enquiryInput = enquiryInput.slice(0, -1);
384
- else if (isPrintable(key))
385
- enquiryInput += key;
386
- else
387
- return;
388
- state.cursor = cursorAfterTyping(state.cursor, had, enquiryInput.trim() !== "", rowsFor(question, enquiryInput).length);
389
- }
390
- /**
391
- * Record one Question's Answer and move on — sending the whole Enquiry once the last one is in.
392
- *
393
- * One command at the end rather than one per Question, because the backend holds a single promise
394
- * for the whole tool call. The pacing is this front-end's; the wire sees one answer.
395
- */
396
- async function commitAnswer(questions, state, answer) {
397
- state.chosen[state.index] = answer;
398
- state.index += 1;
399
- state.cursor = 0;
400
- enquiryInput = "";
401
- if (!isFinished(state, questions))
402
- return;
403
- const askId = answeringFor;
404
- answering = undefined;
405
- answeringFor = undefined;
406
- if (!selected || !askId)
407
- return;
408
- try {
409
- await options.connection.command({
410
- type: "answer_enquiry",
411
- sessionId: selected,
412
- askId,
413
- answers: answersOf(state, questions),
414
- });
415
- }
416
- catch (error) {
417
- notice = error instanceof Error ? error.message : String(error);
418
- }
419
- }
420
- /**
421
- * Drive the Permission Prompt picker.
422
- *
423
- * Simpler than its Enquiry counterpart by the whole of what made that one hard: nothing is typed
424
- * here, so there is no box to hold characters and no rule about which keys the picker may borrow
425
- * once it does. Digits and Enter are unconditionally the picker's.
426
- *
427
- * **Escape denies rather than aborting**, which is where this parts company with the Enquiry
428
- * branch above. Aborting a turn to refuse one tool call is a sledgehammer — a denial is the answer
429
- * the model can carry on from, and it is the whole reason a Deny is not an Abort. Someone wanting
430
- * to stop the turn can press it again once the prompt is gone.
431
- */
432
- async function handlePermissionKey(key) {
433
- const authorising = view.authorising;
434
- if (!authorising)
435
- return;
436
- // Restarted whenever the prompt changes, so a second call cannot inherit the first's cursor —
437
- // which matters more here than for an Enquiry, since a cursor left on Always would put the
438
- // widest decision under an unsuspecting Enter.
439
- if (deciding === undefined || decidingFor !== authorising.callId) {
440
- deciding = 0;
441
- decidingFor = authorising.callId;
442
- }
443
- const choices = permissionChoices(authorising.allowAlways);
444
- if (key === KEY.escape) {
445
- await commitDecision(authorising.callId, "deny");
446
- return;
447
- }
448
- if (key === KEY.up || key === KEY.down) {
449
- // Clamped, not wrapped: every list in this TUI clamps. See `handleEnquiryKey`.
450
- deciding = cursorClamped(deciding, key === KEY.up ? -1 : 1, choices.length);
451
- return;
452
- }
453
- if (/^[1-9]$/.test(key)) {
454
- const choice = choices[Number(key) - 1];
455
- if (!choice)
456
- return;
457
- deciding = Number(key) - 1;
458
- await commitDecision(authorising.callId, choice.decision);
459
- return;
460
- }
461
- if (key === KEY.enter || key === KEY.newline) {
462
- const choice = choices[deciding];
463
- if (choice)
464
- await commitDecision(authorising.callId, choice.decision);
465
- }
466
- }
467
- async function commitDecision(callId, decision) {
468
- deciding = undefined;
469
- decidingFor = undefined;
470
- if (!selected)
471
- return;
472
- try {
473
- await options.connection.command({ type: "answer_permission", sessionId: selected, callId, decision });
474
- }
475
- catch (error) {
476
- notice = error instanceof Error ? error.message : String(error);
477
- }
478
- }
479
- async function handleOverlayKey(key) {
480
- // Snapshot the overlay: TypeScript cannot narrow a mutable closure variable across a guard.
481
- const current = overlay;
482
- if (current.kind === "none")
483
- return;
484
- if (key === KEY.escape) {
485
- overlay = { kind: "none" };
486
- return;
487
- }
488
- const length = current.kind === "sessions"
489
- ? sessions.length
490
- : current.kind === "effort"
491
- ? effortChoices(view).length
492
- : current.kind === "branches"
493
- ? current.branches.length
494
- : modelChoices(view.capabilities).length;
495
- if (key === KEY.up) {
496
- overlay = { ...current, index: Math.max(0, current.index - 1) };
497
- return;
498
- }
499
- if (key === KEY.down) {
500
- overlay = { ...current, index: Math.min(length - 1, current.index + 1) };
501
- return;
502
- }
503
- if (key === "n" && current.kind === "sessions") {
504
- overlay = { kind: "none" };
505
- await newSession();
506
- return;
507
- }
508
- if (key === "w" && current.kind === "sessions") {
509
- // A worktree needs a branch to be cut from, and the TUI has no text entry outside the prompt
510
- // line — so the base is picked from a list, and the new branch's name is derived by the host.
511
- await openBranches("cut", options.scope);
512
- return;
513
- }
514
- if (key === "s" && current.kind === "sessions") {
515
- const chosen = sessions[current.index];
516
- // A Settled Agent Session has nothing to Settle and an Ended one refuses, so offer neither.
517
- if (!chosen || !canSettle(chosen.status))
518
- return;
519
- await options.connection.command({ type: "settle", sessionId: chosen.id });
520
- await refreshSessions();
521
- // Stay on the same identity even though settling moved it into Filed away.
522
- const moved = sessions.findIndex((session) => session.id === chosen.id);
523
- overlay = { kind: "sessions", index: Math.max(0, moved) };
524
- notice = `settled ${sessionLabel(chosen)}`;
525
- return;
526
- }
527
- if (key !== KEY.enter && key !== KEY.newline)
528
- return;
529
- if (current.kind === "sessions") {
530
- const chosen = sessions[current.index];
531
- overlay = { kind: "none" };
532
- if (chosen)
533
- attach(chosen.id);
534
- return;
535
- }
536
- if (current.kind === "branches") {
537
- const branch = current.branches[current.index];
538
- const { purpose } = current;
539
- overlay = { kind: "none" };
540
- if (!branch)
541
- return;
542
- if (purpose === "cut") {
543
- await newSession({ from: branch });
544
- return;
545
- }
546
- if (!selected)
547
- return;
548
- try {
549
- await options.connection.command({ type: "switch_branch", sessionId: selected, branch });
550
- notice = `branch → ${branch}`;
551
- }
552
- catch (error) {
553
- // A refusal carries the reason — a turn in flight, or git's own words about a checkout it
554
- // would not make — and it is the whole of what is worth showing.
555
- notice = error instanceof Error ? error.message : `could not switch to ${branch}`;
556
- }
557
- return;
558
- }
559
- if (current.kind === "effort") {
560
- const effort = effortChoices(view)[current.index];
561
- overlay = { kind: "none" };
562
- if (effort && selected) {
563
- await options.connection.command({ type: "set_effort", sessionId: selected, effort });
564
- notice = `effort → ${effort}`;
565
- }
566
- return;
567
- }
568
- const choice = modelChoices(view.capabilities)[current.index];
569
- overlay = { kind: "none" };
570
- if (choice && selected) {
571
- await options.connection.command({ type: "set_model", sessionId: selected, modelId: choice.model.id });
572
- notice = `model → ${choice.model.label ?? choice.model.id}`;
573
- }
574
- }
575
- /**
576
- * Ask the backend to compact the Conversation Context.
577
- *
578
- * The refusals live in the Session Host, not here — Dormant, Settled and mid-turn are all 409s
579
- * with a sentence saying which — so this sends and reports whatever comes back rather than
580
- * reimplementing that judgement against a `view` that can be a frame behind. The one thing it does
581
- * check locally is the capability, because a backend that cannot compact at all should say so
582
- * without a round trip.
583
- */
584
- async function compact() {
585
- if (!selected)
586
- return;
587
- if (!view.capabilities?.compaction) {
588
- notice = "this backend cannot compact";
589
- return;
590
- }
591
- try {
592
- await options.connection.command({ type: "compact", sessionId: selected });
593
- notice = "compacting…";
594
- }
595
- catch (error) {
596
- notice = error instanceof Error ? error.message : String(error);
597
- }
598
- }
599
- async function submit() {
600
- const text = input.trim();
601
- if (!text || !selected)
602
- return;
603
- input = "";
604
- // Always after_turn, never derived from our own status. The Session Host marks a turn in flight
605
- // when it dispatches rather than when the backend reports turn_started, and only after_turn is
606
- // guarded by that flag — so a client that believed itself idle on the strength of turn_started
607
- // would prompt a busy backend and bypass the Steering Queue ADR 0002 exists to own. after_turn
608
- // already means "queue if busy, else dispatch now", so it is identical in every other case.
609
- // "now" stays in the protocol for a deliberate interrupt-and-steer, which is not this.
610
- await options.connection.command({ type: "send", sessionId: selected, text, when: "after_turn" });
611
- }
612
- }