Forge Workflows (@forge/workflows) is under development and is not yet available. These pages describe the
planned API, which may change before release.
For more details, see Forge EAP, Preview, and GA.
A workflow is a chain of steps that usually starts with a call to a task. Calling a task gives you a future of its
result. You add steps to the future with .pipe(), .catch() and .loop(), then call .start() to start a run. For an
introduction, see Forge Workflows API.
In the snippets on this page, functions such as classify, fetchIssue and postComment are tasks. Each snippet's
diagram shows which calls run in their own invocation.
1 2npm install @forge/workflows
Add the storage:app scope to your manifest.yml:
1 2 3 4permissions: scopes: - storage:app
For the other requirements, see Requirements.
Put each chain in a named function, and return the result of .start():
1 2 3 4 5 6 7export const triage = (issueKeys: string[], projectKey: string) => issueKeys .map(classify) .collect({ concurrency: 10 }) .pipe((labels) => applyLabels(projectKey, labels)) .start();
Then call the function to start a run:
1 2 3 4 5 6 7 8 9import Resolver from '@forge/resolver'; import { runs } from '@forge/workflows'; import { triage } from './workflows'; const resolver = new Resolver(); resolver.define('start', ({ payload }) => triage(payload.issueKeys, payload.projectKey)); // { runId } resolver.define('status', ({ payload }) => runs.get(payload.runId)); export const handler = resolver.getDefinitions();
A chain must follow these rules. If it breaks one, forge deploy and forge tunnel fail with an error that gives
the file, line and column.
all([...]), items.map(task).collect(), or
loop(body, initialState). It can have only one fan-out, and only at the start. To fan out or loop
partway through, call a sub-workflow that starts with one..start(), and return it. Either make the chain a concise arrow function body, or end the function
with return chain.start(). You can't assign the chain to a variable, or put it inside an if, loop or try
block. A chain that you return without .start() defines a sub-workflow instead.all() or loop(), or call .start().sleep(), would never
run. To run several at once, use all([...]) or items.map(task).collect(). You also
can't await a future, or return one to code outside a workflow, such as a resolver: return chain.start()
instead.consts, which are saved when
the run starts. These values must be plain JSON data. A step can't use this, a variable that's reassigned, a
function or class declared inside the function, or a value whose type isn't plain data (such as any,
unknown, Map, Set or Date). Move those to module scope, or import them.To use an earlier step's value in a later step, return both values from a small task. Or save an ID, and fetch the data again in the later step.
1 2task<Args, Result>(handler: (...args: Args) => Result | Promise<Result>, options?: TaskOptions): Task<Args, Result>
Makes a task. Calling a task gives you a Future<Result>. Each call runs in its own invocation, and must finish
within the 900-second function timeout.
| Option | Type | Description |
|---|---|---|
retry.attempts | number | Total attempts, including the first. Default: 3. |
retry.backoffSeconds | number | The delay before the first retry. It doubles on each attempt, up to 900 seconds. Default: 2. |
retry.retryAll | boolean | Retry every error, not only retryable errors. Default: false. |
timeoutSeconds | number | Fail the attempt if it takes longer than this. The attempt is retried. The timed-out call isn't stopped, so it can keep running in the background. |
1 2 3 4 5const classify = task(async (issueKey: string) => callLlm(issueKey), { retry: { attempts: 5, backoffSeconds: 5 }, timeoutSeconds: 120 });
1 2future.pipe<R>(handler: (value: T) => R | Promise<R> | Future<R>): Future<R>
Adds a step that receives the value from the step before it. If the handler calls a task, such as
(text) => classify(text), that task call runs in its own invocation. Otherwise, the handler runs in the same
invocation as the step before it.
1 2future.catch<R>(handler: (error: FutureError) => R | Promise<R> | Future<R>): Future<T | R>
Adds a step that handles a failure from any earlier step. The steps between the failure and the .catch() are
skipped. The handler receives { name, message, code? }, and its result becomes the value for the next step. To
fail the run anyway, throw from the handler.
1 2 3 4 5 6 7 8 9 10 11loop<S, R>( body: (state: S) => LoopStep<S, R> | Promise<LoopStep<S, R>> | Future<LoopStep<S, R>>, initialState: S, options?: { maxIterations?: number } ): Future<R> future.loop<R>( body: (state: T) => LoopStep<T, R> | Promise<LoopStep<T, R>> | Future<LoopStep<T, R>>, options?: { maxIterations?: number } ): Future<R>
Runs body repeatedly. Return next(state) to run it again with a new state, or done(value) to leave the loop
with a result. Each iteration runs in its own invocation, which suits agent loops that call a model on every turn.
Start a chain with loop(body, initialState). Like a task call's arguments, initialState is worked out when the
run starts, from the function's parameters and consts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14import { done, loop, next, task } from '@forge/workflows'; const agentTurn = task(async (state: AgentState) => { const reply = await callLlm(state.messages); return reply.toolCall ? next({ messages: [...state.messages, await runTool(reply.toolCall)] }) : done(reply.text); }); export const answer = (issueKey: string, question: string) => loop(agentTurn, { messages: [question] }, { maxIterations: 10 }) .pipe((text) => postComment(issueKey, text)) .start();
To loop after other steps, call .loop(body, options?) on a future instead. The loop starts with the future's
value:
1 2 3export const answerAbout = (issueKey: string) => fetchIssue(issueKey).pipe(toAgentState).loop(agentTurn, { maxIterations: 10 }).pipe(postComment).start();
maxIterations defaults to 25, and you must write it as a number, such as { maxIterations: 10 }. If the loop
hasn't returned done() by then, the step fails with code LOOP_LIMIT.
To wait between iterations, for example when polling, return sleep(seconds, next(state)) from the body. You can't
use waitForSignal() inside a loop.
For a complete example, see Agent tool-call loop.
1 2future.start(): Promise<{ runId: string }>
Starts a run of the chain, and resolves with its run ID once the run has started. It doesn't wait for the result.
Always await or return it: if your function ends first, the run might not start.
The value of the last step becomes the run's result, which you read with runs.get.
Starting a workflow twice starts two runs.
1 2items.map(task).collect(options?: { concurrency?: number; settle?: boolean }): Future<Result[]>
Calls a task once for every item, in parallel. The next step receives every result, in the same order as the items.
Pass the task itself to map, as in items.map(summarise).
| Option | Type | Description |
|---|---|---|
concurrency | number | The most task calls running at once, from 1 to 25. When one finishes, the next starts. Default: 10. |
settle | boolean | When true, a failed call doesn't fail the collection. Each result is { status: 'fulfilled', value } or { status: 'rejected', reason }. Default: false. |
Without settle, the first failed call fails the collection. The run continues at the next .catch(), or fails.
Calls that are already running still finish, but their results are discarded.
The next step receives all the results as one value, so together they must fit within the 240 KB value limit. For large results, have each call save its result to app storage and return the key.
1 2all([a(x), b(y)]): Future<[A, B]>
Runs calls to different tasks in parallel. The next step receives their results as a typed tuple. Pass an array of task calls written in place, as below.
1 2 3 4 5export const brief = (issueKey: string) => all([fetchIssue(issueKey), fetchComments(issueKey)]) .pipe(([issue, comments]) => summarise(issue, comments)) .start();
A named function that returns a chain without .start() defines a sub-workflow. Call it from a step, wherever you
could call a task, and the step's value is the sub-workflow's result. Use sub-workflows for branches that take more
than one step, for chains you reuse in several workflows, and for several steps per item of a fan-out. For a
complete example, see
Incident response.
1 2 3 4 5 6 7 8 9 10 11 12 13// Sub-workflows: no .start(). const escalate = (issueKey: string) => pageOnCall(issueKey) .pipe(() => addLabel(issueKey, 'incident')) .pipe(() => createIncidentPage(issueKey)); const backlog = (issueKey: string) => addComment(issueKey, 'Triaged. The team will pick this up soon.'); export const routeIssue = (issueKey: string) => classifySeverity(issueKey) .pipe((severity) => (severity === 'P1' ? escalate(issueKey) : backlog(issueKey))) .start();
A sub-workflow runs as a run of its own, and the step that called it waits without holding an invocation open. You can also:
issueKeys.map(escalate).collect()next(state) or done(value) from its last step, so each turn of an
agent can take several stepsreturn escalate(issueKey).start()If a sub-workflow fails, the step that called it fails with the same error, which a later .catch() can handle. A
sub-workflow follows the same rules as any workflow, and can call other sub-workflows, up to 10 deep.
A sub-workflow can wait with waitForSignal(). Send the signal to the run you started, with
runs.signal. If the run is cancelled or fails, its sub-workflows stop at their next step.
A run that's waiting doesn't hold an invocation open. Each wait still uses some of the run's queue pushes.
1 2sleep(seconds: number, value?: T): Future<T>
Pauses the run, then continues with value. seconds can be at most 604800 (7 days).
1 2.pipe((report) => sleep(3600, report))
1 2waitForSignal<T>(name: string, options?: { timeoutSeconds?: number }): Future<T>
Pauses the run until you call runs.signal(runId, name, value), then continues with value. Use it
for human approval, or to wait for a callback from another system.
name is 1–64 letters, numbers, _ or -.timeoutSeconds, the run waits with no timeout, and uses no queue pushes while it waits. A run's state
is kept for 14 days from when it starts, so a run must be signalled and finish within that time. After that, it's
removed without failing: runs.get() returns undefined, and runs.signal() returns false.timeoutSeconds, at most 604800 (7 days), the step fails with code SIGNAL_TIMEOUT if no signal arrives in
time, which a later .catch() can handle. A timeout uses one queue push for every 15 minutes of waiting.waitForSignal(`approve-${issueKey}`). Otherwise, the run fails with code SIGNAL_IN_USE.1 2 3 4 5 6 7export const publishNotes = (version: string) => draftNotes(version) .pipe(() => waitForSignal<{ approved: boolean }>('approval', { timeoutSeconds: 3 * 86400 })) .pipe((decision) => (decision.approved ? publish(version) : 'discarded')) .catch((error) => error.code) .start();
Use the runs object to check on, cancel and signal runs by their run ID:
1 2import { runs } from '@forge/workflows';
runs acts on any run in your app. Before you call it, check that the user is allowed to act on that run. See
Security.
1 2runs.get<T>(runId: string): Promise<RunStatus<T> | undefined>
Returns the run's status, or undefined if there's no such run. A finished run's status is kept for 14 days.
| Field | Type | Description |
|---|---|---|
runId | string | The run's ID. |
workflow | string | Which workflow the run belongs to, as <file>#<function>. For example, workflows#triage for the triage function in src/workflows.ts. |
version | string | Which deployed version of the workflow the run started with. |
state | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED' | The run's state. |
createdAt, updatedAt | number | Epoch milliseconds. |
progress | { done: number; total: number } | For runs that start with map().collect() or all(): how many of the parallel calls have finished. |
result | T | The last step's value, when the state is SUCCEEDED. |
error | { name, message, code? } | Why the run failed, when the state is FAILED. For codes, see Error codes. |
1 2runs.cancel(runId: string): Promise<boolean>
Stops a run. Steps that are already running finish, but no further steps run, including .catch() steps. Returns
true if it cancelled the run, and false if the run doesn't exist or has already finished.
1 2runs.signal(runId: string, name: string, value: unknown): Promise<boolean>
Resumes a run that's waiting in waitForSignal(name), including a wait in one of its
sub-workflows. The run continues with value.
Returns true if it resumed the run. Returns false if the run isn't waiting for that signal: for example, it was
already signalled, it timed out, or the run has finished. If two calls race, only one returns true.
Send the signal after the run reaches waitForSignal. A signal sent earlier is dropped, and runs.signal returns
false.
1 2 3// In a resolver, after checking that the user may approve this run. resolver.define('approve', ({ payload }) => runs.signal(payload.runId, 'approval', { approved: true }));
1 2 3next<S>(state: S): LoopStep<S, never> done<R>(value: R): LoopStep<never, R>
Return one of these from a loop body: next to run the body again with a new state, or done to leave
the loop with a result.
1 2chunk<T>(items: readonly T[], size: number): T[][]
Splits an array into batches of at most size items, for example to summarise in groups.
1 2new RetryableError(message: string, code?: string)
Throw this, or a class that extends it, to have the step retried under its retry policy. For the other errors that are retried, see Retries.
Rate this page: