@pivanov/claude-wire 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,8 +3,7 @@
3
3
  Run [Claude Code](https://claude.ai/download) programmatically from TypeScript.
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/@pivanov/claude-wire)](https://www.npmjs.com/package/@pivanov/claude-wire)
6
- [![npm bundle size](https://img.shields.io/bundlephobia/minzip/@pivanov/claude-wire)](https://bundlephobia.com/package/@pivanov/claude-wire)
7
- [![license](https://img.shields.io/npm/l/claude-wire)](./LICENSE)
6
+ [![license](https://img.shields.io/npm/l/@pivanov/claude-wire)](./LICENSE)
8
7
 
9
8
  ```ts
10
9
  import { claude } from "@pivanov/claude-wire";
@@ -26,7 +25,7 @@ console.log(result.costUsd); // 0.0084
26
25
  - **Cost tracking** - per-request budgets with auto-abort
27
26
  - **Fully typed** - discriminated union events, full IntelliSense
28
27
  - **Resilient** - auto-respawn, transient error detection, AbortSignal
29
- - **Zero dependencies** - 13 kB gzipped
28
+ - **Zero dependencies** - 25.6 kB gzipped
30
29
 
31
30
  ## Install
32
31
 
@@ -38,6 +37,8 @@ npm install @pivanov/claude-wire
38
37
 
39
38
  Requires [Claude Code CLI](https://claude.ai/download) installed and authenticated. Runs on [Bun](https://bun.sh) >= 1.0 or Node.js >= 22.
40
39
 
40
+ > **Platform:** POSIX only (macOS, Linux, WSL). Native Windows isn't supported yet -- binary resolution relies on `which` and POSIX path conventions.
41
+
41
42
  > This SDK wraps Claude Code's `--output-format stream-json` protocol, which is not officially documented by Anthropic and may change between releases.
42
43
 
43
44
  ## Documentation
@@ -66,7 +67,7 @@ apps/examples/ interactive example runner
66
67
 
67
68
  ```bash
68
69
  bun install
69
- bun run test # 147 tests
70
+ bun run test # 192 tests
70
71
  bun run typecheck
71
72
  bun run lint
72
73
  bun run docs:dev # local docs server
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Races `promise` against a timeout. When the timer fires first, resolves
3
+ * with `onTimeout()` (or `undefined` if omitted). The caller decides
4
+ * whether that's an acceptable fallback or a signal to kill/retry.
5
+ *
6
+ * Intentionally does NOT reject on timeout -- callers usually have a
7
+ * specific action to take (kill the process, bail early with undefined)
8
+ * that a thrown error would force into a catch branch for no reason.
9
+ */
10
+ export declare const withTimeout: <T, F = undefined>(promise: Promise<T>, ms: number, onTimeout?: () => F) => Promise<T | F>;
package/dist/async.js ADDED
@@ -0,0 +1,27 @@
1
+ // Small async helpers shared between session.ts and stream.ts. Kept in
2
+ // their own file because both consumers care about the *shape* of the
3
+ // timeout pattern, not its underlying mechanics -- drop a single
4
+ // withTimeout() next to whatever else needs it rather than carrying the
5
+ // Promise.race idiom inline at every site.
6
+ /**
7
+ * Races `promise` against a timeout. When the timer fires first, resolves
8
+ * with `onTimeout()` (or `undefined` if omitted). The caller decides
9
+ * whether that's an acceptable fallback or a signal to kill/retry.
10
+ *
11
+ * Intentionally does NOT reject on timeout -- callers usually have a
12
+ * specific action to take (kill the process, bail early with undefined)
13
+ * that a thrown error would force into a catch branch for no reason.
14
+ */
15
+ export const withTimeout = (promise, ms, onTimeout) => {
16
+ let timer;
17
+ const timeout = new Promise((resolve) => {
18
+ timer = setTimeout(() => {
19
+ resolve(onTimeout ? onTimeout() : undefined);
20
+ }, ms);
21
+ });
22
+ return Promise.race([promise, timeout]).finally(() => {
23
+ if (timer) {
24
+ clearTimeout(timer);
25
+ }
26
+ });
27
+ };
package/dist/client.js CHANGED
@@ -1,11 +1,15 @@
1
1
  import { createSession } from "./session.js";
2
2
  import { createStream } from "./stream.js";
3
- const mergeOptions = (defaults, overrides) => ({
4
- ...defaults,
5
- ...overrides,
6
- tools: overrides && "tools" in overrides ? (overrides.tools ? { ...defaults.tools, ...overrides.tools } : overrides.tools) : defaults.tools,
7
- env: overrides && "env" in overrides ? (overrides.env ? { ...defaults.env, ...overrides.env } : overrides.env) : defaults.env,
8
- });
3
+ const mergeOptions = (defaults, overrides) => {
4
+ const merged = { ...defaults, ...overrides };
5
+ if (overrides && "tools" in overrides) {
6
+ merged.tools = overrides.tools ? { ...defaults.tools, ...overrides.tools } : overrides.tools;
7
+ }
8
+ if (overrides && "env" in overrides) {
9
+ merged.env = overrides.env ? { ...defaults.env, ...overrides.env } : overrides.env;
10
+ }
11
+ return merged;
12
+ };
9
13
  export const createClient = (defaults = {}) => {
10
14
  const ask = async (prompt, options) => {
11
15
  const merged = mergeOptions(defaults, options);
@@ -1,12 +1,16 @@
1
1
  export declare const TIMEOUTS: {
2
2
  readonly defaultAbortMs: 300000;
3
3
  readonly gracefulExitMs: 5000;
4
+ readonly stderrDrainGraceMs: 500;
4
5
  };
5
6
  export declare const LIMITS: {
6
7
  readonly maxRespawnAttempts: 3;
7
8
  readonly sessionMaxTurnsBeforeRecycle: 100;
8
9
  readonly ndjsonMaxLineChars: number;
10
+ readonly fingerprintTextLen: 64;
9
11
  };
12
+ export declare const RESPAWN_BACKOFF_MS: readonly [500, 1000, 2000];
13
+ export declare const MAX_BACKOFF_INDEX: 3;
10
14
  export declare const BINARY: {
11
15
  readonly name: "claude";
12
16
  readonly commonPaths: readonly [`${string}/.local/bin/claude`, `${string}/.claude/bin/claude`, "/usr/local/bin/claude", "/opt/homebrew/bin/claude"];
package/dist/constants.js CHANGED
@@ -2,12 +2,22 @@ import { homedir } from "node:os";
2
2
  export const TIMEOUTS = {
3
3
  defaultAbortMs: 300_000,
4
4
  gracefulExitMs: 5_000,
5
+ // Grace period for stderr drain to catch up before an error is thrown so
6
+ // the error message carries the CLI's actual complaint instead of "".
7
+ stderrDrainGraceMs: 500,
5
8
  };
6
9
  export const LIMITS = {
7
10
  maxRespawnAttempts: 3,
8
11
  sessionMaxTurnsBeforeRecycle: 100,
9
12
  ndjsonMaxLineChars: 10 * 1024 * 1024,
13
+ fingerprintTextLen: 64,
10
14
  };
15
+ // Respawn backoff in ms, indexed by consecutiveCrashes (1st=500ms, 2nd=1s, 3rd=2s).
16
+ export const RESPAWN_BACKOFF_MS = [500, 1000, 2000];
17
+ // Highest index into RESPAWN_BACKOFF_MS[]. Used by respawnBackoff() to
18
+ // clamp the delay lookup to the last defined backoff when crashes exceed
19
+ // the table length -- keeps the table and its bound co-located.
20
+ export const MAX_BACKOFF_INDEX = RESPAWN_BACKOFF_MS.length;
11
21
  const home = homedir();
12
22
  export const BINARY = {
13
23
  name: "claude",
package/dist/cost.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { TCostSnapshot } from "./types/results.js";
2
+ import type { TWarn } from "./warnings.js";
2
3
  export interface ICostTracker {
3
4
  update: (totalCostUsd: number, totalInputTokens: number, totalOutputTokens: number) => void;
4
5
  snapshot: () => TCostSnapshot;
@@ -8,5 +9,6 @@ export interface ICostTracker {
8
9
  export interface ICostTrackerOptions {
9
10
  maxCostUsd?: number;
10
11
  onCostUpdate?: (cost: TCostSnapshot) => void;
12
+ onWarning?: TWarn;
11
13
  }
12
14
  export declare const createCostTracker: (options?: ICostTrackerOptions) => ICostTracker;
package/dist/cost.js CHANGED
@@ -1,6 +1,9 @@
1
- import { assertPositiveNumber, BudgetExceededError } from "./errors.js";
1
+ import { BudgetExceededError } from "./errors.js";
2
+ import { assertPositiveNumber } from "./validation.js";
3
+ import { createWarn } from "./warnings.js";
2
4
  export const createCostTracker = (options = {}) => {
3
5
  assertPositiveNumber(options.maxCostUsd, "maxCostUsd");
6
+ const warn = createWarn(options.onWarning);
4
7
  let totalUsd = 0;
5
8
  let inputTokens = 0;
6
9
  let outputTokens = 0;
@@ -17,8 +20,8 @@ export const createCostTracker = (options = {}) => {
17
20
  try {
18
21
  options.onCostUpdate(snapshot());
19
22
  }
20
- catch {
21
- // user callback error - don't crash the stream/session
23
+ catch (error) {
24
+ warn("onCostUpdate callback threw", error);
22
25
  }
23
26
  }
24
27
  };
package/dist/errors.d.ts CHANGED
@@ -16,8 +16,8 @@ export declare class ProcessError extends ClaudeError {
16
16
  readonly exitCode?: number | undefined;
17
17
  constructor(message: string, exitCode?: number | undefined);
18
18
  }
19
- declare const KNOWN_ERROR_CODES: readonly ["not-authenticated", "binary-not-found", "session-expired", "permission-denied", "invalid-model"];
20
- type TKnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];
19
+ export declare const KNOWN_ERROR_CODES: readonly ["not-authenticated", "binary-not-found", "permission-denied", "retry-exhausted"];
20
+ export type TKnownErrorCode = (typeof KNOWN_ERROR_CODES)[number];
21
21
  export declare class KnownError extends ClaudeError {
22
22
  readonly code: TKnownErrorCode;
23
23
  constructor(code: TKnownErrorCode, message?: string);
@@ -25,5 +25,4 @@ export declare class KnownError extends ClaudeError {
25
25
  export declare const isKnownError: (error: unknown) => error is KnownError;
26
26
  export declare const isTransientError: (error: unknown) => boolean;
27
27
  export declare const errorMessage: (error: unknown) => string;
28
- export declare const assertPositiveNumber: (value: number | undefined, name: string) => void;
29
- export {};
28
+ export declare const processExitedEarly: (stderr: string, exitCode?: number) => ProcessError;
package/dist/errors.js CHANGED
@@ -34,7 +34,10 @@ export class ProcessError extends ClaudeError {
34
34
  this.name = "ProcessError";
35
35
  }
36
36
  }
37
- const KNOWN_ERROR_CODES = ["not-authenticated", "binary-not-found", "session-expired", "permission-denied", "invalid-model"];
37
+ // Only codes the SDK actually constructs are listed. Add a new code here
38
+ // alongside the throw site that needs it -- aspirational entries give
39
+ // consumers false confidence that they can pattern-match on them.
40
+ export const KNOWN_ERROR_CODES = ["not-authenticated", "binary-not-found", "permission-denied", "retry-exhausted"];
38
41
  export class KnownError extends ClaudeError {
39
42
  code;
40
43
  constructor(code, message) {
@@ -46,14 +49,20 @@ export class KnownError extends ClaudeError {
46
49
  export const isKnownError = (error) => {
47
50
  return error instanceof KnownError;
48
51
  };
49
- const TRANSIENT_PATTERN = /fetch failed|ECONNREFUSED|ETIMEDOUT|ECONNRESET|EAI_AGAIN|network error|network timeout|EPIPE|SIGPIPE|broken pipe/i;
52
+ // Network-level transients (ECONNRESET/REFUSED/ABORTED, ENETUNREACH, EHOSTUNREACH),
53
+ // DNS transients (EAI_AGAIN), pipe resets (EPIPE/SIGPIPE, broken pipe), fetch
54
+ // errors, ad-hoc "socket hang up" messages from node, and Anthropic
55
+ // overloaded_error which the CLI bubbles up verbatim for 529 responses.
56
+ const TRANSIENT_PATTERN = /fetch failed|ECONNREFUSED|ETIMEDOUT|ECONNRESET|ECONNABORTED|ENETUNREACH|EHOSTUNREACH|EAI_AGAIN|network error|network timeout|EPIPE|SIGPIPE|broken pipe|socket hang up|overloaded_error/i;
57
+ // Exit codes we treat as transient: 137 = SIGKILL (OOM), 141 = SIGPIPE,
58
+ // 143 = SIGTERM. Non-zero normal exits (e.g. 1) stay non-transient.
59
+ const TRANSIENT_EXIT_CODES = new Set([137, 141, 143]);
50
60
  export const isTransientError = (error) => {
51
61
  if (error instanceof AbortError || error instanceof BudgetExceededError) {
52
62
  return false;
53
63
  }
54
64
  if (error instanceof ProcessError) {
55
- const transientCodes = [137, 143];
56
- return error.exitCode !== undefined && transientCodes.includes(error.exitCode);
65
+ return error.exitCode !== undefined && TRANSIENT_EXIT_CODES.has(error.exitCode);
57
66
  }
58
67
  const message = errorMessage(error);
59
68
  return TRANSIENT_PATTERN.test(message);
@@ -61,8 +70,8 @@ export const isTransientError = (error) => {
61
70
  export const errorMessage = (error) => {
62
71
  return error instanceof Error ? error.message : String(error);
63
72
  };
64
- export const assertPositiveNumber = (value, name) => {
65
- if (value !== undefined && (!Number.isFinite(value) || value <= 0)) {
66
- throw new ClaudeError(`${name} must be a finite positive number`);
67
- }
68
- };
73
+ // Shared error factory for the "process died before emitting turn_complete"
74
+ // case. session.ts + stream.ts both need this; the string used to be
75
+ // duplicated verbatim, which drifted at least once. Prefix stderr when
76
+ // available because CLI error output is the most actionable signal.
77
+ export const processExitedEarly = (stderr, exitCode) => new ProcessError(stderr || "Process exited without completing the turn", exitCode);
package/dist/index.d.ts CHANGED
@@ -3,13 +3,14 @@ export { createClient } from "./client.js";
3
3
  export { BINARY, LIMITS, TIMEOUTS } from "./constants.js";
4
4
  export type { ICostTracker, ICostTrackerOptions } from "./cost.js";
5
5
  export { createCostTracker } from "./cost.js";
6
- export { AbortError, assertPositiveNumber, BudgetExceededError, ClaudeError, errorMessage, isKnownError, isTransientError, KnownError, ProcessError, TimeoutError, } from "./errors.js";
6
+ export type { TKnownErrorCode } from "./errors.js";
7
+ export { AbortError, BudgetExceededError, ClaudeError, errorMessage, isKnownError, isTransientError, KNOWN_ERROR_CODES, KnownError, ProcessError, TimeoutError, } from "./errors.js";
7
8
  export { blockFingerprint, extractContent, parseDoubleEncoded } from "./parser/content.js";
8
9
  export { parseLine } from "./parser/ndjson.js";
9
10
  export type { ITranslator } from "./parser/translator.js";
10
11
  export { createTranslator } from "./parser/translator.js";
11
12
  export type { IClaudeProcess, ISpawnOptions } from "./process.js";
12
- export { buildArgs, resetBinaryCache, spawnClaude } from "./process.js";
13
+ export { buildArgs, resetResolvedEnvCache, spawnClaude } from "./process.js";
13
14
  export type { IReaderOptions } from "./reader.js";
14
15
  export { readNdjsonEvents } from "./reader.js";
15
16
  export type { IClaudeSession } from "./session.js";
@@ -18,9 +19,10 @@ export type { IClaudeStream } from "./stream.js";
18
19
  export { createStream } from "./stream.js";
19
20
  export type { IToolHandlerInstance, TToolDecision } from "./tools/handler.js";
20
21
  export { createToolHandler } from "./tools/handler.js";
21
- export { BUILT_IN_TOOLS, isBuiltInTool } from "./tools/registry.js";
22
+ export type { TBuiltInToolName } from "./tools/registry.js";
23
+ export { BUILT_IN_TOOL_NAMES, BUILT_IN_TOOLS, isBuiltInTool } from "./tools/registry.js";
22
24
  export type { TErrorEvent, TRelayEvent, TSessionMetaEvent, TTextEvent, TThinkingEvent, TToolResultEvent, TToolUseEvent, TTurnCompleteEvent, } from "./types/events.js";
23
- export type { IClaudeOptions, ISessionOptions, IToolHandler } from "./types/options.js";
25
+ export type { IAskOptions, IClaudeOptions, ISessionOptions, IToolHandler } from "./types/options.js";
24
26
  export type { TClaudeContent, TClaudeContentType, TClaudeEvent, TClaudeEventType, TClaudeMessage, TModelUsageEntry } from "./types/protocol.js";
25
27
  export type { TAskResult, TCostSnapshot } from "./types/results.js";
26
28
  export { writer } from "./writer.js";
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
+ import { createClient } from "./client.js";
1
2
  export { createClient } from "./client.js";
2
3
  export { BINARY, LIMITS, TIMEOUTS } from "./constants.js";
3
4
  export { createCostTracker } from "./cost.js";
4
- export { AbortError, assertPositiveNumber, BudgetExceededError, ClaudeError, errorMessage, isKnownError, isTransientError, KnownError, ProcessError, TimeoutError, } from "./errors.js";
5
+ export { AbortError, BudgetExceededError, ClaudeError, errorMessage, isKnownError, isTransientError, KNOWN_ERROR_CODES, KnownError, ProcessError, TimeoutError, } from "./errors.js";
5
6
  export { blockFingerprint, extractContent, parseDoubleEncoded } from "./parser/content.js";
6
7
  export { parseLine } from "./parser/ndjson.js";
7
8
  export { createTranslator } from "./parser/translator.js";
8
- export { buildArgs, resetBinaryCache, spawnClaude } from "./process.js";
9
+ export { buildArgs, resetResolvedEnvCache, spawnClaude } from "./process.js";
9
10
  export { readNdjsonEvents } from "./reader.js";
10
11
  export { createSession } from "./session.js";
11
12
  export { createStream } from "./stream.js";
12
13
  export { createToolHandler } from "./tools/handler.js";
13
- export { BUILT_IN_TOOLS, isBuiltInTool } from "./tools/registry.js";
14
+ export { BUILT_IN_TOOL_NAMES, BUILT_IN_TOOLS, isBuiltInTool } from "./tools/registry.js";
14
15
  export { writer } from "./writer.js";
15
- import { createClient } from "./client.js";
16
16
  export const claude = createClient();
@@ -1,10 +1,11 @@
1
+ import { LIMITS } from "../constants.js";
1
2
  export const blockFingerprint = (block) => {
2
3
  if (block.type === "tool_use" && block.id) {
3
4
  return `tool_use:${block.id}`;
4
5
  }
5
6
  const text = block.type === "thinking" ? (block.thinking ?? block.text ?? "") : (block.text ?? "");
6
7
  if (text) {
7
- return `${block.type}:${text.slice(0, 64)}`;
8
+ return `${block.type}:${text.slice(0, LIMITS.fingerprintTextLen)}`;
8
9
  }
9
10
  return `${block.type}:${block.tool_use_id ?? "unknown"}`;
10
11
  };
@@ -17,7 +18,7 @@ export const extractContent = (content) => {
17
18
  }
18
19
  if (Array.isArray(content)) {
19
20
  return content
20
- .filter((block) => typeof block === "object" && block !== null && "text" in block)
21
+ .filter((block) => typeof block === "object" && block !== null && "text" in block && typeof block.text === "string")
21
22
  .map((block) => block.text)
22
23
  .join("\n");
23
24
  }
@@ -7,7 +7,12 @@ const extractTokens = (modelUsage) => {
7
7
  for (const entry of Object.values(modelUsage)) {
8
8
  inputTokens = (inputTokens ?? 0) + entry.inputTokens + (entry.cacheReadInputTokens ?? 0) + (entry.cacheCreationInputTokens ?? 0);
9
9
  outputTokens = (outputTokens ?? 0) + entry.outputTokens;
10
- contextWindow = entry.contextWindow;
10
+ // Multi-model turns (e.g. sub-agent fan-out) report distinct windows
11
+ // per model. Take max so consumers see the widest context available,
12
+ // not whichever model happened to iterate last.
13
+ if (entry.contextWindow !== undefined && (contextWindow === undefined || entry.contextWindow > contextWindow)) {
14
+ contextWindow = entry.contextWindow;
15
+ }
11
16
  }
12
17
  }
13
18
  return { inputTokens, outputTokens, contextWindow };
@@ -41,13 +46,15 @@ const translateContentBlock = (block) => {
41
46
  return undefined;
42
47
  }
43
48
  case "tool_use": {
44
- if (!block.id) {
49
+ // Drop malformed tool_use events entirely. An empty toolName would
50
+ // otherwise bypass allow/block lists by matching nothing.
51
+ if (!block.id || !block.name) {
45
52
  return undefined;
46
53
  }
47
54
  return {
48
55
  type: "tool_use",
49
56
  toolUseId: block.id,
50
- toolName: block.name ?? "",
57
+ toolName: block.name,
51
58
  input: typeof block.input === "string" ? block.input : JSON.stringify(block.input ?? {}),
52
59
  };
53
60
  }
@@ -1,8 +1,18 @@
1
1
  import type { ICostTracker } from "./cost.js";
2
- import type { IClaudeProcess } from "./process.js";
2
+ import type { IClaudeProcess, ISpawnOptions } from "./process.js";
3
+ import { type IStderrDrain } from "./reader.js";
3
4
  import type { IToolHandlerInstance } from "./tools/handler.js";
4
- import type { TRelayEvent, TToolUseEvent } from "./types/events.js";
5
- import type { TAskResult } from "./types/results.js";
6
- export declare const dispatchToolDecision: (proc: IClaudeProcess, toolHandler: IToolHandlerInstance, event: TToolUseEvent) => Promise<void>;
5
+ import type { TRelayEvent, TToolUseEvent, TTurnCompleteEvent } from "./types/events.js";
6
+ import type { TAskResult, TCostSnapshot } from "./types/results.js";
7
+ import type { TWarn } from "./warnings.js";
8
+ interface IPipeline {
9
+ proc: IClaudeProcess;
10
+ reader: ReadableStreamDefaultReader<Uint8Array>;
11
+ stderr: IStderrDrain;
12
+ }
13
+ export declare const startPipeline: (options: ISpawnOptions) => IPipeline;
14
+ export declare const dispatchToolDecision: (proc: IClaudeProcess, toolHandler: IToolHandlerInstance, event: TToolUseEvent, onWarning?: TWarn) => Promise<void>;
15
+ export declare const applyTurnComplete: (event: TTurnCompleteEvent, costTracker: ICostTracker, offsets?: TCostSnapshot) => void;
7
16
  export declare const extractText: (events: TRelayEvent[]) => string;
8
17
  export declare const buildResult: (events: TRelayEvent[], costTracker: ICostTracker, sessionId: string | undefined) => TAskResult;
18
+ export {};
package/dist/pipeline.js CHANGED
@@ -1,31 +1,51 @@
1
+ import { safeWrite, spawnClaude } from "./process.js";
2
+ import { drainStderr } from "./reader.js";
3
+ import { createWarn } from "./warnings.js";
1
4
  import { writer } from "./writer.js";
2
- export const dispatchToolDecision = async (proc, toolHandler, event) => {
5
+ // Shared process-boot: spawn the CLI, lock the stdout reader, drain
6
+ // stderr. session.ts and stream.ts both need this exact trio; keeping
7
+ // the order in one place prevents the "one forgot to drain stderr and
8
+ // the other swallows exits silently" class of bug.
9
+ export const startPipeline = (options) => {
10
+ const proc = spawnClaude(options);
11
+ const reader = proc.stdout.getReader();
12
+ const stderr = drainStderr(proc);
13
+ return { proc, reader, stderr };
14
+ };
15
+ export const dispatchToolDecision = async (proc, toolHandler, event, onWarning) => {
16
+ const warn = createWarn(onWarning);
3
17
  let decision;
4
18
  try {
5
19
  decision = await toolHandler.decide(event);
6
20
  }
7
21
  catch (error) {
8
- console.warn(`[claude-wire] Tool handler threw, defaulting to deny: ${error instanceof Error ? error.message : String(error)}`);
22
+ warn("Tool handler threw, defaulting to deny", error);
9
23
  decision = "deny";
10
24
  }
11
- try {
12
- if (decision === "approve") {
13
- proc.write(writer.approve(event.toolUseId));
14
- }
15
- else if (decision === "deny") {
16
- proc.write(writer.deny(event.toolUseId));
17
- }
18
- else if (typeof decision === "object" && decision !== null && typeof decision.result === "string") {
19
- proc.write(writer.toolResult(event.toolUseId, decision.result));
20
- }
21
- else {
22
- console.warn("[claude-wire] Invalid tool decision, defaulting to deny");
23
- proc.write(writer.deny(event.toolUseId));
24
- }
25
+ if (decision === "approve") {
26
+ safeWrite(proc, writer.approve(event.toolUseId));
27
+ }
28
+ else if (decision === "deny") {
29
+ safeWrite(proc, writer.deny(event.toolUseId));
25
30
  }
26
- catch {
27
- // stdin closed - process died, error will surface through read path
31
+ else if (typeof decision === "object" && decision !== null && typeof decision.result === "string") {
32
+ const isError = "isError" in decision ? decision.isError : undefined;
33
+ safeWrite(proc, writer.toolResult(event.toolUseId, decision.result, isError ? { isError: true } : undefined));
28
34
  }
35
+ else {
36
+ warn("Invalid tool decision, defaulting to deny");
37
+ safeWrite(proc, writer.deny(event.toolUseId));
38
+ }
39
+ };
40
+ // Applies a turn_complete event's cumulative totals to the cost tracker
41
+ // and enforces the budget. `offsets` covers session's respawn case where
42
+ // the new process starts its cumulative count from zero but the session
43
+ // wants to carry forward what previous processes already spent -- stream
44
+ // has no such concept and passes it undefined.
45
+ export const applyTurnComplete = (event, costTracker, offsets) => {
46
+ const base = offsets ?? { totalUsd: 0, inputTokens: 0, outputTokens: 0 };
47
+ costTracker.update(base.totalUsd + (event.costUsd ?? 0), base.inputTokens + (event.inputTokens ?? 0), base.outputTokens + (event.outputTokens ?? 0));
48
+ costTracker.checkBudget();
29
49
  };
30
50
  export const extractText = (events) => {
31
51
  return events
package/dist/process.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { IClaudeOptions } from "./types/options.js";
2
2
  export interface IClaudeProcess {
3
3
  write: (message: string) => void;
4
- kill: () => void;
4
+ kill: (signal?: NodeJS.Signals | number) => void;
5
5
  exited: Promise<number>;
6
6
  stdout: ReadableStream<Uint8Array>;
7
7
  stderr: ReadableStream<Uint8Array>;
@@ -10,6 +10,20 @@ export interface IClaudeProcess {
10
10
  export interface ISpawnOptions extends IClaudeOptions {
11
11
  prompt?: string;
12
12
  }
13
- export declare const resetBinaryCache: () => void;
13
+ export declare const safeKill: (proc: Pick<IClaudeProcess, "kill">, signal?: NodeJS.Signals | number) => void;
14
+ export declare const safeWrite: (proc: Pick<IClaudeProcess, "write">, line: string) => boolean;
15
+ export declare const ALIAS_PATTERN: RegExp;
16
+ /**
17
+ * Clears the cached resolved environment (binary path + alias-detected
18
+ * `CLAUDE_CONFIG_DIR`). Call this when either has changed mid-process -- for
19
+ * example after installing the Claude CLI during a test run, or when a long-
20
+ * running daemon updates the user's shell rc file. The next `spawnClaude()`
21
+ * will re-resolve from scratch.
22
+ *
23
+ * Normal applications should never need this; the cache is populated once at
24
+ * first use and kept for the process lifetime.
25
+ */
26
+ export declare const resetResolvedEnvCache: () => void;
14
27
  export declare const buildArgs: (options: ISpawnOptions, binaryPath: string) => string[];
28
+ export declare const buildSpawnEnv: (baseEnv: Record<string, string | undefined>, aliasConfigDir: string | undefined, options: Pick<ISpawnOptions, "configDir" | "env">) => Record<string, string | undefined> | undefined;
15
29
  export declare const spawnClaude: (options: ISpawnOptions) => IClaudeProcess;