@aaac/runtime 0.2.5 → 0.2.6
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/dist/adapters/adk-sdk.d.ts +1 -1
- package/dist/adapters/adk-sdk.js +1 -1
- package/dist/adapters/claude-agent-sdk.d.ts +1 -1
- package/dist/adapters/claude-agent-sdk.js +4 -1
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/openai-agents-sdk.d.ts +1 -1
- package/dist/adapters/openai-agents-sdk.js +1 -1
- package/dist/{chunk-3DDB34BU.js → chunk-D2UXESPT.js} +2 -2
- package/dist/chunk-D2UXESPT.js.map +1 -0
- package/dist/{chunk-MG2ULUX6.js → chunk-DEBCJKRX.js} +2 -2
- package/dist/{chunk-2INQL5TG.js → chunk-GWNXNSGL.js} +6 -5
- package/dist/chunk-GWNXNSGL.js.map +1 -0
- package/dist/{chunk-MSVIEEGR.js → chunk-HR2Q64AO.js} +29 -5
- package/dist/chunk-HR2Q64AO.js.map +1 -0
- package/dist/{chunk-FKAI54OM.js → chunk-QVMLALPF.js} +2 -2
- package/dist/{chunk-F5R46S7I.js → chunk-Y7NORFFM.js} +2 -2
- package/dist/claude-bundles/full.js +134 -133
- package/dist/claude-bundles/lean.js +5 -4
- package/dist/generator/index.d.ts +2 -2
- package/dist/generator/index.js +2 -2
- package/dist/{guardrail-hooks-CB23nhZV.d.ts → guardrail-hooks-B-qe4ebW.d.ts} +16 -3
- package/dist/{hook-protocol-CFnNudiV.d.ts → hook-protocol-BH86kCQB.d.ts} +2 -0
- package/dist/{hooks-lite-CoWWnCRH.d.ts → hooks-lite-DvZu9Jhx.d.ts} +2 -2
- package/dist/{index-BlSepCSZ.d.ts → index-C2DHitGz.d.ts} +9 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +27 -8
- package/dist/index.js.map +1 -1
- package/dist/lib/claude-native/hooks-lite.d.ts +3 -3
- package/dist/lib/claude-native/hooks-lite.js +3 -3
- package/dist/lib/claude-native/hooks-prompt.d.ts +4 -4
- package/dist/lib/claude-native/hooks-prompt.js +3 -3
- package/dist/lib/claude-native/index.d.ts +7 -7
- package/dist/lib/claude-native/index.js +6 -6
- package/dist/{navigation-context-B-RpUg3_.d.ts → navigation-context-D1NbiipT.d.ts} +1 -1
- package/dist/{workspace-user-prompt-submit-D11Iu0zO.d.ts → workspace-user-prompt-submit-aErGPoX4.d.ts} +2 -2
- package/package.json +4 -4
- package/dist/chunk-2INQL5TG.js.map +0 -1
- package/dist/chunk-3DDB34BU.js.map +0 -1
- package/dist/chunk-MSVIEEGR.js.map +0 -1
- /package/dist/{chunk-MG2ULUX6.js.map → chunk-DEBCJKRX.js.map} +0 -0
- /package/dist/{chunk-FKAI54OM.js.map → chunk-QVMLALPF.js.map} +0 -0
- /package/dist/{chunk-F5R46S7I.js.map → chunk-Y7NORFFM.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { S as SdkAdapter, C as CacheConfig, A as AdapterSendOptions, a as AgentExecutionRequest, M as MemoryRef, T as TokenUsage } from '../task-runner-37cFPFas.js';
|
|
2
|
-
import { G as GuardrailHooks } from '../guardrail-hooks-
|
|
2
|
+
import { G as GuardrailHooks } from '../guardrail-hooks-B-qe4ebW.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '@aaac/contracts';
|
|
5
5
|
import '@aaac/observability';
|
package/dist/adapters/adk-sdk.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { S as SdkAdapter, C as CacheConfig, A as AdapterSendOptions, a as AgentExecutionRequest, M as MemoryRef, T as TokenUsage } from '../task-runner-37cFPFas.js';
|
|
2
|
-
import { G as GuardrailHooks } from '../guardrail-hooks-
|
|
2
|
+
import { G as GuardrailHooks } from '../guardrail-hooks-B-qe4ebW.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '@aaac/contracts';
|
|
5
5
|
import '@aaac/observability';
|
|
@@ -23,7 +23,10 @@ function buildClaudeHooks(guardrails) {
|
|
|
23
23
|
if (toolName === "Bash" || toolName === "Shell") {
|
|
24
24
|
const command = toolInput?.command ?? toolInput?.input;
|
|
25
25
|
if (command) {
|
|
26
|
-
const result = guardrails.beforeShellExecution({
|
|
26
|
+
const result = guardrails.beforeShellExecution({
|
|
27
|
+
command,
|
|
28
|
+
cwd: input.cwd
|
|
29
|
+
});
|
|
27
30
|
if (result.permission === "deny") {
|
|
28
31
|
return {
|
|
29
32
|
hookEventName: "PreToolUse",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/claude-agent-sdk.ts"],"sourcesContent":["/**\n * Claude Agent SDK Adapter — implements SdkAdapter for @anthropic-ai/claude-agent-sdk\n *\n * Uses the `query()` function from the Claude Agent SDK to run Claude as a\n * stateful coding agent with tool execution (Read, Edit, Bash, etc.).\n *\n * Supports:\n * - send() — start a new query session and return the result text\n * - followUp() — resume the same session for output-format corrections\n * - sendExecution() — rich path using full contract context\n *\n * The SDK returns an AsyncGenerator of SDKMessage events. The adapter iterates\n * the stream, extracts the final result text from the SDKResultSuccess message,\n * and captures the session_id for followUp via `resume`.\n *\n * GuardrailHooks are mapped to the SDK's PreToolUse hook system.\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n AgentProgressEvent,\n CacheConfig,\n CandidateAgent,\n} from \"../lib/task-runner.js\";\nimport type { ObserverEmitFn, TokenUsage } from \"../lib/observability-bridge.js\";\nimport {\n emitLlmTurnOpen,\n emitLlmTurnClose,\n emitToolExecOpen,\n emitToolExecClose,\n} from \"../lib/observability-bridge.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\nimport { DELEGATION_TOOL_NAMES, toolGrantForMode } from \"../lib/claude-tool-grants.js\";\nimport type { MemoryRef } from \"../lib/memory-store.js\";\nimport type { LibraryToolRegistry } from \"../lib/library-tool-binding.js\";\nimport { buildClaudeMcpServer, type McpObservabilityContext } from \"../lib/library-tool-sdk.js\";\nimport { ContextPackAdoptionTracker } from \"../lib/context-pack-adoption.js\";\nimport { ToolExecSpanRegistry } from \"../lib/tool-exec-span-registry.js\";\n\n/**\n * Subset of the Claude Agent SDK `AgentDefinition` shape we populate.\n * Verified against node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts:38\n * (`description`, `prompt`, optional `tools`, `model`).\n */\ntype ClaudeAgentDefinition = {\n description: string;\n prompt: string;\n tools?: string[];\n model?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on zod v4)\n// ---------------------------------------------------------------------------\n\ntype SDKResultSuccess = {\n type: \"result\";\n subtype: \"success\";\n result: string;\n session_id: string;\n};\n\ntype SDKResultError = {\n type: \"result\";\n subtype: \"error\";\n error: string;\n session_id: string;\n};\n\ntype SDKContentBlock = {\n type: string;\n name?: string;\n text?: string;\n input?: unknown;\n};\n\ntype SDKBetaMessage = {\n content?: SDKContentBlock[];\n};\n\ntype SDKMessage = {\n type: string;\n subtype?: string;\n result?: string;\n error?: string;\n session_id?: string;\n tool_name?: string;\n summary?: string;\n message?: SDKBetaMessage;\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n cache_read_input_tokens?: number;\n cache_creation_input_tokens?: number;\n };\n};\n\ntype HookCallbackInput = {\n hook_event_name: string;\n tool_name: string;\n tool_input: unknown;\n [key: string]: unknown;\n};\n\ntype HookCallbackOutput = {\n hookEventName: string;\n permissionDecision?: \"allow\" | \"deny\" | \"ask\";\n permissionDecisionReason?: string;\n additionalContext?: string;\n};\n\ntype HookCallbackMatcher = {\n tool_name?: string;\n hooks: Array<(input: HookCallbackInput) => HookCallbackOutput | Promise<HookCallbackOutput>>;\n};\n\ntype QueryOptions = Record<string, unknown>;\n\ntype QueryFn = (params: {\n prompt: string;\n options?: QueryOptions;\n}) => AsyncGenerator<SDKMessage, void>;\n\n// ---------------------------------------------------------------------------\n// Guardrail hook bridge\n// ---------------------------------------------------------------------------\n\nfunction buildClaudeHooks(\n guardrails: GuardrailHooks,\n): Partial<Record<string, HookCallbackMatcher[]>> {\n const preToolUseHook: HookCallbackMatcher = {\n hooks: [\n (input: HookCallbackInput): HookCallbackOutput => {\n const toolInput = input.tool_input as Record<string, unknown> | undefined;\n const toolName = input.tool_name;\n\n if (toolName === \"Bash\" || toolName === \"Shell\") {\n const command = (toolInput?.command ?? toolInput?.input) as string | undefined;\n if (command) {\n const result = guardrails.beforeShellExecution({ command });\n if (result.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: result.user_message,\n };\n }\n if (result.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: result.additionalContext };\n }\n }\n }\n\n // Passed verbatim. Re-extracting the path here and handing `preToolUse`\n // a synthesised `{ file_path }` meant this adapter decided which keys\n // name a file — a decision `toolTargetPath` owns — and it knew fewer of\n // them than the tools write (#309). `preToolUse` answers `{}` when the\n // call names no file, so there is nothing to pre-check.\n const pathResult = guardrails.preToolUse({\n tool_name: toolName,\n tool_input: toolInput,\n });\n if (pathResult.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: pathResult.user_message,\n };\n }\n if (pathResult.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: pathResult.additionalContext };\n }\n\n return { hookEventName: \"PreToolUse\" };\n },\n ],\n };\n\n return { PreToolUse: [preToolUseHook] };\n}\n\n// ---------------------------------------------------------------------------\n// Input summary truncation\n// ---------------------------------------------------------------------------\n\nfunction truncateInputSummary(input: unknown, maxLen = 80): string {\n if (input == null) return \"\";\n let str: string;\n if (typeof input === \"string\") {\n str = input;\n } else {\n try { str = JSON.stringify(input); } catch { str = String(input); }\n }\n return str.length > maxLen ? str.slice(0, maxLen - 3) + \"...\" : str;\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface ClaudeAgentSdkAdapterConfig {\n /** Working directory for the agent. Defaults to process.cwd(). */\n cwd?: string;\n /** Model identifier (e.g. \"claude-sonnet-4-20250514\"). Uses SDK default if omitted. */\n model?: string;\n /**\n * Available tools. Defaults to read-only or read-write set based on AdapterSendOptions.\n * Set to `{ type: 'preset', preset: 'claude_code' }` for all Claude Code tools.\n */\n tools?: string[] | { type: \"preset\"; preset: \"claude_code\" };\n /** Permission mode. Defaults to \"bypassPermissions\" for automated workflows. */\n permissionMode?: \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n /** Max turns before stopping. */\n maxTurns?: number;\n /** Runtime guardrail hooks enforced via PreToolUse SDK hooks. */\n guardrailHooks?: GuardrailHooks;\n /** Prompt caching configuration. Enabled by default. */\n cacheConfig?: CacheConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class ClaudeAgentSdkAdapter implements SdkAdapter {\n private cwd: string;\n private model: string | undefined;\n private tools: string[] | { type: \"preset\"; preset: \"claude_code\" } | undefined;\n private permissionMode: string;\n private maxTurns: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private cacheConfig: CacheConfig;\n private lastSessionId: string | null = null;\n private lastMemoryRef: MemoryRef | null = null;\n private lastTokenUsage: TokenUsage | null = null;\n private queryFn: QueryFn | null = null;\n\n constructor(config: ClaudeAgentSdkAdapterConfig = {}) {\n this.cwd = config.cwd ?? process.cwd();\n this.model = config.model;\n this.tools = config.tools;\n this.permissionMode = config.permissionMode ?? \"bypassPermissions\";\n this.maxTurns = config.maxTurns;\n this.guardrailHooks = config.guardrailHooks;\n this.cacheConfig = config.cacheConfig ?? { enabled: true };\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveQueryFn(): Promise<QueryFn> {\n if (this.queryFn) return this.queryFn;\n\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as {\n query: QueryFn;\n };\n this.queryFn = sdk.query;\n return this.queryFn;\n }\n\n private buildOptions(\n readonly: boolean,\n resume?: string,\n systemPrompt?: string[],\n agents?: CandidateAgent[],\n allowDynamicWorkflow?: boolean,\n ): QueryOptions {\n const opts: QueryOptions = {\n cwd: this.cwd,\n permissionMode: this.permissionMode,\n allowDangerouslySkipPermissions: this.permissionMode === \"bypassPermissions\",\n // SDK isolation: do not load ambient .claude/ settings, skills, or agents\n // from disk. The runtime injects everything in-code, so disk discovery\n // would break component isolation and reproducibility.\n settingSources: [],\n };\n\n if (this.model) opts.model = this.model;\n if (this.maxTurns) opts.maxTurns = this.maxTurns;\n\n let toolList: string[] | { type: \"preset\"; preset: \"claude_code\" };\n if (this.tools) {\n toolList = Array.isArray(this.tools) ? [...this.tools] : this.tools;\n } else {\n // `readonly` is `agentContract.mode === \"read-only\"` (task-runner.ts).\n // The mode → Claude Code tool grant is shared with the materialized\n // `.claude/agents/*.md` subagents so both mean the same thing (#272).\n toolList = [...toolGrantForMode(readonly ? \"read-only\" : \"read-write\")];\n }\n\n // When candidate sub-agents are registered (model B), the entry agent needs\n // the sub-agent delegation tool to invoke them. The restricted tool list\n // above omits it, so add it explicitly — otherwise the LLM has no way to\n // delegate. The tool names are shared with the materialized subagent\n // frontmatter (#272). (A \"preset\" tools config already includes it.)\n if (agents && agents.length > 0 && Array.isArray(toolList)) {\n for (const t of DELEGATION_TOOL_NAMES) {\n if (!toolList.includes(t)) toolList.push(t);\n }\n }\n\n if (allowDynamicWorkflow && Array.isArray(toolList)) {\n if (!toolList.includes(\"Workflow\")) toolList.push(\"Workflow\");\n }\n opts.tools = toolList;\n\n if (resume) opts.resume = resume;\n\n if (systemPrompt && this.cacheConfig.enabled !== false) {\n opts.systemPrompt = systemPrompt;\n }\n\n // Register candidate sub-agents so the LLM can delegate via the Agent/Task\n // tool (model B, LLM-internal routing). Keyed by candidate name.\n if (agents && agents.length > 0) {\n const record: Record<string, ClaudeAgentDefinition> = {};\n for (const a of agents) {\n record[a.name] = {\n description: a.description,\n prompt: a.prompt,\n ...(a.tools ? { tools: a.tools } : {}),\n ...(a.model ? { model: a.model } : {}),\n };\n }\n opts.agents = record;\n }\n\n if (this.guardrailHooks) {\n opts.hooks = buildClaudeHooks(this.guardrailHooks);\n }\n\n return opts;\n }\n\n private async attachLibraryTools(\n opts: QueryOptions,\n libraryTools?: LibraryToolRegistry,\n observability?: McpObservabilityContext,\n ): Promise<void> {\n if (!libraryTools || libraryTools.getAll().length === 0) return;\n\n try {\n const server = await buildClaudeMcpServer(libraryTools, observability);\n if (server) {\n const existing = (opts.mcpServers ?? []) as unknown[];\n opts.mcpServers = [...existing, server];\n }\n } catch {\n // SDK functions unavailable; library tools silently skipped for Claude\n }\n }\n\n private createMcpObservability(\n observer?: ObserverEmitFn,\n sessionId?: string,\n ): McpObservabilityContext | undefined {\n if (!observer) return undefined;\n return {\n observer,\n sessionId,\n spanRegistry: new ToolExecSpanRegistry(),\n adoptionTracker: new ContextPackAdoptionTracker(),\n };\n }\n\n private async runQuery(\n prompt: string,\n options: QueryOptions,\n onProgress?: (event: AgentProgressEvent) => void,\n observer?: ObserverEmitFn,\n parentSpanId?: string,\n agentSessionId?: string,\n mcpObservability?: McpObservabilityContext,\n ): Promise<{ text: string; sessionId: string; tokenUsage?: TokenUsage }> {\n const queryFn = await this.resolveQueryFn();\n const stream = queryFn({ prompt, options });\n\n let resultText = \"\";\n let sessionId = \"\";\n\n // Token usage accumulation across all messages in this query\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalCacheReadTokens = 0;\n let totalCacheCreationTokens = 0;\n let hasUsageData = false;\n\n // Inner turn-level instrumentation state\n let turnNumber = 0;\n let currentTurnSpanId: string | undefined;\n let currentTurnStart = 0;\n let toolCallsInTurn = 0;\n let turnInputTokens = 0;\n let turnOutputTokens = 0;\n let turnCacheHitTokens = 0;\n const openToolSpans: Array<{ spanId: string; toolName: string; startMs: number }> = [];\n\n const closePendingToolSpans = (): void => {\n for (const ts of openToolSpans) {\n if (mcpObservability?.spanRegistry?.isClosed(ts.spanId)) continue;\n emitToolExecClose(observer, ts.spanId, ts.toolName, Date.now() - ts.startMs, agentSessionId);\n }\n openToolSpans.length = 0;\n };\n\n const closeCurrentTurn = (): void => {\n if (currentTurnSpanId) {\n emitLlmTurnClose(observer, currentTurnSpanId, turnNumber, Date.now() - currentTurnStart, {\n inputTokens: turnInputTokens || undefined,\n outputTokens: turnOutputTokens || undefined,\n cacheHitTokens: turnCacheHitTokens || undefined,\n toolCallsCount: toolCallsInTurn || undefined,\n }, agentSessionId);\n currentTurnSpanId = undefined;\n }\n };\n\n const captureUsage = (usage: SDKMessage[\"usage\"], perTurn = true): void => {\n if (!usage) return;\n if (typeof usage.input_tokens === \"number\") {\n totalInputTokens += usage.input_tokens;\n if (perTurn) turnInputTokens += usage.input_tokens;\n hasUsageData = true;\n }\n if (typeof usage.output_tokens === \"number\") {\n totalOutputTokens += usage.output_tokens;\n if (perTurn) turnOutputTokens += usage.output_tokens;\n hasUsageData = true;\n }\n if (typeof usage.cache_read_input_tokens === \"number\") {\n totalCacheReadTokens += usage.cache_read_input_tokens;\n if (perTurn) turnCacheHitTokens += usage.cache_read_input_tokens;\n hasUsageData = true;\n }\n if (typeof usage.cache_creation_input_tokens === \"number\") {\n totalCacheCreationTokens += usage.cache_creation_input_tokens;\n hasUsageData = true;\n }\n };\n\n for await (const message of stream) {\n if (message.session_id) sessionId = message.session_id;\n\n if (message.type === \"result\") {\n if (message.usage) {\n if (turnInputTokens === 0 && typeof message.usage.input_tokens === \"number\") {\n turnInputTokens = message.usage.input_tokens;\n }\n if (turnOutputTokens === 0 && typeof message.usage.output_tokens === \"number\") {\n turnOutputTokens = message.usage.output_tokens;\n }\n if (turnCacheHitTokens === 0 && typeof message.usage.cache_read_input_tokens === \"number\") {\n turnCacheHitTokens = message.usage.cache_read_input_tokens;\n }\n }\n captureUsage(message.usage, false);\n closePendingToolSpans();\n closeCurrentTurn();\n if (message.subtype === \"success\") {\n resultText = (message as SDKResultSuccess).result;\n } else if (message.subtype === \"error\") {\n throw new Error(`Claude Agent SDK error: ${(message as SDKResultError).error}`);\n }\n } else if (message.type === \"assistant\") {\n closePendingToolSpans();\n closeCurrentTurn();\n\n turnNumber++;\n toolCallsInTurn = 0;\n turnInputTokens = 0;\n turnOutputTokens = 0;\n turnCacheHitTokens = 0;\n currentTurnStart = Date.now();\n currentTurnSpanId = emitLlmTurnOpen(observer, parentSpanId, turnNumber, this.model, undefined, agentSessionId);\n\n captureUsage(message.usage);\n\n const content = message.message?.content;\n if (content) {\n for (const block of content) {\n if (block.type === \"tool_use\" && block.name) {\n toolCallsInTurn++;\n const summary = truncateInputSummary(block.input);\n const adoption = mcpObservability?.adoptionTracker?.evaluate(\n agentSessionId,\n block.name,\n block.input,\n );\n const openOpts = adoption\n ? {\n sessionId: agentSessionId,\n extraAttributes: {\n \"tool.adoption.kind\": adoption.kind,\n \"tool.context_pack_id\": adoption.contextPackId,\n },\n links: adoption.links,\n }\n : agentSessionId;\n const toolSpanId = emitToolExecOpen(\n observer,\n currentTurnSpanId,\n block.name,\n summary,\n turnNumber,\n openOpts,\n );\n if (toolSpanId) {\n const entry = { spanId: toolSpanId, toolName: block.name, startMs: Date.now() };\n openToolSpans.push(entry);\n mcpObservability?.spanRegistry?.register(entry);\n }\n }\n }\n }\n\n if (onProgress) {\n emitProgressFromSdkMessage(message, onProgress, sessionId);\n }\n } else {\n captureUsage(message.usage);\n if (onProgress) {\n emitProgressFromSdkMessage(message, onProgress, sessionId);\n }\n }\n }\n\n closePendingToolSpans();\n closeCurrentTurn();\n\n const tokenUsage: TokenUsage | undefined = hasUsageData\n ? {\n inputTokens: totalInputTokens,\n outputTokens: totalOutputTokens,\n totalTokens: totalInputTokens + totalOutputTokens,\n ...(totalCacheReadTokens > 0 ? { cacheReadTokens: totalCacheReadTokens } : {}),\n ...(totalCacheCreationTokens > 0 ? { cacheCreationTokens: totalCacheCreationTokens } : {}),\n }\n : undefined;\n\n return { text: resultText, sessionId, tokenUsage };\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n options: AdapterSendOptions,\n ): Promise<string> {\n this.lastSessionId = null;\n this.lastMemoryRef = null;\n this.lastTokenUsage = null;\n\n const split = options.splitPrompt;\n const systemPrompt = split?.system;\n const userPrompt = split ? split.user : prompt;\n const opts = this.buildOptions(options.readonly, undefined, systemPrompt, options.agents, options.allowDynamicWorkflow);\n const mcpObservability = this.createMcpObservability(options.observer, options.sessionId);\n await this.attachLibraryTools(opts, options.libraryTools, mcpObservability);\n const { text, sessionId, tokenUsage } = await this.runQuery(\n userPrompt,\n opts,\n options.onProgress,\n options.observer,\n options.parentSpanId,\n options.sessionId,\n mcpObservability,\n );\n\n this.lastSessionId = sessionId;\n this.lastTokenUsage = tokenUsage ?? null;\n this.lastMemoryRef = {\n id: sessionId,\n provider: \"claude-agent-sdk\",\n compat: \"claude-agent-sdk@0.2\",\n created_at: new Date().toISOString(),\n };\n return text;\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastSessionId) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n const opts = this.buildOptions(false, this.lastSessionId);\n const { text, sessionId, tokenUsage } = await this.runQuery(message, opts);\n this.lastSessionId = sessionId;\n if (tokenUsage) {\n this.lastTokenUsage = this.lastTokenUsage\n ? {\n inputTokens: this.lastTokenUsage.inputTokens + tokenUsage.inputTokens,\n outputTokens: this.lastTokenUsage.outputTokens + tokenUsage.outputTokens,\n totalTokens: (this.lastTokenUsage.totalTokens ?? 0) + (tokenUsage.totalTokens ?? 0),\n cacheReadTokens: (this.lastTokenUsage.cacheReadTokens ?? 0) + (tokenUsage.cacheReadTokens ?? 0) || undefined,\n cacheCreationTokens: (this.lastTokenUsage.cacheCreationTokens ?? 0) + (tokenUsage.cacheCreationTokens ?? 0) || undefined,\n }\n : tokenUsage;\n }\n return text;\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastSessionId = null;\n this.lastMemoryRef = null;\n this.lastTokenUsage = null;\n\n const resume = request.memoryRef?.id;\n const split = request.splitPrompt;\n const systemPrompt = split?.system;\n const userPrompt = split ? split.user : request.prompt;\n const agents = request.options.agents ?? request.agents;\n const opts = this.buildOptions(request.options.readonly, resume, systemPrompt, agents, request.options.allowDynamicWorkflow);\n const mcpObservability = this.createMcpObservability(\n request.options.observer,\n request.options.sessionId,\n );\n await this.attachLibraryTools(opts, request.options.libraryTools, mcpObservability);\n const { text, sessionId, tokenUsage } = await this.runQuery(\n userPrompt,\n opts,\n request.options.onProgress,\n request.options.observer,\n request.options.parentSpanId,\n request.options.sessionId,\n mcpObservability,\n );\n\n this.lastSessionId = sessionId;\n this.lastTokenUsage = tokenUsage ?? null;\n this.lastMemoryRef = {\n id: sessionId,\n provider: \"claude-agent-sdk\",\n compat: \"claude-agent-sdk@0.2\",\n created_at: new Date().toISOString(),\n parent_run_id: request.memoryRef?.id,\n };\n return text;\n }\n\n getLastMemoryRef(): MemoryRef | null {\n return this.lastMemoryRef;\n }\n\n getLastTokenUsage(): TokenUsage | null {\n return this.lastTokenUsage;\n }\n\n isCompatible(compat: string): boolean {\n return compat.startsWith(\"claude-agent-sdk@\");\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject a custom query function for testing.\n * Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.\n */\n static withQueryFn(\n queryFn: QueryFn,\n config?: ClaudeAgentSdkAdapterConfig,\n ): ClaudeAgentSdkAdapter {\n const adapter = new ClaudeAgentSdkAdapter(config);\n adapter.queryFn = queryFn;\n return adapter;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Progress event mapping\n// ---------------------------------------------------------------------------\n\nfunction emitProgressFromSdkMessage(\n message: SDKMessage,\n onProgress: (event: AgentProgressEvent) => void,\n sessionId?: string,\n): void {\n const sid = message.session_id ?? sessionId;\n switch (message.type) {\n case \"assistant\": {\n const content = message.message?.content;\n if (!content) break;\n for (const block of content) {\n if (block.type === \"tool_use\" && block.name) {\n const input = block.input && typeof block.input === \"object\"\n ? block.input as Record<string, unknown>\n : undefined;\n onProgress({ type: \"tool_use\", tool_name: block.name, input, session_id: sid });\n } else if (block.type === \"text\" && block.text) {\n onProgress({ type: \"text\", message: block.text, session_id: sid });\n }\n }\n break;\n }\n case \"tool_progress\":\n if (message.tool_name) {\n onProgress({ type: \"tool_use\", tool_name: message.tool_name, session_id: sid });\n }\n break;\n case \"tool_use_summary\":\n if (message.summary) {\n onProgress({ type: \"status\", message: message.summary, session_id: sid });\n }\n break;\n default:\n break;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiIA,SAAS,iBACP,YACgD;AAChD,QAAM,iBAAsC;AAAA,IAC1C,OAAO;AAAA,MACL,CAAC,UAAiD;AAChD,cAAM,YAAY,MAAM;AACxB,cAAM,WAAW,MAAM;AAEvB,YAAI,aAAa,UAAU,aAAa,SAAS;AAC/C,gBAAM,UAAW,WAAW,WAAW,WAAW;AAClD,cAAI,SAAS;AACX,kBAAM,SAAS,WAAW,qBAAqB,EAAE,QAAQ,CAAC;AAC1D,gBAAI,OAAO,eAAe,QAAQ;AAChC,qBAAO;AAAA,gBACL,eAAe;AAAA,gBACf,oBAAoB;AAAA,gBACpB,0BAA0B,OAAO;AAAA,cACnC;AAAA,YACF;AACA,gBAAI,OAAO,mBAAmB;AAC5B,qBAAO,EAAE,eAAe,cAAc,mBAAmB,OAAO,kBAAkB;AAAA,YACpF;AAAA,UACF;AAAA,QACF;AAOA,cAAM,aAAa,WAAW,WAAW;AAAA,UACvC,WAAW;AAAA,UACX,YAAY;AAAA,QACd,CAAC;AACD,YAAI,WAAW,eAAe,QAAQ;AACpC,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,oBAAoB;AAAA,YACpB,0BAA0B,WAAW;AAAA,UACvC;AAAA,QACF;AACA,YAAI,WAAW,mBAAmB;AAChC,iBAAO,EAAE,eAAe,cAAc,mBAAmB,WAAW,kBAAkB;AAAA,QACxF;AAEA,eAAO,EAAE,eAAe,aAAa;AAA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AAAA,MAChF;AACA;AAAA,IACF,KAAK;AACH,UAAI,QAAQ,SAAS;AACnB,mBAAW,EAAE,MAAM,UAAU,SAAS,QAAQ,SAAS,YAAY,IAAI,CAAC;AAAA,MAC1E;AACA;AAAA,IACF;AACE;AAAA,EACJ;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/claude-agent-sdk.ts"],"sourcesContent":["/**\n * Claude Agent SDK Adapter — implements SdkAdapter for @anthropic-ai/claude-agent-sdk\n *\n * Uses the `query()` function from the Claude Agent SDK to run Claude as a\n * stateful coding agent with tool execution (Read, Edit, Bash, etc.).\n *\n * Supports:\n * - send() — start a new query session and return the result text\n * - followUp() — resume the same session for output-format corrections\n * - sendExecution() — rich path using full contract context\n *\n * The SDK returns an AsyncGenerator of SDKMessage events. The adapter iterates\n * the stream, extracts the final result text from the SDKResultSuccess message,\n * and captures the session_id for followUp via `resume`.\n *\n * GuardrailHooks are mapped to the SDK's PreToolUse hook system.\n */\n\nimport type {\n SdkAdapter,\n AdapterSendOptions,\n AgentExecutionRequest,\n AgentProgressEvent,\n CacheConfig,\n CandidateAgent,\n} from \"../lib/task-runner.js\";\nimport type { ObserverEmitFn, TokenUsage } from \"../lib/observability-bridge.js\";\nimport {\n emitLlmTurnOpen,\n emitLlmTurnClose,\n emitToolExecOpen,\n emitToolExecClose,\n} from \"../lib/observability-bridge.js\";\nimport type { GuardrailHooks } from \"../lib/guardrail-hooks.js\";\nimport { DELEGATION_TOOL_NAMES, toolGrantForMode } from \"../lib/claude-tool-grants.js\";\nimport type { MemoryRef } from \"../lib/memory-store.js\";\nimport type { LibraryToolRegistry } from \"../lib/library-tool-binding.js\";\nimport { buildClaudeMcpServer, type McpObservabilityContext } from \"../lib/library-tool-sdk.js\";\nimport { ContextPackAdoptionTracker } from \"../lib/context-pack-adoption.js\";\nimport { ToolExecSpanRegistry } from \"../lib/tool-exec-span-registry.js\";\n\n/**\n * Subset of the Claude Agent SDK `AgentDefinition` shape we populate.\n * Verified against node_modules/@anthropic-ai/claude-agent-sdk/sdk.d.ts:38\n * (`description`, `prompt`, optional `tools`, `model`).\n */\ntype ClaudeAgentDefinition = {\n description: string;\n prompt: string;\n tools?: string[];\n model?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Duck-typed SDK types (avoid hard compile-time dependency on zod v4)\n// ---------------------------------------------------------------------------\n\ntype SDKResultSuccess = {\n type: \"result\";\n subtype: \"success\";\n result: string;\n session_id: string;\n};\n\ntype SDKResultError = {\n type: \"result\";\n subtype: \"error\";\n error: string;\n session_id: string;\n};\n\ntype SDKContentBlock = {\n type: string;\n name?: string;\n text?: string;\n input?: unknown;\n};\n\ntype SDKBetaMessage = {\n content?: SDKContentBlock[];\n};\n\ntype SDKMessage = {\n type: string;\n subtype?: string;\n result?: string;\n error?: string;\n session_id?: string;\n tool_name?: string;\n summary?: string;\n message?: SDKBetaMessage;\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n cache_read_input_tokens?: number;\n cache_creation_input_tokens?: number;\n };\n};\n\ntype HookCallbackInput = {\n hook_event_name: string;\n tool_name: string;\n tool_input: unknown;\n [key: string]: unknown;\n};\n\ntype HookCallbackOutput = {\n hookEventName: string;\n permissionDecision?: \"allow\" | \"deny\" | \"ask\";\n permissionDecisionReason?: string;\n additionalContext?: string;\n};\n\ntype HookCallbackMatcher = {\n tool_name?: string;\n hooks: Array<(input: HookCallbackInput) => HookCallbackOutput | Promise<HookCallbackOutput>>;\n};\n\ntype QueryOptions = Record<string, unknown>;\n\ntype QueryFn = (params: {\n prompt: string;\n options?: QueryOptions;\n}) => AsyncGenerator<SDKMessage, void>;\n\n// ---------------------------------------------------------------------------\n// Guardrail hook bridge\n// ---------------------------------------------------------------------------\n\nfunction buildClaudeHooks(\n guardrails: GuardrailHooks,\n): Partial<Record<string, HookCallbackMatcher[]>> {\n const preToolUseHook: HookCallbackMatcher = {\n hooks: [\n (input: HookCallbackInput): HookCallbackOutput => {\n const toolInput = input.tool_input as Record<string, unknown> | undefined;\n const toolName = input.tool_name;\n\n if (toolName === \"Bash\" || toolName === \"Shell\") {\n const command = (toolInput?.command ?? toolInput?.input) as string | undefined;\n if (command) {\n const result = guardrails.beforeShellExecution({\n command,\n cwd: input.cwd as string | undefined,\n });\n if (result.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: result.user_message,\n };\n }\n if (result.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: result.additionalContext };\n }\n }\n }\n\n // Passed verbatim. Re-extracting the path here and handing `preToolUse`\n // a synthesised `{ file_path }` meant this adapter decided which keys\n // name a file — a decision `toolTargetPath` owns — and it knew fewer of\n // them than the tools write (#309). `preToolUse` answers `{}` when the\n // call names no file, so there is nothing to pre-check.\n const pathResult = guardrails.preToolUse({\n tool_name: toolName,\n tool_input: toolInput,\n });\n if (pathResult.permission === \"deny\") {\n return {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: pathResult.user_message,\n };\n }\n if (pathResult.additionalContext) {\n return { hookEventName: \"PreToolUse\", additionalContext: pathResult.additionalContext };\n }\n\n return { hookEventName: \"PreToolUse\" };\n },\n ],\n };\n\n return { PreToolUse: [preToolUseHook] };\n}\n\n// ---------------------------------------------------------------------------\n// Input summary truncation\n// ---------------------------------------------------------------------------\n\nfunction truncateInputSummary(input: unknown, maxLen = 80): string {\n if (input == null) return \"\";\n let str: string;\n if (typeof input === \"string\") {\n str = input;\n } else {\n try { str = JSON.stringify(input); } catch { str = String(input); }\n }\n return str.length > maxLen ? str.slice(0, maxLen - 3) + \"...\" : str;\n}\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport interface ClaudeAgentSdkAdapterConfig {\n /** Working directory for the agent. Defaults to process.cwd(). */\n cwd?: string;\n /** Model identifier (e.g. \"claude-sonnet-4-20250514\"). Uses SDK default if omitted. */\n model?: string;\n /**\n * Available tools. Defaults to read-only or read-write set based on AdapterSendOptions.\n * Set to `{ type: 'preset', preset: 'claude_code' }` for all Claude Code tools.\n */\n tools?: string[] | { type: \"preset\"; preset: \"claude_code\" };\n /** Permission mode. Defaults to \"bypassPermissions\" for automated workflows. */\n permissionMode?: \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n /** Max turns before stopping. */\n maxTurns?: number;\n /** Runtime guardrail hooks enforced via PreToolUse SDK hooks. */\n guardrailHooks?: GuardrailHooks;\n /** Prompt caching configuration. Enabled by default. */\n cacheConfig?: CacheConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport class ClaudeAgentSdkAdapter implements SdkAdapter {\n private cwd: string;\n private model: string | undefined;\n private tools: string[] | { type: \"preset\"; preset: \"claude_code\" } | undefined;\n private permissionMode: string;\n private maxTurns: number | undefined;\n private guardrailHooks: GuardrailHooks | undefined;\n private cacheConfig: CacheConfig;\n private lastSessionId: string | null = null;\n private lastMemoryRef: MemoryRef | null = null;\n private lastTokenUsage: TokenUsage | null = null;\n private queryFn: QueryFn | null = null;\n\n constructor(config: ClaudeAgentSdkAdapterConfig = {}) {\n this.cwd = config.cwd ?? process.cwd();\n this.model = config.model;\n this.tools = config.tools;\n this.permissionMode = config.permissionMode ?? \"bypassPermissions\";\n this.maxTurns = config.maxTurns;\n this.guardrailHooks = config.guardrailHooks;\n this.cacheConfig = config.cacheConfig ?? { enabled: true };\n }\n\n // -------------------------------------------------------------------------\n // Internal helpers\n // -------------------------------------------------------------------------\n\n private async resolveQueryFn(): Promise<QueryFn> {\n if (this.queryFn) return this.queryFn;\n\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as {\n query: QueryFn;\n };\n this.queryFn = sdk.query;\n return this.queryFn;\n }\n\n private buildOptions(\n readonly: boolean,\n resume?: string,\n systemPrompt?: string[],\n agents?: CandidateAgent[],\n allowDynamicWorkflow?: boolean,\n ): QueryOptions {\n const opts: QueryOptions = {\n cwd: this.cwd,\n permissionMode: this.permissionMode,\n allowDangerouslySkipPermissions: this.permissionMode === \"bypassPermissions\",\n // SDK isolation: do not load ambient .claude/ settings, skills, or agents\n // from disk. The runtime injects everything in-code, so disk discovery\n // would break component isolation and reproducibility.\n settingSources: [],\n };\n\n if (this.model) opts.model = this.model;\n if (this.maxTurns) opts.maxTurns = this.maxTurns;\n\n let toolList: string[] | { type: \"preset\"; preset: \"claude_code\" };\n if (this.tools) {\n toolList = Array.isArray(this.tools) ? [...this.tools] : this.tools;\n } else {\n // `readonly` is `agentContract.mode === \"read-only\"` (task-runner.ts).\n // The mode → Claude Code tool grant is shared with the materialized\n // `.claude/agents/*.md` subagents so both mean the same thing (#272).\n toolList = [...toolGrantForMode(readonly ? \"read-only\" : \"read-write\")];\n }\n\n // When candidate sub-agents are registered (model B), the entry agent needs\n // the sub-agent delegation tool to invoke them. The restricted tool list\n // above omits it, so add it explicitly — otherwise the LLM has no way to\n // delegate. The tool names are shared with the materialized subagent\n // frontmatter (#272). (A \"preset\" tools config already includes it.)\n if (agents && agents.length > 0 && Array.isArray(toolList)) {\n for (const t of DELEGATION_TOOL_NAMES) {\n if (!toolList.includes(t)) toolList.push(t);\n }\n }\n\n if (allowDynamicWorkflow && Array.isArray(toolList)) {\n if (!toolList.includes(\"Workflow\")) toolList.push(\"Workflow\");\n }\n opts.tools = toolList;\n\n if (resume) opts.resume = resume;\n\n if (systemPrompt && this.cacheConfig.enabled !== false) {\n opts.systemPrompt = systemPrompt;\n }\n\n // Register candidate sub-agents so the LLM can delegate via the Agent/Task\n // tool (model B, LLM-internal routing). Keyed by candidate name.\n if (agents && agents.length > 0) {\n const record: Record<string, ClaudeAgentDefinition> = {};\n for (const a of agents) {\n record[a.name] = {\n description: a.description,\n prompt: a.prompt,\n ...(a.tools ? { tools: a.tools } : {}),\n ...(a.model ? { model: a.model } : {}),\n };\n }\n opts.agents = record;\n }\n\n if (this.guardrailHooks) {\n opts.hooks = buildClaudeHooks(this.guardrailHooks);\n }\n\n return opts;\n }\n\n private async attachLibraryTools(\n opts: QueryOptions,\n libraryTools?: LibraryToolRegistry,\n observability?: McpObservabilityContext,\n ): Promise<void> {\n if (!libraryTools || libraryTools.getAll().length === 0) return;\n\n try {\n const server = await buildClaudeMcpServer(libraryTools, observability);\n if (server) {\n const existing = (opts.mcpServers ?? []) as unknown[];\n opts.mcpServers = [...existing, server];\n }\n } catch {\n // SDK functions unavailable; library tools silently skipped for Claude\n }\n }\n\n private createMcpObservability(\n observer?: ObserverEmitFn,\n sessionId?: string,\n ): McpObservabilityContext | undefined {\n if (!observer) return undefined;\n return {\n observer,\n sessionId,\n spanRegistry: new ToolExecSpanRegistry(),\n adoptionTracker: new ContextPackAdoptionTracker(),\n };\n }\n\n private async runQuery(\n prompt: string,\n options: QueryOptions,\n onProgress?: (event: AgentProgressEvent) => void,\n observer?: ObserverEmitFn,\n parentSpanId?: string,\n agentSessionId?: string,\n mcpObservability?: McpObservabilityContext,\n ): Promise<{ text: string; sessionId: string; tokenUsage?: TokenUsage }> {\n const queryFn = await this.resolveQueryFn();\n const stream = queryFn({ prompt, options });\n\n let resultText = \"\";\n let sessionId = \"\";\n\n // Token usage accumulation across all messages in this query\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalCacheReadTokens = 0;\n let totalCacheCreationTokens = 0;\n let hasUsageData = false;\n\n // Inner turn-level instrumentation state\n let turnNumber = 0;\n let currentTurnSpanId: string | undefined;\n let currentTurnStart = 0;\n let toolCallsInTurn = 0;\n let turnInputTokens = 0;\n let turnOutputTokens = 0;\n let turnCacheHitTokens = 0;\n const openToolSpans: Array<{ spanId: string; toolName: string; startMs: number }> = [];\n\n const closePendingToolSpans = (): void => {\n for (const ts of openToolSpans) {\n if (mcpObservability?.spanRegistry?.isClosed(ts.spanId)) continue;\n emitToolExecClose(observer, ts.spanId, ts.toolName, Date.now() - ts.startMs, agentSessionId);\n }\n openToolSpans.length = 0;\n };\n\n const closeCurrentTurn = (): void => {\n if (currentTurnSpanId) {\n emitLlmTurnClose(observer, currentTurnSpanId, turnNumber, Date.now() - currentTurnStart, {\n inputTokens: turnInputTokens || undefined,\n outputTokens: turnOutputTokens || undefined,\n cacheHitTokens: turnCacheHitTokens || undefined,\n toolCallsCount: toolCallsInTurn || undefined,\n }, agentSessionId);\n currentTurnSpanId = undefined;\n }\n };\n\n const captureUsage = (usage: SDKMessage[\"usage\"], perTurn = true): void => {\n if (!usage) return;\n if (typeof usage.input_tokens === \"number\") {\n totalInputTokens += usage.input_tokens;\n if (perTurn) turnInputTokens += usage.input_tokens;\n hasUsageData = true;\n }\n if (typeof usage.output_tokens === \"number\") {\n totalOutputTokens += usage.output_tokens;\n if (perTurn) turnOutputTokens += usage.output_tokens;\n hasUsageData = true;\n }\n if (typeof usage.cache_read_input_tokens === \"number\") {\n totalCacheReadTokens += usage.cache_read_input_tokens;\n if (perTurn) turnCacheHitTokens += usage.cache_read_input_tokens;\n hasUsageData = true;\n }\n if (typeof usage.cache_creation_input_tokens === \"number\") {\n totalCacheCreationTokens += usage.cache_creation_input_tokens;\n hasUsageData = true;\n }\n };\n\n for await (const message of stream) {\n if (message.session_id) sessionId = message.session_id;\n\n if (message.type === \"result\") {\n if (message.usage) {\n if (turnInputTokens === 0 && typeof message.usage.input_tokens === \"number\") {\n turnInputTokens = message.usage.input_tokens;\n }\n if (turnOutputTokens === 0 && typeof message.usage.output_tokens === \"number\") {\n turnOutputTokens = message.usage.output_tokens;\n }\n if (turnCacheHitTokens === 0 && typeof message.usage.cache_read_input_tokens === \"number\") {\n turnCacheHitTokens = message.usage.cache_read_input_tokens;\n }\n }\n captureUsage(message.usage, false);\n closePendingToolSpans();\n closeCurrentTurn();\n if (message.subtype === \"success\") {\n resultText = (message as SDKResultSuccess).result;\n } else if (message.subtype === \"error\") {\n throw new Error(`Claude Agent SDK error: ${(message as SDKResultError).error}`);\n }\n } else if (message.type === \"assistant\") {\n closePendingToolSpans();\n closeCurrentTurn();\n\n turnNumber++;\n toolCallsInTurn = 0;\n turnInputTokens = 0;\n turnOutputTokens = 0;\n turnCacheHitTokens = 0;\n currentTurnStart = Date.now();\n currentTurnSpanId = emitLlmTurnOpen(observer, parentSpanId, turnNumber, this.model, undefined, agentSessionId);\n\n captureUsage(message.usage);\n\n const content = message.message?.content;\n if (content) {\n for (const block of content) {\n if (block.type === \"tool_use\" && block.name) {\n toolCallsInTurn++;\n const summary = truncateInputSummary(block.input);\n const adoption = mcpObservability?.adoptionTracker?.evaluate(\n agentSessionId,\n block.name,\n block.input,\n );\n const openOpts = adoption\n ? {\n sessionId: agentSessionId,\n extraAttributes: {\n \"tool.adoption.kind\": adoption.kind,\n \"tool.context_pack_id\": adoption.contextPackId,\n },\n links: adoption.links,\n }\n : agentSessionId;\n const toolSpanId = emitToolExecOpen(\n observer,\n currentTurnSpanId,\n block.name,\n summary,\n turnNumber,\n openOpts,\n );\n if (toolSpanId) {\n const entry = { spanId: toolSpanId, toolName: block.name, startMs: Date.now() };\n openToolSpans.push(entry);\n mcpObservability?.spanRegistry?.register(entry);\n }\n }\n }\n }\n\n if (onProgress) {\n emitProgressFromSdkMessage(message, onProgress, sessionId);\n }\n } else {\n captureUsage(message.usage);\n if (onProgress) {\n emitProgressFromSdkMessage(message, onProgress, sessionId);\n }\n }\n }\n\n closePendingToolSpans();\n closeCurrentTurn();\n\n const tokenUsage: TokenUsage | undefined = hasUsageData\n ? {\n inputTokens: totalInputTokens,\n outputTokens: totalOutputTokens,\n totalTokens: totalInputTokens + totalOutputTokens,\n ...(totalCacheReadTokens > 0 ? { cacheReadTokens: totalCacheReadTokens } : {}),\n ...(totalCacheCreationTokens > 0 ? { cacheCreationTokens: totalCacheCreationTokens } : {}),\n }\n : undefined;\n\n return { text: resultText, sessionId, tokenUsage };\n }\n\n // -------------------------------------------------------------------------\n // SdkAdapter interface\n // -------------------------------------------------------------------------\n\n async send(\n prompt: string,\n options: AdapterSendOptions,\n ): Promise<string> {\n this.lastSessionId = null;\n this.lastMemoryRef = null;\n this.lastTokenUsage = null;\n\n const split = options.splitPrompt;\n const systemPrompt = split?.system;\n const userPrompt = split ? split.user : prompt;\n const opts = this.buildOptions(options.readonly, undefined, systemPrompt, options.agents, options.allowDynamicWorkflow);\n const mcpObservability = this.createMcpObservability(options.observer, options.sessionId);\n await this.attachLibraryTools(opts, options.libraryTools, mcpObservability);\n const { text, sessionId, tokenUsage } = await this.runQuery(\n userPrompt,\n opts,\n options.onProgress,\n options.observer,\n options.parentSpanId,\n options.sessionId,\n mcpObservability,\n );\n\n this.lastSessionId = sessionId;\n this.lastTokenUsage = tokenUsage ?? null;\n this.lastMemoryRef = {\n id: sessionId,\n provider: \"claude-agent-sdk\",\n compat: \"claude-agent-sdk@0.2\",\n created_at: new Date().toISOString(),\n };\n return text;\n }\n\n async followUp(message: string): Promise<string> {\n if (!this.lastSessionId) {\n throw new Error(\"followUp() called before send() — no active session\");\n }\n const opts = this.buildOptions(false, this.lastSessionId);\n const { text, sessionId, tokenUsage } = await this.runQuery(message, opts);\n this.lastSessionId = sessionId;\n if (tokenUsage) {\n this.lastTokenUsage = this.lastTokenUsage\n ? {\n inputTokens: this.lastTokenUsage.inputTokens + tokenUsage.inputTokens,\n outputTokens: this.lastTokenUsage.outputTokens + tokenUsage.outputTokens,\n totalTokens: (this.lastTokenUsage.totalTokens ?? 0) + (tokenUsage.totalTokens ?? 0),\n cacheReadTokens: (this.lastTokenUsage.cacheReadTokens ?? 0) + (tokenUsage.cacheReadTokens ?? 0) || undefined,\n cacheCreationTokens: (this.lastTokenUsage.cacheCreationTokens ?? 0) + (tokenUsage.cacheCreationTokens ?? 0) || undefined,\n }\n : tokenUsage;\n }\n return text;\n }\n\n async sendExecution(request: AgentExecutionRequest): Promise<string> {\n this.lastSessionId = null;\n this.lastMemoryRef = null;\n this.lastTokenUsage = null;\n\n const resume = request.memoryRef?.id;\n const split = request.splitPrompt;\n const systemPrompt = split?.system;\n const userPrompt = split ? split.user : request.prompt;\n const agents = request.options.agents ?? request.agents;\n const opts = this.buildOptions(request.options.readonly, resume, systemPrompt, agents, request.options.allowDynamicWorkflow);\n const mcpObservability = this.createMcpObservability(\n request.options.observer,\n request.options.sessionId,\n );\n await this.attachLibraryTools(opts, request.options.libraryTools, mcpObservability);\n const { text, sessionId, tokenUsage } = await this.runQuery(\n userPrompt,\n opts,\n request.options.onProgress,\n request.options.observer,\n request.options.parentSpanId,\n request.options.sessionId,\n mcpObservability,\n );\n\n this.lastSessionId = sessionId;\n this.lastTokenUsage = tokenUsage ?? null;\n this.lastMemoryRef = {\n id: sessionId,\n provider: \"claude-agent-sdk\",\n compat: \"claude-agent-sdk@0.2\",\n created_at: new Date().toISOString(),\n parent_run_id: request.memoryRef?.id,\n };\n return text;\n }\n\n getLastMemoryRef(): MemoryRef | null {\n return this.lastMemoryRef;\n }\n\n getLastTokenUsage(): TokenUsage | null {\n return this.lastTokenUsage;\n }\n\n isCompatible(compat: string): boolean {\n return compat.startsWith(\"claude-agent-sdk@\");\n }\n\n // -------------------------------------------------------------------------\n // Test support\n // -------------------------------------------------------------------------\n\n /**\n * Inject a custom query function for testing.\n * Bypasses the dynamic import of @anthropic-ai/claude-agent-sdk.\n */\n static withQueryFn(\n queryFn: QueryFn,\n config?: ClaudeAgentSdkAdapterConfig,\n ): ClaudeAgentSdkAdapter {\n const adapter = new ClaudeAgentSdkAdapter(config);\n adapter.queryFn = queryFn;\n return adapter;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Progress event mapping\n// ---------------------------------------------------------------------------\n\nfunction emitProgressFromSdkMessage(\n message: SDKMessage,\n onProgress: (event: AgentProgressEvent) => void,\n sessionId?: string,\n): void {\n const sid = message.session_id ?? sessionId;\n switch (message.type) {\n case \"assistant\": {\n const content = message.message?.content;\n if (!content) break;\n for (const block of content) {\n if (block.type === \"tool_use\" && block.name) {\n const input = block.input && typeof block.input === \"object\"\n ? block.input as Record<string, unknown>\n : undefined;\n onProgress({ type: \"tool_use\", tool_name: block.name, input, session_id: sid });\n } else if (block.type === \"text\" && block.text) {\n onProgress({ type: \"text\", message: block.text, session_id: sid });\n }\n }\n break;\n }\n case \"tool_progress\":\n if (message.tool_name) {\n onProgress({ type: \"tool_use\", tool_name: message.tool_name, session_id: sid });\n }\n break;\n case \"tool_use_summary\":\n if (message.summary) {\n onProgress({ type: \"status\", message: message.summary, session_id: sid });\n }\n break;\n default:\n break;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiIA,SAAS,iBACP,YACgD;AAChD,QAAM,iBAAsC;AAAA,IAC1C,OAAO;AAAA,MACL,CAAC,UAAiD;AAChD,cAAM,YAAY,MAAM;AACxB,cAAM,WAAW,MAAM;AAEvB,YAAI,aAAa,UAAU,aAAa,SAAS;AAC/C,gBAAM,UAAW,WAAW,WAAW,WAAW;AAClD,cAAI,SAAS;AACX,kBAAM,SAAS,WAAW,qBAAqB;AAAA,cAC7C;AAAA,cACA,KAAK,MAAM;AAAA,YACb,CAAC;AACD,gBAAI,OAAO,eAAe,QAAQ;AAChC,qBAAO;AAAA,gBACL,eAAe;AAAA,gBACf,oBAAoB;AAAA,gBACpB,0BAA0B,OAAO;AAAA,cACnC;AAAA,YACF;AACA,gBAAI,OAAO,mBAAmB;AAC5B,qBAAO,EAAE,eAAe,cAAc,mBAAmB,OAAO,kBAAkB;AAAA,YACpF;AAAA,UACF;AAAA,QACF;AAOA,cAAM,aAAa,WAAW,WAAW;AAAA,UACvC,WAAW;AAAA,UACX,YAAY;AAAA,QACd,CAAC;AACD,YAAI,WAAW,eAAe,QAAQ;AACpC,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,oBAAoB;AAAA,YACpB,0BAA0B,WAAW;AAAA,UACvC;AAAA,QACF;AACA,YAAI,WAAW,mBAAmB;AAChC,iBAAO,EAAE,eAAe,cAAc,mBAAmB,WAAW,kBAAkB;AAAA,QACxF;AAEA,eAAO,EAAE,eAAe,aAAa;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,YAAY,CAAC,cAAc,EAAE;AACxC;AAMA,SAAS,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AAS,QAAQ,SAAS,YAAY,IAAI,CAAC;AAAA,MAC1E;AACA;AAAA,IACF;AACE;AAAA,EACJ;AACF;","names":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { S as SdkAdapter, C as CacheConfig, A as AdapterSendOptions, a as AgentExecutionRequest, M as MemoryRef, T as TokenUsage } from '../task-runner-37cFPFas.js';
|
|
2
|
-
import { G as GuardrailHooks } from '../guardrail-hooks-
|
|
2
|
+
import { G as GuardrailHooks } from '../guardrail-hooks-B-qe4ebW.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '@aaac/contracts';
|
|
5
5
|
import '@aaac/observability';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isGuardrailRuleData,
|
|
3
3
|
matchGlob
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-HR2Q64AO.js";
|
|
5
5
|
|
|
6
6
|
// src/lib/claude-native/hook-protocol.ts
|
|
7
7
|
var MODELLED_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse"];
|
|
@@ -234,4 +234,4 @@ export {
|
|
|
234
234
|
isProtectedArtifact,
|
|
235
235
|
listArtifacts
|
|
236
236
|
};
|
|
237
|
-
//# sourceMappingURL=chunk-
|
|
237
|
+
//# sourceMappingURL=chunk-D2UXESPT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/claude-native/hook-protocol.ts","../src/lib/claude-native/cache-store.ts","../src/lib/claude-native/navigation-freshness.ts","../src/lib/claude-native/ensure-navigation-index-keys.ts","../src/lib/claude-native/artifact-resolver.ts"],"sourcesContent":["/**\n * Claude Code Hook Protocol — parse stdin JSON input and emit hook response JSON.\n *\n * Implements the protocol defined at https://code.claude.com/docs/en/hooks\n * for SessionStart, UserPromptSubmit, and PreToolUse hook events.\n */\n\n// ---------------------------------------------------------------------------\n// Hook Event Types\n// ---------------------------------------------------------------------------\n\n/**\n * One declaration for the events this harness models, so the type and the check\n * `parseHookInput` performs cannot name different sets.\n */\nconst MODELLED_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\"] as const;\n\nexport type HookEventName = (typeof MODELLED_EVENTS)[number];\n\nexport interface SessionStartInput {\n hookEventName: \"SessionStart\";\n session_id?: string;\n type?: \"new\" | \"resume\" | \"clear\" | \"compact\";\n}\n\nexport interface UserPromptSubmitInput {\n hookEventName: \"UserPromptSubmit\";\n session_id?: string;\n prompt?: string;\n}\n\nexport interface PreToolUseInput {\n hookEventName: \"PreToolUse\";\n session_id?: string;\n /** The session's working directory, where a Bash command runs. */\n cwd?: string;\n tool_name?: string;\n tool_input?: {\n file_path?: string;\n path?: string;\n command?: string;\n content?: string;\n [key: string]: unknown;\n };\n}\n\nexport type HookInput = SessionStartInput | UserPromptSubmitInput | PreToolUseInput;\n\n// ---------------------------------------------------------------------------\n// Hook Response Types\n// ---------------------------------------------------------------------------\n\nexport type PermissionDecision = \"allow\" | \"deny\" | \"ask\";\n\nexport interface HookOutput {\n /** Hook-specific output envelope. */\n hookSpecificOutput?: {\n hookEventName: HookEventName;\n /** Additional context injected into the session. */\n additionalContext?: string;\n /** Permission decision for PreToolUse hooks. */\n permissionDecision?: PermissionDecision;\n /** Reason for the permission decision. */\n permissionDecisionReason?: string;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Parse / Emit\n// ---------------------------------------------------------------------------\n\n/** One wording for \"these bytes are not a hook payload\"; `raw` is the diagnosis. */\nconst notAHookPayload = (raw: string): Error =>\n new Error(`Not a hook payload: ${raw.slice(0, 100)}`);\n\nconst optionalString = (value: unknown): boolean =>\n value === undefined || typeof value === \"string\";\n\n/** The `tool_input` bag: four named strings, everything else `unknown`. */\nfunction isToolInput(value: unknown): boolean {\n if (value === undefined) return true;\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const input = value as Record<string, unknown>;\n return (\n optionalString(input.file_path) &&\n optionalString(input.path) &&\n optionalString(input.command) &&\n optionalString(input.content)\n );\n}\n\n/**\n * The single gate between stdin and {@link HookInput}.\n *\n * Every field of the member the discriminant names is checked. `prompt` is one\n * of them and reads like a field nothing would get wrong, which is the reason to\n * check it: `renderCandidateArtifacts` calls `prompt.trim()`, so a non-string\n * there is a `TypeError` two frames from the parse that let it through.\n */\nfunction isHookInput(value: Record<string, unknown>): value is HookInput & Record<string, unknown> {\n if (!optionalString(value.session_id)) return false;\n switch (value.hookEventName) {\n case \"SessionStart\":\n return (\n value.type === undefined ||\n (typeof value.type === \"string\" &&\n [\"new\", \"resume\", \"clear\", \"compact\"].includes(value.type))\n );\n case \"UserPromptSubmit\":\n return optionalString(value.prompt);\n case \"PreToolUse\":\n return optionalString(value.tool_name) && isToolInput(value.tool_input);\n default:\n return false;\n }\n}\n\n/**\n * Parse hook input from a raw JSON string (typically from stdin).\n *\n * Three answers, and the difference between the last two is load-bearing:\n *\n * • a {@link HookInput} — the payload names an event this harness models and\n * carries the fields that member declares;\n * • THROWS — the bytes are not a hook payload at all (not a JSON object, no\n * event name, or a modelled event whose fields are not what it declares).\n * `null` stdin used to reach `parsed.hook_event_name` and answer\n * `TypeError: … reading 'hook_event_name'`;\n * • `undefined` — a well-formed payload for an event this harness does not\n * model. NOT a throw, and that is not a nicety. `pre-tool-use.sh` turns any\n * non-zero bin exit into `exit 2`, which is the one code that BLOCKS a tool\n * call — deliberately, because a guard that could not run must refuse rather\n * than allow (#304). Refusing input we simply do not handle would spend that\n * on every tool call after a version skew, or on a user who registered the\n * launcher under another event, which `settings-merge.ts` explicitly\n * contemplates. Measured end to end: `pre-tool-use.sh` exits 2 on a bin\n * throw, `session-start.sh` and `user-prompt-submit.sh` exit 1 (non-blocking\n * per the protocol — only exit 2 blocks).\n *\n * Routing between the three modelled events stays with each bin's own guard,\n * which spends exit 0 on \"not mine\".\n */\nexport function parseHookInput(raw: string): HookInput | undefined {\n const parsed: unknown = JSON.parse(raw);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw notAHookPayload(raw);\n }\n const record = parsed as Record<string, unknown>;\n // Claude Code's hook INPUT wire protocol sends the event name as snake_case\n // `hook_event_name` (sibling fields session_id / tool_name / tool_input are\n // likewise snake_case). The internal HookInput union — and every hook bin's\n // event guard — reads `hookEventName`. Normalize once here, at the single\n // stdin parse boundary, so the guards match real payloads (#252). Output\n // stays camelCase `hookSpecificOutput.hookEventName`, which the wire expects.\n if (typeof record.hook_event_name === \"string\" && record.hookEventName === undefined) {\n record.hookEventName = record.hook_event_name;\n }\n if (!MODELLED_EVENTS.includes(record.hookEventName as HookEventName)) {\n // A name we do not model is `undefined`; no name at all is not a payload.\n if (typeof record.hookEventName === \"string\") return undefined;\n throw notAHookPayload(raw);\n }\n if (!isHookInput(record)) throw notAHookPayload(raw);\n return record;\n}\n\n/**\n * Read all of stdin and parse as hook input JSON.\n */\nexport async function readHookInput(): Promise<HookInput | undefined> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string));\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\").trim();\n if (!raw) {\n throw new Error(\"Empty stdin — no hook input received\");\n }\n return parseHookInput(raw);\n}\n\n/**\n * Emit a hook response as JSON to stdout.\n */\nexport function emitHookOutput(output: HookOutput): void {\n process.stdout.write(JSON.stringify(output) + \"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Response Builders\n// ---------------------------------------------------------------------------\n\n/**\n * Build a response that injects additional context into the session.\n */\nexport function buildContextResponse(\n eventName: HookEventName,\n additionalContext: string,\n): HookOutput {\n return {\n hookSpecificOutput: {\n hookEventName: eventName,\n additionalContext,\n },\n };\n}\n\n/**\n * Build a deny response for PreToolUse hooks.\n */\nexport function buildDenyResponse(reason: string): HookOutput {\n return {\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: reason,\n },\n };\n}\n\n/**\n * Build an allow response (empty output = allow by default).\n */\nexport function buildAllowResponse(): HookOutput {\n return {};\n}\n","/**\n * Cache Store — read/write `.claude/cache/` directory.\n *\n * Stores navigation-index.json and metadata for graph cache invalidation.\n * Uses atomic write (write-to-temp + rename) for concurrent-access safety.\n */\n\nimport { readFile, writeFile, rename, stat, mkdir } from \"node:fs/promises\";\nimport { join, dirname } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Deciding whether an entry is fresh is deliberately NOT a method here.\n * `navigation-cache.ts` owns that question, and owning it in one place is what\n * keeps the hook that READS the index and the builder that WRITES it from\n * disagreeing about the same file.\n */\nexport interface CacheEntry<T = unknown> {\n data: T;\n /** ISO timestamp of when the cache was written. */\n writtenAt: string;\n /** Hash of source inputs used for invalidation. */\n sourceHash: string;\n /**\n * The files `sourceHash` was computed over.\n *\n * Recorded with the hash, in the same record and the same atomic write, so a\n * reader can re-check freshness without being able to resolve that list\n * itself. Resolving it means parsing the project manifest, which is what the\n * interactive hooks must not pay for; the builder already knows the answer, so\n * it writes it down (#278).\n */\n sourceFiles?: string[];\n}\n\nexport interface CacheStoreOptions {\n /** Absolute path to the `.claude/cache/` directory. */\n cacheDir: string;\n}\n\n// ---------------------------------------------------------------------------\n// Cache Store\n// ---------------------------------------------------------------------------\n\n/**\n * What a caller knows about `data` and this module does not.\n *\n * `read` is generic over `T`, so the only thing here that could establish `T` is\n * the caller's own predicate — `as CacheEntry<T>` promised whatever the call\n * site asked for and delivered whatever was on disk, which is how a cache file\n * written by another process (or an older build) reached `computeCurrentHash`\n * as `sourceFiles: 5` and threw `TypeError: sourceFiles is not iterable`.\n */\nexport type DataPredicate<T> = (value: unknown) => value is T;\n\n/**\n * The shape of an entry whose `data` is declared no more precisely than \"an\n * object\" — what both navigation-index readers ask for. It checks exactly that\n * and no more: a predicate that demanded the index's own keys would promise more\n * than {@link FreshNavigationBuild} declares, and reject builds the type admits.\n */\nexport const isCachedRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport interface CacheStore {\n /**\n * The entry under `key` if the file holds one whose `data` satisfies `isData`,\n * else `null` — the same answer an absent or unparseable file gets, because a\n * record this reader cannot use is not one, however it came to be that way.\n */\n read<T>(key: string, isData: DataPredicate<T>): Promise<CacheEntry<T> | null>;\n write<T = unknown>(\n key: string,\n data: T,\n sourceHash: string,\n sourceFiles?: string[],\n ): Promise<void>;\n /** Get the mtime of a file (for invalidation checks). */\n getFileMtime(filePath: string): Promise<number | null>;\n}\n\n/**\n * The single gate between a cache file's bytes and {@link CacheEntry}.\n *\n * Every declared field is checked, `sourceFiles` included — that one is what\n * `readFreshNavigationBuild` iterates, and it is optional in the type, so\n * \"absent\" and \"present but not a list of strings\" are different answers and\n * only the first is an entry.\n */\nfunction isCacheEntry<T>(value: unknown, isData: DataPredicate<T>): value is CacheEntry<T> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const entry = value as Record<string, unknown>;\n return (\n typeof entry.writtenAt === \"string\" &&\n typeof entry.sourceHash === \"string\" &&\n (entry.sourceFiles === undefined ||\n (Array.isArray(entry.sourceFiles) &&\n entry.sourceFiles.every((f) => typeof f === \"string\"))) &&\n isData(entry.data)\n );\n}\n\nexport function createCacheStore(options: CacheStoreOptions): CacheStore {\n const { cacheDir } = options;\n\n function cacheFilePath(key: string): string {\n return join(cacheDir, `${key}.json`);\n }\n\n async function ensureDir(): Promise<void> {\n await mkdir(cacheDir, { recursive: true });\n }\n\n const store: CacheStore = {\n async read<T>(key: string, isData: DataPredicate<T>): Promise<CacheEntry<T> | null> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(cacheFilePath(key), \"utf-8\"));\n } catch {\n return null;\n }\n return isCacheEntry(parsed, isData) ? parsed : null;\n },\n\n async write<T = unknown>(\n key: string,\n data: T,\n sourceHash: string,\n sourceFiles?: string[],\n ): Promise<void> {\n await ensureDir();\n const entry: CacheEntry<T> = {\n data,\n writtenAt: new Date().toISOString(),\n sourceHash,\n ...(sourceFiles ? { sourceFiles } : {}),\n };\n const content = JSON.stringify(entry, null, 2);\n const target = cacheFilePath(key);\n const tmpPath = `${target}.${randomBytes(4).toString(\"hex\")}.tmp`;\n\n // Atomic write: write to temp file then rename\n await writeFile(tmpPath, content, \"utf-8\");\n try {\n await rename(tmpPath, target);\n } catch {\n // Fallback: direct write if rename fails (cross-device)\n await writeFile(target, content, \"utf-8\");\n }\n },\n\n async getFileMtime(filePath: string): Promise<number | null> {\n try {\n const s = await stat(filePath);\n return s.mtimeMs;\n } catch {\n return null;\n }\n },\n };\n\n return store;\n}\n\n/**\n * Compute a simple hash string from an array of file mtimes and content strings.\n * Not cryptographic — used only for cache invalidation.\n */\nexport function computeSourceHash(inputs: Array<string | number>): string {\n return inputs.map(String).join(\":\");\n}\n","/**\n * Is the cached navigation build still the one this project's sources describe?\n *\n * THE freshness predicate — there is deliberately no other. `cache-store` offers\n * no freshness method, and `ensureNavigationIndex` decides whether to rebuild by\n * asking this, so the hooks that READ a build and the builder that WRITES it\n * cannot answer differently about the same files.\n *\n * ITS OWN MODULE, and that is load-bearing rather than tidiness. The bundler\n * layers chunks by MODULE (`layerOnto` in scripts/build-claude-bundles.mjs), so\n * everything in one file lands on one side of the #278 split. Freshness is\n * needed on BOTH sides — by `build-contextpack`, which escalates a stale cache\n * to a rebuild, and by `check-artifact-edit`, which must not judge from one —\n * while the escalation itself (`runEnsureNavigationIndexBin`, a `spawn`) must\n * never be reachable from the PreToolUse guard: that hook fires on every tool\n * call and has no business starting the DSL loader. Splitting the file is what\n * makes \"the guard can ask, and cannot rebuild\" a fact about the chunk graph\n * instead of a convention.\n */\n\nimport { stat } from \"node:fs/promises\";\nimport { createCacheStore, computeSourceHash, isCachedRecord } from \"./cache-store.js\";\nimport { guardrailCacheKey } from \"./ensure-navigation-index-keys.js\";\nimport { isGuardrailRuleData, type GuardrailRuleData } from \"../guardrail-hooks.js\";\n\nexport const DEFAULT_CACHE_KEY = \"navigation-index\";\n\n/**\n * Cache hash for a set of source files: their mtimes, in order.\n *\n * There is no TTL — the index is stale exactly when one of the files it was\n * built from has been touched. Callers must pass the same `sourceFiles` the\n * build used, or the hash will never match.\n */\nexport async function computeCurrentHash(sourceFiles: string[]): Promise<string> {\n const mtimes: Array<string | number> = [];\n for (const file of sourceFiles) {\n try {\n const s = await stat(file);\n mtimes.push(s.mtimeMs);\n } catch {\n // File not found — include a sentinel so hash changes if file appears\n mtimes.push(`missing:${file}`);\n }\n }\n return computeSourceHash(mtimes);\n}\n\n/**\n * What one `ensureNavigationIndex` run produced: the navigation index and the\n * DSL guardrail rules resolved alongside it.\n *\n * Returned together because they were WRITTEN together, under one hash. A\n * caller that could take one without the other would be free to pair a current\n * artifact registry with a superseded rule set.\n */\nexport interface FreshNavigationBuild {\n navigationIndex: Record<string, unknown>;\n guardrailRules: GuardrailRuleData;\n}\n\n/**\n * The cached build if it is still fresh, else undefined. Never builds.\n *\n * The file list the hash is checked against comes from the CACHE ENTRY, not from\n * re-resolving the project manifest. That is what keeps this readable from the\n * lean graph: resolving the list means loading the manifest parser (zod + yaml),\n * which every per-interaction hook would then carry. The builder resolved it\n * already and wrote it down, so the reader just re-stats it.\n *\n * An entry with no recorded list is treated as stale. It was written by an older\n * build, and rebuilding is exactly what upgrades it — the alternative, assuming\n * it is fresh, would pin a stale index forever.\n *\n * FRESH MEANS THE WHOLE BUILD, not just the index. One run writes both entries,\n * so an index sitting next to no companion is the same \"written by an older\n * build\" case and has to be answered the same way. Asking only about the index\n * is not merely incomplete: `ensureNavigationIndex` returns early on this\n * predicate, so it would keep returning the untouched index and the companion\n * the PreToolUse guard reads could never come back (#304).\n */\nexport async function readFreshNavigationBuild(options: {\n cacheDir: string;\n cacheKey?: string;\n}): Promise<FreshNavigationBuild | undefined> {\n const cacheKey = options.cacheKey ?? DEFAULT_CACHE_KEY;\n const store = createCacheStore({ cacheDir: options.cacheDir });\n const entry = await store.read(cacheKey, isCachedRecord);\n if (!entry?.sourceFiles) return undefined;\n const current = await computeCurrentHash(entry.sourceFiles);\n if (current !== entry.sourceHash) return undefined;\n // Written in the same run, from the same hash — no second stat pass needed.\n const companion = await store.read(guardrailCacheKey(cacheKey), isGuardrailRuleData);\n if (companion?.sourceHash !== entry.sourceHash) return undefined;\n return { navigationIndex: entry.data, guardrailRules: companion.data };\n}\n","/**\n * Cache-key helpers shared between the heavy navigation-index warm path\n * (`ensure-navigation-index.ts`) and the lean PreToolUse hot path\n * (`workspace-pre-tool-use.ts`).\n *\n * This module is intentionally dependency-free (no `navigation-context` /\n * `agent-contracts` imports) so it is safe to include in the lean\n * `hooks-lite` entry point without pulling the heavy DSL loader.\n */\n\n/**\n * Cache-key suffix under which a member's DSL guardrail rules are persisted\n * alongside its navigation-index (#238 / C5).\n *\n * The navigation-index cache stays byte-identical to previous versions; the\n * guardrail rules live in a companion entry (e.g.\n * `navigation-index.aaac.guardrails.json`) so the lean PreToolUse hook can\n * read them without importing the heavy `agent-contracts` DSL loader.\n */\nexport const GUARDRAIL_CACHE_SUFFIX = \".guardrails\";\n\n/** Companion cache key for a navigation-index cache key's guardrail rules. */\nexport function guardrailCacheKey(navigationCacheKey: string): string {\n return `${navigationCacheKey}${GUARDRAIL_CACHE_SUFFIX}`;\n}\n","/**\n * Artifact Resolver — reverse-lookup path to artifact_id using navigation-index.\n *\n * Uses glob matching from guardrail-hooks.ts to match file paths against\n * artifact path_patterns defined in the navigation index.\n */\n\nimport { matchGlob } from \"../guardrail-hooks.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Minimal shape of a navigation-index artifact node. */\nexport interface NavigationArtifact {\n properties?: {\n type?: string;\n authority?: string;\n manual_edit?: string;\n [key: string]: unknown;\n };\n files?: {\n path_patterns?: string[];\n [key: string]: unknown;\n };\n agents?: {\n owners?: string[];\n editors?: string[];\n [key: string]: unknown;\n };\n routes?: {\n regenerate?: string;\n [key: string]: unknown;\n };\n relations?: {\n derived_artifacts?: string[];\n [key: string]: unknown;\n };\n}\n\nexport interface ArtifactMatch {\n artifactId: string;\n artifact: NavigationArtifact;\n /** The glob pattern that matched. */\n matchedPattern: string;\n}\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a file path to its artifact(s) in the navigation index.\n * Returns all matching artifacts (a file may belong to multiple artifacts).\n */\nexport function resolvePathToArtifacts(\n filePath: string,\n navigationIndex: Record<string, unknown>,\n): ArtifactMatch[] {\n const artifacts =\n (navigationIndex.artifacts as Record<string, NavigationArtifact>) ?? {};\n const matches: ArtifactMatch[] = [];\n\n for (const [id, artifact] of Object.entries(artifacts)) {\n const patterns = artifact?.files?.path_patterns;\n if (!Array.isArray(patterns)) continue;\n\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n if (matchGlob(pattern, filePath)) {\n matches.push({ artifactId: id, artifact, matchedPattern: pattern });\n break; // One match per artifact is sufficient\n }\n }\n }\n\n return matches;\n}\n\n/**\n * Check if a file path targets a protected artifact (generated or manual_edit: forbidden).\n */\nexport function isProtectedArtifact(match: ArtifactMatch): {\n protected: boolean;\n reason: string;\n} {\n const props = match.artifact.properties ?? {};\n\n if (props.authority === \"generated\") {\n const regen = match.artifact.routes?.regenerate;\n const hint = regen\n ? ` Run '${regen}' to regenerate.`\n : \" Edit the source artifact and regenerate instead.\";\n return {\n protected: true,\n reason:\n `File belongs to generated artifact '${match.artifactId}'.` +\n ` Direct editing is not allowed.${hint}`,\n };\n }\n\n if (props.manual_edit === \"forbidden\") {\n return {\n protected: true,\n reason:\n `File belongs to artifact '${match.artifactId}' which has manual_edit: forbidden.` +\n ` This artifact must not be edited directly.`,\n };\n }\n\n return { protected: false, reason: \"\" };\n}\n\n/**\n * Get all artifact entries from a navigation index as a flat list.\n */\nexport function listArtifacts(\n navigationIndex: Record<string, unknown>,\n): Array<{ id: string; artifact: NavigationArtifact }> {\n const artifacts =\n (navigationIndex.artifacts as Record<string, NavigationArt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AACtD,UAAM,WAAW,UAAU,OAAO;AAClC,QAAI,CAAC,MAAM,QAAQ,QAAQ,EAAG;AAE9B,eAAW,WAAW,UAAU;AAC9B,UAAI,OAAO,YAAY,SAAU;AACjC,UAAI,UAAU,SAAS,QAAQ,GAAG;AAChC,gBAAQ,KAAK,EAAE,YAAY,IAAI,UAAU,gBAAgB,QAAQ,CAAC;AAClE;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAKO,SAAS,oBAAoB,OAGlC;AACA,QAAM,QAAQ,MAAM,SAAS,cAAc,CAAC;AAE5C,MAAI,MAAM,cAAc,aAAa;AACnC,UAAM,QAAQ,MAAM,SAAS,QAAQ;AACrC,UAAM,OAAO,QACT,SAAS,KAAK,qBACd;AACJ,WAAO;AAAA,MACL,WAAW;AAAA,MACX,QACE,uCAAuC,MAAM,UAAU,oCACrB,IAAI;AAAA,IAC1C;AAAA,EACF;AAEA,MAAI,MAAM,gBAAgB,aAAa;AACrC,WAAO;AAAA,MACL,WAAW;AAAA,MACX,QACE,6BAA6B,MAAM,UAAU;AAAA,IAEjD;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,OAAO,QAAQ,GAAG;AACxC;AAKO,SAAS,cACd,iBACqD;AACrD,QAAM,YACH,gBAAgB,aAAoD,CAAC;AACxE,SAAO,OAAO,QAAQ,SAAS,EAAE,IAAI,CAAC,CAAC,IAAI,QAAQ,OAAO;AAAA,IACxD;AAAA,IACA;AAAA,EACF,EAAE;AACJ;","names":["stat","stat"]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
PROJECT_CONFIG_FILENAME,
|
|
6
6
|
buildGuardrailContext,
|
|
7
7
|
loadProjectConfig
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-Y7NORFFM.js";
|
|
9
9
|
|
|
10
10
|
// src/lib/artifact-resolver.ts
|
|
11
11
|
import { readFile } from "fs/promises";
|
|
@@ -692,4 +692,4 @@ export {
|
|
|
692
692
|
buildNavigationContext,
|
|
693
693
|
resolveNavigationSources
|
|
694
694
|
};
|
|
695
|
-
//# sourceMappingURL=chunk-
|
|
695
|
+
//# sourceMappingURL=chunk-DEBCJKRX.js.map
|
|
@@ -7,12 +7,12 @@ import {
|
|
|
7
7
|
listArtifacts,
|
|
8
8
|
readFreshNavigationBuild,
|
|
9
9
|
resolvePathToArtifacts
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-D2UXESPT.js";
|
|
11
11
|
import {
|
|
12
12
|
createGuardrailHooksFromRules,
|
|
13
13
|
toolPendingContent,
|
|
14
14
|
toolWriteTarget
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-HR2Q64AO.js";
|
|
16
16
|
|
|
17
17
|
// src/lib/claude-native/pre-tool-use.ts
|
|
18
18
|
function commandGuardCovers(input) {
|
|
@@ -42,7 +42,8 @@ function createPreToolUseHandler(config) {
|
|
|
42
42
|
if (guardrailHooks) {
|
|
43
43
|
if (commandGuardCovers(input)) {
|
|
44
44
|
const verdict2 = guardrailHooks.beforeShellExecution({
|
|
45
|
-
command: input.tool_input?.command
|
|
45
|
+
command: input.tool_input?.command,
|
|
46
|
+
cwd: input.cwd
|
|
46
47
|
});
|
|
47
48
|
if (verdict2.permission === "deny") {
|
|
48
49
|
return buildDenyResponse(verdict2.user_message);
|
|
@@ -239,7 +240,7 @@ function createWorkspacePreToolUseHandler(config) {
|
|
|
239
240
|
unmaterializedGuardReason("guardrail-rules", `member "${member2.name}"`)
|
|
240
241
|
);
|
|
241
242
|
}
|
|
242
|
-
const verdict = build2.hooks.beforeShellExecution({ command });
|
|
243
|
+
const verdict = build2.hooks.beforeShellExecution({ command, cwd: input.cwd });
|
|
243
244
|
if (verdict.permission === "deny") {
|
|
244
245
|
return buildDenyResponse(verdict.user_message);
|
|
245
246
|
}
|
|
@@ -295,4 +296,4 @@ export {
|
|
|
295
296
|
stripMemberPrefix,
|
|
296
297
|
createWorkspacePreToolUseHandler
|
|
297
298
|
};
|
|
298
|
-
//# sourceMappingURL=chunk-
|
|
299
|
+
//# sourceMappingURL=chunk-GWNXNSGL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/claude-native/pre-tool-use.ts","../src/lib/claude-native/file-suggestion.ts","../src/lib/claude-native/workspace-router.ts","../src/lib/claude-native/workspace-pre-tool-use.ts"],"sourcesContent":["/**\n * PreToolUse Hook Handler — artifact guardrail + DSL guardrail enforcement.\n *\n * Executed before EVERY tool use — `.claude/settings.json` registers this hook\n * with no matcher, so which guard covers a call is decided here. Two guards:\n * 1. the ARTIFACT guard: file path → artifact reverse lookup → deny if protected\n * 2. the DSL GUARDRAIL guard: every rule the project declares — `command_regex`\n * over the command, `file_glob` over the file the call names, `content_regex`\n * over the text it is about to write — through `GuardrailHooks`. This hook is\n * Claude Code's ONLY refusal point, so a rule kind that is not consulted here\n * is a rule kind the session does not enforce (#316).\n *\n * Both read an input the SessionStart / UserPromptSubmit hooks materialize into\n * `.claude/cache/`. An input that is not there is not the same as an input that\n * says nothing — see `unmaterializedGuardReason`.\n *\n * The two guards are independent — `commandGuardCovers` and\n * `artifactGuardTarget` are asked separately, so one payload can answer to\n * both — and the artifact side defaults to COVERED: an enumeration of the tools\n * to guard is an enumeration that goes stale every time Claude Code grows one\n * (#309).\n */\n\nimport {\n createGuardrailHooksFromRules,\n toolWriteTarget,\n type GuardrailRuleData,\n} from \"../guardrail-hooks.js\";\nimport {\n resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n buildDenyResponse,\n buildAllowResponse,\n type HookOutput,\n type PreToolUseInput,\n} from \"./hook-protocol.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PreToolUseHandlerConfig {\n /**\n * Navigation index read from the cache, or `undefined` when that cache entry\n * was not there to read. Pass what the read returned — do NOT substitute an\n * empty index, which reads as \"this project protects no artifact\".\n */\n navigationIndex?: Record<string, unknown>;\n /**\n * DSL guardrail rules read from the companion cache entry, or `undefined`\n * when that entry was not there to read. A project with no guardrails still\n * HAS the entry (the builder writes it empty), so `undefined` means the guard\n * has no rules to consult, never that there are none.\n */\n guardrailRules?: GuardrailRuleData;\n}\n\n/**\n * Does the command guard cover this call?\n *\n * A call that carries a `command` is a command about to be executed, whatever\n * the tool is called; `Bash` and `PowerShell` are both built-ins today and a\n * third spelling costs nothing. Reading the payload rather than the tool name\n * is also what `guard evaluate` already does (`guard-commands.ts`), so the CLI\n * evaluator and the hook classify a payload the same way.\n */\nexport function commandGuardCovers(input: PreToolUseInput): boolean {\n return input.tool_input?.command !== undefined;\n}\n\n/**\n * The file the artifact guard must judge for this call, or `\"\"` when there is\n * none — a PreToolUse-payload adapter over `toolWriteTarget`, which is where the\n * answer lives.\n *\n * It lives THERE and not here because the DSL file guardrails ask the identical\n * question, and the moment the two asked it separately they answered\n * differently: the workspace route excused a read-only tool and the\n * single-component route refused the same `Read` (#316). The artifact guard and\n * the `file_glob` guard now cover exactly the same operations because there is\n * one function to change.\n *\n * The two guard CLASSES are still independent, not alternatives. Classifying a\n * call into one of them let a payload carrying both a `command` and a path skip\n * the artifact check entirely; no built-in carries both today, which is exactly\n * the kind of \"no tool does that yet\" that #309 exists to stop relying on.\n */\nexport function artifactGuardTarget(input: PreToolUseInput): string {\n return toolWriteTarget(input.tool_name, input.tool_input);\n}\n\n/** A `.claude/cache/` input the PreToolUse guard cannot reach a verdict without. */\nexport type PreToolUseGuardInput = \"navigation-index\" | \"guardrail-rules\";\n\n/** Which cache entry backs which guard, and what refusing it protects. */\nconst GUARD_INPUT_DESCRIPTION: Record<PreToolUseGuardInput, string> = {\n \"navigation-index\": \"the artifact edit guard\",\n // Every rule kind the DSL declares — command, file and content — comes out of\n // this one entry, so naming only the command half here would tell a refused\n // edit that the guard it tripped is about something else (#316).\n \"guardrail-rules\": \"the DSL guardrails\",\n};\n\n/**\n * Refusal message for a guard with no build it may judge from.\n *\n * This is the #293 rule applied one level further out. There, a guardrail whose\n * policy declares no action denies, because an unknowable verdict must not come\n * out permissive. Here the rules (or the artifact index) cannot be consulted at\n * all, so the verdict is unknowable for the same reason — and the previous\n * behaviour, allowing, is exactly how `git commit --no-verify` ran through\n * Claude Code with the guard saying nothing (#304). Only the operations the\n * missing guard covers are refused; a Read or a Grep is not one of them.\n *\n * ONE state, not two. \"Never materialized\" and \"materialized from sources that\n * have since changed\" differ only in how the cache got that way; both leave the\n * guard unable to answer for the project as it stands NOW, and both are repaired\n * by the same rebuild. Telling them apart here would mean two messages for one\n * decision — and the second one was the silent case: a warm cache whose DSL no\n * longer parses kept the guard judging by rules the project had already stopped\n * declaring, so a newly added rule was simply never enforced (#316).\n *\n * The message names the repair, because the repair is automatic: SessionStart\n * and every UserPromptSubmit run `ensure-navigation-index`, which writes the\n * whole build. Seeing this means that has not happened yet — or cannot, in which\n * case the per-prompt hook is already reporting why on stderr (#310).\n */\nexport function unmaterializedGuardReason(\n input: PreToolUseGuardInput,\n scope?: string,\n): string {\n const where = scope ? ` for ${scope}` : \"\";\n return (\n `[guard-unavailable] ${GUARD_INPUT_DESCRIPTION[input]} cannot run: the ` +\n `\\`${input}\\` cache entry${where} is absent or was built from sources that ` +\n `have since changed, so this operation gets no verdict and is refused rather ` +\n `than judged by superseded rules or silently allowed. ` +\n `Run \\`.claude/bin/ensure-navigation-index\\` (SessionStart and every prompt ` +\n `submission do this automatically — if it keeps failing, that failure is the bug).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Create a PreToolUse hook handler.\n *\n * The caller passes the cache reads verbatim; deciding what an absent read\n * means is this handler's job, not the calling bin's.\n */\nexport function createPreToolUseHandler(config: PreToolUseHandlerConfig) {\n // Pre-compiled once; `null` means the rules were never materialized, which is\n // a refusal below — not a quiet skip of the command guard.\n const guardrailHooks = config.guardrailRules\n ? createGuardrailHooksFromRules(config.guardrailRules)\n : null;\n\n return async function handlePreToolUse(\n input: PreToolUseInput,\n ): Promise<HookOutput> {\n const target = artifactGuardTarget(input);\n\n // The DSL guardrails cover both classes of operation, so a rule set that was\n // never materialized refuses both — not just the command half, which is how\n // `file_glob` rules stayed unenforced with nothing said (#316).\n if (!guardrailHooks && (commandGuardCovers(input) || target)) {\n return buildDenyResponse(unmaterializedGuardReason(\"guardrail-rules\"));\n }\n\n if (guardrailHooks) {\n // --- Shell command: DSL command guardrails ---\n if (commandGuardCovers(input)) {\n const verdict = guardrailHooks.beforeShellExecution({\n command: input.tool_input?.command,\n cwd: input.cwd,\n });\n if (verdict.permission === \"deny\") {\n return buildDenyResponse(verdict.user_message);\n }\n }\n\n // --- DSL file + content guardrails ---\n //\n // The payload goes to the evaluator VERBATIM. It reads the target and the\n // pending content out of the tool input itself and answers `{}` for a call\n // that names no file, so which calls are covered is decided once, there —\n // exactly as `guard evaluate` and the SDK adapter already ask it, which is\n // what keeps the three routes on one verdict.\n const verdict = guardrailHooks.preToolUse({\n tool_name: input.tool_name,\n tool_input: input.tool_input,\n });\n if (verdict.permission === \"deny\") {\n return buildDenyResponse(verdict.user_message);\n }\n }\n\n // --- Candidate file write: artifact protection ---\n if (target) {\n if (!config.navigationIndex) {\n return buildDenyResponse(unmaterializedGuardReason(\"navigation-index\"));\n }\n for (const match of resolvePathToArtifacts(target, config.navigationIndex)) {\n const check = isProtectedArtifact(match);\n if (check.protected) {\n return buildDenyResponse(check.reason);\n }\n }\n }\n\n // --- Default: allow ---\n return buildAllowResponse();\n };\n}\n","/**\n * File Suggestion Handler — artifact-aware @ completion for Claude Code.\n *\n * Reads stdin prefix, filters navigation-index artifacts, and emits NDJSON\n * candidates sorted by relevance score.\n */\n\nimport { listArtifacts, type NavigationArtifact } from \"./artifact-resolver.js\";\nimport { createCacheStore, isCachedRecord } from \"./cache-store.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface FileSuggestionCandidate {\n label: string;\n path: string;\n kind: \"artifact\" | \"file\";\n /** Artifact ID this file/pattern belongs to. */\n artifact?: string;\n /** Authority of the artifact (canonical, generated, etc.). */\n authority?: string;\n /** Manual edit policy for the artifact. */\n manual_edit?: string;\n /** Relevance score (higher = more relevant). */\n score: number;\n}\n\nexport interface FileSuggestionOptions {\n /** The navigation index to search. */\n navigationIndex: Record<string, unknown>;\n /** Maximum number of candidates to return. */\n maxCandidates?: number;\n /**\n * Prefix prepended to every emitted path (#266). Artifact `path_patterns` are\n * project-root relative, so in a workspace — where Claude Code's cwd is the\n * workspace root — a member's candidates must be re-rooted under the member\n * directory. The mirror image of `stripMemberPrefix` on the PreToolUse side.\n */\n pathPrefix?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Implementation\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_CANDIDATES = 100;\n\n/**\n * Generate file suggestion candidates from the navigation index.\n * Filters by prefix if provided, then returns NDJSON-formatted candidates.\n */\nexport function generateCandidates(\n prefix: string,\n options: FileSuggestionOptions,\n): FileSuggestionCandidate[] {\n const { navigationIndex, maxCandidates = DEFAULT_MAX_CANDIDATES } = options;\n const artifacts = listArtifacts(navigationIndex);\n const candidates: FileSuggestionCandidate[] = [];\n const lowerPrefix = prefix.toLowerCase();\n const rootPath = (path: string) => joinPathPrefix(options.pathPrefix, path);\n\n for (const { id, artifact } of artifacts) {\n const props = artifact.properties ?? {};\n const patterns = artifact.files?.path_patterns ?? [];\n\n // Artifact-level candidate\n if (!prefix || id.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: id,\n path: rootPath(patterns.length > 0 ? String(patterns[0]) : id),\n kind: \"artifact\",\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeArtifactScore(id, artifact, prefix),\n });\n }\n\n // File-level candidates from path patterns\n for (const pattern of patterns) {\n if (typeof pattern !== \"string\") continue;\n // Skip pure glob patterns for file-level suggestions (they're covered by artifact-level)\n if (pattern.includes(\"*\") || pattern.includes(\"?\")) continue;\n\n if (!prefix || pattern.toLowerCase().includes(lowerPrefix)) {\n candidates.push({\n label: pattern,\n path: rootPath(pattern),\n kind: \"file\",\n artifact: id,\n authority: props.authority as string | undefined,\n manual_edit: props.manual_edit as string | undefined,\n score: computeFileScore(pattern, prefix),\n });\n }\n }\n }\n\n // Sort by score descending, then by label\n candidates.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n return a.label.localeCompare(b.label);\n });\n\n return candidates.slice(0, maxCandidates);\n}\n\n/** Join a member path prefix with a project-relative path. */\nfunction joinPathPrefix(prefix: string | undefined, path: string): string {\n if (!prefix) return path;\n const normalized = prefix.replace(/^\\.\\//, \"\").replace(/\\/+$/, \"\");\n return normalized ? `${normalized}/${path}` : path;\n}\n\n/**\n * Format candidates as NDJSON (one JSON object per line).\n */\nexport function formatNdjson(candidates: FileSuggestionCandidate[]): string {\n return candidates.map((c) => JSON.stringify(c)).join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Scoring helpers\n// ---------------------------------------------------------------------------\n\nfunction computeArtifactScore(\n id: string,\n artifact: NavigationArtifact,\n prefix: string,\n): number {\n let score = 50;\n const props = artifact.properties ?? {};\n\n // Boost canonical, editable artifacts\n if (props.authority === \"canonical\") score += 20;\n if (props.manual_edit === \"allowed\") score += 10;\n\n // Boost source artifacts\n if (props.type === \"source\") score += 15;\n\n // Penalize generated artifacts\n if (props.authority === \"generated\") score -= 20;\n if (props.manual_edit === \"forbidden\") score -= 10;\n\n // Boost exact prefix match\n if (prefix && id.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 20;\n }\n\n return score;\n}\n\nfunction computeFileScore(path: string, prefix: string): number {\n let score = 40;\n\n // Boost exact prefix match\n if (prefix && path.toLowerCase().startsWith(prefix.toLowerCase())) {\n score += 30;\n }\n\n // Boost shorter paths (more specific)\n score += Math.max(0, 20 - path.split(\"/\").length * 2);\n\n return score;\n}\n\n/**\n * Main handler for file-suggestion bin script.\n * Reads prefix from stdin, returns NDJSON candidates to stdout.\n */\nexport async function handleFileSuggestion(\n navigationIndex: Record<string, unknown>,\n stdinData: string,\n): Promise<string> {\n const prefix = stdinData.trim();\n const candidates = generateCandidates(prefix, { navigationIndex });\n return formatNdjson(candidates);\n}\n\n/** One workspace member's cached index, as the file-suggestion bin knows it. */\nexport interface WorkspaceFileSuggestionMember {\n /** Member name (for diagnostics only). */\n name: string;\n /** Workspace-relative member path — prepended to every candidate path. */\n memberPath: string;\n /** Cache key of this member's navigation-index. */\n cacheKey: string;\n}\n\n/**\n * Workspace variant (#266): merge candidates from every member's own index.\n *\n * The single-component handler reads the lone `navigation-index` cache entry,\n * which workspace mode never writes (each member has its own key) — so `@`\n * completion returned nothing at all. Members whose index has not been built yet\n * are skipped rather than failing the hook: SessionStart warms them.\n */\nexport async function handleWorkspaceFileSuggestion(\n cacheDir: string,\n members: WorkspaceFileSuggestionMember[],\n stdinData: string,\n maxCandidates = DEFAULT_MAX_CANDIDATES,\n): Promise<string> {\n const prefix = stdinData.trim();\n const store = createCacheStore({ cacheDir });\n const merged: FileSuggestionCandidate[] = [];\n\n for (const member of members) {\n const entry = await store.read(member.cacheKey, isCachedRecord);\n if (!entry) continue;\n merged.push(\n ...generateCandidates(prefix, {\n navigationIndex: entry.data,\n pathPrefix: member.memberPath,\n maxCandidates: Number.POSITIVE_INFINITY,\n }),\n );\n }\n\n merged.sort((a, b) => (b.score !== a.score ? b.score - a.score : a.label.localeCompare(b.label)));\n return formatNdjson(merged.slice(0, maxCandidates));\n}\n","/**\n * Workspace Router — route a file path to the owning workspace member.\n *\n * Pure path-manipulation module. No imports from navigation-context,\n * agent-contracts, or any heavy dependency — safe for the lean hooks-lite\n * entry point.\n *\n * Algorithm: longest-prefix match among member absolute root paths.\n *\n * C4 resolution: stripMemberPrefix converts a workspace-relative path\n * (`aaac/packages/runtime/x.ts`) into a repo-relative path\n * (`packages/runtime/x.ts`) so existing member DSL path_patterns work\n * without modification.\n */\n\nimport { resolve } from \"node:path\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceMember {\n /** Human-readable member name (e.g. `\"aaac\"`). */\n name: string;\n /** Absolute path to the member root directory. */\n root: string;\n}\n\n// ---------------------------------------------------------------------------\n// Router\n// ---------------------------------------------------------------------------\n\n/**\n * Route a file path to the workspace member whose root is the longest\n * matching prefix of that path.\n *\n * Generic over `T extends WorkspaceMember` so callers that pass a richer\n * member type (e.g. `WorkspaceMemberPreToolUseConfig`) get back that type\n * without a cast.\n *\n * @param filePath - Absolute or workspace-root-relative file path (as\n * received from Claude Code's `tool_input.file_path`).\n * @param members - Workspace members with **absolute** root paths.\n * @param workspaceRoot - Absolute path to the workspace root directory.\n * Used to resolve relative `filePath` values.\n * @returns The owning member, or `null` when no member claims this path.\n */\nexport function routePathToMember<T extends WorkspaceMember>(\n filePath: string,\n members: T[],\n workspaceRoot: string,\n): T | null {\n if (!filePath) return null;\n\n // Normalise to absolute path\n const absPath = filePath.startsWith(\"/\")\n ? filePath\n : resolve(workspaceRoot, filePath);\n\n let best: T | null = null;\n let bestPrefixLen = 0;\n\n for (const member of members) {\n const memberRoot = member.root;\n // Ensure the prefix ends with \"/\" so \"aaac-extra\" doesn't match \"aaac\"\n const prefix = memberRoot.endsWith(\"/\") ? memberRoot : memberRoot + \"/\";\n\n if (absPath.startsWith(prefix) && prefix.length > bestPrefixLen) {\n best = member;\n bestPrefixLen = prefix.length;\n }\n }\n\n return best;\n}\n\n/**\n * Strip the member root prefix from `filePath` to obtain a repo-relative\n * path that member DSL `path_patterns` can match against unchanged (C4).\n *\n * Example:\n * filePath = \"aaac/packages/runtime/x.ts\" (workspace-relative)\n * memberRoot = \"/abs/workspace/aaac\"\n * workspaceRoot = \"/abs/workspace\"\n * → returns \"packages/runtime/x.ts\"\n *\n * @param filePath - Absolute or workspace-root-relative path.\n * @param memberRoot - Absolute path to the member root.\n * @param workspaceRoot - Absolute path to the workspace root.\n * @returns Repo-relative path (no leading slash/dot).\n * Falls back to the original `filePath` when stripping is not possible.\n */\nexport function stripMemberPrefix(\n filePath: string,\n memberRoot: string,\n workspaceRoot: string,\n): string {\n const absPath = filePath.startsWith(\"/\")\n ? filePath\n : resolve(workspaceRoot, filePath);\n\n const prefix = memberRoot.endsWith(\"/\") ? memberRoot : memberRoot + \"/\";\n if (absPath.startsWith(prefix)) {\n return absPath.slice(prefix.length);\n }\n\n return filePath;\n}\n","/**\n * Workspace PreToolUse Hook Handler — routes edits to the owning member\n * and enforces that member's artifact guardrails.\n *\n * Hot-path module. Does NOT import navigation-context or agent-contracts —\n * it only reads an already-built navigation index from the cache. Suitable\n * for inclusion in the lean hooks-lite entry point.\n *\n * Flow (per PreToolUse invocation, once `artifactGuardTarget` names a file the\n * file guards have to judge):\n * 1. Extract file path from tool input.\n * 2. Route to owning member via longest-prefix match (workspace-router).\n * 3. Read the member's fresh build — navigation-index + guardrail rules.\n * 4. Strip member-root prefix → repo-relative path (C4 resolution).\n * 5. Apply the member's file + content guardrails to that path.\n * 6. Resolve path to artifacts; deny if protected.\n */\n\nimport {\n createGuardrailHooksFromRules,\n toolPendingContent,\n type GuardrailHooks,\n} from \"../guardrail-hooks.js\";\nimport {\n resolvePathToArtifacts,\n isProtectedArtifact,\n} from \"./artifact-resolver.js\";\nimport {\n readFreshNavigationBuild,\n type FreshNavigationBuild,\n} from \"./navigation-freshness.js\";\nimport {\n buildDenyResponse,\n buildAllowResponse,\n type HookOutput,\n type PreToolUseInput,\n} from \"./hook-protocol.js\";\n// The guard classification and the unavailable-guard refusal come from the\n// single-component handler, which is where both are defined (#304). Two copies\n// would let the workspace route admit what the single-component route refuses;\n// the same direction already carries `renderCandidateArtifacts` from\n// user-prompt-submit.\nimport {\n artifactGuardTarget,\n commandGuardCovers,\n unmaterializedGuardReason,\n} from \"./pre-tool-use.js\";\nimport {\n routePathToMember,\n stripMemberPrefix,\n type WorkspaceMember,\n} from \"./workspace-router.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface WorkspaceMemberPreToolUseConfig extends WorkspaceMember {\n /**\n * Cache key for this member's navigation-index JSON.\n * Format: `navigation-index.<name>` (e.g. `navigation-index.aaac`).\n *\n * The member's DSL guardrail rules live in the companion entry this key\n * implies. There is no override for that: `ensureNavigationIndex` — the only\n * writer — derives the companion key from this one, so a reader free to name\n * a different entry could only ever name one nothing writes (#316).\n */\n cacheKey: string;\n}\n\nexport interface WorkspacePreToolUseConfig {\n /** Absolute path to the workspace root directory. */\n workspaceRoot: string;\n /** Absolute path to the shared `.claude/cache/` directory. */\n cacheDir: string;\n /** Workspace members to route edits to. */\n members: WorkspaceMemberPreToolUseConfig[];\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\n/**\n * Extract path-like tokens from a shell command so a Bash invocation can be\n * routed to the owning workspace member (#238 / C5).\n *\n * Whitespace-split, strips common shell quoting; keeps only tokens that look\n * like paths (contain a `/` or `\\`). This is a best-effort heuristic — command\n * guardrails that fail to route to a specific member fall back to evaluating\n * against every member's rules (safety-preserving union).\n */\nfunction extractCommandPathTokens(command: string): string[] {\n const tokens: string[] = [];\n for (const raw of command.split(/\\s+/)) {\n const t = raw.replace(/^['\"]+|['\"]+$/g, \"\");\n if (t && (t.includes(\"/\") || t.includes(\"\\\\\"))) {\n tokens.push(t);\n }\n }\n return tokens;\n}\n\n/**\n * Create a workspace-aware PreToolUse hook handler.\n *\n * On each invocation both guards are asked — independently, so one payload can\n * answer to both — and the handler:\n * - file guards, over the file `artifactGuardTarget` names:\n * - Routes the target path to the owning member by longest-prefix match.\n * - Reads the member's fresh build (refuses if it has none).\n * - Strips the member-root prefix so the member's `path_patterns` and\n * `file_glob` patterns both receive the repo-relative path they are written\n * against (C4).\n * - Denies a blocking `file_glob` / `content_regex` violation, then denies if\n * any matched artifact is protected (Phase 1).\n * - command guard, when the call carries one (#238 / C5, Phase 3):\n * - Routes the command to the owning member via a path token in the command\n * (longest-prefix match); when no member path is present, evaluates the\n * command against every member's rules so safety guardrails are never\n * silently skipped.\n * - Denies blocking command violations from that member's rules.\n *\n * Artifact protection (Phase 1) and DSL guardrails (Phase 3) are independent and\n * coexist: a member with only artifact rules keeps working unchanged, and a\n * member with only guardrail rules still enforces command and file safety.\n *\n * A member with no usable build refuses the operations its guards cover, rather\n * than admitting them — see `unmaterializedGuardReason`.\n */\nexport function createWorkspacePreToolUseHandler(\n config: WorkspacePreToolUseConfig,\n) {\n /**\n * One member's fresh build plus its compiled hooks, memoised for the life of\n * this hook invocation. `undefined` means the member has no build this guard\n * may judge from — absent, or superseded by an edit to the member's sources.\n *\n * Both entries come from ONE freshness answer. Read separately, a member's\n * artifact registry and its rule set could be paired across two builds.\n */\n const buildByMember = new Map<\n string,\n (FreshNavigationBuild & { hooks: GuardrailHooks }) | undefined\n >();\n\n async function loadMemberBuild(member: WorkspaceMemberPreToolUseConfig) {\n if (buildByMember.has(member.name)) {\n return buildByMember.get(member.name);\n }\n const build = await readFreshNavigationBuild({\n cacheDir: config.cacheDir,\n cacheKey: member.cacheKey,\n });\n // A member that declares no guardrail still HAS a rule set — the builder\n // writes it empty — so an empty one is an answer (\"nothing matches\") and is\n // compiled like any other. Treating empty as \"no hooks\" made the two\n // indistinguishable (#304).\n const loaded = build\n ? { ...build, hooks: createGuardrailHooksFromRules(build.guardrailRules) }\n : undefined;\n buildByMember.set(member.name, loaded);\n return loaded;\n }\n\n /**\n * Route a Bash command to the member(s) whose guardrail rules apply. Returns\n * a single owning member when a member-prefixed path is present in the\n * command; otherwise returns every member (safety-preserving union).\n */\n function membersForCommand(\n command: string,\n ): WorkspaceMemberPreToolUseConfig[] {\n for (const token of extractCommandPathTokens(command)) {\n const owner = routePathToMember(\n token,\n config.members,\n config.workspaceRoot,\n );\n if (owner) return [owner];\n }\n return config.members;\n }\n\n return async function handleWorkspacePreToolUse(\n input: PreToolUseInput,\n ): Promise<HookOutput> {\n // --- Shell command: member-scoped DSL guardrail enforcement (Phase 3 / C5) ---\n if (commandGuardCovers(input)) {\n const command = input.tool_input?.command ?? \"\";\n for (const member of membersForCommand(command)) {\n const build = await loadMemberBuild(member);\n if (!build) {\n return buildDenyResponse(\n unmaterializedGuardReason(\"guardrail-rules\", `member \"${member.name}\"`),\n );\n }\n const verdict = build.hooks.beforeShellExecution({ command, cwd: input.cwd });\n if (verdict.permission === \"deny\") {\n return buildDenyResponse(verdict.user_message);\n }\n }\n }\n\n // The file guards run on the same call, not instead of it: a payload\n // carrying both a command and a path is judged by both.\n const filePath = artifactGuardTarget(input);\n if (!filePath) {\n return buildAllowResponse();\n }\n\n // Step 1: Route to owning member\n const member = routePathToMember(\n filePath,\n config.members,\n config.workspaceRoot,\n );\n if (!member) {\n // Path does not belong to any declared member — allow\n return buildAllowResponse();\n }\n\n // Step 2: Load the member's build — index and rules, one freshness answer\n const build = await loadMemberBuild(member);\n if (!build) {\n return buildDenyResponse(\n unmaterializedGuardReason(\"navigation-index\", `member \"${member.name}\"`),\n );\n }\n\n // Step 3: Strip member-root prefix → repo-relative path (C4)\n const repoRelPath = stripMemberPrefix(\n filePath,\n member.root,\n config.workspaceRoot,\n );\n\n // Step 4: The member's DSL file + content guardrails.\n //\n // Asked through the ALREADY-EXTRACTED gate, not the tool-input one the\n // single-component route uses, because the path this member's `file_glob`\n // patterns are written against is the repo-relative one Step 3 produced —\n // not the workspace-scoped path the tool named. Handing the tool input over\n // instead would make the evaluator re-read that path and judge the wrong\n // string; rewriting the payload would put the \"which key names the file\"\n // decision back in a caller, which is what #309 removed. The verdict is the\n // same one `preToolUse` reaches — one evaluator, two payload shapes.\n const fileVerdict = build.hooks.afterFileEdit({\n file_path: repoRelPath,\n content: toolPendingContent(input.tool_input),\n });\n if (fileVerdict.permission === \"deny\") {\n return buildDenyResponse(fileVerdict.user_message);\n }\n\n // Step 5: Resolve path to artifacts and check protection\n for (const match of resolvePathToArtifacts(repoRelPath, build.navigationIndex)) {\n const check = isProtectedArtifact(match);\n if (check.protected) {\n return buildDenyResponse(check.reason);\n }\n }\n\n return buildAll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
1
|
+
// src/lib/command-body-files.ts
|
|
2
|
+
import { readFileSync, statSync } from "fs";
|
|
3
|
+
import { resolve } from "path";
|
|
4
|
+
var BODY_FILE_FLAG = /(?:^|\s)(?:--body-file|--notes-file|--file|-F)(?:=|\s+)(?:'([^']*)'|"([^"]*)"|([^\s;|&]+))/g;
|
|
5
|
+
function commandScanText(command, cwd) {
|
|
6
|
+
const bodies = [];
|
|
7
|
+
for (const match of command.matchAll(BODY_FILE_FLAG)) {
|
|
8
|
+
const path = match[1] ?? match[2] ?? match[3];
|
|
9
|
+
if (!path || path === "-") continue;
|
|
10
|
+
const absPath = resolve(cwd ?? process.cwd(), path);
|
|
11
|
+
try {
|
|
12
|
+
if (!statSync(absPath).isFile()) continue;
|
|
13
|
+
bodies.push(readFileSync(absPath, "utf8"));
|
|
14
|
+
} catch {
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return bodies.length === 0 ? command : [command, ...bodies].join("\n");
|
|
19
|
+
}
|
|
20
|
+
|
|
1
21
|
// src/lib/guardrail-hooks.ts
|
|
2
22
|
var GUARDRAIL_ACTIONS = [
|
|
3
23
|
"block",
|
|
@@ -148,10 +168,14 @@ function createGuardrailHooks(...sources) {
|
|
|
148
168
|
}
|
|
149
169
|
return results;
|
|
150
170
|
}
|
|
151
|
-
function
|
|
171
|
+
function checkShellCommand(input) {
|
|
152
172
|
const command = input.command ?? "";
|
|
153
|
-
if (!command) return
|
|
154
|
-
|
|
173
|
+
if (!command) return [];
|
|
174
|
+
return runChecks({ command: commandScanText(command, input.cwd) });
|
|
175
|
+
}
|
|
176
|
+
function beforeShellExecution(input) {
|
|
177
|
+
const results = checkShellCommand(input);
|
|
178
|
+
if (results.length === 0) return {};
|
|
155
179
|
const blocks = getBlockingViolations(results);
|
|
156
180
|
const warns = getWarnings(results);
|
|
157
181
|
if (blocks.length > 0) {
|
|
@@ -176,7 +200,7 @@ function createGuardrailHooks(...sources) {
|
|
|
176
200
|
function afterFileEdit(input) {
|
|
177
201
|
return fileWriteVerdict(input.file_path ?? "", input.content ?? "");
|
|
178
202
|
}
|
|
179
|
-
return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };
|
|
203
|
+
return { beforeShellExecution, checkShellCommand, preToolUse, afterFileEdit, runChecks };
|
|
180
204
|
}
|
|
181
205
|
function compileGuardrailPattern(pattern) {
|
|
182
206
|
if (pattern.startsWith("(?i)")) {
|
|
@@ -266,4 +290,4 @@ export {
|
|
|
266
290
|
createGuardrailHooks,
|
|
267
291
|
createGuardrailHooksFromRules
|
|
268
292
|
};
|
|
269
|
-
//# sourceMappingURL=chunk-
|
|
293
|
+
//# sourceMappingURL=chunk-HR2Q64AO.js.map
|