{"version":3,"file":"codecs.mjs","names":[],"sources":["../../src/compat/codecs.ts"],"sourcesContent":["/**\n * Agent compatibility codecs — bidirectional transforms between our canonical\n * `.agents/permissions.json` format and each agent's native permission config.\n *\n * Usage: decode: agent native config → canonical AgentPermissionPolicy encode: canonical\n * AgentPermissionPolicy → agent native config\n *\n * Import { claudeCodeCodec } from \"./compat/codecs.js\";\n *\n * // Read Claude Code settings and convert to canonical const canonical =\n * claudeCodeCodec.decode(claudeSettings.permissions);\n *\n * // Write canonical policy back out as Claude Code settings const claudePermBlock =\n * z.encode(claudeCodeCodec, canonical);\n */\n\nimport * as z from \"zod\";\nimport {\n  AgentPermissionPolicy,\n  type PermissionMode,\n  type PermissionTiers,\n  type Rule,\n  type Sandbox,\n} from \"../schema.ts\";\nimport {\n  normaliseStringRule,\n  parseRulePattern,\n  ruleToString,\n  collectRules,\n  mapMode,\n} from \"../evaluate.ts\";\nimport { resolveProfiles } from \"../profiles.ts\";\nimport {\n  UnsupportedCapabilityError,\n  type UnsupportedRule,\n  type UnsupportedSetting,\n} from \"./unsupported.ts\";\nimport {\n  ClaudeCodePermissionMode,\n  CodexApprovalMode,\n  CodexDomainAccess,\n  CodexFilesystemAccess,\n  CodexSandboxMode,\n  PermissionBehavior,\n} from \"./enums.ts\";\n\n/**\n * The canonical rules as a codec for `agent` can hold them. No agent format can limit a rule to an\n * actor or a role, so a rule carrying either is not written as if it were unconditional: an allow is\n * left out, which is stricter, and a deny or ask is refused, since writing it would either widen the\n * rule or restrict everyone. Any other condition (a directory, a branch, an environment variable, a\n * remote) is dropped the same way an allow is, but a deny or ask keeps applying everywhere, which\n * is stricter. An ask that names approvers is refused too: written plain, anyone the agent's user\n * is could approve it. All refused rules are reported together.\n *\n * @throws UnsupportedCapabilityError if a deny or ask rule is limited to an actor or a role, or an\n *   ask names approvers.\n */\nfunction agentRules(\n  policy: Parameters<typeof collectRules>[0],\n  agent: string,\n): Rule[] {\n  const unsupported: UnsupportedRule[] = [];\n  const kept = collectRules(policy).filter((rule) => {\n    if (rule.approvers !== undefined) {\n      unsupported.push({\n        rule,\n        reason: `${agent} cannot restrict who may approve a request`,\n      });\n      return false;\n    }\n    if (rule.when?.actor === undefined && rule.when?.role === undefined) {\n      // No agent format holds any other condition either. Written without it, a deny or ask only\n      // becomes stricter; an allow would apply everywhere, so it is left out.\n      return rule.when === undefined || rule.tier !== \"allow\";\n    }\n    if (rule.tier !== \"allow\") {\n      unsupported.push({\n        rule,\n        reason: `${agent} cannot limit a rule to an actor or a role`,\n      });\n    }\n    return false;\n  });\n  if (unsupported.length > 0) {\n    throw new UnsupportedCapabilityError(agent, unsupported);\n  }\n  return kept;\n}\n\n// ---------------------------------------------------------------------------\n// Canonical agent identifiers\n// ---------------------------------------------------------------------------\n\nexport const agentId = z.enum([\n  \"claude-code\",\n  \"codex\",\n  \"kiro\",\n  \"opencode\",\n  \"crush\",\n  \"omp\",\n]);\n\nexport type AgentId = z.infer<typeof agentId>;\n\n// ---------------------------------------------------------------------------\n// Claude Code codec\n// ---------------------------------------------------------------------------\n// Claude Code uses `Tool(pattern)` rule strings in allow/deny/ask arrays.\n// Our spec is a compatible superset — same rule syntax, same tiers.\n// Conversion is mostly structural: our top-level defaultMode maps to/from\n// their permissions.defaultMode (which we also accept inside permissions).\n\n/**\n * The Claude Code mode for a canonical mode it has no name for, never looser than the original.\n * `readonly` refuses what no rule allows, which is what dontAsk does. `restricted` and `standard`\n * ask, which is default. `autonomous` writes none: Claude Code's own default asks, which is stricter.\n */\nconst claudeModeForCanonical: Partial<Record<string, \"default\" | \"dontAsk\">> = {\n  readonly: \"dontAsk\",\n  restricted: \"default\",\n  standard: \"default\",\n};\n\nconst claudeCodeNative = z\n  .object({\n    allow: z.array(z.string()).optional(),\n    deny: z.array(z.string()).optional(),\n    ask: z.array(z.string()).optional(),\n    defaultMode: ClaudeCodePermissionMode.optional(),\n    additionalDirectories: z.array(z.string()).optional(),\n  })\n  .partial()\n  .strict();\n\ntype ClaudeCodeNative = z.infer<typeof claudeCodeNative>;\n\nexport const claudeCodeCodec = z.codec(\n  claudeCodeNative,\n  AgentPermissionPolicy,\n  {\n    decode(native) {\n      const rules: Rule[] = [];\n\n      if (native.deny) {\n        rules.push(...native.deny.map((r) => normaliseStringRule(r, \"deny\")));\n      }\n      if (native.ask) {\n        rules.push(...native.ask.map((r) => normaliseStringRule(r, \"ask\")));\n      }\n      if (native.allow) {\n        rules.push(...native.allow.map((r) => normaliseStringRule(r, \"allow\")));\n      }\n\n      const result: Partial<AgentPermissionPolicy> = {};\n      if (rules.length > 0) result.rules = rules;\n      if (native.additionalDirectories?.length) {\n        result.permissions = {\n          additionalDirectories: native.additionalDirectories,\n        };\n      }\n      if (native.defaultMode) {\n        result.defaultMode = native.defaultMode;\n      }\n\n      return result;\n    },\n    encode(canonical) {\n      const result: Partial<ClaudeCodeNative> = {};\n\n      const allRules = agentRules(canonical, \"claude-code\");\n      if (allRules.length > 0) {\n        result.deny = allRules\n          .filter((r) => r.tier === \"deny\")\n          .map(ruleToString);\n        result.ask = allRules.filter((r) => r.tier === \"ask\").map(ruleToString);\n        result.allow = allRules\n          .filter((r) => r.tier === \"allow\")\n          .map(ruleToString);\n      }\n\n      if (canonical.permissions?.additionalDirectories?.length) {\n        result.additionalDirectories =\n          canonical.permissions.additionalDirectories;\n      }\n\n      // defaultMode — only include modes that Claude Code accepts\n      const ccDefaultMode =\n        canonical.defaultMode ?? canonical.permissions?.defaultMode;\n      if (ccDefaultMode) {\n        const claudeCodeModes = [\n          \"acceptEdits\",\n          \"auto\",\n          \"bypassPermissions\",\n          \"default\",\n          \"dontAsk\",\n          \"plan\",\n        ] as const;\n        const match =\n          claudeCodeModes.find((m) => m === ccDefaultMode) ??\n          claudeModeForCanonical[ccDefaultMode];\n        if (match) {\n          result.defaultMode = match;\n        }\n      }\n\n      return result;\n    },\n  },\n);\n\n// ---------------------------------------------------------------------------\n// OpenCode codec\n// ---------------------------------------------------------------------------\n// OpenCode uses `{ tool: { pattern: \"action\" } }` with last-match-wins.\n// Pattern syntax differs: space-separated (`\"git *\"`) vs our `:*` prefix.\n// Tool names differ: lowercase (`edit`, `list`) vs our PascalCase (`Edit`, `Glob`).\n\nconst ocAction = PermissionBehavior;\n\nconst ocRule = z.union([ocAction, z.record(z.string(), ocAction)]);\n\nconst opencodeNative = z.union([\n  ocAction,\n  z\n    .object({\n      read: ocRule.optional(),\n      edit: ocRule.optional(),\n      glob: ocRule.optional(),\n      grep: ocRule.optional(),\n      list: ocRule.optional(),\n      bash: ocRule.optional(),\n      task: ocRule.optional(),\n      external_directory: ocRule.optional(),\n      todowrite: ocAction.optional(),\n      question: ocAction.optional(),\n      webfetch: ocAction.optional(),\n      websearch: ocAction.optional(),\n      lsp: ocRule.optional(),\n      doom_loop: ocAction.optional(),\n      skill: ocRule.optional(),\n    })\n    .strict(),\n]);\n\n/** Map OpenCode tool names to our canonical names. OpenCode uses lowercase; we use PascalCase. */\nconst ocToCanonical: Record<string, string> = {\n  bash: \"Bash\",\n  read: \"Read\",\n  edit: \"Edit\",\n  glob: \"Glob\",\n  grep: \"Grep\",\n  list: \"Glob\", // list ≈ Glob\n  webfetch: \"WebFetch\",\n  websearch: \"WebFetch\", // websearch ≈ WebFetch\n  task: \"Agent\", // subagent spawning ≈ Agent\n  codesearch: \"Grep\", // codesearch ≈ Grep\n};\n\n/**\n * Map canonical tool names back to OpenCode tool names. Each canonical tool maps to the primary\n * OpenCode equivalent.\n */\nconst OC_STRICTNESS = { allow: 0, ask: 1, deny: 2 } as const;\n\nconst canonicalToOc: Record<string, string> = {\n  Bash: \"bash\",\n  Read: \"read\",\n  Write: \"edit\", // write → edit in OpenCode\n  Edit: \"edit\",\n  Glob: \"glob\",\n  Grep: \"grep\",\n  WebFetch: \"webfetch\",\n  Agent: \"task\",\n};\n\n/** Tools with no canonical mapping — silently skipped during decode. */\nconst OC_UNMAPPED_TOOLS = new Set([\n  \"doom_loop\",\n  \"lsp\",\n  \"skill\",\n  \"question\",\n  \"todowrite\",\n]);\n\nexport const opencodeCodec = z.codec(opencodeNative, AgentPermissionPolicy, {\n  decode(native) {\n    // Shorthand \"allow\"/\"deny\" applies to everything\n    if (typeof native === \"string\") {\n      const mode =\n        native === \"allow\"\n          ? (\"autonomous\" as const)\n          : native === \"deny\"\n            ? (\"restricted\" as const)\n            : (\"standard\" as const);\n      return { defaultMode: mode };\n    }\n\n    const rules: Rule[] = [];\n    let sandbox: Partial<Sandbox> | undefined;\n    const additionalDirectories: string[] = [];\n\n    for (const [ocTool, rule] of Object.entries(native)) {\n      if (rule === undefined) continue;\n      if (OC_UNMAPPED_TOOLS.has(ocTool)) continue;\n\n      if (ocTool === \"external_directory\") {\n        if (typeof rule === \"object\") {\n          for (const [dir, action] of Object.entries(rule)) {\n            if (action === \"allow\") additionalDirectories.push(dir);\n          }\n        }\n        continue;\n      }\n\n      if (typeof rule === \"string\") {\n        // Shorthand action for entire tool\n        const canonicalTool = ocToCanonical[ocTool] ?? ocTool;\n        rules.push({\n          tool: canonicalTool,\n          tier: rule,\n        });\n      } else {\n        // Granular patterns: { \"git *\": \"allow\", \"rm *\": \"deny\" }\n        for (const [pattern, action] of Object.entries(rule)) {\n          const canonicalTool = ocToCanonical[ocTool] ?? ocTool;\n          rules.push({\n            tool: canonicalTool,\n            // Wrap bare pattern — no Tool(...) wrapper needed in structured rules\n            pattern,\n            tier: action,\n          });\n        }\n      }\n    }\n\n    const result: Partial<AgentPermissionPolicy> = {};\n    if (rules.length > 0) result.rules = rules;\n    if (additionalDirectories.length > 0) {\n      result.permissions = { additionalDirectories };\n      sandbox = { writableRoots: additionalDirectories };\n    }\n    if (sandbox) result.sandbox = sandbox;\n    return result;\n  },\n  encode(canonical) {\n    const allRules = agentRules(canonical, \"opencode\");\n    if (allRules.length === 0) return { bash: \"ask\" };\n\n    const result: Record<string, Record<string, \"allow\" | \"deny\" | \"ask\">> = {};\n    const unsupported: UnsupportedRule[] = [];\n\n    for (const rule of allRules) {\n      const ocTool = canonicalToOc[rule.tool];\n      if (!ocTool) {\n        if (rule.tier !== \"allow\") {\n          unsupported.push({\n            rule,\n            reason: `OpenCode has no permission setting for ${rule.tool}`,\n          });\n        }\n        continue;\n      }\n\n      const pattern = rule.pattern ? rule.pattern.replace(/:\\*$/, \" *\") : \"*\";\n\n      let toolRules = result[ocTool];\n      if (!toolRules) {\n        toolRules = {};\n        result[ocTool] = toolRules;\n      }\n      // Two rules on one pattern collapse to the stricter, whatever order they came in.\n      const existing = toolRules[pattern];\n      toolRules[pattern] =\n        existing === undefined ||\n        OC_STRICTNESS[rule.tier] > OC_STRICTNESS[existing]\n          ? rule.tier\n          : existing;\n    }\n    if (unsupported.length > 0) {\n      throw new UnsupportedCapabilityError(\"opencode\", unsupported);\n    }\n\n    // Map sandbox.writableRoots → external_directory\n    if (canonical.sandbox?.writableRoots?.length) {\n      const extDir: Record<string, \"allow\"> = {};\n      for (const root of canonical.sandbox.writableRoots) {\n        extDir[root] = \"allow\";\n      }\n      result.external_directory = extDir;\n    }\n\n    // If any tool has only a single \"*\" pattern, simplify to shorthand\n    const simplified: Record<string, unknown> = { ...result };\n    for (const [tool, patterns] of Object.entries(result)) {\n      if (tool === \"external_directory\") continue;\n      const keys = Object.keys(patterns);\n      if (keys.length === 1 && keys[0] === \"*\") {\n        simplified[tool] = patterns[\"*\"];\n      }\n    }\n\n    return simplified;\n  },\n});\n\n// ---------------------------------------------------------------------------\n// Crush codec\n// ---------------------------------------------------------------------------\n// Crush has a simple allowlist: `permissions.allowed_tools: string[]`.\n// No deny, no ask, no patterns. Tool names are lowercase.\n\nconst crushNative = z\n  .object({\n    allowed_tools: z.array(z.string()),\n  })\n  .strict();\n\n/** Map Crush tool names to canonical names. */\nconst crushToCanonical: Record<string, string> = {\n  view: \"Read\",\n  ls: \"Glob\",\n  grep: \"Grep\",\n  edit: \"Edit\",\n  multiedit: \"Edit\",\n  write: \"Write\",\n  bash: \"Bash\",\n  fetch: \"WebFetch\",\n  agentic_fetch: \"WebFetch\",\n  glob: \"Glob\",\n  download: \"WebFetch\",\n  sourcegraph: \"Grep\",\n  agent: \"Agent\",\n  todos: \"Agent\",\n};\n\nconst canonicalToCrush: Record<string, string> = {\n  Read: \"view\",\n  Glob: \"glob\",\n  Grep: \"grep\",\n  Edit: \"edit\",\n  Write: \"write\",\n  Bash: \"bash\",\n  WebFetch: \"fetch\",\n  Agent: \"agent\",\n};\n\nexport const crushCodec = z.codec(crushNative, AgentPermissionPolicy, {\n  decode(native) {\n    const rules: Rule[] = [];\n    for (const tool of native.allowed_tools) {\n      // MCP tools pass through as-is (mcp_server_tool format)\n      const canonical = crushToCanonical[tool] ?? tool;\n      rules.push({ tool: canonical, tier: \"allow\" });\n    }\n    return { rules };\n  },\n  encode(canonical) {\n    const allRules = agentRules(canonical, \"crush\");\n    const allowed: string[] = [];\n    const unsupported: UnsupportedRule[] = [];\n    for (const rule of allRules) {\n      // Crush has an allowlist of tools and nothing else: no deny, no ask, no patterns. A deny or\n      // ask is refused, and an allow it cannot express is left out, which is stricter.\n      if (rule.tier !== \"allow\") {\n        unsupported.push({\n          rule,\n          reason: \"Crush has only an allowlist of tools: no deny, no ask\",\n        });\n        continue;\n      }\n      if (rule.pattern !== undefined) continue;\n      const crushTool = canonicalToCrush[rule.tool];\n      if (crushTool) allowed.push(crushTool);\n    }\n    if (unsupported.length > 0) {\n      throw new UnsupportedCapabilityError(\"crush\", unsupported);\n    }\n    return { allowed_tools: allowed };\n  },\n});\n\n// ---------------------------------------------------------------------------\n// Kiro (Amazon) codec\n// ---------------------------------------------------------------------------\n// Kiro uses declarative per-agent JSON configs with interactive tiered trust.\n// No SDK — alignment by manual review of https://kiro.dev/docs/.\n//\n// Key concepts:\n//   allowedTools: auto-approved tools (glob patterns with * and ?)\n//   toolsSettings.shell.allowedCommands/deniedCommands: regex patterns\n//   toolsSettings.shell.autoAllowReadonly / denyByDefault: booleans\n//   toolsSettings.<tool>.allowedPaths/deniedPaths: path globs\n//   toolsSettings.aws.allowedServices/deniedServices: service names\n//   toolsSettings.web_fetch.trusted/blocked: regex URL patterns\n//\n// Mapping:\n//   allowedTools → allow rules (bare tool or MCP glob)\n//   toolsSettings.shell.deniedCommands → deny Bash rules\n//   toolsSettings.shell.allowedCommands → allow Bash rules\n//   toolsSettings.<tool>.deniedPaths → deny rules for that tool\n//   toolsSettings.<tool>.allowedPaths → allow rules for that tool\n//   toolsSettings.web_fetch.blocked/trusted → deny/allow WebFetch (domain: regex)\n//   toolsSettings.shell.denyByDefault → defaultMode \"restricted\"\n//   toolsSettings.shell.autoAllowReadonly → allow Bash rules for readonly\n\n/** Kiro → canonical tool name mapping. */\nconst kiroToCanonical: Record<string, string> = {\n  read: \"Read\",\n  write: \"Write\",\n  shell: \"Bash\",\n  aws: \"Aws\",\n  glob: \"Glob\",\n  grep: \"Grep\",\n  web_search: \"WebSearch\",\n  web_fetch: \"WebFetch\",\n  code: \"Code\",\n  delegate: \"Delegate\",\n  subagent: \"Agent\",\n};\n\n/** Canonical → Kiro tool name mapping (reverse of kiroToCanonical). */\nconst canonicalToKiro: Record<string, string> = {};\nfor (const [kiro, canonical] of Object.entries(kiroToCanonical)) {\n  canonicalToKiro[canonical] = kiro;\n}\n\n/**\n * Strip Kiro regex anchors (\\A → ^, \\z → $) from a pattern for canonical use. Kiro auto-anchors\n * with \\A/\\z; we store the pattern without anchors.\n */\nfunction stripKiroAnchors(pattern: string): string {\n  return pattern.replace(/^\\\\A/, \"\").replace(/\\\\z$/, \"\");\n}\n\n/** Add Kiro regex anchors to a pattern for native output. */\nfunction addKiroAnchors(pattern: string): string {\n  return `\\\\A${pattern}\\\\z`;\n}\n\n/** Check if a Kiro allowedTools entry is an MCP reference (starts with @) vs a built-in tool name. */\nfunction isKiroMcpRef(entry: string): boolean {\n  return entry.startsWith(\"@\");\n}\n\n/**\n * Convert a Kiro allowedTools glob pattern to canonical pattern syntax. Kiro uses * and ? globs;\n * MCP refs use @server/tool format.\n */\nfunction kiroGlobToPattern(glob: string): string | undefined {\n  if (!isKiroMcpRef(glob) && !glob.includes(\"*\") && !glob.includes(\"?\"))\n    return undefined;\n  return glob;\n}\n\nconst kiroNative = z.object({\n  allowedTools: z.array(z.string()).optional(),\n  toolsSettings: z\n    .object({\n      shell: z\n        .object({\n          allowedCommands: z.array(z.string()).optional(),\n          deniedCommands: z.array(z.string()).optional(),\n          autoAllowReadonly: z.boolean().optional(),\n          denyByDefault: z.boolean().optional(),\n        })\n        .partial()\n        .optional(),\n      read: z\n        .object({\n          allowedPaths: z.array(z.string()).optional(),\n          deniedPaths: z.array(z.string()).optional(),\n        })\n        .partial()\n        .optional(),\n      write: z\n        .object({\n          allowedPaths: z.array(z.string()).optional(),\n          deniedPaths: z.array(z.string()).optional(),\n        })\n        .partial()\n        .optional(),\n      aws: z\n        .object({\n          allowedServices: z.array(z.string()).optional(),\n          deniedServices: z.array(z.string()).optional(),\n          autoAllowReadonly: z.boolean().optional(),\n        })\n        .partial()\n        .optional(),\n      web_fetch: z\n        .object({\n          trusted: z.array(z.string()).optional(),\n          blocked: z.array(z.string()).optional(),\n        })\n        .partial()\n        .optional(),\n    })\n    .partial()\n    .optional(),\n});\n\ntype KiroNative = z.infer<typeof kiroNative>;\n\nexport const kiroCodec = z.codec(kiroNative, AgentPermissionPolicy, {\n  decode(native) {\n    const rules: Rule[] = [];\n    const result: Partial<AgentPermissionPolicy> = {};\n\n    // --- allowedTools → allow rules ---\n    if (native.allowedTools) {\n      for (const entry of native.allowedTools) {\n        if (isKiroMcpRef(entry)) {\n          // MCP reference: @server, @server/tool, @server/prefix_*\n          rules.push({ tool: entry, tier: \"allow\" });\n        } else {\n          const canonical = kiroToCanonical[entry] ?? entry;\n          const pattern = kiroGlobToPattern(entry);\n          rules.push({\n            tool: canonical,\n            tier: \"allow\",\n            ...(pattern && { pattern }),\n          });\n        }\n      }\n    }\n\n    // --- toolsSettings ---\n    const ts = native.toolsSettings;\n    if (ts) {\n      // Shell (Bash)\n      if (ts.shell) {\n        if (ts.shell.deniedCommands) {\n          for (const cmd of ts.shell.deniedCommands) {\n            rules.push({\n              tool: \"Bash\",\n              pattern: stripKiroAnchors(cmd),\n              tier: \"deny\",\n            });\n          }\n        }\n        if (ts.shell.allowedCommands) {\n          for (const cmd of ts.shell.allowedCommands) {\n            rules.push({\n              tool: \"Bash\",\n              pattern: stripKiroAnchors(cmd),\n              tier: \"allow\",\n            });\n          }\n        }\n        if (ts.shell.denyByDefault) {\n          result.defaultMode = \"restricted\";\n        }\n        // autoAllowReadonly is a Kiro-specific behaviour flag; no canonical mapping\n      }\n\n      // Read paths\n      if (ts.read) {\n        if (ts.read.deniedPaths) {\n          for (const path of ts.read.deniedPaths) {\n            rules.push({ tool: \"Read\", pattern: path, tier: \"deny\" });\n          }\n        }\n        if (ts.read.allowedPaths) {\n          for (const path of ts.read.allowedPaths) {\n            rules.push({ tool: \"Read\", pattern: path, tier: \"allow\" });\n          }\n        }\n      }\n\n      // Write paths\n      if (ts.write) {\n        if (ts.write.deniedPaths) {\n          for (const path of ts.write.deniedPaths) {\n            rules.push({ tool: \"Write\", pattern: path, tier: \"deny\" });\n          }\n        }\n        if (ts.write.allowedPaths) {\n          for (const path of ts.write.allowedPaths) {\n            rules.push({ tool: \"Write\", pattern: path, tier: \"allow\" });\n          }\n        }\n      }\n\n      // AWS services\n      if (ts.aws) {\n        if (ts.aws.deniedServices) {\n          for (const svc of ts.aws.deniedServices) {\n            rules.push({\n              tool: \"Aws\",\n              pattern: `service:${svc}`,\n              tier: \"deny\",\n            });\n          }\n        }\n        if (ts.aws.allowedServices) {\n          for (const svc of ts.aws.allowedServices) {\n            rules.push({\n              tool: \"Aws\",\n              pattern: `service:${svc}`,\n              tier: \"allow\",\n            });\n          }\n        }\n      }\n\n      // Web fetch (URL regex → domain-like patterns)\n      if (ts.web_fetch) {\n        if (ts.web_fetch.blocked) {\n          for (const urlPattern of ts.web_fetch.blocked) {\n            rules.push({\n              tool: \"WebFetch\",\n              pattern: `url:${stripKiroAnchors(urlPattern)}`,\n              tier: \"deny\",\n            });\n          }\n        }\n        if (ts.web_fetch.trusted) {\n          for (const urlPattern of ts.web_fetch.trusted) {\n            rules.push({\n              tool: \"WebFetch\",\n              pattern: `url:${stripKiroAnchors(urlPattern)}`,\n              tier: \"allow\",\n            });\n          }\n        }\n      }\n    }\n\n    if (rules.length > 0) result.rules = rules;\n    return result;\n  },\n\n  encode(canonical) {\n    const allRules = agentRules(canonical, \"kiro\");\n    const result: Partial<KiroNative> = {};\n\n    const allowedTools: string[] = [];\n    const unsupported: UnsupportedRule[] = [];\n    const shellSettings: NonNullable<KiroNative[\"toolsSettings\"]>[\"shell\"] = {};\n    const readSettings: NonNullable<KiroNative[\"toolsSettings\"]>[\"read\"] = {};\n    const writeSettings: NonNullable<KiroNative[\"toolsSettings\"]>[\"write\"] = {};\n    const awsSettings: NonNullable<KiroNative[\"toolsSettings\"]>[\"aws\"] = {};\n    const webFetchSettings: NonNullable<\n      KiroNative[\"toolsSettings\"]\n    >[\"web_fetch\"] = {};\n\n    for (const rule of allRules) {\n      const kiroTool = canonicalToKiro[rule.tool];\n      let written = false;\n\n      // Bare allow rules (no pattern) → allowedTools\n      if (rule.tier === \"allow\" && rule.pattern === undefined) {\n        if (isKiroMcpRef(rule.tool)) {\n          allowedTools.push(rule.tool);\n        } else if (kiroTool) {\n          allowedTools.push(kiroTool);\n        }\n        continue;\n      }\n\n      // Patterned rules → toolsSettings\n      if (rule.tool === \"Bash\" && rule.pattern !== undefined) {\n        if (rule.tier === \"deny\") {\n          shellSettings.deniedCommands ??= [];\n          shellSettings.deniedCommands.push(addKiroAnchors(rule.pattern));\n          written = true;\n        } else if (rule.tier === \"allow\") {\n          shellSettings.allowedCommands ??= [];\n          shellSettings.allowedCommands.push(addKiroAnchors(rule.pattern));\n          written = true;\n        }\n      } else if (rule.tool === \"Read\" && rule.pattern !== undefined) {\n        if (rule.tier === \"deny\") {\n          readSettings.deniedPaths ??= [];\n          readSettings.deniedPaths.push(rule.pattern);\n          written = true;\n        } else if (rule.tier === \"allow\") {\n          readSettings.allowedPaths ??= [];\n          readSettings.allowedPaths.push(rule.pattern);\n          written = true;\n        }\n      } else if (rule.tool === \"Write\" && rule.pattern !== undefined) {\n        if (rule.tier === \"deny\") {\n          writeSettings.deniedPaths ??= [];\n          writeSettings.deniedPaths.push(rule.pattern);\n          written = true;\n        } else if (rule.tier === \"allow\") {\n          writeSettings.allowedPaths ??= [];\n          writeSettings.allowedPaths.push(rule.pattern);\n          written = true;\n        }\n      } else if (rule.tool === \"Aws\" && rule.pattern?.startsWith(\"service:\")) {\n        const svc = rule.pattern.slice(\"service:\".length);\n        if (rule.tier === \"deny\") {\n          awsSettings.deniedServices ??= [];\n          awsSettings.deniedServices.push(svc);\n          written = true;\n        } else if (rule.tier === \"allow\") {\n          awsSettings.allowedServices ??= [];\n          awsSettings.allowedServices.push(svc);\n          written = true;\n        }\n      } else if (rule.tool === \"WebFetch\" && rule.pattern?.startsWith(\"url:\")) {\n        const urlPattern = rule.pattern.slice(\"url:\".length);\n        if (rule.tier === \"deny\") {\n          webFetchSettings.blocked ??= [];\n          webFetchSettings.blocked.push(addKiroAnchors(urlPattern));\n          written = true;\n        } else if (rule.tier === \"allow\") {\n          webFetchSettings.trusted ??= [];\n          webFetchSettings.trusted.push(addKiroAnchors(urlPattern));\n          written = true;\n        }\n      }\n      // A deny or ask with nowhere to go in Kiro's settings is refused, not dropped.\n      if (!written && rule.tier !== \"allow\") {\n        unsupported.push({\n          rule,\n          reason: `Kiro has no setting for a ${rule.tier} on ${rule.tool}${rule.pattern === undefined ? \"\" : ` matching ${rule.pattern}`}`,\n        });\n      }\n    }\n\n    if (unsupported.length > 0) {\n      throw new UnsupportedCapabilityError(\"kiro\", unsupported);\n    }\n\n    if (canonical.defaultMode === \"restricted\") {\n      shellSettings.denyByDefault = true;\n    }\n\n    if (allowedTools.length > 0) result.allowedTools = allowedTools;\n\n    const toolsSettings: NonNullable<KiroNative[\"toolsSettings\"]> = {};\n    if (Object.keys(shellSettings).length > 0)\n      toolsSettings.shell = shellSettings;\n    if (Object.keys(readSettings).length > 0) toolsSettings.read = readSettings;\n    if (Object.keys(writeSettings).length > 0)\n      toolsSettings.write = writeSettings;\n    if (Object.keys(awsSettings).length > 0) toolsSettings.aws = awsSettings;\n    if (Object.keys(webFetchSettings).length > 0)\n      toolsSettings.web_fetch = webFetchSettings;\n    if (Object.keys(toolsSettings).length > 0)\n      result.toolsSettings = toolsSettings;\n\n    return result;\n  },\n});\n\n// ---------------------------------------------------------------------------\n// Codex (OpenAI) codec\n// ---------------------------------------------------------------------------\n// Codex uses OS-level sandboxing + an approval_policy field, not rule strings.\n// TOML serialisation is a file-I/O concern, not the codec's job.\n// The codec works on the JS object that any TOML parser produces.\n//\n// Key concepts:\n//   approval_policy: \"untrusted\" | \"on-request\" | \"on-failure\" | \"never\" | { granular: {...} }\n//   sandbox_mode: \"read-only\" | \"workspace-write\" | \"danger-full-access\"\n//   permissions: named profiles with filesystem + network rules\n//   default_permissions: name of the active profile\n//   sandbox_workspace_write: writable_roots, network_access\n//\n// Mapping:\n//   approval_policy ↔ defaultMode\n//   sandbox_mode → sandbox.mode + defaultMode\n//   sandbox_workspace_write → sandbox.writableRoots + sandbox.networkAccess\n// permissions.<name>.filesystem → deny rules with Read/Write/Edit patterns permissions.<name>.network.domains → network.domains + WebFetch rules named profiles → profiles record + activeProfile\n//\n// Filesystem keys (Codex's `permissions_toml.rs` and `config/permissions.rs`): a key is an absolute path, `~/...`, or a special root such as `:root`, `:minimal`, `:tmpdir` or `:workspace_roots`. A key takes an access value (`read`, `write` or `deny`, with `none` read as a legacy alias of `deny`) or a table of descendant subpaths, and `:workspace_roots` is always given as such a table, with `.` for each root itself. An entry covers its path and everything under it, and the more specific of two entries wins. Codex reads `*`, `?`, `[` and `]` as glob syntax, supported only for `deny`.\n//\n// A canonical `./path` is relative to the working directory, so it becomes a subpath of `:workspace_roots`; an absolute path stays an absolute key. Both cover the whole subtree, and the workspace roots include any Codex adds beyond the working directory, so a written entry is never narrower than the rule it came from. A trailing `/*` or `/**` is that same subtree. Every other pattern (a wildcard elsewhere, a string prefix, `~`, a bare relative path, `.` or `..` segments, a character Codex would read as glob syntax) has no faithful Codex form and is refused.\n\nconst codexApprovalPolicy = z.union([\n  CodexApprovalMode,\n  z.object({\n    granular: z.object({\n      sandbox_approval: z.boolean(),\n      rules: z.boolean(),\n      mcp_elicitations: z.boolean(),\n      request_permissions: z.boolean().optional(),\n      skill_approval: z.boolean().optional(),\n    }),\n  }),\n]);\n\ntype CodexApprovalPolicy = z.infer<typeof codexApprovalPolicy>;\n\n/** One Codex filesystem entry: an access value, or a table of descendant subpaths under its key. */\nconst codexFilesystemEntry = z.union([\n  CodexFilesystemAccess,\n  z.record(z.string(), CodexFilesystemAccess),\n]);\n\ntype CodexFilesystemEntry = z.infer<typeof codexFilesystemEntry>;\n\n/**\n * Codex native config object — what a TOML parser produces from codex config. Only the\n * permission-relevant fields; the full schema has 60+ keys.\n */\nconst codexNative = z.object({\n  approval_policy: codexApprovalPolicy.optional(),\n  sandbox_mode: CodexSandboxMode.optional(),\n  default_permissions: z.string().optional(),\n  sandbox_workspace_write: z\n    .object({\n      writable_roots: z.array(z.string()).optional(),\n      network_access: z.boolean().optional(),\n      exclude_slash_tmp: z.boolean().optional(),\n      exclude_tmpdir_env_var: z.boolean().optional(),\n    })\n    .partial()\n    .optional(),\n  // Named permission profiles: { [name]: { filesystem: { ... }, network: { ... } } }\n  permissions: z\n    .record(\n      z.string(),\n      z.object({\n        // { \"/abs/path\": \"deny\", \":workspace_roots\": { \".\": \"write\", \"secrets\": \"deny\" } }\n        filesystem: z.record(z.string(), codexFilesystemEntry).optional(),\n        network: z\n          .object({\n            enabled: z.boolean().optional(),\n            domains: z.record(z.string(), CodexDomainAccess).optional(),\n          })\n          .partial()\n          .optional(),\n      }),\n    )\n    .optional(),\n});\n\ntype CodexNative = z.infer<typeof codexNative>;\ntype CodexSandboxWorkspaceWrite = NonNullable<\n  CodexNative[\"sandbox_workspace_write\"]\n>;\n\nexport interface CodexProfile {\n  filesystem?: Record<string, CodexFilesystemEntry> | undefined;\n  network?:\n    | {\n        enabled?: boolean | undefined;\n        domains?: Record<string, \"allow\" | \"deny\"> | undefined;\n      }\n    | undefined;\n}\n\n/** Map Codex approval_policy to canonical defaultMode. */\nfunction codexApprovalToMode(\n  policy: CodexApprovalPolicy,\n): AgentPermissionPolicy[\"defaultMode\"] {\n  if (typeof policy === \"string\") {\n    switch (policy) {\n      case \"untrusted\":\n        return \"restricted\";\n      case \"on-request\":\n        return \"standard\";\n      case \"on-failure\":\n        return \"standard\";\n      case \"never\":\n        return \"autonomous\";\n    }\n  }\n  // Granular — treat as standard (some ops auto-approved, some ask)\n  return \"standard\";\n}\n\n/** Map canonical defaultMode back to Codex approval_policy. */\nfunction modeToCodexApproval(\n  mode: AgentPermissionPolicy[\"defaultMode\"],\n): CodexApprovalPolicy {\n  // mapMode names what each mode does to a call no rule covers; dontAsk refuses it, so it is never \"never\"\n  const mapped = mapMode(mode ?? \"standard\");\n  if (mapped === \"autonomous\") return \"never\";\n  if (mapped === \"restricted\" || mapped === \"readonly\") return \"untrusted\";\n  return \"on-request\";\n}\n\n/** Map Codex sandbox_mode to canonical sandbox.mode. */\nfunction codexSandboxToCanonical(\n  mode: z.infer<typeof CodexSandboxMode>,\n): \"readonly\" | \"workspace-write\" | \"full-access\" {\n  switch (mode) {\n    case \"read-only\":\n      return \"readonly\";\n    case \"workspace-write\":\n      return \"workspace-write\";\n    case \"danger-full-access\":\n      return \"full-access\";\n  }\n}\n\n/** Map canonical sandbox.mode back to Codex sandbox_mode. */\nfunction canonicalSandboxToCodex(\n  mode: \"readonly\" | \"workspace-write\" | \"full-access\",\n): z.infer<typeof CodexSandboxMode> {\n  switch (mode) {\n    case \"readonly\":\n      return \"read-only\";\n    case \"workspace-write\":\n      return \"workspace-write\";\n    case \"full-access\":\n      return \"danger-full-access\";\n  }\n}\n\n/** The Codex special root whose subpaths are relative to each workspace root. */\nconst WORKSPACE_ROOTS = \":workspace_roots\";\n\n/** Codex's earlier name for `:workspace_roots`, which it still reads. */\nconst PROJECT_ROOTS = \":project_roots\";\n\n/** The characters Codex reads as glob syntax in a filesystem key or subpath. */\nconst CODEX_GLOB = /[*?[\\]]/;\n\n/** The canonical pattern for everything under a path, given the path's own pattern. */\nfunction subtreePattern(location: string): string {\n  return location === \"/\" ? \"/**\" : `${location}/**`;\n}\n\n/**\n * A literal path as a canonical exact pattern. Exact patterns give a backslash escape meaning, so each is doubled; a path reaching here carries no `*`, which Codex would have read as glob syntax.\n */\nfunction literalPattern(path: string): string {\n  return path.replaceAll(\"\\\\\", \"\\\\\\\\\");\n}\n\n/**\n * Map Codex filesystem entries to canonical deny rules. An entry covers its path and everything under it, so each becomes a rule on the path and one on its subtree. A `write` entry restricts nothing and adds no rule.\n *\n * @throws Error on a `read` or `deny` entry whose location has no canonical form: a special root other than `:workspace_roots`, a `~` path, or glob syntax. Leaving it out would drop a restriction.\n */\nfunction codexFilesystemToRules(\n  fs: Record<string, CodexFilesystemEntry>,\n  rules: Rule[],\n): void {\n  for (const [key, entry] of Object.entries(fs)) {\n    const table = typeof entry === \"string\" ? { \".\": entry } : entry;\n    for (const [subpath, access] of Object.entries(table)) {\n      if (access === \"write\") continue;\n      const location = canonicalLocation(key, subpath);\n      if (location === undefined) {\n        const where = subpath === \".\" ? key : `${key} ${subpath}`;\n        throw new Error(\n          `Codex filesystem entry ${where} = \"${access}\" has no canonical path: only absolute paths and :workspace_roots subpaths without glob syntax convert`,\n        );\n      }\n      const tools =\n        access === \"read\" ? [\"Write\", \"Edit\"] : [\"Read\", \"Write\", \"Edit\"];\n      for (const tool of tools) {\n        rules.push(\n          { tool, pattern: literalPattern(location), tier: \"deny\" },\n          {\n            tool,\n            pattern: subtreePattern(literalPattern(location)),\n            tier: \"deny\",\n          },\n        );\n      }\n    }\n  }\n}\n\n/** The canonical path for a Codex key and one of its subpaths (`.` for the key itself), or `undefined`. */\nfunction canonicalLocation(key: string, subpath: string): string | undefined {\n  if (CODEX_GLOB.test(key) || CODEX_GLOB.test(subpath)) return undefined;\n  const base =\n    key === WORKSPACE_ROOTS || key === PROJECT_ROOTS\n      ? \".\"\n      : key.startsWith(\"/\")\n        ? key\n        : undefined;\n  if (base === undefined || subpath === \".\") return base;\n  return base.endsWith(\"/\") ? `${base}${subpath}` : `${base}/${subpath}`;\n}\n\n/** The file and network restrictions a set of rules puts on a Codex profile. */\ninterface CodexRestrictions {\n  /** Absolute filesystem keys. */\n  absolute: Record<string, CodexRestriction>;\n  /** Subpaths of `:workspace_roots`, with `.` for the roots themselves. */\n  workspace: Record<string, CodexRestriction>;\n  domains: Record<string, \"allow\" | \"deny\">;\n  /** Execpolicy prefix rules, keyed by their space-joined words. */\n  commands: Record<string, CodexCommandRule>;\n}\n\n/** The two filesystem access values a restrictive rule becomes: `read` blocks writes, `deny` blocks everything. */\ntype CodexRestriction = \"read\" | \"deny\";\n\n/** Where a canonical path rule lands in Codex, or why it cannot. */\ntype CodexPathLocation =\n  | { kind: \"absolute\" | \"workspace\"; path: string }\n  | { kind: \"refused\"; reason: string };\n\nfunction refusedPath(reason: string): CodexPathLocation {\n  return { kind: \"refused\", reason };\n}\n\n/** Whether a path is one or more segments, none of them empty, `.` or `..`. */\nfunction isDescendantPath(path: string): boolean {\n  return path\n    .split(\"/\")\n    .every((segment) => segment !== \"\" && segment !== \".\" && segment !== \"..\");\n}\n\n/**\n * Where Codex protects the paths a canonical file pattern names. An exact path and a trailing `/*` or `/**` map to the path's subtree, which is never narrower; anything else is refused.\n */\nfunction codexPathLocation(pattern: string): CodexPathLocation {\n  const parsed = parseRulePattern(pattern);\n  let path: string;\n  if (parsed.type === \"exact\") {\n    path = parsed.content;\n  } else if (parsed.type === \"prefix\") {\n    return refusedPath(\"Codex matches a whole path, not a string prefix\");\n  } else {\n    const base = /^(.*)\\/\\*\\*?$/.exec(parsed.pattern)?.[1];\n    const baseParsed = base === undefined ? undefined : parseRulePattern(base);\n    if (baseParsed?.type !== \"exact\") {\n      return refusedPath(\n        \"Codex matches a path and everything under it, not a wildcard elsewhere in the path\",\n      );\n    }\n    path = baseParsed.content === \"\" ? \"/\" : baseParsed.content;\n  }\n  if (CODEX_GLOB.test(path)) {\n    return refusedPath(\"Codex reads *, ?, [ and ] in a path as glob syntax\");\n  }\n  if (path === \".\" || path === \"./\") return { kind: \"workspace\", path: \".\" };\n  if (path.startsWith(\"./\")) {\n    const subpath = path.slice(2).replace(/\\/$/, \"\");\n    return isDescendantPath(subpath)\n      ? { kind: \"workspace\", path: subpath }\n      : refusedPath(\n          \"Codex takes a workspace path only as a descendant with no empty, . or .. segments\",\n        );\n  }\n  if (path === \"/\") return { kind: \"absolute\", path };\n  if (path.startsWith(\"/\")) {\n    const absolute = path.replace(/\\/$/, \"\");\n    return isDescendantPath(absolute.slice(1))\n      ? { kind: \"absolute\", path: absolute }\n      : refusedPath(\n          \"Codex takes an absolute path only with no empty, . or .. segments\",\n        );\n  }\n  return refusedPath(\n    \"Codex takes an absolute path or a ./ path under the workspace roots\",\n  );\n}\n\nconst FILE_TOOLS: ReadonlySet<string> = new Set([\"Read\", \"Write\", \"Edit\"]);\nconst DOMAIN_PREFIX = \"domain:\";\n\n/** Why Codex cannot enforce a restrictive rule as written, or `undefined` when it can. */\nfunction codexRefusal(\n  rule: Rule,\n  writesBlockedBySandbox: boolean,\n  commandScope: CommandRuleScope,\n): string | undefined {\n  if (rule.when !== undefined) {\n    return \"Codex cannot limit a rule with a condition\";\n  }\n  if (rule.approvers !== undefined) {\n    return \"Codex cannot restrict who may approve a request\";\n  }\n  if (rule.tool === \"WebFetch\" && rule.pattern?.startsWith(DOMAIN_PREFIX)) {\n    return rule.tier === \"ask\"\n      ? \"Codex network domains are allowed or denied, never asked\"\n      : undefined;\n  }\n  if (FILE_TOOLS.has(rule.tool)) {\n    if (rule.pattern === undefined) {\n      // A read-only sandbox already blocks every write, which is at least as strict as denying the tool.\n      if (\n        rule.tier === \"deny\" &&\n        rule.tool !== \"Read\" &&\n        writesBlockedBySandbox\n      ) {\n        return undefined;\n      }\n      return \"Codex takes filesystem access per path, not for a whole tool\";\n    }\n    // Whether Codex can place the path is codexPathLocation's to decide\n    return rule.tier === \"ask\"\n      ? \"Codex filesystem access is read, write or deny, never asked\"\n      : undefined;\n  }\n  if (rule.tool === \"Bash\") {\n    if (commandScope === \"config-only\") {\n      return \"Codex enforces command rules through execpolicy rules files, which only encodeCodex writes\";\n    }\n    if (commandScope === \"profile\") {\n      return \"Codex execpolicy rules apply to every profile, not to one named profile\";\n    }\n    // Whether Codex can match the command exactly is codexCommandPrefix's to decide\n    return rule.pattern === undefined\n      ? \"Codex prefix rules match a command, not the whole tool\"\n      : undefined;\n  }\n  return `Codex has no equivalent of a ${rule.tier} rule for ${rule.tool}`;\n}\n\n/**\n * Where a command rule can go. `config-only` is the config codec on its own, which cannot hold one; `rules-file` is the top level under `encodeCodex`, which writes an execpolicy rules file; `profile` is a named profile under `encodeCodex`, whose command rules a rules file would apply to every profile.\n */\ntype CommandRuleScope = \"config-only\" | \"rules-file\" | \"profile\";\n\n/** The execpolicy decision a restrictive command rule becomes. */\ntype CodexCommandDecision = \"forbidden\" | \"prompt\";\n\n/** One execpolicy prefix rule: the leading words a command must start with, and the decision. */\ninterface CodexCommandRule {\n  words: string[];\n  decision: CodexCommandDecision;\n}\n\n/**\n * A word Codex tokenises exactly as the policy spells it: no quoting, escapes, globbing, expansion or shell operators, so the shell word and the literal text agree.\n */\nconst PLAIN_WORD = /^[\\w@%+=:,./-]+$/;\n\n/**\n * The words of an execpolicy prefix rule matching exactly the commands a canonical command pattern matches, or why there is none. A `prefix:*` pattern and a pattern whose only wildcard is a trailing ` *` both match the words alone or followed by a space and anything, which is what a prefix rule matches once Codex has split the command into words.\n */\nfunction codexCommandPrefix(\n  pattern: string,\n): { words: string[] } | { reason: string } {\n  const parsed = parseRulePattern(pattern);\n  let prefix: string;\n  if (parsed.type === \"prefix\") {\n    prefix = parsed.prefix;\n  } else if (parsed.type === \"wildcard\") {\n    const base = /^(.*) \\*$/.exec(parsed.pattern)?.[1];\n    const baseParsed = base === undefined ? undefined : parseRulePattern(base);\n    if (baseParsed?.type !== \"exact\") {\n      return {\n        reason:\n          \"Codex prefix rules match leading words, not a wildcard elsewhere in the command\",\n      };\n    }\n    prefix = baseParsed.content;\n  } else {\n    return {\n      reason:\n        \"Codex prefix rules match a command with any arguments, not one exact command\",\n    };\n  }\n  const words = prefix.split(\" \");\n  if (!words.every((word) => PLAIN_WORD.test(word))) {\n    return {\n      reason:\n        \"Codex splits a command into shell words, so the prefix must be plain words separated by single spaces, with no quoting or shell syntax\",\n    };\n  }\n  if (words[0]?.includes(\"=\")) {\n    return {\n      reason:\n        \"Codex does not split a command that starts with a variable assignment into words\",\n    };\n  }\n  return { words };\n}\n\n/** The tighter of two command decisions: forbidden over prompt. */\nfunction strictestDecision(\n  a: CodexCommandDecision | undefined,\n  b: CodexCommandDecision,\n): CodexCommandDecision {\n  return a === \"forbidden\" || b === \"forbidden\" ? \"forbidden\" : \"prompt\";\n}\n\n/**\n * Turn rules into Codex restrictions. A `deny` or `ask` rule Codex cannot enforce is recorded in `unsupported` rather than dropped. An `allow` rule that cannot be represented is left out, which can only make the result stricter; one carrying a condition is left out too, since applying it unconditionally would widen it. `writesBlockedBySandbox` says the output already carries a read-only sandbox, which covers a tool-wide write or edit deny.\n */\nfunction codexRestrictions(\n  rules: readonly Rule[],\n  profile: string | undefined,\n  writesBlockedBySandbox: boolean,\n  commandScope: CommandRuleScope,\n  unsupported: UnsupportedRule[],\n): CodexRestrictions {\n  const restrictions: CodexRestrictions = {\n    absolute: {},\n    workspace: {},\n    domains: {},\n    commands: {},\n  };\n  for (const rule of rules) {\n    if (rule.tier === \"allow\") {\n      if (\n        rule.when === undefined &&\n        rule.tool === \"WebFetch\" &&\n        rule.pattern?.startsWith(DOMAIN_PREFIX)\n      ) {\n        const domain = rule.pattern.slice(DOMAIN_PREFIX.length);\n        restrictions.domains[domain] = strictestDomain(\n          restrictions.domains[domain],\n          \"allow\",\n        );\n      }\n      continue;\n    }\n    const refuse = (reason: string): void => {\n      unsupported.push({\n        rule,\n        reason:\n          profile === undefined\n            ? reason\n            : `${reason} (in profile \"${profile}\")`,\n      });\n    };\n    const reason = codexRefusal(rule, writesBlockedBySandbox, commandScope);\n    if (reason !== undefined) {\n      refuse(reason);\n      continue;\n    }\n    if (rule.tool === \"Bash\" && rule.pattern !== undefined) {\n      const prefix = codexCommandPrefix(rule.pattern);\n      if (\"reason\" in prefix) {\n        refuse(prefix.reason);\n        continue;\n      }\n      const key = prefix.words.join(\" \");\n      restrictions.commands[key] = {\n        words: prefix.words,\n        decision: strictestDecision(\n          restrictions.commands[key]?.decision,\n          rule.tier === \"deny\" ? \"forbidden\" : \"prompt\",\n        ),\n      };\n    } else if (rule.tool === \"WebFetch\" && rule.pattern !== undefined) {\n      const domain = rule.pattern.slice(DOMAIN_PREFIX.length);\n      restrictions.domains[domain] = \"deny\";\n    } else if (rule.pattern === undefined) {\n      // A tool-wide write or edit deny, already carried by the read-only sandbox\n    } else {\n      const location = codexPathLocation(rule.pattern);\n      if (location.kind === \"refused\") {\n        refuse(location.reason);\n        continue;\n      }\n      const table =\n        location.kind === \"absolute\"\n          ? restrictions.absolute\n          : restrictions.workspace;\n      table[location.path] = strictestAccess(\n        table[location.path],\n        rule.tool === \"Read\" ? \"deny\" : \"read\",\n      );\n    }\n  }\n  return restrictions;\n}\n\n/** The tighter of two restrictions on one path: deny over read. */\nfunction strictestAccess(\n  a: CodexRestriction | undefined,\n  b: CodexRestriction,\n): CodexRestriction {\n  return a === \"deny\" || b === \"deny\" ? \"deny\" : \"read\";\n}\n\n/** The tighter of two domain actions: deny over allow. */\nfunction strictestDomain(\n  a: \"allow\" | \"deny\" | undefined,\n  b: \"allow\" | \"deny\",\n): \"allow\" | \"deny\" {\n  return a === \"deny\" || b === \"deny\" ? \"deny\" : \"allow\";\n}\n\nfunction mergeAccess(\n  a: Record<string, CodexRestriction>,\n  b: Record<string, CodexRestriction>,\n): Record<string, CodexRestriction> {\n  const merged = { ...a };\n  for (const [path, access] of Object.entries(b)) {\n    merged[path] = strictestAccess(merged[path], access);\n  }\n  return merged;\n}\n\nfunction mergeDomains(\n  a: Record<string, \"allow\" | \"deny\">,\n  b: Record<string, \"allow\" | \"deny\">,\n): Record<string, \"allow\" | \"deny\"> {\n  const merged = { ...a };\n  for (const [domain, action] of Object.entries(b)) {\n    merged[domain] = strictestDomain(merged[domain], action);\n  }\n  return merged;\n}\n\n/** Whether `ancestor` is a strict ancestor of `path` in one filesystem table, where `.` and `/` are roots. */\nfunction isAncestorPath(ancestor: string, path: string): boolean {\n  if (ancestor === path) return false;\n  if (ancestor === \".\" || ancestor === \"/\") return true;\n  return path.startsWith(`${ancestor}/`);\n}\n\n/**\n * The table with each path at least as strict as every ancestor in it. Codex lets the more specific of two entries win, so a nested `read` under a `deny` would reopen part of a subtree the rules deny.\n */\nfunction inheritAncestors(\n  table: Record<string, CodexRestriction>,\n): Record<string, CodexRestriction> {\n  return Object.fromEntries(\n    Object.entries(table).map(([path, access]) => [\n      path,\n      Object.entries(table).reduce(\n        (strictest, [ancestor, inherited]) =>\n          isAncestorPath(ancestor, path)\n            ? strictestAccess(strictest, inherited)\n            : strictest,\n        access,\n      ),\n    ]),\n  );\n}\n\n/** A Codex profile for the restrictions, with no empty sections. */\nfunction codexProfileOf(restrictions: CodexRestrictions): CodexProfile {\n  const profile: CodexProfile = {};\n  const filesystem: Record<string, CodexFilesystemEntry> = inheritAncestors(\n    restrictions.absolute,\n  );\n  if (Object.keys(restrictions.workspace).length > 0) {\n    filesystem[WORKSPACE_ROOTS] = inheritAncestors(restrictions.workspace);\n  }\n  if (Object.keys(filesystem).length > 0) {\n    profile.filesystem = filesystem;\n  }\n  if (Object.keys(restrictions.domains).length > 0) {\n    profile.network = { domains: restrictions.domains };\n  }\n  return profile;\n}\n\n/**\n * Encode a canonical policy for Codex: the config object and the execpolicy prefix rules for its command rules, which only the `rules-file` scope collects.\n *\n * @throws UnsupportedCapabilityError listing every restrictive rule Codex cannot enforce exactly.\n */\nfunction codexEncoding(\n  canonical: AgentPermissionPolicy,\n  commandScope: \"config-only\" | \"rules-file\",\n): { config: Partial<CodexNative>; commands: CodexCommandRule[] } {\n  const result: Partial<CodexNative> = {};\n\n  // --- defaultMode → approval_policy ---\n  if (canonical.defaultMode) {\n    result.approval_policy = modeToCodexApproval(canonical.defaultMode);\n  }\n\n  // --- sandbox → sandbox_mode + sandbox_workspace_write ---\n  if (canonical.sandbox) {\n    if (canonical.sandbox.mode) {\n      result.sandbox_mode = canonicalSandboxToCodex(canonical.sandbox.mode);\n    }\n    if (\n      canonical.sandbox.writableRoots?.length ||\n      canonical.sandbox.networkAccess !== undefined\n    ) {\n      const sw: Partial<CodexSandboxWorkspaceWrite> = {};\n      if (canonical.sandbox.writableRoots?.length) {\n        sw.writable_roots = canonical.sandbox.writableRoots;\n      }\n      if (canonical.sandbox.networkAccess !== undefined) {\n        sw.network_access = canonical.sandbox.networkAccess;\n      }\n      result.sandbox_workspace_write = sw;\n    }\n  } else if (canonical.defaultMode) {\n    // Derive sandbox_mode from defaultMode if no explicit sandbox\n    if (mapMode(canonical.defaultMode) === \"readonly\") {\n      result.sandbox_mode = \"read-only\";\n    } else if (\n      canonical.defaultMode === \"autonomous\" ||\n      canonical.defaultMode === \"bypassPermissions\"\n    ) {\n      result.sandbox_mode = \"danger-full-access\";\n    } else {\n      result.sandbox_mode = \"workspace-write\";\n    }\n  }\n\n  // --- additionalDirectories → writable_roots ---\n  if (\n    canonical.permissions?.additionalDirectories?.length &&\n    !result.sandbox_workspace_write\n  ) {\n    result.sandbox_workspace_write = {\n      writable_roots: canonical.permissions.additionalDirectories,\n    };\n  }\n\n  // --- Rules: represent every restrictive rule exactly, or refuse the conversion ---\n  const unsupported: UnsupportedRule[] = [];\n  const writesBlockedBySandbox = result.sandbox_mode === \"read-only\";\n  const topLevel = codexRestrictions(\n    collectRules(canonical),\n    undefined,\n    writesBlockedBySandbox,\n    commandScope,\n    unsupported,\n  );\n  if (canonical.network?.domains) {\n    for (const [domain, action] of Object.entries(canonical.network.domains)) {\n      topLevel.domains[domain] = strictestDomain(\n        topLevel.domains[domain],\n        action,\n      );\n    }\n  }\n\n  // --- profiles → named Codex profiles, each carrying the top-level restrictions ---\n  const profiles: Record<string, CodexProfile> = {};\n  for (const [name, profileTiers] of Object.entries(\n    resolveProfiles(canonical.profiles),\n  )) {\n    const own = codexRestrictions(\n      collectRules({ permissions: profileTiers }),\n      name,\n      writesBlockedBySandbox,\n      commandScope === \"config-only\" ? \"config-only\" : \"profile\",\n      unsupported,\n    );\n    profiles[name] = codexProfileOf({\n      absolute: mergeAccess(topLevel.absolute, own.absolute),\n      workspace: mergeAccess(topLevel.workspace, own.workspace),\n      domains: mergeDomains(topLevel.domains, own.domains),\n      commands: {},\n    });\n  }\n\n  if (unsupported.length > 0) {\n    throw new UnsupportedCapabilityError(\"codex\", unsupported);\n  }\n\n  if (Object.keys(profiles).length > 0) {\n    const named = Object.fromEntries(\n      Object.entries(profiles).filter(\n        ([, profile]) => Object.keys(profile).length > 0,\n      ),\n    );\n    if (Object.keys(named).length > 0) {\n      result.permissions = named;\n      if (canonical.activeProfile) {\n        result.default_permissions = canonical.activeProfile;\n      }\n    }\n  } else {\n    // No named profiles: one \"default\" profile holds the top-level restrictions\n    const profile = codexProfileOf(topLevel);\n    if (Object.keys(profile).length > 0) {\n      result.permissions = { default: profile };\n      result.default_permissions = \"default\";\n    }\n  }\n\n  return { config: result, commands: Object.values(topLevel.commands) };\n}\n\nexport const codexCodec = z.codec(codexNative, AgentPermissionPolicy, {\n  decode(native) {\n    const rules: Rule[] = [];\n    const networkDomains: Record<string, \"allow\" | \"deny\"> = {};\n    const namedProfiles: Record<string, Partial<PermissionTiers>> = {};\n\n    // --- approval_policy → defaultMode ---\n    let defaultMode: AgentPermissionPolicy[\"defaultMode\"] | undefined;\n    if (native.approval_policy) {\n      defaultMode = codexApprovalToMode(native.approval_policy);\n    }\n\n    // --- sandbox_mode → sandbox.mode ---\n    let sandbox: Partial<Sandbox> | undefined;\n    if (native.sandbox_mode) {\n      sandbox = { mode: codexSandboxToCanonical(native.sandbox_mode) };\n    }\n\n    // --- sandbox_workspace_write → sandbox fields ---\n    if (native.sandbox_workspace_write) {\n      sandbox ??= {};\n      if (native.sandbox_workspace_write.writable_roots?.length) {\n        sandbox.writableRoots = native.sandbox_workspace_write.writable_roots;\n      }\n      if (native.sandbox_workspace_write.network_access !== undefined) {\n        sandbox.networkAccess = native.sandbox_workspace_write.network_access;\n      }\n    }\n\n    // --- sandbox_mode \"read-only\" override ---\n    if (native.sandbox_mode === \"read-only\") {\n      defaultMode = \"readonly\";\n      rules.push(\n        { tool: \"Write\", tier: \"deny\" },\n        { tool: \"Edit\", tier: \"deny\" },\n      );\n    } else if (native.sandbox_mode === \"danger-full-access\") {\n      if (!native.approval_policy) defaultMode = \"autonomous\";\n    }\n\n    // --- Named permission profiles ---\n    const allProfiles = native.permissions ?? {};\n    const activeProfileName = native.default_permissions;\n\n    for (const [name, profile] of Object.entries(allProfiles)) {\n      const profileRules: Rule[] = [];\n\n      if (profile.filesystem) {\n        codexFilesystemToRules(profile.filesystem, profileRules);\n      }\n\n      if (profile.network?.domains) {\n        for (const [domain, action] of Object.entries(\n          profile.network.domains,\n        )) {\n          profileRules.push({\n            tool: \"WebFetch\",\n            pattern: `domain:${domain}`,\n            tier: action === \"allow\" ? \"allow\" : \"deny\",\n          });\n        }\n      }\n\n      // If this is the active profile, contribute to top-level rules\n      if (!activeProfileName || name === activeProfileName) {\n        rules.push(...profileRules);\n\n        if (profile.network?.domains) {\n          Object.assign(networkDomains, profile.network.domains);\n        }\n      }\n\n      // Store as named profile (using string arrays for compat)\n      if (profileRules.length > 0) {\n        namedProfiles[name] = {\n          deny: profileRules.filter((r) => r.tier === \"deny\").map(ruleToString),\n          allow: profileRules\n            .filter((r) => r.tier === \"allow\")\n            .map(ruleToString),\n        };\n      }\n    }\n\n    // Build result\n    const result: Partial<AgentPermissionPolicy> = {};\n    if (defaultMode !== undefined) result.defaultMode = defaultMode;\n    if (sandbox) result.sandbox = sandbox;\n    if (rules.length > 0) result.rules = rules;\n\n    if (Object.keys(namedProfiles).length > 0) {\n      result.profiles = namedProfiles;\n      if (activeProfileName) result.activeProfile = activeProfileName;\n    }\n\n    if (Object.keys(networkDomains).length > 0) {\n      result.network = { domains: networkDomains };\n    }\n\n    return result;\n  },\n  encode(canonical) {\n    return codexEncoding(canonical, \"config-only\").config;\n  },\n});\n\n/**\n * Where the execpolicy rules file goes, relative to the directory holding Codex's config. Codex loads every `*.rules` file in the `rules` directory of each config layer (`~/.codex/rules`, a project's `.codex/rules`).\n */\nexport const CODEX_EXECPOLICY_RULES_PATH = \"rules/agent-perms.rules\";\n\n/**\n * A canonical policy encoded for Codex: the config object, and the content of an execpolicy rules file when the policy has command rules.\n */\nexport interface CodexEncoding {\n  config: z.input<typeof codexNative>;\n  /** Starlark `prefix_rule` calls for {@link CODEX_EXECPOLICY_RULES_PATH}, or `undefined` when there are none. */\n  rules: string | undefined;\n}\n\n/**\n * Encode a canonical policy for Codex, writing its top-level command `deny` and `ask` rules as execpolicy prefix rules (`forbidden` and `prompt`) instead of refusing them. Only a `prefix:*` pattern, or one whose sole wildcard is a trailing ` *`, made of plain words, is written; a command `allow` is left out, which is stricter.\n *\n * @throws UnsupportedCapabilityError listing every restrictive rule Codex cannot enforce exactly, including a command rule in a named profile, since a rules file applies to every profile.\n */\nexport function encodeCodex(canonical: AgentPermissionPolicy): CodexEncoding {\n  const { config, commands } = codexEncoding(canonical, \"rules-file\");\n  if (commands.length === 0) return { config, rules: undefined };\n  const lines = commands.map(\n    ({ words, decision }) =>\n      `prefix_rule(pattern = [${words.map((word) => JSON.stringify(word)).join(\", \")}], decision = \"${decision}\")\\n`,\n  );\n  return {\n    config,\n    rules: `# Generated by agent-perms from a canonical permission policy.\\n${lines.join(\"\")}`,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Oh My Pi (OMP) codec\n// ---------------------------------------------------------------------------\n// OMP keeps an ordered list of `bash.patterns` in its config.yml (global at ~/.omp/agent, and per\n// project). Each entry is `{ match, approval }` with approval allow, prompt or deny.\n//\n// How OMP evaluates it (its bash tool, checked against its source):\n//   - `match` is a glob where only `*` is special (it matches any run of characters); everything\n//     else is literal, and there is no way to write a literal asterisk. Whitespace is collapsed in\n//     the pattern and the command, and the match is anchored to the whole command.\n//   - The first matching entry wins, in list order.\n//   - deny and prompt entries apply to the whole command or to any one segment of a compound\n//     command; an allow entry applies to a simple command only.\n//\n// Canonical rules use the strictest matching tier whatever their order, so the codec writes deny entries first, then prompt, then allow. Only rules for the bash tool are converted.\n//\n// OMP's `tools.approvalMode` decides calls no rule covers, by the tier each tool declares (read, write or exec): `always-ask` approves read and prompts for write and exec, `write` prompts for exec only, and `yolo`, its default, approves every tier. No mode prompts for a read and none denies, so a canonical mode that asks is written as `always-ask`, which leaves reads approved (the one gap), and `readonly` has no equivalent and is refused. A `bash.patterns` allow still wins under `always-ask`, as it does under a canonical mode that asks.\n\nconst OMP_APPROVALS = [\"allow\", \"prompt\", \"deny\"] as const;\nconst OmpPatternEntry = z.object({\n  match: z.string(),\n  approval: z.enum(OMP_APPROVALS),\n});\n\n/**\n * What encoding writes into an OMP config: its only keys a conversion or a sync changes, so\n * everything else in the file can be left as it is.\n */\nexport const OmpEncoded = z.object({\n  bash: z.object({ patterns: z.array(OmpPatternEntry) }).optional(),\n  tools: z.object({ approvalMode: z.literal(\"always-ask\") }).optional(),\n});\nexport type OmpEncoded = z.infer<typeof OmpEncoded>;\n\n/** OMP's approval modes, from the least to the most permissive. */\nexport const OMP_APPROVAL_MODES = [\"always-ask\", \"write\", \"yolo\"] as const;\n\nconst ompNative = z.looseObject({\n  bash: z.looseObject({ patterns: z.array(z.unknown()).optional() }).optional(),\n  tools: z\n    .looseObject({ approvalMode: z.enum(OMP_APPROVAL_MODES).optional() })\n    .optional(),\n});\n\n/**\n * OMP approval mode to canonical mode, never looser than OMP: `write` approves writes without asking, which no canonical mode short of `autonomous` does, so it is read as `standard` like `always-ask`.\n */\nconst ompModeToCanonical = {\n  \"always-ask\": \"standard\",\n  write: \"standard\",\n  yolo: \"autonomous\",\n} as const;\n\n/**\n * The OMP approval mode for a canonical mode, none when OMP's own mode is left alone, or the\n * refusal when OMP cannot enforce it. Aliases are read as the evaluator reads them.\n */\nfunction ompApprovalMode(\n  mode: PermissionMode,\n): { mode?: \"always-ask\" } | { refused: UnsupportedSetting } {\n  switch (mapMode(mode)) {\n    case \"autonomous\":\n      return {};\n    case \"readonly\":\n      return {\n        refused: {\n          setting: \"defaultMode\",\n          value: mode,\n          reason:\n            \"OMP has no mode that denies calls no rule covers, and none that prompts for a read\",\n        },\n      };\n    default:\n      return { mode: \"always-ask\" };\n  }\n}\n\nconst ompApprovalToTier = {\n  allow: \"allow\",\n  prompt: \"ask\",\n  deny: \"deny\",\n} as const;\n\nconst tierToOmpApproval = {\n  allow: \"allow\",\n  ask: \"prompt\",\n  deny: \"deny\",\n} as const;\n\n/** OMP collapses whitespace in patterns and commands before matching. */\nfunction normaliseOmpText(text: string): string {\n  return text.trim().replace(/\\s+/gu, \" \");\n}\n\n/**\n * The OMP `match` globs that together match what a canonical pattern matches, or the reason OMP\n * cannot express it. A canonical prefix or trailing-wildcard pattern also matches the bare command,\n * so it is written twice: OMP's `git *` does not match `git`.\n */\nfunction ompMatches(\n  pattern: string | undefined,\n): { matches: string[] } | { reason: string } {\n  if (pattern === undefined) return { matches: [\"*\"] };\n\n  const parsed = parseRulePattern(pattern);\n  const literalStar = {\n    reason: \"OMP has no way to match a literal asterisk\",\n  };\n  switch (parsed.type) {\n    case \"exact\":\n      return parsed.content.includes(\"*\")\n        ? literalStar\n        : { matches: [parsed.content] };\n    case \"prefix\":\n      return parsed.prefix.includes(\"*\")\n        ? literalStar\n        : { matches: [parsed.prefix, `${parsed.prefix} *`] };\n    case \"wildcard\": {\n      let glob = \"\";\n      let stars = 0;\n      const text = parsed.pattern;\n      for (let i = 0; i < text.length; i++) {\n        const c = text.charAt(i);\n        const next = text.charAt(i + 1);\n        if (c === \"\\\\\" && next === \"*\") return literalStar;\n        if (c === \"\\\\\" && (next === \"\\\\\" || next === \"(\" || next === \")\")) {\n          glob += next;\n          i += 1;\n        } else {\n          if (c === \"*\") stars += 1;\n          glob += c;\n        }\n      }\n      return glob.endsWith(\" *\") && stars === 1\n        ? { matches: [glob.slice(0, -2), glob] }\n        : { matches: [glob] };\n    }\n  }\n}\n\n/**\n * Canonical policy to OMP `bash.patterns`. A deny or ask that OMP cannot enforce as written is\n * refused; an allow it cannot express is left out, which is stricter.\n *\n * @throws UnsupportedCapabilityError listing the rules OMP cannot enforce.\n */\nfunction encodeOmp(canonical: AgentPermissionPolicy): OmpEncoded {\n  const unsupported: UnsupportedRule[] = [];\n  const settings: UnsupportedSetting[] = [];\n  const defaultMode =\n    canonical.defaultMode ?? canonical.permissions?.defaultMode;\n  const approvalMode =\n    defaultMode === undefined ? {} : ompApprovalMode(defaultMode);\n  if (\"refused\" in approvalMode) settings.push(approvalMode.refused);\n  const byApproval: Record<\"deny\" | \"prompt\" | \"allow\", string[]> = {\n    deny: [],\n    prompt: [],\n    allow: [],\n  };\n\n  for (const rule of agentRules(canonical, \"omp\")) {\n    const approval = tierToOmpApproval[rule.tier];\n    let reason: string | undefined;\n    let matches: string[] = [];\n\n    if (rule.tool.toLowerCase() !== \"bash\") {\n      reason = \"OMP applies bash.patterns to the bash tool only\";\n    } else if (rule.when !== undefined) {\n      reason = \"OMP cannot limit a rule with a condition\";\n    } else {\n      const converted = ompMatches(rule.pattern);\n      if (\"reason\" in converted) reason = converted.reason;\n      else matches = converted.matches.map(normaliseOmpText);\n      if (matches.some((match) => match === \"\")) {\n        reason = \"OMP ignores an empty pattern\";\n      }\n    }\n\n    if (reason !== undefined) {\n      if (rule.tier !== \"allow\") unsupported.push({ rule, reason });\n      continue;\n    }\n    for (const match of matches) {\n      if (!byApproval[approval].includes(match)) {\n        byApproval[approval].push(match);\n      }\n    }\n  }\n\n  if (unsupported.length > 0 || settings.length > 0) {\n    throw new UnsupportedCapabilityError(\"omp\", unsupported, settings);\n  }\n\n  // OMP takes the first matching entry, so the strictest tier goes first.\n  const patterns = ([\"deny\", \"prompt\", \"allow\"] as const).flatMap((approval) =>\n    byApproval[approval].map((match) => ({ match, approval })),\n  );\n  return {\n    ...(patterns.length > 0 && { bash: { patterns } }),\n    ...(\"mode\" in approvalMode && {\n      tools: { approvalMode: approvalMode.mode },\n    }),\n  };\n}\n\n/**\n * OMP `bash.patterns` to canonical rules, in the order written. OMP takes the first match while a\n * canonical policy takes the strictest, so a broad allow written before a narrow deny is read as\n * the deny winning: never looser than OMP. An entry that cannot be read faithfully is an error, not\n * skipped, since skipping a deny would loosen the policy.\n */\nfunction decodeOmp(native: z.infer<typeof ompNative>): AgentPermissionPolicy {\n  const rules: Rule[] = [];\n  for (const [index, raw] of (native.bash?.patterns ?? []).entries()) {\n    const entry = OmpPatternEntry.parse(raw);\n    const match = normaliseOmpText(entry.match);\n    if (match === \"\") {\n      throw new Error(`bash.patterns[${String(index)}] has an empty match`);\n    }\n    if (match.endsWith(\":*\")) {\n      throw new Error(\n        `bash.patterns[${String(index)}] ends in \":*\", which the canonical pattern dialect reads as a prefix rule and OMP as a literal colon`,\n      );\n    }\n    rules.push({\n      tool: \"Bash\",\n      pattern: match.replace(/\\\\/gu, \"\\\\\\\\\"),\n      tier: ompApprovalToTier[entry.approval],\n    });\n  }\n  const approvalMode = native.tools?.approvalMode;\n  return {\n    ...(approvalMode !== undefined && {\n      defaultMode: ompModeToCanonical[approvalMode],\n    }),\n    ...(rules.length > 0 && { rules }),\n  };\n}\n\nexport const ompCodec = z.codec(ompNative, AgentPermissionPolicy, {\n  decode: decodeOmp,\n  encode: encodeOmp,\n});\n\n// ---------------------------------------------------------------------------\n// Codec registry\n// ---------------------------------------------------------------------------\n\nexport const CODECS = {\n  \"claude-code\": claudeCodeCodec,\n  codex: codexCodec,\n  kiro: kiroCodec,\n  opencode: opencodeCodec,\n  crush: crushCodec,\n  omp: ompCodec,\n} as const;\n\nexport type Codecs = typeof CODECS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAS,WACP,QACA,OACQ;CACR,MAAM,cAAiC,CAAC;CACxC,MAAM,OAAO,aAAa,MAAM,CAAC,CAAC,QAAQ,SAAS;EACjD,IAAI,KAAK,cAAc,QAAW;GAChC,YAAY,KAAK;IACf;IACA,QAAQ,GAAG,MAAM;GACnB,CAAC;GACD,OAAO;EACT;EACA,IAAI,KAAK,MAAM,UAAU,UAAa,KAAK,MAAM,SAAS,QAGxD,OAAO,KAAK,SAAS,UAAa,KAAK,SAAS;EAElD,IAAI,KAAK,SAAS,SAChB,YAAY,KAAK;GACf;GACA,QAAQ,GAAG,MAAM;EACnB,CAAC;EAEH,OAAO;CACT,CAAC;CACD,IAAI,YAAY,SAAS,GACvB,MAAM,IAAI,2BAA2B,OAAO,WAAW;CAEzD,OAAO;AACT;AAMA,MAAa,UAAU,EAAE,KAAK;CAC5B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAiBD,MAAM,yBAAyE;CAC7E,UAAU;CACV,YAAY;CACZ,UAAU;AACZ;AAEA,MAAM,mBAAmB,EACtB,OAAO;CACN,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CACpC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CACnC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CAClC,aAAa,yBAAyB,SAAS;CAC/C,uBAAuB,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;AACtD,CAAC,CAAC,CACD,QAAQ,CAAC,CACT,OAAO;AAIV,MAAa,kBAAkB,EAAE,MAC/B,kBACA,uBACA;CACE,OAAO,QAAQ;EACb,MAAM,QAA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