@nathanstephenson/flow 0.1.5 → 0.1.6

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 (49) hide show
  1. package/dist/backend/claude/index.js +28 -6
  2. package/dist/backend/claude/workflow-builder.js +12 -0
  3. package/dist/backend/mcp.js +47 -7
  4. package/dist/backend/pi/index.js +30 -16
  5. package/dist/backend/pi/workflow-builder.js +11 -0
  6. package/dist/backend/worker/entry.js +11 -3
  7. package/dist/backend/worker/index.js +31 -8
  8. package/dist/backend/worker/launcher.js +1 -0
  9. package/dist/backend/workflow-builder.js +8 -0
  10. package/dist/build-id +1 -1
  11. package/dist/cli/bootstrap.js +1 -1
  12. package/dist/cli/main.js +13 -1
  13. package/dist/daemon/host.js +14 -0
  14. package/dist/daemon/mcp-auth.js +32 -4
  15. package/dist/daemon/runtime.js +13 -3
  16. package/dist/daemon/server.js +34 -0
  17. package/dist/daemon/workflow-authoring-scope-checks.js +134 -0
  18. package/dist/daemon/workflow-authoring-scope-reader.js +42 -0
  19. package/dist/daemon/workflow-authoring-scope.js +49 -0
  20. package/dist/daemon/workflow-builder-files.js +321 -0
  21. package/dist/daemon/workflow-builder-guidance.js +31 -0
  22. package/dist/daemon/workflow-builder-reader.js +131 -0
  23. package/dist/daemon/workflow-builder-routes.js +61 -0
  24. package/dist/daemon/workflow-builder.js +480 -0
  25. package/dist/daemon/workflow-mcp-authoring-routes.js +44 -0
  26. package/dist/daemon/workflow-mcp-authoring.js +313 -0
  27. package/dist/isolation/filesystem.js +7 -4
  28. package/dist/protocol/workflow-builder.js +1 -0
  29. package/dist/protocol/workflow-mcp-authoring.js +1 -0
  30. package/package.json +1 -1
  31. package/web/dist/assets/index-C_M0oDHN.js +38 -0
  32. package/web/dist/assets/index-D8CGXp1X.css +2 -0
  33. package/web/dist/assets/{input-CqyJUgIE.js → input-D9fbSfQF.js} +1 -1
  34. package/web/dist/assets/settings-mcp-BvSvGrcs.js +1 -0
  35. package/web/dist/assets/{settings-secrets-D3zCO2H1.js → settings-secrets-DlkU6W_Z.js} +1 -1
  36. package/web/dist/assets/settings-workflows-DNGE-b_U.js +23 -0
  37. package/web/dist/assets/switch-DEvHojwW.js +1 -0
  38. package/web/dist/assets/workflow-editors-D6XT6pcb.js +137 -0
  39. package/web/dist/assets/{workflows-9aO6cptD.css → workflows-Bb90N0XJ.css} +1 -1
  40. package/web/dist/assets/workflows-LSCnXIxN.js +7 -0
  41. package/web/dist/assets/workflows-pane-BIlp7uyg.js +1 -0
  42. package/web/dist/index.html +5 -4
  43. package/web/dist/assets/index-2oJWC9JF.css +0 -2
  44. package/web/dist/assets/index-6BD3ul5N.js +0 -174
  45. package/web/dist/assets/settings-mcp-DOQOULdG.js +0 -1
  46. package/web/dist/assets/settings-workflows-BSVIqm4R.js +0 -23
  47. package/web/dist/assets/switch-ehZe7Kr5.js +0 -1
  48. package/web/dist/assets/workflows-DC1k1O8g.js +0 -7
  49. package/web/dist/assets/workflows-pane-B0hL69SD.js +0 -1
@@ -1,4 +1,5 @@
1
1
  import { workflowParentServer } from "./workflow-parent.js";
2
+ import { workflowBuilderServer, claudeWorkflowBuilderToolNames } from "./workflow-builder.js";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { claudeAutoCompactionEnv } from "./auto-compaction.js";
4
5
  import { spawn, spawnSync } from "node:child_process";
