@nathanstephenson/flow 0.1.0 → 0.1.1

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 (51) hide show
  1. package/README.md +6 -1
  2. package/dist/backend/fake/index.js +3 -1
  3. package/dist/backend/pi/effort-capabilities.js +12 -0
  4. package/dist/backend/pi/index.js +25 -36
  5. package/dist/backend/pi/workflow-subagent.js +8 -3
  6. package/dist/build-id +1 -1
  7. package/dist/cli/application.js +9 -1
  8. package/dist/cli/bootstrap.js +258 -22
  9. package/dist/cli/install-guard.js +52 -9
  10. package/dist/cli/update.js +30 -13
  11. package/dist/cli/web-update.js +357 -0
  12. package/dist/client/model-choices.js +22 -4
  13. package/dist/client/reduce.js +18 -6
  14. package/dist/client/status.js +34 -20
  15. package/dist/client/workflow-effort.js +30 -0
  16. package/dist/daemon/credential-redaction.js +97 -4
  17. package/dist/daemon/host.js +341 -74
  18. package/dist/daemon/release-checker.js +104 -0
  19. package/dist/daemon/runtime.js +12 -4
  20. package/dist/daemon/server.js +81 -14
  21. package/dist/daemon/summariser.js +81 -15
  22. package/dist/daemon/update-api.js +3 -0
  23. package/dist/daemon/workflow-executions.js +146 -15
  24. package/dist/protocol/update.js +1 -0
  25. package/dist/tui/app.js +104 -10
  26. package/dist/tui/keys.js +46 -10
  27. package/dist/tui/render.js +58 -13
  28. package/dist/workflows/records.js +3 -1
  29. package/dist/workflows/scheduler.js +15 -1
  30. package/package.json +1 -1
  31. package/web/dist/apple-touch-icon.png +0 -0
  32. package/web/dist/assets/index-CaJfF2tQ.js +170 -0
  33. package/web/dist/assets/index-DWF4-3Fh.css +2 -0
  34. package/web/dist/assets/{settings-mcp-CcT0ADJR.js → settings-mcp-COi1p_1o.js} +1 -1
  35. package/web/dist/assets/{settings-secrets-CK4uF7fd.js → settings-secrets-C599riFl.js} +1 -1
  36. package/web/dist/assets/settings-workflows-BPjeFoaT.js +23 -0
  37. package/web/dist/assets/{workflows-D4T4Gy_7.css → workflows-9aO6cptD.css} +1 -1
  38. package/web/dist/assets/workflows-Bmsrl5kE.js +7 -0
  39. package/web/dist/assets/workflows-pane-DJ3UwHjd.js +1 -0
  40. package/web/dist/favicon-16x16.png +0 -0
  41. package/web/dist/favicon-32x32.png +0 -0
  42. package/web/dist/favicon.ico +0 -0
  43. package/web/dist/favicon.svg +8 -0
  44. package/web/dist/index.html +8 -3
  45. package/web/dist/safari-pinned-tab.svg +4 -0
  46. package/web/dist/assets/index-BC0gLS53.js +0 -106
  47. package/web/dist/assets/index-CCeZYKES.css +0 -2
  48. package/web/dist/assets/settings-workflows-CrbZF-nM.js +0 -23
  49. package/web/dist/assets/workflow-editors-naPqAmYO.js +0 -65
  50. package/web/dist/assets/workflows-hh6ioeEA.js +0 -7
  51. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +0 -1
@@ -1,6 +1,7 @@
1
1
  import { recoveryRevision, safeAutomaticRecovery, successfulProgress } from "../workflows/recovery.js";
2
2
  import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../backend/workflow-tools.js";
3
3
  import { redactCredentials } from "./credential-redaction.js";
4
+ import { workflowAgentNameInput, workflowOutcomeNameInput } from "./summariser.js";
4
5
  import { connectionIdentity, snapshotTool, sameSchema } from "./workflow-mcp.js";
5
6
  import { compileJsonSchema, validateJsonSchema } from "../workflows/json-schema.js";
6
7
  import { boundedMcpValue } from "../workflows/mcp.js";
