@aaac/runtime 0.1.55 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -11
- package/dist/adapters/adk-sdk.d.ts +3 -3
- package/dist/adapters/adk-sdk.js +6 -8
- package/dist/adapters/adk-sdk.js.map +1 -1
- package/dist/adapters/claude-agent-sdk.d.ts +3 -3
- package/dist/adapters/claude-agent-sdk.js +22 -23
- package/dist/adapters/claude-agent-sdk.js.map +1 -1
- package/dist/adapters/mock.d.ts +2 -3
- package/dist/adapters/openai-agents-sdk.d.ts +3 -3
- package/dist/adapters/openai-agents-sdk.js +6 -5
- package/dist/adapters/openai-agents-sdk.js.map +1 -1
- package/dist/chunk-2INQL5TG.js +298 -0
- package/dist/chunk-2INQL5TG.js.map +1 -0
- package/dist/chunk-3CLWG72V.js +47 -0
- package/dist/chunk-3CLWG72V.js.map +1 -0
- package/dist/chunk-3DDB34BU.js +237 -0
- package/dist/chunk-3DDB34BU.js.map +1 -0
- package/dist/chunk-ABXDSTUV.js +685 -0
- package/dist/chunk-ABXDSTUV.js.map +1 -0
- package/dist/{chunk-3H3PVPPF.js → chunk-F5R46S7I.js} +151 -204
- package/dist/chunk-F5R46S7I.js.map +1 -0
- package/dist/chunk-FKAI54OM.js +234 -0
- package/dist/chunk-FKAI54OM.js.map +1 -0
- package/dist/chunk-KTVMMG33.js +1111 -0
- package/dist/chunk-KTVMMG33.js.map +1 -0
- package/dist/chunk-MSVIEEGR.js +269 -0
- package/dist/chunk-MSVIEEGR.js.map +1 -0
- package/dist/chunk-VJXGCWSZ.js +36 -0
- package/dist/chunk-VJXGCWSZ.js.map +1 -0
- package/dist/claude-bundles/full.js +311 -309
- package/dist/claude-bundles/lean.js +6 -6
- package/dist/claude-bundles/prompt.js +17 -0
- package/dist/generator/index.d.ts +2 -2
- package/dist/generator/index.js +8 -7
- package/dist/guardrail-hooks-CB23nhZV.d.ts +202 -0
- package/dist/hook-protocol-CFnNudiV.d.ts +96 -0
- package/dist/hooks-lite-CoWWnCRH.d.ts +428 -0
- package/dist/index-BlSepCSZ.d.ts +296 -0
- package/dist/index.d.ts +785 -105
- package/dist/index.js +2189 -634
- package/dist/index.js.map +1 -1
- package/dist/lib/claude-native/hooks-lite.d.ts +3 -26
- package/dist/lib/claude-native/hooks-lite.js +18 -36
- package/dist/lib/claude-native/hooks-prompt.d.ts +5 -0
- package/dist/lib/claude-native/hooks-prompt.js +33 -0
- package/dist/lib/claude-native/hooks-prompt.js.map +1 -0
- package/dist/lib/claude-native/index.d.ts +56 -214
- package/dist/lib/claude-native/index.js +79 -280
- package/dist/lib/claude-native/index.js.map +1 -1
- package/dist/{navigation-context-D_E1NIUf.d.ts → navigation-context-B-RpUg3_.d.ts} +1 -1
- package/dist/navigation-index-prompt-CbrS5laO.d.ts +43 -0
- package/dist/{task-runner-DfIEorkU.d.ts → task-runner-GWoI7_71.d.ts} +100 -493
- package/dist/workspace-user-prompt-submit-D11Iu0zO.d.ts +269 -0
- package/package.json +15 -6
- package/dist/chunk-3H3PVPPF.js.map +0 -1
- package/dist/chunk-DBM5XN67.js +0 -354
- package/dist/chunk-DBM5XN67.js.map +0 -1
- package/dist/chunk-KXGUWBGK.js +0 -370
- package/dist/chunk-KXGUWBGK.js.map +0 -1
- package/dist/chunk-LDCQZPDG.js +0 -11
- package/dist/chunk-LDCQZPDG.js.map +0 -1
- package/dist/chunk-N4KNGDYY.js +0 -1963
- package/dist/chunk-N4KNGDYY.js.map +0 -1
- package/dist/chunk-NMX4C6LC.js +0 -332
- package/dist/chunk-NMX4C6LC.js.map +0 -1
- package/dist/chunk-QVH5KKBR.js +0 -374
- package/dist/chunk-QVH5KKBR.js.map +0 -1
- package/dist/context-DKkamYX_.d.ts +0 -31
- package/dist/guardrail-hooks-slK-z0Dz.d.ts +0 -83
- package/dist/index-LqEvaRk-.d.ts +0 -299
- package/dist/workspace-pre-tool-use-C6nidc0q.d.ts +0 -333
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/analyzer-bridge.ts","../src/lib/observability-bridge.ts","../src/lib/context-pack-adoption.ts","../src/lib/tool-exec-span-registry.ts","../src/lib/library-tool-sdk.ts"],"sourcesContent":["/**\n * Analyzer Bridge — integrates artifact-contracts-analyzer as a standard\n * runtime tool provider.\n *\n * Wraps analyzeImpact, generateContextPack, and buildCallGraph behind a\n * lazily-initialised DependencyGraph, and exposes them as SdkFunctionTool[]\n * for adapter consumption.\n *\n * `artifact-contracts-analyzer` is a peerDependency (optional) loaded via\n * dynamic import; when absent, every method returns a descriptive error\n * rather than crashing.\n */\n\nimport type { SdkFunctionTool } from \"./library-tool-sdk.js\";\n\n// ---------------------------------------------------------------------------\n// Re-exported duck types — the bridge never statically imports the analyzer\n// package, so we define the minimal shapes callers need.\n// ---------------------------------------------------------------------------\n\n/** Subset of DependencyGraph that the bridge caches and exposes. */\nexport type DependencyGraph = Record<string, unknown>;\n\n/** Subset of ImpactReport returned by analyzeImpact. */\nexport type ImpactReport = Record<string, unknown>;\n\n/** Subset of ContextPack returned by generateContextPack. */\nexport type ContextPack = {\n entries: Array<{\n path: string;\n artifactId?: string;\n relevanceScore: number;\n contentMode: string;\n content: string;\n reason: string;\n }>;\n metadata: {\n totalTokens: number;\n budgetTokens: number;\n filesIncluded: number;\n filesExcluded: number;\n filesReferenced: number;\n artifactsCovered: string[];\n generatedAt: string;\n };\n taskId?: string;\n};\n\n/** Subset of CallGraph returned by buildCallGraph. */\nexport type CallGraph = Record<string, unknown>;\n\n/** Subset of ContextMap returned by getContextMap. */\nexport type ContextMap = Record<string, unknown>;\n\nexport interface GetContextMapInput {\n instruction: string;\n candidates: Array<{\n path?: string;\n symbolId?: string;\n artifactId?: string;\n }>;\n depth?: number;\n direction?: \"downstream\" | \"upstream\" | \"both\";\n budgetTokens?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Bridge options and interface\n// ---------------------------------------------------------------------------\n\nexport interface AnalyzerBridgeOptions {\n projectRoot: string;\n navigationIndex?: Record<string, unknown>;\n artifactPatterns?: Map<string, string[]>;\n manifests?: string[];\n}\n\nexport interface AnalyzeImpactInput {\n direction: \"downstream\" | \"upstream\";\n maxDepth: number;\n limit: number;\n}\n\nexport interface GenerateContextPackInput {\n budgetTokens: number;\n granularity: \"file\" | \"symbol\";\n}\n\nexport interface BuildCallGraphInput {\n maxDepth: number;\n direction: \"forward\" | \"reverse\";\n}\n\nexport interface AnalyzerBridge {\n buildGraph(): Promise<void>;\n getGraph(): Promise<DependencyGraph>;\n analyzeImpact(\n changed: string[],\n options?: Partial<AnalyzeImpactInput>,\n ): Promise<ImpactReport>;\n generateContextPack(\n changed: string[],\n options?: Partial<GenerateContextPackInput>,\n ): Promise<ContextPack>;\n buildCallGraph(\n entry: string,\n options?: Partial<BuildCallGraphInput>,\n ): Promise<CallGraph>;\n getContextMap(\n input: GetContextMapInput,\n ): Promise<ContextMap>;\n invalidateCache(): void;\n buildAnalyzerTools(): SdkFunctionTool[];\n}\n\n// ---------------------------------------------------------------------------\n// Dynamic import helper\n// ---------------------------------------------------------------------------\n\ninterface AnalyzerModule {\n buildAstGraph: (options: Record<string, unknown>) => Promise<{ graph: Record<string, unknown>; fileContents: Map<string, string> }>;\n buildDependencyGraph: (options: Record<string, unknown>) => Promise<DependencyGraph>;\n analyzeImpact: (options: Record<string, unknown>) => Promise<ImpactReport>;\n generateContextPack: (options: Record<string, unknown>) => Promise<ContextPack>;\n getContextMap: (options: Record<string, unknown>) => Promise<ContextMap>;\n buildCallGraph: (options: Record<string, unknown>) => CallGraph;\n createDefaultRegistry: () => Record<string, unknown>;\n loadExternalProviders?: (projectRoot: string, configPath?: string) => Promise<unknown[]>;\n integrateExternalInsights?: (\n graph: DependencyGraph,\n providers: unknown[],\n query: Record<string, unknown>,\n ) => Promise<{ graph: DependencyGraph }>;\n}\n\nconst ANALYZER_PKG = \"artifact-contracts-analyzer\";\n\nasync function loadAnalyzerModule(): Promise<AnalyzerModule> {\n const mod = (await import(\n /* webpackIgnore: true */ ANALYZER_PKG\n )) as Record<string, unknown>;\n return mod as unknown as AnalyzerModule;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport function createAnalyzerBridge(\n options: AnalyzerBridgeOptions,\n): AnalyzerBridge {\n const { projectRoot, navigationIndex, artifactPatterns, manifests } = options;\n\n let cachedGraph: DependencyGraph | null = null;\n let cachedFileContents: Map<string, string> | null = null;\n let graphBuildPromise: Promise<void> | null = null;\n\n async function ensureGraph(): Promise<DependencyGraph> {\n if (cachedGraph) return cachedGraph;\n if (graphBuildPromise) {\n await graphBuildPromise;\n return cachedGraph!;\n }\n graphBuildPromise = doBuildGraph();\n await graphBuildPromise;\n return cachedGraph!;\n }\n\n async function doBuildGraph(): Promise<void> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n throw new Error(\n `artifact-contracts-analyzer is not available. ` +\n `Install it to use analyzer features: ${msg}`,\n );\n }\n\n const patterns = artifactPatterns ?? new Map<string, string[]>();\n const registry = mod.createDefaultRegistry();\n\n const astResult = await mod.buildAstGraph({\n projectRoot,\n artifactPatterns: patterns,\n registry,\n });\n\n cachedFileContents = astResult.fileContents;\n\n cachedGraph = await mod.buildDependencyGraph({\n ast: astResult.graph,\n projectRoot,\n artifactPatterns: patterns,\n manifests: manifests ?? [],\n });\n\n if (\n typeof (mod as { loadExternalProviders?: unknown }).loadExternalProviders ===\n \"function\" &&\n typeof (mod as { integrateExternalInsights?: unknown })\n .integrateExternalInsights === \"function\"\n ) {\n try {\n const loadProviders = (\n mod as {\n loadExternalProviders: (\n projectRoot: string,\n ) => Promise<unknown[]>;\n }\n ).loadExternalProviders;\n const integrate = (\n mod as {\n integrateExternalInsights: (\n graph: DependencyGraph,\n providers: unknown[],\n query: Record<string, unknown>,\n ) => Promise<{ graph: DependencyGraph }>;\n }\n ).integrateExternalInsights;\n const providers = await loadProviders(projectRoot);\n if (providers.length > 0) {\n const integration = await integrate(\n cachedGraph,\n providers,\n { projectRoot },\n );\n cachedGraph = integration.graph;\n }\n } catch {\n // External providers are optional — fail open.\n }\n }\n }\n\n const bridge: AnalyzerBridge = {\n async buildGraph(): Promise<void> {\n await ensureGraph();\n },\n\n async getGraph(): Promise<DependencyGraph> {\n return ensureGraph();\n },\n\n async analyzeImpact(\n changed: string[],\n opts?: Partial<AnalyzeImpactInput>,\n ): Promise<ImpactReport> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n error:\n \"artifact-contracts-analyzer is not installed. Install it as a peer dependency to use impact analysis.\",\n changed,\n };\n }\n\n const graph = await ensureGraph();\n return mod.analyzeImpact({\n graph,\n changed,\n direction: opts?.direction ?? \"downstream\",\n ...(opts?.maxDepth !== undefined ? { maxDepth: opts.maxDepth } : {}),\n ...(opts?.limit !== undefined ? { limit: opts.limit } : {}),\n ...(navigationIndex ? { navigationIndex } : {}),\n });\n },\n\n async generateContextPack(\n changed: string[],\n opts?: Partial<GenerateContextPackInput>,\n ): Promise<ContextPack> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n entries: [],\n metadata: {\n totalTokens: 0,\n budgetTokens: opts?.budgetTokens ?? 50_000,\n filesIncluded: 0,\n filesExcluded: 0,\n filesReferenced: 0,\n artifactsCovered: [],\n generatedAt: new Date().toISOString(),\n },\n } as ContextPack;\n }\n\n const graph = await ensureGraph();\n return mod.generateContextPack({\n graph,\n changed,\n projectRoot,\n ...(opts?.budgetTokens !== undefined\n ? { budgetTokens: opts.budgetTokens }\n : {}),\n ...(opts?.granularity ? { granularity: opts.granularity } : {}),\n ...(navigationIndex ? { navigationIndex } : {}),\n ...(cachedFileContents ? { fileContents: cachedFileContents } : {}),\n });\n },\n\n async buildCallGraph(\n entry: string,\n opts?: Partial<BuildCallGraphInput>,\n ): Promise<CallGraph> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n error:\n \"artifact-contracts-analyzer is not installed. Install it as a peer dependency to use call graph analysis.\",\n entry,\n };\n }\n\n const graph = await ensureGraph();\n return mod.buildCallGraph({\n graph,\n entry,\n ...(opts?.maxDepth !== undefined ? { maxDepth: opts.maxDepth } : {}),\n ...(opts?.direction ? { direction: opts.direction } : {}),\n }) as CallGraph;\n },\n\n async getContextMap(input: GetContextMapInput): Promise<ContextMap> {\n let mod: AnalyzerModule;\n try {\n mod = await loadAnalyzerModule();\n } catch {\n return {\n error:\n \"artifact-contracts-analyzer is not installed. Install it as a peer dependency to use context map analysis.\",\n instruction: input.instruction,\n };\n }\n\n const graph = await ensureGraph();\n return mod.getContextMap({\n graph,\n projectRoot,\n instruction: input.instruction,\n candidates: input.candidates,\n ...(input.depth !== undefined ? { depth: input.depth } : {}),\n ...(input.direction ? { direction: input.direction } : {}),\n ...(input.budgetTokens !== undefined\n ? { budgetTokens: input.budgetTokens }\n : {}),\n ...(navigationIndex ? { navigationIndex } : {}),\n ...(cachedFileContents ? { fileContents: cachedFileContents } : {}),\n });\n },\n\n invalidateCache(): void {\n cachedGraph = null;\n cachedFileContents = null;\n graphBuildPromise = null;\n },\n\n buildAnalyzerTools(): SdkFunctionTool[] {\n return [\n {\n name: \"analyzer.analyzeImpact\",\n description:\n \"Analyze the impact of changed files across the dependency graph\",\n inputSchema: {\n type: \"object\",\n properties: {\n changed: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"File paths that changed\",\n },\n direction: {\n type: \"string\",\n enum: [\"downstream\", \"upstream\"],\n description:\n \"Traversal direction. downstream = what breaks if this changes\",\n },\n maxDepth: {\n type: \"number\",\n description: \"Maximum BFS depth to explore\",\n },\n limit: {\n type: \"number\",\n description:\n \"Cap the number of affected entries returned\",\n },\n },\n required: [\"changed\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const changed = args.changed as string[];\n const result = await bridge.analyzeImpact(changed, {\n direction: args.direction as\n | \"downstream\"\n | \"upstream\"\n | undefined,\n maxDepth: args.maxDepth as number | undefined,\n limit: args.limit as number | undefined,\n });\n return JSON.stringify(result);\n },\n },\n {\n name: \"analyzer.generateContextPack\",\n description:\n \"Generate a token-budget-constrained context pack for changed files\",\n inputSchema: {\n type: \"object\",\n properties: {\n changed: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"File paths that changed\",\n },\n budgetTokens: {\n type: \"number\",\n description: \"Token budget for the context pack\",\n },\n granularity: {\n type: \"string\",\n enum: [\"file\", \"symbol\"],\n description: \"Context granularity level\",\n },\n },\n required: [\"changed\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const changed = args.changed as string[];\n const result = await bridge.generateContextPack(changed, {\n budgetTokens: args.budgetTokens as number | undefined,\n granularity: args.granularity as\n | \"file\"\n | \"symbol\"\n | undefined,\n });\n return JSON.stringify(result);\n },\n },\n {\n name: \"analyzer.getContextMap\",\n description:\n \"Build a structured context map from instruction and candidate paths/artifacts/symbols\",\n inputSchema: {\n type: \"object\",\n properties: {\n instruction: {\n type: \"string\",\n description: \"Natural-language task instruction\",\n },\n candidates: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n symbolId: { type: \"string\" },\n artifactId: { type: \"string\" },\n },\n },\n description:\n \"Candidate seeds from navigation-index (paths, symbols, artifacts)\",\n },\n depth: {\n type: \"number\",\n description: \"Traversal depth (default 2)\",\n },\n direction: {\n type: \"string\",\n enum: [\"downstream\", \"upstream\", \"both\"],\n description: \"Impact traversal direction\",\n },\n budgetTokens: {\n type: \"number\",\n description: \"Token budget for suggested read targets\",\n },\n },\n required: [\"instruction\", \"candidates\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const result = await bridge.getContextMap({\n instruction: args.instruction as string,\n candidates: args.candidates as GetContextMapInput[\"candidates\"],\n depth: args.depth as number | undefined,\n direction: args.direction as GetContextMapInput[\"direction\"],\n budgetTokens: args.budgetTokens as number | undefined,\n });\n return JSON.stringify(result);\n },\n },\n {\n name: \"analyzer.buildCallGraph\",\n description: \"Build a call graph rooted at a symbol\",\n inputSchema: {\n type: \"object\",\n properties: {\n entry: {\n type: \"string\",\n description:\n \"Entry symbolId (filePath#name) to root the call graph at\",\n },\n maxDepth: {\n type: \"number\",\n description: \"Maximum traversal depth\",\n },\n direction: {\n type: \"string\",\n enum: [\"forward\", \"reverse\"],\n description:\n \"Traversal direction: forward (callees) or reverse (callers)\",\n },\n },\n required: [\"entry\"],\n },\n handler: async (\n args: Record<string, unknown>,\n ): Promise<string> => {\n const entry = args.entry as string;\n const result = await bridge.buildCallGraph(entry, {\n maxDepth: args.maxDepth as number | undefined,\n direction: args.direction as\n | \"forward\"\n | \"reverse\"\n | undefined,\n });\n return JSON.stringify(result);\n },\n },\n ];\n },\n };\n\n return bridge;\n}\n\n// ---------------------------------------------------------------------------\n// ContextPack prompt rendering utilities\n// ---------------------------------------------------------------------------\n\nfunction isContextPackEntry(\n value: unknown,\n): value is ContextPack[\"entries\"][number] {\n if (typeof value !== \"object\" || value === null) return false;\n const entry = value as Record<string, unknown>;\n return (\n typeof entry.path === \"string\" &&\n (entry.artifactId === undefined || typeof entry.artifactId === \"string\") &&\n typeof entry.relevanceScore === \"number\" &&\n typeof entry.contentMode === \"string\" &&\n typeof entry.content === \"string\" &&\n typeof entry.reason === \"string\"\n );\n}\n\nfunction isContextPackMetadata(\n value: unknown,\n): value is ContextPack[\"metadata\"] {\n if (typeof value !== \"object\" || value === null) return false;\n const meta = value as Record<string, unknown>;\n return (\n typeof meta.totalTokens === \"number\" &&\n typeof meta.budgetTokens === \"number\" &&\n typeof meta.filesIncluded === \"number\" &&\n typeof meta.filesExcluded === \"number\" &&\n typeof meta.filesReferenced === \"number\" &&\n Array.isArray(meta.artifactsCovered) &&\n meta.artifactsCovered.every((a) => typeof a === \"string\") &&\n typeof meta.generatedAt === \"string\"\n );\n}\n\n/**\n * The single gate between untyped analyzer output and the `ContextPack` type\n * declared above. Whatever passes may be walked without further guarding; what\n * fails is not a ContextPack and none of it may be read as one.\n *\n * Every declared field is checked, including the ones no caller reads today,\n * because the predicate's return type — not the set of fields some caller\n * happens to dereference — is what it promises. Checking a subset promises a\n * `ContextPack` while verifying something weaker, and the difference surfaces\n * as a TypeError one dereference away: `{ entries: [null], metadata: {\n * totalTokens, budgetTokens } }` satisfied an `entries`-is-an-array check and\n * threw in both callers (#326).\n */\nexport function isContextPack(value: unknown): value is ContextPack {\n if (typeof value !== \"object\" || value === null) return false;\n const obj = value as Record<string, unknown>;\n return (\n Array.isArray(obj.entries) &&\n obj.entries.every(isContextPackEntry) &&\n isContextPackMetadata(obj.metadata) &&\n (obj.taskId === undefined || typeof obj.taskId === \"string\")\n );\n}\n\n/**\n * Render a ContextPack as a structured prompt section.\n * Used by task-runner when `variables.analyzerContextPack` is present.\n */\nexport function renderContextPackPrompt(pack: ContextPack): string {\n const m = pack.metadata;\n const sections: string[] = [];\n\n sections.push(\"## Source Code Context\");\n\n sections.push(\n `### Budget\\n- Tokens used: ${m.totalTokens} / ${m.budgetTokens}\\n` +\n `- Files included: ${m.filesIncluded}, excluded: ${m.filesExcluded}, referenced: ${m.filesReferenced}`,\n );\n\n if (m.artifactsCovered.length > 0) {\n sections.push(\n `### Affected Artifacts\\n${m.artifactsCovered.map((a) => `- ${a}`).join(\"\\n\")}`,\n );\n }\n\n if (pack.entries.length > 0) {\n const fileBlocks: string[] = [];\n for (const entry of pack.entries) {\n const ext = entry.path.split(\".\").pop() ?? \"\";\n const header = `#### ${entry.path} (relevance: ${entry.relevanceScore}, mode: ${entry.contentMode})`;\n const reason = `> ${entry.reason}`;\n if (entry.content) {\n fileBlocks.push(\n `${header}\\n${reason}\\n\\n\\`\\`\\`${ext}\\n${entry.content}\\n\\`\\`\\``,\n );\n } else {\n fileBlocks.push(`${header}\\n${reason}`);\n }\n }\n sections.push(`### Files\\n${fileBlocks.join(\"\\n\\n\")}`);\n }\n\n return sections.join(\"\\n\\n\");\n}\n","/**\n * observability-bridge.ts\n *\n * Bridge between @aaac/runtime execution and @aaac/observability agent-axis spans.\n *\n * Responsibilities:\n * - Generate ExecutionEnvelope (run_id = UUIDv7) for every task/workflow execution\n * - Emit agent.session (open/close) for runWorkflow() — root run span\n * - Emit agent.subagent (open/close) for runTask() — handoff/task span\n * - Emit toolchain.execution (open/close) for toolchain tool invocations\n * - Observer is OPTIONAL — all emit* functions are no-ops when observer is undefined\n *\n * No circular dependency: @aaac/observability does NOT import @aaac/runtime.\n * Types (ExecutionEnvelope, EmitInput) are consumed from @aaac/observability.\n *\n * event-catalog.md §1.5, §2.2 / OBSERVABILITY_TASKS.md Phase 1 / architecture.md §6, §7\n */\n\nimport { generateId } from \"@aaac/observability\";\nimport type { ExecutionEnvelope, EmitInput, AttrValue, CanonicalLink } from \"@aaac/observability\";\n\n// ── Re-exports ────────────────────────────────────────────────────────────────\n\nexport type { ExecutionEnvelope } from \"@aaac/observability\";\n\n// ── TokenUsage ────────────────────────────────────────────────────────────────\n\n/** Token usage metrics returned by LLM adapters after a query/session. */\nexport interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n totalTokens?: number;\n cacheReadTokens?: number;\n cacheCreationTokens?: number;\n}\n\n// ── Observability env propagation (git-hook correlation, #115) ─────────────────\n\n/** Observability correlation ids propagated to spawned subprocesses. */\nexport interface ObservabilityIds {\n /** Agent-axis session id (= the session/run envelope run_id). */\n sessionId?: string;\n /** Distributed trace id, when available. */\n traceId?: string;\n /** Execution run id (ExecutionEnvelope.run_id). */\n runId?: string;\n}\n\n/** Environment variable names read by `.cursor/hooks/observ-record.sh`. */\nexport const OBSERVABILITY_ENV_VARS = {\n sessionId: \"AAAC_SESSION_ID\",\n traceId: \"AAAC_TRACE_ID\",\n runId: \"AAAC_RUN_ID\",\n} as const;\n\n/**\n * Build a subprocess environment that propagates the active observability\n * correlation ids as AAAC_SESSION_ID / AAAC_TRACE_ID / AAAC_RUN_ID.\n *\n * When @aaac/runtime spawns `git` (directly via a toolchain check, or\n * indirectly through an agent shell), the git `post-commit` hook runs\n * `.cursor/hooks/observ-record.sh`, whose highest-priority session_id source is\n * `$AAAC_SESSION_ID` (#115). Propagating these ids lets the promotion.commit /\n * promotion.file events emitted by the hook correlate to the originating agent\n * session.\n *\n * Returns a shallow clone of {@link baseEnv}; only ids that are defined and\n * non-empty are set, so the child never inherits empty/stale values.\n */\nexport function buildObservabilityEnv(\n ids: ObservabilityIds,\n baseEnv: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...baseEnv };\n if (ids.sessionId) env[OBSERVABILITY_ENV_VARS.sessionId] = ids.sessionId;\n if (ids.traceId) env[OBSERVABILITY_ENV_VARS.traceId] = ids.traceId;\n if (ids.runId) env[OBSERVABILITY_ENV_VARS.runId] = ids.runId;\n return env;\n}\n\n// ── ObserverEmitFn ────────────────────────────────────────────────────────────\n\n/**\n * Minimal observer emit signature — structurally matches EventCollector.emit().\n * Pass `collector.emit.bind(collector)` to wire up the full observability pipeline.\n * When undefined, all emission is a no-op.\n */\nexport type ObserverEmitFn = (event: EmitInput) => void;\n\n/**\n * Serialize writes through a shared in-process observer.\n * Concurrent workflow steps that emit in parallel can hit SQLITE_BUSY on the\n * shared SqliteSink without this guard.\n */\nexport function serializeObserverEmit(emit: ObserverEmitFn): ObserverEmitFn {\n let queue: EmitInput[] = [];\n let draining = false;\n\n function drain(): void {\n if (draining) return;\n draining = true;\n try {\n while (queue.length > 0) {\n const next = queue.shift()!;\n emit(next);\n }\n } finally {\n draining = false;\n if (queue.length > 0) {\n drain();\n }\n }\n }\n\n return (event: EmitInput) => {\n queue.push(event);\n drain();\n };\n}\n\n// ── Envelope creation ─────────────────────────────────────────────────────────\n\nexport interface EnvelopeParams {\n /** run_id of the parent execution (populated by workflow-runner for task spans). */\n parentRunId?: string;\n /** Component / agent identifier from the agent-contracts definition. */\n componentId?: string;\n /** Agent that issued this execution (handoff source). */\n fromAgent?: string;\n /** Agent that receives this execution (handoff target). */\n toAgent?: string;\n /** agent-contracts schema version. */\n contractVersion?: string;\n /** LLM adapter identifier (e.g. 'claude-agent-sdk'). */\n adapter?: string;\n /** LLM model identifier (e.g. 'claude-opus-4-5'). */\n model?: string;\n /** Task instance identifier within the run. */\n taskInstanceId?: string;\n}\n\n/**\n * Create an ExecutionEnvelope with a fresh UUIDv7 run_id and current timestamp.\n * Only defined fields are included — undefined values are omitted.\n */\nexport function createExecutionEnvelope(params: EnvelopeParams = {}): ExecutionEnvelope {\n const envelope: ExecutionEnvelope = {\n run_id: generateId(),\n timestamp: new Date().toISOString(),\n };\n if (params.parentRunId !== undefined) envelope.parent_run_id = params.parentRunId;\n if (params.componentId !== undefined) envelope.component_id = params.componentId;\n if (params.fromAgent !== undefined) envelope.from_agent = params.fromAgent;\n if (params.toAgent !== undefined) envelope.to_agent = params.toAgent;\n if (params.contractVersion !== undefined) envelope.contract_version = params.contractVersion;\n if (params.adapter !== undefined) envelope.adapter = params.adapter;\n if (params.model !== undefined) envelope.model = params.model;\n if (params.taskInstanceId !== undefined) envelope.task_instance_id = params.taskInstanceId;\n return envelope;\n}\n\n// ── attribute builder helpers ─────────────────────────────────────────────────\n\n/** Build attribute record; omits keys with undefined/empty-string values. */\nfunction attrs(base: Record<string, AttrValue | undefined>): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n for (const [k, v] of Object.entries(base)) {\n if (v !== undefined && v !== \"\") out[k] = v;\n }\n return out;\n}\n\n/** Resolve agent.session_id for Agent-axis child spans. */\nfunction resolveAgentSessionId(envelope: ExecutionEnvelope, parentSpanId?: string): string {\n return envelope.parent_run_id ?? parentSpanId ?? envelope.run_id;\n}\n\n/**\n * Extract token usage fields into OTel GenAI semantic conventions attributes.\n *\n * Standard keys (#125 §6):\n * gen_ai.usage.input_tokens — OTel GenAI: total input tokens for the operation\n * gen_ai.usage.output_tokens — OTel GenAI: total output tokens for the operation\n * gen_ai.usage.total_tokens — non-standard extension (no OTel equivalent)\n * gen_ai.usage.cache_read_input_tokens — Anthropic-specific extension\n * gen_ai.usage.cache_creation_input_tokens — Anthropic-specific extension\n * cost_usd — OTel GenAI に標準キーが存在しないためカスタム属性のまま据え置き\n */\nfunction tokenAttrs(meta: Record<string, unknown>): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n const tu = meta.token_usage;\n if (tu && typeof tu === \"object\") {\n const t = tu as Record<string, unknown>;\n if (typeof t.input_tokens === \"number\") out[\"gen_ai.usage.input_tokens\"] = t.input_tokens;\n if (typeof t.output_tokens === \"number\") out[\"gen_ai.usage.output_tokens\"] = t.output_tokens;\n if (typeof t.total_tokens === \"number\") out[\"gen_ai.usage.total_tokens\"] = t.total_tokens;\n if (typeof t.cache_read_input_tokens === \"number\") out[\"gen_ai.usage.cache_read_input_tokens\"] = t.cache_read_input_tokens;\n if (typeof t.cache_creation_input_tokens === \"number\") out[\"gen_ai.usage.cache_creation_input_tokens\"] = t.cache_creation_input_tokens;\n }\n if (typeof meta.cost_usd === \"number\") out[\"cost_usd\"] = meta.cost_usd;\n return out;\n}\n\n// ── agent.session ─────────────────────────────────────────────────────────────\n\n/**\n * Emit an agent.session open span (root workflow/session execution).\n *\n * Uses envelope.run_id as the spanId so that child agent.subagent spans can\n * reference it as parentSpanId for hierarchical correlation.\n *\n * Returns the spanId emitted (= envelope.run_id).\n * Returns undefined when observer is undefined (no-op).\n *\n * event-catalog.md §2.2 — required: agent.session_id; axis: agent\n */\nexport function emitSessionOpen(\n observer: ObserverEmitFn | undefined,\n envelope: ExecutionEnvelope,\n workflowId: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = envelope.run_id;\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.session\",\n lifecycle: \"open\",\n spanId,\n parentSpanId: envelope.parent_run_id,\n attributes: attrs({\n axis: \"agent\",\n \"agent.session_id\": envelope.run_id,\n \"agent.run_id\": envelope.run_id,\n \"workflow.id\": workflowId,\n \"component.id\": envelope.component_id,\n \"gen_ai.request.model\": envelope.model,\n \"gen_ai.system\": envelope.adapter,\n contract_version: envelope.contract_version,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an agent.session close span.\n *\n * `errorMessage` is set on the exception path (workflow body threw) so the\n * failure cause is recorded alongside the run status. Omitted on the normal path.\n *\n * event-catalog.md §2.2 — optional: agent.session.duration_ms, agent.status, agent.error\n */\nexport function emitSessionClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n envelope: ExecutionEnvelope,\n durationMs: number,\n status: string,\n errorMessage?: string,\n): void {\n if (!observer) return;\n\n const metaAttrs: Record<string, AttrValue> =\n envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.session\",\n lifecycle: \"close\",\n spanId,\n attributes: {\n ...attrs({\n axis: \"agent\",\n \"agent.session_id\": envelope.run_id,\n \"agent.session.duration_ms\": durationMs,\n \"agent.status\": status,\n \"agent.error\": errorMessage,\n }),\n ...metaAttrs,\n },\n });\n}\n\n// ── agent.subagent ────────────────────────────────────────────────────────────\n\n/**\n * Emit an agent.subagent open span (task/handoff execution).\n *\n * Uses envelope.run_id as the spanId and parentSpanId for hierarchical correlation\n * (typically the session span's run_id).\n *\n * Returns the spanId emitted (= envelope.run_id).\n * Returns undefined when observer is undefined (no-op).\n *\n * event-catalog.md §2.2 — required: agent.role; axis: agent\n */\nexport function emitSubagentOpen(\n observer: ObserverEmitFn | undefined,\n envelope: ExecutionEnvelope,\n parentSpanId: string | undefined,\n taskId: string,\n agentRole: string,\n sessionId?: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = envelope.run_id;\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.subagent\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"agent.session_id\": sessionId ?? resolveAgentSessionId(envelope, parentSpanId),\n \"agent.role\": agentRole,\n \"agent.kind\": \"task\",\n \"task.id\": taskId,\n \"agent.run_id\": envelope.run_id,\n \"agent.parent_run_id\": envelope.parent_run_id,\n \"gen_ai.request.model\": envelope.model,\n \"gen_ai.system\": envelope.adapter,\n \"component.id\": envelope.component_id,\n \"agent.from_agent\": envelope.from_agent,\n \"agent.to_agent\": envelope.to_agent,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an agent.subagent close span.\n *\n * `errorMessage` records the failure cause on `agent.error` (parity with\n * emitSessionClose); it is omitted from the attributes when undefined.\n *\n * event-catalog.md §2.2 — optional: agent.duration_ms, agent.status, agent.error,\n * token_usage, cost_usd\n */\nexport function emitSubagentClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n envelope: ExecutionEnvelope,\n durationMs: number,\n status: string,\n agentRole: string,\n errorMessage?: string,\n sessionId?: string,\n): void {\n if (!observer) return;\n\n const metaAttrs: Record<string, AttrValue> =\n envelope.execution_metadata ? tokenAttrs(envelope.execution_metadata) : {};\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.subagent\",\n lifecycle: \"close\",\n spanId,\n attributes: {\n ...attrs({\n axis: \"agent\",\n \"agent.session_id\": sessionId ?? resolveAgentSessionId(envelope),\n \"agent.role\": agentRole,\n \"agent.status\": status,\n \"agent.duration_ms\": durationMs,\n \"agent.error\": errorMessage,\n }),\n ...metaAttrs,\n },\n });\n}\n\n// ── evaluate.iteration ────────────────────────────────────────────────────────\n\n/**\n * Emit an evaluate.iteration open span (one closed-loop iteration).\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitIterationOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n evaluateTaskId: string,\n loopTo: string,\n iterationNumber: number,\n maxIterations: number,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"evaluate.iteration\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"evaluate.task\": evaluateTaskId,\n \"evaluate.loop_to\": loopTo,\n \"evaluate.iteration\": iterationNumber,\n \"evaluate.max_iterations\": maxIterations,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an evaluate.iteration close span.\n */\nexport function emitIterationClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n evaluateTaskId: string,\n iterationNumber: number,\n verdict: string,\n durationMs: number,\n feedbackInjected: boolean,\n): void {\n if (!observer) return;\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"evaluate.iteration\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"agent\",\n \"evaluate.task\": evaluateTaskId,\n \"evaluate.iteration\": iterationNumber,\n \"evaluate.verdict\": verdict,\n \"evaluate.duration_ms\": durationMs,\n \"evaluate.feedback_injected\": feedbackInjected,\n }),\n });\n}\n\n/**\n * Emit an evaluate.metric instant event when an evaluate step terminates.\n */\nexport function emitIterationMetric(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n evaluateTaskId: string,\n totalIterations: number,\n terminalOutcome: string,\n): void {\n if (!observer) return;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"evaluate.metric\",\n lifecycle: \"instant\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"evaluate.task\": evaluateTaskId,\n \"evaluate.total_iterations\": totalIterations,\n \"evaluate.terminal_outcome\": terminalOutcome,\n }),\n });\n}\n\n// ── InnerSpanOptions (for adapter plumbing) ──────────────────────────────────\n\n/** Options forwarded from task-runner to adapters for inner turn-level spans. */\nexport interface InnerSpanOptions {\n observer?: ObserverEmitFn;\n parentSpanId?: string;\n /**\n * Agent-axis session id (= the enclosing agent.session run_id). Threaded so\n * inner agent.llm_turn / agent.tool_exec spans carry a non-NULL session_id and\n * join the cross-axis correlation rules (#143 / #140).\n */\n sessionId?: string;\n}\n\n// ── agent.llm_turn ───────────────────────────────────────────────────────────\n\n/**\n * Emit an agent.llm_turn open span when a new LLM turn begins.\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitLlmTurnOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n turnNumber: number,\n model?: string,\n llmParams?: { temperature?: number; reasoningEffort?: string },\n sessionId?: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.llm_turn\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"agent\",\n \"agent.session_id\": sessionId,\n \"llm.turn_number\": turnNumber,\n \"gen_ai.request.model\": model,\n \"llm.temperature\": llmParams?.temperature,\n \"llm.reasoning_effort\": llmParams?.reasoningEffort,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit an agent.llm_turn close span.\n */\nexport function emitLlmTurnClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n turnNumber: number,\n durationMs: number,\n tokenAttrs?: {\n inputTokens?: number;\n outputTokens?: number;\n cacheHitTokens?: number;\n toolCallsCount?: number;\n },\n sessionId?: string,\n): void {\n if (!observer) return;\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.llm_turn\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"agent\",\n \"agent.session_id\": sessionId,\n \"llm.turn_number\": turnNumber,\n \"llm.duration_ms\": durationMs,\n \"gen_ai.usage.input_tokens\": tokenAttrs?.inputTokens,\n \"gen_ai.usage.output_tokens\": tokenAttrs?.outputTokens,\n \"llm.cache_hit_tokens\": tokenAttrs?.cacheHitTokens,\n \"llm.tool_calls_count\": tokenAttrs?.toolCallsCount,\n }),\n });\n}\n\n// ── agent.tool_exec ──────────────────────────────────────────────────────────\n\n/** Optional emit-time attributes and links for agent.tool_exec spans (#151). */\nexport interface ToolExecOpenOptions {\n sessionId?: string;\n extraAttributes?: Record<string, AttrValue>;\n links?: CanonicalLink[];\n}\n\nexport interface ToolExecCloseOptions {\n sessionId?: string;\n extraAttributes?: Record<string, AttrValue>;\n outputSummary?: string;\n}\n\nfunction resolveToolExecOpenOptions(\n sessionIdOrOptions?: string | ToolExecOpenOptions,\n): ToolExecOpenOptions {\n if (typeof sessionIdOrOptions === \"string\") {\n return { sessionId: sessionIdOrOptions };\n }\n return sessionIdOrOptions ?? {};\n}\n\nfunction resolveToolExecCloseOptions(\n sessionIdOrOptions?: string | ToolExecCloseOptions,\n): ToolExecCloseOptions {\n if (typeof sessionIdOrOptions === \"string\") {\n return { sessionId: sessionIdOrOptions };\n }\n return sessionIdOrOptions ?? {};\n}\n\n/**\n * Emit an agent.tool_exec open span when a tool execution begins.\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitToolExecOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n toolName: string,\n inputSummary: string,\n turnNumber: number,\n sessionIdOrOptions?: string | ToolExecOpenOptions,\n): string | undefined {\n if (!observer) return undefined;\n\n const opts = resolveToolExecOpenOptions(sessionIdOrOptions);\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.tool_exec\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n links: opts.links,\n attributes: {\n ...attrs({\n axis: \"agent\",\n \"agent.session_id\": opts.sessionId,\n \"tool.name\": toolName,\n \"tool.input_summary\": inputSummary,\n \"llm.turn_number\": turnNumber,\n }),\n ...(opts.extraAttributes ?? {}),\n },\n });\n return spanId;\n}\n\n/**\n * Emit an agent.tool_exec close span.\n */\nexport function emitToolExecClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n toolName: string,\n durationMs: number,\n sessionIdOrOptions?: string | ToolExecCloseOptions,\n): void {\n if (!observer) return;\n\n const opts = resolveToolExecCloseOptions(sessionIdOrOptions);\n observer({\n source: \"aaac-runtime\",\n eventType: \"agent.tool_exec\",\n lifecycle: \"close\",\n spanId,\n attributes: {\n ...attrs({\n axis: \"agent\",\n \"agent.session_id\": opts.sessionId,\n \"tool.name\": toolName,\n \"tool.duration_ms\": durationMs,\n \"tool.output_summary\": opts.outputSummary,\n }),\n ...(opts.extraAttributes ?? {}),\n },\n });\n}\n\n// ── toolchain.execution ──────────────────────────────────────────────────────\n\n/**\n * Emit a toolchain.execution open span when a toolchain tool is invoked.\n *\n * Returns the spanId emitted (= generated UUIDv7).\n * Returns undefined when observer is undefined (no-op).\n */\nexport function emitToolchainOpen(\n observer: ObserverEmitFn | undefined,\n parentSpanId: string | undefined,\n toolchainId: string,\n operation: string,\n artifactIds: string[],\n componentId?: string,\n): string | undefined {\n if (!observer) return undefined;\n\n const spanId = generateId();\n observer({\n source: \"aaac-runtime\",\n eventType: \"toolchain.execution\",\n lifecycle: \"open\",\n spanId,\n parentSpanId,\n attributes: attrs({\n axis: \"toolchain\",\n \"toolchain.id\": toolchainId,\n \"toolchain.operation\": operation,\n \"toolchain.artifact_ids\": artifactIds.join(\",\"),\n \"component.id\": componentId,\n }),\n });\n return spanId;\n}\n\n/**\n * Emit a toolchain.execution close span.\n */\nexport function emitToolchainClose(\n observer: ObserverEmitFn | undefined,\n spanId: string,\n toolchainId: string,\n operation: string,\n durationMs: number,\n status: \"success\" | \"failure\",\n errorMessage?: string,\n): void {\n if (!observer) return;\n\n observer({\n source: \"aaac-runtime\",\n eventType: \"toolchain.execution\",\n lifecycle: \"close\",\n spanId,\n attributes: attrs({\n axis: \"toolchain\",\n \"toolchain.id\": toolchainId,\n \"toolchain.operation\": operation,\n \"toolchain.status\": status,\n \"toolchain.duration_ms\": durationMs,\n ...(errorMessage ? { \"toolchain.error\": errorMessage } : {}),\n }),\n });\n}\n","/**\n * ContextPack adoption observability (#151).\n *\n * Session-scoped cache of ContextPack / analyzeImpact metadata for emit-time\n * adoption marking on subsequent Read/Glob/Grep tool_exec spans.\n */\n\nimport { generateId } from \"@aaac/observability\";\nimport type { CanonicalLink } from \"@aaac/observability\";\nimport { isContextPack } from \"./analyzer-bridge.js\";\nimport type { ContextPack } from \"./analyzer-bridge.js\";\n\nexport type AdoptionKind = \"pack_hit\" | \"pack_redundant\" | \"pack_miss\";\n\nexport interface AdoptionMarking {\n kind: AdoptionKind;\n contextPackId: string;\n links: CanonicalLink[];\n}\n\ninterface PackRecord {\n contextPackId: string;\n spanId: string;\n paths: Set<string>;\n readPaths: Set<string>;\n}\n\nconst PATH_PROBE_TOOLS = new Set([\"Read\", \"Grep\", \"Glob\"]);\nconst CONTEXT_PACK_TOOLS = new Set([\n \"analyzer.generateContextPack\",\n \"generateContextPack\",\n]);\nconst CONTEXT_MAP_TOOLS = new Set([\n \"analyzer.getContextMap\",\n \"getContextMap\",\n]);\nconst IMPACT_TOOLS = new Set([\n \"analyzer.analyzeImpact\",\n \"analyzeImpact\",\n]);\n\nconst MAX_ENTRIES_PATHS = 20;\nconst MAX_TOP_PATHS = 20;\n\n/** Normalise file paths for set membership checks. */\nexport function normalizeToolPath(path: string): string {\n let p = path.trim().replace(/\\\\/g, \"/\");\n if (p.startsWith(\"./\")) p = p.slice(2);\n while (p.startsWith(\"/\")) p = p.slice(1);\n return p.toLowerCase();\n}\n\n/** Extract probe paths from Read/Glob/Grep tool input. */\nexport function extractProbePaths(toolName: string, input: unknown): string[] {\n if (input == null || typeof input !== \"object\") return [];\n const obj = input as Record<string, unknown>;\n const paths: string[] = [];\n\n if (toolName === \"Read\") {\n const fp = obj.file_path ?? obj.path;\n if (typeof fp === \"string\" && fp.length > 0) paths.push(fp);\n return paths;\n }\n\n if (toolName === \"Grep\") {\n const fp = obj.path ?? obj.file_path;\n if (typeof fp === \"string\" && fp.length > 0) paths.push(fp);\n return paths;\n }\n\n if (toolName === \"Glob\") {\n const fp = obj.path ?? obj.cwd;\n if (typeof fp === \"string\" && fp.length > 0) paths.push(fp);\n return paths;\n }\n\n return paths;\n}\n\nexport function isPathProbeTool(toolName: string): boolean {\n return PATH_PROBE_TOOLS.has(toolName);\n}\n\nexport function isContextPackTool(toolName: string): boolean {\n return CONTEXT_PACK_TOOLS.has(toolName);\n}\n\nexport function isContextMapTool(toolName: string): boolean {\n return CONTEXT_MAP_TOOLS.has(toolName);\n}\n\nexport function isImpactTool(toolName: string): boolean {\n return IMPACT_TOOLS.has(toolName);\n}\n\nexport function isAnalyzerObservabilityTool(toolName: string): boolean {\n return isContextPackTool(toolName) || isContextMapTool(toolName) || isImpactTool(toolName);\n}\n\nexport function buildContextPackOutputSummary(pack: ContextPack): string {\n const entriesPaths = pack.entries\n .map((e) => e.path)\n .slice(0, MAX_ENTRIES_PATHS);\n return JSON.stringify({\n files_included: pack.metadata.filesIncluded,\n files_referenced: pack.metadata.filesReferenced,\n artifacts_covered: pack.metadata.artifactsCovered,\n total_tokens: pack.metadata.totalTokens,\n budget_tokens: pack.metadata.budgetTokens,\n entries_paths: entriesPaths,\n });\n}\n\n// ---------------------------------------------------------------------------\n// What the other two analyzer tools print, and the gate in front of it\n// ---------------------------------------------------------------------------\n\n/**\n * The projection of `getContextMap` / `analyzeImpact` output this summariser\n * reads, declared here because this module is its only structural reader\n * (`analyzer-bridge.ts` types both results `Record<string, unknown>` — a\n * deliberate \"we do not model this\" — so there is no upstream shape to tighten\n * and no predicate to extend). Same placement as `EnsureBinOutput` next to\n * `isEnsureBinOutput` in `navigation-cache.ts` (#327): the type and the one gate\n * that grants it sit together.\n *\n * Fields are optional here only where the producer makes them optional. The\n * analyzer declares `ContextMapTarget.path` and `.symbolId` optional (a\n * symbol-only target carries no path) and `ImpactReport`'s affected entries with\n * `path: string` / `depth: number` required. Modelling a required field as\n * optional would describe the producer as looser than it is and put a `??` in\n * every consumer — which is what `?? 0` on `depth` was.\n */\nexport interface ContextMapTarget {\n path?: string;\n symbolId?: string;\n}\n\nexport interface ContextMapOutput {\n roots: unknown[];\n nodes: unknown[];\n edges: unknown[];\n suggestedReadTargets: ContextMapTarget[];\n}\n\nexport interface AffectedEntry {\n path: string;\n depth: number;\n}\n\nexport interface ImpactReportOutput {\n directlyAffected: AffectedEntry[];\n transitivelyAffected: AffectedEntry[];\n}\n\n/** An object, and nothing weaker — `typeof null` is `\"object\"`. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isContextMapTarget(value: unknown): value is ContextMapTarget {\n if (!isRecord(value)) return false;\n return (\n (value.path === undefined || typeof value.path === \"string\") &&\n (value.symbolId === undefined || typeof value.symbolId === \"string\")\n );\n}\n\nfunction isAffectedEntry(value: unknown): value is AffectedEntry {\n if (!isRecord(value)) return false;\n return typeof value.path === \"string\" && typeof value.depth === \"number\";\n}\n\n/**\n * The single gate between `getContextMap`'s untyped output and the type above.\n *\n * Every declared field is checked, including `roots` / `nodes` / `edges`, whose\n * elements nothing here reads: the predicate's return type — not the set of\n * fields some caller happens to dereference — is what it promises. Gating only\n * the branch a crash was reported from is exactly how the pack branch came to be\n * guarded while these two walked a `null` element straight into\n * `TypeError: … reading 'path'` (#326 fixed one of three).\n */\nexport function isContextMapOutput(value: unknown): value is ContextMapOutput {\n if (!isRecord(value)) return false;\n return (\n Array.isArray(value.roots) &&\n Array.isArray(value.nodes) &&\n Array.isArray(value.edges) &&\n Array.isArray(value.suggestedReadTargets) &&\n value.suggestedReadTargets.every(isContextMapTarget)\n );\n}\n\n/** The same gate for `analyzeImpact`. */\nexport function isImpactReportOutput(value: unknown): value is ImpactReportOutput {\n if (!isRecord(value)) return false;\n return (\n Array.isArray(value.directlyAffected) &&\n value.directlyAffected.every(isAffectedEntry) &&\n Array.isArray(value.transitivelyAffected) &&\n value.transitivelyAffected.every(isAffectedEntry)\n );\n}\n\nexport function buildContextMapOutputSummary(map: ContextMapOutput): string {\n const paths = map.suggestedReadTargets\n .map((t) => t.path)\n .filter((p): p is string => typeof p === \"string\")\n .slice(0, MAX_TOP_PATHS);\n return JSON.stringify({\n roots: map.roots.length,\n nodes: map.nodes.length,\n edges: map.edges.length,\n read_targets: map.suggestedReadTargets.length,\n top_paths: paths,\n });\n}\n\nexport function buildAnalyzeImpactOutputSummary(report: ImpactReportOutput): string {\n const affected = [...report.directlyAffected, ...report.transitivelyAffected];\n return JSON.stringify({\n affected_count: affected.length,\n max_depth_reached: Math.max(...affected.map((e) => e.depth), 0),\n top_paths: affected.map((e) => e.path).slice(0, MAX_TOP_PATHS),\n });\n}\n\n/** Build close attributes + register paths from an analyzer MCP handler result. */\nexport function buildAnalyzerCloseAttributes(\n toolName: string,\n resultText: string,\n): { extraAttributes: Record<string, string>; paths: string[]; contextPackId?: string } {\n // Another process wrote these bytes, so what they parse to is `unknown` until\n // a predicate says otherwise — `as Record<string, unknown>` promised an object\n // and answered `null` with `TypeError: … reading 'suggestedReadTargets'`.\n let parsed: unknown;\n try {\n parsed = JSON.parse(resultText);\n } catch {\n return { extraAttributes: {}, paths: [] };\n }\n\n if (isContextPackTool(toolName)) {\n // The pack comes from another process, so it is a ContextPack only once\n // `isContextPack` says so; output that is not gets the same answer as\n // output that would not parse — no attributes, no paths. This runs after\n // the tool has already answered its caller, so a shape this summariser\n // cannot read must not turn a served call into a failed one. The same\n // holds for the two branches below: same layer, same answer.\n if (!isContextPack(parsed)) return { extraAttributes: {}, paths: [] };\n const contextPackId = generateId();\n const outputSummary = buildContextPackOutputSummary(parsed);\n const paths = parsed.entries.map((e) => e.path);\n return {\n extraAttributes: {\n \"tool.output_summary\": outputSummary,\n \"tool.context_pack_id\": contextPackId,\n },\n paths,\n contextPackId,\n };\n }\n\n if (isContextMapTool(toolName)) {\n if (!isContextMapOutput(parsed)) return { extraAttributes: {}, paths: [] };\n const contextPackId = generateId();\n const outputSummary = buildContextMapOutputSummary(parsed);\n const paths = parsed.suggestedReadTargets\n .map((t) => t.path ?? t.symbolId)\n .filter((p): p is string => typeof p === \"string\");\n return {\n extraAttributes: {\n \"tool.output_summary\": outputSummary,\n \"tool.context_pack_id\": contextPackId,\n \"tool.context_map\": \"true\",\n },\n paths,\n contextPackId,\n };\n }\n\n if (isImpactTool(toolName)) {\n if (!isImpactReportOutput(parsed)) return { extraAttributes: {}, paths: [] };\n const outputSummary = buildAnalyzeImpactOutputSummary(parsed);\n const contextPackId = generateId();\n const paths = [...parsed.directlyAffected, ...parsed.transitivelyAffected].map(\n (e) => e.path,\n );\n return {\n extraAttributes: {\n \"tool.output_summary\": outputSummary,\n \"tool.context_pack_id\": contextPackId,\n },\n paths,\n contextPackId,\n };\n }\n\n return { extraAttributes: {}, paths: [] };\n}\n\nexport class ContextPackAdoptionTracker {\n private readonly packsBySession = new Map<string, PackRecord[]>();\n\n registerPack(\n sessionId: string | undefined,\n spanId: string,\n contextPackId: string,\n paths: string[],\n ): void {\n if (!sessionId) return;\n const normalized = new Set(\n paths.map(normalizeToolPath).filter((p) => p.length > 0),\n );\n const records = this.packsBySession.get(sessionId) ?? [];\n records.push({\n contextPackId,\n spanId,\n paths: normalized,\n readPaths: new Set(),\n });\n this.packsBySession.set(sessionId, records);\n }\n\n /**\n * Evaluate adoption for a path-probe tool at emit time.\n * Returns undefined when no pack was registered before this call.\n */\n evaluate(\n sessionId: string | undefined,\n toolName: string,\n input: unknown,\n ): AdoptionMarking | undefined {\n if (!sessionId || !isPathProbeTool(toolName)) return undefined;\n\n const packs = this.packsBySession.get(sessionId);\n if (!packs || packs.length === 0) return undefined;\n\n const probePaths = extractProbePaths(toolName, input).map(normalizeToolPath);\n if (probePaths.length === 0) return undefined;\n\n const latestPack = packs[packs.length - 1];\n const probePath = probePaths[0];\n\n const inPack = latestPack.paths.has(probePath);\n let kind: AdoptionKind;\n if (inPack) {\n kind = latestPack.readPaths.has(probePath) ? \"pack_redundant\" : \"pack_hit\";\n latestPack.readPaths.add(probePath);\n } else {\n kind = \"pack_miss\";\n }\n\n return {\n kind,\n contextPackId: latestPack.contextPackId,\n links: [\n {\n linkType: \"uses_context_from\",\n targetSpanId: latestPack.spanId,\n },\n ],\n };\n }\n}\n","/**\n * Tracks pending agent.tool_exec open spans so MCP handlers can close them\n * immediately on completion (#151) without waiting for the next assistant turn.\n */\n\nexport interface PendingToolSpan {\n spanId: string;\n toolName: string;\n startMs: number;\n closed: boolean;\n}\n\nexport class ToolExecSpanRegistry {\n private readonly pending: PendingToolSpan[] = [];\n\n register(span: Omit<PendingToolSpan, \"closed\">): void {\n this.pending.push({ ...span, closed: false });\n }\n\n /** Close the oldest still-open span for {@link toolName} (FIFO). */\n closeFirst(toolName: string): PendingToolSpan | undefined {\n const idx = this.pending.findIndex((s) => !s.closed && s.toolName === toolName);\n if (idx === -1) return undefined;\n this.pending[idx].closed = true;\n return this.pending[idx];\n }\n\n isClosed(spanId: string): boolean {\n const span = this.pending.find((s) => s.spanId === spanId);\n return span?.closed ?? false;\n }\n\n /** Return spans that are still open (for turn-boundary close). */\n getStillOpen(): PendingToolSpan[] {\n return this.pending.filter((s) => !s.closed);\n }\n}\n","/**\n * Library Tool → SDK Function Tool conversion.\n *\n * Converts LibraryToolDefinition entries into SDK-native function tools\n * that each adapter can register with its respective LLM SDK.\n *\n * Each adapter receives tools in its native format:\n * - Claude Agent SDK: MCP tool via createSdkMcpServer + tool()\n * - OpenAI Agents SDK: function tool object\n * - Google ADK: FunctionDeclaration tool\n */\n\nimport type { LibraryToolRegistry } from \"./library-tool-binding.js\";\nimport type { ObserverEmitFn } from \"./observability-bridge.js\";\nimport { emitToolExecClose } from \"./observability-bridge.js\";\nimport {\n buildAnalyzerCloseAttributes,\n ContextPackAdoptionTracker,\n isAnalyzerObservabilityTool,\n} from \"./context-pack-adoption.js\";\nimport { ToolExecSpanRegistry } from \"./tool-exec-span-registry.js\";\n\n/** Observability context for MCP handler completion-time tool_exec close (#151). */\nexport interface McpObservabilityContext {\n observer?: ObserverEmitFn;\n sessionId?: string;\n spanRegistry?: ToolExecSpanRegistry;\n adoptionTracker?: ContextPackAdoptionTracker;\n}\n\n/**\n * Adapter-agnostic function tool descriptor. Adapters convert this\n * into their SDK-specific tool format.\n */\nexport interface SdkFunctionTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n handler: (args: Record<string, unknown>) => Promise<string>;\n}\n\n/**\n * Build adapter-agnostic function tool descriptors from a LibraryToolRegistry.\n * Each tool's handler calls registry.execute() and serialises the result.\n */\nexport function buildSdkFunctionTools(\n registry: LibraryToolRegistry,\n): SdkFunctionTool[] {\n return registry.getAll().map((def) => ({\n name: def.toolId,\n description: def.description,\n inputSchema: def.inputSchema ?? { type: \"object\", properties: {} },\n handler: async (args: Record<string, unknown>): Promise<string> => {\n const result = await registry.execute(def.toolId, args);\n return typeof result === \"string\" ? result : JSON.stringify(result);\n },\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Claude Agent SDK — MCP server wrapping\n// ---------------------------------------------------------------------------\n\n/**\n * Build Claude MCP server tools from a LibraryToolRegistry.\n *\n * Dynamically imports `tool` and `createSdkMcpServer` from the\n * Claude Agent SDK. Returns an MCP server instance to be passed\n * to query() via options.mcpServers.\n *\n * Returns undefined if no tools or if SDK functions are unavailable.\n */\nexport async function buildClaudeMcpServer(\n registry: LibraryToolRegistry,\n observability?: McpObservabilityContext,\n): Promise<unknown | undefined> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return undefined;\n\n const sdk = (await import(\"@anthropic-ai/claude-agent-sdk\")) as Record<\n string,\n unknown\n >;\n type McpToolFn = (\n name: string,\n description: string,\n inputSchema: Record<string, unknown>,\n handler: (\n args: Record<string, unknown>,\n extra: unknown,\n ) => Promise<{ content: Array<{ type: string; text: string }> }>,\n ) => unknown;\n\n const toolFn = sdk.tool as McpToolFn | undefined;\n const createServer = sdk.createSdkMcpServer as\n | ((options: {\n name: string;\n version?: string;\n tools?: unknown[];\n }) => unknown)\n | undefined;\n\n if (!toolFn || !createServer) return undefined;\n\n const { z } = await import(\"zod\");\n const { jsonSchemaToZod } = await import(\"./schema-converter.js\");\n\n const sdkTools = tools.map((t) => {\n const zodType = jsonSchemaToZod(t.inputSchema);\n const shape =\n zodType instanceof z.ZodObject\n ? (zodType.shape as Record<string, unknown>)\n : {};\n\n return toolFn(\n t.name,\n t.description,\n shape,\n async (args) => {\n const startMs = Date.now();\n const text = await t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n if (observability?.observer && observability.spanRegistry) {\n const pending = observability.spanRegistry.closeFirst(t.name);\n if (pending) {\n const closeAttrs = isAnalyzerObservabilityTool(t.name)\n ? buildAnalyzerCloseAttributes(t.name, text)\n : { extraAttributes: {}, paths: [] as string[], contextPackId: undefined };\n emitToolExecClose(\n observability.observer,\n pending.spanId,\n t.name,\n Date.now() - startMs,\n {\n sessionId: observability.sessionId,\n extraAttributes: closeAttrs.extraAttributes,\n outputSummary: closeAttrs.extraAttributes[\"tool.output_summary\"] as string | undefined,\n },\n );\n if (\n observability.adoptionTracker &&\n closeAttrs.contextPackId &&\n closeAttrs.paths.length > 0\n ) {\n observability.adoptionTracker.registerPack(\n observability.sessionId,\n pending.spanId,\n closeAttrs.contextPackId,\n closeAttrs.paths,\n );\n }\n }\n }\n return { content: [{ type: \"text\", text }] };\n },\n );\n });\n\n return createServer({\n name: \"aaac-library-tools\",\n version: \"1.0.0\",\n tools: sdkTools,\n });\n}\n\n// ---------------------------------------------------------------------------\n// OpenAI Agents SDK — function tool objects\n// ---------------------------------------------------------------------------\n\n/**\n * Build OpenAI Agents SDK function tool objects from a LibraryToolRegistry.\n *\n * Dynamically imports `tool` from @openai/agents if available.\n * Falls back to a raw function-tool shape that the SDK also accepts.\n */\nexport async function buildOpenAIFunctionTools(\n registry: LibraryToolRegistry,\n): Promise<unknown[]> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return [];\n\n try {\n const sdk = (await import(\"@openai/agents\")) as Record<string, unknown>;\n const toolFn = sdk.tool as\n | ((def: Record<string, unknown>) => unknown)\n | undefined;\n\n if (toolFn) {\n const { jsonSchemaToZod } = await import(\"./schema-converter.js\");\n return tools.map((t) =>\n toolFn({\n name: t.name,\n description: t.description,\n parameters: jsonSchemaToZod(t.inputSchema),\n execute: async (_ctx: unknown, args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }),\n );\n }\n } catch {\n // SDK not available; fall through to raw format\n }\n\n return tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n },\n execute: async (args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }));\n}\n\n// ---------------------------------------------------------------------------\n// Google ADK — function tool objects\n// ---------------------------------------------------------------------------\n\n/**\n * Build Google ADK function tool objects from a LibraryToolRegistry.\n *\n * ADK's LlmAgent accepts tools as objects with a FunctionDeclaration shape\n * or as callable tool instances. We produce lightweight callable wrappers.\n */\nexport async function buildAdkFunctionTools(\n registry: LibraryToolRegistry,\n): Promise<unknown[]> {\n const tools = buildSdkFunctionTools(registry);\n if (tools.length === 0) return [];\n\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n execute: async (args: unknown) => {\n return t.handler(\n (args ?? {}) as Record<string, unknown>,\n );\n },\n }));\n}\n"],"mappings":";AAuIA,IAAM,eAAe;AAErB,eAAe,qBAA8C;AAC3D,QAAM,MAAO,MAAM;AAAA;AAAA,IACS;AAAA;AAE5B,SAAO;AACT;AAMO,SAAS,qBACd,SACgB;AAChB,QAAM,EAAE,aAAa,iBAAiB,kBAAkB,UAAU,IAAI;AAEtE,MAAI,cAAsC;AAC1C,MAAI,qBAAiD;AACrD,MAAI,oBAA0C;AAE9C,iBAAe,cAAwC;AACrD,QAAI,YAAa,QAAO;AACxB,QAAI,mBAAmB;AACrB,YAAM;AACN,aAAO;AAAA,IACT;AACA,wBAAoB,aAAa;AACjC,UAAM;AACN,WAAO;AAAA,EACT;AAEA,iBAAe,eAA8B;AAC3C,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,mBAAmB;AAAA,IACjC,SAAS,OAAO;AACd,YAAM,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACjE,YAAM,IAAI;AAAA,QACR,sFAC0C,GAAG;AAAA,MAC/C;AAAA,IACF;AAEA,UAAM,WAAW,oBAAoB,oBAAI,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S,IAAI;AAInB,QAAI,QAAQ;AACV,YAAM,EAAE,gBAAgB,IAAI,MAAM,OAAO,gCAAuB;AAChE,aAAO,MAAM;AAAA,QAAI,CAAC,MAChB,OAAO;AAAA,UACL,MAAM,EAAE;AAAA,UACR,aAAa,EAAE;AAAA,UACf,YAAY,gBAAgB,EAAE,WAAW;AAAA,UACzC,SAAS,OAAO,MAAe,SAAkB;AAC/C,mBAAO,EAAE;AAAA,cACN,QAAQ,CAAC;AAAA,YACZ;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO,MAAM,IAAI,CAAC,OAAO;AAAA,IACvB,MAAM;AAAA,IACN,UAAU;AAAA,MACR,MAAM,EAAE;AAAA,MACR,aAAa,EAAE;AAAA,MACf,YAAY,EAAE;AAAA,IAChB;AAAA,IACA,SAAS,OAAO,SAAkB;AAChC,aAAO,EAAE;AAAA,QACN,QAAQ,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF,EAAE;AACJ;AAYA,eAAsB,sBACpB,UACoB;AACpB,QAAM,QAAQ,sBAAsB,QAAQ;AAC5C,MAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAEhC,SAAO,MAAM,IAAI,CAAC,OAAO;AAAA,IACvB,MAAM,EAAE;AAAA,IACR,aAAa,EAAE;AAAA,IACf,aAAa,EAAE;AAAA,IACf,SAAS,OAAO,SAAkB;AAChC,aAAO,EAAE;AAAA,QACN,QAAQ,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,EACF,EAAE;AACJ;","names":["tokenAttrs","generateId","generateId"]}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// src/lib/guardrail-hooks.ts
|
|
2
|
+
var GUARDRAIL_ACTIONS = [
|
|
3
|
+
"block",
|
|
4
|
+
"warn",
|
|
5
|
+
"shadow",
|
|
6
|
+
"info",
|
|
7
|
+
"unresolved"
|
|
8
|
+
];
|
|
9
|
+
var UNRESOLVED_GUARDRAIL_ACTION = "unresolved";
|
|
10
|
+
function isGuardrailRule(value) {
|
|
11
|
+
if (typeof value !== "object" || value === null) return false;
|
|
12
|
+
const rule = value;
|
|
13
|
+
return typeof rule.guardrail_id === "string" && typeof rule.pattern === "string" && GUARDRAIL_ACTIONS.includes(rule.action) && typeof rule.message === "string" && (rule.file_glob === void 0 || typeof rule.file_glob === "string") && (rule.exclude_glob === void 0 || typeof rule.exclude_glob === "string");
|
|
14
|
+
}
|
|
15
|
+
function isGuardrailRuleData(value) {
|
|
16
|
+
if (typeof value !== "object" || value === null) return false;
|
|
17
|
+
const data = value;
|
|
18
|
+
return Array.isArray(data.commandRules) && data.commandRules.every(isGuardrailRule) && Array.isArray(data.fileRules) && data.fileRules.every(isGuardrailRule) && Array.isArray(data.contentRules) && data.contentRules.every(isGuardrailRule);
|
|
19
|
+
}
|
|
20
|
+
function globFragmentToRegex(fragment) {
|
|
21
|
+
let out = "";
|
|
22
|
+
for (const ch of fragment) {
|
|
23
|
+
if (ch === "*") out += "[^/]*";
|
|
24
|
+
else if (ch === "?") out += "[^/]";
|
|
25
|
+
else if (".+^$|()[]\\".includes(ch)) out += "\\" + ch;
|
|
26
|
+
else out += ch;
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
function expandDirectoryPattern(pattern) {
|
|
31
|
+
return pattern.endsWith("/") ? `${pattern}**` : pattern;
|
|
32
|
+
}
|
|
33
|
+
function matchGlob(rawPattern, path) {
|
|
34
|
+
const pattern = expandDirectoryPattern(rawPattern);
|
|
35
|
+
let regex = "";
|
|
36
|
+
let i = 0;
|
|
37
|
+
while (i < pattern.length) {
|
|
38
|
+
if (pattern[i] === "*" && pattern[i + 1] === "*" && pattern[i + 2] === "/") {
|
|
39
|
+
regex += "(?:.+/)?";
|
|
40
|
+
i += 3;
|
|
41
|
+
} else if (pattern[i] === "*" && pattern[i + 1] === "*") {
|
|
42
|
+
regex += ".*";
|
|
43
|
+
i += 2;
|
|
44
|
+
} else if (pattern[i] === "*") {
|
|
45
|
+
regex += "[^/]*";
|
|
46
|
+
i += 1;
|
|
47
|
+
} else if (pattern[i] === "?") {
|
|
48
|
+
regex += "[^/]";
|
|
49
|
+
i += 1;
|
|
50
|
+
} else if (pattern[i] === "{") {
|
|
51
|
+
const end = pattern.indexOf("}", i);
|
|
52
|
+
if (end !== -1) {
|
|
53
|
+
const alts = pattern.slice(i + 1, end).split(",").map(globFragmentToRegex);
|
|
54
|
+
regex += "(?:" + alts.join("|") + ")";
|
|
55
|
+
i = end + 1;
|
|
56
|
+
} else {
|
|
57
|
+
regex += "\\{";
|
|
58
|
+
i += 1;
|
|
59
|
+
}
|
|
60
|
+
} else if (".+^$|()[]\\".includes(pattern[i])) {
|
|
61
|
+
regex += "\\" + pattern[i];
|
|
62
|
+
i += 1;
|
|
63
|
+
} else {
|
|
64
|
+
regex += pattern[i];
|
|
65
|
+
i += 1;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return new RegExp("^" + regex + "$").test(path);
|
|
69
|
+
}
|
|
70
|
+
function namesTargetFile(key) {
|
|
71
|
+
return key === "path" || key === "file" || key === "filename" || key.endsWith("_path");
|
|
72
|
+
}
|
|
73
|
+
function namesPendingContent(key) {
|
|
74
|
+
return key === "content" || key.startsWith("new_");
|
|
75
|
+
}
|
|
76
|
+
function firstStringValue(toolInput, names) {
|
|
77
|
+
if (!toolInput) return "";
|
|
78
|
+
for (const key of Object.keys(toolInput).sort()) {
|
|
79
|
+
if (!names(key)) continue;
|
|
80
|
+
const value = toolInput[key];
|
|
81
|
+
if (typeof value === "string" && value) return value;
|
|
82
|
+
}
|
|
83
|
+
return "";
|
|
84
|
+
}
|
|
85
|
+
function toolTargetPath(toolInput) {
|
|
86
|
+
return firstStringValue(toolInput, namesTargetFile);
|
|
87
|
+
}
|
|
88
|
+
var NON_MUTATING_TOOLS = /* @__PURE__ */ new Set([
|
|
89
|
+
// Name a path in their input and only ever read it.
|
|
90
|
+
"Read",
|
|
91
|
+
"Glob",
|
|
92
|
+
"Grep",
|
|
93
|
+
"LSP",
|
|
94
|
+
// Load or delegate: whatever they set in motion arrives at the same guard as
|
|
95
|
+
// its own tool call, and is guarded there.
|
|
96
|
+
"Task",
|
|
97
|
+
"Agent",
|
|
98
|
+
"Skill",
|
|
99
|
+
// Reach outside the working tree entirely.
|
|
100
|
+
"WebFetch",
|
|
101
|
+
"WebSearch",
|
|
102
|
+
// Session-local state rather than files.
|
|
103
|
+
"TodoWrite",
|
|
104
|
+
"AskUserQuestion",
|
|
105
|
+
"ToolSearch",
|
|
106
|
+
"EnterPlanMode",
|
|
107
|
+
"ExitPlanMode"
|
|
108
|
+
]);
|
|
109
|
+
function toolWriteTarget(toolName, toolInput) {
|
|
110
|
+
if (NON_MUTATING_TOOLS.has(toolName ?? "")) return "";
|
|
111
|
+
return toolTargetPath(toolInput);
|
|
112
|
+
}
|
|
113
|
+
function toolPendingContent(toolInput) {
|
|
114
|
+
return firstStringValue(toolInput, namesPendingContent);
|
|
115
|
+
}
|
|
116
|
+
function isDenyAction(action) {
|
|
117
|
+
return action === "block" || action === UNRESOLVED_GUARDRAIL_ACTION;
|
|
118
|
+
}
|
|
119
|
+
function getBlockingViolations(results) {
|
|
120
|
+
return results.filter((r) => !r.passed && isDenyAction(r.action));
|
|
121
|
+
}
|
|
122
|
+
function getWarnings(results) {
|
|
123
|
+
return results.filter((r) => !r.passed && r.action === "warn");
|
|
124
|
+
}
|
|
125
|
+
function hasBlockingViolation(results) {
|
|
126
|
+
return getBlockingViolations(results).length > 0;
|
|
127
|
+
}
|
|
128
|
+
function renderViolations(results) {
|
|
129
|
+
return results.map((r) => `[${r.guardrail_id}] ${r.message}`).join("\n");
|
|
130
|
+
}
|
|
131
|
+
function denyResponse(blocks) {
|
|
132
|
+
const message = renderViolations(blocks);
|
|
133
|
+
return { permission: "deny", user_message: message, agent_message: message };
|
|
134
|
+
}
|
|
135
|
+
function createGuardrailHooks(...sources) {
|
|
136
|
+
function runChecks(ctx) {
|
|
137
|
+
const results = [];
|
|
138
|
+
if (ctx.command) {
|
|
139
|
+
for (const source of sources) results.push(...source.checkCommand(ctx.command));
|
|
140
|
+
}
|
|
141
|
+
if (ctx.filePath) {
|
|
142
|
+
for (const source of sources) results.push(...source.checkFilePath(ctx.filePath));
|
|
143
|
+
}
|
|
144
|
+
if (ctx.filePath && ctx.content) {
|
|
145
|
+
for (const source of sources) {
|
|
146
|
+
results.push(...source.checkContent(ctx.filePath, ctx.content));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return results;
|
|
150
|
+
}
|
|
151
|
+
function beforeShellExecution(input) {
|
|
152
|
+
const command = input.command ?? "";
|
|
153
|
+
if (!command) return {};
|
|
154
|
+
const results = runChecks({ command });
|
|
155
|
+
const blocks = getBlockingViolations(results);
|
|
156
|
+
const warns = getWarnings(results);
|
|
157
|
+
if (blocks.length > 0) {
|
|
158
|
+
return denyResponse(blocks);
|
|
159
|
+
}
|
|
160
|
+
if (warns.length > 0) {
|
|
161
|
+
return { additionalContext: renderViolations(warns) };
|
|
162
|
+
}
|
|
163
|
+
return {};
|
|
164
|
+
}
|
|
165
|
+
function fileWriteVerdict(filePath, content) {
|
|
166
|
+
if (!filePath) return {};
|
|
167
|
+
const blocks = getBlockingViolations(runChecks({ filePath, content }));
|
|
168
|
+
return blocks.length > 0 ? denyResponse(blocks) : {};
|
|
169
|
+
}
|
|
170
|
+
function preToolUse(input) {
|
|
171
|
+
return fileWriteVerdict(
|
|
172
|
+
toolWriteTarget(input.tool_name, input.tool_input),
|
|
173
|
+
toolPendingContent(input.tool_input)
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
function afterFileEdit(input) {
|
|
177
|
+
return fileWriteVerdict(input.file_path ?? "", input.content ?? "");
|
|
178
|
+
}
|
|
179
|
+
return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };
|
|
180
|
+
}
|
|
181
|
+
function compileGuardrailPattern(pattern) {
|
|
182
|
+
if (pattern.startsWith("(?i)")) {
|
|
183
|
+
return new RegExp(pattern.slice(4), "i");
|
|
184
|
+
}
|
|
185
|
+
return new RegExp(pattern);
|
|
186
|
+
}
|
|
187
|
+
function createGuardrailHooksFromRules(rules, ...extraSources) {
|
|
188
|
+
const commandChecks = rules.commandRules.map((rule) => ({
|
|
189
|
+
guardrail_id: rule.guardrail_id,
|
|
190
|
+
pattern: compileGuardrailPattern(rule.pattern),
|
|
191
|
+
action: rule.action,
|
|
192
|
+
message: rule.message
|
|
193
|
+
}));
|
|
194
|
+
const fileChecks = rules.fileRules;
|
|
195
|
+
const contentChecks = rules.contentRules.map((rule) => ({
|
|
196
|
+
guardrail_id: rule.guardrail_id,
|
|
197
|
+
pattern: compileGuardrailPattern(rule.pattern),
|
|
198
|
+
action: rule.action,
|
|
199
|
+
message: rule.message,
|
|
200
|
+
file_glob: rule.file_glob,
|
|
201
|
+
exclude_glob: rule.exclude_glob
|
|
202
|
+
}));
|
|
203
|
+
return createGuardrailHooks({
|
|
204
|
+
checkCommand(command) {
|
|
205
|
+
const results = [];
|
|
206
|
+
for (const check of commandChecks) {
|
|
207
|
+
const passed = !check.pattern.test(command);
|
|
208
|
+
results.push({
|
|
209
|
+
guardrail_id: check.guardrail_id,
|
|
210
|
+
passed,
|
|
211
|
+
action: check.action,
|
|
212
|
+
message: passed ? "" : check.message
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return results;
|
|
216
|
+
},
|
|
217
|
+
checkFilePath(filePath) {
|
|
218
|
+
const results = [];
|
|
219
|
+
for (const check of fileChecks) {
|
|
220
|
+
if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
const matched = matchGlob(check.pattern, filePath);
|
|
224
|
+
results.push({
|
|
225
|
+
guardrail_id: check.guardrail_id,
|
|
226
|
+
passed: !matched,
|
|
227
|
+
action: check.action,
|
|
228
|
+
message: matched ? check.message : ""
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
return results;
|
|
232
|
+
},
|
|
233
|
+
checkContent(filePath, content) {
|
|
234
|
+
const results = [];
|
|
235
|
+
for (const check of contentChecks) {
|
|
236
|
+
if (check.file_glob && !matchGlob(check.file_glob, filePath)) {
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const matched = check.pattern.test(content);
|
|
243
|
+
results.push({
|
|
244
|
+
guardrail_id: check.guardrail_id,
|
|
245
|
+
passed: !matched,
|
|
246
|
+
action: check.action,
|
|
247
|
+
message: matched ? check.message : ""
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return results;
|
|
251
|
+
}
|
|
252
|
+
}, ...extraSources);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export {
|
|
256
|
+
UNRESOLVED_GUARDRAIL_ACTION,
|
|
257
|
+
isGuardrailRuleData,
|
|
258
|
+
matchGlob,
|
|
259
|
+
toolTargetPath,
|
|
260
|
+
toolWriteTarget,
|
|
261
|
+
toolPendingContent,
|
|
262
|
+
getBlockingViolations,
|
|
263
|
+
getWarnings,
|
|
264
|
+
hasBlockingViolation,
|
|
265
|
+
renderViolations,
|
|
266
|
+
createGuardrailHooks,
|
|
267
|
+
createGuardrailHooksFromRules
|
|
268
|
+
};
|
|
269
|
+
//# sourceMappingURL=chunk-MSVIEEGR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/guardrail-hooks.ts"],"sourcesContent":["/**\n * SDK Guardrail Hook Bridge — generic adapter from guardrail check functions to\n * SDK-compatible hook responses.\n *\n * Embedded guardrail rules are converted via createGuardrailHooksFromRules(),\n * which delegates to createGuardrailHooks(). All hook logic lives here.\n *\n * Every check this module runs arrives as an ARGUMENT. It has no ambient\n * source: it does not know what a plugin is, and it reaches for no registry, so\n * what a route enforces is decided by that route and is readable at its call\n * site. This is also what keeps the module light enough to sit on the lean\n * hot-path graph — see `PluginRegistry.guardrailChecks` for the measurement and\n * for which layer supplies the plugin source.\n */\n\n/**\n * Enforcement action of a guardrail.\n *\n * `block` / `warn` / `shadow` / `info` are DECLARED by the active guardrail\n * policy. `unresolved` is not an enforcement level a policy can declare: it is\n * the state of a guardrail that has a binding implementation while the active\n * policy declares no action for it (no `active_guardrail_policy` in the project\n * manifest, an unknown policy name, or a policy with no rule for the guardrail).\n *\n * An unresolved guardrail DENIES — see `getBlockingViolations`. Substituting a\n * permissive default here is what turned every `action: block` guardrail in a\n * policy-less project into a no-op while the guardrail cache still listed it\n * (#293); the action is not knowable, so the operation the guardrail covers is\n * refused and the message says how to fix the manifest.\n *\n * ONE declaration for the set, so the type and the check `isGuardrailRuleData`\n * performs cannot name different ones — a bare union has nothing a predicate\n * can read, and the rules cross a process boundary as JSON.\n */\nexport const GUARDRAIL_ACTIONS = [\n \"block\",\n \"warn\",\n \"shadow\",\n \"info\",\n \"unresolved\",\n] as const;\n\nexport type GuardrailAction = (typeof GUARDRAIL_ACTIONS)[number];\n\n/** The action of a guardrail whose active policy declares none (see GuardrailAction). */\nexport const UNRESOLVED_GUARDRAIL_ACTION = \"unresolved\" as const;\n\nexport interface GuardrailCheckResult {\n guardrail_id: string;\n passed: boolean;\n action: GuardrailAction;\n message: string;\n}\n\n/**\n * What a guardrail hook answers.\n *\n * A refusal CARRIES ITS MESSAGE — one fact, not two independently optional\n * ones. Declared as separate optionals, every consumer had to supply a value\n * for a case no producer can reach (`beforeShellExecution`, `preToolUse` and\n * `afterFileEdit` all refuse through `denyResponse`, which always writes one),\n * and they supplied three different ones: two hand-written copies of \"Command\n * blocked by guardrail\" in the PreToolUse routes and a fall-back to\n * `agent_message` in the SDK adapter (#311). Nothing rejected a fourth, and\n * nothing noticed when one of them drifted, because a string literal that\n * disagrees with another string literal is not a type error.\n *\n * So the union states what the producer already guarantees, and the question\n * disappears instead of being answered in more places.\n */\nexport type HookResponse =\n | {\n permission: \"deny\";\n /** Every blocking violation, rendered. Never empty — a refusal has a cause. */\n user_message: string;\n agent_message: string;\n additionalContext?: undefined;\n }\n | {\n permission?: undefined;\n user_message?: undefined;\n agent_message?: undefined;\n /** Violations to surface to the agent without refusing. */\n additionalContext?: string;\n };\n\nexport interface GuardrailRule {\n guardrail_id: string;\n pattern: string;\n action: GuardrailAction;\n message: string;\n file_glob?: string;\n exclude_glob?: string;\n}\n\nexport interface GuardrailRuleData {\n commandRules: GuardrailRule[];\n fileRules: GuardrailRule[];\n contentRules: GuardrailRule[];\n}\n\nfunction isGuardrailRule(value: unknown): value is GuardrailRule {\n if (typeof value !== \"object\" || value === null) return false;\n const rule = value as Record<string, unknown>;\n return (\n typeof rule.guardrail_id === \"string\" &&\n typeof rule.pattern === \"string\" &&\n GUARDRAIL_ACTIONS.includes(rule.action as GuardrailAction) &&\n typeof rule.message === \"string\" &&\n (rule.file_glob === undefined || typeof rule.file_glob === \"string\") &&\n (rule.exclude_glob === undefined || typeof rule.exclude_glob === \"string\")\n );\n}\n\n/**\n * The single gate in front of {@link GuardrailRuleData}, next to the type it\n * grants — the rules are written to a cache file by one process and read back by\n * another, so the reader has only bytes and this predicate is what turns them\n * into rules the PreToolUse guard may run.\n *\n * Every declared field is checked, `action` against {@link GUARDRAIL_ACTIONS} —\n * the rules decide whether an operation is refused, so a rule carrying an action\n * the evaluator does not implement is not one this guard may run.\n */\nexport function isGuardrailRuleData(value: unknown): value is GuardrailRuleData {\n if (typeof value !== \"object\" || value === null) return false;\n const data = value as Record<string, unknown>;\n return (\n Array.isArray(data.commandRules) &&\n data.commandRules.every(isGuardrailRule) &&\n Array.isArray(data.fileRules) &&\n data.fileRules.every(isGuardrailRule) &&\n Array.isArray(data.contentRules) &&\n data.contentRules.every(isGuardrailRule)\n );\n}\n\nexport interface GuardrailCheckFunctions {\n checkCommand: (command: string) => GuardrailCheckResult[];\n checkFilePath: (filePath: string) => GuardrailCheckResult[];\n checkContent: (filePath: string, content: string) => GuardrailCheckResult[];\n}\n\nfunction globFragmentToRegex(fragment: string): string {\n let out = \"\";\n for (const ch of fragment) {\n if (ch === \"*\") out += \"[^/]*\";\n else if (ch === \"?\") out += \"[^/]\";\n else if (\".+^$|()[]\\\\\".includes(ch)) out += \"\\\\\" + ch;\n else out += ch;\n }\n return out;\n}\n\n/**\n * A pattern ending in `/` denotes a DIRECTORY and matches everything under it\n * (#262). This is the dominant style in artifact `path_patterns` — the embedded\n * dev-team DSL (`src/`, `lib/`, `tests/`, `.cursor/rules/`) and every\n * artifact-contracts registry rely on it. Without this, such a pattern compiles\n * to `^src/$`, which no file path can ever equal, so path → artifact reverse\n * lookup silently matched nothing and the artifact edit guard never fired.\n *\n * The rewrite is monotonic: file paths never end in `/`, so a pattern that\n * matched something before still matches exactly the same paths.\n */\nfunction expandDirectoryPattern(pattern: string): string {\n return pattern.endsWith(\"/\") ? `${pattern}**` : pattern;\n}\n\nexport function matchGlob(rawPattern: string, path: string): boolean {\n const pattern = expandDirectoryPattern(rawPattern);\n let regex = \"\";\n let i = 0;\n while (i < pattern.length) {\n if (pattern[i] === \"*\" && pattern[i + 1] === \"*\" && pattern[i + 2] === \"/\") {\n regex += \"(?:.+/)?\";\n i += 3;\n } else if (pattern[i] === \"*\" && pattern[i + 1] === \"*\") {\n regex += \".*\";\n i += 2;\n } else if (pattern[i] === \"*\") {\n regex += \"[^/]*\";\n i += 1;\n } else if (pattern[i] === \"?\") {\n regex += \"[^/]\";\n i += 1;\n } else if (pattern[i] === \"{\") {\n const end = pattern.indexOf(\"}\", i);\n if (end !== -1) {\n const alts = pattern.slice(i + 1, end).split(\",\").map(globFragmentToRegex);\n regex += \"(?:\" + alts.join(\"|\") + \")\";\n i = end + 1;\n } else {\n regex += \"\\\\{\";\n i += 1;\n }\n } else if (\".+^$|()[]\\\\\".includes(pattern[i])) {\n regex += \"\\\\\" + pattern[i];\n i += 1;\n } else {\n regex += pattern[i];\n i += 1;\n }\n }\n return new RegExp(\"^\" + regex + \"$\").test(path);\n}\n\n/**\n * Does this tool-input key name a file the call acts on?\n *\n * Derived from the naming convention rather than from a census of today's\n * tools. `NotebookEdit` calls its target `notebook_path`, so a reader that knew\n * only `file_path`/`path` classified that call correctly and then judged\n * nothing — the artifact guard was reached and found no path to protect (#309).\n * Every such key so far ends in `path`, so the rule follows the suffix and the\n * next tool to name an `output_path` is already covered.\n *\n * `file` / `filename` carry no suffix; they are the SDK progress-event\n * spellings the task runner reads, and are named for that reason.\n */\nfunction namesTargetFile(key: string): boolean {\n return (\n key === \"path\" || key === \"file\" || key === \"filename\" || key.endsWith(\"_path\")\n );\n}\n\n/**\n * Does this tool-input key carry text the call is about to WRITE?\n *\n * The same convention rule as `namesTargetFile`, over the other half of a file\n * edit. `Write` calls it `content`; `Edit` and `NotebookEdit` prefix the value\n * they are installing with `new_` (`new_string`, `new_source`), so the rule\n * follows the prefix and a tool that arrives naming a `new_text` is covered.\n *\n * The exclusions are the point. `old_string` is the text being REMOVED, and\n * scanning it would refuse the very edit that takes a forbidden string OUT of a\n * file — a content guardrail that fights its own repair. `file_path` and the\n * `cell_id` / `edit_mode` sort of parameter are neither. So \"everything the\n * payload happens to hold\" is not an available answer; the key has to say it is\n * the incoming value.\n */\nfunction namesPendingContent(key: string): boolean {\n return key === \"content\" || key.startsWith(\"new_\");\n}\n\n/**\n * The first non-empty string value under a key `names` accepts, or `\"\"`.\n *\n * Keys are scanned in sorted order, so the answer cannot depend on the order a\n * payload happened to serialize its properties in.\n *\n * Reads TOP-LEVEL string values only, and returns the first match: a payload\n * carrying its files in an array (`file_paths`) or nested (`edits[].new_string`)\n * is not covered, and no built-in has that shape today (#309).\n */\nfunction firstStringValue(\n toolInput: Record<string, unknown> | undefined | null,\n names: (key: string) => boolean,\n): string {\n if (!toolInput) return \"\";\n for (const key of Object.keys(toolInput).sort()) {\n if (!names(key)) continue;\n const value = toolInput[key];\n if (typeof value === \"string\" && value) return value;\n }\n return \"\";\n}\n\n/**\n * The file a tool call names as its target, or `\"\"` when it names none.\n *\n * ONE reader for every consumer that asks \"which file is this call about\": the\n * `preToolUse` file guardrails below, both Claude Code PreToolUse routes, the\n * `guard evaluate` CLI, the Claude SDK adapter and the task runner's\n * `process.edit` events. They had four spellings of it between them, agreeing\n * on `file_path` and diverging after — and a reader that knows fewer keys than\n * the tool writes turns a guard that runs into a guard that decides nothing.\n *\n * Scope is a TOOL INPUT. The after-file-edit payloads (`afterFileEdit` here,\n * the Cursor hook input in `guard-commands`) are not tool inputs: their\n * `file_path` is a top-level protocol field and is the whole interface.\n */\nexport function toolTargetPath(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesTargetFile);\n}\n\n/**\n * Claude Code tools that cannot modify a file in the working tree — the ONLY\n * calls a `file_glob` / `content_regex` guardrail lets past unexamined.\n *\n * This list is inverted on purpose. Naming the tools to guard (`Edit`, `Write`,\n * `MultiEdit`) meant the guard covered exactly the tools that existed when it\n * was written, and `NotebookEdit` — a first-party file editor — walked through\n * a `manual_edit: forbidden` artifact for as long as it has existed (#309).\n * Every future tool would have arrived the same way, silently, because a name\n * that is missing from an allowlist looks identical to a name that is absent\n * for a reason.\n *\n * Naming the tools NOT to guard puts the staleness on the harmless side. An\n * unrecognised tool is judged instead of waved through, and being judged costs\n * it nothing unless it names a covered file: `toolTargetPath` reads the file out\n * of the call, so a tool that targets no file resolves to nothing and is\n * allowed. \"Deny by default\" here therefore means \"examined by default\", not\n * \"refused by default\" — a new Claude Code release does not lock the session\n * down.\n *\n * Every name is a Claude Code built-in, pinned against an independent\n * transcription of the tool reference in `__tests__/fixtures/`.\n */\nexport const NON_MUTATING_TOOLS: ReadonlySet<string> = new Set([\n // Name a path in their input and only ever read it.\n \"Read\",\n \"Glob\",\n \"Grep\",\n \"LSP\",\n // Load or delegate: whatever they set in motion arrives at the same guard as\n // its own tool call, and is guarded there.\n \"Task\",\n \"Agent\",\n \"Skill\",\n // Reach outside the working tree entirely.\n \"WebFetch\",\n \"WebSearch\",\n // Session-local state rather than files.\n \"TodoWrite\",\n \"AskUserQuestion\",\n \"ToolSearch\",\n \"EnterPlanMode\",\n \"ExitPlanMode\",\n]);\n\n/**\n * The file this call may WRITE, or `\"\"` when there is none.\n *\n * ONE answer to \"which operations do the file guards cover\", for every route:\n * the `preToolUse` gate below, both Claude Code PreToolUse routes (through\n * `artifactGuardTarget`), the `guard evaluate` CLI and the Claude SDK adapter.\n *\n * `file_glob` and `content_regex` guard WRITES. That is not a reading of what\n * the matcher could mean — it is what every rule declared against it says:\n * across `agents/bindings/runtime.yaml`, `examples/governance/bindings/runtime.yaml`\n * and the bindings `aaac init` bootstraps a new project with, all 19 messages\n * are \"Writing to … is blocked\", \"Generated files must not be hand-edited\" or\n * \"Do not write … at repo root\". None is about reading one. So a guard that\n * refused `Read` would refuse an operation no rule in this repo asks it to, and\n * `protect-generated-files` — `action: block` under the default policy — would\n * stop an agent reading the generated code it has to read to work.\n *\n * Answering it HERE rather than in the hook is what keeps the routes on one\n * verdict. Answered per-consumer, it went two ways immediately: the workspace\n * PreToolUse route filtered by this set and the single-component one did not, so\n * the same `Read secrets/prod.env` was allowed by one and refused by the other\n * (#316).\n */\nexport function toolWriteTarget(\n toolName: string | undefined,\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n if (NON_MUTATING_TOOLS.has(toolName ?? \"\")) return \"\";\n return toolTargetPath(toolInput);\n}\n\n/**\n * The text a tool call is about to write into `toolTargetPath`, or `\"\"`.\n *\n * The companion reader, and the reason `content_regex` guardrails are decided\n * BEFORE the write rather than reported after it. Claude Code hands PreToolUse\n * the tool's parameters in full, so the pending content is already in the\n * payload; the only event that could carry it afterwards is PostToolUse, whose\n * `block` cannot un-write the file and would answer the same declared\n * `action: block` differently from every other route (#316).\n */\nexport function toolPendingContent(\n toolInput: Record<string, unknown> | undefined | null,\n): string {\n return firstStringValue(toolInput, namesPendingContent);\n}\n\n/**\n * What one check is asked about: a command, a path, or a path and the content\n * about to go into it. Nothing here names an AGENT.\n *\n * Which rules an agent is checked against is settled before an evaluator\n * exists, by the layer that knows where rules come from — see\n * `createAgentGuardrailHooks` in `execute.ts`, the one constructor of per-agent\n * hooks. An agent id travelling inside the context would mean that same\n * question could also be answered later, from in here, and it did: a second\n * per-agent constructor exported beside that one wrote `agentId` on every\n * context it forwarded, no gate read it, and the two disagreed on memoisation\n * and on what an agent with no rules gets (#333).\n *\n * So the field is gone, and an OBJECT LITERAL naming an agent is now TS2353 —\n * which is what makes that constructor un-pasteable verbatim.\n * `adapter-guardrail-hooks.test.ts` pins the absence with a `@ts-expect-error`\n * that turns into TS2578 if the field returns.\n *\n * That is the whole of what the type says, and it is less than it sounds.\n * Excess-property checking reaches object literals only: an `as HookContext`\n * cast, an interface that extends this one, a literal bound to a variable\n * first, and a plain `Record<string, unknown>` all compile — measured, not\n * assumed. And a second per-agent constructor that simply never writes an agent\n * id needs none of them and compiles as it is. What is removed here is the\n * AFFORDANCE the duplicate happened to use, not the possibility of another one.\n * The invariant — ONE constructor of per-agent hooks — is held by the\n * declaration on `createAgentGuardrailHooks` and by reading it, and nothing\n * mechanical will fail if it is broken.\n */\nexport interface HookContext {\n command?: string;\n filePath?: string;\n content?: string;\n}\n\n/**\n * The guardrail gates, one per payload SHAPE — not one per rule kind.\n *\n * Which gate a caller picks is decided by what it holds, never by which rules\n * it wants consulted: every gate runs every rule the context can answer. An\n * object with four methods hid the opposite for as long as this existed — the\n * Claude Code PreToolUse route called `beforeShellExecution` and nothing else,\n * so a project's `file_glob` and `content_regex` guardrails were enforced by\n * `guard evaluate` and by the SDK adapter while the session a person actually\n * works in never consulted them, and no type or single-route test could say so\n * (#316).\n */\nexport interface GuardrailHooks {\n /** A command about to run. Claude Code PreToolUse (both routes), `guard evaluate`. */\n beforeShellExecution: (input: { command?: string }) => HookResponse;\n /**\n * A TOOL INPUT, verbatim: `toolTargetPath` reads the file out of it and\n * `toolPendingContent` the text about to go in. The single-component Claude\n * Code PreToolUse route, `guard evaluate` and the Claude SDK adapter.\n */\n preToolUse: (input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n }) => HookResponse;\n /**\n * A file write whose path and content the caller has ALREADY extracted —\n * Cursor's after-file-edit event, where both are top-level protocol fields,\n * and the workspace Claude Code PreToolUse route, which must ask about the\n * member-repo-relative path (`stripMemberPrefix`) rather than the one the\n * tool named, because member guardrail patterns are written in that space.\n */\n afterFileEdit: (input: { file_path?: string; content?: string }) => HookResponse;\n /** The shared check runner. Not a gate: `getBlockingViolations` is what refuses. */\n runChecks: (ctx: HookContext) => GuardrailCheckResult[];\n}\n\n/**\n * Does this action refuse the operation? `block` because the policy says so,\n * `unresolved` because the policy says nothing and a guardrail whose action is\n * unknown must not be permissive (#293). Single definition — every deny gate\n * (shell / pre-tool-use / after-file-edit hooks, `guard evaluate`'s exit code,\n * the OpenAI Agents SDK tripwire) reads it through `getBlockingViolations`.\n */\nfunction isDenyAction(action: GuardrailAction): boolean {\n return action === \"block\" || action === UNRESOLVED_GUARDRAIL_ACTION;\n}\n\nexport function getBlockingViolations(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && isDenyAction(r.action));\n}\n\nexport function getWarnings(results: GuardrailCheckResult[]): GuardrailCheckResult[] {\n return results.filter((r) => !r.passed && r.action === \"warn\");\n}\n\nexport function hasBlockingViolation(results: GuardrailCheckResult[]): boolean {\n return getBlockingViolations(results).length > 0;\n}\n\n/**\n * How a guardrail violation reads: `[guardrail-id] message`, one per line.\n *\n * Single definition — the shell, pre-tool-use and after-file-edit hooks all\n * refuse in the same words, a warning reads the same as the refusal it would\n * have been under a stricter policy, and the ADK adapter throws the same text\n * where it has no hook response to return. Exported for that last one only:\n * not re-exported from the package barrel, because no consumer outside this\n * runtime renders a violation.\n */\nexport function renderViolations(results: GuardrailCheckResult[]): string {\n return results.map((r) => `[${r.guardrail_id}] ${r.message}`).join(\"\\n\");\n}\n\n/**\n * The refusal every guardrail hook returns.\n *\n * The message is written HERE, once, rather than at each of the three hooks —\n * that is what makes `HookResponse`'s \"a denial carries its message\" a fact\n * about the code and not a convention. `user_message` and `agent_message` are\n * the same text on purpose: the agent is told exactly what the user is told.\n */\nfunction denyResponse(blocks: GuardrailCheckResult[]): HookResponse {\n const message = renderViolations(blocks);\n return { permission: \"deny\", user_message: message, agent_message: message };\n}\n\n/**\n * Create SDK hook functions from guardrail check functions.\n *\n * Returns hook functions in the format expected by the Claude SDK, plus a\n * generic runChecks() for programmatic use.\n *\n * Takes any number of check SOURCES and asks every one of them every question\n * the context can answer — which is the same rule `GuardrailHooks` states about\n * its gates, one level down. A source is not a rule kind and not a route: it is\n * one supplier of checks, and the hooks it produces cannot tell which supplier a\n * verdict came from. That is what lets a second supplier be added (the execution\n * layer adds the process's plugin guardrails, see\n * `PluginRegistry.guardrailChecks`) without there being a second EVALUATOR —\n * the property #304 and #316 exist to hold.\n *\n * Ordering is by question, then by source, so the sources a caller lists are\n * consulted in the order it listed them and a refusal reads the same way every\n * time (`renderViolations` joins in result order).\n *\n * Zero sources is a legitimate answer, not a degenerate one: it is what an agent\n * with no resolved rules and no plugins has, and the hooks it gets deny nothing.\n */\nexport function createGuardrailHooks(...sources: GuardrailCheckFunctions[]): GuardrailHooks {\n function runChecks(ctx: HookContext): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n\n if (ctx.command) {\n for (const source of sources) results.push(...source.checkCommand(ctx.command));\n }\n\n if (ctx.filePath) {\n for (const source of sources) results.push(...source.checkFilePath(ctx.filePath));\n }\n\n if (ctx.filePath && ctx.content) {\n for (const source of sources) {\n results.push(...source.checkContent(ctx.filePath, ctx.content));\n }\n }\n\n return results;\n }\n\n function beforeShellExecution(input: { command?: string }): HookResponse {\n const command = input.command ?? \"\";\n if (!command) return {};\n\n const results = runChecks({ command });\n const blocks = getBlockingViolations(results);\n const warns = getWarnings(results);\n\n if (blocks.length > 0) {\n return denyResponse(blocks);\n }\n\n if (warns.length > 0) {\n return { additionalContext: renderViolations(warns) };\n }\n\n return {};\n }\n\n /**\n * The verdict on one file write — the ONE gate behind both file-shaped hooks\n * below, so `file_glob` and `content_regex` are decided together and cannot\n * be decided differently depending on which payload shape arrived.\n *\n * They diverged before: `preToolUse` asked `runChecks({ filePath })` and so\n * consulted `checkFilePath` alone, while `afterFileEdit` asked with the\n * content and got both. The rules a project declares are the same rules\n * either way (#316).\n */\n function fileWriteVerdict(filePath: string, content: string): HookResponse {\n if (!filePath) return {};\n\n const blocks = getBlockingViolations(runChecks({ filePath, content }));\n return blocks.length > 0 ? denyResponse(blocks) : {};\n }\n\n function preToolUse(input: {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n }): HookResponse {\n return fileWriteVerdict(\n toolWriteTarget(input.tool_name, input.tool_input),\n toolPendingContent(input.tool_input),\n );\n }\n\n function afterFileEdit(input: { file_path?: string; content?: string }): HookResponse {\n return fileWriteVerdict(input.file_path ?? \"\", input.content ?? \"\");\n }\n\n return { beforeShellExecution, preToolUse, afterFileEdit, runChecks };\n}\n\n/** Compile a guardrail regex pattern, supporting inline `(?i)` case-insensitivity prefix. */\nexport function compileGuardrailPattern(pattern: string): RegExp {\n if (pattern.startsWith(\"(?i)\")) {\n return new RegExp(pattern.slice(4), \"i\");\n }\n return new RegExp(pattern);\n}\n\n/**\n * Create SDK hook functions from embedded guardrail rule data.\n *\n * The rules are the first check source; `extraSources` are consulted after\n * them, on every question. This is the funnel every route reaches the evaluator\n * through — both Claude Code PreToolUse routes, `guard evaluate` and the\n * execution layer — so what distinguishes those routes is visible here as an\n * argument list and nowhere else.\n */\nexport function createGuardrailHooksFromRules(\n rules: GuardrailRuleData,\n ...extraSources: GuardrailCheckFunctions[]\n): GuardrailHooks {\n const commandChecks = rules.commandRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n }));\n\n const fileChecks = rules.fileRules;\n\n const contentChecks = rules.contentRules.map((rule) => ({\n guardrail_id: rule.guardrail_id,\n pattern: compileGuardrailPattern(rule.pattern),\n action: rule.action,\n message: rule.message,\n file_glob: rule.file_glob,\n exclude_glob: rule.exclude_glob,\n }));\n\n return createGuardrailHooks({\n checkCommand(command: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of commandChecks) {\n const passed = !check.pattern.test(command);\n results.push({\n guardrail_id: check.guardrail_id,\n passed,\n action: check.action,\n message: passed ? \"\" : check.message,\n });\n }\n return results;\n },\n\n checkFilePath(filePath: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of fileChecks) {\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = matchGlob(check.pattern, filePath);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n\n checkContent(filePath: string, content: string): GuardrailCheckResult[] {\n const results: GuardrailCheckResult[] = [];\n for (const check of contentChecks) {\n if (check.file_glob && !matchGlob(check.file_glob, filePath)) {\n continue;\n }\n if (check.exclude_glob && matchGlob(check.exclude_glob, filePath)) {\n continue;\n }\n const matched = check.pattern.test(content);\n results.push({\n guardrail_id: check.guardrail_id,\n passed: !matched,\n action: check.action,\n message: matched ? check.message : \"\",\n });\n }\n return results;\n },\n }, ...extraSources);\n}\n"],"mappings":";AAkCO,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKO,IAAM,8BAA8B;AAwD3C,SAAS,gBAAgB,OAAwC;AAC/D,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,OAAO;AACb,SACE,OAAO,KAAK,iBAAiB,YAC7B,OAAO,KAAK,YAAY,YACxB,kBAAkB,SAAS,KAAK,MAAyB,KACzD,OAAO,KAAK,YAAY,aACvB,KAAK,cAAc,UAAa,OAAO,KAAK,cAAc,cAC1D,KAAK,iBAAiB,UAAa,OAAO,KAAK,iBAAi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,UACpB,QAAQ,CAAC;AAAA,UACT,QAAQ,MAAM;AAAA,UACd,SAAS,UAAU,MAAM,UAAU;AAAA,QACrC,CAAC;AAAA,MACH;AACA,aAAO;AAAA,IACT;AAAA,EACF,GAAG,GAAG,YAAY;AACpB;","names":[]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// src/lib/claude-tool-grants.ts
|
|
2
|
+
var READ_ONLY_TOOL_GRANT = ["Read", "Glob", "Grep", "Bash"];
|
|
3
|
+
var READ_WRITE_TOOL_GRANT = [
|
|
4
|
+
"Read",
|
|
5
|
+
"Glob",
|
|
6
|
+
"Grep",
|
|
7
|
+
"Edit",
|
|
8
|
+
"Write",
|
|
9
|
+
"Bash"
|
|
10
|
+
];
|
|
11
|
+
var WRITE_TOOL_NAMES = READ_WRITE_TOOL_GRANT.filter(
|
|
12
|
+
(t) => !READ_ONLY_TOOL_GRANT.includes(t)
|
|
13
|
+
);
|
|
14
|
+
function toolGrantForMode(mode) {
|
|
15
|
+
return mode === "read-write" ? READ_WRITE_TOOL_GRANT : READ_ONLY_TOOL_GRANT;
|
|
16
|
+
}
|
|
17
|
+
var DELEGATION_TOOL_NAME = "Agent";
|
|
18
|
+
var DELEGATION_TOOL_LEGACY_NAME = "Task";
|
|
19
|
+
var DELEGATION_TOOL_NAMES = [
|
|
20
|
+
DELEGATION_TOOL_LEGACY_NAME,
|
|
21
|
+
DELEGATION_TOOL_NAME
|
|
22
|
+
];
|
|
23
|
+
function toolGrantForAgent(agent) {
|
|
24
|
+
const grant = [...toolGrantForMode(agent.mode)];
|
|
25
|
+
if (agent.can_invoke_agents && agent.can_invoke_agents.length > 0) {
|
|
26
|
+
grant.push(...DELEGATION_TOOL_NAMES);
|
|
27
|
+
}
|
|
28
|
+
return grant;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
toolGrantForMode,
|
|
33
|
+
DELEGATION_TOOL_NAMES,
|
|
34
|
+
toolGrantForAgent
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=chunk-VJXGCWSZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/claude-tool-grants.ts"],"sourcesContent":["/**\n * Claude Code built-in tool grant per agent `mode`.\n *\n * ONE definition of \"which Claude Code tools does a `read-only` / `read-write`\n * agent get\". Two consumers, one rule:\n *\n * - in-process: `task-runner.ts` derives `readonly` from `agentContract.mode`\n * and the Claude adapter turns it into the SDK `tools` option.\n * - on-disk: `claude-materialize/agent-render.ts` writes the same names\n * into the `tools:` frontmatter of a materialized `.claude/agents/*.md`\n * subagent (#272).\n *\n * Both must agree — a subagent that Claude Code launches from disk and the same\n * agent delegated to in-process are the same agent, so a divergent tool grant\n * would mean the DSL's `mode` means two different things.\n *\n * `mode` normalization itself lives in `dsl-context.ts` (`buildAgentRegistry`)\n * and is fail-safe: anything that is not exactly `read-write` becomes\n * `read-only`, so an unrecognized mode can never widen the grant.\n */\n\n/** Tools a `read-only` agent may use: inspection + command execution, no writes. */\nexport const READ_ONLY_TOOL_GRANT: readonly string[] = [\"Read\", \"Glob\", \"Grep\", \"Bash\"];\n\n/** Tools a `read-write` agent may use: the read-only set plus the write tools. */\nexport const READ_WRITE_TOOL_GRANT: readonly string[] = [\n \"Read\",\n \"Glob\",\n \"Grep\",\n \"Edit\",\n \"Write\",\n \"Bash\",\n];\n\n/** The Claude Code tool names that mutate the working tree. */\nexport const WRITE_TOOL_NAMES: readonly string[] = READ_WRITE_TOOL_GRANT.filter(\n (t) => !READ_ONLY_TOOL_GRANT.includes(t),\n);\n\n/** Claude Code tool grant for an agent mode. */\nexport function toolGrantForMode(mode: \"read-write\" | \"read-only\"): readonly string[] {\n return mode === \"read-write\" ? READ_WRITE_TOOL_GRANT : READ_ONLY_TOOL_GRANT;\n}\n\n/**\n * The sub-agent delegation tool, canonical spelling. An agent that declares\n * `can_invoke_agents` cannot delegate without it, because neither mode grant\n * includes it. Listing it in a subagent's `tools:` is also what lets that\n * subagent spawn subagents of its own.\n *\n * Claude Code renamed `Task` to `Agent` in 2.1.63; the SDK likewise documents\n * \"a custom subagent that can be invoked via the Agent tool\"\n * (`@anthropic-ai/claude-agent-sdk` sdk.d.ts:36).\n */\nexport const DELEGATION_TOOL_NAME = \"Agent\";\n\n/** Pre-2.1.63 spelling. Claude Code still resolves it as an alias. */\nexport const DELEGATION_TOOL_LEGACY_NAME = \"Task\";\n\n/**\n * Both delegation spellings, granted everywhere.\n *\n * `Agent` does not resolve before Claude Code 2.1.63 and `Task` is the alias\n * that does, so granting only one silently costs the agent its ability to\n * delegate on some installed versions. Granting both is free: a `tools:` list —\n * in a subagent file exactly as in the SDK `tools` option — is an **allowlist**\n * resolved against the available tool pool, and an entry that does not resolve\n * is simply not granted. Only a list where NOTHING resolves fails the launch.\n */\nexport const DELEGATION_TOOL_NAMES: readonly string[] = [\n DELEGATION_TOOL_LEGACY_NAME,\n DELEGATION_TOOL_NAME,\n];\n\n/**\n * The Claude Code tool grant for one agent: its mode grant, plus the delegation\n * tool when the DSL says it may invoke other agents.\n *\n * This is the grant an agent gets wherever it runs — the same rule the adapter\n * applies in-process — so a DSL agent does not gain or lose the ability to\n * delegate depending on whether Claude Code launched it from\n * `.claude/agents/<id>.md` or the runtime registered it as a candidate.\n */\nexport function toolGrantForAgent(agent: {\n mode: \"read-write\" | \"read-only\";\n can_invoke_agents?: readonly string[];\n}): readonly string[] {\n const grant = [...toolGrantForMode(agent.mode)];\n if (agent.can_invoke_agents && agent.can_invoke_agents.length > 0) {\n grant.push(...DELEGATION_TOOL_NAMES);\n }\n return grant;\n}\n"],"mappings":";AAsBO,IAAM,uBAA0C,CAAC,QAAQ,QAAQ,QAAQ,MAAM;AAG/E,IAAM,wBAA2C;AAAA,EACtD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,mBAAsC,sBAAsB;AAAA,EACvE,CAAC,MAAM,CAAC,qBAAqB,SAAS,CAAC;AACzC;AAGO,SAAS,iBAAiB,MAAqD;AACpF,SAAO,SAAS,eAAe,wBAAwB;AACzD;AAYO,IAAM,uBAAuB;AAG7B,IAAM,8BAA8B;AAYpC,IAAM,wBAA2C;AAAA,EACtD;AAAA,EACA;AACF;AAWO,SAAS,kBAAkB,OAGZ;AACpB,QAAM,QAAQ,CAAC,GAAG,iBAAiB,MAAM,IAAI,CAAC;AAC9C,MAAI,MAAM,qBAAqB,MAAM,kBAAkB,SAAS,GAAG;AACjE,UAAM,KAAK,GAAG,qBAAqB;AAAA,EACrC;AACA,SAAO;AACT;","names":[]}
|