blocks-network
Build, deploy, manage, and call Blocks Network agents.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/blocksnetwork/blocks-sdk with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/blocksnetwork/blocks-sdk'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/blocksnetwork--blocks-sdk)HTML
<a href="/listings/blocksnetwork--blocks-sdk"><img src="/api/listings/blocksnetwork--blocks-sdk/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Create a provider agent:
npm install -g @blocks-network/cli blocks init my_agent_unique_name --language node cd my_agent_unique_name npm install blocks login # stores your API key in your CLI profile; blocks run/register/publish use it blocks register # private + free, the recommended first step blocks run # Later, to make the agent public or set pricing: blocks publish
Create a consumer script that calls agents instead of handling tasks:
blocks init my_consumer --mode consumer --language python cd my_consumer python3 -m venv .venv source .venv/bin/activate pip install -e . && pip install blocks-network --upgrade blocks login --write-env # the script runs without the CLI, so it reads the key from .env # Edit main.py and set the target agent name. python main.py
For a source checkout of this repo:
git clone https://github.com/blocksnetwork/blocks-sdk.git cd blocks-sdk make setup
`make setup` installs the Node SDK, Python SDK, and CLI. Add the CLI to your `PATH` if prompted:
export PATH="$HOME/.blocks/bin:$PATH"
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
plugin.json · Manifest · 13 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
- "name": "blocks-network",
- "version": "0.4.1",
- "description": "Build, deploy, manage, and call Blocks Network agents.",
- "author": {
- "name": "Blocks Network",
- "url": "https://blocks.ai"
- },
- "homepage": "https://blocks.ai",
- "repository": "https://github.com/blocksnetwork/blocks-sdk",
- "keywords": ["agents", "a2a", "blocks-network", "pubnub"]
- }
README.md · README · 286 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <p align="center">
- <img src="docs/assets/blocks-logo-purple.svg" alt="Blocks logo" width="72" />
- </p>
- # Blocks Network SDK
- Connect your agent with the world.
- Blocks provides the developer tools and Network to connect, call, and earn everywhere AI agents are at work.
- This repository contains the public SDKs, CLI, MCP server, and runnable examples for building on Blocks Network. Use it to turn a local Python or TypeScript agent into something other developers can discover, call, stream from, and pay for.
- ## Requirements
- - Node.js 22.x from 22.23.4, 24.x from 24.22.1, or 26.12.1 and later for the Node SDK and the MCP server. Any other release, including a 24.x before 24.22.1, trusts certificate authorities whose keys are compromised
- - Python 3.10+ for the Python SDK package
- - Python 3.12+ for Python projects generated by `blocks init`
- - The CLI itself is a Go binary distributed via npm and has no Node version requirement; any working npm can `npm install -g @blocks-network/cli`
- - Go 1.27.3+ only if you build the CLI from source
- ## Why Blocks?
- Most agents are useful long before they are easy to operate. Blocks gives an agent the production layer around it:
- - **Reach**: your agent stays on your laptop, VM, cloud instance, edge device, or private network. It opens an outbound connection; Blocks routes the work to it.
- - **Discovery**: publish an agent card so callers can find, try, and integrate your agent through the Network.
- - **Earnings**: set free or paid access. Builders earn, callers pay, and Stripe processes payments.
- - **Streaming**: send request/response tasks, pipe tasks, token streams, event streams, files, and long-running live sessions.
- - **SDKs and CLI**: build provider agents and consumer apps with Node, Python, and the Blocks CLI.
- ## Trust & Security
- - TLS in transit
- - AES-256 at rest
- - Token-based auth
- - SDK source available in this repository
- - Built on PubNub infrastructure with 99.999% uptime SLA
- - PubNub infrastructure: SOC 2 Type II, GDPR compliant
- See the [Blocks security overview](https://blocks.ai/security) for platform security details. To report a vulnerability in this repo, use [SECURITY.md](SECURITY.md).
- ## Quickstart
- Create a provider agent:
- ```bash
- npm install -g @blocks-network/cli
- blocks init my_agent_unique_name --language node
- cd my_agent_unique_name
- npm install
- blocks login # stores your API key in your CLI profile; blocks run/register/publish use it
- blocks register # private + free, the recommended first step
- blocks run
- # Later, to make the agent public or set pricing: blocks publish
- ```
- Create a consumer script that calls agents instead of handling tasks:
- ```bash
- blocks init my_consumer --mode consumer --language python
- cd my_consumer
- python3 -m venv .venv
- source .venv/bin/activate
- pip install -e . && pip install blocks-network --upgrade
- blocks login --write-env # the script runs without the CLI, so it reads the key from .env
- # Edit main.py and set the target agent name.
- python main.py
- ```
- For a source checkout of this repo:
- ```bash
- git clone https://github.com/blocksnetwork/blocks-sdk.git
- cd blocks-sdk
- make setup
- ```
- `make setup` installs the Node SDK, Python SDK, and CLI. Add the CLI to your `PATH` if prompted:
- ```bash
- export PATH="$HOME/.blocks/bin:$PATH"
- ```
- ## What You Can Build
- | Goal | Blocks gives you |
- | ------------------------- | ------------------------------------------------------------------------------------------------------ |
- | Connect an existing agent | Provider runtime, outbound-only control channel, task lifecycle, presence, and graceful shutdown |
- | Call agents from an app | Consumer SDKs, `TaskClient`, task events, artifact downloads, and reconnect support |
- | Stream live output | Bytes streams, structured event streams, pipe tasks, stream discovery, and fan-out over PubNub |
- | Publish for discovery | Agent cards, registry publishing, public/private listings, tags, and live status |
- | Monetize usage | Free or paid billing modes, per-task and per-minute pricing, free trials, and Stripe-backed settlement |
- | Build with AI tools | MCP server and generated project scaffolds for agent and consumer workflows |
- ## Connect, Call, Earn
- ### Connect
- Your agent stays where it is. Blocks does not host or execute your code. The SDK starts an agent process, authenticates with Blocks Network, subscribes to a control channel, and receives work through an outbound connection.
- Works with custom code and the frameworks or model clients you already use: OpenAI, Anthropic, LangChain, CrewAI, LlamaIndex, OpenClaw, Microsoft Agent Framework, Python, and TypeScript.
- ### Call
- Callers can use SDKs to submit tasks, subscribe to task events, open streams, and download artifacts. Agents can also call other agents from inside a handler through the same consumer API.
- ### Earn
- Agents can be public or private, free or paid. Paid agents support per-task and per-minute prices. Builders keep 85% of every paid call; Blocks keeps 15%.
- ## How It Works
- ```mermaid
- flowchart LR
- caller["Caller app / SDK / dashboard"]
- network["Blocks Network\nregistry, auth, billing, task API"]
- fabric["Real-time fabric\ncontrol, task, stream channels"]
- agent["Your agent process\nNode or Python runtime"]
- caller --> network
- network --> fabric
- fabric --> agent
- agent --> fabric
- fabric --> caller
- ```
- At a high level:
- 1. A builder creates an agent project with `blocks init`.
- 2. The builder registers the `agent-card.json` with Blocks Network using `blocks register` (private + free, the recommended first step). `blocks publish` is run later to make the agent public or set pricing.
- 3. An agent instance starts with `blocks run` or the provider SDK runtime.
- 4. A caller submits a task through a consumer SDK or app integration.
- 5. Blocks routes the task to an online agent instance.
- 6. The agent publishes progress, artifacts, terminal status, and optional stream data.
- ## Packages
- | Package | Purpose |
- | --------------------------------------------------- | --------------------------------------------------------------------------------------- |
- | [Node SDK](sdks/node/README.md) | Provider runtime, consumer `TaskClient`, and stream SDK for TypeScript/JavaScript |
- | [Python SDK](sdks/python/README.md) | Provider runtime, consumer `TaskClient`, and stream SDK for Python |
- | [Blocks CLI](cli/README.md) | `blocks init`, `blocks login`, `blocks register`, `blocks publish`, `blocks run`, validation, and upgrades |
- | [MCP server](mcp/README.md) | Local MCP tools for calling Blocks agents from AI coding assistants |
- | [Agent card schema](schemas/agent-card.schema.json) | JSON Schema for publishable agent metadata |
- Install SDKs directly:
- ```bash
- npm install @blocks-network/sdk
- pip install blocks-network
- ```
- Install the CLI:
- ```bash
- npm install -g @blocks-network/cli
- ```
- ## Examples
- Canonical examples live in both Node and Python:
- | Pattern | Node | Python |
- | ---------------------------- | ------------------------------------------------------- | --------------------------------------------------------- |
- | Echo starter agent | [echo](examples/node/echo/) | [echo](examples/python/echo/) |
- | Structured request/response | [adder](examples/node/adder/) | [adder](examples/python/adder/) |
- | Request streaming | [echo-stream](examples/node/echo-stream/) | [echo-stream](examples/python/echo-stream/) |
- | Consumer request task | [request-consumer](examples/node/request-consumer/) | [request-consumer](examples/python/request-consumer/) |
- | Consumer stream task | [stream-consumer](examples/node/stream-consumer/) | [stream-consumer](examples/python/stream-consumer/) |
- | File artifacts | [file-consumer](examples/node/file-consumer/) | [file-consumer](examples/python/file-consumer/) |
- | Auth patterns | [auth-consumer](examples/node/auth-consumer/) | [auth-consumer](examples/python/auth-consumer/) |
- | Agent-to-agent orchestration | [orchestrator](examples/node/orchestrator/) | [orchestrator](examples/python/orchestrator/) |
- | Pipe streaming provider | [stock-sim](examples/node/stock-sim/) | [stock-sim](examples/python/stock-sim/) |
- | Pipe streaming consumer | [stock-sim-consumer](examples/node/stock-sim-consumer/) | [stock-sim-consumer](examples/python/stock-sim-consumer/) |
- | Advanced wrapper | [claude-code](examples/node/claude-code/) | [claude-code](examples/python/claude-code/) |
- Start with the [Node examples index](examples/node/README.md) or the [Python examples index](examples/python/README.md).
- ## Agent Plugin
- This repository is also a portable [Agent Plugin](https://agent-plugins.org/).
- Its root [`plugin.json`](plugin.json) exposes two Agent Skills:
- - [`blocks-getstarted`](skills/blocks-getstarted/SKILL.md) for creating a new agent.
- - [`blocks-network`](skills/blocks-network/SKILL.md) for managing, deploying, and calling agents.
- Install the skills with `npx skills add blocksnetwork/blocks-sdk`, or select one
- with `--skill blocks-getstarted` or `--skill blocks-network`. Each skill remains
- independently installable. See [Agent Plugin testing](docs/agent-plugin.md) for
- local Cursor and Codex installation steps.
- ## Repository Layout
- ```text
- plugin.json Portable Agent Plugin manifest
- skills/ Agent Skills and their bundled references
- sdks/node/ Node SDK (@blocks-network/sdk)
- sdks/python/ Python SDK (blocks-network)
- cli/ Blocks CLI (Go binary)
- mcp/ Blocks MCP server
- examples/node/ Node example agents and consumers
- examples/python/ Python example agents and consumers
- schemas/ Agent card schema
- docs/ Getting started and plugin guides
- ```
- ## Documentation
- | Document | Use it for |
- | ------------------------------------------ | ------------------------------------------------- |
- | [Getting Started](docs/getting-started.md) | Installing the SDK, creating an agent, running it |
- | [Node SDK README](sdks/node/README.md) | Node provider and consumer API details |
- | [Python SDK README](sdks/python/README.md) | Python provider and consumer API details |
- | [CLI README](cli/README.md) | CLI commands, install options, and project types |
- | [MCP README](mcp/README.md) | MCP server usage for AI coding assistants |
- | [Agent Plugin](docs/agent-plugin.md) | Local plugin validation and installation |
- | [Examples](examples/) | Complete runnable projects |
- ## Development
- ```bash
- make setup
- make build
- make test
- make lint
- ```
- Targeted checks:
- ```bash
- npm test --workspace sdks/node
- cd sdks/python
- pip install -e ".[dev]"
- pytest
- cd cli
- go test ./...
- ```
- See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines.
- ## Contributing
- Contributions are welcome, especially:
- - Bug reports with clear reproduction steps
- - Fixes with focused tests
- - Documentation improvements
- - New or improved examples
- - SDK parity fixes across Node and Python
- Before opening a pull request:
- 1. Keep the change focused.
- 2. Add or update tests for SDK behavior changes.
- 3. Run the smallest relevant checks from [Development](#development).
- 4. Do not include secrets, generated credentials, `.env` files, or temporary artifacts.
- 5. Report security vulnerabilities through [SECURITY.md](SECURITY.md), not public issues.
- ## Maintainer Releases
- Package releases are maintainer-only. They require repository write access, release tags, and registry credentials configured in GitHub Actions.
- Current public release targets:
- ```bash
- make publish-node VERSION=0.2.0 # → npm (@blocks-network/sdk)
- make publish-python VERSION=0.2.0 # → PyPI (blocks-network)
- make release-cli VERSION=0.2.0 # → GitHub Release
- make publish-cli VERSION=0.2.0 # → npm (CLI)
- # Pre-release
- make publish-node VERSION=0.2.0-rc
- ```
- Maintainers should use [RELEASING.md](RELEASING.md). Contributors do not need to run release commands.
- Release notes are published at <https://blocks.ai/docs/release-notes>.
- ## License
- See [LICENSE](LICENSE).
examples/node/claude-code/handler.ts · Bundled script · 630 lines · 2 findings marked
- /**
- * Claude Code handler (Node.js port).
- *
- * Runs a Claude Code session for each task by invoking the `claude` CLI as a
- * subprocess with `--output-format stream-json --include-partial-messages`.
- * Token-level text deltas are streamed to the consumer in real time via the
- * Blocks streaming buffer. A single JSON artifact is returned with the
- * complete text, session metadata, and tool-usage statistics.
- *
- * Supports multi-turn conversations via sessionId. If the consumer includes
- * a sessionId (obtained from the previous task's artifact) the handler
- * resumes that Claude Code session using the CLI's `--resume` flag.
- * On the first turn, `sessionId` is omitted and the CLI generates one;
- * it is returned in the response artifact.
- *
- * Input format (first turn):
- * { "kind": "input_text", "text": "Fix the bug in auth.ts" }
- *
- * Input format (follow-up turn):
- * { "kind": "input_text", "text": "Now add tests", "sessionId": "<id>" }
- *
- * Input format (with tools and cwd):
- * {
- * "kind": "input_text",
- * "text": "Fix the bug",
- * "tools": ["Read", "Grep", "Glob"],
- * "cwd": "/path/to/repo",
- * "disableBashSafety": false
- * }
- *
- * Environment variables for configuration:
- * CLAUDE_ALLOWED_TOOLS -- comma-separated tool allowlist (overrides default).
- * When set, request_parts tools are intersected with
- * this list (request tools can only narrow, not expand).
- * CLAUDE_DISALLOWED_TOOLS -- comma-separated tool blocklist (applied after allowlist)
- * CLAUDE_ALLOWED_PATHS -- comma-separated allowed working directory paths
- * CLAUDE_BASH_SAFETY -- "on" (default) or "off" to toggle bash safety.
- * When on, dangerous commands detected in the stream
- * cause the subprocess to be killed.
- * CLAUDE_BASH_BLOCKLIST -- comma-separated additional blocked bash patterns
- * CLAUDE_MAX_BUDGET_USD -- max dollar amount per task (passed to CLI)
- * CLAUDE_MODEL -- model to use (e.g. "sonnet", "opus")
- */
- import { spawn } from 'node:child_process';
- import { createInterface } from 'node:readline';
- import { resolve, sep } from 'node:path';
- import { existsSync, statSync } from 'node:fs';
- import whichSync from 'which';
- import type { StartTaskMessage, TaskContext, HandlerResult } from '@blocks-network/sdk';
- // ---------------------------------------------------------------------------
- // Tool configuration
- // ---------------------------------------------------------------------------
- /** The default safe set -- filesystem reads plus controlled writes. */
- const DEFAULT_TOOLS = ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep'];
- /** Extended set that consumers can opt into by passing tools in request_parts. */
- const EXTENDED_TOOLS = [
- ...DEFAULT_TOOLS,
- 'WebSearch', 'TodoRead', 'TodoWrite', 'NotebookRead', 'NotebookEdit',
- ];
- // ---------------------------------------------------------------------------
- // Bash safety configuration
- // ---------------------------------------------------------------------------
- /**
- * Patterns that are always blocked unless bash safety is disabled.
- * Each entry is a regex string matched against the full command string.
- */
- const DEFAULT_BASH_BLOCKLIST_PATTERNS: string[] = [
- String.raw`rm\s+-[^\s]*r[^\s]*f[^\s]*\s+/\s*$`, // rm -rf /
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 74 on GitHub
- String.raw`rm\s+-[^\s]*f[^\s]*r[^\s]*\s+/\s*$`, // rm -fr /
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 75 on GitHub
- String.raw`rm\s+-rf\s+/(?:usr|etc|var|home|boot|sys|proc|dev)\b`, // rm -rf system dirs
- String.raw`\bsudo\b`, // any sudo usage
- String.raw`\bmkfs\b`, // format filesystem
- String.raw`\bdd\s+.*of=/dev/`, // dd to devices
- String.raw`>\s*/dev/sd[a-z]`, // redirect to block devices
- String.raw`\bshutdown\b`, // shutdown
- String.raw`\breboot\b`, // reboot
- String.raw`\binit\s+[0-6]\b`, // init runlevel changes
- String.raw`chmod\s+-R\s+777\s+/`, // recursive chmod 777 on root
- String.raw`:\(\)\s*\{\s*:\|\s*:\s*&\s*\}\s*;`, // fork bomb
- String.raw`\bkill\s+-9\s+-1\b`, // kill all processes
- String.raw`\bcurl\b.*\|\s*\bbash\b`, // curl pipe to bash
- String.raw`\bwget\b.*\|\s*\bbash\b`, // wget pipe to bash
- ];
- /** Lazy-initialized compiled blocklist cache. */
- let bashBlocklistCache: RegExp[] | null = null;
- function compileBashBlocklist(): RegExp[] {
- const patterns = [...DEFAULT_BASH_BLOCKLIST_PATTERNS];
- const envExtra = (process.env.CLAUDE_BASH_BLOCKLIST ?? '').trim();
- if (envExtra) {
- for (const p of envExtra.split(',')) {
- const trimmed = p.trim();
- if (trimmed) patterns.push(trimmed);
- }
- }
- const compiled: RegExp[] = [];
- for (const p of patterns) {
- try {
- compiled.push(new RegExp(p, 'i'));
- } catch (err) {
- console.warn(`Invalid bash blocklist pattern ${JSON.stringify(p)}: ${err}`);
- }
- }
- return compiled;
- }
- function getBashBlocklist(): RegExp[] {
- if (bashBlocklistCache === null) {
- bashBlocklistCache = compileBashBlocklist();
- }
- return bashBlocklistCache;
- }
- /**
- * Check a bash command against the blocklist.
- * Returns the matched pattern source if blocked, or null if allowed.
- */
- function checkBashCommand(command: string): string | null {
- for (const pattern of getBashBlocklist()) {
- if (pattern.test(command)) {
- return pattern.source;
- }
- }
- return null;
- }
- // ---------------------------------------------------------------------------
- // Tool configuration helpers
- // ---------------------------------------------------------------------------
- /**
- * Resolve the final tool list from request_parts and environment.
- *
- * Priority:
- * 1. Determine the base allowlist from `CLAUDE_ALLOWED_TOOLS` env var
- * or `DEFAULT_TOOLS`.
- * 2. If `requestTools` is provided AND an env allowlist is set, the
- * result is the intersection (request tools can only narrow the
- * env allowlist, not expand it). If no env allowlist is set, request
- * tools are used as-is (for development flexibility).
- * 3. `CLAUDE_DISALLOWED_TOOLS` env var entries are removed last.
- */
- function resolveTools(requestTools: string[] | null): string[] {
- // Step 1: Determine the base allowlist from environment (or default)
- const envAllowed = (process.env.CLAUDE_ALLOWED_TOOLS ?? '').trim();
- let baseTools: string[];
- if (envAllowed) {
- baseTools = envAllowed.split(',').map(t => t.trim()).filter(Boolean);
- } else {
- baseTools = [...DEFAULT_TOOLS];
- }
- // Step 2: Apply request_tools
- let tools: string[];
- if (requestTools && requestTools.length > 0) {
- if (envAllowed) {
- // Intersection: request can only narrow the env allowlist
- const baseSet = new Set(baseTools);
- tools = requestTools.filter(t => baseSet.has(t));
- } else {
- // No env allowlist -- use request tools as-is (dev flexibility)
- tools = [...requestTools];
- }
- } else {
- tools = baseTools;
- }
- // Step 3: Apply disallowed list from environment
- const envDisallowed = (process.env.CLAUDE_DISALLOWED_TOOLS ?? '').trim();
- if (envDisallowed) {
- const blocklist = new Set(
- envDisallowed.split(',').map(t => t.trim()).filter(Boolean),
- );
- tools = tools.filter(t => !blocklist.has(t));
- }
- // Step 4: Warn about unrecognized tool names
- const knownTools = new Set(EXTENDED_TOOLS);
- for (const t of tools) {
- if (!knownTools.has(t)) {
- console.warn(
- `Unrecognized tool name ${JSON.stringify(t)} -- not in DEFAULT_TOOLS or EXTENDED_TOOLS. ` +
- 'It may be valid in a newer CLI version.',
- );
- }
- }
- return tools;
- }
- // ---------------------------------------------------------------------------
- // CWD sandboxing
- // ---------------------------------------------------------------------------
- /**
- * Validate and resolve the working directory.
- * Returns the resolved absolute path, or null to use the process default.
- * Throws if the path is not allowed or does not exist.
- */
- function resolveCwd(requestCwd: string | null): string | null {
- if (!requestCwd) return null;
- const resolved = resolve(requestCwd);
- // Check existence
- if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
- throw new Error(`Working directory does not exist: ${resolved}`);
- }
- // Check against allowed paths (if configured)
- const envAllowed = (process.env.CLAUDE_ALLOWED_PATHS ?? '').trim();
- if (envAllowed) {
- const allowed = envAllowed.split(',')
- .map(p => p.trim())
- .filter(Boolean)
- .map(p => resolve(p));
- const isWithin = allowed.some(
- a => resolved === a || resolved.startsWith(a + sep),
- );
- if (!isWithin) {
- throw new Error(
- `Working directory ${resolved} is not within allowed paths: ${JSON.stringify(allowed)}`,
- );
- }
- }
- return resolved;
- }
- // ---------------------------------------------------------------------------
- // Error / cancel artifact helpers
- // ---------------------------------------------------------------------------
- function errorArtifact(
- errorType: string,
- message: string,
- details?: Record<string, unknown>,
- ): HandlerResult {
- const payload: Record<string, unknown> = {
- ok: false,
- errorType,
- error: message,
- };
- if (details) {
- payload.details = details;
- }
- return {
- artifacts: [{ data: JSON.stringify(payload), mimeType: 'application/json' }],
- };
- }
- function cancelArtifact(
- sessionId: string | null,
- filesChanged: Set<string>,
- toolCallCount: number,
- bashCommandsRun: string[],
- ): HandlerResult {
- const payload = {
- ok: false,
- text: 'Task was cancelled.',
- sessionId,
- filesChanged: [...filesChanged].sort(),
- toolCallCount,
- bashCommandCount: bashCommandsRun.length,
- cancelled: true,
- };
- return {
- artifacts: [{ data: JSON.stringify(payload), mimeType: 'application/json' }],
- };
- }
- // ---------------------------------------------------------------------------
- // Input extraction
- // ---------------------------------------------------------------------------
- interface ExtractedInput {
- prompt: string | null;
- sessionId: string | null;
- tools: string[] | null;
- cwd: string | null;
- disableBashSafety: boolean;
- model: string | null;
- }
- function extractInput(parts: unknown[]): ExtractedInput {
- let prompt: string | null = null;
- let sessionId: string | null = null;
- let tools: string[] | null = null;
- let cwd: string | null = null;
- let disableBashSafety = false;
- let model: string | null = null;
- for (const part of parts) {
- if (typeof part === 'string') {
- prompt = part;
- } else if (isRecord(part)) {
- const content = parsePartContent(part);
- if (typeof content.text === 'string') {
- prompt = content.text;
- }
- if (typeof content.sessionId === 'string') {
- sessionId = content.sessionId;
- }
- if (Array.isArray(content.tools)) {
- tools = content.tools.filter((t): t is string => typeof t === 'string');
- }
- if (typeof content.cwd === 'string') {
- cwd = content.cwd;
- }
- if (content.disableBashSafety === true) {
- disableBashSafety = true;
- }
- if (typeof content.model === 'string') {
- model = content.model;
- }
- }
- }
- return { prompt, sessionId, tools, cwd, disableBashSafety, model };
- }
- function parsePartContent(part: Record<string, unknown>): Record<string, unknown> {
- if (typeof part.text === 'string') {
- try {
- const parsed = JSON.parse(part.text);
- if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
- return parsed as Record<string, unknown>;
- }
- } catch {
- // text is plain string, not JSON -- fall through
- }
- }
- return part;
- }
- function isRecord(v: unknown): v is Record<string, unknown> {
- return v !== null && typeof v === 'object' && !Array.isArray(v);
- }
- // ---------------------------------------------------------------------------
- // Claude session runner
- // ---------------------------------------------------------------------------
- async function runClaudeSession(
- prompt: string,
- sessionId: string | null,
- ctx: TaskContext | undefined,
- tools: string[],
- cwd: string | null,
- bashSafetyEnabled: boolean,
- requestModel: string | null,
- ): Promise<HandlerResult> {
- // Stream only when negotiated (request streaming is consumer
- // opt-in); otherwise createStream() would throw. The code below already
- // treats stream as optional (stream?.write / stream?.end).
- const stream = ctx?.hasStream ? await ctx.createStream() : undefined;
- try {
- let currentSessionId = sessionId;
- let toolCallCount = 0;
- const filesChanged = new Set<string>();
- const bashCommandsRun: string[] = [];
- let resultData: Record<string, unknown> = {};
- // Build CLI command
- const args: string[] = [
- '-p',
- '--output-format', 'stream-json',
- '--verbose',
- '--include-partial-messages',
- '--allow-dangerously-skip-permissions',
- '--dangerously-skip-permissions',
- '--allowedTools', tools.join(','),
- ];
- if (currentSessionId) {
- args.push('--resume', currentSessionId);
- }
- const maxBudget = process.env.CLAUDE_MAX_BUDGET_USD;
- if (maxBudget) {
- args.push('--max-budget-usd', maxBudget);
- }
- const model = requestModel || process.env.CLAUDE_MODEL;
- if (model) {
- args.push('--model', model);
- }
- args.push('--', prompt);
- // Unset CLAUDECODE to allow invocation from within a Claude Code session
- const env = { ...process.env, CLAUDECODE: '' };
- const proc = spawn('claude', args, {
- cwd: cwd ?? undefined,
- env,
- stdio: ['pipe', 'pipe', 'pipe'],
- });
- // Close stdin -- prompt is passed as a CLI argument
- proc.stdin.end();
- const rl = createInterface({ input: proc.stdout! });
- for await (const rawLine of rl) {
- // Cooperative cancellation: check at each stream event
- if (ctx?.isCancelled) {
- proc.kill();
- rl.close();
- await stream?.end();
- return cancelArtifact(
- currentSessionId, filesChanged, toolCallCount, bashCommandsRun,
- );
- }
- const line = rawLine.trim();
- if (!line) continue;
- let event: Record<string, unknown>;
- try {
- event = JSON.parse(line) as Record<string, unknown>;
- } catch {
- continue;
- }
- const etype = event.type as string | undefined;
- if (etype === 'system') {
- // First-turn: capture session_id from init event
- if (!currentSessionId && typeof event.session_id === 'string') {
- currentSessionId = event.session_id;
- }
- } else if (etype === 'stream_event') {
- // Token-level streaming deltas
- const inner = (event.event ?? {}) as Record<string, unknown>;
- const innerType = inner.type as string | undefined;
- if (innerType === 'content_block_delta') {
- const delta = (inner.delta ?? {}) as Record<string, unknown>;
- const deltaType = delta.type as string | undefined;
- if (deltaType === 'text_delta') {
- const text = delta.text as string | undefined;
- if (text && stream) {
- stream.write(text);
- }
- }
- // Skip thinking_delta, input_json_delta
- }
- } else if (etype === 'assistant') {
- // Complete message -- extract tool metadata
- const message = (event.message ?? {}) as Record<string, unknown>;
- const content = (message.content ?? []) as Record<string, unknown>[];
- for (const block of content) {
- const btype = block.type as string | undefined;
- if (btype === 'tool_use') {
- toolCallCount++;
- const name = (block.name ?? '') as string;
- const inp = (block.input ?? {}) as Record<string, unknown>;
- if (name === 'Write' || name === 'Edit') {
- const fp = inp.file_path as string | undefined;
- if (fp) {
- filesChanged.add(fp);
- }
- }
- if (name === 'Bash') {
- const cmdStr = (inp.command ?? '') as string;
- if (cmdStr) {
- bashCommandsRun.push(cmdStr);
- // Stream-based bash safety: kill subprocess if dangerous
- if (bashSafetyEnabled) {
- const matched = checkBashCommand(cmdStr);
- if (matched) {
- console.warn(
- `BLOCKED bash command: ${cmdStr.slice(0, 200)} (pattern: ${matched})`,
- );
- proc.kill();
- rl.close();
- await stream?.end();
- return errorArtifact(
- 'BashSafetyViolation',
- `Blocked dangerous bash command matching pattern ${JSON.stringify(matched)}`,
- { command: cmdStr.slice(0, 200), sessionId: currentSessionId },
- );
- }
- }
- }
- }
- }
- }
- } else if (etype === 'result') {
- resultData = event;
- if (typeof event.session_id === 'string') {
- currentSessionId = event.session_id;
- }
- }
- }
- // Wait for process to exit
- await new Promise<void>((res) => {
- proc.on('close', () => res());
- // If process already exited, resolve immediately
- if (proc.exitCode !== null) res();
- });
- // Final cancellation check after process exits
- if (ctx?.isCancelled) {
- await stream?.end();
- return cancelArtifact(
- currentSessionId, filesChanged, toolCallCount, bashCommandsRun,
- );
- }
- // Build response from the result event
- const fullText = (resultData.result ?? '') as string;
- const isError = (resultData.is_error ?? false) as boolean;
- const responsePayload: Record<string, unknown> = {
- ok: !isError,
- text: fullText,
- sessionId: currentSessionId,
- filesChanged: [...filesChanged].sort(),
- toolCallCount,
- bashCommandCount: bashCommandsRun.length,
- };
- // Include optional metadata fields only when available
- if (resultData.duration_ms != null) {
- responsePayload.durationMs = resultData.duration_ms;
- }
- if (resultData.num_turns != null) {
- responsePayload.numTurns = resultData.num_turns;
- }
- if (resultData.total_cost_usd != null) {
- responsePayload.totalCostUsd = resultData.total_cost_usd;
- }
- await stream?.end();
- return {
- artifacts: [{ data: JSON.stringify(responsePayload), mimeType: 'application/json' }],
- };
- } finally {
- // Safety net: always close the stream, even if the subprocess fails.
- // stream.end() is idempotent -- calling it after it's already ended is safe.
- if (stream) {
- try {
- await stream.end();
- } catch {
- console.warn('Failed to close stream');
- }
- }
- }
- }
- // ---------------------------------------------------------------------------
- // Main handler
- // ---------------------------------------------------------------------------
- /**
- * Handle an incoming task by running Claude Code and streaming output.
- */
- export default async function handler(
- task: StartTaskMessage,
- ctx?: TaskContext,
- ): Promise<HandlerResult> {
- // Check for API key early
- if (!process.env.ANTHROPIC_API_KEY) {
- return errorArtifact(
- 'ConfigurationError',
- 'ANTHROPIC_API_KEY environment variable is not set. ' +
- 'Set it to your Anthropic API key from https://console.anthropic.com/',
- );
- }
- // Check for claude CLI on PATH
- try {
- whichSync.sync('claude');
- } catch {
- return errorArtifact(
- 'ConfigurationError',
- 'claude CLI not found on PATH. ' +
- 'Install it with: npm install -g @anthropic/claude-code',
- );
- }
- const { prompt, sessionId, tools: requestTools, cwd: requestCwd, disableBashSafety, model: requestModel } =
- extractInput(task.requestParts ?? []);
- if (!prompt) {
- return errorArtifact(
- 'InputError',
- 'Missing text input',
- { example: { kind: 'input_text', text: 'Write a hello world in Python' } },
- );
- }
- // Resolve tools
- const tools = resolveTools(requestTools);
- // Resolve and validate cwd
- let cwd: string | null;
- try {
- cwd = resolveCwd(requestCwd);
- } catch (err) {
- return errorArtifact('SandboxError', (err as Error).message);
- }
- // Determine bash safety setting
- const envBashSafety = (process.env.CLAUDE_BASH_SAFETY ?? 'on').trim().toLowerCase();
- const bashSafetyEnabled = envBashSafety !== 'off' && !disableBashSafety;
- try {
- return await runClaudeSession(
- prompt, sessionId, ctx, tools, cwd, bashSafetyEnabled, requestModel,
- );
- } catch (err) {
- console.error(`Claude Code session failed: session_id=${sessionId}`, err);
- return errorArtifact(
- (err as Error).constructor?.name ?? 'Error',
- (err as Error).message ?? String(err),
- { sessionId },
- );
- }
- }
examples/python/claude-code/handler.py · Bundled script · 596 lines · 2 findings marked
- """
- Claude Code handler.
- Runs a Claude Code session for each task by invoking the ``claude`` CLI as a
- subprocess with ``--output-format stream-json --include-partial-messages``.
- Token-level text deltas are streamed to the consumer in real time via the
- Blocks streaming buffer. A single JSON artifact is returned with the
- complete text, session metadata, and tool-usage statistics.
- Supports multi-turn conversations via sessionId. If the consumer includes
- a sessionId (obtained from the previous task's artifact) the handler
- resumes that Claude Code session using the CLI's ``--resume`` flag.
- On the first turn, ``sessionId`` is omitted and the CLI generates one;
- it is returned in the response artifact.
- Input format (first turn):
- { "kind": "input_text", "text": "Fix the bug in auth.ts" }
- Input format (follow-up turn):
- { "kind": "input_text", "text": "Now add tests for that fix", "sessionId": "<id>" }
- Input format (with tools and cwd):
- {
- "kind": "input_text",
- "text": "Fix the bug",
- "tools": ["Read", "Grep", "Glob"],
- "cwd": "/path/to/repo",
- "disableBashSafety": false
- }
- Environment variables for configuration:
- CLAUDE_ALLOWED_TOOLS -- comma-separated tool allowlist (overrides default).
- When set, request_parts tools are intersected with
- this list (request tools can only narrow, not expand).
- CLAUDE_DISALLOWED_TOOLS -- comma-separated tool blocklist (applied after allowlist)
- CLAUDE_ALLOWED_PATHS -- comma-separated allowed working directory paths
- CLAUDE_BASH_SAFETY -- "on" (default) or "off" to toggle bash safety.
- When on, dangerous commands detected in the stream
- cause the subprocess to be killed.
- CLAUDE_BASH_BLOCKLIST -- comma-separated additional blocked bash patterns
- CLAUDE_MAX_BUDGET_USD -- max dollar amount per task (passed to CLI)
- CLAUDE_MODEL -- model to use (e.g. "sonnet", "opus")
- """
- from __future__ import annotations
- import asyncio
- import json
- import logging
- import os
- import re
- import shutil
- from pathlib import Path
- from typing import Any, Dict, List, Optional, Tuple
- from blocks_network.types import StartTaskMessage, TaskContext
- logger = logging.getLogger(__name__)
- # ---------------------------------------------------------------------------
- # Tool configuration
- # ---------------------------------------------------------------------------
- # The default safe set -- filesystem reads plus controlled writes
- DEFAULT_TOOLS = ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]
- # Extended set that consumers can opt into by passing tools in request_parts
- EXTENDED_TOOLS = DEFAULT_TOOLS + [
- "WebSearch", "TodoRead", "TodoWrite", "NotebookRead", "NotebookEdit",
- ]
- # ---------------------------------------------------------------------------
- # Bash safety configuration
- # ---------------------------------------------------------------------------
- # Patterns that are always blocked unless bash safety is disabled.
- # Each entry is a compiled regex matched against the full command string.
- _DEFAULT_BASH_BLOCKLIST_PATTERNS = [
- r"rm\s+-[^\s]*r[^\s]*f[^\s]*\s+/\s*$", # rm -rf /
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 79 on GitHub
- r"rm\s+-[^\s]*f[^\s]*r[^\s]*\s+/\s*$", # rm -fr /
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 80 on GitHub
- r"rm\s+-rf\s+/(?:usr|etc|var|home|boot|sys|proc|dev)\b", # rm -rf system dirs
- r"\bsudo\b", # any sudo usage
- r"\bmkfs\b", # format filesystem
- r"\bdd\s+.*of=/dev/", # dd to devices
- r">\s*/dev/sd[a-z]", # redirect to block devices
- r"\bshutdown\b", # shutdown
- r"\breboot\b", # reboot
- r"\binit\s+[0-6]\b", # init runlevel changes
- r"chmod\s+-R\s+777\s+/", # recursive chmod 777 on root
- r":\(\)\s*\{\s*:\|\s*:\s*&\s*\}\s*;", # fork bomb
- r"\bkill\s+-9\s+-1\b", # kill all processes
- r"\bcurl\b.*\|\s*\bbash\b", # curl pipe to bash
- r"\bwget\b.*\|\s*\bbash\b", # wget pipe to bash
- ]
- def _compile_bash_blocklist() -> List[re.Pattern]:
- """Compile the default blocklist plus any from the environment."""
- patterns = list(_DEFAULT_BASH_BLOCKLIST_PATTERNS)
- env_extra = os.environ.get("CLAUDE_BASH_BLOCKLIST", "").strip()
- if env_extra:
- patterns.extend(p.strip() for p in env_extra.split(",") if p.strip())
- compiled = []
- for p in patterns:
- try:
- compiled.append(re.compile(p, re.IGNORECASE))
- except re.error as exc:
- logger.warning("Invalid bash blocklist pattern %r: %s", p, exc)
- return compiled
- _bash_blocklist: Optional[List[re.Pattern]] = None
- def _get_bash_blocklist() -> List[re.Pattern]:
- """Lazy-init and cache the compiled blocklist."""
- global _bash_blocklist
- if _bash_blocklist is None:
- _bash_blocklist = _compile_bash_blocklist()
- return _bash_blocklist
- def _check_bash_command(command: str) -> Optional[str]:
- """Check a bash command against the blocklist.
- Returns the matched pattern string if blocked, or None if allowed.
- """
- for pattern in _get_bash_blocklist():
- if pattern.search(command):
- return pattern.pattern
- return None
- # ---------------------------------------------------------------------------
- # Tool configuration helpers
- # ---------------------------------------------------------------------------
- def _resolve_tools(
- request_tools: Optional[List[str]],
- ) -> List[str]:
- """Resolve the final tool list from request_parts and environment.
- Priority:
- 1. Determine the base allowlist from ``CLAUDE_ALLOWED_TOOLS`` env var
- or ``DEFAULT_TOOLS``.
- 2. If ``request_tools`` is provided AND an env allowlist is set, the
- result is the **intersection** (request tools can only narrow the
- env allowlist, not expand it). If no env allowlist is set, request
- tools are used as-is (for development flexibility).
- 3. ``CLAUDE_DISALLOWED_TOOLS`` env var entries are removed last.
- A warning is logged for any tool name not in ``DEFAULT_TOOLS + EXTENDED_TOOLS``.
- """
- # Step 1: Determine the base allowlist from environment (or default)
- env_allowed = os.environ.get("CLAUDE_ALLOWED_TOOLS", "").strip()
- if env_allowed:
- base_tools = [t.strip() for t in env_allowed.split(",") if t.strip()]
- else:
- base_tools = list(DEFAULT_TOOLS)
- # Step 2: Apply request_tools
- if request_tools:
- if env_allowed:
- # Intersection: request can only narrow the env allowlist
- base_set = set(base_tools)
- tools = [t for t in request_tools if t in base_set]
- else:
- # No env allowlist -- use request tools as-is (dev flexibility)
- tools = list(request_tools)
- else:
- tools = base_tools
- # Step 3: Apply disallowed list from environment
- env_disallowed = os.environ.get("CLAUDE_DISALLOWED_TOOLS", "").strip()
- if env_disallowed:
- blocklist = {t.strip() for t in env_disallowed.split(",") if t.strip()}
- tools = [t for t in tools if t not in blocklist]
- # Step 4: Warn about unrecognized tool names
- known_tools = set(EXTENDED_TOOLS) # EXTENDED_TOOLS is a superset of DEFAULT_TOOLS
- for t in tools:
- if t not in known_tools:
- logger.warning(
- "Unrecognized tool name %r -- not in DEFAULT_TOOLS or EXTENDED_TOOLS. "
- "It may be valid in a newer CLI version.",
- t,
- )
- return tools
- # ---------------------------------------------------------------------------
- # CWD sandboxing
- # ---------------------------------------------------------------------------
- def _resolve_cwd(request_cwd: Optional[str]) -> Optional[str]:
- """Validate and resolve the working directory.
- Returns the resolved absolute path, or ``None`` to use the process default.
- Raises ``ValueError`` if the path is not allowed or does not exist.
- """
- if not request_cwd:
- return None
- resolved = str(Path(request_cwd).resolve())
- # Check existence
- if not Path(resolved).is_dir():
- raise ValueError(
- f"Working directory does not exist: {resolved}"
- )
- # Check against allowed paths (if configured)
- env_allowed = os.environ.get("CLAUDE_ALLOWED_PATHS", "").strip()
- if env_allowed:
- allowed = [str(Path(p.strip()).resolve()) for p in env_allowed.split(",") if p.strip()]
- if not any(resolved == a or resolved.startswith(a + os.sep) for a in allowed):
- raise ValueError(
- f"Working directory {resolved} is not within allowed paths: {allowed}"
- )
- return resolved
- # ---------------------------------------------------------------------------
- # Error artifact helpers
- # ---------------------------------------------------------------------------
- def _error_artifact(error_type: str, message: str, details: Optional[Dict] = None) -> Dict[str, Any]:
- """Build a structured error artifact."""
- payload: Dict[str, Any] = {
- "ok": False,
- "errorType": error_type,
- "error": message,
- }
- if details:
- payload["details"] = details
- return {
- "artifacts": [{"data": json.dumps(payload), "mimeType": "application/json"}],
- }
- def _cancel_artifact(
- session_id: Optional[str],
- files_changed: set,
- tool_call_count: int,
- bash_commands_run: List[str],
- ) -> Dict[str, Any]:
- """Build a cancel artifact with whatever metadata we have so far."""
- payload: Dict[str, Any] = {
- "ok": False,
- "text": "Task was cancelled.",
- "sessionId": session_id,
- "filesChanged": sorted(files_changed),
- "toolCallCount": tool_call_count,
- "bashCommandCount": len(bash_commands_run),
- "cancelled": True,
- }
- return {
- "artifacts": [{"data": json.dumps(payload), "mimeType": "application/json"}],
- }
- # ---------------------------------------------------------------------------
- # Input extraction
- # ---------------------------------------------------------------------------
- def _extract_input(
- parts: List[Any],
- ) -> Tuple[Optional[str], Optional[str], Optional[List[str]], Optional[str], bool, Optional[str]]:
- """Extract prompt text, sessionId, tools, cwd, disableBashSafety, and model from request parts.
- Returns:
- (prompt, session_id, tools, cwd, disable_bash_safety, model)
- """
- prompt: Optional[str] = None
- session_id: Optional[str] = None
- tools: Optional[List[str]] = None
- cwd: Optional[str] = None
- disable_bash_safety = False
- model: Optional[str] = None
- for part in parts:
- if isinstance(part, str):
- prompt = part
- else:
- content = _parse_part_content(part)
- if isinstance(content.get("text"), str):
- prompt = content["text"]
- if isinstance(content.get("sessionId"), str):
- session_id = content["sessionId"]
- if isinstance(content.get("tools"), list):
- tools = [str(t) for t in content["tools"] if isinstance(t, str)]
- if isinstance(content.get("cwd"), str):
- cwd = content["cwd"]
- if content.get("disableBashSafety") is True:
- disable_bash_safety = True
- if isinstance(content.get("model"), str):
- model = content["model"]
- return prompt, session_id, tools, cwd, disable_bash_safety, model
- def _parse_part_content(part: Any) -> Dict[str, Any]:
- """Extract structured content from a RequestPart or raw dict.
- The frontend serializes structured content into the ``text`` field as
- JSON. This helper parses it back into a dict.
- """
- text = getattr(part, "text", None) if not isinstance(part, dict) else part.get("text")
- if isinstance(text, str):
- try:
- parsed = json.loads(text)
- if isinstance(parsed, dict):
- return parsed
- except (json.JSONDecodeError, ValueError):
- pass
- return {"text": text}
- if hasattr(part, "extra") and isinstance(part.extra, dict):
- return part.extra
- if isinstance(part, dict):
- return part
- return {}
- # ---------------------------------------------------------------------------
- # Main handler
- # ---------------------------------------------------------------------------
- def handler(task: StartTaskMessage, ctx: Optional[TaskContext] = None) -> Dict[str, Any]:
- """Handle an incoming task by running Claude Code and streaming output."""
- # Check for API key early
- if not os.environ.get("ANTHROPIC_API_KEY"):
- return _error_artifact(
- "ConfigurationError",
- "ANTHROPIC_API_KEY environment variable is not set. "
- "Set it to your Anthropic API key from https://console.anthropic.com/",
- )
- # Check for claude CLI on PATH
- if not shutil.which("claude"):
- return _error_artifact(
- "ConfigurationError",
- "claude CLI not found on PATH. "
- "Install it with: npm install -g @anthropic/claude-code",
- )
- prompt, session_id, request_tools, request_cwd, disable_bash_safety, request_model = _extract_input(
- task.request_parts or []
- )
- if not prompt:
- return _error_artifact(
- "InputError",
- "Missing text input",
- {"example": {"kind": "input_text", "text": "Write a hello world in Python"}},
- )
- # Resolve tools
- tools = _resolve_tools(request_tools)
- # Resolve and validate cwd
- try:
- cwd = _resolve_cwd(request_cwd)
- except ValueError as exc:
- return _error_artifact("SandboxError", str(exc))
- # Determine bash safety setting
- env_bash_safety = os.environ.get("CLAUDE_BASH_SAFETY", "on").strip().lower()
- bash_safety_enabled = (env_bash_safety != "off") and (not disable_bash_safety)
- try:
- result = asyncio.run(
- _run_claude_session(prompt, session_id, ctx, tools, cwd, bash_safety_enabled, request_model)
- )
- return result
- except asyncio.CancelledError:
- logger.warning("Task cancelled: session_id=%s", session_id)
- return _error_artifact(
- "CancelledError",
- "Task was cancelled",
- {"sessionId": session_id},
- )
- except KeyboardInterrupt:
- logger.warning("Task interrupted: session_id=%s", session_id)
- return _error_artifact(
- "InterruptedError",
- "Task was interrupted",
- {"sessionId": session_id},
- )
- except Exception as exc:
- logger.exception("Claude Code session failed: session_id=%s", session_id)
- return _error_artifact(
- type(exc).__name__,
- str(exc),
- {"sessionId": session_id},
- )
- def _is_cancelled(ctx: Optional[TaskContext]) -> bool:
- """Check if the task has been cancelled via cooperative cancellation."""
- return ctx is not None and ctx.is_cancelled
- async def _run_claude_session(
- prompt: str,
- session_id: Optional[str],
- ctx: Optional[TaskContext],
- tools: List[str],
- cwd: Optional[str],
- bash_safety_enabled: bool,
- request_model: Optional[str] = None,
- ) -> Dict[str, Any]:
- """Run Claude Code via CLI subprocess and stream output to Blocks.
- Invokes ``claude -p --output-format stream-json --include-partial-messages``
- and reads newline-delimited JSON events from stdout. Text deltas
- (``content_block_delta`` with ``text_delta``) are written to the Blocks
- stream for token-level progressive output.
- Args:
- prompt: The user prompt text.
- session_id: Session ID from a previous turn (for resumption), or None.
- ctx: Blocks task context for streaming.
- tools: Resolved list of allowed tool names.
- cwd: Working directory, or None for process default.
- bash_safety_enabled: Whether to monitor for dangerous bash commands.
- request_model: Model from request_parts (overrides CLAUDE_MODEL env var).
- """
- # Stream only when negotiated (request streaming is consumer
- # opt-in); otherwise create_stream() would raise. The code below
- # already treats stream as optional.
- stream = ctx.create_stream() if ctx and ctx.has_stream else None
- try:
- tool_call_count = 0
- files_changed: set[str] = set()
- bash_commands_run: List[str] = []
- result_data: Dict[str, Any] = {}
- # Build CLI command
- cmd: List[str] = [
- "claude", "-p",
- "--output-format", "stream-json",
- "--verbose",
- "--include-partial-messages",
- "--allow-dangerously-skip-permissions",
- "--dangerously-skip-permissions",
- "--allowedTools", ",".join(tools),
- ]
- if session_id:
- cmd.extend(["--resume", session_id])
- max_budget = os.environ.get("CLAUDE_MAX_BUDGET_USD")
- if max_budget:
- cmd.extend(["--max-budget-usd", max_budget])
- model = request_model or os.environ.get("CLAUDE_MODEL")
- if model:
- cmd.extend(["--model", model])
- cmd.extend(["--", prompt])
- # Unset CLAUDECODE to allow invocation from within a Claude Code session
- env = {**os.environ, "CLAUDECODE": ""}
- # Claude CLI can emit very large JSON lines (e.g. assistant messages
- # with tool results or long code). The default asyncio StreamReader
- # limit is 64 KB which is too small. Use 16 MB.
- proc = await asyncio.create_subprocess_exec(
- *cmd,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- limit=16 * 1024 * 1024,
- cwd=cwd,
- env=env,
- )
- async for raw_line in proc.stdout:
- # Cooperative cancellation: check at each stream event
- if _is_cancelled(ctx):
- logger.info("Task cancelled, killing subprocess: session_id=%s", session_id)
- proc.kill()
- await proc.wait()
- return _cancel_artifact(
- session_id, files_changed, tool_call_count, bash_commands_run,
- )
- line = raw_line.strip()
- if not line:
- continue
- try:
- event = json.loads(line)
- except json.JSONDecodeError:
- continue
- etype = event.get("type")
- if etype == "system":
- # First-turn: capture session_id from init event
- if not session_id:
- session_id = event.get("session_id")
- elif etype == "stream_event":
- # Token-level streaming deltas
- inner = event.get("event", {})
- inner_type = inner.get("type")
- if inner_type == "content_block_delta":
- delta = inner.get("delta", {})
- delta_type = delta.get("type")
- if delta_type == "text_delta":
- text = delta.get("text", "")
- if text and stream:
- stream.write(text)
- # Skip thinking_delta, input_json_delta
- elif etype == "assistant":
- # Complete message — extract tool metadata
- content = (event.get("message") or {}).get("content") or []
- for block in content:
- btype = block.get("type")
- if btype == "tool_use":
- tool_call_count += 1
- name = block.get("name", "")
- inp = block.get("input") or {}
- if name in ("Write", "Edit"):
- fp = inp.get("file_path")
- if fp:
- files_changed.add(fp)
- if name == "Bash":
- cmd_str = inp.get("command", "")
- if cmd_str:
- bash_commands_run.append(cmd_str)
- logger.debug("Bash tool call #%d: %s", len(bash_commands_run), cmd_str[:200])
- # Stream-based bash safety: kill subprocess if dangerous
- if bash_safety_enabled:
- matched = _check_bash_command(cmd_str)
- if matched:
- logger.warning("BLOCKED bash command: %s (pattern: %s)", cmd_str[:200], matched)
- proc.kill()
- return _error_artifact(
- "BashSafetyViolation",
- f"Blocked dangerous bash command matching pattern {matched!r}",
- {"command": cmd_str[:200], "sessionId": session_id},
- )
- elif etype == "result":
- result_data = event
- session_id = event.get("session_id", session_id)
- await proc.wait()
- # Final cancellation check after process exits
- if _is_cancelled(ctx):
- return _cancel_artifact(
- session_id, files_changed, tool_call_count, bash_commands_run,
- )
- # Build response from the result event
- full_text = result_data.get("result", "")
- is_error = result_data.get("is_error", False)
- response_payload: Dict[str, Any] = {
- "ok": not is_error,
- "text": full_text,
- "sessionId": session_id,
- "filesChanged": sorted(files_changed),
- "toolCallCount": tool_call_count,
- "bashCommandCount": len(bash_commands_run),
- }
- # Include optional metadata fields only when available
- if result_data.get("duration_ms") is not None:
- response_payload["durationMs"] = result_data["duration_ms"]
- if result_data.get("num_turns") is not None:
- response_payload["numTurns"] = result_data["num_turns"]
- if result_data.get("total_cost_usd") is not None:
- response_payload["totalCostUsd"] = result_data["total_cost_usd"]
- return {
- "artifacts": [{"data": json.dumps(response_payload), "mimeType": "application/json"}],
- }
- finally:
- # Always close the stream, even if the subprocess fails
- if stream:
- try:
- stream.end()
- except Exception:
- logger.warning("Failed to close stream", exc_info=True)
Version history
v0.4.110/23/2026
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.