@unieai/rabi-tool-workflow 0.0.0-stage → 0.2.2-rc.5

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @unieai/rabi-tool-workflow
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Model-facing workflow tool: run a JavaScript orchestration script over ctx.workflowEngine
4
+
5
+ Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
+ not meant to be used on its own.
7
+
8
+ See LICENSE for the license and copyright of this package.
package/lib/index.js ADDED
@@ -0,0 +1,442 @@
1
+ import z from "@unieai/schemastery";
2
+ import { defineTool } from "@unieai/rabi-tools";
3
+ //#region lib/types/record.js
4
+ /**
5
+ * Live-progress mirror for background workflow runs: streams the engine's
6
+ * `workflow/phase`, `workflow/log`, and member lifecycle events into the
7
+ * owning job's output ring as `log` chunks — observer-only narration the
8
+ * model's `job_output` never renders — and keeps the job's live progress
9
+ * line on the current phase. Appends against a settled job log and drop
10
+ * inside the registry, so a straggling event after settlement is harmless.
11
+ * @module @unieai/rabi-tool-workflow/record
12
+ */
13
+ /**
14
+ * Create the run-to-ring mirror and subscribe the engine's live progress
15
+ * events for the runs it tracks.
16
+ * @param ctx - plugin context whose event bus carries the `workflow/*` events.
17
+ * @returns the mirror taps the tool wires around each background run.
18
+ */
19
+ function createWorkflowRecordMirror(ctx) {
20
+ const active = /* @__PURE__ */ new Map();
21
+ ctx.on("workflow/phase", (info, title) => {
22
+ const job = active.get(info.id);
23
+ if (job === void 0) return;
24
+ job.updateProgress(title);
25
+ job.append(`▸ ${title}\n`, { channel: "log" });
26
+ });
27
+ ctx.on("workflow/log", (info, message) => {
28
+ active.get(info.id)?.append(`${message}\n`, { channel: "log" });
29
+ });
30
+ ctx.on("workflow/agent-start", (info, agent) => {
31
+ active.get(info.id)?.append(`agent #${agent.seq} ${agent.label} started\n`, { channel: "log" });
32
+ });
33
+ ctx.on("workflow/agent-end", (info, agent) => {
34
+ active.get(info.id)?.append(`agent #${agent.seq} ${agent.outcome}\n`, { channel: "log" });
35
+ });
36
+ return {
37
+ start(runId, job) {
38
+ active.set(runId, job);
39
+ },
40
+ stop(runId) {
41
+ active.delete(runId);
42
+ }
43
+ };
44
+ }
45
+ //#endregion
46
+ //#region lib/types/index.js
47
+ /**
48
+ * The model-facing `workflow` tool: run a JavaScript orchestration script that fans out
49
+ * subagents, and return the script's final value. It owns the model-facing schema and run lifecycle; script
50
+ * parsing, execution, caps, and cancellation live behind `ctx.workflowEngine`
51
+ * (`@unieai/rabi-workflow`), so a hardened engine swaps in without touching what the model
52
+ * sees. Foreground execution awaits `run.result` and always disposes the run; non-completed reasons
53
+ * become tool errors. `run_in_background: true` instead registers the run as an owned `ctx.jobs` job
54
+ * and returns its id immediately — the job's output ring streams live progress, and the run's value
55
+ * arrives with the job's completion notice. Presentation is an args-only generic card
56
+ * titled from `meta.name`. Explicit-ask usage guidance is registered as the tool's own prompt
57
+ * section rather than deployment persona prose.
58
+ * @module @unieai/rabi-tool-workflow
59
+ */
60
+ const name = "tool-workflow";
61
+ const inject = [
62
+ "tools",
63
+ "workflowEngine",
64
+ "systemPrompt"
65
+ ];
66
+ const Config = z.object({
67
+ toolName: z.string().default("workflow"),
68
+ maxResultChars: z.natural().min(1).default(5e4),
69
+ enableRunInBackground: z.boolean().default(true)
70
+ });
71
+ /** Render a contained recording failure without trusting the thrown value. */
72
+ function renderRecordingError(error) {
73
+ try {
74
+ return String(error);
75
+ } catch {
76
+ return "[unrenderable thrown value]";
77
+ }
78
+ }
79
+ /**
80
+ * Project active top-level workflow runs into their parent Sessions without
81
+ * letting recording failure affect tool execution.
82
+ */
83
+ function createWorkflowRecorder(ctx) {
84
+ const active = /* @__PURE__ */ new Map();
85
+ const append = (session, type, data) => {
86
+ const appendRecord = session.append.bind(session);
87
+ try {
88
+ appendRecord(type, data);
89
+ return true;
90
+ } catch (error) {
91
+ ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`);
92
+ return false;
93
+ }
94
+ };
95
+ ctx.on("workflow/agent-start", (info, agent) => {
96
+ const session = active.get(info.id);
97
+ if (session === void 0) return;
98
+ if (!append(session, "tool-workflow/agent-start", {
99
+ runId: info.id,
100
+ seq: agent.seq,
101
+ label: agent.label,
102
+ ...agent.phase === void 0 ? {} : { phase: agent.phase },
103
+ childId: agent.childId
104
+ })) active.delete(info.id);
105
+ });
106
+ ctx.on("workflow/agent-end", (info, agent) => {
107
+ const session = active.get(info.id);
108
+ if (session === void 0) return;
109
+ if (!append(session, "tool-workflow/agent-end", {
110
+ runId: info.id,
111
+ seq: agent.seq,
112
+ outcome: agent.outcome
113
+ })) active.delete(info.id);
114
+ });
115
+ return {
116
+ start(session, run) {
117
+ if (append(session, "tool-workflow/run-start", {
118
+ runId: run.id,
119
+ name: run.meta.name
120
+ })) active.set(run.id, session);
121
+ },
122
+ finish(runId, stopReason) {
123
+ const session = active.get(runId);
124
+ if (session !== void 0) append(session, "tool-workflow/run-end", {
125
+ runId,
126
+ stopReason
127
+ });
128
+ active.delete(runId);
129
+ },
130
+ abandon: (runId) => {
131
+ active.delete(runId);
132
+ }
133
+ };
134
+ }
135
+ /**
136
+ * The script-authoring contract, embedded in the tool description: the hooks,
137
+ * their exact semantics, and the supported schema subset. Parameter-level
138
+ * rules live in the parameter descriptions.
139
+ */
140
+ const DESCRIPTION = `Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.
141
+
142
+ Script-body hooks:
143
+ - \`agent(prompt, opts?): Promise<any>\` — run one subagent to completion. Without \`opts.schema\` it resolves to the child's final text; with \`opts.schema\` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves \`null\` when the child fails (filter with \`.filter(Boolean)\`). Other opts: \`label\` (display), \`phase\` (progress group), and independent \`provider\`/\`model\` LLM target overrides.
144
+ - \`pipeline(items, ...stages): Promise<any[]>\` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives \`(prev, item, index)\`. A stage throw drops that ITEM to \`null\` and skips its remaining stages.
145
+ - \`parallel(thunks): Promise<any[]>\` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to \`null\`.
146
+ - \`phase(title)\` — start a progress phase; \`log(message)\` — narrate progress; \`args\` — the tool call's \`args\` input, verbatim.
147
+
148
+ Misused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing \`null\`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.`;
149
+ /** The pending-state card: a generic card titled by the workflow's meta name. */
150
+ function presentWorkflowCall(args) {
151
+ return {
152
+ card: "generic",
153
+ title: `workflow: ${args.meta.name}`,
154
+ rawInput: args.script
155
+ };
156
+ }
157
+ /** The completed-state card: keep the pending title; render the result content as-is. */
158
+ function presentWorkflowResult(args, result) {
159
+ return { card: "generic" };
160
+ }
161
+ /** A non-`completed` stop reason means the script did not finish cleanly. */
162
+ function stopReasonError(result) {
163
+ switch (result.stopReason) {
164
+ case "completed": return;
165
+ case "cancelled": return `workflow run was cancelled${result.error !== void 0 ? ` (${result.error})` : ""}`;
166
+ case "error": return `workflow run failed: ${result.error ?? "unknown error"}`;
167
+ /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
168
+ default: return `workflow run ended abnormally (${String(result.stopReason)})`;
169
+ }
170
+ }
171
+ /**
172
+ * Map a settled background run onto the job outcome vocabulary. A completed
173
+ * run carries the rendered return value as the job's result; a
174
+ * cancelled run leaves the detail to the registry's kill-reason merge (the
175
+ * cancel reason it forwarded is the same string); an errored run fails with
176
+ * the script's failure message.
177
+ */
178
+ function jobOutcomeOf(result, name, maxChars) {
179
+ switch (result.stopReason) {
180
+ case "completed": return {
181
+ status: "completed",
182
+ detail: `${result.agentsStarted} agent${result.agentsStarted === 1 ? "" : "s"}`,
183
+ result: renderResult(name, result.agentsStarted, result.value, maxChars)
184
+ };
185
+ case "cancelled": return { status: "killed" };
186
+ case "error": return {
187
+ status: "failed",
188
+ detail: result.error ?? "unknown error"
189
+ };
190
+ /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
191
+ default: return {
192
+ status: "failed",
193
+ detail: `workflow run ended abnormally (${String(result.stopReason)})`
194
+ };
195
+ }
196
+ }
197
+ /** Render the run's outcome text: the meta name, agent count, and the JSON value (capped). */
198
+ function renderResult(name, agentsStarted, value, maxChars) {
199
+ const rendered = JSON.stringify(value, null, 2);
200
+ const clipped = rendered.length > maxChars ? `${rendered.slice(0, maxChars)}\n… [truncated: ${rendered.length - maxChars} more characters]` : rendered;
201
+ return `workflow "${name}" completed (${agentsStarted} agent${agentsStarted === 1 ? "" : "s"}).\nReturn value:\n${clipped}`;
202
+ }
203
+ /**
204
+ * Register a background run as an owned job. The engine run is started
205
+ * inside the job starter with no tool-step signal — the run belongs to the
206
+ * job, so a registry kill or owner teardown is what cancels it — and its
207
+ * settlement is the job's settlement: dispose, stop the mirrors, then map the
208
+ * stop reason onto the job outcome (a completed run's rendered return value
209
+ * rides `result` to the model's first read after settlement).
210
+ * @param ctx - plugin context (engine, optional jobs registry, logger).
211
+ * @param args - the validated tool call.
212
+ * @param parent - the calling agent; owns the job.
213
+ * @param toolCall - creating invocation, including its root call.
214
+ * @param recordsRun - whether this top-level call records durable run events.
215
+ * @param deps - the tool's recorder/mirror taps and the render cap.
216
+ * @returns the background result for the tool's output schema.
217
+ */
218
+ function startBackgroundRun(ctx, args, parent, toolCall, recordsRun, deps) {
219
+ const jobs = ctx.get("jobs");
220
+ if (jobs === void 0) throw new Error("background jobs unavailable: load @unieai/rabi-jobs and @unieai/rabi-tool-jobs");
221
+ let run;
222
+ return {
223
+ kind: "background",
224
+ jobId: jobs.start({
225
+ kind: "workflow",
226
+ label: args.meta.name,
227
+ owner: parent.id,
228
+ toolCall,
229
+ run: (job) => {
230
+ run = ctx.workflowEngine.start({
231
+ script: args.script,
232
+ meta: args.meta,
233
+ ...args.args !== void 0 ? { args: args.args } : {},
234
+ parent
235
+ });
236
+ deps.mirror.start(run.id, job);
237
+ if (recordsRun) deps.recorder.start(parent.session, run);
238
+ return {
239
+ cancel: (reason) => {
240
+ run.cancel(reason ?? "background workflow job killed");
241
+ },
242
+ done: run.result.then(async (result) => {
243
+ try {
244
+ await run.dispose();
245
+ } catch (error) {
246
+ ctx.logger.warn(`background workflow run ${run.id} dispose failed: ${String(error)}`);
247
+ }
248
+ deps.mirror.stop(run.id);
249
+ if (recordsRun) {
250
+ deps.recorder.finish(run.id, result.stopReason);
251
+ deps.recorder.abandon(run.id);
252
+ }
253
+ return jobOutcomeOf(result, args.meta.name, deps.maxResultChars);
254
+ })
255
+ };
256
+ }
257
+ }),
258
+ runId: run.id
259
+ };
260
+ }
261
+ function apply(ctx, config) {
262
+ const { toolName, maxResultChars, enableRunInBackground } = config;
263
+ const recorder = createWorkflowRecorder(ctx);
264
+ const mirror = createWorkflowRecordMirror(ctx);
265
+ ctx.systemPrompt.section({
266
+ name: `tool:${toolName}`,
267
+ order: ctx.systemPrompt.getSectionOrder("TOOL_WORKFLOW"),
268
+ text: `Use the ${toolName} tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls.`
269
+ });
270
+ ctx.tools.register(defineTool({
271
+ name: toolName,
272
+ description: DESCRIPTION,
273
+ parameters: {
274
+ script: {
275
+ type: "string",
276
+ required: true,
277
+ description: "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return <value>`; the JSON-serializable value is this tool's result."
278
+ },
279
+ meta: {
280
+ type: "object",
281
+ additionalProperties: true,
282
+ required: true,
283
+ description: "The workflow identity as plain JSON, not code.",
284
+ properties: {
285
+ name: {
286
+ type: "string",
287
+ required: true,
288
+ description: "Short kebab-case workflow name."
289
+ },
290
+ description: {
291
+ type: "string",
292
+ required: true,
293
+ description: "One-line description of what the workflow does."
294
+ },
295
+ whenToUse: {
296
+ type: "string",
297
+ description: "Optional guidance on when this workflow applies."
298
+ },
299
+ phases: {
300
+ type: "array",
301
+ description: "Optional phase declarations matched by phase() calls.",
302
+ items: {
303
+ type: "object",
304
+ additionalProperties: true,
305
+ properties: {
306
+ title: {
307
+ type: "string",
308
+ required: true,
309
+ description: "The phase title phase() calls match by exact string."
310
+ },
311
+ detail: {
312
+ type: "string",
313
+ description: "Optional one-line description of the phase."
314
+ },
315
+ provider: {
316
+ type: "string",
317
+ description: "Optional provider override this phase is expected to use."
318
+ },
319
+ model: {
320
+ type: "string",
321
+ description: "Optional model override this phase is expected to use."
322
+ }
323
+ }
324
+ }
325
+ }
326
+ }
327
+ },
328
+ args: {
329
+ type: "object",
330
+ additionalProperties: true,
331
+ description: "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]})."
332
+ },
333
+ ...enableRunInBackground ? { run_in_background: {
334
+ type: "boolean",
335
+ description: "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice."
336
+ } } : {}
337
+ },
338
+ output: {
339
+ schema: { oneOf: [{
340
+ type: "object",
341
+ additionalProperties: false,
342
+ properties: {
343
+ kind: {
344
+ type: "string",
345
+ required: true,
346
+ const: "background"
347
+ },
348
+ jobId: {
349
+ type: "string",
350
+ required: true
351
+ },
352
+ runId: {
353
+ type: "string",
354
+ required: true
355
+ }
356
+ }
357
+ }, {
358
+ type: "object",
359
+ additionalProperties: false,
360
+ properties: {
361
+ kind: {
362
+ type: "string",
363
+ required: true,
364
+ const: "foreground"
365
+ },
366
+ runId: {
367
+ type: "string",
368
+ required: true
369
+ },
370
+ agentsStarted: {
371
+ type: "integer",
372
+ required: true
373
+ },
374
+ result: {
375
+ type: "json",
376
+ required: true
377
+ }
378
+ }
379
+ }] },
380
+ render: (args, value) => [{
381
+ type: "text",
382
+ text: value.kind === "background" ? `workflow "${args.meta.name}" started in the background as job ${value.jobId}. Its return value arrives with the completion notice; check on it with job_output, stop it with job_kill.` : renderResult(args.meta.name, value.agentsStarted, value.result, maxResultChars)
383
+ }]
384
+ },
385
+ async execute(args, exec) {
386
+ const parent = exec.agent;
387
+ if (!parent) throw new Error("workflow tool requires a calling agent (exec.agent was undefined)");
388
+ if (args.run_in_background === true) {
389
+ if (!enableRunInBackground) throw new Error("run_in_background is disabled for this tool");
390
+ return startBackgroundRun(ctx, args, parent, {
391
+ callId: exec.callId,
392
+ rootCallId: exec.rootCallId
393
+ }, exec.parent === void 0, {
394
+ recorder,
395
+ mirror,
396
+ maxResultChars
397
+ });
398
+ }
399
+ const run = ctx.workflowEngine.start({
400
+ script: args.script,
401
+ meta: args.meta,
402
+ ...args.args !== void 0 ? { args: args.args } : {},
403
+ parent,
404
+ signal: exec.signal
405
+ });
406
+ const recordsRun = exec.parent === void 0;
407
+ if (recordsRun) recorder.start(parent.session, run);
408
+ const onAbort = () => {
409
+ run.cancel("parent step aborted");
410
+ };
411
+ exec.signal.addEventListener("abort", onAbort, { once: true });
412
+ let result;
413
+ try {
414
+ result = await run.result;
415
+ const error = stopReasonError(result);
416
+ if (error !== void 0) throw new Error(error);
417
+ return {
418
+ kind: "foreground",
419
+ runId: run.id,
420
+ agentsStarted: result.agentsStarted,
421
+ result: result.value
422
+ };
423
+ } finally {
424
+ exec.signal.removeEventListener("abort", onAbort);
425
+ try {
426
+ await run.dispose();
427
+ if (recordsRun) {
428
+ /* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
429
+ if (result === void 0) throw new Error("workflow run settled without a result");
430
+ recorder.finish(run.id, result.stopReason);
431
+ }
432
+ } finally {
433
+ if (recordsRun) recorder.abandon(run.id);
434
+ }
435
+ }
436
+ },
437
+ presentCall: (args) => presentWorkflowCall(args),
438
+ presentResult: (args, result) => presentWorkflowResult(args, result)
439
+ }));
440
+ }
441
+ //#endregion
442
+ export { Config, apply, inject, name };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The model-facing `workflow` tool: run a JavaScript orchestration script that fans out
3
+ * subagents, and return the script's final value. It owns the model-facing schema and run lifecycle; script
4
+ * parsing, execution, caps, and cancellation live behind `ctx.workflowEngine`
5
+ * (`@unieai/rabi-workflow`), so a hardened engine swaps in without touching what the model
6
+ * sees. Foreground execution awaits `run.result` and always disposes the run; non-completed reasons
7
+ * become tool errors. `run_in_background: true` instead registers the run as an owned `ctx.jobs` job
8
+ * and returns its id immediately — the job's output ring streams live progress, and the run's value
9
+ * arrives with the job's completion notice. Presentation is an args-only generic card
10
+ * titled from `meta.name`. Explicit-ask usage guidance is registered as the tool's own prompt
11
+ * section rather than deployment persona prose.
12
+ * @module @unieai/rabi-tool-workflow
13
+ */
14
+ import type { Context } from '@unieai/cordis';
15
+ import z from '@unieai/schemastery';
16
+ declare module '@unieai/rabi-jobs' {
17
+ interface JobKindMap {
18
+ workflow: 'workflow';
19
+ }
20
+ }
21
+ export declare const name = "tool-workflow";
22
+ export declare const inject: string[];
23
+ /** Config: the model-facing tool name plus result rendering caps. */
24
+ export interface Config {
25
+ /** The model-facing tool name to register (default `workflow`). */
26
+ toolName?: string;
27
+ /** Rendered-result ceiling, in characters: a longer JSON value is truncated with a notice (default 50000). */
28
+ maxResultChars?: number;
29
+ /**
30
+ * Expose `run_in_background` (default true); disabled calls are also
31
+ * rejected. A background run needs a live `ctx.jobs` registry with a
32
+ * controller serving the caller (`rabi-jobs-local` plus `rabi-tool-jobs` in
33
+ * the shipped composition); without one the call fails with the missing
34
+ * piece named.
35
+ */
36
+ enableRunInBackground?: boolean;
37
+ }
38
+ export declare const Config: z<Config>;
39
+ export declare function apply(ctx: Context, config: Config): void;
40
+ //# sourceMappingURL=index.d.ts.map