OpenProgram Docs

Write and check a Workflow

A Workflow is a small Python package: Agent instances are the roles, Context objects set what each model call sees, plain functions set the order. Once openprogram programs check passes, its entries are callable tools. To show instead of write: record a demonstration.

Contract in README.md

ItemRequired
PurposeThe concrete task and the evidence needed to complete it
InputEntry parameters, required context, invalid-input behavior
OutputReturn type, files produced, how success is verified
EffectsModel, tool, file, network and external-submission behavior
Failure and cancellationWhat remains after a failure or interruption; whether retry is safe
DependenciesImported Workflows, required tools and services
TestsBehavior checks, scripted model replies, separate live checks
UsageOne reproducible invocation and its expected result

Keep functions small. Handle expected invalid input explicitly; let runtime cancellation propagate.

Layout

~/.openprogram/programs/project_report/
├── .git/
├── README.md
├── __init__.py
├── workflow.py
├── steps/
│   └── prepare.py
└── tests/
    └── test_workflow.py

The directory name is the package name: a lowercase Python identifier, not a standard-library module or another importable package. Each Workflow is its own Git repository. It imports under its own name (project_report.steps.prepare); relative imports and imports of other Workflows both work.

Roles, Context, functions

ObjectRule
RoleAgent at module top level. Configuration only: model, instructions, tools, effort. Without a model it uses the caller's.
ContextBuilt inside functions, passed to role calls explicitly
FunctionPlain Python: calls roles, transforms, branches, loops
"""Prepare a project report from verified notes."""

from openprogram import Agent, Context

writer = Agent(instructions="You write project reports.")
reviewer = Agent(instructions="You check facts.", tools=[])


def project_report(notes: str) -> str:
    """Turn this week's project notes into a report."""
    ctx = Context({"notes": notes})
    draft = write_draft(ctx)
    return check(draft, ctx)


def write_draft(ctx: Context) -> str:
    """Write three sections: progress, problems, plans. At most three items each."""
    return writer("Write this week's report", context=ctx)


def check(draft: str, ctx: Context) -> str:
    """Only check that the draft matches the notes. Do not change the style."""
    return reviewer("Fix any mismatch and return the final text",
                    context=ctx.derive({"draft": draft}))


PROGRAM_ENTRIES = [project_report]
  • role(prompt, context=ctx) runs one model turn with the role's tools; role.choose(prompt, {id: label}, context=ctx) returns an option ID. Workflow code never calls the free llm() or agent().
  • PROGRAM_ENTRIES lists the tools. Each needs a docstring (tool description) and a type annotation on every parameter (tool schema).
  • No decorators, base classes or dispatch tables. Use another Workflow through a normal import.

What one model call sees

Part, in orderDefined by
The role's instructions, as the system promptAgent(...)
History, empty by defaulthistory of ctx
Docstring of the Workflow function that calledThat function
Named blocks of ctx, each name: then valueThe code that builds or derives ctx
promptThe call

Nothing else enters: no chat history, recalled memory or other roles' outputs. Context never changes tools or permissions. The docstring comes from the nearest Workflow-package function on the stack and applies to that one request; helpers without one add nothing.

Context

FormEffect
Context({"notes": notes}), ctx["notes"] = notesBlocks
Context(providers={"today": lambda c: ...})Synchronous callable evaluated at each call
ctx.derive({...})Independent copy; the caller's ctx is unchanged
history=NoneNo history, the default for a role call
history="thread"Earlier calls with this same ctx object
history="chat"The conversation that invoked the Workflow
history=callable(node, context) -> bool selects conversation nodes

History goes in Context(..., history=...) or ctx.derive(history=...).

Built-in providers show a model where its call sits:

from openprogram.runtime.context import call_path, workflow_source

ctx = Context(providers={"call path": call_path, "program": workflow_source})

call_path lists Workflow functions on the stack (project_report → check); call_path(docs=True) adds docstrings. workflow_source returns the entry's source. A plain block such as {"flow": "Draft first, then review."} also works.

Entry options