@@ -216,7 +217,10 @@ class ClaudeSession {
216
217
  claudeState;
217
218
  constructor(options, backendOptions, claudeState) {
218
219
  this.claudeState = claudeState;
219
- this.parentWorkflow = workflowParentServer(options.tools === "none" ? undefined : options.workflow);
220
+ this.parentWorkflow = options.workflowBuilder ? workflowBuilderServer(options.workflowBuilder)
221
+ : workflowParentServer(options.tools === "none" ? undefined : options.workflow);
222
+ if (options.workflowBuilder)
223
+ this.capabilities = { ...this.capabilities, subagents: false, enquiries: false, permissions: false };
220
224
  this.options = options;
221
225
  this.permissionMode = options.permissionMode ?? "ask";
222
226
  this.backendOptions = backendOptions;
@@ -230,8 +234,9 @@ class ClaudeSession {
230
234
  this.spend = options.priorSpend;
231
235
  // A one-shot text call pre-approves nothing and authorises nothing — see
232
236
  // `BackendCreateOptions.tools`. The deny in `canUseTool` below is the half that makes it hold.
233
- const toolless = options.tools === "none";
234
- const preApproved = toolless ? [] : [...(backendOptions.allowedTools ?? DEFAULT_ALLOWED_TOOLS), ...(options.workflow ? ["mcp__flow_workflow__workflow_inspect", "mcp__flow_workflow__workflow_recover", "mcp__flow_workflow__workflow_relay_enquiry", "mcp__flow_workflow__workflow_relay_permission"] : [])];
237
+ const builder = options.workflowBuilder;
238
+ const toolless = !builder && options.tools === "none";
239
+ const preApproved = builder ? claudeWorkflowBuilderToolNames : toolless ? [] : [...(backendOptions.allowedTools ?? DEFAULT_ALLOWED_TOOLS), ...(options.workflow ? ["mcp__flow_workflow__workflow_inspect", "mcp__flow_workflow__workflow_recover", "mcp__flow_workflow__workflow_relay_enquiry", "mcp__flow_workflow__workflow_relay_permission"] : [])];
235
240
  this.allowed = new Set(toolless ? [] : [...preApproved, ...(options.standingAuthorisations ?? [])]);
236
241
  // `allowedTools` is what the CLI auto-approves before the callback, and it is given only the
237
242
  // pre-approved set. A Standing Authorisation is honoured in `canUseTool` instead, so that
@@ -242,7 +247,7 @@ class ClaudeSession {
242
247
  cwd: options.scope,
243
248
  env,
244
249
  includePartialMessages: true,
245
- mcpServers: toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow },
250
+ mcpServers: builder ? this.parentWorkflow : toolless ? {} : { ...claudeMcpServers(options.mcp), ...this.parentWorkflow },
246
251
  strictMcpConfig: true,
247
252
  // NOT bypassPermissions: it auto-approves before canUseTool is consulted, and the SDK warns
248
253
  // as much. "default" runs the permission flow, allowedTools auto-approves the pre-approved
@@ -250,7 +255,12 @@ class ClaudeSession {
250
255
  permissionMode: "default",
251
256
  allowedTools: preApproved,
252
257
  ...(backendOptions.disallowedTools ? { disallowedTools: backendOptions.disallowedTools } : {}),
253
- ...(backendOptions.systemPrompt ? { systemPrompt: backendOptions.systemPrompt } : {}),
258
+ ...(builder ? {
259
+ tools: [], settingSources: [], skills: [], plugins: [], agents: {},
260
+ settings: { disableAllHooks: true, enabledPlugins: {}, syncClaudeAiSkills: false, syncClaudeAiPlugins: false,
261
+ disableClaudeAiConnectors: true, disableBundledSkills: true },
262
+ systemPrompt: builder.instructions,
263
+ } : backendOptions.systemPrompt ? { systemPrompt: backendOptions.systemPrompt } : {}),
254
264
  ...(options.modelId ? { model: options.modelId } : {}),
255
265
  // Effort is also settable later, but starting with it avoids a first turn at the wrong level
256
266
  // while the model list is still in flight. Levels Claude does not have wait for the clamp.
@@ -279,6 +289,11 @@ class ClaudeSession {
279
289
  return { behavior: "deny", message: "This session runs no tools" };
280
290
  if (extra.signal.aborted || this.disposed)
281
291
  return { behavior: "deny", message: `${toolName} was not authorised: the permission request was cancelled. Continue without it.` };
292
+ // Restriction precedes permission modes and Standing Authorisations. Never park a builder.
293
+ if (builder)
294
+ return claudeWorkflowBuilderToolNames.includes(toolName)
295
+ ? { behavior: "allow", updatedInput: input }
296
+ : { behavior: "deny", message: "This workflow builder tool is not enabled" };
282
297
  if (toolName === ASK_TOOL)
283
298
  return await this.ask(extra.toolUseID, input);
284
299
  if (this.permissionMode === "always" || this.allowed.has(toolName) || this.workflowGrants.has(toolName))
@@ -433,6 +448,8 @@ class ClaudeSession {
433
448
  * Skill opens the menu expecting to find it.
434
449
  */
435
450
  async skills() {
451
+ if (this.options.workflowBuilder)
452
+ return [];
436
453
  const { skills } = await this.stream.reloadSkills();
437
454
  return skills.map((skill) => ({
438
455
  name: skill.name,
@@ -566,7 +583,8 @@ class ClaudeSession {
566
583
  }
567
584
  }
568
585
  async setPermissionMode(mode) {
569
- await this.stream.setPermissionMode(mode === "auto" ? "auto" : "default");
586
+ // Native Auto can authorise before canUseTool. Builders always retain the callback gate.
587
+ await this.stream.setPermissionMode(!this.options.workflowBuilder && mode === "auto" ? "auto" : "default");
570
588
  this.permissionMode = mode;
571
589
  }
572
590
  async setModel(modelId) {
@@ -614,11 +632,15 @@ class ClaudeSession {
614
632
  return known ?? { id: modelId ?? "default", provider: "anthropic" };
615
633
  }
616
634
  async refreshMcp() {
635
+ if (this.options.workflowBuilder)
636
+ return;
617
637
  await refreshClaudeMcp(this.stream, this.options.mcp, this.parentWorkflow);
618
638
  }
619
639
  startWorkflowSubagent(options) {
620
640
  if (this.disposed)
621
641
  throw new Error("Backend Session disposed");
642
+ if (this.options.workflowBuilder)
643
+ throw new Error("Workflow builder cannot create Subagents");
622
644
  if (this.options.tools === "none")
623
645
  throw new Error("This Backend Session runs no tools");
624
646
  const handle = new ClaudeWorkflowSubagent({ cwd: this.options.scope,
@@ -0,0 +1,12 @@
1
+ import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
2
+ import { z } from "zod";
3
+ import { workflowBuilderTools } from "../workflow-builder.js";
4
+ export const claudeWorkflowBuilderToolNames = workflowBuilderTools.map(({ name }) => `mcp__flow_workflow_builder__${name}`);
5
+ export function workflowBuilderServer(builder) {
6
+ // Only this in-process transport is enabled: no external MCP connections are inherited.
7
+ return { flow_workflow_builder: createSdkMcpServer({ name: "flow_workflow_builder", alwaysLoad: true,
8
+ tools: workflowBuilderTools.map(({ name, field, method, description }) => tool(name, description, { [field]: z.string() }, async (input) => ({
9
+ content: [{ type: "text", text: await builder[method](input[field]) }],
10
+ }))),
11
+ }) };
12
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, realpathSync, statSync } from "node:fs";
2
+ import { closeSync, constants, existsSync, fstatSync, openSync, realpathSync, statSync } from "node:fs";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { prepareFilesystemIsolation } from "../isolation/filesystem.js";
5
5
  import { SupervisedStdioTransport } from "./mcp-stdio-supervisor.js";
@@ -48,6 +48,7 @@ export class McpSession {
48
48
  states = new Map();
49
49
  pending = new Map();
50
50
  activeCalls = new Map();
51
+ exits = new Set();
51
52
  disposed = false;
52
53
  direct;
53
54
  connections;
@@ -57,7 +58,8 @@ export class McpSession {
57
58
  protectedPaths;
58
59
  stateRoot;
59
60
  isolationEnabled;
60
- constructor(connections, scope, auth, direct = false, resolveSecret, protectedPaths, stateRoot, isolationEnabled = true) {
61
+ expectedScopeIdentity;
62
+ constructor(connections, scope, auth, direct = false, resolveSecret, protectedPaths, stateRoot, isolationEnabled = true, expectedScopeIdentity) {
61
63
  this.connections = structuredClone(connections);
62
64
  this.scope = scope;
63
65
  this.auth = auth;
@@ -66,6 +68,7 @@ export class McpSession {
66
68
  this.protectedPaths = protectedPaths;
67
69
  this.stateRoot = stateRoot;
68
70
  this.isolationEnabled = isolationEnabled;
71
+ this.expectedScopeIdentity = expectedScopeIdentity;
69
72
  }
70
73
  registrationFailed() {
71
74
  for (const [id] of this.states)
@@ -116,6 +119,14 @@ export class McpSession {
116
119
  const client = new Client({ name: "Flow", version: "1.0.0" }, { capabilities: {} });
117
120
  this.clients.set(id, client);
118
121
  let isolation;
122
+ let scopeFd;
123
+ const cleanup = () => {
124
+ isolation?.cleanup();
125
+ if (scopeFd !== undefined) {
126
+ closeSync(scopeFd);
127
+ scopeFd = undefined;
128
+ }
129
+ };
119
130
  let transport;
120
131
  let stopping;
121
132
  const stop = () => stopping ??= (async () => {
@@ -125,7 +136,7 @@ export class McpSession {
125
136
  // A bounded stdio close may return before a kernel-stalled process exits. Its pinned
126
137
  // mount state is released only by the actual-exit hook registered below.
127
138
  if (!(transport instanceof SupervisedStdioTransport))
128
- isolation?.cleanup();
139
+ cleanup();
129
140
  })();
130
141
  this.stops.set(id, stop);
131
142
  try {
@@ -137,19 +148,36 @@ export class McpSession {
137
148
  }
138
149
  const configured = connection.transport === "http" ? this.configuredHeaders(connection.headers) : {};
139
150
  if (connection.transport === "stdio" && !this.isolationEnabled) {
151
+ // Refuse unsupported authoring before touching a potentially stalled Scope path.
152
+ if (this.expectedScopeIdentity !== undefined && process.platform !== "linux")
153
+ throw new Error("Descriptor-bound MCP authoring requires Linux");
140
154
  const scope = realpathSync(this.scope);
141
155
  if (!statSync(scope).isDirectory())
142
156
  throw new Error("Scope must be a directory");
157
+ let cwd = scope;
158
+ if (this.expectedScopeIdentity !== undefined) {
159
+ if (scope !== resolve(this.scope))
160
+ throw new Error("Scope redirected since selection");
161
+ scopeFd = openSync(scope, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
162
+ const pinned = fstatSync(scopeFd, { bigint: true });
163
+ cwd = `/proc/${process.pid}/fd/${scopeFd}`;
164
+ const bound = statSync(cwd, { bigint: true });
165
+ if (`${pinned.dev}:${pinned.ino}` !== this.expectedScopeIdentity || !pinned.isDirectory()
166
+ || bound.dev !== pinned.dev || bound.ino !== pinned.ino) {
167
+ throw new Error("Scope changed since selection");
168
+ }
169
+ }
143
170
  transport = new SupervisedStdioTransport({
144
171
  command: connection.command,
145
172
  args: connection.args,
146
173
  env: getDefaultEnvironment(),
147
- cwd: scope,
174
+ cwd,
148
175
  });
149
176
  }
150
177
  else if (connection.transport === "stdio") {
151
178
  isolation = await prepareFilesystemIsolation({
152
179
  scope: this.scope, expectedScope: resolve(this.scope),
180
+ ...(this.expectedScopeIdentity !== undefined ? { expectedScopeIdentity: this.expectedScopeIdentity } : {}),
153
181
  command: connection.command.includes("/") ? resolve(this.scope, connection.command) : connection.command,
154
182
  args: connection.args,
155
183
  readablePaths: executionAssets(connection, this.scope),
@@ -174,8 +202,6 @@ export class McpSession {
174
202
  env: isolation.env,
175
203
  cwd: isolation.scope,
176
204
  });
177
- const prepared = isolation;
178
- void transport.exited.then(() => prepared.cleanup());
179
205
  }
180
206
  else {
181
207
  // HTTP MCP deliberately retains its external/network authority.
@@ -200,6 +226,12 @@ export class McpSession {
200
226
  },
201
227
  });
202
228
  }
229
+ if (transport instanceof SupervisedStdioTransport) {
230
+ const exited = transport.exited;
231
+ void exited.then(cleanup);
232
+ this.exits.add(exited);
233
+ void exited.then(() => this.exits.delete(exited));
234
+ }
203
235
  if (this.disposed) {
204
236
  await stop();
205
237
  return;
@@ -272,14 +304,22 @@ export class McpSession {
272
304
  await stop();
273
305
  this.entries.delete(id);
274
306
  this.states.set(id, { id, state: "failed", tools: 0 });
307
+ if (connection.transport === "stdio" && this.expectedScopeIdentity !== undefined) {
308
+ throw new Error(process.platform !== "linux"
309
+ ? "Descriptor-bound MCP authoring requires Linux; launch refused."
310
+ : "MCP authoring launch failed. Refresh the selected Scope and Retry.");
311
+ }
275
312
  }
276
313
  }
277
- async dispose() {
314
+ /** Ordinary callers retain bounded stdio close; authoring owns capacity until actual exit. */
315
+ async dispose({ waitForExit = false } = {}) {
278
316
  this.disposed = true;
279
317
  this.entries.clear();
280
318
  await Promise.all([...this.stops.values()].map((stop) => stop()));
281
319
  await Promise.allSettled(this.pending.values());
282
320
  // A connect may have been waiting for the previous connection's teardown.
283
321
  await Promise.all([...this.stops.values()].map((stop) => stop()));
322
+ if (waitForExit)
323
+ await Promise.all(this.exits);
284
324
  }
285
325
  }
@@ -1,4 +1,5 @@
1
1
  import { workflowParentTools } from "./workflow-parent.js";
2
+ import { piWorkflowBuilderTools } from "./workflow-builder.js";
2
3
  import { piMcpTools } from "./mcp.js";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
@@ -20,6 +21,7 @@ export class PiSession {
20
21
  completions = [];
21
22
  workflows = new Map();
22
23
  mcp;
24
+ workflowBuilder;
23
25
  recreate;
24
26
  async refreshMcp() {
25
27
  if (!this.recreate)
@@ -58,6 +60,7 @@ export class PiSession {
58
60
  messageSeq = 0;
59
61
  currentMessageId;
60
62
  constructor(session, emit, sessionDir, support = {}) {
63
+ this.workflowBuilder = support.workflowBuilder ?? false;
61
64
  this.mcp = support.mcp;
62
65
  this.recreate = support.recreate;
63
66
  this.standingAuthorisations = [...(support.standingAuthorisations ?? [])];
@@ -78,12 +81,14 @@ export class PiSession {
78
81
  this.answerPermission = async (callId, decision) => this.agentPermissions.answer(callId, decision);
79
82
  if (enquiries)
80
83
  this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
81
- this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false);
84
+ this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false, !this.workflowBuilder);
82
85
  this.unsubscribe = session.subscribe((event) => this.translate(event));
83
86
  }
84
87
  startWorkflowSubagent(options) {
85
88
  if (this.disposed)
86
89
  throw new Error("Backend Session stopped");
90
+ if (this.workflowBuilder)
91
+ throw new Error("Workflow builder cannot create Subagents");
87
92
  if (this.workflows.has(options.id))
88
93
  throw new Error(`Duplicate workflow Subagent: ${options.id}`);
89
94
  const handle = new PiWorkflowSubagent(this.session, options, this.standingAuthorisations, this.mcp, this.workflowAutoCompaction, this.workflowCompactionModelId);
@@ -124,7 +129,7 @@ export class PiSession {
124
129
  this.applyAutoCompaction?.(this.session.model);
125
130
  // Which levels are on offer follows the model, and pi may have clamped its own thinking level
126
131
  // on the way through, so both the list and the level in force are re-read here.
127
- this.capabilities = capabilitiesOf(this.session, this.enquiries !== undefined, this.capabilities.subagents);
132
+ this.capabilities = capabilitiesOf(this.session, this.enquiries !== undefined, this.capabilities.subagents, !this.workflowBuilder);
128
133
  // Publish the new list first. A client that receives the model first would briefly classify its
129
134
  // Effort support as unknown (or, worse, reuse the old model's list).
130
135
  this.emit({ type: "capabilities_changed", capabilities: this.capabilities });
@@ -411,17 +416,25 @@ export class PiBackend {
411
416
  const agentDir = getAgentDir();
412
417
  // Extensions are not loaded: they expect pi's own UI surface, and a background session that
413
418
  // registers UI hooks has nowhere to render them.
414
- const settingsManager = SettingsManager.create(options.scope, agentDir);
415
- const agentPermissions = options.tools === "none" ? undefined : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
419
+ const builder = options.workflowBuilder;
420
+ const settingsManager = builder ? SettingsManager.inMemory() : SettingsManager.create(options.scope, agentDir);
421
+ const agentPermissions = builder || options.tools === "none" ? undefined : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
416
422
  const resourceLoader = new DefaultResourceLoader({
417
423
  cwd: options.scope,
418
424
  agentDir,
419
425
  settingsManager,
420
426
  noExtensions: true,
421
- extensionFactories: [
422
- ...(agentPermissions ? [agentPermissions.extension()] : []),
423
- ...(options.compactionModelId ? [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] : []),
424
- ],
427
+ ...(builder ? {
428
+ noSkills: true, noPromptTemplates: true, noThemes: true,
429
+ agentsFilesOverride: () => ({ agentsFiles: [] }),
430
+ appendSystemPromptOverride: () => [],
431
+ systemPromptOverride: () => builder.instructions,
432
+ } : {
433
+ extensionFactories: [
434
+ ...(agentPermissions ? [agentPermissions.extension()] : []),
435
+ ...(options.compactionModelId ? [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] : []),
436
+ ],
437
+ }),
425
438
  });
426
439
  await resourceLoader.reload();
427
440
  // Reviving reopens the most recent pi session in the directory we gave this Agent Session;
@@ -433,17 +446,18 @@ export class PiBackend {
433
446
  : SessionManager.create(options.scope, sessionDir)
434
447
  : undefined;
435
448
  const defaults = settingsManager.getDefaultTools() ?? ["read", "bash", "edit", "write"];
436
- const tools = options.tools === "none" ? [] : [...(this.options.tools ?? [
449
+ const builderTools = builder ? piWorkflowBuilderTools(builder) : [];
450
+ const tools = builder ? builderTools.map(tool => tool.name) : options.tools === "none" ? [] : [...(this.options.tools ?? [
437
451
  ...defaults, ASK_TOOL, SUBAGENT_TOOL, ...(defaults.includes("bash") ? ["bash_output", "kill_shell"] : []),
438
452
  ])];
439
- const mcp = options.tools === "none" ? undefined : options.mcp;
440
- const workflowTools = workflowParentTools(options.tools === "none" ? undefined : options.workflow);
453
+ const mcp = builder || options.tools === "none" ? undefined : options.mcp;
454
+ const workflowTools = workflowParentTools(builder || options.tools === "none" ? undefined : options.workflow);
441
455
  tools.push(...workflowTools.map(tool => tool.name));
442
456
  const enabled = (name) => tools.includes(name);
443
457
  const enquiries = enabled(ASK_TOOL) ? new PiEnquiries(options.emit) : undefined;
444
458
  const work = new PiWork(options.emit, (completion) => piSession.completed(completion));
445
459
  const subagents = enabled(SUBAGENT_TOOL);
446
- const customTools = [
460
+ const customTools = builder ? builderTools : [
447
461
  ...workflowTools,
448
462
  ...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
449
463
  ...(enquiries ? [enquiries.tool] : []),
@@ -460,7 +474,7 @@ export class PiBackend {
460
474
  tools: [...tools, ...mcpTools.map((tool) => tool.name)],
461
475
  ...(current ? { sessionManager: current.sessionManager, modelRuntime: current.modelRuntime, thinkingLevel: current.thinkingLevel, ...(current.model ? { model: current.model } : {}) }
462
476
  : sessionManager ? { sessionManager } : {}),
463
- ...(tools.length === 0 ? { noTools: "all" } : {}),
477
+ ...(builder ? { noTools: "builtin" } : tools.length === 0 ? { noTools: "all" } : {}),
464
478
  });
465
479
  };
466
480
  let { session, extensionsResult } = await start();
@@ -470,7 +484,7 @@ export class PiBackend {
470
484
  throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
471
485
  }
472
486
  const autoCompaction = structuredClone(options.autoCompaction);
473
- const piSession = new PiSession(session, options.emit, sessionDir, { ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
487
+ const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
474
488
  if (options.modelId) {
475
489
  try {
476
490
  await piSession.setModel(options.modelId);
@@ -584,7 +598,7 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
584
598
  await work.stopOwnedCalls(id);
585
599
  }
586
600
  }
587
- function capabilitiesOf(session, enquiries, subagents) {
601
+ function capabilitiesOf(session, enquiries, subagents, permissions = true) {
588
602
  // The SDK populates this auth-filtered snapshot before createAgentSession resolves. Every model is
589
603
  // described directly: effort discovery is observational and must never switch the active model.
590
604
  const models = session.modelRuntime.getAvailableSnapshot().map(describeModel);
@@ -597,7 +611,7 @@ function capabilitiesOf(session, enquiries, subagents) {
597
611
  fork: false,
598
612
  subagents,
599
613
  enquiries,
600
- permissions: true,
614
+ permissions,
601
615
  };
602
616
  }
603
617
  export function describeModel(model) {
@@ -0,0 +1,11 @@
1
+ import { Type } from "typebox";
2
+ import { workflowBuilderTools } from "../workflow-builder.js";
3
+ export function piWorkflowBuilderTools(builder) {
4
+ return workflowBuilderTools.map(({ name, label, field, method, description }) => ({
5
+ name, label, description,
6
+ parameters: Type.Object({ [field]: Type.String() }),
7
+ execute: async (_id, input) => ({
8
+ content: [{ type: "text", text: await builder[method](input[field]) }], details: {},
9
+ }),
10
+ }));
11
+ }
@@ -43,7 +43,13 @@ export function runWorker() {
43
43
  if (creating || closing)
44
44
  throw new Error("Backend worker already initialized");
45
45
  creating = true;
46
- const { mcpTools, workflowEnabled, backendModule, backend: backendName = "pi", ...options } = args[0];
46
+ const { mcpTools, workflowEnabled, workflowBuilderInstructions, backendModule, backend: backendName = "pi", ...options } = args[0];
47
+ const workflowBuilder = workflowBuilderInstructions === undefined ? undefined : {
48
+ instructions: workflowBuilderInstructions,
49
+ read: (path) => rpc.call("workflowBuilder.read", [path]),
50
+ list: (path) => rpc.call("workflowBuilder.list", [path]),
51
+ write: (content) => rpc.call("workflowBuilder.write", [content]),
52
+ };
47
53
  updateTools(mcpTools ?? []);
48
54
  const workflow = {
49
55
  inspect: (input) => rpc.call("workflow.inspect", [input]),
@@ -65,8 +71,10 @@ export function runWorker() {
65
71
  }
66
72
  session = await backend.create({
67
73
  ...options,
68
- ...(mcpTools ? { mcp: { tools: () => tools } } : {}),
69
- ...(workflowEnabled ? { workflow } : {}),
74
+ ...(workflowBuilder ? { workflowBuilder } : {
75
+ ...(mcpTools ? { mcp: { tools: () => tools } } : {}),
76
+ ...(workflowEnabled ? { workflow } : {}),
77
+ }),
70
78
  emit: (event) => {
71
79
  // Models can be a large catalogue. Do not resend it for every text/tool delta, but do
72
80
  // mirror any changed state before the event that exposes it to the Session Host.
@@ -17,6 +17,7 @@ export class WorkerBackend {
17
17
  options;
18
18
  constructor(options = {}) { this.options = options; this.name = options.backend ?? "pi"; }
19
19
  async create(options) {
20
+ options.signal?.throwIfAborted();
20
21
  const isolationEnabled = this.options.isolationEnabled?.() ?? true;
21
22
  if (!isolationEnabled) {
22
23
  const scope = realpathSync(options.scope);
@@ -28,7 +29,7 @@ export class WorkerBackend {
28
29
  let proxy;
29
30
  try {
30
31
  proxy = new WorkerSession({ ...options, scope }, claude ? { ...this.options, env: claude.env } : this.options, claude?.cleanup ?? (() => { }));
31
- await proxy.open();
32
+ await proxy.open(options.signal);
32
33
  return proxy;
33
34
  }
34
35
  catch (error) {
@@ -60,10 +61,11 @@ export class WorkerBackend {
60
61
  env: this.options.env ?? {}, credentials: this.name, ipc: true, readablePaths: assets });
61
62
  let proxy;
62
63
  try {
64
+ options.signal?.throwIfAborted();
63
65
  if (this.name === "claude")
64
66
  migrateLegacyClaudeState(options.stateDir, { ...process.env, ...this.options.env }, isolation.scope, options.resume);
65
67
  proxy = new WorkerSession({ ...options, scope: isolation.scope, stateDir: isolation.stateDir }, { ...this.options, command: isolation.command, args: isolation.args, env: isolation.env, stdioFds: isolation.stdioFds }, isolation.cleanup);
66
- await proxy.open();
68
+ await proxy.open(options.signal);
67
69
  return proxy;
68
70
  }
69
71
  catch (error) {
@@ -108,8 +110,15 @@ class WorkerSession {
108
110
  }, async (method, args, signal) => {
109
111
  if (this.disposing || this.failed)
110
112
  throw new Error("Backend Session stopped");
113
+ // Builders never inherit other host capabilities, even if the worker asks directly.
114
+ if (this.options.workflowBuilder && !["workflowBuilder.read", "workflowBuilder.list", "workflowBuilder.write"].includes(method)) {
115
+ throw new Error("Host capability is not enabled for workflow builder");
116
+ }
111
117
  // Never look up host functions by a worker-supplied property name.
112
118
  switch (method) {
119
+ case "workflowBuilder.read": return this.requireWorkflowBuilder(args[0]).read(args[0]);
120
+ case "workflowBuilder.list": return this.requireWorkflowBuilder(args[0]).list(args[0]);
121
+ case "workflowBuilder.write": return this.requireWorkflowBuilder(args[0]).write(args[0]);
113
122
  case "mcp.call": {
114
123
  const tool = this.options.mcp?.tools().find((tool) => tool.name === args[0]);
115
124
  if (!tool)
@@ -134,24 +143,37 @@ class WorkerSession {
134
143
  child.once("disconnect", () => this.fail(new Error("Backend worker disconnected")));
135
144
  child.once("exit", (code, signal) => this.fail(new Error(`Backend worker exited (${signal ?? code ?? "unknown"})${this.worker.diagnostics() ? `: ${this.worker.diagnostics()}` : ""}`)));
136
145
  }
146
+ requireWorkflowBuilder(input) {
147
+ if (!this.options.workflowBuilder)
148
+ throw new Error("Workflow builder tools are not enabled");
149
+ if (typeof input !== "string")
150
+ throw new Error("Invalid workflow builder input: expected a string");
151
+ return this.options.workflowBuilder;
152
+ }
137
153
  requireWorkflow() {
138
154
  if (!this.options.workflow)
139
155
  throw new Error("Workflow tools are not enabled");
140
156
  return this.options.workflow;
141
157
  }
142
- async open() {
143
- const { emit: _emit, onFailure: _onFailure, mcp, workflow, ...options } = this.options;
158
+ async open(signal) {
159
+ const { emit: _emit, onFailure: _onFailure, signal: _signal, mcp, workflow, workflowBuilder, ...options } = this.options;
144
160
  const controller = new AbortController();
161
+ const cancel = () => controller.abort(signal?.reason);
162
+ if (signal?.aborted)
163
+ cancel();
164
+ else
165
+ signal?.addEventListener('abort', cancel, { once: true });
145
166
  const timer = setTimeout(() => controller.abort(), this.launchOptions.startupTimeoutMs ?? 60_000);
146
167
  try {
147
168
  const state = await this.rpc.call("create", [{ ...options, backend: this.launchOptions.backend ?? "pi",
148
- workflowEnabled: !!workflow,
149
- ...(mcp ? { mcpTools: mcpMetadata(mcp) } : {}),
169
+ workflowEnabled: !workflowBuilder && !!workflow,
170
+ ...(workflowBuilder ? { workflowBuilderInstructions: workflowBuilder.instructions }
171
+ : mcp ? { mcpTools: mcpMetadata(mcp) } : {}),
150
172
  ...(this.launchOptions.backendModule ? { backendModule: this.launchOptions.backendModule } : {}),
151
173
  }], controller.signal);
152
174
  this.updateSnapshot(state);
153
175
  const methods = new Set(state.methods);
154
- if (methods.has("refreshMcp"))
176
+ if (!workflowBuilder && methods.has("refreshMcp"))
155
177
  this.refreshMcp = () => this.rpc.call("refreshMcp", [mcpMetadata(this.options.mcp)]);
156
178
  if (methods.has("compact"))
157
179
  this.compact = (instructions) => this.rpc.call("compact", [instructions]);
@@ -163,11 +185,12 @@ class WorkerSession {
163
185
  this.answerPermission = (id, decision) => this.rpc.call("answerPermission", [id, decision]);
164
186
  if (methods.has("setPermissionMode"))
165
187
  this.setPermissionMode = (mode) => this.rpc.call("setPermissionMode", [mode]);
166
- if (methods.has("startWorkflowSubagent"))
188
+ if (!workflowBuilder && methods.has("startWorkflowSubagent"))
167
189
  this.startWorkflowSubagent = (options) => this.startWorkflow(options);
168
190
  }
169
191
  finally {
170
192
  clearTimeout(timer);
193
+ signal?.removeEventListener('abort', cancel);
171
194
  }
172
195
  }
173
196
  updateSnapshot(state) {
@@ -13,6 +13,7 @@ export function launchWorker(options = {}) {
13
13
  const { command, args } = workerCommand(options);
14
14
  const child = spawn(command, args, {
15
15
  env: { ...process.env, ...options.env, FLOW_BACKEND_WORKER: "1" },
16
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
16
17
  detached: process.platform !== "win32",
17
18
  stdio: ["ignore", "ignore", "pipe", "ipc", ...(options.stdioFds ?? [])],
18
19
  serialization: "advanced",
@@ -0,0 +1,8 @@
1
+ export const workflowBuilderTools = [
2
+ { name: "workflow_builder_read", label: "Read workflow reference", field: "path", method: "read",
3
+ description: "Read a reference at a host-approved path. This is not an arbitrary filesystem reader." },
4
+ { name: "workflow_builder_list", label: "List workflow references", field: "path", method: "list",
5
+ description: "List references at a host-approved path. This is not an arbitrary directory listing." },
6
+ { name: "workflow_builder_write", label: "Save workflow definition", field: "content", method: "write",
7
+ description: "Validate and save Workflow Definition content through the host. The host chooses the destination; no file path is accepted." },
8
+ ];
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- e1e3aecb-f4c5-4999-b30d-e82ca6809759
1
+ dd94e5bf-c6e7-43c8-9b45-5cd67ff6c921
@@ -883,7 +883,7 @@ async function bootstrap() {
883
883
  if (!managed) throw new Error("Missing systemd update configuration");
884
884
  await assertSystemdOwner(managed, managed.updater, process.pid);
885
885
  }
886
- const lease = await install.register("e1e3aecb-f4c5-4999-b30d-e82ca6809759", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
886
+ const lease = await install.register("dd94e5bf-c6e7-43c8-9b45-5cd67ff6c921", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
887
887
  delete process.env.FLOW_UPDATE_CAPABILITY;
888
888
  process.on("exit", lease.release);
889
889
  if (args[0] === "update") {
package/dist/cli/main.js CHANGED
@@ -1,6 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { isSea } from 'node:sea';
3
- if (process.argv[2] === '--flow-isolation-launch' ||
3
+ if (process.argv[2] === '--flow-workflow-authoring-scope-reader' && process.send && process.env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER === '1') {
4
+ void import("../daemon/workflow-authoring-scope-reader.js").then(({ runWorkflowAuthoringScopeReader }) => runWorkflowAuthoringScopeReader()).catch(() => {
5
+ process.exitCode = 1;
6
+ process.disconnect?.();
7
+ });
8
+ }
9
+ else if (process.argv[2] === '--flow-workflow-builder-reader' && process.send && process.env.FLOW_WORKFLOW_BUILDER_READER === '1') {
10
+ void import("../daemon/workflow-builder-reader.js").then(({ runWorkflowBuilderReader }) => runWorkflowBuilderReader()).catch(() => {
11
+ process.exitCode = 1;
12
+ process.disconnect?.();
13
+ });
14
+ }
15
+ else if (process.argv[2] === '--flow-isolation-launch' ||
4
16
  (process.argv[2] === '--flow-backend-worker' && process.send && process.env.FLOW_BACKEND_WORKER === '1')) {
5
17
  void import("../backend/worker/entry.js").catch(error => {
6
18
  console.error(error instanceof Error ? error.message : error);
@@ -1964,6 +1964,14 @@ export class SessionHost {
1964
1964
  const scope = this.workflowSession(id).scope;
1965
1965
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationEnabled);
1966
1966
  }
1967
+ /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
1968
+ async openWorkflowMcpAuthoring(scope, connectionId, isolationEnabled = this.filesystemIsolationEnabled(), expectedScopeIdentity) {
1969
+ const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
1970
+ if (!connection)
1971
+ throw new Error('MCP connection removed. Refresh the workflow editor.');
1972
+ const { McpSession } = await import("../backend/mcp.js");
1973
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationEnabled, expectedScopeIdentity);
1974
+ }
1967
1975
  mcpStatus(id) {
1968
1976
  const record = this.sessions.get(id);
1969
1977
  if (!record)
@@ -2587,6 +2595,12 @@ export class SessionHost {
2587
2595
  ...(store ? { sink: (entry) => store.append(entry) } : {}),
2588
2596
  });
2589
2597
  }
2598
+ /** Independent, host-mediated authoring; never inherits Agent Session tools or MCP. */
2599
+ createWorkflowBuilderSession(backend, options) {
2600
+ if (!options.workflowBuilder)
2601
+ throw new Error('Workflow builder capabilities are required');
2602
+ return this.backendFor(backend).create(options);
2603
+ }
2590
2604
  backendFor(name) {
2591
2605
  const backend = this.backends.get(name);
2592
2606
  if (!backend)