@nathanstephenson/flow 0.1.10-beta.5 → 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 (67) hide show
  1. package/README.md +5 -19
  2. package/build/backend-worker-chunks/{chunk-JOI2POLP.mjs → chunk-U73G6KK4.mjs} +18 -0
  3. package/build/backend-worker-chunks/{claude-GY27HBAY.mjs → claude-THGSOTC2.mjs} +7 -1
  4. package/build/backend-worker-chunks/{pi-JV6MWPW7.mjs → pi-5LAWIJNE.mjs} +82 -3
  5. package/build/backend-worker.mjs +7 -3
  6. package/dist/backend/claude/index.js +6 -0
  7. package/dist/backend/fake/index.js +6 -0
  8. package/dist/backend/pi/index.js +34 -2
  9. package/dist/backend/pi/plan-limits.js +41 -0
  10. package/dist/backend/plan-limits.js +17 -0
  11. package/dist/backend/worker/entry.js +4 -1
  12. package/dist/backend/worker/index.js +5 -0
  13. package/dist/backend/worker/protocol.js +2 -1
  14. package/dist/build-id +1 -1
  15. package/dist/cli/application.js +4 -37
  16. package/dist/cli/bootstrap.js +2 -2
  17. package/dist/cli/install-guard.js +1 -1
  18. package/dist/client/context-usage.js +3 -4
  19. package/dist/client/enquiry.js +0 -6
  20. package/dist/client/markdown.js +3 -2
  21. package/dist/client/model-choices.js +1 -1
  22. package/dist/client/permission.js +1 -2
  23. package/dist/client/relative-time.js +1 -1
  24. package/dist/client/scope-kind.js +2 -3
  25. package/dist/client/search.js +1 -1
  26. package/dist/client/status.js +1 -1
  27. package/dist/client/subagent-tree.js +1 -1
  28. package/dist/client/tool-chains.js +1 -1
  29. package/dist/client/tool-summary.js +2 -3
  30. package/dist/daemon/config-store.js +3 -0
  31. package/dist/daemon/config.js +63 -3
  32. package/dist/daemon/git.js +33 -2
  33. package/dist/daemon/github-image.js +18 -0
  34. package/dist/daemon/host.js +159 -9
  35. package/dist/daemon/runtime.js +2 -2
  36. package/dist/daemon/server.js +28 -2
  37. package/dist/daemon/skills.js +24 -0
  38. package/dist/daemon/spend-ledger.js +118 -0
  39. package/dist/daemon/summariser.js +11 -4
  40. package/dist/daemon/tour.js +42 -0
  41. package/dist/daemon/workflow-builder.js +3 -1
  42. package/dist/daemon/workflow-execution-resources.js +1 -1
  43. package/dist/daemon/workflow-routes.js +19 -0
  44. package/dist/daemon/workflow-schedule-driver.js +5 -1
  45. package/dist/daemon/workflow-schedules.js +6 -5
  46. package/dist/protocol/plan-limits.js +1 -0
  47. package/dist/protocol/spend.js +2 -0
  48. package/dist/workflows/scheduler.js +26 -14
  49. package/dist/workflows/schedules.js +1 -0
  50. package/dist/workflows/store.js +16 -2
  51. package/package.json +1 -1
  52. package/web/dist/assets/index-5E7qbtVD.js +51 -0
  53. package/web/dist/assets/index-BvkM2cWL.css +2 -0
  54. package/web/dist/assets/{switch-B00FEUA7.js → select-C-BND5Jn.js} +1 -1
  55. package/web/dist/assets/{settings-mcp-BwOPXAfH.js → settings-mcp-CBXZt_cf.js} +1 -1
  56. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-29ZG3w6p.js} +1 -1
  57. package/web/dist/assets/{settings-workflows-DocTa31_.js → settings-workflows-CE11fxNj.js} +2 -2
  58. package/web/dist/assets/workflow-api-DkUjAZ4w.js +6 -0
  59. package/web/dist/assets/{workflows-DJqUuGyg.js → workflows-DdogjBu3.js} +6 -6
  60. package/web/dist/assets/{workflows-pane-oM1fO_BC.js → workflows-pane-B0dyuSuz.js} +1 -1
  61. package/web/dist/index.html +5 -5
  62. package/dist/tui/app.js +0 -612
  63. package/dist/tui/keys.js +0 -90
  64. package/dist/tui/render.js +0 -417
  65. package/web/dist/assets/index-BqZ_iUmY.css +0 -2
  66. package/web/dist/assets/index-CxdSb7k0.js +0 -51
  67. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
