{"version":3,"file":"agent-files-D0ptwuts.cjs","names":["agentId","basename","isAgentId","isRecord","CODECS","collectRules","mapMode","evaluate","isRecord","resolve","join","existsSync","dirname","readFile","mkdir","writeFile","AgentPermissionPolicy","CODECS"],"sources":["../src/api.ts","../src/agent-files.ts"],"sourcesContent":["/**\n * Programmatic API for agent-perms — side-effect-free functions for\n * converting, validating, and checking permission policies.\n *\n * Import:\n *   import { convert, validate, check, detectFormat } from \"agent-perms/api\";\n */\n\nimport { CODECS, agentId, type AgentId } from \"./compat/codecs.ts\";\nimport { evaluate, collectRules, mapMode } from \"./evaluate.ts\";\nimport { validatePolicy, type ValidationError } from \"./agent-files.ts\";\nimport { isAgentId, isRecord } from \"./guards.ts\";\nimport { AgentPermissionPolicy } from \"./schema.ts\";\nexport type { ValidationError } from \"./agent-files.ts\";\nimport { basename } from \"node:path\";\n\nconst AGENTS = agentId.options;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Supported format identifiers, including canonical. */\nexport type Format = AgentId | \"canonical\";\n\n/** Result of a successful conversion. */\nexport interface ConvertResult {\n  /** The converted output (agent-native JSON object). */\n  output: unknown;\n  /** The format that was decoded from (auto-detected or explicit). */\n  from: Format;\n  /** Number of rules in the intermediate canonical representation. */\n  ruleCount: number;\n}\n\n/** Result of validating a policy. */\nexport interface ValidateResult {\n  /** Whether the policy is valid. */\n  valid: boolean;\n  /** Validation errors (empty when valid). */\n  errors: ValidationError[];\n}\n\n/** Result of checking a tool call against a policy. */\nexport interface CheckResult {\n  /** The evaluation decision. */\n  decision: \"allow\" | \"deny\" | \"ask\";\n}\n\n// ---------------------------------------------------------------------------\n// detectFormat / detectFormatFromPath / resolveFormat\n// ---------------------------------------------------------------------------\n\n/**\n * Detect the agent format from a file path.\n *\n * Matches against known config file names:\n *   - `.claude/settings.json` or `.claude/settings.local.json` → claude-code\n *   - `opencode.json` → opencode\n *   - `.kiro/permissions.json` → kiro\n *   - `codex.toml` → codex\n *   - `.agents/permissions.json` or `.agents/permissions.local.json` → canonical\n */\nexport function detectFormatFromPath(filePath: string): Format | undefined {\n  const base = basename(filePath);\n  const dir = filePath.replace(/\\\\/g, \"/\");\n\n  // Check directory-qualified paths first\n  if (\n    dir.endsWith(\"/.claude/settings.json\") ||\n    dir.endsWith(\"/.claude/settings.local.json\")\n  ) {\n    return \"claude-code\";\n  }\n  if (\n    dir.endsWith(\"/.agents/permissions.json\") ||\n    dir.endsWith(\"/.agents/permissions.local.json\")\n  ) {\n    return \"canonical\";\n  }\n  if (dir.endsWith(\"/.kiro/permissions.json\")) return \"kiro\";\n\n  // Check basenames\n  if (base === \"opencode.json\") return \"opencode\";\n  if (base === \"codex.toml\") return \"codex\";\n  if (base === \".crush.json\") return \"crush\";\n\n  return undefined;\n}\n\n/**\n * Resolve a format specifier that may be an agent name or a file path.\n *\n * Returns the format if it's a known agent name.\n * Returns the detected format if it's a known config file path.\n * Returns undefined if neither.\n */\nexport function resolveFormat(spec: string): Format | undefined {\n  // Check agent names first\n  if (spec === \"canonical\" || isAgentId(spec)) {\n    return spec;\n  }\n\n  // Try file path detection\n  return detectFormatFromPath(spec);\n}\n\n/**\n * Detect the agent format from parsed JSON content.\n *\n * Distinguishing features:\n *   canonical — `rules` array of {tool, tier} objects, or top-level `permissions`, `sandbox`, `profiles`, etc.\n *   claude-code — `allow`/`deny`/`ask` arrays of plain strings, `additionalDirectories`\n *   crush — `allowed_tools` (required) array of plain strings\n *   kiro — `allowedTools` or `toolsSettings`\n *   codex — `approval_policy`, `sandbox_mode`, `permissions` (record of named profiles)\n *   opencode — bare \"allow\"/\"deny\" string, or object with lowercase tool keys (bash, read, edit, …)\n */\nexport function detectFormat(value: unknown): Format | undefined {\n  if (typeof value === \"string\") {\n    if (value === \"allow\" || value === \"deny\") return \"opencode\";\n    return undefined;\n  }\n\n  if (!isRecord(value)) return undefined;\n  const obj = value;\n\n  // Crush: required allowed_tools array\n  if (Array.isArray(obj.allowed_tools)) return \"crush\";\n\n  // Kiro: allowedTools or toolsSettings\n  if (Array.isArray(obj.allowedTools) || \"toolsSettings\" in obj) return \"kiro\";\n\n  // Codex: approval_policy, sandbox_mode, or permissions as record of named profiles\n  if (\n    \"approval_policy\" in obj ||\n    \"sandbox_mode\" in obj ||\n    \"default_permissions\" in obj\n  ) {\n    return \"codex\";\n  }\n\n  // Claude Code: allow/deny/ask arrays of strings, additionalDirectories\n  if (\n    (\"allow\" in obj && Array.isArray(obj.allow)) ||\n    (\"deny\" in obj && Array.isArray(obj.deny)) ||\n    (\"ask\" in obj && Array.isArray(obj.ask))\n  ) {\n    // Distinguish from canonical: Claude Code arrays contain plain strings,\n    // canonical `rules` contains objects with {tool, tier}\n    const check = (arr: unknown): boolean =>\n      Array.isArray(arr) && arr.length > 0 && typeof arr[0] === \"string\";\n    if (check(obj.allow) || check(obj.deny) || check(obj.ask))\n      return \"claude-code\";\n  }\n\n  // Canonical: rules array of {tool, tier} objects\n  if (Array.isArray(obj.rules)) {\n    const first: unknown = obj.rules[0];\n    if (\n      typeof first === \"object\" &&\n      first !== null &&\n      \"tool\" in first &&\n      \"tier\" in first\n    ) {\n      return \"canonical\";\n    }\n  }\n\n  // Canonical: top-level keys like sandbox, profiles, delegation, network\n  if (\n    \"sandbox\" in obj ||\n    \"profiles\" in obj ||\n    \"delegation\" in obj ||\n    \"network\" in obj ||\n    \"activeProfile\" in obj\n  ) {\n    return \"canonical\";\n  }\n\n  // Canonical: permissions with allow/deny/ask containing string rules\n  if (isRecord(obj.permissions)) {\n    const perms = obj.permissions;\n    if (\n      (\"allow\" in perms && typeof perms.allow !== \"undefined\") ||\n      (\"deny\" in perms && typeof perms.deny !== \"undefined\")\n    ) {\n      return \"canonical\";\n    }\n  }\n\n  // OpenCode: object with lowercase tool keys\n  const ocTools = new Set([\n    \"bash\",\n    \"read\",\n    \"edit\",\n    \"glob\",\n    \"grep\",\n    \"list\",\n    \"task\",\n    \"external_directory\",\n    \"todowrite\",\n    \"question\",\n    \"webfetch\",\n    \"websearch\",\n    \"lsp\",\n    \"doom_loop\",\n    \"skill\",\n  ]);\n  for (const key of Object.keys(obj)) {\n    if (ocTools.has(key)) return \"opencode\";\n  }\n\n  // Fallback: if there's a `permissions` key with `defaultMode`, likely canonical\n  if (\"defaultMode\" in obj) return \"canonical\";\n\n  return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// convert\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a permission config between agent formats.\n *\n * @param from - Source format. Omit or `undefined` to auto-detect.\n * @param to - Target format (required).\n * @param json - Parsed JSON input (any agent-native or canonical object).\n * @returns Conversion result with output, detected format, and rule count.\n * @throws Error on invalid input, unknown format, or codec failure.\n */\nexport function convert(\n  from: Format | undefined,\n  to: Format,\n  json: unknown,\n): ConvertResult {\n  // Auto-detect --from\n  let fromAgent: Format;\n  if (from !== undefined) {\n    fromAgent = from;\n  } else {\n    const detected = detectFormat(json);\n    if (!detected) {\n      throw new Error(\n        \"could not auto-detect input format. Specify from explicitly.\",\n      );\n    }\n    fromAgent = detected;\n  }\n\n  // Validate formats\n  if (fromAgent !== \"canonical\" && !AGENTS.includes(fromAgent)) {\n    throw new TypeError(\n      `unknown from format: ${fromAgent}. Valid: ${[...AGENTS, \"canonical\"].join(\", \")}`,\n    );\n  }\n  if (to !== \"canonical\" && !AGENTS.includes(to)) {\n    throw new TypeError(\n      `unknown to format: ${to}. Valid: ${[...AGENTS, \"canonical\"].join(\", \")}`,\n    );\n  }\n\n  // Decode: agent-native → canonical\n  let canonical: AgentPermissionPolicy;\n  if (fromAgent === \"canonical\") {\n    const result = validatePolicy(json);\n    if (!result.ok) throw new ConvertError(result.error, result.errors);\n    canonical = result.value;\n  } else {\n    const codec = CODECS[fromAgent];\n    // The decoded agent config is unknown-shaped here while the zod codec's decode is typed for its own native input — a config of the wrong shape throws inside decode.\n    // @ts-expect-error unknown JSON passed to a native-typed decode; invalid shapes throw and surface as conversion errors\n    canonical = codec.decode(json);\n    const validated = validatePolicy(canonical);\n    if (!validated.ok)\n      throw new ConvertError(validated.error, validated.errors);\n    canonical = validated.value;\n  }\n\n  // Count rules in intermediate canonical form\n  const ruleCount = countRules(canonical);\n\n  // Encode: canonical → agent-native\n  let output: unknown;\n  if (to === \"canonical\") {\n    // Inject $schema so generated files get IDE support\n    const schemaUrl =\n      \"https://github.com/Mearman/agent-permissions/releases/latest/download/agent-permissions.schema.json\";\n    output = { $schema: schemaUrl, ...canonical };\n  } else {\n    const codec = CODECS[to];\n    output = codec.encode(canonical);\n  }\n\n  return { output, from: fromAgent, ruleCount };\n}\n\n// ---------------------------------------------------------------------------\n// validate\n// ---------------------------------------------------------------------------\n\n/**\n * Validate a parsed JSON object against the canonical policy schema.\n *\n * @param json - Parsed JSON to validate.\n * @returns Validation result with errors array (empty when valid).\n */\nexport function validate(json: unknown): ValidateResult {\n  const result = validatePolicy(json);\n  if (result.ok) return { valid: true, errors: [] };\n  return { valid: false, errors: result.errors };\n}\n\n// ---------------------------------------------------------------------------\n// check\n// ---------------------------------------------------------------------------\n\n/**\n * Evaluate a tool call against a canonical policy.\n *\n * @param tool - Tool name (e.g. \"Bash\", \"Read\").\n * @param input - Tool input string to match against patterns.\n * @param json - Parsed canonical policy JSON.\n * @param context - Optional evaluation context (cwd, branch).\n * @returns Check result with the evaluation decision.\n * @throws Error if the policy is invalid.\n */\nexport function check(\n  tool: string,\n  input: string,\n  json: unknown,\n  context?: { cwd?: string; branch?: string },\n): CheckResult {\n  const result = validatePolicy(json);\n  if (!result.ok) throw new ConvertError(result.error, result.errors);\n\n  const policy = result.value;\n\n  const rules = collectRules(policy);\n  const mode = policy.defaultMode ?? \"standard\";\n  const mappedMode = mapMode(mode);\n\n  const decision = evaluate(\n    { defaultMode: mappedMode, rules },\n    tool,\n    input,\n    context,\n  );\n\n  return { decision };\n}\n\n// ---------------------------------------------------------------------------\n// Error class\n// ---------------------------------------------------------------------------\n\n/** Error thrown when conversion or validation fails. */\nexport class ConvertError extends Error {\n  /** Validation errors that caused the failure. */\n  readonly errors: ValidationError[];\n\n  constructor(message: string, errors: ValidationError[]) {\n    super(message);\n    this.name = \"ConvertError\";\n    this.errors = errors;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction countRules(canonical: unknown): number {\n  if (isRecord(canonical) && Array.isArray(canonical.rules)) {\n    return canonical.rules.length;\n  }\n  return 0;\n}\n","/**\n * Agent config file resolution — shared between CLI and sync.\n *\n * Maps format names to default file paths, walks directories to find configs,\n * and provides read/write helpers for the convert/validate/check/sync pipeline.\n */\n\nimport { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { existsSync } from \"node:fs\";\nimport { type AgentId } from \"./compat/codecs.ts\";\nimport { isRecord } from \"./guards.ts\";\nimport { type Format } from \"./api.ts\";\n\n// ---------------------------------------------------------------------------\n// File mapping\n// ---------------------------------------------------------------------------\n\n/** Per-format config file info. */\nexport interface AgentFileDef {\n  /** Relative path to the main config file. */\n  name: string;\n  /** Relative path to the local override file (read-only, never written). */\n  localName?: string;\n  /**\n   * Extract the permissions payload from a parsed native config.\n   * Returns undefined if the config doesn't contain a permissions block.\n   */\n  extract?: (raw: unknown) => unknown;\n  /**\n   * Wrap encoded permissions back into the native config structure.\n   */\n  wrap?: (encoded: unknown) => unknown;\n}\n\n/** Default config file for each agent format, relative to a project root. */\nexport const AGENT_FILES: Record<AgentId | \"canonical\", AgentFileDef> = {\n  canonical: {\n    name: \".agents/permissions.json\",\n    localName: \".agents/permissions.local.json\",\n    extract: (raw) => raw,\n    wrap: (encoded) => encoded,\n  },\n  \"claude-code\": {\n    name: \".claude/settings.json\",\n    localName: \".claude/settings.local.json\",\n    extract: (raw) => {\n      if (!isRecord(raw) || !(\"permissions\" in raw)) return undefined;\n      return raw.permissions;\n    },\n    wrap: (encoded) => ({ permissions: encoded }),\n  },\n  codex: { name: \"codex.toml\" }, // TOML — read only if pre-parsed\n  opencode: {\n    name: \"opencode.json\",\n    extract: (raw) => {\n      if (!isRecord(raw) || !(\"permission\" in raw)) return undefined;\n      return raw.permission;\n    },\n    wrap: (encoded) => ({ permission: encoded }),\n  },\n  crush: { name: \".crush.json\" }, // Crush has no standard config file\n  kiro: {\n    name: \".kiro/permissions.json\",\n    extract: (raw) => raw,\n    wrap: (encoded) => encoded,\n  },\n};\n\n/** Get the default file name for a format. */\nexport function defaultFileName(format: Format): string {\n  return AGENT_FILES[format].name;\n}\n\n// ---------------------------------------------------------------------------\n// Walk-up resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Walk up from a starting directory, looking for a format's default file.\n * Returns the first existing file found, or the default path in `startDir`.\n */\nexport function findDefaultFile(format: Format, startDir: string): string {\n  const fileName = defaultFileName(format);\n  let dir = resolve(startDir);\n  for (;;) {\n    const candidate = join(dir, fileName);\n    if (existsSync(candidate)) return candidate;\n    const parent = dirname(dir);\n    if (parent === dir) break;\n    dir = parent;\n  }\n  return join(resolve(startDir), fileName);\n}\n\n// ---------------------------------------------------------------------------\n// Result type\n// ---------------------------------------------------------------------------\n\n/** Discriminated union for operations that can fail. */\nexport type Result<T> = { ok: true; value: T } | { ok: false; error: string };\n\n/** Create a successful result. */\nexport function ok<T>(value: T): Result<T> {\n  return { ok: true, value };\n}\n\n/** Create a failed result. */\nexport function fail<T>(error: string): Result<T> {\n  return { ok: false, error };\n}\n\n// ---------------------------------------------------------------------------\n// Read / write helpers\n// ---------------------------------------------------------------------------\n\n/** Read stdin as a string. */\nexport async function readStdin(): Promise<string> {\n  const chunks: Uint8Array[] = [];\n  for await (const chunk of process.stdin) {\n    // The stream's iterator types its chunks as `any`; instanceof narrows without an assertion. Buffer is a Uint8Array subclass, so binary chunks take the first branch.\n    if (chunk instanceof Uint8Array) {\n      chunks.push(chunk);\n    } else if (typeof chunk === \"string\") {\n      chunks.push(new TextEncoder().encode(chunk));\n    }\n  }\n  return Buffer.concat(chunks).toString(\"utf-8\");\n}\n\n/** Read from a file path, or stdin if undefined. */\nexport async function readInput(path: string | undefined): Promise<string> {\n  if (path === undefined) return readStdin();\n  return readFile(path, \"utf-8\");\n}\n\n/** Parse a JSON string. Returns a Result instead of throwing. */\nexport function parseJson(raw: string, source: string): Result<unknown> {\n  try {\n    return ok(JSON.parse(raw));\n  } catch {\n    return fail(`${source}: invalid JSON`);\n  }\n}\n\n/** Write JSON to a file, creating parent directories as needed. */\nexport async function writeJsonFile(\n  path: string,\n  content: string,\n): Promise<void> {\n  await mkdir(dirname(path), { recursive: true });\n  await writeFile(path, content);\n}\n\n// ---------------------------------------------------------------------------\n// Decode / validate helpers\n// ---------------------------------------------------------------------------\n\nimport { AgentPermissionPolicy } from \"./schema.ts\";\nimport { CODECS } from \"./compat/codecs.ts\";\n\n/** Validation error for a single field. */\nexport interface ValidationError {\n  /** Dot-separated path to the invalid field, or \"(root)\". */\n  path: string;\n  /** Human-readable error message. */\n  message: string;\n}\n\n/** Detailed validation result with structured errors. */\nexport type ValidateResult =\n  | { ok: true; value: AgentPermissionPolicy }\n  | { ok: false; error: string; errors: ValidationError[] };\n\n/** Validate parsed JSON against the canonical policy schema. */\nexport function validatePolicy(json: unknown): ValidateResult {\n  const result = AgentPermissionPolicy.safeParse(json);\n  if (result.success) return { ok: true, value: result.data };\n  const errors: ValidationError[] = result.error.issues.map((issue) => ({\n    path: issue.path.length > 0 ? issue.path.join(\".\") : \"(root)\",\n    message: issue.message,\n  }));\n  return {\n    ok: false,\n    error: `validation failed: ${errors.map((e) => `${e.path}: ${e.message}`).join(\", \")}`,\n    errors,\n  };\n}\n\n/**\n * Decode native agent config → canonical policy.\n * Extracts the permissions payload using the agent's extract(),\n * decodes via codec, then validates against the canonical schema.\n */\nexport function decodeNative(format: AgentId, raw: unknown): ValidateResult {\n  const def = AGENT_FILES[format];\n  if (def.extract === undefined) {\n    return {\n      ok: false,\n      error: `${format}: no extract defined for this format`,\n      errors: [],\n    };\n  }\n\n  const payload = def.extract(raw);\n  if (payload === undefined || payload === null) {\n    return {\n      ok: false,\n      error: `${format}: no permissions payload found in config`,\n      errors: [],\n    };\n  }\n\n  const codec = CODECS[format];\n  let decoded: unknown;\n  try {\n    // The payload genuinely is unknown here (an extract() output), while each zod codec's decode is typed for its own native input — a payload of the wrong shape throws inside decode and lands in the catch below.\n    // @ts-expect-error unknown payload passed to a native-typed decode; invalid shapes throw and are handled by the catch\n    decoded = codec.decode(payload);\n  } catch (e) {\n    const message = e instanceof Error ? e.message : String(e);\n    return {\n      ok: false,\n      error: `${format} decode failed: ${message}`,\n      errors: [],\n    };\n  }\n\n  return validatePolicy(decoded);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAM,SAASA,8BAAQ;;;;;;;;;;;AA+CvB,SAAgB,qBAAqB,UAAsC;CACzE,MAAM,WAAOC,oBAAS,QAAQ;CAC9B,MAAM,MAAM,SAAS,QAAQ,OAAO,GAAG;CAGvC,IACE,IAAI,SAAS,wBAAwB,KACrC,IAAI,SAAS,8BAA8B,GAE3C,OAAO;CAET,IACE,IAAI,SAAS,2BAA2B,KACxC,IAAI,SAAS,iCAAiC,GAE9C,OAAO;CAET,IAAI,IAAI,SAAS,yBAAyB,GAAG,OAAO;CAGpD,IAAI,SAAS,iBAAiB,OAAO;CACrC,IAAI,SAAS,cAAc,OAAO;CAClC,IAAI,SAAS,eAAe,OAAO;AAGrC;;;;;;;;AASA,SAAgB,cAAc,MAAkC;CAE9D,IAAI,SAAS,eAAeC,yBAAU,IAAI,GACxC,OAAO;CAIT,OAAO,qBAAqB,IAAI;AAClC;;;;;;;;;;;;AAaA,SAAgB,aAAa,OAAoC;CAC/D,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,UAAU,WAAW,UAAU,QAAQ,OAAO;EAClD;CACF;CAEA,IAAI,CAACC,wBAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,MAAM;CAGZ,IAAI,MAAM,QAAQ,IAAI,aAAa,GAAG,OAAO;CAG7C,IAAI,MAAM,QAAQ,IAAI,YAAY,KAAK,mBAAmB,KAAK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