@unieai/rabi-tool-workflow 0.2.1-rc.3 → 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/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Workflow-Tools",
4
+ "description": "Lassen Sie die KI JavaScript-Skripte schreiben und ausführen, um mehrere Werkzeugvorgänge zu orchestrieren."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Herramientas de flujo de trabajo",
4
+ "description": "Deje que la IA escriba y ejecute scripts JavaScript para organizar múltiples operaciones de herramientas."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Outils de flux de travail",
4
+ "description": "Laissez l'IA écrire et exécuter des scripts JavaScript pour orchestrer plusieurs opérations d'outils."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "ワークフローツール",
4
+ "description": "AI が JavaScript スクリプトを作成、実行し、複数のツール操作を組み合わせられます。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Ferramentas de fluxo de trabalho",
4
+ "description": "Deixe a IA escrever e executar scripts JavaScript para orquestrar várias operações de ferramentas."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Инструменты рабочего процесса",
4
+ "description": "Позвольте ИИ писать и запускать сценарии JavaScript для управления несколькими операциями инструментов."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-tool-workflow",
3
3
  "description": "Model-facing workflow tool: run a JavaScript orchestration script over ctx.workflowEngine",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -26,20 +26,23 @@
26
26
  "lib/index.js",
27
27
  "lib/types/**/*.js",
28
28
  "lib/types/**/*.d.ts",
29
+ "lib/types/**/*.d.ts.map",
30
+ "lib/**/*.js.map",
31
+ "src",
29
32
  "README.md"
30
33
  ],
31
34
  "license": "MIT",
32
35
  "peerDependencies": {
33
- "@unieai/cordis": "4.0.5",
34
- "@unieai/rabi-agent": "0.2.1-rc.3",
35
- "@unieai/rabi-jobs": "0.2.1-rc.3",
36
- "@unieai/rabi-llm": "0.2.1-rc.3",
37
- "@unieai/rabi-session": "0.2.1-rc.3",
38
- "@unieai/rabi-system-prompt": "0.2.1-rc.3",
39
- "@unieai/rabi-tools": "0.2.1-rc.3",
40
- "@unieai/rabi-workflow": "0.2.1-rc.3"
36
+ "@unieai/cordis": "4.1.0",
37
+ "@unieai/rabi-agent": "0.2.2-rc.5",
38
+ "@unieai/rabi-jobs": "0.2.2-rc.5",
39
+ "@unieai/rabi-llm": "0.2.2-rc.5",
40
+ "@unieai/rabi-session": "0.2.2-rc.5",
41
+ "@unieai/rabi-system-prompt": "0.2.2-rc.5",
42
+ "@unieai/rabi-tools": "0.2.2-rc.5",
43
+ "@unieai/rabi-workflow": "0.2.2-rc.5"
41
44
  },
42
45
  "dependencies": {
43
- "@unieai/schemastery": "3.18.5"
46
+ "@unieai/schemastery": "3.19.0"
44
47
  }
45
48
  }
