@blackbelt-technology/pi-dashboard-flows-plugin 0.11.0 → 0.12.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.
- package/README.md +5 -1
- package/package.json +23 -4
- package/src/bridge/flow-catalog-publisher.ts +138 -0
- package/src/bridge/flow-event-forward.ts +132 -0
- package/src/bridge/flow-files-reporter.ts +16 -14
- package/src/bridge/flow-open-tool.ts +124 -0
- package/src/bridge/flow-probe.ts +20 -0
- package/src/bridge/flow-tool-registry.ts +298 -0
- package/src/bridge/flow-tools-guideline.ts +52 -0
- package/src/bridge/index.ts +67 -10
- package/src/bridge/run-snapshot-reporter.ts +146 -0
- package/src/catalog-timings.ts +70 -0
- package/src/client/AskSession.tsx +82 -0
- package/src/client/FlowActionDialogs.tsx +143 -0
- package/src/client/FlowActivityBadge.tsx +42 -4
- package/src/client/FlowAgentCard.tsx +63 -8
- package/src/client/FlowAgentDetail.tsx +3 -5
- package/src/client/FlowDashboard.tsx +381 -273
- package/src/client/FlowEditMenu.tsx +69 -0
- package/src/client/FlowEditPopover.tsx +130 -0
- package/src/client/FlowGraph.tsx +127 -44
- package/src/client/FlowHeaderActions.tsx +83 -0
- package/src/client/FlowInputWiring.tsx +1 -1
- package/src/client/FlowOpenListener.tsx +82 -0
- package/src/client/FlowQuestionBlock.tsx +226 -0
- package/src/client/FlowStepCards.tsx +189 -0
- package/src/client/FlowSummary.tsx +72 -240
- package/src/client/FlowWriteToolRenderer.tsx +46 -17
- package/src/client/FlowYamlPopoverButton.tsx +2 -2
- package/src/client/FlowsContextGroup.tsx +156 -0
- package/src/client/FlowsSessionStateContext.tsx +202 -54
- package/src/client/FlowsSettings.tsx +145 -17
- package/src/client/SessionFlowActions.tsx +65 -10
- package/src/client/SessionFlowMenuClaim.tsx +48 -241
- package/src/client/ask-session-store.ts +243 -0
- package/src/client/flow-attach-store.ts +2 -0
- package/src/client/flow-card-grid.ts +2 -2
- package/src/client/flow-collapse-storage.ts +36 -6
- package/src/client/flow-edges.ts +91 -35
- package/src/client/flow-files.ts +16 -4
- package/src/client/flow-idle-state.ts +93 -37
- package/src/client/flowsActionsGate.ts +1 -1
- package/src/client/flowsAvailability.ts +8 -2
- package/src/client/index.tsx +13 -11
- package/src/client/shouldRender.ts +1 -1
- package/src/client/useEditModeState.ts +78 -0
- package/src/client/useFlowActions.tsx +191 -0
- package/src/client/useFlowCatalog.ts +69 -0
- package/src/client/useMinuteClock.ts +21 -0
- package/src/client/useRunReattach.ts +50 -0
- package/src/configSchema.json +37 -2
- package/src/flow-catalog-contract.ts +65 -0
- package/src/flow-questions.ts +138 -0
- package/src/flow-reducer.ts +434 -13
- package/src/flow-state-serialize.ts +132 -0
- package/src/i18n.ts +144 -6
- package/src/server/automation-actions.ts +4 -3
- package/src/server/edit-mode.ts +307 -0
- package/src/server/flow-catalog.ts +127 -0
- package/src/server/flow-control.ts +263 -0
- package/src/server/flow-files.ts +140 -14
- package/src/server/flow-open.ts +385 -0
- package/src/server/index.ts +112 -34
- package/src/server/render-actions.ts +3 -2
- package/src/server/state-store.ts +11 -5
- package/src/types.ts +180 -0
- package/src/bridge/flow-question-adapter.ts +0 -93
- package/src/client/FlowQuestionCard.tsx +0 -218
- package/src/client/FlowQuestionTranscriptPill.tsx +0 -58
- package/src/client/FlowsCommandRoutes.tsx +0 -245
- package/src/client/flow-yaml-parse.ts +0 -140
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* flows-plugin · dashboard tool-registry facade for pi-flows code nodes.
|
|
3
|
+
*
|
|
4
|
+
* pi-flows' `CodeNodeContext` carries no tool handle. Code-node handlers run in
|
|
5
|
+
* this same pi process, so the bridge publishes a narrow facade over the
|
|
6
|
+
* dashboard tool registry on `globalThis[Symbol.for("pi-dashboard.flow-tools")]`.
|
|
7
|
+
* Handlers resolve and run any registered tool by name through the same
|
|
8
|
+
* resolution the dashboard uses (overrides, managed runtimes, bundled bash).
|
|
9
|
+
*
|
|
10
|
+
* - `has` / `resolve` — by name only; no resolve-all `list()` (it would block
|
|
11
|
+
* the event loop on every probe).
|
|
12
|
+
* - `run` / `shell` — async spawn so the bridge sharing this event loop never
|
|
13
|
+
* stalls; never throw; 127 unresolved, 130 pre-aborted; timeout / abort /
|
|
14
|
+
* 64 MiB-per-stream cap kill the whole process group within 2 s.
|
|
15
|
+
* - `shell` — registry bash, `--noprofile --norc`, inherited BASH_ENV/ENV dropped.
|
|
16
|
+
*
|
|
17
|
+
* Plugin-scoped: nothing in pi-flows, dashboard core or the registry changes.
|
|
18
|
+
* See change: add-flow-code-node-tools (design D1–D4, D6).
|
|
19
|
+
*/
|
|
20
|
+
import { ToolResolver } from "@blackbelt-technology/pi-dashboard-shared/platform/binary-lookup.js";
|
|
21
|
+
import { buildSafeArgv, spawn as defaultSpawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
22
|
+
import { killProcessGroup } from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
|
|
23
|
+
import { buildSpawnEnvForArgv } from "@blackbelt-technology/pi-dashboard-shared/platform/runner.js";
|
|
24
|
+
import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
|
|
25
|
+
|
|
26
|
+
/** `Symbol.for` key of the process-global slot code-node handlers read. */
|
|
27
|
+
export const FLOW_TOOLS_SYMBOL_KEY = "pi-dashboard.flow-tools";
|
|
28
|
+
const SLOT = Symbol.for(FLOW_TOOLS_SYMBOL_KEY);
|
|
29
|
+
|
|
30
|
+
/** Fixed per-stream output cap (stdout and stderr each). */
|
|
31
|
+
export const MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
|
|
32
|
+
/** SIGTERM → SIGKILL grace, keeping termination inside the 2 s bound. */
|
|
33
|
+
const KILL_GRACE_MS = 1000;
|
|
34
|
+
/** Upper wait for stdio to close after the group is killed. */
|
|
35
|
+
const CLOSE_WAIT_MS = 500;
|
|
36
|
+
|
|
37
|
+
interface FlowToolRunOptions {
|
|
38
|
+
cwd?: string;
|
|
39
|
+
/** Merged over the dashboard spawn env (caller wins). */
|
|
40
|
+
env?: Record<string, string>;
|
|
41
|
+
/** Positive finite ms; anything else means no timeout. */
|
|
42
|
+
timeoutMs?: number;
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface FlowToolResult {
|
|
47
|
+
/** True only when the process exited 0. */
|
|
48
|
+
ok: boolean;
|
|
49
|
+
/** Exit code; 127 unresolved, 130 aborted, 124 timed out. */
|
|
50
|
+
code: number;
|
|
51
|
+
stdout: string;
|
|
52
|
+
stderr: string;
|
|
53
|
+
/** stdout followed by stderr. */
|
|
54
|
+
out: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface FlowTools {
|
|
58
|
+
has(name: string): boolean;
|
|
59
|
+
/** Absolute resolved path, or null (unregistered, unresolved, path-less, error). */
|
|
60
|
+
resolve(name: string): string | null;
|
|
61
|
+
run(name: string, args?: readonly string[], opts?: FlowToolRunOptions): Promise<FlowToolResult>;
|
|
62
|
+
shell(script: string, opts?: FlowToolRunOptions): Promise<FlowToolResult>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The registry surface the facade reads. */
|
|
66
|
+
interface RegistryLike {
|
|
67
|
+
has(name: string): boolean;
|
|
68
|
+
resolve(name: string): { ok: boolean; path: string | null };
|
|
69
|
+
resolveExecutor(name: string): { ok: boolean; argv: string[] };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface FlowToolsDeps {
|
|
73
|
+
registry?: () => RegistryLike;
|
|
74
|
+
spawn?: typeof defaultSpawn;
|
|
75
|
+
/** Platform for spawn-argv routing (win32 `.cmd` shims); default `process.platform`. */
|
|
76
|
+
platform?: NodeJS.Platform;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const fail = (code: number, message: string): FlowToolResult => ({
|
|
80
|
+
ok: false,
|
|
81
|
+
code,
|
|
82
|
+
stdout: "",
|
|
83
|
+
stderr: message,
|
|
84
|
+
out: message,
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
/** Drop a trailing incomplete UTF-8 sequence left by truncating a stream at the byte cap. */
|
|
88
|
+
function dropPartialUtf8Tail(buf: Buffer): Buffer {
|
|
89
|
+
let i = buf.length - 1;
|
|
90
|
+
let continuation = 0;
|
|
91
|
+
while (i >= 0 && continuation < 3 && (buf[i] & 0xc0) === 0x80) {
|
|
92
|
+
i--;
|
|
93
|
+
continuation++;
|
|
94
|
+
}
|
|
95
|
+
if (i < 0) return buf;
|
|
96
|
+
const lead = buf[i];
|
|
97
|
+
const need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 1;
|
|
98
|
+
return need > 1 && continuation + 1 < need ? buf.subarray(0, i) : buf;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const isAbsolutePath = (p: string): boolean => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
|
|
102
|
+
|
|
103
|
+
/** Env for a facade spawn: dashboard PATH augmentation, caller overrides, Electron-as-Node when needed. */
|
|
104
|
+
function spawnEnv(argv0: string, opts: FlowToolRunOptions | undefined, dropShellInit: boolean): NodeJS.ProcessEnv {
|
|
105
|
+
const base = new ToolResolver({ processExecPath: process.execPath }).buildSpawnEnv(process.env);
|
|
106
|
+
const merged = { ...base, ...(opts?.env ?? {}) };
|
|
107
|
+
// buildSpawnEnvForArgv re-merges process.env, so drop inherited shell-init vars AFTER it.
|
|
108
|
+
const env = buildSpawnEnvForArgv(argv0, merged) ?? merged;
|
|
109
|
+
if (dropShellInit) {
|
|
110
|
+
for (const key of ["BASH_ENV", "ENV"]) {
|
|
111
|
+
if (opts?.env?.[key] === undefined) delete env[key];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return env;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function execArgv(
|
|
118
|
+
argv: string[],
|
|
119
|
+
args: readonly string[],
|
|
120
|
+
opts: FlowToolRunOptions | undefined,
|
|
121
|
+
spawnFn: typeof defaultSpawn,
|
|
122
|
+
dropShellInit: boolean,
|
|
123
|
+
platform: NodeJS.Platform,
|
|
124
|
+
): Promise<FlowToolResult> {
|
|
125
|
+
if (opts?.signal?.aborted) return Promise.resolve(fail(130, "aborted before start"));
|
|
126
|
+
const [bin, ...prefix] = argv;
|
|
127
|
+
return new Promise<FlowToolResult>((resolve) => {
|
|
128
|
+
let child: ReturnType<typeof defaultSpawn>;
|
|
129
|
+
try {
|
|
130
|
+
// win32 `.cmd`/`.bat` shims (e.g. npx.cmd) cannot run with shell:false; route via cmd.exe.
|
|
131
|
+
const { argv: safe } = buildSafeArgv(bin, [...prefix, ...args], platform);
|
|
132
|
+
child = spawnFn(safe[0], safe.slice(1), {
|
|
133
|
+
cwd: opts?.cwd,
|
|
134
|
+
env: spawnEnv(bin, opts, dropShellInit),
|
|
135
|
+
detached: process.platform !== "win32", // platform-branch-ok: POSIX own process group so killProcessGroup reaches grandchildren; win32 detach would escape the job object
|
|
136
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
137
|
+
shell: false,
|
|
138
|
+
});
|
|
139
|
+
} catch (err) {
|
|
140
|
+
resolve(fail(127, (err as Error).message));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const out: Buffer[] = [];
|
|
145
|
+
const err: Buffer[] = [];
|
|
146
|
+
let outBytes = 0;
|
|
147
|
+
let errBytes = 0;
|
|
148
|
+
let killedFor: "abort" | "timeout" | "cap" | null = null;
|
|
149
|
+
let settled = false;
|
|
150
|
+
let timer: NodeJS.Timeout | undefined;
|
|
151
|
+
|
|
152
|
+
const finish = (exitCode: number | null, spawnError?: Error): void => {
|
|
153
|
+
if (settled) return;
|
|
154
|
+
settled = true;
|
|
155
|
+
if (timer) clearTimeout(timer);
|
|
156
|
+
opts?.signal?.removeEventListener("abort", onAbort);
|
|
157
|
+
// Chunks are already cut at the byte cap; a cut stream may end mid-character.
|
|
158
|
+
// Invalid bytes decode to U+FFFD (3 bytes each), so re-cap the decoded text too.
|
|
159
|
+
const decode = (chunks: Buffer[], total: number) => {
|
|
160
|
+
const buf = Buffer.concat(chunks);
|
|
161
|
+
const text = (total > MAX_OUTPUT_BYTES ? dropPartialUtf8Tail(buf) : buf).toString("utf8");
|
|
162
|
+
if (Buffer.byteLength(text, "utf8") <= MAX_OUTPUT_BYTES) return text;
|
|
163
|
+
return dropPartialUtf8Tail(Buffer.from(text, "utf8").subarray(0, MAX_OUTPUT_BYTES)).toString("utf8");
|
|
164
|
+
};
|
|
165
|
+
const stdout = decode(out, outBytes);
|
|
166
|
+
let stderr = decode(err, errBytes);
|
|
167
|
+
if (spawnError) stderr += `${stderr ? "\n" : ""}${spawnError.message}`;
|
|
168
|
+
const code = spawnError
|
|
169
|
+
? (spawnError as NodeJS.ErrnoException).code === "ENOENT"
|
|
170
|
+
? 127
|
|
171
|
+
: 126
|
|
172
|
+
: killedFor === "abort"
|
|
173
|
+
? 130
|
|
174
|
+
: killedFor === "timeout"
|
|
175
|
+
? 124
|
|
176
|
+
: (exitCode ?? 1);
|
|
177
|
+
resolve({ ok: !spawnError && killedFor === null && exitCode === 0, code, stdout, stderr, out: stdout + stderr });
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const kill = (reason: "abort" | "timeout" | "cap"): void => {
|
|
181
|
+
if (killedFor || settled) return;
|
|
182
|
+
killedFor = reason;
|
|
183
|
+
const pid = child.pid;
|
|
184
|
+
const done = () => {
|
|
185
|
+
// stdio may be held open by an unkillable descendant; never wait past the bound.
|
|
186
|
+
setTimeout(() => {
|
|
187
|
+
child.stdout?.destroy();
|
|
188
|
+
child.stderr?.destroy();
|
|
189
|
+
finish(null);
|
|
190
|
+
}, CLOSE_WAIT_MS).unref();
|
|
191
|
+
};
|
|
192
|
+
if (!pid) return done();
|
|
193
|
+
killProcessGroup(pid, { timeoutMs: KILL_GRACE_MS }).then(done, () => {
|
|
194
|
+
try {
|
|
195
|
+
child.kill("SIGKILL");
|
|
196
|
+
} catch {
|
|
197
|
+
/* already gone */
|
|
198
|
+
}
|
|
199
|
+
done();
|
|
200
|
+
});
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const collect = (chunks: Buffer[], stream: "out" | "err") => (chunk: Buffer) => {
|
|
204
|
+
const used = stream === "out" ? outBytes : errBytes;
|
|
205
|
+
const room = MAX_OUTPUT_BYTES - used;
|
|
206
|
+
if (room > 0) chunks.push(room >= chunk.length ? chunk : chunk.subarray(0, room));
|
|
207
|
+
const next = used + chunk.length;
|
|
208
|
+
if (stream === "out") outBytes = next;
|
|
209
|
+
else errBytes = next;
|
|
210
|
+
if (next > MAX_OUTPUT_BYTES) kill("cap");
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
function onAbort(): void {
|
|
214
|
+
kill("abort");
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
child.stdout?.on("data", collect(out, "out"));
|
|
218
|
+
child.stderr?.on("data", collect(err, "err"));
|
|
219
|
+
child.on("error", (e) => finish(null, e));
|
|
220
|
+
child.on("close", (code) => finish(code));
|
|
221
|
+
opts?.signal?.addEventListener("abort", onAbort, { once: true });
|
|
222
|
+
const t = opts?.timeoutMs;
|
|
223
|
+
if (typeof t === "number" && Number.isFinite(t) && t > 0) timer = setTimeout(() => kill("timeout"), t);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Build a facade. Defaults: the process-wide dashboard registry and the windowsHide spawn wrapper. */
|
|
228
|
+
export function createFlowTools(deps: FlowToolsDeps = {}): FlowTools {
|
|
229
|
+
const registry = deps.registry ?? getDefaultRegistry;
|
|
230
|
+
const spawnFn = deps.spawn ?? defaultSpawn;
|
|
231
|
+
const platform = deps.platform ?? process.platform;
|
|
232
|
+
|
|
233
|
+
const argvFor = (name: string): string[] => {
|
|
234
|
+
try {
|
|
235
|
+
const reg = registry();
|
|
236
|
+
if (!reg.has(name)) return [];
|
|
237
|
+
const exec = reg.resolveExecutor(name);
|
|
238
|
+
return exec.ok ? exec.argv : [];
|
|
239
|
+
} catch {
|
|
240
|
+
return [];
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
has(name) {
|
|
246
|
+
try {
|
|
247
|
+
return registry().has(name);
|
|
248
|
+
} catch {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
resolve(name) {
|
|
253
|
+
try {
|
|
254
|
+
const reg = registry();
|
|
255
|
+
if (!reg.has(name)) return null;
|
|
256
|
+
const r = reg.resolve(name);
|
|
257
|
+
return r.ok && typeof r.path === "string" && isAbsolutePath(r.path) ? r.path : null;
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
async run(name, args = [], opts) {
|
|
263
|
+
if (opts?.signal?.aborted) return fail(130, "aborted before start");
|
|
264
|
+
const argv = argvFor(name);
|
|
265
|
+
if (!argv.length) return fail(127, `${name}: not registered or not resolved`);
|
|
266
|
+
return execArgv(argv, args, opts, spawnFn, false, platform);
|
|
267
|
+
},
|
|
268
|
+
async shell(script, opts) {
|
|
269
|
+
if (opts?.signal?.aborted) return fail(130, "aborted before start");
|
|
270
|
+
const argv = argvFor("bash");
|
|
271
|
+
if (!argv.length) return fail(127, "bash: not registered or not resolved");
|
|
272
|
+
// Inherited BASH_ENV/ENV are dropped from the base; an explicit opts.env value is merged back on top.
|
|
273
|
+
return execArgv(argv, ["--noprofile", "--norc", "-c", script], opts, spawnFn, true, platform);
|
|
274
|
+
},
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Publish the facade on the process-global slot. Builds the registry eagerly so
|
|
280
|
+
* a broken registry leaves the slot as it was. Never throws.
|
|
281
|
+
*/
|
|
282
|
+
export function publishFlowTools(): void {
|
|
283
|
+
try {
|
|
284
|
+
const reg = getDefaultRegistry();
|
|
285
|
+
(globalThis as unknown as Record<symbol, FlowTools>)[SLOT] = createFlowTools({ registry: () => reg });
|
|
286
|
+
} catch {
|
|
287
|
+
/* registry unavailable — handlers take their own fallback path */
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Remove the facade (session_shutdown). Idempotent, never throws. */
|
|
292
|
+
export function clearFlowTools(): void {
|
|
293
|
+
try {
|
|
294
|
+
delete (globalThis as unknown as Record<symbol, FlowTools | undefined>)[SLOT];
|
|
295
|
+
} catch {
|
|
296
|
+
/* nothing to clear */
|
|
297
|
+
}
|
|
298
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* flows-plugin · `flow_write` guideline for the flow-tools facade.
|
|
3
|
+
*
|
|
4
|
+
* Before each agent run whose selected tools include pi-flows' `flow_write`
|
|
5
|
+
* (flow edit mode on), appends ONE guideline telling the model how code-node
|
|
6
|
+
* handlers reach the dashboard tool registry (see `flow-tool-registry.ts`).
|
|
7
|
+
*
|
|
8
|
+
* Dashboard-only by construction (roles-plugin `Agent` guideline pattern): this
|
|
9
|
+
* ships only with the flows plugin, whose bridge is registered only while the
|
|
10
|
+
* plugin is enabled — any project opened through the dashboard gets it; plain
|
|
11
|
+
* pi-flows never does. Deduped, because a stale and a current bridge generation
|
|
12
|
+
* can both fire after `/reload`. See change: add-flow-code-node-tools (D5).
|
|
13
|
+
*/
|
|
14
|
+
import { FLOW_TOOLS_SYMBOL_KEY } from "./flow-tool-registry.js";
|
|
15
|
+
|
|
16
|
+
export const FLOW_WRITE_TOOL = "flow_write";
|
|
17
|
+
|
|
18
|
+
export const FLOW_TOOLS_GUIDELINE =
|
|
19
|
+
"Code handlers (code / code-decision nodes) can run any dashboard-registered tool (bash, git, node, npm, npx, gh, …) " +
|
|
20
|
+
"through the pi-dashboard tool registry instead of running bare names off PATH. Guard and fall back, because the " +
|
|
21
|
+
`facade exists only under the dashboard: \`const tools = (globalThis as any)[Symbol.for("${FLOW_TOOLS_SYMBOL_KEY}")]; ` +
|
|
22
|
+
'if (tools) { const r = await tools.run("git", ["status"], { cwd: ctx.cwd, signal: ctx.signal }); } ' +
|
|
23
|
+
"else { /* node:child_process fallback */ }`. Methods: `has(name)`, `resolve(name)` (absolute path or null; do not " +
|
|
24
|
+
"execute it directly, use run), `await run(name, args, { cwd, env, timeoutMs, signal })`, `await shell(script, opts)` (registry " +
|
|
25
|
+
"bash without login profiles). Results are `{ ok, code, stdout, stderr, out }` and never throw: 127 = tool not " +
|
|
26
|
+
"found, 130 = aborted; output is capped at 64 MiB per stream. Address tools by name; there is no list().";
|
|
27
|
+
|
|
28
|
+
interface PromptOptionsLike {
|
|
29
|
+
selectedTools?: string[];
|
|
30
|
+
toolGuidelines?: Record<string, string[]>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface PiLike {
|
|
34
|
+
on?: (event: string, handler: (event: unknown) => unknown) => unknown;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Register the per-run guideline injector. Never throws, never blocks a run. */
|
|
38
|
+
export function startFlowToolsGuideline(pi: PiLike): void {
|
|
39
|
+
if (!pi || typeof pi.on !== "function") return;
|
|
40
|
+
pi.on("before_agent_start", (event: unknown) => {
|
|
41
|
+
try {
|
|
42
|
+
const opts = (event as { systemPromptOptions?: PromptOptionsLike } | undefined)?.systemPromptOptions;
|
|
43
|
+
if (!opts || !Array.isArray(opts.selectedTools) || !opts.selectedTools.includes(FLOW_WRITE_TOOL)) return;
|
|
44
|
+
opts.toolGuidelines ??= {};
|
|
45
|
+
const existing = opts.toolGuidelines[FLOW_WRITE_TOOL] ?? [];
|
|
46
|
+
if (existing.includes(FLOW_TOOLS_GUIDELINE)) return;
|
|
47
|
+
opts.toolGuidelines[FLOW_WRITE_TOOL] = [...existing, FLOW_TOOLS_GUIDELINE];
|
|
48
|
+
} catch {
|
|
49
|
+
/* guidance is best-effort; never block a run */
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
package/src/bridge/index.ts
CHANGED
|
@@ -7,28 +7,85 @@
|
|
|
7
7
|
* the top-level `packages[]` array so pi-coding-agent loads it as a pi
|
|
8
8
|
* extension on the next session start.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* existing handler in `packages/extension/src/bridge.ts`. PromptBus
|
|
14
|
-
* sorts adapters by `priority`; `FlowQuestionAdapter` (priority 100)
|
|
15
|
-
* therefore claims flow-tagged prompts before `DashboardDefaultAdapter`
|
|
16
|
-
* (priority 9999).
|
|
10
|
+
* Registers no PromptBus adapter: pi-flows 0.11+ asks through the parent
|
|
11
|
+
* mailbox (`flow:question` / `flow:answer`, forwarded below), so the old
|
|
12
|
+
* flow-question adapter is gone. See change: adopt-flow-parent-mailbox (D8).
|
|
17
13
|
*
|
|
18
|
-
*
|
|
14
|
+
* Starts the flow-files reporter (see `flow-files-reporter.ts`) and the
|
|
15
|
+
* flow catalog publisher (see `flow-catalog-publisher.ts`; change
|
|
16
|
+
* flows-dock-chip-and-panel-actions), and declares every pi-flows run channel
|
|
17
|
+
* plus the persisted `flow-event` entry type through the generic forward seam
|
|
18
|
+
* (see `flow-event-forward.ts`; change update-flows-plugin), and persists each
|
|
19
|
+
* run dismissal as a `flow-run-close` entry (change persist-flow-run-close).
|
|
20
|
+
*
|
|
21
|
+
* Claude subscription compat for flow agents: pi-flows builds agents with an
|
|
22
|
+
* in-memory loader that never loads the settings packages, so the dashboard
|
|
23
|
+
* extension's own registration misses them. This bridge announces one stable
|
|
24
|
+
* compat factory on pi-flows' spawn hook (`flow:register-agent-extension`) on
|
|
25
|
+
* activate and every `session_start` (pi-flows dedupes by reference and may
|
|
26
|
+
* re-seed on `/reload`). See change: restore-flow-agent-claude-compat.
|
|
19
27
|
*
|
|
20
28
|
* See change: route-flow-asks-to-upper-slot.
|
|
21
29
|
*/
|
|
30
|
+
import { claudeCompatExtension } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/claude-compat.js";
|
|
31
|
+
import { startFlowCatalogPublisher } from "./flow-catalog-publisher.js";
|
|
32
|
+
import { startFlowEventForward } from "./flow-event-forward.js";
|
|
22
33
|
import { startFlowFilesReporter } from "./flow-files-reporter.js";
|
|
23
|
-
import {
|
|
34
|
+
import { startFlowOpenTool } from "./flow-open-tool.js";
|
|
35
|
+
import { clearFlowTools, publishFlowTools } from "./flow-tool-registry.js";
|
|
36
|
+
import { startRunSnapshotReporter } from "./run-snapshot-reporter.js";
|
|
37
|
+
import { startFlowToolsGuideline } from "./flow-tools-guideline.js";
|
|
38
|
+
|
|
39
|
+
// Switch value the dashboard extension mirrors process-globally on
|
|
40
|
+
// `preferences_update` (`packages/extension/src/bridge.ts` BRIDGE_KEY). Flow
|
|
41
|
+
// agents run in this process. Absent bridge or value → off.
|
|
42
|
+
const readSwitch = (): boolean =>
|
|
43
|
+
(process as unknown as { __pi_dashboard_bridge__?: { claudeSubscriptionCompat?: boolean } }).__pi_dashboard_bridge__
|
|
44
|
+
?.claudeSubscriptionCompat === true;
|
|
45
|
+
const claudeCompatAgentFactory = claudeCompatExtension(readSwitch);
|
|
46
|
+
|
|
47
|
+
function announceAgentFactory(events: { emit: (name: string, payload: unknown) => void }): void {
|
|
48
|
+
try {
|
|
49
|
+
events.emit("flow:register-agent-extension", { factory: claudeCompatAgentFactory });
|
|
50
|
+
} catch {
|
|
51
|
+
/* never throw from an announce */
|
|
52
|
+
}
|
|
53
|
+
}
|
|
24
54
|
|
|
25
55
|
export default function activate(ctx: unknown): void {
|
|
26
56
|
const c = ctx as { pi?: { events?: { emit: (name: string, payload: unknown) => void } }; events?: unknown };
|
|
27
57
|
const pi = c?.pi ?? c;
|
|
28
58
|
const events = (pi as { events?: { emit: (name: string, payload: unknown) => void } })?.events;
|
|
29
59
|
if (!events || typeof events.emit !== "function") return;
|
|
30
|
-
|
|
60
|
+
|
|
61
|
+
announceAgentFactory(events);
|
|
62
|
+
const piOn = pi as { on?: (name: string, handler: () => void) => unknown };
|
|
63
|
+
if (typeof piOn.on === "function") piOn.on("session_start", () => announceAgentFactory(events));
|
|
64
|
+
|
|
65
|
+
// Tool-registry facade for pi-flows code nodes: publish on activate + every
|
|
66
|
+
// session_start, clear on session_shutdown. Never throws.
|
|
67
|
+
// See change: add-flow-code-node-tools (D1, D6).
|
|
68
|
+
publishFlowTools();
|
|
69
|
+
if (typeof piOn.on === "function") {
|
|
70
|
+
piOn.on("session_start", () => publishFlowTools());
|
|
71
|
+
piOn.on("session_shutdown", () => clearFlowTools());
|
|
72
|
+
}
|
|
73
|
+
// Teach flow_write how code handlers reach the facade (dashboard-only guideline).
|
|
74
|
+
startFlowToolsGuideline(pi as Parameters<typeof startFlowToolsGuideline>[0]);
|
|
75
|
+
|
|
31
76
|
// Report this session's flow / agent / handler files to the plugin server so
|
|
32
77
|
// the UI can open them. See change: attach-flow-before-run.
|
|
33
78
|
startFlowFilesReporter(pi as Parameters<typeof startFlowFilesReporter>[0]);
|
|
79
|
+
// Forward pi-flows run events (core holds no flow map) and request a
|
|
80
|
+
// commands resend on rediscover / complete. See change: update-flows-plugin.
|
|
81
|
+
startFlowEventForward(pi as Parameters<typeof startFlowEventForward>[0]);
|
|
82
|
+
// Report the run active in this process on each report ask, so a live run
|
|
83
|
+
// reattaches. See change: fix-flow-reattach-per-run-state (D3).
|
|
84
|
+
startRunSnapshotReporter(pi as Parameters<typeof startRunSnapshotReporter>[0]);
|
|
85
|
+
// Publish this session's flow catalog through declared event forwarding.
|
|
86
|
+
// See change: flows-dock-chip-and-panel-actions.
|
|
87
|
+
startFlowCatalogPublisher(pi as Parameters<typeof startFlowCatalogPublisher>[0]);
|
|
88
|
+
// Agent `flow_open` tool: show a catalog or path flow in the flow slot.
|
|
89
|
+
// See change: add-flow-open-tool.
|
|
90
|
+
startFlowOpenTool(pi as Parameters<typeof startFlowOpenTool>[0]);
|
|
34
91
|
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reports the run pi-flows is executing in THIS pi process as one
|
|
3
|
+
* `flow:run-snapshot` (forwarded as `flow_run_snapshot`), so a live run
|
|
4
|
+
* reattaches after a dashboard restart, a refresh or a windowed replay whose
|
|
5
|
+
* tail lost the run's `flow_started`.
|
|
6
|
+
*
|
|
7
|
+
* - Tracking: `flow:flow-started` with a `runId` marks the run active;
|
|
8
|
+
* `flow:complete` with the same `runId`, or `session_shutdown`, clears it. A
|
|
9
|
+
* rejection (no `runId`) leaves it alone. A replayed or phantom run is never
|
|
10
|
+
* active here, so it is never reported.
|
|
11
|
+
* - Entries: `ctx.sessionManager` captured on `session_start`.
|
|
12
|
+
* - Report: each `dashboard-flows:report-files` ask schedules a 300 ms
|
|
13
|
+
* debounced build that re-checks the active run, scans the session entries
|
|
14
|
+
* backwards to its `flow_started`, folds only its `flow-event` records,
|
|
15
|
+
* serializes, trims to the byte budget and emits. Never throws.
|
|
16
|
+
*
|
|
17
|
+
* See change: fix-flow-reattach-per-run-state (D3, D4).
|
|
18
|
+
*/
|
|
19
|
+
import type { DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
20
|
+
import { FLOW_FILES_REQUEST_EVENT } from "../flow-files-contract.js";
|
|
21
|
+
import { reduceFlowEvent } from "../flow-reducer.js";
|
|
22
|
+
import { type RunSnapshotData, serializeFlowState, trimToBudget } from "../flow-state-serialize.js";
|
|
23
|
+
import type { FlowState } from "../types.js";
|
|
24
|
+
|
|
25
|
+
/** pi bus channel the bridge emits a run snapshot on. */
|
|
26
|
+
export const RUN_SNAPSHOT_CHANNEL = "flow:run-snapshot";
|
|
27
|
+
const DEBOUNCE_MS = 300;
|
|
28
|
+
const FLOW_EVENT_ENTRY = "flow-event";
|
|
29
|
+
|
|
30
|
+
interface SessionEntryLike {
|
|
31
|
+
type?: unknown;
|
|
32
|
+
customType?: unknown;
|
|
33
|
+
data?: unknown;
|
|
34
|
+
timestamp?: unknown;
|
|
35
|
+
}
|
|
36
|
+
interface SessionManagerLike {
|
|
37
|
+
getEntries(): readonly SessionEntryLike[];
|
|
38
|
+
}
|
|
39
|
+
interface PiEvents {
|
|
40
|
+
on(name: string, fn: (data: unknown) => void): unknown;
|
|
41
|
+
emit(name: string, data: unknown): unknown;
|
|
42
|
+
}
|
|
43
|
+
interface PiLike {
|
|
44
|
+
events?: PiEvents;
|
|
45
|
+
on?: (name: string, fn: (event: unknown, ctx: unknown) => void) => unknown;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface FlowRecord {
|
|
49
|
+
seq: number;
|
|
50
|
+
eventType: string;
|
|
51
|
+
data: Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function flowRecord(entry: SessionEntryLike): FlowRecord | undefined {
|
|
55
|
+
if (entry?.type !== "custom" || entry.customType !== FLOW_EVENT_ENTRY) return undefined;
|
|
56
|
+
const rec = entry.data as { seq?: unknown; eventType?: unknown; data?: unknown } | undefined;
|
|
57
|
+
if (!rec || typeof rec.eventType !== "string" || !rec.data || typeof rec.data !== "object") return undefined;
|
|
58
|
+
return { seq: typeof rec.seq === "number" ? rec.seq : 0, eventType: rec.eventType, data: rec.data as Record<string, unknown> };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function entryTime(ts: unknown): number {
|
|
62
|
+
const n = typeof ts === "string" ? Date.parse(ts) : Number(ts);
|
|
63
|
+
return Number.isFinite(n) ? n : 0;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The snapshot of run `runId` from the session entries, or `undefined` when its
|
|
68
|
+
* `flow_started` record is absent. Scans backwards to the run start, then folds
|
|
69
|
+
* only that run's records forward.
|
|
70
|
+
*/
|
|
71
|
+
export function buildRunSnapshot(entries: readonly SessionEntryLike[], runId: string): RunSnapshotData | undefined {
|
|
72
|
+
let start = -1;
|
|
73
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
74
|
+
const rec = flowRecord(entries[i]);
|
|
75
|
+
if (rec?.eventType === "flow_started" && rec.data.runId === runId) {
|
|
76
|
+
start = i;
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (start < 0) return undefined;
|
|
81
|
+
let state: FlowState | null = null;
|
|
82
|
+
for (let i = start; i < entries.length; i++) {
|
|
83
|
+
const rec = flowRecord(entries[i]);
|
|
84
|
+
if (!rec || rec.data.runId !== runId) continue;
|
|
85
|
+
const event = { seq: rec.seq, timestamp: entryTime(entries[i].timestamp), eventType: rec.eventType, data: rec.data };
|
|
86
|
+
state = reduceFlowEvent(state, event as unknown as DashboardEvent);
|
|
87
|
+
}
|
|
88
|
+
if (!state) return undefined;
|
|
89
|
+
return trimToBudget({
|
|
90
|
+
runId,
|
|
91
|
+
flowName: state.flowName,
|
|
92
|
+
startedAt: entryTime(entries[start].timestamp),
|
|
93
|
+
state: serializeFlowState(state),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function startRunSnapshotReporter(pi: PiLike): void {
|
|
98
|
+
const events = pi.events;
|
|
99
|
+
if (!events || typeof events.emit !== "function" || typeof events.on !== "function") return;
|
|
100
|
+
let active: { runId: string } | undefined;
|
|
101
|
+
let sessionManager: SessionManagerLike | undefined;
|
|
102
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
103
|
+
|
|
104
|
+
const build = () => {
|
|
105
|
+
timer = undefined;
|
|
106
|
+
try {
|
|
107
|
+
const run = active;
|
|
108
|
+
if (!run || !sessionManager || typeof sessionManager.getEntries !== "function") return;
|
|
109
|
+
const snapshot = buildRunSnapshot(sessionManager.getEntries(), run.runId);
|
|
110
|
+
if (snapshot && active?.runId === run.runId) events.emit(RUN_SNAPSHOT_CHANNEL, snapshot);
|
|
111
|
+
} catch {
|
|
112
|
+
/* best-effort: the orphan re-ask or a refresh asks again */
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const runIdOf = (data: unknown): string | undefined => {
|
|
116
|
+
const id = (data as { runId?: unknown } | null | undefined)?.runId;
|
|
117
|
+
return typeof id === "string" && id ? id : undefined;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
pi.on?.("session_start", (_event, ctx) => {
|
|
122
|
+
const sm = (ctx as { sessionManager?: SessionManagerLike } | null | undefined)?.sessionManager;
|
|
123
|
+
if (sm) sessionManager = sm;
|
|
124
|
+
});
|
|
125
|
+
pi.on?.("session_shutdown", () => {
|
|
126
|
+
active = undefined;
|
|
127
|
+
if (timer) clearTimeout(timer);
|
|
128
|
+
timer = undefined;
|
|
129
|
+
});
|
|
130
|
+
events.on("flow:flow-started", (data) => {
|
|
131
|
+
const runId = runIdOf(data);
|
|
132
|
+
if (runId) active = { runId };
|
|
133
|
+
});
|
|
134
|
+
events.on("flow:complete", (data) => {
|
|
135
|
+
const runId = runIdOf(data);
|
|
136
|
+
if (runId && runId === active?.runId) active = undefined;
|
|
137
|
+
});
|
|
138
|
+
events.on(FLOW_FILES_REQUEST_EVENT, () => {
|
|
139
|
+
if (timer) clearTimeout(timer);
|
|
140
|
+
timer = setTimeout(build, DEBOUNCE_MS);
|
|
141
|
+
(timer as { unref?: () => void }).unref?.();
|
|
142
|
+
});
|
|
143
|
+
} catch {
|
|
144
|
+
/* never break activation */
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flow catalog timings stored in the flows plugin config (`configSchema.json`).
|
|
3
|
+
* One table drives defaults, ranges, validation messages and the reader used
|
|
4
|
+
* by the plugin server and client. Import-free leaf.
|
|
5
|
+
* See change: flows-dock-chip-and-panel-actions (D11).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type CatalogTimingKey =
|
|
9
|
+
| "catalogAskLimitSec"
|
|
10
|
+
| "catalogReaskIntervalSec"
|
|
11
|
+
| "catalogReaskAttempts"
|
|
12
|
+
| "catalogServerStartIntervalSec"
|
|
13
|
+
| "catalogServerStartWindowSec";
|
|
14
|
+
|
|
15
|
+
export interface CatalogTimingSpec {
|
|
16
|
+
key: CatalogTimingKey;
|
|
17
|
+
default: number;
|
|
18
|
+
min: number;
|
|
19
|
+
max: number;
|
|
20
|
+
/** Unit shown in the range message ("s" or ""). */
|
|
21
|
+
unit: "s" | "";
|
|
22
|
+
/** Whole numbers only. */
|
|
23
|
+
integer: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const CATALOG_TIMING_SPECS: readonly CatalogTimingSpec[] = [
|
|
27
|
+
{ key: "catalogAskLimitSec", default: 2, min: 0.5, max: 60, unit: "s", integer: false },
|
|
28
|
+
{ key: "catalogReaskIntervalSec", default: 5, min: 1, max: 60, unit: "s", integer: false },
|
|
29
|
+
{ key: "catalogReaskAttempts", default: 12, min: 1, max: 60, unit: "", integer: true },
|
|
30
|
+
{ key: "catalogServerStartIntervalSec", default: 5, min: 1, max: 60, unit: "s", integer: false },
|
|
31
|
+
{ key: "catalogServerStartWindowSec", default: 60, min: 10, max: 600, unit: "s", integer: false },
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
export interface CatalogTimings {
|
|
35
|
+
askLimitMs: number;
|
|
36
|
+
reaskIntervalMs: number;
|
|
37
|
+
reaskAttempts: number;
|
|
38
|
+
serverStartIntervalMs: number;
|
|
39
|
+
serverStartWindowMs: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Range label, e.g. "0.5–60 s" or "1–60". */
|
|
43
|
+
export function rangeLabel(spec: CatalogTimingSpec): string {
|
|
44
|
+
return `${spec.min}–${spec.max}${spec.unit ? ` ${spec.unit}` : ""}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Null when valid, else the range label the value violates. */
|
|
48
|
+
export function validateTiming(spec: CatalogTimingSpec, value: unknown): string | null {
|
|
49
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return rangeLabel(spec);
|
|
50
|
+
if (spec.integer && !Number.isInteger(value)) return rangeLabel(spec);
|
|
51
|
+
if (value < spec.min || value > spec.max) return rangeLabel(spec);
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function pick(cfg: Record<string, unknown> | undefined, spec: CatalogTimingSpec): number {
|
|
56
|
+
const v = cfg?.[spec.key];
|
|
57
|
+
return validateTiming(spec, v) === null ? (v as number) : spec.default;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Effective timings; a missing or out-of-range stored value falls back to its default. */
|
|
61
|
+
export function readCatalogTimings(cfg: Record<string, unknown> | undefined): CatalogTimings {
|
|
62
|
+
const [ask, reask, attempts, ssInterval, ssWindow] = CATALOG_TIMING_SPECS.map((s) => pick(cfg, s));
|
|
63
|
+
return {
|
|
64
|
+
askLimitMs: ask * 1000,
|
|
65
|
+
reaskIntervalMs: reask * 1000,
|
|
66
|
+
reaskAttempts: attempts,
|
|
67
|
+
serverStartIntervalMs: ssInterval * 1000,
|
|
68
|
+
serverStartWindowMs: ssWindow * 1000,
|
|
69
|
+
};
|
|
70
|
+
}
|