### Code Examples Source: https://github.com/openclaw/lobster/blob/main/_autodocs/MANIFEST.txt Practical code examples demonstrating various patterns for using the Lobster SDK, workflows, and CLI. ```APIDOC ## Examples ### Description Illustrates common and advanced usage patterns for the Lobster SDK, workflow files, and CLI commands through practical code snippets. ``` -------------------------------- ### Install the Lobster SDK Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-START-HERE.md This command installs the Lobster SDK package using npm. This is the first step to using the SDK for building workflows. ```bash npm install @clawdbot/lobster ``` -------------------------------- ### Lobster Workflow File Example Source: https://github.com/openclaw/lobster/blob/main/README.md An example of a Lobster workflow file defining steps for fetching data, requiring approval, and invoking an LLM for advice. ```yaml name: jacket-advice args: location: default: Phoenix steps: - id: fetch run: weather --json ${location} - id: confirm approval: Want jacket advice from the LLM? stdin: $fetch.json - id: advice pipeline: > llm.invoke --prompt "Given this weather data, should I wear a jacket? Be concise and return JSON." stdin: $fetch.json when: $confirm.approved ``` -------------------------------- ### Install Lobster with npm or pnpm Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Install the Lobster package using your preferred Node.js package manager. ```bash npm install @clawdbot/lobster # or pnpm add @clawdbot/lobster ``` -------------------------------- ### Run Data Migration Workflow Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/11-examples.md Demonstrates how to run the data migration workflow using the 'lobster run' command with specific arguments. ```bash lobster run --file data-migration.lobster --args-json '{"batch_size":50}' ``` -------------------------------- ### Lobster Graph Command: Mermaid Output Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example visualization of a workflow graph using Mermaid syntax. ```mermaid flowchart TD fetch[fetch] review{review} send[send] fetch --> review review -->|approved| send ``` -------------------------------- ### Lobster Graph Command: DOT Output Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example visualization of a workflow graph using DOT syntax for Graphviz. ```dot digraph { fetch [label="fetch", shape=box]; review [label="review", shape=diamond]; fetch -> review; } ``` -------------------------------- ### Configuration Options Source: https://github.com/openclaw/lobster/blob/main/_autodocs/MANIFEST.txt Details on how to configure Lobster, including environment variables, runtime options, and LLM setup. ```APIDOC ## Configuration ### Description Explains the various ways to configure Lobster, including environment variables, command-line options, and settings for Large Language Model integration. ``` -------------------------------- ### Approval Gate Workflow Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/README.md Demonstrates how to use the `Lobster` class and `exec`, `approve` primitives to create a workflow that includes an approval step. ```APIDOC ## Approval Gate Workflow Example This example illustrates a common workflow pattern involving an approval gate, using the Lobster SDK. ### Usage ```typescript new Lobster() .pipe(exec('fetch-items')) .pipe(approve({ prompt: 'Proceed?' })) .run(); ``` ### Description 1. Initializes a new `Lobster` instance. 2. Pipes the `exec` primitive to fetch items. 3. Pipes the `approve` primitive, pausing the workflow for user confirmation with a prompt. 4. Executes the constructed workflow. ``` -------------------------------- ### State Persistence Workflow Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/README.md Shows how to implement state persistence in a Lobster workflow using `stateGet` and `stateSet` primitives. ```APIDOC ## State Persistence Workflow Example This example demonstrates how to manage persistent state within a Lobster workflow. ### Usage ```typescript new Lobster() .pipe(stateGet('last-run')) .pipe(/*...process...*/) .pipe(stateSet('last-run')) .run(); ``` ### Description 1. Initializes a new `Lobster` instance. 2. Retrieves the state associated with the key 'last-run' using `stateGet`. 3. Includes a placeholder for processing logic. 4. Sets the state associated with the key 'last-run' using `stateSet`. 5. Executes the workflow. ``` -------------------------------- ### prMonitor Usage Examples Source: https://github.com/openclaw/lobster/blob/main/_autodocs/03-github-recipes.md Demonstrates how to use prMonitor for full monitoring, compact summaries, and change-only output. ```typescript import { prMonitor } from '@clawdbot/lobster/recipes/github'; // Full monitoring with state persistence const wf = prMonitor({ repo: 'openclaw/openclaw', pr: 1152 }); const result = await wf.run(); console.log(result.output[0]); // { // kind: 'github.pr.monitor', // repo: 'openclaw/openclaw', // prNumber: 1152, // changed: true, // summary: { // changedFields: ['state', 'reviewDecision'], // changes: { // state: { from: 'OPEN', to: 'MERGED' }, // reviewDecision: { from: '', to: 'APPROVED' } // } // }, // prSnapshot: {...} // } // Compact summary only const compact = await prMonitor({ repo: 'openclaw/openclaw', pr: 1152, summaryOnly: true }).run(); // Only output when changed const onchange = await prMonitor({ repo: 'openclaw/openclaw', pr: 1152, changesOnly: true }).run(); ``` -------------------------------- ### ParsedCommand Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/07-types.md An example demonstrating the input and output structure for a ParsedCommand, showing how a command line is translated into a structured object. ```typescript // Input: exec --json gh pr list --json number // Output: { name: 'exec', args: { json: true, _: ['gh', 'pr', 'list', '--json', 'number'] } } ``` -------------------------------- ### Lobster Run Command: Execute Workflow File Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of running a workflow defined in a file. ```bash lobster run --file workflow.lobster ``` -------------------------------- ### Lobster Change Detection Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/README.md Shows how to use the `diffLast` primitive to detect changes compared to a previously stored state. This example fetches data and compares it against the 'pr-state'. ```typescript new Lobster() .pipe(exec('fetch-pr')) .pipe(diffLast('pr-state')) .run(); ``` -------------------------------- ### Change Detection Workflow Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/README.md Illustrates how to use the `diffLast` primitive to detect changes compared to the previous run's state. ```APIDOC ## Change Detection Workflow Example This example shows how to implement change detection in Lobster workflows using the `diffLast` primitive. ### Usage ```typescript new Lobster() .pipe(exec('fetch-pr')) .pipe(diffLast('pr-state')) .run(); ``` ### Description 1. Initializes a new `Lobster` instance. 2. Executes a command to fetch PR information using `exec`. 3. Compares the fetched data with the state stored under 'pr-state' using `diffLast`. 4. Executes the workflow. ``` -------------------------------- ### Run Lobster Commands Source: https://github.com/openclaw/lobster/blob/main/README.md This snippet demonstrates basic Lobster command execution, including installing dependencies, running tests, linting, and accessing help or diagnostic information. It also shows how to execute a simple shell command with JSON output shaping. ```bash pnpm install pnpm test pnpm lint node ./bin/lobster.js --help node ./bin/lobster.js doctor node ./bin/lobster.js "exec --json --shell 'echo [1,2,3]' | where '0>=0' | json" ``` -------------------------------- ### Create a workflow file with basic steps Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-START-HERE.md This example demonstrates creating a simple workflow file named 'wf.lobster' using bash redirection. It defines a workflow with a single step that runs a command. ```bash cat > wf.lobster << 'EOF' name: example steps: - id: step1 run: command EOF ``` -------------------------------- ### Lobster Doctor Command: Example Output Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example output from the 'doctor' command, showing system checks and their status. ```text # ✓ Node.js: v22.3.0 # ✓ Lobster: 2026.6.11 # ✓ gh: 2.54.0 (authenticated) # ✓ Git: in repository (main) # ✓ State dir: ~/.lobster/state (writable) ``` -------------------------------- ### Lobster State Persistence Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/README.md Illustrates how to use `stateGet` and `stateSet` primitives to persist workflow state across runs. This example retrieves a value, processes it, and then saves an updated value. ```typescript new Lobster() .pipe(stateGet('last-run')) .pipe(/*...process...*/) .pipe(stateSet('last-run')) .run(); ``` -------------------------------- ### Lobster CLI Workflow Execution Source: https://github.com/openclaw/lobster/blob/main/_autodocs/06-workflow-files.md Demonstrates how to start a Lobster workflow from the command line, including passing arguments as JSON, and how to resume a halted workflow. ```bash # Start the workflow lobster run --file workflow.lobster --args-json '{"key":"value"}' # Returns: { "status": "needs_approval", "resumeToken": "..." } # Resume with approval lobster resume --token --approved true ``` -------------------------------- ### Lobster Resume Command: Provide Input Response Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of resuming a workflow by providing input data. ```bash lobster resume --token "eyJ..." --response '{"ids":[1,2,3]}' ``` -------------------------------- ### Lobster Graph Command: ASCII Output Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example visualization of a workflow graph using ASCII format for terminal display. ```text fetch: run review: approval when: $fetch.changed send: run stdin: $fetch.json ``` -------------------------------- ### Lobster Approval Gate Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/README.md Demonstrates a basic workflow using the `Lobster` class with an `exec` stage followed by an `approve` gate. The workflow pauses for user confirmation. ```typescript new Lobster() .pipe(exec('fetch-items')) .pipe(approve({ prompt: 'Proceed?' })) .run(); ``` -------------------------------- ### Lobster Run Command: Successful Output Format Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example JSON structure for a successful workflow execution. ```json { "status": "ok", "output": [...] } ``` -------------------------------- ### Lobster Run Command: Execute Workflow with Arguments Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of running a workflow file with JSON-formatted arguments. ```bash lobster run --file workflow.lobster --args-json '{"location":"Seattle","count":10}' ``` -------------------------------- ### Lobster Run Command: Execute Pipeline DSL Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of executing a pipeline directly from a DSL string. ```bash lobster run --pipeline 'exec echo hello | json' ``` -------------------------------- ### Lobster Resume Command: Approve and Continue Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of resuming a workflow by approving a halt. ```bash lobster resume --token "eyJ..." --approved true ``` -------------------------------- ### Run Weather Advice Workflow Command Source: https://github.com/openclaw/lobster/blob/main/_autodocs/11-examples.md Example command to execute the 'weather-advice' workflow defined in YAML, specifying arguments via JSON. ```bash lobster run --file weather-advice.lobster --args-json '{"location":"Seattle"}' ``` -------------------------------- ### Simple Approval Workflow Source: https://github.com/openclaw/lobster/blob/main/_autodocs/06-workflow-files.md An example workflow demonstrating fetching data, requiring manual approval, and then sending emails based on the approval decision. ```yaml name: send-emails description: Fetch and send emails with approval args: folder: type: string default: inbox description: Email folder to scan steps: - id: fetch run: fetch-emails --folder ${folder} - id: review approval: Send these email replies? stdin: $fetch.json - id: send run: send-emails stdin: $fetch.json when: $review.approved ``` -------------------------------- ### Build a workflow using the Lobster SDK Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-START-HERE.md This snippet demonstrates how to create a basic workflow using the Lobster SDK. It chains an execution step with an approval gate. Ensure you have installed the SDK package. ```typescript import { Lobster, exec, approve } from '@clawdbot/lobster'; const wf = new Lobster() .pipe(exec('fetch-items')) .pipe(approve({ prompt: 'Proceed?' })) .run(); ``` -------------------------------- ### Write SDK code for a simple workflow Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-START-HERE.md This snippet shows a minimal example of using the Lobster SDK to create and run a workflow with a single execution step. It requires importing the necessary components. ```typescript import { Lobster, exec } from '@clawdbot/lobster'; const wf = new Lobster().pipe(exec('...')).run(); ``` -------------------------------- ### Approval Workflow Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/01-sdk-lobster-class.md Shows a typical approval workflow where a Lobster instance is run, and if it requires approval, it is resumed with an approval decision. This pattern is useful for user-gated processes. ```typescript const wf = new Lobster() .pipe(exec('fetch-items.sh')) .pipe(approve({ prompt: 'Send these?' })); const result1 = await wf.run(); if (result1.status === 'needs_approval') { const result2 = await wf.resume( result1.requiresApproval.resumeToken, { approved: true } ); console.log(result2.output); } ``` -------------------------------- ### Lobster Resume Command: Reject Approval Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of resuming a workflow by rejecting a halt. ```bash lobster resume --token "eyJ..." --approved false ``` -------------------------------- ### Lobster Run Command: Approval/Input Halt Output Format Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example JSON structure for a workflow that requires approval or input. ```json { "status": "needs_approval", "requiresApproval": { "prompt": "Proceed?", "items": [...], "resumeToken": "..." } } ``` -------------------------------- ### Input Request Workflow Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/01-sdk-lobster-class.md Demonstrates a workflow that requires structured user input. The workflow halts, requesting specific data based on a schema, and is then resumed with the provided response. ```typescript const wf = new Lobster() .pipe(() => [{ id: 1 }, { id: 2 }]) .pipe(ctx => ({ halt: true, output: (async function* () { yield { type: 'input_request', prompt: 'Which items to process?', responseSchema: { type: 'object', properties: { ids: { type: 'array', items: { type: 'number' } } } } }; })() })); const result1 = await wf.run(); if (result1.status === 'needs_input') { const result2 = await wf.resume( result1.requiresInput.resumeToken, { response: { ids: [1] } } ); } ``` -------------------------------- ### Lobster State Directory Structure Source: https://github.com/openclaw/lobster/blob/main/_autodocs/08-configuration.md Illustrates the typical structure of the Lobster state directory, including example file names and key sanitization rules. ```bash ~/.lobster/state/ ├── github.pr_openclaw_openclaw_1152.json # Sanitized key names ├── my_cache.json └── last_run_time.json ``` -------------------------------- ### Run GH PR List Command and Filter Results Source: https://github.com/openclaw/lobster/blob/main/_autodocs/02-sdk-primitives.md This example demonstrates using the `exec` primitive to list GitHub PRs, parse the JSON output, and then filter out draft PRs. ```typescript import { Lobster, exec } from '@clawdbot/lobster'; // Run a command and parse JSON output new Lobster() .pipe(exec('gh pr list --json number,title,author')) .pipe(prs => { console.log(`Found ${prs.length} PRs`); return prs.filter(pr => !pr.draft); }) .run(); ``` -------------------------------- ### Lobster Resume Command: Using Approval ID Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of resuming a workflow using a shorter approval ID instead of a token. ```bash lobster resume --approval-id abc123 --approved true ``` -------------------------------- ### Get Command Help Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Retrieves help information for Lobster commands. Use `help ` for general command help or ` --help` for specific command options. ```bash lobster help lobster --help ``` -------------------------------- ### Get and Set State with state.get and state.set Source: https://github.com/openclaw/lobster/blob/main/_autodocs/02-sdk-primitives.md Demonstrates retrieving a value from state using state.get and then persisting a new value using state.set with the same key. ```typescript import { state } from '@clawdbot/lobster'; new Lobster() .pipe(state.get('my-key')) .pipe(state.set('my-key')) .run(); ``` -------------------------------- ### Lobster Graph Command: DOT Format with PNG Output Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of generating a workflow graph in DOT format and converting it to PNG. ```bash lobster graph --file workflow.lobster --format dot | dot -Tpng > graph.png ``` -------------------------------- ### Error Handling Workflow Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/06-workflow-files.md Demonstrates a resilient workflow that continues execution even if a primary step fails, using 'on_error' and conditional logic for fallback commands. ```yaml name: resilient-task description: Example of error handling steps: - id: primary run: primary-command on_error: continue - id: fallback run: fallback-command when: $primary.stdout | not - id: cleanup run: cleanup # Runs even if previous steps fail ``` -------------------------------- ### Run Workflow with Arguments Source: https://github.com/openclaw/lobster/blob/main/_autodocs/08-configuration.md Example of a Lobster workflow definition specifying arguments and how they are used within a 'run' step. Arguments are exposed as shell variables and environment variables. ```yaml args: repo: type: string default: openclaw/openclaw steps: - id: fetch run: gh api repos/${repo} env: REPO: ${LOBSTER_ARG_REPO} ``` -------------------------------- ### Invoking an LLM task using openclaw.invoke Source: https://github.com/openclaw/lobster/blob/main/README.md This example demonstrates calling the 'llm-task' tool with JSON arguments via the 'openclaw.invoke' shim in a workflow step. ```yaml name: hello-world steps: - id: greeting run: > openclaw.invoke --tool llm-task --action json --args-json '{"prompt":"Hello"}' ``` -------------------------------- ### Integrate Lobster Jobs with Cron Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example cron job configuration to schedule a Lobster workflow to run periodically. Output and errors are redirected to a log file. ```bash # /etc/cron.d/lobster-jobs 0 */6 * * * /usr/local/bin/lobster run --file /opt/workflows/check-prs.lobster >> /var/log/lobster.log 2>&1 ``` -------------------------------- ### Read, Increment, and Set State Counter Source: https://github.com/openclaw/lobster/blob/main/_autodocs/02-sdk-primitives.md This example uses `stateGet` to read a counter, increments it, and then uses `stateSet` to persist the updated value back to the state store. ```typescript import { Lobster, stateGet, stateSet } from '@clawdbot/lobster'; // Read and increment a counter new Lobster() .pipe(stateGet('counter')) .pipe(value => [{ count: (value?.count ?? 0) + 1 }]) .pipe(stateSet('counter')) .run(); ``` -------------------------------- ### Execute Command with Shell Mode Enabled Source: https://github.com/openclaw/lobster/blob/main/_autodocs/02-sdk-primitives.md This example shows how to use `exec` with the `shell: true` option to execute commands that rely on shell features like piping and redirection. ```typescript // Run with shell mode new Lobster() .pipe(exec('echo "hello" && echo "world"', { shell: true })) .run(); ``` -------------------------------- ### Iterate Over Lobster Pipeline Output Items Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Processes each item from the output of a Lobster pipeline. This example assumes the pipeline outputs a JSON array of items. Requires `jq` to parse JSON output. ```bash lobster run --pipeline 'exec echo "[1,2,3]" | json' | \ jq '.output[]' | while read ITEM; do echo "Processing: $ITEM" done ``` -------------------------------- ### Basic Lobster CLI Usage Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Shows how to create a simple workflow.lobster file and run/resume it using the Lobster CLI. ```bash # Create workflow.lobster cat > workflow.lobster << 'EOF' name: example steps: - id: fetch run: echo '{"msg":"hello"}' - id: approve approval: Continue? stdin: $fetch.json EOF # Run it lobster run --file workflow.lobster # Resume with approval lobster resume --token --approved true ``` -------------------------------- ### Basic Lobster SDK Usage Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Demonstrates creating a workflow with exec and approve commands, running it, and resuming after approval. ```typescript import { Lobster, exec, approve } from '@clawdbot/lobster'; const workflow = new Lobster() .pipe(exec('gh pr list --json number,title')) .pipe(approve({ prompt: 'Merge these PRs?' })); const result = await workflow.run(); if (result.status === 'needs_approval') { // Get user approval... const continued = await workflow.resume( result.requiresApproval.resumeToken, { approved: true } ); } ``` -------------------------------- ### Create and Run a Lobster Pipeline Source: https://github.com/openclaw/lobster/blob/main/_autodocs/04-core-runtime.md Demonstrates how to create a default command registry, parse a pipeline string, and run the pipeline using the Lobster core runtime. Ensure necessary imports are included. ```typescript import { createDefaultRegistry, runPipeline, parsePipeline } from '@clawdbot/lobster/core'; const registry = createDefaultRegistry(); // registry.get('exec') → execCommand // registry.get('approve') → approveCommand // ... const pipeline = parsePipeline('exec echo test | json'); await runPipeline({ pipeline, registry, // ... other params }); ``` -------------------------------- ### Lobster Resume Command: Cancel Workflow Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of cancelling a halted workflow. ```bash lobster resume --token "eyJ..." --cancel ``` -------------------------------- ### Lobster Graph Command: Mermaid Format Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Example of generating a workflow graph in Mermaid format. ```bash lobster graph --file workflow.lobster --format mermaid ``` -------------------------------- ### List Available Workflows Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Lists all available workflows. Use `--format json` for machine-readable output. ```bash lobster workflows.list [--format json|table] ``` ```bash lobster workflows.list ``` ```bash lobster workflows.list --format json ``` -------------------------------- ### Initialize Lobster with Constructor Options Source: https://github.com/openclaw/lobster/blob/main/_autodocs/08-configuration.md Instantiate the Lobster SDK with custom environment variables and a specific state directory. Useful for isolating environments or managing state in non-default locations. ```typescript new Lobster({ env: { GITHUB_TOKEN: 'ghp_...', API_KEY: 'sk_...' }, stateDir: '/tmp/lobster-state' }); ``` -------------------------------- ### List Available Workflows Source: https://github.com/openclaw/lobster/blob/main/_autodocs/05-pipeline-commands.md Use this command to see all available workflows. ```bash workflows.list ``` -------------------------------- ### CommandMeta Type Definition Source: https://github.com/openclaw/lobster/blob/main/_autodocs/07-types.md Defines metadata for a command, including its description, argument schema, and example invocations. ```typescript type CommandMeta = { description?: string; argsSchema?: JSONSchema; examples?: Array<{ args: Record; description?: string }>; sideEffects?: string[]; }; ``` -------------------------------- ### Lobster Constructor Source: https://github.com/openclaw/lobster/blob/main/_autodocs/01-sdk-lobster-class.md Initializes a new Lobster instance with optional configuration for environment variables and state directory. ```APIDOC ## new Lobster(options?) ### Description Initializes a new Lobster instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (`Object`) - Optional configuration options. - **options.env** (`Record`) - Environment variables to use for the workflow. Defaults to `process.env`. - **options.stateDir** (`string`) - Directory for persisting state across workflow runs. Defaults to `~/.lobster/state`. ### Example ```typescript import { Lobster } from '@clawdbot/lobster'; const workflow = new Lobster({ env: { GITHUB_TOKEN: 'ghp_...' }, stateDir: '/tmp/lobster-state' }); ``` ``` -------------------------------- ### run(initialInput?) Source: https://github.com/openclaw/lobster/blob/main/_autodocs/01-sdk-lobster-class.md Executes the workflow with optional initial input. ```APIDOC ## run(initialInput?) ### Description Executes the workflow with optional initial input. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **initialInput** (`any[]`) - Optional initial array of items to process. Defaults to `[]`. ### Returns - `Promise` - A promise that resolves to the workflow result. ### Response #### Success Response (200) - **ok** (`boolean`) - Indicates if the workflow completed successfully. - **status** (`'ok' | 'needs_approval' | 'needs_input' | 'cancelled' | 'error'`) - The status of the workflow execution. - **output** (`any[]`) - The output of the workflow. - **requiresApproval** (`object | null`) - Approval prompt and items if the workflow requires approval. - **requiresInput** (`object | null`) - Input prompt and schema if the workflow requires input. - **error** (`object | undefined`) - Error details if the workflow failed. ### Example ```typescript const result = await workflow.run([ { id: 1, email: 'user@example.com' }, { id: 2, email: 'other@example.com' } ]); if (result.status === 'needs_approval') { console.log('Waiting for approval:', result.requiresApproval.prompt); console.log('Items:', result.requiresApproval.items); } if (result.ok && result.status === 'ok') { console.log('Processed:', result.output); } ``` ``` -------------------------------- ### Workflow Files DSL Source: https://github.com/openclaw/lobster/blob/main/_autodocs/MANIFEST.txt Documentation for the Workflow YAML DSL, covering its structure, steps, fields, and usage examples. ```APIDOC ## Workflow Files ### Description Defines the structure and syntax for creating workflows using YAML. Covers steps, fields, and provides examples for defining complex processes. ``` -------------------------------- ### Today's workflow in OpenClaw Source: https://github.com/openclaw/lobster/blob/main/VISION.md Illustrates a typical, multi-step workflow in OpenClaw without Lobster, highlighting potential issues like high token usage, LLM-driven risks, lack of memory, and non-repeatability. ```text User: "Check my email, draft replies to anything urgent, and send them" What happens: 1. LLM plans: "I should search emails first" 2. Tool call: gmail.search 3. LLM interprets results, plans next step 4. Tool call: gmail.get (for each email) 5. LLM drafts replies 6. LLM decides to send 7. Tool call: gmail.send ... repeat for each email ``` -------------------------------- ### Get Persisted State Source: https://github.com/openclaw/lobster/blob/main/_autodocs/05-pipeline-commands.md Retrieves a value from the state store using a specified key. Returns null if the key is not found. ```bash state.get ``` ```bash state.get my-cache ``` -------------------------------- ### Instantiate Lobster with Options Source: https://github.com/openclaw/lobster/blob/main/_autodocs/01-sdk-lobster-class.md Create a new Lobster instance, optionally providing environment variables and a state directory for persistence. The state directory is used to save workflow progress across runs. ```typescript import { Lobster } from '@clawdbot/lobster'; const workflow = new Lobster({ env: { GITHUB_TOKEN: 'ghp_...' }, stateDir: '/tmp/lobster-state' }); ``` -------------------------------- ### Async Generator Stage Example Source: https://github.com/openclaw/lobster/blob/main/_autodocs/07-types.md Illustrates how a stage function can use an async generator to yield transformed items from an input async iterable. ```typescript async function* stage({ input, ctx }) { for await (const item of input) { yield transformedItem; } } ``` -------------------------------- ### Workflow with Lobster Source: https://github.com/openclaw/lobster/blob/main/VISION.md Demonstrates how Lobster simplifies and secures a workflow by consolidating steps, introducing a human approval checkpoint, and ensuring statefulness for future runs. ```text OpenClaw calls: lobster.run("email.triage") What happens: 1. Lobster fetches emails (deterministic) 2. Lobster classifies them (rule-based) 3. Lobster drafts replies (optional LLM step) 4. Lobster HALTS: "Send 3 drafts? [approve/reject]" 5. User approves 6. Lobster sends Tomorrow: Lobster remembers cursor, only processes new emails ``` -------------------------------- ### JSON Output from Workflow Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Pipelines and workflows output JSON by default, which is suitable for tool integration. This example shows a simple pipeline outputting JSON. ```bash lobster run --pipeline 'exec echo 123 | json' # Output: [123] ``` ```bash lobster run --pipeline 'exec gh pr list --json number | table' # Output: ASCII table (or JSON if piped) ``` -------------------------------- ### List Available Pipeline Commands Source: https://github.com/openclaw/lobster/blob/main/_autodocs/05-pipeline-commands.md Use this command to list all available pipeline commands and their metadata. ```bash commands.list ``` -------------------------------- ### Run a Shell Command Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Executes a shell command using the `exec` pipe within a Lobster workflow. Ensure the `gh` CLI is installed and configured for GitHub-related commands. ```typescript const result = await new Lobster() .pipe(exec('gh pr list --json number')) .run(); ``` -------------------------------- ### Set Core Configuration Environment Variables Source: https://github.com/openclaw/lobster/blob/main/_autodocs/08-configuration.md Configure the state storage directory and the timeout for TTY approval prompts using environment variables. This is a common way to set global configurations. ```bash export LOBSTER_STATE_DIR=/custom/state export LOBSTER_APPROVAL_INPUT_TIMEOUT_MS=60000 ``` -------------------------------- ### Notifying on PR Approval Source: https://github.com/openclaw/lobster/blob/main/_autodocs/03-github-recipes.md A concise example showing how to use `prMonitorNotify` to check for PR changes and trigger a notification if the output is not suppressed. Assumes `repo` and `pr` are defined. ```typescript const result = await prMonitorNotify({ repo, pr }).run(); if (!result.output[0]?.suppressed) { // Send notification console.log(result.output[0].message); } ``` -------------------------------- ### Pipeline Command Chaining Source: https://github.com/openclaw/lobster/blob/main/_autodocs/05-pipeline-commands.md Illustrates how to chain commands together using the pipe operator in a pipeline. ```bash command1 arg1 arg2 | command2 --flag arg | command3 ... ``` -------------------------------- ### Simple Pipeline with Approval Source: https://github.com/openclaw/lobster/blob/main/_autodocs/11-examples.md Creates a pipeline to list non-draft GitHub PRs, prompts for approval, and merges them. Handles both initial execution and resuming after approval. ```typescript import { Lobster, exec, approve } from '@clawdbot/lobster'; const workflow = new Lobster() .pipe(exec('gh pr list --json number,title')) .pipe(prs => prs.filter(pr => !pr.draft)) .pipe(approve({ prompt: 'Merge these PRs?' })) .pipe(async function* (prs) { for (const pr of prs) { console.log(`Merging PR #${pr.number}`); yield { ...pr, merged: true }; } }); const result = await workflow.run(); if (result.status === 'needs_approval') { console.log('Awaiting approval from:', result.requiresApproval.items.length, 'PRs'); // Later, when user approves: const continued = await workflow.resume( result.requiresApproval.resumeToken, { approved: true } ); console.log('Merged PRs:', continued.output); } else if (result.ok) { console.log('Done:', result.output); } ``` -------------------------------- ### Lobster SDK Workflow Resume Source: https://github.com/openclaw/lobster/blob/main/_autodocs/06-workflow-files.md Illustrates how to programmatically run a Lobster workflow using the SDK and resume it if it halts for approval or input. ```typescript const result = await workflow.run(); if (result.status === 'needs_approval') { const continued = await workflow.resume( result.requiresApproval.resumeToken, { approved: true } ); } ``` -------------------------------- ### GitHub Actions Workflow for Lobster Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Integrates Lobster into a GitHub Actions workflow to run a workflow file. Ensure the Lobster CLI is installed globally and the GITHUB_TOKEN secret is configured. ```yaml name: Lobster Workflow on: [workflow_dispatch] jobs: run: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '22' - run: npm install -g @clawdbot/lobster - run: | lobster run --file workflow.lobster \ --args-json '{"owner":"${{ github.repository_owner }}"}' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Show Help for a Command Source: https://github.com/openclaw/lobster/blob/main/_autodocs/10-cli-reference.md Displays help information for a specific Lobster command or subcommand. ```bash lobster help [command] ``` ```bash lobster [command] --help ``` ```bash lobster help run ``` ```bash lobster exec --help ``` -------------------------------- ### Lobster Class SDK Source: https://github.com/openclaw/lobster/blob/main/_autodocs/MANIFEST.txt Documentation for the main Lobster class, covering its constructor and core methods for managing and executing pipelines. ```APIDOC ## Lobster Class ### Description Provides the primary interface for interacting with the Lobster system programmatically. Allows for pipeline construction, execution, and state management. ### Methods - **constructor()**: Initializes a new Lobster instance. - **pipe(command)**: Adds a command to the current pipeline. - **run()**: Executes the constructed pipeline. - **resume()**: Resumes a previously paused or failed pipeline. - **clone()**: Creates a deep copy of the current Lobster instance. - **meta()**: Retrieves metadata about the Lobster instance or pipeline. ``` -------------------------------- ### CLI Reference Source: https://github.com/openclaw/lobster/blob/main/_autodocs/MANIFEST.txt Documentation for the Lobster command-line interface, including available commands and their options. ```APIDOC ## CLI Reference ### Description Details the commands available via the Lobster CLI, such as `run`, `resume`, `graph`, `doctor`, and `workflows.list`, along with their respective options. ``` -------------------------------- ### Get Approval Before Proceeding Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Adds an approval step to a workflow, pausing execution until user approval is granted. The `approve` pipe requires a prompt message and can be resumed using a token. ```typescript const result = await new Lobster() .pipe(() => [/* items to approve */]) .pipe(approve({ prompt: 'Proceed?' })) .run(); if (result.status === 'needs_approval') { // Prompt user or await external signal await workflow.resume(token, { approved: true }); } ``` -------------------------------- ### Lobster CLI Global Options Source: https://github.com/openclaw/lobster/blob/main/_autodocs/08-configuration.md Basic usage of the Lobster CLI, showing the general command structure and available global options like help, working directory, environment variables, and state directory. ```bash lobster [command] [options] ``` -------------------------------- ### createToolContext Source: https://github.com/openclaw/lobster/blob/main/_autodocs/04-core-runtime.md Creates and configures a tool execution context, allowing customization of the working directory, environment variables, I/O streams, cancellation signals, command registry, and LLM adapters. ```APIDOC ## createToolContext(ctx?) ### Description Create and configure a tool execution context. ### Parameters #### Path Parameters - **ctx.cwd** (string) - Optional - Working directory (default: `process.cwd()`) - **ctx.env** (Record) - Optional - Environment variables (default: `process.env`) - **ctx.stdin** (NodeJS.ReadableStream) - Optional - Input stream (default: `process.stdin`) - **ctx.stdout** (NodeJS.WritableStream) - Optional - Output stream (default: `process.stdout`) - **ctx.stderr** (NodeJS.WritableStream) - Optional - Error stream (default: `process.stderr`) - **ctx.signal** (AbortSignal) - Optional - Cancellation signal - **ctx.registry** (Map) - Optional - Custom command registry - **ctx.llmAdapters** (Record) - Optional - LLM provider adapters ### Returns Configured context object ready for pipeline execution. ### Example ```typescript import { createToolContext, runPipeline, parsePipeline, createDefaultRegistry } from '@clawdbot/lobster/core'; const ctx = createToolContext({ cwd: '/home/user', env: { ...process.env, CUSTOM_VAR: 'value' } }); const pipeline = parsePipeline('exec echo $CUSTOM_VAR | json'); const result = await runPipeline({ pipeline, registry: ctx.registry, stdin: ctx.stdin, stdout: ctx.stdout, stderr: ctx.stderr, env: ctx.env, cwd: ctx.cwd }); ``` ``` -------------------------------- ### Using prMonitorNotify to Monitor PR Changes Source: https://github.com/openclaw/lobster/blob/main/_autodocs/03-github-recipes.md Example demonstrating how to use the `prMonitorNotify` function to monitor a GitHub PR and log a message if changes are detected. Requires the Lobster library and `gh` CLI. ```typescript import { prMonitorNotify } from '@clawdbot/lobster/recipes/github'; const wf = prMonitorNotify({ repo: 'openclaw/openclaw', pr: 1200 }); const result = await wf.run(); const item = result.output[0]; if (!item.suppressed) { console.log(item.message); // Output: "PR updated: openclaw/openclaw#1200 (state, reviewDecision). // feat(tui): add syntax highlighting for code blocks. // https://github.com/openclaw/openclaw/pull/1200" } ``` -------------------------------- ### Daily Planning Workflow Source: https://github.com/openclaw/lobster/blob/main/VISION.md Generates a daily plan by combining calendar events and tasks, then prompts for approval before posting to a messaging channel. ```Lobster calendar.today | join tasks.today | prioritize | format.plan | approve --prompt "Post to #daily?" | message.send --channel slack --to "#daily" ``` -------------------------------- ### Using ghPrView to Fetch and Log PR Details Source: https://github.com/openclaw/lobster/blob/main/_autodocs/03-github-recipes.md Example of using `ghPrView` within a Lobster workflow to fetch PR details and log its number, title, state, and draft status. Requires `gh` CLI and accessible repository. ```typescript import { Lobster } from '@clawdbot/lobster'; import { ghPrView } from '@clawdbot/lobster/recipes/github'; const wf = new Lobster() .pipe(ghPrView({ repo: 'owner/repo', pr: 123 })) .pipe(pr => { console.log(`PR #${pr.number}: ${pr.title}`); console.log(`State: ${pr.state}, Draft: ${pr.isDraft}`); }) .run(); ``` -------------------------------- ### Pipeline Commands Reference Source: https://github.com/openclaw/lobster/blob/main/_autodocs/MANIFEST.txt A complete reference for all built-in commands available for use within Lobster pipelines. ```APIDOC ## Pipeline Commands ### Description Detailed documentation for approximately 20 built-in commands that can be used to construct Lobster pipelines. Each command includes its syntax, parameters, and expected behavior. ``` -------------------------------- ### Define a workflow using YAML syntax Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-START-HERE.md This snippet shows the basic YAML syntax for defining a Lobster workflow. It includes defining arguments, steps, and commands. This is an alternative to using the SDK for workflow definition. ```yaml name: my-workflow args: count: { type: number, default: 10 } steps: - id: fetch run: fetch-items --limit ${LOBSTER_ARG_COUNT} - id: approve approval: Continue? stdin: $fetch.json ``` -------------------------------- ### Resume Workflow with Approval/Response Source: https://github.com/openclaw/lobster/blob/main/_autodocs/08-configuration.md Resume a workflow at an approval gate, setting environment variables for initiated and approved by users, and then executing the resume command. ```bash export LOBSTER_APPROVAL_INITIATED_BY=alice@example.com export LOBSTER_APPROVAL_APPROVED_BY=bob@example.com lobster resume --token --approved true ``` -------------------------------- ### Approval Workflow with Lobster Resume Source: https://github.com/openclaw/lobster/blob/main/_autodocs/11-examples.md Initiate a workflow that requires approval, capture the resume token, and later approve the action using the token. ```bash # Start workflow RESULT=$(lobster run --file workflow.lobster) TOKEN=$(echo $RESULT | jq -r '.requiresApproval.resumeToken') ITEMS=$(echo $RESULT | jq '.requiresApproval.items') echo "Waiting for approval on: $ITEMS" # Later, approve and resume lobster resume --token "$TOKEN" --approved true ``` -------------------------------- ### Main SDK Exports Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Imports core functionalities from the main Lobster SDK package. ```typescript // import from '@clawdbot/lobster' export { Lobster }; export { approve, exec, shell, stateGet, stateSet, state, diffLast }; export { runPipeline, readState, writeState }; ``` -------------------------------- ### Configure LLM Pricing Source: https://github.com/openclaw/lobster/blob/main/_autodocs/08-configuration.md Provide custom token pricing for LLM providers in JSON format to enable accurate workflow cost calculation. Lobster includes built-in pricing for common models. ```bash export LOBSTER_LLM_PRICING_JSON='{"claude-opus-4-8":{"input":0.003,"output":0.015},"gpt-4":{"input":0.03,"output":0.06}}' ``` -------------------------------- ### CI/CD Deployment Workflow Source: https://github.com/openclaw/lobster/blob/main/_autodocs/11-examples.md This workflow automates the build, test, security scan, approval, deployment, verification, and notification steps for a CI/CD pipeline. ```yaml name: deploy description: Build, test, and deploy args: environment: type: string default: staging description: Deployment environment version: type: string description: Version to deploy steps: - id: build run: ./scripts/build.sh retry: max_attempts: 3 delay_ms: 2000 - id: test run: ./scripts/test.sh timeout_ms: 300000 - id: scan run: security-scan . on_error: continue - id: approval approval: Deploy v${LOBSTER_ARG_VERSION} to ${LOBSTER_ARG_ENVIRONMENT}? required_approver: devops-team@example.com - id: deploy run: ./scripts/deploy.sh --env "${environment}" --version "${version}" when: $approval.approved retry: max_attempts: 2 - id: verify run: ./scripts/smoke-test.sh timeout_ms: 60000 - id: notify run: send-notification --channel deployments "Deployment successful: v${LOBSTER_ARG_VERSION}" on_error: continue ``` -------------------------------- ### Render Strings with Template Substitution Source: https://github.com/openclaw/lobster/blob/main/_autodocs/05-pipeline-commands.md Use the `template` command to render strings using placeholders. It accepts a template string with `{{field.path}}` placeholders. ```bash template --template ``` ```bash exec echo '{"id": 123, "user": "alice"}' | json | template --template "User {{user}} (ID {{id}})" ``` -------------------------------- ### Select Specific Fields from Objects Source: https://github.com/openclaw/lobster/blob/main/_autodocs/05-pipeline-commands.md Projects objects to include only the specified fields. Fields are provided as a comma-separated list. ```bash exec gh pr list --json number,title,author,state | pick number,title ``` -------------------------------- ### Run Lobster in CI/CD Source: https://github.com/openclaw/lobster/blob/main/_autodocs/00-index.md Shows how to execute a Lobster workflow file within a CI/CD pipeline, such as GitHub Actions, passing arguments and setting environment variables like GITHUB_TOKEN. ```yaml - run: | lobster run --file workflow.lobster \ --args-json '{"env":"prod"}' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### SDK Primitives Source: https://github.com/openclaw/lobster/blob/main/_autodocs/MANIFEST.txt Reference for fundamental SDK operations used for executing commands, managing state, and comparing data. ```APIDOC ## SDK Primitives ### Description Low-level functions for interacting with the Lobster runtime and state. ### Methods - **exec(command)**: Executes a single command within the Lobster environment. - **approve()**: Approves a pending state or action. - **stateGet(key)**: Retrieves the current state associated with a given key. - **stateSet(key, value)**: Sets or updates a state value. - **diffLast()**: Computes the difference between the last two states. ```