@@ -0,0 +1,42 @@
1
+ import { head, run, GIT_READ_TIMEOUT_MS } from "./git.js";
2
+ import { gh } from "./github.js";
3
+ import { changes, changesText } from "./changes.js";
4
+ import { resolveRepository } from "./repository.js";
5
+ export const TOUR_INSTRUCTIONS = [
6
+ "Give an in-depth tour of this branch's committed changes, with the diff shown for each change you discuss.",
7
+ "Step through the functional implementation in the order it runs, not file by file.",
8
+ "Include all important diffs. Put a short summary of the supporting changes at the bottom.",
9
+ "The input has the branch, its base, the commits and the diff. Read files in the Scope only when the diff is not enough.",
10
+ "Read only: do not edit, write, run commands or ask questions.",
11
+ 'Write the tour as markdown and return it as {"tour":"<markdown>"}.',
12
+ ].join("\n");
13
+ export const TOUR_READ_TOOLS = ["Read", "Glob", "Grep", "read", "grep", "find", "ls"];
14
+ export async function tourInput(scope, github = gh) {
15
+ const branch = await head(scope);
16
+ if (!branch.ok)
17
+ throw new Error(branch.failure.message);
18
+ if (branch.value.detached)
19
+ throw new Error("HEAD is detached. Switch to a branch before you start a tour.");
20
+ const sha = await run(scope, ["rev-parse", "HEAD"], GIT_READ_TIMEOUT_MS);
21
+ if (!sha.ok)
22
+ throw new Error(sha.failure.message);
23
+ const repository = await resolveRepository(scope, branch.value.name, github);
24
+ const listed = await changes(scope, "branch", undefined, github);
25
+ if (listed.commits.length === 0)
26
+ throw new Error("This branch has no committed changes to tour.");
27
+ return {
28
+ branch: branch.value.name,
29
+ head: sha.value.trim(),
30
+ repo: repository.head.repo,
31
+ input: `Branch: ${branch.value.name}\nBase: ${listed.base}\n${await changesText(scope, "branch", undefined, undefined, github)}`,
32
+ };
33
+ }
34
+ export function tourText(raw) {
35
+ try {
36
+ const parsed = JSON.parse(raw);
37
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.tour === "string")
38
+ return parsed.tour;
39
+ }
40
+ catch { }
41
+ return raw;
42
+ }
@@ -374,8 +374,10 @@ export class WorkflowBuilderService {
374
374
  },
