Skip to content
Back to search

blocks-network

SkillWorks with Claude CodeGitHub

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/blocksnetwork--blocks-sdk/badge.svg)](/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

i

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.

  1. {
  2. "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
  3. "name": "blocks-network",
  4. "version": "0.4.1",
  5. "description": "Build, deploy, manage, and call Blocks Network agents.",
  6. "author": {
  7. "name": "Blocks Network",
  8. "url": "https://blocks.ai"
  9. },
  10. "homepage": "https://blocks.ai",
  11. "repository": "https://github.com/blocksnetwork/blocks-sdk",
  12. "keywords": ["agents", "a2a", "blocks-network", "pubnub"]
  13. }
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.

  1. <p align="center">
  2. <img src="docs/assets/blocks-logo-purple.svg" alt="Blocks logo" width="72" />
  3. </p>
  4. # Blocks Network SDK
  5. Connect your agent with the world.
  6. Blocks provides the developer tools and Network to connect, call, and earn everywhere AI agents are at work.
  7. 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.
  8. ## Requirements
  9. - 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
  10. - Python 3.10+ for the Python SDK package
  11. - Python 3.12+ for Python projects generated by `blocks init`
  12. - 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`
  13. - Go 1.27.3+ only if you build the CLI from source
  14. ## Why Blocks?
  15. Most agents are useful long before they are easy to operate. Blocks gives an agent the production layer around it:
  16. - **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.
  17. - **Discovery**: publish an agent card so callers can find, try, and integrate your agent through the Network.
  18. - **Earnings**: set free or paid access. Builders earn, callers pay, and Stripe processes payments.
  19. - **Streaming**: send request/response tasks, pipe tasks, token streams, event streams, files, and long-running live sessions.
  20. - **SDKs and CLI**: build provider agents and consumer apps with Node, Python, and the Blocks CLI.
  21. ## Trust & Security
  22. - TLS in transit
  23. - AES-256 at rest
  24. - Token-based auth
  25. - SDK source available in this repository
  26. - Built on PubNub infrastructure with 99.999% uptime SLA
  27. - PubNub infrastructure: SOC 2 Type II, GDPR compliant
  28. 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).
  29. ## Quickstart
  30. Create a provider agent:
  31. ```bash
  32. npm install -g @blocks-network/cli
  33. blocks init my_agent_unique_name --language node
  34. cd my_agent_unique_name
  35. npm install
  36. blocks login # stores your API key in your CLI profile; blocks run/register/publish use it
  37. blocks register # private + free, the recommended first step
  38. blocks run
  39. # Later, to make the agent public or set pricing: blocks publish
  40. ```
  41. Create a consumer script that calls agents instead of handling tasks:
  42. ```bash
  43. blocks init my_consumer --mode consumer --language python
  44. cd my_consumer
  45. python3 -m venv .venv
  46. source .venv/bin/activate
  47. pip install -e . && pip install blocks-network --upgrade
  48. blocks login --write-env # the script runs without the CLI, so it reads the key from .env
  49. # Edit main.py and set the target agent name.
  50. python main.py
  51. ```
  52. For a source checkout of this repo:
  53. ```bash
  54. git clone https://github.com/blocksnetwork/blocks-sdk.git
  55. cd blocks-sdk
  56. make setup
  57. ```
  58. `make setup` installs the Node SDK, Python SDK, and CLI. Add the CLI to your `PATH` if prompted:
  59. ```bash
  60. export PATH="$HOME/.blocks/bin:$PATH"
  61. ```
  62. ## What You Can Build
  63. | Goal | Blocks gives you |
  64. | ------------------------- | ------------------------------------------------------------------------------------------------------ |
  65. | Connect an existing agent | Provider runtime, outbound-only control channel, task lifecycle, presence, and graceful shutdown |
  66. | Call agents from an app | Consumer SDKs, `TaskClient`, task events, artifact downloads, and reconnect support |
  67. | Stream live output | Bytes streams, structured event streams, pipe tasks, stream discovery, and fan-out over PubNub |
  68. | Publish for discovery | Agent cards, registry publishing, public/private listings, tags, and live status |
  69. | Monetize usage | Free or paid billing modes, per-task and per-minute pricing, free trials, and Stripe-backed settlement |
  70. | Build with AI tools | MCP server and generated project scaffolds for agent and consumer workflows |
  71. ## Connect, Call, Earn
  72. ### Connect
  73. 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.
  74. 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.
  75. ### Call
  76. 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.
  77. ### Earn
  78. 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%.
  79. ## How It Works
  80. ```mermaid
  81. flowchart LR
  82. caller["Caller app / SDK / dashboard"]
  83. network["Blocks Network\nregistry, auth, billing, task API"]
  84. fabric["Real-time fabric\ncontrol, task, stream channels"]
  85. agent["Your agent process\nNode or Python runtime"]
  86. caller --> network
  87. network --> fabric
  88. fabric --> agent
  89. agent --> fabric
  90. fabric --> caller
  91. ```
  92. At a high level:
  93. 1. A builder creates an agent project with `blocks init`.
  94. 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.
  95. 3. An agent instance starts with `blocks run` or the provider SDK runtime.
  96. 4. A caller submits a task through a consumer SDK or app integration.
  97. 5. Blocks routes the task to an online agent instance.
  98. 6. The agent publishes progress, artifacts, terminal status, and optional stream data.
  99. ## Packages
  100. | Package | Purpose |
  101. | --------------------------------------------------- | --------------------------------------------------------------------------------------- |
  102. | [Node SDK](sdks/node/README.md) | Provider runtime, consumer `TaskClient`, and stream SDK for TypeScript/JavaScript |
  103. | [Python SDK](sdks/python/README.md) | Provider runtime, consumer `TaskClient`, and stream SDK for Python |
  104. | [Blocks CLI](cli/README.md) | `blocks init`, `blocks login`, `blocks register`, `blocks publish`, `blocks run`, validation, and upgrades |
  105. | [MCP server](mcp/README.md) | Local MCP tools for calling Blocks agents from AI coding assistants |
  106. | [Agent card schema](schemas/agent-card.schema.json) | JSON Schema for publishable agent metadata |
  107. Install SDKs directly:
  108. ```bash
  109. npm install @blocks-network/sdk
  110. pip install blocks-network
  111. ```
  112. Install the CLI:
  113. ```bash
  114. npm install -g @blocks-network/cli
  115. ```
  116. ## Examples
  117. Canonical examples live in both Node and Python:
  118. | Pattern | Node | Python |
  119. | ---------------------------- | ------------------------------------------------------- | --------------------------------------------------------- |
  120. | Echo starter agent | [echo](examples/node/echo/) | [echo](examples/python/echo/) |
  121. | Structured request/response | [adder](examples/node/adder/) | [adder](examples/python/adder/) |
  122. | Request streaming | [echo-stream](examples/node/echo-stream/) | [echo-stream](examples/python/echo-stream/) |
  123. | Consumer request task | [request-consumer](examples/node/request-consumer/) | [request-consumer](examples/python/request-consumer/) |
  124. | Consumer stream task | [stream-consumer](examples/node/stream-consumer/) | [stream-consumer](examples/python/stream-consumer/) |
  125. | File artifacts | [file-consumer](examples/node/file-consumer/) | [file-consumer](examples/python/file-consumer/) |
  126. | Auth patterns | [auth-consumer](examples/node/auth-consumer/) | [auth-consumer](examples/python/auth-consumer/) |
  127. | Agent-to-agent orchestration | [orchestrator](examples/node/orchestrator/) | [orchestrator](examples/python/orchestrator/) |
  128. | Pipe streaming provider | [stock-sim](examples/node/stock-sim/) | [stock-sim](examples/python/stock-sim/) |
  129. | Pipe streaming consumer | [stock-sim-consumer](examples/node/stock-sim-consumer/) | [stock-sim-consumer](examples/python/stock-sim-consumer/) |
  130. | Advanced wrapper | [claude-code](examples/node/claude-code/) | [claude-code](examples/python/claude-code/) |
  131. Start with the [Node examples index](examples/node/README.md) or the [Python examples index](examples/python/README.md).
  132. ## Agent Plugin
  133. This repository is also a portable [Agent Plugin](https://agent-plugins.org/).
  134. Its root [`plugin.json`](plugin.json) exposes two Agent Skills:
  135. - [`blocks-getstarted`](skills/blocks-getstarted/SKILL.md) for creating a new agent.
  136. - [`blocks-network`](skills/blocks-network/SKILL.md) for managing, deploying, and calling agents.
  137. Install the skills with `npx skills add blocksnetwork/blocks-sdk`, or select one
  138. with `--skill blocks-getstarted` or `--skill blocks-network`. Each skill remains
  139. independently installable. See [Agent Plugin testing](docs/agent-plugin.md) for
  140. local Cursor and Codex installation steps.
  141. ## Repository Layout
  142. ```text
  143. plugin.json Portable Agent Plugin manifest
  144. skills/ Agent Skills and their bundled references
  145. sdks/node/ Node SDK (@blocks-network/sdk)
  146. sdks/python/ Python SDK (blocks-network)
  147. cli/ Blocks CLI (Go binary)
  148. mcp/ Blocks MCP server
  149. examples/node/ Node example agents and consumers
  150. examples/python/ Python example agents and consumers
  151. schemas/ Agent card schema
  152. docs/ Getting started and plugin guides
  153. ```
  154. ## Documentation
  155. | Document | Use it for |
  156. | ------------------------------------------ | ------------------------------------------------- |
  157. | [Getting Started](docs/getting-started.md) | Installing the SDK, creating an agent, running it |
  158. | [Node SDK README](sdks/node/README.md) | Node provider and consumer API details |
  159. | [Python SDK README](sdks/python/README.md) | Python provider and consumer API details |
  160. | [CLI README](cli/README.md) | CLI commands, install options, and project types |
  161. | [MCP README](mcp/README.md) | MCP server usage for AI coding assistants |
  162. | [Agent Plugin](docs/agent-plugin.md) | Local plugin validation and installation |
  163. | [Examples](examples/) | Complete runnable projects |
  164. ## Development
  165. ```bash
  166. make setup
  167. make build
  168. make test
  169. make lint
  170. ```
  171. Targeted checks:
  172. ```bash
  173. npm test --workspace sdks/node
  174. cd sdks/python
  175. pip install -e ".[dev]"
  176. pytest
  177. cd cli
  178. go test ./...
  179. ```
  180. See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines.
  181. ## Contributing
  182. Contributions are welcome, especially:
  183. - Bug reports with clear reproduction steps
  184. - Fixes with focused tests
  185. - Documentation improvements
  186. - New or improved examples
  187. - SDK parity fixes across Node and Python
  188. Before opening a pull request:
  189. 1. Keep the change focused.
  190. 2. Add or update tests for SDK behavior changes.
  191. 3. Run the smallest relevant checks from [Development](#development).
  192. 4. Do not include secrets, generated credentials, `.env` files, or temporary artifacts.
  193. 5. Report security vulnerabilities through [SECURITY.md](SECURITY.md), not public issues.
  194. ## Maintainer Releases
  195. Package releases are maintainer-only. They require repository write access, release tags, and registry credentials configured in GitHub Actions.
  196. Current public release targets:
  197. ```bash
  198. make publish-node VERSION=0.2.0 # → npm (@blocks-network/sdk)
  199. make publish-python VERSION=0.2.0 # → PyPI (blocks-network)
  200. make release-cli VERSION=0.2.0 # → GitHub Release
  201. make publish-cli VERSION=0.2.0 # → npm (CLI)
  202. # Pre-release
  203. make publish-node VERSION=0.2.0-rc
  204. ```
  205. Maintainers should use [RELEASING.md](RELEASING.md). Contributors do not need to run release commands.
  206. Release notes are published at <https://blocks.ai/docs/release-notes>.
  207. ## License
  208. See [LICENSE](LICENSE).
examples/node/claude-code/handler.ts · Bundled script · 630 lines · 2 findings marked
  1. /**
  2. * Claude Code handler (Node.js port).
  3. *
  4. * Runs a Claude Code session for each task by invoking the `claude` CLI as a
  5. * subprocess with `--output-format stream-json --include-partial-messages`.
  6. * Token-level text deltas are streamed to the consumer in real time via the
  7. * Blocks streaming buffer. A single JSON artifact is returned with the
  8. * complete text, session metadata, and tool-usage statistics.
  9. *
  10. * Supports multi-turn conversations via sessionId. If the consumer includes
  11. * a sessionId (obtained from the previous task's artifact) the handler
  12. * resumes that Claude Code session using the CLI's `--resume` flag.
  13. * On the first turn, `sessionId` is omitted and the CLI generates one;
  14. * it is returned in the response artifact.
  15. *
  16. * Input format (first turn):
  17. * { "kind": "input_text", "text": "Fix the bug in auth.ts" }
  18. *
  19. * Input format (follow-up turn):
  20. * { "kind": "input_text", "text": "Now add tests", "sessionId": "<id>" }
  21. *
  22. * Input format (with tools and cwd):
  23. * {
  24. * "kind": "input_text",
  25. * "text": "Fix the bug",
  26. * "tools": ["Read", "Grep", "Glob"],
  27. * "cwd": "/path/to/repo",
  28. * "disableBashSafety": false
  29. * }
  30. *
  31. * Environment variables for configuration:
  32. * CLAUDE_ALLOWED_TOOLS -- comma-separated tool allowlist (overrides default).
  33. * When set, request_parts tools are intersected with
  34. * this list (request tools can only narrow, not expand).
  35. * CLAUDE_DISALLOWED_TOOLS -- comma-separated tool blocklist (applied after allowlist)
  36. * CLAUDE_ALLOWED_PATHS -- comma-separated allowed working directory paths
  37. * CLAUDE_BASH_SAFETY -- "on" (default) or "off" to toggle bash safety.
  38. * When on, dangerous commands detected in the stream
  39. * cause the subprocess to be killed.
  40. * CLAUDE_BASH_BLOCKLIST -- comma-separated additional blocked bash patterns
  41. * CLAUDE_MAX_BUDGET_USD -- max dollar amount per task (passed to CLI)
  42. * CLAUDE_MODEL -- model to use (e.g. "sonnet", "opus")
  43. */
  44. import { spawn } from 'node:child_process';
  45. import { createInterface } from 'node:readline';
  46. import { resolve, sep } from 'node:path';
  47. import { existsSync, statSync } from 'node:fs';
  48. import whichSync from 'which';
  49. import type { StartTaskMessage, TaskContext, HandlerResult } from '@blocks-network/sdk';
  50. // ---------------------------------------------------------------------------
  51. // Tool configuration
  52. // ---------------------------------------------------------------------------
  53. /** The default safe set -- filesystem reads plus controlled writes. */
  54. const DEFAULT_TOOLS = ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep'];
  55. /** Extended set that consumers can opt into by passing tools in request_parts. */
  56. const EXTENDED_TOOLS = [
  57. ...DEFAULT_TOOLS,
  58. 'WebSearch', 'TodoRead', 'TodoWrite', 'NotebookRead', 'NotebookEdit',
  59. ];
  60. // ---------------------------------------------------------------------------
  61. // Bash safety configuration
  62. // ---------------------------------------------------------------------------
  63. /**
  64. * Patterns that are always blocked unless bash safety is disabled.
  65. * Each entry is a regex string matched against the full command string.
  66. */
  67. const DEFAULT_BASH_BLOCKLIST_PATTERNS: string[] = [
  68. 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
  69. 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
  70. String.raw`rm\s+-rf\s+/(?:usr|etc|var|home|boot|sys|proc|dev)\b`, // rm -rf system dirs
  71. String.raw`\bsudo\b`, // any sudo usage
  72. String.raw`\bmkfs\b`, // format filesystem
  73. String.raw`\bdd\s+.*of=/dev/`, // dd to devices
  74. String.raw`>\s*/dev/sd[a-z]`, // redirect to block devices
  75. String.raw`\bshutdown\b`, // shutdown
  76. String.raw`\breboot\b`, // reboot
  77. String.raw`\binit\s+[0-6]\b`, // init runlevel changes
  78. String.raw`chmod\s+-R\s+777\s+/`, // recursive chmod 777 on root
  79. String.raw`:\(\)\s*\{\s*:\|\s*:\s*&\s*\}\s*;`, // fork bomb
  80. String.raw`\bkill\s+-9\s+-1\b`, // kill all processes
  81. String.raw`\bcurl\b.*\|\s*\bbash\b`, // curl pipe to bash
  82. String.raw`\bwget\b.*\|\s*\bbash\b`, // wget pipe to bash
  83. ];
  84. /** Lazy-initialized compiled blocklist cache. */
  85. let bashBlocklistCache: RegExp[] | null = null;
  86. function compileBashBlocklist(): RegExp[] {
  87. const patterns = [...DEFAULT_BASH_BLOCKLIST_PATTERNS];
  88. const envExtra = (process.env.CLAUDE_BASH_BLOCKLIST ?? '').trim();
  89. if (envExtra) {
  90. for (const p of envExtra.split(',')) {
  91. const trimmed = p.trim();
  92. if (trimmed) patterns.push(trimmed);
  93. }
  94. }
  95. const compiled: RegExp[] = [];
  96. for (const p of patterns) {
  97. try {
  98. compiled.push(new RegExp(p, 'i'));
  99. } catch (err) {
  100. console.warn(`Invalid bash blocklist pattern ${JSON.stringify(p)}: ${err}`);
  101. }
  102. }
  103. return compiled;
  104. }
  105. function getBashBlocklist(): RegExp[] {
  106. if (bashBlocklistCache === null) {
  107. bashBlocklistCache = compileBashBlocklist();
  108. }
  109. return bashBlocklistCache;
  110. }
  111. /**
  112. * Check a bash command against the blocklist.
  113. * Returns the matched pattern source if blocked, or null if allowed.
  114. */
  115. function checkBashCommand(command: string): string | null {
  116. for (const pattern of getBashBlocklist()) {
  117. if (pattern.test(command)) {
  118. return pattern.source;
  119. }
  120. }
  121. return null;
  122. }
  123. // ---------------------------------------------------------------------------
  124. // Tool configuration helpers
  125. // ---------------------------------------------------------------------------
  126. /**
  127. * Resolve the final tool list from request_parts and environment.
  128. *
  129. * Priority:
  130. * 1. Determine the base allowlist from `CLAUDE_ALLOWED_TOOLS` env var
  131. * or `DEFAULT_TOOLS`.
  132. * 2. If `requestTools` is provided AND an env allowlist is set, the
  133. * result is the intersection (request tools can only narrow the
  134. * env allowlist, not expand it). If no env allowlist is set, request
  135. * tools are used as-is (for development flexibility).
  136. * 3. `CLAUDE_DISALLOWED_TOOLS` env var entries are removed last.
  137. */
  138. function resolveTools(requestTools: string[] | null): string[] {
  139. // Step 1: Determine the base allowlist from environment (or default)
  140. const envAllowed = (process.env.CLAUDE_ALLOWED_TOOLS ?? '').trim();
  141. let baseTools: string[];
  142. if (envAllowed) {
  143. baseTools = envAllowed.split(',').map(t => t.trim()).filter(Boolean);
  144. } else {
  145. baseTools = [...DEFAULT_TOOLS];
  146. }
  147. // Step 2: Apply request_tools
  148. let tools: string[];
  149. if (requestTools && requestTools.length > 0) {
  150. if (envAllowed) {
  151. // Intersection: request can only narrow the env allowlist
  152. const baseSet = new Set(baseTools);
  153. tools = requestTools.filter(t => baseSet.has(t));
  154. } else {
  155. // No env allowlist -- use request tools as-is (dev flexibility)
  156. tools = [...requestTools];
  157. }
  158. } else {
  159. tools = baseTools;
  160. }
  161. // Step 3: Apply disallowed list from environment
  162. const envDisallowed = (process.env.CLAUDE_DISALLOWED_TOOLS ?? '').trim();
  163. if (envDisallowed) {
  164. const blocklist = new Set(
  165. envDisallowed.split(',').map(t => t.trim()).filter(Boolean),
  166. );
  167. tools = tools.filter(t => !blocklist.has(t));
  168. }
  169. // Step 4: Warn about unrecognized tool names
  170. const knownTools = new Set(EXTENDED_TOOLS);
  171. for (const t of tools) {
  172. if (!knownTools.has(t)) {
  173. console.warn(
  174. `Unrecognized tool name ${JSON.stringify(t)} -- not in DEFAULT_TOOLS or EXTENDED_TOOLS. ` +
  175. 'It may be valid in a newer CLI version.',
  176. );
  177. }
  178. }
  179. return tools;
  180. }
  181. // ---------------------------------------------------------------------------
  182. // CWD sandboxing
  183. // ---------------------------------------------------------------------------
  184. /**
  185. * Validate and resolve the working directory.
  186. * Returns the resolved absolute path, or null to use the process default.
  187. * Throws if the path is not allowed or does not exist.
  188. */
  189. function resolveCwd(requestCwd: string | null): string | null {
  190. if (!requestCwd) return null;
  191. const resolved = resolve(requestCwd);
  192. // Check existence
  193. if (!existsSync(resolved) || !statSync(resolved).isDirectory()) {
  194. throw new Error(`Working directory does not exist: ${resolved}`);
  195. }
  196. // Check against allowed paths (if configured)
  197. const envAllowed = (process.env.CLAUDE_ALLOWED_PATHS ?? '').trim();
  198. if (envAllowed) {
  199. const allowed = envAllowed.split(',')
  200. .map(p => p.trim())
  201. .filter(Boolean)
  202. .map(p => resolve(p));
  203. const isWithin = allowed.some(
  204. a => resolved === a || resolved.startsWith(a + sep),
  205. );
  206. if (!isWithin) {
  207. throw new Error(
  208. `Working directory ${resolved} is not within allowed paths: ${JSON.stringify(allowed)}`,
  209. );
  210. }
  211. }
  212. return resolved;
  213. }
  214. // ---------------------------------------------------------------------------
  215. // Error / cancel artifact helpers
  216. // ---------------------------------------------------------------------------
  217. function errorArtifact(
  218. errorType: string,
  219. message: string,
  220. details?: Record<string, unknown>,
  221. ): HandlerResult {
  222. const payload: Record<string, unknown> = {
  223. ok: false,
  224. errorType,
  225. error: message,
  226. };
  227. if (details) {
  228. payload.details = details;
  229. }
  230. return {
  231. artifacts: [{ data: JSON.stringify(payload), mimeType: 'application/json' }],
  232. };
  233. }
  234. function cancelArtifact(
  235. sessionId: string | null,
  236. filesChanged: Set<string>,
  237. toolCallCount: number,
  238. bashCommandsRun: string[],
  239. ): HandlerResult {
  240. const payload = {
  241. ok: false,
  242. text: 'Task was cancelled.',
  243. sessionId,
  244. filesChanged: [...filesChanged].sort(),
  245. toolCallCount,
  246. bashCommandCount: bashCommandsRun.length,
  247. cancelled: true,
  248. };
  249. return {
  250. artifacts: [{ data: JSON.stringify(payload), mimeType: 'application/json' }],
  251. };
  252. }
  253. // ---------------------------------------------------------------------------
  254. // Input extraction
  255. // ---------------------------------------------------------------------------
  256. interface ExtractedInput {
  257. prompt: string | null;
  258. sessionId: string | null;
  259. tools: string[] | null;
  260. cwd: string | null;
  261. disableBashSafety: boolean;
  262. model: string | null;
  263. }
  264. function extractInput(parts: unknown[]): ExtractedInput {
  265. let prompt: string | null = null;
  266. let sessionId: string | null = null;
  267. let tools: string[] | null = null;
  268. let cwd: string | null = null;
  269. let disableBashSafety = false;
  270. let model: string | null = null;
  271. for (const part of parts) {
  272. if (typeof part === 'string') {
  273. prompt = part;
  274. } else if (isRecord(part)) {
  275. const content = parsePartContent(part);
  276. if (typeof content.text === 'string') {
  277. prompt = content.text;
  278. }
  279. if (typeof content.sessionId === 'string') {
  280. sessionId = content.sessionId;
  281. }
  282. if (Array.isArray(content.tools)) {
  283. tools = content.tools.filter((t): t is string => typeof t === 'string');
  284. }
  285. if (typeof content.cwd === 'string') {
  286. cwd = content.cwd;
  287. }
  288. if (content.disableBashSafety === true) {
  289. disableBashSafety = true;
  290. }
  291. if (typeof content.model === 'string') {
  292. model = content.model;
  293. }
  294. }
  295. }
  296. return { prompt, sessionId, tools, cwd, disableBashSafety, model };
  297. }
  298. function parsePartContent(part: Record<string, unknown>): Record<string, unknown> {
  299. if (typeof part.text === 'string') {
  300. try {
  301. const parsed = JSON.parse(part.text);
  302. if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
  303. return parsed as Record<string, unknown>;
  304. }
  305. } catch {
  306. // text is plain string, not JSON -- fall through
  307. }
  308. }
  309. return part;
  310. }
  311. function isRecord(v: unknown): v is Record<string, unknown> {
  312. return v !== null && typeof v === 'object' && !Array.isArray(v);
  313. }
  314. // ---------------------------------------------------------------------------
  315. // Claude session runner
  316. // ---------------------------------------------------------------------------
  317. async function runClaudeSession(
  318. prompt: string,
  319. sessionId: string | null,
  320. ctx: TaskContext | undefined,
  321. tools: string[],
  322. cwd: string | null,
  323. bashSafetyEnabled: boolean,
  324. requestModel: string | null,
  325. ): Promise<HandlerResult> {
  326. // Stream only when negotiated (request streaming is consumer
  327. // opt-in); otherwise createStream() would throw. The code below already
  328. // treats stream as optional (stream?.write / stream?.end).
  329. const stream = ctx?.hasStream ? await ctx.createStream() : undefined;
  330. try {
  331. let currentSessionId = sessionId;
  332. let toolCallCount = 0;
  333. const filesChanged = new Set<string>();
  334. const bashCommandsRun: string[] = [];
  335. let resultData: Record<string, unknown> = {};
  336. // Build CLI command
  337. const args: string[] = [
  338. '-p',
  339. '--output-format', 'stream-json',
  340. '--verbose',
  341. '--include-partial-messages',
  342. '--allow-dangerously-skip-permissions',
  343. '--dangerously-skip-permissions',
  344. '--allowedTools', tools.join(','),
  345. ];
  346. if (currentSessionId) {
  347. args.push('--resume', currentSessionId);
  348. }
  349. const maxBudget = process.env.CLAUDE_MAX_BUDGET_USD;
  350. if (maxBudget) {
  351. args.push('--max-budget-usd', maxBudget);
  352. }
  353. const model = requestModel || process.env.CLAUDE_MODEL;
  354. if (model) {
  355. args.push('--model', model);
  356. }
  357. args.push('--', prompt);
  358. // Unset CLAUDECODE to allow invocation from within a Claude Code session
  359. const env = { ...process.env, CLAUDECODE: '' };
  360. const proc = spawn('claude', args, {
  361. cwd: cwd ?? undefined,
  362. env,
  363. stdio: ['pipe', 'pipe', 'pipe'],
  364. });
  365. // Close stdin -- prompt is passed as a CLI argument
  366. proc.stdin.end();
  367. const rl = createInterface({ input: proc.stdout! });
  368. for await (const rawLine of rl) {
  369. // Cooperative cancellation: check at each stream event
  370. if (ctx?.isCancelled) {
  371. proc.kill();
  372. rl.close();
  373. await stream?.end();
  374. return cancelArtifact(
  375. currentSessionId, filesChanged, toolCallCount, bashCommandsRun,
  376. );
  377. }
  378. const line = rawLine.trim();
  379. if (!line) continue;
  380. let event: Record<string, unknown>;
  381. try {
  382. event = JSON.parse(line) as Record<string, unknown>;
  383. } catch {
  384. continue;
  385. }
  386. const etype = event.type as string | undefined;
  387. if (etype === 'system') {
  388. // First-turn: capture session_id from init event
  389. if (!currentSessionId && typeof event.session_id === 'string') {
  390. currentSessionId = event.session_id;
  391. }
  392. } else if (etype === 'stream_event') {
  393. // Token-level streaming deltas
  394. const inner = (event.event ?? {}) as Record<string, unknown>;
  395. const innerType = inner.type as string | undefined;
  396. if (innerType === 'content_block_delta') {
  397. const delta = (inner.delta ?? {}) as Record<string, unknown>;
  398. const deltaType = delta.type as string | undefined;
  399. if (deltaType === 'text_delta') {
  400. const text = delta.text as string | undefined;
  401. if (text && stream) {
  402. stream.write(text);
  403. }
  404. }
  405. // Skip thinking_delta, input_json_delta
  406. }
  407. } else if (etype === 'assistant') {
  408. // Complete message -- extract tool metadata
  409. const message = (event.message ?? {}) as Record<string, unknown>;
  410. const content = (message.content ?? []) as Record<string, unknown>[];
  411. for (const block of content) {
  412. const btype = block.type as string | undefined;
  413. if (btype === 'tool_use') {
  414. toolCallCount++;
  415. const name = (block.name ?? '') as string;
  416. const inp = (block.input ?? {}) as Record<string, unknown>;
  417. if (name === 'Write' || name === 'Edit') {
  418. const fp = inp.file_path as string | undefined;
  419. if (fp) {
  420. filesChanged.add(fp);
  421. }
  422. }
  423. if (name === 'Bash') {
  424. const cmdStr = (inp.command ?? '') as string;
  425. if (cmdStr) {
  426. bashCommandsRun.push(cmdStr);
  427. // Stream-based bash safety: kill subprocess if dangerous
  428. if (bashSafetyEnabled) {
  429. const matched = checkBashCommand(cmdStr);
  430. if (matched) {
  431. console.warn(
  432. `BLOCKED bash command: ${cmdStr.slice(0, 200)} (pattern: ${matched})`,
  433. );
  434. proc.kill();
  435. rl.close();
  436. await stream?.end();
  437. return errorArtifact(
  438. 'BashSafetyViolation',
  439. `Blocked dangerous bash command matching pattern ${JSON.stringify(matched)}`,
  440. { command: cmdStr.slice(0, 200), sessionId: currentSessionId },
  441. );
  442. }
  443. }
  444. }
  445. }
  446. }
  447. }
  448. } else if (etype === 'result') {
  449. resultData = event;
  450. if (typeof event.session_id === 'string') {
  451. currentSessionId = event.session_id;
  452. }
  453. }
  454. }
  455. // Wait for process to exit
  456. await new Promise<void>((res) => {
  457. proc.on('close', () => res());
  458. // If process already exited, resolve immediately
  459. if (proc.exitCode !== null) res();
  460. });
  461. // Final cancellation check after process exits
  462. if (ctx?.isCancelled) {
  463. await stream?.end();
  464. return cancelArtifact(
  465. currentSessionId, filesChanged, toolCallCount, bashCommandsRun,
  466. );
  467. }
  468. // Build response from the result event
  469. const fullText = (resultData.result ?? '') as string;
  470. const isError = (resultData.is_error ?? false) as boolean;
  471. const responsePayload: Record<string, unknown> = {
  472. ok: !isError,
  473. text: fullText,
  474. sessionId: currentSessionId,
  475. filesChanged: [...filesChanged].sort(),
  476. toolCallCount,
  477. bashCommandCount: bashCommandsRun.length,
  478. };
  479. // Include optional metadata fields only when available
  480. if (resultData.duration_ms != null) {
  481. responsePayload.durationMs = resultData.duration_ms;
  482. }
  483. if (resultData.num_turns != null) {
  484. responsePayload.numTurns = resultData.num_turns;
  485. }
  486. if (resultData.total_cost_usd != null) {
  487. responsePayload.totalCostUsd = resultData.total_cost_usd;
  488. }
  489. await stream?.end();
  490. return {
  491. artifacts: [{ data: JSON.stringify(responsePayload), mimeType: 'application/json' }],
  492. };
  493. } finally {
  494. // Safety net: always close the stream, even if the subprocess fails.
  495. // stream.end() is idempotent -- calling it after it's already ended is safe.
  496. if (stream) {
  497. try {
  498. await stream.end();
  499. } catch {
  500. console.warn('Failed to close stream');
  501. }
  502. }
  503. }
  504. }
  505. // ---------------------------------------------------------------------------
  506. // Main handler
  507. // ---------------------------------------------------------------------------
  508. /**
  509. * Handle an incoming task by running Claude Code and streaming output.
  510. */
  511. export default async function handler(
  512. task: StartTaskMessage,
  513. ctx?: TaskContext,
  514. ): Promise<HandlerResult> {
  515. // Check for API key early
  516. if (!process.env.ANTHROPIC_API_KEY) {
  517. return errorArtifact(
  518. 'ConfigurationError',
  519. 'ANTHROPIC_API_KEY environment variable is not set. ' +
  520. 'Set it to your Anthropic API key from https://console.anthropic.com/',
  521. );
  522. }
  523. // Check for claude CLI on PATH
  524. try {
  525. whichSync.sync('claude');
  526. } catch {
  527. return errorArtifact(
  528. 'ConfigurationError',
  529. 'claude CLI not found on PATH. ' +
  530. 'Install it with: npm install -g @anthropic/claude-code',
  531. );
  532. }
  533. const { prompt, sessionId, tools: requestTools, cwd: requestCwd, disableBashSafety, model: requestModel } =
  534. extractInput(task.requestParts ?? []);
  535. if (!prompt) {
  536. return errorArtifact(
  537. 'InputError',
  538. 'Missing text input',
  539. { example: { kind: 'input_text', text: 'Write a hello world in Python' } },
  540. );
  541. }
  542. // Resolve tools
  543. const tools = resolveTools(requestTools);
  544. // Resolve and validate cwd
  545. let cwd: string | null;
  546. try {
  547. cwd = resolveCwd(requestCwd);
  548. } catch (err) {
  549. return errorArtifact('SandboxError', (err as Error).message);
  550. }
  551. // Determine bash safety setting
  552. const envBashSafety = (process.env.CLAUDE_BASH_SAFETY ?? 'on').trim().toLowerCase();
  553. const bashSafetyEnabled = envBashSafety !== 'off' && !disableBashSafety;
  554. try {
  555. return await runClaudeSession(
  556. prompt, sessionId, ctx, tools, cwd, bashSafetyEnabled, requestModel,
  557. );
  558. } catch (err) {
  559. console.error(`Claude Code session failed: session_id=${sessionId}`, err);
  560. return errorArtifact(
  561. (err as Error).constructor?.name ?? 'Error',
  562. (err as Error).message ?? String(err),
  563. { sessionId },
  564. );
  565. }
  566. }
examples/python/claude-code/handler.py · Bundled script · 596 lines · 2 findings marked
  1. """
  2. Claude Code handler.
  3. Runs a Claude Code session for each task by invoking the ``claude`` CLI as a
  4. subprocess with ``--output-format stream-json --include-partial-messages``.
  5. Token-level text deltas are streamed to the consumer in real time via the
  6. Blocks streaming buffer. A single JSON artifact is returned with the
  7. complete text, session metadata, and tool-usage statistics.
  8. Supports multi-turn conversations via sessionId. If the consumer includes
  9. a sessionId (obtained from the previous task's artifact) the handler
  10. resumes that Claude Code session using the CLI's ``--resume`` flag.
  11. On the first turn, ``sessionId`` is omitted and the CLI generates one;
  12. it is returned in the response artifact.
  13. Input format (first turn):
  14. { "kind": "input_text", "text": "Fix the bug in auth.ts" }
  15. Input format (follow-up turn):
  16. { "kind": "input_text", "text": "Now add tests for that fix", "sessionId": "<id>" }
  17. Input format (with tools and cwd):
  18. {
  19. "kind": "input_text",
  20. "text": "Fix the bug",
  21. "tools": ["Read", "Grep", "Glob"],
  22. "cwd": "/path/to/repo",
  23. "disableBashSafety": false
  24. }
  25. Environment variables for configuration:
  26. CLAUDE_ALLOWED_TOOLS -- comma-separated tool allowlist (overrides default).
  27. When set, request_parts tools are intersected with
  28. this list (request tools can only narrow, not expand).
  29. CLAUDE_DISALLOWED_TOOLS -- comma-separated tool blocklist (applied after allowlist)
  30. CLAUDE_ALLOWED_PATHS -- comma-separated allowed working directory paths
  31. CLAUDE_BASH_SAFETY -- "on" (default) or "off" to toggle bash safety.
  32. When on, dangerous commands detected in the stream
  33. cause the subprocess to be killed.
  34. CLAUDE_BASH_BLOCKLIST -- comma-separated additional blocked bash patterns
  35. CLAUDE_MAX_BUDGET_USD -- max dollar amount per task (passed to CLI)
  36. CLAUDE_MODEL -- model to use (e.g. "sonnet", "opus")
  37. """
  38. from __future__ import annotations
  39. import asyncio
  40. import json
  41. import logging
  42. import os
  43. import re
  44. import shutil
  45. from pathlib import Path
  46. from typing import Any, Dict, List, Optional, Tuple
  47. from blocks_network.types import StartTaskMessage, TaskContext
  48. logger = logging.getLogger(__name__)
  49. # ---------------------------------------------------------------------------
  50. # Tool configuration
  51. # ---------------------------------------------------------------------------
  52. # The default safe set -- filesystem reads plus controlled writes
  53. DEFAULT_TOOLS = ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]
  54. # Extended set that consumers can opt into by passing tools in request_parts
  55. EXTENDED_TOOLS = DEFAULT_TOOLS + [
  56. "WebSearch", "TodoRead", "TodoWrite", "NotebookRead", "NotebookEdit",
  57. ]
  58. # ---------------------------------------------------------------------------
  59. # Bash safety configuration
  60. # ---------------------------------------------------------------------------
  61. # Patterns that are always blocked unless bash safety is disabled.
  62. # Each entry is a compiled regex matched against the full command string.
  63. _DEFAULT_BASH_BLOCKLIST_PATTERNS = [
  64. 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
  65. 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
  66. r"rm\s+-rf\s+/(?:usr|etc|var|home|boot|sys|proc|dev)\b", # rm -rf system dirs
  67. r"\bsudo\b", # any sudo usage
  68. r"\bmkfs\b", # format filesystem
  69. r"\bdd\s+.*of=/dev/", # dd to devices
  70. r">\s*/dev/sd[a-z]", # redirect to block devices
  71. r"\bshutdown\b", # shutdown
  72. r"\breboot\b", # reboot
  73. r"\binit\s+[0-6]\b", # init runlevel changes
  74. r"chmod\s+-R\s+777\s+/", # recursive chmod 777 on root
  75. r":\(\)\s*\{\s*:\|\s*:\s*&\s*\}\s*;", # fork bomb
  76. r"\bkill\s+-9\s+-1\b", # kill all processes
  77. r"\bcurl\b.*\|\s*\bbash\b", # curl pipe to bash
  78. r"\bwget\b.*\|\s*\bbash\b", # wget pipe to bash
  79. ]
  80. def _compile_bash_blocklist() -> List[re.Pattern]:
  81. """Compile the default blocklist plus any from the environment."""
  82. patterns = list(_DEFAULT_BASH_BLOCKLIST_PATTERNS)
  83. env_extra = os.environ.get("CLAUDE_BASH_BLOCKLIST", "").strip()
  84. if env_extra:
  85. patterns.extend(p.strip() for p in env_extra.split(",") if p.strip())
  86. compiled = []
  87. for p in patterns:
  88. try:
  89. compiled.append(re.compile(p, re.IGNORECASE))
  90. except re.error as exc:
  91. logger.warning("Invalid bash blocklist pattern %r: %s", p, exc)
  92. return compiled
  93. _bash_blocklist: Optional[List[re.Pattern]] = None
  94. def _get_bash_blocklist() -> List[re.Pattern]:
  95. """Lazy-init and cache the compiled blocklist."""
  96. global _bash_blocklist
  97. if _bash_blocklist is None:
  98. _bash_blocklist = _compile_bash_blocklist()
  99. return _bash_blocklist
  100. def _check_bash_command(command: str) -> Optional[str]:
  101. """Check a bash command against the blocklist.
  102. Returns the matched pattern string if blocked, or None if allowed.
  103. """
  104. for pattern in _get_bash_blocklist():
  105. if pattern.search(command):
  106. return pattern.pattern
  107. return None
  108. # ---------------------------------------------------------------------------
  109. # Tool configuration helpers
  110. # ---------------------------------------------------------------------------
  111. def _resolve_tools(
  112. request_tools: Optional[List[str]],
  113. ) -> List[str]:
  114. """Resolve the final tool list from request_parts and environment.
  115. Priority:
  116. 1. Determine the base allowlist from ``CLAUDE_ALLOWED_TOOLS`` env var
  117. or ``DEFAULT_TOOLS``.
  118. 2. If ``request_tools`` is provided AND an env allowlist is set, the
  119. result is the **intersection** (request tools can only narrow the
  120. env allowlist, not expand it). If no env allowlist is set, request
  121. tools are used as-is (for development flexibility).
  122. 3. ``CLAUDE_DISALLOWED_TOOLS`` env var entries are removed last.
  123. A warning is logged for any tool name not in ``DEFAULT_TOOLS + EXTENDED_TOOLS``.
  124. """
  125. # Step 1: Determine the base allowlist from environment (or default)
  126. env_allowed = os.environ.get("CLAUDE_ALLOWED_TOOLS", "").strip()
  127. if env_allowed:
  128. base_tools = [t.strip() for t in env_allowed.split(",") if t.strip()]
  129. else:
  130. base_tools = list(DEFAULT_TOOLS)
  131. # Step 2: Apply request_tools
  132. if request_tools:
  133. if env_allowed:
  134. # Intersection: request can only narrow the env allowlist
  135. base_set = set(base_tools)
  136. tools = [t for t in request_tools if t in base_set]
  137. else:
  138. # No env allowlist -- use request tools as-is (dev flexibility)
  139. tools = list(request_tools)
  140. else:
  141. tools = base_tools
  142. # Step 3: Apply disallowed list from environment
  143. env_disallowed = os.environ.get("CLAUDE_DISALLOWED_TOOLS", "").strip()
  144. if env_disallowed:
  145. blocklist = {t.strip() for t in env_disallowed.split(",") if t.strip()}
  146. tools = [t for t in tools if t not in blocklist]
  147. # Step 4: Warn about unrecognized tool names
  148. known_tools = set(EXTENDED_TOOLS) # EXTENDED_TOOLS is a superset of DEFAULT_TOOLS
  149. for t in tools:
  150. if t not in known_tools:
  151. logger.warning(
  152. "Unrecognized tool name %r -- not in DEFAULT_TOOLS or EXTENDED_TOOLS. "
  153. "It may be valid in a newer CLI version.",
  154. t,
  155. )
  156. return tools
  157. # ---------------------------------------------------------------------------
  158. # CWD sandboxing
  159. # ---------------------------------------------------------------------------
  160. def _resolve_cwd(request_cwd: Optional[str]) -> Optional[str]:
  161. """Validate and resolve the working directory.
  162. Returns the resolved absolute path, or ``None`` to use the process default.
  163. Raises ``ValueError`` if the path is not allowed or does not exist.
  164. """
  165. if not request_cwd:
  166. return None
  167. resolved = str(Path(request_cwd).resolve())
  168. # Check existence
  169. if not Path(resolved).is_dir():
  170. raise ValueError(
  171. f"Working directory does not exist: {resolved}"
  172. )
  173. # Check against allowed paths (if configured)
  174. env_allowed = os.environ.get("CLAUDE_ALLOWED_PATHS", "").strip()
  175. if env_allowed:
  176. allowed = [str(Path(p.strip()).resolve()) for p in env_allowed.split(",") if p.strip()]
  177. if not any(resolved == a or resolved.startswith(a + os.sep) for a in allowed):
  178. raise ValueError(
  179. f"Working directory {resolved} is not within allowed paths: {allowed}"
  180. )
  181. return resolved
  182. # ---------------------------------------------------------------------------
  183. # Error artifact helpers
  184. # ---------------------------------------------------------------------------
  185. def _error_artifact(error_type: str, message: str, details: Optional[Dict] = None) -> Dict[str, Any]:
  186. """Build a structured error artifact."""
  187. payload: Dict[str, Any] = {
  188. "ok": False,
  189. "errorType": error_type,
  190. "error": message,
  191. }
  192. if details:
  193. payload["details"] = details
  194. return {
  195. "artifacts": [{"data": json.dumps(payload), "mimeType": "application/json"}],
  196. }
  197. def _cancel_artifact(
  198. session_id: Optional[str],
  199. files_changed: set,
  200. tool_call_count: int,
  201. bash_commands_run: List[str],
  202. ) -> Dict[str, Any]:
  203. """Build a cancel artifact with whatever metadata we have so far."""
  204. payload: Dict[str, Any] = {
  205. "ok": False,
  206. "text": "Task was cancelled.",
  207. "sessionId": session_id,
  208. "filesChanged": sorted(files_changed),
  209. "toolCallCount": tool_call_count,
  210. "bashCommandCount": len(bash_commands_run),
  211. "cancelled": True,
  212. }
  213. return {
  214. "artifacts": [{"data": json.dumps(payload), "mimeType": "application/json"}],
  215. }
  216. # ---------------------------------------------------------------------------
  217. # Input extraction
  218. # ---------------------------------------------------------------------------
  219. def _extract_input(
  220. parts: List[Any],
  221. ) -> Tuple[Optional[str], Optional[str], Optional[List[str]], Optional[str], bool, Optional[str]]:
  222. """Extract prompt text, sessionId, tools, cwd, disableBashSafety, and model from request parts.
  223. Returns:
  224. (prompt, session_id, tools, cwd, disable_bash_safety, model)
  225. """
  226. prompt: Optional[str] = None
  227. session_id: Optional[str] = None
  228. tools: Optional[List[str]] = None
  229. cwd: Optional[str] = None
  230. disable_bash_safety = False
  231. model: Optional[str] = None
  232. for part in parts:
  233. if isinstance(part, str):
  234. prompt = part
  235. else:
  236. content = _parse_part_content(part)
  237. if isinstance(content.get("text"), str):
  238. prompt = content["text"]
  239. if isinstance(content.get("sessionId"), str):
  240. session_id = content["sessionId"]
  241. if isinstance(content.get("tools"), list):
  242. tools = [str(t) for t in content["tools"] if isinstance(t, str)]
  243. if isinstance(content.get("cwd"), str):
  244. cwd = content["cwd"]
  245. if content.get("disableBashSafety") is True:
  246. disable_bash_safety = True
  247. if isinstance(content.get("model"), str):
  248. model = content["model"]
  249. return prompt, session_id, tools, cwd, disable_bash_safety, model
  250. def _parse_part_content(part: Any) -> Dict[str, Any]:
  251. """Extract structured content from a RequestPart or raw dict.
  252. The frontend serializes structured content into the ``text`` field as
  253. JSON. This helper parses it back into a dict.
  254. """
  255. text = getattr(part, "text", None) if not isinstance(part, dict) else part.get("text")
  256. if isinstance(text, str):
  257. try:
  258. parsed = json.loads(text)
  259. if isinstance(parsed, dict):
  260. return parsed
  261. except (json.JSONDecodeError, ValueError):
  262. pass
  263. return {"text": text}
  264. if hasattr(part, "extra") and isinstance(part.extra, dict):
  265. return part.extra
  266. if isinstance(part, dict):
  267. return part
  268. return {}
  269. # ---------------------------------------------------------------------------
  270. # Main handler
  271. # ---------------------------------------------------------------------------
  272. def handler(task: StartTaskMessage, ctx: Optional[TaskContext] = None) -> Dict[str, Any]:
  273. """Handle an incoming task by running Claude Code and streaming output."""
  274. # Check for API key early
  275. if not os.environ.get("ANTHROPIC_API_KEY"):
  276. return _error_artifact(
  277. "ConfigurationError",
  278. "ANTHROPIC_API_KEY environment variable is not set. "
  279. "Set it to your Anthropic API key from https://console.anthropic.com/",
  280. )
  281. # Check for claude CLI on PATH
  282. if not shutil.which("claude"):
  283. return _error_artifact(
  284. "ConfigurationError",
  285. "claude CLI not found on PATH. "
  286. "Install it with: npm install -g @anthropic/claude-code",
  287. )
  288. prompt, session_id, request_tools, request_cwd, disable_bash_safety, request_model = _extract_input(
  289. task.request_parts or []
  290. )
  291. if not prompt:
  292. return _error_artifact(
  293. "InputError",
  294. "Missing text input",
  295. {"example": {"kind": "input_text", "text": "Write a hello world in Python"}},
  296. )
  297. # Resolve tools
  298. tools = _resolve_tools(request_tools)
  299. # Resolve and validate cwd
  300. try:
  301. cwd = _resolve_cwd(request_cwd)
  302. except ValueError as exc:
  303. return _error_artifact("SandboxError", str(exc))
  304. # Determine bash safety setting
  305. env_bash_safety = os.environ.get("CLAUDE_BASH_SAFETY", "on").strip().lower()
  306. bash_safety_enabled = (env_bash_safety != "off") and (not disable_bash_safety)
  307. try:
  308. result = asyncio.run(
  309. _run_claude_session(prompt, session_id, ctx, tools, cwd, bash_safety_enabled, request_model)
  310. )
  311. return result
  312. except asyncio.CancelledError:
  313. logger.warning("Task cancelled: session_id=%s", session_id)
  314. return _error_artifact(
  315. "CancelledError",
  316. "Task was cancelled",
  317. {"sessionId": session_id},
  318. )
  319. except KeyboardInterrupt:
  320. logger.warning("Task interrupted: session_id=%s", session_id)
  321. return _error_artifact(
  322. "InterruptedError",
  323. "Task was interrupted",
  324. {"sessionId": session_id},
  325. )
  326. except Exception as exc:
  327. logger.exception("Claude Code session failed: session_id=%s", session_id)
  328. return _error_artifact(
  329. type(exc).__name__,
  330. str(exc),
  331. {"sessionId": session_id},
  332. )
  333. def _is_cancelled(ctx: Optional[TaskContext]) -> bool:
  334. """Check if the task has been cancelled via cooperative cancellation."""
  335. return ctx is not None and ctx.is_cancelled
  336. async def _run_claude_session(
  337. prompt: str,
  338. session_id: Optional[str],
  339. ctx: Optional[TaskContext],
  340. tools: List[str],
  341. cwd: Optional[str],
  342. bash_safety_enabled: bool,
  343. request_model: Optional[str] = None,
  344. ) -> Dict[str, Any]:
  345. """Run Claude Code via CLI subprocess and stream output to Blocks.
  346. Invokes ``claude -p --output-format stream-json --include-partial-messages``
  347. and reads newline-delimited JSON events from stdout. Text deltas
  348. (``content_block_delta`` with ``text_delta``) are written to the Blocks
  349. stream for token-level progressive output.
  350. Args:
  351. prompt: The user prompt text.
  352. session_id: Session ID from a previous turn (for resumption), or None.
  353. ctx: Blocks task context for streaming.
  354. tools: Resolved list of allowed tool names.
  355. cwd: Working directory, or None for process default.
  356. bash_safety_enabled: Whether to monitor for dangerous bash commands.
  357. request_model: Model from request_parts (overrides CLAUDE_MODEL env var).
  358. """
  359. # Stream only when negotiated (request streaming is consumer
  360. # opt-in); otherwise create_stream() would raise. The code below
  361. # already treats stream as optional.
  362. stream = ctx.create_stream() if ctx and ctx.has_stream else None
  363. try:
  364. tool_call_count = 0
  365. files_changed: set[str] = set()
  366. bash_commands_run: List[str] = []
  367. result_data: Dict[str, Any] = {}
  368. # Build CLI command
  369. cmd: List[str] = [
  370. "claude", "-p",
  371. "--output-format", "stream-json",
  372. "--verbose",
  373. "--include-partial-messages",
  374. "--allow-dangerously-skip-permissions",
  375. "--dangerously-skip-permissions",
  376. "--allowedTools", ",".join(tools),
  377. ]
  378. if session_id:
  379. cmd.extend(["--resume", session_id])
  380. max_budget = os.environ.get("CLAUDE_MAX_BUDGET_USD")
  381. if max_budget:
  382. cmd.extend(["--max-budget-usd", max_budget])
  383. model = request_model or os.environ.get("CLAUDE_MODEL")
  384. if model:
  385. cmd.extend(["--model", model])
  386. cmd.extend(["--", prompt])
  387. # Unset CLAUDECODE to allow invocation from within a Claude Code session
  388. env = {**os.environ, "CLAUDECODE": ""}
  389. # Claude CLI can emit very large JSON lines (e.g. assistant messages
  390. # with tool results or long code). The default asyncio StreamReader
  391. # limit is 64 KB which is too small. Use 16 MB.
  392. proc = await asyncio.create_subprocess_exec(
  393. *cmd,
  394. stdout=asyncio.subprocess.PIPE,
  395. stderr=asyncio.subprocess.PIPE,
  396. limit=16 * 1024 * 1024,
  397. cwd=cwd,
  398. env=env,
  399. )
  400. async for raw_line in proc.stdout:
  401. # Cooperative cancellation: check at each stream event
  402. if _is_cancelled(ctx):
  403. logger.info("Task cancelled, killing subprocess: session_id=%s", session_id)
  404. proc.kill()
  405. await proc.wait()
  406. return _cancel_artifact(
  407. session_id, files_changed, tool_call_count, bash_commands_run,
  408. )
  409. line = raw_line.strip()
  410. if not line:
  411. continue
  412. try:
  413. event = json.loads(line)
  414. except json.JSONDecodeError:
  415. continue
  416. etype = event.get("type")
  417. if etype == "system":
  418. # First-turn: capture session_id from init event
  419. if not session_id:
  420. session_id = event.get("session_id")
  421. elif etype == "stream_event":
  422. # Token-level streaming deltas
  423. inner = event.get("event", {})
  424. inner_type = inner.get("type")
  425. if inner_type == "content_block_delta":
  426. delta = inner.get("delta", {})
  427. delta_type = delta.get("type")
  428. if delta_type == "text_delta":
  429. text = delta.get("text", "")
  430. if text and stream:
  431. stream.write(text)
  432. # Skip thinking_delta, input_json_delta
  433. elif etype == "assistant":
  434. # Complete message — extract tool metadata
  435. content = (event.get("message") or {}).get("content") or []
  436. for block in content:
  437. btype = block.get("type")
  438. if btype == "tool_use":
  439. tool_call_count += 1
  440. name = block.get("name", "")
  441. inp = block.get("input") or {}
  442. if name in ("Write", "Edit"):
  443. fp = inp.get("file_path")
  444. if fp:
  445. files_changed.add(fp)
  446. if name == "Bash":
  447. cmd_str = inp.get("command", "")
  448. if cmd_str:
  449. bash_commands_run.append(cmd_str)
  450. logger.debug("Bash tool call #%d: %s", len(bash_commands_run), cmd_str[:200])
  451. # Stream-based bash safety: kill subprocess if dangerous
  452. if bash_safety_enabled:
  453. matched = _check_bash_command(cmd_str)
  454. if matched:
  455. logger.warning("BLOCKED bash command: %s (pattern: %s)", cmd_str[:200], matched)
  456. proc.kill()
  457. return _error_artifact(
  458. "BashSafetyViolation",
  459. f"Blocked dangerous bash command matching pattern {matched!r}",
  460. {"command": cmd_str[:200], "sessionId": session_id},
  461. )
  462. elif etype == "result":
  463. result_data = event
  464. session_id = event.get("session_id", session_id)
  465. await proc.wait()
  466. # Final cancellation check after process exits
  467. if _is_cancelled(ctx):
  468. return _cancel_artifact(
  469. session_id, files_changed, tool_call_count, bash_commands_run,
  470. )
  471. # Build response from the result event
  472. full_text = result_data.get("result", "")
  473. is_error = result_data.get("is_error", False)
  474. response_payload: Dict[str, Any] = {
  475. "ok": not is_error,
  476. "text": full_text,
  477. "sessionId": session_id,
  478. "filesChanged": sorted(files_changed),
  479. "toolCallCount": tool_call_count,
  480. "bashCommandCount": len(bash_commands_run),
  481. }
  482. # Include optional metadata fields only when available
  483. if result_data.get("duration_ms") is not None:
  484. response_payload["durationMs"] = result_data["duration_ms"]
  485. if result_data.get("num_turns") is not None:
  486. response_payload["numTurns"] = result_data["num_turns"]
  487. if result_data.get("total_cost_usd") is not None:
  488. response_payload["totalCostUsd"] = result_data["total_cost_usd"]
  489. return {
  490. "artifacts": [{"data": json.dumps(response_payload), "mimeType": "application/json"}],
  491. }
  492. finally:
  493. # Always close the stream, even if the subprocess fails
  494. if stream:
  495. try:
  496. stream.end()
  497. except Exception:
  498. 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 in

Free to use. If it’s helped, pass it on.