{"version":3,"sources":["../src/errors.ts","../src/hitl.ts"],"names":["DOCS_BASE","formatError","code","message","hint","docsUrl","lines","AgentsKitError","options","ConfigError","ErrorCodes","createApprovalGate","store","id","name","payload","existing","created","pollMs","deadline","current","r","decision","metadata","updated","createInMemoryApprovalStore","map","approval","hit","update","next"],"mappings":"aAIA,IAAMA,CAAAA,CAAY,+BAAA,CAalB,SAASC,CAAAA,CAAYC,EAAcC,CAAAA,CAAiBC,CAAAA,CAAeC,CAAAA,CAA0B,CAC3F,IAAMC,CAAAA,CAAkB,CAAC,CAAA,MAAA,EAASJ,CAAI,MAAMC,CAAO,CAAA,CAAE,CAAA,CACrD,OAAIC,CAAAA,EAAME,CAAAA,CAAM,IAAA,CAAK,CAAA,YAAA,EAAeF,CAAI,CAAA,CAAE,CAAA,CACtCC,CAAAA,EAASC,CAAAA,CAAM,KAAK,CAAA,YAAA,EAAeD,CAAO,CAAA,CAAE,CAAA,CACzCC,EAAM,IAAA,CAAK;AAAA,CAAI,CACxB,CAMO,IAAMC,CAAAA,CAAN,cAA6B,KAAM,CAMxC,WAAA,CAAYC,CAAAA,CAMT,CACD,KAAA,CAAMA,CAAAA,CAAQ,OAAO,CAAA,CACrB,IAAA,CAAK,IAAA,CAAO,gBAAA,CACZ,IAAA,CAAK,IAAA,CAAOA,EAAQ,IAAA,CACpB,IAAA,CAAK,IAAA,CAAOA,CAAAA,CAAQ,IAAA,CACpB,IAAA,CAAK,QAAUA,CAAAA,CAAQ,OAAA,CACvB,IAAA,CAAK,KAAA,CAAQA,CAAAA,CAAQ,MACvB,CAES,QAAA,EAAmB,CAC1B,OAAOP,CAAAA,CAAY,IAAA,CAAK,IAAA,CAAM,KAAK,OAAA,CAAS,IAAA,CAAK,IAAA,CAAM,IAAA,CAAK,OAAO,CACrE,CACF,CAAA,CA6CO,IAAMQ,CAAAA,CAAN,cAA0BF,CAAe,CAC9C,YAAYC,CAAAA,CAMT,CACD,KAAA,CAAM,CAAE,OAAA,CAAS,CAAA,E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9C,MAAA,CAAQ,YACR,SAAA,CAAW,IAAI,IAAA,EAAK,CAAE,WAAA,EACxB,CAAC,CAAA,CACD,GAAI,CAACW,CAAAA,CAAS,MAAM,IAAI,MAAM,CAAA,UAAA,EAAaX,CAAE,CAAA,WAAA,CAAa,CAAA,CAC1D,OAAOW,CACT,CACF,CACF,CAGO,SAASC,CAAAA,EAA6C,CAC3D,IAAMC,EAAM,IAAI,GAAA,CAChB,OAAO,CACL,MAAM,GAAA,CAAIC,EAAU,CAClBD,CAAAA,CAAI,GAAA,CAAIC,CAAAA,CAAS,EAAA,CAAI,CAAE,GAAGA,CAAS,CAAC,EACtC,CAAA,CACA,MAAM,GAAA,CAAOd,EAAyC,CACpD,IAAMe,CAAAA,CAAMF,CAAAA,CAAI,GAAA,CAAIb,CAAE,EACtB,OAAOe,CAAAA,CAAO,CAAE,GAAIA,CAAoB,CAAA,CAAK,IAC/C,CAAA,CACA,MAAM,KAAA,CAASf,CAAAA,CAAYgB,CAAAA,CAA2D,CACpF,IAAMD,CAAAA,CAAMF,CAAAA,CAAI,GAAA,CAAIb,CAAE,CAAA,CACtB,GAAI,CAACe,CAAAA,CAAK,OAAO,IAAA,CACjB,IAAME,CAAAA,CAAO,CAAE,GAAIF,CAAAA,CAAqB,GAAGC,CAAO,CAAA,CAClD,OAAAH,CAAAA,CAAI,GAAA,CAAIb,CAAAA,CAAIiB,CAAyB,CAAA,CAC9BA,CACT,CACF,CACF","file":"hitl.cjs","sourcesContent":["// ---------------------------------------------------------------------------\n// AgentsKit didactic error system — Rust-compiler-style helpful errors\n// ---------------------------------------------------------------------------\n\nconst DOCS_BASE = 'https://www.agentskit.io/docs'\n\n/**\n * Format an error for display, Rust-compiler style.\n *\n * Example output:\n * ```\n * error[AK_ADAPTER_MISSING]: No adapter provided\n *   --> Hint: Pass an adapter when creating the chat controller, e.g.\n *             createChatController({ adapter: openai({ apiKey, model: 'gpt-4o' }) })\n *   --> Docs: https://www.agentskit.io/docs/data/providers\n * ```\n */\nfunction formatError(code: string, message: string, hint?: string, docsUrl?: string): string {\n  const lines: string[] = [`error[${code}]: ${message}`]\n  if (hint) lines.push(`  --> Hint: ${hint}`)\n  if (docsUrl) lines.push(`  --> Docs: ${docsUrl}`)\n  return lines.join('\\n')\n}\n\n// ---------------------------------------------------------------------------\n// Base class\n// ---------------------------------------------------------------------------\n\nexport class AgentsKitError extends Error {\n  readonly code: string\n  readonly hint: string | undefined\n  readonly docsUrl: string | undefined\n  readonly cause: unknown\n\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super(options.message)\n    this.name = 'AgentsKitError'\n    this.code = options.code\n    this.hint = options.hint\n    this.docsUrl = options.docsUrl\n    this.cause = options.cause\n  }\n\n  override toString(): string {\n    return formatError(this.code, this.message, this.hint, this.docsUrl)\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Subclasses\n// ---------------------------------------------------------------------------\n\nexport class AdapterError extends AgentsKitError {\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super({ docsUrl: `${DOCS_BASE}/data/providers`, ...options })\n    this.name = 'AdapterError'\n  }\n}\n\nexport class ToolError extends AgentsKitError {\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super({ docsUrl: `${DOCS_BASE}/agents/tools`, ...options })\n    this.name = 'ToolError'\n  }\n}\n\nexport class MemoryError extends AgentsKitError {\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super({ docsUrl: `${DOCS_BASE}/data/memory`, ...options })\n    this.name = 'MemoryError'\n  }\n}\n\nexport class ConfigError extends AgentsKitError {\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super({ docsUrl: `${DOCS_BASE}/get-started/concepts/errors`, ...options })\n    this.name = 'ConfigError'\n  }\n}\n\nexport class RuntimeError extends AgentsKitError {\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super({ docsUrl: `${DOCS_BASE}/agents/runtime`, ...options })\n    this.name = 'RuntimeError'\n  }\n}\n\nexport class SandboxError extends AgentsKitError {\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super({ docsUrl: `${DOCS_BASE}/production/security/mandatory-sandbox`, ...options })\n    this.name = 'SandboxError'\n  }\n}\n\nexport class SkillError extends AgentsKitError {\n  constructor(options: {\n    code: string\n    message: string\n    hint?: string\n    docsUrl?: string\n    cause?: unknown\n  }) {\n    super({ docsUrl: `${DOCS_BASE}/agents/skills`, ...options })\n    this.name = 'SkillError'\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Error code constants\n// ---------------------------------------------------------------------------\n\nexport const ErrorCodes = {\n  // Adapter errors\n  AK_ADAPTER_MISSING: 'AK_ADAPTER_MISSING',\n  AK_ADAPTER_STREAM_FAILED: 'AK_ADAPTER_STREAM_FAILED',\n\n  // Tool errors\n  AK_TOOL_NOT_FOUND: 'AK_TOOL_NOT_FOUND',\n  AK_TOOL_EXEC_FAILED: 'AK_TOOL_EXEC_FAILED',\n  AK_TOOL_PEER_MISSING: 'AK_TOOL_PEER_MISSING',\n  AK_TOOL_INVALID_INPUT: 'AK_TOOL_INVALID_INPUT',\n  AK_TOOL_QUOTA_EXCEEDED: 'AK_TOOL_QUOTA_EXCEEDED',\n  AK_TOOL_FORBIDDEN: 'AK_TOOL_FORBIDDEN',\n\n  // Memory errors\n  AK_MEMORY_LOAD_FAILED: 'AK_MEMORY_LOAD_FAILED',\n  AK_MEMORY_SAVE_FAILED: 'AK_MEMORY_SAVE_FAILED',\n  AK_MEMORY_DESERIALIZE_FAILED: 'AK_MEMORY_DESERIALIZE_FAILED',\n  AK_MEMORY_PEER_MISSING: 'AK_MEMORY_PEER_MISSING',\n  AK_MEMORY_REMOTE_HTTP: 'AK_MEMORY_REMOTE_HTTP',\n\n  // Config errors\n  AK_CONFIG_INVALID: 'AK_CONFIG_INVALID',\n\n  // Runtime errors\n  AK_RUNTIME_INVALID_INPUT: 'AK_RUNTIME_INVALID_INPUT',\n  AK_RUNTIME_STEP_FAILED: 'AK_RUNTIME_STEP_FAILED',\n  AK_RUNTIME_DELEGATE_FAILED: 'AK_RUNTIME_DELEGATE_FAILED',\n\n  // Sandbox errors\n  AK_SANDBOX_DENIED: 'AK_SANDBOX_DENIED',\n  AK_SANDBOX_INVALID_TOOL: 'AK_SANDBOX_INVALID_TOOL',\n  AK_SANDBOX_PEER_MISSING: 'AK_SANDBOX_PEER_MISSING',\n  AK_SANDBOX_BACKEND_FAILED: 'AK_SANDBOX_BACKEND_FAILED',\n\n  // Skill errors\n  AK_SKILL_INVALID: 'AK_SKILL_INVALID',\n  AK_SKILL_DUPLICATE: 'AK_SKILL_DUPLICATE',\n} as const\n","import { AgentsKitError, ConfigError, ErrorCodes } from './errors'\n\n/**\n * Human-in-the-loop primitives. A gate pauses agent execution at a\n * named decision point and records an `Approval` in a user-supplied\n * `ApprovalStore`. When a human (or another automation) writes a\n * decision, any waiter resumes with that decision.\n *\n * The store can be in-memory for tests, SQLite for single-node\n * deployments, or a shared DB / queue for multi-worker setups. Any\n * store that implements the 3-method contract works.\n */\n\nexport type ApprovalDecision = 'approved' | 'rejected'\n\nexport interface Approval<TPayload = unknown> {\n  id: string\n  /** Logical gate name (e.g. 'delete-user', 'send-email'). */\n  name: string\n  /** Caller-provided context for whoever reviews the approval. */\n  payload: TPayload\n  status: 'pending' | ApprovalDecision | 'cancelled'\n  createdAt: string\n  decidedAt?: string\n  /** Free-form metadata the approver attached (reason, user id, etc.). */\n  decisionMetadata?: Record<string, unknown>\n}\n\nexport interface ApprovalStore {\n  /** Persist a new pending approval. */\n  put: <T>(approval: Approval<T>) => Promise<void>\n  /** Read the current state of an approval. */\n  get: <T>(id: string) => Promise<Approval<T> | null>\n  /** Update status + metadata. */\n  patch: <T>(id: string, update: Partial<Approval<T>>) => Promise<Approval<T> | null>\n}\n\nexport interface RequestApprovalInput<TPayload> {\n  /** Gate name (reuse across invocations — how approvers identify it). */\n  name: string\n  /** Context passed to reviewers. Safe to store — no secrets. */\n  payload: TPayload\n  /** Stable id for idempotent gating (e.g. tool call id). */\n  id: string\n}\n\nexport interface ApprovalGate<TPayload = unknown> {\n  /**\n   * Reserve or reuse an approval by id. First caller creates a\n   * `pending` record. Subsequent calls return the existing record\n   * — perfect for resuming a crashed run.\n   */\n  request: (input: RequestApprovalInput<TPayload>) => Promise<Approval<TPayload>>\n  /**\n   * Wait for `approved` or `rejected`. Resolves immediately if the\n   * approval is already decided. Polls at `pollMs` (default 500ms)\n   * up to `timeoutMs` (default Infinity).\n   */\n  await: (\n    id: string,\n    options?: { timeoutMs?: number; pollMs?: number; signal?: AbortSignal },\n  ) => Promise<Approval<TPayload>>\n  /** Approve, rejecting, or cancelling an approval. */\n  decide: (\n    id: string,\n    decision: ApprovalDecision,\n    metadata?: Record<string, unknown>,\n  ) => Promise<Approval<TPayload>>\n  cancel: (id: string) => Promise<Approval<TPayload>>\n}\n\n/**\n * Build an approval gate over any `ApprovalStore`. The core loop\n * couldn't be simpler — create-or-load + poll + patch — but having it\n * behind a stable contract lets you swap persistence without touching\n * agent code.\n */\nexport function createApprovalGate<TPayload = unknown>(\n  store: ApprovalStore,\n): ApprovalGate<TPayload> {\n  return {\n    async request({ id, name, payload }) {\n      const existing = await store.get<TPayload>(id)\n      if (existing) return existing\n      const created: Approval<TPayload> = {\n        id,\n        name,\n        payload,\n        status: 'pending',\n        createdAt: new Date().toISOString(),\n      }\n      await store.put(created)\n      return created\n    },\n\n    async await(id, options = {}) {\n      const pollMs = Math.max(50, options.pollMs ?? 500)\n      const deadline =\n        options.timeoutMs !== undefined && options.timeoutMs !== Infinity\n          ? Date.now() + options.timeoutMs\n          : Infinity\n      while (true) {\n        if (options.signal?.aborted) {\n          throw new AgentsKitError({\n            code: ErrorCodes.AK_CONFIG_INVALID,\n            message: `await approval aborted (id=\"${id}\")`,\n            hint: 'Caller passed an AbortSignal that fired before the approval was decided.',\n          })\n        }\n        const current = await store.get<TPayload>(id)\n        if (!current) {\n          throw new ConfigError({\n            code: ErrorCodes.AK_CONFIG_INVALID,\n            message: `approval \"${id}\" not found`,\n            hint: 'Open the approval with createApprovalGate.open() before awaiting it.',\n          })\n        }\n        if (current.status !== 'pending') return current\n        if (Date.now() >= deadline) {\n          throw new AgentsKitError({\n            code: ErrorCodes.AK_CONFIG_INVALID,\n            message: `approval \"${id}\" timed out after ${options.timeoutMs}ms`,\n            hint: 'Extend options.timeoutMs (default Infinity), or wire a faster decider.',\n          })\n        }\n        await new Promise(r => setTimeout(r, pollMs))\n      }\n    },\n\n    async decide(id, decision, metadata) {\n      const updated = await store.patch<TPayload>(id, {\n        status: decision,\n        decidedAt: new Date().toISOString(),\n        decisionMetadata: metadata,\n      })\n      if (!updated) {\n        throw new ConfigError({\n          code: ErrorCodes.AK_CONFIG_INVALID,\n          message: `approval \"${id}\" not found`,\n          hint: 'The approval id was never opened, or it was cleared from the store.',\n        })\n      }\n      return updated\n    },\n\n    async cancel(id) {\n      const updated = await store.patch<TPayload>(id, {\n        status: 'cancelled',\n        decidedAt: new Date().toISOString(),\n      })\n      if (!updated) throw new Error(`approval \"${id}\" not found`)\n      return updated\n    },\n  }\n}\n\n/** In-memory `ApprovalStore` — handy for tests and single-worker demos. */\nexport function createInMemoryApprovalStore(): ApprovalStore {\n  const map = new Map<string, Approval<unknown>>()\n  return {\n    async put(approval) {\n      map.set(approval.id, { ...approval })\n    },\n    async get<T>(id: string): Promise<Approval<T> | null> {\n      const hit = map.get(id)\n      return hit ? ({ ...(hit as Approval<T>) }) : null\n    },\n    async patch<T>(id: string, update: Partial<Approval<T>>): Promise<Approval<T> | null> {\n      const hit = map.get(id)\n      if (!hit) return null\n      const next = { ...(hit as Approval<T>), ...update }\n      map.set(id, next as Approval<unknown>)\n      return next\n    },\n  }\n}\n"]}