diff --git a/docs/CLOUD.md b/docs/CLOUD.md index f3ade962f..6479ffd1e 100644 --- a/docs/CLOUD.md +++ b/docs/CLOUD.md @@ -163,6 +163,14 @@ same history as your hosted ones — readable afterwards through `flows runs`, `flows status --cloud` and `flows logs`, which until now only answered for runs Cloud had launched. +An authored flow composed with `use` and `f.dispatch` still occupies one +dashboard run. The mirror follows child journals named by the root's authored +index and uploads journal-derived labels and dependency edges, so parent steps, +qualified child steps, and dispatch receipts render as one flattened connected +DAG both while the run is live and after its final report. Internal authored +`complete-N` receipts remain durable journal evidence and are intentionally not +shown as work nodes. + ### Why it is opt-in Because it is the richer view, it is also the one that *stores* all of that. diff --git a/docs/EVENT-AWAIT.md b/docs/EVENT-AWAIT.md index 63721c291..0c4acf79a 100644 --- a/docs/EVENT-AWAIT.md +++ b/docs/EVENT-AWAIT.md @@ -50,8 +50,8 @@ Verified against `main` at `85e7e372`: running a fix step is lost. - **The authored `Ctx` has no `on`.** `packages/surface/src/context.ts` exposes `human`, `dispatch`, and `done`; `human` lowers to `wait.human` - (SURFACE.md §5 *Human gates*); the authored executor still throws - `unsupported_verb` for `dispatch`. + (SURFACE.md §5 *Human gates*). `dispatch` runs a direct static `use` child; + it does not provide the durable buffered event subscription designed here. ## 3. Surface diff --git a/docs/RFC-0002-callable-flow-tools.md b/docs/RFC-0002-callable-flow-tools.md index 89b54bd61..4b720b374 100644 --- a/docs/RFC-0002-callable-flow-tools.md +++ b/docs/RFC-0002-callable-flow-tools.md @@ -296,16 +296,17 @@ authored `flow` has a validated public input schema until the author supplies one (or it is generated and reviewed from a trusted source). An input schema must be snapshot into the built bundle and verified again at admission. -**Nested calls:** do not allow arbitrary Flow Tools to call arbitrary Flow -Tools in MVP. `f.dispatch` is a promising composition surface but is not a -publicly implemented durable child-flow capability in the current SDK. Phase 2 -may allow only statically declared child digests with a parent-issued, -attenuated capability token, a depth limit (recommend 3), a descendant budget -reservation, a run-tree concurrency limit, and cycle detection over flow -digests. A child may never inherit wider credentials, write scope, human -approval authority, or the ability to alter its parent’s gates. A model calling -the external tool endpoint from inside an agent step is prohibited by default; -it bypasses those controls and makes recursion unaccounted for. +**Nested calls:** do not allow arbitrary public Flow Tools to call arbitrary +Flow Tools in MVP. The SDK now implements the narrower authored-flow +`f.dispatch` slice: a child must be a direct static `use`, the loader rejects +path cycles and ambiguous child names, depth is capped at three, capabilities +attenuate, and the root budget and worker pool are shared. Children cannot +declare their own budget or acquire human approval authority in this release. +This is durable local/hosted run-tree composition, not a public catalog call, +an immutable child-digest admission contract, or a cross-run capability token. +A model calling the external tool endpoint from inside an agent step remains +prohibited by default; it bypasses those controls and makes recursion +unaccounted for. ## What exists today, and the exact gap @@ -316,11 +317,12 @@ it bypasses those controls and makes recursion unaccounted for. `run.cancel` / `run.resume` protocol verbs. See `kernel/relayflowd-core/src/{journal.rs,machine.rs,retry.rs,state.rs}` and `kernel/relayflowd/src/{engine.rs,server.rs}`. -* The authoring surface has `run`, `llm`, `agent`, `human`, `done`, headers for - budgets, identity, tools and workspace, and a TypeScript flow loader. See - `packages/surface/src/{context.ts,flow.ts}`. `f.human` is presently a - yes/no wait and `Ctx.dispatch` is typed but lacks a corresponding SDK - implementation. +* The authoring surface has `run`, `llm`, `agent`, `human`, `dispatch`, `done`, + headers for budgets, identity, tools, workspace and static `use`, and a + TypeScript flow loader. See `packages/surface/src/{context.ts,flow.ts}` and + `packages/sdk/src/{authored-flow-loader.ts,authored-flow-executor.ts}`. + `f.dispatch` executes a direct declared child in the same durable run tree; + it is intentionally narrower than a public Flow Tool invocation. * Declarative step outputs can be gated with JSON Schema; SDK and kernel share bounded schema validation. See `packages/sdk/src/{json-schema.ts, json-schema-bound.ts,output-schema.ts,validate.ts}` and @@ -381,8 +383,9 @@ it bypasses those controls and makes recursion unaccounted for. spend guarantee in that state. 8. Existing evidence/status is strong for a run but lacks a policy-controlled, tenant-safe external evidence envelope and artifact retention/ACL contract. -9. `f.dispatch`, general typed human forms, public channels, and durable - cross-run composition are not ready to support arbitrary nested tool calls. +9. Authored `f.dispatch` does not make general typed human forms, public + channels, immutable child-digest admission, or durable cross-run/public-tool + composition ready for arbitrary nested tool calls. ## Target architecture @@ -421,7 +424,7 @@ see a compiled spec and journal protocol, not a customer/tool identity. | Budgets | Tool declares non-escalatable token/dollar/wallclock ceilings; reserve descendant budget; terminal `budget_exceeded` | `surface/flow.ts`, `sdk/authored-budget.ts`, kernel budget tests | Block/label unmetered-dollar deployments or use a conservative policy | | Audit and evidence | Immutable journal digest + invocation/authorization/effect decision records; scoped redacted artifact URLs; retention policy | journal, `cli/status.ts`, Cloud logs/status rendering | New evidence projection, ACL and retention contract | | Prompt injection | Schema separates untrusted data; catalog metadata is signed/operator-owned; agents receive explicit data boundaries; verifier/gates decide effects | Babysitter explicitly treats PR input as untrusted in `examples/babysitter/babysitter.flow.ts` | Enforced surfaces/credentials, taint-aware templates or review rules, adversarial E2E | -| Recursion | Static child digests, depth/cycle/concurrency/budget limits, attenuation; prohibit raw outward tool calls in steps | `Ctx.dispatch` type only | Implement deliberately after MVP, not a loophole | +| Recursion | Static child digests, depth/cycle/concurrency/budget limits, attenuation; prohibit raw outward tool calls in steps | Direct authored `use`/`f.dispatch` has cycle/depth/attenuation and shared root limits | Add immutable digest admission and public/cross-run capability policy; do not turn the authored slice into a loophole | | Failures | Canonical status/reason taxonomy, retry policy per failure class, event replay, human wait expiry, cancel semantics | `failure-kinds.ts`, `protocol.ts`, `run-state.ts`, kernel retry/cancel | Map host API failures precisely; no “completed” without a valid terminal verdict | ## MVP and phased delivery @@ -473,8 +476,9 @@ declared surface. ### Phase 3 — composition and catalog scale (4–6 weeks) -* Implement durable `f.dispatch`/child tool policy with static digest graph, - depth/cycle/budget/concurrency limits and capability attenuation. +* Harden authored `f.dispatch` into a public child-tool policy with immutable + static digests, descendant budget reservation, and cross-run capability + tokens; retain its existing cycle/depth/shared-concurrency/attenuation gates. * Add dynamic MCP tools for small catalogs, catalog search/ranking for large ones, policy/approval templates, and version rollout/rollback controls. * Add organization analytics that aggregate declared outcomes without exposing diff --git a/docs/SURFACE.md b/docs/SURFACE.md index cb0865562..4231e1d87 100644 --- a/docs/SURFACE.md +++ b/docs/SURFACE.md @@ -34,6 +34,7 @@ export default flow("chief", { identity: "chief", // gate 8 — a principal memory: { script: true, agent: true }, // gate 5 — relayhistory-backed budget: "$20/day", + use: ["./garden/implement.flow.ts"], // direct child allowlist }) .on(slack.mention("#exec"), async (f, event) => { // gate 2 — trigger = entry condition const intent = await f.llm`Extract the work request, if any: ${event.text}` @@ -49,8 +50,8 @@ export default flow("chief", { const ok = await f.human(`Ship this?\n${plan.summary}`, { to: "khaliq" }); if (!ok) return f.done("declined"); // choose not to proceed after a negative answer - const pr = await f.dispatch("garden/implement", plan); // gate 3 — child flow - await f.slack.reply(event, `Shipped: ${pr.url}`); + const child = await f.dispatch("garden/implement", plan); // gate 3 — child flow + await f.slack.reply(event, `Shipped: ${child.name} (${child.completionReason})`); }); ``` @@ -1452,9 +1453,10 @@ The exit codes are part of the surface contract: Without an attached worker, reaching an `llm` or `agent` step returns a durable parked outcome. For authored TypeScript, `--local-agent` attaches both local -workers as described above. Event, deployed-digest, HTTP, SDK-call, and -flow-to-flow invocation remain later-gate surface work; they are not shipped -by this CLI. Schedules are: `schedule.cron(...)` / `schedule.every(...)` are +workers as described above. Direct, statically declared child-flow invocation +is shipped through `use` / `f.dispatch`; event, deployed-digest, HTTP, SDK-call, +and arbitrary public-flow invocation remain later-gate surface work. Schedules +are: `schedule.cron(...)` / `schedule.every(...)` are declared on a flow, lowered to the `flows.tick` subscription, printed by `flows check` with the `flows tick start` invocation that drives a fixed interval locally, and registered on Cloud by `flows schedule` (see @@ -1514,6 +1516,48 @@ with is refused the same way, naming the resume that keeps it. On a declarative run the flag is honoured rather than refused: it attaches a worker and drives the parked step. The flag is never accepted and ignored. +### Child flows: `f.dispatch` + +```ts +export default flow("release", { + use: ["./implement.flow.ts"], + budget: { tokens: 50_000 }, +}, async (f, input) => { + await f.run("printf '%s' prepare"); + const child = await f.dispatch("implement", { issue: input.issue }); + await f.run("printf '%s' publish"); + f.done(child.completionReason); +}); +``` + +`f.dispatch(name, input)` runs one **direct** child named by the current +flow's static `use` header. `use` entries are relative `.flow.ts` paths; the +loader resolves their complete graph before any authored body runs and refuses +missing files, cycles, repeated paths, and two direct children with the same +declared flow name. A computed path or an undeclared/transitive-only child name +cannot widen that graph at runtime. + +The input is snapshotted as JSON before admission. Child operations share the +parent's durable root and receive qualified identities such as +`dispatch-2--run-1`. The first child operation depends on the parent's current +predecessors; the journaled `dispatch-2` receipt joins the child's leaves; the +next parent operation depends on that receipt. Resume replays those identities, +so neither parent nor child effects repeat. A successful call returns +`{ name, completionReason: "success", completionDetail? }`; any other child +verdict fails the dispatch rather than turning failure into a value. + +Authority narrows down the tree. All descendants share the root budget +accumulator and worker-capacity pool. In this release a child may not declare a +second budget, require a tool capability its parent did not grant, or call +`f.human`; the root owns the budget ceiling and approval authority. Static +`use` cycles are refused and runtime child depth is capped at three. These are +local/hosted authored-flow composition semantics, not permission for arbitrary +public Flow Tools to call one another. + +With `--cloud-mirror`, the root, child operations and dispatch receipts are +projected as one flattened, connected dashboard graph. Internal `complete-N` +verdict receipts stay in the journal as evidence but are hidden from the graph. + ### Human gates: `f.human` ```ts @@ -1578,8 +1622,8 @@ answer, and `answeredBy` records the OS user who did. On Cloud the same wait is answered through the run's answer route — by the delivered channel above, or `POST /api/v1/workflows/runs//answer` — with the answerer's identity (`slack:@handle`, `github:@login`, or the Cloud user). `timeout` is not yet -enforced (DESIGN.md §1.4). `f.dispatch` still fails closed as -`unsupported_verb`. +enforced (DESIGN.md §1.4). A child flow cannot call `f.human`; approval +authority remains with the root flow. `flows resume` reports `run_unavailable` only when relayflowd returns the typed `run_not_found` refusal. A dropped connection, request failure, or diff --git a/packages/sdk/src/authored-dispatch.ts b/packages/sdk/src/authored-dispatch.ts new file mode 100644 index 000000000..e2c30cccf --- /dev/null +++ b/packages/sdk/src/authored-dispatch.ts @@ -0,0 +1,113 @@ +import type { DispatchResult } from '@relayflows/surface'; +import type { FlowHandle } from './authored-flow.js'; +import { AuthoredFlowExecutionError } from './authored-flow-error.js'; +import type { LoadedAuthoredFlowNode } from './authored-flow-loader.js'; +import { flowRequirements, type RequirementsFlowDefinition } from './flow-requirements.js'; + +export const MAX_DISPATCH_DEPTH = 3; + +/** Resolve one attenuated direct child from the statically loaded `use` graph. */ +export function resolveDispatchChild(options: { + readonly handle: FlowHandle; + readonly definition: RequirementsFlowDefinition & { readonly name: string }; + readonly graph?: readonly LoadedAuthoredFlowNode[]; + readonly flowName: string; + readonly depth: number; +}): LoadedAuthoredFlowNode { + if (typeof options.flowName !== 'string' || options.flowName.trim() === '') { + throw new AuthoredFlowExecutionError('dispatch_invalid', 'f.dispatch requires a non-empty declared child flow name'); + } + if (options.depth >= MAX_DISPATCH_DEPTH) { + throw new AuthoredFlowExecutionError( + 'dispatch_depth_exceeded', + `f.dispatch depth exceeds ${MAX_DISPATCH_DEPTH}; flatten the flow tree or move work into the current child`, + ); + } + const current = options.graph?.find(node => node.handle === options.handle); + const direct = current?.use.map(path => options.graph!.find(node => node.path === path)) ?? []; + const matches = direct.filter((node): node is LoadedAuthoredFlowNode => + node !== undefined && node.getDefinition(node.handle).name === options.flowName); + if (matches.length !== 1) { + const declared = direct.filter((node): node is LoadedAuthoredFlowNode => node !== undefined) + .map(node => node.getDefinition(node.handle).name).sort(); + throw new AuthoredFlowExecutionError( + matches.length > 1 ? 'dispatch_invalid' : 'dispatch_unknown', + `flow "${options.definition.name}" cannot dispatch ${JSON.stringify(options.flowName)}; direct use children: ${declared.length === 0 ? '(none)' : declared.join(', ')}`, + ); + } + const child = matches[0]!; + const childDefinition = child.getDefinition(child.handle); + assertChildCapabilities(options.definition, childDefinition); + if (childDefinition.header.budget !== undefined) { + throw new AuthoredFlowExecutionError( + 'dispatch_invalid', + `child flow "${childDefinition.name}" declares its own budget; put the run-tree ceiling on "${options.definition.name}" until nested budget intersection ships`, + ); + } + return child; +} + +export function parseDispatchReceipt(value: string, step: string): DispatchResult { + let parsed: unknown; + try { parsed = JSON.parse(value); } catch { + throw new AuthoredFlowExecutionError('journal_protocol_violation', `dispatch step "${step}" recorded invalid JSON`); + } + const receipt = parsed as Partial | null; + if (typeof receipt !== 'object' || receipt === null || typeof receipt.name !== 'string' + || receipt.completionReason !== 'success' + || (receipt.completionDetail !== undefined && typeof receipt.completionDetail !== 'string')) { + throw new AuthoredFlowExecutionError('journal_protocol_violation', `dispatch step "${step}" recorded an invalid child receipt`); + } + return { + name: receipt.name, + completionReason: 'success', + ...(receipt.completionDetail === undefined ? {} : { completionDetail: receipt.completionDetail }), + }; +} + +/** Last visible child operations; the dispatch receipt joins all of them. */ +export function childLeaves(steps: readonly { readonly id: string; readonly after?: readonly string[] }[]): string[] { + const visible = steps.filter(step => !/(?:^|--)complete-[1-9][0-9]*$/.test(step.id)); + const parents = new Set(visible.flatMap(step => step.after ?? [])); + return visible.map(step => step.id).filter(id => !parents.has(id)); +} + +/** A child may use only provider/MCP capabilities its parent already declared. */ +function assertChildCapabilities( + parent: RequirementsFlowDefinition & { readonly name: string }, + child: RequirementsFlowDefinition & { readonly name: string }, +): void { + const parentTools = parent.header?.tools ?? {}; + const childTools = child.header?.tools ?? {}; + for (const [tool, declared] of Object.entries(childTools)) { + if (tool === 'mcp') { + const allowed = new Set(Array.isArray(parentTools.mcp) ? parentTools.mcp as readonly unknown[] : []); + const requested = Array.isArray(declared) ? declared : []; + if (requested.some(server => !allowed.has(server))) { + throw new AuthoredFlowExecutionError( + 'dispatch_invalid', + `child flow "${child.name}" widens tools.mcp beyond parent "${parent.name}"`, + ); + } + } + } + const parentHelpers = helperAuthority(parent); + for (const requirement of flowRequirements(child).integrations) { + if ((requirement.from === 'tools' || requirement.from === 'helper') + && !parentHelpers.has(requirement.provider)) { + throw new AuthoredFlowExecutionError( + 'dispatch_invalid', + `child flow "${child.name}" requires ${requirement.detail}, which parent "${parent.name}" did not grant`, + ); + } + } +} + +/** Helper providers this flow can delegate, from explicit or statically visible use. */ +export function helperAuthority( + definition: RequirementsFlowDefinition, +): ReadonlySet { + return new Set(flowRequirements(definition).integrations + .filter(requirement => requirement.from === 'tools' || requirement.from === 'helper') + .map(requirement => requirement.provider)); +} diff --git a/packages/sdk/src/authored-flow-error.ts b/packages/sdk/src/authored-flow-error.ts index d5ed2251f..662fb0c46 100644 --- a/packages/sdk/src/authored-flow-error.ts +++ b/packages/sdk/src/authored-flow-error.ts @@ -16,6 +16,9 @@ export type AuthoredFlowExecutionErrorCode = | 'llm_cli_unresolved' | 'llm_parked' | 'duplicate_completion' + | 'dispatch_depth_exceeded' + | 'dispatch_invalid' + | 'dispatch_unknown' | 'journal_protocol_violation' | 'missing_completion' | 'memory_unreachable' diff --git a/packages/sdk/src/authored-flow-executor.ts b/packages/sdk/src/authored-flow-executor.ts index aab885287..efbc73fa1 100644 --- a/packages/sdk/src/authored-flow-executor.ts +++ b/packages/sdk/src/authored-flow-executor.ts @@ -22,6 +22,7 @@ import { import { commitAuthoredVerdict } from './authored-completion-record.js'; import { type AgentResult, + type DispatchResult, type LlmOptions, type CloudHelper, type CompletionReason as SurfaceCompletionReason, @@ -38,6 +39,7 @@ import { observeStep, type ProgressEvent } from './progress.js'; import { parseStepTimeout } from './compile.js'; import { getAuthoredFlowDefinition } from './authored-flow.js'; import type { GetFlowDefinition } from './authored-flow-loader.js'; +import type { LoadedAuthoredFlowNode } from './authored-flow-loader.js'; import type { RunLifecycleOptions } from './cli/run.js'; import { AuthoredFlowExecutionError, @@ -66,6 +68,8 @@ import type { CompletionReason as ProtocolCompletionReason, RunCompletionReason as ProtocolRunCompletionReason, } from './protocol.js'; +import type { AuthoredWorkerSlots } from './worker-slots.js'; +import { childLeaves, helperAuthority, parseDispatchReceipt, resolveDispatchChild } from './authored-dispatch.js'; type Assert = T; type Equal = [A] extends [B] @@ -185,6 +189,20 @@ export interface ExecuteAuthoredFlowOptions { * from authored input: direct `/workflows/run` callers control that JSON. */ readonly extensionDispatch?: HostedExtensionDispatch; + /** Pinned static `use:` graph available to `f.dispatch`. */ + readonly flowGraph?: readonly LoadedAuthoredFlowNode[]; + /** Internal namespace for descendant step/admission identities. */ + readonly stepPrefix?: string; + /** Current child depth. Root is zero; dispatch is capped at three. */ + readonly dispatchDepth?: number; + /** Parent predecessors inherited by the first operation in a child body. */ + readonly entryAfter?: readonly string[]; + /** Root-owned budget accumulator shared by every descendant. */ + readonly sharedBudget?: AuthoredBudget; + /** Root-owned worker capacity shared by every descendant. */ + readonly workerSlots?: AuthoredWorkerSlots; + /** Parent helper authority inherited by this dispatched child. */ + readonly allowedHelperProviders?: ReadonlySet; } export async function executeAuthoredFlow( @@ -209,7 +227,7 @@ export async function executeAuthoredFlow( }; const definition = getDefinition(handle); const hostedHandler = extensionHandlerForHostedDispatch(options.extensionDispatch, options.extensions ?? []); - const headerFields = Object.keys(definition.header).filter(key => key !== 'tools' && key !== 'budget' && key !== 'memory' && key !== 'version' && key !== 'hooks'); + const headerFields = Object.keys(definition.header).filter(key => key !== 'tools' && key !== 'budget' && key !== 'memory' && key !== 'version' && key !== 'hooks' && key !== 'use'); if (definition.header.tools && Object.keys(definition.header.tools).some(key => !['mcp', ...helperProviders.map(p => p.namespace)].includes(key))) headerFields.push('tools'); if (definition.header.tools?.relayfile !== undefined) headerFields.push('tools.relayfile'); const helperPreflight = checkSlackHelpers(definition); @@ -242,7 +260,7 @@ export async function executeAuthoredFlow( ); } - const budget = new AuthoredBudget(definition.header.budget); + const budget = options.sharedBudget ?? new AuthoredBudget(definition.header.budget); if (definition.header.memory?.agent === true) { throw new AuthoredFlowExecutionError('unsupported_header', 'memory.agent requires the follow-up identity-scoped agent memory adapter'); } @@ -255,10 +273,28 @@ export async function executeAuthoredFlow( const journalSteps: AuthoredFlowJournalStep[] = []; const authoredSteps: AuthoredFlowOperation[] = []; const lifecycle = new AuthoredFlowLifecycle(); - const stepEdges = (step: string): AuthoredStepEdges | undefined => lifecycle.stepEdges(step); + const edgeOverrides = new Map(); + const stepEdges = (step: string): AuthoredStepEdges | undefined => { + const overridden = edgeOverrides.get(step); + if (overridden !== undefined) return overridden; + const local = lifecycle.stepEdges(step); + if (local === undefined || (local.after !== undefined && local.after.length > 0) || options.entryAfter === undefined + || options.entryAfter.length === 0) return local; + return { ...local, after: [...options.entryAfter] }; + }; let nextStep = 1; let requestedCompletion: LoweredCompletionReason | undefined; let requestedDetail: string | undefined; + const qualify = (id: string): string => `${options.stepPrefix ?? ''}${id}`; + const nextId = (kind: string): string => qualify(`${kind}-${nextStep++}`); + const assertHelperAllowed = (provider: string): void => { + if (options.allowedHelperProviders !== undefined && !options.allowedHelperProviders.has(provider)) { + throw new AuthoredFlowExecutionError( + 'dispatch_invalid', + `child flow "${definition.name}" attempted helper provider "${provider}" outside its parent's granted integrations`, + ); + } + }; const lowerDeterministic = authoredDeterministicRunner( definition.name, journal, journalSteps, budget, { @@ -271,6 +307,7 @@ export async function executeAuthoredFlow( const worker = authoredWorkerRunner( definition, journal, flowPath, journalSteps, waitOptions, localAgentStream, budget, definition.header.budget, options.rootRunId, options.workerCapacity, stepEdges, + options.workerSlots, ); /** @@ -373,7 +410,7 @@ export async function executeAuthoredFlow( function llmOperation(prompt: string, options: LlmOptions): Step; function llmOperation(prompt: string | TemplateStringsArray, ...values: unknown[]): Step { assertOperationAllowed('llm', definition.name, requestedCompletion); - const id = `llm-${nextStep++}`; + const id = nextId('llm'); // Hoist the operation reference so the start closure can read the // caller's `.gate(config)` at spec-build time. AuthoredFlowOperation // begins after construction returns, so `llmOp` is defined by then. @@ -420,7 +457,7 @@ export async function executeAuthoredFlow( `f.run options.onNonZero must be 'fail' or 'record' (got ${JSON.stringify(policy)}).`, ); } - const id = `run-${nextStep++}`; + const id = nextId('run'); if (policy === 'record') { let recordOp!: AuthoredFlowOperation; recordOp = new AuthoredFlowOperation( @@ -451,8 +488,9 @@ export async function executeAuthoredFlow( const slackRun = options.rootRunId ?? randomUUID(); function slackOperation(call: SlackCall): Step { assertOperationAllowed(`slack.${call.verb}`, definition.name, requestedCompletion); + assertHelperAllowed(call.provider); const snapshot = snapshotJsonValue(call, 'f.slack call') as unknown as SlackCall; - const id = `slack-${slackRun}-${nextStep++}`; + const id = qualify(`slack-${slackRun}-${nextStep++}`); return trackStep(authoredSteps, new AuthoredFlowOperation( id, `slack.${call.verb}`, () => assertOperationAllowed(`slack.${call.verb}`, definition.name, requestedCompletion), @@ -480,8 +518,9 @@ export async function executeAuthoredFlow( ...createHelpers((call: HelperCall): Step => { const verb = `${call.provider}.${call.verb}`; assertOperationAllowed(verb, definition.name, requestedCompletion); + assertHelperAllowed(call.provider); const snapshot = snapshotJsonValue(call, `f.${verb} call`) as unknown as HelperCall; - const id = `${call.provider}-${slackRun}-${nextStep++}`; + const id = qualify(`${call.provider}-${slackRun}-${nextStep++}`); return trackStep(authoredSteps, new AuthoredFlowOperation(id, verb, () => assertOperationAllowed(verb, definition.name, requestedCompletion), async () => await runHelperEffect(journal, definition.name, id, snapshot, @@ -496,7 +535,7 @@ export async function executeAuthoredFlow( }, mcp: buildMcpProxy(checkedMcp.inventory, (server, tool, args, known) => { assertOperationAllowed('mcp', definition.name, requestedCompletion); - const id = `mcp-${nextStep++}`; + const id = nextId('mcp'); return trackStep(authoredSteps, new AuthoredFlowOperation( id, 'mcp', () => assertOperationAllowed('mcp', definition.name, requestedCompletion), @@ -516,7 +555,7 @@ export async function executeAuthoredFlow( assertOperationAllowed('agent', definition.name, requestedCompletion); // Authored headers do not yet declare reusable named agents, so the name // identifies nothing to the kernel; it is the step's label in the DAG. - const id = `agent-${nextStep++}`; + const id = nextId('agent'); let agentOp!: AuthoredFlowOperation; agentOp = new AuthoredFlowOperation( id, @@ -545,6 +584,12 @@ export async function executeAuthoredFlow( */ human(question, humanOptions) { assertOperationAllowed('human', definition.name, requestedCompletion); + if ((options.dispatchDepth ?? 0) > 0) { + throw new AuthoredFlowExecutionError( + 'dispatch_invalid', + `child flow "${definition.name}" cannot call f.human in this release; the parent owns approval authority`, + ); + } if (typeof question !== 'string' || question.trim() === '') { throw new AuthoredFlowExecutionError('human_answer_invalid', 'f.human requires a non-empty question'); } @@ -558,7 +603,7 @@ export async function executeAuthoredFlow( if (!parsedTo.ok) { throw new AuthoredFlowExecutionError('human_to_invalid', `f.human to ${parsedTo.reason}`); } - const id = `human-${nextStep++}`; + const id = nextId('human'); const to = humanOptions.to; // Hoisted like `llmOp`/`runOp`: the start closure reads the caller's // `.gate(config)` at spec-build time, so a named gate on the answer is @@ -590,13 +635,79 @@ export async function executeAuthoredFlow( ); return trackStep(authoredSteps, humanOp); }, - dispatch() { + dispatch(flowName, dispatchInput) { assertOperationAllowed('dispatch', definition.name, requestedCompletion); - throw unsupportedVerb('dispatch'); + const depth = options.dispatchDepth ?? 0; + const child = resolveDispatchChild({ + handle, definition, graph: options.flowGraph, + flowName, depth, + }); + const childDefinition = child.getDefinition(child.handle); + const inputSnapshot = snapshotJsonValue(dispatchInput, `f.dispatch(${JSON.stringify(flowName)}) input`); + const id = nextId('dispatch'); + let dispatchOp!: AuthoredFlowOperation; + dispatchOp = new AuthoredFlowOperation( + id, + 'dispatch', + () => assertOperationAllowed('dispatch', definition.name, requestedCompletion), + async () => { + const inheritedAfter = stepEdges(id)?.after ?? []; + const currentHelperAuthority = helperAuthority(definition); + const allowedHelperProviders = options.allowedHelperProviders === undefined + ? currentHelperAuthority + : new Set([...currentHelperAuthority].filter(provider => options.allowedHelperProviders!.has(provider))); + const childResult = await executeAuthoredFlow(child.handle, journal, inputSnapshot, { + getDefinition: child.getDefinition, + dataDir: options.dataDir, + flowPath: child.path, + ...(localAgentStream === undefined ? {} : { localAgentStream }), + ...(options.workerCapacity === undefined ? {} : { workerCapacity: options.workerCapacity }), + ...(options.rootRunId === undefined ? {} : { rootRunId: options.rootRunId }), + flowGraph: options.flowGraph, + stepPrefix: `${id}--`, + dispatchDepth: depth + 1, + entryAfter: inheritedAfter, + sharedBudget: budget, + ...(worker.slots === undefined ? {} : { workerSlots: worker.slots }), + allowedHelperProviders, + ...(options.extensions === undefined ? {} : { extensions: options.extensions }), + onProgress, + ...(options.onWait === undefined ? {} : { onWait: options.onWait }), + ...(options.signal === undefined ? {} : { signal: options.signal }), + }); + if (childResult.completionReason !== 'success') { + throw new AuthoredFlowExecutionError( + 'step_failed', + `child flow "${childResult.name}" completed with ${childResult.completionReason}` + + (childResult.completionDetail === undefined ? '' : `: ${childResult.completionDetail}`), + childResult.completionReason === 'step_failed' ? 'step_failed' : undefined, + ); + } + const leaves = childLeaves(childResult.journalSteps); + edgeOverrides.set(id, { + ...displayLabel(childResult.name), + ...(leaves.length > 0 ? { after: leaves } : inheritedAfter.length === 0 + ? {} : { after: inheritedAfter }), + }); + const receipt: DispatchResult = { + name: childResult.name, + completionReason: 'success', + ...(childResult.completionDetail === undefined ? {} : { completionDetail: childResult.completionDetail }), + }; + const literal = `'${JSON.stringify(receipt).replaceAll("'", "'\\''")}'`; + const recorded = await lowerDeterministic( + id, `printf '%s' ${literal}`, false, undefined, dispatchOp.namedGate, + ); + return parseDispatchReceipt(recorded, id); + }, + lifecycle, + displayLabel(flowName), + ); + return trackStep(authoredSteps, dispatchOp); }, hook(name, input) { assertOperationAllowed('hook', definition.name, requestedCompletion); - const id = `hook-${nextStep++}`; + const id = nextId('hook'); const snapshot = snapshotJsonValue(input, 'f.hook input'); return trackStep(authoredSteps, new AuthoredFlowOperation( id, 'hook', @@ -661,7 +772,7 @@ export async function executeAuthoredFlow( Object.assign(context, pluginHelpers(checkedMcp.plugins ?? [], (plugin, verb, args) => { const label = `${verb.namespace}.${verb.method}`; assertOperationAllowed(label, definition.name, requestedCompletion); - const id = `plugin-${nextStep++}`; + const id = nextId('plugin'); return trackStep(authoredSteps, new AuthoredFlowOperation( id, label, () => assertOperationAllowed(label, definition.name, requestedCompletion), () => runPluginEffect(journal, definition.name, id, plugin, verb, args, @@ -735,7 +846,7 @@ export async function executeAuthoredFlow( // explanation the root had already journaled to `run_admission_conflict`. // With no detail there is no environment in the command and nothing to // commit, so that path is untouched. - const terminalId = `complete-${nextStep}`; + const terminalId = qualify(`complete-${nextStep}`); const verdict = await commitAuthoredVerdict(journal, options.rootRunId, terminalId, { reason: requestedCompletion, ...(requestedDetail === undefined ? {} : { detail: requestedDetail }), diff --git a/packages/sdk/src/authored-flow-loader.ts b/packages/sdk/src/authored-flow-loader.ts index 5a7db01a4..b311e749d 100644 --- a/packages/sdk/src/authored-flow-loader.ts +++ b/packages/sdk/src/authored-flow-loader.ts @@ -100,6 +100,18 @@ export async function loadAuthoredFlow(path: string, options: LoadAuthoredFlowOp } dependencies.push(child.path); } + const childNames = new Set(); + for (const path of dependencies) { + const child = loaded.get(path)!; + const name = child.getDefinition(child.handle).name; + if (childNames.has(name)) { + throw new AuthoredFlowLoadError( + `Flow "${absolutePath}" declares two direct use children named "${name}".`, + 'use_invalid', + ); + } + childNames.add(name); + } const node = Object.freeze({ path: absolutePath, handle, getDefinition, surfaceAuthority, use: Object.freeze(dependencies) }); loaded.set(absolutePath, node); return node; diff --git a/packages/sdk/src/authored-node-entry.ts b/packages/sdk/src/authored-node-entry.ts index 90705e6ef..12611816c 100644 --- a/packages/sdk/src/authored-node-entry.ts +++ b/packages/sdk/src/authored-node-entry.ts @@ -75,6 +75,7 @@ try { getDefinition: loaded.getDefinition, dataDir: request.dataDir, flowPath: request.metadata.flowPath, rootRunId: request.rootRunId, extensions: loaded.extensions, + flowGraph: loaded.graph, localAgentStream: request.localAgentStream, signal: controller.signal, ...(request.workerCapacity === undefined ? {} : { workerCapacity: request.workerCapacity }), onProgress: event => send({ type: 'progress', event }), diff --git a/packages/sdk/src/authored-root.ts b/packages/sdk/src/authored-root.ts index bf2aefa49..75bd943d7 100644 --- a/packages/sdk/src/authored-root.ts +++ b/packages/sdk/src/authored-root.ts @@ -228,6 +228,7 @@ async function driveRoot( ...(options.workerCapacity === undefined ? {} : { workerCapacity: options.workerCapacity }), rootRunId: dispatch.run_id, extensions: loaded.extensions, + flowGraph: loaded.graph, ...options.lifecycle, signal: callerSignal === undefined ? rootSignal diff --git a/packages/sdk/src/authored-worker-step.ts b/packages/sdk/src/authored-worker-step.ts index 1c99374e4..e20b072f9 100644 --- a/packages/sdk/src/authored-worker-step.ts +++ b/packages/sdk/src/authored-worker-step.ts @@ -16,7 +16,7 @@ import { snapshotJsonValue } from './json-value.js'; import { authoredChildAdmissionKey } from './authored-admission.js'; import { alsoRecord, recordAuthoredChild } from './authored-step-index.js'; import type { StepFailedDetails } from './failure-kinds.js'; -import { WorkerSlots } from './worker-slots.js'; +import { authoredWorkerSlots, type AuthoredWorkerSlots } from './worker-slots.js'; const WORKSPACE_PERMISSION_ANNOTATION = /:\s*(readonly|readwrite)\s*$/i; @@ -26,11 +26,16 @@ export function authoredWorkerRunner( journalSteps: AuthoredFlowJournalStep[], waitOptions: RunLifecycleOptions, localAgentStream?: string, budget?: AuthoredBudget, headerBudget?: unknown, rootRunId?: string, workerCapacity?: number, stepEdges?: AuthoredStepContext['stepEdges'], + sharedSlots?: AuthoredWorkerSlots, ) { // Sized to the attached local workers, so concurrent calls wait here for a // slot instead of being admitted and parked for want of a free worker. - const slots = workerCapacity === undefined ? undefined - : { agent: new WorkerSlots(workerCapacity), llm: new WorkerSlots(workerCapacity) }; + const ownsSlots = sharedSlots === undefined; + const slots = sharedSlots ?? (workerCapacity === undefined ? undefined : authoredWorkerSlots(workerCapacity)); + const slotScopes = slots === undefined ? undefined : { + agent: slots.agent.scope(), + llm: slots.llm.scope(), + }; const check = authoredPreflight(flowPath); const context: AuthoredStepContext = { ...(rootRunId === undefined ? {} : { rootRunId }), @@ -136,14 +141,20 @@ export function authoredWorkerRunner( const admit = async () => budget === undefined ? consume(await journal.runStart(spec, undefined, admissionKey)) : budget.execute(journal, spec, consume, admissionKey); - return slots === undefined ? admit() : slots[step.type === 'llm' ? 'llm' : 'agent'].run(admit); + return slotScopes === undefined ? admit() : slotScopes[step.type === 'llm' ? 'llm' : 'agent'].run(admit); } return { + slots, /** Refuse every agent/LLM call still waiting for a worker slot (body teardown). */ stop(reason: unknown): void { - slots?.agent.close(reason); - slots?.llm.close(reason); + if (ownsSlots) { + slots?.agent.close(reason); + slots?.llm.close(reason); + } else { + slotScopes?.agent.close(reason); + slotScopes?.llm.close(reason); + } }, async agent(id: string, options: AgentOptions, verification?: NamedGate): Promise { if (options.workspace !== undefined && localAgentStream !== undefined) { diff --git a/packages/sdk/src/cli.ts b/packages/sdk/src/cli.ts index e5be59c1e..394997bbb 100644 --- a/packages/sdk/src/cli.ts +++ b/packages/sdk/src/cli.ts @@ -380,6 +380,9 @@ export async function runCli( observer?.onRunStarted(run); mirror?.onRunStarted(run); }, + ...(mirror === undefined ? {} : { + onRunReceipt: (run: { runId: string }) => { mirror.onRunStarted(run); }, + }), }), onWait: (progress: RunProgress) => { emitWait(progress, logged); diff --git a/packages/sdk/src/cli/run.ts b/packages/sdk/src/cli/run.ts index 9763b4b0e..86c07ce92 100644 --- a/packages/sdk/src/cli/run.ts +++ b/packages/sdk/src/cli/run.ts @@ -122,6 +122,8 @@ export interface RunLifecycleOptions { onJournalEntry?: (entry: JournalEvent) => void; /** An authored root was admitted: its id is known before its body runs. */ onRunStarted?: (run: { runId: string; flow: string; resumed?: boolean }) => void; + /** A declarative root returned its admission receipt, even if no watched entry arrived. */ + onRunReceipt?: (run: { runId: string; flow: string }) => void; localAgent?: boolean; /** `--agent-capacity`: the local workers' concurrency; the default is `DEFAULT_LOCAL_AGENT_CAPACITY`. */ agentCapacity?: number; @@ -191,6 +193,14 @@ async function executeCheckedFlow( } if (options.onJournalEntry !== undefined) client.on('entry', options.onJournalEntry); const outcome = await startWatched(client, spec, options); + // `run.start { watch: true }` is an event stream, not the source of the + // root identity. A short deterministic run can finish before its first + // watched entry is delivered (and an older daemon may refuse `watch`), so + // receipt consumers such as the Cloud mirror need the admitted id too. + // This stays separate from `onRunStarted`: opening the observer without a + // streamed journal would manufacture an empty projection and suppress its + // truthful "not projected" diagnostic. + options.onRunReceipt?.({ runId: outcome.run_id, flow: spec.name ?? 'flow' }); const execution = await classifyOutcome(client, 'run', outcome, base, socketPath, { ...options, dataDir }); if (options.reuseFromRunId !== undefined) { execution.report.reuse = await reuseSummary(client, outcome.run_id, options.reuseFromRunId); diff --git a/packages/sdk/src/cloud-mirror-step.ts b/packages/sdk/src/cloud-mirror-step.ts index 42b50ac86..542bba0ed 100644 --- a/packages/sdk/src/cloud-mirror-step.ts +++ b/packages/sdk/src/cloud-mirror-step.ts @@ -152,6 +152,8 @@ export interface MirroredJournal { children: string[]; /** Authored graph hints by step id, from an authored root's step index. */ hints: Map; + /** Authored completion receipts are durable evidence, not graph nodes. */ + hidden: string[]; } type Payload = Record; @@ -507,6 +509,7 @@ export function mirrorJournal( transcripts, children: index.children, hints: index.hints, + hidden: index.hidden, }; } @@ -522,7 +525,11 @@ export function mirrorJournal( function authoredIndex( events: readonly JournalEvent[], env: NodeJS.ProcessEnv, -): { children: string[]; hints: Map } { +): { + children: string[]; + hints: Map; + hidden: string[]; +} { const messages: unknown[] = []; for (const event of events) { if (event.entry_type !== 'stream.appended') continue; @@ -531,8 +538,15 @@ function authoredIndex( } const children: string[] = []; const hints = new Map(); + const hidden: string[] = []; for (const entry of foldAuthoredStepRecords(messages).values()) { if (/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(entry.runId)) children.push(entry.runId); + // This is the executor's durable verdict receipt, not an authored unit of + // work. Only an entry in the authored root index can be hidden here, so a + // declarative step coincidentally named `complete-N` remains visible. + if (/(?:^|--)complete-[1-9][0-9]*$/.test(entry.step)) { + hidden.push(`${entry.runId}/${entry.step}`); + } const name = label(entry.label, env); const after = entry.after === undefined ? undefined @@ -546,7 +560,7 @@ function authoredIndex( ...(after === undefined ? {} : { after }), }); } - return { children, hints }; + return { children, hints, hidden }; } /** diff --git a/packages/sdk/src/cloud-mirror.ts b/packages/sdk/src/cloud-mirror.ts index 2620680d3..09d7d9bec 100644 --- a/packages/sdk/src/cloud-mirror.ts +++ b/packages/sdk/src/cloud-mirror.ts @@ -287,6 +287,7 @@ export function createRunMirror(options: RunMirrorOptions): RunMirror { const finals = new Map(); const transcripts = new Map }>(); const hints = new Map(); + const hidden = new Set(); /** Live steps the cache cap dropped, by identity, so a capped view owns up to it. */ const evicted = new Set(); /** Finished steps past the report cap, by identity. Counted, never sent. */ @@ -318,6 +319,7 @@ export function createRunMirror(options: RunMirrorOptions): RunMirror { const remember = (journalRunId: string, step: SnapshotStep, order: number): void => { const key = `${journalRunId}/${step.stepName}`; + if (hidden.has(key)) return; const existing = steps.get(key); const changed = existing === undefined || fingerprint(existing.step) !== fingerprint(step); steps.set(key, { step, order, changedAt: changed ? now() : existing!.changedAt }); @@ -365,19 +367,30 @@ export function createRunMirror(options: RunMirrorOptions): RunMirror { continue; } for (const child of folded.children) admit(child); + for (const key of folded.hidden) { + hidden.add(key); + steps.delete(key); + finals.delete(key); + transcripts.delete(key); + } for (const [key, hint] of folded.hints) { // Merge, never replace: a completion record can omit a label or an // edge the admission carried, and the view must not lose a step's // name between them. const existing = hints.get(key); hints.set(key, { - ...(hint.label ?? existing?.label ? { label: hint.label ?? existing?.label } : {}), - ...(hint.after ?? existing?.after ? { after: hint.after ?? existing?.after } : {}), + // The root's authored index is scanned before the child journal and + // carries causal edges across child runs. A child spec only knows + // its own single-step graph (`depends_on: []`), so it may fill a + // missing field but must never erase the root's richer answer. + ...(existing?.label ?? hint.label ? { label: existing?.label ?? hint.label } : {}), + ...(existing?.after ?? hint.after ? { after: existing?.after ?? hint.after } : {}), }); } folded.steps.forEach((step, order) => remember(runId, step, order)); for (const row of folded.finals) { const key = `${runId}/${row.stepName}`; + if (hidden.has(key)) continue; // The report cap bounds what this process holds, not just what it // sends: a run with ten thousand steps must not grow its own mirror. // Steps past it are counted by identity, so a step read twice is one diff --git a/packages/sdk/src/worker-slots.ts b/packages/sdk/src/worker-slots.ts index 24b9ffb77..ec8368aba 100644 --- a/packages/sdk/src/worker-slots.ts +++ b/packages/sdk/src/worker-slots.ts @@ -7,6 +7,16 @@ export function isAgentCapacity(value: unknown): value is number { return Number.isInteger(value) && (value as number) >= 1 && (value as number) <= MAX_LOCAL_AGENT_CAPACITY; } +export interface WorkerSlotScope { + run(work: () => Promise): Promise; + /** Refuse this flow's queued/future work without closing the shared pool. */ + close(reason: unknown): void; +} + +interface ScopeState { + closed?: { readonly reason: unknown }; +} + /** * First-come admission to a worker that holds `capacity` dispatches at once. * @@ -19,7 +29,11 @@ export function isAgentCapacity(value: unknown): value is number { */ export class WorkerSlots { private held = 0; - private readonly waiting: Array<{ resolve: () => void; reject: (reason: unknown) => void }> = []; + private readonly waiting: Array<{ + resolve: () => void; + reject: (reason: unknown) => void; + scope?: ScopeState; + }> = []; private closed: { readonly reason: unknown } | undefined; constructor(readonly capacity: number) { @@ -27,18 +41,37 @@ export class WorkerSlots { } async run(work: () => Promise): Promise { + return this.runInScope(work); + } + + /** One independently closable admission scope over this shared capacity. */ + scope(): WorkerSlotScope { + const scope: ScopeState = {}; + return Object.freeze({ + run: (work: () => Promise) => this.runInScope(work, scope), + close: (reason: unknown) => this.closeScope(scope, reason), + }); + } + + private async runInScope(work: () => Promise, scope?: ScopeState): Promise { if (this.closed !== undefined) throw this.closed.reason; + if (scope?.closed !== undefined) throw scope.closed.reason; if (this.held < this.capacity) this.held++; // A released slot is handed straight to the next waiter, so `held` never // dips below capacity while anyone is queued and no later caller can jump it. else { - await new Promise((resolve, reject) => this.waiting.push({ resolve, reject })); + await new Promise((resolve, reject) => this.waiting.push({ resolve, reject, scope })); // Woken with the slot, but the body may have failed in between (see release). const closed = this.closedReason(); if (closed !== undefined) { this.release(); throw closed.reason; } + const scopeClosed = scopeClosedReason(scope); + if (scopeClosed !== undefined) { + this.release(); + throw scopeClosed.reason; + } } try { return await work(); @@ -66,17 +99,28 @@ export class WorkerSlots { return; } setImmediate(() => { - if (this.closed === undefined) { + if (this.closed === undefined && next.scope?.closed === undefined) { next.resolve(); return; } // Closed meanwhile. `close` could not see this waiter (already taken off // the queue), so refuse it here, and pass the slot on instead of leaking it. - next.reject(this.closed.reason); + next.reject(this.closed?.reason ?? next.scope!.closed!.reason); this.release(); }); } + private closeScope(scope: ScopeState, reason: unknown): void { + if (scope.closed !== undefined) return; + scope.closed = { reason }; + for (let index = this.waiting.length - 1; index >= 0; index--) { + const waiter = this.waiting[index]!; + if (waiter.scope !== scope) continue; + this.waiting.splice(index, 1); + waiter.reject(reason); + } + } + /** * Refuse every queued and future admission with `reason`; work already * holding a slot is not interrupted. The authored body calls this when it @@ -90,3 +134,18 @@ export class WorkerSlots { for (const waiter of this.waiting.splice(0)) waiter.reject(reason); } } + +/** Read through a call so a check after an `await` is not narrowed away. */ +function scopeClosedReason(scope?: ScopeState): { readonly reason: unknown } | undefined { + return scope?.closed; +} + +/** One run-tree-wide capacity pool, shared by parent and child flows. */ +export interface AuthoredWorkerSlots { + readonly agent: WorkerSlots; + readonly llm: WorkerSlots; +} + +export function authoredWorkerSlots(capacity: number): AuthoredWorkerSlots { + return Object.freeze({ agent: new WorkerSlots(capacity), llm: new WorkerSlots(capacity) }); +} diff --git a/packages/sdk/tests/authored-dispatch-live.test.ts b/packages/sdk/tests/authored-dispatch-live.test.ts new file mode 100644 index 000000000..a5c20257d --- /dev/null +++ b/packages/sdk/tests/authored-dispatch-live.test.ts @@ -0,0 +1,131 @@ +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { afterEach, describe, expect, it } from 'vitest'; +import { AUTHORED_STEP_STREAM } from '../src/authored-step-index.js'; +import { JournalClient } from '../src/journal-client.js'; +import { socketPathFor } from '../src/daemon-connection.js'; +import { readJournalEvents } from '../src/cloud-mirror.js'; +import { mirrorJournal } from '../src/cloud-mirror-step.js'; +import { chainFixture } from './flow-chain-fixture.js'; + +const closes: Array<() => Promise> = []; +afterEach(async () => { + for (const close of closes.splice(0).reverse()) await close(); +}); + +describe('durable child flow dispatch', () => { + it('runs a declared child in the parent DAG and replays it without repeating effects', async () => { + const fixture = chainFixture(); + closes.push(() => fixture.close()); + const grandchildPath = `${fixture.root}/grandchild.flow.ts`; + writeFileSync(grandchildPath, `import { flow } from '@relayflows/surface'; +export default flow('grandchild', async (f, input: { word: string }) => { + await f.run(\`printf '%s' \"\${input.word}\" >> effects\`); + f.done('success'); +}); +`); + writeFileSync(`${fixture.root}/empty.flow.ts`, `import { flow } from '@relayflows/surface'; +export default flow('empty', async f => { f.done('success'); }); +`); + const childPath = `${fixture.root}/child.flow.ts`; + writeFileSync(childPath, `import { flow } from '@relayflows/surface'; +export default flow('child', { use: ['./empty.flow.ts', './grandchild.flow.ts'] }, async (f, input: { word: string }) => { + await f.dispatch('empty', {}); + await f.dispatch('grandchild', { word: 'grandchild' }); + await f.run(\`printf '%s' \"\${input.word}\" >> effects\`); + f.done('success'); +}); +`); + writeFileSync(fixture.flowPath, `import { flow } from '@relayflows/surface'; +export default flow('parent', { use: ['./child.flow.ts'] }, async f => { + await f.run("printf '%s' before >> effects"); + const child = await f.dispatch('child', { word: 'child' }); + await f.run("printf '%s' after >> effects"); + f.done(child.name === 'child' ? 'success' : 'step_failed'); +}); +`); + + const first = fixture.invoke('run', '--no-observer-link', '--json', '--data-dir', fixture.data, + fixture.flowPath, '--input', '{}'); + expect(first.status, first.stderr + first.stdout).toBe(0); + const report = JSON.parse(first.stdout) as { runId: string; completionReason: string }; + expect(report.completionReason).toBe('success'); + expect(readFileSync(`${fixture.root}/effects`, 'utf8')).toBe('beforegrandchildchildafter'); + + const journal = new JournalClient(socketPathFor(fixture.data)); + await journal.connect(); + await journal.hello('dispatch-live-test'); + const messages = (await journal.streamRead(report.runId, AUTHORED_STEP_STREAM, 0, 1000)).messages + .map(message => (message as { message?: unknown }).message ?? message) as Array>; + journal.close(); + const completed = messages.filter(record => record['state'] === 'completed'); + expect(completed.map(record => record['step'])).toEqual([ + 'run-1', + 'dispatch-2--dispatch-1--complete-1', + 'dispatch-2--dispatch-1', + 'dispatch-2--dispatch-2--run-1', + 'dispatch-2--dispatch-2--complete-2', + 'dispatch-2--dispatch-2', + 'dispatch-2--run-3', + 'dispatch-2--complete-4', + 'dispatch-2', + 'run-3', + 'complete-4', + ]); + expect(Object.fromEntries(completed.map(record => [record['step'], { + label: record['label'], after: record['after'], + }]))).toEqual({ + 'run-1': { label: undefined, after: undefined }, + 'dispatch-2--dispatch-1--complete-1': { label: undefined, after: undefined }, + 'dispatch-2--dispatch-1': { label: 'empty', after: ['run-1'] }, + 'dispatch-2--dispatch-2--run-1': { label: undefined, after: ['dispatch-2--dispatch-1'] }, + 'dispatch-2--dispatch-2--complete-2': { label: undefined, after: undefined }, + 'dispatch-2--dispatch-2': { label: 'grandchild', after: ['dispatch-2--dispatch-2--run-1'] }, + 'dispatch-2--run-3': { label: undefined, after: ['dispatch-2--dispatch-2'] }, + 'dispatch-2--complete-4': { label: undefined, after: undefined }, + 'dispatch-2': { label: 'child', after: ['dispatch-2--dispatch-1', 'dispatch-2--run-3'] }, + 'run-3': { label: undefined, after: ['dispatch-2'] }, + 'complete-4': { label: undefined, after: undefined }, + }); + const folded = mirrorJournal(report.runId, + await readJournalEvents(report.runId, fixture.data), Date.now(), process.env); + const runIds = Object.fromEntries(completed.map(record => [record['step'], record['runId']])) as Record; + expect(Object.fromEntries([ + 'run-1', 'dispatch-2--dispatch-1', 'dispatch-2--dispatch-2--run-1', + 'dispatch-2--dispatch-2', 'dispatch-2--run-3', 'dispatch-2', 'run-3', + ].map(step => [step, folded.hints.get(`${runIds[step]}/${step}`)]))).toEqual({ + 'run-1': undefined, + 'dispatch-2--dispatch-1': { label: 'empty', after: ['run-1'] }, + 'dispatch-2--dispatch-2--run-1': { after: ['dispatch-2--dispatch-1'] }, + 'dispatch-2--dispatch-2': { label: 'grandchild', after: ['dispatch-2--dispatch-2--run-1'] }, + 'dispatch-2--run-3': { after: ['dispatch-2--dispatch-2'] }, + 'dispatch-2': { label: 'child', after: ['dispatch-2--dispatch-1', 'dispatch-2--run-3'] }, + 'run-3': { after: ['dispatch-2'] }, + }); + + const resumed = fixture.invoke('resume', '--no-observer-link', '--json', '--data-dir', fixture.data, report.runId); + expect(resumed.status, resumed.stderr + resumed.stdout).toBe(0); + expect(readFileSync(`${fixture.root}/effects`, 'utf8')).toBe('beforegrandchildchildafter'); + expect(existsSync(childPath)).toBe(true); + expect(existsSync(grandchildPath)).toBe(true); + }, 90_000); + + it('lowers a named gate attached to the dispatch receipt', () => { + const fixture = chainFixture(); + closes.push(() => fixture.close()); + writeFileSync(`${fixture.root}/child.flow.ts`, `import { flow } from '@relayflows/surface'; +export default flow('child', async f => { f.done('success'); }); +`); + writeFileSync(fixture.flowPath, `import { flow } from '@relayflows/surface'; +export default flow('parent', { use: ['./child.flow.ts'] }, async f => { + await f.dispatch('child', {}).gate({ type: 'regex_match', pattern: '^NEVER_MATCHES$' }); + f.done('success'); +}); +`); + + const run = fixture.invoke('run', '--no-observer-link', '--json', '--data-dir', fixture.data, + fixture.flowPath, '--input', '{}'); + expect(run.status, run.stderr + run.stdout).toBe(1); + expect(run.stdout).toContain('dispatch-1.gate'); + expect(run.stdout).toContain('retries_exhausted'); + }, 90_000); +}); diff --git a/packages/sdk/tests/authored-flow.test.ts b/packages/sdk/tests/authored-flow.test.ts index 7f1baca1a..2d6385002 100644 --- a/packages/sdk/tests/authored-flow.test.ts +++ b/packages/sdk/tests/authored-flow.test.ts @@ -273,24 +273,129 @@ describe('authored flow journal executor', () => { } }); - it('refuses unsupported promise verbs synchronously even when their results are ignored', async () => { + it('refuses undeclared dispatches and unsupported promise verbs synchronously even when ignored', async () => { const disconnectedJournal = new JournalClient('/journal-must-not-be-contacted'); - const cases = [ - flow('unawaited-dispatch', async (f) => { - f.dispatch('child', {}); - f.done('success'); - }), - flow('unawaited-cloud', async (f) => { - f.cloud.workers.list({ workspaceId: 'workspace', as: 'principal' }); - f.done('success'); - }), + await expect(executeAuthoredFlow(flow('unawaited-dispatch', async (f) => { + f.dispatch('child', {}); + f.done('success'); + }), disconnectedJournal)).rejects.toMatchObject({ code: 'dispatch_unknown' }); + + await expect(executeAuthoredFlow(flow('unawaited-cloud', async (f) => { + f.cloud.workers.list({ workspaceId: 'workspace', as: 'principal' }); + f.done('success'); + }), disconnectedJournal)).rejects.toMatchObject({ code: 'unsupported_verb' }); + }); + + it('attenuates child capabilities and keeps the run-tree budget at the root', async () => { + const disconnectedJournal = new JournalClient('/journal-must-not-be-contacted'); + const wider = flow('wider', { tools: { slack: true } }, async (f) => f.done('success')); + const visibleHelper = flow('visible-helper', async (f) => { + await f.slack.post('#ops', 'must not send'); + f.done('success'); + }); + const hiddenSlack = (f: Ctx) => f.slack.post('#ops', 'must not send'); + const hiddenHelper = flow('hidden-helper', async (f) => { + await hiddenSlack(f); + f.done('success'); + }); + const budgeted = flow('budgeted', { budget: { tokens: 1 } }, async (f) => f.done('success')); + const parent = flow('parent', { use: ['./wider.flow.ts', './budgeted.flow.ts'] }, async (f) => { + await f.dispatch('wider', {}); + f.done('success'); + }); + const graph = [ + { path: '/wider.flow.ts', handle: wider, getDefinition: getFlowDefinition, use: [] }, + { path: '/budgeted.flow.ts', handle: budgeted, getDefinition: getFlowDefinition, use: [] }, + { path: '/parent.flow.ts', handle: parent, getDefinition: getFlowDefinition, + use: ['/wider.flow.ts', '/budgeted.flow.ts'] }, ]; - for (const handle of cases) { - await expect(executeAuthoredFlow(handle, disconnectedJournal)).rejects.toMatchObject({ - code: 'unsupported_verb', + await expect(executeAuthoredFlow(parent, disconnectedJournal, undefined, { flowGraph: graph as never })) + .rejects.toMatchObject({ code: 'dispatch_invalid', message: expect.stringContaining('requires tools.slack') }); + + for (const child of [visibleHelper, hiddenHelper]) { + const childName = getFlowDefinition(child).name; + const helperParent = flow(`parent-${childName}`, { use: ['./helper.flow.ts'] }, async (f) => { + await f.dispatch(childName, {}); + f.done('success'); }); + const helperGraph = [ + { path: '/helper.flow.ts', handle: child, getDefinition: getFlowDefinition, use: [] }, + { path: '/parent.flow.ts', handle: helperParent, getDefinition: getFlowDefinition, use: ['/helper.flow.ts'] }, + ]; + await expect(executeAuthoredFlow(helperParent, disconnectedJournal, undefined, { flowGraph: helperGraph as never })) + .rejects.toMatchObject({ code: 'dispatch_invalid', message: expect.stringContaining('slack') }); + } + + const budgetParent = flow('budget-parent', { use: ['./budgeted.flow.ts'] }, async (f) => { + await f.dispatch('budgeted', {}); + f.done('success'); + }); + const budgetGraph = [graph[1], + { path: '/budget-parent.flow.ts', handle: budgetParent, getDefinition: getFlowDefinition, + use: ['/budgeted.flow.ts'] }, + ]; + await expect(executeAuthoredFlow(budgetParent, disconnectedJournal, undefined, { flowGraph: budgetGraph as never })) + .rejects.toMatchObject({ code: 'dispatch_invalid', message: expect.stringContaining('declares its own budget') }); + }); + + it('caps nested dispatch at three child levels before contacting the journal', async () => { + const disconnectedJournal = new JournalClient('/journal-must-not-be-contacted'); + const four = flow('four', async (f) => f.done('success')); + const three = flow('three', { use: ['./four.flow.ts'] }, async (f) => { + await f.dispatch('four', {}); f.done('success'); + }); + const two = flow('two', { use: ['./three.flow.ts'] }, async (f) => { + await f.dispatch('three', {}); f.done('success'); + }); + const one = flow('one', { use: ['./two.flow.ts'] }, async (f) => { + await f.dispatch('two', {}); f.done('success'); + }); + const root = flow('root', { use: ['./one.flow.ts'] }, async (f) => { + await f.dispatch('one', {}); f.done('success'); + }); + const graph = [ + { path: '/four.flow.ts', handle: four, getDefinition: getFlowDefinition, use: [] }, + { path: '/three.flow.ts', handle: three, getDefinition: getFlowDefinition, use: ['/four.flow.ts'] }, + { path: '/two.flow.ts', handle: two, getDefinition: getFlowDefinition, use: ['/three.flow.ts'] }, + { path: '/one.flow.ts', handle: one, getDefinition: getFlowDefinition, use: ['/two.flow.ts'] }, + { path: '/root.flow.ts', handle: root, getDefinition: getFlowDefinition, use: ['/one.flow.ts'] }, + ]; + + await expect(executeAuthoredFlow(root, disconnectedJournal, undefined, { flowGraph: graph as never })) + .rejects.toMatchObject({ code: 'dispatch_depth_exceeded' }); + }); + + it('passes project hook implementations into a dispatched child', async () => { + let hookRuns = 0; + const child = flow('child', { hooks: ['policy'] }, async (f) => { + const allowed = await f.hook('policy', { target: 'child' }); + f.done(allowed ? 'success' : 'step_failed'); + }); + const parent = flow('parent', { use: ['./child.flow.ts'] }, async (f) => { + await f.dispatch('child', {}); + f.done('success'); + }); + const graph = [ + { path: '/child.flow.ts', handle: child, getDefinition: getFlowDefinition, use: [] }, + { path: '/parent.flow.ts', handle: parent, getDefinition: getFlowDefinition, use: ['/child.flow.ts'] }, + ]; + const base = loadedExtension('policy-extension', flow('policy-extension', async f => f.done('success'))); + const extension: LoadedFlowExtension = { + ...base, + manifest: { ...base.manifest, extends: { ...base.manifest.extends, hooks: ['policy'] } }, + hooks: Object.freeze({ policy: async () => { hookRuns += 1; return true; } }), + }; + const client = await connectedClient('authored-child-hook-test'); + try { + await expect(executeAuthoredFlow(parent, client, undefined, { + flowGraph: graph as never, + extensions: [extension], + })).resolves.toMatchObject({ completionReason: 'success' }); + } finally { + client.close(); } + expect(hookRuns).toBe(1); }); it('treats done as terminal and rejects later operations before journal contact', async () => { @@ -727,5 +832,7 @@ function loadedExtension(name: string, handle: ReturnType): LoadedF function outputFor(command: string): string { if (command.startsWith('emit:')) return command.slice('emit:'.length); + const literal = /^printf '%s' '(\{.*\})'$/u.exec(command)?.[1]; + if (literal?.startsWith('{"name":')) return literal; return command === 'printf authored-journal-ok' ? 'authored-journal-ok' : ''; } diff --git a/packages/sdk/tests/authored-node-runtime.test.ts b/packages/sdk/tests/authored-node-runtime.test.ts index 47f73ef08..91cf53b67 100644 --- a/packages/sdk/tests/authored-node-runtime.test.ts +++ b/packages/sdk/tests/authored-node-runtime.test.ts @@ -241,8 +241,8 @@ f.done('${reason}');`); expect(existsSync(join(f.directory,'forbidden-effects'))).toBe(false); }, 60_000); - it('loads captured graph bytes before preserving the unsupported-use refusal', () => { - const f=fixture(`f.done('success');`); + it('dispatches the captured child graph even when the source changes before execution', () => { + const f=fixture(`await f.dispatch('child',{});f.done('success');`); const original=`import {flow} from '@relayflows/surface';import {writeFileSync} from 'node:fs';if(!process.versions.bun)writeFileSync('loaded-source','original');export default flow('child',async f=>{f.done('success')});`; const modified=original.replace("'original'", "'modified'"); writeFileSync(join(f.directory,'child.flow.ts'),original); @@ -250,8 +250,7 @@ f.done('${reason}');`); .replace("flow('runtime-case',async", "flow('runtime-case',{use:['./child.flow.ts']},async"); writeFileSync(join(f.directory,'case.flow.ts'), `if(!process.versions.bun)writeFileSync('child.flow.ts',${JSON.stringify(modified)});\n`+root); - const result=f.run();expect(result.status,result.stderr+result.stdout).toBe(2); - expect(result.stderr+result.stdout).toContain('unsupported_header'); + const result=f.run();expect(result.status,result.stderr+result.stdout).toBe(0); expect(readFileSync(join(f.directory,'child.flow.ts'),'utf8')).toBe(modified); expect(readFileSync(join(f.directory,'loaded-source'),'utf8')).toBe('original'); },30_000); diff --git a/packages/sdk/tests/authored-use-loader.test.ts b/packages/sdk/tests/authored-use-loader.test.ts index e9009774a..edff8c981 100644 --- a/packages/sdk/tests/authored-use-loader.test.ts +++ b/packages/sdk/tests/authored-use-loader.test.ts @@ -55,6 +55,15 @@ describe('authored use graph loader', () => { await expect(loadAuthoredFlow(join(directory, 'root.flow.ts'))).rejects.toMatchObject({ kind: 'use_not_found' }); }); + it('refuses two direct children with the same dispatch name', async () => { + const directory = fixture({ root: ['./one.flow.ts', './two.flow.ts'], one: [], two: [] }); + writeFileSync(join(directory, 'two.flow.ts'), ` + import { flow } from '@relayflows/surface'; + export default flow('one', async f => { f.done('success'); }); + `); + await expect(loadAuthoredFlow(join(directory, 'root.flow.ts'))).rejects.toMatchObject({ kind: 'use_invalid' }); + }); + it.each([ 'throw new Error("import failed");', 'export default { name: "forged" };', diff --git a/packages/sdk/tests/cli.test.ts b/packages/sdk/tests/cli.test.ts index ac82ace71..3d97b0b3b 100644 --- a/packages/sdk/tests/cli.test.ts +++ b/packages/sdk/tests/cli.test.ts @@ -1126,6 +1126,29 @@ describe('flows run/resume CLI over the journal protocol', () => { })); }); + it('reports a declarative admission receipt when no watched journal entry arrives', async () => { + const dataDir = temporaryProject('flows-run-receipt-'); + await startCliLoopback(dataDir, { + hello: sendOk, + 'run.start': (ctx) => sendResult(ctx, { + run_id: 'run-fast-receipt', + status: 'completed', + completion_reason: 'success', + completed_steps: 2, + }), + }); + const receipts: Array<{ runId: string; flow: string }> = []; + + const execution = await runFlow( + join(TESTDATA, 'hello-deterministic.flow.yaml'), + dataDir, + { onJournalEntry: () => {}, onRunReceipt: receipt => receipts.push(receipt) }, + ); + + expect(execution.exitCode).toBe(0); + expect(receipts).toEqual([{ runId: 'run-fast-receipt', flow: 'hello-deterministic' }]); + }); + it('resumes a parked run from snapshot step types without reading journal sequence one', async () => { const dataDir = temporaryProject('flows-resume-snapshot-'); await startCliLoopback(dataDir, { diff --git a/packages/sdk/tests/cloud-mirror-live.test.ts b/packages/sdk/tests/cloud-mirror-live.test.ts index a9b3f83a3..c44e8ca58 100644 --- a/packages/sdk/tests/cloud-mirror-live.test.ts +++ b/packages/sdk/tests/cloud-mirror-live.test.ts @@ -8,7 +8,7 @@ // // Local HTTPS only. No hosted run is claimed and nothing leaves this machine. -import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { existsSync, readdirSync, readFileSync, statSync, symlinkSync } from 'node:fs'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { createServer, type Server } from 'node:https'; import { homedir, tmpdir } from 'node:os'; @@ -78,6 +78,8 @@ beforeAll(async () => { expect(existsSync(BUILT_CLI), `built CLI at ${BUILT_CLI} — build it with (cd packages/sdk && npm run build)`).toBe(true); work = await mkdtemp(join(tmpdir(), 'cloud-mirror-live-')); + symlinkSync(join(ROOT, 'packages', 'sdk', 'node_modules'), join(work, 'node_modules')); + await writeFile(join(work, 'package.json'), '{"type":"module"}'); const config = join(work, 'openssl.cnf'); await writeFile(config, '[req]\ndistinguished_name=dn\nx509_extensions=ext\n[dn]\n[ext]\n' + 'subjectAltName=IP:127.0.0.1\nbasicConstraints=critical,CA:TRUE\n'); @@ -127,12 +129,12 @@ describe('a local run on the Cloud dashboard', () => { seen = []; const run = await runCli(['run', '--cloud-mirror', '--no-observer-link', '--data-dir', join(work, 'data'), FLOW]); expect(run.code).toBe(0); - expect(run.stderr).toContain(`Dashboard: ${origin}/dashboard/workflow/live-cloud-run/runner`); // Registration is the operator's call; everything after it is the run's. expect(seen[0]).toMatchObject({ method: 'POST', url: '/api/v1/workflows/local-run', authorization: 'Bearer operator-token', }); + expect(run.stderr).toContain(`Dashboard: ${origin}/dashboard/workflow/live-cloud-run/runner`); const registration = seen[0]!.body as { workflow: string; fileType: string; relayflowVersion: string }; expect(registration.fileType).toBe('yaml'); expect(registration.relayflowVersion).toBe('v2'); @@ -184,4 +186,45 @@ describe('a local run on the Cloud dashboard', () => { expect(shell.stderr).toContain('Dashboard:'); expect(seen.some((call) => call.url === '/api/v1/workflows/local-run')).toBe(true); }, 180_000); + + it('publishes a composed authored flow as one connected dashboard DAG', async () => { + seen = []; + await writeFile(join(work, 'child.flow.ts'), `import { flow } from '@relayflows/surface'; +export default flow('child', async f => { + await f.run("printf '%s' child"); + f.done('success'); +}); +`); + const parent = join(work, 'parent.flow.ts'); + await writeFile(parent, `import { flow } from '@relayflows/surface'; +export default flow('parent', { use: ['./child.flow.ts'] }, async f => { + await f.run("printf '%s' before"); + await f.dispatch('child', {}); + await f.run("printf '%s' after"); + f.done('success'); +}); +`); + const run = await runCli(['run', '--cloud-mirror', '--no-observer-link', '--data-dir', + join(work, 'child-data'), parent, '--input', '{}']); + expect(run.code, run.stderr).toBe(0); + + const final = seen.find(call => call.url === '/api/v1/workflows/runs/live-cloud-run/steps')!; + const rows = (final.body as { steps: Array<{ stepName: string; label?: string; dependsOn?: string[] }> }).steps; + expect(rows.map(row => row.stepName)).toEqual([ + 'run-1', 'dispatch-2--run-1', 'dispatch-2', 'run-3', + ]); + expect(Object.fromEntries(rows.map(row => [row.stepName, { + label: row.label, dependsOn: row.dependsOn, + }]))).toEqual({ + 'run-1': { label: undefined, dependsOn: [] }, + 'dispatch-2--run-1': { label: undefined, dependsOn: ['run-1'] }, + 'dispatch-2': { label: 'child', dependsOn: ['dispatch-2--run-1'] }, + 'run-3': { label: undefined, dependsOn: ['dispatch-2'] }, + }); + expect(rows.some(row => /(?:^|--)complete-/.test(row.stepName))).toBe(false); + + const snapshot = seen.filter(call => call.url.endsWith('/steps/snapshot')).at(-1)!; + const live = (snapshot.body as { steps: Array<{ stepName: string; dependsOn?: string[] }> }).steps; + expect(live.map(step => step.stepName).sort()).toEqual(rows.map(row => row.stepName).sort()); + }, 120_000); }); diff --git a/packages/sdk/tests/worker-slots.test.ts b/packages/sdk/tests/worker-slots.test.ts index e7c1b304c..52fb55da2 100644 --- a/packages/sdk/tests/worker-slots.test.ts +++ b/packages/sdk/tests/worker-slots.test.ts @@ -51,6 +51,28 @@ describe('WorkerSlots', () => { expect(started).toEqual(['a']); }); + it('closing one scope leaves sibling and later pool admissions available', async () => { + const slots = new WorkerSlots(1); + const child = slots.scope(); + const sibling = slots.scope(); + const gate = deferred(); + const started: string[] = []; + const holder = slots.run(async () => { started.push('holder'); await gate.promise; }); + const childQueued = child.run(async () => { started.push('child'); }); + const siblingQueued = sibling.run(async () => { started.push('sibling'); return 'sibling'; }); + await Promise.resolve(); + + const reason = new Error('child failed'); + child.close(reason); + await expect(childQueued).rejects.toBe(reason); + await expect(child.run(async () => undefined)).rejects.toBe(reason); + gate.resolve(); + await holder; + expect(await siblingQueued).toBe('sibling'); + expect(await slots.run(async () => 'later')).toBe('later'); + expect(started).toEqual(['holder', 'sibling']); + }); + // The Cursor case on #554: the holder's own rejection fails the body, and // that failure reaches close() through microtasks only. A synchronous // handoff let the next waiter start before close() could refuse it. diff --git a/packages/surface/src/context.ts b/packages/surface/src/context.ts index 10cd9f1ee..2dbad9649 100644 --- a/packages/surface/src/context.ts +++ b/packages/surface/src/context.ts @@ -101,6 +101,16 @@ export interface LlmOptions { model?: string; } +/** Durable receipt returned after a statically declared child flow succeeds. */ +export interface DispatchResult { + /** The child flow's declared name. */ + name: string; + /** `success`; every other child verdict rejects the dispatch. */ + completionReason: 'success'; + /** The child's journaled completion detail, when it supplied one. */ + completionDetail?: string; +} + /** The optional second argument to {@link Ctx.done}. */ export interface DoneOptions { /** Why the flow reached this verdict; redacted, bounded, and journaled. */ @@ -143,7 +153,12 @@ export interface Ctx extends Helpers { * recorded with the question; it is not a delivery address. */ human(question: string, options: { to: string }): Step; - dispatch(flow: string, input: unknown): Promise; + /** + * Run a direct child declared in this flow's `use` header. The child shares + * this durable root, budget, worker capacity and Cloud graph; arbitrary + * paths and undeclared flow names are refused before the child body runs. + */ + dispatch(flow: string, input: unknown): Step; /** * Run every installed implementation of a named hook in lock order and * AND-compose the booleans. With no implementations this is a journaled diff --git a/packages/surface/src/index.ts b/packages/surface/src/index.ts index 2fcec2c38..ae42fee17 100644 --- a/packages/surface/src/index.ts +++ b/packages/surface/src/index.ts @@ -11,7 +11,7 @@ export type { CloudBabysitterTurnDelivery, CloudBabysitterTurnReceipt, } from "./cloud.js"; -export type { AgentOptions, AgentResult, DoneOptions, PermissionsSpec, LlmOptions, RunOptions, RunResult, Ctx } from "./context.js"; +export type { AgentOptions, AgentResult, DispatchResult, DoneOptions, PermissionsSpec, LlmOptions, RunOptions, RunResult, Ctx } from "./context.js"; export { COMPLETION_DETAIL_MAX_CODE_POINTS, COMPLETION_REASONS,