@@ -32,6 +33,7 @@ export class WorkflowExecutionService {
32
33
  launches = new Map();
33
34
  /** Pending Workflow input, ordered independently of polling clients and addressed by opaque IDs. */
34
35
  relayRequests = new Map();
36
+ newestRelayBySession = new Map();
35
37
  relayOrder = 0;
36
38
  secretValues = new Map();
37
39
  runtimeSnapshots = new Map();
@@ -78,11 +80,18 @@ export class WorkflowExecutionService {
78
80
  if (step.kind !== 'agent')
79
81
  throw new Error('Invalid Agent step');
80
82
  const backend = host.workflowSession(session.sessionId).session;
81
- const model = backend?.capabilities.models.find(model => model.id === step.model);
82
- if (!backend?.startWorkflowSubagent || !model)
83
- throw new Error('Agent model is unavailable');
84
- if (model.effortLevels?.length ? !model.effortLevels.includes(step.effort) : step.effort !== 'off')
85
- throw new Error('Unsupported Effort');
83
+ if (!backend?.startWorkflowSubagent)
84
+ throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
85
+ const model = backend.capabilities.models.find(model => model.id === step.model);
86
+ if (!model)
87
+ throw new Error(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
88
+ const levels = model.effortLevels ?? [];
89
+ if (levels.length > 0 && !levels.includes(step.effort)) {
90
+ throw new Error(`Effort “${step.effort}” is unsupported for ${model.label ?? model.id}. Choose one of ${levels.join(', ')}.`);
91
+ }
92
+ if (levels.length === 0 && step.effort !== 'off') {
93
+ throw new Error(`${model.label ?? model.id} has no Effort control. Re-select the model to use internal off.`);
94
+ }
86
95
  },
87
96
  execute: async (context) => {
88
97
  try {
@@ -137,6 +146,10 @@ export class WorkflowExecutionService {
137
146
  active(sessionId) {
138
147
  return this.scheduler.activeFull(sessionId) ? 1 : 0;
139
148
  }
149
+ pendingInput(sessionId) {
150
+ const newest = this.newestRelayBySession.get(sessionId);
151
+ return newest ? { at: newest.attentionAt, version: newest.attentionVersion } : undefined;
152
+ }
140
153
  list(sessionId) {
141
154
  this.host.logFor(sessionId);
142
155
  return { occupied: this.scheduler.occupied(sessionId), executions: this.store.listExecutions(sessionId).map(record => ({ id: record.id, workflowId: record.definition.id, name: record.definition.name, status: record.status, startedAt: record.startedAt, ...(record.finishedAt === undefined ? {} : { finishedAt: record.finishedAt }), ...(record.testStepId ? { testStepId: record.testStepId } : {}) })) };
@@ -423,6 +436,13 @@ export class WorkflowExecutionService {
423
436
  session.projectId = definition.projectId;
424
437
  }
425
438
  this.host.assertWorkflowSession(sessionId, session.session);
439
+ const workflowBackend = session.session;
440
+ if (!workflowBackend)
441
+ throw new Error('Workflow Backend Session is unavailable');
442
+ // Confirmed no-control is the sole automatic persisted-effort correction. Do it before the
443
+ // scheduler validates or records the definition, so old drafts and direct launches both run
444
+ // with the same internal sentinel the editor applies.
445
+ const preparedDefinition = withConfirmedNoControlOff(definition, workflowBackend.capabilities.models);
426
446
  const pinned = new Map();
427
447
  for (const step of definition.steps) {
428
448
  if (step.kind !== 'mcp' || (stepId && step.id !== stepId))
@@ -444,15 +464,13 @@ export class WorkflowExecutionService {
444
464
  }
445
465
  if (this.scheduler.occupied(sessionId))
446
466
  throw new WorkflowConflict();
447
- const record = this.scheduler.start(definition, session, input, stepId, launchId);
467
+ const record = this.scheduler.start(preparedDefinition, session, input, stepId, launchId, nameSession && !stepId);
448
468
  this.secretValues.set(record.id, values);
449
469
  this.runtimeSnapshots.set(record.id, workflowRuntimeOptions(this.config.view().workflowRuntime));
450
470
  this.privateView(sessionId, record.id).historyComplete = true;
451
471
  this.savePrivate(sessionId, record.id, this.privateView(sessionId, record.id));
452
472
  this.snapshots.set(record.id, this.code);
453
473
  this.watch(record);
454
- if (nameSession && !stepId)
455
- void this.host.nameWorkflow(sessionId, record.definition.name, record.input);
456
474
  return this.view(sessionId, record.id);
457
475
  }
458
476
  async recover(sessionId, executionId, action, authority) {
@@ -595,9 +613,19 @@ export class WorkflowExecutionService {
595
613
  item.kind === request.kind && (item.kind === 'enquiry' && request.kind === 'enquiry' ? item.askId === request.askId : item.kind === 'permission' && request.kind === 'permission' && item.callId === request.callId));
596
614
  if (duplicate)
597
615
  return;
598
- const item = { ...request, id: randomUUID(), order: ++this.relayOrder, announced: false, deliveryAttempts: 0, relaying: false, abort: new AbortController() };
616
+ const id = randomUUID();
617
+ // Publish the relay before waking the host. The host may drain synchronously and takeInput must
618
+ // already be able to find this request when it does.
619
+ const item = { ...request, id, order: ++this.relayOrder, attentionAt: new Date().toISOString(), attentionVersion: 0, announced: false, deliveryAttempts: 0, relaying: false, abort: new AbortController() };
599
620
  this.relayRequests.set(item.id, item);
600
- this.host.workflowInput(item.sessionId);
621
+ const attention = this.host.workflowInput(request.sessionId, id);
622
+ if (attention) {
623
+ item.attentionAt = attention.at;
624
+ item.attentionVersion = attention.version;
625
+ }
626
+ const newest = this.newestRelayBySession.get(item.sessionId);
627
+ if (!newest || item.attentionAt > newest.attentionAt)
628
+ this.newestRelayBySession.set(item.sessionId, item);
601
629
  }
602
630
  dropRelays(match, abort = true) {
603
631
  const sessions = new Set();
@@ -609,8 +637,18 @@ export class WorkflowExecutionService {
609
637
  request.abort.abort();
610
638
  sessions.add(request.sessionId);
611
639
  }
612
- for (const sessionId of sessions)
640
+ for (const sessionId of sessions) {
641
+ let newest;
642
+ for (const request of this.relayRequests.values()) {
643
+ if (request.sessionId === sessionId && (!newest || request.attentionAt > newest.attentionAt))
644
+ newest = request;
645
+ }
646
+ if (newest)
647
+ this.newestRelayBySession.set(sessionId, newest);
648
+ else
649
+ this.newestRelayBySession.delete(sessionId);
613
650
  this.wakeNextRelay(sessionId);
651
+ }
614
652
  }
615
653
  oldestRelay(sessionId) {
616
654
  let oldest;
@@ -749,6 +787,7 @@ export class WorkflowExecutionService {
749
787
  async agent(context) {
750
788
  if (context.step.kind !== 'agent')
751
789
  throw new Error('Invalid Agent step');
790
+ const resolvedInstructions = context.step.instructions;
752
791
  const backend = this.host.workflowSession(context.sessionId).session;
753
792
  if (!backend?.startWorkflowSubagent)
754
793
  throw new Error('Workflow Backend Session is unavailable');
@@ -774,7 +813,7 @@ export class WorkflowExecutionService {
774
813
  const aliases = Object.create(null);
775
814
  for (const [alias, reference] of Object.entries(context.step.secrets ?? {}))
776
815
  aliases[alias] = this.secrets.resolve(reference, context.signal);
777
- const values = [...(this.secretValues.get(context.executionId) ?? []), ...Object.values(aliases)];
816
+ const values = uniqueCredentials([...(this.secretValues.get(context.executionId) ?? []), ...Object.values(aliases)]);
778
817
  const id = randomUUID();
779
818
  const view = this.privateView(context.sessionId, context.executionId);
780
819
  const priorSpend = view.stepSpend[context.step.id];
@@ -836,6 +875,14 @@ export class WorkflowExecutionService {
836
875
  this.host.workflowSpend(context.sessionId, context.executionId, view.spend);
837
876
  },
838
877
  });
878
+ const execution = this.scheduler.get(context.sessionId, context.executionId);
879
+ this.requestNaming(context.sessionId, context.executionId, () => workflowAgentNameInput({
880
+ workflowName: execution.definition.name,
881
+ workflowInput: execution.input,
882
+ stepName: context.step.name,
883
+ instructions: resolvedInstructions,
884
+ input: context.input,
885
+ }, values));
839
886
  if (context.permission === 'ask' && typeof handle.answerPermission !== 'function') {
840
887
  await handle.cancel();
841
888
  throw new Error('Workflow Agent permissions are unavailable');
@@ -869,18 +916,62 @@ export class WorkflowExecutionService {
869
916
  }
870
917
  watch(record) {
871
918
  void this.scheduler.wait(record.sessionId, record.id).then(result => {
919
+ const credentials = this.secretValues.get(record.id) ?? [];
920
+ this.publishResult(result, credentials);
921
+ }).catch(() => { }).finally(() => {
872
922
  this.snapshots.delete(record.id);
873
923
  this.secretValues.delete(record.id);
874
- this.publishResult(result);
875
- }).catch(() => { });
924
+ });
876
925
  }
877
- publishResult(result) {
926
+ publishResult(result, knownCredentials = []) {
927
+ if (!result.testStepId && ['recovery-required', 'completed', 'completed-with-recovery', 'cancelled'].includes(result.status)) {
928
+ this.requestNaming(result.sessionId, result.id, () => {
929
+ const { results, errors } = outcomeNamingData(result);
930
+ return workflowOutcomeNameInput({
931
+ workflowName: result.definition.name,
932
+ workflowInput: result.input,
933
+ outcome: result.status,
934
+ results,
935
+ errors,
936
+ }, uniqueCredentials([...knownCredentials, ...this.namingCredentials(result)]));
937
+ });
938
+ }
878
939
  if (!result.testStepId && result.status === 'recovery-required')
879
940
  this.host.workflowWake(result.sessionId, result.id, recoveryRevision(result));
880
941
  if (!result.testStepId && (result.status === 'completed' || result.status === 'completed-with-recovery')) {
881
942
  this.host.workflowComplete(result.sessionId, result.id);
882
943
  }
883
944
  }
945
+ /** A shutdown leaves the durable request pending so restart reconciliation can name it. */
946
+ requestNaming(sessionId, executionId, context) {
947
+ if (!this.host.workflowNamingAllowed(sessionId) || !context)
948
+ return;
949
+ try {
950
+ if (!this.scheduler.claimNaming(sessionId, executionId))
951
+ return;
952
+ }
953
+ catch {
954
+ return;
955
+ }
956
+ let input;
957
+ try {
958
+ input = context();
959
+ }
960
+ catch {
961
+ return;
962
+ }
963
+ void this.host.nameWorkflow(sessionId, input).catch(() => { });
964
+ }
965
+ namingCredentials(record) {
966
+ const values = [...this.host.workflowMcpCredentials()];
967
+ for (const reference of new Set(record.definition.steps.flatMap(step => Object.values(step.secrets ?? {})))) {
968
+ try {
969
+ values.push(this.secrets.resolve(reference));
970
+ }
971
+ catch { /* Missing secrets cannot make naming affect execution. */ }
972
+ }
973
+ return uniqueCredentials(values);
974
+ }
884
975
  privateView(sessionId, executionId) {
885
976
  let view = this.views.get(executionId);
886
977
  if (!view) {
@@ -972,6 +1063,19 @@ function redactEvent(event, secrets, publicId) {
972
1063
  };
973
1064
  return visit(event);
974
1065
  }
1066
+ function withConfirmedNoControlOff(definition, models) {
1067
+ let changed = false;
1068
+ const steps = definition.steps.map(step => {
1069
+ if (step.kind !== 'agent')
1070
+ return step;
1071
+ const model = models.find(candidate => candidate.id === step.model);
1072
+ if (!model || (model.effortLevels?.length ?? 0) > 0 || step.effort === 'off')
1073
+ return step;
1074
+ changed = true;
1075
+ return { ...step, effort: 'off' };
1076
+ });
1077
+ return changed ? { ...definition, steps } : definition;
1078
+ }
975
1079
  function publicDefinition(definition) {
976
1080
  return { ...definition, steps: definition.steps.map(({ secrets, ...step }) => step) };
977
1081
  }
@@ -990,6 +1094,33 @@ function safeError(error, values) {
990
1094
  const message = redact(error instanceof Error ? error.message : String(error), values);
991
1095
  return error instanceof WorkflowStepError ? new WorkflowStepError(message, error.partialOutput === undefined ? undefined : redact(error.partialOutput, values)) : new Error(message);
992
1096
  }
1097
+ function outcomeNamingData(record) {
1098
+ const stepNames = new Map(record.definition.steps.map(step => [step.id, step.name]));
1099
+ function* results() {
1100
+ for (const id in record.steps) {
1101
+ const output = record.steps[id].output;
1102
+ if (output !== undefined)
1103
+ yield { step: stepNames.get(id) ?? id, output };
1104
+ }
1105
+ }
1106
+ function* errors() {
1107
+ for (const id in record.steps)
1108
+ for (const attempt of record.steps[id].attempts) {
1109
+ if (attempt.error !== undefined)
1110
+ yield {
1111
+ step: stepNames.get(id) ?? id, attempt: attempt.number, error: attempt.error,
1112
+ ...(attempt.partialOutput === undefined ? {} : { partialOutput: attempt.partialOutput }),
1113
+ };
1114
+ }
1115
+ }
1116
+ return {
1117
+ results: record.result === undefined ? results() : record.result,
1118
+ errors: errors(),
1119
+ };
1120
+ }
1121
+ function uniqueCredentials(values) {
1122
+ return [...new Set(values.filter(Boolean))];
1123
+ }
993
1124
  function relayContext(record, stepId, attempt) {
994
1125
  const step = record.definition.steps.find(item => item.id === stepId);
995
1126
  return `Workflow “${record.definition.name}” · Step “${step?.name ?? stepId}” · Attempt ${attempt}${record.testStepId ? ' · Step test' : ''}`;
@@ -0,0 +1 @@
1
+ export {};
package/dist/tui/app.js CHANGED
@@ -4,7 +4,7 @@ import { sessionLabel } from "../client/session-label.js";
4
4
  import { canSettle } from "../client/status.js";
5
5
  import { answersOf, canCommit, cursorAfterTyping, cursorClamped, isFinished, rowsFor, startAnswering, toggled, } from "../client/enquiry.js";
6
6
  import { permissionChoices } from "../client/permission.js";
7
- import { isPrintable, KEY, splitKeys } from "./keys.js";
7
+ import { isPrintable, KeySplitter, KEY } from "./keys.js";
8
8
  import { renderFrame } from "./render.js";
9
9
  export async function runTui(options) {
10
10
  const stdin = options.stdin ?? process.stdin;
@@ -30,6 +30,13 @@ export async function runTui(options) {
30
30
  let decidingFor;
31
31
  let notice;
32
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();
33
40
  const draw = () => {
34
41
  const ui = {
35
42
  sessions,
@@ -45,6 +52,39 @@ export async function runTui(options) {
45
52
  const frame = renderFrame(ui, { columns: stdout.columns ?? 80, rows: stdout.rows ?? 24 });
46
53
  stdout.write(`${frame.join("\r\n")}`);
47
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
+ };
48
88
  const attach = (sessionId) => {
49
89
  unsubscribe?.();
50
90
  selected = sessionId;
@@ -58,6 +98,9 @@ export async function runTui(options) {
58
98
  if (view.asking?.askId !== previousAsk)
59
99
  enquiryInput = "";
60
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(() => { });
61
104
  },
62
105
  onError: (error) => {
63
106
  notice = error.message;
@@ -65,9 +108,7 @@ export async function runTui(options) {
65
108
  },
66
109
  });
67
110
  draw();
68
- };
69
- const refreshSessions = async () => {
70
- sessions = await options.connection.listSessions();
111
+ void acknowledgeVisible().catch(() => { });
71
112
  };
72
113
  const newSession = async (worktree) => {
73
114
  try {
@@ -126,10 +167,39 @@ export async function runTui(options) {
126
167
  stdin.setRawMode?.(true);
127
168
  stdin.resume();
128
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");
129
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();
130
192
  await new Promise((resolve) => {
131
193
  const finish = () => {
194
+ if (stopped)
195
+ return;
196
+ stopped = true;
197
+ refreshGeneration++;
198
+ if (refreshTimer)
199
+ clearTimeout(refreshTimer);
132
200
  unsubscribe?.();
201
+ if (stdin.isTTY)
202
+ stdout.write("\u001b[?1004l");
133
203
  stdin.setRawMode?.(false);
134
204
  stdin.pause();
135
205
  stdout.write("");
@@ -138,10 +208,19 @@ export async function runTui(options) {
138
208
  // Chunks are processed one at a time. handleKey is async, so without this a chunk arriving
139
209
  // mid-walk would interleave with the previous one and keys would be applied out of order.
140
210
  let pending = Promise.resolve();
141
- stdin.on("data", (chunk) => {
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
+ }
142
221
  pending = pending.then(async () => {
143
222
  try {
144
- for (const key of splitKeys(chunk)) {
223
+ for (const key of received) {
145
224
  if (await handleKey(key)) {
146
225
  finish();
147
226
  return;
@@ -153,15 +232,30 @@ export async function runTui(options) {
153
232
  draw();
154
233
  }
155
234
  });
156
- });
235
+ };
236
+ const keys = new KeySplitter(processKeys);
237
+ stdin.on("data", (chunk) => processKeys(keys.push(chunk)));
157
238
  });
158
239
  /** Returns true when the app should exit. */
159
240
  async function handleKey(key) {
160
241
  if (key === KEY.ctrlC)
161
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
+ }
162
253
  if (overlay.kind !== "none") {
163
254
  await handleOverlayKey(key);
164
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(() => { });
165
259
  return false;
166
260
  }
167
261
  /*
@@ -424,9 +518,9 @@ export async function runTui(options) {
424
518
  return;
425
519
  await options.connection.command({ type: "settle", sessionId: chosen.id });
426
520
  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)) };
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) };
430
524
  notice = `settled ${sessionLabel(chosen)}`;
431
525
  return;
432
526
  }
package/dist/tui/keys.js CHANGED
@@ -23,6 +23,9 @@ export const KEY = {
23
23
  backspaceAlt: "\b",
24
24
  up: "\u001b[A",
25
25
  down: "\u001b[B",
26
+ /** Focus events emitted after the client enables DECSET 1004. Unsupported terminals ignore it. */
27
+ focusIn: "\u001b[I",
28
+ focusOut: "\u001b[O",
26
29
  };
27
30
  export function isPrintable(key) {
28
31
  return key.length === 1 && key >= " " && key !== KEY.backspace;
@@ -33,22 +36,55 @@ export function isPrintable(key) {
33
36
  * A chunk is not a keystroke: a paste arrives as one chunk of many characters, and an arrow key
34
37
  * arrives as a three-byte escape sequence. Treating a chunk as one key silently drops both.
35
38
  */
36
- export function splitKeys(chunk) {
39
+ function parseKeys(chunk) {
37
40
  const keys = [];
38
41
  let index = 0;
39
42
  while (index < chunk.length) {
40
43
  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;
44
+ if (char === "\u001b") {
45
+ if (index + 1 === chunk.length)
46
+ return { keys, remainder: chunk.slice(index) };
47
+ if (chunk[index + 1] === "[") {
48
+ let end = index + 2;
49
+ while (end < chunk.length && !/[@-~]/.test(chunk[end] ?? ""))
50
+ end += 1;
51
+ if (end === chunk.length)
52
+ return { keys, remainder: chunk.slice(index) };
53
+ keys.push(chunk.slice(index, end + 1));
54
+ index = end + 1;
55
+ continue;
56
+ }
49
57
  }
50
58
  keys.push(char);
51
59
  index += 1;
52
60
  }
53
- return keys;
61
+ return { keys, remainder: "" };
62
+ }
63
+ export function splitKeys(chunk) {
64
+ return parseKeys(chunk).keys;
65
+ }
66
+ export class KeySplitter {
67
+ buffered = "";
68
+ timer;
69
+ onFlush;
70
+ flushAfterMs;
71
+ constructor(onFlush, flushAfterMs = 25) {
72
+ this.onFlush = onFlush;
73
+ this.flushAfterMs = flushAfterMs;
74
+ }
75
+ push(chunk) {
76
+ if (this.timer)
77
+ clearTimeout(this.timer);
78
+ const parsed = parseKeys(this.buffered + chunk);
79
+ this.buffered = parsed.remainder;
80
+ if (this.buffered) {
81
+ this.timer = setTimeout(() => {
82
+ this.timer = undefined;
83
+ const buffered = this.buffered;
84
+ this.buffered = "";
85
+ this.onFlush?.([...buffered]);
86
+ }, this.flushAfterMs);
87
+ }
88
+ return parsed.keys;
89
+ }
54
90
  }
@@ -1,11 +1,12 @@
1
1
  import { contextUsageLabel } from "../client/context-usage.js";
2
- import { effortChoices, modelChoices } from "../client/model-choices.js";
2
+ import { effortCapability, effortChoices, modelChoices } from "../client/model-choices.js";
3
3
  import { answerLines, progressLabel, rowsFor, } from "../client/enquiry.js";
4
4
  import { authorisationLabel, permissionChoices } from "../client/permission.js";
5
5
  import { toolSummary } from "../client/tool-summary.js";
6
6
  import { relativeTime } from "../client/relative-time.js";
7
7
  import { scopeKindLabel } from "../client/scope-kind.js";
8
8
  import { sessionLabel } from "../client/session-label.js";
9
+ import { railGroup, railGroupLabel, RAIL_GROUPS } from "../client/status.js";
9
10
  export function renderFrame(ui, size) {
10
11
  const width = Math.max(20, size.columns);
11
12
  const height = Math.max(6, size.rows);
@@ -255,20 +256,59 @@ function overlay(ui, width, height) {
255
256
  const cursor = ui.overlay.index;
256
257
  const now = ui.now ?? Date.now();
257
258
  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.
259
+ const counts = new Map(RAIL_GROUPS.map((group) => [group, 0]));
260
+ for (const session of ui.sessions) {
261
+ const group = railGroup(session);
262
+ counts.set(group, (counts.get(group) ?? 0) + 1);
263
+ }
264
+ let opened;
265
+ // Headings are inserted into the rendered rows but never into ui.sessions, so the numeric
266
+ // cursor cannot land on one. The host already sorts by this same shared group identity.
261
267
  for (const [index, session] of ui.sessions.entries()) {
262
- if (session.status === "settled" && !openedSettled) {
263
- openedSettled = true;
264
- rows.push(clip(" ── settled ──", width));
268
+ const group = railGroup(session);
269
+ if (group !== opened) {
270
+ opened = group;
271
+ rows.push({ type: "heading", line: clip(` ── ${railGroupLabel(group)} (${counts.get(group) ?? 0}) ──`, width) });
272
+ }
273
+ const ageAt = session.attention?.at ?? session.restingAt;
274
+ const age = relativeTime(ageAt, now);
275
+ const attention = session.attention
276
+ ? `${session.attention.group === "needs-input" ? "!" : "●"} ${session.attention.reason.toLowerCase()}`
277
+ : session.status;
278
+ // Backend and fixed columns earn their width. On a narrow terminal the reason, age, and title
279
+ // are the actionable parts; dropping metadata is better than clipping the identity away.
280
+ const detail = width >= 64
281
+ ? `${attention.padEnd(16)} ${session.backend.padEnd(7)} ${age.padEnd(10)}`
282
+ : width >= 44
283
+ ? `${attention.padEnd(16)} ${age.padEnd(10)}`
284
+ : `${attention} ${age}`;
285
+ rows.push({
286
+ type: "session",
287
+ sessionIndex: index,
288
+ line: clip(`${index === cursor ? ">" : " "} ${detail} ${sessionLabel(session)}`, width),
289
+ });
290
+ if (session.outputPreview)
291
+ rows.push({ type: "preview", line: ellipsised(` ${session.outputPreview}`, width) });
292
+ }
293
+ // Group headings consume rows but not cursor positions. Window the rendered rows around the
294
+ // selected identity so adding headings never makes keyboard navigation walk off-screen.
295
+ const room = Math.max(1, height - 1);
296
+ const cursorRow = rows.findIndex((row) => row.type === "session" && row.sessionIndex === cursor);
297
+ const start = Math.max(0, Math.min(cursorRow - Math.floor(room / 2), rows.length - room));
298
+ let visibleRows = rows.slice(start, start + room);
299
+ // When the window starts halfway through a large group, keep its heading as a sticky first row.
300
+ // There is always still room for the cursor because a centered/clamped cursor is not first.
301
+ if (room > 1 && start > 0 && visibleRows[0]?.type !== "heading") {
302
+ let heading = start - 1;
303
+ while (heading > 0 && rows[heading]?.type !== "heading")
304
+ heading -= 1;
305
+ const groupHeading = rows[heading];
306
+ if (groupHeading?.type === "heading") {
307
+ visibleRows = [groupHeading, ...visibleRows.slice(1)];
265
308
  }
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
309
  }
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);
310
+ const visible = visibleRows.map((row) => row.line);
311
+ return padTo(["sessions (enter to switch, n for new, w for new in a worktree, s to settle, esc to close)", ...visible], height, width);
272
312
  }
273
313
  if (ui.overlay.kind === "branches") {
274
314
  const { index, purpose, branches, head } = ui.overlay;
@@ -298,7 +338,12 @@ function overlay(ui, width, height) {
298
338
  const inForce = level === ui.view.effort ? " (in force)" : "";
299
339
  return clip(`${index === cursor ? ">" : " "} ${level}${inForce}`, width);
300
340
  });
301
- const title = levels.length > 0 ? "effort (enter to set, esc to close)" : "this model has no effort control";
341
+ const capability = effortCapability(ui.view.capabilities, ui.view.model);
342
+ const title = levels.length > 0
343
+ ? "effort (enter to set, esc to close)"
344
+ : capability.status === "unknown"
345
+ ? capability.reason
346
+ : "this model has no effort control";
302
347
  return padTo([title, ...rows], height, width);
303
348
  }
304
349
  const choices = modelChoices(ui.view.capabilities);
@@ -16,7 +16,7 @@ const attemptValidator = z.object({
16
16
  }).strict();
17
17
  export const workflowExecutionValidator = z.object({
18
18
  version: z.literal(1), id: z.string().min(1), sessionId: z.string().min(1), scope: z.string(), definition: workflowDefinitionValidator,
19
- input: z.json(), launchId: z.string().min(1).optional(), testStepId: z.string().optional(), status: z.enum(['running', 'recovery-required', 'completed', 'completed-with-recovery', 'cancelled']),
19
+ input: z.json(), launchId: z.string().min(1).optional(), naming: z.enum(['pending', 'requested']).optional(), testStepId: z.string().optional(), status: z.enum(['running', 'recovery-required', 'completed', 'completed-with-recovery', 'cancelled']),
20
20
  startedAt: z.number().nonnegative(), finishedAt: z.number().nonnegative().optional(), result: z.json().optional(),
21
21
  loops: z.record(z.string(), loopValidator).optional(),
22
22
  steps: z.record(z.string(), z.object({
@@ -31,6 +31,8 @@ export function parseExecution(value) {
31
31
  throw new Error('Execution steps do not match the definition');
32
32
  if (record.testStepId && !Object.hasOwn(record.steps, record.testStepId))
33
33
  throw new Error('Unknown test step');
34
+ if (record.testStepId && record.naming)
35
+ throw new Error('Step tests cannot name Agent Sessions');
34
36
  const loops = record.testStepId ? [] : graph.loops;
35
37
  if (loops.length !== Object.keys(record.loops ?? {}).length || loops.some(loop => !record.loops?.[loop.headerId]))
36
38
  throw new Error('Execution loops do not match the definition');