Look up an API by name to find its signature, parameters, return type, example, and failure behavior. Each entry has a permanent link. For a first integration, start with Quick start. For a first flow, use Flows from scratch.
These docs describe version 0.6.0. See release notes for verified publication status. Replay, fixture comparison, and display masking require 0.5.0 or later. Check the changelog and your installed version.
How to read the signatures
Signatures below use Expression<T> as shorthand for FlowExpression<T> and Adapter for ReturnType<typeof createJevDevtools>; these are reading aids, not additional exports. Readable signatures omit some generic detail; expand the exact declarations below when you need it. SDKClientOptions means the TypeSafe SDK constructor options, and JoinedReferences means an object of lane-name references. These labels are not package exports. SDK request/client types belong to @typesafe-ai/sdk.
Find an API#
Code fragments use inspector for an adapter, recorder for a recorder, flow for a builder, and program for a defined flow. Fragments explain individual calls; the linked guides supply complete setup. Every builder method accepts optional final display: FlowDisplay metadata. See flow limits for shared ID, nesting, and execution limits.
jev-devtools
React#
JevDevtools#
The React component that adds the inspector drawer to your app. Use it to view requests and flow runs captured by your server adapter.
Signature#
JevDevtools(props: JevDevtoolsProps): ReactElement | nullProps for the React inspector. Enable it explicitly in development and point it at the matching server endpoint.
Import from jev-devtools
type JevDevtoolsProps = {
enabled?: boolean;
endpoint?: string;
defaultOpen?: boolean;
redactAdditionalSensitiveData?: boolean;
}- enabled?
- Defaults to false. Starts the browser inspector when true.
- endpoint?
- Same-origin inspector path; defaults to /api/jev-devtools.
- defaultOpen?
- Defaults to true. Controls the initial drawer state.
- redactAdditionalSensitiveData?
- Available since 0.5.0. Defaults to true; masks supported personal fields in the display, not the stored capture.
API reference: JevDevtoolsProps
Import: jev-devtools. Render once in your React app. It returns nothing during SSR or while disabled; once enabled and mounted it loads the connected drawer.
Inputs#
| Input prop | Default | Meaning |
|---|---|---|
enabled?: boolean |
false |
Opt in to connecting and showing the inspector. |
endpoint?: string |
/api/jev-devtools |
Same-origin inspector path; match the server. |
defaultOpen?: boolean |
true |
Open the drawer on its initial mount. |
redactAdditionalSensitiveData?: boolean |
true |
0.5.0. Mask supported personal fields in the display. Captured/streamed values remain unchanged. |
Unmounting or disabling closes its subscription. Closing the drawer alone does not stop capture. React setup explains mounting and styling.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | React element or null |
Nothing during SSR/disabled state; the mounted inspector when enabled. |
Example#
import { JevDevtools } from "jev-devtools";
<JevDevtools enabled={import.meta.env.DEV} />;Mount the inspector once near your application root. It connects after mounting when enabled; it renders nothing during SSR.
<JevDevtools enabled defaultOpen={false} />- enabled
- Load and connect the browser inspector. Defaults to false; enable the server adapter separately.
- defaultOpen
- Whether the drawer starts expanded. Defaults to true; false starts at the launcher.
- endpoint
- Same-origin inspector path. Defaults to /api/jev-devtools; must match the server adapter.
- redactAdditionalSensitiveData
- Mask supported personal fields in the display. Does not remove captured data. Available since 0.5.0; defaults to true.
Load and connect the browser inspector. Defaults to false; enable the server adapter separately.
enabledAPI reference: JevDevtools
How it works#
The component enables the inspector only in Vite development builds through import.meta.env.DEV. Mounting it once gives the application one drawer and one connection.
The drawer injects its own stylesheet into its Shadow DOM; no CSS import is needed.
JevFlowViewer#
Version 0.6.0. Embed the same diagram and request inspector used by the drawer in an ordinary React layout.
Signature#
JevFlowViewer(props: JevFlowViewerProps): ReactElementUnreleased. Graph, optional captured execution, and presentation controls for the embedded flow viewer. Filtering and highlighting do not change execution.
Import from jev-devtools/viewer
type JevFlowViewerProps = { definition: FlowDefinition; run?: FlowRun; traces?: Trace[]; selectedNodeId?: string; onNodeSelect?: (id: string) => void; visibleNodeIds?: readonly string[]; highlightedNodeIds?: readonly string[]; nodeAccents?: Readonly<Record<string, string>>; }API reference: JevFlowViewerProps
Import: jev-devtools/viewer. This browser entry does not import the Node flow runner.
Inputs#
| Prop | Meaning |
|---|---|
definition: FlowDefinition |
Authored graph to render. |
run?: FlowRun |
Captured execution for this definition. Omit to show a definition that has not run. |
traces?: Trace[] |
Captured request details, default []. |
selectedNodeId?: string |
Controlled selected node. Keeps the selected or highlighted nodes framed when the container resizes. Omit for internal selection. |
onNodeSelect?: (id: string) => void |
Receives a selected top-level node ID. |
visibleNodeIds?: readonly string[] |
Present only these top-level nodes and their visible dependency edges. Omit to show all. |
highlightedNodeIds?: readonly string[] |
Add an outline to matching nodes. |
nodeAccents?: Readonly<Record<string, string>> |
CSS colors for node top rules, indexed by node ID. |
Returns#
A React host element. On mount, the diagram renders inside its Shadow DOM with its own styles. SSR renders the empty host. Set the container height; 400 pixels or more is recommended, but the viewer can shrink with a smaller split pane. Display masking is always applied and leaves the supplied data unchanged. Missing request capture remains explicitly unavailable.
Example#
import { JevFlowViewer, useJevInspection } from "jev-devtools/viewer";
export function FlowWorkspace() {
const { flows, traces, connection } = useJevInspection({
enabled: import.meta.env.DEV,
});
const run = flows.runs[flows.runs.length - 1];
const definition = flows.definitions.find(
(item) => item.id === run?.definitionId,
);
return (
<section>
<p>{connection}</p>
{definition && (
<div style={{ height: 600 }}>
<JevFlowViewer definition={definition} run={run} traces={traces} />
</div>
)}
</section>
);
}Unreleased. Subscribe to validated, display-masked flow and trace snapshots from the existing server adapter.
useJevInspection({ enabled, endpoint? })- enabled
- Opt in to connecting. Defaults to false; enable the server separately.
- endpoint
- Same-origin inspector path, default /api/jev-devtools. Queries and fragments are rejected.
Opt in to connecting. Defaults to false; enable the server separately.
enabledUnreleased. Embed the drawer's flow diagram in a Shadow DOM. Without a run it shows the authored structure; rendering never executes the flow.
<JevFlowViewer definition={definition} run={run} traces={traces} />- definition
- The authored FlowDefinition to render.
- run
- Optional captured execution for this definition.
- traces
- Captured request details; defaults to an empty array.
- selectedNodeId
- Control which top-level node is selected.
- onNodeSelect
- Receive the selected node ID.
- visibleNodeIds
- Limit the presented top-level nodes without modifying execution.
- highlightedNodeIds
- Outline matching nodes.
- nodeAccents
- CSS colors indexed by node ID for source-to-diagram cues.
The authored FlowDefinition to render.
definitionOptional captured execution for this definition.
runCaptured request details; defaults to an empty array.
tracesHow it works#
The viewer reuses the drawer's flow cards, request diagrams, details, and pan/zoom controls. Selection can focus nodes; visible-node changes animate unless reduced motion is requested. Presentation filters never modify the supplied definition or execute a flow. Source-code mapping belongs to the application.
useJevInspection#
Version 0.6.0. Subscribe to the validated flow and request capture streams used by the drawer.
Signature#
useJevInspection(options?: { endpoint?: string; enabled?: boolean }): InspectionSnapshotUnreleased. Latest validated, display-masked request and flow history, plus the inspector connection status.
Import from jev-devtools/viewer
type InspectionSnapshot = { traces: Trace[]; flows: { runs: FlowRun[]; definitions: FlowDefinition[] }; connection: string; }API reference: InspectionSnapshot
Import: jev-devtools/viewer.
Inputs#
enabled defaults to false. endpoint defaults to /api/jev-devtools and must be same-origin without credentials, query, or fragment. The server adapter must also be enabled.
Returns#
{ flows: { definitions, runs }, traces, connection }. Disabled state contains empty histories. Connection failures appear in connection. Unmounting, disabling, or changing endpoints closes the previous subscriptions. Display masking does not remove values from server capture or transport.
Example#
The checked FlowWorkspace example above selects a captured run, resolves its definition, and passes both to the viewer.
How it works#
The hook verifies the adapter handshake, then subscribes to validated flow and trace streams. Each update contains the latest retained history, including removals and reconnections.
jev-devtools/server
Server adapter#
Import factories from jev-devtools/server. All server adapter and recorder runtime code belongs on Node.
createJevDevtools#
Creates the server adapter that connects SDK request capture to the browser inspector. Share one instance between your clients and inspector routes.
Signature#
createJevDevtools(options: JevDevtoolsServerOptions): AdapterServer adapter configuration. Extends CaptureOptions with enablement, origin checks, routing, and session selection.
Import from jev-devtools/server
type JevDevtoolsServerOptions = CaptureOptions & {
origin: string;
enabled?: boolean;
endpoint?: string;
authorize?: (request: Request) => boolean | Promise<boolean>;
getSession?: (request: Request) => string | Promise<string>;
}- origin
- Exact browser origin, including port.
- enabled?
- Recording is disabled unless explicitly enabled.
- authorize?
- Application access check; required for non-loopback origins.
- getSession?
- Derives the recording session on the server; defaults to local.
API reference: JevDevtoolsServerOptions
Each call creates independent in-memory histories. Use getJevDevtools() when modules need to reuse an adapter by key.
Inputs#
| Input | Default | Meaning |
|---|---|---|
origin: string |
Required | Exact browser origin, including port. |
enabled?: boolean |
false |
Enable recording and HTTP endpoints. |
endpoint?: string |
/api/jev-devtools |
Absolute path without query or fragment. |
limit?: number |
50 |
Global trace retention; clamped to 1–200. |
redact?: (path: string[], value: unknown) => unknown |
None | Transform the captured copy before storage/delivery. |
authorize?: (request: Request) => boolean | Promise<boolean> |
None | Access check; required for enabled non-loopback origins. |
getSession?: (request: Request) => string | Promise<string> |
"local" |
Trusted recording scope, nonempty and at most 200 characters. |
Invalid origin or endpoint configuration throws. Enabling a non-loopback origin without authorize also throws. See Privacy & access for authentication, session scopes, and redaction.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Adapter |
Independent adapter with client, routing, session, observer, and disposal methods. |
Example#
import { createJevDevtools } from "jev-devtools/server";
const inspector = createJevDevtools({
enabled: true,
origin: "http://localhost:3000",
});Create an independent Node server adapter. Share it between your HTTP endpoints and instrumented clients.
createJevDevtools(options)- enabled
- Opt into server capture and inspector endpoints. Defaults to false; disabling capture does not stop inference.
- origin
- The exact browser origin, including scheme, hostname, and port.
- endpoint
- The inspector URL path. Defaults to /api/jev-devtools; must match the browser component.
- limit
- Maximum retained request traces across sessions. Defaults to 50; clamped to 1–200.
- redact
- Transform the captured copy before storage or streaming. Incompatible structured content remains as JSON in Trace.capture with warnings. The drawer keeps usable fields visible beside unavailable placeholders. SDK inputs and application values stay unchanged.
- authorize
- Your application access check. Required for an enabled non-loopback origin.
- getSession
- Derive a trusted recording scope from the request. Defaults to the shared local scope.
Opt into server capture and inspector endpoints. Defaults to false; disabling capture does not stop inference.
enabledThe exact browser origin, including scheme, hostname, and port.
originAPI reference: createJevDevtools()
How it works#
The example enables capture and binds inspector access to the browser origin http://localhost:3000. Keep this adapter instance shared between the HTTP routes and instrumented clients.
getJevDevtools#
Gets or creates a server adapter under a stable key. Use it to preserve the same recorder and history across module reloads in one Node process.
Signature#
getJevDevtools(key: string, createOptions: () => JevDevtoolsServerOptions): AdapterAPI reference: JevDevtoolsServerOptions
Inputs#
| Parameter / option | Type |
|---|---|
key |
string |
createOptions |
() => JevDevtoolsServerOptions |
Use a nonblank, app-specific key and a synchronous options factory. The first call creates an adapter. Later calls with the same key in the same Node realm return that adapter without calling the factory again.
The first options remain in effect until disposal or process restart. Empty keys throw. Separate processes have separate histories. See Next.js setup for sharing an adapter across module reloads.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Adapter |
Existing adapter for the key, or a newly created adapter. |
Example#
import { getJevDevtools } from "jev-devtools/server";
const inspector = getJevDevtools("my-app", () => ({
enabled: true,
origin: "http://localhost:3000",
}));Reuse an adapter for a stable key in the same Node realm. The options factory runs once per key; restart after configuration changes. Different processes do not share history.
getJevDevtools(key, createOptions)- key
- A stable, nonempty application key.
- createOptions
- Return the server options, including enabled and origin.
API reference: getJevDevtools() · createJevDevtools()
How it works#
The stable "my-app" key reuses the adapter during module reloads. The callback supplies configuration only when an adapter for that key does not already exist.
adapter.createClient#
Creates a TypeSafe SDK client with request recording configured for this adapter. Use it for the calls you want to inspect.
Signature#
inspector.createClient(options: SDKClientOptions, metadata?: ClientMetadata): TypeSafeClientOptional labels attached to captured calls. A sample label does not prevent a real network request.
Import from jev-devtools/server
type ClientMetadata = { label?: string; source?: "sample" | "live" }- label?
- Name shown for captured requests.
- source?
- Marks captures as sample or live; it does not alter the client transport.
API reference: ClientMetadata
Inputs#
| Parameter / option | Type |
|---|---|
options |
SDKClientOptions |
metadata? |
ClientMetadata |
Pass the TypeSafe SDK's constructor options, including a server-side key or custom fetch. Optional metadata defaults to label: "Jev request" and source: "live".
When enabled, the adapter records systemOne calls through the returned client. When disabled, it returns an ordinary SDK client. Other SDK methods are not instrumented. source: "sample" only labels a capture: the client's transport still determines whether a call reaches the inference service.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | TypeSafeClient |
SDK client; instrumented when the adapter is enabled. |
Example#
const client = inspector.createClient(
{ apiKey: process.env.TYPESAFE_API_KEY },
{ label: "Support", source: "live" },
);Create an instrumented TypeSafe client. Captures systemOne calls when recording is enabled; otherwise returns an ordinary SDK client. Keep credentials on the server.
adapter.createClient(options, metadata?)- label
- Optional capture label. Defaults to Jev request.
- source
- Capture label: sample or live. Defaults to live. This does not switch transports or prevent inference.
Optional capture label. Defaults to Jev request.
labelCapture label: sample or live. Defaults to live. This does not switch transports or prevent inference.
sourceAPI reference: adapter.createClient()
How it works#
The first argument configures the SDK with a server-side key. The second adds a human-readable capture label and marks the capture as live; it does not change the SDK request behavior.
adapter.handle#
Serves the inspector’s HTTP endpoints from a Web Request. Use it when your framework exposes the request’s actual public URL.
Signature#
inspector.handle(request: Request): Promise<Response>Inputs#
| Parameter / option | Type |
|---|---|
request |
Request |
Forward the base inspector path and all its subpaths to this handler. It returns configuration JSON, an event stream, a clear response, or an HTTP error.
Disabled adapters and unmatched paths return 404. Origin or authorization failures return 403. Errors thrown by authorization or session callbacks can reject the promise, so let your framework handle them.
A Web Request does not expose the socket address. Bind the server to loopback or configure authorization.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Promise<Response> |
Resolves to an HTTP response; includes HTTP error responses. |
Example#
const response = await inspector.handle(request);Handle a Web Request with its actual public URL and return a Web Response. Applies the adapter's access checks.
adapter.handle(request)API reference: adapter.handle()
How it works#
The application passes its incoming Web Request to the adapter and awaits a Web Response. Return that response from your framework’s inspector route.
adapter.handleNodeRoute#
Serves inspector endpoints in Node frameworks that may expose internal request URLs. It validates the Host header before routing the request.
Signature#
inspector.handleNodeRoute(request: Request): Promise<Response>Inputs#
| Parameter / option | Type |
|---|---|
request |
Request |
Pass the framework's Web Request with its actual Host header. The handler checks Host against the configured origin's host and port, then normalizes the request URL and delegates to handle().
Forwarded host headers are not trusted. The response and error behavior otherwise follows handle(), including its loopback-binding or authorization requirement. See the Next.js route example.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Promise<Response> |
Response after Host validation and URL normalization. |
Example#
export const GET = (request: Request) => inspector.handleNodeRoute(request);
export const DELETE = GET;Check Host, normalize a Node framework's internal request URL, and apply the adapter's access checks. Route the base endpoint and all subpaths here.
adapter.handleNodeRoute(request)API reference: adapter.handleNodeRoute()
How it works#
The route exposes the same handler for GET and DELETE. The adapter checks Host before serving configuration, event streams, or a clear request.
adapter.middleware#
Connects the inspector endpoints to an Express or Connect-style server. Requests outside the inspector path continue to your application.
Signature#
inspector.middleware(req: IncomingMessage, res: ServerResponse, next: () => void): Promise<void>Inputs#
| Parameter / option | Type |
|---|---|
req |
IncomingMessage |
res |
ServerResponse |
next |
() => void |
Mount at the application root so the inspector path reaches the middleware unchanged. It handles matching requests and calls next() for unrelated paths. The returned promise completes when handling or delegation finishes.
Without authorize, enabled endpoints accept only loopback socket connections. Route errors produce HTTP 500 when possible, or destroy a response that has already started.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Promise<void> |
Completes after response handling or calls next for an unrelated path. |
Example#
app.use(inspector.middleware); // app is your Express/Connect serverMount at the application root to serve inspector endpoints and their subpaths. Unrelated routes call next().
app.use(adapter.middleware)API reference: adapter.middleware
How it works#
Mounting the middleware on app preserves the full inspector path. Requests outside that path continue through next() to the application’s other handlers.
adapter.run#
Runs application work within the recording session selected for an incoming request. Use it when separate users or requests need separate inspection histories.
Signature#
inspector.run<T>(request: Request, callback: () => T | Promise<T>): Promise<T>Inputs#
| Parameter / option | Type |
|---|---|
request |
Request |
callback |
() => T | Promise<T> |
Pass the application's authenticated request and a callback containing the work to record. The adapter calls getSession(request) and keeps that recording scope active for the callback's asynchronous work.
The promise resolves to the callback's value and propagates failures. This wrapper is needed for custom session scopes. It does not authorize the application action.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Promise<T> |
Resolves to the application callback’s result; callback errors propagate. |
Example#
return inspector.run(request, () => client.systemOne(input));Run application code in the request's server-derived recording scope. Needed when getSession is customized. Authenticate the application action separately.
adapter.run(request, callback)API reference: adapter.run()
How it works#
The request determines the recording session. The callback performs the SDK call inside that session, and its result becomes the resolved value of inspector.run().
adapter.dispose#
Shuts down an adapter, stopping capture and closing its event streams. Call it when the server shuts down or you deliberately replace the adapter.
Signature#
inspector.dispose(): voidInputs#
No parameters.
Disposal disables capture and inspector endpoints and closes active streams. A shared adapter releases its key, allowing a later getJevDevtools() call to create a new instance. Dispose at shutdown or deliberate reinitialization, not after each request.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | void |
No data is returned. |
Example#
inspector.dispose();Disable the adapter and close active streams. A shared adapter also releases its key. Use at shutdown, not after each request.
adapter.dispose()API reference: adapter.dispose()
How it works#
This shutdown call disables recording and closes streams owned by the adapter. A shared adapter also releases its registry key.
jev-devtools/flow
Flow definitions and steps#
Import defineJevFlow from jev-devtools/flow on Node. Builder methods describe work synchronously; they do not execute it. The complete examples below pair each definition with an async function that awaits its run() and reads the result. Call that function from Node to execute the example. Start with Flows from scratch for a greeting task. The entries below provide complete examples for the other operations.
defineJevFlow#
Defines a reusable sequence of tasks, Jev requests, and decisions. The callback builds the recipe synchronously; calling the returned flow’s run() executes it.
Signature#
defineJevFlow<Input>(name: string, build: (flow: FlowBuilder<Input>) => Expression<FlowOutcome>): { definition: FlowDefinition; run: /* see below */ }The object passed to a synchronous flow-building callback. Its input and step methods create references; run() later executes the definition.
Import from jev-devtools/flow
FlowBuilder<Input>- input
- A reference to this builder's input shape.
- task / jev
- Define application work or a model request.
- if / branch / parallel / map / loop
- Define conditional, concurrent, or repeated work.
- output
- Return a named terminal outcome and optional value.
The named result of a completed flow. run() adds a runId. The public value type is unknown; narrow it before using it in application code.
Import from jev-devtools/flow
type FlowOutcome = { outcome: string; value?: unknown }- outcome
- The name passed to the selected output() step.
- value?
- The resolved output data, when supplied.
API reference: FlowBuilder · FlowOutcome
Inputs#
| Parameter / option | Type |
|---|---|
name |
string |
build |
(flow: FlowBuilder<Input>) => FlowExpression<FlowOutcome> |
Use a nonblank name of at most 100 characters. The synchronous build callback must return a terminal output() or branch().
The returned { definition, run } can be reused for multiple executions. Building it sends no SDK requests. Invalid IDs, scopes, nesting, or terminal structure throw during definition.
Returns#
| Value / member | Type | Description |
|---|---|---|
| definition | FlowDefinition |
Static graph. |
| run | (input: Input, options: FlowRunOptions) => Promise<FlowOutcome & { runId: string }> |
Executes a fresh run. |
Example#
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the steps. No application work runs here.
export const greet = defineJevFlow<{ name: string }>("greet", (flow) => {
return flow.output("greeted", flow.input.get("name"));
});
// This flow has no Jev steps: no API key or network access is needed.
const noInference = {
systemOne() { throw new Error("This example does not call Jev"); },
};
// 2. Call tryGreeting() from Node to execute the flow.
export async function tryGreeting() {
const result = await greet.run({ name: "Ada" }, { client: noInference });
console.log(result.outcome); // "greeted"
console.log(result.value); // "Ada"
return result;
}Describe a flow once, then run it with different inputs. Defining it does not send requests.
defineJevFlow<Input>(name, build)- name
- The flow name shown in DevTools.
- build
- Receives a builder. Return an output or a terminal branch.
Finish this path with a named outcome and, optionally, a value for your application.
flow.output(name, value?, display?)- name
- The outcome string returned by run().
- value?
- Optional result data. Narrow its type in your application before using it.
- display?
- Optional labels and display metadata for DevTools.
A reference to the data passed to run(). Inside map/loop programs, it refers to the item or iteration input instead.
flow.input: FlowExpression<Input>Select a field owned by an object, an array index, or array length. TypeScript rejects array methods. Missing fields and array bounds remain execution checks; use a task for string operations.
expression.get(key)Start the flow with new input and await its steps, including SDK requests. Use await to read { runId, outcome, value? }.
program.run(input, { client, devtools?, signal? })- input
- Data matching the input type declared in defineJevFlow.
- client
- The TypeSafe-compatible client that executes Jev requests.
- devtools?
- An optional observer, such as the shared server adapter, that records execution.
- signal?
- An optional AbortSignal to cancel the run.
The TypeSafe-compatible client that executes Jev requests.
clientAPI reference: defineJevFlow() · flow.output() · flow.input · expression.get() · program.run()
How it works#
greet records the input reference and terminal output synchronously. Calling tryGreeting() awaits greet.run({ name: "Ada" }, ...) and reads outcome "greeted" and value "Ada". The no-inference client needs no key because this definition has no Jev steps.
flow.run#
Executes a defined flow with concrete input and a client. Await it to receive the selected outcome and resolved output value.
Signature#
program.run(input: Input, options: FlowRunOptions): Promise<{ runId: string; outcome: string; value?: unknown }>Execution settings passed to a flow's run() method. The client is required even when the flow contains only tasks.
Import from jev-devtools/flow
type FlowRunOptions = {
client: Pick<TypeSafeClient, "systemOne">;
devtools?: FlowObserver;
signal?: AbortSignal;
}- client
- Executes Jev request steps. Use your server client for live requests.
- devtools?
- Observer that records the execution, usually the server adapter.
- signal?
- Cancels the run. Tasks should cooperate with the signal they receive.
API reference: FlowRunOptions
Inputs: the typed input promised by defineJevFlow and these options:
Inputs#
| Option | Meaning |
|---|---|
client |
Required client with SDK-compatible systemOne, even for task-only flows. |
devtools? |
Optional FlowObserver, usually your server adapter. |
signal? |
Optional AbortSignal to cancel the run. |
Each execution gets a fresh runId and resolves to the selected outcome and optional value. The public value type is unknown, so validate or narrow it before use. The result is not an inferred discriminated union.
Errors and cancellation reject the promise. Tasks must cooperate with their signal. Execution has no rollback or automatic retry.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Promise<FlowOutcome & { runId: string }> |
Await to receive the fields below. |
| runId | string |
Unique execution ID. |
| outcome | string |
Selected terminal outcome name. |
| value? | unknown |
Resolved output value; narrow its type in application code. |
Example#
const result = await program.run(
{ name: "Ada" },
{ client, devtools: inspector },
);
console.log(result.outcome, result.value);How it works#
The input object supplies Ada’s name. client enables SDK steps and devtools: inspector enables recording. Awaiting the promise yields the chosen outcome and resolved output value.
flow.definition#
The static graph describing a flow’s steps and connections. Read it to inspect the recipe or pair it with a captured run when creating a fixture.
Signature#
program.definition: FlowDefinitionInputs#
No parameters.
Treat this graph as read-only. It contains the version, ID, name, and nodes. Reading it does not execute the flow, and mutating it is not a supported way to change execution. Pair it with a captured FlowRun when building a fixture.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Property value | FlowDefinition |
Version, identity, name, and graph nodes. No work is executed. |
Example#
console.log(program.definition.name, program.definition.nodes.length);How it works#
Reading name and the node count inspects the recipe’s static structure. It does not execute tasks or send requests.
flow.input#
A reference to the data supplied to the current flow, map item, or loop iteration. Use it to pass input into steps or select individual fields.
Signature#
flow.input: FlowExpression<Input>A typed reference to a value that becomes available when the flow runs. It is not the value itself and is not a promise to await.
Import from jev-devtools/flow
FlowExpression<T>- get
- Select an own object field, array index, or array length. Array methods and primitive properties are unsupported.
- eq / lt / gt / gte
- Build scalar equality or numeric ordering conditions. Execution validates matching scalar types and finite numbers.
API reference: FlowExpression
Inputs#
No parameters.
During definition, this property is a reference to the input. Its resolved shape depends on the builder:
- Ordinary flow, path, or lane:
Input. - Map item:
{ item, index, context }. - Loop iteration:
{ state, index, context }.
Select a field with get(), or pass the whole reference to a task, request, or output.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Property value | FlowExpression<Input> |
Reference to the current flow, item, or iteration input. |
Inside a synchronous defineJevFlow() callback; these references resolve when you await the flow’s run(). See the complete definition and execution.
Example#
const name = flow.input.get("name");API reference: flow.input · expression.get()
How it works#
The get("name") call selects a typed field reference. Pass that reference to a task or output to resolve it during execution.
flow.task#
Adds a step that runs your application code, such as fetching data or transforming a value. Its callback receives resolved inputs and can return a value or a promise.
0.5.1: Task inputs reject own symbol keys, including nested objects and arrays. Literal templates fail during definition; referenced values fail when resolved, before the callback runs.
Signature#
flow.task<I, O>(id: string, task: FlowTask<I, O>, display?: FlowDisplay): Expression<Awaited<O>>Configuration for application code inside a flow. Input references resolve before the callback runs; the callback can return a value or a promise.
Import from jev-devtools/flow
type FlowTask<I, O> = {
input: I;
run: (input: Resolved<I>, context: TaskContext) => O | Promise<O>;
timeoutMs?: number;
}- input
- Values or nested flow references passed to the callback.
- run
- Receives actual values and produces the task result.
- timeoutMs?
- Limits the wait and signals cancellation. It cannot undo side effects or forcibly stop non-cooperating work.
Optional labels for a step in the inspector. These are display metadata, not instructions to the model or changes to execution.
Import from jev-devtools/flow
type FlowDisplay = { title?: string; description?: string }- title?
- A readable step title.
- description?
- Short explanation for someone inspecting the flow. Keep it safe to display.
API reference: FlowTask · FlowDisplay
Inputs#
| Parameter / option | Type |
|---|---|
id |
string |
task.input |
I |
task.run |
(input: Resolved<I>, context: TaskContext) => O | Promise<O> |
task.timeoutMs? |
number |
display? |
FlowDisplay |
The runner resolves nested references in input before calling run(resolvedInput, context). The callback may return a value or a promise. Its context contains signal, runId, stepId, and executionId.
If provided, timeoutMs must be an integer from 1 to 2,147,483,647. A failure rejects the flow. A timeout stops waiting and signals cancellation, but cannot stop code that ignores the signal or undo its side effects. See the greeting task example.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Builder return | FlowExpression<Awaited<O>> |
Reference to the callback result. |
| Resolved value | Awaited<O> |
Actual callback result after awaiting it, if needed. |
Example#
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the steps. No application work runs here.
export const greeting = defineJevFlow<{ name: string }>("greeting", (flow) => {
const message = flow.task("make-message", {
input: flow.input.get("name"),
run: (name) => `Hello, ${name}!`,
});
return flow.output("greeted", message);
});
// This flow has no Jev steps: no API key or network access is needed.
const noInference = {
systemOne() { throw new Error("This example does not call Jev"); },
};
// 2. Call tryTask() from Node to execute the flow.
export async function tryTask() {
const result = await greeting.run({ name: "Ada" }, { client: noInference });
console.log(result.outcome); // "greeted"
console.log(result.value); // "Hello, Ada!"
return result;
}Resolve input references, run application code, and return a reference to its result. Tasks do not retry automatically.
flow.task(id, { input, run, timeoutMs? }, display?)- input
- Values and nested flow references resolved before run is called.
- run
- Your callback receives the resolved input and task context, including a cancellation signal.
- timeoutMs?
- Optional time limit. The callback must cooperate with cancellation; a timeout cannot undo side effects.
Values and nested flow references resolved before run is called.
inputYour callback receives the resolved input and task context, including a cancellation signal.
runAPI reference: defineJevFlow() · flow.task() · flow.input · expression.get() · flow.output() · program.run()
How it works#
get("name") selects the input field. The task resolves it before calling run, so name inside the callback is an ordinary string. The template literal constructs the greeting. output("greeted", message) resolves that task result and makes it the final flow value. Calling tryTask() awaits greeting.run({ name: "Ada" }, ...), then reads outcome "greeted" and value "Hello, Ada!" from the finished run.
flow.jev#
Adds a Jev request step and provides references to its future answers. The request is sent when the flow runs, so later steps can use those answers.
Signature#
flow.jev(id, request, display?): AnswerRefs
flow.jev(id, { input, request: (resolvedInput) => sdkRequest }, display?): AnswerRefsInputs#
| Parameter / option | Type |
|---|---|
id |
string |
request |
SDK request with expression-capable state, or FlowRequestFactory<I, Q> |
display? |
FlowDisplay |
Choose one request form:
- SDK request: pass a regular request whose
statemay contain nested flow references. The runner resolves state before sending it. - Request factory: pass
{ input, request }. The runner resolvesinput, then calls the synchronousrequestcallback to construct the SDK request. Use a preceding task for asynchronous preparation.
The request's questions define the named SDK question types. Other SDK request options pass through.
Both forms return .answer(name) field references and .answers for the full answer object, typed from the questions. Use .answers when a factory generates question names dynamically.
SDK failures reject the run. A request factory must return synchronously, not return a promise. Complete examples of both forms follow.
Returns#
| Value / member | Type | Description |
|---|---|---|
| answer(name) | Object of typed answer-field expressions |
Selects one question’s fields, such as choice or noul. |
| answers | FlowExpression<{ [K in keyof Q]: ResultFor<Q[K]> }> |
Reference to all answers. |
| Resolved answer fields | SDK ResultFor<Q[K]> fields |
Actual field values for the selected SDK question type. |
Define now, request later. flow.jev() returns future-answer references, not a promise. await classify.run(...) executes the request and waits for its answer. Call tryClassify(jev) with the client from the server setup.
Example#
import { choice, type TypeSafeClient } from "@typesafe-ai/sdk";
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the request. This does not contact Jev.
export const classify = defineJevFlow<{ message: string }>("classify", (flow) => {
const result = flow.jev("ask-team", {
state: flow.input,
questions: {
team: choice("Which team can help?", {
billing: "Charges and payments",
support: "Everything else",
}),
},
});
return flow.output("classified", result.answer("team").choice);
});
// 2. Call tryClassify(jev) from your Node handler.
// jev is the client created in the server setup; it needs a real API key.
export async function tryClassify(client: TypeSafeClient) {
const result = await classify.run(
{ message: "I was charged twice." },
{ client },
);
console.log(result.outcome); // "classified"
console.log(result.value); // "billing" or "support", chosen by the model
return result;
}Define a Jev request step synchronously. Returns future-answer references, not a promise. The request runs and is awaited when you call program.run().
flow.jev(id, { state, questions }, display?)- id
- A unique step ID within this flow.
- state
- Context sent to Jev for this request. Flow references are resolved when the step runs.
- questions
- Named questions to ask. Their keys identify the returned answers.
- display?
- Optional labels and display metadata for DevTools.
Context sent to Jev for this request. Flow references are resolved when the step runs.
stateNamed questions to ask. Their keys identify the returned answers.
questionsReference the result of a named question. The name must match a key in questions; answer fields can be used in later steps.
request.answer(name)A reference to the label selected by a Choice question. Its allowed labels come from that question’s alternatives.
choice: FlowExpression<Label>API reference: defineJevFlow() · flow.jev() · flow.input · flow.output() · answer.choice · program.run()
How it works#
state: flow.input sends the message as context. The SDK's choice() helper defines the allowed teams and their descriptions. answer("team").choice selects the model's chosen label, and output() returns it. tryClassify() supplies a concrete message to await classify.run(...). After the request finishes, result.outcome is "classified" and result.value contains the chosen team. The selected team is not predetermined.
Request factory example#
Use the factory form when a question needs a resolved input value. Call tryCustomQuestion(jev) with the same server client. This example makes a live request and requires a server-side API key.
import { choice, type TypeSafeClient } from "@typesafe-ai/sdk";
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the request. This does not contact Jev.
export const customQuestion = defineJevFlow<{ message: string }>(
"custom-question",
(flow) => {
const result = flow.jev("ask", {
input: flow.input.get("message"),
request: (message) => ({
state: { message },
questions: {
team: choice(`Who can help with: ${message}?`, {
billing: null,
support: null,
}),
},
}),
});
return flow.output("answered", result.answers);
},
);
// 2. Call tryCustomQuestion(jev) from your Node handler.
// jev is the client created in the server setup; it needs a real API key.
export async function tryCustomQuestion(client: TypeSafeClient) {
const result = await customQuestion.run(
{ message: "I was charged twice." },
{ client },
);
console.log(result.outcome); // "answered"
console.log(result.value); // The full answer object, including team and its metadata
return result;
}API reference: defineJevFlow() · flow.jev() · flow.input · expression.get() · flow.output() · program.run()
The factory receives the resolved message and includes it in the question. result.answers keeps the complete answer object, which flow.output() returns as the run's value. The factory returns synchronously; use a preceding task for asynchronous preparation. await customQuestion.run(...) executes the request before tryCustomQuestion() reads the result.
request.answer#
Selects one named question’s answer fields as flow references. Use it when a later step needs a specific field, such as a chosen label or numeric result.
Signature#
result.answer<Name extends keyof Questions>(name: Name): AnswerFieldReferencesInputs#
| Parameter / option | Type |
|---|---|
name |
A key of the request’s Questions type |
Use the name of a question in the Jev step. The returned object contains typed field references such as .choice, .noul, .score, and .box, plus other fields supported by that question type.
Selecting an answer does not send another request. Unknown static question names fail during definition. Questions generated by a factory must exist when executed. A Noul represents the probability that a statement is true, not a confidence score.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Object of FlowExpression fields |
Each result field is an expression with its SDK-defined value type. |
Inside a synchronous defineJevFlow() callback; these references resolve when you await the flow’s run(). See the complete definition and execution.
Example#
const team = result.answer("team").choice; // expression for a Choice resultHow it works#
answer("team") selects the named question and .choice selects its chosen label. The assignment stores a reference, not an immediate model response.
request.answers#
A reference to the complete answer object from a Jev step. Use it to pass all answers onward, including questions named dynamically by a request factory.
Signature#
result.answers: Expression<{ [Name in keyof Questions]: ResultFor<Questions[Name]> }>Inputs#
No parameters.
During definition, this property is a reference to the full SDK answer object. Pass it to a task or output to use the resolved answers. It is useful when a request factory generates question names at runtime.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Property value | FlowExpression<{ [K in keyof Q]: ResultFor<Q[K]> }> |
Reference to the complete answer object. |
Inside a synchronous defineJevFlow() callback; these references resolve when you await the flow’s run(). See the complete definition and execution.
Example#
return flow.output("answers", result.answers);API reference: flow.output()
How it works#
Passing the full answer reference to output() returns every answer and its SDK metadata in the flow value, rather than extracting one field.
flow.if#
Chooses between two paths and produces a value for subsequent steps. Use it when the paths should rejoin and the flow should continue.
Signature#
flow.if<A, B>(id, { when, then, else }, display?): Expression<A | B>Inputs#
| Parameter / option | Type |
|---|---|
id |
string |
paths.when |
FlowExpression<boolean> |
paths.then |
(path: FlowBuilder<Input>) => FlowExpression<A> |
paths.else |
(path: FlowBuilder<Input>) => FlowExpression<B> |
display? |
FlowDisplay |
when must be a Boolean expression. Both path callbacks build synchronously using their supplied path builder, but only the selected path executes.
Each callback must return a value reference. The selected value becomes available to later shared steps. Do not return terminal outputs here: use branch() when the decision should end the flow.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Builder return | FlowExpression<A | B> |
Reference to the selected path’s result. |
| Resolved value | A | B |
Value from the executed path, available to later steps. |
Example#
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the steps. No application work runs here.
export const delivery = defineJevFlow<{ express: boolean }>("delivery", (flow) => {
const days = flow.if("choose-speed", {
when: flow.input.get("express").eq(true),
then: (path) => path.task("fast", { input: 1, run: (n) => n }),
else: (path) => path.task("standard", { input: 5, run: (n) => n }),
});
const message = flow.task("describe", {
input: days,
run: (n) => `Delivery in ${n} day(s)`,
});
return flow.output("estimated", message);
});
// This flow has no Jev steps: no API key or network access is needed.
const noInference = {
systemOne() { throw new Error("This example does not call Jev"); },
};
// 2. Call tryDelivery() from Node to execute the flow.
export async function tryDelivery() {
const result = await delivery.run({ express: true }, { client: noInference });
console.log(result.outcome); // "estimated"
console.log(result.value); // "Delivery in 1 day(s)"
return result;
}Choose one value-returning path, then continue with its result. Unlike branch(), this does not finish the flow.
flow.if(id, { when, then, else }, display?)- when
- A flow condition evaluated during the run.
- then
- Build the path selected when the condition is true. Return an expression for its value; direct output() and branch() calls are rejected with if path context.
- else
- Build the path selected when the condition is false. Return an expression for its value; direct output() and branch() calls are rejected with if path context.
A flow condition evaluated during the run.
whenBuild an equality condition for strings, numbers, booleans, or null. TypeScript rejects non-scalar receivers; execution checks matching types and finite numbers.
expression.eq(value)Build the path selected when the condition is true. Return an expression for its value; direct output() and branch() calls are rejected with if path context.
thenBuild the path selected when the condition is false. Return an expression for its value; direct output() and branch() calls are rejected with if path context.
elseAPI reference: defineJevFlow() · flow.if() · flow.input · expression.get() · expression.eq() · flow.task() · flow.output() · program.run()
How it works#
.eq(true) turns the express reference into a condition. Each path uses a task to supply a number. After the paths join, the shared describe task receives the selected number and formats the delivery message. This shared continuation is why the example uses if() rather than branch(). Calling tryDelivery() awaits delivery.run({ express: true }, ...), then reads outcome "estimated" and value "Delivery in 1 day(s)" from the finished run.
flow.branch#
Chooses between two paths that each finish the flow with an outcome. Use it when the decision determines how the flow ends.
Signature#
flow.branch(id, { when, then, else }, display?): Expression<FlowOutcome>API reference: FlowOutcome
Inputs#
| Parameter / option | Type |
|---|---|
id |
string |
paths.when |
FlowExpression<boolean> |
paths.then, paths.else |
(path: FlowBuilder<Input>) => FlowExpression<FlowOutcome> |
display? |
FlowDisplay |
when must be a Boolean expression. Each path callback must return output() or another terminal branch().
Return the branch from the containing flow or path. No steps may follow this terminal decision. Use if() when both paths should rejoin and continue.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Builder return | FlowExpression<FlowOutcome> |
Terminal result reference. |
| Resolved outcome | string |
Name returned by the selected terminal path. |
| Resolved value? | unknown |
Optional resolved value returned by that path. |
Example#
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the steps. No application work runs here.
export const route = defineJevFlow<{ needsReview: boolean }>("route", (flow) => {
return flow.branch("pick-path", {
when: flow.input.get("needsReview").eq(true),
then: (path) => path.output("manual-review", "A person should review this"),
else: (path) => path.output("ready", "Continue automatically"),
});
});
// This flow has no Jev steps: no API key or network access is needed.
const noInference = {
systemOne() { throw new Error("This example does not call Jev"); },
};
// 2. Call tryBranch() from Node to execute the flow.
export async function tryBranch() {
const result = await route.run({ needsReview: true }, { client: noInference });
console.log(result.outcome); // "manual-review"
console.log(result.value); // "A person should review this"
return result;
}Finish the flow by choosing one of two paths. Each path must return an output or another branch.
flow.branch(id, { when, then, else }, display?)- id
- A unique step ID within this flow.
- when
- A flow condition evaluated when the branch runs.
- then
- The path used when the condition is true.
- else
- The path used when the condition is false.
- display?
- Optional labels and display metadata for DevTools.
A flow condition evaluated when the branch runs.
whenThe path used when the condition is true.
thenThe path used when the condition is false.
elseAPI reference: defineJevFlow() · flow.branch() · flow.input · expression.get() · expression.eq() · flow.output() · program.run()
How it works#
.eq(true) checks needsReview. The selected path calls output() with its own outcome name and message. Returning the branch ends the flow; there is no shared step afterward. Use if() when the paths should rejoin. Calling tryBranch() awaits route.run({ needsReview: true }, ...), then reads outcome "manual-review" and value "A person should review this" from the finished run.
flow.parallel#
Defines independent lanes of work that run concurrently and then join. Later steps can read each lane’s result by its name.
Signature#
flow.parallel(id, lanes: { [name: string]: (lane) => Expression<unknown> }, display?): JoinedReferencesInputs#
| Parameter / option | Type |
|---|---|
id |
string |
lanes |
Named builder callbacks, each returning a FlowExpression |
display? |
FlowDisplay |
Supply a nonempty object of named lane callbacks. Lane names follow the step ID naming rules, and each callback returns a value expression. The returned object preserves the lane names and their expression types.
Lanes execute concurrently, with sequential steps inside each lane. A lane cannot read a sibling's private intermediate results. If a lane fails, the runner signals cancellation to sibling work. That work must cooperate with cancellation.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Builder return | Object with the lane keys |
Each member preserves its lane’s expression type. |
| Resolved lane values | Each lane’s result type |
Available through the named references after the join. |
Example#
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the steps. No application work runs here.
export const totals = defineJevFlow<{ price: number }>("totals", (flow) => {
const prices = flow.parallel("calculate", {
regular: (lane) => lane.task("full-price", {
input: lane.input.get("price"),
run: (price) => price,
}),
sale: (lane) => lane.task("sale-price", {
input: lane.input.get("price"),
run: (price) => price * 0.8,
}),
});
return flow.output("priced", { regular: prices.regular, sale: prices.sale });
});
// This flow has no Jev steps: no API key or network access is needed.
const noInference = {
systemOne() { throw new Error("This example does not call Jev"); },
};
// 2. Call tryParallel() from Node to execute the flow.
export async function tryParallel() {
const result = await totals.run({ price: 100 }, { client: noInference });
console.log(result.outcome); // "priced"
console.log(result.value); // { regular: 100, sale: 80 }
return result;
}Run named lanes concurrently and join their returned expressions. Each lane's work stays sequential. Lane names belong to your application.
flow.parallel(id, lanes, display?)- lanes
- An object of builder callbacks, each returning an expression. Private sibling intermediates are not available across lanes.
API reference: defineJevFlow() · flow.parallel() · flow.task() · flow.input · expression.get() · flow.output() · program.run()
How it works#
Both lanes read the same input price through their own builders. full-price returns it unchanged, while sale-price multiplies it by 0.8. The flow joins the lanes before resolving both references in the output object. A lane cannot read another lane's private intermediate steps. Calling tryParallel() awaits totals.run({ price: 100 }, ...), then reads outcome "priced" and value { regular: 100, sale: 80 } from the finished run.
flow.map#
Runs the same steps for every item in an array and collects their results in input order. Use it for repeated work with a bounded number of concurrent items.
Signature#
flow.map<Item, Context, Output>(id, { items, input, maxItems, concurrency? }, build, display?): Expression<Output[]>Inputs#
| Parameter / option | Type |
|---|---|
id |
string |
options.items |
readonly Item[] | FlowExpression<readonly Item[]> |
options.input |
Context |
options.maxItems |
number |
options.concurrency? |
number |
build (whole-array reference or scalar array) |
(item: FlowBuilder<{ item: Item; index: number; context: Resolved<Context> }>) => FlowExpression<Output> |
build (literal/template) |
(item: FlowBuilder<{ item: Resolved<Item>; index: number; context: Resolved<Context> }>) => FlowExpression<Output> |
display? |
FlowDisplay |
items accepts a literal array, a whole-array reference, or an array containing nested reference templates. input supplies shared context to each item program. Set maxItems to an integer from 1–64. concurrency is an integer from 1–16 and defaults to 4.
The item builder receives { item, index, context } through item.input and must return a value reference. Whole-array references and scalar arrays preserve Item, including generic payloads and branded primitives. Nested templates resolve each item to Resolved<Item>. For example, with items: [flow.input.get("count")], the item reference has type FlowExpression<number> and a task receiving it gets a number.
Results preserve the original item order, even when items finish out of order. Empty input resolves to an empty array. Exceeding maxItems rejects the run instead of truncating the input.
Pass outer data through explicit context. The item program cannot contain another map or a loop.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Builder return | FlowExpression<Output[]> |
Reference to the result array. |
| Resolved value | Output[] |
One result per item, in original input order. |
Example#
import { defineJevFlow } from "jev-devtools/flow";
// 1. Define the steps. No application work runs here.
export const doubleEach = defineJevFlow<{ numbers: number[] }>("double-each", (flow) => {
const doubled = flow.map("double", {
items: flow.input.get("numbers"),
input: { multiplier: 2 },
maxItems: 10,
concurrency: 2,
}, (item) => item.task("multiply", {
input: {
number: item.input.get("item"),
multiplier: item.input.get("context").get("multiplier"),
},
run: ({ number, multiplier }) => number * multiplier,
}));
return flow.output("doubled", doubled);
});
// This flow has no Jev steps: no API key or network access is needed.
const noInference = {
systemOne() { throw new Error("This example does not call Jev"); },
};
// 2. Call tryMap() from Node to execute the flow.
export async function tryMap() {
const result = await doubleEach.run({ numbers: [2, 4, 6] }, { client: noInference });
console.log(result.outcome); // "doubled"
console.log(result.value); // [4, 8, 12]
return result;
}Run a bounded item program for each item. Results preserve input order even when items execute concurrently.
flow.map(id, options, build, display?)- items
- An array or a reference to one. Each item is passed to the item program.
- input
- Explicit shared context for each item program, available as input.context.
- maxItems
- Required bound on the number of items.
- concurrency?
- Maximum number of item programs allowed to run concurrently.
- build
- Receives a builder with input { item, index, context }. Return an expression for the item result. Direct output() and branch() calls are rejected with map context.
An array or a reference to one. Each item is passed to the item program.
itemsExplicit shared context for each item program, available as input.context.
inputRequired bound on the number of items.
maxItemsMaximum number of item programs allowed to run concurrently.
concurrencyAPI reference: defineJevFlow() · flow.map() · flow.input · expression.get() · flow.task() · flow.output() · program.run()
How it works#
items selects the input array, and input supplies a multiplier shared by all items. Within each item program, get("item") selects its number and get("context").get("multiplier") selects the multiplier. The task resolves both before multiplying. Up to two item programs run at once, but the result array preserves the original item order. Explicit context keeps the item program independent of outer step references. Calling tryMap() awaits doubleEach.run({ numbers: [2, 4, 6] }, ...), then reads outcome "doubled" and value [4, 8, 12] from the finished run.
flow.loop#
Repeats a sequence of steps while a condition is true, carrying updated state between iterations. A required iteration limit bounds how long it can run.
Signature#
// Whole-state reference or scalar: preserves State, including generic payloads.
flow.loop<State, Context>(id, { initial, input, while, maxIterations }, build, display?): Expression<State>
// Object/array template initial state: resolves nested references.
flow.loop<State, Context>(id, { initial, input, while, maxIterations }, build, display?): Expression<Resolved<State>>Replaces flow references inside task inputs, map items and loop state with their actual value types, including nested objects and arrays, while preserving branded primitives. Whole-value reference payloads are already resolved and remain intact.
Import from jev-devtools/flow
// Example of the resulting type:
Resolved<{ name: FlowExpression<string> }>
// becomes { name: string }API reference: Resolved
Inputs#
| Parameter / option | Type |
|---|---|
id |
string |
options.initial |
State | FlowExpression<State> |
options.input |
Context |
options.while (whole-state reference or scalar) |
(state: FlowExpression<State>) => FlowExpression<boolean> |
options.while (literal/template) |
(state: FlowExpression<Resolved<State>>) => FlowExpression<boolean> |
options.maxIterations |
number |
build (whole-state reference or scalar) |
(iteration: FlowBuilder<{ state: State; index: number; context: Resolved<Context> }>) => FlowExpression<State> |
build (literal/template) |
(iteration: FlowBuilder<{ state: Resolved<State>; index: number; context: Resolved<Context> }>) => FlowExpression<Resolved<State>> |
display? |
FlowDisplay |
initial supplies JSON state as a literal, whole-state reference, or nested object/array template. input supplies explicit shared context. The synchronous while(state) callback builds a Boolean expression from the state. Set maxIterations to an integer from 1–64.
The iteration builder receives { state, index, context } through its input. It must return the next state reference with the shape determined by initial:
- Whole-state references and scalar values preserve
State, including generic payloads. - Object/array templates resolve nested references to
Resolved<State>. Branded primitives keep their types.
For initial: { count: flow.input.get("count") }, both the condition and iteration select count as FlowExpression<number>. A task receiving that state works with an ordinary number at state.count.
The runner tests the condition before each iteration. When it becomes false, the loop resolves to the current state. If it starts false, the result is the initial state. If it remains true at the iteration limit, the run rejects with FlowLoopLimitError.
A loop may contain a map, but cannot contain another loop. Direct output() and branch() calls in map bodies, loop bodies, and if() paths throw definition errors that name the containing step and operation. Return a value expression instead. Parallel lanes inside these bodies still support terminal outputs and branches as lane values.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Builder return (whole-state reference or scalar) | FlowExpression<State> |
Reference to the final state, preserving the initial payload type. |
| Builder return (literal/template) | FlowExpression<Resolved<State>> |
Reference to the final resolved state. |
| Resolved value | State for whole-state references/scalars; Resolved<State> for templates |
State when the condition becomes false; initial state if no iterations run. |
Example#
import { defineJevFlow, FlowLoopLimitError } from "jev-devtools/flow";
// 1. Define the steps. No application work runs here.
export const countToThree = defineJevFlow<{}>("count-to-three", (flow) => {
const count = flow.loop(
"count",
{
initial: 0,
input: {},
while: (state) => state.lt(3),
maxIterations: 3,
},
(iteration) =>
iteration.task("increment", {
input: iteration.input.get("state"),
run: (state) => state + 1,
}),
);
return flow.output("counted", count);
});
// This flow has no Jev steps: no API key or network access is needed.
const noInference = {
systemOne() {
throw new Error("This example does not call Jev");
},
};
// 2. Call tryLoop() from Node to execute the flow.
export async function tryLoop() {
const result = await countToThree
.run({}, { client: noInference })
.catch((error: unknown) => {
if (error instanceof FlowLoopLimitError) {
console.error("Loop reached its iteration limit:", error.stepId);
}
throw error;
});
console.log(result.outcome); // "counted"
console.log(result.value); // 3
return result;
}Test a condition before each iteration and return the final state. Rejects if the condition still holds at the iteration limit.
flow.loop(id, options, build, display?)- initial
- The starting JSON state, or a reference to it.
- input
- Explicit shared context, available to the iteration program as input.context.
- while
- Build a Boolean flow condition from the current state. Tested before each iteration.
- maxIterations
- Required bound. Exceeding it while the condition is still true rejects with FlowLoopLimitError identifying the loop in stepId and its message.
- build
- Receives a builder with input { state, index, context }. Return an expression for the next state. Direct output() and branch() calls are rejected with loop context.
The starting JSON state, or a reference to it.
initialExplicit shared context, available to the iteration program as input.context.
inputBuild a Boolean flow condition from the current state. Tested before each iteration.
whileBuild a strictly-less-than condition. Compares finite numeric values when the flow runs.
expression.lt(value)Required bound. Exceeding it while the condition is still true rejects with FlowLoopLimitError identifying the loop in stepId and its message.
maxIterationsAPI reference: defineJevFlow() · flow.loop() · expression.lt() · flow.task() · flow.input · expression.get() · flow.output() · program.run()
How it works#
initial starts the state at zero. while uses .lt(3) to build the stopping condition. The increment task reads the current state and adds one, producing 0 → 1 → 2 → 3. Before a fourth iteration, the condition is false, so the loop returns 3. If the initial condition is false, no iterations run and the initial state is returned. Calling tryLoop() awaits countToThree.run({}, ...), then reads outcome "counted" and value 3 from the finished run.
flow.output#
Defines the end of a flow or branch with a named outcome and optional result data. References in that data resolve when the flow executes.
Signature#
flow.output(name: string, value?: unknown, display?: FlowDisplay): Expression<FlowOutcome>API reference: FlowDisplay · FlowOutcome
Inputs#
| Parameter / option | Type |
|---|---|
name |
string |
value? |
unknown |
display? |
FlowDisplay |
The outcome name is also a node ID, so it must be unique in the definition. The optional value can contain literals and nested references, which resolve during execution. display supplies static inspection metadata.
Return this terminal expression from the flow or branch path. No steps may follow it. Naming an outcome does not perform a business action.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Builder return | FlowExpression<FlowOutcome> |
Terminal result reference. |
| Resolved outcome | string |
The supplied name. |
| Resolved value? | unknown |
The supplied value with nested references resolved. |
Inside a synchronous defineJevFlow() callback; these references resolve when you await the flow’s run(). See the complete definition and execution.
Example#
return flow.output("done", { message, count });API reference: flow.output()
How it works#
The object groups two previously defined references, message and count. Both are resolved into ordinary values under outcome "done"; naming the outcome performs no external action.
jev-devtools/flow
Expressions and conditions#
The short expression snippets below belong inside a synchronous defineJevFlow() callback. They build references; use them in a step or terminal output(), then await the flow’s run() to get actual data. See the complete expression and execution example.
All these runtime exports come from jev-devtools/flow. References must belong to the same flow and be available in the current execution scope. See expression scopes. 0.5.2: construction enforces complete expression depth and expansion limits, including reused children.
FlowExpression#
A typed reference to a value available during flow execution. Builders create these references so later steps can select fields, compare values, and use earlier results.
Signature#
new FlowExpression<T>(ast, owner?: object)
expression.ast: AstAPI reference: FlowExpression
Inputs#
| Parameter / option | Type |
|---|---|
ast |
Expression AST; see supporting structural types |
owner? |
object; ownership is managed by the builder |
The constructor accepts an expression tree (input, ref, get, literal, or supported operator nodes) and an optional ownership token. It freezes the tree. The resulting ast describes how to obtain a value during execution; it does not contain the resolved value.
Ordinary consumers should obtain owned expressions from builders. Hand-constructed expressions are generally unowned and cannot be inserted into a flow; the optional owner is not an application integration mechanism. The structural AST is visible in installed declarations, but not exported as a named public Ast type.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<T> |
Immutable expression object. |
| ast | Ast |
Frozen expression structure, not a resolved application value. |
Example#
const message = flow.input.get("message"); // obtain an owned expressionAPI reference: flow.input · expression.get()
How it works#
Use the builder’s owned input reference and select its message field. This avoids manually constructing an AST or ownership token.
expression.get#
Selects an own property from a referenced object or array. Chain calls to reach nested fields while preserving their types. Primitive properties, including string length and character indexes, are unsupported.
Signature#
expression.get<
K extends keyof T &
keyof ExpressionFields<T> &
(string | number)
>(
this: FlowExpression<object>, key: K
): FlowExpression<T[K]>API reference: FlowExpression
Inputs#
| Parameter / option | Type |
|---|---|
this (expression receiver) |
FlowExpression<object> |
key |
keyof T & keyof ExpressionFields<T> & (string | number) |
Choose an own object field, a numeric array index, or array length. ExpressionFields<T> retains object fields and filters arrays to indices and length, including tuple string indices such as "0". Array methods such as map, slice, and push are rejected by TypeScript. For unions, the key must be supported by every member. The receiver is the expression before .get(), not an extra argument.
Missing, inherited, or undefined properties fail when execution reaches them. Ordinary array bounds, including numeric tuple indices, remain runtime checks. Optional fields retain undefined in their inferred type. This operation does not provide optional chaining.
For a generic field-selection helper, constrain its key with K extends keyof T & Parameters<FlowExpression<T>["get"]>[0] and return FlowExpression<T[K]>. A helper that accepts every keyof T can otherwise admit array methods. General structural object types cannot prove that a property is owned by an instance.
0.5.1 type correction: primitive receivers and unions that may contain primitives are rejected during type checking. Version 0.5.0 can accept these calls in TypeScript but rejects primitive property access at runtime. To compute a string's length, pass the string reference into a task and read .length inside its callback.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<T[K]> |
Reference to the selected field. |
Example#
import { defineJevFlow } from "jev-devtools/flow";
export const fields = defineJevFlow<{
message: string;
tags: readonly string[];
}>("fields", (flow) => {
const tags = flow.input.get("tags");
const messageLength = flow.task("message-length", {
input: flow.input.get("message"),
run: (message) => message.length,
});
return flow.output("selected", {
firstTag: tags.get(0),
tagCount: tags.get("length"),
messageLength,
firstIsNew: tags.get(0).eq("new"),
});
});
// No Jev steps: no API key or network access is needed.
const noInference = {
systemOne() {
throw new Error("This example does not call Jev");
},
};
export async function tryFieldSelection() {
const result = await fields.run(
{ message: "abc", tags: ["new", "support"] },
{ client: noInference },
);
console.log(result.value); // { firstTag: "new", tagCount: 2, messageLength: 3, firstIsNew: true }
return result;
}API reference: defineJevFlow() · flow.input · expression.get() · flow.task() · flow.output() · expression.eq() · program.run()
How it works#
get("tags") selects the input array. Its get(0) selects the first item, and get("length") selects its length. get("message") selects a string, so the task computes its length using the resolved message value. firstIsNew compares the first tag with "new". Calling tryFieldSelection() runs the flow with "abc" and two tags, returning { firstTag: "new", tagCount: 2, messageLength: 3, firstIsNew: true } as its value. All .get() calls construct references during definition; the runner reads their values during execution.
expression.eq#
Builds a condition that checks whether two scalar values are equal when the flow runs. Use it to compare labels, numbers, booleans, or null.
Signature#
expression.eq(
this: FlowExpression<string | number | boolean | null>,
value: T | FlowExpression<T>
): FlowExpression<boolean>API reference: FlowExpression
Inputs#
| Parameter / option | Type |
|---|---|
this (expression receiver) |
FlowExpression<string | number | boolean | null> |
value |
T | FlowExpression<T> |
Pass a literal or compatible expression. The resolved operands must have matching scalar types: string, number, Boolean, or null. This method does not perform deep object equality.
TypeScript rejects object, array, undefined, and unknown receivers, including unions with unsupported members. Literal labels, branded scalars, and generic scalar helpers retain their operand types. Scalar unions remain supported, but the resolved operands must have matching types. JavaScript callers, non-finite numbers, and mismatched union values still require runtime validation.
It returns a Boolean expression that evaluates during the run. Invalid scalar comparisons reject execution.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<boolean> |
Reference to the comparison/condition result. |
| Resolved value | boolean |
True or false when the flow evaluates it. |
Example#
const condition = flow.input.get("count").eq(3);API reference: flow.input · expression.get() · expression.eq()
How it works#
The comparison checks whether the resolved count equals 3. Pass the resulting Boolean expression to when or another condition helper.
expression.lt#
Builds a condition that checks whether a numeric value is below a limit. Use it for thresholds and loop stopping rules.
Signature#
expression.lt(value: number | Expression<number>): Expression<boolean>Inputs#
| Parameter / option | Type |
|---|---|
value |
number | FlowExpression<number> |
Pass a number or compatible numeric expression. Both resolved operands must be finite numbers. Missing, nullable, or nonnumeric operands reject during execution.
The comparison is strictly less than. For an inclusive upper bound, use not(value.gt(limit)) with valid numeric operands. There is no lte() method.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<boolean> |
Reference to the comparison/condition result. |
| Resolved value | boolean |
True or false when the flow evaluates it. |
Example#
const condition = flow.input.get("count").lt(3);API reference: flow.input · expression.get() · expression.lt()
How it works#
The comparison is true when the resolved count is below 3. It describes a condition now and evaluates it when the flow runs.
expression.gt#
Builds a condition that checks whether a numeric value is above a limit. The limit itself does not satisfy the condition.
Signature#
expression.gt(value: number | Expression<number>): Expression<boolean>Inputs#
| Parameter / option | Type |
|---|---|
value |
number | FlowExpression<number> |
Pass a number or compatible numeric expression. Both resolved operands must be finite numbers. Missing, nullable, or nonnumeric operands reject during execution.
The comparison is strictly greater than. For an inclusive upper bound, use not(value.gt(limit)) with valid numeric operands. There is no lte() method.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<boolean> |
Reference to the comparison/condition result. |
| Resolved value | boolean |
True or false when the flow evaluates it. |
Example#
const condition = flow.input.get("count").gt(3);Build a strictly-greater-than condition. Compares finite numeric values when the flow runs.
expression.gt(value)API reference: flow.input · expression.get() · expression.gt()
How it works#
The comparison is true when the resolved count is above 3. Both operands must resolve to finite numbers.
expression.gte#
Builds a condition that checks whether a numeric value meets or exceeds a limit. Use it when the boundary value should count.
Signature#
expression.gte(value: number | Expression<number>): Expression<boolean>Inputs#
| Parameter / option | Type |
|---|---|
value |
number | FlowExpression<number> |
Pass a number or compatible numeric expression. Both resolved operands must be finite numbers. Missing, nullable, or nonnumeric operands reject during execution.
The comparison includes equality. For an inclusive upper bound, use not(value.gt(limit)) with valid numeric operands. There is no lte() method.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<boolean> |
Reference to the comparison/condition result. |
| Resolved value | boolean |
True or false when the flow evaluates it. |
Example#
const condition = flow.input.get("count").gte(3);Build a greater-than-or-equal condition. Compares finite numeric values when the flow runs.
expression.gte(value)API reference: flow.input · expression.get() · expression.gte()
How it works#
The comparison includes the boundary: a count of 3 satisfies it. It returns a condition reference for a later decision.
all#
Combines flow conditions into one condition that requires every check to pass. Use it when several requirements must hold together.
Signature#
all(...conditions: Expression<boolean>[]): Expression<boolean>Inputs#
| Parameter / option | Type |
|---|---|
...conditions |
FlowExpression<boolean>[] |
Pass Boolean expressions belonging to the flow. The result resolves to true only when every condition is true. Supply at least one owned condition: a zero-operand expression has no flow owner and cannot be used in a definition.
Every operand is evaluated. Unlike JavaScript &&, an earlier false result does not prevent a missing-reference error in a later operand.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<boolean> |
Reference to the comparison/condition result. |
| Resolved value | boolean |
True or false when the flow evaluates it. |
Example#
const ready = all(
flow.input.get("count").gte(1),
flow.input.get("count").lt(10),
);Combine Boolean flow conditions: every condition must be true. All operands are evaluated; this does not short-circuit missing references.
all(...conditions)API reference: all() · flow.input · expression.get() · expression.gte() · expression.lt()
How it works#
The two comparisons describe an inclusive lower bound of 1 and an exclusive upper bound of 10. all() combines them so both must hold.
any#
Combines flow conditions into one condition that passes when at least one check passes. Use it for alternative ways to satisfy a decision.
Signature#
any(...conditions: Expression<boolean>[]): Expression<boolean>Inputs#
| Parameter / option | Type |
|---|---|
...conditions |
FlowExpression<boolean>[] |
Pass Boolean expressions belonging to the flow. The result resolves to true when at least one condition is true. Supply at least one owned condition: a zero-operand expression has no flow owner and cannot be used in a definition.
Every operand is evaluated. Unlike JavaScript ||, an earlier true result does not prevent a missing-reference error in a later operand.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<boolean> |
Reference to the comparison/condition result. |
| Resolved value | boolean |
True or false when the flow evaluates it. |
Example#
const boundary = any(
flow.input.get("count").eq(0),
flow.input.get("count").eq(10),
);Combine Boolean flow conditions: at least one condition must be true. All operands are evaluated.
any(...conditions)API reference: any() · flow.input · expression.get() · expression.eq()
How it works#
The two comparisons test the endpoints zero and ten. any() is true when either endpoint matches.
not#
Reverses a flow condition: true becomes false and false becomes true. Use it when a path should run only if another condition does not hold.
Signature#
not(condition: Expression<boolean>): Expression<boolean>Inputs#
| Parameter / option | Type |
|---|---|
condition |
FlowExpression<boolean> |
Pass one Boolean expression. The returned expression resolves to its inverse during execution. The operand must still resolve successfully: not() does not suppress missing-reference errors.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowExpression<boolean> |
Reference to the comparison/condition result. |
| Resolved value | boolean |
True or false when the flow evaluates it. |
Example#
const remaining = not(flow.input.get("count").eq(0));Invert a Boolean flow condition, evaluated when the flow runs.
not(condition)API reference: not() · flow.input · expression.get() · expression.eq()
How it works#
The equality expression checks for zero; not() inverts it so a nonzero count satisfies the condition.
FlowLoopLimitError#
The error raised when a loop reaches its iteration limit while its condition is still true. Catch it around an awaited run to handle loop exhaustion.
Signature#
new FlowLoopLimitError(stepId?: string): FlowLoopLimitError
error.name: "FlowLoopLimitError"
error.stepId: string | undefinedParameters#
| Parameter | Type | Default | Description |
|---|---|---|---|
stepId |
string |
undefined |
Optional loop step ID included in the error message. |
Runtime limit errors supply the failing loop ID. Zero-argument construction keeps the original generic message and an undefined stepId. Catch it around the awaited run if your application handles loop exhaustion, and let unrelated errors propagate. A limit error means the run failed, not that it returned a successful partial result.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | FlowLoopLimitError |
Error instance. |
| name | "FlowLoopLimitError" |
Identifies a still-true condition at the loop limit. |
| stepId | string | undefined |
Read-only failing loop ID, present on runtime limit errors. |
Example#
import { FlowLoopLimitError } from "jev-devtools/flow";
try {
await program.run(input, { client });
} catch (error) {
if (!(error instanceof FlowLoopLimitError)) throw error;
console.error("Loop reached its iteration limit:", error.stepId);
}How it works#
The catch block handles only loop exhaustion and rethrows other failures. Captured error fields keep only the error name, without the message or input values. The flow did not complete successfully, so the handler reports the limit instead of treating a partial state as a result.
jev-devtools/flow
Fixtures and comparison#
New in 0.5.0. Fixtures contain captured response bodies, not the original input or executable recipe.
flowFixture#
Builds a replay fixture from a captured flow run and its request traces. It also reports missing responses and capture limitations to review before saving.
Signature#
flowFixture(definition: FlowDefinition, run: FlowRun, traces: ReadonlyMap<string, Trace>): BuiltFlowFixtureInputs#
| Parameter / option | Type |
|---|---|
definition |
FlowDefinition |
run |
FlowRun |
traces |
ReadonlyMap<string, Trace> |
Import from jev-devtools in browser code or jev-devtools/flow on Node. Pass the recorded definition, recorded run, and a trace map indexed by trace ID.
The result contains fixture, missing, and warnings. missing lists completed Jev steps whose response captures are unavailable. warnings reports capture redaction or truncation. Task results are not included as fixture responses.
Check both arrays before saving. Server redaction remains; this helper does not apply the drawer's current display masking. The drawer's Copy fixture action does. Failed/cancelled runs can yield partial fixtures.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | BuiltFlowFixture |
Export result with fields below. |
| fixture | FlowFixture |
Saved response bodies by step ID. |
| missing | string[] |
Completed Jev steps with missing response captures. |
| warnings | string[] |
Capture limitations such as redaction or truncation. |
Example#
const built = flowFixture(
definition,
capturedRun,
new Map(traces.map((trace) => [trace.id, trace])),
);
if (built.missing.length || built.warnings.length) console.warn(built);
const json = JSON.stringify(built.fixture, null, 2);How it works#
The map indexes captures by trace ID. flowFixture() finds responses linked to completed Jev steps; the example checks limitations before serializing only the fixture payload.
replayClient#
Creates a client that supplies saved Jev responses during a flow run. Use it to replay requests without inference calls; application tasks still execute.
Signature#
replayClient(fixture: FlowFixture): TypeSafeClientAvailable since 0.5.0. Stored Jev responses used for replay. It contains neither the original flow implementation nor its input.
Import from jev-devtools/flow
type FlowFixture = {
version: 1;
flow: string;
steps: Record<string, unknown>;
}- flow
- Must match the flow name being replayed.
- steps
- Saved response bodies keyed by step ID, including composed map/loop IDs. Tasks still execute during replay.
API reference: FlowFixture
Inputs#
| Parameter / option | Type |
|---|---|
fixture |
FlowFixture |
Import from jev-devtools/flow and pass a fixture with { version: 1, flow, steps }. The returned client supplies saved responses during a flow run without an API key or inference request.
Replay checks the flow name, step IDs, and requested question names. It does not check prompts or state. Invalid fixtures throw, and missing steps or answers reject instead of falling back to live inference. Map and loop step keys include item or iteration indices.
Tasks and request factories run again and can have side effects. Pass controlled tasks in tests. Complete replay example.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | TypeSafeClient |
Supplies fixture answers when used as a flow run’s client. |
Example#
const result = await program.run(input, { client: replayClient(fixture) });How it works#
The client supplies stored answers for Jev steps while the same recipe executes with the supplied input. Tasks and request factories still execute, so control side effects in replay tests.
compareWithFixture#
Runs a flow against saved responses and then with the supplied live client, comparing the results. Use it to inspect changes in outcomes, decisions, and answers.
Signature#
compareWithFixture<Input>(flow: ComparableFlow<Input>, input: Input, fixture: FlowFixture, options: FlowRunOptions & { tolerance?: number }): Promise<FixtureComparison>API reference: FlowFixture · FlowRunOptions
Inputs#
| Parameter / option | Type |
|---|---|
flow |
ComparableFlow<Input> |
input |
Input |
fixture |
FlowFixture |
options |
FlowRunOptions & { tolerance?: number } |
Import from jev-devtools/flow. Pass the executable flow, input, fixture, and run options. client supplies the second run's answers. devtools and signal are optional. Numeric answer tolerance defaults to 0 and must be finite and nonnegative.
The helper replays the fixture first, then runs the flow again with the supplied client and the same input. Tasks execute on both sides. Only the second run reaches your observer.
The result compares outcomes, values, branch/if decisions, scalar answer fields, and executed Jev steps. It also includes a new liveFixture.
Check answers even when changed is false. The top-level flag tracks outcome, value, decision, or executed Jev-step differences. Answer drift alone does not set it. Numeric tolerance applies only to answer fields, not outcome or value comparisons.
Invalid tolerance or an unreplayable fixture rejects the comparison. Errors from the supplied client propagate.
The second run uses the supplied client, so a live client makes inference calls. The returned liveFixture contains unredacted, untruncated response bodies. Review them before storing or sharing.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Promise<FixtureComparison> |
Resolves to the comparison fields below. |
| changed | boolean |
Outcome, value, decision, or executed Jev steps differ; answer drift alone does not set it. |
| outcome | { recorded: string; live: string; changed: boolean } |
Terminal outcome comparison. |
| value | { recorded?: unknown; live?: unknown; changed: boolean } |
Resolved output comparison. |
| decisions | Array<{ stepId: string; recorded?: boolean; live?: boolean; changed: boolean }> |
Branch and if decisions. |
| answers | AnswerChange[] |
Scalar answer-field comparisons, including numeric deltas when finite. |
| steps | { onlyRecorded: string[]; onlyLive: string[] } |
Jev step IDs executed on only one side. |
| liveFixture | FlowFixture |
Unredacted, untruncated live response bodies. |
Example#
import { compareWithFixture, formatComparison } from "jev-devtools/flow";
const comparison = await compareWithFixture(program, input, fixture, {
client,
devtools: inspector,
tolerance: 0.01,
});
console.log(formatComparison(comparison));How it works#
The helper first replays the saved fixture, then executes with the supplied client. The tolerance permits small numeric answer differences. formatComparison() returns a text summary, which console.log() prints. Neither operation changes the runs' results.
formatComparison#
Turns a fixture comparison into a readable text summary. Use it in logs or reports after running compareWithFixture().
Signature#
formatComparison(comparison: FixtureComparison): stringInputs#
| Parameter / option | Type |
|---|---|
comparison |
FixtureComparison |
Import from jev-devtools/flow and pass a comparison result. The returned text has one line per change, or "no changes from fixture" when there are none.
The formatter performs no I/O. Print or store the string in application code. It can report answer drift even when comparison.changed is false.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | string |
One line per reported change, or no changes from fixture. |
Example#
const summary = formatComparison(comparison);
console.log(summary);How it works#
Formatting produces text only. console.log() is the application-owned output operation; the formatter itself performs no logging.
jev-devtools/server
Recorder#
Import JevRecorder from jev-devtools/server. This is for custom integrations; most apps can use the server adapter. Complete recorder setup.
JevRecorder#
Captures SDK requests and keeps their inspection history in memory. Use it directly when building a custom integration beyond the server adapter.
Signature#
new JevRecorder(options?: CaptureOptions): JevRecorderControls how much request history is kept and how captured values are redacted. Shared by JevRecorder and the server adapter; it does not change the SDK response your application receives.
Import from jev-devtools/server
type CaptureOptions = {
limit?: number;
redact?: (path: string[], value: unknown) => unknown;
}- limit?
- Maximum retained traces across all sessions. Defaults to 50; clamped to 1–200.
- redact?
- Called with a field path and value. Return the value to store in the captured copy, for example a masked string. Keep credentials on the server.
API reference: CaptureOptions
Inputs#
| Parameter / option | Type |
|---|---|
options? |
CaptureOptions |
The optional limit defaults to 50 and is clamped to 1–200 across all sessions. The optional redact(path, value) callback transforms captured values. If transformed JSON cannot support a structured request or result view, Trace.capture retains it and captureWarnings explains the unavailable view. The drawer displays usable fields beside placeholders for incompatible fields. Fixture export still reports an incompatible response as missing.
History is bounded process memory, not durable storage. Pair instrument() with transport() to record both logical SDK calls and their HTTP attempts.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | JevRecorder |
Recorder instance with the methods below. |
Example#
import { JevRecorder } from "jev-devtools/server";
const recorder = new JevRecorder({ limit: 50 });Create a lower-level in-memory request recorder for a custom integration.
new JevRecorder(options?)- limit
- Maximum retained request traces across sessions. Defaults to 50; clamped to 1–200.
- redact
- Transform the captured copy before storage or streaming. Incompatible structured content remains as JSON in Trace.capture with warnings. The drawer keeps usable fields visible beside unavailable placeholders. SDK inputs and application values stay unchanged.
Maximum retained request traces across sessions. Defaults to 50; clamped to 1–200.
limitAPI reference: JevRecorder
How it works#
Constructing the recorder sets a global retention bound of 50 traces. The instance can then wrap an SDK client and expose history to a custom viewer.
recorder.transport#
Wraps the SDK’s fetch function to record HTTP attempts. Pair it with instrument() to connect those attempts to their logical SDK calls.
Signature#
recorder.transport(fetcher: Fetch): FetchInputs#
| Parameter / option | Type |
|---|---|
fetcher |
SDK-compatible Fetch |
Pass an SDK-compatible fetch implementation such as globalThis.fetch, then give the returned wrapper to the SDK's fetch option.
The wrapper records HTTP attempts associated with instrumented calls. It does not create HTTP endpoints or capture unrelated clients.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Fetch |
SDK-compatible fetch wrapper; request/response contract is retained. |
Example#
const sdk = new TypeSafeClient({
apiKey,
fetch: recorder.transport(globalThis.fetch),
});How it works#
The SDK receives a wrapped fetch, so HTTP attempts can be associated with instrumented logical calls. Pair this client with recorder.instrument() to record both levels.
recorder.instrument#
Wraps a TypeSafe client to record its systemOne calls with session and display labels. The returned client preserves the SDK’s request and response behavior.
Signature#
recorder.instrument<T extends TypeSafeClient>(client: T, metadata: { session: string; label: string; source: "sample" | "live" } | (() => Metadata)): TInputs#
| Parameter / option | Type |
|---|---|
client |
T extends TypeSafeClient |
metadata |
{ session: string; label: string; source: "sample" | "live" }, or a factory returning it |
Pass an SDK client and either complete metadata or a synchronous metadata factory. session partitions history, label identifies the call, and source labels it as sample or live.
The proxy preserves the client's type, SDK promise, response helpers, and application result. It records only systemOne calls. Pair it with transport() to capture HTTP attempts. A sample label does not prevent network calls.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | T |
Instrumented client proxy preserving its original SDK type. |
Example#
const client = recorder.instrument(sdk, {
session: "local",
label: "Support",
source: "live",
});How it works#
The proxy records systemOne calls under the local session with the Support label. The original SDK’s response helpers remain available on the returned client.
recorder.snapshot#
Reads the retained request history for one session as a detached array. Use it to populate a viewer without changing the stored history.
Signature#
recorder.snapshot(session: string): Trace[]Inputs#
| Parameter / option | Type |
|---|---|
session |
string |
Pass the session to read. The returned traces are detached inspection copies, ordered newest first. They remain subject to redaction and capture limits.
Reading a snapshot does not clear history or return the original SDK objects.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | Trace[] |
Detached retained traces for the session, newest first. |
Example#
const traces = recorder.snapshot("local");How it works#
The call retrieves a detached copy of the local session’s current history. Reading the array does not clear or mutate recorder storage.
recorder.changes#
Reads trace updates since a revision, together with the current retained order. Use it to keep a viewer in sync without fetching every trace again.
Signature#
recorder.changes(session: string, after?: number): { revision: number; order: string[]; upserts: Trace[] }Inputs#
| Parameter / option | Type |
|---|---|
session |
string |
after? |
number |
Pass the session and, after the first read, the last returned revision as after. Omitting after requests a full initial view.
Apply upserts to your local cache, then remove cached traces whose IDs are absent from order. Do this even when upserts is empty: order is the authoritative retained history, newest first. Save the returned revision for the next read. Returned traces are detached copies.
Returns#
| Value / member | Type | Description |
|---|---|---|
| revision | number |
Cursor for the next call. |
| order | string[] |
Authoritative newest-first retained trace IDs. |
| upserts | Trace[] |
Detached traces changed since the supplied cursor. |
Example#
const initial = recorder.changes("local");
const next = recorder.changes("local", initial.revision);How it works#
The initial call requests a full view. Passing its revision into the second call requests changed traces; use the returned order to remove traces no longer retained.
recorder.subscribe#
Registers a listener for changes to recording sessions. Use the notified session names to decide which snapshots or updates your viewer should read.
Signature#
recorder.subscribe(listener: (sessions: ReadonlySet<string>) => void): () => voidInputs#
| Parameter / option | Type |
|---|---|
listener |
(sessions: ReadonlySet<string>) => void |
The listener receives the set of sessions affected by a change. Notifications contain session names, not trace payloads. Read snapshot() or changes() for the sessions your viewer needs.
Call the returned function to unsubscribe during cleanup.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | () => void |
Unsubscribe function; call when the listener is no longer needed. |
Example#
const stop = recorder.subscribe((sessions) => {
if (sessions.has("local")) console.log(recorder.snapshot("local"));
});
// On shutdown:
stop();How it works#
The listener filters notifications to the local session before reading its snapshot. Calling stop() removes that listener during cleanup.
recorder.clear#
Removes retained traces for one recording session and notifies listeners. Use it to reset inspection history while leaving application work running.
Signature#
recorder.clear(session: string): voidInputs#
| Parameter / option | Type |
|---|---|
session |
string |
Pass the session to clear. The recorder removes its retained traces and notifies listeners, leaving other sessions intact.
Clearing history does not cancel the application's in-flight SDK work. The method returns no value.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | void |
No data; affected listeners are notified. |
Example#
recorder.clear("local");How it works#
Only retained traces for the local session are removed. Other session histories and application inference continue.
recorder.withFlow#
Links captured SDK requests to the flow step executing them. Custom observers use it to establish recording context around a request callback.
Signature#
recorder.withFlow<T>(link: { runId: string; stepId: string; executionId: string }, onTrace: (id: string) => void, callback: () => T): TInputs#
| Parameter / option | Type |
|---|---|
link |
{ runId: string; stepId: string; executionId: string } |
onTrace |
(id: string) => void |
callback |
() => T |
Pass the flow linkage, a callback that receives the captured trace ID, and the request callback. The wrapper establishes asynchronous recording context and calls the request callback immediately. Its result is returned unchanged, including a promise if it returns one.
The adapter's flow observer normally handles this linkage. Custom integrations must preserve synchronous call-through.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | T |
The callback result unchanged, including a promise when applicable. |
Example#
return recorder.withFlow(
link,
(traceId) => {
latestTraceId = traceId;
},
callback,
);How it works#
The wrapper establishes flow linkage around the request callback. onTrace stores the captured trace ID, while the callback’s result is returned unchanged.
jev-devtools/flow
Observer hooks#
FlowObserver is exported as a type from jev-devtools/flow. Pass an implementation as devtools to a run; the server adapter already implements it. Observers record execution and must not control application work. Observer failure containment is new in 0.5.0.
observer.startFlow#
Starts observation of a flow run and supplies the hooks for its updates and requests. The runner calls it automatically when a devtools observer is provided.
Signature#
observer.startFlow(definition: FlowDefinition, run: FlowRun): { update; request } | undefinedInputs#
| Parameter / option | Type |
|---|---|
definition |
FlowDefinition |
run |
FlowRun |
The runner supplies the definition and initial captured run. Return update and request hooks for that execution, or undefined to skip observation.
The server adapter records in the current session and returns undefined when disabled. Application code normally passes the adapter as devtools rather than calling this method directly.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | { update, request } | undefined |
Per-run hooks, or undefined to skip recording. |
| update | (run: FlowRun) => void |
Receives execution updates. |
| request | Generic callback wrapper |
Links a request to its flow step; signature below. |
Example#
await program.run(input, { client, devtools: inspector }); // runner calls startFlowHow it works#
Passing the inspector as devtools lets the runner call startFlow and manage the returned hooks. Application code does not need to invoke those hooks manually.
observer.update#
Receives the latest captured run state as execution progresses. Use it in a custom observer to update a viewer or store run information.
Signature#
hooks.update(run: FlowRun): voidInputs#
| Parameter / option | Type |
|---|---|
run |
FlowRun |
The runner calls this hook with the latest captured run state, including step status and any outcome or error. Use the snapshot to update your viewer or storage.
The hook returns no value. Keep application actions in flow steps, not observer callbacks.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | void |
No application result is produced. |
Example#
const hooks = {
update(run: FlowRun) {
console.log(run.id, run.status);
},
request<T>(
_link: unknown,
_onTrace: (id: string) => void,
callback: () => T,
): T {
return callback();
},
};How it works#
The update hook logs the run ID and status. Its companion request hook calls through immediately; these hooks observe execution rather than implement application steps.
observer.request#
Wraps a flow’s request callback so an observer can associate its capture with the current step. It must call through synchronously and preserve the callback’s result.
Signature#
hooks.request<T>(link: { runId: string; stepId: string; executionId: string }, onTrace: (id: string) => void, callback: () => T): TInputs#
| Parameter / option | Type |
|---|---|
link |
{ runId: string; stepId: string; executionId: string } |
onTrace |
(id: string) => void |
callback |
() => T |
The runner supplies execution linkage, a callback for reporting the captured trace ID, and the request callback. Call through synchronously and return the callback's original result.
Custom observers can delegate to recorder.withFlow() to establish recording context. The runner owns the request result.
Returns#
| Value / member | Type | Description |
|---|---|---|
| Return | T |
The original request callback result. |
Example#
request<T>(link: Link, onTrace: (id: string) => void, callback: () => T): T {
return recorder.withFlow(link, onTrace, callback);
} // method inside a custom hook object; Link is the shape aboveHow it works#
The custom observer delegates to withFlow() so the recorder can associate the SDK request with its run, step, and execution ID. Returning the callback result preserves the runner’s request behavior.
Public types#
Use import type for these contracts. The expandable declarations below are read from the actual public package exports at docs build time, including their supporting structural types. They supplement the method explanations above and make exact fields and unions available without a browser TypeScript runtime. A type's declaration is not a promise that the same API exists in an older installed package.
Type: Trace#
One captured request, attempts, timing, status, and warnings. Optional capture retains redacted JSON when a structured request or result view is unavailable. The drawer can display usable fields from that JSON.
Import type from: jev-devtools.
Exact TypeScript declaration
export type Trace = {
version: 1;
id: string;
session: string;
flow?: {
runId: string;
stepId: string;
executionId: string;
};
label: string;
source: "sample" | "live";
startedAt: number;
durationMs?: number;
status: "pending" | "success" | "error" | "cancelled";
request: {
model: string;
state: Json;
questions: Record<string, QuestionView>;
assets?: Json;
};
result?: {
model: string;
answers: Record<string, AnswerView>;
usage?: {
input_tokens: number;
output_tokens: number;
};
};
/** Bounded redacted JSON whose structured request/result view is unavailable.
* Presence, including null, identifies an unavailable section. Never infer
* availability from user strings. The recorder owns this metadata. */
capture?: {
request?: Json;
result?: Json;
};
requestId?: string;
error?: {
name: string;
message: string;
status?: number;
};
attempts: {
number: number;
durationMs?: number;
status?: number;
error?: string;
}[];
captureWarnings: string[];
};Type: Snapshot#
Version 1 full trace history message.
Import type from: jev-devtools.
Exact TypeScript declaration
export type Snapshot = {
version: 1;
traces: Trace[];
};Type: StreamSnapshot#
Version 2 initial trace history with a revision cursor.
Import type from: jev-devtools.
Exact TypeScript declaration
export type StreamSnapshot = {
version: 2;
revision: number;
traces: Trace[];
};Type: TraceDelta#
Version 2 incremental update. order is authoritative: remove retained IDs absent from it.
Import type from: jev-devtools.
Exact TypeScript declaration
export type TraceDelta = {
version: 2;
base: number;
revision: number;
upserts: Trace[];
/** Authoritative newest-first retained IDs. Omitted IDs are removed. */
order: string[];
};Type: Json#
The JSON-safe shape used for captured data, which may be redacted or truncated.
Import type from: jev-devtools.
Exact TypeScript declaration
export type Json = null | boolean | number | string | Json[] | {
[key: string]: Json;
};Type: AnswerView#
Validated structured answer fields; available fields depend on the question type. Incompatible redacted response content remains in Trace.capture.result.
Import type from: jev-devtools.
Exact TypeScript declaration
export type AnswerView = {
type: string;
choice?: string;
score?: number;
noul?: number;
confidence?: number;
probabilities?: Record<string, number>;
legend?: Record<string, Json>;
box?: {
left: number;
top: number;
right: number;
bottom: number;
};
};Type: QuestionView#
Captured question type, instructions, and criteria.
Import type from: jev-devtools.
Exact TypeScript declaration
export type QuestionView = {
type: string;
instructions?: Json;
criteria?: Json;
};Type: FlowFixture#
Available since 0.5.0. Stored Jev responses used for replay. It contains neither the original flow implementation nor its input.
Import type from: jev-devtools or jev-devtools/flow.
Exact TypeScript declaration
export type FlowFixture = {
version: 1;
flow: string;
steps: Record<string, unknown>;
};API reference: FlowFixture
Type: BuiltFlowFixture#
Available since 0.5.0. Exported fixture plus missing capture IDs and warnings to inspect before saving.
Import type from: jev-devtools or jev-devtools/flow.
Exact TypeScript declaration
export type BuiltFlowFixture = {
fixture: FlowFixture;
/** Completed jev steps whose capture was evicted, unlinked, or has no result. */
missing: string[];
/** Capture warnings from the traces used; redaction or truncation may show in the answers. */
warnings: string[];
};API reference: FlowFixture
Type: JevDevtoolsProps#
Props for the React inspector. Enable it explicitly in development and point it at the matching server endpoint.
Import type from: jev-devtools.
Exact TypeScript declaration
export type JevDevtoolsProps = {
endpoint?: string;
/** Opt in explicitly, normally with import.meta.env.DEV. */
enabled?: boolean;
defaultOpen?: boolean;
/** Mask supported personal fields in DevTools views only. Defaults to true.
* Captures still contain these values; credentials remain server-redacted. */
redactAdditionalSensitiveData?: boolean;
};API reference: JevDevtoolsProps
Type: CaptureOptions#
Controls how much request history is kept and how captured values are redacted. Shared by JevRecorder and the server adapter; it does not change the SDK response your application receives.
Import type from: jev-devtools/server.
Exact TypeScript declaration
export type CaptureOptions = {
limit?: number;
redact?: (path: string[], value: unknown) => unknown;
};API reference: CaptureOptions
Type: JevDevtoolsServerOptions#
Server adapter configuration. Extends CaptureOptions with enablement, origin checks, routing, and session selection.
Import type from: jev-devtools/server.
Exact TypeScript declaration
export type JevDevtoolsServerOptions = CaptureOptions & {
/** Explicit opt-in; disabled by default. */
enabled?: boolean;
origin: string;
endpoint?: string;
/**
* Required for non-loopback origins. Without it, Node middleware only accepts
* loopback connections. Apply your application's authentication.
*/
authorize?: (request: Request) => boolean | Promise<boolean>;
/** Server-derived scope. Defaults to a shared local-development history. */
getSession?: (request: Request) => string | Promise<string>;
};API reference: JevDevtoolsServerOptions · CaptureOptions
Type: ClientMetadata#
Optional labels attached to captured calls. A sample label does not prevent a real network request.
Import type from: jev-devtools/server.
Exact TypeScript declaration
export type ClientMetadata = {
label?: string;
source?: "sample" | "live";
};API reference: ClientMetadata
Type: FlowDisplay#
Optional labels for a step in the inspector. These are display metadata, not instructions to the model or changes to execution.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FlowDisplay = {
title?: string;
description?: string;
};API reference: FlowDisplay
Type: FlowDefinition#
Static recipe graph, including its identity, name, and node metadata.
Import type from: jev-devtools/flow or jev-devtools/viewer.
Exact TypeScript declaration
export type FlowDefinition = {
version: 1;
id: string;
name: string;
nodes: FlowNode[];
};Type: FlowRun#
Captured execution state, with per-step progress and optional outcome, value, capture warnings, or error.
Import type from: jev-devtools/flow or jev-devtools/viewer.
Exact TypeScript declaration
export type FlowRun = {
version: 1;
id: string;
definitionId: string;
name: string;
startedAt: number;
durationMs?: number;
status: "pending" | "success" | "error" | "cancelled";
steps: Record<string, FlowStep>;
outcome?: string;
value?: Json;
/** Capture limitations for value, including observer failures; absent in older captures. */
captureWarnings?: string[];
error?: string;
};Type: FlowStep#
Captured step state, timing, decisions, trace linkage, and collection/loop progress.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FlowStep = {
id: string;
executionId: string;
status: "waiting" | "running" | "completed" | "untaken" | "blocked" | "error" | "cancelled";
startedAt?: number;
durationMs?: number;
decision?: boolean;
traceId?: string;
error?: string;
/** Optional bounded, redacted task input/output or selected merge value; never executable code. */
data?: Json;
captureWarnings?: string[];
loop?: {
maxIterations: number;
stopReason?: "condition" | "limit";
};
collection?: {
total: number;
concurrency: number;
items: Array<{
index: number;
status: FlowStep["status"];
run?: FlowRun;
}>;
};
};Type: AnswerChange#
Available since 0.5.0. One scalar answer-field comparison; delta exists only for finite numeric differences.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type AnswerChange = {
stepId: string;
question: string;
field: string;
recorded?: AnswerValue;
live?: AnswerValue;
delta?: number;
changed: boolean;
};Type: ComparableFlow#
Available since 0.5.0. A definition and executable run method accepted by compareWithFixture.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type ComparableFlow<T> = {
definition: FlowDefinition;
run(input: T, options: FlowRunOptions): Promise<FlowOutcome & {
runId: string;
}>;
};API reference: FlowRunOptions · FlowOutcome
Type: FixtureComparison#
Available since 0.5.0. Outcome/value/decision/step changes, answer drift, and unredacted live fixture.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FixtureComparison = {
/** Outcome, value or a decision differs, or a jev step ran on only one side. Answer drift alone does not set it. */
changed: boolean;
outcome: {
recorded: string;
live: string;
changed: boolean;
};
value: {
recorded?: unknown;
live?: unknown;
changed: boolean;
};
decisions: {
stepId: string;
recorded?: boolean;
live?: boolean;
changed: boolean;
}[];
answers: AnswerChange[];
/** Jev step ids; map and loop items use `${parentId}/${index}/${innerId}`. */
steps: {
onlyRecorded: string[];
onlyLive: string[];
};
/** The live run's response bodies, unredacted and untruncated. */
liveFixture: FlowFixture;
};API reference: FlowFixture
Type: FlowOutcome#
The named result of a completed flow. run() adds a runId. The public value type is unknown; narrow it before using it in application code.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FlowOutcome = {
outcome: string;
value?: unknown;
};API reference: FlowOutcome
Type: Resolved#
Replaces flow references inside task inputs, map items and loop state with their actual value types, including nested objects and arrays, while preserving branded primitives. Whole-value reference payloads are already resolved and remain intact.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type Resolved<T> = T extends FlowExpression<infer V> ? V : T extends string | number | boolean | null | undefined ? T : T extends readonly unknown[] ? {
[K in keyof T]: Resolved<T[K]>;
} : T extends object ? {
[K in keyof T]: Resolved<T[K]>;
} : T;API reference: Resolved · FlowExpression
Type: TaskContext#
The second argument received by a task's run callback, containing cancellation and execution identifiers.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type TaskContext = {
signal: AbortSignal;
runId: string;
stepId: string;
executionId: string;
};The second argument received by a task's run callback, containing cancellation and execution identifiers.
Import from jev-devtools/flow
type TaskContext = {
signal: AbortSignal;
runId: string;
stepId: string;
executionId: string;
}- signal
- Pass to cancellable work such as fetch.
- runId
- Identifies this flow run.
- stepId
- Identifies the defined step.
- executionId
- Identifies this execution of the step, including repeated map or loop work.
API reference: TaskContext
Type: FlowTask#
Configuration for application code inside a flow. Input references resolve before the callback runs; the callback can return a value or a promise.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FlowTask<I, O> = {
input: I;
run: (input: Resolved<I>, context: TaskContext) => O | Promise<O>;
timeoutMs?: number;
};API reference: FlowTask · Resolved · TaskContext
Type: FlowRequestFactory#
Builds an SDK request from resolved input during flow execution. The factory itself must return synchronously; the runner sends and awaits the request.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FlowRequestFactory<I, Q extends Questions> = {
input: I;
/** Synchronous construction only; the runner executes the SDK request. */
request: (input: Resolved<I>) => SystemOneRequest<Q>;
};Builds an SDK request from resolved input during flow execution. The factory itself must return synchronously; the runner sends and awaits the request.
Import from jev-devtools/flow
type FlowRequestFactory<I, Q extends Questions> = {
input: I;
request: (input: Resolved<I>) => SystemOneRequest<Q>;
}- input
- Data to resolve before constructing the question.
- request
- Returns an SDK request. Use an earlier task for asynchronous preparation.
API reference: FlowRequestFactory · Resolved
Type: FlowObserver#
Records flow progress and request linkage. The server adapter implements this interface. Observation must not control application work.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FlowObserver = {
startFlow(definition: FlowDefinition, run: FlowRun): {
update(run: FlowRun): void;
/** Call through synchronously to establish recording context. The runner owns the result. */
request<T>(link: {
runId: string;
stepId: string;
executionId: string;
}, onTrace: (id: string) => void, callback: () => T): T;
} | undefined;
};Records flow progress and request linkage. The server adapter implements this interface. Observation must not control application work.
Import from jev-devtools/flow
FlowObserver- startFlow
- Receives the definition and initial run; returns per-run hooks or undefined to skip recording.
- update
- Receives run updates.
- request
- Calls through synchronously to preserve request linkage.
API reference: FlowObserver
Type: FlowRunOptions#
Execution settings passed to a flow's run() method. The client is required even when the flow contains only tasks.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export type FlowRunOptions = {
client: Pick<TypeSafeClient, "systemOne">;
devtools?: FlowObserver;
signal?: AbortSignal;
};API reference: FlowRunOptions · FlowObserver
Type: FlowBuilder#
The object passed to a synchronous flow-building callback. Its input and step methods create references; run() later executes the definition.
Import type from: jev-devtools/flow.
Exact TypeScript declaration
export interface FlowBuilder<T> {
readonly input: FlowExpression<T>;
jev<const Q extends Questions>(id: string, request: Request<Q>, display?: FlowDisplay): AnswerRefs<Q>;
jev<I, const Q extends Questions>(id: string, request: FlowRequestFactory<I, Q>, display?: FlowDisplay): AnswerRefs<Q>;
task<I, O>(id: string, task: FlowTask<I, O>, display?: FlowDisplay): FlowExpression<Awaited<O>>;
/** References and scalar arrays already carry their resolved item type. */
map<I, C, O>(id: string, options: {
items: FlowExpression<readonly I[]> | (readonly I[] & readonly (string | number | {
valueOf(): boolean;
} | null)[]);
input: C;
concurrency?: number;
maxItems: number;
}, build: (item: FlowBuilder<{
item: I;
index: number;
context: Resolved<C>;
}>) => FlowExpression<O>, display?: FlowDisplay): FlowExpression<O[]>;
/** Execute a reusable program over resolved items; return results in input order. */
map<I, C, O>(id: string, options: {
items: FlowExpression<readonly I[]> | readonly I[];
input: C;
concurrency?: number;
maxItems: number;
}, build: (item: FlowBuilder<{
item: Resolved<I>;
index: number;
context: Resolved<C>;
}>) => FlowExpression<O>, display?: FlowDisplay): FlowExpression<O[]>;
/** References and scalar initial values preserve their generic state type. */
loop<S, C>(id: string, options: {
initial: S | FlowExpression<S>;
input: C;
while: (state: FlowExpression<NoInfer<S>>) => FlowExpression<boolean>;
maxIterations: number;
} & {
initial: FlowExpression<S> | string | number | {
valueOf(): boolean;
} | null;
}, build: (iteration: FlowBuilder<{
state: S;
index: number;
context: Resolved<C>;
}>) => FlowExpression<NoInfer<S>>, display?: FlowDisplay): FlowExpression<S>;
/** Pre-test loop over resolved JSON state, with explicit context and an iteration limit. */
loop<S, C>(id: string, options: {
initial: S | FlowExpression<S>;
input: C;
while: (state: FlowExpression<NoInfer<Resolved<S>>>) => FlowExpression<boolean>;
maxIterations: number;
}, build: (iteration: FlowBuilder<{
state: Resolved<S>;
index: number;
context: Resolved<C>;
}>) => FlowExpression<NoInfer<Resolved<S>>>, display?: FlowDisplay): FlowExpression<Resolved<S>>;
/** Execute one value-returning path, then continue with its typed result. */
if<A, B>(id: string, paths: {
when: FlowExpression<boolean>;
then: (path: FlowBuilder<T>) => FlowExpression<A>;
else: (path: FlowBuilder<T>) => FlowExpression<B>;
}, display?: FlowDisplay): FlowExpression<A | B>;
/** Terminal decision: each callback must return output() or another branch(). */
branch(id: string, paths: {
when: FlowExpression<boolean>;
then: (path: FlowBuilder<T>) => FlowExpression<FlowOutcome>;
else: (path: FlowBuilder<T>) => FlowExpression<FlowOutcome>;
}, display?: FlowDisplay): FlowExpression<FlowOutcome>;
parallel<const B extends Record<string, (lane: FlowBuilder<T>) => FlowExpression<unknown>>>(id: string, lanes: B, display?: FlowDisplay): {
[K in keyof B]: ReturnType<B[K]>;
};
output(name: string, value?: unknown, display?: FlowDisplay): FlowExpression<FlowOutcome>;
}API reference: FlowBuilder · FlowExpression · FlowDisplay · FlowRequestFactory · FlowTask · Resolved · FlowOutcome
Type: InspectionSnapshot#
Unreleased. Latest validated, display-masked request and flow history, plus the inspector connection status.
Import type from: jev-devtools/viewer.
Exact TypeScript declaration
export type InspectionSnapshot = {
traces: Trace[];
flows: FlowHistory;
connection: string;
};API reference: InspectionSnapshot
Type: JevFlowViewerProps#
Unreleased. Graph, optional captured execution, and presentation controls for the embedded flow viewer. Filtering and highlighting do not change execution.
Import type from: jev-devtools/viewer.
Exact TypeScript declaration
export type JevFlowViewerProps = {
definition: FlowDefinition;
/** Omit for an authored definition without execution state. */
run?: FlowRun;
traces?: Trace[];
selectedNodeId?: string;
onNodeSelect?: (id: string) => void;
/** Presentation only; does not change the flow or its execution. */
visibleNodeIds?: readonly string[];
highlightedNodeIds?: readonly string[];
nodeAccents?: Readonly<Record<string, string>>;
};API reference: JevFlowViewerProps
Exact callable declarations#
These expandable declarations preserve the actual generic signatures behind the readable method summaries.
JevDevtools declaration#
The React component that adds the inspector drawer to your app. Use it to view requests and flow runs captured by your server adapter.
Import from jev-devtools.
Exact TypeScript declaration
export declare function JevDevtools({ enabled, ...props }: JevDevtoolsProps): import("react").JSX.Element | null;API reference: JevDevtoolsProps
flowFixture declaration#
Builds a replay fixture from a captured flow run and its request traces. It also reports missing responses and capture limitations to review before saving.
Import from jev-devtools.
Exact TypeScript declaration
export declare function flowFixture(definition: FlowDefinition, run: FlowRun, traces: ReadonlyMap<string, Trace>): BuiltFlowFixture;createJevDevtools declaration#
Creates the server adapter that connects SDK request capture to the browser inspector. Share one instance between your clients and inspector routes.
Import from jev-devtools/server.
Exact TypeScript declaration
export declare function createJevDevtools(options: JevDevtoolsServerOptions): {
startFlow: (definition: import("../src/flow-protocol.js").FlowDefinition, run: import("../src/flow-protocol.js").FlowRun) => {
update(run: import("../src/flow-protocol.js").FlowRun): void;
request<T>(link: {
runId: string;
stepId: string;
executionId: string;
}, onTrace: (id: string) => void, callback: () => T): T;
} | undefined;
handle: (request: Request) => Promise<Response>;
/**
* For Node framework routes whose Request URL uses an internal hostname.
* Require the actual Host header to match the configured public authority;
* never trust forwarded host/protocol headers. Origin checks still apply.
* A Request does not expose the socket peer and any non-browser client can
* set Host, so bind the server to loopback or set authorize.
*/
handleNodeRoute(request: Request): Promise<Response>;
middleware: (req: IncomingMessage, res: ServerResponse, next: () => void) => Promise<void>;
createClient(clientOptions: ConstructorParameters<typeof TypeSafeClient>[0], meta?: ClientMetadata): TypeSafeClient;
/** Needed only when getSession is customized. Wrap the application's request handler. */
run<T>(request: Request, callback: () => T | Promise<T>): Promise<T>;
dispose(): void;
};API reference: JevDevtoolsServerOptions · ClientMetadata
getJevDevtools declaration#
Gets or creates a server adapter under a stable key. Use it to preserve the same recorder and history across module reloads in one Node process.
Import from jev-devtools/server.
Exact TypeScript declaration
export declare function getJevDevtools(key: string, createOptions: () => JevDevtoolsServerOptions): Adapter;API reference: JevDevtoolsServerOptions
JevRecorder declaration#
Captures SDK requests and keeps their inspection history in memory. Use it directly when building a custom integration beyond the server adapter.
Import from jev-devtools/server.
Exact TypeScript declaration
export declare class JevRecorder {
private options;
private traces;
private listeners;
private revision;
private revisions;
private context;
private flowContext;
withFlow<T>(link: NonNullable<Trace["flow"]>, onTrace: (id: string) => void, callback: () => T): T;
private limit;
constructor(options?: CaptureOptions);
snapshot(session: string): Trace[];
changes(session: string, after?: number): {
revision: number;
order: string[];
upserts: Trace[];
};
subscribe(listener: (sessions: ReadonlySet<string>) => void): () => void;
clear(session: string): void;
private notify;
private update;
transport(fetcher: Fetch): Fetch;
instrument<T extends TypeSafeClient>(client: T, meta: {
session: string;
label: string;
source: "sample" | "live";
} | (() => {
session: string;
label: string;
source: "sample" | "live";
})): T;
}API reference: CaptureOptions
defineJevFlow declaration#
Defines a reusable sequence of tasks, Jev requests, and decisions. The callback builds the recipe synchronously; calling the returned flow’s run() executes it.
Import from jev-devtools/flow.
Exact TypeScript declaration
export declare function defineJevFlow<T>(name: string, build: (flow: FlowBuilder<T>) => FlowExpression<FlowOutcome>): {
definition: FlowDefinition;
run(data: T, options: FlowRunOptions): Promise<{
runId: string;
outcome: string;
value?: unknown;
}>;
};API reference: FlowBuilder · FlowExpression · FlowOutcome · FlowRunOptions
replayClient declaration#
Creates a client that supplies saved Jev responses during a flow run. Use it to replay requests without inference calls; application tasks still execute.
Import from jev-devtools/flow.
Exact TypeScript declaration
export declare function replayClient(fixture: FlowFixture): TypeSafeClient;API reference: FlowFixture
compareWithFixture declaration#
Runs a flow against saved responses and then with the supplied live client, comparing the results. Use it to inspect changes in outcomes, decisions, and answers.
Import from jev-devtools/flow.
Exact TypeScript declaration
export declare function compareWithFixture<T>(flow: ComparableFlow<T>, input: T, fixture: FlowFixture, options: FlowRunOptions & {
tolerance?: number;
}): Promise<FixtureComparison>;API reference: FlowFixture · FlowRunOptions
formatComparison declaration#
Turns a fixture comparison into a readable text summary. Use it in logs or reports after running compareWithFixture().
Import from jev-devtools/flow.
Exact TypeScript declaration
export declare function formatComparison(comparison: FixtureComparison): string;FlowExpression declaration#
A typed reference to a value available during flow execution. Builders create these references so later steps can select fields, compare values, and use earlier results.
Import from jev-devtools/flow.
Exact TypeScript declaration
export declare class FlowExpression<T> {
readonly ast: Ast;
protected readonly [valueTypeBrand]: T;
constructor(ast: Ast, owner?: object);
/** Select an own object field, array index, or array length. Missing values fail at runtime. */
get<K extends keyof T & keyof ExpressionFields<T> & (string | number)>(this: FlowExpression<object>, key: K): FlowExpression<T[K]>;
/** Compare matching scalar values; numbers must be finite at runtime. */
eq(this: FlowExpression<Scalar>, value: T | FlowExpression<T>): FlowExpression<boolean>;
lt(this: FlowExpression<number>, value: number | FlowExpression<number>): FlowExpression<boolean>;
gt(this: FlowExpression<number>, value: number | FlowExpression<number>): FlowExpression<boolean>;
gte(this: FlowExpression<number>, value: number | FlowExpression<number>): FlowExpression<boolean>;
}API reference: FlowExpression
all declaration#
Combines flow conditions into one condition that requires every check to pass. Use it when several requirements must hold together.
Import from jev-devtools/flow.
Exact TypeScript declaration
declare const all: (...conditions: FlowExpression<boolean>[]) => FlowExpression<boolean>;API reference: FlowExpression
any declaration#
Combines flow conditions into one condition that passes when at least one check passes. Use it for alternative ways to satisfy a decision.
Import from jev-devtools/flow.
Exact TypeScript declaration
declare const any: (...conditions: FlowExpression<boolean>[]) => FlowExpression<boolean>;API reference: FlowExpression
not declaration#
Reverses a flow condition: true becomes false and false becomes true. Use it when a path should run only if another condition does not hold.
Import from jev-devtools/flow.
Exact TypeScript declaration
declare const not: (condition: FlowExpression<boolean>) => FlowExpression<boolean>;API reference: FlowExpression
FlowLoopLimitError declaration#
The error raised when a loop reaches its iteration limit while its condition is still true. Catch it around an awaited run to handle loop exhaustion.
Import from jev-devtools/flow.
Exact TypeScript declaration
export declare class FlowLoopLimitError extends Error {
readonly stepId?: string | undefined;
readonly name = "FlowLoopLimitError";
constructor(stepId?: string | undefined);
}useJevInspection declaration#
Version 0.6.0. Subscribe to the validated flow and request capture streams used by the drawer.
Import from jev-devtools/viewer.
Exact TypeScript declaration
export declare function useJevInspection({ endpoint, enabled, }?: {
endpoint?: string;
enabled?: boolean;
}): InspectionSnapshot;API reference: InspectionSnapshot
JevFlowViewer declaration#
Version 0.6.0. Embed the same diagram and request inspector used by the drawer in an ordinary React layout.
Import from jev-devtools/viewer.
Exact TypeScript declaration
export declare function JevFlowViewer({ definition, run, traces, ...presentation }: JevFlowViewerProps): import("react").JSX.Element;API reference: JevFlowViewerProps
Supporting structural types#
These shapes appear inside the public contracts above. They are not named public exports; do not import them from package internals. SDK and platform types are defined by their respective packages.
FlowNode shape#
One step in a flow’s static graph, including its kind, dependencies, and any nested item program. Optional conditionCaptureWarnings describe limitations in captured conditionRule data. The inspector uses these nodes to display the recipe.
Exact TypeScript declaration
export type FlowNode = FlowDisplay & {
id: string;
kind: "jev" | "task" | "map" | "loop" | "if" | "merge" | "branch" | "parallel" | "output";
dependencies: string[];
path: string[];
condition?: string;
/** Conditional merge edges; only the selected arm supplies a value. */
merge?: {
condition: string;
then: string;
else: string;
};
/** Optional for older captures; Json allows redacted/truncated subtrees. */
conditionRule?: Json | FlowCondition;
/** Capture limitations for conditionRule; absent in older captures. */
conditionCaptureWarnings?: string[];
/** Named concurrent lanes; optional for older captures. */
lanes?: string[];
/** Reusable item program; map nesting is not supported in v1. */
itemDefinition?: FlowDefinition;
};API reference: FlowDisplay
FlowCondition shape#
A recorded description of a condition, built from references, literal values, and comparison operators. It lets the inspector display the rule behind a decision.
Exact TypeScript declaration
export type FlowCondition = {
op: "reference";
label: string;
probability: boolean;
name?: string;
stepId?: string;
path?: string[];
source?: "task";
} | {
op: "literal";
value: string | number | boolean | null;
} | {
op: "eq" | "lt" | "gt" | "gte" | "all" | "any" | "not";
args: FlowCondition[];
};AnswerValue shape#
A scalar answer field used in fixture comparisons: a string, number, boolean, or null.
Exact TypeScript declaration
type AnswerValue = string | number | boolean | null;Request shape#
The flow builder’s request shape, based on the SDK request with state that can contain flow references. The runner resolves that state before sending the request.
Exact TypeScript declaration
type Request<Q extends Questions> = Omit<SystemOneRequest<Q>, "state"> & {
state: unknown;
};AnswerRefs shape#
The references returned by a Jev step: named answer fields through answer(), and the complete answer object through answers. These values resolve during execution.
Exact TypeScript declaration
type AnswerRefs<Q extends Questions> = {
/** All answers, including question names created by a runtime request factory. */
readonly answers: FlowExpression<{
[K in keyof Q]: ResultFor<Q[K]>;
}>;
answer<K extends keyof Q & string>(name: K): {
[F in keyof ResultFor<Q[K]>]: FlowExpression<ResultFor<Q[K]>[F]>;
};
};API reference: FlowExpression
FlowHistory shape#
Retained flow runs and their definitions inside an InspectionSnapshot. The validated stream updates both collections together, including removal and reconnection snapshots.
Exact TypeScript declaration
export type FlowHistory = {
runs: FlowRun[];
definitions: FlowDefinition[];
};Adapter shape#
The object returned by createJevDevtools(), containing client creation, HTTP handlers, session handling, and flow observation methods.
Exact TypeScript declaration
type Adapter = ReturnType<typeof createJevDevtools>;Ast shape#
The expression tree that describes how a flow value is read or calculated. It stores inputs, step references, field selections, literals, and operators for evaluation during a run.
Exact TypeScript declaration
type Ast = {
op: "input";
} | {
op: "ref";
id: string;
} | {
op: "get";
from: Ast;
key: string;
} | {
op: "literal";
value: unknown;
} | {
op: "eq" | "lt" | "gt" | "gte" | "all" | "any" | "not";
args: Ast[];
};ExpressionFields shape#
The fields available to get(): object fields, or array indices and length. Common keys across union members remain selectable; missing values still fail during execution.
Exact TypeScript declaration
type ExpressionFields<T> = T extends readonly unknown[] ? Pick<T, number | "length" | Extract<keyof T, `${number}`>> : T;Scalar shape#
The value types accepted by flow equality: string, number, boolean, and null. Execution also requires matching types and finite numbers.
Exact TypeScript declaration
type Scalar = string | number | boolean | null;