{"version":3,"sources":["../src/errors.ts","../src/http/retry.ts","../src/http/schema.ts","../src/http/client.ts","../src/telemetry.ts","../src/middleware.ts","../src/risk-manifest.ts","../src/tool-approval.ts","../src/jurisdiction.ts","../src/jurisdictions/ar.ts","../src/rails/accounting.ts","../src/rails/open-usd.ts"],"names":["round2"],"mappings":";;;AAwBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EAC9B,IAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CAAY,SAAiB,IAAA,EAAyB;AACpD,IAAA,KAAA,CAAM,OAAA,EAAS,KAAK,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,IAAA,CAAK,KAAA,EAAM,GAAI,MAAS,CAAA;AAC3E,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,SAAA,GAAY,KAAK,SAAA,IAAa,KAAA;AACnC,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA,CAAK,OAAA,IAAW,EAAC;AAAA,EAClC;AACF;AAGO,IAAM,uBAAA,GAAN,cAAsC,aAAA,CAAc;AAAA,EAChD,KAAA;AAAA,EACT,WAAA,CAAY,KAAA,EAAe,OAAA,EAAiB,OAAA,EAAmC;AAC7E,IAAA,KAAA,CAAM,CAAA,QAAA,EAAW,KAAK,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA,EAAI;AAAA,MACpC,IAAA,EAAM,mBAAA;AAAA,MACN,SAAA,EAAW,KAAA;AAAA,MACX,OAAA,EAAS,EAAE,GAAG,OAAA,EAAS,KAAA;AAAM,KAC9B,CAAA;AACD,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AACZ,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AACF;AAeO,IAAM,+BAAA,GAAN,cAA8C,aAAA,CAAc;AAAA,EACxD,KAAA;AAAA,EACT,WA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AAA,CAAS,KAAA,EAAO,EAAA,EAAI,IAAA,CAAK,EAAA,EAAI,aAAA,EAAe,QAAA,EAAU,IAAI,CAAA;AAAA,IAChH;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Error base + taxonomy primitives for @ar-agents/*.\n *\n * Every package SHOULD extend `ArAgentsError` for its own typed\n * errors so callers can rely on:\n *\n *   - `code: string` — machine-readable identifier\n *   - `retryable: boolean` — whether the caller should backoff + retry\n *   - `context: Record<string, unknown>` — structured ctx for logs\n *\n * Use the helper subclasses when the situation matches; subclass them\n * for jurisdiction/service-specific cases.\n */\n\nexport interface ArAgentsErrorInit {\n  code: string;\n  /** Retry after backoff? Defaults to false. */\n  retryable?: boolean;\n  /** Structured context attached to the error. Never include secrets. */\n  context?: Record<string, unknown>;\n  /** Underlying cause. */\n  cause?: unknown;\n}\n\nexport class ArAgentsError extends Error {\n  readonly code: string;\n  readonly retryable: boolean;\n  readonly context: Record<string, unknown>;\n\n  constructor(message: string, init: ArAgentsErrorInit) {\n    super(message, init.cause !== undefined ? { cause: init.cause } : undefined);\n    this.name = \"ArAgentsError\";\n    this.code = init.code;\n    this.retryable = init.retryable ?? false;\n    this.context = init.context ?? {};\n  }\n}\n\n/** Caller passed bad input. Do NOT retry. */\nexport class ArAgentsValidationError extends ArAgentsError {\n  readonly field: string;\n  constructor(field: string, message: string, context?: Record<string, unknown>) {\n    super(`Invalid ${field}: ${message}`, {\n      code: \"validation_failed\",\n      retryable: false,\n      context: { ...context, field },\n    });\n    this.name = \"ArAgentsValidationError\";\n    this.field = field;\n  }\n}\n\n/**\n * Upstream returned a 2xx body whose SHAPE failed the response schema.\n *\n * This is the single most important error in the SDK's live-integration\n * story: it is what turns a malformed / partial / silently-changed API\n * response into a LOUD failure instead of letting `?? 0 / ?? [] / ?? false`\n * defaults fabricate a clean, creditworthy, zero-debt, invoiced, or canceled\n * result. Distinct from {@link ArAgentsValidationError} (bad *caller* input) so\n * a caller can tell \"I sent garbage\" apart from \"the State/bank sent garbage.\"\n *\n * NOT retryable: a contract mismatch does not fix itself on backoff. Surface it\n * — a human needs to look at whether the upstream shape drifted.\n */\nexport class ArAgentsResponseValidationError extends ArAgentsError {\n  readonly field: string;\n  constructor(field: string, message: string, context?: Record<string, unknown>) {\n    super(`Response validation failed at ${field}: ${message}`, {\n      code: \"response_validation_failed\",\n      retryable: false,\n      context: { ...context, field },\n    });\n    this.name = \"ArAgentsResponseValidationError\";\n    this.field = field;\n  }\n}\n\n/** Adapter not wired. Surface to the operator. */\nexport class ArAgentsUnconfiguredError extends ArAgentsError {\n  constructor(\n    operation: string,\n    label = \"unconfigured\",\n    context?: Record<string, unknown>,\n  ) {\n    super(`Operation \"${operation}\" is not configured (${label}).`, {\n      code: \"unconfigured\",\n      retryable: false,\n      context: { ...context, operation, label },\n    });\n    this.name = \"ArAgentsUnconfiguredError\";\n  }\n}\n\n/** Auth rejected (token missing / expired / wrong scope). Don't retry blindly. */\nexport class ArAgentsAuthError extends ArAgentsError {\n  constructor(message: string, context?: Record<string, unknown>) {\n    super(message, {\n      code: \"auth_failed\",\n      retryable: false,\n      context: context ?? {},\n    });\n    this.name = \"ArAgentsAuthError\";\n  }\n}\n\n/** Rate limit hit. Honors `retryAfterMs` for the caller's backoff loop. */\nexport class ArAgentsRateLimitError extends ArAgentsError {\n  readonly retryAfterMs: number;\n  constructor(retryAfterMs: number, context?: Record<string, unknown>) {\n    super(`Rate limit exceeded; retry in ${retryAfterMs}ms.`, {\n      code: \"rate_limited\",\n      retryable: true,\n      context: { ...context, retryAfterMs },\n    });\n    this.name = \"ArAgentsRateLimitError\";\n    this.retryAfterMs = retryAfterMs;\n  }\n}\n\n/** Network / HTTP / upstream-service-down. Generally safe to retry. */\nexport class ArAgentsProtocolError extends ArAgentsError {\n  readonly status: number | null;\n  constructor(\n    message: string,\n    init: { status?: number | null; context?: Record<string, unknown>; cause?: unknown } = {},\n  ) {\n    super(message, {\n      code: \"protocol_error\",\n      retryable: true,\n      context: { ...init.context, status: init.status ?? null },\n      cause: init.cause,\n    });\n    this.name = \"ArAgentsProtocolError\";\n    this.status = init.status ?? null;\n  }\n}\n\n/**\n * Type guard for any `@ar-agents/*` error. Use in switch logic:\n *\n *   try { ... } catch (e) {\n *     if (isArAgentsError(e) && e.retryable) backoffAndRetry();\n *     else throw e;\n *   }\n */\nexport function isArAgentsError(value: unknown): value is ArAgentsError {\n  return value instanceof Error && (value as ArAgentsError).code !== undefined;\n}\n","// HTTP retry with exponential backoff + jitter.\n//\n// Lifted from @ar-agents/mercadolibre's battle-tested transport into core so\n// every adapter shares ONE retry policy instead of re-inventing it (or, worse,\n// shipping none). Retries 5xx + 429 + network/timeout errors, honors\n// `Retry-After`, and — critically — only retries NON-idempotent methods\n// (POST/PATCH) when the caller explicitly marks the request safe. Without that\n// guard a timeout-after-write duplicates a payment, an invoice, or a shipment.\n\nexport interface HttpRetryOptions {\n  /** Max attempts (including the first). Default 4. */\n  maxAttempts?: number;\n  /** Base delay in ms before the first retry. Default 200. */\n  baseDelayMs?: number;\n  /** Max delay between retries in ms. Default 8000. */\n  maxDelayMs?: number;\n  /** Jitter factor 0..1. Default 0.3 (±30%). */\n  jitter?: number;\n  /** Fired before each retry (attempt is 1-based, pre-increment). */\n  onRetry?: (attempt: number, lastError: unknown) => void;\n}\n\nconst DEFAULTS = {\n  maxAttempts: 4,\n  baseDelayMs: 200,\n  maxDelayMs: 8000,\n  jitter: 0.3,\n} as const;\n\nexport interface RetryDecision {\n  shouldRetry: boolean;\n  /** Override delay (e.g. from a `Retry-After` header), in ms. */\n  delayMsOverride?: number;\n}\n\nexport interface RetryContext {\n  /** HTTP method of the request, uppercase. Default \"GET\". */\n  method?: string;\n  /** Attempt number (1-based). */\n  attempt?: number;\n  /**\n   * Explicit override of method-based idempotency. When set it wins: pass\n   * `true` for a POST that is safe to retry (idempotent endpoint or an\n   * Idempotency-Key header), `false` to forbid retrying an otherwise-idempotent\n   * method. Undefined → derive from {@link IDEMPOTENT_METHODS}.\n   */\n  idempotent?: boolean;\n}\n\n/** A function that decides whether a thrown error / response is retryable. */\nexport type RetryClassifier = (\n  error: unknown,\n  response: Response | null,\n  ctx?: RetryContext,\n) => RetryDecision;\n\n/** HTTP methods safe to retry by default (RFC 9110 idempotent set). */\nexport const IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([\n  \"GET\",\n  \"HEAD\",\n  \"OPTIONS\",\n  \"PUT\",\n  \"DELETE\",\n]);\n\n/** Parse a `Retry-After` header value: integer seconds OR HTTP-date → ms. */\nexport function parseRetryAfter(value: string): number | null {\n  const seconds = Number.parseInt(value, 10);\n  if (Number.isFinite(seconds) && String(seconds) === value.trim()) {\n    return seconds * 1000;\n  }\n  const dateMs = Date.parse(value);\n  if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now());\n  return null;\n}\n\n/**\n * Default classifier — retry on 5xx, 429, and network/timeout errors, but only\n * for idempotent requests (see {@link RetryContext.idempotent}).\n *\n * - **429**: retryable only if idempotent — honors `Retry-After`. A\n *   non-idempotent money POST is NOT retried on a 429 (double-spend risk).\n * - **5xx**: retry only if idempotent — a gateway can persist a write after a\n *   5xx (split-brain), so retrying a POST risks a duplicate.\n * - **network error**: retry if idempotent.\n * - **our own timeout** (`TimeoutError` from `AbortSignal.timeout`): retry if\n *   idempotent — the attempt was abandoned before a response.\n * - **caller cancellation** (`AbortError`): never retry — the caller asked to\n *   stop.\n */\nexport const defaultRetryClassifier: RetryClassifier = (error, response, ctx) => {\n  const method = ctx?.method?.toUpperCase() ?? \"GET\";\n  const idempotent = ctx?.idempotent ?? IDEMPOTENT_METHODS.has(method);\n\n  if (response) {\n    if (response.status === 429) {\n      // A 429 is only safe to retry on an idempotent request. Retrying a\n      // non-idempotent money POST on a 429 can double-spend: the server may\n      // have rate-limited AFTER partially processing (or the retry itself\n      // re-submits an order). Gate on idempotency exactly like 5xx — callers\n      // whose POST is genuinely safe opt in with `idempotent: true`.\n      if (!idempotent) return { shouldRetry: false };\n      const retryAfter = response.headers.get(\"Retry-After\");\n      if (retryAfter) {\n        const delayMs = parseRetryAfter(retryAfter);\n        if (delayMs !== null) return { shouldRetry: true, delayMsOverride: delayMs };\n      }\n      return { shouldRetry: true };\n    }\n    if (response.status >= 500 && response.status < 600) {\n      return { shouldRetry: idempotent };\n    }\n    return { shouldRetry: false };\n  }\n\n  if (error instanceof Error) {\n    // Caller cancelled — respect it, never retry.\n    if (error.name === \"AbortError\") return { shouldRetry: false };\n    // Our timeout, or a raw network failure → retry only if idempotent.\n    return { shouldRetry: idempotent };\n  }\n  return { shouldRetry: false };\n};\n\n/**\n * Run an async op with exponential backoff. The op receives the 1-based attempt\n * number and either resolves or throws; the classifier decides on retry. For\n * HTTP prefer {@link fetchWithRetry}, which composes this with response\n * inspection.\n */\nexport async function runWithRetry<T>(\n  op: (attempt: number) => Promise<T>,\n  classifier: RetryClassifier = defaultRetryClassifier,\n  options: HttpRetryOptions = {},\n  ctx: RetryContext = {},\n): Promise<T> {\n  const opts = { ...DEFAULTS, ...options };\n  let lastError: unknown = null;\n  for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {\n    try {\n      return await op(attempt);\n    } catch (err) {\n      lastError = err;\n      const response = (err as { response?: Response }).response ?? null;\n      const decision = classifier(err, response, { ...ctx, attempt });\n      if (!decision.shouldRetry || attempt === opts.maxAttempts) throw err;\n      const delay =\n        decision.delayMsOverride ??\n        computeBackoffMs(attempt, opts.baseDelayMs, opts.maxDelayMs, opts.jitter);\n      opts.onRetry?.(attempt, err);\n      await sleep(delay);\n    }\n  }\n  throw lastError;\n}\n\n/**\n * `runWithRetry` specialized for `fetch`. The wrapped call MUST return the\n * `Response` (not throw on 4xx/5xx) — this helper inspects the status itself and\n * synthesizes a retry-carrying error when the classifier says so. Network\n * errors (fetch throwing) propagate to the classifier as-is.\n */\nexport async function fetchWithRetry(\n  url: string,\n  init: RequestInit,\n  options: HttpRetryOptions = {},\n  classifier: RetryClassifier = defaultRetryClassifier,\n  fetchImpl: typeof fetch = fetch,\n  ctx: RetryContext = {},\n): Promise<Response> {\n  const method = (init.method ?? ctx.method ?? \"GET\").toUpperCase();\n  const fullCtx: RetryContext = { ...ctx, method };\n  return runWithRetry(\n    async () => {\n      const response = await fetchImpl(url, init);\n      const decision = classifier(null, response, fullCtx);\n      if (decision.shouldRetry) {\n        const synthetic = new Error(`HTTP ${response.status} ${response.statusText}`);\n        (synthetic as { response?: Response }).response = response;\n        throw synthetic;\n      }\n      return response;\n    },\n    classifier,\n    options,\n    fullCtx,\n  );\n}\n\nfunction computeBackoffMs(attempt: number, base: number, max: number, jitter: number): number {\n  const exp = Math.min(max, base * 2 ** (attempt - 1));\n  const j = exp * jitter * (Math.random() * 2 - 1);\n  return Math.max(0, Math.floor(exp + j));\n}\n\nexport function sleep(ms: number): Promise<void> {\n  if (ms <= 0) return Promise.resolve();\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","// Response-schema validation at the HTTP boundary.\n//\n// The whole point: parse the upstream body against a schema and THROW when it\n// doesn't match, instead of blind-casting (`as T`) and letting downstream\n// `?? 0 / ?? [] / ?? false` defaults fabricate a clean result. This is the fix\n// for the audit's headline finding — the SDK's parsers were validated against\n// invented fixtures, so a real (or drifted) API shape sailed through as\n// debt-free / creditworthy / invoiced.\n//\n// We deliberately do NOT import zod here. `ResponseSchema` is the structural\n// subset of a Zod schema's `safeParse` result, so any `z.ZodType` satisfies it\n// by duck-typing — @ar-agents/core stays zero-runtime-dependency, and adapters\n// keep using whatever zod version they already ship.\n\nimport { ArAgentsResponseValidationError } from \"../errors\";\n\n/** One validation issue — the structural subset we read from zod's error. */\nexport interface SchemaIssue {\n  /** Path to the offending field. `join(\".\")`-able (zod gives `PropertyKey[]`). */\n  path?: ReadonlyArray<PropertyKey>;\n  message: string;\n}\n\nexport type SafeParseResult<T> =\n  | { success: true; data: T }\n  | { success: false; error: { issues: ReadonlyArray<SchemaIssue> } };\n\n/**\n * The structural contract a response schema must satisfy. Any Zod schema\n * (`z.object({...})`, `z.array(...)`, …) already does, with no cast — pass it\n * straight in. Custom validators can implement `safeParse` too.\n */\nexport interface ResponseSchema<T> {\n  safeParse(value: unknown): SafeParseResult<T>;\n}\n\n/**\n * Validate `value` against `schema`, returning the typed data or throwing\n * {@link ArAgentsResponseValidationError}. Use at every network boundary that\n * touches money or the State so a malformed body fails loud.\n *\n * @param context optional `{ url, status }` merged into the error's structured\n *   context for logs — never put PII in the message; keep it here.\n */\nexport function parseOrThrow<T>(\n  schema: ResponseSchema<T>,\n  value: unknown,\n  context?: Record<string, unknown>,\n): T {\n  const result = schema.safeParse(value);\n  if (result.success) return result.data;\n\n  const issue = result.error.issues[0];\n  const field =\n    issue?.path && issue.path.length > 0 ? issue.path.map(String).join(\".\") : \"(root)\";\n  throw new ArAgentsResponseValidationError(\n    field,\n    issue?.message ?? \"response did not match the expected schema\",\n    {\n      ...(context ?? {}),\n      // Cap the issue list so a huge zod error can't bloat logs.\n      issues: result.error.issues.slice(0, 8).map((i) => ({\n        path: i.path ? i.path.map(String).join(\".\") : \"(root)\",\n        message: i.message,\n      })),\n    },\n  );\n}\n","// `HttpClient` — the one HTTP transport every @ar-agents/* adapter should build\n// on. It concentrates the things each adapter used to re-invent (usually\n// incompletely): a real per-request timeout, bounded jittered backoff,\n// 429/Retry-After handling, idempotency-aware retry, SSRF-safe URL building,\n// typed `ArAgentsError` mapping, and — the reason this exists — response-schema\n// validation at the boundary so a malformed body fails LOUD instead of being\n// blind-cast into a clean-looking result.\n//\n// Scope note: this is transport + validation, not a rate limiter. Proactive\n// throttling (e.g. MELI's per-seller token bucket) stays in the adapters that\n// need it; the client handles reactive 429s.\n\nimport {\n  ArAgentsAuthError,\n  ArAgentsError,\n  ArAgentsProtocolError,\n  ArAgentsRateLimitError,\n} from \"../errors\";\nimport {\n  defaultRetryClassifier,\n  fetchWithRetry,\n  parseRetryAfter,\n  type HttpRetryOptions,\n  type RetryClassifier,\n} from \"./retry\";\nimport { parseOrThrow, type ResponseSchema } from \"./schema\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"HEAD\";\n\nexport type QueryParams = Record<string, string | number | boolean | undefined | null>;\n\n/**\n * Supplies the `Authorization` header value (the FULL value, e.g.\n * `\"Bearer abc\"`). A function is called per request so token refresh is\n * transparent; return `null` for an unauthenticated request.\n */\nexport type AuthProvider =\n  | string\n  | (() => string | null | Promise<string | null>);\n\nexport interface HttpClientOptions {\n  /** Base URL; every request path is resolved against it. */\n  baseUrl: string;\n  /** Override fetch (tests / msw). Defaults to `globalThis.fetch`. */\n  fetch?: typeof fetch;\n  /** Per-request timeout in ms. Default 30_000. */\n  timeoutMs?: number;\n  /** Retry policy forwarded to {@link fetchWithRetry}. */\n  retry?: HttpRetryOptions;\n  /** Custom retry classifier. Default: idempotency-aware 5xx/429/network. */\n  retryClassifier?: RetryClassifier;\n  /** `User-Agent` sent on every request. */\n  userAgent?: string;\n  /** Headers merged into every request (request-level headers win). */\n  defaultHeaders?: Record<string, string>;\n  /** Provides the `Authorization` header value; see {@link AuthProvider}. */\n  auth?: AuthProvider;\n}\n\nexport interface HttpRequest<T = unknown> {\n  method?: HttpMethod;\n  /** Path relative to `baseUrl` (must start with `/`). Absolute URLs rejected. */\n  path: string;\n  query?: QueryParams;\n  /** Request body. Objects are JSON-serialized; strings are sent as-is. */\n  body?: unknown;\n  /** Per-request headers (override `defaultHeaders`). */\n  headers?: Record<string, string>;\n  /**\n   * Schema validated against the 2xx JSON body. STRONGLY recommended on\n   * money/State paths: without it the raw parsed JSON is returned and the old\n   * blind-cast footgun is back. With it, a malformed body throws\n   * `ArAgentsResponseValidationError`.\n   */\n  schema?: ResponseSchema<T>;\n  /** Caller AbortSignal, composed with the per-request timeout. */\n  signal?: AbortSignal;\n  /** Per-request timeout override (ms). */\n  timeoutMs?: number;\n  /**\n   * Mark a non-idempotent method (POST/PATCH) as safe to retry — e.g. the\n   * endpoint is idempotent or you set an Idempotency-Key header. Default:\n   * method-based (GET/PUT/DELETE/HEAD retried, POST/PATCH not).\n   */\n  idempotent?: boolean;\n  /** Per-request retry override, or `false` to disable retry entirely. */\n  retry?: HttpRetryOptions | false;\n  /** `Accept` header. Default `application/json`. */\n  accept?: string;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nexport class HttpClient {\n  readonly baseUrl: string;\n  private readonly fetchImpl: typeof fetch;\n  private readonly timeoutMs: number;\n  private readonly retry: HttpRetryOptions;\n  private readonly retryClassifier: RetryClassifier;\n  private readonly userAgent: string | undefined;\n  private readonly defaultHeaders: Record<string, string>;\n  private readonly auth: AuthProvider | undefined;\n\n  constructor(options: HttpClientOptions) {\n    this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n    this.fetchImpl =\n      options.fetch ?? ((globalThis as { fetch?: typeof fetch }).fetch as typeof fetch);\n    if (typeof this.fetchImpl !== \"function\") {\n      throw new ArAgentsProtocolError(\n        \"HttpClient requires `fetch` (Node 20+, browsers, or Vercel Edge). Pass `fetch` explicitly if none is global.\",\n      );\n    }\n    this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n    this.retry = options.retry ?? {};\n    this.retryClassifier = options.retryClassifier ?? defaultRetryClassifier;\n    this.userAgent = options.userAgent;\n    this.defaultHeaders = options.defaultHeaders ?? {};\n    this.auth = options.auth;\n  }\n\n  /** Make a request and return the parsed (and, if `schema` given, validated) body. */\n  async request<T = unknown>(req: HttpRequest<T>): Promise<T> {\n    const res = await this.execute(req);\n    if (res.status === 204 || res.status === 205) return undefined as T;\n\n    let body: unknown;\n    try {\n      body = await res.json();\n    } catch (err) {\n      throw new ArAgentsProtocolError(\n        `${req.method ?? \"GET\"} ${this.hostOf(res.url)} returned a non-JSON body`,\n        { status: res.status, context: { url: res.url }, cause: err },\n      );\n    }\n    if (req.schema) {\n      return parseOrThrow(req.schema, body, { url: res.url, status: res.status });\n    }\n    return body as T;\n  }\n\n  /**\n   * Make a request and return the raw `Response` (for binary bodies: PDFs, ZPL\n   * labels, SOAP XML). Still runs the full auth + timeout + retry pipeline and\n   * still throws a typed error on status >= 400 — the caller only owns body\n   * decoding.\n   */\n  async requestRaw(req: HttpRequest): Promise<Response> {\n    return this.execute(req);\n  }\n\n  /** Shared pipeline. Returns a < 400 Response; throws a typed error otherwise. */\n  private async execute(req: HttpRequest): Promise<Response> {\n    const method = req.method ?? \"GET\";\n    const url = this.buildUrl(req.path, req.query);\n    const authHeader = await this.resolveAuth();\n\n    const headers: Record<string, string> = {\n      Accept: req.accept ?? \"application/json\",\n      ...this.defaultHeaders,\n      ...(this.userAgent ? { \"User-Agent\": this.userAgent } : {}),\n      ...(authHeader ? { Authorization: authHeader } : {}),\n      ...(req.headers ?? {}),\n    };\n    const hasBody = req.body !== undefined && req.body !== null;\n    if (hasBody && headers[\"Content-Type\"] === undefined && headers[\"content-type\"] === undefined) {\n      headers[\"Content-Type\"] = \"application/json\";\n    }\n\n    const timeoutSignal = AbortSignal.timeout(req.timeoutMs ?? this.timeoutMs);\n    const signal = req.signal ? anySignal(req.signal, timeoutSignal) : timeoutSignal;\n\n    const init: RequestInit = {\n      method,\n      headers,\n      signal,\n      ...(hasBody\n        ? { body: typeof req.body === \"string\" ? req.body : JSON.stringify(req.body) }\n        : {}),\n    };\n\n    const retryOpts: HttpRetryOptions = req.retry === false ? { maxAttempts: 1 } : { ...this.retry, ...(req.retry ?? {}) };\n\n    let response: Response;\n    try {\n      response = await fetchWithRetry(\n        url,\n        init,\n        retryOpts,\n        this.retryClassifier,\n        this.fetchImpl,\n        { method, ...(req.idempotent !== undefined ? { idempotent: req.idempotent } : {}) },\n      );\n    } catch (err) {\n      // fetchWithRetry throws either a synthetic error carrying `.response`\n      // (retryable status, attempts exhausted) or the raw network/timeout error.\n      const carried = (err as { response?: Response }).response;\n      if (carried) throw await this.toHttpError(carried, method);\n      throw this.toNetworkError(err, method, url, req.signal);\n    }\n\n    if (response.status >= 400) throw await this.toHttpError(response, method);\n    return response;\n  }\n\n  private async resolveAuth(): Promise<string | null> {\n    if (this.auth === undefined) return null;\n    if (typeof this.auth === \"string\") return this.auth;\n    try {\n      return await this.auth();\n    } catch (err) {\n      throw new ArAgentsAuthError(\n        `Auth provider failed: ${err instanceof Error ? err.message : String(err)}`,\n        { cause: err instanceof Error ? err.message : String(err) },\n      );\n    }\n  }\n\n  /** Map a >= 400 Response to the right typed error, attaching a body snippet. */\n  private async toHttpError(res: Response, method: string): Promise<ArAgentsError> {\n    const body = await safeReadBodySnippet(res);\n    const context: Record<string, unknown> = { url: res.url, method, status: res.status };\n    if (body !== null) context[\"body\"] = body;\n    const where = `${method} ${this.hostOf(res.url)} → HTTP ${res.status}`;\n\n    if (res.status === 401 || res.status === 403) {\n      return new ArAgentsAuthError(where, context);\n    }\n    if (res.status === 429) {\n      const header = res.headers.get(\"Retry-After\");\n      const retryAfterMs = (header ? parseRetryAfter(header) : null) ?? 0;\n      return new ArAgentsRateLimitError(retryAfterMs, context);\n    }\n    return new ArAgentsProtocolError(where, { status: res.status, context });\n  }\n\n  /** Map a thrown network/timeout error. Caller-cancellation is re-raised as-is. */\n  private toNetworkError(\n    err: unknown,\n    method: string,\n    url: string,\n    callerSignal: AbortSignal | undefined,\n  ): unknown {\n    // If the CALLER's signal is what aborted, honor the cancellation verbatim —\n    // don't dress it up as a retryable protocol error.\n    if (callerSignal?.aborted && err instanceof Error && err.name === \"AbortError\") {\n      return err;\n    }\n    const isTimeout = err instanceof Error && err.name === \"TimeoutError\";\n    return new ArAgentsProtocolError(\n      `${method} ${this.hostOf(url)} ${isTimeout ? \"timed out\" : \"network error\"}: ${\n        err instanceof Error ? err.message : String(err)\n      }`,\n      { status: null, context: { url, method, timeout: isTimeout }, cause: err },\n    );\n  }\n\n  private buildUrl(path: string, query?: QueryParams): string {\n    // SSRF defense: reject a \"path\" that is actually an absolute or\n    // protocol-relative URL, which would silently rebase the request onto\n    // another host. Adapters always pass a leading-slash path.\n    if (\n      typeof path !== \"string\" ||\n      /^[a-z][a-z0-9+.-]*:\\/\\//i.test(path) ||\n      path.startsWith(\"//\") ||\n      /\\s/.test(path) ||\n      /(^|\\/)\\.\\.(\\/|$)/.test(path)\n    ) {\n      throw new ArAgentsProtocolError(\n        `HttpClient: refusing a path that is an absolute URL, escapes with \"..\" , or contains whitespace/NUL: ${JSON.stringify(path)}`,\n      );\n    }\n    // Resolve RELATIVE to the base so a base WITH a path prefix\n    // (e.g. https://host/wsfe) is preserved instead of being dropped by a\n    // leading-slash \"absolute\" path.\n    const url = new URL(path.replace(/^\\/+/, \"\"), `${this.baseUrl}/`);\n    if (query) {\n      for (const [k, v] of Object.entries(query)) {\n        if (v === undefined || v === null) continue;\n        url.searchParams.set(k, String(v));\n      }\n    }\n    return url.toString();\n  }\n\n  private hostOf(url: string): string {\n    try {\n      return new URL(url).host;\n    } catch {\n      return \"(unknown host)\";\n    }\n  }\n}\n\n/** Read a small JSON/text snippet from an error response for log context. Tolerant. */\nasync function safeReadBodySnippet(res: Response): Promise<unknown> {\n  try {\n    const text = await res.clone().text();\n    if (text === \"\") return null;\n    try {\n      return JSON.parse(text);\n    } catch {\n      return text.slice(0, 500);\n    }\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Compose AbortSignals into one that aborts when any input does, propagating the\n * first abort reason. Uses native `AbortSignal.any` when present, else a small\n * polyfill for older Node 20.x.\n */\nfunction anySignal(...signals: AbortSignal[]): AbortSignal {\n  const anyFn = (AbortSignal as unknown as { any?: (s: AbortSignal[]) => AbortSignal }).any;\n  if (typeof anyFn === \"function\") return anyFn(signals);\n\n  const ctrl = new AbortController();\n  const onAbort = (ev: Event) => ctrl.abort((ev.target as AbortSignal | null)?.reason);\n  for (const s of signals) {\n    if (s.aborted) {\n      ctrl.abort(s.reason);\n      break;\n    }\n    s.addEventListener(\"abort\", onAbort, { once: true });\n  }\n  return ctrl.signal;\n}\n","/**\n * Telemetry hook contract.\n *\n * A single `TelemetryHook` interface that every middleware in this\n * package speaks. Plug in an OpenTelemetry adapter, a Datadog\n * shipper, a console logger, or your own — the middleware doesn't\n * care.\n *\n * # Why we don't depend on `@opentelemetry/api` directly\n *\n * @opentelemetry/api is heavy (≈30KB), version-volatile, and not\n * everyone uses OTel. By staying behind a tiny interface we let the\n * consumer choose their observability stack without pulling code we\n * don't need.\n *\n * # Convention\n *\n * Each tool invocation produces one ToolEvent. Fields:\n *   - name      tool name (e.g. \"uala_create_payment_link\")\n *   - durationMs latency from `execute` start to settle\n *   - ok        whether `execute` resolved (true) or threw (false)\n *   - errorCode iff ok=false and the error is an ArAgentsError\n *   - attrs     free-form structured attributes (avoid PII)\n */\n\nexport interface ToolEvent {\n  name: string;\n  durationMs: number;\n  ok: boolean;\n  errorCode?: string;\n  errorRetryable?: boolean;\n  attrs?: Record<string, string | number | boolean>;\n}\n\nexport interface TelemetryHook {\n  onToolEvent(event: ToolEvent): void;\n}\n\n/**\n * A no-op hook. Use as a default so middleware never crashes when no\n * hook was wired.\n */\nexport const noopTelemetryHook: TelemetryHook = {\n  onToolEvent() {\n    /* intentionally empty */\n  },\n};\n\n/**\n * Combine multiple hooks into one. Each event is delivered to all\n * hooks in order; a throwing hook does NOT block the others — its\n * exception is swallowed (observability must never crash the request).\n */\nexport function combineHooks(...hooks: TelemetryHook[]): TelemetryHook {\n  if (hooks.length === 0) return noopTelemetryHook;\n  if (hooks.length === 1) return hooks[0]!;\n  return {\n    onToolEvent(event) {\n      for (const h of hooks) {\n        try {\n          h.onToolEvent(event);\n        } catch {\n          // Swallow — observability hooks must never crash the app.\n        }\n      }\n    },\n  };\n}\n\n/**\n * A console-backed hook. Useful for local dev + CI. Emits JSON lines\n * to stdout so log shippers can pick them up.\n */\nexport function consoleTelemetryHook(\n  opts: { prefix?: string } = {},\n): TelemetryHook {\n  const prefix = opts.prefix ?? \"[ar-agents]\";\n  return {\n    onToolEvent(event) {\n      // eslint-disable-next-line no-console\n      console.log(`${prefix} ${JSON.stringify(event)}`);\n    },\n  };\n}\n","/**\n * Tool middleware — composable wrappers around Vercel AI SDK 6 tools.\n *\n * Every middleware is a `Tool → Tool` function. They wrap the\n * `execute` callback (the network/IO/state-mutating part) with a\n * cross-cutting concern (metrics, retry, timeout, HITL gate) WITHOUT\n * modifying the tool's input schema, description, or output type.\n *\n * # Composition order\n *\n * Middleware applies innermost-first when called via `compose()`:\n *\n *   compose(A, B, C)(tool) ≡ A(B(C(tool)))\n *\n * Execution order at runtime is THE OPPOSITE (outermost first):\n *   request → A → B → C → tool.execute → C → B → A → response\n *\n * Recommended ordering (outermost first):\n *   withApproval   — gate the call BEFORE we burn time on it\n *   withRetry      — surround the real work\n *   withTimeout    — cap the real work\n *   withMetrics    — closest to execute, sees the real timing\n */\n\nimport type { Tool } from \"ai\";\nimport {\n  ArAgentsError,\n  ArAgentsRateLimitError,\n  isArAgentsError,\n} from \"./errors\";\nimport type { TelemetryHook } from \"./telemetry\";\nimport { noopTelemetryHook } from \"./telemetry\";\n\n// Matches the AI SDK's heterogeneous ToolSet: a record of tools with differing\n// input/output generics. `Tool<unknown, unknown>` rejects them because a tool's\n// `needsApproval` is contravariant in its input type, so a strongly-typed tool\n// (e.g. Tool<{ text: string }>) is not assignable to Tool<unknown>. `any` is the\n// SDK's own choice for a tool of unknown shape; the middleware only wraps\n// `execute` and never reads the input/output types, so this is safe.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyTool = Tool<any, any>;\nexport type ToolMiddleware = <T extends AnyTool>(tool: T) => T;\n\n/**\n * Combine multiple middleware into one. Innermost-first composition:\n *\n *   compose(A, B, C)(tool) ≡ A(B(C(tool)))\n *\n * At call time the runtime order is reversed: A wraps B wraps C wraps tool.\n */\nexport function compose(...middlewares: ToolMiddleware[]): ToolMiddleware {\n  if (middlewares.length === 0) return (t) => t;\n  return <T extends AnyTool>(tool: T): T =>\n    middlewares.reduceRight<T>((acc, mw) => mw(acc), tool);\n}\n\n/**\n * Apply one middleware (or composition) to every tool in a record\n * (the shape Vercel AI SDK 6 expects for the `tools` option). Each\n * tool gets the same middleware stack; tool name is passed to the\n * underlying middleware via the closure so middleware can label its\n * telemetry by the tool name.\n *\n *   const wrapped = applyToAllTools(tools, (name) =>\n *     compose(withMetrics(name, { telemetry }), withTimeout(name, 10_000)),\n *   );\n */\nexport function applyToAllTools<T extends Record<string, AnyTool>>(\n  tools: T,\n  middlewareForName: (name: string) => ToolMiddleware,\n): T {\n  const out: Record<string, AnyTool> = {};\n  for (const [name, tool] of Object.entries(tools)) {\n    out[name] = middlewareForName(name)(tool);\n  }\n  return out as T;\n}\n\n// ── withMetrics ────────────────────────────────────────────────\n\nexport interface WithMetricsOptions {\n  telemetry?: TelemetryHook;\n  /** Static attributes attached to every event. */\n  attrs?: Record<string, string | number | boolean>;\n}\n\n/**\n * Emit one ToolEvent per invocation to the configured telemetry hook.\n * Captures latency + success/error + ArAgentsError code & retryable\n * fields when available.\n */\nexport function withMetrics(\n  toolName: string,\n  opts: WithMetricsOptions = {},\n): ToolMiddleware {\n  const hook = opts.telemetry ?? noopTelemetryHook;\n  const staticAttrs = opts.attrs ?? {};\n  return <T extends AnyTool>(tool: T): T => {\n    const original = tool.execute as\n      | ((args: unknown, ctx: unknown) => Promise<unknown> | unknown)\n      | undefined;\n    if (typeof original !== \"function\") return tool;\n    const wrapped = {\n      ...tool,\n      execute: async (args: unknown, ctx: unknown) => {\n        const start = Date.now();\n        let ok = false;\n        let errorCode: string | undefined;\n        let errorRetryable: boolean | undefined;\n        try {\n          const r = await original(args, ctx);\n          ok = true;\n          return r;\n        } catch (err) {\n          if (isArAgentsError(err)) {\n            errorCode = err.code;\n            errorRetryable = err.retryable;\n          }\n          throw err;\n        } finally {\n          try {\n            const ev: import(\"./telemetry\").ToolEvent = {\n              name: toolName,\n              durationMs: Date.now() - start,\n              ok,\n              attrs: staticAttrs,\n              ...(errorCode !== undefined ? { errorCode } : {}),\n              ...(errorRetryable !== undefined ? { errorRetryable } : {}),\n            };\n            hook.onToolEvent(ev);\n          } catch {\n            // Observability never crashes the request.\n          }\n        }\n      },\n    } as T;\n    return wrapped;\n  };\n}\n\n// ── withTimeout ────────────────────────────────────────────────\n\n/**\n * Cap execute() at `timeoutMs`. On timeout, throws a NON-retryable\n * ArAgentsError(code=\"timeout\"). The middleware does NOT cancel the underlying\n * call (no AbortController is plumbed through here — that's tool-internal); it\n * merely returns control promptly so the caller's response budget is honored.\n *\n * SECURITY: the timeout error is `retryable: false` ON PURPOSE. Because the\n * original execute() keeps running after a timeout, marking it retryable let\n * withRetry re-invoke a still-running side-effectful tool — turning one approved\n * money/fiscal/irreversible action into several (double-spend). A timeout is only\n * safe to retry once execution is genuinely cancelled (AbortSignal) or the tool\n * is protected by a deterministic idempotency key; until then, do not retry it.\n */\nexport function withTimeout(toolName: string, timeoutMs: number): ToolMiddleware {\n  return <T extends AnyTool>(tool: T): T => {\n    const original = tool.execute as\n      | ((args: unknown, ctx: unknown) => Promise<unknown> | unknown)\n      | undefined;\n    if (typeof original !== \"function\") return tool;\n    const wrapped = {\n      ...tool,\n      execute: async (args: unknown, ctx: unknown) => {\n        let timer: ReturnType<typeof setTimeout> | undefined;\n        try {\n          return await Promise.race([\n            original(args, ctx),\n            new Promise<never>((_, reject) => {\n              timer = setTimeout(() => {\n                reject(\n                  new ArAgentsError(\n                    `Tool \"${toolName}\" timed out after ${timeoutMs}ms`,\n                    {\n                      code: \"timeout\",\n                      // NOT retryable: execute() is still running (uncancelled), so\n                      // retrying would double-execute a side-effectful tool. See the\n                      // SECURITY note on withTimeout above.\n                      retryable: false,\n                      context: { toolName, timeoutMs },\n                    },\n                  ),\n                );\n              }, timeoutMs);\n            }),\n          ]);\n        } finally {\n          if (timer) clearTimeout(timer);\n        }\n      },\n    } as T;\n    return wrapped;\n  };\n}\n\n// ── withRetry ──────────────────────────────────────────────────\n\nexport interface WithRetryOptions {\n  /** Max attempts INCLUDING the first. Default 3. */\n  maxAttempts?: number;\n  /** Base backoff in ms (exponential). Default 250. */\n  baseMs?: number;\n  /** Max backoff in ms. Default 5_000. */\n  maxMs?: number;\n  /** Predicate that decides whether THIS error is retryable. Default:\n   * `ArAgentsError.retryable === true`. */\n  shouldRetry?: (err: unknown, attempt: number) => boolean;\n  /** Jitter ratio (0..1). Default 0.2. */\n  jitter?: number;\n}\n\n/**\n * Retry transient failures (network blips, rate-limits, 5xx) with\n * exponential backoff + jitter. Bails immediately on non-retryable\n * errors (e.g. validation, auth).\n *\n * For ArAgentsRateLimitError, honors the error's `retryAfterMs` over\n * the computed backoff so the caller respects server signals.\n */\nexport function withRetry(opts: WithRetryOptions = {}): ToolMiddleware {\n  const maxAttempts = opts.maxAttempts ?? 3;\n  const baseMs = opts.baseMs ?? 250;\n  const maxMs = opts.maxMs ?? 5_000;\n  const jitter = opts.jitter ?? 0.2;\n  const shouldRetry =\n    opts.shouldRetry ?? ((err) => isArAgentsError(err) && err.retryable);\n\n  return <T extends AnyTool>(tool: T): T => {\n    const original = tool.execute as\n      | ((args: unknown, ctx: unknown) => Promise<unknown> | unknown)\n      | undefined;\n    if (typeof original !== \"function\") return tool;\n    const wrapped = {\n      ...tool,\n      execute: async (args: unknown, ctx: unknown) => {\n        let lastErr: unknown;\n        for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n          try {\n            return await original(args, ctx);\n          } catch (err) {\n            lastErr = err;\n            if (attempt === maxAttempts || !shouldRetry(err, attempt)) {\n              throw err;\n            }\n            const waitMs =\n              err instanceof ArAgentsRateLimitError\n                ? err.retryAfterMs\n                : Math.min(\n                    maxMs,\n                    baseMs * Math.pow(2, attempt - 1) * (1 + (Math.random() - 0.5) * 2 * jitter),\n                  );\n            await new Promise((r) => setTimeout(r, Math.max(0, waitMs)));\n          }\n        }\n        // Unreachable — the for loop always returns or throws.\n        throw lastErr;\n      },\n    } as T;\n    return wrapped;\n  };\n}\n\n// ── withApproval (HITL gate) ───────────────────────────────────\n\nexport interface WithApprovalOptions {\n  /**\n   * Called BEFORE execute. Return true to proceed, false (or throw)\n   * to refuse. This is the real runtime enforcement of the\n   * `requiresConfirmation` flag in tools.manifest.json (which is\n   * merely a hint to clients).\n   */\n  approve: (\n    toolName: string,\n    args: unknown,\n  ) => Promise<boolean> | boolean;\n  /** Optional reason emitted in the error when refused. */\n  refusedMessage?: string;\n}\n\n/**\n * Human-in-the-loop gate. Use on side-effectful tools (money moves,\n * tax returns, irreversible writes). The `approve` callback is the\n * host's hook to ask the user / call a policy engine / consult an\n * allowlist.\n */\nexport function withApproval(\n  toolName: string,\n  opts: WithApprovalOptions,\n): ToolMiddleware {\n  return <T extends AnyTool>(tool: T): T => {\n    const original = tool.execute as\n      | ((args: unknown, ctx: unknown) => Promise<unknown> | unknown)\n      | undefined;\n    if (typeof original !== \"function\") return tool;\n    const wrapped = {\n      ...tool,\n      execute: async (args: unknown, ctx: unknown) => {\n        let approved = false;\n        try {\n          approved = await opts.approve(toolName, args);\n        } catch (err) {\n          throw new ArAgentsError(\n            opts.refusedMessage ??\n              `HITL approval threw for tool \"${toolName}\".`,\n            {\n              code: \"approval_error\",\n              retryable: false,\n              context: { toolName },\n              cause: err,\n            },\n          );\n        }\n        if (!approved) {\n          throw new ArAgentsError(\n            opts.refusedMessage ??\n              `HITL approval denied for tool \"${toolName}\".`,\n            {\n              code: \"approval_denied\",\n              retryable: false,\n              context: { toolName },\n            },\n          );\n        }\n        return original(args, ctx);\n      },\n    } as T;\n    return wrapped;\n  };\n}\n\n// ── withHalt (kill-switch) ─────────────────────────────────────\n\nexport interface WithHaltOptions {\n  /**\n   * Called BEFORE execute. Return true if the society is suspended, so the tool\n   * must refuse. Unlike withApproval (which only gates high-stakes acts), the\n   * kill-switch halts EVERY operation, regardless of risk level, while the\n   * society is suspended.\n   */\n  isHalted: (toolName: string, args: unknown) => Promise<boolean> | boolean;\n  /** Optional reason emitted in the error when halted. */\n  haltedMessage?: string;\n}\n\n/**\n * Kill-switch. When `isHalted` returns true the tool refuses before doing\n * anything. This is the operational form of the art. 102 supervision duty: a\n * human administrator (or supervisor) can suspend a Sociedad Automatizada and\n * every one of its tools stops, enforced centrally rather than trusted to each\n * agent. FAILS CLOSED: if the halt state cannot be read, the tool refuses (a\n * kill-switch we cannot consult must never silently let the society act).\n */\nexport function withHalt(toolName: string, opts: WithHaltOptions): ToolMiddleware {\n  return <T extends AnyTool>(tool: T): T => {\n    const original = tool.execute as\n      | ((args: unknown, ctx: unknown) => Promise<unknown> | unknown)\n      | undefined;\n    if (typeof original !== \"function\") return tool;\n    const wrapped = {\n      ...tool,\n      execute: async (args: unknown, ctx: unknown) => {\n        let halted = false;\n        try {\n          halted = await opts.isHalted(toolName, args);\n        } catch (err) {\n          throw new ArAgentsError(\n            opts.haltedMessage ??\n              `Halt check failed for tool \"${toolName}\"; refusing (fail closed).`,\n            { code: \"halt_check_error\", retryable: false, context: { toolName }, cause: err },\n          );\n        }\n        if (halted) {\n          throw new ArAgentsError(\n            opts.haltedMessage ??\n              `Society is suspended (kill-switch); tool \"${toolName}\" refused.`,\n            { code: \"society_suspended\", retryable: false, context: { toolName } },\n          );\n        }\n        return original(args, ctx);\n      },\n    } as T;\n    return wrapped;\n  };\n}\n","// Central risk manifest — the one place that decides which tools may run on\n// their own and which need a human to approve them first.\n//\n// Why this exists: ar-agents tools touch real money (Mercado Pago), real taxes\n// (AFIP/ARCA facturación) and real legal acts (incorporating a company). The\n// Sociedad Automatizada regime (art. 102) makes a human administrator\n// responsible for what the AI does and bars delegating that supervision. So the\n// irreversible/financial/legal/fiscal acts MUST pass through a human, and that\n// decision cannot live in each agent's own code (an agent could forget it, or a\n// third party calling the public MCP would never have it). It lives here, once,\n// and `enforceRiskPolicy` applies it to any ToolSet — local agent or MCP server.\n//\n// Design: a tool's risk is decided by POSITIVE signals (an explicit critical\n// override, an `**IRREVERSIBLE**` description flag, or the manifest `sideEffects`\n// field) winning over a benign read-name heuristic. Anything we cannot classify\n// is `unknown` and FAILS CLOSED (treated as needing approval), so a new or\n// forgotten tool can never move money or constitute a company silently.\n\nimport type { AnyTool, ToolMiddleware } from \"./middleware\";\nimport { applyToAllTools, compose, withApproval, withHalt } from \"./middleware\";\n\n/** Risk tiers, lowest to highest stakes. */\nexport type RiskLevel =\n  | \"read\" // network read, no side effect\n  | \"create\" // creates a low-stakes, reversible resource\n  | \"money\" // moves money\n  | \"fiscal\" // tax act (AFIP/ARCA: facturación, withholdings)\n  | \"legal\" // legal/registry act (incorporation, filings)\n  | \"irreversible\" // cannot be undone\n  | \"unknown\"; // not classifiable -> fail closed\n\n// The art. 102 invariant: these tiers require a human approval before execute.\n// `unknown` is included on purpose (fail closed).\nconst APPROVAL_LEVELS: ReadonlySet<RiskLevel> = new Set<RiskLevel>([\n  \"money\",\n  \"fiscal\",\n  \"legal\",\n  \"irreversible\",\n  \"unknown\",\n]);\n\n/** Whether a given risk level demands human approval before the tool runs. */\nexport function levelRequiresApproval(level: RiskLevel): boolean {\n  return APPROVAL_LEVELS.has(level);\n}\n\nexport interface ToolRiskInput {\n  name: string;\n  description?: string | undefined;\n  /** The `sideEffects` value from a package's tools.manifest.json, if present. */\n  sideEffects?: string | undefined;\n}\n\n// Explicit overrides for known-critical name patterns. Positive signal: these\n// win over the read-name heuristic, so a `get_`-looking name that actually moves\n// money or files a tax form is still gated. Small and auditable on purpose.\nconst OVERRIDES: ReadonlyArray<readonly [RegExp, RiskLevel]> = [\n  [/incorporar_sociedad|(^|_)constitu/i, \"legal\"],\n  // Fiscal ACTS only (emit/cancel/file a tax return). Tax CALCULATORS\n  // (iva/sicore/suss *_calculate) are pure math with no side effect -> they read\n  // (see READ_SIGNALS). DDJJ submissions are matched for any filing verb\n  // (presentar/enviar/submit) so sicore_submit_ddjj, suss_submit_ddjj and the\n  // iva_*_submit_ddjj tools classify fiscal, not fall through to unknown.\n  [/emitir_factura|anular_factura|generar_factura|nota_credito|nota_debito|(^|_)cae(_|$)|(presentar|enviar|submit)_(ddjj|f29|f931|declaracion)/i, \"fiscal\"],\n  // Money-MOVING verbs only. \"payment\" as a noun (get_payment, list_payments)\n  // must NOT match here, or reads would be gated; those fall through to read.\n  // `paid_fetch` is the x402 pay-per-call HTTP tool (settles a micropayment);\n  // `(accept|reject)_invoice` is the FCE (factura de crédito) act that creates\n  // or declines a legally-enforceable payment obligation.\n  // Spanish money verbs (pagar/abonar/girar/retirar) are segment-bounded so a\n  // read like `list_pagares` (promissory notes) is NOT gated as money — only the\n  // verb \"pagar\", not the noun \"pagarés\", matches. Closes the gap where a Spanish\n  // money verb + a read-ish noun (`pagar_saldo`) downgraded to \"read\".\n  [/transfer|payout|withdraw|reembols|refund|(^|_)cobr|(^|_)depos|(^|_)swap|(^|_)pay(_|$)|(^|_)pagar(_|$)|(^|_)abonar(_|$)|(^|_)girar(_|$)|(^|_)retir(ar|o)?(_|$)|(create|cancel|capture|refund|void|process)_payment|charge|checkout|send_money|paid_fetch|(accept|reject)_invoice/i, \"money\"],\n  [/(^|_)delete(_|$)|(^|_)remove(_|$)|revoke|destroy|cancel(_|$)/i, \"irreversible\"],\n  // registrar_decision appends to the signed audit log: a write, but low-stakes\n  // and the agent should log its own decisions without a human in the loop.\n  [/registrar_decision/i, \"create\"],\n];\n\n// Benign read-name patterns. Only consulted when no positive signal fired.\nconst READ_PATTERNS =\n  /^(get|list|search|validate|validar|lookup|consultar|consulta|health|fetch|read|check|is_|describe|info|show|find|status)(_|$)/i;\n\n// Read/compute words that can appear ANYWHERE in a tool name (a calculator, a\n// balance lookup, a monetary-variable read). Only consulted after the risk\n// overrides + sideEffects, so a genuinely risky name still gates first.\nconst READ_SIGNALS =\n  /(calcula|calcular|calculate|calculo|compute|cotiz|estimat|simul|preview|lookup|consulta|(^|_)info(_|$)|status|balance|saldo|variable|deudas|padron)/i;\n\n// Mutating verbs that carry a read-ish noun (set_balance, credit_saldo,\n// modificar_padron, emitir_padron, presentar_saldo, anular_deudas). READ_SIGNALS\n// matches the noun ANYWHERE, so without this a mutation would be downgraded to\n// \"read\" and skip the gate. A name whose verb is here is NOT downgraded: it falls\n// through to \"unknown\" (fail closed) unless an OVERRIDE already caught its true\n// category first. This is a denylist, so keep it broad — a false \"mutating\" only\n// costs a needless human approval (safe), while a miss silently skips the gate.\nconst MUTATING_SIGNALS =\n  /(^|_)(set|update|adjust|credit|debit|deduct|increment|decrement|acreditar|debitar|cargar|modificar|actualizar|incrementar|decrementar|write|overwrite|emitir|anular|firmar|aprobar|rechazar|ejecutar|confirmar|suspender|reanudar|presentar|enviar|dar_de_baja|dar_de_alta)(_|$)/i;\n\nfunction fromSideEffects(se?: string): RiskLevel | null {\n  switch ((se ?? \"\").toLowerCase().trim()) {\n    case \"irreversible\":\n      return \"irreversible\";\n    case \"moves money\":\n      return \"money\";\n    case \"creates resource\":\n      return \"create\";\n    case \"network read\":\n    case \"none\":\n      return \"read\";\n    default:\n      return null;\n  }\n}\n\n/** Classify a tool into a {@link RiskLevel}. Positive signals win; unknown fails closed. */\nexport function classifyTool(input: ToolRiskInput): RiskLevel {\n  const name = input.name ?? \"\";\n  // 1. Explicit critical overrides (positive signal beats everything).\n  for (const [re, level] of OVERRIDES) {\n    if (re.test(name)) return level;\n  }\n  // 2. Description flag (packages mark irreversible tools as **IRREVERSIBLE**).\n  if (input.description && /\\bIRREVERSIBLE\\b/i.test(input.description)) {\n    return \"irreversible\";\n  }\n  // 3. Manifest sideEffects hint.\n  const se = fromSideEffects(input.sideEffects);\n  if (se) return se;\n  // 4. Benign read heuristics: anchored read verbs, or read/compute words\n  // anywhere — but NOT when the name also carries a mutating verb (a mutation\n  // dressed in a read-ish noun must never be downgraded to \"read\").\n  if (\n    (READ_PATTERNS.test(name) || READ_SIGNALS.test(name)) &&\n    !MUTATING_SIGNALS.test(name)\n  ) {\n    return \"read\";\n  }\n  // 5. Fail closed.\n  return \"unknown\";\n}\n\n/** Whether a tool needs a human approval before it may run. */\nexport function requiresApproval(input: ToolRiskInput): boolean {\n  return levelRequiresApproval(classifyTool(input));\n}\n\nconst identity: ToolMiddleware = (tool) => tool;\n\nexport interface EnforceRiskPolicyOptions {\n  /**\n   * The HITL hook, called BEFORE an approval-level tool runs. Return true to\n   * proceed; false (or throw) refuses. This is where the host asks the human\n   * administrator, consults a policy engine, or checks an approval token.\n   */\n  approve: (toolName: string, args: unknown) => Promise<boolean> | boolean;\n  /** Supply a tool's manifest `sideEffects` by name to sharpen classification. */\n  sideEffectsFor?: (toolName: string) => string | undefined;\n  refusedMessage?: string;\n  /**\n   * Kill-switch. When provided and it returns true, EVERY tool refuses (the\n   * society is suspended), regardless of risk level — checked before the risk\n   * gate. The art. 102 supervision duty made operational: a human can halt the\n   * whole society, enforced centrally here rather than trusted to each agent.\n   * Fails closed (see {@link withHalt}).\n   */\n  isHalted?: (toolName: string, args: unknown) => Promise<boolean> | boolean;\n}\n\n/**\n * Gate every approval-level tool in a ToolSet behind the `approve` callback;\n * read/create tools pass through untouched. This is the central art. 102\n * enforcement: a caller cannot invoke a money/fiscal/legal/irreversible tool\n * (or an unclassified one) without a human approval, no matter which agent or\n * transport made the call.\n */\nexport function enforceRiskPolicy<T extends Record<string, AnyTool>>(\n  tools: T,\n  opts: EnforceRiskPolicyOptions,\n): T {\n  return applyToAllTools(tools, (name) => {\n    const tool = tools[name] as AnyTool | undefined;\n    const input: ToolRiskInput = {\n      name,\n      description:\n        typeof tool?.description === \"string\" ? tool.description : undefined,\n      sideEffects: opts.sideEffectsFor?.(name),\n    };\n    const riskMw = requiresApproval(input)\n      ? withApproval(name, {\n          approve: opts.approve,\n          refusedMessage:\n            opts.refusedMessage ??\n            `Tool \"${name}\" needs human approval (art. 102): ${classifyTool(input)} risk.`,\n        })\n      : identity;\n    // Kill-switch outermost: a suspended society halts EVERY tool (read or not)\n    // before the risk gate runs. Same central enforcement point as art. 102.\n    if (!opts.isHalted) return riskMw;\n    return compose(withHalt(name, { isHalted: opts.isHalted }), riskMw);\n  });\n}\n","// AI SDK 7 native tool-approval, driven by the SAME risk manifest as\n// `enforceRiskPolicy` (see ./risk-manifest). This is the agent-loop counterpart\n// to the middleware gate: pass it as the `toolApproval` setting on a v7\n// generateText / streamText / Agent call, paired with\n// `experimental_toolApprovalSecret` so the SDK HMAC-signs each approval request\n// and rejects forged/replayed approvals (InvalidToolApprovalSignatureError).\n//\n// Why both this AND enforceRiskPolicy exist:\n//   - enforceRiskPolicy wraps tool `execute` with middleware — it protects EVERY\n//     transport, including a third party calling the public MCP server, where no\n//     agent-loop `toolApproval` setting is in play. It stays the universal gate.\n//   - toolApprovalFromRisk is the agent-loop-native path: it lets the AI SDK 7\n//     runtime emit a cryptographically-signed approval request and pause, instead\n//     of the tool's execute returning a refusal. Use it when the host implements\n//     the v7 approval lifecycle (e.g. a WorkflowAgent with durable, resumable\n//     approvals). The classification law is identical, so the two never disagree.\n//\n// Same invariant as the manifest: money / fiscal / legal / irreversible / unknown\n// require approval; read / create proceed. Unknown FAILS CLOSED ('user-approval').\n\nimport {\n  classifyTool,\n  levelRequiresApproval,\n  type ToolRiskInput,\n} from \"./risk-manifest\";\n\n/**\n * The subset of the AI SDK 7 `toolApproval` generic-function argument this\n * helper reads. Declared structurally so `@ar-agents/core` does not depend on\n * `ai` at the type level; the returned function is assignable to the SDK's\n * `ToolApprovalConfiguration` generic-function form.\n */\nexport interface ToolApprovalCallInfo {\n  toolCall: { toolName: string; input?: unknown };\n}\n\n/**\n * The AI SDK 7 approval statuses this helper returns. `'user-approval'` defers\n * to a human; `'not-applicable'` lets the tool run without approval. (The SDK\n * also accepts `'approved'` / `'denied'`; we never auto-approve or auto-deny a\n * classified-risky tool here — that decision belongs to the human gate.)\n */\nexport type RiskToolApprovalStatus = \"user-approval\" | \"not-applicable\";\n\nexport interface ToolApprovalFromRiskOptions {\n  /** Supply a tool's manifest `sideEffects` by name to sharpen classification. */\n  sideEffectsFor?: (toolName: string) => string | undefined;\n  /**\n   * Supply a tool's description by name so the `**IRREVERSIBLE**` flag is seen.\n   * Optional: when the tools are passed to the SDK they carry their own\n   * descriptions, but the approval callback only receives the tool NAME, so the\n   * host can thread descriptions through here for parity with enforceRiskPolicy.\n   */\n  descriptionFor?: (toolName: string) => string | undefined;\n}\n\n/**\n * Build an AI SDK 7 `toolApproval` generic function from the risk manifest.\n *\n * @example\n * ```ts\n * import { toolApprovalFromRisk } from \"@ar-agents/core\";\n * const result = await agent.generate({\n *   prompt,\n *   toolApproval: toolApprovalFromRisk({ sideEffectsFor }),\n *   experimental_toolApprovalSecret: process.env.TOOL_APPROVAL_SECRET, // HMAC-signs requests\n * });\n * ```\n */\nexport function toolApprovalFromRisk(\n  opts: ToolApprovalFromRiskOptions = {},\n): (info: ToolApprovalCallInfo) => RiskToolApprovalStatus {\n  return (info) => {\n    const name = info.toolCall.toolName;\n    const input: ToolRiskInput = {\n      name,\n      description: opts.descriptionFor?.(name),\n      sideEffects: opts.sideEffectsFor?.(name),\n    };\n    return levelRequiresApproval(classifyTool(input))\n      ? \"user-approval\"\n      : \"not-applicable\";\n  };\n}\n","// The jurisdiction seam.\n//\n// Why this exists: @ar-agents started AR-first, but the architecture is\n// global-first (CAPTURE-TRANSFORMATION.md:22, 124-126). An autonomous company\n// is \"in good standing\" in some jurisdiction; it settles fiat in some currency\n// through some rail; it owes tax under some rule; and a registry-of-record\n// vouches for it. Today all of that is hardcoded to Argentina. These four pure\n// interfaces — Jurisdiction / FiatRail / Registry / TaxRule — name the seam so\n// AR becomes jurisdiction #1 (in ./jurisdictions/ar) rather than the only one,\n// WITHOUT pulling any runtime dependency into core: the host injects the real\n// IGJ lookup and the treasury off-ramp. Pure types + pure helpers only.\n\n/** ISO 3166-1 alpha-2 country code, optionally with a subdivision (ISO 3166-2). AR is jurisdiction #1, not the only one. */\nexport type CountryCode = string; // \"AR\", \"US\", \"EE\", \"MH\", \"SG\"\n/** ISO 3166-2 subdivision code — an optional refinement of a country. */\nexport type SubdivisionCode = string; // \"US-WY\", \"AR-C\" — optional refinement\n/** ISO 4217 currency code the jurisdiction settles fiat in. */\nexport type CurrencyCode = string; // \"ARS\", \"USD\", \"EUR\"\n\n/** A legal jurisdiction in which an autonomous company can be in good standing. The composition root that ties a Registry, its FiatRail(s) and TaxRule(s) together. */\nexport interface Jurisdiction {\n  /** ISO 3166-1 alpha-2. */\n  readonly country: CountryCode;\n  /** Optional subdivision (e.g. \"US-WY\" Wyoming, \"AR-C\" CABA). */\n  readonly subdivision?: SubdivisionCode | undefined;\n  /** Human label, e.g. \"Argentina\", \"Wyoming DAO LLC\". */\n  readonly name: string;\n  /** Default settlement currency. Rails (FiatRail.currency) and tax (TaxOwed.currency) carry their own; this is only the jurisdiction's primary. */\n  readonly defaultCurrency: CurrencyCode;\n  /** The registry-of-record for good-standing in this jurisdiction. */\n  readonly registry: Registry;\n  /** Fiat off/on-ramps available here (first = preferred). May be empty pre-integration. */\n  readonly fiatRails: ReadonlyArray<FiatRail>;\n  /** Tax rules that apply to an entity's acts here. */\n  readonly taxRules: ReadonlyArray<TaxRule>;\n  /** Whether this jurisdiction's autonomous-company regime is enacted law or proposed. Drives the LAW_STATUS pre/live switch on the site. */\n  readonly status: \"operational\" | \"proposal\";\n}\n\n/** A fiat settlement rail (off-ramp / on-ramp), jurisdiction-agnostic generalization of treasury's OffRampAdapter. Crypto<->fiat. Async, idempotent, gateable. */\nexport interface FiatRail {\n  /** Stable id, e.g. \"manteca\", \"bitso\", \"bridge-us\". */\n  readonly id: string;\n  /** Country this rail settles into. */\n  readonly country: CountryCode;\n  /** Fiat currency this rail pays out. */\n  readonly currency: CurrencyCode;\n  /** Direction(s) supported. */\n  readonly direction: \"off-ramp\" | \"on-ramp\" | \"both\";\n  /** Quote a crypto->fiat (or fiat->crypto) conversion. No side effects. amount in the SOURCE asset's minor-agnostic units. */\n  quote(input: { amount: number; fromAsset: string; toAsset: string }): Promise<FiatRailQuote>;\n  /**\n   * Execute the conversion + payout. IRREVERSIBLE: callers MUST gate behind the art.102 approval (enforceRiskPolicy / toolApprovalFromRisk).\n   * externalId is a REQUIRED idempotency key (same key on retry => same receipt, never double-spend).\n   */\n  settle(input: {\n    amount: number;\n    fromAsset: string;\n    toAsset: string;\n    externalId: string;\n  }): Promise<FiatRailReceipt>;\n  /** Poll async settlement. Optional (in-memory rails settle instantly). */\n  getStatus?(txId: string): Promise<FiatRailStatusReport>;\n}\nexport interface FiatRailQuote {\n  amount: number;\n  out: number;\n  rate: number;\n  spread: number;\n}\nexport interface FiatRailReceipt {\n  amount: number;\n  received: number;\n  rate: number;\n  txId: string;\n  depositAddress?: string | undefined;\n}\nexport type FiatRailStatus =\n  | \"PENDING\"\n  | \"PROCESSING\"\n  | \"COMPLETED\"\n  | \"FAILED\"\n  | \"UNKNOWN\";\nexport interface FiatRailStatusReport {\n  txId: string;\n  status: FiatRailStatus;\n  settled?: number | undefined;\n  raw?: string | undefined;\n}\n\n/** The registry-of-record / good-standing ORACLE for a jurisdiction. The moat surface: trust-minimized, publicly verifiable (no ar-agents key required to verify). Sprint 2 makes the AR impl writable+queryable; this interface is the contract counterparties consult. */\nexport interface Registry {\n  /** Stable id, e.g. \"ar-igj\", \"us-wy-sos\". */\n  readonly id: string;\n  readonly country: CountryCode;\n  /** Human label, e.g. \"IGJ (Argentina)\". */\n  readonly name: string;\n  /** Look up a company's good-standing by its registry id. Read-only; what a bank/marketplace/agent-framework calls before transacting (the demand side, CAPTURE-TRANSFORMATION.md:66-73). Returns null if unknown. */\n  lookup(entityId: string): Promise<GoodStandingRecord | null>;\n  /** Verify a signed attestation WITHOUT trusting any ar-agents private key, by checking the public anchor (transparency log / L2 / OpenTimestamps). A conformant impl MUST set trustMinimized:true ONLY when the verdict was reached solely via the PublicAnchor, never via an operator-held key (thesis #2). */\n  verifyAttestation(attestation: GoodStandingAttestation): Promise<AttestationVerification>;\n}\nexport interface GoodStandingRecord {\n  /** Registry-native entity id. */\n  readonly entityId: string;\n  readonly jurisdiction: CountryCode;\n  /** Legal name on record. */\n  readonly name: string;\n  /** Current standing. \"suspended\" = good-standing administratively paused by the registry (in AR, the art.102 kill-switch state). */\n  readonly status: \"good-standing\" | \"suspended\" | \"revoked\" | \"unknown\";\n  /** ISO-8601 of last status change. */\n  readonly asOf: string;\n}\nexport interface GoodStandingAttestation {\n  readonly record: GoodStandingRecord;\n  /** Signature of convenience (NOT the root of trust per thesis #2). */\n  readonly signature?: string | undefined;\n  /** Public anchor proving the record was committed at a point in time without trusting our key (e.g. OpenTimestamps proof, L2 tx hash, CT entry). */\n  readonly anchor?: PublicAnchor | undefined;\n}\nexport interface PublicAnchor {\n  readonly type: \"opentimestamps\" | \"l2-tx\" | \"ct-log\" | string;\n  readonly proof: string;\n  readonly anchoredAt?: string | undefined;\n}\nexport interface AttestationVerification {\n  readonly valid: boolean;\n  /** True ONLY if `valid` was established without any operator-held key, i.e. solely from the PublicAnchor. A black-box (key-only) verdict MUST set this false. */\n  readonly trustMinimized: boolean;\n  readonly reason?: string | undefined;\n}\n\n/** A tax/fiscal rule for a jurisdiction: a PURE calculator of what is owed. Jurisdiction-neutral by design — it carries NO risk taxonomy, so a non-AR jurisdiction is never forced into Argentina's art.102 vocabulary. Each jurisdiction maps its own filings onto its own approval regime; AR refines this as `ArTaxRule` (with a RiskLevel) in ./jurisdictions/ar. Generalizes AR's cedular/monotributo/IIBB so non-AR jurisdictions slot in. */\nexport interface TaxRule {\n  /** Stable id, e.g. \"ar-cedular\", \"ar-monotributo\", \"us-wy-annual\". */\n  readonly id: string;\n  readonly country: CountryCode;\n  /** Human label. */\n  readonly label: string;\n  /** Pure calculator: tax owed for a taxable event. No side effects. */\n  computeOwed(event: TaxableEvent): TaxOwed;\n}\nexport interface TaxableEvent {\n  readonly kind: string;\n  readonly amount: number;\n  readonly currency: CurrencyCode;\n  readonly meta?: Record<string, unknown> | undefined;\n}\nexport interface TaxOwed {\n  readonly amount: number;\n  readonly currency: CurrencyCode;\n  readonly ruleId: string;\n}\n\n/** Registry of installed jurisdictions, keyed by CountryCode (+optional subdivision). Pure, no I/O. Lets a host resolve \"AR\" -> the AR Jurisdiction, and later \"US-WY\" etc. */\nexport interface JurisdictionRegistry {\n  get(country: CountryCode, subdivision?: SubdivisionCode): Jurisdiction | undefined;\n  list(): ReadonlyArray<Jurisdiction>;\n}\n\n/** Build a pure {@link JurisdictionRegistry}. No I/O. Each jurisdiction is keyed by `${country}` and, when it has a subdivision, ALSO by `${country}/${subdivision}` so callers can resolve either granularity. */\nexport function createJurisdictionRegistry(\n  jurisdictions: ReadonlyArray<Jurisdiction>,\n): JurisdictionRegistry {\n  const byKey = new Map<string, Jurisdiction>();\n  for (const j of jurisdictions) {\n    byKey.set(j.country, j);\n    if (j.subdivision !== undefined) {\n      byKey.set(`${j.country}/${j.subdivision}`, j);\n    }\n  }\n  return {\n    get(country: CountryCode, subdivision?: SubdivisionCode): Jurisdiction | undefined {\n      if (subdivision !== undefined) {\n        // noUncheckedIndexedAccess: Map.get already returns `T | undefined`;\n        // prefer the more specific key, fall back to the country-level one.\n        return byKey.get(`${country}/${subdivision}`) ?? byKey.get(country);\n      }\n      return byKey.get(country);\n    },\n    list(): ReadonlyArray<Jurisdiction> {\n      return jurisdictions;\n    },\n  };\n}\n","// Argentina — jurisdiction #1.\n//\n// The AR first implementation of the jurisdiction seam. This file proves the\n// seam closes over a real jurisdiction without dragging AFIP/Manteca runtime\n// deps into core: the tax rules are PURE calculators (the math is reproduced\n// faithfully from @ar-agents/treasury, NOT imported, so core stays dep-free),\n// and the Registry + FiatRails are INJECTED by the host via createArJurisdiction.\n//\n// status: \"proposal\" — the Sociedad Automatizada regime (art.102) is an\n// anteproyecto, not enacted law (CAPTURE-TRANSFORMATION.md). When it is enacted,\n// flip to \"operational\" (the LAW_STATUS pre/live switch).\n\nimport type {\n  FiatRail,\n  Jurisdiction,\n  Registry,\n  TaxableEvent,\n  TaxOwed,\n  TaxRule,\n} from \"../jurisdiction\";\nimport type { RiskLevel } from \"../risk-manifest\";\n\n/**\n * An AR tax rule: a neutral {@link TaxRule} plus the art.102 risk tier the AR\n * regime assigns to acting on it (a pure calculator is \"read\"; a filing/payment\n * is \"fiscal\"). This refinement is what keeps RiskLevel OUT of the\n * jurisdiction-neutral core contract — a non-AR jurisdiction is never forced\n * into Argentina's risk vocabulary.\n */\nexport interface ArTaxRule extends TaxRule {\n  readonly riskLevel: RiskLevel;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AR cedular (Ganancias) on a crypto disposal.\n//\n// Reproduces @ar-agents/treasury cedularTax (treasury/src/index.ts:41-62)\n// FAITHFULLY as a pure TaxRule — core must not depend on treasury:\n//   proceeds = amount * fxRate\n//   cost     = amount * costBasisPerUsd * fxRate\n//   gain     = max(0, proceeds - cost)\n//   owed     = gain * rate     where rate = 5% (ARS-denominated) / 15% (foreign)\n// Taxed on the GAIN only; 0 if no gain. Pure: clock/fx are passed in via the\n// taxable event's `meta`, never read.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Cedular rate by denomination of the disposed asset. Mirrors treasury CEDULAR_RATE. */\nconst AR_CEDULAR_RATE: { readonly ARS: number; readonly FOREIGN: number } = {\n  ARS: 0.05,\n  FOREIGN: 0.15,\n};\n\n/**\n * AR cedular tax on a crypto disposal, as a pure {@link TaxRule}.\n *\n * The {@link TaxableEvent}:\n *   - `kind`: \"crypto-disposal\"\n *   - `amount`: units of crypto disposed (the USD/USDC amount, like treasury's `amountUsd`)\n *   - `currency`: \"ARS\" (the tax is denominated/paid in pesos)\n *   - `meta.fxRate`: ARS per USD (required)\n *   - `meta.costBasisPerUsd`: average USD cost basis per unit (default 1, like USDC)\n *   - `meta.denomination`: \"ARS\" (5%) | \"FOREIGN\" (15%) — default \"ARS\"\n *\n * riskLevel \"read\": this is a pure calculator with NO side effect (the actual\n * filing is a separate fiscal act). Mirrors how risk-manifest classifies tax\n * CALCULATORS as read and tax ACTS as fiscal.\n */\nexport const AR_CEDULAR: ArTaxRule = {\n  id: \"ar-cedular\",\n  country: \"AR\",\n  riskLevel: \"read\",\n  label: \"Ganancias cedular sobre disposición de cripto (5% ARS / 15% extranjera)\",\n  computeOwed(event: TaxableEvent): TaxOwed {\n    const meta = event.meta ?? {};\n    const fxRate = typeof meta[\"fxRate\"] === \"number\" ? meta[\"fxRate\"] : 1;\n    const costBasisPerUsd =\n      typeof meta[\"costBasisPerUsd\"] === \"number\" ? meta[\"costBasisPerUsd\"] : 1;\n    const denom = meta[\"denomination\"] === \"FOREIGN\" ? \"FOREIGN\" : \"ARS\";\n    const amount = event.amount;\n    const proceeds = amount * fxRate;\n    const cost = amount * costBasisPerUsd * fxRate;\n    const gain = Math.max(0, proceeds - cost);\n    const owed = gain * AR_CEDULAR_RATE[denom];\n    return { amount: owed, currency: \"ARS\", ruleId: \"ar-cedular\" };\n  },\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// AR monotributo — the fixed monthly cuota as a TaxRule.\n//\n// Reproduces @ar-agents/treasury MONOTRIBUTO_2026 + monotributoCuota\n// (treasury/src/afip.ts:65-92) FAITHFULLY. Values per ARCA \"Valores de\n// aplicación desde el 1/02/2026\". The cuota is a FIXED monthly amount for a\n// category + activity, not a function of the event's amount.\n//\n// The {@link TaxableEvent}:\n//   - `kind`: \"monotributo-cuota\"\n//   - `amount`: ignored (the cuota is fixed by category, not by the event)\n//   - `currency`: \"ARS\"\n//   - `meta.category`: \"A\"..\"K\" (default \"A\")\n//   - `meta.activity`: \"servicios\" | \"bienes\" (default \"servicios\")\n//\n// riskLevel \"fiscal\": paying/declaring monotributo is a fiscal ACT (mirrors\n// risk-manifest classifying fiscal acts as needing the art.102 gate).\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface MonotributoRow {\n  readonly category: string;\n  readonly cuotaServicios: number;\n  readonly cuotaBienes: number;\n  /** I/J/K are only available when selling goods. */\n  readonly bienesOnly: boolean;\n}\n\n// Faithful copy of treasury MONOTRIBUTO_2026 (cuota columns; the annual cap is\n// not needed to compute the cuota owed). MONOTRIBUTO_TABLE_EFFECTIVE 2026-02-01.\nconst AR_MONOTRIBUTO_2026: readonly MonotributoRow[] = [\n  { category: \"A\", cuotaServicios: 42_386.74, cuotaBienes: 42_386.74, bienesOnly: false },\n  { category: \"B\", cuotaServicios: 48_250.78, cuotaBienes: 48_250.78, bienesOnly: false },\n  { category: \"C\", cuotaServicios: 56_501.85, cuotaBienes: 55_227.06, bienesOnly: false },\n  { category: \"D\", cuotaServicios: 72_414.10, cuotaBienes: 70_661.26, bienesOnly: false },\n  { category: \"E\", cuotaServicios: 102_537.97, cuotaBienes: 92_658.35, bienesOnly: false },\n  { category: \"F\", cuotaServicios: 129_045.32, cuotaBienes: 111_198.27, bienesOnly: false },\n  { category: \"G\", cuotaServicios: 197_108.23, cuotaBienes: 135_918.34, bienesOnly: false },\n  { category: \"H\", cuotaServicios: 447_346.93, cuotaBienes: 272_063.40, bienesOnly: false },\n  { category: \"I\", cuotaServicios: 824_802.26, cuotaBienes: 406_512.05, bienesOnly: true },\n  { category: \"J\", cuotaServicios: 999_007.65, cuotaBienes: 497_059.41, bienesOnly: true },\n  { category: \"K\", cuotaServicios: 1_381_687.90, cuotaBienes: 600_879.51, bienesOnly: true },\n];\n\n/**\n * AR monotributo monthly cuota, as a fiscal {@link TaxRule}. Reproduces\n * treasury monotributoCuota: throws on an unknown category and on a\n * services taxpayer requesting a bienes-only (I/J/K) category.\n */\nexport const AR_MONOTRIBUTO: ArTaxRule = {\n  id: \"ar-monotributo\",\n  country: \"AR\",\n  riskLevel: \"fiscal\",\n  label: \"Monotributo — cuota mensual (ARCA, vigente 2026-02-01)\",\n  computeOwed(event: TaxableEvent): TaxOwed {\n    const meta = event.meta ?? {};\n    const category = typeof meta[\"category\"] === \"string\" ? meta[\"category\"] : \"A\";\n    const activity = meta[\"activity\"] === \"bienes\" ? \"bienes\" : \"servicios\";\n    const row = AR_MONOTRIBUTO_2026.find((r) => r.category === category);\n    if (!row) throw new Error(`unknown monotributo category: ${category}`);\n    if (row.bienesOnly && activity === \"servicios\") {\n      throw new Error(\n        `category ${category} is only available for venta de bienes (servicios caps at H)`,\n      );\n    }\n    const owed = activity === \"servicios\" ? row.cuotaServicios : row.cuotaBienes;\n    return { amount: owed, currency: \"ARS\", ruleId: \"ar-monotributo\" };\n  },\n};\n\n/** All AR tax rules wired into the AR Jurisdiction. */\nexport const AR_TAX_RULES: ReadonlyArray<TaxRule> = [AR_CEDULAR, AR_MONOTRIBUTO];\n\n/**\n * Build the AR {@link Jurisdiction}. `registry` and `fiatRails` are INJECTED —\n * the host wires the real IGJ good-standing lookup and the treasury off-ramp\n * (as a FiatRail) — so core carries no AFIP/Manteca runtime dependency.\n */\nexport function createArJurisdiction(opts: {\n  registry: Registry;\n  fiatRails?: ReadonlyArray<FiatRail>;\n}): Jurisdiction {\n  return {\n    country: \"AR\",\n    name: \"Argentina\",\n    defaultCurrency: \"ARS\",\n    status: \"proposal\",\n    taxRules: AR_TAX_RULES,\n    registry: opts.registry,\n    fiatRails: opts.fiatRails ?? [],\n  };\n}\n","// The Accounting Rule (rail-neutral).\n//\n// Every USD-stablecoin movement an autonomous company makes must yield a\n// SECONDARY local-currency (ARS for AR) valuation AT EXECUTION TIME, so the act is\n// AFIP/ARCA-correct even though it settled in USD. This is what makes a USD rail\n// legal-to-report for an AR Sociedad. It is rail-NEUTRAL: OUSD, USDC, or any USD\n// asset builds the same payload; and currency-neutral: the local currency is a\n// parameter (defaulting ARS), honoring the jurisdiction/currency decoupling.\n//\n// Pure: no chain deps, no I/O of its own. The FX feed is injected (FxOracle); a\n// deterministic mock is provided for tests + pre-launch dev.\n\nimport type { CurrencyCode } from \"../jurisdiction\";\n\nexport interface FxRate {\n  /** Units of `to` per 1 unit of `from` (e.g. ARS per USD). */\n  rate: number;\n  from: CurrencyCode;\n  to: CurrencyCode;\n  /** ISO-8601 of the quote. */\n  at: string;\n  /** Where the rate came from, e.g. \"mock\", \"bcra\", \"criptoya\". */\n  source: string;\n}\n\n/** Pluggable FX oracle. The host injects a real feed; {@link mockFxOracle} is for tests. */\nexport interface FxOracle {\n  rate(from: CurrencyCode, to: CurrencyCode, at?: string): Promise<FxRate>;\n}\n\n/**\n * The secondary valuation attached to a USD-denominated movement. `local` is the\n * local-currency equivalent at `at` (== execution time), for invoicing, tax, and\n * registry scoring.\n */\nexport interface AccountingPayload {\n  /** The USD-denominated amount that moved (for OUSD/USDC, 1 unit == 1 USD). */\n  usd: number;\n  /** Local-currency equivalent at execution time. */\n  local: number;\n  /** Local currency code (e.g. \"ARS\"). */\n  localCurrency: CurrencyCode;\n  /** FX rate used: local per USD. */\n  fxRate: number;\n  /** Provenance of the rate (never \"mock\" in production valuation). */\n  fxSource: string;\n  /** ISO-8601 of the valuation, equal to the execution timestamp. */\n  at: string;\n  /** Asset ticker, e.g. \"OUSD\", \"USDC\". */\n  asset: string;\n}\n\nfunction round2(n: number): number {\n  return Math.round(n * 100) / 100;\n}\n\n/**\n * Build the accounting payload for a USD-denominated movement. `at` is REQUIRED and\n * MUST be the execution timestamp (the valuation is point-in-time, per the rule).\n * Pure: the only external call is the injected FxOracle.\n */\nexport async function buildAccountingPayload(input: {\n  usd: number;\n  asset: string;\n  fx: FxOracle;\n  at: string;\n  /** Defaults to \"ARS\". */\n  localCurrency?: CurrencyCode;\n}): Promise<AccountingPayload> {\n  if (!Number.isFinite(input.usd) || input.usd < 0) {\n    throw new TypeError(`buildAccountingPayload: invalid usd amount ${input.usd}`);\n  }\n  const localCurrency = input.localCurrency ?? \"ARS\";\n  const q = await input.fx.rate(\"USD\", localCurrency, input.at);\n  if (!Number.isFinite(q.rate) || q.rate <= 0) {\n    throw new TypeError(`buildAccountingPayload: FX oracle returned an invalid rate ${q.rate}`);\n  }\n  return {\n    usd: input.usd,\n    local: round2(input.usd * q.rate),\n    localCurrency,\n    fxRate: q.rate,\n    fxSource: q.source,\n    at: input.at,\n    asset: input.asset,\n  };\n}\n\n/**\n * A deterministic mock FX oracle for tests + pre-launch dev. `source: \"mock\"` so a\n * downstream tax/invoicing module can REFUSE a mock-sourced valuation in production.\n */\nexport function mockFxOracle(rate = 1000): FxOracle {\n  return {\n    async rate(from, to, at) {\n      return { rate, from, to, at: at ?? \"1970-01-01T00:00:00.000Z\", source: \"mock\" };\n    },\n  };\n}\n","// OpenUsdRail — the FiatRail implementation for Open USD (OUSD).\n//\n// OUSD is the consortium USD stablecoin (Open Standard: Visa/Mastercard/Stripe/\n// BlackRock/Coinbase/... ), designed for businesses, with reserve yield paid back\n// to adopters. ar-agents adopts it as the FLAGSHIP USD rail — but is architected\n// around the FiatRail SEAM, not around OUSD: this is ONE FiatRail impl among many\n// (Bitso/Ripio/Manteca already exist), so the registry/oracle stay rail-neutral.\n//\n// MOCK-ONLY until OUSD is live (launches later in 2026 on Solana/Polygon/Aptos/\n// Stellar) AND the AR legal/FX treatment is cleared. ALL chain interaction lives\n// behind OpenUsdSettlementBackend; core carries ZERO web3 dependencies. Every\n// settlement also emits the accounting_payload (ARS-equivalent at execution) so an\n// OUSD movement is AFIP/ARCA-correct.\n\nimport type {\n  CountryCode,\n  CurrencyCode,\n  FiatRail,\n  FiatRailQuote,\n  FiatRailReceipt,\n  FiatRailStatusReport,\n} from \"../jurisdiction\";\nimport { buildAccountingPayload, type AccountingPayload, type FxOracle } from \"./accounting\";\n\n/** Lifecycle of the OUSD asset. Flip to \"live\" once OUSD is issued + a provider lists it. */\nexport type OpenUsdStatus = \"pre-launch\" | \"live\";\n\n/** Static facts about Open USD. `status` gates any real integration (MOCK until \"live\"). */\nexport const OPEN_USD: {\n  readonly asset: \"OUSD\";\n  readonly issuer: string;\n  readonly chains: readonly string[];\n  readonly status: OpenUsdStatus;\n} = {\n  asset: \"OUSD\",\n  issuer: \"Open Standard\",\n  chains: [\"solana\", \"polygon\", \"aptos\", \"stellar\"],\n  status: \"pre-launch\",\n};\n\n/**\n * The on/off-chain settlement backend for OUSD, injected by the host. The default\n * is a deterministic MOCK (no chain deps). A real backend (Open Standard SDK /\n * Fireblocks / a chain client) is wired ONLY once OUSD is live + legally cleared.\n */\nexport interface OpenUsdSettlementBackend {\n  /** Move `amount` OUSD off-ramp, idempotent by externalId (same key => same txId). */\n  transfer(input: {\n    amount: number;\n    toAsset: string;\n    externalId: string;\n  }): Promise<{ txId: string; depositAddress?: string }>;\n  getStatus?(txId: string): Promise<FiatRailStatusReport>;\n}\n\n/** Deterministic mock backend: txId derived from externalId (idempotent), no I/O. */\nexport function mockOpenUsdBackend(): OpenUsdSettlementBackend {\n  return {\n    async transfer({ externalId }) {\n      let h = 0;\n      for (let i = 0; i < externalId.length; i++) h = (h * 31 + externalId.charCodeAt(i)) >>> 0;\n      return { txId: `ousd-mock-${h.toString(16).padStart(8, \"0\")}` };\n    },\n  };\n}\n\nexport interface OpenUsdRailOptions {\n  /** Local off-ramp fiat (default \"ARS\"). */\n  currency?: CurrencyCode;\n  /** Settlement country (default \"AR\"). */\n  country?: CountryCode;\n  /** FX feed for accounting + off-ramp valuation (injected). */\n  fx: FxOracle;\n  /** On/off-chain backend (default: deterministic mock). */\n  backend?: OpenUsdSettlementBackend;\n  /** Fractional spread charged on the off-ramp quote (0..1, default 0). */\n  spread?: number;\n}\n\n/** OpenUsdRail also exposes {@link accountingFor} to value a raw OUSD movement (no off-ramp). */\nexport interface OpenUsdRail extends FiatRail {\n  readonly asset: \"OUSD\";\n  /** The accounting_payload for a bare OUSD movement of `amount` at `at` (execution time). */\n  accountingFor(input: { amount: number; at: string }): Promise<AccountingPayload>;\n}\n\nfunction round2(n: number): number {\n  return Math.round(n * 100) / 100;\n}\n\n/**\n * Build the OUSD FiatRail. MOCK by default (pass a real `backend` + `fx` when OUSD\n * is live). `settle` is IRREVERSIBLE — callers MUST gate it behind the art.102\n * approval + spending guardrails, exactly like any other FiatRail.\n */\nexport function createOpenUsdRail(opts: OpenUsdRailOptions): OpenUsdRail {\n  const currency: CurrencyCode = opts.currency ?? \"ARS\";\n  const country: CountryCode = opts.country ?? \"AR\";\n  const backend = opts.backend ?? mockOpenUsdBackend();\n  const spread = opts.spread ?? 0;\n\n  async function localPerUsd(at?: string): Promise<number> {\n    const q = await opts.fx.rate(\"USD\", currency, at);\n    if (!Number.isFinite(q.rate) || q.rate <= 0) {\n      throw new TypeError(`OpenUsdRail: FX oracle returned an invalid rate ${q.rate}`);\n    }\n    return q.rate;\n  }\n\n  return {\n    id: \"open-usd\",\n    asset: \"OUSD\",\n    country,\n    currency,\n    direction: \"both\",\n\n    async quote({ amount }): Promise<FiatRailQuote> {\n      const rate = (await localPerUsd()) * (1 - spread);\n      return { amount, out: round2(amount * rate), rate, spread };\n    },\n\n    async settle({ amount, toAsset, externalId }): Promise<FiatRailReceipt> {\n      const rate = (await localPerUsd()) * (1 - spread);\n      const received = round2(amount * rate);\n      const { txId, depositAddress } = await backend.transfer({ amount, toAsset, externalId });\n      return {\n        amount,\n        received,\n        rate,\n        txId,\n        ...(depositAddress ? { depositAddress } : {}),\n      };\n    },\n\n    ...(backend.getStatus\n      ? { getStatus: (txId: string) => backend.getStatus!(txId) }\n      : {}),\n\n    async accountingFor({ amount, at }): Promise<AccountingPayload> {\n      return buildAccountingPayload({ usd: amount, asset: OPEN_USD.asset, fx: opts.fx, localCurrency: currency, at });\n    },\n  };\n}\n"]}