@nathanstephenson/flow 0.1.0 → 0.1.2

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 (54) hide show
  1. package/README.md +10 -2
  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 +424 -37
  9. package/dist/cli/host-control.js +2 -2
  10. package/dist/cli/install-guard.js +57 -11
  11. package/dist/cli/systemd-update.js +129 -0
  12. package/dist/cli/update.js +64 -17
  13. package/dist/cli/web-update.js +376 -0
  14. package/dist/client/model-choices.js +22 -4
  15. package/dist/client/reduce.js +18 -6
  16. package/dist/client/status.js +34 -20
  17. package/dist/client/workflow-effort.js +30 -0
  18. package/dist/daemon/credential-redaction.js +97 -4
  19. package/dist/daemon/host-control-routes.js +18 -2
  20. package/dist/daemon/host.js +341 -74
  21. package/dist/daemon/release-checker.js +104 -0
  22. package/dist/daemon/runtime.js +12 -4
  23. package/dist/daemon/server.js +98 -15
  24. package/dist/daemon/summariser.js +81 -15
  25. package/dist/daemon/update-api.js +3 -0
  26. package/dist/daemon/workflow-executions.js +146 -15
  27. package/dist/protocol/update.js +1 -0
  28. package/dist/tui/app.js +104 -10
  29. package/dist/tui/keys.js +46 -10
  30. package/dist/tui/render.js +58 -13
  31. package/dist/workflows/records.js +3 -1
  32. package/dist/workflows/scheduler.js +15 -1
  33. package/package.json +1 -1
  34. package/web/dist/apple-touch-icon.png +0 -0
  35. package/web/dist/assets/index-BlZBshi8.js +170 -0
  36. package/web/dist/assets/index-DWF4-3Fh.css +2 -0
  37. package/web/dist/assets/{settings-mcp-CcT0ADJR.js → settings-mcp-ZMIfuuZU.js} +1 -1
  38. package/web/dist/assets/{settings-secrets-CK4uF7fd.js → settings-secrets-CgTrBpi2.js} +1 -1
  39. package/web/dist/assets/settings-workflows-1DMYfZtn.js +23 -0
  40. package/web/dist/assets/{workflows-D4T4Gy_7.css → workflows-9aO6cptD.css} +1 -1
  41. package/web/dist/assets/workflows-CBuB_bva.js +7 -0
  42. package/web/dist/assets/workflows-pane-DPXGg0na.js +1 -0
  43. package/web/dist/favicon-16x16.png +0 -0
  44. package/web/dist/favicon-32x32.png +0 -0
  45. package/web/dist/favicon.ico +0 -0
  46. package/web/dist/favicon.svg +8 -0
  47. package/web/dist/index.html +8 -3
  48. package/web/dist/safari-pinned-tab.svg +4 -0
  49. package/web/dist/assets/index-BC0gLS53.js +0 -106
  50. package/web/dist/assets/index-CCeZYKES.css +0 -2
  51. package/web/dist/assets/settings-workflows-CrbZF-nM.js +0 -23
  52. package/web/dist/assets/workflow-editors-naPqAmYO.js +0 -65
  53. package/web/dist/assets/workflows-hh6ioeEA.js +0 -7
  54. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +0 -1