375
375
  emit: event => {
376
376
  if (event.type === 'context_usage') {
377
- if (event.spend && entry.meterGeneration === generation)
377
+ if (event.spend && entry.meterGeneration === generation) {
378
378
  entry.view.spend = structuredClone(event.spend);
379
+ this.options.host.recordSpend('builder', entry.view.id, entry.view.scope || undefined, event.spend);
380
+ }
379
381
  if (!entry.closed && entry.generation === generation)
380
382
  this.event(entry, event);
381
383
  }
@@ -22,7 +22,7 @@ export class OccurrenceResources {
22
22
  connections() { return this.host.scheduledConnections(this.environment.connectionIds); }
23
23
  mcp(connectionId, _mode, signal) { return this.environment.client(connectionId, signal); }
24
24
  sandbox() { return this.environment.vm(); }
25
- attach() { return this.attached ??= this.attachment(); }
25
+ attach() { return this.attached ??= this.attachment().catch(error => { this.attached = undefined; throw error; }); }
26
26
  restoreAttachment(attach) { this.attachment = attach; }
27
27
  }
28
28
  export class WorkflowExecutionResources {
@@ -32,6 +32,25 @@ function validateWorkflowContracts(definition, workflows) {
32
32
  if (!selected || !isDeepStrictEqual(selected.contract, step.contract))
33
33
  throw new Error(`Workflow step ${step.name} requires a saved host-derived contract`);
34
34
  }
35
+ const path = new Set();
36
+ const visit = (current) => {
37
+ if (path.has(current.id))
38
+ throw new Error('Recursive Workflow call');
39
+ path.add(current.id);
40
+ for (const step of current.steps) {
41
+ if (step.kind !== 'workflow')
42
+ continue;
43
+ let target = step.workflowId === definition.id ? definition : undefined;
44
+ try {
45
+ target ??= workflows.getDefinition(step.workflowId);
46
+ }
47
+ catch { }
48
+ if (target)
49
+ visit(target);
50
+ }
51
+ path.delete(current.id);
52
+ };
53
+ visit(definition);
35
54
  }
36
55
  export function workflowRequestError(error, redact = message => message) {
37
56
  // Redact before truncation: a credential containing ':' must not leak its prefix.
@@ -7,7 +7,7 @@ import { ScheduledExecutionStarted } from './workflow-schedules.js';
7
7
  import { resolveWorkflowCalls } from '../workflows/calls.js';
8
8
  import { ScheduleValidationError } from '../workflows/schedule-errors.js';
9
9
  import { includedProjects } from './projects.js';
10
- import { isClean, localBranches, planWorktree, removeMergedBranch, removeWorktree, run, GIT_WRITE_TIMEOUT_MS } from './git.js';
10
+ import { isClean, localBranches, planWorktree, removeMergedBranch, removeWorktree, run, updateSourceBranch, GIT_WRITE_TIMEOUT_MS } from './git.js';
11
11
  export function scheduleDriver(options) {
12
12
  const { host, config, workflows, executions, schedules, transcripts } = options;
13
13
  const repositories = new Map();
@@ -164,6 +164,10 @@ export function scheduleDriver(options) {
164
164
  const provision = previous.catch(() => { }).then(async () => {
165
165
  signal?.throwIfAborted();
166
166
  const from = occurrence.settings.worktree.from;
167
+ if (config.updateSourceBranch() && !(await updateSourceBranch(repo, from)).ok) {
168
+ occurrence = { ...occurrence, warning: 'Source Branch not updated; cut from the local branch.' };
169
+ }
170
+ signal?.throwIfAborted();
167
171
  const planned = await planWorktree({ repo, from, branch: `flow/schedule-${occurrence.id}`, under: transcripts.worktreesRoot() });
168
172
  if (!planned.ok)
169
173
  throw new Error('Could not plan worktree');
@@ -254,15 +254,16 @@ export class WorkflowScheduleService {
254
254
  }
255
255
  }
256
256
  }
257
- create(settings, enabled) {
258
- return this.serial(async () => { await this.driver.validate(settings); const saved = createSchedule(settings, this.now(), enabled); this.store.saveSchedule(saved); return saved; });
257
+ async create(settings, enabled) {
258
+ await this.driver.validate(settings);
259
+ return this.serial(() => { const saved = createSchedule(settings, this.now(), enabled); this.store.saveSchedule(saved); return saved; });
259
260
  }
260
- update(id, revision, settings, enabled) {
261
- return this.serial(async () => {
261
+ async update(id, revision, settings, enabled) {
262
+ await this.driver.validate(settings);
263
+ return this.serial(() => {
262
264
  const current = this.store.getSchedule(id);
263
265
  if (current.revision !== revision)
264
266
  throw new ScheduleRevisionConflict();
265
- await this.driver.validate(settings);
266
267
  const saved = editSchedule(current, settings, enabled, this.now());
267
268
  this.store.saveSchedule(saved, revision);
268
269
  return saved;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export const SPEND_SOURCES = ["session", "workflow", "naming", "publish", "builder"];
2
+ export const SPEND_WINDOWS = ["day", "week", "month", "lifetime"];
@@ -27,7 +27,15 @@ export class WorkflowScheduler {
27
27
  this.executors = executors;
28
28
  this.onResume = onResume;
29
29
  for (const owner of store.listOwners()) {
30
- for (const record of store.listOwnedExecutions(owner)) {
30
+ let records;
31
+ try {
32
+ records = store.listOwnedExecutions(owner);
33
+ }
34
+ catch {
35
+ console.error('Workflow Execution owner records are invalid. Files retained for manual review.');
36
+ continue;
37
+ }
38
+ for (const record of records) {
31
39
  if (!occupied(record))
32
40
  continue;
33
41
  if (this.slots.has(executionOwnerKey(owner)))
@@ -320,20 +328,22 @@ export class WorkflowScheduler {
320
328
  }
321
329
  }
322
330
  reconcile(active) {
331
+ if (occupied(active.record)) {
332
+ for (const [id, state] of Object.entries(active.record.steps)) {
333
+ if (state.status !== 'running' || active.calls.has(id))
334
+ continue;
335
+ state.status = 'interrupted';
336
+ const attempt = state.attempts.at(-1);
337
+ attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
338
+ attempt.finishedAt ??= Date.now();
339
+ }
340
+ active.record.status = 'recovery-required';
341
+ active.stopped = !!active.parent?.stopped || Object.values(active.record.steps).some(state => state.status === 'interrupted');
342
+ for (const id of active.calls.keys())
343
+ this.armCall(active, id);
344
+ }
323
345
  for (const call of active.calls.values())
324
346
  this.reconcile(call.child);
325
- if (!occupied(active.record))
326
- return;
327
- for (const [id, state] of Object.entries(active.record.steps)) {
328
- if (state.status !== 'running' || active.calls.has(id))
329
- continue;
330
- state.status = 'interrupted';
331
- const attempt = state.attempts.at(-1);
332
- attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
333
- attempt.finishedAt ??= Date.now();
334
- }
335
- active.record.status = 'recovery-required';
336
- active.stopped = true;
337
347
  }
338
348
  releaseCancelledCall(active, stepId) {
339
349
  const call = active.calls.get(stepId);
@@ -617,7 +627,9 @@ export class WorkflowScheduler {
617
627
  else {
618
628
  const terminals = active.graph.order.filter(step => active.record.steps[step.id].status === 'completed' && (active.record.testStepId || !active.graph.outgoing.get(step.id).some(edge => this.edgeState(active, edge) === 'selected')));
619
629
  active.record.result = terminals.length === 1 ? active.record.steps[terminals[0].id].output : Object.fromEntries(terminals.map(step => [step.name, active.record.steps[step.id].output]));
620
- active.record.status = Object.values(active.record.loops ?? {}).some(loop => loop.grants.length) || Object.values((active.root ?? active).record.invocations ?? {}).some(invocation => invocation.status === 'completed-with-recovery') || states.some(([, state]) => state.attempts.some(attempt => attempt.error || attempt.action !== 'execute')) ? 'completed-with-recovery' : 'completed';
630
+ const invocations = (active.root ?? active).record.invocations ?? {};
631
+ const descends = (id) => id !== undefined && (id === active.record.id || descends(invocations[id].parentInvocationId));
632
+ active.record.status = Object.values(active.record.loops ?? {}).some(loop => loop.grants.length) || Object.values(invocations).some(invocation => invocation.status === 'completed-with-recovery' && (!active.parent || descends(invocation.parentInvocationId))) || states.some(([, state]) => state.attempts.some(attempt => attempt.error || attempt.action !== 'execute')) ? 'completed-with-recovery' : 'completed';
621
633
  active.record.finishedAt = Date.now();
622
634
  }
623
635
  this.persist(active);
@@ -44,6 +44,7 @@ export const occurrenceValidator = z.object({
44
44
  createdAt: timestamp, finishedAt: timestamp.optional(), sessionId: storageId.optional(), association: z.enum(['pending', 'attached', 'failed']).optional(), executionId: storageId.optional(),
45
45
  scope: z.string().min(1).optional(), worktree: z.object({ path: z.string(), repo: z.string(), branch: z.string() }).strict().optional(),
46
46
  outcome: z.string().max(2000).optional(),
47
+ warning: z.string().max(2000).optional(),
47
48
  }).strict().superRefine((value, context) => {
48
49
  if (value.id !== occurrenceId(value.scheduleId, value.activation, value.scheduledAt))
49
50
  context.addIssue({ code: 'custom', message: 'Invalid occurrence identity' });
@@ -63,9 +63,23 @@ export class WorkflowStore {
63
63
  const directory = join(stateRoot, 'workflow-schedules', 'executions');
64
64
  const occurrences = existsSync(directory) ? readdirSync(directory, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => ({ kind: 'occurrence', occurrenceId: entry.name })) : [];
65
65
  for (const owner of [...this.listSessionIds().map(sessionId => ({ kind: 'session', sessionId })), ...occurrences]) {
66
+ let history;
67
+ try {
68
+ history = this.historyPath(owner);
69
+ }
70
+ catch {
71
+ console.error('Workflow Execution owner directory is invalid. Directory retained for manual review.');
72
+ continue;
73
+ }
66
74
  this.owners.set(this.ownerIndexKey(owner), owner);
67
- for (const id of ids(this.historyPath(owner)))
68
- this.index(this.readExecution(owner, id));
75
+ for (const id of ids(history)) {
76
+ try {
77
+ this.index(this.readExecution(owner, id));
78
+ }
79
+ catch {
80
+ console.error('Workflow Execution checkpoint is invalid. File retained for manual review.');
81
+ }
82
+ }
69
83
  }
70
84
  }
71
85
  saveDefinition(definition) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathanstephenson/flow",
3
- "version": "0.1.10-beta.5",
3
+ "version": "0.1.10-beta.7",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",