@nathanstephenson/flow 0.1.4 → 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 (50) hide show
  1. package/dist/backend/claude/index.js +30 -8
  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/claude-state.js +131 -9
  7. package/dist/backend/worker/entry.js +11 -3
  8. package/dist/backend/worker/index.js +35 -10
  9. package/dist/backend/worker/launcher.js +1 -0
  10. package/dist/backend/workflow-builder.js +8 -0
  11. package/dist/build-id +1 -1
  12. package/dist/cli/bootstrap.js +1 -1
  13. package/dist/cli/main.js +13 -1
  14. package/dist/daemon/host.js +14 -0
  15. package/dist/daemon/mcp-auth.js +32 -4
  16. package/dist/daemon/runtime.js +13 -3
  17. package/dist/daemon/server.js +34 -0
  18. package/dist/daemon/workflow-authoring-scope-checks.js +134 -0
  19. package/dist/daemon/workflow-authoring-scope-reader.js +42 -0
  20. package/dist/daemon/workflow-authoring-scope.js +49 -0
  21. package/dist/daemon/workflow-builder-files.js +321 -0
  22. package/dist/daemon/workflow-builder-guidance.js +31 -0
  23. package/dist/daemon/workflow-builder-reader.js +131 -0
  24. package/dist/daemon/workflow-builder-routes.js +61 -0
  25. package/dist/daemon/workflow-builder.js +480 -0
  26. package/dist/daemon/workflow-mcp-authoring-routes.js +44 -0
  27. package/dist/daemon/workflow-mcp-authoring.js +313 -0
  28. package/dist/isolation/filesystem.js +7 -4
  29. package/dist/protocol/workflow-builder.js +1 -0
  30. package/dist/protocol/workflow-mcp-authoring.js +1 -0
  31. package/package.json +1 -1
  32. package/web/dist/assets/index-C_M0oDHN.js +38 -0
  33. package/web/dist/assets/index-D8CGXp1X.css +2 -0
  34. package/web/dist/assets/{input-NIrLDFaS.js → input-D9fbSfQF.js} +1 -1
  35. package/web/dist/assets/settings-mcp-BvSvGrcs.js +1 -0
  36. package/web/dist/assets/{settings-secrets-BtQwc-w4.js → settings-secrets-DlkU6W_Z.js} +1 -1
  37. package/web/dist/assets/settings-workflows-DNGE-b_U.js +23 -0
  38. package/web/dist/assets/switch-DEvHojwW.js +1 -0
  39. package/web/dist/assets/workflow-editors-D6XT6pcb.js +137 -0
  40. package/web/dist/assets/{workflows-9aO6cptD.css → workflows-Bb90N0XJ.css} +1 -1
  41. package/web/dist/assets/workflows-LSCnXIxN.js +7 -0
  42. package/web/dist/assets/workflows-pane-BIlp7uyg.js +1 -0
  43. package/web/dist/index.html +5 -4
  44. package/web/dist/assets/index-Bn-ECZ7w.js +0 -174
  45. package/web/dist/assets/index-DL0CGVaN.css +0 -2
  46. package/web/dist/assets/settings-mcp-B60T2XUv.js +0 -1
  47. package/web/dist/assets/settings-workflows-BZ4W0Ja8.js +0 -23
  48. package/web/dist/assets/switch-DyYU6B5T.js +0 -1
  49. package/web/dist/assets/workflows-BAdf2yKH.js +0 -7
  50. package/web/dist/assets/workflows-pane-MSSNIrgu.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))
@@ -313,7 +328,7 @@ class ClaudeSession {
313
328
  }
314
329
  catch (error) {
315
330
  this.emit({ type: "notice", level: "warn", text: `Could not list models: ${message(error)}` });
316
- return;
331
+ throw new Error(`Claude model capabilities are unavailable: ${message(error)}`, { cause: error });
317
332
  }
318
333
  if (this.disposed)
319
334
  return;
