{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "use-approval-policy",
  "title": "useApprovalPolicy",
  "author": "Diogo Esteves <https://github.com/dgesteves>",
  "description": "Approval rules without markup: once, session or always, by tool and argument glob, deny winning; pluggable storage, an audit trail, and the same rules as AI SDK 7 toolApproval.",
  "dependencies": [],
  "files": [
    {
      "path": "packages/signoff-ui/src/use-approval-policy.ts",
      "content": "'use client';\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport {\n  decisionEffect,\n  evaluateRules,\n  ruleFromDecision,\n  toPlainRules,\n  type ApprovalDecision,\n  type ApprovalRequest,\n  type ApprovalRule,\n  type RuleMatch,\n} from './lib/policy';\nimport { approvalPolicyLabels, type SignoffLabelsInput } from './lib/labels';\nimport { useLabels } from './labels';\n\n/** The labels' sections this module reads. */\nconst LABELS = { approvalPolicy: approvalPolicyLabels };\n\nexport type { ApprovalDecision, ApprovalRequest, ApprovalRule, RuleMatch } from './lib/policy';\n\n/**\n * Where `always` rules are kept between visits. Session rules are never saved, and nor is a rule\n * with a `when`: `when` is code, and without it the rule would cover more calls than it does.\n */\nexport interface ApprovalRuleStorage {\n  /** The saved rules, read once, after the first render. It may return a promise. */\n  load(): readonly ApprovalRule[] | PromiseLike<readonly ApprovalRule[]>;\n  /**\n   * Keep these rules, in place of the ones saved before: the `always` rules without a `when`, after\n   * each change. It may return a promise, which nothing waits for.\n   */\n  save(rules: readonly ApprovalRule[]): void | PromiseLike<void>;\n  /**\n   * The ids of `always` default rules the person removed, so they stay removed on the next load.\n   * Optional: without this and `saveRemovedDefaults`, a removed default comes back on each load.\n   */\n  loadRemovedDefaults?(): readonly string[] | PromiseLike<readonly string[]>;\n  /**\n   * Keep the ids of the `always` defaults the person removed, after a change to them. Optional, with\n   * `loadRemovedDefaults`.\n   */\n  saveRemovedDefaults?(ids: readonly string[]): void | PromiseLike<void>;\n}\n\n/** Rules kept in memory, for this page only: the default. */\nexport function memoryRuleStorage(initial: readonly ApprovalRule[] = []): ApprovalRuleStorage {\n  let rules = [...initial];\n  let removed: string[] = [];\n  return {\n    load: () => rules,\n    save: (next) => {\n      rules = [...next];\n    },\n    loadRemovedDefaults: () => removed,\n    saveRemovedDefaults: (ids) => {\n      removed = [...ids];\n    },\n  };\n}\n\n/**\n * Rules kept in `localStorage` (or another `Storage`) as JSON under `key`, and the ids of default\n * rules the person removed under `<key>:removed-defaults`. A rule with a `when` is not kept: JSON\n * can't hold the code. Nothing is read or written on the server.\n */\nexport function webStorageRules(\n  key = 'signoff-ui:approval-rules',\n  storage: () => Storage | undefined = () => (typeof window === 'undefined' ? undefined : window.localStorage),\n): ApprovalRuleStorage {\n  const read = (name: string): unknown[] => {\n    try {\n      const text = storage()?.getItem(name);\n      const parsed: unknown = text ? JSON.parse(text) : [];\n      return Array.isArray(parsed) ? parsed : [];\n    } catch {\n      return [];\n    }\n  };\n  const write = (name: string, value: unknown) => {\n    try {\n      storage()?.setItem(name, JSON.stringify(value));\n    } catch {\n      // Full or blocked storage: the rules still hold for this page.\n    }\n  };\n  const removedKey = `${key}:removed-defaults`;\n  return {\n    load: () => read(key).filter(isRule),\n    // Not a rule with a `when`: JSON would keep it without the `when`, covering more calls.\n    save: (rules) =>\n      write(\n        key,\n        rules.filter((rule) => !rule.when),\n      ),\n    loadRemovedDefaults: () => read(removedKey).filter((id): id is string => typeof id === 'string'),\n    saveRemovedDefaults: (ids) => write(removedKey, ids),\n  };\n}\n\nfunction isRule(value: unknown): value is ApprovalRule {\n  if (!value || typeof value !== 'object') return false;\n  const rule = value as Partial<ApprovalRule>;\n  return (\n    typeof rule.id === 'string' &&\n    typeof rule.tool === 'string' &&\n    (rule.effect === 'allow' || rule.effect === 'deny') &&\n    (rule.scope === 'session' || rule.scope === 'always') &&\n    (rule.args === undefined ||\n      (!!rule.args &&\n        typeof rule.args === 'object' &&\n        !Array.isArray(rule.args) &&\n        Object.values(rule.args).every((v) => typeof v === 'string')))\n  );\n}\n\n/** Everything the policy did, for an audit trail. */\nexport type ApprovalAuditEvent =\n  | {\n      type: 'decision';\n      at: number;\n      request: ApprovalRequest;\n      decision: ApprovalDecision;\n      /** A person decided, or one of the rules did. */\n      by: 'user' | 'rule';\n      /** The rule that decided, or the one this decision made. */\n      rule?: ApprovalRule | undefined;\n      reason?: string | undefined;\n      /** The arguments as approved, when the person edited them. */\n      input?: unknown;\n    }\n  | { type: 'rule-added' | 'rule-removed'; at: number; rule: ApprovalRule }\n  | { type: 'session-cleared'; at: number; rules: ApprovalRule[] };\n\n/** A decision, ready to send: `approved` and `reason` for the agent, the rest for your app. */\nexport interface ApprovalOutcome {\n  /** The request's `id`: the approval this answers. */\n  id: string;\n  /** Whether the call may run. */\n  approved: boolean;\n  /**\n   * Why, for the agent: the reason the person gave, or for a deny rule its own `reason`, else\n   * `labels.approvalPolicy.ruleDenial`.\n   */\n  reason?: string | undefined;\n  /** The arguments to run with, when the person edited them. */\n  input?: unknown;\n  /**\n   * What was decided, and for how long. A rule's answer is `allow-session` or `allow-always`, after\n   * the rule's scope, or `deny-always`.\n   */\n  decision: ApprovalDecision;\n  /** Who decided: the person (`user`) or one of the rules (`rule`). */\n  by: 'user' | 'rule';\n  /** The rule that decided, or the one the person's session or always decision made. */\n  rule?: ApprovalRule | undefined;\n}\n\n/** What `useApprovalPolicy` takes: the rules, where they are kept, and what to call as they change. */\nexport interface UseApprovalPolicyOptions {\n  /**\n   * Controlled rules: the policy decides with these, and hands every change to `onRulesChange` for\n   * you to pass back. Without them, it keeps its own.\n   */\n  rules?: readonly ApprovalRule[] | undefined;\n  /**\n   * Rules to start with, before any the storage loads. An `always` default the person removes stays\n   * removed on later loads, with a storage that keeps removed defaults (`webStorageRules` and\n   * `memoryRuleStorage` do). A default you add later appears, removed ones aside.\n   * @default []\n   */\n  defaultRules?: readonly ApprovalRule[] | undefined;\n  /**\n   * The rules after each change: a session or always decision, `addRule`, `removeRule` or\n   * `clearSession`, not the storage loading. With `rules`, set them from it.\n   */\n  onRulesChange?: ((rules: ApprovalRule[]) => void) | undefined;\n  /** Where `always` rules are loaded from and saved to. Default: memory, for this page. */\n  storage?: ApprovalRuleStorage | undefined;\n  /** Every decision, rule added or removed, and session cleared, as it happens. */\n  onAudit?: ((event: ApprovalAuditEvent) => void) | undefined;\n  /**\n   * Words to use instead of the English defaults: the reason a deny rule without one of its own\n   * sends (`labels.approvalPolicy.ruleDenial`). See `SignoffLabelsProvider`.\n   */\n  labels?: SignoffLabelsInput | undefined;\n}\n\n/**\n * What `useApprovalPolicy` returns: the rules, and what records a decision or answers a call from\n * them. Pass it to `ToolApprovalCard`, `AgentMessage` or `ToolApprovalBatch` as their policy.\n */\nexport interface ApprovalPolicy {\n  /**\n   * The rules as of this render: `rules` when you control them, else the defaults, the rules the\n   * storage loaded and the ones added since.\n   */\n  rules: readonly ApprovalRule[];\n  /**\n   * The rules as they are now, as plain data to send with a request (see `toPlainRules`: a rule\n   * with a `when` stays on the page, and a deny one keeps back the allow rules it would overrule,\n   * so the server asks about those calls). The same function for the policy's life, so a transport\n   * made once can call it in `body`, and it has a rule a decision just made before the page re-renders.\n   */\n  getRules(): ApprovalRule[];\n  /** The storage has loaded: after the first render, or once an async storage's promise settles. */\n  ready: boolean;\n  /** The rule that decides a call, if one does. */\n  match(toolName: string, input: unknown): RuleMatch | undefined;\n  /**\n   * Record a person's decision and the rule it leaves (for session and always decisions, over the\n   * call's `args` when given, else every call of the tool), and return it ready to send.\n   */\n  decide(\n    request: ApprovalRequest,\n    decision: ApprovalDecision,\n    options?: { reason?: string | undefined; input?: unknown; args?: Record<string, string> | undefined },\n  ): ApprovalOutcome;\n  /**\n   * Answer a request from the rules, if one matches, recorded as decided by that rule. A request it\n   * answered before, or a person decided, gets the same outcome while its tool and input are the\n   * ones answered (or the edit the person approved); another call with that id is decided again.\n   */\n  answer(request: ApprovalRequest): ApprovalOutcome | undefined;\n  /** How an answered request was decided, by its id: by a person or by which rule. */\n  outcomeOf(id: string): ApprovalOutcome | undefined;\n  /**\n   * Add a rule, in place of one with the same id, and save it if it is an `always` rule without a\n   * `when`. A removed default's id brings that default back, as a \"Reset\" button would.\n   */\n  addRule(rule: ApprovalRule): void;\n  /**\n   * Remove the rule with this id. An `always` default stays removed on later loads, with a storage\n   * that keeps removed defaults.\n   */\n  removeRule(id: string): void;\n  /** Forget the session rules. */\n  clearSession(): void;\n}\n\n/**\n * Approval rules, held for the page: once, for the session or always, scoped by tool and by\n * argument patterns, deny winning over allow. Pass the policy to `ToolApprovalCard`, `AgentMessage`\n * or `ToolApprovalBatch`, and they offer the choices, answer what a rule already decides, and record\n * the rest. Persistence is pluggable: `always` rules go to `storage`, session rules stay in memory.\n */\nexport function useApprovalPolicy({\n  rules: rulesProp,\n  defaultRules = [],\n  onRulesChange,\n  storage: storageProp,\n  onAudit,\n  labels,\n}: UseApprovalPolicyOptions = {}): ApprovalPolicy {\n  const ruleDenial = useLabels(LABELS, labels).approvalPolicy.ruleDenial;\n  const [fallbackStorage] = useState(() => memoryRuleStorage());\n  const storage = storageProp ?? fallbackStorage;\n  // The storage is read after the first render, on the client: a server render and the hydrating\n  // client then agree, whatever is stored.\n  const [own, setOwn] = useState<readonly ApprovalRule[]>(defaultRules);\n  const [ready, setReady] = useState(false);\n  const rules = rulesProp ?? own;\n  // The latest rules for handlers that run before a re-render, such as two answers in one tick, or\n  // effects that run before this hook's own, as a child's do. Each change sets them as it happens, so\n  // a render never sets them back; rules passed in replace them when they change.\n  const latest = useRef(rules);\n  const controlled = useRef(rulesProp !== undefined);\n  useEffect(() => {\n    controlled.current = rulesProp !== undefined;\n    if (rulesProp !== undefined) latest.current = rulesProp;\n  }, [rulesProp]);\n  const outcomes = useRef(new Map<string, ApprovalOutcome>());\n  // The call each outcome answers, by id: its tool, and the input asked about and the one approved.\n  const calls = useRef(new Map<string, { toolName: string; inputs: unknown[] }>());\n  // The ids of `always` defaults the person removed, as last loaded or saved.\n  const removedDefaults = useRef<readonly string[]>([]);\n  // Until the storage has loaded, the rules changed meanwhile, by id (`undefined`: removed). Saving\n  // them then would replace the rules it holds, so they go over the rules it loads, and are saved\n  // with them.\n  const early = useRef<Map<string, ApprovalRule | undefined> | undefined>(new Map());\n  const flush = useRef(false);\n\n  const save = (next: readonly ApprovalRule[]) => {\n    // A rule with a `when` stays in memory: saved, it would load without it.\n    void storage.save(next.filter((r) => r.scope === 'always' && !r.when));\n    if (storage.saveRemovedDefaults) {\n      // An `always` default missing from the rules was removed; one that is back was restored.\n      const kept = new Set(next.map((r) => r.id));\n      const defaults = defaultRules.filter((r) => r.scope === 'always').map((r) => r.id);\n      const removed = [...new Set([...removedDefaults.current, ...defaults])].filter((id) => !kept.has(id));\n      if (removed.join('\\n') !== removedDefaults.current.join('\\n')) {\n        removedDefaults.current = removed;\n        void storage.saveRemovedDefaults(removed);\n      }\n    }\n  };\n\n  // Loaded once, from the storage the policy started with: an inline storage object (a new one on\n  // every render) does not reload it. Saves go to the current one.\n  const [loadFrom] = useState(storage);\n  useEffect(() => {\n    // Run again once it has loaded, as StrictMode does: loading again would put the saved rules back\n    // over the changes made before, and drop their save.\n    if (!early.current) return;\n    let live = true;\n    const apply = ([loaded, removed]: readonly [readonly ApprovalRule[], readonly string[]]) => {\n      if (!live) return;\n      removedDefaults.current = removed;\n      const changes = early.current ?? new Map<string, ApprovalRule | undefined>();\n      early.current = undefined;\n      flush.current = changes.size > 0;\n      // The defaults, less the ones the person removed, then the saved rules, which win, then the\n      // changes made before they loaded. In `latest` now: a change made in the effects of the render\n      // this causes, such as a child's waiting for `ready`, builds on them.\n      const gone = new Set(removed);\n      const current = latest.current;\n      const next = over(merge(gone.size ? current.filter((r) => !gone.has(r.id)) : current, loaded), changes);\n      if (!controlled.current) latest.current = next;\n      setOwn(next);\n      setReady(true);\n    };\n    const loaded = loadFrom.load();\n    const removed = loadFrom.loadRemovedDefaults?.() ?? [];\n    if (isThenable(loaded) || isThenable(removed)) {\n      // Removed defaults that fail to load leave the defaults as they are; the saved rules still load.\n      const removedOrNone = Promise.resolve(removed).then(undefined, () => []);\n      Promise.all([loaded, removedOrNone]).then(apply, () => apply([[], []]));\n    } else apply([loaded, removed]);\n    return () => {\n      live = false;\n    };\n  }, [loadFrom]);\n  // The changes made before the storage loaded, saved with the rules it loaded once they have\n  // rendered, to the storage of that render.\n  useEffect(() => {\n    if (!flush.current || !ready) return;\n    flush.current = false;\n    save(latest.current);\n  });\n\n  const audit = (event: ApprovalAuditEvent) => onAudit?.(event);\n  const setRules = (next: ApprovalRule[]) => {\n    const changes = early.current;\n    if (changes) {\n      const kept = new Set(next.map((r) => r.id));\n      for (const rule of latest.current) if (!kept.has(rule.id)) changes.set(rule.id, undefined);\n      for (const rule of next) if (!latest.current.includes(rule)) changes.set(rule.id, rule);\n    }\n    latest.current = next;\n    if (rulesProp === undefined) setOwn(next);\n    onRulesChange?.(next);\n    if (!changes) save(next);\n  };\n\n  const record = (outcome: ApprovalOutcome) => {\n    outcomes.current.set(outcome.id, outcome);\n    return outcome;\n  };\n  const answers = ({ id, toolName, input }: ApprovalRequest, edited?: unknown) =>\n    calls.current.set(id, { toolName, inputs: edited === undefined ? [input] : [input, edited] });\n  const getRules = useCallback(() => toPlainRules(latest.current), []);\n\n  return {\n    rules,\n    getRules,\n    ready,\n    match: (toolName, input) => evaluateRules(latest.current, toolName, input),\n    decide(request, decision, { reason, input, args } = {}) {\n      const rule = ruleFromDecision(decision, request, { args, reason });\n      if (rule) {\n        setRules([...latest.current, rule]);\n        audit({ type: 'rule-added', at: Date.now(), rule });\n      }\n      const { approved } = decisionEffect(decision);\n      audit({\n        type: 'decision',\n        at: Date.now(),\n        request,\n        decision,\n        by: 'user',\n        rule,\n        ...(reason ? { reason } : {}),\n        ...(input !== undefined ? { input } : {}),\n      });\n      answers(request, input);\n      return record({\n        id: request.id,\n        approved,\n        ...(reason ? { reason } : {}),\n        ...(input !== undefined ? { input } : {}),\n        decision,\n        by: 'user',\n        rule,\n      });\n    },\n    answer(request) {\n      const known = outcomes.current.get(request.id);\n      const call = calls.current.get(request.id);\n      // The outcome it gave, for the call it answered: another call with the same id is decided again.\n      if (known && call?.toolName === request.toolName && call.inputs.some((input) => sameInput(input, request.input)))\n        return known;\n      const match = evaluateRules(latest.current, request.toolName, request.input);\n      if (!match) return undefined;\n      const decision: ApprovalDecision =\n        match.effect === 'allow' ? (match.rule.scope === 'session' ? 'allow-session' : 'allow-always') : 'deny-always';\n      // A rule that ran out before it could tell (`unchecked`) didn't find what its reason is about.\n      const reason =\n        match.effect === 'deny' ? ((match.unchecked ? undefined : match.rule.reason) ?? ruleDenial) : undefined;\n      audit({ type: 'decision', at: Date.now(), request, decision, by: 'rule', rule: match.rule, reason });\n      answers(request);\n      return record({\n        id: request.id,\n        approved: match.effect === 'allow',\n        ...(reason ? { reason } : {}),\n        decision,\n        by: 'rule',\n        rule: match.rule,\n      });\n    },\n    outcomeOf: (id) => outcomes.current.get(id),\n    addRule(rule) {\n      setRules([...latest.current.filter((r) => r.id !== rule.id), rule]);\n      audit({ type: 'rule-added', at: Date.now(), rule });\n    },\n    removeRule(id) {\n      const rule = latest.current.find((r) => r.id === id);\n      if (!rule) return;\n      setRules(latest.current.filter((r) => r.id !== id));\n      audit({ type: 'rule-removed', at: Date.now(), rule });\n    },\n    clearSession() {\n      const session = latest.current.filter((r) => r.scope === 'session');\n      if (session.length === 0) return;\n      setRules(latest.current.filter((r) => r.scope !== 'session'));\n      audit({ type: 'session-cleared', at: Date.now(), rules: session });\n    },\n  };\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n  return !!value && typeof (value as { then?: unknown }).then === 'function';\n}\n\n/**\n * Whether two inputs are one call's: the same value, or the same as JSON. The policy keeps the\n * inputs it answered, not a copy of each as text. Input JSON can't write, such as a cycle, is the\n * same only as itself.\n */\nfunction sameInput(answered: unknown, input: unknown): boolean {\n  if (answered === input) return true;\n  try {\n    const text = JSON.stringify(answered);\n    return text !== undefined && text === JSON.stringify(input);\n  } catch {\n    return false;\n  }\n}\n\n/** Rules with changes by id over them: a rule in place of the one with its id, or after them; `undefined` removes it. */\nfunction over(rules: ApprovalRule[], changes: ReadonlyMap<string, ApprovalRule | undefined>): ApprovalRule[] {\n  if (!changes.size) return rules;\n  const byId = new Map(rules.map((r) => [r.id, r]));\n  for (const [id, rule] of changes) {\n    if (rule) byId.set(id, rule);\n    else byId.delete(id);\n  }\n  return [...byId.values()];\n}\n\n/**\n * Rules from both lists, the later one winning for an id that repeats, but not over a rule with a\n * `when`: an earlier version saved such a rule without it.\n */\nfunction merge(first: readonly ApprovalRule[], second: readonly ApprovalRule[]): ApprovalRule[] {\n  const byId = new Map(first.map((r) => [r.id, r]));\n  for (const rule of second) if (!byId.get(rule.id)?.when) byId.set(rule.id, rule);\n  return [...byId.values()];\n}\n",
      "type": "registry:component",
      "target": "components/signoff-ui/use-approval-policy.ts"
    },
    {
      "path": "packages/signoff-ui/src/labels.tsx",
      "content": "'use client';\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react';\nimport { defaultLabels, mergeLabels, type SignoffLabels, type SignoffLabelsInput } from './lib/labels';\n\n/** What the providers above give: their labels merged, the nearest winning. Empty without one. */\nconst LabelsContext = createContext<SignoffLabelsInput>({});\n\n/**\n * Labels for every component inside: a translation of `defaultLabels`, whole or in part. Providers\n * nest, the inner one winning key by key. Labels hold functions, so render the provider from a\n * Client Component (a module with 'use client') and keep the object stable: at module scope, or memoized.\n */\nexport function SignoffLabelsProvider({ labels, children }: { labels: SignoffLabelsInput; children: ReactNode }) {\n  const parent = useContext(LabelsContext);\n  const value = useMemo(() => mergeLabels(parent, labels), [parent, labels]);\n  return <LabelsContext.Provider value={value}>{children}</LabelsContext.Provider>;\n}\n\n/** A component's own `labels`, for what it renders inside too; nothing extra without them. */\nexport function WithLabels({ labels, children }: { labels: SignoffLabelsInput | undefined; children: ReactNode }) {\n  return labels ? <SignoffLabelsProvider labels={labels}>{children}</SignoffLabelsProvider> : children;\n}\n\n/** Every label in effect here: the English, the providers' over it, and `overrides` over both. */\nexport function useSignoffLabels(overrides?: SignoffLabelsInput): SignoffLabels {\n  const context = useContext(LabelsContext);\n  return useMemo(() => mergeLabels(defaultLabels, context, overrides), [context, overrides]);\n}\n\n/**\n * The sections a component reads, from their English defaults (a module-level object, such as\n * `{ sources: sourcesLabels }`), with the providers' labels and the component's own over them.\n * Only those sections' defaults end up in the component's bundle.\n */\nexport function useLabels<T extends Partial<SignoffLabels>>(defaults: T, overrides?: SignoffLabelsInput): T {\n  const context = useContext(LabelsContext);\n  return useMemo(() => {\n    const keys = Object.keys(defaults) as (keyof T & keyof SignoffLabelsInput)[];\n    if (!overrides && keys.every((key) => context[key] === undefined)) return defaults;\n    const own: SignoffLabelsInput = {};\n    const theirs: SignoffLabelsInput = {};\n    for (const key of keys) {\n      if (context[key] !== undefined) Object.assign(theirs, { [key]: context[key] });\n      if (overrides?.[key] !== undefined) Object.assign(own, { [key]: overrides[key] });\n    }\n    return mergeLabels(defaults as SignoffLabelsInput, theirs, own) as T;\n  }, [defaults, context, overrides]);\n}\n",
      "type": "registry:component",
      "target": "components/signoff-ui/labels.tsx"
    },
    {
      "path": "packages/signoff-ui/src/lib/format.ts",
      "content": "/** Formatting helpers shared by the components. All output is locale-stable. */\n\n/*\n * Each unit is chosen by the value as it will be printed, not the raw value: otherwise rounding\n * produces \"1000ms\", \"60.0s\" or \"1000.0k\" instead of moving up to the next unit.\n */\n\nexport function formatDuration(ms: number | undefined | null): string {\n  if (ms == null || !Number.isFinite(ms) || ms < 0) return '–';\n  if (Math.round(ms) < 1000) return `${Math.round(ms)}ms`;\n  const centis = (ms / 1000).toFixed(2);\n  if (Number(centis) < 10) return `${centis}s`;\n  const tenths = (ms / 1000).toFixed(1);\n  if (Number(tenths) < 60) return `${tenths}s`;\n  const seconds = Math.round(ms / 1000);\n  return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, '0')}s`;\n}\n\n/** Spoken form for screen readers, e.g. \"1.2 seconds\". */\nexport function formatDurationLong(ms: number | undefined | null): string {\n  if (ms == null || !Number.isFinite(ms) || ms < 0) return 'unknown duration';\n  if (Math.round(ms) < 1000) return `${Math.round(ms)} milliseconds`;\n  const tenths = (ms / 1000).toFixed(1);\n  if (Number(tenths) < 60) return `${tenths} seconds`;\n  const total = Math.round(ms / 1000);\n  const minutes = Math.floor(total / 60);\n  const rest = total % 60;\n  return `${minutes} minute${minutes === 1 ? '' : 's'} ${rest} second${rest === 1 ? '' : 's'}`;\n}\n\nexport function formatTokens(n: number | undefined | null): string {\n  if (n == null || !Number.isFinite(n)) return '–';\n  if (Math.abs(Math.round(n)) < 1000) return String(Math.round(n));\n  const hundredths = (n / 1000).toFixed(2);\n  if (Math.abs(Number(hundredths)) < 10) return `${hundredths}k`;\n  const tenths = (n / 1000).toFixed(1);\n  if (Math.abs(Number(tenths)) < 1000) return `${tenths}k`;\n  return `${(n / 1_000_000).toFixed(2)}M`;\n}\n\nexport function formatCost(usd: number | undefined | null): string {\n  if (usd == null || !Number.isFinite(usd)) return '–';\n  if (usd === 0) return '$0.00';\n  const four = usd.toFixed(4);\n  if (Math.abs(Number(four)) < 0.01) return `$${four}`;\n  const three = usd.toFixed(3);\n  if (Math.abs(Number(three)) < 1) return `$${three}`;\n  return `$${usd.toFixed(2)}`;\n}\n\n/** `read_file` / `readFile` / `read-file` → \"Read file\". */\nexport function humanizeToolName(name: string): string {\n  const spaced = name\n    .replace(/[_-]+/g, ' ')\n    .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n    .trim()\n    .toLowerCase();\n  return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\nexport function getHostname(url: string): string {\n  try {\n    return new URL(url).hostname.replace(/^www\\./, '');\n  } catch {\n    return url;\n  }\n}\n\n/** Compact one-line preview of an arbitrary tool input. */\nexport function summarizeValue(value: unknown, max = 72): string | undefined {\n  if (value == null) return undefined;\n  let text: string;\n  if (typeof value === 'string') text = value;\n  else if (typeof value === 'number' || typeof value === 'boolean') text = String(value);\n  else if (typeof value === 'object') {\n    const entries = Object.entries(value as Record<string, unknown>);\n    if (entries.length === 0) return undefined;\n    // Prefer the first string-ish field: it is usually the most descriptive (query, path, command).\n    const primary = entries.find(([, v]) => typeof v === 'string');\n    text = primary\n      ? String(primary[1])\n      : entries.map(([k, v]) => `${k}: ${typeof v === 'object' ? '…' : String(v)}`).join(', ');\n  } else return undefined;\n  text = text.replace(/\\s+/g, ' ').trim();\n  return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\n/**\n * A value as JSON, for showing it: a bigint as `10n`, and an object inside itself as `[Circular]`.\n * Only a cycle is: an object that comes twice, side by side (`{ a: env, b: env }`), is written out\n * each time, as the call that receives it reads it.\n */\nexport function safeStringify(value: unknown, space = 2): string {\n  if (value === undefined) return 'undefined';\n  if (typeof value === 'string') return JSON.stringify(value);\n  // The objects from the root down to the one being written, which only a cycle comes back to.\n  const path: object[] = [];\n  try {\n    return (\n      JSON.stringify(\n        value,\n        function (this: unknown, _key, v: unknown) {\n          if (typeof v === 'bigint') return `${v.toString()}n`;\n          if (typeof v === 'object' && v !== null) {\n            // `this` holds `v`: what is below it on the path was written, and is not around `v`.\n            while (path.length > 0 && path.at(-1) !== this) path.pop();\n            if (path.includes(v)) return '[Circular]';\n            path.push(v);\n          }\n          return v;\n        },\n        space,\n      ) ?? String(value)\n    );\n  } catch {\n    return String(value);\n  }\n}\n",
      "type": "registry:lib",
      "target": "components/signoff-ui/lib/format.ts"
    },
    {
      "path": "packages/signoff-ui/src/lib/labels.ts",
      "content": "/**\n * Every word the components show or announce, in one object: pass a translation of it to\n * `SignoffLabelsProvider`, or part of one to a component's `labels`. Strings are fixed text;\n * functions build text from values (counts, names, line numbers), so a translation can get its\n * plurals and word order right. The English here is the default.\n */\nimport { formatCost, formatDuration, formatDurationLong, formatTokens } from './format';\n\n/*\n * The states the labels name, spelled out here so this module imports nothing but the formatters:\n * a copied registry item that only shows sources does not need the diff engine. They are the same\n * unions as `AgentState`, `ToolPhase`, `FileStatus`, `HunkDecision` and `ApprovalDecision`, which\n * test/labels-types.test.ts checks.\n */\ntype AgentState = 'idle' | 'thinking' | 'working' | 'awaiting-approval' | 'done' | 'stopped' | 'error';\ntype ToolPhase = 'streaming' | 'running' | 'awaiting-approval' | 'success' | 'error' | 'denied';\ntype FileStatus = 'added' | 'deleted' | 'modified' | 'renamed';\ntype HunkDecision = 'pending' | 'accepted' | 'rejected';\ntype ApprovalDecision = 'allow-once' | 'allow-session' | 'allow-always' | 'deny-once' | 'deny-always';\ntype CommentSide = 'new' | 'old';\n\nexport type RiskLevel = 'low' | 'medium' | 'high' | 'critical';\n\n/** A rule, as its description needs it: the tool and the argument patterns. */\nexport interface RuleLabel {\n  tool: string;\n  args?: Readonly<Record<string, string>> | undefined;\n}\n\n/** Where a comment is, as its description needs it. */\nexport interface CommentLabel {\n  target: 'lines' | 'hunk' | 'file';\n  side?: CommentSide | undefined;\n  startLine?: number | undefined;\n  endLine?: number | undefined;\n}\n\n/** Which choices an approval card offers, for its keyboard hint. */\nexport interface OfferedChoices {\n  approve: boolean;\n  session: boolean;\n  always: boolean;\n  deny: boolean;\n  alwaysDeny: boolean;\n}\n\n/** Lines of a hunk, as a range in one of the files. */\nexport interface RangeLabel {\n  side: CommentSide;\n  startLine: number;\n  endLine: number;\n}\n\nexport interface SignoffLabels {\n  /** How values read. Swap these for your locale's number formats. */\n  format: {\n    /** \"120ms\", \"1.20s\", \"2m 05s\". */\n    duration: (ms: number | undefined | null) => string;\n    /** For screen readers: \"1.2 seconds\". */\n    durationLong: (ms: number | undefined | null) => string;\n    /** \"980\", \"1.20k\", \"1.25M\". */\n    tokens: (n: number | undefined | null) => string;\n    /** \"$0.0123\". */\n    cost: (usd: number | undefined | null) => string;\n    /** \"42%\", from a fraction. */\n    percent: (fraction: number) => string;\n  };\n  common: {\n    /** A copy button's name for a moment after it copied. */\n    copied: string;\n    /** A copy button for something named: \"Copy arguments\". */\n    copyThe: (what: string) => string;\n    showAllLines: (count: number) => string;\n    showLess: string;\n    /** After a link that opens a new tab, for screen readers. */\n    opensInNewTab: string;\n    /** The modifier key as printed on the keyboard: ⌘ on a Mac, Ctrl elsewhere. */\n    modKey: (mac: boolean) => string;\n  };\n  agentStatus: {\n    states: Record<AgentState, string>;\n    /** What a pill says along with its state and detail, for screen readers. */\n    spoken: (state: string, detail: string | undefined) => string;\n    /** `deriveAgentState`'s detail while the model writes. */\n    writingResponse: string;\n  };\n  toolCallTimeline: {\n    list: string;\n    phases: Record<ToolPhase, string>;\n    stopped: string;\n    finished: (name: string, durationLong: string) => string;\n    failed: (name: string, error: string | undefined) => string;\n    blockedByPolicy: (name: string) => string;\n    denied: (name: string) => string;\n    input: string;\n    inputStreaming: string;\n    output: string;\n    outputPartial: string;\n    error: string;\n    deniedBy: (automatic: boolean) => string;\n    waitingForInput: string;\n    /** A sub-agent nested under the call that started it. */\n    subagent: {\n      /** Its name, when the agent gave none. */\n      name: string;\n      /** How many tool calls it made. */\n      calls: (count: number) => string;\n      /** The name of the list of its calls. */\n      list: (name: string) => string;\n      /** Paused until a later run (AG-UI's `suspended`). */\n      paused: string;\n    };\n  };\n  approvalCard: {\n    required: string;\n    risk: Record<RiskLevel, string>;\n    /** What a pending card's preview of a command is called, while it scrolls sideways. */\n    command: string;\n    arguments: string;\n    approve: string;\n    session: string;\n    always: string;\n    deny: string;\n    alwaysDeny: string;\n    sendDenial: string;\n    confirm: string;\n    denyWithFeedback: string;\n    reasonLabel: string;\n    reasonPlaceholder: string;\n    approveHint: string;\n    keyboardHint: (offered: OfferedChoices, mod: string) => string;\n    /**\n     * What a pending card says after its reason, for screen readers: the risk, what will run (the\n     * arguments' `command` and `cwd`), the first names and values of the arguments besides those\n     * (of all of them when there is no command), and the calls a lasting decision covers, as\n     * `describeRule` words them. Each is `undefined` or empty when the card has none.\n     */\n    summary: (card: {\n      risk: string | undefined;\n      command: string | undefined;\n      cwd: string | undefined;\n      args: readonly (readonly [name: string, value: string])[];\n      rule: string | undefined;\n    }) => string;\n    /** What a resolved card says of a person's decision. */\n    resolved: Record<ApprovalDecision, string>;\n    /** A lasting decision, announced with the calls its rule covers: `resolved`'s text and `describeRule`'s. */\n    resolvedFor: (resolved: string, rule: string) => string;\n    approved: string;\n    denied: string;\n    autoApproved: string;\n    blockedByPolicy: string;\n    allowedByRule: string;\n    deniedByRule: string;\n    /** A rule in words: \"run_command with command npm test*\". */\n    describeRule: (rule: RuleLabel) => string;\n    critical: string;\n    /** Announced when a critical action's first press is let go: Escape, or focus going elsewhere. */\n    confirmCancelled: string;\n    invalidJson: string;\n    editArguments: string;\n    doneEditing: string;\n    undoEdits: string;\n    edited: string;\n    argumentsJson: string;\n    notValidJson: (error: string) => string;\n    ruleLegend: string;\n    /** Around the tool's name: \"Remembered for \", run_command, \" calls where:\". */\n    rememberedFor: (anyArguments: boolean) => { before: string; after: string };\n    argumentMatches: (name: string) => string;\n    anyArguments: string;\n    globHelp: string;\n    batch: {\n      group: string;\n      waiting: (count: number) => string;\n      approveAll: string;\n      denyAll: string;\n      confirm: string;\n      critical: string;\n      answered: (count: number, approved: boolean) => string;\n    };\n  };\n  diffReview: {\n    title: string;\n    layout: string;\n    views: { unified: string; split: string };\n    files: (count: number) => string;\n    hunks: (count: number, comparing: boolean) => string;\n    status: Record<FileStatus, { letter: string; name: string }>;\n    navigator: string;\n    /** A file in the navigator, after its path, for screen readers. */\n    navigatorState: (decided: number, total: number, viewed: boolean) => string;\n    comparingShort: string;\n    /** Between a renamed file's old and new path, for screen readers (the screen shows an arrow). */\n    renamedTo: string;\n    toggleFile: (collapsed: boolean, path: string) => string;\n    viewed: string;\n    rejectFile: string;\n    acceptFile: string;\n    comparing: string;\n    fallback: string;\n    noChanges: string;\n    /** A whole file, decided as one: what the card in its place says. */\n    wholeFile: (status: FileStatus, binary: boolean, oldPath: string | undefined) => string;\n    accept: string;\n    reject: string;\n    /** \"hunk 2\" or \"change 5\", in the decision buttons' names. */\n    itemName: (kind: 'hunk' | 'file', n: number) => string;\n    acceptItem: (item: string) => string;\n    rejectItem: (item: string) => string;\n    resetItem: (item: string) => string;\n    commentOn: (what: string) => string;\n    /** The badge on a decided hunk. */\n    badge: Record<Exclude<HunkDecision, 'pending'>, string>;\n    /** A hunk's name: where it is and how it was decided. */\n    hunk: (n: number, total: number, path: string, from: number, to: number, decision: HunkDecision) => string;\n    /** A whole-file item's name; `what` is `describeFile`'s. */\n    fileItem: (n: number, total: number, path: string, what: string, decision: HunkDecision) => string;\n    describeFile: (status: FileStatus, binary: boolean, oldPath: string | undefined) => string;\n    hunkCode: (n: number, path: string) => string;\n    added: string;\n    removed: string;\n    decided: (kind: 'hunk' | 'file', n: number, total: number, decision: HunkDecision, remaining: number) => string;\n    decidedAll: (total: number, decision: Exclude<HunkDecision, 'pending'>) => string;\n    decidedFile: (count: number, path: string, decision: Exclude<HunkDecision, 'pending'>) => string;\n    viewedAnnouncement: (path: string, viewed: number, total: number) => string;\n    notViewedAnnouncement: (path: string) => string;\n    lines: (range: RangeLabel) => string;\n    selected: (line: string, range: RangeLabel) => string;\n    where: (comment: CommentLabel) => string;\n    /** Over a comment: what it is on, and before that, for screen readers only, what it is. */\n    commentHeading: (where: string) => { hidden: string; visible: string };\n    commentField: (where: string) => string;\n    commentPlaceholder: string;\n    editComment: (where: string) => string;\n    deleteComment: (where: string) => string;\n    edit: string;\n    delete: string;\n    cancel: string;\n    saveComment: string;\n    addComment: string;\n    commentAdded: (where: string, path: string) => string;\n    commentUpdated: string;\n    commentDeleted: string;\n    unchangedLines: (count: number) => string;\n    /** The gap buttons: what shows, then what only screen readers hear after it. */\n    moreAfter: (count: number, hunk: number) => { visible: string; hidden: string };\n    moreBefore: (count: number, hunk: number) => { visible: string; hidden: string };\n    showAll: (count: number) => { visible: string; hidden: string };\n    expanded: (count: number) => string;\n    /** After \"3/5\". */\n    reviewed: string;\n    filesViewed: (viewed: number, total: number) => string;\n    comments: (count: number) => string;\n    comparingFiles: string;\n    skipped: string;\n    apply: (accepted: number, total: number) => string;\n    /** Announced when the review is sent: items accepted of all, and the comments sent with them. */\n    submitted: (accepted: number, total: number, comments: number) => string;\n    acceptAll: string;\n    rejectAll: string;\n    keyHints: { move: string; accept: string; reject: string; comment: string; apply: string };\n    keyboardHelp: (mod: string) => string;\n  };\n  markdown: {\n    code: (language: string | undefined) => string;\n    /** The badge on a code block with no language. */\n    codeBadge: string;\n    copyCode: string;\n    table: string;\n    image: string;\n    imageFallback: string;\n    citation: (n: number | string) => string;\n    /** The name of a task list's checkbox (`- [x] done`), read with its state. */\n    task: string;\n  };\n  reasoning: {\n    thinking: string;\n    thoughtFor: (duration: string) => string;\n    reasoning: string;\n  };\n  runMeter: {\n    title: string;\n    metrics: (live: boolean) => string;\n    summary: (values: {\n      input: string;\n      output: string;\n      cost: string | undefined;\n      ttft: string | undefined;\n      total: string | undefined;\n    }) => string;\n    inputTokens: string;\n    outputTokens: string;\n    estimatedCost: string;\n    timeToFirstToken: string;\n    totalTime: string;\n    ttft: string;\n    live: string;\n    tokens: string;\n    estCost: string;\n    breakdown: string;\n    split: (input: string, output: string) => string;\n    input: string;\n    output: string;\n    cached: (n: string) => string;\n    reasoningTokens: (n: string) => string;\n    total: string;\n    cacheHit: string;\n    costSplit: (input: string, output: string) => string;\n    rates: (input: number, output: number) => string;\n  };\n  approvalPolicy: {\n    /** The reason a deny rule sends the agent when it has none of its own; resolved cards show it. */\n    ruleDenial: string;\n  };\n  sources: { label: string; document: string };\n  agentMessage: { attachedImage: string };\n  /** The marks on text from the agent, where it could read as something it is not. */\n  untrusted: {\n    /** A mark in place of characters that do not show, such as a bidi control or a zero-width space; `codes` lists each once. */\n    invisible: (count: number, codes: readonly string[]) => string;\n    /**\n     * A mark in place of a long run of spaces and tabs, or of blank lines, in a command or a path:\n     * `lines` is how many line breaks a run of blank lines has, which its mark shows, and 0 for spaces.\n     */\n    blank: (count: number, lines: number) => string;\n    /** Beside a link whose text names another host than the one it goes to. */\n    linksTo: (host: string) => string;\n  };\n}\n\nconst plural = (n: number, one: string, many = `${one}s`) => (n === 1 ? one : many);\n\nconst lines = (range: RangeLabel) =>\n  `${range.startLine === range.endLine ? `line ${range.startLine}` : `lines ${range.startLine} to ${range.endLine}`}${range.side === 'old' ? ' of the original' : ''}`;\n\nconst DECISION: Record<HunkDecision, string> = { pending: 'not reviewed', accepted: 'accepted', rejected: 'rejected' };\n\n/*\n * Each section on its own, so a component's bundle keeps the sections it reads and no others.\n */\nexport const formatLabels: SignoffLabels['format'] = {\n  duration: formatDuration,\n  durationLong: formatDurationLong,\n  tokens: formatTokens,\n  cost: formatCost,\n  percent: (fraction) => `${Math.round(fraction * 100)}%`,\n};\n\nexport const commonLabels: SignoffLabels['common'] = {\n  copied: 'Copied',\n  copyThe: (what) => `Copy ${what.toLowerCase()}`,\n  showAllLines: (count) => `Show all ${count} lines`,\n  showLess: 'Show less',\n  opensInNewTab: '(opens in a new tab)',\n  modKey: (mac) => (mac ? '⌘' : 'Ctrl'),\n};\n\nexport const agentStatusLabels: SignoffLabels['agentStatus'] = {\n  states: {\n    idle: 'Idle',\n    thinking: 'Thinking',\n    working: 'Working',\n    'awaiting-approval': 'Waiting for approval',\n    done: 'Done',\n    stopped: 'Stopped',\n    error: 'Error',\n  },\n  spoken: (state, detail) => (detail ? `${state}: ${detail}` : state),\n  writingResponse: 'Writing response',\n};\n\nexport const toolCallTimelineLabels: SignoffLabels['toolCallTimeline'] = {\n  list: 'Tool calls',\n  phases: {\n    streaming: 'Preparing',\n    running: 'Running',\n    'awaiting-approval': 'Needs approval',\n    success: 'Done',\n    error: 'Failed',\n    denied: 'Denied',\n  },\n  stopped: 'Stopped',\n  finished: (name, duration) => `${name} finished in ${duration}`,\n  failed: (name, error) => `${name} failed: ${error ?? 'unknown error'}`,\n  blockedByPolicy: (name) => `${name} was blocked by policy`,\n  denied: (name) => `${name} was denied`,\n  input: 'Input',\n  inputStreaming: 'Input (streaming)',\n  output: 'Output',\n  outputPartial: 'Output (partial)',\n  error: 'Error',\n  deniedBy: (automatic) => (automatic ? 'Blocked by policy' : 'Denied by user'),\n  waitingForInput: 'Waiting for input…',\n  subagent: {\n    name: 'Sub-agent',\n    calls: (count) => `${count} ${count === 1 ? 'call' : 'calls'}`,\n    list: (name) => `${name}’s tool calls`,\n    paused: 'Paused',\n  },\n};\n\nexport const approvalCardLabels: SignoffLabels['approvalCard'] = {\n  required: 'Approval required',\n  risk: { low: 'Low risk', medium: 'Medium risk', high: 'High risk', critical: 'Critical' },\n  command: 'Command',\n  arguments: 'Arguments',\n  approve: 'Approve',\n  session: 'For this session',\n  always: 'Always',\n  deny: 'Deny',\n  alwaysDeny: 'Always deny',\n  sendDenial: 'Send denial',\n  confirm: 'Confirm approval',\n  denyWithFeedback: 'Deny with feedback',\n  reasonLabel: 'Tell the agent why (optional)',\n  reasonPlaceholder: 'What should the agent do instead?',\n  approveHint: 'approve',\n  keyboardHint: (offered, mod) =>\n    `Keyboard: press ${[\n      offered.approve && 'Y to approve',\n      offered.session && 'S to approve for this session',\n      offered.always && 'A to always approve',\n      offered.deny && 'N to deny',\n      offered.alwaysDeny && 'Shift N to always deny',\n    ]\n      .filter(Boolean)\n      .join(', ')}, or ${mod} Enter to approve.`,\n  summary: ({ risk, command, cwd, args, rule }) =>\n    [\n      risk && `${risk}.`,\n      command !== undefined && `Runs ${command}${cwd ? ` in ${cwd}` : ''}.`,\n      args.length > 0 &&\n        `${command !== undefined ? 'With' : 'Arguments:'} ${args.map((arg) => arg.join(' ')).join(', ')}.`,\n      rule && `A lasting decision covers ${rule}.`,\n    ]\n      .filter(Boolean)\n      .join(' '),\n  resolved: {\n    'allow-once': 'Approved',\n    'allow-session': 'Approved for this session',\n    'allow-always': 'Always approved',\n    'deny-once': 'Denied',\n    'deny-always': 'Always denied',\n  },\n  resolvedFor: (resolved, rule) => `${resolved}: ${rule}.`,\n  approved: 'Approved',\n  denied: 'Denied',\n  autoApproved: 'Auto-approved',\n  blockedByPolicy: 'Blocked by policy',\n  allowedByRule: 'Allowed by your rule',\n  deniedByRule: 'Denied by your rule',\n  describeRule: (rule) => {\n    const args = Object.entries(rule.args ?? {});\n    const tool = rule.tool === '*' ? 'any tool' : rule.tool.replace(/\\\\(.)/g, '$1');\n    return args.length === 0\n      ? `${tool}, any arguments`\n      : `${tool} with ${args.map(([name, pattern]) => `${name} ${pattern}`).join(', ')}`;\n  },\n  critical: 'Critical action. Press approve again to confirm.',\n  confirmCancelled: 'Confirmation cancelled.',\n  invalidJson: 'The arguments are not valid JSON.',\n  editArguments: 'Edit arguments',\n  doneEditing: 'Done editing',\n  undoEdits: 'Undo edits',\n  edited: 'Edited: approving runs the new arguments.',\n  argumentsJson: 'Arguments, as JSON',\n  notValidJson: (error) => `Not valid JSON: ${error}`,\n  ruleLegend: 'Calls a lasting decision covers',\n  rememberedFor: (any) => ({ before: 'Remembered for ', after: any ? ' with any arguments.' : ' calls where:' }),\n  argumentMatches: (name) => `${name} matches`,\n  anyArguments: 'Any arguments',\n  globHelp: '* matches any text but shell operators (; & | > < and backticks); ** matches anything.',\n  batch: {\n    group: 'Approvals waiting',\n    waiting: (count) => `${count} approvals are waiting.`,\n    approveAll: 'Approve all',\n    denyAll: 'Deny all',\n    confirm: 'Confirm approve all',\n    critical: 'One of them is critical. Press Approve all again to confirm.',\n    answered: (count, approved) => `${count} approvals ${approved ? 'approved' : 'denied'}.`,\n  },\n};\n\nexport const diffReviewLabels: SignoffLabels['diffReview'] = {\n  title: 'Review changes',\n  layout: 'Diff layout',\n  views: { unified: 'Unified', split: 'Split' },\n  files: (count) => `${count} ${plural(count, 'file')}`,\n  hunks: (count, comparing) => `${count} ${plural(count, 'hunk')}${comparing ? ' so far' : ''}`,\n  status: {\n    modified: { letter: 'M', name: 'Modified' },\n    added: { letter: 'A', name: 'Added' },\n    deleted: { letter: 'D', name: 'Deleted' },\n    renamed: { letter: 'R', name: 'Renamed' },\n  },\n  navigator: 'Files in this review',\n  navigatorState: (decided, total, viewed) => `, ${decided} of ${total} decided${viewed ? ', viewed' : ''}`,\n  comparingShort: 'comparing…',\n  renamedTo: 'to',\n  toggleFile: (collapsed, path) => `${collapsed ? 'Show' : 'Hide'} ${path}`,\n  viewed: 'Viewed',\n  rejectFile: 'Reject file',\n  acceptFile: 'Accept file',\n  comparing: 'Comparing changes…',\n  fallback: 'Too many changes to compare line by line: the changed lines are shown as one hunk that replaces them.',\n  noChanges: 'No textual changes.',\n  wholeFile: (status, binary, oldPath) =>\n    binary\n      ? 'Binary file, not shown.'\n      : status === 'renamed'\n        ? `Renamed from ${oldPath}, without changes.`\n        : status === 'deleted'\n          ? 'Empty file, deleted.'\n          : 'New empty file.',\n  accept: 'Accept',\n  reject: 'Reject',\n  itemName: (kind, n) => `${kind === 'hunk' ? 'hunk' : 'change'} ${n}`,\n  acceptItem: (item) => `Accept ${item}`,\n  rejectItem: (item) => `Reject ${item}`,\n  resetItem: (item) => `Reset ${item}`,\n  commentOn: (what) => `Comment on ${what}`,\n  badge: { accepted: 'accepted', rejected: 'rejected' },\n  hunk: (n, total, path, from, to, decision) =>\n    `Hunk ${n} of ${total}, ${path}, lines ${from} to ${to}, ${DECISION[decision]}`,\n  fileItem: (n, total, path, what, decision) => `Change ${n} of ${total}, ${path}, ${what}, ${DECISION[decision]}`,\n  describeFile: (status, binary, oldPath) =>\n    binary\n      ? 'binary file'\n      : status === 'renamed'\n        ? `renamed from ${oldPath}`\n        : status === 'deleted'\n          ? 'deleted empty file'\n          : 'new empty file',\n  hunkCode: (n, path) => `Hunk ${n} code, ${path}`,\n  added: 'Added: ',\n  removed: 'Removed: ',\n  decided: (kind, n, total, decision, remaining) =>\n    `${kind === 'hunk' ? 'Hunk' : 'Change'} ${n} of ${total} ${decision === 'pending' ? 'reset' : decision}. ${\n      remaining === 0 ? 'All hunks reviewed.' : `${remaining} remaining.`\n    }`,\n  decidedAll: (total, decision) => `All ${total} hunks ${decision}.`,\n  decidedFile: (count, path, decision) => `${count === 1 ? 'The hunk' : `All ${count} hunks`} in ${path} ${decision}.`,\n  viewedAnnouncement: (path, viewed, total) => `${path} viewed. ${viewed} of ${total} files viewed.`,\n  notViewedAnnouncement: (path) => `${path} no longer viewed.`,\n  lines,\n  selected: (line, range) => {\n    const text = lines(range);\n    return `${line}. ${text.charAt(0).toUpperCase()}${text.slice(1)} selected.`;\n  },\n  where: (comment) =>\n    comment.target === 'file'\n      ? 'the file'\n      : comment.target === 'hunk'\n        ? 'the hunk'\n        : lines({ side: comment.side ?? 'new', startLine: comment.startLine ?? 0, endLine: comment.endLine ?? 0 }),\n  commentHeading: (where) => ({ hidden: 'Comment ', visible: `On ${where}` }),\n  commentField: (where) => `Comment on ${where}, for the agent`,\n  commentPlaceholder: 'What should change here?',\n  editComment: (where) => `Edit comment on ${where}`,\n  deleteComment: (where) => `Delete comment on ${where}`,\n  edit: 'Edit',\n  delete: 'Delete',\n  cancel: 'Cancel',\n  saveComment: 'Save comment',\n  addComment: 'Comment',\n  commentAdded: (where, path) => `Comment added on ${where} of ${path}.`,\n  commentUpdated: 'Comment updated.',\n  commentDeleted: 'Comment deleted.',\n  unchangedLines: (count) => `${count} unchanged ${plural(count, 'line')}`,\n  moreAfter: (count, hunk) => ({\n    visible: `${count} more`,\n    hidden: ` unchanged ${plural(count, 'line')} after hunk ${hunk}`,\n  }),\n  moreBefore: (count, hunk) => ({\n    visible: `${count} more`,\n    hidden: ` unchanged ${plural(count, 'line')} before hunk ${hunk}`,\n  }),\n  showAll: (count) => ({ visible: 'Show all', hidden: ` ${count} unchanged ${plural(count, 'line')}` }),\n  expanded: (count) => `Showing ${count} more unchanged ${plural(count, 'line')}.`,\n  reviewed: 'reviewed',\n  filesViewed: (viewed, total) => `${viewed} of ${total} files viewed`,\n  comments: (count) => `${count} ${plural(count, 'comment')}`,\n  comparingFiles: 'comparing files…',\n  skipped: 'unreviewed hunks are skipped',\n  apply: (accepted, total) => (accepted > 0 ? `Apply ${accepted} of ${total}` : 'Apply changes'),\n  submitted: (accepted, total, comments) =>\n    `Review sent: ${accepted} of ${total} accepted${comments > 0 ? `, ${comments} ${plural(comments, 'comment')}` : ''}.`,\n  acceptAll: 'Accept all',\n  rejectAll: 'Reject all',\n  keyHints: { move: 'move', accept: 'accept', reject: 'reject', comment: 'comment', apply: 'apply' },\n  keyboardHelp: (mod) =>\n    `Keyboard: J or K to move between hunks, Shift J or Shift K between files, A to accept, R to reject, U to reset, Alt A or Alt R for the whole file, Shift A or Shift R for every hunk, Shift with the up or down arrow to select lines, C to comment on them or on the hunk, E to show more unchanged lines, V to mark the file viewed, ${mod} Enter to apply.`,\n};\n\nexport const markdownLabels: SignoffLabels['markdown'] = {\n  code: (language) => (language && language !== 'text' ? `Code, ${language}` : 'Code'),\n  codeBadge: 'code',\n  copyCode: 'Copy code',\n  table: 'Table',\n  image: 'Image:',\n  imageFallback: 'image',\n  citation: (n) => `Source ${n}`,\n  task: 'Task',\n};\n\nexport const reasoningLabels: SignoffLabels['reasoning'] = {\n  thinking: 'Thinking',\n  thoughtFor: (duration) => `Thought for ${duration}`,\n  reasoning: 'Reasoning',\n};\n\nexport const runMeterLabels: SignoffLabels['runMeter'] = {\n  title: 'Run',\n  metrics: (live) => `Run metrics${live ? ' (live)' : ''}`,\n  summary: ({ input, output, cost, ttft, total }) =>\n    [\n      `${input} input tokens`,\n      `${output} output tokens`,\n      cost !== undefined ? `estimated cost ${cost}` : undefined,\n      ttft !== undefined ? `time to first token ${ttft}` : undefined,\n      total !== undefined ? `total ${total}` : undefined,\n    ]\n      .filter(Boolean)\n      .join(', '),\n  inputTokens: 'Input tokens',\n  outputTokens: 'Output tokens',\n  estimatedCost: 'Estimated cost',\n  timeToFirstToken: 'Time to first token',\n  totalTime: 'Total time',\n  ttft: 'TTFT',\n  live: 'Live',\n  tokens: 'Tokens',\n  estCost: 'Est. cost',\n  breakdown: 'Token breakdown',\n  split: (input, output) => `Input ${input} · Output ${output}`,\n  input: 'Input',\n  output: 'Output',\n  cached: (n) => `(${n} cached)`,\n  reasoningTokens: (n) => `(${n} reasoning)`,\n  total: 'Total',\n  cacheHit: 'Cache hit',\n  costSplit: (input, output) => `${input} input · ${output} output`,\n  rates: (input, output) => `$${input}/$${output} per 1M`,\n};\n\nexport const approvalPolicyLabels: SignoffLabels['approvalPolicy'] = { ruleDenial: 'Denied by a rule' };\n\nexport const sourcesLabels: SignoffLabels['sources'] = { label: 'Sources', document: 'Document' };\n\nexport const agentMessageLabels: SignoffLabels['agentMessage'] = { attachedImage: 'Attached image' };\n\nexport const untrustedLabels: SignoffLabels['untrusted'] = {\n  invisible: (count, codes) =>\n    count === 1 ? `Invisible character ${codes[0]}` : `${count} invisible characters: ${codes.join(', ')}`,\n  blank: (count, lines) => (lines ? `${lines} line breaks` : `${count} blank characters`),\n  linksTo: (host) => `Links to ${host}`,\n};\n\n/** The English labels, as the components read without any. */\nexport const defaultLabels: SignoffLabels = {\n  format: formatLabels,\n  common: commonLabels,\n  agentStatus: agentStatusLabels,\n  toolCallTimeline: toolCallTimelineLabels,\n  approvalCard: approvalCardLabels,\n  diffReview: diffReviewLabels,\n  markdown: markdownLabels,\n  reasoning: reasoningLabels,\n  runMeter: runMeterLabels,\n  approvalPolicy: approvalPolicyLabels,\n  sources: sourcesLabels,\n  agentMessage: agentMessageLabels,\n  untrusted: untrustedLabels,\n};\n\n/** A part of the labels: any section, any key, at any depth. */\nexport type SignoffLabelsInput = {\n  [K in keyof SignoffLabels]?: DeepPartial<SignoffLabels[K]>;\n};\n\ntype DeepPartial<T> = T extends (...args: never[]) => unknown\n  ? T\n  : T extends object\n    ? { [K in keyof T]?: DeepPartial<T[K]> }\n    : T;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n  typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Labels with some replaced: plain objects merge key by key, strings and functions replace. */\nexport function mergeLabels<T extends SignoffLabelsInput>(\n  base: T,\n  ...overrides: (SignoffLabelsInput | undefined)[]\n): T {\n  const merge = (a: unknown, b: unknown): unknown => {\n    if (b === undefined) return a;\n    if (!isRecord(a) || !isRecord(b)) return b;\n    const out: Record<string, unknown> = { ...a };\n    for (const [key, value] of Object.entries(b)) out[key] = merge(a[key], value);\n    return out;\n  };\n  return overrides.reduce<T>((labels, next) => merge(labels, next) as T, base);\n}\n",
      "type": "registry:lib",
      "target": "components/signoff-ui/lib/labels.ts"
    },
    {
      "path": "packages/signoff-ui/src/lib/policy.ts",
      "content": "/**\n * Approval rules: what a person decided once, applied to the calls that follow. Pure, with no React,\n * so the same rules decide on the client (answering a request before anyone is asked) and on the\n * server (`toToolApproval`, for AI SDK 7's `toolApproval`).\n */\n\n/** What a person can decide about a tool call, and for how long it holds. */\nexport type ApprovalDecision = 'allow-once' | 'allow-session' | 'allow-always' | 'deny-once' | 'deny-always';\n\nexport const APPROVAL_DECISIONS: readonly ApprovalDecision[] = [\n  'allow-once',\n  'allow-session',\n  'allow-always',\n  'deny-once',\n  'deny-always',\n];\n\n/** A standing decision about a tool's calls: allowed or denied, for the session or always. */\nexport interface ApprovalRule {\n  /** Unique among the rules. */\n  id: string;\n  /**\n   * The tool's name, or a glob over names: `*` for every tool, `mcp_github_*` for a family. In a\n   * deny rule `*` and `?` match any character of a name; in an allow rule they stop at a shell\n   * operator, as in `args`.\n   */\n  tool: string;\n  /**\n   * Globs by argument name, which must all match: `{ command: 'npm test*' }`. A dotted name reads\n   * a nested argument (`'options.cwd'`), and a key of that name too. A deny rule's globs also match\n   * each command of a shell line (see `ruleMatches`). Absent: any arguments.\n   */\n  args?: Readonly<Record<string, string>> | undefined;\n  /** A test of your own on the input, on top of `args`. Code, so storage does not keep the rule. */\n  when?: ((input: unknown) => boolean) | undefined;\n  /** Whether the calls it covers run without asking, or are refused. A deny rule wins over an allow rule. */\n  effect: 'allow' | 'deny';\n  /** `session`: until the page reloads or the session is cleared. `always`: kept by the storage. */\n  scope: 'session' | 'always';\n  /** When it was made, in milliseconds since the epoch. */\n  createdAt?: number | undefined;\n  /** Why it was made, e.g. the reason a person gave when denying. */\n  reason?: string | undefined;\n}\n\n/** A tool call that needs a decision. */\nexport interface ApprovalRequest {\n  /**\n   * The id a response answers: AI SDK's `approval.id`, an AG-UI interrupt's id, or for ACP the\n   * tool call's id.\n   */\n  id: string;\n  /** The tool's name, which a rule's `tool` matches. */\n  toolName: string;\n  /** The call's arguments, which a rule's `args` and `when` match. */\n  input: unknown;\n  /** The tool call's own id, when the request has one apart from `id`, as AI SDK's approvals do. */\n  toolCallId?: string | undefined;\n}\n\n/** The rule that decides a call. */\nexport interface RuleMatch {\n  effect: 'allow' | 'deny';\n  rule: ApprovalRule;\n  /**\n   * The rule is a deny rule that ran out of steps before it could tell whether it covers the call,\n   * the arguments being too long for its patterns, and no other deny rule covers it: the call is\n   * denied, and the rule's own `reason` doesn't apply.\n   */\n  unchecked?: boolean | undefined;\n}\n\n/**\n * Characters a single `*` or `?` never matches: what chains, pipes, substitutes or redirects a\n * shell command. So `npm test*` allows `npm test -- --watch` but not `npm test && rm -rf ~`.\n */\nconst SHELL_CONTROL = ';&|`<>\\r\\n';\n\nfunction escapeRegExp(text: string) {\n  return text.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&');\n}\n\n/* A glob's parts: a character, as its code, or one of these. */\nconst ONE = -1; // ?\nconst STAR = -2; // *\nconst ANY = -3; // ** (or more)\nconst END = 0x10000; // past the last part, in `globMatch`: no character's code\n\n/** A pattern in parts: `\\` and the character it makes literal, a run of `*`, or one character. */\nconst globParts = (pattern: string) =>\n  (pattern.match(/\\\\[\\s\\S]|\\*+|[\\s\\S]/g) ?? []).map((part) =>\n    part[0] === '\\\\' && part[1]\n      ? part.charCodeAt(1)\n      : part[1]\n        ? ANY\n        : part === '*'\n          ? STAR\n          : part === '?'\n            ? ONE\n            : part.charCodeAt(0),\n  );\n\n/**\n * A glob as a regular expression over the whole value:\n * - `*` matches any run of characters but shell control characters (`;`, `&`, `|`, `` ` ``, `<`,\n *   `>`, line breaks) and `$(`;\n * - `?` matches one such character;\n * - `**` matches any run of characters at all;\n * - `\\` makes the next character literal; everything else is literal.\n *\n * The expression backtracks: with a few `*` and a long value it doesn't match, a test can take\n * seconds. `matchesGlob` gives the same answers without backtracking.\n */\nexport function globToRegExp(pattern: string): RegExp {\n  const safe = `(?:(?!\\\\$\\\\()[^${escapeRegExp(SHELL_CONTROL)}])`;\n  const source = globParts(pattern).map((part) =>\n    part === ANY\n      ? '[\\\\s\\\\S]*'\n      : part === STAR\n        ? `${safe}*`\n        : part === ONE\n          ? safe\n          : escapeRegExp(String.fromCharCode(part)),\n  );\n  return new RegExp(`^${source.join('')}$`);\n}\n\n/**\n * Matching work a rule has left for a call, in steps. Each character it reads costs the places in\n * the pattern that match so far, plus one, and earns `STEPS_PER_CHARACTER`. An empty value, such as\n * an array's item, counts as one character.\n */\ninterface Budget {\n  left: number;\n}\n\n/**\n * The steps a rule starts with, for the tool's name and again for its arguments: enough for any\n * pattern on a short argument. Each character it reads earns it `STEPS_PER_CHARACTER` more, several\n * times what a common pattern takes, so a rule such as `**PRIVATE KEY**` never runs out, however\n * long the argument. A pattern that takes more for each character, such as 500 characters of `a`\n * against an argument of `a`s, stops after a few hundred: each rule's work grows with what it reads,\n * and no more.\n */\nconst RULE_STEPS = 20_000;\nconst STEPS_PER_CHARACTER = 30;\n\n/** A value to match, and where in it a match may start, ascending. */\ntype Candidate = readonly [value: string, starts: readonly number[]];\n\nconst FROM_START: readonly number[] = [0];\n\n/**\n * Whether a glob's parts match one of the values from one of its starts to its end, or `undefined`\n * once `budget` runs out. It reads each value once, keeping the places in the pattern that match so\n * far, each once, so its time grows with the values' length times the pattern's, and no more. With\n * `loose`, `*` and `?` match any character, as they do in a deny rule's tool pattern.\n */\nfunction globMatch(\n  values: readonly Candidate[],\n  parts: readonly number[],\n  loose: boolean,\n  budget: Budget,\n): boolean | undefined {\n  const end = parts.length;\n  // The parts, and past the last one a part no character matches: the loops never read past them.\n  const pattern = Int32Array.from([...parts, END]);\n  // Whether a single `*` or `?` must stop at a shell operator: none in the pattern, nothing to check.\n  const narrow = !loose && parts.some((part) => part === STAR || part === ONE);\n  // The places in the pattern that match so far, `count` of them, and those after the next character.\n  let places = new Int32Array(end + 1);\n  let next = new Int32Array(end + 1);\n  // The step at which each place was last reached, so a place joins a step's list once. Steps count\n  // on from one value to the next, so no mark carries over.\n  const seen = new Int32Array(end + 1).fill(-1);\n  let step = 0;\n  for (const [value, starts] of values) {\n    let count = 0;\n    for (let i = 0, s = 0; ; i++, step++) {\n      if (s < starts.length && starts[s] === i && seen[0] !== step) {\n        seen[0] = step;\n        places[count++] = 0;\n      }\n      while (s < starts.length && starts[s]! <= i) s++;\n      // A `*` or `**` can match nothing, so the place after it is reached too (the loop visits what it adds).\n      for (let k = 0; k < count; k++) {\n        const after = places[k]! + 1;\n        if (pattern[after - 1]! < ONE && seen[after] !== step) {\n          seen[after] = step;\n          places[count++] = after;\n        }\n      }\n      if (i === value.length) {\n        if (seen[end] === step) return true;\n        // An empty value reads no character, and counts as one: so the steps grow with the values read.\n        if (!i && (budget.left += STEPS_PER_CHARACTER - count - 1) < 0) return undefined;\n        break;\n      }\n      if (!count && s === starts.length) break;\n      if ((budget.left += STEPS_PER_CHARACTER - count - 1) < 0) return undefined;\n      const code = value.charCodeAt(i);\n      // What a single `*` or `?` may match: no shell control character, and no `$` that starts `$(`.\n      const safe = !narrow || (!SHELL_CONTROL.includes(value[i]!) && !(code === 36 && value.charCodeAt(i + 1) === 40));\n      let reached = 0;\n      for (let k = 0; k < count; k++) {\n        const place = places[k]!;\n        const part = pattern[place]!;\n        const to =\n          part === ANY || (part === STAR && safe) ? place : part === code || (part === ONE && safe) ? place + 1 : -1;\n        if (to >= 0 && seen[to] !== step + 1) {\n          seen[to] = step + 1;\n          next[reached++] = to;\n        }\n      }\n      const read = places;\n      places = next;\n      next = read;\n      count = reached;\n    }\n    step++;\n  }\n  return false;\n}\n\n/**\n * Whether a whole value matches a glob (see `globToRegExp`). It reads the value once, keeping the\n * places in the pattern that match so far, so its time grows with the value's length times the\n * pattern's, and no more: a long argument written by a model can't hold up the server or the page.\n */\nexport function matchesGlob(value: string, pattern: string): boolean {\n  return globMatch([[value, FROM_START]], globParts(pattern), false, { left: Infinity }) === true;\n}\n\n/** Where a shell line splits into commands, inside quotes too: its operators, `$(`, and a subshell's parentheses. */\nconst COMMAND_BREAK = ';&|`\\r\\n()';\n/** Space between words; line breaks are in `COMMAND_BREAK`. */\nconst SPACE = /\\s/;\n/** A stretch of a line with nothing in it for `pieces` to do: no space, quote, `\\`, redirect or break. */\nconst PLAIN = /[^\\s\"'\\\\<>;&|`()]+/y;\n/** Words that run the next one, past options of their own: `nohup git push`, `if git push; then`. */\nconst RUNS_NEXT = /^(?:[!{]|if|then|else|elif|do|while|until|time|command|exec|builtin|nohup)$/;\n/** Programs that run a command among their arguments: `sudo -u root git push`, `sh -c \"git push\"`. */\nconst RUNS_LATER = /^(?:sudo|doas|env|nice|xargs|timeout|watch|eval|(?:ba|da|k|z)?sh)$/;\n/** `find`'s options that run the words after them: `find . -exec rm {} \\;`. */\nconst RUNS_AFTER = /^-(?:exec|execdir|ok|okdir)$/;\n\n/** A command of a shell line: its words, each as its runs of non-space characters. */\ninterface Piece {\n  words: string[][];\n  /** It starts inside a quote, so its first word began in the piece before. */\n  continued: boolean;\n}\n\n/**\n * A shell line in pieces, split at each character of `COMMAND_BREAK`, inside quotes too, and inside\n * quotes at `<` and `>` as well, since a quoted line may be one a shell runs (`sh -c \"git push 2>&1\"`).\n * Each piece holds its words as a shell splits them, quotes and `\\` taken off. Outside quotes, a\n * redirect goes with the word it names (`>out`, `2>/dev/null`, `>&2`, `<<'EOF'`), so the words on\n * either side of it are one command, as a shell runs them, and a `\\` before a line break joins the\n * lines. It reads the line once.\n */\nfunction pieces(line: string): Piece[] {\n  const out: Piece[] = [];\n  let words: string[][] = [];\n  // The word being read, as its runs so far, and the run being read.\n  let word: string[] | undefined;\n  let run = '';\n  // The quote the line is in, a quote inside it, and whether the word being read is the one a\n  // redirect names.\n  let quote = '';\n  let inner = '';\n  let target = false;\n  let continued = false;\n  const endRun = () => {\n    if (run) (word ??= []).push(run);\n    run = '';\n  };\n  const endWord = () => {\n    endRun();\n    if (word?.length && !target) words.push(word);\n    word = undefined;\n    target = false;\n  };\n  const endPiece = () => {\n    endWord();\n    out.push({ words, continued });\n    words = [];\n    inner = '';\n    continued = quote !== '';\n    if (continued) word = [];\n  };\n  // A plain stretch from `i`, added to the run at once, and where it ends.\n  const plain = (i: number) => {\n    PLAIN.lastIndex = i;\n    PLAIN.test(line);\n    run += line.slice(i, PLAIN.lastIndex);\n    return PLAIN.lastIndex - 1;\n  };\n  for (let i = 0; i < line.length; i++) {\n    const c = line[i]!;\n    const next = line[i + 1];\n    if (c === '\\\\' && quote !== \"'\") {\n      // Before a line break, `\\` joins the lines. Before a break, it leaves the break to split the\n      // line, as a quote does. In double quotes, `\\\"` is a quote to the shell the line is given to.\n      // Any other character it makes literal.\n      if (next === '\\n') i++;\n      else if (quote && next === '\"') {\n        inner = inner ? '' : next;\n        i++;\n      } else if (next !== undefined && !COMMAND_BREAK.includes(next) && !(quote && (next === '<' || next === '>'))) {\n        run += next;\n        i++;\n      }\n    } else if (quote) {\n      // A quoted line may be one a shell runs, which reads its quotes in turn: `inner`, the other\n      // quote, keeps its spaces in the run, from where it opens in the piece.\n      if (c === quote) quote = inner = '';\n      else if (c === '\"' || c === \"'\") inner = inner ? '' : c;\n      else if (COMMAND_BREAK.includes(c) || c === '<' || c === '>') endPiece();\n      else if (SPACE.test(c)) {\n        if (inner) run += c;\n        else endRun();\n      } else if (c === '\\\\') run += c;\n      else i = plain(i);\n    } else if (c === '\"' || c === \"'\") {\n      quote = c;\n      word ??= [];\n    } else if (COMMAND_BREAK.includes(c) || ((c === '<' || c === '>') && next === '(')) {\n      // `<(` and `>(` run a command of their own: the next piece.\n      endPiece();\n    } else if (c === '<' || c === '>') {\n      // A redirect. A number written against it is the descriptor it redirects, not a word.\n      if (!word && /^\\d+$/.test(run)) run = '';\n      endWord();\n      // `>>`, `<>`, `>&`, `<&`, `>|`, then `<<`, `<<<` and `<<-`.\n      if (next === '&' || next === '>' || (c === '>' && next === '|')) i++;\n      else if (c === '<' && next === '<') {\n        i++;\n        if (line[i + 1] === '<' || line[i + 1] === '-') i++;\n      }\n      while (line[i + 1] === ' ' || line[i + 1] === '\\t') i++;\n      target = true;\n    } else if (SPACE.test(c)) endWord();\n    else i = plain(i);\n  }\n  endPiece();\n  return out;\n}\n\n/**\n * Each command of a shell line (`pieces`), as its words joined by one space, with where in it the\n * command may start: its first word past `NAME=value` settings, that word without its path\n * (`/usr/bin/git` as `git`), the word after one in `RUNS_NEXT` or `RUNS_AFTER`, and every word after\n * one in `RUNS_LATER`. A quoted word a command may start at is a line a shell may run, read the same\n * way (`sh -c \"FOO=1 git push\"`), and so is the first word of a piece that starts inside a quote,\n * where the words after it may start a command too (`FOO=\"a;b\" git push`).\n */\nfunction commands(line: string): Candidate[] {\n  return pieces(line).map(({ words, continued }) => {\n    const runs = words.flat();\n    // Each run's offset in the runs joined by spaces, and each word's first run.\n    const at: number[] = [];\n    for (let k = 0, offset = 0; k < runs.length; offset += runs[k++]!.length + 1) at.push(offset);\n    const first: number[] = [];\n    for (let k = 0, run = 0; k < words.length; run += words[k++]!.length) first.push(run);\n    const texts = words.map((word) => word.join(' '));\n    const starts: number[] = [];\n    /**\n     * Where a command may start among items `k` to `end` (words, or a quoted word's runs), in one\n     * pass: the offset of each, and past its path, the program as a shell finds it.\n     */\n    const read = (\n      items: readonly string[],\n      offset: (k: number) => number,\n      nest: (k: number) => void,\n      k: number,\n      end: number,\n    ) => {\n      // Looking for the command, among its arguments, or past a program that runs any of them.\n      let state: 'command' | 'arguments' | 'any' = 'command';\n      let options = false;\n      for (; k < end; k++) {\n        const item = items[k]!;\n        if (state === 'arguments') {\n          if (RUNS_AFTER.test(item)) {\n            state = 'command';\n            options = false;\n          }\n          continue;\n        }\n        if (state === 'command' && (/^[A-Za-z_]\\w*=/.test(item) || (options && item.startsWith('-')))) continue;\n        const path = item.lastIndexOf('/') + 1;\n        starts.push(offset(k), offset(k) + path);\n        nest(k);\n        if (state === 'any') continue;\n        const name = item.slice(path);\n        if (RUNS_LATER.test(name)) state = 'any';\n        else if (RUNS_NEXT.test(name)) options = true;\n        else state = 'arguments';\n      }\n    };\n    const none = () => {};\n    const inRuns = (k: number) => read(runs, (j) => at[j]!, none, first[k]!, first[k]! + words[k]!.length);\n    const nest = (j: number) => {\n      if (words[j]!.length > 1) inRuns(j);\n    };\n    const inWords = (k: number) => read(texts, (j) => at[first[j]!]!, nest, k, words.length);\n    if (continued && words.length) {\n      inRuns(0);\n      inWords(1);\n    } else inWords(0);\n    return [runs.join(' '), starts.sort((a, b) => a - b)] as const;\n  });\n}\n\n/**\n * A text's commands (`commands`), less the matches its whole already tried: from the start of a\n * command that is the whole text, as `a`s or `npm test` are.\n */\nfunction commandsOf(text: string): Candidate[] {\n  const list: Candidate[] = [];\n  for (const [command, starts] of commands(text)) {\n    const from = command === text ? starts.filter((start) => start > 0) : starts;\n    if (from.length) list.push([command, from]);\n  }\n  return list;\n}\n\n/**\n * What a deny rule matches of some texts: each whole from its start, and then each of their\n * commands, split the first time a rule needs them.\n */\ninterface Reading {\n  whole: Candidate[];\n  commands?: Candidate[] | undefined;\n}\n\n/** Each argument as deny rules read it (`readingsOf`), worked out once for all the rules of a call. */\ntype Readings = Map<unknown, Reading[] | undefined>;\n\n/** Some texts as a deny rule reads them, each text once however often it comes. */\nconst reading = (texts: readonly string[]): Reading => ({\n  whole: [...new Set(texts)].map((text) => [text, FROM_START] as const),\n});\n\n/**\n * What a deny rule reads of an argument: a text, or an array's items and then the items joined by\n * spaces; `undefined` for one it can't read: an object, or an array with an item that isn't text.\n * Worked out once for all the rules of a call, in `readings`.\n */\nfunction readingsOf(value: unknown, readings: Readings): Reading[] | undefined {\n  if (readings.has(value)) return readings.get(value);\n  const text = argumentText(value);\n  const items = text === undefined && Array.isArray(value) ? value.map(argumentText) : [text];\n  const read = items.includes(undefined)\n    ? undefined\n    : text === undefined\n      ? [reading(items as string[]), reading([items.join(' ')])]\n      : [reading([text])];\n  readings.set(value, read);\n  return read;\n}\n\n/**\n * Whether a deny rule's pattern covers one of a reading's texts: the whole of it, as an allow rule\n * reads it, or any of its commands from where one may start (`commands`), so `git push*` denies\n * `git status && git push`. All the texts go in one pass each way, so an array's items cost what\n * their characters do, not the pattern's length each.\n */\nfunction denyMatch(texts: Reading, parts: readonly number[], budget: Budget): boolean | undefined {\n  const whole = globMatch(texts.whole, parts, false, budget);\n  if (whole !== false) return whole;\n  texts.commands ??= texts.whole.flatMap(([text]) => commandsOf(text));\n  return globMatch(texts.commands, parts, false, budget);\n}\n\nconst own = (value: object, key: string) => Object.prototype.hasOwnProperty.call(value, key);\n\n/**\n * An argument by name, as each reading of it present: the key itself, and for a dotted name the\n * nested argument too (`'options.cwd'`), since a call may carry both.\n */\nfunction argumentValues(input: unknown, name: string): unknown[] {\n  if (input === null || typeof input !== 'object') return [];\n  const values = own(input, name) ? [(input as Record<string, unknown>)[name]] : [];\n  if (!name.includes('.')) return values;\n  let value: unknown = input;\n  for (const key of name.split('.')) {\n    if (value === null || typeof value !== 'object' || !own(value, key)) return values;\n    value = (value as Record<string, unknown>)[key];\n  }\n  return [...values, value];\n}\n\n/** A string, number or boolean argument as text; anything else matches no allow pattern. */\nfunction argumentText(value: unknown): string | undefined {\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') return String(value);\n  return undefined;\n}\n\n/**\n * Whether an argument matches a pattern, or `undefined` once `budget` runs out: as text for an allow\n * rule. A deny rule reads a text's commands too, an array by its items, all in one pass, and by the\n * items joined with spaces (`readingsOf`), and covers any other object, which it can't read: it\n * fails closed.\n */\nfunction argumentMatches(\n  value: unknown,\n  parts: readonly number[],\n  deny: boolean,\n  budget: Budget,\n  readings: Readings,\n): boolean | undefined {\n  if (!deny) {\n    const text = argumentText(value);\n    return text !== undefined && globMatch([[text, FROM_START]], parts, false, budget);\n  }\n  if (value == null) return false;\n  const read = readingsOf(value, readings);\n  if (!read) return true;\n  let result: boolean | undefined = false;\n  for (const texts of read) {\n    const matched = denyMatch(texts, parts, budget);\n    if (matched) return true;\n    if (matched === undefined) result = undefined;\n  }\n  return result;\n}\n\n/**\n * Whether a rule covers a call: `true`, `false`, or `undefined` when it ran out of steps before it\n * could tell. The tool's name is read first, on steps of its own, which a name of usual length never\n * runs out of: a rule on another tool doesn't count against the call. A deny rule counts what it\n * can't read as covered: an object argument, or a `when` that throws.\n */\nfunction covers(rule: ApprovalRule, toolName: string, input: unknown, readings: Readings): boolean | undefined {\n  const deny = rule.effect !== 'allow';\n  // A tool's name is no shell command: in a deny rule, `*` and `?` match any character of it, so `*`\n  // covers every tool. An allow rule's tool pattern reads a name as its argument patterns read text.\n  const tool = globMatch([[toolName, FROM_START]], globParts(rule.tool), deny, { left: RULE_STEPS });\n  if (tool !== true) return tool;\n  const budget: Budget = { left: RULE_STEPS };\n  let result: boolean | undefined = true;\n  for (const [name, pattern] of Object.entries(rule.args ?? {})) {\n    const parts = globParts(pattern);\n    // Each reading of the argument must match for an allow rule; one does for a deny rule.\n    let matched: boolean | undefined = false;\n    for (const value of argumentValues(input, name)) {\n      const one = argumentMatches(value, parts, deny, budget, readings);\n      if (!deny && one !== true) return one;\n      if (one !== false) matched = one;\n      if (deny && one) break;\n    }\n    if (matched === false) return false;\n    if (matched === undefined) result = undefined;\n  }\n  if (rule.when) {\n    let test: boolean;\n    try {\n      test = !!rule.when(input);\n    } catch {\n      test = deny;\n    }\n    if (!test) return false;\n  }\n  return result;\n}\n\n/**\n * Whether a rule applies to a call: its tool, every argument pattern, and its own test. A deny rule\n * reads more than an allow rule, to hold when a command is written another way: each command of a\n * shell line, from its first word past `NAME=value` settings, a path and a redirect, or after `sudo`,\n * `env`, `sh -c`, `find -exec`… (see `commands`); an array by its items; and an object, or a `when`\n * that throws, as covered. Matching takes a bounded amount of work (see `evaluateRules`), and what\n * it can't finish counts against the call: an allow rule doesn't apply, a deny rule does.\n */\nexport function ruleMatches(rule: ApprovalRule, toolName: string, input: unknown): boolean {\n  return covers(rule, toolName, input, new Map()) ?? rule.effect !== 'allow';\n}\n\n/** How narrow a rule is, to report the most specific of several that match. */\nconst specificity = (rule: ApprovalRule) =>\n  (rule.tool.includes('*') || rule.tool.includes('?') ? 0 : 100) +\n  Object.keys(rule.args ?? {}).length * 10 +\n  (rule.when ? 5 : 0);\n\n/**\n * The rule that decides a call, if any. A deny rule wins over an allow rule, whatever their\n * order; among rules of the same effect the most specific is the one reported. Each rule's matching\n * takes a bounded amount of work, in proportion to the arguments it reads, an array's item counting\n * as one character at least: far more than common patterns need, however long the arguments. The\n * bound is each rule's, so a call's work grows with the number of rules times the arguments' length,\n * and a deny rule reads a string up to twice (whole, then by command) and an array up to four times\n * (all its items in one pass, each once however often it comes, then the items joined, each both\n * ways): cap the arguments where a client sends rules. A rule that runs out before it can tell\n * counts against the call: an allow rule allows nothing, and a deny rule denies, reported as\n * `unchecked` when no other deny rule covers the call.\n */\nexport function evaluateRules(rules: readonly ApprovalRule[], toolName: string, input: unknown): RuleMatch | undefined {\n  // Each argument as deny rules read it, worked out once for all the rules.\n  const readings: Readings = new Map();\n  let best: ApprovalRule | undefined;\n  let unchecked: ApprovalRule | undefined;\n  // Deny rules first: one that covers the call wins, and then no allow rule is read. A rule that\n  // can't beat the best so far by specificity isn't read either.\n  for (const rule of rules) {\n    if (rule.effect === 'allow' || (best && specificity(rule) <= specificity(best))) continue;\n    const covered = covers(rule, toolName, input, readings);\n    if (covered) best = rule;\n    else if (covered === undefined && (!unchecked || specificity(rule) > specificity(unchecked))) unchecked = rule;\n  }\n  if (best) return { effect: 'deny', rule: best };\n  if (unchecked) return { effect: 'deny', rule: unchecked, unchecked: true };\n  for (const rule of rules) {\n    if (rule.effect !== 'allow' || (best && specificity(rule) <= specificity(best))) continue;\n    if (covers(rule, toolName, input, readings) === true) best = rule;\n  }\n  return best && { effect: 'allow', rule: best };\n}\n\n/** What a decision does now, and the rule it leaves, if any. */\nexport function decisionEffect(decision: ApprovalDecision): {\n  approved: boolean;\n  scope: 'once' | 'session' | 'always';\n} {\n  const approved = decision.startsWith('allow');\n  const scope = decision.endsWith('session') ? 'session' : decision.endsWith('always') ? 'always' : 'once';\n  return { approved, scope };\n}\n\n/** Program and subcommand words of a shell command, before the first option or operator. */\nfunction commandPrefix(command: string) {\n  const words: string[] = [];\n  for (const word of command.trim().split(/\\s+/)) {\n    if (!word || word.startsWith('-') || /[;&|`<>$'\"\\\\*?]/.test(word) || words.length === 2) break;\n    words.push(word);\n  }\n  return words;\n}\n\n/**\n * Programs that run what their arguments say, by name or path: shells, interpreters, `npx`, and\n * commands that run or fetch another. Their program-and-next-word pattern would cover any code:\n * `sudo rm*` allows `sudo rm -rf /`, and `npx prettier*` allows `npx prettier-evil`.\n */\nconst RUNS_ARGUMENTS = /^(?:.*\\/)?(?:(?:ba|z)?sh|node|python[\\d.]*|sudo|env|npx|xargs|curl|wget)$/;\n\n/**\n * The argument patterns a rule made from this call would start with: for a shell command, its\n * program and subcommand (`npm test*`), or the whole command when it has no subcommand or runs what\n * its arguments say (`rm -rf build`, `node -e \"…\"`), since `rm*` would allow `rm -rf ~`; otherwise\n * each string, number and boolean argument as it is. Globs are escaped. The person can widen them\n * before saving.\n */\nexport function suggestArgs(input: unknown): Record<string, string> | undefined {\n  if (input === null || typeof input !== 'object' || Array.isArray(input)) return undefined;\n  const record = input as Record<string, unknown>;\n  if (typeof record.command === 'string') {\n    // The prefix's words have no glob characters to escape.\n    const words = commandPrefix(record.command);\n    return {\n      command:\n        words[1] && !words.some((word) => RUNS_ARGUMENTS.test(word))\n          ? `${words.join(' ')}*`\n          : record.command.replace(/[\\\\*?]/g, '\\\\$&'),\n    };\n  }\n  const out: Record<string, string> = {};\n  for (const [name, value] of Object.entries(record)) {\n    const text = argumentText(value);\n    if (text !== undefined) out[name] = text.replace(/[\\\\*?]/g, '\\\\$&');\n  }\n  return Object.keys(out).length > 0 ? out : undefined;\n}\n\nlet ruleIds = 0;\n\n/**\n * The rule a decision leaves: none for `allow-once` and `deny-once`. `args` narrows it to some\n * arguments; without it, it covers every call of the tool.\n */\nexport function ruleFromDecision(\n  decision: ApprovalDecision,\n  request: Pick<ApprovalRequest, 'toolName'>,\n  {\n    args,\n    reason,\n    id,\n    now,\n  }: { args?: Record<string, string> | undefined; reason?: string; id?: string; now?: number } = {},\n): ApprovalRule | undefined {\n  const { approved, scope } = decisionEffect(decision);\n  if (scope === 'once') return undefined;\n  return {\n    id: id ?? `rule-${Date.now().toString(36)}-${++ruleIds}`,\n    tool: request.toolName.replace(/[\\\\*?]/g, '\\\\$&'),\n    ...(args && Object.keys(args).length > 0 ? { args: { ...args } } : {}),\n    effect: approved ? 'allow' : 'deny',\n    scope: scope === 'session' ? 'session' : 'always',\n    createdAt: now ?? Date.now(),\n    ...(reason ? { reason } : {}),\n  };\n}\n\n/** A rule in words: \"run_command with command npm test*\". */\nexport function describeRule(rule: Pick<ApprovalRule, 'tool' | 'args'>): string {\n  const args = Object.entries(rule.args ?? {});\n  const tool = rule.tool === '*' ? 'any tool' : rule.tool.replace(/\\\\(.)/g, '$1');\n  return args.length === 0 ? `${tool}, any arguments` : `${tool} with ${args.map(([k, v]) => `${k} ${v}`).join(', ')}`;\n}\n\n/* AI SDK 7: the same rules on the server, for `streamText({ toolApproval })`. */\n\n/** AI SDK 7's `ToolApprovalStatus`, as `toToolApproval` returns it. */\nexport type ToolApprovalStatusLike =\n  | 'not-applicable'\n  | 'approved'\n  | 'denied'\n  | 'user-approval'\n  | { type: 'approved' | 'denied' | 'user-approval'; reason?: string };\n\n/** How `toToolApproval` answers: for the calls no rule covers, and in the reason a rule gives. */\nexport interface ToToolApprovalOptions {\n  /**\n   * What a call no rule covers gets. Default `'user-approval'`: a person decides.\n   * `'not-applicable'` leaves the call to another `toolApproval`, such as a second set of rules.\n   */\n  otherwise?: ToolApprovalStatusLike | undefined;\n  /**\n   * The reason for a call a rule decides, which the approval keeps as `approval.reason`: say whose\n   * rules these are, so a page can tell the server's from the person's. Default: \"Allowed by a\n   * rule: …\" or \"Denied by a rule: …\", the rule in words (`describeRule`), then its own reason; for\n   * an `unchecked` match, \"Denied: the arguments are too long to check against a rule: …\".\n   */\n  reason?: ((match: RuleMatch) => string) | undefined;\n}\n\n/**\n * The reason `toToolApproval` gives unless told otherwise: \"Denied by a rule: rm * (No deletes)\", or\n * for an `unchecked` rule \"Denied: the arguments are too long to check against a rule: …\".\n */\nfunction ruleReason({ effect, rule, unchecked }: RuleMatch) {\n  if (unchecked) return `Denied: the arguments are too long to check against a rule: ${describeRule(rule)}`;\n  return `${effect === 'allow' ? 'Allowed' : 'Denied'} by a rule: ${describeRule(rule)}${\n    rule.reason ? ` (${rule.reason})` : ''\n  }`;\n}\n\n/**\n * Rules as AI SDK 7's generic `toolApproval` function: a matching rule approves or denies the call\n * on the server, with the rule in the reason (`reason` words it), and any other call gets\n * `otherwise` (by default `'user-approval'`, a person decides). The SDK checks it again on the\n * approved call before it runs, edited arguments included.\n *\n * Rules a client sends are the choices of the person using it: take them for that person's own\n * runs only, and keep rules that protect others on the server.\n */\nexport function toToolApproval(\n  rules: readonly ApprovalRule[] | (() => readonly ApprovalRule[]),\n  { otherwise = 'user-approval', reason = ruleReason }: ToToolApprovalOptions = {},\n): (options: { toolCall: { toolName: string; input: unknown } }) => ToolApprovalStatusLike {\n  return ({ toolCall }) => {\n    const match = evaluateRules(typeof rules === 'function' ? rules() : rules, toolCall.toolName, toolCall.input);\n    if (!match) return otherwise;\n    return { type: match.effect === 'allow' ? 'approved' : 'denied', reason: reason(match) };\n  };\n}\n\n/** A decision as the response `addToolApprovalResponse` (from `useChat`) takes. */\nexport function toToolApprovalResponse(\n  id: string,\n  decision: ApprovalDecision,\n  reason?: string,\n): { id: string; approved: boolean; reason?: string } {\n  const { approved } = decisionEffect(decision);\n  return reason ? { id, approved, reason } : { id, approved };\n}\n\n/**\n * Messages with one tool call's input replaced, for approving edited arguments with AI SDK 7: set\n * them with `setMessages` (from `useChat`), then answer the approval. The server runs the call with the\n * input in the messages, after checking it against the tool's schema and `toolApproval` again.\n * When the tool's schema changed what the model sent (a default filled in, a value coerced, a key\n * dropped), the approval keeps what the model sent as `inputSchemaInput`, and the server checks the\n * call against it, so it gets the edit too. The server runs only an edit that comes out of the\n * schema unchanged, and out of `experimental_refineToolInput` too when that is set: keep the fields\n * the schema fills in (the card starts an edit from the input it shows, defaults included), and use\n * transforms that give the same result when run twice.\n * With `experimental_toolApprovalSecret` set, the server signs the input it asked about and refuses\n * any other, so edits fail there by design.\n */\nexport function setToolInput<M extends { parts: readonly unknown[] }>(\n  messages: readonly M[],\n  toolCallId: string,\n  input: unknown,\n): M[] {\n  return messages.map((message) => {\n    const index = message.parts.findIndex(\n      (part) =>\n        typeof part === 'object' &&\n        part !== null &&\n        (part as { toolCallId?: unknown }).toolCallId === toolCallId &&\n        'input' in part,\n    );\n    if (index === -1) return message;\n    const parts = [...message.parts];\n    const part = parts[index] as { approval?: unknown };\n    const { approval } = part;\n    parts[index] =\n      typeof approval === 'object' && approval !== null && 'inputSchemaInput' in approval\n        ? { ...part, input, approval: { ...approval, inputSchemaInput: input } }\n        : { ...part, input };\n    return { ...message, parts };\n  });\n}\n\n/* A person's rules with each request: plain data from the page, checked again on the server. */\n\n/**\n * A tool pattern's literal start, and its literal end backwards: what comes before its first\n * wildcard, and after its last. A `\\` escape counts as a wildcard too, which can only make the\n * pattern seem to match more. Each has a `\\uffff` where the pattern starts or ends, so one with no\n * wildcard can't meet a pattern that needs more characters than it has.\n */\nfunction ends(tool: string): string[] {\n  const runs = `\\uffff${tool}\\uffff`.split(/\\\\[\\s\\S]|[*?]/);\n  return [runs[0]!, runs.at(-1)!.split('').reverse().join('')];\n}\n\n/**\n * Whether two tool patterns, as `ends`, could match one name: of their literal starts one starts\n * the other, and so it is with their ends. It can say yes for two that never meet, never no for\n * two that do.\n */\nconst mayOverlap = (x: string[], y: string[]) =>\n  x.every((end, i) => end.slice(0, y[i]!.length) === y[i]!.slice(0, end.length));\n\n/**\n * The rules less the allow rules that left-out deny rules would overrule: those on a tool one of\n * them could name. The calls they cover then go to the page, which has every rule.\n */\nfunction withoutOverruled(rules: ApprovalRule[], leftOut: string[]): ApprovalRule[] {\n  // Each pattern's ends once: a pair then costs only the two compares in `mayOverlap`.\n  const denied = leftOut.map(ends);\n  return rules.filter((rule) => {\n    const tool = rule.effect === 'allow' && ends(rule.tool);\n    return !tool || !denied.some((other) => mayOverlap(tool, other));\n  });\n}\n\n/**\n * Rules as plain data, to send with a request: copies, as JSON carries them. A rule with a `when`\n * is left out, since `when` is code and without it the rule would cover more calls than it does on\n * the page. For a deny rule with a `when`, so are the allow rules on the tools it covers, which it\n * would overrule on the page: the server asks about those calls, and the page answers them with\n * every rule.\n */\nexport function toPlainRules(rules: readonly ApprovalRule[]): ApprovalRule[] {\n  const sent = rules.filter((rule) => !rule.when);\n  const leftOut = rules.filter((rule) => rule.when && rule.effect === 'deny').map((rule) => rule.tool);\n  return JSON.parse(JSON.stringify(withoutOverruled(sent, leftOut))) as ApprovalRule[];\n}\n\n/** What `parseApprovalRules` accepts from a client. */\nexport interface ApprovalRuleLimits {\n  /** How many rules are read: those after the first `maxRules` are left out. Default 100. */\n  maxRules?: number | undefined;\n  /** Argument patterns in one rule. Default 20. */\n  maxArgs?: number | undefined;\n  /** Characters in one string: an id, a tool, an argument's name or pattern, a reason. Default 500. */\n  maxLength?: number | undefined;\n  /**\n   * `*` wildcards in one pattern, `**` counting as one. Default 3, enough for a rule on what a\n   * command contains (`git push*--force*`). Matching takes the argument's length times the\n   * pattern's, whatever the number of `*`; `evaluateRules` bounds what each rule takes.\n   */\n  maxWildcards?: number | undefined;\n}\n\n/** The `*` wildcards in a pattern: a run of them counts once, an escaped one not at all. */\nfunction wildcards(pattern: string) {\n  let count = 0;\n  for (let i = 0; i < pattern.length; i++) {\n    if (pattern[i] === '\\\\') i++;\n    else if (pattern[i] === '*') {\n      count++;\n      while (pattern[i + 1] === '*') i++;\n    }\n  }\n  return count;\n}\n\n/** Tools named by the deny rules `parseApprovalRules` leaves out: past this many, it keeps no allow rule. */\nconst MAX_LEFT_OUT_TOOLS = 10;\n\n/**\n * The rules a client sent, such as a request body's `rules`, checked on the server: each field of\n * the right type and within `limits`, other fields dropped. A rule that fails a check is left out,\n * and so is everything when `value` is not an array. A deny rule left out takes with it the allow\n * rules it could overrule: those on a tool it names, or all of them when its tool is missing, not\n * a string or too long, when it comes after the first `maxRules`, or when the deny rules left out\n * name more than 10 tools. A rule left out still holds on the page, which answers the call when the\n * server asks.\n */\nexport function parseApprovalRules(\n  value: unknown,\n  { maxRules = 100, maxArgs = 20, maxLength = 500, maxWildcards = 3 }: ApprovalRuleLimits = {},\n): ApprovalRule[] {\n  if (!Array.isArray(value)) return [];\n  const text = (v: unknown): v is string => typeof v === 'string' && v.length <= maxLength;\n  const pattern = (v: unknown): v is string => text(v) && wildcards(v) <= maxWildcards;\n  const rules: ApprovalRule[] = [];\n  // The tool of each deny rule left out: `undefined` when it can't bound the calls the rule covers.\n  const leftOut: Array<string | undefined> = [];\n  for (const item of value.slice(0, maxRules)) {\n    if (!item || typeof item !== 'object' || Array.isArray(item)) continue;\n    const { id, tool, args, effect, scope, createdAt, reason } = item as Record<string, unknown>;\n    // A deny rule counts as left out until it passes every check.\n    if (effect === 'deny') leftOut.push(text(tool) ? tool : undefined);\n    if (!text(id) || !pattern(tool)) continue;\n    if ((effect !== 'allow' && effect !== 'deny') || (scope !== 'session' && scope !== 'always')) continue;\n    if ((createdAt !== undefined && !Number.isFinite(createdAt)) || (reason !== undefined && !text(reason))) continue;\n    let checked: Record<string, string> | undefined;\n    if (args !== undefined) {\n      if (!args || typeof args !== 'object' || Array.isArray(args)) continue;\n      const entries = Object.entries(args);\n      if (entries.length > maxArgs || !entries.every(([name, glob]) => text(name) && pattern(glob))) continue;\n      checked = Object.fromEntries(entries) as Record<string, string>;\n    }\n    if (effect === 'deny') leftOut.pop();\n    rules.push({\n      id,\n      tool,\n      ...(checked ? { args: checked } : {}),\n      effect,\n      scope,\n      ...(createdAt !== undefined ? { createdAt: createdAt as number } : {}),\n      ...(reason !== undefined ? { reason } : {}),\n    });\n  }\n  const tools = new Set(leftOut);\n  // A deny rule whose tool can't be read, or one past `maxRules`, could be on any tool. Past a few\n  // tools, no allow rule stays either: each one is checked against each tool, so the check grows\n  // with the number of rules, not its square.\n  const anyTool =\n    tools.has(undefined) ||\n    tools.size > MAX_LEFT_OUT_TOOLS ||\n    value.slice(maxRules).some((item) => item?.effect === 'deny');\n  if (anyTool) return rules.filter((rule) => rule.effect === 'deny');\n  return tools.size ? withoutOverruled(rules, [...tools] as string[]) : rules;\n}\n\n/* Agent Client Protocol: `session/request_permission`, typed here so nothing new is installed. */\n\n/** ACP `PermissionOptionKind`. */\nexport type AcpPermissionOptionKind = 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always';\n\n/** ACP `PermissionOption`: a choice the agent offers. */\nexport interface AcpPermissionOption {\n  optionId: string;\n  name: string;\n  kind: AcpPermissionOptionKind;\n}\n\n/** What `toAcpPermissionResponse` reads of ACP's `RequestPermissionRequest`. */\nexport interface AcpRequestPermissionRequest {\n  sessionId: string;\n  toolCall: {\n    toolCallId: string;\n    title?: string | null | undefined;\n    /** The tool's programmatic name, when the agent sends one (ACP 1.8). */\n    name?: string | null | undefined;\n    kind?: string | null | undefined;\n    rawInput?: unknown;\n  };\n  options: readonly AcpPermissionOption[];\n}\n\n/** ACP `RequestPermissionResponse`. */\nexport interface AcpRequestPermissionResponse {\n  outcome: { outcome: 'cancelled' } | { outcome: 'selected'; optionId: string };\n}\n\nconst ACP_KIND: Record<AcpPermissionOptionKind, ApprovalDecision> = {\n  allow_once: 'allow-once',\n  allow_always: 'allow-always',\n  reject_once: 'deny-once',\n  reject_always: 'deny-always',\n};\n\n/**\n * The tool name rules and cards use for an ACP tool call: its programmatic `name` when the agent\n * sends one, else its `kind` (`edit`, `execute`…), else its `title`.\n */\nexport function acpToolName(toolCall: {\n  name?: string | null | undefined;\n  kind?: string | null | undefined;\n  title?: string | null | undefined;\n}): string {\n  return toolCall.name || toolCall.kind || toolCall.title || 'tool';\n}\n\n/** An ACP permission request as the card's request: the tool call's id, name, and raw input. */\nexport function fromAcpPermissionRequest(request: AcpRequestPermissionRequest): ApprovalRequest & { title?: string } {\n  const { toolCall } = request;\n  return {\n    id: toolCall.toolCallId,\n    toolCallId: toolCall.toolCallId,\n    toolName: acpToolName(toolCall),\n    input: toolCall.rawInput,\n    ...(toolCall.title ? { title: toolCall.title } : {}),\n  };\n}\n\n/**\n * The option a decision answers: the agent's only option of that kind, `allow_once` for\n * `allow-session`. None when the agent sent several, as they grant different things. `deny-once`\n * takes the agent's first `reject_once` even then: a \"no\" grants nothing, and the card can always\n * decline.\n */\nfunction acpOption(decision: ApprovalDecision, options: readonly AcpPermissionOption[]) {\n  const want = decision === 'allow-session' ? 'allow-once' : decision;\n  const matching = options.filter((o) => ACP_KIND[o.kind] === want);\n  return matching.length === 1 || want === 'deny-once' ? matching[0] : undefined;\n}\n\n/**\n * The decisions to offer for an ACP request: one per kind of option the agent sent, plus\n * `allow-session`, which the client keeps as a rule of its own (ACP has no session option). A kind\n * the agent sent several options of is left out, since a button can't say which one it picks:\n * Claude Code's ExitPlanMode sends up to three `allow_always` options, one of them clearing the\n * context and switching to auto mode, so it gets Approve and Deny but no Always. Deny stays\n * whenever the agent sent a `reject_once`, and answers its first one.\n */\nexport function decisionsFromAcpOptions(options: readonly AcpPermissionOption[]): ApprovalDecision[] {\n  return APPROVAL_DECISIONS.filter((d) => acpOption(d, options));\n}\n\n/**\n * A decision as ACP's response: the agent's one option of the same kind. `allow-session` selects\n * `allow_once`: the session rule stays on the client, so it never grants more than the agent's\n * \"once\". With no option of that kind, or several, the request is cancelled, as ACP asks of a\n * client that can't answer: it never picks one of several grants for the person. `deny-once`\n * answers the first of several `reject_once` options, since a denial grants nothing.\n */\nexport function toAcpPermissionResponse(\n  decision: ApprovalDecision,\n  options: readonly AcpPermissionOption[],\n): AcpRequestPermissionResponse {\n  const option = acpOption(decision, options);\n  return option\n    ? { outcome: { outcome: 'selected', optionId: option.optionId } }\n    : { outcome: { outcome: 'cancelled' } };\n}\n\n/** An ACP response as the decision it records, or `cancelled`. */\nexport function fromAcpPermissionResponse(\n  response: AcpRequestPermissionResponse,\n  options: readonly AcpPermissionOption[],\n): ApprovalDecision | 'cancelled' {\n  if (response.outcome.outcome === 'cancelled') return 'cancelled';\n  const { optionId } = response.outcome;\n  const option = options.find((o) => o.optionId === optionId);\n  return option ? ACP_KIND[option.kind] : 'cancelled';\n}\n",
      "type": "registry:lib",
      "target": "components/signoff-ui/lib/policy.ts"
    }
  ],
  "cssVars": {
    "theme": {
      "color-signoff-bg": "var(--signoff-bg)",
      "color-signoff-surface": "var(--signoff-surface)",
      "color-signoff-surface-2": "var(--signoff-surface-2)",
      "color-signoff-border": "var(--signoff-border)",
      "color-signoff-border-strong": "var(--signoff-border-strong)",
      "color-signoff-fg": "var(--signoff-fg)",
      "color-signoff-fg-muted": "var(--signoff-fg-muted)",
      "color-signoff-fg-subtle": "var(--signoff-fg-subtle)",
      "color-signoff-accent": "var(--signoff-accent)",
      "color-signoff-accent-fg": "var(--signoff-accent-fg)",
      "color-signoff-on-accent": "var(--signoff-on-accent)",
      "color-signoff-hot": "var(--signoff-hot)",
      "color-signoff-hot-fg": "var(--signoff-hot-fg)",
      "color-signoff-on-hot": "var(--signoff-on-hot)",
      "color-signoff-warn": "var(--signoff-warn)",
      "color-signoff-warn-fg": "var(--signoff-warn-fg)",
      "color-signoff-ring": "var(--signoff-ring)",
      "color-signoff-add": "var(--signoff-add-bg)",
      "color-signoff-add-strong": "var(--signoff-add-strong)",
      "color-signoff-del": "var(--signoff-del-bg)",
      "color-signoff-del-strong": "var(--signoff-del-strong)",
      "color-signoff-chart-input": "var(--signoff-chart-input)",
      "color-signoff-chart-output": "var(--signoff-chart-output)",
      "color-signoff-code-keyword": "var(--signoff-code-keyword)",
      "color-signoff-code-string": "var(--signoff-code-string)",
      "color-signoff-code-number": "var(--signoff-code-number)",
      "color-signoff-code-comment": "var(--signoff-code-comment)",
      "color-signoff-code-punctuation": "var(--signoff-code-punctuation)",
      "radius-signoff": "var(--signoff-radius)",
      "font-signoff-sans": "var(--signoff-font-sans)",
      "font-signoff-mono": "var(--signoff-font-mono)",
      "animate-signoff-shimmer": "signoff-shimmer 2.2s linear infinite",
      "animate-signoff-ping": "signoff-ping 1.6s cubic-bezier(0, 0, 0.2, 1) infinite",
      "animate-signoff-spin": "signoff-spin 0.9s linear infinite",
      "animate-signoff-blink": "signoff-blink 1.1s steps(2, start) infinite",
      "animate-signoff-enter": "signoff-enter 0.32s cubic-bezier(0.2, 0.7, 0.2, 1) backwards",
      "animate-signoff-indeterminate": "signoff-indeterminate 1.4s ease-in-out infinite",
      "animate-signoff-expand": "signoff-expand 0.22s cubic-bezier(0.2, 0.7, 0.2, 1)",
      "animate-signoff-collapse": "signoff-collapse 0.18s ease-in"
    },
    "light": {
      "signoff-bg": "#ffffff",
      "signoff-surface": "#f6f7f9",
      "signoff-surface-2": "#eef0f3",
      "signoff-border": "#e2e5ea",
      "signoff-border-strong": "#cdd2d9",
      "signoff-fg": "#0d0f12",
      "signoff-fg-muted": "#4b5563",
      "signoff-fg-subtle": "#5f6875",
      "signoff-accent": "#0e7490",
      "signoff-accent-fg": "#155e75",
      "signoff-on-accent": "#ffffff",
      "signoff-hot": "#be185d",
      "signoff-hot-fg": "#9d174d",
      "signoff-on-hot": "#ffffff",
      "signoff-warn": "#b45309",
      "signoff-warn-fg": "#92400e",
      "signoff-ring": "#0e7490",
      "signoff-add-bg": "rgb(8 145 178 / 0.08)",
      "signoff-add-strong": "rgb(8 145 178 / 0.16)",
      "signoff-del-bg": "rgb(190 24 93 / 0.07)",
      "signoff-del-strong": "rgb(190 24 93 / 0.14)",
      "signoff-chart-input": "#0891b2",
      "signoff-chart-output": "#db2777",
      "signoff-code-keyword": "#155e75",
      "signoff-code-string": "#9a3412",
      "signoff-code-number": "#9d174d",
      "signoff-code-comment": "#525b67",
      "signoff-code-punctuation": "#4b5563",
      "signoff-radius": "0.75rem",
      "signoff-font-sans": "var(--font-sans, var(--font-geist-sans, ui-sans-serif, system-ui, sans-serif))",
      "signoff-font-mono": "var(--font-mono, var(--font-geist-mono, ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace))"
    },
    "dark": {
      "signoff-bg": "#0d0f12",
      "signoff-surface": "#181c22",
      "signoff-surface-2": "#1e232a",
      "signoff-border": "#262b33",
      "signoff-border-strong": "#353c47",
      "signoff-fg": "#e8eaed",
      "signoff-fg-muted": "#a1a9b4",
      "signoff-fg-subtle": "#8b94a0",
      "signoff-accent": "#22d3ee",
      "signoff-accent-fg": "#67e8f9",
      "signoff-on-accent": "#0d0f12",
      "signoff-hot": "#f0468a",
      "signoff-hot-fg": "#f472a8",
      "signoff-on-hot": "#0d0f12",
      "signoff-warn": "#fbbf24",
      "signoff-warn-fg": "#fcd34d",
      "signoff-ring": "#67e8f9",
      "signoff-add-bg": "rgb(34 211 238 / 0.08)",
      "signoff-add-strong": "rgb(34 211 238 / 0.14)",
      "signoff-del-bg": "rgb(240 70 138 / 0.08)",
      "signoff-del-strong": "rgb(240 70 138 / 0.26)",
      "signoff-chart-input": "#11a2bc",
      "signoff-chart-output": "#f0468a",
      "signoff-code-keyword": "#67e8f9",
      "signoff-code-string": "#f5c27a",
      "signoff-code-number": "#f9a8d4",
      "signoff-code-comment": "#a1a9b4",
      "signoff-code-punctuation": "#a1a9b4"
    }
  },
  "css": {
    "@keyframes signoff-shimmer": {
      "from": {
        "background-position": "200% 0"
      },
      "to": {
        "background-position": "-200% 0"
      }
    },
    "@keyframes signoff-ping": {
      "0%": {
        "transform": "scale(1)",
        "opacity": "0.7"
      },
      "80%, 100%": {
        "transform": "scale(2.2)",
        "opacity": "0"
      }
    },
    "@keyframes signoff-spin": {
      "to": {
        "transform": "rotate(360deg)"
      }
    },
    "@keyframes signoff-blink": {
      "to": {
        "visibility": "hidden"
      }
    },
    "@keyframes signoff-enter": {
      "from": {
        "opacity": "0",
        "transform": "translateY(4px)"
      },
      "to": {
        "opacity": "1",
        "transform": "none"
      }
    },
    "@keyframes signoff-expand": {
      "from": {
        "height": "0",
        "opacity": "0"
      },
      "to": {
        "height": "var(--radix-collapsible-content-height)",
        "opacity": "1"
      }
    },
    "@keyframes signoff-collapse": {
      "from": {
        "height": "var(--radix-collapsible-content-height)",
        "opacity": "1"
      },
      "to": {
        "height": "0",
        "opacity": "0"
      }
    },
    "@keyframes signoff-indeterminate": {
      "0%": {
        "transform": "translateX(-100%)"
      },
      "100%": {
        "transform": "translateX(250%)"
      }
    }
  },
  "type": "registry:component",
  "meta": {
    "version": "0.14.1",
    "unreleasedChanges": false
  }
}
