@fractal-solutions/qflow 1.0.84 → 2.0.0-canary.4
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/CHANGELOG.md +107 -0
- package/LICENSE +21 -504
- package/MIGRATION.md +1130 -0
- package/README.md +1432 -823
- package/dist/agent/agent.d.ts +4 -22
- package/dist/agent/agent.js +4 -364
- package/dist/agent/base_agent.d.ts +8 -20
- package/dist/agent/base_agent.js +8 -205
- package/dist/agent/control_nodes.d.ts +61 -0
- package/dist/agent/control_nodes.js +164 -0
- package/dist/agent/engine.d.ts +45 -0
- package/dist/agent/engine.js +415 -0
- package/dist/agent/flow.d.ts +77 -0
- package/dist/agent/flow.js +148 -0
- package/dist/agent/index.d.ts +12 -0
- package/dist/agent/index.js +12 -0
- package/dist/agent/lpavrl_agent.d.ts +1 -2
- package/dist/agent/lpavrl_agent.js +2 -175
- package/dist/agent/ooda_agent.d.ts +1 -2
- package/dist/agent/ooda_agent.js +2 -164
- package/dist/agent/pema_agent.d.ts +1 -2
- package/dist/agent/pema_agent.js +2 -168
- package/dist/agent/raor_agent.d.ts +1 -2
- package/dist/agent/raor_agent.js +2 -161
- package/dist/agent/strategies.d.ts +126 -0
- package/dist/agent/strategies.js +159 -0
- package/dist/agent/tools.d.ts +1 -0
- package/dist/agent/tools.js +42 -24
- package/dist/approval.d.ts +42 -0
- package/dist/approval.js +86 -0
- package/dist/budget.d.ts +103 -0
- package/dist/budget.js +133 -0
- package/dist/bun_nodes.d.ts +119 -0
- package/dist/bun_nodes.js +331 -0
- package/dist/contracts.d.ts +30 -0
- package/dist/contracts.js +103 -0
- package/dist/durable.d.ts +278 -0
- package/dist/durable.js +730 -0
- package/dist/eval.d.ts +165 -0
- package/dist/eval.js +263 -0
- package/dist/graph.d.ts +157 -0
- package/dist/graph.js +330 -0
- package/dist/llm/index.d.ts +359 -0
- package/dist/llm/index.js +924 -0
- package/dist/logger.js +7 -3
- package/dist/mcp/client.d.ts +55 -0
- package/dist/mcp/client.js +145 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +2 -0
- package/dist/mcp/server.d.ts +106 -0
- package/dist/mcp/server.js +154 -0
- package/dist/mcp/stdio.d.ts +2 -0
- package/dist/mcp/stdio.js +3 -0
- package/dist/memory.d.ts +101 -0
- package/dist/memory.js +217 -0
- package/dist/nodes/browser_control.js +5 -4
- package/dist/nodes/data_extractor.js +2 -1
- package/dist/nodes/data_validation.d.ts +3 -3
- package/dist/nodes/data_validation.js +19 -5
- package/dist/nodes/database.d.ts +2 -1
- package/dist/nodes/database.js +71 -58
- package/dist/nodes/gis.js +1 -1
- package/dist/nodes/git.d.ts +1 -1
- package/dist/nodes/git.js +65 -51
- package/dist/nodes/github.d.ts +1 -0
- package/dist/nodes/hardware_interaction.d.ts +2 -4
- package/dist/nodes/hardware_interaction.js +4 -3
- package/dist/nodes/http.d.ts +1 -7
- package/dist/nodes/http.js +46 -33
- package/dist/nodes/image_gallery.js +45 -45
- package/dist/nodes/index.d.ts +8 -0
- package/dist/nodes/index.js +8 -0
- package/dist/nodes/interactive_webview.d.ts +1 -2
- package/dist/nodes/interactive_webview.js +217 -216
- package/dist/nodes/multimedia_processing.js +1 -1
- package/dist/nodes/navigator.d.ts +7 -0
- package/dist/nodes/navigator.js +48 -8
- package/dist/nodes/pdf_processor.js +2 -1
- package/dist/nodes/remote_execution.js +2 -2
- package/dist/nodes/s3.d.ts +1 -0
- package/dist/nodes/scheduler.js +2 -2
- package/dist/nodes/search.d.ts +1 -1
- package/dist/nodes/search.js +3 -2
- package/dist/nodes/speech_synthesis.js +2 -1
- package/dist/nodes/spreadsheet.d.ts +1 -7
- package/dist/nodes/spreadsheet.js +2 -1
- package/dist/nodes/streaming_llm.d.ts +51 -0
- package/dist/nodes/streaming_llm.js +120 -0
- package/dist/nodes/webhook.d.ts +1 -5
- package/dist/nodes/webhook.js +106 -93
- package/dist/nodes/websockets.js +5 -3
- package/dist/nodes/webview.js +3 -2
- package/dist/optional.d.ts +32 -0
- package/dist/optional.js +61 -0
- package/dist/qflow.d.ts +25 -14
- package/dist/qflow.js +140 -49
- package/dist/schedule.d.ts +41 -0
- package/dist/schedule.js +149 -0
- package/dist/side_effects.d.ts +50 -0
- package/dist/side_effects.js +94 -0
- package/dist/streaming.d.ts +35 -0
- package/dist/streaming.js +199 -0
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +130 -0
- package/dist/tool_spec.d.ts +76 -0
- package/dist/tool_spec.js +321 -0
- package/dist/trace.d.ts +28 -0
- package/dist/trace.js +190 -0
- package/dist/util.d.ts +57 -0
- package/dist/util.js +122 -0
- package/package.json +153 -67
- package/qflow.config.js +18 -18
- package/scripts/postinstall.js +50 -0
- package/scripts/verify-package.js +114 -0
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { AsyncNode, Flow, AsyncFlow } from './qflow.js';
|
|
2
|
+
import { stableHash, resolveTemplate } from './util.js';
|
|
3
|
+
const WRITE_VERBS = /\b(write|create|insert|update|delete|remove|push|commit|send|post|put|patch|execute|shell|spawn|pay|charge)\b/i;
|
|
4
|
+
/**
|
|
5
|
+
* Provider-neutral tool description. The same object can produce agent tool
|
|
6
|
+
* definitions, MCP tools, LLM tool calls, and Markdown documentation.
|
|
7
|
+
*/
|
|
8
|
+
export class ToolSpec {
|
|
9
|
+
constructor(spec = {}) {
|
|
10
|
+
if (!spec.name)
|
|
11
|
+
throw new Error('ToolSpec requires a name.');
|
|
12
|
+
this.name = spec.name;
|
|
13
|
+
this.namespace = spec.namespace ?? '';
|
|
14
|
+
this.description = spec.description ?? '';
|
|
15
|
+
this.parameters = spec.parameters ?? { type: 'object', properties: {} };
|
|
16
|
+
this.capabilities = new Set(spec.capabilities ?? []);
|
|
17
|
+
this.permissions = new Set(spec.permissions ?? []);
|
|
18
|
+
this.idempotencyKey = spec.idempotencyKey ?? null;
|
|
19
|
+
this.timeoutMs = spec.timeoutMs ?? null;
|
|
20
|
+
this.dryRun = spec.dryRun ?? null;
|
|
21
|
+
this.sideEffect = spec.sideEffect ?? (WRITE_VERBS.test(`${this.name} ${this.description}`) ? 'write' : 'read');
|
|
22
|
+
this.node = spec.node ?? null;
|
|
23
|
+
this.execute = spec.execute ?? null;
|
|
24
|
+
this.hidden = Boolean(spec.hidden);
|
|
25
|
+
this.metadata = { ...(spec.metadata ?? {}) };
|
|
26
|
+
}
|
|
27
|
+
get qualifiedName() {
|
|
28
|
+
return this.namespace ? `${this.namespace}.${this.name}` : this.name;
|
|
29
|
+
}
|
|
30
|
+
has(capability) {
|
|
31
|
+
return this.capabilities.has(capability);
|
|
32
|
+
}
|
|
33
|
+
hasAll(capabilities = []) {
|
|
34
|
+
return capabilities.every(capability => this.has(capability));
|
|
35
|
+
}
|
|
36
|
+
definition() {
|
|
37
|
+
return {
|
|
38
|
+
name: this.qualifiedName,
|
|
39
|
+
description: this.description,
|
|
40
|
+
parameters: this.parameters,
|
|
41
|
+
capabilities: [...this.capabilities],
|
|
42
|
+
permissions: [...this.permissions],
|
|
43
|
+
sideEffect: this.sideEffect,
|
|
44
|
+
idempotencyKey: this.idempotencyKey,
|
|
45
|
+
timeoutMs: this.timeoutMs,
|
|
46
|
+
dryRun: Boolean(this.dryRun),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
toJSONSchema() {
|
|
50
|
+
return this.parameters;
|
|
51
|
+
}
|
|
52
|
+
toMCPTool() {
|
|
53
|
+
return {
|
|
54
|
+
name: this.qualifiedName,
|
|
55
|
+
description: this.description,
|
|
56
|
+
inputSchema: this.parameters,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
toLLMTool() {
|
|
60
|
+
return {
|
|
61
|
+
type: 'function',
|
|
62
|
+
function: {
|
|
63
|
+
name: this.qualifiedName,
|
|
64
|
+
description: this.description,
|
|
65
|
+
parameters: this.parameters,
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
validate(args = {}) {
|
|
70
|
+
const errors = [];
|
|
71
|
+
const schema = this.parameters ?? {};
|
|
72
|
+
const properties = schema.properties ?? {};
|
|
73
|
+
const required = schema.required ?? [];
|
|
74
|
+
const value = args && typeof args === 'object' ? args : {};
|
|
75
|
+
for (const key of required) {
|
|
76
|
+
if (value[key] === undefined)
|
|
77
|
+
errors.push(`Missing required parameter: '${key}'.`);
|
|
78
|
+
}
|
|
79
|
+
for (const [key, property] of Object.entries(properties)) {
|
|
80
|
+
const child = value[key];
|
|
81
|
+
if (child === undefined)
|
|
82
|
+
continue;
|
|
83
|
+
if (property.enum && !property.enum.includes(child)) {
|
|
84
|
+
errors.push(`Parameter '${key}' must be one of ${property.enum.join(', ')}.`);
|
|
85
|
+
}
|
|
86
|
+
if (property.type === 'array' && !Array.isArray(child)) {
|
|
87
|
+
errors.push(`Parameter '${key}' must be an array.`);
|
|
88
|
+
}
|
|
89
|
+
if (property.type === 'object' && (typeof child !== 'object' || Array.isArray(child))) {
|
|
90
|
+
errors.push(`Parameter '${key}' must be an object.`);
|
|
91
|
+
}
|
|
92
|
+
if (property.type === 'number' && typeof child !== 'number') {
|
|
93
|
+
errors.push(`Parameter '${key}' must be a number.`);
|
|
94
|
+
}
|
|
95
|
+
if (property.type === 'boolean' && typeof child !== 'boolean') {
|
|
96
|
+
errors.push(`Parameter '${key}' must be a boolean.`);
|
|
97
|
+
}
|
|
98
|
+
if (property.type === 'string' && typeof child !== 'string') {
|
|
99
|
+
errors.push(`Parameter '${key}' must be a string.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return errors;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
export function toolSpecFromNode(nodeOrClass, overrides = {}) {
|
|
106
|
+
const isInstance = nodeOrClass instanceof AsyncNode || (nodeOrClass && typeof nodeOrClass === 'object' && typeof nodeOrClass.execAsync === 'function');
|
|
107
|
+
const source = isInstance ? nodeOrClass.constructor : nodeOrClass;
|
|
108
|
+
if (typeof source?.getToolDefinition !== 'function') {
|
|
109
|
+
throw new Error('toolSpecFromNode requires a node class/instance with getToolDefinition().');
|
|
110
|
+
}
|
|
111
|
+
const definition = source.getToolDefinition();
|
|
112
|
+
return new ToolSpec({
|
|
113
|
+
...definition,
|
|
114
|
+
...overrides,
|
|
115
|
+
node: overrides.node ?? nodeOrClass,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
function matchesFilter(spec, filter = {}) {
|
|
119
|
+
if (filter.namespace && spec.namespace !== filter.namespace)
|
|
120
|
+
return false;
|
|
121
|
+
if (filter.capability && !spec.hasAll(Array.isArray(filter.capability) ? filter.capability : [filter.capability]))
|
|
122
|
+
return false;
|
|
123
|
+
if (filter.permission && !Array.from(spec.permissions).some(permission => filter.permission.includes(permission)))
|
|
124
|
+
return false;
|
|
125
|
+
if (filter.tag && !spec.metadata.tags?.includes(filter.tag))
|
|
126
|
+
return false;
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
async function resolveIdempotencyKey(spec, args, context) {
|
|
130
|
+
if (typeof spec.idempotencyKey === 'function') {
|
|
131
|
+
return await spec.idempotencyKey(args, context);
|
|
132
|
+
}
|
|
133
|
+
if (spec.idempotencyKey === true) {
|
|
134
|
+
return `${spec.qualifiedName}:${stableHash(args)}`;
|
|
135
|
+
}
|
|
136
|
+
if (typeof spec.idempotencyKey === 'string') {
|
|
137
|
+
return `${spec.qualifiedName}:${resolveTemplate(spec.idempotencyKey, {
|
|
138
|
+
...context,
|
|
139
|
+
...args,
|
|
140
|
+
args,
|
|
141
|
+
params: args,
|
|
142
|
+
shared: context.shared ?? {},
|
|
143
|
+
})}`;
|
|
144
|
+
}
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
/** Namespaced, capability-filtered registry shared by agents, MCP and docs. */
|
|
148
|
+
export class ToolRegistry {
|
|
149
|
+
constructor({ tools = [], grantedCapabilities = null, grantedPermissions = null, idempotencyStore = new Map(), } = {}) {
|
|
150
|
+
this.tools = new Map();
|
|
151
|
+
this.grantedCapabilities = grantedCapabilities ? new Set(grantedCapabilities) : null;
|
|
152
|
+
this.grantedPermissions = grantedPermissions ? new Set(grantedPermissions) : null;
|
|
153
|
+
this.idempotencyStore = idempotencyStore;
|
|
154
|
+
for (const tool of tools)
|
|
155
|
+
this.register(tool);
|
|
156
|
+
}
|
|
157
|
+
register(tool, overrides = {}) {
|
|
158
|
+
const spec = tool instanceof ToolSpec
|
|
159
|
+
? tool
|
|
160
|
+
: toolSpecFromNode(tool, overrides);
|
|
161
|
+
this.tools.set(spec.qualifiedName, spec);
|
|
162
|
+
this.tools.set(spec.name, spec);
|
|
163
|
+
return spec;
|
|
164
|
+
}
|
|
165
|
+
unregister(name) {
|
|
166
|
+
const spec = this.tools.get(name);
|
|
167
|
+
if (!spec)
|
|
168
|
+
return false;
|
|
169
|
+
this.tools.delete(spec.name);
|
|
170
|
+
this.tools.delete(spec.qualifiedName);
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
allowed(spec, options = {}) {
|
|
174
|
+
const asSet = value => value == null ? null : value instanceof Set ? value : new Set(value);
|
|
175
|
+
const capabilities = asSet(options.grantedCapabilities ?? this.grantedCapabilities);
|
|
176
|
+
const permissions = asSet(options.grantedPermissions ?? this.grantedPermissions);
|
|
177
|
+
if (capabilities && [...spec.capabilities].some(c => !capabilities.has(c)))
|
|
178
|
+
return false;
|
|
179
|
+
if (permissions && [...spec.permissions].some(p => !permissions.has(p)))
|
|
180
|
+
return false;
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
list(options = {}) {
|
|
184
|
+
return [...new Set(this.tools.values())].filter(spec => !spec.hidden &&
|
|
185
|
+
matchesFilter(spec, options) &&
|
|
186
|
+
this.allowed(spec, options));
|
|
187
|
+
}
|
|
188
|
+
get(name) {
|
|
189
|
+
return this.tools.get(name) ?? null;
|
|
190
|
+
}
|
|
191
|
+
definitions(options = {}) {
|
|
192
|
+
return this.list(options).map(spec => spec.definition());
|
|
193
|
+
}
|
|
194
|
+
mcpTools(options = {}) {
|
|
195
|
+
return this.list(options).map(spec => spec.toMCPTool());
|
|
196
|
+
}
|
|
197
|
+
llmTools(options = {}) {
|
|
198
|
+
return this.list(options).map(spec => spec.toLLMTool());
|
|
199
|
+
}
|
|
200
|
+
async execute(name, args = {}, options = {}) {
|
|
201
|
+
const spec = this.get(name);
|
|
202
|
+
if (!spec)
|
|
203
|
+
throw new Error(`Tool '${name}' is not registered.`);
|
|
204
|
+
if (!this.allowed(spec, options)) {
|
|
205
|
+
throw new Error(`Tool '${name}' is not allowed by the current capability grant.`);
|
|
206
|
+
}
|
|
207
|
+
const validationErrors = spec.validate(args);
|
|
208
|
+
if (validationErrors.length) {
|
|
209
|
+
throw new Error(`${spec.qualifiedName}: ${validationErrors.join(' ')}`);
|
|
210
|
+
}
|
|
211
|
+
const context = {
|
|
212
|
+
shared: options.shared ?? {},
|
|
213
|
+
observer: options.observer ?? {},
|
|
214
|
+
runId: options.runId ?? options.observer?.runId ?? null,
|
|
215
|
+
checkpointer: options.checkpointer ?? options.observer?.checkpointer ?? null,
|
|
216
|
+
signal: options.signal ?? options.observer?.signal ?? null,
|
|
217
|
+
};
|
|
218
|
+
if (options.dryRun || context.shared?.dryRun) {
|
|
219
|
+
if (typeof spec.dryRun === 'function') {
|
|
220
|
+
const preview = await spec.dryRun(args, context);
|
|
221
|
+
return { tool: spec.qualifiedName, dryRun: true, args, preview, result: preview };
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
tool: spec.qualifiedName,
|
|
225
|
+
dryRun: true,
|
|
226
|
+
args,
|
|
227
|
+
preview: { sideEffect: spec.sideEffect, capabilities: [...spec.capabilities] },
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const idempotencyKey = options.idempotencyKey ?? await resolveIdempotencyKey(spec, args, context);
|
|
231
|
+
const pending = Symbol('qflow-tool-pending');
|
|
232
|
+
const cacheKey = idempotencyKey ? `${spec.qualifiedName}:${idempotencyKey}` : null;
|
|
233
|
+
const storeGet = key => this.idempotencyStore.get?.(key) ?? this.idempotencyStore[key];
|
|
234
|
+
const storeSet = (key, value) => {
|
|
235
|
+
if (this.idempotencyStore.set)
|
|
236
|
+
this.idempotencyStore.set(key, value);
|
|
237
|
+
else
|
|
238
|
+
this.idempotencyStore[key] = value;
|
|
239
|
+
};
|
|
240
|
+
if (cacheKey) {
|
|
241
|
+
const cached = storeGet(cacheKey);
|
|
242
|
+
if (cached === pending) {
|
|
243
|
+
throw new Error(`Tool '${spec.qualifiedName}' is already running for idempotency key '${idempotencyKey}'.`);
|
|
244
|
+
}
|
|
245
|
+
if (cached !== undefined)
|
|
246
|
+
return { ...cached, replayed: true };
|
|
247
|
+
storeSet(cacheKey, pending);
|
|
248
|
+
}
|
|
249
|
+
const run = async () => {
|
|
250
|
+
if (typeof spec.execute === 'function') {
|
|
251
|
+
return await spec.execute(args, context);
|
|
252
|
+
}
|
|
253
|
+
if (!spec.node) {
|
|
254
|
+
throw new Error(`Tool '${spec.qualifiedName}' has no execute function or node.`);
|
|
255
|
+
}
|
|
256
|
+
const NodeClassOrInstance = spec.node;
|
|
257
|
+
const node = NodeClassOrInstance instanceof AsyncNode || NodeClassOrInstance instanceof Flow
|
|
258
|
+
? NodeClassOrInstance
|
|
259
|
+
: new NodeClassOrInstance();
|
|
260
|
+
node.setParams(args ?? {});
|
|
261
|
+
if (node instanceof AsyncNode) {
|
|
262
|
+
return await new AsyncFlow(node).runAsync({}, context.observer);
|
|
263
|
+
}
|
|
264
|
+
if (node instanceof Flow)
|
|
265
|
+
return node.run({});
|
|
266
|
+
return node.run(context.shared);
|
|
267
|
+
};
|
|
268
|
+
const timeoutMs = options.timeoutMs ?? spec.timeoutMs;
|
|
269
|
+
let timer = null;
|
|
270
|
+
let result;
|
|
271
|
+
try {
|
|
272
|
+
if (timeoutMs) {
|
|
273
|
+
const controller = new AbortController();
|
|
274
|
+
const forwardAbort = () => controller.abort(context.signal?.reason);
|
|
275
|
+
context.signal?.addEventListener?.('abort', forwardAbort, { once: true });
|
|
276
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
277
|
+
timer = setTimeout(() => {
|
|
278
|
+
const error = new Error(`Tool '${spec.qualifiedName}' timed out after ${timeoutMs}ms.`);
|
|
279
|
+
error.name = 'TimeoutError';
|
|
280
|
+
controller.abort(error);
|
|
281
|
+
reject(error);
|
|
282
|
+
}, timeoutMs);
|
|
283
|
+
});
|
|
284
|
+
context.signal = controller.signal;
|
|
285
|
+
result = await Promise.race([run(), timeout]);
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
result = await run();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
if (cacheKey)
|
|
293
|
+
storeSet(cacheKey, undefined);
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
if (timer)
|
|
298
|
+
clearTimeout(timer);
|
|
299
|
+
}
|
|
300
|
+
const outcome = { tool: spec.qualifiedName, result, args };
|
|
301
|
+
if (cacheKey)
|
|
302
|
+
storeSet(cacheKey, outcome);
|
|
303
|
+
return outcome;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
export function generateToolDocs(registry, { title = 'Available Tools' } = {}) {
|
|
307
|
+
const lines = [`# ${title}`, ''];
|
|
308
|
+
for (const spec of registry.list()) {
|
|
309
|
+
lines.push(`## \`${spec.qualifiedName}\``, '', spec.description || '_No description_', '');
|
|
310
|
+
if (spec.capabilities.size)
|
|
311
|
+
lines.push(`- Capabilities: ${[...spec.capabilities].join(', ')}`);
|
|
312
|
+
if (spec.permissions.size)
|
|
313
|
+
lines.push(`- Permissions: ${[...spec.permissions].join(', ')}`);
|
|
314
|
+
lines.push(`- Side effect: \`${spec.sideEffect}\``, '');
|
|
315
|
+
const required = spec.parameters?.required ?? [];
|
|
316
|
+
if (required.length)
|
|
317
|
+
lines.push(`Required: ${required.map(name => `\`${name}\``).join(', ')}`, '');
|
|
318
|
+
lines.push('```json', JSON.stringify(spec.parameters ?? {}, null, 2), '```', '');
|
|
319
|
+
}
|
|
320
|
+
return lines.join('\n');
|
|
321
|
+
}
|
package/dist/trace.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Pair `*:start` / `*:end` events into timeline spans. */
|
|
2
|
+
export function buildTraceSpans(events?: any[]): any[];
|
|
3
|
+
/**
|
|
4
|
+
* Accepts a raw event array, `recordFlow()` events, `createTraceSnapshot()`
|
|
5
|
+
* output, an `exportRunTrace()` result, or `{ events, checkpoints }`.
|
|
6
|
+
*/
|
|
7
|
+
export function normalizeTrace(input: any): {
|
|
8
|
+
schema: string;
|
|
9
|
+
runId: any;
|
|
10
|
+
flowName: any;
|
|
11
|
+
status: any;
|
|
12
|
+
steps: any;
|
|
13
|
+
startedAt: any;
|
|
14
|
+
endedAt: any;
|
|
15
|
+
events: any[];
|
|
16
|
+
checkpoints: any;
|
|
17
|
+
spans: any[];
|
|
18
|
+
};
|
|
19
|
+
/** Pretty-printed JSON suitable for download or clipboard. */
|
|
20
|
+
export function serializeTrace(trace: any): string;
|
|
21
|
+
/** Write a trace to disk. Bun-only, matching the 2.0 runtime contract. */
|
|
22
|
+
export function writeTraceFile(trace: any, filepath: any): Promise<any>;
|
|
23
|
+
/**
|
|
24
|
+
* Trace normalization helpers shared by testing, durable runs, and the trace
|
|
25
|
+
* viewer. The output is plain JSON so it can be saved, shipped, or pasted into
|
|
26
|
+
* the site viewer without pulling in Bun-specific modules.
|
|
27
|
+
*/
|
|
28
|
+
export const TRACE_SCHEMA: "qflow.trace/v1";
|
package/dist/trace.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Trace normalization helpers shared by testing, durable runs, and the trace
|
|
3
|
+
* viewer. The output is plain JSON so it can be saved, shipped, or pasted into
|
|
4
|
+
* the site viewer without pulling in Bun-specific modules.
|
|
5
|
+
*/
|
|
6
|
+
export const TRACE_SCHEMA = 'qflow.trace/v1';
|
|
7
|
+
function cloneValue(value, seen = new WeakSet()) {
|
|
8
|
+
if (value == null || typeof value === 'string' || typeof value === 'boolean')
|
|
9
|
+
return value;
|
|
10
|
+
if (typeof value === 'number')
|
|
11
|
+
return Number.isFinite(value) ? value : String(value);
|
|
12
|
+
if (typeof value === 'bigint')
|
|
13
|
+
return String(value);
|
|
14
|
+
if (typeof value === 'function')
|
|
15
|
+
return `[Function ${value.name || 'anonymous'}]`;
|
|
16
|
+
if (value instanceof Error)
|
|
17
|
+
return { name: value.name, message: value.message };
|
|
18
|
+
if (value instanceof Date)
|
|
19
|
+
return value.toISOString();
|
|
20
|
+
if (typeof value !== 'object')
|
|
21
|
+
return String(value);
|
|
22
|
+
if (seen.has(value))
|
|
23
|
+
return '[Circular]';
|
|
24
|
+
seen.add(value);
|
|
25
|
+
if (Array.isArray(value))
|
|
26
|
+
return value.map(item => cloneValue(item, seen));
|
|
27
|
+
const result = {};
|
|
28
|
+
for (const [key, child] of Object.entries(value)) {
|
|
29
|
+
result[key] = cloneValue(child, seen);
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
function normalizeEvent(entry, index) {
|
|
34
|
+
if (typeof entry === 'string')
|
|
35
|
+
return { seq: index, event: entry };
|
|
36
|
+
if (!entry || typeof entry !== 'object') {
|
|
37
|
+
return { seq: index, event: 'log', message: String(entry) };
|
|
38
|
+
}
|
|
39
|
+
const { event, type, payload, ...topLevel } = entry;
|
|
40
|
+
const eventName = event ?? type ?? 'custom';
|
|
41
|
+
const payloadObject = payload && typeof payload === 'object' && !Array.isArray(payload)
|
|
42
|
+
? cloneValue(payload)
|
|
43
|
+
: null;
|
|
44
|
+
if (payloadObject) {
|
|
45
|
+
return { seq: index, event: eventName, ...cloneValue(topLevel), ...payloadObject };
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
seq: index,
|
|
49
|
+
event: eventName,
|
|
50
|
+
...cloneValue(topLevel),
|
|
51
|
+
...(payload !== undefined ? { message: cloneValue(payload) } : {}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function lastDefined(events, key) {
|
|
55
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
56
|
+
const value = events[i]?.[key];
|
|
57
|
+
if (value != null)
|
|
58
|
+
return cloneValue(value);
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
function firstTime(events, keys) {
|
|
63
|
+
for (const event of events) {
|
|
64
|
+
for (const key of keys) {
|
|
65
|
+
if (event?.[key] != null)
|
|
66
|
+
return event[key];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
function lastTime(events, keys) {
|
|
72
|
+
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
73
|
+
for (const key of keys) {
|
|
74
|
+
if (events[i]?.[key] != null)
|
|
75
|
+
return events[i][key];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
function deriveStatus(events) {
|
|
81
|
+
const terminal = [...events].reverse().find(event => event.event === 'flow:end' || event.event === 'run:end');
|
|
82
|
+
if (terminal?.status)
|
|
83
|
+
return terminal.status;
|
|
84
|
+
if (terminal?.error || events.some(event => event.error || event.status === 'error'))
|
|
85
|
+
return 'failed';
|
|
86
|
+
if (events.some(event => event.event === 'flow:start' || event.event === 'run:start'))
|
|
87
|
+
return 'running';
|
|
88
|
+
return 'unknown';
|
|
89
|
+
}
|
|
90
|
+
function spanKey(event) {
|
|
91
|
+
if (event.nodeClass)
|
|
92
|
+
return `node:${event.flowId ?? event.runId ?? ''}:${event.nodeClass}`;
|
|
93
|
+
if (event.event?.startsWith('flow:'))
|
|
94
|
+
return `flow:${event.flowId ?? ''}`;
|
|
95
|
+
return `run:${event.runId ?? ''}`;
|
|
96
|
+
}
|
|
97
|
+
/** Pair `*:start` / `*:end` events into timeline spans. */
|
|
98
|
+
export function buildTraceSpans(events = []) {
|
|
99
|
+
const open = new Map();
|
|
100
|
+
const spans = [];
|
|
101
|
+
for (const event of events) {
|
|
102
|
+
const name = event.event ?? '';
|
|
103
|
+
if (name === 'node:start' || name === 'flow:start' || name === 'run:start') {
|
|
104
|
+
const key = spanKey(event);
|
|
105
|
+
open.set(key, {
|
|
106
|
+
seq: event.seq,
|
|
107
|
+
kind: name.split(':')[0],
|
|
108
|
+
label: event.nodeClass ?? event.flowName ?? event.runId ?? name,
|
|
109
|
+
flowId: event.flowId ?? null,
|
|
110
|
+
runId: event.runId ?? null,
|
|
111
|
+
startTime: event.startTime ?? event.createdAt ?? event.timestamp ?? null,
|
|
112
|
+
endTime: null,
|
|
113
|
+
duration: null,
|
|
114
|
+
status: 'running',
|
|
115
|
+
params: event.params ?? null,
|
|
116
|
+
});
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (name !== 'node:end' && name !== 'flow:end' && name !== 'run:end')
|
|
120
|
+
continue;
|
|
121
|
+
const key = spanKey(event);
|
|
122
|
+
const span = open.get(key) ?? [...open.entries()].reverse().find(([openKey]) => openKey.startsWith(name.split(':')[0]))?.[1];
|
|
123
|
+
if (span) {
|
|
124
|
+
span.endTime = event.endTime ?? event.updatedAt ?? event.timestamp ?? null;
|
|
125
|
+
span.duration = event.duration ?? (span.startTime != null && span.endTime != null ? span.endTime - span.startTime : null);
|
|
126
|
+
span.status = event.status ?? (event.error ? 'error' : 'success');
|
|
127
|
+
span.error = event.error != null ? cloneValue(event.error) : null;
|
|
128
|
+
span.result = event.result != null ? cloneValue(event.result) : null;
|
|
129
|
+
span.step = event.step ?? null;
|
|
130
|
+
if (span.kind === 'node' && event.nodeClass)
|
|
131
|
+
span.label = event.nodeClass;
|
|
132
|
+
open.delete(key);
|
|
133
|
+
}
|
|
134
|
+
spans.push({
|
|
135
|
+
seq: event.seq,
|
|
136
|
+
kind: name.split(':')[0],
|
|
137
|
+
label: event.nodeClass ?? event.flowName ?? event.runId ?? name,
|
|
138
|
+
startTime: event.startTime ?? event.createdAt ?? event.timestamp ?? null,
|
|
139
|
+
endTime: event.endTime ?? event.updatedAt ?? event.timestamp ?? null,
|
|
140
|
+
duration: event.duration ?? null,
|
|
141
|
+
status: event.status ?? (event.error ? 'error' : 'instant'),
|
|
142
|
+
error: event.error != null ? cloneValue(event.error) : null,
|
|
143
|
+
step: event.step ?? null,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
for (const span of open.values()) {
|
|
147
|
+
span.status = 'open';
|
|
148
|
+
spans.push(span);
|
|
149
|
+
}
|
|
150
|
+
return spans.sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0));
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Accepts a raw event array, `recordFlow()` events, `createTraceSnapshot()`
|
|
154
|
+
* output, an `exportRunTrace()` result, or `{ events, checkpoints }`.
|
|
155
|
+
*/
|
|
156
|
+
export function normalizeTrace(input) {
|
|
157
|
+
const source = Array.isArray(input)
|
|
158
|
+
? { events: input }
|
|
159
|
+
: input && typeof input === 'object'
|
|
160
|
+
? input
|
|
161
|
+
: {};
|
|
162
|
+
const rawEvents = source.events ?? source.trace ?? source.entries ?? [];
|
|
163
|
+
const events = (Array.isArray(rawEvents) ? rawEvents : []).map(normalizeEvent);
|
|
164
|
+
const checkpoints = (Array.isArray(source.checkpoints) ? source.checkpoints : [])
|
|
165
|
+
.map(checkpoint => cloneValue(checkpoint));
|
|
166
|
+
return {
|
|
167
|
+
schema: TRACE_SCHEMA,
|
|
168
|
+
runId: source.runId ?? lastDefined(events, 'runId'),
|
|
169
|
+
flowName: source.flowName ?? lastDefined(events, 'flowName'),
|
|
170
|
+
status: source.status ?? deriveStatus(events),
|
|
171
|
+
steps: source.steps ?? (checkpoints.length || events.filter(event => event.event === 'node:end').length || null),
|
|
172
|
+
startedAt: source.startedAt ?? source.createdAt ?? firstTime(events, ['startTime', 'createdAt', 'timestamp']),
|
|
173
|
+
endedAt: source.endedAt ?? source.updatedAt ?? lastTime(events, ['endTime', 'updatedAt', 'timestamp']),
|
|
174
|
+
events,
|
|
175
|
+
checkpoints,
|
|
176
|
+
spans: buildTraceSpans(events),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/** Pretty-printed JSON suitable for download or clipboard. */
|
|
180
|
+
export function serializeTrace(trace) {
|
|
181
|
+
return JSON.stringify(normalizeTrace(trace), null, 2);
|
|
182
|
+
}
|
|
183
|
+
/** Write a trace to disk. Bun-only, matching the 2.0 runtime contract. */
|
|
184
|
+
export async function writeTraceFile(trace, filepath) {
|
|
185
|
+
if (typeof globalThis.Bun?.write !== 'function') {
|
|
186
|
+
throw new Error('writeTraceFile() requires the Bun runtime.');
|
|
187
|
+
}
|
|
188
|
+
await globalThis.Bun.write(filepath, serializeTrace(trace));
|
|
189
|
+
return filepath;
|
|
190
|
+
}
|
package/dist/util.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Small, dependency-free helpers shared by the 2.0 node families. */
|
|
2
|
+
export function stableStringify(value: any, seen?: WeakSet<WeakKey>): any;
|
|
3
|
+
/** Deterministic 32-bit hash, useful for operation and idempotency keys. */
|
|
4
|
+
export function stableHash(value: any): string;
|
|
5
|
+
export function cloneValue(value: any, seen?: WeakSet<WeakKey>): any;
|
|
6
|
+
export function resolveTemplate(template: any, context: any): any;
|
|
7
|
+
export class SideEffectUncertainError extends Error {
|
|
8
|
+
constructor(operationId: any, message: any);
|
|
9
|
+
code: string;
|
|
10
|
+
operationId: any;
|
|
11
|
+
}
|
|
12
|
+
/** Another worker holds an active lease on an operation; do not execute it. */
|
|
13
|
+
export class SideEffectClaimedError extends SideEffectUncertainError {
|
|
14
|
+
constructor(operationId: any, claimedBy: any, message: any);
|
|
15
|
+
claimedBy: any;
|
|
16
|
+
}
|
|
17
|
+
/** A durable run is waiting for a human/webhook decision. */
|
|
18
|
+
export class ApprovalPendingError extends Error {
|
|
19
|
+
constructor(approvalId: any, { runId, prompt, step }?: {
|
|
20
|
+
runId?: null | undefined;
|
|
21
|
+
prompt?: null | undefined;
|
|
22
|
+
step?: number | undefined;
|
|
23
|
+
});
|
|
24
|
+
code: string;
|
|
25
|
+
approvalId: any;
|
|
26
|
+
runId: any;
|
|
27
|
+
prompt: any;
|
|
28
|
+
step: number;
|
|
29
|
+
}
|
|
30
|
+
/** A durable run is waiting until a future time. */
|
|
31
|
+
export class SchedulePendingError extends Error {
|
|
32
|
+
constructor(scheduleId: any, { runId, dueAt, step }?: {
|
|
33
|
+
runId?: null | undefined;
|
|
34
|
+
dueAt?: number | undefined;
|
|
35
|
+
step?: number | undefined;
|
|
36
|
+
});
|
|
37
|
+
code: string;
|
|
38
|
+
scheduleId: any;
|
|
39
|
+
runId: any;
|
|
40
|
+
dueAt: number;
|
|
41
|
+
step: number;
|
|
42
|
+
}
|
|
43
|
+
/** A resumed run targets a different flow version than the one it started with. */
|
|
44
|
+
export class FlowVersionMismatchError extends Error {
|
|
45
|
+
constructor(runId: any, expected: any, actual: any, message: any);
|
|
46
|
+
code: string;
|
|
47
|
+
runId: any;
|
|
48
|
+
expected: any;
|
|
49
|
+
actual: any;
|
|
50
|
+
}
|
|
51
|
+
/** A run exceeded a configured cost/token/latency/step budget. */
|
|
52
|
+
export class BudgetExceededError extends Error {
|
|
53
|
+
constructor(reasons: any[] | undefined, snapshot: {} | undefined, message: any);
|
|
54
|
+
code: string;
|
|
55
|
+
reasons: any[];
|
|
56
|
+
snapshot: {};
|
|
57
|
+
}
|