Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/CLOUD.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions docs/EVENT-AWAIT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
44 changes: 24 additions & 20 deletions docs/RFC-0002-callable-flow-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,16 +296,17 @@ authored `flow<Input>` 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

Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
58 changes: 51 additions & 7 deletions docs/SURFACE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}`
Expand All @@ -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})`);
});
```

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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/<id>/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
Expand Down
113 changes: 113 additions & 0 deletions packages/sdk/src/authored-dispatch.ts
Original file line number Diff line number Diff line change
@@ -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<DispatchResult> | 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<string> {
return new Set(flowRequirements(definition).integrations
.filter(requirement => requirement.from === 'tools' || requirement.from === 'helper')
.map(requirement => requirement.provider));
}
3 changes: 3 additions & 0 deletions packages/sdk/src/authored-flow-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Loading
Loading