@@ -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,
@@ -1022,7 +1044,7 @@ export class ClaudeBackend {
1022
1044
  // Do not await the init message: streaming input yields none until the first prompt. The
1023
1045
  // supportedModels control request does answer before that prompt, however. Returning while it
1024
1046
  // is still in flight lets the first send race the empty provisional capabilities.
1025
- const claudeState = prepareClaudeState(options.stateDir, process.env, options.scope);
1047
+ const claudeState = prepareClaudeState(options.stateDir, process.env, options.scope, options.resume);
1026
1048
  let session;
1027
1049
  try {
1028
1050
  session = new ClaudeSession(options, this.options, claudeState);
@@ -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
+ }
@@ -1,6 +1,133 @@
1
- import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, copyFileSync, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
2
3
  import { homedir, tmpdir } from "node:os";
3
4
  import { join, resolve } from "node:path";
5
+ function ownedProjects(stateDir) {
6
+ const projects = join(realpathSync(stateDir), "claude-projects");
7
+ if (!existsSync(projects))
8
+ mkdirSync(projects, { mode: 0o700 });
9
+ if (!lstatSync(projects).isDirectory() || realpathSync(projects) !== projects) {
10
+ throw new Error("Unsafe Claude backend transcript directory");
11
+ }
12
+ return projects;
13
+ }
14
+ /** Claude's Scope key, including the CLI's suffix for paths longer than 200 characters. */
15
+ function projectKey(scope) {
16
+ const key = scope.replace(/[^a-zA-Z0-9]/g, "-");
17
+ if (key.length <= 200)
18
+ return key;
19
+ let hash = 0;
20
+ for (let i = 0; i < scope.length; i++)
21
+ hash = ((hash << 5) - hash + scope.charCodeAt(i)) | 0;
22
+ return `${key.slice(0, 200)}-${Math.abs(hash).toString(36)}`;
23
+ }
24
+ /** Copy only regular, unlinked records; never follow a link into other host state. */
25
+ function copyRecord(source, destination, from = source) {
26
+ const before = lstatSync(from);
27
+ if (realpathSync(source) !== source || (!before.isDirectory() && (!before.isFile() || before.nlink !== 1))) {
28
+ throw new Error("Unsafe legacy Claude conversation record");
29
+ }
30
+ const fd = openSync(from, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
31
+ try {
32
+ const pinned = fstatSync(fd);
33
+ const descriptor = process.platform === "linux" ? `/proc/self/fd/${fd}` : source;
34
+ if (pinned.dev !== before.dev || pinned.ino !== before.ino || realpathSync(descriptor) !== source) {
35
+ throw new Error("Legacy Claude conversation record changed during migration");
36
+ }
37
+ const hash = createHash("sha256");
38
+ if (before.isDirectory()) {
39
+ mkdirSync(destination, { mode: 0o700 });
40
+ hash.update("directory\0");
41
+ // Linux copies through pinned directories, never through mutable ancestors. Elsewhere,
42
+ // no-follow opens and a post-copy identity check refuse a changed tree before publication.
43
+ for (const name of readdirSync(descriptor).sort()) {
44
+ hash.update(JSON.stringify([name, copyRecord(join(source, name), join(destination, name), join(descriptor, name))]));
45
+ }
46
+ }
47
+ else {
48
+ const content = readFileSync(fd);
49
+ writeFileSync(destination, content, { mode: 0o600, flag: "wx" });
50
+ hash.update("file\0").update(content);
51
+ }
52
+ const after = lstatSync(source);
53
+ if (after.dev !== pinned.dev || after.ino !== pinned.ino || realpathSync(source) !== source) {
54
+ throw new Error("Legacy Claude conversation record changed during migration");
55
+ }
56
+ return hash.digest("hex");
57
+ }
58
+ finally {
59
+ closeSync(fd);
60
+ }
61
+ }
62
+ /**
63
+ * Pre-isolation Claude wrote Conversation Context into the global projects tree. On Revive,
64
+ * import only the saved UUID under this Scope, plus its UUID-owned sidecars (Subagents and tool
65
+ * results). Never import another conversation, credentials, or overwrite a newer owned record.
66
+ * This runs on the host before restricted launch: workers must not gain access to global state.
67
+ */
68
+ export function migrateLegacyClaudeState(stateDir, inherited, scope, resume) {
69
+ if (!stateDir || !resume)
70
+ return;
71
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(resume)) {
72
+ throw new Error("Invalid Claude resume ID");
73
+ }
74
+ const projects = ownedProjects(stateDir);
75
+ const key = projectKey(scope);
76
+ const destination = join(projects, key);
77
+ const record = `${resume}.jsonl`;
78
+ if (existsSync(destination) && (!lstatSync(destination).isDirectory() || realpathSync(destination) !== destination)) {
79
+ throw new Error("Unsafe Claude backend project directory");
80
+ }
81
+ // Do not consult global storage at all once the owned copy exists.
82
+ const owned = join(destination, record);
83
+ if (existsSync(owned)) {
84
+ if (!lstatSync(owned).isFile() || realpathSync(owned) !== owned)
85
+ throw new Error("Unsafe Claude backend conversation record");
86
+ return;
87
+ }
88
+ const config = resolve(scope, inherited.CLAUDE_CONFIG_DIR || join(inherited.HOME ?? homedir(), ".claude"));
89
+ if (!existsSync(config))
90
+ return;
91
+ const source = join(realpathSync(config), "projects", key);
92
+ if (!existsSync(join(source, record)))
93
+ return;
94
+ if (realpathSync(source) !== source)
95
+ throw new Error("Unsafe legacy Claude project directory");
96
+ const staged = mkdtempSync(join(projects, ".migrate-"));
97
+ let movedSidecars = false;
98
+ try {
99
+ copyRecord(join(source, record), join(staged, record));
100
+ const sidecars = existsSync(join(source, resume)) ? copyRecord(join(source, resume), join(staged, resume)) : undefined;
101
+ if (!existsSync(destination)) {
102
+ // The ordinary legacy case publishes the transcript and all sidecars together.
103
+ renameSync(staged, destination);
104
+ return;
105
+ }
106
+ if (sidecars !== undefined) {
107
+ if (existsSync(join(destination, resume))) {
108
+ // A restart between sidecar publication and the atomic main-record link is retryable.
109
+ // Reuse only an exact match; never discard or overwrite potentially newer owned state.
110
+ if (copyRecord(join(destination, resume), join(staged, ".existing-sidecars")) !== sidecars) {
111
+ throw new Error("Claude conversation sidecars differ from the legacy record without their transcript");
112
+ }
113
+ }
114
+ else {
115
+ renameSync(join(staged, resume), join(destination, resume));
116
+ movedSidecars = true;
117
+ }
118
+ }
119
+ // Publish a complete main record last, atomically and without replacing an existing one.
120
+ linkSync(join(staged, record), join(destination, record));
121
+ }
122
+ catch (error) {
123
+ if (movedSidecars)
124
+ rmSync(join(destination, resume), { recursive: true, force: true });
125
+ throw error;
126
+ }
127
+ finally {
128
+ rmSync(staged, { recursive: true, force: true });
129
+ }
130
+ }
4
131
  /**
5
132
  * Keep projects durable in the Backend Session's state. CLAUDE_SECURESTORAGE_CONFIG_DIR
6
133
  * separates Claude's auth root (credential storage AND refresh/write locks) from its config /
@@ -8,16 +135,11 @@ import { join, resolve } from "node:path";
8
135
  * restricted launches already bind projects into a narrowly staged config root and must NEVER
9
136
  * receive the host auth override.
10
137
  */
11
- export function prepareClaudeState(stateDir, inherited = process.env, scope = process.cwd()) {
138
+ export function prepareClaudeState(stateDir, inherited = process.env, scope = process.cwd(), resume) {
12
139
  if (!stateDir)
13
140
  return { env: inherited, cleanup() { } };
14
- const backend = realpathSync(stateDir);
15
- const projects = join(backend, "claude-projects");
16
- if (!existsSync(projects))
17
- mkdirSync(projects, { mode: 0o700 });
18
- if (!lstatSync(projects).isDirectory() || realpathSync(projects) !== projects) {
19
- throw new Error("Unsafe Claude backend transcript directory");
20
- }
141
+ migrateLegacyClaudeState(stateDir, inherited, scope, resume);
142
+ const projects = ownedProjects(stateDir);
21
143
  const home = inherited.HOME ?? homedir();
22
144
  // Match the CLI: relative config roots are Scope-relative, and literal ~ is not
23
145
  // expanded. Restricted callers reject nonabsolute host roots before reaching here.
@@ -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.