Embed claude-p in a Zig Program
Goal: Add claude_p to a Zig 0.15.2 executable, run a one-shot prompt, stream live JSONL lines to a custom writer, and merge library-level extra_hooks and extra_settings_json without touching ~/.claude/.
Time: 10 minutes. You need Zig 0.15.2 (zmux enforces 0.15.2 at comptime) and claude on $PATH.
Step 1: Fetch claude_p and wire build.zig
Section titled “Step 1: Fetch claude_p and wire build.zig”In your Zig project directory, fetch the package:
zig fetch --save=claude_p git+https://github.com/smithersai/claude-pThen import the claude_p module and add a run step in build.zig:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const claude_p_dep = b.dependency("claude_p", .{ .target = target, .optimize = optimize, });
const exe = b.addExecutable(.{ .name = "my-agent", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "claude_p", .module = claude_p_dep.module("claude_p") }, }, }), }); b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| run_cmd.addArgs(args); const run_step = b.step("run", "Run my-agent"); run_step.dependOn(&run_cmd.step);}Step 2: Run your first prompt from Zig
Section titled “Step 2: Run your first prompt from Zig”Replace src/main.zig with a minimal one-shot call:
const std = @import("std");const claude_p = @import("claude_p");
pub fn main() !void { var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{}; defer _ = gpa.deinit(); const alloc = gpa.allocator();
var result = try claude_p.run(alloc, .{ .prompt = "What is the capital of France? Reply with one word.", .output_format = .text, .skip_permissions = true, .timeout_ms = 60_000, }); defer result.deinit(alloc);
std.debug.print("answer: {s}\n", .{result.summary.final_text}); std.debug.print("session: {s}\n", .{result.summary.session_id}); std.debug.print("tokens: in={d} out={d} ({d} ms)\n", .{ result.summary.usage.input_tokens, result.summary.usage.output_tokens, result.duration_ms, });}Build and run through the run step, or run the installed binary directly:
zig build run# orzig build && ./zig-out/bin/my-agentNotice the ownership contract: claude_p.run takes an explicit std.mem.Allocator and returns a Result whose Summary owns final_text, session_id, and jsonl_replay. Always pair it with defer result.deinit(alloc);.
Step 3: Stream live lines + attach custom hooks
Section titled “Step 3: Stream live lines + attach custom hooks”You can combine stream_writer (live per-message streaming straight into any std.Io.Writer) with inline hook and settings merging (extra_hooks and extra_settings_json, also available on the CLI via --extra-hook and --setting-json) without touching ~/.claude/.
Update src/main.zig:
const std = @import("std");const claude_p = @import("claude_p");
pub fn main() !void { var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{}; defer _ = gpa.deinit(); const alloc = gpa.allocator();
var stdout_buf: [4096]u8 = undefined; var stdout_writer = std.fs.File.stdout().writer(&stdout_buf); const stdout = &stdout_writer.interface;
var result = try claude_p.run(alloc, .{ .prompt = "Reply with the single word OK.", .output_format = .stream_json, .verbose = true, .skip_permissions = true, .stream_writer = stdout, // Appended AFTER claude-p's relay hooks (relay stays index 0). .extra_hooks = &.{ .{ .event = "Stop", .command = "echo 'turn finished' >&2" }, }, // Top-level keys merged into --settings; any "hooks" key here is ignored. .extra_settings_json = "{\"cleanupPeriodDays\":7}", }); defer result.deinit(alloc);
// Safe to call even in stream_json mode: Result.write is a no-op // when result.streamed == true so nothing is double-emitted. try result.write(alloc, stdout, .stream_json); try stdout.flush();}What happens if you pass this option to claude_p.run?
.extra_settings_json = "{\"hooks\":{\"Stop\":[]},\"cleanupPeriodDays\":7}" Check your answer
claude_p silently ignores the “hooks” key and keeps its own relay hooks intact.
cleanupPeriodDays: 7 is merged into the generated —settings object.
error.InvalidExtraSettings is returned only for malformed JSON, a non-object root
(like ”[]” or “42”), nesting deeper than 128 levels,
“disableAllHooks”: true (it would silence the relay hooks), or an empty or
non-UTF-8 ExtraHook.event/command.
There are no dumb questions
Section titled “There are no dumb questions”Q: Why does build.zig fail if I run Zig 0.16 or 0.17?
A: zmux checks the compiler version at comptime and pins Zig 0.15.2. Use zvm use 0.15.2 (or point your CI action at 0.15.2) when building or embedding claude_p.
Q: Who frees result.summary.final_text, session_id, and jsonl_replay?
A: Your allocator. Every public function in claude_p follows allocator-per-function ownership; calling defer result.deinit(alloc); frees all three heap buffers.
Next steps
Section titled “Next steps”- Need every struct field and error variant? Open the Zig Library API Reference.
- Curious how
Tailerreads a file while Claude appends to it? See Hooks and Transcripts.