@@ -0,0 +1,376 @@
1
+ import { systemdUpdate, launchSystemdUpdate, SystemdLaunchUncertain } from "./systemd-update.js";
2
+ import { randomUUID } from 'node:crypto';
3
+ import { closeSync, constants, fchmodSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync, } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { spawn } from 'node:child_process';
6
+ import { newerStableVersion, ReleaseChecker } from "../daemon/release-checker.js";
7
+ import { UpdateRefusal } from "../daemon/update-api.js";
8
+ export { UpdateRefusal } from "../daemon/update-api.js";
9
+ import { processAlive } from "./host-control.js";
10
+ import { inspectUpdateInstallation } from "./update.js";
11
+ const STATUS_FILE = 'web-update.json';
12
+ const STATUS_LOCK = 'web-update-lock';
13
+ const STATUS_LOCK_ATTEMPTS = 100;
14
+ const STATUS_LOCK_WAIT_MS = 25;
15
+ export const WEB_UPDATE_LAUNCH_WINDOW_MS = 15_000;
16
+ function statusPath(root) { return join(root, STATUS_FILE); }
17
+ function readOperation(root) {
18
+ try {
19
+ const value = JSON.parse(readFileSync(statusPath(root), 'utf8'));
20
+ if (!value || typeof value.id !== 'string' || !['updating', 'succeeded', 'failed', 'unverified'].includes(value.state))
21
+ return undefined;
22
+ return value;
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ }
28
+ function writeOperation(root, operation) {
29
+ const temporary = join(root, `${STATUS_FILE}-${process.pid}-${randomUUID()}`);
30
+ writeFileSync(temporary, JSON.stringify(operation), { mode: 0o600 });
31
+ renameSync(temporary, statusPath(root));
32
+ }
33
+ function removeLockOwner(path, filename) {
34
+ try {
35
+ unlinkSync(join(path, filename));
36
+ }
37
+ catch (error) {
38
+ if (error.code !== 'ENOENT')
39
+ throw error;
40
+ }
41
+ try {
42
+ rmdirSync(path);
43
+ }
44
+ catch (error) {
45
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
46
+ throw error;
47
+ }
48
+ }
49
+ function sleep(milliseconds) {
50
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
51
+ }
52
+ /** Serialize cross-process status transitions so reconciliation cannot replace a helper's result. */
53
+ function transitionOperation(root, transition) {
54
+ const ownerId = randomUUID();
55
+ const filename = `${ownerId}.json`;
56
+ const candidate = join(root, `${STATUS_LOCK}-${ownerId}`);
57
+ const lock = join(root, STATUS_LOCK);
58
+ mkdirSync(candidate, { mode: 0o700 });
59
+ writeFileSync(join(candidate, filename), JSON.stringify({ pid: process.pid, id: ownerId }), { mode: 0o600 });
60
+ let acquired = false;
61
+ try {
62
+ for (let attempt = 0; !acquired; attempt++) {
63
+ try {
64
+ renameSync(candidate, lock);
65
+ acquired = true;
66
+ }
67
+ catch (error) {
68
+ if (!['ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
69
+ throw error;
70
+ if (attempt >= STATUS_LOCK_ATTEMPTS)
71
+ throw new Error('Web update status is busy');
72
+ let entries;
73
+ try {
74
+ entries = readdirSync(lock);
75
+ }
76
+ catch (readError) {
77
+ if (readError.code === 'ENOENT')
78
+ continue;
79
+ throw readError;
80
+ }
81
+ if (entries.length === 0) {
82
+ sleep(STATUS_LOCK_WAIT_MS);
83
+ continue;
84
+ }
85
+ if (entries.length !== 1 || !/^[a-f0-9-]+\.json$/.test(entries[0]))
86
+ throw new Error('Invalid web update status owner');
87
+ let owner;
88
+ try {
89
+ owner = JSON.parse(readFileSync(join(lock, entries[0]), 'utf8'));
90
+ }
91
+ catch (readError) {
92
+ if (readError.code === 'ENOENT')
93
+ continue;
94
+ throw readError;
95
+ }
96
+ if (!owner || typeof owner !== 'object' || !Number.isInteger(owner.pid) || owner.pid <= 0 || owner.id !== entries[0].slice(0, -5)) {
97
+ throw new Error('Invalid web update status owner');
98
+ }
99
+ if (!processAlive(owner.pid))
100
+ removeLockOwner(lock, entries[0]);
101
+ sleep(STATUS_LOCK_WAIT_MS);
102
+ }
103
+ }
104
+ const current = readOperation(root);
105
+ const next = transition(current);
106
+ if (next !== undefined && next !== current)
107
+ writeOperation(root, next);
108
+ return next;
109
+ }
110
+ finally {
111
+ removeLockOwner(acquired ? lock : candidate, filename);
112
+ }
113
+ }
114
+ function publicError(error) {
115
+ const message = error instanceof Error ? error.message : String(error);
116
+ return message
117
+ .replace(/Bearer\s+\S+/gi, 'Bearer [redacted]')
118
+ .replace(/((?:token|secret|password)[=:]\s*)[^\s;,]+/gi, '$1[redacted]')
119
+ .slice(0, 2000);
120
+ }
121
+ export function claimWebUpdate(root, id) {
122
+ transitionOperation(root, current => current?.id === id && ['updating', 'unverified'].includes(current.state)
123
+ ? { ...current, state: 'updating', pid: process.pid } : current);
124
+ }
125
+ /** Called by the detached `flow update` helper after restoration/recovery has settled. */
126
+ export function finishWebUpdate(root, id, result, error) {
127
+ transitionOperation(root, current => {
128
+ // A replacement host may have reconciled the launch to unverified when the old host exited before
129
+ // recording the helper PID. The ID still binds this completion to the authorized detached helper,
130
+ // so its eventual verified result may safely replace that provisional recovery-needed state.
131
+ if (!current || current.id !== id || !['updating', 'unverified'].includes(current.state))
132
+ return current;
133
+ const finishedAt = new Date().toISOString();
134
+ if (error !== undefined)
135
+ return { ...current, state: 'failed', finishedAt, message: publicError(error) };
136
+ if (!result?.changed) {
137
+ return {
138
+ ...current,
139
+ state: 'failed',
140
+ installedVersion: result?.installedVersion ?? current.previousVersion,
141
+ finishedAt,
142
+ message: `npm completed, but Flow remains at ${result?.installedVersion ?? current.previousVersion}. No update was installed.`,
143
+ };
144
+ }
145
+ return {
146
+ ...current,
147
+ state: 'succeeded',
148
+ installedVersion: result.installedVersion,
149
+ finishedAt,
150
+ message: `Flow updated from ${result.previousVersion} to ${result.installedVersion}.`,
151
+ };
152
+ });
153
+ }
154
+ export class WebUpdateController {
155
+ launching = false;
156
+ options;
157
+ checker;
158
+ constructor(options) {
159
+ this.options = options;
160
+ const registryUrl = process.env.FLOW_UPDATE_REGISTRY_URL;
161
+ this.checker = options.checker ?? new ReleaseChecker(registryUrl ? { registryUrl } : {});
162
+ }
163
+ async status(refresh = false) {
164
+ const installedVersion = this.installedVersion();
165
+ const check = await this.checker.check(refresh);
166
+ const operation = this.operation(installedVersion);
167
+ return {
168
+ installedVersion,
169
+ updateAvailable: 'latestVersion' in check && newerStableVersion(installedVersion, check.latestVersion),
170
+ ...('latestVersion' in check ? { latestVersion: check.latestVersion } : { checkError: check.error }),
171
+ checkedAt: check.checkedAt,
172
+ eligibility: this.eligibility(),
173
+ ...(operation === undefined ? {} : { operation }),
174
+ };
175
+ }
176
+ async start(confirmedVersion) {
177
+ if (this.launching)
178
+ throw new UpdateRefusal('An update request is already starting.');
179
+ this.launching = true;
180
+ let launchedOperationId;
181
+ let helperStarted = false;
182
+ try {
183
+ const initiallyInstalledVersion = this.installedVersion();
184
+ this.refuseUnsettledOperation(this.operation(initiallyInstalledVersion), initiallyInstalledVersion);
185
+ const eligibility = this.eligibility();
186
+ if (eligibility.state !== 'eligible')
187
+ throw new UpdateRefusal(eligibility.reason);
188
+ const installedVersion = this.installedVersion();
189
+ // Mutation never trusts the up-to-fifteen-minute discovery cache. The confirmed version must
190
+ // still be npm's stable latest tag, and the detached helper installs that exact version.
191
+ const release = await this.checker.check(true);
192
+ if ('error' in release)
193
+ throw new UpdateRefusal(`${release.error} Check again before updating.`);
194
+ if (!newerStableVersion(installedVersion, release.latestVersion)) {
195
+ throw new UpdateRefusal(`Flow ${installedVersion} is already up to date.`);
196
+ }
197
+ if (release.latestVersion !== confirmedVersion) {
198
+ throw new UpdateRefusal(`The latest release changed from ${confirmedVersion} to ${release.latestVersion}. Check again and confirm the new version.`);
199
+ }
200
+ // Revalidate after the asynchronous release check and immediately before spawning. The helper
201
+ // repeats installation and target checks yet again before beginning its transaction.
202
+ const finalEligibility = this.eligibility();
203
+ if (finalEligibility.state !== 'eligible')
204
+ throw new UpdateRefusal(finalEligibility.reason);
205
+ const installation = this.options.installation;
206
+ const bootstrapEntry = this.options.bootstrapEntry;
207
+ if (!installation || !bootstrapEntry)
208
+ throw new UpdateRefusal('This Flow installation cannot update itself.');
209
+ const id = randomUUID();
210
+ const operation = {
211
+ id,
212
+ state: 'updating',
213
+ previousVersion: installedVersion,
214
+ targetVersion: confirmedVersion,
215
+ startedAt: new Date(this.now()).toISOString(),
216
+ message: 'Starting the guarded npm update.',
217
+ launcherPid: process.pid,
218
+ };
219
+ transitionOperation(this.options.root, current => {
220
+ // Discovery is asynchronous. Recheck under the cross-process status lock so an old helper
221
+ // cannot become provisional while this request replaces its operation ID.
222
+ this.refuseUnsettledOperation(current, installedVersion);
223
+ return operation;
224
+ });
225
+ launchedOperationId = id;
226
+ const managed = systemdUpdate(this.options.root);
227
+ if (managed) {
228
+ await launchSystemdUpdate(this.options.root, managed, { id, version: confirmedVersion, force: false });
229
+ helperStarted = true;
230
+ return await this.status(false);
231
+ }
232
+ const log = openSync(join(this.options.root, 'web-update.log'), constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
233
+ let child;
234
+ try {
235
+ fchmodSync(log, 0o600);
236
+ child = spawn(process.execPath, [bootstrapEntry, 'update'], {
237
+ cwd: process.cwd(),
238
+ detached: true,
239
+ stdio: ['ignore', log, log],
240
+ env: {
241
+ ...process.env,
242
+ FLOW_STATE_DIR: this.options.root,
243
+ FLOW_WEB_UPDATE_ID: id,
244
+ FLOW_WEB_UPDATE_VERSION: confirmedVersion,
245
+ },
246
+ });
247
+ }
248
+ finally {
249
+ closeSync(log);
250
+ }
251
+ await new Promise((resolvePromise, reject) => {
252
+ child.once('spawn', resolvePromise);
253
+ child.once('error', reject);
254
+ });
255
+ child.unref();
256
+ const helperPid = child.pid;
257
+ if (!helperPid)
258
+ throw new Error('The update helper did not start');
259
+ helperStarted = true;
260
+ // A fast refusal can finish before the parent observes `spawn`; the locked transition never
261
+ // overwrites that durable result merely to add the helper pid.
262
+ transitionOperation(this.options.root, current => current?.id === id && current.state === 'updating' ? { ...current, pid: helperPid } : current);
263
+ return await this.status(false);
264
+ }
265
+ catch (error) {
266
+ if (launchedOperationId !== undefined && !helperStarted) {
267
+ const operationId = launchedOperationId;
268
+ transitionOperation(this.options.root, operation => {
269
+ if (!operation || operation.id !== operationId || !['updating', 'unverified'].includes(operation.state) || operation.pid !== undefined)
270
+ return operation;
271
+ return { ...operation, state: error instanceof SystemdLaunchUncertain ? 'unverified' : 'failed', finishedAt: new Date(this.now()).toISOString(), message: publicError(error) };
272
+ });
273
+ }
274
+ throw error;
275
+ }
276
+ finally {
277
+ this.launching = false;
278
+ }
279
+ }
280
+ installedVersion() {
281
+ try {
282
+ return this.options.installation ? inspectUpdateInstallation(this.options.installation).version : this.options.installedVersion;
283
+ }
284
+ catch {
285
+ return this.options.installedVersion;
286
+ }
287
+ }
288
+ eligibility() {
289
+ let managed;
290
+ try {
291
+ managed = systemdUpdate(this.options.root);
292
+ }
293
+ catch (error) {
294
+ return { state: 'unsupported', reason: publicError(error) };
295
+ }
296
+ if ((managed && (this.options.mode !== 'foreground' || process.env.FLOW_SYSTEMD_HOST !== '1')) ||
297
+ (!managed && this.options.mode !== 'background')) {
298
+ return { state: 'unsupported', reason: 'Web updates require a background Session Host or configured systemd updater. Start Flow with `flow serve start`, or follow docs/systemd-updates.md.' };
299
+ }
300
+ if (!this.options.installation || !this.options.bootstrapEntry) {
301
+ return { state: 'unsupported', reason: this.options.unsupportedReason ?? 'This installation cannot update itself. Use npm to update Flow manually.' };
302
+ }
303
+ try {
304
+ inspectUpdateInstallation(this.options.installation);
305
+ }
306
+ catch (error) {
307
+ return { state: 'unsupported', reason: publicError(error) };
308
+ }
309
+ if (this.options.hasActiveWork()) {
310
+ return {
311
+ state: 'blocked',
312
+ reason: 'Finish active Agent Sessions, Workflow Executions, and Shells before updating. Then try again.',
313
+ };
314
+ }
315
+ return { state: 'eligible' };
316
+ }
317
+ operation(installedVersion) {
318
+ const observed = readOperation(this.options.root);
319
+ if (!observed)
320
+ return undefined;
321
+ let recoveryMessage;
322
+ if (observed.state === 'updating' && observed.pid !== undefined && !processAlive(observed.pid)) {
323
+ recoveryMessage = 'The update helper stopped before it reported a verified result. Reconnect to the Session Host; if it remains unavailable, repair the installation manually with npm.';
324
+ }
325
+ else if (observed.state === 'updating' && observed.pid === undefined && this.launchWasAbandoned(observed)) {
326
+ recoveryMessage = 'The Session Host stopped or timed out before it recorded the update helper process. Flow cannot verify whether the update started. Reconnect; if the host remains unavailable, repair the private global npm installation manually and restart it.';
327
+ }
328
+ const stored = recoveryMessage === undefined ? observed : transitionOperation(this.options.root, current => {
329
+ // `processAlive` and the abandonment checks happen outside the lock. Compare the launch fields
330
+ // again under the lock: a helper result or parent PID write that won meanwhile is authoritative.
331
+ if (current?.id !== observed.id || current.state !== 'updating' || current.startedAt !== observed.startedAt ||
332
+ current.pid !== observed.pid || current.launcherPid !== observed.launcherPid)
333
+ return current;
334
+ return {
335
+ ...current,
336
+ state: 'unverified',
337
+ finishedAt: new Date(this.now()).toISOString(),
338
+ message: recoveryMessage,
339
+ };
340
+ });
341
+ if (!stored)
342
+ return undefined;
343
+ if (stored.state === 'succeeded' && stored.installedVersion !== installedVersion) {
344
+ return this.publicOperation({
345
+ ...stored,
346
+ state: 'unverified',
347
+ message: `The update reported ${stored.installedVersion}, but the running Session Host is ${installedVersion}. Restart or repair Flow manually.`,
348
+ });
349
+ }
350
+ return this.publicOperation(stored);
351
+ }
352
+ refuseUnsettledOperation(operation, installedVersion) {
353
+ if (operation?.state === 'updating')
354
+ throw new UpdateRefusal('An update is already in progress.');
355
+ if (operation?.state === 'unverified' ||
356
+ (operation?.state === 'succeeded' && operation.installedVersion !== installedVersion)) {
357
+ throw new UpdateRefusal('The previous update still has an unverified result. Reconnect and verify or repair the Session Host before starting another update.');
358
+ }
359
+ }
360
+ launchWasAbandoned(operation) {
361
+ const startedAt = Date.parse(operation.startedAt);
362
+ const now = this.now();
363
+ if (!Number.isFinite(startedAt) || startedAt > now || now - startedAt >= WEB_UPDATE_LAUNCH_WINDOW_MS)
364
+ return true;
365
+ if (operation.launcherPid === undefined)
366
+ return false;
367
+ if (!Number.isInteger(operation.launcherPid) || operation.launcherPid <= 0)
368
+ return true;
369
+ return !processAlive(operation.launcherPid);
370
+ }
371
+ publicOperation(stored) {
372
+ const { pid: _pid, launcherPid: _launcherPid, ...operation } = stored;
373
+ return operation;
374
+ }
375
+ now() { return (this.options.now ?? Date.now)(); }
376
+ }
@@ -23,10 +23,28 @@ export function modelChoicesOf(models) {
23
23
  .flatMap(([provider, models]) => models.map((model) => ({ provider, model })));
24
24
  }
25
25
  /**
26
- * The Effort levels on offer, which belong to the model in force rather than to the session — a
27
- * model without an effort control returns none and the picker has nothing to show.
26
+ * Classify effort support without collapsing an absent/stale capability list into confirmed
27
+ * no-control. Only a model found in a confirmed list can produce `none`.
28
28
  */
29
+ export function effortCapability(capabilities, model) {
30
+ if (!capabilities)
31
+ return { status: "unknown", levels: [], reason: "Effort support is still loading." };
32
+ if (!model)
33
+ return { status: "unknown", levels: [], reason: "Select a model to confirm Effort support." };
34
+ const current = capabilities.models.find((candidate) => candidate.id === model.id);
35
+ if (!current)
36
+ return { status: "unknown", levels: [], reason: `Effort support for ${model.label ?? model.id} is unavailable.` };
37
+ const levels = current.effortLevels ?? [];
38
+ return levels.length > 0 ? { status: "supported", levels: [...levels] } : { status: "none", levels: [] };
39
+ }
40
+ /** The confirmed choices shared by the web and terminal pickers. */
29
41
  export function effortChoices(view) {
30
- const current = view.capabilities?.models.find((model) => model.id === view.model?.id);
31
- return (current ?? view.model)?.effortLevels ?? [];
42
+ return effortCapability(view.capabilities, view.model).levels;
43
+ }
44
+ /** First-model workflow default; never manufactures an unverified `medium`. */
45
+ export function initialWorkflowEffort(model) {
46
+ const levels = model.effortLevels ?? [];
47
+ if (levels.length === 0)
48
+ return "off";
49
+ return levels.includes("medium") ? "medium" : levels[0];
32
50
  }
@@ -70,7 +70,10 @@ export function reduce(state, entry) {
70
70
  status: deriveStatus({
71
71
  lifecycle: next.lifecycle,
72
72
  turnInFlight: next.turnInFlight,
73
- awaiting: next.asking !== undefined || next.authorising !== undefined,
73
+ // Independent producers can still need input after the parent turn ends, but their
74
+ // requests do not occupy that turn.
75
+ awaiting: (next.asking !== undefined && next.asking.producer === undefined) ||
76
+ (next.authorising !== undefined && next.authorising.producer === undefined),
74
77
  }),
75
78
  lastSeq: entry.seq,
76
79
  };
@@ -204,7 +207,12 @@ function applyEvent(state, event, at) {
204
207
  const asking = open && state.asking?.askId === event.askId
205
208
  ? state.asking
206
209
  : open
207
- ? { askId: event.askId, questions: event.questions, ...(event.context === undefined ? {} : { context: event.context }) }
210
+ ? {
211
+ askId: event.askId,
212
+ questions: event.questions,
213
+ ...(event.context === undefined ? {} : { context: event.context }),
214
+ ...(event.producer === undefined ? {} : { producer: event.producer }),
215
+ }
208
216
  : state.asking?.askId === event.askId
209
217
  ? undefined
210
218
  : state.asking;
@@ -241,6 +249,7 @@ function applyEvent(state, event, at) {
241
249
  ...(event.context === undefined ? {} : { context: event.context }),
242
250
  ...(event.allowAlways === undefined ? {} : { allowAlways: event.allowAlways }),
243
251
  ...(event.authorizationScope === undefined ? {} : { authorizationScope: event.authorizationScope }),
252
+ ...(event.producer === undefined ? {} : { producer: event.producer }),
244
253
  })
245
254
  : state.authorising?.callId === event.callId
246
255
  ? nextAwaiting(state.entries, event.callId)
@@ -258,10 +267,12 @@ function applyEvent(state, event, at) {
258
267
  };
259
268
  }
260
269
  case "turn_ended":
261
- // `asking` and `authorising` cleared here as well as on their own terminal snapshots. A backend
262
- // that tore down without emitting one would otherwise leave the composer locked out for good —
263
- // see ViewState.asking. Clearing twice costs nothing; clearing never is unrecoverable.
264
- return { ...state, turnInFlight: false, asking: undefined, authorising: undefined };
270
+ return {
271
+ ...state,
272
+ turnInFlight: false,
273
+ asking: state.asking?.producer === undefined ? undefined : state.asking,
274
+ authorising: state.authorising?.producer === undefined ? undefined : state.authorising,
275
+ };
265
276
  case "queue_changed":
266
277
  return {
267
278
  ...state,
@@ -435,6 +446,7 @@ function nextAwaiting(entries, except) {
435
446
  ...(next.permissionContext === undefined ? {} : { context: next.permissionContext }),
436
447
  ...(next.allowAlways === undefined ? {} : { allowAlways: next.allowAlways }),
437
448
  ...(next.authorizationScope === undefined ? {} : { authorizationScope: next.authorizationScope }),
449
+ ...(next.producer === undefined ? {} : { producer: next.producer }),
438
450
  } : undefined;
439
451
  }
440
452
  /** Spread onto an Entry, so an unattributed event does not carry an explicit `producer: undefined`. */
@@ -33,27 +33,41 @@ export function deriveStatus(of) {
33
33
  export function occupied(status) {
34
34
  return status === "running" || status === "awaiting";
35
35
  }
36
- /**
37
- * Which band of the rail an Agent Session belongs to, most alive first.
38
- *
39
- * The rail is banded rather than ordered by one timestamp, because a single recency key put a
40
- * finished Agent Session above one that was still working — and the top of a list is where a reader
41
- * looks for what is happening. Banding fixes that without reintroducing churn: a row moves when its
42
- * band changes and at no other time, so a turn can stream for an hour without touching the order.
43
- *
44
- * Ended has no band of its own. An Ended Agent Session is not reaped and stays in the list, and it
45
- * is as finished as a Settled one, so it sits with them at the bottom.
46
- */
47
- export function railBand(of) {
48
- if (of.status === "awaiting")
49
- return 0;
50
- if (of.status === "running" || working(of))
51
- return 1;
36
+ export const RAIL_GROUPS = [
37
+ "needs-input",
38
+ "unread",
39
+ "working",
40
+ "idle",
41
+ "dormant",
42
+ "filed-away",
43
+ ];
44
+ export function railGroup(of) {
45
+ // Terminal Lifecycle wins over stale independent-work/request indexes. Settle and End file a row
46
+ // away; nothing belonging to a stopped Backend Session can remain answerable above that boundary.
47
+ if (of.status === "settled" || of.status === "ended")
48
+ return "filed-away";
49
+ if (of.attention?.group === "needs-input")
50
+ return "needs-input";
51
+ if (of.attention?.group === "unread")
52
+ return "unread";
53
+ if (of.status === "running" || of.status === "awaiting" || working(of))
54
+ return "working";
52
55
  if (of.status === "idle")
53
- return 2;
54
- if (of.status === "dormant")
55
- return 3;
56
- return 4;
56
+ return "idle";
57
+ return "dormant";
58
+ }
59
+ export function railGroupLabel(group) {
60
+ switch (group) {
61
+ case "needs-input": return "Needs input";
62
+ case "unread": return "Unread";
63
+ case "working": return "Working";
64
+ case "idle": return "Idle";
65
+ case "dormant": return "Dormant";
66
+ case "filed-away": return "Filed away";
67
+ }
68
+ }
69
+ export function railGroupRank(of) {
70
+ return RAIL_GROUPS.indexOf(railGroup(of));
57
71
  }
58
72
  /**
59
73
  * Working, but not occupancy. A backgrounded Subagent or an open Background Call leaves the status
@@ -0,0 +1,30 @@
1
+ import { initialWorkflowEffort } from "./model-choices.js";
2
+ /**
3
+ * Effort after choosing a workflow model. Existing configured values remain untouched when invalid;
4
+ * only the first selection gets a confirmed default, while no-control always uses the `off`
5
+ * sentinel.
6
+ */
7
+ export function effortForWorkflowModelSelection(currentModelId, currentEffort, nextModel) {
8
+ if ((nextModel.effortLevels?.length ?? 0) === 0)
9
+ return "off";
10
+ return currentModelId === "" ? initialWorkflowEffort(nextModel) : currentEffort;
11
+ }
12
+ /** The one allowed automatic workflow correction: confirmed no-control always stores `off`. */
13
+ export function normalizeNoControlEffort(definition, catalogue) {
14
+ if (!definition || !catalogue)
15
+ return definition;
16
+ const listing = catalogue.find((entry) => entry.backend === definition.backend);
17
+ if (!listing || listing.problem)
18
+ return definition;
19
+ let changed = false;
20
+ const steps = definition.steps.map((step) => {
21
+ if (step.kind !== "agent")
22
+ return step;
23
+ const model = listing.models.find((candidate) => candidate.id === step.model);
24
+ if (!model || (model.effortLevels?.length ?? 0) > 0 || step.effort === "off")
25
+ return step;
26
+ changed = true;
27
+ return { ...step, effort: "off" };
28
+ });
29
+ return changed ? { ...definition, steps } : definition;
30
+ }