@nathanstephenson/flow 0.1.0

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 (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,190 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
4
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
+ export class McpSession {
6
+ clients = new Map();
7
+ entries = new Map();
8
+ states = new Map();
9
+ pending = new Map();
10
+ activeCalls = new Map();
11
+ disposed = false;
12
+ direct;
13
+ connections;
14
+ scope;
15
+ auth;
16
+ resolveSecret;
17
+ constructor(connections, scope, auth, direct = false, resolveSecret) {
18
+ this.connections = structuredClone(connections);
19
+ this.scope = scope;
20
+ this.auth = auth;
21
+ this.direct = direct;
22
+ this.resolveSecret = resolveSecret;
23
+ }
24
+ registrationFailed() {
25
+ for (const [id] of this.states)
26
+ this.states.set(id, { id, state: "failed", tools: 0 });
27
+ }
28
+ tools() {
29
+ return [...this.entries.values()].flat();
30
+ }
31
+ status() {
32
+ return [...this.states.values()].map((state) => ({ ...state }));
33
+ }
34
+ async open() {
35
+ await Promise.all(this.connections.map((connection) => this.retry(connection.id)));
36
+ }
37
+ retry(id) {
38
+ if (this.disposed)
39
+ return Promise.reject(new Error("Backend Session stopped"));
40
+ if (this.activeCalls.get(id))
41
+ return Promise.reject(new Error("MCP tools are still running"));
42
+ const pending = this.pending.get(id);
43
+ if (pending)
44
+ return pending;
45
+ const connection = this.connections.find((entry) => entry.id === id);
46
+ if (!connection)
47
+ return Promise.reject(new Error("Unknown MCP connection"));
48
+ const promise = this.connect(connection).finally(() => this.pending.delete(id));
49
+ this.pending.set(id, promise);
50
+ return promise;
51
+ }
52
+ configuredHeaders(headers) {
53
+ return Object.fromEntries(Object.entries(headers).map(([name, source]) => {
54
+ if ("value" in source)
55
+ return [name, source.value];
56
+ if (!this.resolveSecret)
57
+ throw new Error(`No secret resolver for header ${name}`);
58
+ return [name, this.resolveSecret(source.secret)];
59
+ }));
60
+ }
61
+ async connect(connection) {
62
+ const { id } = connection;
63
+ this.states.set(id, { id, state: "connecting", tools: 0 });
64
+ this.entries.delete(id);
65
+ await this.clients
66
+ .get(id)
67
+ ?.close()
68
+ .catch(() => { });
69
+ if (this.disposed)
70
+ return;
71
+ const client = new Client({ name: "Flow", version: "1.0.0" }, { capabilities: {} });
72
+ this.clients.set(id, client);
73
+ // Direct workflow sessions never initiate login or replay a POST after a 401.
74
+ const tokens = this.direct && connection.transport === 'http' && connection.oauth ? await this.auth?.(connection).tokens() : undefined;
75
+ if (this.direct && connection.transport === 'http' && connection.oauth && !tokens?.access_token) {
76
+ this.states.set(id, { id, state: 'failed', tools: 0 });
77
+ return;
78
+ }
79
+ let configured = {};
80
+ if (connection.transport === "http") {
81
+ try {
82
+ configured = this.configuredHeaders(connection.headers);
83
+ }
84
+ catch {
85
+ this.states.set(id, { id, state: "failed", tools: 0 });
86
+ return;
87
+ }
88
+ }
89
+ const transport = connection.transport === "stdio"
90
+ ? new StdioClientTransport({
91
+ command: connection.command,
92
+ args: connection.args,
93
+ cwd: this.scope,
94
+ stderr: "ignore",
95
+ })
96
+ : new StreamableHTTPClientTransport(new URL(connection.url), {
97
+ ...(connection.oauth && this.auth && !this.direct
98
+ ? { authProvider: this.auth(connection) }
99
+ : {}),
100
+ // A Headers object rather than a spread, because header names are case-insensitive: a
101
+ // configured `Authorization` must lose to the OAuth token, not travel beside it.
102
+ fetch: (input, init) => {
103
+ const headers = new Headers(configured);
104
+ new Headers(init?.headers).forEach((value, name) => headers.set(name, value));
105
+ if (tokens)
106
+ headers.set("Authorization", `Bearer ${tokens.access_token}`);
107
+ return fetch(input, {
108
+ ...init,
109
+ headers,
110
+ signal: this.direct ? init?.signal ?? null : init?.signal
111
+ ? AbortSignal.any([init.signal, AbortSignal.timeout(10_000)])
112
+ : AbortSignal.timeout(10_000),
113
+ });
114
+ },
115
+ });
116
+ const signal = AbortSignal.timeout(10_000);
117
+ try {
118
+ await client.connect(transport, { timeout: 10_000, signal });
119
+ const serverIdentity = createHash("sha256").update(JSON.stringify(client.getServerVersion() ?? null)).digest("hex");
120
+ const tools = [];
121
+ let cursor;
122
+ const seen = new Set();
123
+ do {
124
+ const result = await client.listTools(cursor ? { cursor } : {}, {
125
+ timeout: 10_000,
126
+ signal,
127
+ });
128
+ for (const definition of result.tools) {
129
+ const original = definition.name;
130
+ const local = /^[A-Za-z0-9_-]+$/.test(original) &&
131
+ original.length <= 57 - id.length &&
132
+ !/^h[0-9a-f]{16}$/.test(original)
133
+ ? original
134
+ : `h${createHash("sha256").update(original).digest("hex").slice(0, 16)}`;
135
+ const name = `mcp__${id}__${local}`;
136
+ tools.push({
137
+ name,
138
+ connectionId: id,
139
+ definition,
140
+ serverIdentity,
141
+ call: async (input, signal, timeoutMs = 60_000) => {
142
+ if (this.disposed)
143
+ throw new Error("Backend Session stopped");
144
+ this.activeCalls.set(id, (this.activeCalls.get(id) ?? 0) + 1);
145
+ try {
146
+ return (await this.clients
147
+ .get(id)
148
+ .callTool({ name: definition.name, arguments: input }, undefined, { timeout: timeoutMs, ...(signal ? { signal } : {}) }));
149
+ }
150
+ catch {
151
+ if (!signal?.aborted)
152
+ this.states.set(id, { id, state: "failed", tools: 0 });
153
+ throw new Error("MCP tool call failed. Check the connection and Retry.");
154
+ }
155
+ finally {
156
+ this.activeCalls.set(id, this.activeCalls.get(id) - 1);
157
+ }
158
+ },
159
+ });
160
+ }
161
+ cursor = result.nextCursor;
162
+ if (seen.size >= 100)
163
+ throw new Error("MCP tool list is too large");
164
+ if (cursor && seen.has(cursor))
165
+ throw new Error("Repeated MCP cursor");
166
+ if (cursor)
167
+ seen.add(cursor);
168
+ } while (cursor);
169
+ if (this.disposed) {
170
+ await client.close();
171
+ return;
172
+ }
173
+ this.entries.set(id, tools);
174
+ this.states.set(id, { id, state: "connected", tools: tools.length });
175
+ client.onclose = () => {
176
+ if (!this.disposed)
177
+ this.states.set(id, { id, state: "failed", tools: 0 });
178
+ };
179
+ }
180
+ catch {
181
+ await client.close().catch(() => { });
182
+ this.states.set(id, { id, state: "failed", tools: 0 });
183
+ }
184
+ }
185
+ async dispose() {
186
+ this.disposed = true;
187
+ await Promise.all([...this.clients.values()].map((client) => client.close().catch(() => { })));
188
+ await Promise.allSettled(this.pending.values());
189
+ }
190
+ }
@@ -0,0 +1,16 @@
1
+ export function piAutoCompaction(settings, snapshot) {
2
+ const defaults = settings.getCompactionSettings();
3
+ return (model) => {
4
+ const id = model?.provider ? `${model.provider}/${model.id}` : model?.id;
5
+ const setting = id ? snapshot[id] : undefined;
6
+ const window = model?.contextWindow;
7
+ const compaction = { ...defaults };
8
+ if (setting?.mode === "disabled")
9
+ compaction.enabled = false;
10
+ else if (setting?.mode === "enabled" && window !== undefined && Number.isFinite(window) && window > 0) {
11
+ compaction.enabled = true;
12
+ compaction.reserveTokens = Math.floor(window * (1 - setting.targetPercent / 100));
13
+ }
14
+ settings.applyOverrides({ compaction });
15
+ };
16
+ }
@@ -0,0 +1,56 @@
1
+ import { createBashToolDefinition, createLocalBashOperations, defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { callIdFor } from "./work.js";
4
+ export function backgroundTools(scope, settings, work, producer, endsWithSubagent = false, completeOutput = false) {
5
+ const shellPath = settings.getShellPath();
6
+ const commandPrefix = settings.getShellCommandPrefix();
7
+ const bash = createBashToolDefinition(scope, {
8
+ ...(shellPath ? { shellPath } : {}), ...(commandPrefix ? { commandPrefix } : {}),
9
+ });
10
+ return [
11
+ defineTool({
12
+ name: "bash", label: bash.label,
13
+ description: `${bash.description} Set run_in_background to return immediately; completion is reported automatically. Use bash_output to read progress and kill_shell to stop a Background Call.${endsWithSubagent ? " In this foreground Subagent, Background Calls stop when you return your final response." : ""}`,
14
+ promptSnippet: bash.promptSnippet ?? "Execute bash commands",
15
+ promptGuidelines: bash.promptGuidelines ?? [],
16
+ parameters: Type.Object({ ...bash.parameters.properties, run_in_background: Type.Optional(Type.Boolean()) }),
17
+ execute: async (id, input, signal, onUpdate, ctx) => {
18
+ const execute = async (id, input, signal, update, ctx) => {
19
+ if (!completeOutput)
20
+ return bash.execute(id, input, signal, update, ctx);
21
+ // Capture before the SDK preview is truncated; the host redacts/persists this result.
22
+ const chunks = [];
23
+ const operations = createLocalBashOperations(shellPath ? { shellPath } : undefined);
24
+ const full = createBashToolDefinition(scope, {
25
+ ...(commandPrefix ? { commandPrefix } : {}),
26
+ operations: { exec: (command, cwd, options) => operations.exec(command, cwd, { ...options, onData: data => { chunks.push(Buffer.from(data)); options.onData(data); } }) },
27
+ });
28
+ try {
29
+ const result = await full.execute(id, input, signal, update, ctx);
30
+ return { ...result, content: [{ type: 'text', text: Buffer.concat(chunks).toString('utf8') }], details: {} };
31
+ }
32
+ catch (error) {
33
+ update?.({ content: [{ type: 'text', text: Buffer.concat(chunks).toString('utf8') }], details: {} });
34
+ throw error;
35
+ }
36
+ };
37
+ if (!input.run_in_background)
38
+ return execute(id, input, signal, onUpdate, ctx);
39
+ const callId = callIdFor(id, producer);
40
+ return work.run({ type: "background_call", callId, tool: "bash", ...(producer ? { producer } : {}) }, (signal, update) => execute(id, input, signal, update, ctx), true, signal);
41
+ },
42
+ }),
43
+ defineTool({
44
+ name: "bash_output", label: "Background Call output",
45
+ description: "Read the current state and bounded output of a Background Call using the callId from its launch receipt.",
46
+ parameters: Type.Object({ call_id: Type.String() }),
47
+ execute: async (_id, { call_id }) => work.read(call_id, producer),
48
+ }),
49
+ defineTool({
50
+ name: "kill_shell", label: "Stop a Background Call",
51
+ description: "Stop a Background Call and its process tree using the callId from its launch receipt.",
52
+ parameters: Type.Object({ call_id: Type.String() }),
53
+ execute: async (_id, { call_id }) => work.stop(call_id, producer),
54
+ }),
55
+ ];
56
+ }
@@ -0,0 +1,63 @@
1
+ import { defineTool } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ export const ASK_TOOL = "ask_question";
4
+ const parameters = Type.Object({
5
+ questions: Type.Array(Type.Object({
6
+ header: Type.String({ minLength: 1 }),
7
+ question: Type.String({ minLength: 1 }),
8
+ multiSelect: Type.Boolean(),
9
+ options: Type.Array(Type.Object({
10
+ label: Type.String({ minLength: 1 }),
11
+ description: Type.Optional(Type.String()),
12
+ preview: Type.Optional(Type.String()),
13
+ }), { minItems: 2, maxItems: 4 }),
14
+ }), { minItems: 1, maxItems: 4 }),
15
+ });
16
+ export class PiEnquiries {
17
+ open = new Map();
18
+ emit;
19
+ constructor(emit) {
20
+ this.emit = emit;
21
+ }
22
+ tool = defineTool({
23
+ name: ASK_TOOL,
24
+ label: "Ask a question",
25
+ description: "Ask the human one to four questions and wait for their answers. They can select options or write their own answer. Do not add an Other option.",
26
+ promptSnippet: "Ask the human for a decision or missing information",
27
+ parameters,
28
+ execute: async (askId, { questions }, signal) => {
29
+ const answers = signal?.aborted ? undefined : await new Promise((resolve) => {
30
+ const abort = () => this.abandon(askId);
31
+ this.open.set(askId, { questions, resolve: (answers) => {
32
+ signal?.removeEventListener("abort", abort);
33
+ resolve(answers);
34
+ } });
35
+ signal?.addEventListener("abort", abort, { once: true });
36
+ this.emit({ type: "enquiry", askId, questions, state: "asked" });
37
+ });
38
+ return {
39
+ content: [{ type: "text", text: answers
40
+ ? JSON.stringify(questions.map((question, index) => ({ question: question.question, answers: answers[index] })))
41
+ : "The human did not answer because the turn stopped." }],
42
+ details: { answers },
43
+ };
44
+ },
45
+ });
46
+ abandon(askId) {
47
+ const pending = this.open.get(askId);
48
+ if (!pending)
49
+ return;
50
+ this.open.delete(askId);
51
+ this.emit({ type: "enquiry", askId, questions: pending.questions, state: "aborted" });
52
+ pending.resolve(undefined);
53
+ }
54
+ answer(askId, answers) {
55
+ const pending = this.open.get(askId);
56
+ if (!pending || answers.length !== pending.questions.length)
57
+ return false;
58
+ this.open.delete(askId);
59
+ this.emit({ type: "enquiry", askId, questions: pending.questions, state: "answered", answers });
60
+ pending.resolve(answers);
61
+ return true;
62
+ }
63
+ }