ENTRY_OPTIONS = {
    "project_report": {
        "input": {"notes": {"description": "This week's notes", "multiline": True}},
    },
}

ENTRY_OPTIONS maps an entry to tool options. "run_in_worker": True runs in the worker instead of a forked subprocess, for worker-owned state such as browser sessions.

Resume after a restart

from openprogram.runtime.agent.durable_steps import step


def project_report(notes: str) -> str:
    """Turn this week's project notes into a report."""
    draft = step("draft", write_draft, notes)
    return step("check", check, notes, draft)


ENTRY_OPTIONS = {"project_report": {"resumable": True}}
RuleDetail
StepsRuns once, result saved. On continuing the entry reruns from the top; completed steps return saved results, so role calls do not repeat.
Outside stepsRuns again: keep it deterministic and side-effect free, with stable step names and order
ValuesArguments and results are JSON. A Context does not survive; build it inside the step.
ContinuingRestart: automatic within execution.auto_resume_window_seconds. Paused: from the chat.
Changed codeA run is tied to the commit. execution.code_change_policy: keep_original (default) stops with "Workflow code changed"; use_latest continues, and a removed or reordered completed step stops it.
LimitsSynchronous; no run_in_worker

Execution parameters

Users give task, evidence and deliverable, never model IDs, effort, iterations, timeouts, token budgets or retries.

CaseRule
Fixed valuesOn the role or in code
Values that depend on the taskOne role call makes the complete plan; code validates keys, types, ranges and limit relationships, and falls back to a validated default
PrecedenceUser constraints and application limits beat model output
ResumeA resumable Workflow checkpoints the plan

Behavior tests

from openprogram.programs._authoring.testing import script_roles

from project_report import workflow as wf


def test_reviewer_sees_the_draft_but_not_the_writer_prompt():
    with script_roles({wf.writer: ["Draft"], wf.reviewer: ["Final"]}) as calls:
        assert wf.project_report("Shipped the parser.") == "Final"

    request = calls[wf.reviewer][0]
    assert "Do not change the style" in request.text      # check() docstring
    assert "Draft" in request.text                        # the draft block
    assert "Write this week's report" not in request.text
    assert request.history_text == ""
  • A reply is a string or JSON-serializable value (for response_format); for role.choose, the option ID.
  • An exception in the script is raised by the call and stays queued, so it answers the model loop's retries too.
  • request.text: instructions, docstring, blocks, prompt. request.history_text: history.
  • Patch tools, files and services with monkeypatch. Live provider checks cannot run during a check: keep them out of tests/.

Check and list

openprogram programs check ~/.openprogram/programs/project_report
openprogram programs check ~/.openprogram/programs/project_report -m "Tighten the review step"
openprogram programs list
  1. Imports the package in a separate process and validates PROGRAM_ENTRIES and signatures.
  2. Runs tests/ with pytest, in the OS sandbox when available: no network, package read-only, HOME an empty temporary directory.
  3. Commits to the Workflow's repository when all pass and records that commit in refs/openprogram/checked. -m sets the message; --json prints the report.

Only the checked commit loads: a plain git commit does not, and uncommitted edits keep the checked version serving, across restarts too. The worker watches ~/.openprogram/programs and reloads within seconds. programs list and the Programs page show loaded, error (with the error) or pending (with the reason, such as no checked commit yet). History and rollback use Git.

CaseBehavior
Where it runsA copy of the checked commit in ~/.openprogram/programs-cache/<name>/<commit>/. Files read next to the code must be committed; anything written belongs outside the package.
New version fails to importThe previous one keeps running. State error, note "Kept version <old>; version <new> failed." The Programs page heads a red line under the title with it, then the reason and a See full error link.
Calls still runningThe new version waits for them up to 30 seconds, then tries again on the next pass.

Run

FromHow
ChatEach entry is a tool
Programs pageAbilities → Programs, select under Applications, Use opens the form in chat; nothing runs until sent
Command lineopenprogram programs run <entry> -a key=value
PythonImportable functions

Each entry call is recorded in the session graph with a child node per role call, holding the exact request. Plain functions are not recorded.

Last updated · 2026-11-25