package/src/index.ts ADDED
@@ -0,0 +1,487 @@
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
+
15
+ import type { Context } from '@unieai/cordis'
16
+ import z from '@unieai/schemastery'
17
+ import { defineTool } from '@unieai/rabi-tools'
18
+ import type { ToolCallView, ToolResultView } from '@unieai/rabi-tools'
19
+ import type { Agent } from '@unieai/rabi-agent'
20
+ import type { ContentBlock } from '@unieai/rabi-llm'
21
+ import type { JobId, JobOutcome, JobToolCall } from '@unieai/rabi-jobs'
22
+ import type { Session, SessionEventMap } from '@unieai/rabi-session'
23
+ import type { JsonValue } from '@unieai/rabi-util-values'
24
+ import type {
25
+ WorkflowResult, WorkflowRun, WorkflowRunId, WorkflowStopReason,
26
+ } from '@unieai/rabi-workflow'
27
+ import { createWorkflowRecordMirror } from './record.ts'
28
+ import type { WorkflowRecordMirror } from './record.ts'
29
+ import type {
30
+ ToolWorkflowAgentEndData, ToolWorkflowAgentStartData,
31
+ ToolWorkflowRunEndData, ToolWorkflowRunStartData,
32
+ } from './types.ts'
33
+
34
+ declare module '@unieai/rabi-jobs' {
35
+ interface JobKindMap {
36
+ workflow: 'workflow'
37
+ }
38
+ }
39
+
40
+ export const name = 'tool-workflow'
41
+ export const inject = ['tools', 'workflowEngine', 'systemPrompt']
42
+
43
+ /** Config: the model-facing tool name plus result rendering caps. */
44
+ export interface Config {
45
+ /** The model-facing tool name to register (default `workflow`). */
46
+ toolName?: string
47
+ /** Rendered-result ceiling, in characters: a longer JSON value is truncated with a notice (default 50000). */
48
+ maxResultChars?: number
49
+ /**
50
+ * Expose `run_in_background` (default true); disabled calls are also
51
+ * rejected. A background run needs a live `ctx.jobs` registry with a
52
+ * controller serving the caller (`rabi-jobs-local` plus `rabi-tool-jobs` in
53
+ * the shipped composition); without one the call fails with the missing
54
+ * piece named.
55
+ */
56
+ enableRunInBackground?: boolean
57
+ }
58
+
59
+ export const Config: z<Config> = z.object({
60
+ toolName: z.string().default('workflow'),
61
+ maxResultChars: z.natural().min(1).default(50_000),
62
+ enableRunInBackground: z.boolean().default(true),
63
+ })
64
+
65
+ type ResolvedConfig = Required<Config>
66
+
67
+ interface WorkflowRecorder {
68
+ start(session: Session, run: WorkflowRun): void
69
+ finish(runId: WorkflowRunId, stopReason: WorkflowStopReason): void
70
+ abandon(runId: WorkflowRunId): void
71
+ }
72
+
73
+ interface ToolWorkflowRecordEventMap {
74
+ 'tool-workflow/run-start': ToolWorkflowRunStartData
75
+ 'tool-workflow/agent-start': ToolWorkflowAgentStartData
76
+ 'tool-workflow/agent-end': ToolWorkflowAgentEndData
77
+ 'tool-workflow/run-end': ToolWorkflowRunEndData
78
+ }
79
+
80
+ /** Render a contained recording failure without trusting the thrown value. */
81
+ function renderRecordingError(error: unknown): string {
82
+ try {
83
+ return String(error)
84
+ } catch {
85
+ return '[unrenderable thrown value]'
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Project active top-level workflow runs into their parent Sessions without
91
+ * letting recording failure affect tool execution.
92
+ */
93
+ function createWorkflowRecorder(ctx: Context): WorkflowRecorder {
94
+ const active = new Map<WorkflowRunId, Session>()
95
+ const append = <Type extends keyof ToolWorkflowRecordEventMap>(
96
+ session: Session,
97
+ type: Type,
98
+ data: SessionEventMap[Type],
99
+ ): boolean => {
100
+ // These four package-owned events are all log-only. Narrowing the generic
101
+ // append face here discharges Session.append's conditional options tuple.
102
+ const appendRecord = session.append.bind(session) as <Event extends keyof ToolWorkflowRecordEventMap>(
103
+ event: Event,
104
+ value: SessionEventMap[Event],
105
+ ) => void
106
+ try {
107
+ appendRecord(type, data)
108
+ return true
109
+ } catch (error: unknown) {
110
+ ctx.logger.warn(`tool-workflow: disabled durable record after ${type} append failed: ${renderRecordingError(error)}`)
111
+ return false
112
+ }
113
+ }
114
+
115
+ ctx.on('workflow/agent-start', (info, agent) => {
116
+ const session = active.get(info.id)
117
+ if (session === undefined) return
118
+ const data: ToolWorkflowAgentStartData = {
119
+ runId: info.id,
120
+ seq: agent.seq,
121
+ label: agent.label,
122
+ ...agent.phase === undefined ? {} : { phase: agent.phase },
123
+ childId: agent.childId,
124
+ }
125
+ if (!append(session, 'tool-workflow/agent-start', data)) active.delete(info.id)
126
+ })
127
+ ctx.on('workflow/agent-end', (info, agent) => {
128
+ const session = active.get(info.id)
129
+ if (session === undefined) return
130
+ const data: ToolWorkflowAgentEndData = {
131
+ runId: info.id,
132
+ seq: agent.seq,
133
+ outcome: agent.outcome,
134
+ }
135
+ if (!append(session, 'tool-workflow/agent-end', data)) active.delete(info.id)
136
+ })
137
+
138
+ return {
139
+ start(session, run) {
140
+ if (append(session, 'tool-workflow/run-start', { runId: run.id, name: run.meta.name })) {
141
+ active.set(run.id, session)
142
+ }
143
+ },
144
+ finish(runId, stopReason) {
145
+ const session = active.get(runId)
146
+ if (session !== undefined) append(session, 'tool-workflow/run-end', { runId, stopReason })
147
+ active.delete(runId)
148
+ },
149
+ abandon: (runId) => { active.delete(runId) },
150
+ }
151
+ }
152
+
153
+ /**
154
+ * The script-authoring contract, embedded in the tool description: the hooks,
155
+ * their exact semantics, and the supported schema subset. Parameter-level
156
+ * rules live in the parameter descriptions.
157
+ */
158
+ 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.
159
+
160
+ Script-body hooks:
161
+ - \`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.
162
+ - \`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.
163
+ - \`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\`.
164
+ - \`phase(title)\` — start a progress phase; \`log(message)\` — narrate progress; \`args\` — the tool call's \`args\` input, verbatim.
165
+
166
+ 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.`
167
+
168
+ type WorkflowCallArgs = {
169
+ script: string
170
+ meta: {
171
+ name: string
172
+ description: string
173
+ whenToUse?: string
174
+ phases?: { title: string; detail?: string; provider?: string; model?: string }[]
175
+ }
176
+ args?: Record<string, unknown>
177
+ run_in_background?: boolean
178
+ }
179
+
180
+ /** The pending-state card: a generic card titled by the workflow's meta name. */
181
+ function presentWorkflowCall(args: WorkflowCallArgs): ToolCallView {
182
+ return {
183
+ card: 'generic',
184
+ title: `workflow: ${args.meta.name}`,
185
+ rawInput: args.script,
186
+ }
187
+ }
188
+
189
+ /** The completed-state card: keep the pending title; render the result content as-is. */
190
+ function presentWorkflowResult(args: WorkflowCallArgs, result: { content: ContentBlock[]; isError: boolean }): ToolResultView {
191
+ void args
192
+ void result
193
+ return { card: 'generic' }
194
+ }
195
+
196
+ /** A non-`completed` stop reason means the script did not finish cleanly. */
197
+ function stopReasonError(result: WorkflowResult): string | undefined {
198
+ switch (result.stopReason) {
199
+ case 'completed':
200
+ return undefined
201
+ case 'cancelled':
202
+ return `workflow run was cancelled${result.error !== undefined ? ` (${result.error})` : ''}`
203
+ case 'error':
204
+ return `workflow run failed: ${result.error ?? 'unknown error'}`
205
+ /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
206
+ default:
207
+ return `workflow run ended abnormally (${String(result.stopReason satisfies never)})`
208
+ /* v8 ignore stop */
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Map a settled background run onto the job outcome vocabulary. A completed
214
+ * run carries the rendered return value as the job's result; a
215
+ * cancelled run leaves the detail to the registry's kill-reason merge (the
216
+ * cancel reason it forwarded is the same string); an errored run fails with
217
+ * the script's failure message.
218
+ */
219
+ function jobOutcomeOf(result: WorkflowResult, name: string, maxChars: number): JobOutcome {
220
+ switch (result.stopReason) {
221
+ case 'completed':
222
+ return {
223
+ status: 'completed',
224
+ detail: `${result.agentsStarted} agent${result.agentsStarted === 1 ? '' : 's'}`,
225
+ result: renderResult(name, result.agentsStarted, result.value as JsonValue, maxChars),
226
+ }
227
+ case 'cancelled':
228
+ return { status: 'killed' }
229
+ case 'error':
230
+ return { status: 'failed', detail: result.error ?? 'unknown error' }
231
+ /* v8 ignore start -- defensive: WorkflowStopReason is a closed union, exhaustive by construction; a future variant fails here loudly */
232
+ default:
233
+ return { status: 'failed', detail: `workflow run ended abnormally (${String(result.stopReason satisfies never)})` }
234
+ /* v8 ignore stop */
235
+ }
236
+ }
237
+
238
+ /** Render the run's outcome text: the meta name, agent count, and the JSON value (capped). */
239
+ function renderResult(name: string, agentsStarted: number, value: JsonValue, maxChars: number): string {
240
+ // The engine returns JSON data (null for a valueless script), so stringify never yields undefined.
241
+ const rendered = JSON.stringify(value, null, 2)
242
+ const clipped = rendered.length > maxChars
243
+ ? `${rendered.slice(0, maxChars)}\n… [truncated: ${rendered.length - maxChars} more characters]`
244
+ : rendered
245
+ return `workflow "${name}" completed (${agentsStarted} agent${agentsStarted === 1 ? '' : 's'}).\nReturn value:\n${clipped}`
246
+ }
247
+
248
+ /**
249
+ * Register a background run as an owned job. The engine run is started
250
+ * inside the job starter with no tool-step signal — the run belongs to the
251
+ * job, so a registry kill or owner teardown is what cancels it — and its
252
+ * settlement is the job's settlement: dispose, stop the mirrors, then map the
253
+ * stop reason onto the job outcome (a completed run's rendered return value
254
+ * rides `result` to the model's first read after settlement).
255
+ * @param ctx - plugin context (engine, optional jobs registry, logger).
256
+ * @param args - the validated tool call.
257
+ * @param parent - the calling agent; owns the job.
258
+ * @param toolCall - creating invocation, including its root call.
259
+ * @param recordsRun - whether this top-level call records durable run events.
260
+ * @param deps - the tool's recorder/mirror taps and the render cap.
261
+ * @returns the background result for the tool's output schema.
262
+ */
263
+ function startBackgroundRun(
264
+ ctx: Context,
265
+ args: WorkflowCallArgs,
266
+ parent: Agent,
267
+ toolCall: JobToolCall,
268
+ recordsRun: boolean,
269
+ deps: { recorder: WorkflowRecorder; mirror: WorkflowRecordMirror; maxResultChars: number },
270
+ ): { kind: 'background'; jobId: JobId; runId: WorkflowRunId } {
271
+ const jobs = ctx.get('jobs')
272
+ if (jobs === undefined) {
273
+ throw new Error('background jobs unavailable: load @unieai/rabi-jobs and @unieai/rabi-tool-jobs')
274
+ }
275
+ let run!: WorkflowRun
276
+ const jobId = jobs.start({
277
+ kind: 'workflow',
278
+ label: args.meta.name,
279
+ owner: parent.id,
280
+ toolCall,
281
+ run: (job) => {
282
+ // A synchronous engine rejection (META_INVALID/SCRIPT_PARSE) propagates
283
+ // out of the starter, so the registry registers nothing and the model
284
+ // sees the violation list as an ordinary tool error.
285
+ run = ctx.workflowEngine.start({
286
+ script: args.script,
287
+ meta: args.meta,
288
+ ...args.args !== undefined ? { args: args.args } : {},
289
+ parent,
290
+ })
291
+ deps.mirror.start(run.id, job)
292
+ if (recordsRun) deps.recorder.start(parent.session, run)
293
+ const done = run.result.then(async (result): Promise<JobOutcome> => {
294
+ try {
295
+ // Keep member listeners alive through disposal: an engine may
296
+ // synthesize cancelled member endings while reaching quiescence.
297
+ await run.dispose()
298
+ } catch (error: unknown) {
299
+ // done must not reject; a failed disposal still has a settled result to report.
300
+ ctx.logger.warn(`background workflow run ${run.id} dispose failed: ${String(error)}`)
301
+ }
302
+ deps.mirror.stop(run.id)
303
+ if (recordsRun) {
304
+ deps.recorder.finish(run.id, result.stopReason)
305
+ deps.recorder.abandon(run.id)
306
+ }
307
+ return jobOutcomeOf(result, args.meta.name, deps.maxResultChars)
308
+ })
309
+ return {
310
+ cancel: (reason?: string) => { run.cancel(reason ?? 'background workflow job killed') },
311
+ done,
312
+ }
313
+ },
314
+ })
315
+ return { kind: 'background' as const, jobId, runId: run.id }
316
+ }
317
+
318
+ export function apply(ctx: Context, config: Config): void {
319
+ // schemastery (the exported Config schema) has already filled the defaulted
320
+ // fields; the assertion records that resolution, not a hidden fallback.
321
+ const { toolName, maxResultChars, enableRunInBackground } = config as ResolvedConfig
322
+ const recorder = createWorkflowRecorder(ctx)
323
+ const mirror = createWorkflowRecordMirror(ctx)
324
+ // Usage policy ships with the tool (the master convention: tool guidance
325
+ // lives in tool plugins as prompt sections, not in the deployment persona).
326
+ ctx.systemPrompt.section({
327
+ name: `tool:${toolName}`,
328
+ order: ctx.systemPrompt.getSectionOrder('TOOL_WORKFLOW'),
329
+ 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.`,
330
+ })
331
+ ctx.tools.register(defineTool({
332
+ name: toolName,
333
+ description: DESCRIPTION,
334
+ parameters: {
335
+ script: {
336
+ type: 'string',
337
+ required: true,
338
+ description: 'The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. '
339
+ + 'End with `return <value>`; the JSON-serializable value is this tool\'s result.',
340
+ },
341
+ meta: {
342
+ type: 'object',
343
+ additionalProperties: true,
344
+ required: true,
345
+ description: 'The workflow identity as plain JSON, not code.',
346
+ properties: {
347
+ name: { type: 'string', required: true, description: 'Short kebab-case workflow name.' },
348
+ description: { type: 'string', required: true, description: 'One-line description of what the workflow does.' },
349
+ whenToUse: { type: 'string', description: 'Optional guidance on when this workflow applies.' },
350
+ phases: {
351
+ type: 'array',
352
+ description: 'Optional phase declarations matched by phase() calls.',
353
+ items: {
354
+ type: 'object',
355
+ additionalProperties: true,
356
+ properties: {
357
+ title: { type: 'string', required: true, description: 'The phase title phase() calls match by exact string.' },
358
+ detail: { type: 'string', description: 'Optional one-line description of the phase.' },
359
+ provider: { type: 'string', description: 'Optional provider override this phase is expected to use.' },
360
+ model: { type: 'string', description: 'Optional model override this phase is expected to use.' },
361
+ },
362
+ },
363
+ },
364
+ },
365
+ },
366
+ args: {
367
+ type: 'object',
368
+ additionalProperties: true,
369
+ description: 'Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {"files": [...]}).',
370
+ },
371
+ ...enableRunInBackground ? {
372
+ run_in_background: {
373
+ type: 'boolean' as const,
374
+ description: 'Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice.',
375
+ },
376
+ } : {},
377
+ },
378
+ output: {
379
+ schema: {
380
+ oneOf: [
381
+ {
382
+ type: 'object',
383
+ additionalProperties: false,
384
+ properties: {
385
+ kind: { type: 'string', required: true, const: 'background' },
386
+ jobId: { type: 'string', required: true },
387
+ runId: { type: 'string', required: true },
388
+ },
389
+ },
390
+ {
391
+ type: 'object',
392
+ additionalProperties: false,
393
+ properties: {
394
+ kind: { type: 'string', required: true, const: 'foreground' },
395
+ runId: { type: 'string', required: true },
396
+ agentsStarted: { type: 'integer', required: true },
397
+ result: { type: 'json', required: true },
398
+ },
399
+ },
400
+ ],
401
+ },
402
+ render: (args, value) => [{
403
+ type: 'text',
404
+ text: value.kind === 'background'
405
+ ? `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.`
406
+ : renderResult(args.meta.name, value.agentsStarted, value.result, maxResultChars),
407
+ }],
408
+ },
409
+ async execute(args, exec) {
410
+ const parent = exec.agent
411
+ if (!parent) {
412
+ // The loop sets `exec.agent` for every model-driven call; its absence
413
+ // means a non-agent caller invoked the tool directly, which has no
414
+ // parent to attribute the children to. Fail loud rather than guess.
415
+ throw new Error('workflow tool requires a calling agent (exec.agent was undefined)')
416
+ }
417
+ if (args.run_in_background === true) {
418
+ if (!enableRunInBackground) {
419
+ throw new Error('run_in_background is disabled for this tool')
420
+ }
421
+ // No pre-abort check here, unlike bash/pwsh: ToolRuntime re-reads the
422
+ // caller signal right before execute(), and this branch reaches
423
+ // jobs.start synchronously from there. The shell tools await a
424
+ // sandbox escalation approval before registering, which is the window
425
+ // their check covers.
426
+ return startBackgroundRun(ctx, args, parent, { callId: exec.callId, rootCallId: exec.rootCallId }, exec.parent === undefined, {
427
+ recorder,
428
+ mirror,
429
+ maxResultChars,
430
+ })
431
+ }
432
+
433
+ // Meta/body validation failures (META_INVALID/SCRIPT_PARSE) throw
434
+ // synchronously here and become isError results via the registry — the
435
+ // model sees the violation list and can correct the call.
436
+ const run = ctx.workflowEngine.start({
437
+ script: args.script,
438
+ meta: args.meta,
439
+ ...args.args !== undefined ? { args: args.args } : {},
440
+ parent,
441
+ signal: exec.signal,
442
+ })
443
+ const recordsRun = exec.parent === undefined
444
+ // The engine publishes member events after start() returns and this run record is active.
445
+ if (recordsRun) recorder.start(parent.session, run)
446
+
447
+ // Bridge the tool's abort signal to the run: if the parent step is aborted while the
448
+ // script is in flight, cancel the whole run. The signal also enters the engine directly, but
449
+ // this local bridge preserves the tool contract even if an implementation ignores it.
450
+ const onAbort = (): void => { run.cancel('parent step aborted') }
451
+ exec.signal.addEventListener('abort', onAbort, { once: true })
452
+
453
+ let result: WorkflowResult | undefined
454
+ try {
455
+ result = await run.result
456
+ const error = stopReasonError(result)
457
+ if (error !== undefined) {
458
+ // Map a non-clean finish to an isError result (the registry turns a
459
+ // throw into an isError). Report the reason, not partial output.
460
+ throw new Error(error)
461
+ }
462
+ return {
463
+ kind: 'foreground' as const,
464
+ runId: run.id,
465
+ agentsStarted: result.agentsStarted,
466
+ result: result.value as JsonValue,
467
+ }
468
+ } finally {
469
+ exec.signal.removeEventListener('abort', onAbort)
470
+ try {
471
+ // Keep member listeners alive through disposal: an engine may
472
+ // synthesize cancelled member endings while reaching quiescence.
473
+ await run.dispose()
474
+ if (recordsRun) {
475
+ /* v8 ignore next -- WorkflowRun.result never rejects by contract, so result is assigned before finally. */
476
+ if (result === undefined) throw new Error('workflow run settled without a result')
477
+ recorder.finish(run.id, result.stopReason)
478
+ }
479
+ } finally {
480
+ if (recordsRun) recorder.abandon(run.id)
481
+ }
482
+ }
483
+ },
484
+ presentCall: args => presentWorkflowCall(args),
485
+ presentResult: (args, result) => presentWorkflowResult(args, result),
486
+ }))
487
+ }
package/src/record.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Live-progress mirror for background workflow runs: streams the engine's
3
+ * `workflow/phase`, `workflow/log`, and member lifecycle events into the
4
+ * owning job's output ring as `log` chunks — observer-only narration the
5
+ * model's `job_output` never renders — and keeps the job's live progress
6
+ * line on the current phase. Appends against a settled job log and drop
7
+ * inside the registry, so a straggling event after settlement is harmless.
8
+ * @module @unieai/rabi-tool-workflow/record
9
+ */
10
+
11
+ import type { Context } from '@unieai/cordis'
12
+ import type { JobHandle } from '@unieai/rabi-jobs'
13
+ import type { WorkflowRunId } from '@unieai/rabi-workflow'
14
+
15
+ /** Job-ring taps for the background runs the tool tracks. */
16
+ export interface WorkflowRecordMirror {
17
+ /**
18
+ * Route a run's progress events into a job's ring. Call once per background
19
+ * run, from the job starter, before the worker publishes its first event.
20
+ * @param runId - the started run.
21
+ * @param job - the owning job's producer face.
22
+ */
23
+ start(runId: WorkflowRunId, job: JobHandle): void
24
+ /**
25
+ * Stop routing a settled or abandoned run. Idempotent.
26
+ * @param runId - the run to drop.
27
+ */
28
+ stop(runId: WorkflowRunId): void
29
+ }
30
+
31
+ /**
32
+ * Create the run-to-ring mirror and subscribe the engine's live progress
33
+ * events for the runs it tracks.
34
+ * @param ctx - plugin context whose event bus carries the `workflow/*` events.
35
+ * @returns the mirror taps the tool wires around each background run.
36
+ */
37
+ export function createWorkflowRecordMirror(ctx: Context): WorkflowRecordMirror {
38
+ const active = new Map<WorkflowRunId, JobHandle>()
39
+
40
+ ctx.on('workflow/phase', (info, title) => {
41
+ const job = active.get(info.id)
42
+ if (job === undefined) return
43
+ job.updateProgress(title)
44
+ job.append(`▸ ${title}\n`, { channel: 'log' })
45
+ })
46
+ ctx.on('workflow/log', (info, message) => {
47
+ active.get(info.id)?.append(`${message}\n`, { channel: 'log' })
48
+ })
49
+ ctx.on('workflow/agent-start', (info, agent) => {
50
+ active.get(info.id)?.append(`agent #${agent.seq} ${agent.label} started\n`, { channel: 'log' })
51
+ })
52
+ ctx.on('workflow/agent-end', (info, agent) => {
53
+ active.get(info.id)?.append(`agent #${agent.seq} ${agent.outcome}\n`, { channel: 'log' })
54
+ })
55
+
56
+ return {
57
+ start(runId, job) {
58
+ active.set(runId, job)
59
+ },
60
+ stop(runId) {
61
+ active.delete(runId)
62
+ },
63
+ }
64
+ }
package/src/types.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Browser-safe durable workflow-record events written by the model-facing
3
+ * workflow tool into its calling parent Session.
4
+ *
5
+ * @module @unieai/rabi-tool-workflow/types
6
+ */
7
+
8
+ import type { SessionId } from '@unieai/rabi-session/types'
9
+ import type {
10
+ WorkflowAgentOutcome, WorkflowRunId, WorkflowStopReason,
11
+ } from '@unieai/rabi-workflow/types'
12
+
13
+ /** Opens one durable top-level workflow run record. */
14
+ export interface ToolWorkflowRunStartData {
15
+ readonly runId: WorkflowRunId
16
+ readonly name: string
17
+ }
18
+
19
+ /** Records one workflow member after its child Session is published. */
20
+ export interface ToolWorkflowAgentStartData {
21
+ readonly runId: WorkflowRunId
22
+ readonly seq: number
23
+ readonly label: string
24
+ readonly phase?: string
25
+ readonly childId: SessionId
26
+ }
27
+
28
+ /** Settles one previously started workflow member. */
29
+ export interface ToolWorkflowAgentEndData {
30
+ readonly runId: WorkflowRunId
31
+ readonly seq: number
32
+ readonly outcome: WorkflowAgentOutcome
33
+ }
34
+
35
+ /** Settles one workflow run after its live resources reach quiescence. */
36
+ export interface ToolWorkflowRunEndData {
37
+ readonly runId: WorkflowRunId
38
+ readonly stopReason: WorkflowStopReason
39
+ }
40
+
41
+ declare module '@unieai/rabi-session/types' {
42
+ interface SessionEventMap {
43
+ /**
44
+ * Opens one top-level workflow record.
45
+ * @param data - stable run identity and display name.
46
+ */
47
+ 'tool-workflow/run-start': ToolWorkflowRunStartData
48
+ /**
49
+ * Records one published workflow member.
50
+ * @param data - run identity, member sequence, display identity, and child Session.
51
+ */
52
+ 'tool-workflow/agent-start': ToolWorkflowAgentStartData
53
+ /**
54
+ * Records one member settlement.
55
+ * @param data - run identity, paired member sequence, and outcome.
56
+ */
57
+ 'tool-workflow/agent-end': ToolWorkflowAgentEndData
58
+ /**
59
+ * Closes one workflow record after cleanup.
60
+ * @param data - stable run identity and terminal reason.
61
+ */
62
+ 'tool-workflow/run-end': ToolWorkflowRunEndData
63
+ }
64
+ }