{"openapi":"3.1.0","info":{"title":"Salesbooth Agent API","version":"1.20.2","description":"AI-agent integration surface for discovery, negotiation, delegation, trust, tooling, and executable commerce workflows.","contact":{"name":"Salesbooth","url":"https://salesbooth.com"},"license":{"name":"Proprietary","identifier":"LicenseRef-Proprietary"}},"servers":[{"url":"https://api.salesbooth.com/v1","description":"Salesbooth API (Production)"}],"security":[{"bearerAuth":[]},{"apiKeyHeader":[]}],"tags":[{"name":"Deals","description":"Manage deals and the deal lifecycle"},{"name":"Contracts","description":"Manage contracts and agreements"},{"name":"Discovery","description":"Agent deal discovery — browse available offers"},{"name":"Negotiations","description":"Agent-to-agent deal negotiation protocol"},{"name":"Delegations","description":"Agent authorization delegations with spending limits and delegation chains"},{"name":"Schema","description":"Machine-readable schema definitions for state machines and entity metadata. No authentication required."},{"name":"Payments","description":"Payment lifecycle management via payment intents — create, confirm, and refund payments for deals"},{"name":"Agent Tools","description":"AI agent tool schema and MCP server — machine-readable capability discovery for LLM function-calling"},{"name":"System","description":"System health checks and observability endpoints"},{"name":"Trust","description":"Tenant trust level system — view trust status, progress metrics, auto top-up ceilings, and level change history"},{"name":"AgentWorkflows","description":"Autonomous deal orchestration — plan and execute multi-step deal workflows within delegation spending limits"},{"name":"AgentTrust","description":"Agent trust levels — per-API-key trust scoring, trust locks for capability gating, promotion/demotion, and abuse protection"},{"name":"Federation","description":"Cross-instance agent-to-agent deal negotiation protocol — discovery manifests, signed negotiation envelopes, escrow coordination, and federated audit trails"},{"name":"Events","description":"Real-time event streaming via Server-Sent Events — subscribe to deal, negotiation, payment, and other domain events with automatic reconnection and missed-event recovery"}],"x-tagGroups":[{"name":"Core Commerce","tags":["Deals","Contracts","Payments"]},{"name":"AI Agents","tags":["Agent Tools","AgentWorkflows","AgentTrust","Delegations","Discovery","Negotiations","Federation"]},{"name":"Payments & Billing","tags":["Trust"]},{"name":"Webhooks & Events","tags":["Events"]},{"name":"Developer Tools","tags":["Schema","System"]}],"paths":{"/api":{"servers":[{"url":"https://salesbooth.com","description":"Salesbooth API root"}],"get":{"tags":["System"],"summary":"API discovery and endpoint listing","description":"Returns API discovery information including available endpoints, authentication methods, agent integration details, and a link to the OpenAPI specification. No authentication required.","operationId":"getApiIndex","security":[],"responses":{"200":{"description":"API discovery information","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"name":{"type":"string","example":"Salesbooth API"},"version":{"type":"string","example":"1.20.2"},"base_url":{"type":"string","example":"https://api.salesbooth.com/v1"},"documentation":{"type":"string","example":"https://salesbooth.com/docs"},"openapi_spec":{"type":"string","example":"https://api.salesbooth.com/openapi.json"},"endpoints":{"type":"object","description":"Map of core endpoint names to their URL, supported methods, and description","additionalProperties":{"type":"object","properties":{"url":{"type":"string"},"methods":{"type":"array","items":{"type":"string"}},"description":{"type":"string"}},"required":["url","methods","description"]}},"schema":{"type":"object","description":"State machine schema endpoint URLs","additionalProperties":{"type":"object","properties":{"url":{"type":"string"},"methods":{"type":"array","items":{"type":"string"}},"description":{"type":"string"},"authentication":{"type":"string"}},"required":["url","methods","description"]}},"agent":{"type":"object","description":"Agent integration URLs for AI agent discovery (tools, MCP, agent SDK)","properties":{"tools_url":{"type":"string","description":"URL for AI agent tool definitions (universal, AI provider, AI provider)"},"tools_description":{"type":"string"},"mcp_url":{"type":"string","description":"Model Context Protocol (MCP) server URL — JSON-RPC 2.0 over HTTP"},"mcp_description":{"type":"string"},"agent_sdk_url":{"type":"string","description":"Agent SDK URL with getToolDefinitions() and executeTool() methods"},"agent_sdk_description":{"type":"string"},"deal_terms_schema":{"type":"string"},"required_scopes":{"type":"array","items":{"type":"string"}}},"required":["tools_url","mcp_url","agent_sdk_url"]},"authentication":{"type":"object","description":"Authentication method descriptions and key format","properties":{"methods":{"type":"array","items":{"type":"string"},"description":"Supported authentication header formats"},"key_format":{"type":"string","example":"sb_live_* or sb_test_*"},"manage_keys_api":{"type":"string"}},"required":["methods","key_format"]},"recommended_spec":{"type":"string","example":"https://api.salesbooth.com/core-openapi.json","description":"Recommended starting spec covering core public commerce flows."},"specs":{"type":"object","description":"Published public OpenAPI spec variants for different integration audiences.","properties":{"full":{"type":"object","properties":{"url":{"type":"string","example":"https://api.salesbooth.com/openapi.json"},"description":{"type":"string","example":"Default public compatibility specification. Admin and internal dashboard surfaces are not published."}},"required":["url","description"]},"core":{"type":"object","properties":{"url":{"type":"string","example":"https://api.salesbooth.com/core-openapi.json"},"description":{"type":"string","example":"Recommended starting spec for customers, products, deals, contracts, payments, webhooks, and machine-readable commerce schemas."}},"required":["url","description"]},"widget":{"type":"object","properties":{"url":{"type":"string","example":"https://api.salesbooth.com/widget-openapi.json"},"description":{"type":"string","example":"Embedded widget flows for configuration, validation, saved configs, pricing previews, bookings, and widget analytics."}},"required":["url","description"]},"public":{"type":"object","properties":{"url":{"type":"string","example":"https://api.salesbooth.com/public-openapi.json"},"description":{"type":"string","example":"Compatibility alias for the default public spec that combines the legacy public core and widget surfaces in one document."}},"required":["url","description"]},"agent":{"type":"object","properties":{"url":{"type":"string","example":"https://api.salesbooth.com/agent-openapi.json"},"description":{"type":"string","example":"Agent workflows, tools, trust, negotiation, federation, and executable commerce flows."}},"required":["url","description"]}},"required":["full","core","widget","public","agent"]}}}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"}}}},"/deals":{"get":{"tags":["Deals"],"summary":"List, retrieve, or bulk export deals (action=export for CSV/JSON/JSONL)","description":"Returns a paginated list of deals, or a single deal when `id` is provided.\n\nSupported actions (with `id`):\n- `terms` — Get structured deal terms\n- `audit` — Get deal audit trail\n- `verify_audit` — Verify audit-chain integrity\n- `escrow` — Get escrow status for the deal\n- `credential` — Get the deal verifiable credential\n- `valid_transitions` — Get valid status transitions\n- `settlements` — Get settlement breakdown\n- `signing_certificate` — Get the signing proof document\n\nSupported actions (without `id`):\n- `compare-terms` — Compare terms between two deals (requires `deal_id_1` and `deal_id_2`)\n- `export` — Bulk export deals as CSV/JSON/JSONL (no `id` required)","operationId":"getDeals","security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Deal ID to retrieve a specific deal (e.g. `deal_xxxxxxxxxx`). When provided, returns a single deal object instead of a list.","required":false,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}},{"name":"deal_id","in":"query","description":"Deprecated alias for `id`. Use `id` instead.","required":false,"deprecated":true,"schema":{"type":"string"}},{"name":"status","in":"query","description":"Filter by deal status","required":false,"schema":{"type":"string","enum":["draft","in_progress","pending_signature","awaiting_signatures","pending_payment","partially_accepted","closed","cancelled","expired"]}},{"name":"action","in":"query","description":"Action to perform. `terms` returns structured deal terms (requires `id`). `compare-terms` compares terms between two deals (requires `deal_id_1` and `deal_id_2`). `signing_certificate` returns a structured proof document of the signing event for legal purposes. `export` — Bulk export deals as CSV, JSON, or JSONL (supports filters and include options). `settlements` returns the settlement breakdown for a deal (requires `id`).","required":false,"schema":{"type":"string","enum":["terms","compare-terms","audit","verify_audit","escrow","credential","valid_transitions","settlements","signing_certificate","export"]}},{"name":"deal_id_1","in":"query","description":"First deal ID for `compare-terms` action","required":false,"schema":{"type":"string"}},{"name":"deal_id_2","in":"query","description":"Second deal ID for `compare-terms` action","required":false,"schema":{"type":"string"}},{"name":"customer_id","in":"query","description":"Filter by customer ID","required":false,"schema":{"type":"string"}},{"name":"created_after","in":"query","description":"Filter deals created after this datetime (ISO 8601)","required":false,"schema":{"type":"string","format":"date-time"}},{"name":"created_before","in":"query","description":"Filter deals created before this datetime (ISO 8601)","required":false,"schema":{"type":"string","format":"date-time"}},{"name":"search","in":"query","description":"Search by deal title or deal ID","required":false,"schema":{"type":"string"}},{"$ref":"#/components/parameters/limit"},{"$ref":"#/components/parameters/offset"},{"$ref":"#/components/parameters/after"},{"$ref":"#/components/parameters/before"},{"$ref":"#/components/parameters/sort"},{"$ref":"#/components/parameters/fields"},{"name":"include","in":"query","required":false,"description":"Comma-separated list of nested resources or export data to include.\n\nFor **list/detail requests**: controls which nested resources are embedded in each deal object. Available values: `customer`, `line_items`, `pricing`, `terms`, `payment`, `escrow`, `metadata`, `deal_score`, `outcome`. No nested resources are included by default on list endpoints.\n\nFor **`action=export`**: controls which related records are appended to each exported deal row. Valid values: `items`, `payments`, `negotiations`.","schema":{"type":"string","examples":["line_items,pricing","items,payments,negotiations"]}},{"$ref":"#/components/parameters/exclude"},{"name":"format","in":"query","description":"Response/export format. For list queries: `minimal` returns only `id`, `status`, and `updated_at`. For `action=export`: `csv` (default), `json`, or `jsonl`.","required":false,"schema":{"type":"string","enum":["minimal","csv","json","jsonl"]}},{"name":"min_value","in":"query","description":"Filter deals with total value >= this amount (used with `action=export`). Must be a non-negative number.","required":false,"schema":{"type":"number","minimum":0}},{"name":"max_value","in":"query","description":"Filter deals with total value <= this amount (used with `action=export`). Must be a non-negative number and greater than or equal to `min_value` when both are provided.","required":false,"schema":{"type":"number","minimum":0}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"oneOf":[{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"deals":{"type":"array","items":{"$ref":"#/components/schemas/DealListItem"}},"pagination":{"oneOf":[{"$ref":"#/components/schemas/Pagination"},{"$ref":"#/components/schemas/CursorPagination"}]}},"required":["deals","pagination"]}},"required":["error","success","data"]},{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"deal":{"$ref":"#/components/schemas/Deal"}},"required":["deal"]}},"required":["error","success","data"]},{"type":"array","description":"Raw JSON array of deal export records (returned when `action=export&format=json`). Each element is a deal export record.","items":{"type":"object","description":"Deal export record","properties":{"deal_id":{"type":"string"},"title":{"type":["string","null"]},"status":{"type":"string"},"total_amount":{"type":"number"},"currency":{"type":"string"},"customer_name":{"type":["string","null"]},"customer_email":{"type":["string","null"]},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}},"additionalProperties":true}},{"type":"object","description":"Terms comparison result between two deals (action=compare-terms)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealCompareTermsResult"}},"required":["error","success","data"]},{"type":"object","description":"Paginated audit trail for a deal (action=audit)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealAuditTrailResult"}},"required":["error","success","data"]},{"type":"object","description":"Valid transitions for a deal (action=valid_transitions)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/ValidTransitionsResponse"}},"required":["error","success","data"]},{"type":"object","description":"Settlement records for a deal (action=settlements)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"settlements":{"type":"array","items":{"$ref":"#/components/schemas/DealSettlement"}}},"required":["settlements"]}},"required":["error","success","data"]},{"type":"object","description":"Audit chain verification result (action=verify_audit)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealVerifyAuditResult"}},"required":["error","success","data"]},{"type":"object","description":"Escrow status for a deal (action=escrow)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealEscrowResult"}},"required":["error","success","data"]},{"type":"object","description":"Verifiable credential for a deal (action=credential)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealCredentialResult"}},"required":["error","success","data"]},{"type":"object","description":"Signing certificate document for a deal (action=signing_certificate)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealSigningCertificateResult"}},"required":["error","success","data"]},{"type":"object","description":"Structured machine-readable terms for a deal (action=terms)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealTermsResult"}},"required":["error","success","data"]}]}},"text/csv":{"schema":{"type":"string","description":"CSV file content. Returned when `action=export&format=csv` (default export format). First row is the header. Columns vary based on `include` query parameter."}},"application/x-ndjson":{"schema":{"type":"string","description":"Newline-delimited JSON (NDJSON). Returned when `action=export&format=jsonl`. Each line is a complete JSON object representing one deal export record."}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"post":{"tags":["Deals"],"summary":"Create a deal or perform deal actions (including partial_accept)","description":"Publishable widget keys are limited to widget-owned checkout mutations. They may create deals, add items, apply discounts, and transition their own widget-created deals through the checkout flow. Admin-only deal actions are rejected for publishable auth. For signing, `action=sign` requires `deals:sign`; API keys with `deals:write` for backward compatibility inherit `deals:sign`. Delegation auth still requires `deals:sign` in `allowed_actions`.","operationId":"postDeal","x-action-scopes":{"default":[["deals:write"]],"create-configured":[["deals:write"],["agent:execute"]],"sign":[["deals:sign"]]},"security":[{"bearerAuth":["deals:write"]},{"bearerAuth":["deals:sign"]},{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["deals:write"]},{"apiKeyHeader":["deals:sign"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Deal ID for actions on an existing deal","required":false,"schema":{"type":"string"}},{"name":"action","in":"query","description":"Action to perform on the deal. Scope varies by action: most actions use `deals:write`; `create-configured` also accepts `agent:execute`; `sign` routes through `deals:sign`.","required":false,"schema":{"type":"string","enum":["add_item","update_item","apply_discount","transition","sign","set-terms","create-configured","partial_accept","escrow","release_escrow","refund_escrow","fulfill_condition","revoke_credential","unsign","record-outcome","save-as-template"]}},{"name":"item_id","in":"query","description":"Line item ID (required for `update_item` action)","required":false,"schema":{"type":"string"}},{"name":"status","in":"query","description":"Target status for the `transition` action","required":false,"schema":{"type":"string","enum":["in_progress","pending_signature","awaiting_signatures","pending_payment","partially_accepted","closed","cancelled","expired"]}},{"$ref":"#/components/parameters/validateOnly"},{"$ref":"#/components/parameters/idempotencyKey"}],"requestBody":{"description":"Request body varies by action. See schema options.","required":true,"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/DealCreateRequest"},{"$ref":"#/components/schemas/DealAddItemRequest"},{"$ref":"#/components/schemas/DealUpdateItemRequest"},{"$ref":"#/components/schemas/DealApplyDiscountRequest"},{"$ref":"#/components/schemas/DealSignRequest"},{"$ref":"#/components/schemas/DealSetTermsRequest"},{"$ref":"#/components/schemas/DealCreateConfiguredRequest"},{"$ref":"#/components/schemas/DealPartialAcceptRequest"},{"$ref":"#/components/schemas/DealEscrowRequest"},{"$ref":"#/components/schemas/DealReleaseEscrowRequest"},{"$ref":"#/components/schemas/DealRefundEscrowRequest"},{"$ref":"#/components/schemas/DealFulfillConditionRequest"},{"$ref":"#/components/schemas/DealRevokeCredentialRequest"},{"$ref":"#/components/schemas/DealUnsignRequest"},{"$ref":"#/components/schemas/DealRecordOutcomeRequest"},{"$ref":"#/components/schemas/DealSaveAsTemplateRequest"}]}}}},"responses":{"201":{"description":"Returned for deal creation (no action), create-configured, escrow, and save-as-template. Standard creation and create-configured return `{ deal: Deal }`, escrow returns `{ escrow: Escrow }`, save-as-template returns `{ template: DealTemplate }`.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"oneOf":[{"type":"object","properties":{"deal":{"$ref":"#/components/schemas/Deal"}},"required":["deal"],"description":"Returned for standard deal creation and most actions"},{"type":"object","properties":{"escrow":{"$ref":"#/components/schemas/Escrow"}},"required":["escrow"],"description":"Returned when action=escrow"},{"type":"object","properties":{"template":{"$ref":"#/components/schemas/DealTemplate"}},"required":["template"],"description":"Returned when action=save-as-template"}],"description":"Returns `{ deal }` for standard create and action requests, `{ escrow }` when action=escrow, or `{ template }` when action=save-as-template."}},"required":["error","success","data"]}}}},"200":{"description":"Action performed on existing deal, or validation passed (validate_only=true). The shape of `data` depends on the action: `release_escrow`, `refund_escrow`, and `fulfill_condition` return a bare `Escrow` object; `record-outcome` returns a bare `DealOutcomeResult`; `revoke_credential` returns a bare `DealCredentialRevocationResult`; basic `validate_only=true` returns a bare `ValidationResult` (`{ valid, message }`); all other actions return `{ deal: Deal }`.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"oneOf":[{"type":"object","properties":{"deal":{"$ref":"#/components/schemas/Deal"}},"required":["deal"],"description":"Returned for add_item, update_item, apply_discount, sign, transition, unsign, set-terms, partial_accept, and create-configured validate_only"},{"$ref":"#/components/schemas/ValidationResult"},{"$ref":"#/components/schemas/Escrow"},{"$ref":"#/components/schemas/DealOutcomeResult"},{"$ref":"#/components/schemas/DealCredentialRevocationResult"}],"description":"Returns `{ deal }` for most action requests (add_item, update_item, apply_discount, sign, transition, unsign, set-terms, partial_accept, create-configured with validate_only); `Escrow` for release_escrow/refund_escrow/fulfill_condition; `DealOutcomeResult` for record-outcome; `DealCredentialRevocationResult` for revoke_credential; `ValidationResult` (`{ valid, message }`) when validate_only=true on basic deal creation."}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"patch":{"tags":["Deals"],"summary":"Update a deal","description":"Publishable widget keys may patch only their own widget-created deals, and only the checkout fields used to attach the buyer and payment terms.","operationId":"patchDeal","security":[{"bearerAuth":["deals:write"]},{"apiKeyHeader":["deals:write"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Deal ID to update","required":true,"schema":{"type":"string"}},{"$ref":"#/components/parameters/ifMatch"},{"$ref":"#/components/parameters/idempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DealUpdateRequest"}}}},"responses":{"200":{"description":"Deal updated","headers":{"ETag":{"description":"New resource version after update","schema":{"type":"string","example":"W/\"2\""}}},"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"deal":{"$ref":"#/components/schemas/Deal"}},"required":["deal"],"description":"The updated deal object."}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"412":{"$ref":"#/components/responses/PreconditionFailed"},"422":{"description":"Unprocessable Entity — status changes must use the transition action","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"428":{"$ref":"#/components/responses/PreconditionRequired"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"delete":{"tags":["Deals"],"summary":"Cancel a deal or remove a line item","description":"Publishable widget keys cannot cancel deals, hard-delete deals, or remove deal line items through the generic /deals endpoint. Optional cancellation metadata can be sent as query parameters (`reason`, `notes`) or as an optional JSON request body.","operationId":"deleteDeal","security":[{"bearerAuth":["deals:write"]},{"apiKeyHeader":["deals:write"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Deal ID","required":true,"schema":{"type":"string"}},{"name":"action","in":"query","description":"Action to perform. Use `remove_item` to remove a line item instead of cancelling.","required":false,"schema":{"type":"string","enum":["remove_item"]}},{"name":"item_id","in":"query","description":"Line item ID to remove (required when action=remove_item)","required":false,"schema":{"type":"string"}},{"name":"reason","in":"query","description":"Optional cancellation reason when cancelling a deal. May be sent as a query parameter instead of in the JSON request body.","required":false,"schema":{"type":"string","enum":["price","competitor","timing","budget","fit","no_response","champion_left","terms","other"]}},{"name":"notes","in":"query","description":"Optional cancellation notes when cancelling a deal. May be sent as a query parameter instead of in the JSON request body.","required":false,"schema":{"type":"string"}},{"$ref":"#/components/parameters/ifMatchOptional"},{"$ref":"#/components/parameters/idempotencyKey"}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DealCancellationRequest"}}}},"responses":{"200":{"description":"Deal cancelled, deleted, or item removed. All paths return { message, deal_id, deal } with the deal object reflecting the state at the time of the operation.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DealDeleteResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"412":{"$ref":"#/components/responses/PreconditionFailed"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}}},"/deals/verify":{"get":{"tags":["Deals"],"summary":"Verify deal or contract integrity","description":"Public endpoint (no authentication required). Verifies that a deal or contract has not been tampered with after signing by comparing the current state hash against the signed state hash. **At least one of `id` or `contract_id` must be provided.**","operationId":"verifyDeal","security":[],"x-required-one-of":[["id","contract_id"]],"parameters":[{"name":"id","in":"query","description":"Deal ID to verify","required":false,"schema":{"type":"string"}},{"name":"contract_id","in":"query","description":"Contract ID to verify","required":false,"schema":{"type":"string"}}],"responses":{"200":{"description":"Verification result","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","example":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"verification":{"type":"object","properties":{"deal_id":{"type":"string"},"status":{"type":"string","enum":["verified","tampered","unsigned"],"description":"verified = deal matches signed state, tampered = deal modified after signing, unsigned = no signature exists"},"message":{"type":"string"},"deal_hash":{"type":"object","properties":{"stored":{"type":["string","null"]},"current":{"type":"string"},"matches":{"type":"boolean"}}},"signature":{"type":["object","null"],"properties":{"signature_id":{"type":"string"},"signer_type":{"type":"string"},"signer_id":{"type":"string"},"signature_method":{"type":"string"},"signed_at":{"type":"string","format":"date-time"},"ip_address":{"type":"string"},"valid":{"type":"boolean"}}},"verified_at":{"type":"string","format":"date-time"},"verification_method":{"type":"string","description":"Verification method used (e.g. 'public_key' for Ed25519 signatures)","example":"public_key"},"verification_note":{"type":"string","description":"Human-readable note about verification capabilities"}}}}}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"429":{"$ref":"#/components/responses/RateLimited"}}}},"/contracts":{"get":{"tags":["Contracts"],"summary":"List or retrieve contracts","description":"Returns a paginated list of contracts, or a single contract when `id` is provided.","operationId":"getContracts","security":[{"bearerAuth":["contracts:read"]},{"apiKeyHeader":["contracts:read"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Contract ID to retrieve a specific contract. When provided, returns a single contract object.","required":false,"schema":{"type":"integer"}},{"name":"contract_id","in":"query","description":"Deprecated alias for `id`. Use `id` instead.","required":false,"deprecated":true,"schema":{"type":"integer"}},{"name":"action","in":"query","description":"Action to perform on a specific contract (requires `id`). `audit` returns the audit trail. `verify_audit` verifies hash chain integrity. `signing_certificate` returns a structured proof document of the signing event for legal purposes.","required":false,"schema":{"type":"string","enum":["audit","verify_audit","signing_certificate"]}},{"name":"status","in":"query","description":"Filter by contract status","required":false,"schema":{"type":"string","enum":["draft","signed","pending","active","terminated","expired"]}},{"name":"customer_id","in":"query","description":"Filter by customer ID","required":false,"schema":{"type":"string"}},{"name":"renewal_type","in":"query","description":"Filter by renewal type","required":false,"schema":{"type":"string","enum":["manual","auto","none"]}},{"name":"expiring_soon","in":"query","description":"Filter contracts expiring within N days","required":false,"schema":{"type":"integer","minimum":1}},{"$ref":"#/components/parameters/limit"},{"$ref":"#/components/parameters/offset"},{"$ref":"#/components/parameters/after"},{"$ref":"#/components/parameters/before"},{"$ref":"#/components/parameters/sort"},{"$ref":"#/components/parameters/fields"},{"$ref":"#/components/parameters/include"},{"$ref":"#/components/parameters/exclude"}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"oneOf":[{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"contracts":{"type":"array","items":{"$ref":"#/components/schemas/ContractListItem"}},"pagination":{"oneOf":[{"$ref":"#/components/schemas/Pagination"},{"$ref":"#/components/schemas/CursorPagination"}]}},"required":["contracts","pagination"]}},"required":["error","success","data"]},{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"contract":{"$ref":"#/components/schemas/Contract"}},"required":["contract"]}},"required":["error","success","data"]},{"type":"object","description":"Response when action=audit. Returns the paginated audit trail for a specific contract.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"entries":{"type":"array","description":"Audit trail entries in chronological order","items":{"type":"object","properties":{"log_id":{"type":"integer","description":"Unique audit log entry ID"},"entity_type":{"type":"string","description":"Type of entity audited"},"entity_id":{"type":"string","description":"ID of the audited entity"},"action":{"type":"string","description":"Action that was performed"},"actor_type":{"type":"string","description":"Type of actor who performed the action (user, customer, agent, system)"},"actor_id":{"type":"string","description":"ID of the actor who performed the action"},"changes":{"type":["object","null"],"description":"Field-level changes recorded for this entry"},"snapshot":{"type":["object","null"],"description":"Full entity snapshot at time of action"},"previous_hash":{"type":["string","null"],"description":"SHA-256 hash of the previous entry in the chain"},"entry_hash":{"type":"string","description":"SHA-256 hash of this entry (for chain integrity verification)"},"created_at":{"type":"string","format":"date-time","description":"Timestamp when this audit entry was created"}},"required":["log_id","entity_type","entity_id","action","created_at"]}},"pagination":{"type":"object","properties":{"total":{"type":"integer","description":"Total number of audit entries for this contract"},"limit":{"type":"integer","description":"Maximum entries returned per page"},"offset":{"type":"integer","description":"Number of entries skipped"},"count":{"type":"integer","description":"Number of entries returned in this response"}},"required":["total","limit","offset","count"]}},"required":["entries","pagination"]}},"required":["error","success","data"]},{"type":"object","description":"Response when action=verify_audit. Returns the hash chain integrity verification result for a contract's audit trail.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"entity_type":{"type":"string","description":"Entity type that was verified","example":"contract"},"entity_id":{"type":"string","description":"ID of the entity whose audit trail was verified"},"status":{"type":"string","enum":["verified","tampered","no_entries"],"description":"Result of the hash chain integrity check. `verified` means all entries are intact. `tampered` means the chain has been broken or modified. `no_entries` means no audit entries exist."},"message":{"type":"string","description":"Human-readable description of the verification result"},"total_entries":{"type":"integer","description":"Total number of audit entries checked"},"verified_at":{"type":"string","format":"date-time","description":"Timestamp when the verification was performed"},"first_entry":{"type":"integer","description":"Log ID of the first entry in the chain (present when status=verified)"},"last_entry":{"type":"integer","description":"Log ID of the last entry in the chain (present when status=verified)"},"broken_at":{"type":"object","description":"Details of where the chain was broken (present when status=tampered)","properties":{"entry_index":{"type":"integer","description":"Zero-based index of the entry where tampering was detected"},"log_id":{"type":"integer","description":"Log ID of the tampered entry"},"reason":{"type":"string","description":"Why the entry failed verification (e.g. 'previous_hash mismatch' or 'entry_hash mismatch')"}},"required":["entry_index","log_id","reason"]}},"required":["entity_type","entity_id","status","message","total_entries","verified_at"]}},"required":["error","success","data"]},{"type":"object","description":"Response when action=signing_certificate. Returns a structured legal compliance proof document for the contract signing event, referencing the Electronic Transactions Act 1999 (Cth).","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"certificate_version":{"type":"string","description":"Version of the certificate format","example":"1.0"},"generated_at":{"type":"string","format":"date-time","description":"Timestamp when this certificate was generated"},"legislation":{"type":"string","description":"Applicable legislation under which the electronic signing is valid","example":"Electronic Transactions Act 1999 (Cth) and state/territory equivalents"},"contract":{"type":"object","description":"Key metadata of the signed contract","properties":{"contract_id":{"type":"string","description":"Contract ID"},"contract_number":{"type":["string","null"],"description":"Human-readable contract number"},"title":{"type":["string","null"],"description":"Contract title"},"status":{"type":"string","description":"Contract status at time of certificate generation"},"currency":{"type":["string","null"],"description":"ISO 4217 currency code"},"value":{"type":["number","null"],"description":"Contract value"},"start_date":{"type":["string","null"],"format":"date","description":"Contract start date"},"end_date":{"type":["string","null"],"format":"date","description":"Contract end date"},"created_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the contract was created"}},"required":["contract_id","status"]},"signers":{"type":"array","description":"List of parties who signed the contract","items":{"type":"object","properties":{"signer_type":{"type":["string","null"],"description":"Type of signer (user, customer, agent)"},"signer_id":{"type":["string","null"],"description":"ID of the signer"},"signature_method":{"type":["string","null"],"description":"Method used to sign (e.g. 'checkbox', 'typed_name', 'ed25519')"},"signature_algorithm":{"type":["string","null"],"description":"Cryptographic algorithm used for the signature"},"signature_hash":{"type":"string","description":"Hash of the signature"},"contract_hash":{"type":["string","null"],"description":"Hash of the contract content at time of signing"},"signed_date":{"type":["string","null"],"format":"date-time","description":"Timestamp when the contract was signed"},"is_agent_signer":{"type":"boolean","description":"Whether the signer is an AI agent (true) or a human (false)"}},"required":["signature_hash","is_agent_signer"]}},"consent_events":{"type":"array","description":"Audit log entries recording explicit consent to sign, providing evidence of informed consent","items":{"type":"object","properties":{"actor_type":{"type":["string","null"],"description":"Type of actor who granted consent"},"actor_id":{"type":["string","null"],"description":"ID of the actor who granted consent"},"consented_at":{"type":"string","format":"date-time","description":"Timestamp when consent was granted"},"details":{"type":["object","null"],"description":"Additional details about the consent event"}},"required":["consented_at"]}},"hash_chain_verification":{"type":"object","description":"Summary of the audit trail hash chain integrity check performed at certificate generation time","properties":{"status":{"type":"string","enum":["verified","tampered","no_entries"],"description":"Result of the hash chain integrity check"},"total_entries":{"type":"integer","description":"Total number of audit entries verified"},"verified_at":{"type":"string","format":"date-time","description":"Timestamp when the verification was performed"}},"required":["status","total_entries","verified_at"]},"note":{"type":"string","description":"Disclaimer note about the certificate's legal standing"}},"required":["certificate_version","generated_at","legislation","contract","signers","consent_events","hash_chain_verification","note"]}},"required":["error","success","data"]}]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"post":{"tags":["Contracts"],"summary":"Create a contract or perform contract actions","description":"Without `id`: creates a new contract. With `id` and `action`: performs a lifecycle action.\n\nSupported actions:\n- `sign` — Sign a draft contract\n- `activate` — Activate a signed/pending contract\n- `terminate` — Terminate an active contract\n- `renew` — Manually trigger contract renewal (bypasses renewal_type check)\n- `opt_out_renewal` — Decline the upcoming auto-renewal\n\nUse `validate_only=true` when creating a contract to validate the request body without persisting it.","operationId":"postContract","security":[{"bearerAuth":["contracts:write"]},{"apiKeyHeader":["contracts:write"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Contract ID for actions on an existing contract","required":false,"schema":{"type":"integer"}},{"name":"action","in":"query","description":"Lifecycle action to perform","required":false,"schema":{"type":"string","enum":["sign","activate","terminate","renew","opt_out_renewal"]}},{"$ref":"#/components/parameters/validateOnly"},{"$ref":"#/components/parameters/idempotencyKey"}],"requestBody":{"description":"Required when creating a contract. Not needed for lifecycle actions.","required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractCreateRequest"}}}},"responses":{"201":{"description":"Contract created","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"contract":{"$ref":"#/components/schemas/ContractListItem"}},"required":["contract"]}},"required":["error","success","data"]}}}},"200":{"description":"Lifecycle action completed","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"contract":{"$ref":"#/components/schemas/ContractListItem"}},"required":["contract"]}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"patch":{"tags":["Contracts"],"summary":"Update a contract","description":"Update fields on an existing contract. Requires `If-Match` header with the current ETag for optimistic locking.","operationId":"updateContract","security":[{"bearerAuth":["contracts:write"]},{"apiKeyHeader":["contracts:write"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Contract ID to update","required":true,"schema":{"type":"integer"}},{"$ref":"#/components/parameters/ifMatch"},{"$ref":"#/components/parameters/idempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractUpdateRequest"}}}},"responses":{"200":{"description":"Contract updated","headers":{"ETag":{"description":"New resource version after update","schema":{"type":"string"}}},"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"contract":{"$ref":"#/components/schemas/ContractListItem"}},"required":["contract"]}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"412":{"$ref":"#/components/responses/PreconditionFailed"},"428":{"$ref":"#/components/responses/PreconditionRequired"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"delete":{"tags":["Contracts"],"summary":"Delete a contract","description":"Delete a contract. Active contracts must be terminated first. Optionally accepts `If-Match` header with the current ETag for optimistic locking.","operationId":"deleteContract","security":[{"bearerAuth":["contracts:write"]},{"apiKeyHeader":["contracts:write"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","description":"Contract ID to delete","required":true,"schema":{"type":"integer"}},{"$ref":"#/components/parameters/ifMatchOptional"},{"$ref":"#/components/parameters/idempotencyKey"}],"responses":{"200":{"description":"Contract deleted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContractDeleteResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"412":{"$ref":"#/components/responses/PreconditionFailed"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}}},"/deal-discovery":{"get":{"tags":["Discovery"],"summary":"Discover available deals","description":"Returns a paginated list of discoverable deals. Filter by category, price range, currency, pricing model, or payment terms. Requires `agent:discover` scope.","operationId":"discoverDeals","parameters":[{"name":"category","in":"query","schema":{"type":"string"},"description":"Filter by deal category"},{"name":"min_price","in":"query","schema":{"type":"number","minimum":0},"description":"Minimum deal total"},{"name":"max_price","in":"query","schema":{"type":"number","minimum":0},"description":"Maximum deal total"},{"name":"currency","in":"query","schema":{"type":"string"},"description":"Filter by currency code"},{"name":"pricing_model","in":"query","schema":{"type":"string","enum":["fixed","tiered","volume","usage"]},"description":"Filter by pricing model"},{"name":"payment_terms","in":"query","schema":{"type":"string","enum":["due_on_receipt","net_15","net_30","net_60","net_90","custom"]},"description":"Filter by payment terms"},{"name":"limit","in":"query","schema":{"type":"integer","default":50,"minimum":1,"maximum":100}},{"name":"offset","in":"query","schema":{"type":"integer","minimum":0,"default":0}},{"name":"action","in":"query","schema":{"type":"string","enum":["schema"]},"description":"Set to 'schema' to retrieve the deal terms JSON schema"}],"responses":{"200":{"description":"Discoverable deals or terms schema","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"oneOf":[{"description":"Discoverable deals (default)","type":"object","properties":{"deals":{"type":"array","description":"List of discoverable deal summaries","items":{"type":"object","properties":{"deal_id":{"type":"string"},"status":{"type":"string"},"category":{"type":["string","null"]},"currency":{"type":"string"},"total":{"type":"string"},"structured_terms":{"type":["object","null"]},"line_item_count":{"type":"integer"},"metadata":{"type":["object","null"]},"created_at":{"type":"string","format":"date-time"}},"required":["deal_id","status","currency","total","line_item_count","created_at"]}},"pagination":{"type":"object","properties":{"total":{"type":"integer","description":"Total number of records"},"limit":{"type":"integer","description":"Records per page"},"offset":{"type":"integer","description":"Records skipped"},"count":{"type":"integer","description":"Records returned in this response"}},"required":["total","limit","offset","count"]}},"required":["deals","pagination"]},{"description":"Deal terms JSON Schema (action=schema)","type":"object","properties":{"schema":{"type":"object","description":"JSON Schema definition describing the deal terms structure.","additionalProperties":true}},"required":["schema"]}]}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"400":{"$ref":"#/components/responses/BadRequest"},"403":{"$ref":"#/components/responses/Forbidden"},"405":{"description":"Method not allowed — only GET is accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"500":{"$ref":"#/components/responses/ServerError"},"429":{"$ref":"#/components/responses/RateLimited"}},"security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]},{"sessionAuth":[]}]}},"/deal-negotiations":{"get":{"tags":["Negotiations"],"summary":"Get negotiation history for a deal","description":"Returns the full round-by-round negotiation history for a deal, including term changes between rounds. Set action=intelligence for pricing intelligence, or omit action for history. Any other action returns 400. Requires `agent:negotiate` scope.","operationId":"getNegotiationHistory","parameters":[{"name":"deal_id","in":"query","required":true,"schema":{"type":"string"},"description":"Deal ID to get negotiations for"},{"name":"action","in":"query","schema":{"type":"string","enum":["intelligence"]},"description":"Set to 'intelligence' for pricing suggestions. Omit for history."}],"responses":{"200":{"description":"Negotiation history (default) or pricing intelligence (action=intelligence)","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"oneOf":[{"$ref":"#/components/schemas/NegotiationHistory","description":"Default response: full round-by-round negotiation history"},{"$ref":"#/components/schemas/NegotiationIntelligence","description":"action=intelligence: pricing intelligence for informing counter-offers"}]}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["agent:negotiate"]},{"apiKeyHeader":["agent:negotiate"]},{"sessionAuth":[]}]},"post":{"tags":["Negotiations"],"summary":"Propose, counter, accept, reject, or get AI suggestions for deal terms","description":"Perform a negotiation action on a deal. Use action=propose for initial proposal, action=counter for counter-proposal, action=accept to accept, action=reject to reject, or action=suggest to get AI counter-proposal suggestions.\n\n**Authentication note:** The operation-level `security` block lists every scope alternative used by this endpoint across its action branches. No single listed scope works for every action. Check `x-action-scopes` and the request variants below for the exact scope accepted by each action.\n\n**Scope matrix:** `propose`, `counter`, `reject`, and `suggest` require `agent:negotiate`. `accept` requires `agent:execute`. The operation-level `security` therefore advertises the union of `agent:negotiate` and `agent:execute`.","operationId":"negotiateDeal","x-action-scopes":{"propose":[["agent:negotiate"]],"counter":[["agent:negotiate"]],"accept":[["agent:execute"]],"reject":[["agent:negotiate"]],"suggest":[["agent:negotiate"]]},"parameters":[{"name":"deal_id","in":"query","required":true,"schema":{"type":"string"},"description":"Deal ID to negotiate"},{"name":"action","in":"query","required":true,"schema":{"type":"string","enum":["propose","counter","accept","reject","suggest"]},"description":"Negotiation action. `propose`, `counter`, `reject`, and `suggest` require `agent:negotiate`; `accept` requires `agent:execute`."}],"requestBody":{"content":{"application/json":{"schema":{"oneOf":[{"title":"ProposeRequest","description":"Body for action=propose. Submits an initial proposal. Requires `agent:negotiate` scope.","type":"object","required":["proposed_terms"],"properties":{"proposed_terms":{"type":"object","description":"Structured deal terms to propose"},"message":{"type":"string","description":"Optional message to accompany the proposal","maxLength":2000},"expires_at":{"type":"string","format":"date-time","description":"When this proposal expires"}}},{"title":"CounterRequest","description":"Body for action=counter. Submits a counter-proposal. Requires `agent:negotiate` scope.","type":"object","required":["proposed_terms"],"properties":{"proposed_terms":{"type":"object","description":"Structured deal terms for the counter-proposal"},"message":{"type":"string","description":"Optional message to accompany the counter-proposal","maxLength":2000},"expires_at":{"type":"string","format":"date-time","description":"When this counter-proposal expires"}}},{"title":"AcceptRequest","description":"Body for action=accept. No fields required. Requires `agent:execute` scope.","type":"object","properties":[]},{"title":"RejectRequest","description":"Body for action=reject. Optionally includes a reason. Requires `agent:negotiate` scope.","type":"object","properties":{"reason":{"type":"string","description":"Reason for rejection","maxLength":2000}}},{"title":"SuggestRequest","description":"Body for action=suggest. Requests AI counter-proposal suggestions. Requires `agent:negotiate` scope.","type":"object","properties":{"current_terms":{"type":"object","description":"Current terms on the table. If omitted, uses latest round's terms."}}}]}}},"required":true},"responses":{"200":{"description":"Negotiation action completed (action=accept, action=reject, or action=suggest)","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"oneOf":[{"$ref":"#/components/schemas/NegotiationRound","description":"action=accept or action=reject: the finalised negotiation round"},{"$ref":"#/components/schemas/NegotiationSuggestions","description":"action=suggest: AI-generated counter-proposal suggestions"}]}},"required":["error","success","data"]}}}},"201":{"description":"Proposal or counter-proposal created (action=propose or action=counter)","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/NegotiationRound","description":"The newly created negotiation round"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["agent:negotiate"]},{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["agent:negotiate"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]}]}},"/delegations":{"get":{"tags":["Delegations"],"summary":"List or retrieve delegations; use action=check to validate the calling agent's active delegation; use action=spending&id={id} for spending totals; use action=analytics&id={id} for per-delegation analytics; use action=activity&id={id} for paginated/filtered audit trail","description":"Returns a paginated list of active delegations for the current user, or a single delegation when `id` is provided.","operationId":"getDelegations","parameters":[{"name":"id","in":"query","description":"Specific delegation ID to retrieve","schema":{"type":"string"}},{"name":"action","in":"query","description":"Action to perform. Use `check` (no `id` required) to validate the calling agent's own active delegation and retrieve its allowed_actions. Use `spending` with an `id` to retrieve spending totals and limit utilisation for a delegation. Use `verify` with an `id` to check delegation validity. Use `analytics` with an `id` to retrieve per-delegation analytics (spending breakdown, deals created, activity log, ROI metrics, and 30-day spending chart). Use `activity` with an `id` to retrieve a paginated, filterable audit trail of all actions taken under this delegation (supports `from_date`, `to_date`, `action_type`, `entity_type` query parameters).","schema":{"type":"string","enum":["check","spending","verify","analytics","summary","pending","proposal","activity"]}},{"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":100,"default":50}},{"name":"offset","in":"query","schema":{"type":"integer","minimum":0,"default":0}},{"name":"from_date","in":"query","description":"ISO 8601 start date for filtering activity results (used with action=activity)","schema":{"type":"string","format":"date-time"}},{"name":"to_date","in":"query","description":"ISO 8601 end date for filtering activity results (used with action=activity)","schema":{"type":"string","format":"date-time"}},{"name":"action_type","in":"query","description":"Filter activity by action type (e.g. deal_created, deal_signed). Used with action=activity.","schema":{"type":"string"}},{"name":"entity_type","in":"query","description":"Filter activity by entity type (e.g. deal, contract). Used with action=activity.","schema":{"type":"string"}},{"name":"status","in":"query","description":"Filter delegations by status","schema":{"type":"string","enum":["active","revoked","expired"]}}],"responses":{"200":{"description":"Delegation(s) retrieved successfully","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"oneOf":[{"$ref":"#/components/schemas/Delegation"},{"type":"object","description":"Paginated list of delegations (no action, no id)","properties":{"delegations":{"type":"array","items":{"$ref":"#/components/schemas/Delegation"}},"pagination":{"$ref":"#/components/schemas/Pagination"}}},{"$ref":"#/components/schemas/DelegationSummary"},{"$ref":"#/components/schemas/DelegationAnalytics"},{"$ref":"#/components/schemas/DelegationActivity"},{"$ref":"#/components/schemas/DelegationPermissionCheck"},{"$ref":"#/components/schemas/DelegationSpending"},{"$ref":"#/components/schemas/DelegationPendingProposals"},{"$ref":"#/components/schemas/DelegationProposal"},{"$ref":"#/components/schemas/DelegationVerification"}]}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"Forbidden — API key authentication required for action=check (session auth insufficient)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"404":{"$ref":"#/components/responses/NotFound"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["delegations:read"]},{"apiKeyHeader":["delegations:read"]},{"sessionAuth":[]}]},"post":{"tags":["Delegations"],"summary":"Create a new delegation","description":"Create a new delegation or perform a proposal action. Use action=propose to propose agent-to-agent delegation, action=accept/reject/counter to respond to pending proposals.","operationId":"createDelegation","parameters":[{"name":"action","in":"query","schema":{"type":"string","enum":["propose","accept","reject","counter"]},"description":"Proposal action to perform (agent-to-agent delegation protocol)"},{"name":"id","in":"query","schema":{"type":"string"},"description":"Proposal ID for accept/reject/counter actions"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/CreateDelegationRequest"},{"$ref":"#/components/schemas/ProposeDelegationRequest"}],"description":"Body schema depends on the action query parameter. Default (no action) uses CreateDelegationRequest with grantee_agent_key_id + allowed_actions. action=propose uses ProposeDelegationRequest with target_api_key_id + proposed_actions."},"examples":{"create":{"summary":"Create delegation (default, no action param)","value":{"grantee_agent_key_id":"key_abc123","allowed_actions":["deals:read","deals:write","agent:negotiate"],"max_transaction_amount":5000,"max_daily_amount":10000,"max_monthly_amount":50000,"expires_at":"2027-12-31T23:59:59Z"}},"propose":{"summary":"Propose delegation (action=propose)","value":{"target_api_key_id":"key_xyz789","proposed_actions":["deals:read","agent:negotiate"],"proposed_duration_hours":24,"message":"Proposing a sub-delegation for deal negotiation"}}}}}},"responses":{"201":{"description":"Delegation created successfully","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/Delegation"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"description":"Forbidden — API key authentication required for action=propose (session auth insufficient)","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"}}}},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["delegations:write"]},{"apiKeyHeader":["delegations:write"]},{"sessionAuth":[]}]},"put":{"tags":["Delegations"],"summary":"Update a delegation","description":"Updates an existing delegation's allowed actions, spending limits, or expiry.","operationId":"updateDelegation","parameters":[{"name":"id","in":"query","required":true,"description":"Delegation ID to update","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"allowed_actions":{"type":"array","items":{"type":"string"},"description":"Updated list of allowed action scopes"},"max_transaction_amount":{"type":["number","null"],"description":"Updated per-transaction spending limit"},"max_daily_amount":{"type":["number","null"],"description":"Updated daily spending limit"},"max_monthly_amount":{"type":["number","null"],"description":"Updated monthly spending limit"},"expires_at":{"type":["string","null"],"format":"date-time","description":"Updated expiry datetime"},"description":{"type":["string","null"],"maxLength":500,"description":"Updated human-readable description"},"approval_threshold":{"type":["number","null"],"minimum":0,"maximum":99999999.99,"description":"Updated transaction amount above which human approval is required"},"approval_steps":{"type":["object","null"],"description":"Updated approval workflow definition. Maximum nesting depth of 3."},"approval_timeout":{"type":["integer","null"],"minimum":0,"maximum":86400,"description":"Updated approval timeout in seconds (0–86400)"},"auto_approve_policy":{"type":["object","null"],"description":"Updated auto-approve policy rules. Maximum nesting depth of 3."},"alert_threshold_pct":{"type":["integer","null"],"minimum":1,"maximum":100,"description":"Updated budget alert threshold percentage (1–100)"}}}}}},"responses":{"200":{"description":"Delegation updated successfully","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/Delegation"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["delegations:write"]},{"apiKeyHeader":["delegations:write"]},{"sessionAuth":[]}]},"delete":{"tags":["Delegations"],"summary":"Revoke a delegation","description":"Revokes a delegation and cascades revocation to all sub-delegations in the chain.","operationId":"revokeDelegation","parameters":[{"name":"id","in":"query","required":true,"description":"Delegation ID to revoke","schema":{"type":"string"}}],"responses":{"200":{"description":"Delegation revoked successfully","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"delegation_id":{"type":"string"},"revoked":{"type":"boolean","const":true}}}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/IdempotencyConflict"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["delegations:write"]},{"apiKeyHeader":["delegations:write"]},{"sessionAuth":[]}]}},"/schema/state-machine":{"get":{"tags":["Schema"],"summary":"Get state machine definitions","description":"Returns machine-readable state machine definitions for entity types (deals, contracts). No authentication required — this is metadata. Responses are cacheable (1 hour client, 24 hours CDN).","operationId":"getStateMachine","security":[],"parameters":[{"name":"entity","in":"query","description":"Filter by entity type. Omit to get all entity types.","required":false,"schema":{"type":"string","enum":["deals","contracts"]}}],"responses":{"200":{"description":"State machine definitions","headers":{"Cache-Control":{"schema":{"type":"string"},"description":"public, max-age=3600, s-maxage=86400"}},"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/StateMachineResponse"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"}}}},"/schema/deal-terms":{"get":{"tags":["Schema"],"summary":"Get deal terms JSON schema","description":"Returns the JSON Schema document defining the structure of machine-readable deal terms. Agents can fetch this schema to understand what terms are expressible. No authentication required — this is metadata.","operationId":"getDealTermsSchema","security":[],"responses":{"200":{"description":"Deal terms JSON schema","headers":{"Cache-Control":{"schema":{"type":"string"},"description":"public, max-age=3600, s-maxage=86400"}},"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","description":"JSON Schema document (draft 2020-12)","additionalProperties":true}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"}}}},"/deals/{id}/valid-transitions":{"get":{"tags":["Deals"],"summary":"Get valid status transitions for a deal","description":"Returns context-aware valid transitions for a specific deal, checking both state machine rules and business rules (has line items, has customer, signature status).","operationId":"getDealValidTransitions","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"responses":{"200":{"description":"Valid transitions for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/ValidTransitionsResponse"}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"403":{"$ref":"#/components/responses/Forbidden"},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}]}},"/payments":{"get":{"tags":["Payments"],"summary":"Get payment status for a deal or payment settings","description":"Returns the current payment status for a deal, or payment settings (payment account status, payment method toggles, invoice settings) when action=settings.","operationId":"getPayment","parameters":[{"name":"action","in":"query","description":"Action to perform. Use 'settings' to get payment settings.","schema":{"type":"string","enum":["settings"]}},{"name":"deal_id","in":"query","description":"Deal ID to check payment status for. Required when action is omitted (payment status query). Not needed for action=settings.","required":false,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"responses":{"200":{"description":"Payment status or payment settings","content":{"application/json":{"schema":{"oneOf":[{"title":"PaymentStatusResponse","description":"Payment status for a deal (returned when deal_id is provided)","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"deal_id":{"type":"string"},"payment_processor":{"type":["string","null"]},"payment_intent_id":{"type":["string","null"]},"payment_charge_id":{"type":["string","null"]},"payment_status":{"type":"string"},"payment_amount":{"type":["string","null"]},"paid_at":{"type":["string","null"],"format":"date-time"},"deposit_collected":{"type":["string","null"]},"balance_due":{"type":["string","null"]},"total":{"type":"string"},"currency":{"type":"string"},"stripe_status":{"type":["string","null"],"description":"Raw payment intent status (e.g. succeeded, requires_payment_method). Present when payment provider is Stripe."}}}},"required":["error","success","data"]},{"title":"PaymentSettingsResponse","description":"Payment settings (returned when action=settings)","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"stripe":{"type":"object","description":"payment account status and configuration","properties":{"connected":{"type":"boolean","description":"Whether a payment account account is linked"},"account_id":{"type":["string","null"],"description":"The payment account account ID"},"key_configured":{"type":"boolean","description":"Whether a payment secret key is configured"}}},"payment_methods":{"type":"object","description":"Enabled payment method toggles","properties":{"accept_card":{"type":"boolean","description":"Whether card payments are accepted"},"accept_bank":{"type":"boolean","description":"Whether bank/ACH payments are accepted"},"accept_manual":{"type":"boolean","description":"Whether manual payments are accepted"}}},"invoice_settings":{"type":"object","description":"Invoice configuration","properties":{"invoice_prefix":{"type":"string","description":"Prefix for invoice numbers (e.g. INV-)"},"payment_terms_days":{"type":"integer","description":"Default payment terms in days"}}}}}},"required":["error","success","data"]}]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}]},"post":{"tags":["Payments"],"summary":"Create a payment intent or perform payment actions","description":"Perform payment operations on a deal or manage payment settings. Use the `action` query parameter to specify the operation:\n\n- `create-intent`: **Deprecated** — use `POST /payment-intent` instead. Create a payment intent for a deal\n- `confirm`: Confirm a payment has succeeded\n- `capture`: Capture a previously-authorized PaymentIntent (auth-only flows)\n- `refund`: Process a partial or full refund\n- `record-manual`: Record a manual (non-payment provider) payment\n- `charge-saved-method`: Charge a customer's saved payment method off-session (agent use)\n- `poll-intent`: Poll payment intent status without webhook dependency\n- `generate-link`: Generate a hosted checkout Session URL for customer payment\n- `save-settings`: Save payment method toggles and invoice settings\n- `connect-provider`: Initiate payment account onboarding\n- `connect-stripe`: **Deprecated alias** for `connect-provider`\n- `disconnect-provider`: Disconnect payment account\n- `disconnect-stripe`: **Deprecated alias** for `disconnect-provider`","operationId":"postPayment","parameters":[{"name":"action","in":"query","description":"Payment action to perform","required":true,"schema":{"type":"string","enum":["confirm","capture","refund","record-manual","charge-saved-method","poll-intent","generate-link","save-settings","connect-provider","connect-stripe","disconnect-provider","disconnect-stripe","create-intent"]}},{"$ref":"#/components/parameters/idempotencyKey"}],"requestBody":{"description":"Request body varies by action. Each action requires different fields — see the per-action schemas.","required":true,"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/PaymentConfirmRequest"},{"$ref":"#/components/schemas/PaymentCaptureRequest"},{"$ref":"#/components/schemas/PaymentRefundRequest"},{"$ref":"#/components/schemas/PaymentRecordManualRequest"},{"$ref":"#/components/schemas/PaymentChargeSavedMethodRequest"},{"$ref":"#/components/schemas/PaymentPollIntentRequest"},{"$ref":"#/components/schemas/PaymentGenerateLinkRequest"},{"$ref":"#/components/schemas/PaymentSaveSettingsRequest"},{"$ref":"#/components/schemas/PaymentConnectProviderRequest"},{"$ref":"#/components/schemas/PaymentDisconnectProviderRequest"},{"$ref":"#/components/schemas/PaymentCreateIntentRequest"}]}}}},"responses":{"201":{"description":"Payment intent created (create-intent action)","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"client_secret":{"type":"string"},"payment_intent_id":{"type":"string"},"amount":{"type":"number"},"currency":{"type":"string"},"status":{"type":"string","description":"payment intent status (e.g. requires_payment_method, requires_confirmation, requires_action)"},"existing":{"type":"boolean","description":"Whether an existing PaymentIntent was reused (true) or a new one was created (false)"}}}},"required":["error","success","data"]}}}},"200":{"description":"Payment action completed successfully","content":{"application/json":{"schema":{"oneOf":[{"title":"CaptureResponse","description":"Response for capture action","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"payment_intent_id":{"type":"string"},"captured_amount":{"type":"number"},"currency":{"type":"string"},"payment_status":{"type":"string"},"deal_status":{"type":"string"}}}},"required":["error","success","data"]},{"title":"ChargeSavedMethodResponse","description":"Response for charge-saved-method action","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"payment_intent_id":{"type":"string"},"amount":{"type":"number"},"currency":{"type":"string"},"payment_status":{"type":"string"},"deal_status":{"type":"string"},"balance_due":{"type":"number"}}}},"required":["error","success","data"]},{"title":"PollIntentResponse","description":"Response for poll-intent action","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"payment_intent_id":{"type":"string"},"status":{"type":"string"},"amount":{"type":"number"},"amount_received":{"type":"number"},"currency":{"type":"string"},"last_payment_error":{"type":["object","null"]}}}},"required":["error","success","data"]},{"title":"GenerateLinkResponse","description":"Response for generate-link action","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"payment_link":{"type":"string","format":"uri"},"checkout_session_id":{"type":"string"},"amount":{"type":"number"},"currency":{"type":"string"},"expires_at":{"type":"string","format":"date-time"}}}},"required":["error","success","data"]},{"title":"ConfirmPaymentResponse","description":"Response for confirm action — full payment status after confirmation","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"deal_id":{"type":"string"},"payment_processor":{"type":["string","null"]},"payment_intent_id":{"type":["string","null"]},"payment_charge_id":{"type":["string","null"]},"payment_status":{"type":"string"},"payment_amount":{"type":["string","null"]},"paid_at":{"type":["string","null"],"format":"date-time"},"deposit_collected":{"type":["string","null"]},"balance_due":{"type":["string","null"]},"total":{"type":"string"},"currency":{"type":"string"}}}},"required":["error","success","data"]},{"title":"RefundPaymentResponse","description":"Response for refund action","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"refund_id":{"type":"string","description":"payment refund ID"},"deal_id":{"type":"string"},"payment_intent_id":{"type":"string"},"refund_amount":{"type":"string","description":"Refunded amount as decimal string"},"currency":{"type":"string"},"refund_type":{"type":"string","enum":["full","partial"],"description":"Whether this was a full or partial refund"},"payment_status":{"type":"string","description":"Updated deal payment status (refunded or partially_refunded)"},"balance_due":{"type":"string","description":"Updated balance due after refund"},"status":{"type":"string","description":"payment refund status"}}}},"required":["error","success","data"]},{"title":"RecordManualPaymentResponse","description":"Response for record-manual action","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"deal_id":{"type":"string"},"payment_processor":{"type":"string","description":"Always 'manual' for manually recorded payments"},"payment_status":{"type":"string","description":"Always 'captured' for manually recorded payments"},"payment_amount":{"type":"string","description":"Amount recorded as decimal string"},"method":{"type":"string","enum":["cash","wire","cheque","bank_transfer","other"],"description":"Payment method used"},"reference":{"type":"string","description":"Optional reference number or identifier"},"paid_at":{"type":"string","format":"date-time","description":"Timestamp when payment was recorded"},"deposit_collected":{"type":"string","description":"Total deposit collected to date"},"balance_due":{"type":"string","description":"Remaining balance due"}}}},"required":["error","success","data"]},{"title":"SaveSettingsResponse","description":"Response for save-settings action","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"message":{"type":"string","example":"Payment settings saved"}}}},"required":["error","success","data"]},{"title":"Connectpayment providerResponse","description":"Response for connect-provider action. Deprecated alias: connect-stripe.","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"url":{"type":"string","format":"uri","description":"payment provider Account Link URL for onboarding"},"account_id":{"type":"string","description":"The newly created payment account account ID"}}}},"required":["error","success","data"]},{"title":"Disconnectpayment providerResponse","description":"Response for disconnect-provider action. Deprecated alias: disconnect-stripe.","type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"message":{"type":"string","example":"payment account disconnected"}}}},"required":["error","success","data"]},{"title":"SuccessResponse","description":"Generic success response for other actions","$ref":"#/components/schemas/SuccessResponse"}]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"503":{"description":"Stripe is not configured for connect-provider onboarding. Please contact support.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"payment_not_configured":{"summary":"Stripe is not configured","value":{"error":true,"success":false,"code":"billing_error.payment_not_configured","message":"Stripe API key is not configured. Please contact support.","recovery":{"action":"contact_merchant","retryable":false}}}}}}},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"security":[{"bearerAuth":["deals:write"]},{"apiKeyHeader":["deals:write"]},{"sessionAuth":[]}]}},"/tools":{"get":{"tags":["Agent Tools"],"summary":"List available agent tool definitions","description":"Returns curated tool definitions optimized for LLM function-calling. Supports AI provider, AI provider, and universal formats. Tools map to high-level business operations.","operationId":"listAgentTools","security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]},{"sessionAuth":[]}],"parameters":[{"name":"format","in":"query","description":"Output format: universal (default), openai, or anthropic","schema":{"type":"string","enum":["universal","openai","anthropic"],"default":"universal"}},{"name":"category","in":"query","description":"Filter tools by category","schema":{"type":"string","enum":["deal_management","product_catalog","customer_management","contracts","negotiation","templates","intelligence","payments","subscriptions","widgets","configuration","saved_configs","webhooks","delegations","compliance","search","audit","sandbox","workflows","agent_trust","federation","agent_registry","deal_participants","closure","catalog_management","documents","billing","headless_flow"]}}],"responses":{"200":{"description":"Tool definitions","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","example":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"schema_version":{"type":"string","example":"1.0"},"format":{"type":"string"},"tools":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"category":{"type":"string"},"description":{"type":"string"},"required_scope":{"type":"string"},"parameters":{"type":"object","description":"JSON Schema describing the tool's input parameters.","additionalProperties":true},"returns":{"type":"object","description":"JSON Schema describing the tool's return value.","additionalProperties":true}}}},"total":{"type":"integer"},"categories":{"type":"array","items":{"type":"string"}}}}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/mcp":{"post":{"tags":["Agent Tools"],"summary":"Handle MCP JSON-RPC requests","description":"Model Context Protocol server endpoint. Accepts JSON-RPC 2.0 requests for tool listing (tools/list), tool execution (tools/call), resource browsing (resources/list, resources/read, resources/templates/list), prompt templates (prompts/list, prompts/get), resource subscriptions (resources/subscribe, resources/unsubscribe), and protocol handshake (initialize).","operationId":"handleMcpRequest","security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]},{"sessionAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["jsonrpc","method"],"properties":{"jsonrpc":{"type":"string","const":"2.0"},"id":{"type":"string","description":"Request ID for response correlation"},"method":{"type":"string","enum":["initialize","tools/list","tools/call","tools/batch","resources/list","resources/templates/list","resources/read","resources/subscribe","resources/unsubscribe","notifications/list","prompts/list","prompts/get","ping"]},"params":{"type":"object","description":"Method-specific parameters"}}}}}},"responses":{"200":{"description":"JSON-RPC 2.0 response. MCP method results and protocol-level JSON-RPC errors both return HTTP 200 with a JSON-RPC envelope.","content":{"application/json":{"schema":{"oneOf":[{"type":"object","required":["jsonrpc","id","result"],"properties":{"jsonrpc":{"type":"string","const":"2.0"},"id":{"type":["string","null"]},"result":{"type":"object","description":"JSON-RPC 2.0 result payload. Shape depends on the called method (tools/list, tools/call, initialize, resources/list, etc.).","additionalProperties":true}}},{"type":"object","required":["jsonrpc","id","error"],"properties":{"jsonrpc":{"type":"string","const":"2.0"},"id":{"type":["string","null"]},"error":{"type":"object","required":["code","message"],"properties":{"code":{"type":"integer"},"message":{"type":"string"},"data":{"type":"object","additionalProperties":true}}}}}]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"400":{"description":"Bad request before JSON-RPC processing, such as an invalid JSON HTTP body. Once the request body is parsed, MCP protocol errors are returned as HTTP 200 JSON-RPC error envelopes.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"validation_error":{"summary":"Field-level validation errors","value":{"error":true,"code":"validation_error.invalid_fields","category":"validation_error","message":"Validation failed","recovery":{"action":"fix_request","retryable":false,"hint":"Check the details.fields object for specific field errors."},"details":{"fields":{"email":{"code":"invalid","message":"Valid email is required"},"customer_id":{"code":"required","message":"Customer ID is required"}}}}},"bad_request":{"summary":"General bad request","value":{"error":true,"code":"validation_error.bad_request","category":"validation_error","message":"Invalid JSON in request body","recovery":{"action":"fix_request","retryable":false}}}}}}},"405":{"$ref":"#/components/responses/MethodNotAllowed"}}}},"/agent-workflow":{"get":{"tags":["AgentWorkflows"],"summary":"List or retrieve agent workflows, spending summaries, anomalies, and agent stats","description":"Returns agent workflow data. Use `action=spending_summary` for per-agent spending analytics, `action=anomalies` or `action=detect_anomalies` (SDK alias) for anomaly detection, `action=agent_stats&agent_id=X` for detailed agent analytics, `action=pending_approvals` to list workflows awaiting approval, `action=approval_status&id=X` to check approval token status, or no action for workflow listing. Unsupported non-empty action values return 400 before the default workflow list branch runs.","operationId":"getAgentWorkflows","parameters":[{"name":"action","in":"query","description":"Action to perform: spending_summary, anomalies, detect_anomalies, agent_stats, pending_approvals, or approval_status","schema":{"type":"string","enum":["spending_summary","anomalies","detect_anomalies","agent_stats","pending_approvals","approval_status"]}},{"name":"id","in":"query","description":"Specific workflow ID to retrieve (wf_xxx). Required for `action=approval_status`.","schema":{"type":"string"}},{"name":"agent_id","in":"query","description":"Agent key ID for agent_stats action","schema":{"type":"string"}},{"name":"period","in":"query","description":"Time period for spending_summary: day, week, or month","schema":{"type":"string","enum":["day","week","month"],"default":"month"}},{"name":"granularity","in":"query","description":"Granularity for agent_stats trend data: daily or weekly","schema":{"type":"string","enum":["daily","weekly"],"default":"daily"}},{"name":"status","in":"query","description":"Filter by workflow status","schema":{"type":"string","enum":["planned","executing","negotiating","awaiting_approval","completed","failed","cancelled","degraded","dead_letter"]}},{"name":"delegation_id","in":"query","description":"Filter by delegation ID for workflow listing, spending summaries, anomaly detection, and concurrent workflow tracking","schema":{"type":"string"}},{"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":100,"default":50}},{"name":"offset","in":"query","schema":{"type":"integer","minimum":0,"default":0}}],"responses":{"200":{"description":"Workflow(s) retrieved successfully. Response shape varies by `action` parameter: omit for workflow listing, `approval_status` for token status, `pending_approvals` for approval queue, `spending_summary` for per-agent spend analytics, `anomalies`/`detect_anomalies` for anomaly detection, `agent_stats` for detailed agent metrics.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"oneOf":[{"description":"Default (no action or action=list): workflow list with pagination","$ref":"#/components/schemas/AgentWorkflowListResponse"},{"description":"action=approval_status: approval token status for a specific workflow","$ref":"#/components/schemas/AgentWorkflowApprovalStatusResponse"},{"description":"action=pending_approvals: workflows awaiting approval","$ref":"#/components/schemas/AgentWorkflowPendingApprovalsResponse"},{"description":"action=spending_summary: per-agent spending analytics for the current period","$ref":"#/components/schemas/AgentWorkflowSpendingSummaryResponse"},{"description":"action=anomalies or action=detect_anomalies: detected spending anomalies","$ref":"#/components/schemas/AgentWorkflowAnomaliesResponse"},{"description":"action=agent_stats: detailed stats and trend data for a single agent key","$ref":"#/components/schemas/AgentWorkflowAgentStatsResponse"}]}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"security":[{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]}]},"post":{"tags":["AgentWorkflows"],"summary":"Plan, execute, modify, approve, or reject a workflow","description":"Plan a new autonomous deal workflow, execute a planned workflow asynchronously, modify an in-progress deal, or cancel a workflow. Use `action=execute` with `id` to execute, `action=modify` with `id` to modify, `action=cancel` with `id` to cancel, or omit action to plan a new workflow. Unsupported non-empty action values return 400, and every explicit action requires `id` before the default planning branch is considered.\n\nApproval gate actions: POST with `action=approve` or `action=reject` resumes or cancels a workflow in `awaiting_approval` state. These two actions accept either the normal authenticated request flow or a one-time approval token for webhook deep-links; all other actions on this endpoint still require standard auth.","operationId":"createAgentWorkflow","parameters":[{"name":"id","in":"query","description":"Workflow ID for all explicit POST actions (`execute`, `modify`, `cancel`, `approve`, `reject`, `resend_approval`, `escalate_approval`, and `delegate_approve`).","schema":{"type":"string"}},{"name":"action","in":"query","description":"Action to perform. Omit to plan a new workflow. Use execute/modify/cancel to manage workflow execution. Use approve/reject to handle approval gates. Use resend_approval to resend the notification, escalate_approval to escalate to the grantor, or delegate_approve for agent-scoped approval.","schema":{"type":"string","enum":["execute","modify","cancel","approve","reject","resend_approval","escalate_approval","delegate_approve"]}},{"name":"token","in":"query","description":"One-time approval token for `action=approve` or `action=reject`. When present, those two approval-gate actions may be processed without prior API key or session authentication.","schema":{"type":"string"}},{"$ref":"#/components/parameters/idempotencyKey"}],"requestBody":{"x-required-mode":"conditional","content":{"application/json":{"schema":{"oneOf":[{"title":"WorkflowPlanRequest","type":"object","description":"Default POST with no `action` query parameter. Requires `delegation_id` and accepts planning fields.","required":["delegation_id"],"properties":{"delegation_id":{"type":"string","description":"Delegation ID to operate under when planning a workflow"},"intent":{"type":"string","enum":["purchase","sell","fulfill"],"description":"Workflow intent: purchase (buy products), sell (list inventory for sale), or fulfill (deliver an existing deal)"},"constraints":{"type":"object","properties":{"max_budget":{"type":"number","description":"Maximum budget for the deal"},"product_categories":{"type":"array","items":{"type":"string"},"description":"Product categories to search"},"required_options":{"type":"object","description":"Required product options"},"auto_negotiate":{"type":"boolean","description":"Whether to auto-negotiate if counter-offered"},"max_negotiation_rounds":{"type":"integer","description":"Maximum negotiation rounds"},"max_discount_percent":{"type":"number","description":"Maximum discount percent to accept"},"customer_id":{"type":"string","description":"Existing customer ID to use for the deal"},"customer_email":{"type":"string","description":"Customer email — looks up existing or creates new"},"saved_config_id":{"type":"string","description":"Saved configuration ID — skips product discovery and builds the deal from this saved config (purchase intent)"},"retry_policy":{"type":"object","description":"Step retry policy. Overrides the default retry behaviour for this workflow.","properties":{"max_retries":{"type":"integer","description":"Maximum step retry attempts before dead-lettering (default 3)"},"delay_seconds":{"type":"integer","description":"Initial retry delay in seconds (default 60)"},"backoff_multiplier":{"type":"number","description":"Exponential backoff multiplier applied per retry attempt (default 2.0)"}}},"auto_accept_threshold":{"type":"number","description":"For sell intent — deal value threshold (absolute) below which an incoming purchase proposal is automatically accepted without human review"},"deal_id":{"type":"string","description":"Required for fulfill intent — the existing deal ID to execute fulfillment steps for"}}}}},{"title":"WorkflowActionNoBodyRequest","type":"object","description":"For `action=execute`, `action=cancel`, and `action=resend_approval`, omit the request body entirely.","additionalProperties":false,"maxProperties":0},{"title":"WorkflowModifyRequest","type":"object","description":"For `action=modify`, send at least one modification field in the JSON body.","minProperties":1,"additionalProperties":true,"properties":{"discount":{"type":"object","description":"Discount to apply (for modify action)","properties":{"type":{"type":"string","enum":["fixed","percentage"]},"value":{"type":"number"},"code":{"type":"string"},"description":{"type":"string"}}},"metadata":{"type":"object","description":"Metadata to merge into deal (for modify action)"},"notes":{"type":"string","description":"Notes to add to deal (for modify action)"}}},{"title":"WorkflowApproveRequest","type":"object","description":"For `action=approve`, reviewer fields are optional. A valid one-time token may be supplied in the JSON body instead of the query string.","additionalProperties":false,"properties":{"approved_by":{"type":"string","maxLength":255,"description":"Identifier of the approver (defaults to the authenticated user or `approval_link` for token-only approval)"},"note":{"type":"string","maxLength":2000,"description":"Optional note to attach when approving a workflow"},"token":{"type":"string","maxLength":255,"description":"One-time approval token for `action=approve` when supplied in the JSON body instead of the query string"}}},{"title":"WorkflowRejectRequest","type":"object","description":"For `action=reject`, reviewer fields are optional. A valid one-time token may be supplied in the JSON body instead of the query string.","additionalProperties":false,"properties":{"rejected_by":{"type":"string","maxLength":255,"description":"Identifier of the reviewer rejecting the workflow (defaults to the authenticated user or `approval_link` for token-only rejection)"},"reason":{"type":"string","maxLength":2000,"description":"Rejection reason (for reject action)"},"token":{"type":"string","maxLength":255,"description":"One-time approval token for `action=reject` when supplied in the JSON body instead of the query string"}}},{"title":"WorkflowEscalateApprovalRequest","type":"object","description":"For `action=escalate_approval`, `escalation_reason` is required.","required":["escalation_reason"],"properties":{"escalation_reason":{"type":"string","maxLength":2000,"description":"Required reason when escalating an approval to the delegation grantor"}}},{"title":"WorkflowDelegateApproveRequest","type":"object","description":"For `action=delegate_approve`, `delegation_id` is required and `approval_note` is optional.","required":["delegation_id"],"properties":{"delegation_id":{"type":"string","description":"Delegation ID granting approval authority for `action=delegate_approve`"},"approval_note":{"type":"string","maxLength":2000,"description":"Optional note when approving via delegation scope"}}}]}}}},"responses":{"200":{"description":"Workflow action completed successfully. Response shape varies by `action`: `execute` returns job_id and current_step (or reason/unavailable_services when degraded); `modify` returns the updated workflow with modifications_applied; `approve`/`delegate_approve` return job_id and approved_by; `resend_approval` returns resend counts and approval URLs; `escalate_approval` returns escalation details and approval URLs; `cancel`/`reject` return the updated workflow status.","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"oneOf":[{"description":"action=execute (normal): workflow queued for async execution","$ref":"#/components/schemas/AgentWorkflowExecuteResponse"},{"description":"action=execute (degraded): circuit breaker open, workflow in degraded mode","$ref":"#/components/schemas/AgentWorkflowExecuteDegradedResponse"},{"description":"action=modify: updated workflow with applied modifications","$ref":"#/components/schemas/AgentWorkflowModifyResponse"},{"description":"action=approve: workflow approval by session user","$ref":"#/components/schemas/AgentWorkflowApproveResponse"},{"description":"action=delegate_approve: approval granted via agent delegation scope","$ref":"#/components/schemas/AgentWorkflowDelegateApproveResponse"},{"description":"action=resend_approval: approval notification re-sent","$ref":"#/components/schemas/AgentWorkflowResendApprovalResponse"},{"description":"action=escalate_approval: approval escalated to delegation grantor","$ref":"#/components/schemas/AgentWorkflowEscalateApprovalResponse"},{"description":"action=cancel or action=reject: updated workflow","$ref":"#/components/schemas/AgentWorkflow"}]}},"required":["error","success","data"]}}}},"201":{"description":"Workflow planned successfully (no action body — creates a new planned workflow)","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/AgentWorkflowPlanResponse"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"x-security-override":true,"security":[{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]},{"workflowApprovalToken":[]}]}},"/agent-trust":{"get":{"tags":["AgentTrust"],"summary":"Get agent trust level, capabilities, and progress","description":"Returns the agent trust level, score, unlocked capabilities, trust lock statuses, and progress toward the next level for the authenticated API key. Use `?action=history` for trust level change history, or `?action=locks` for all trust lock statuses.","operationId":"getAgentTrust","parameters":[{"name":"action","in":"query","description":"Action to perform: omit for full status, 'history' for change log, 'locks' for capability gates","schema":{"type":"string","enum":["history","locks"]}},{"name":"limit","in":"query","description":"Max results for history action (1-100, default 25)","schema":{"type":"integer","minimum":1,"maximum":100,"default":25}},{"name":"offset","in":"query","description":"Pagination offset for history action","schema":{"type":"integer","minimum":0,"default":0}}],"responses":{"400":{"$ref":"#/components/responses/BadRequest"},"200":{"description":"Agent trust status, history, or lock information","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean"},"data":{"type":"object","properties":{"key_id":{"type":"string"},"trust_level":{"type":"integer","minimum":0,"maximum":4},"trust_label":{"type":"string"},"trust_score":{"type":"integer"},"transaction_cap":{"type":["number","null"]},"capabilities":{"type":"object","description":"Per-capability unlock status, keyed by capability name.","additionalProperties":{"type":"object","properties":{"unlocked":{"type":"boolean"},"required_level":{"type":"integer"},"required_label":{"type":"string"}}}},"progress":{"type":["object","null"]}}}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"403":{"$ref":"#/components/responses/Forbidden"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]}]}},"/agent-trust-credentials":{"get":{"tags":["AgentTrust"],"summary":"Export the current agent's trust credential","description":"Export the current agent's W3C Verifiable Credential for trust portability. The credential contains the agent's trust level, score, and deal history, signed by the tenant's Ed25519 key. Requires trust level 2+.","operationId":"getAgentTrustCredential","responses":{"200":{"description":"Agent trust credential","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean"},"data":{"type":"object","properties":{"credential_id":{"type":"string"},"status":{"type":"string","enum":["active","revoked","expired"]},"valid_from":{"type":"string","format":"date-time"},"valid_until":{"type":"string","format":"date-time"},"credential":{"type":"object","description":"W3C Verifiable Credential (Ed25519Signature2020)","properties":{"@context":{"type":"array","items":{"type":"string"}},"id":{"type":"string"},"type":{"type":"array","items":{"type":"string"}},"issuer":{"type":"string"},"issuanceDate":{"type":"string","format":"date-time"},"validFrom":{"type":"string","format":"date-time"},"validUntil":{"type":"string","format":"date-time"},"credentialSubject":{"type":"object","properties":{"id":{"type":"string"},"trustLevel":{"type":"integer"},"trustScore":{"type":"integer"},"dealsCompleted":{"type":"integer"},"disputeRate":{"type":"number"},"businessVerified":{"type":"boolean"},"issuedAt":{"type":"string","format":"date-time"}}},"proof":{"type":"object","properties":{"type":{"type":"string"},"created":{"type":"string","format":"date-time"},"verificationMethod":{"type":"string"},"proofPurpose":{"type":"string"},"proofValue":{"type":"string"}}}}}}}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"404":{"$ref":"#/components/responses/NotFound"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]},{"sessionAuth":[]}]},"post":{"tags":["AgentTrust"],"summary":"Issue, present, verify, or revoke trust credentials","description":"Manage W3C Verifiable Credentials for agent trust portability. Use `?action=issue` to issue a new credential, `?action=present` to present a credential for trust bootstrapping, `?action=verify` to verify a credential, or `?action=revoke` to revoke a credential.","operationId":"handleAgentTrustCredential","parameters":[{"name":"action","in":"query","required":true,"schema":{"type":"string","enum":["issue","present","verify","revoke"]},"description":"Action to perform"}],"requestBody":{"x-required-mode":"conditional","content":{"application/json":{"schema":{"oneOf":[{"title":"IssueAgentTrustCredentialRequest","description":"Body for `action=issue`. No request body fields are used and the JSON body may be omitted.","type":"object","properties":[],"additionalProperties":false,"maxProperties":0},{"title":"PresentAgentTrustCredentialRequest","description":"Body for `action=present`. Requires the W3C Verifiable Credential to present for trust bootstrapping.","type":"object","required":["credential"],"properties":{"credential":{"type":"object","description":"W3C VC JSON to present for trust bootstrapping"}}},{"title":"VerifyAgentTrustCredentialRequest","description":"Body for `action=verify`. Requires the W3C Verifiable Credential to verify.","type":"object","required":["credential"],"properties":{"credential":{"type":"object","description":"W3C VC JSON to verify"}}},{"title":"RevokeAgentTrustCredentialRequest","description":"Body for `action=revoke`. Requires the credential ID and accepts an optional revocation reason.","type":"object","required":["credential_id"],"properties":{"credential_id":{"type":"string","description":"Credential ID to revoke"},"reason":{"type":"string","description":"Revocation reason"}}}],"description":"Request body requirements vary by `action`: `issue` accepts no body, `present` and `verify` require `credential`, and `revoke` requires `credential_id`."}}}},"responses":{"200":{"description":"Operation result","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","description":"Credential presentation, verification, or revocation result (varies by action)","oneOf":[{"description":"Credential presentation result (action=present)","type":"object","properties":{"presentation_id":{"type":"string"},"verified":{"type":"boolean"},"verification":{"type":"object","properties":{"valid":{"type":"boolean"},"status":{"type":"string"},"reason":{"type":["string","null"]},"details":{"type":"object","properties":{"issuer":{"type":"string"},"trust_level":{"type":["integer","null"]},"trust_score":{"type":["integer","null"]},"deals_completed":{"type":["integer","null"]},"dispute_rate":{"type":["number","null"]},"valid_until":{"type":"string","format":"date-time"},"credential_status":{"type":"string"}}},"verified_at":{"type":"string","format":"date-time"}}},"bootstrapped_level":{"type":"string"},"message":{"type":"string"}},"required":["presentation_id","verified"]},{"description":"Credential verification result (action=verify)","type":"object","properties":{"valid":{"type":"boolean"},"status":{"type":"string"},"reason":{"type":["string","null"]},"details":{"type":"object","properties":{"issuer":{"type":"string"},"trust_level":{"type":["integer","null"]},"trust_score":{"type":["integer","null"]},"deals_completed":{"type":["integer","null"]},"dispute_rate":{"type":["number","null"]},"valid_until":{"type":"string","format":"date-time"},"credential_status":{"type":"string"}}},"verified_at":{"type":"string","format":"date-time"}},"required":["valid","status"]},{"description":"Revoked credential (action=revoke)","type":"object","properties":{"credential_id":{"type":"string"},"status":{"type":"string","const":"revoked"},"valid_from":{"type":"string","format":"date-time"},"valid_until":{"type":["string","null"],"format":"date-time"},"revoked_at":{"type":"string","format":"date-time"},"revocation_reason":{"type":"string"},"credential":{"type":"object","description":"W3C Verifiable Credential (Ed25519Signature2020)","properties":{"@context":{"type":"array","items":{"type":"string"}},"id":{"type":"string"},"type":{"type":"array","items":{"type":"string"}},"issuer":{"type":"string"},"issuanceDate":{"type":"string","format":"date-time"},"validFrom":{"type":"string","format":"date-time"},"validUntil":{"type":"string","format":"date-time"},"credentialSubject":{"type":"object","properties":{"id":{"type":"string"},"trustLevel":{"type":"integer"},"trustScore":{"type":"integer"},"dealsCompleted":{"type":"integer"},"disputeRate":{"type":"number"},"businessVerified":{"type":"boolean"},"issuedAt":{"type":"string","format":"date-time"}}},"proof":{"type":"object","properties":{"type":{"type":"string"},"created":{"type":"string","format":"date-time"},"verificationMethod":{"type":"string"},"proofPurpose":{"type":"string"},"proofValue":{"type":"string"}}}}}},"required":["credential_id","status"]}]}},"required":["error","success","data"]}}}},"201":{"description":"Credential issued","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","description":"Newly issued agent trust credential","properties":{"credential_id":{"type":"string"},"status":{"type":"string"},"valid_from":{"type":"string","format":"date-time"},"valid_until":{"type":["string","null"],"format":"date-time"},"revoked_at":{"type":["string","null"],"format":"date-time"},"revocation_reason":{"type":["string","null"]},"credential":{"type":"object","description":"W3C Verifiable Credential (Ed25519Signature2020)","properties":{"@context":{"type":"array","items":{"type":"string"}},"id":{"type":"string"},"type":{"type":"array","items":{"type":"string"}},"issuer":{"type":"string"},"issuanceDate":{"type":"string","format":"date-time"},"validFrom":{"type":"string","format":"date-time"},"validUntil":{"type":"string","format":"date-time"},"credentialSubject":{"type":"object","properties":{"id":{"type":"string"},"trustLevel":{"type":"integer"},"trustScore":{"type":"integer"},"dealsCompleted":{"type":"integer"},"disputeRate":{"type":"number"},"businessVerified":{"type":"boolean"},"issuedAt":{"type":"string","format":"date-time"}}},"proof":{"type":"object","properties":{"type":{"type":"string"},"created":{"type":"string","format":"date-time"},"verificationMethod":{"type":"string"},"proofPurpose":{"type":"string"},"proofValue":{"type":"string"}}}}}},"required":["credential_id","status","valid_from","credential"]}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]},{"sessionAuth":[]}]}},"/trust/revocations":{"get":{"tags":["Trust"],"summary":"Get revoked agent trust credentials list","description":"Public endpoint returning the list of revoked agent trust credentials for a tenant. Used by receiving Salesbooth instances to verify credential revocation status.","operationId":"getTrustRevocations","parameters":[{"name":"tenant_id","in":"query","required":true,"schema":{"type":"string"},"description":"Tenant ID to get revocations for"}],"responses":{"200":{"description":"Revocation list","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean"},"data":{"type":"object","properties":{"issuer":{"type":"string","description":"Issuer DID"},"type":{"type":"string"},"revoked_credentials":{"type":"array","items":{"type":"object","properties":{"credential_id":{"type":"string"},"revoked_at":{"type":"string","format":"date-time"},"revocation_reason":{"type":"string"}},"required":["credential_id","revoked_at","revocation_reason"]},"description":"List of revoked credentials with revocation metadata"},"count":{"type":"integer"},"updated_at":{"type":"string","format":"date-time"}}}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"429":{"$ref":"#/components/responses/RateLimited"}},"security":[]}},"/federation-peers":{"get":{"tags":["Federation"],"operationId":"listFederationPeers","summary":"List trusted federation peers for tenant","description":"Returns the list of approved peer hostnames for cross-instance federation. When at least one peer is configured, the tenant is in closed-federation mode and only listed peers may send inbound envelopes.","security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]},{"sessionAuth":[]}],"responses":{"200":{"description":"List of federation peers","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","example":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"peers":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer"},"hostname":{"type":"string"},"remote_tenant_id":{"type":["string","null"]},"trust_level":{"type":"integer"},"status":{"type":"string","enum":["active","suspended"]},"last_seen_at":{"type":["string","null"]},"created_at":{"type":"string"}}}},"count":{"type":"integer"},"open_mode":{"type":"boolean"}}}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"post":{"tags":["Federation"],"operationId":"addFederationPeer","summary":"Add a trusted federation peer","description":"Adds a remote Salesbooth instance hostname to the peer whitelist. Once any peer is added, all unlisted hostnames are blocked from sending inbound envelopes.","security":[{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["hostname"],"properties":{"hostname":{"type":"string","maxLength":255,"description":"Remote instance FQDN (no scheme)"},"remote_tenant_id":{"type":"string","maxLength":128},"trust_level":{"type":"integer","minimum":0,"maximum":5,"default":1},"status":{"type":"string","enum":["active","suspended"],"default":"active"}}}}}},"responses":{"201":{"description":"Peer added","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"id":{"type":"integer"},"hostname":{"type":"string"},"remote_tenant_id":{"type":"string"},"trust_level":{"type":"integer"},"status":{"type":"string"}},"required":["id","hostname"]}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"403":{"$ref":"#/components/responses/Forbidden"},"500":{"$ref":"#/components/responses/ServerError"}}},"patch":{"tags":["Federation"],"operationId":"updateFederationPeer","summary":"Update federation peer status or trust level","description":"Updates the status (active/suspended) or trust_level of an existing federation peer.","security":[{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","required":true,"schema":{"type":"integer"},"description":"Peer ID to update"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"status":{"type":"string","enum":["active","suspended"]},"trust_level":{"type":"integer","minimum":0,"maximum":5}}}}}},"responses":{"200":{"description":"Peer updated","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"updated":{"type":"boolean"},"id":{"type":"integer"}},"required":["updated","id"]}},"required":["error","success","data"]}}}},"404":{"$ref":"#/components/responses/NotFound"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"403":{"$ref":"#/components/responses/Forbidden"},"500":{"$ref":"#/components/responses/ServerError"}}},"delete":{"tags":["Federation"],"operationId":"removeFederationPeer","summary":"Remove a federation peer from the whitelist","description":"Permanently removes a peer from the tenant's federation whitelist.","security":[{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]}],"parameters":[{"name":"id","in":"query","required":true,"schema":{"type":"integer"},"description":"Peer ID to delete"}],"responses":{"200":{"description":"Peer deleted","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","example":false},"success":{"type":"boolean","example":true},"data":{"type":"object","properties":{"deleted":{"type":"boolean","example":true},"id":{"type":"integer","example":42}}}},"required":["error","success","data"]}}}},"404":{"$ref":"#/components/responses/NotFound"},"401":{"$ref":"#/components/responses/Unauthorized"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"403":{"$ref":"#/components/responses/Forbidden"},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/federation/discovery":{"get":{"tags":["Federation"],"operationId":"getFederationDiscovery","summary":"Get federation discovery manifest","description":"Returns the discovery manifest for a Salesbooth instance. Includes available products, deal capabilities, supported currencies, and the tenant's Ed25519 public key for signature verification. Public endpoint — no authentication required.","security":[],"parameters":[{"name":"tenant_id","in":"query","required":true,"schema":{"type":"string"},"description":"Tenant ID to get discovery manifest for"}],"responses":{"200":{"description":"Discovery manifest","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","example":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"protocol":{"type":"string","example":"salesbooth-negotiate/1.0"},"instance":{"type":"object","properties":{"tenant_id":{"type":"string"},"name":{"type":"string"},"version":{"type":"string"}}},"capabilities":{"type":"object","properties":{"discovery":{"type":"boolean"},"negotiation":{"type":"boolean"},"escrow":{"type":"boolean"},"signatures":{"type":"boolean"}}},"catalog":{"type":"object","properties":{"product_count":{"type":"integer"},"deal_count":{"type":"integer"},"currencies":{"type":"array","items":{"type":"string"}}}},"endpoints":{"type":"object","properties":{"discovery":{"type":"string","example":"/api/v1/deal-discovery"},"negotiate":{"type":"string","example":"/api/v1/federation/negotiate"},"public_key":{"type":"string","example":"/api/v1/tenant/public-key"}},"required":["discovery","negotiate","public_key"]},"rate_limits":{"type":"object","properties":{"discovery_per_minute":{"type":"integer","example":30},"negotiate_per_minute":{"type":"integer","example":10}},"required":["discovery_per_minute","negotiate_per_minute"]},"updated_at":{"type":"string","format":"date-time"},"signing":{"type":["object","null"],"properties":{"algorithm":{"type":"string","example":"ed25519"},"key_id":{"type":"string"},"public_key":{"type":"string"}}}},"required":["protocol","instance","capabilities","catalog","endpoints","rate_limits","updated_at"]}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"429":{"$ref":"#/components/responses/RateLimited"}}}},"/federation/negotiate":{"get":{"tags":["Federation"],"operationId":"getFederationStatus","summary":"Get federation negotiation status","description":"Returns federation capabilities for the authenticated tenant, or fetches the federated audit trail for a specific cross-reference ID.","parameters":[{"name":"action","in":"query","schema":{"type":"string","enum":["status","audit"]},"description":"Action: 'status' (default) or 'audit'"},{"name":"xref_id","in":"query","schema":{"type":"string"},"description":"Cross-reference ID (required when action=audit)"}],"responses":{"200":{"description":"Federation status or audit trail entries","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"oneOf":[{"description":"Federation capabilities manifest (default action=status)","type":"object","properties":{"federation":{"type":"object","properties":{"protocol":{"type":"string"},"capabilities":{"type":"object","properties":{"discovery":{"type":"boolean"},"negotiation":{"type":"boolean"},"escrow":{"type":"boolean"},"signatures":{"type":"boolean"}},"required":["discovery","negotiation","escrow","signatures"]},"signing":{"type":["object","null"],"additionalProperties":true}},"required":["protocol","capabilities"]}},"required":["federation"]},{"description":"Audit trail entries for a cross-reference ID (action=audit)","type":"object","properties":{"xref_id":{"type":"string"},"entries":{"type":"array","items":{"type":"object","properties":{"entry_id":{"type":"string"},"xref_id":{"type":"string"},"action":{"type":"string"},"actor_tenant_id":{"type":"string"},"created_at":{"type":"string","format":"date-time"}}}},"count":{"type":"integer"}},"required":["xref_id","entries","count"]}]}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"security":[{"bearerAuth":["agent:discover"]},{"apiKeyHeader":["agent:discover"]},{"sessionAuth":[]}]},"post":{"tags":["Federation"],"operationId":"handleFederationNegotiation","summary":"Process cross-instance negotiation envelope","description":"Handles cross-instance federation operations: discover remote instances, send signed negotiation envelopes, receive incoming envelopes, and coordinate escrow.\n\n**Authentication note:** The operation-level `security` block lists every scope alternative used by this endpoint across its action branches. No single listed scope works for every action. Check `x-action-scopes` for the exact scope accepted by each action.\n\n**Scope matrix:** `discover` requires `agent:discover`; `send` and `negotiate` require `agent:negotiate`; `escrow`, `settle`, and `dispute` require `agent:execute`. The operation-level `security` therefore advertises the union of `agent:discover`, `agent:negotiate`, and `agent:execute`. Some actions also require trust-level checks enforced by the endpoint.","x-action-scopes":{"discover":[["agent:discover"]],"send":[["agent:negotiate"]],"negotiate":[["agent:negotiate"]],"escrow":[["agent:execute"]],"settle":[["agent:execute"]],"dispute":[["agent:execute"]]},"parameters":[{"name":"action","in":"query","required":true,"schema":{"type":"string","enum":["discover","send","negotiate","escrow","settle","dispute"]},"description":"Federation action type. Scope varies by action: `discover` uses `agent:discover`; `send` and `negotiate` use `agent:negotiate`; `escrow`, `settle`, and `dispute` use `agent:execute`."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"instance":{"type":"string","description":"Remote instance hostname (for discover)"},"filters":{"type":"object","description":"Optional discovery filters for action=discover, such as category, min_price, max_price, and currency"},"target_instance":{"type":"string","description":"Remote instance hostname (for send)"},"target_agent_id":{"type":"string","description":"Remote agent ID"},"type":{"type":"string","enum":["discover","propose","counter","accept","reject","escrow_coordinate"],"description":"Envelope type"},"payload":{"type":"object","description":"Action-specific payload"},"protocol":{"type":"string","description":"Protocol version (for incoming envelopes)"},"remote_tenant_id":{"type":"string","description":"Remote tenant ID (for escrow)"},"local_deal_id":{"type":"string","description":"Local deal ID (for escrow)"},"remote_deal_id":{"type":"string","description":"Remote deal ID (for escrow)"},"amount":{"type":"number","description":"Escrow amount (for escrow)"},"currency":{"type":"string","description":"Currency code (for escrow)"},"xref_id":{"type":"string","description":"Cross-reference ID (for settle/dispute)"},"local_escrow_id":{"type":"string","description":"Local escrow ID to release (for settle)"},"remote_escrow_id":{"type":"string","description":"Remote escrow ID (for settle)"},"timeout_seconds":{"type":"integer","description":"Settlement timeout override in seconds (for settle)"},"reason":{"type":"string","description":"Dispute reason (for dispute)"}}}}}},"responses":{"200":{"description":"Federation operation result","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","description":"Federation negotiation envelope processing result","additionalProperties":true}},"required":["error","success","data"]}}}},"201":{"description":"Federation envelope sent or escrow coordinated","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"envelope_id":{"type":"string"},"xref_id":{"type":"string"},"sent_to":{"type":"string"},"type":{"type":"string"},"remote_response":{"type":["object","null"]},"delivery_status":{"type":"string","enum":["delivered","failed"]}}}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"429":{"$ref":"#/components/responses/RateLimited"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"security":[{"bearerAuth":["agent:discover"]},{"bearerAuth":["agent:negotiate"]},{"bearerAuth":["agent:execute"]},{"apiKeyHeader":["agent:discover"]},{"apiKeyHeader":["agent:negotiate"]},{"apiKeyHeader":["agent:execute"]},{"sessionAuth":[]}]}},"/events/stream":{"get":{"tags":["Events"],"operationId":"streamEvents","summary":"Stream real-time events via SSE","description":"Opens a Server-Sent Events stream for real-time deal, negotiation, payment, and other domain events. Supports event type filtering, entity-scoped streams, heartbeat keep-alive, and automatic reconnection with Last-Event-ID for missed-event recovery. Max 5 concurrent connections per API key. Stream auto-closes after 5 minutes; client should reconnect.","parameters":[{"name":"api_key","in":"query","required":false,"schema":{"type":"string"},"description":"API key for authentication. Required for browser EventSource which cannot send Authorization headers. The key appears in server access logs — rotate if exposed. All other endpoints require the Authorization header instead."},{"name":"events","in":"query","required":false,"schema":{"type":"string"},"description":"Comma-separated event types to filter (e.g. 'deal.updated,negotiation.countered'). Supports wildcards like 'deal.*'. Omit to receive all events.","example":"deal.updated,deal.negotiation_accepted,payment.received"},{"name":"deal_id","in":"query","required":false,"schema":{"type":"string"},"description":"Filter events for a specific deal"},{"name":"customer_id","in":"query","required":false,"schema":{"type":"string"},"description":"Filter events for a specific customer"},{"name":"last_event_id","in":"query","required":false,"schema":{"type":"string"},"description":"Resume from this event ID (format: seq:<number>). Also supported via Last-Event-ID header for automatic reconnection."}],"responses":{"200":{"description":"SSE event stream. Content-Type: text/event-stream. Each event includes id (seq:<number>), event type, and JSON data with _signature and _timestamp fields for integrity verification.","content":{"text/event-stream":{"schema":{"type":"string","description":"SSE formatted stream with events matching webhook event types"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"429":{"$ref":"#/components/responses/RateLimited"},"401":{"$ref":"#/components/responses/Unauthorized"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"}},"security":[{"bearerAuth":["webhooks:read"]},{"apiKeyHeader":["webhooks:read"]},{"sessionAuth":[]}]}},"/delegations/proposals":{"get":{"operationId":"listPendingProposals","summary":"List pending delegation proposals targeting this agent","description":"Returns pending proposals where the authenticated agent is the target. Requires agent API key auth and delegations:read scope.","tags":["Delegations"],"security":[{"bearerAuth":["delegations:read"]},{"apiKeyHeader":["delegations:read"]}],"parameters":[{"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":100,"default":50}},{"name":"offset","in":"query","schema":{"type":"integer","minimum":0,"default":0}}],"responses":{"200":{"description":"Pending proposals list","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"proposals":{"type":"array","items":{"$ref":"#/components/schemas/DelegationProposal"}},"pagination":{"$ref":"#/components/schemas/Pagination"}}}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}},"post":{"operationId":"proposeAgentDelegation","summary":"Propose agent-to-agent delegation","description":"Agent A proposes a delegation to Agent B. Requires trust level 2+ and the delegate action in proposer's own delegation scope.","tags":["Delegations"],"security":[{"bearerAuth":["delegations:write"]},{"apiKeyHeader":["delegations:write"]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["target_api_key_id","proposed_actions"],"properties":{"target_api_key_id":{"type":"string","description":"API key ID of target agent"},"proposed_actions":{"type":"array","items":{"type":"string"}},"max_transaction_amount":{"type":"number"},"max_daily_amount":{"type":"number"},"max_monthly_amount":{"type":"number"},"proposed_duration_hours":{"type":"integer"},"message":{"type":"string"}}}}}},"responses":{"201":{"description":"Proposal created","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DelegationProposal"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}}},"/delegations/proposals/{id}/accept":{"post":{"operationId":"acceptDelegationProposal","summary":"Accept a pending delegation proposal","description":"Target agent accepts, creating an actual delegation. Requires agent API key auth.","tags":["Delegations"],"security":[{"bearerAuth":["delegations:write"]},{"apiKeyHeader":["delegations:write"]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"Proposal accepted and delegation created","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"proposal":{"$ref":"#/components/schemas/DelegationProposal"},"delegation":{"type":"object","description":"The created delegation record.","properties":{"delegation_id":{"type":"string"},"grantor_id":{"type":"string"},"grantor_type":{"type":"string","enum":["user","agent"]},"grantee_agent_key_id":{"type":"string"},"allowed_actions":{"type":"array","items":{"type":"string"}},"max_transaction_amount":{"type":["number","null"]},"max_daily_amount":{"type":["number","null"]},"max_monthly_amount":{"type":["number","null"]},"expires_at":{"type":["string","null"],"format":"date-time"},"created_at":{"type":"string","format":"date-time"},"status":{"type":"string","enum":["active","revoked","expired"]}}}}}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","description":"No request body required. The proposal ID is specified in the path.","properties":[]}}}}}},"/delegations/proposals/{id}/reject":{"post":{"operationId":"rejectDelegationProposal","summary":"Reject a pending delegation proposal","tags":["Delegations"],"security":[{"bearerAuth":["delegations:write"]},{"apiKeyHeader":["delegations:write"]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string"}}}}}},"responses":{"200":{"description":"Proposal rejected","content":{"application/json":{"schema":{"type":"object","required":["error","success","data"],"properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DelegationProposal"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}},"description":"Rejects a pending delegation proposal by ID. The proposing agent is notified of the rejection and the proposal is archived."}},"/delegations/proposals/{id}/counter":{"post":{"operationId":"counterDelegationProposal","summary":"Counter-propose delegation terms","description":"Target agent proposes modified terms (subset of original). Creates a new proposal round.","tags":["Delegations"],"security":[{"bearerAuth":["delegations:write"]},{"apiKeyHeader":["delegations:write"]}],"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["proposed_actions"],"properties":{"proposed_actions":{"type":"array","items":{"type":"string"}},"max_transaction_amount":{"type":"number"},"max_daily_amount":{"type":"number"},"max_monthly_amount":{"type":"number"},"proposed_duration_hours":{"type":"integer"},"message":{"type":"string"}}}}}},"responses":{"201":{"description":"Counter-proposal created","content":{"application/json":{"schema":{"type":"object","required":["error","success","data"],"properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DelegationProposal"}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"500":{"$ref":"#/components/responses/ServerError"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"}}}},"/deals/{id}/settlements":{"get":{"tags":["Deals"],"summary":"Get revenue settlement breakdown for a deal","description":"Returns all revenue settlement records for a closed deal, showing how the deal total was distributed among participants after platform fee deduction. Agent participants receive USDC; merchant participants receive payment account transfers.","operationId":"getDealSettlements","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"responses":{"200":{"description":"Settlement records for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"settlements":{"type":"array","items":{"$ref":"#/components/schemas/DealSettlement"}}}}},"required":["error","success","data"]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"400":{"$ref":"#/components/responses/BadRequest"},"500":{"$ref":"#/components/responses/ServerError"}},"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}]}},"/agent-openapi.json":{"get":{"tags":["System"],"summary":"Serve the AI agent API specification","description":"Returns the generated OpenAPI view for AI agent integrations, including tools, MCP, workflows, trust, negotiation, and delegated commerce routes. This alias is public, requires no authentication, and responds with the filtered JSON specification for agent tooling.","operationId":"getAgentOpenApiSpec","security":[],"responses":{"200":{"description":"OpenAPI specification document","content":{"application/json":{"schema":{"type":"object","description":"OpenAPI 3.1.0 specification object","additionalProperties":true}}}},"400":{"$ref":"#/components/responses/BadRequest"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/deals/export":{"get":{"tags":["Deals"],"summary":"Bulk export deals using a canonical resource path","description":"Streams the same bulk export result as `GET /deals?action=export` through a canonical read route. Authenticate with a deals read credential, pass the same export query parameters, and expect a file or streamed payload in the requested export format.","operationId":"exportDealsAlias","security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Successful export response","content":{"application/json":{"schema":{"type":"array","description":"Raw JSON array of deal export records (returned when `action=export&format=json`). Each element is a deal export record.","items":{"type":"object","description":"Deal export record","properties":{"deal_id":{"type":"string"},"title":{"type":["string","null"]},"status":{"type":"string"},"total_amount":{"type":"number"},"currency":{"type":"string"},"customer_name":{"type":["string","null"]},"customer_email":{"type":["string","null"]},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}},"additionalProperties":true}}},"text/csv":{"schema":{"type":"string","description":"CSV file content. Returned when `action=export&format=csv` (default export format). First row is the header. Columns vary based on `include` query parameter."}},"application/x-ndjson":{"schema":{"type":"string","description":"Newline-delimited JSON (NDJSON). Returned when `action=export&format=jsonl`. Each line is a complete JSON object representing one deal export record."}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}},"parameters":[{"name":"status","in":"query","description":"Filter by deal status","required":false,"schema":{"type":"string","enum":["draft","in_progress","pending_signature","awaiting_signatures","pending_payment","partially_accepted","closed","cancelled","expired"]}},{"name":"customer_id","in":"query","description":"Filter by customer ID","required":false,"schema":{"type":"string"}},{"name":"created_after","in":"query","description":"Filter deals created after this datetime (ISO 8601)","required":false,"schema":{"type":"string","format":"date-time"}},{"name":"created_before","in":"query","description":"Filter deals created before this datetime (ISO 8601)","required":false,"schema":{"type":"string","format":"date-time"}},{"name":"include","in":"query","required":false,"description":"Comma-separated export expansions. Valid values: `items`, `payments`, `negotiations`.","schema":{"type":"string","examples":["items,payments,negotiations"]}},{"name":"format","in":"query","description":"Export format: `csv` (default), `json`, or `jsonl`.","required":false,"schema":{"type":"string","enum":["csv","json","jsonl"]}},{"name":"min_value","in":"query","description":"Filter deals with total value >= this amount (used with `action=export`). Must be a non-negative number.","required":false,"schema":{"type":"number","minimum":0}},{"name":"max_value","in":"query","description":"Filter deals with total value <= this amount (used with `action=export`). Must be a non-negative number and greater than or equal to `min_value` when both are provided.","required":false,"schema":{"type":"number","minimum":0}}]}},"/deals/compare-terms":{"get":{"tags":["Deals"],"summary":"Compare structured terms between two deals","description":"Compares the machine-readable terms of two tenant-scoped deals and returns a structured diff for review or agent reasoning. Requires deals read access and responds with JSON that highlights normalized term changes rather than mutating either deal.","operationId":"compareDealTerms","parameters":[{"name":"deal_id_1","in":"query","description":"First deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}},{"name":"deal_id_2","in":"query","description":"Second deal ID to compare against","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Terms comparison for the two requested deals","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/DealCompareTermsResult"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/deals/{id}/audit":{"get":{"tags":["Deals"],"summary":"Get the immutable audit trail for a deal","description":"Returns the immutable audit entries recorded for the specified deal, including lifecycle and approval activity used to review agent actions and operator changes. Requires deals read access and responds with the canonical JSON audit trail for that deal.","operationId":"getDealAudit","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Paginated audit trail for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/DealAuditTrailResult"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/deals/{id}/verify-audit":{"get":{"tags":["Deals"],"summary":"Verify the cryptographic integrity of a deal audit chain","description":"Validates the stored audit chain for the specified deal and reports whether the signed history remains intact. Requires deals read access and responds with JSON verification results instead of returning the raw audit log.","operationId":"verifyDealAudit","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Audit-chain verification result for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/DealVerifyAuditResult"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/deals/{id}/escrow":{"get":{"tags":["Deals"],"summary":"Get escrow status for a deal","description":"Returns the current escrow record and release state associated with the specified deal when escrow has been configured. Requires deals read access and responds with the canonical JSON escrow status for external monitoring or follow-up workflows.","operationId":"getDealEscrow","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Escrow details for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/DealEscrowResult"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/deals/{id}/credential":{"get":{"tags":["Deals"],"summary":"Get the verifiable credential issued for a deal","description":"Returns the verifiable credential issued for the specified deal so external systems can inspect or present the signed commercial record. Requires deals read access and responds with the credential payload in JSON form.","operationId":"getDealCredential","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Verifiable credential issued for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/DealCredentialResult"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/deals/{id}/signing-certificate":{"get":{"tags":["Deals"],"summary":"Get the structured signing certificate for a deal","description":"Returns the structured signing certificate for the specified deal, including the signing evidence assembled for downstream verification. Requires deals read access and responds with the normalized certificate document as JSON.","operationId":"getDealSigningCertificate","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Structured signing certificate for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/DealSigningCertificateResult"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}},"/deals/{id}/terms":{"get":{"tags":["Deals"],"summary":"Get structured machine-readable terms for a deal","description":"Returns the normalized machine-readable terms for the specified deal so agents and external systems can reason about obligations, approvals, pricing, and commercial conditions. Requires deals read access and responds with the canonical JSON terms document.","operationId":"getDealTerms","parameters":[{"name":"id","in":"path","description":"Deal ID","required":true,"schema":{"type":"string","pattern":"^deal_[a-zA-Z0-9_]+$"}}],"security":[{"bearerAuth":["deals:read"]},{"apiKeyHeader":["deals:read"]},{"sessionAuth":[]}],"responses":{"200":{"description":"Structured terms for this deal","content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/DealTermsResult"}},"required":["error","success","data"]}}}},"400":{"$ref":"#/components/responses/BadRequest"},"413":{"$ref":"#/components/responses/PayloadTooLarge"},"405":{"$ref":"#/components/responses/MethodNotAllowed"},"401":{"$ref":"#/components/responses/Unauthorized"},"403":{"$ref":"#/components/responses/Forbidden"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/RateLimited"},"500":{"$ref":"#/components/responses/ServerError"}}}}},"components":{"securitySchemes":{"bearerAuth":{"type":"http","scheme":"bearer","description":"API key passed as Bearer token. Format: `sb_live_{region}_*` (production) or `sb_test_{region}_*` (testing), where `{region}` is `au`, `eu`, or `us`."},"customerBearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"JWT","description":"Customer JWT obtained via /customer-auth magic link flow"},"apiKeyHeader":{"type":"apiKey","in":"header","name":"X-API-Key","description":"API key passed via X-API-Key header. Format: `sb_live_{region}_*` or `sb_test_{region}_*`, where `{region}` is `au`, `eu`, or `us`."},"sessionAuth":{"type":"apiKey","in":"cookie","name":"PHPSESSID","description":"Session cookie for browser-based requests. Required for API key management endpoints."},"workflowApprovalToken":{"type":"apiKey","in":"query","name":"token","description":"One-time approval token accepted by `POST /agent-workflow` when `action=approve` or `action=reject`. This alternate auth path bypasses bearer/API-key/session auth only for those two approval-gate actions."},"publishableKeyAuth":{"type":"http","scheme":"bearer","description":"Publishable widget key passed as Bearer token. Format: `sb_pub_{region}_*`, where `{region}` is `au`, `eu`, or `us`. Accepted only on widget embed endpoints (e.g. /saved-configs GET, POST, PATCH) for client-side use cases; bypasses scope checks. NOT accepted for destructive operations such as DELETE."}},"headers":{"X-Salesbooth-Signature":{"description":"HMAC-SHA256 signature of the webhook payload. Format: `v1=<hex>`. Computed as `HMAC-SHA256(timestamp + '.' + body, webhook_secret)` where `webhook_secret` is the plaintext secret provided at registration.","schema":{"type":"string","pattern":"^v1=[a-f0-9]{64}$","example":"v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd"}},"X-Salesbooth-Timestamp":{"description":"Unix timestamp (seconds) when the webhook was sent. Included in signature computation to prevent replay attacks. Integrators should reject deliveries where this timestamp is more than 5 minutes old.","schema":{"type":"string","pattern":"^[0-9]+$","example":"1709500000"}},"X-Salesbooth-Delivery-Id":{"description":"Unique delivery identifier for idempotency and deduplication. Format: `whd_<hex>`.","schema":{"type":"string","pattern":"^whd_[a-f0-9]+$","example":"whd_a1b2c3d4e5f6a7b8"}},"X-Salesbooth-Signature-Version":{"description":"Signature scheme version. Currently `v1`. Allows future algorithm upgrades without breaking existing integrations.","schema":{"type":"string","enum":["v1"],"example":"v1"}},"X-Salesbooth-Event":{"description":"The event type that triggered this webhook delivery.","schema":{"type":"string","example":"deal.created"}}},"parameters":{"limit":{"name":"limit","in":"query","description":"Maximum number of results per page","required":false,"schema":{"type":"integer","default":50,"minimum":1,"maximum":100}},"offset":{"name":"offset","in":"query","description":"Number of results to skip for pagination. Ignored when cursor parameters (after/before) are provided.","required":false,"schema":{"type":"integer","default":0,"minimum":0}},"after":{"name":"after","in":"query","description":"Cursor for forward pagination. Pass the `next_cursor` value from a previous response to fetch the next page. When provided, offset-based pagination is disabled and keyset (cursor) pagination is used instead.","required":false,"schema":{"type":"string"}},"before":{"name":"before","in":"query","description":"Cursor for backward pagination. Pass the `prev_cursor` value from a previous response to fetch the previous page. When provided, offset-based pagination is disabled and keyset (cursor) pagination is used instead.","required":false,"schema":{"type":"string"}},"sort":{"name":"sort","in":"query","description":"Sort field for cursor-based pagination. Determines which timestamp column cursors reference. Default: `created_at`. Use `updated_at` for sync/polling workflows (\"give me everything changed since my last check\").","required":false,"schema":{"type":"string","enum":["created_at","updated_at"],"default":"created_at"}},"ifMatch":{"name":"If-Match","in":"header","description":"Optimistic locking header. Must contain the resource's current ETag value (e.g. `W/\"3\"`). Required on PATCH requests. Obtain the ETag from the GET response. If the version has changed since you last read the resource, the request will fail with 412 Precondition Failed.","required":true,"schema":{"type":"string","pattern":"^(W/)?\"[0-9]+\"$","examples":["W/\"1\"","W/\"3\""]}},"ifMatchOptional":{"name":"If-Match","in":"header","description":"Optional optimistic locking header for DELETE requests. When provided, must contain the resource's current ETag value (e.g. `W/\"3\"`). If the version has changed since you last read the resource, the request will fail with 412 Precondition Failed. Obtain the ETag from the GET response. If omitted, the delete proceeds without version checking.","required":false,"schema":{"type":"string","pattern":"^(W/)?\"[0-9]+\"$","examples":["W/\"1\"","W/\"3\""]}},"dashboardCsrfToken":{"name":"X-CSRF-Token","in":"header","required":true,"description":"Required dashboard CSRF token for session-backed mutations.","schema":{"type":"string"}},"xDelegationId":{"name":"X-Delegation-ID","in":"header","description":"Explicitly specify which delegation the agent is operating under. If omitted, the most recent active delegation for the API key is used.","required":false,"schema":{"type":"string","examples":["deleg_abc123def456"]}},"fields":{"name":"fields","in":"query","description":"Comma-separated list of fields to include in the response. Only specified fields (plus `id`) are returned. Unknown field names are silently ignored for forward compatibility. Example: `fields=id,status,total,customer_id`.","required":false,"schema":{"type":"string","examples":["id,status,total","id,name,email,status"]}},"include":{"name":"include","in":"query","description":"Comma-separated list of nested resources to include. For single-resource endpoints, all nested resources are included by default; use this to request only specific ones. For list endpoints, no nested resources are included by default. Available nested resources vary by entity:\n- Deals: `customer`, `line_items`, `pricing`, `terms`, `payment`, `escrow`, `metadata`, `deal_score`, `outcome`\n- Customers: `deals`, `contracts`, `communications`, `activity_log`\n- Products: `deals`, `activity_log`\n- Contracts: `activity_log`","required":false,"schema":{"type":"string","examples":["line_items,pricing","deals,activity_log"]}},"exclude":{"name":"exclude","in":"query","description":"Comma-separated list of nested resources to exclude from the response. Inverse of `include`. Example: `exclude=activity_log,deals` removes those nested resources from the response.","required":false,"schema":{"type":"string","examples":["activity_log","deals,activity_log"]}},"format":{"name":"format","in":"query","description":"Response format shortcut. `minimal` returns only `id`, `status`, and `updated_at` — ideal for polling use cases.","required":false,"schema":{"type":"string","enum":["minimal"]}},"idempotencyKey":{"name":"Idempotency-Key","in":"header","description":"Client-generated unique key for safe request retries. If a request with the same key has already been processed, the cached response is returned with `Idempotency-Replayed: true`. Use a UUID v4 value and reuse the same key across retries. Keys expire after 24 hours. Required for AI agent integrations to prevent duplicate mutations on retries due to timeouts, network errors, or 5xx responses.","required":false,"schema":{"type":"string","maxLength":255,"examples":["550e8400-e29b-41d4-a716-446655440000"]}},"validateOnly":{"name":"validate_only","in":"query","description":"When true, validates the request body without creating the resource. Returns `{valid: true, message: \"Validation passed\"}` on success without persisting any data.","required":false,"schema":{"type":"boolean"}}},"schemas":{"HealthCheckResponse":{"type":"object","description":"Flat health payload returned by `/health`. `checks` is omitted for `?type=liveness` and included for default and readiness probes.","properties":{"status":{"type":"string","enum":["healthy","unhealthy"]},"timestamp":{"type":"string","format":"date-time"},"checks":{"$ref":"#/components/schemas/HealthChecks"}},"required":["status","timestamp"]},"HealthChecks":{"type":"object","properties":{"database":{"$ref":"#/components/schemas/HealthDatabaseCheck"},"redis":{"$ref":"#/components/schemas/HealthRedisCheck"},"cache":{"$ref":"#/components/schemas/HealthCacheCheck"},"api":{"$ref":"#/components/schemas/HealthApiCheck"},"circuit_breakers":{"$ref":"#/components/schemas/HealthCircuitBreakersCheck"},"job_queue":{"$ref":"#/components/schemas/HealthJobQueueCheck"},"disk":{"$ref":"#/components/schemas/HealthDiskCheck"}}},"HealthDatabaseCheck":{"type":"object","properties":{"status":{"type":"string","enum":["healthy","unhealthy"]},"message":{"type":"string"}},"required":["status"]},"HealthRedisCheck":{"type":"object","properties":{"status":{"type":"string","enum":["healthy","unhealthy","not_configured"]},"message":{"type":"string"}},"required":["status"]},"HealthCacheCheck":{"type":"object","properties":{"status":{"type":"string","enum":["healthy","degraded"]},"backends":{"type":"object","description":"Enabled cache backends keyed by backend name.","properties":{"apcu":{"type":"boolean"},"redis":{"type":"boolean"}},"additionalProperties":{"type":"boolean"}}},"required":["status","backends"]},"HealthApiCheck":{"type":"object","properties":{"status":{"type":"string","enum":["healthy","degraded","unknown"]},"requests_5m":{"type":"integer"},"error_rate_5m":{"type":"number"},"avg_response_ms":{"type":"integer"},"message":{"type":"string"}},"required":["status"]},"HealthCircuitBreakersCheck":{"type":"object","description":"Circuit breaker status for external service dependencies.","properties":{"status":{"type":"string","enum":["healthy","degraded"]},"services":{"type":"object","description":"Current circuit state per protected service.","additionalProperties":{"type":"string","enum":["closed","open","half_open"]}},"details":{"type":"object","description":"Detailed circuit breaker state keyed by service name.","additionalProperties":{"type":"object","properties":{"state":{"type":"string","enum":["closed","open","half_open"]},"failure_count":{"type":"integer"},"consecutive_successes":{"type":"integer"},"backoff_multiplier":{"type":"integer"},"last_failure_at":{"type":["string","null"]},"opened_at":{"type":["string","null"]},"closed_at":{"type":["string","null"]}},"required":["state","failure_count","consecutive_successes","backoff_multiplier","last_failure_at","opened_at","closed_at"]}}},"required":["status","services","details"]},"HealthJobQueueCheck":{"type":"object","description":"Job queue depth per topic.","properties":{"status":{"type":"string","enum":["healthy","degraded","unknown"]},"total_pending":{"type":"integer","description":"Total pending jobs across all topics."},"by_topic":{"type":"object","description":"Per-topic queue depth with pending and processing counts.","additionalProperties":{"type":"object","properties":{"pending":{"type":"integer"},"processing":{"type":"integer"}}}},"redis_queue_depths":{"type":"object","description":"Redis fast-path queue depths keyed by topic.","additionalProperties":{"type":"integer"}},"redis_total_pending":{"type":"integer"},"message":{"type":"string"}},"required":["status"]},"HealthDiskCheck":{"type":"object","properties":{"status":{"type":"string","enum":["healthy","warning"]},"used_percent":{"type":"number"},"free_mb":{"type":"number"}},"required":["status","used_percent","free_mb"]},"IntelligenceScore":{"type":"object","description":"Response for GET /intelligence?type=score. Deal scoring result with factor breakdown.","properties":{"score":{"type":["integer","null"],"minimum":0,"maximum":100,"description":"Overall deal score 0-100, or null if insufficient historical data"},"factors":{"type":"object","description":"Scoring factor breakdown keyed by factor name (time_in_status, deal_value, line_items, discount, customer_history)","additionalProperties":{"type":"object","properties":{"score":{"type":"number","description":"Points earned for this factor"},"max":{"type":"number","description":"Maximum possible points for this factor"},"detail":{"type":"string","description":"Human-readable detail for this factor"},"points":{"type":"number"},"max_points":{"type":"number"}}}},"win_probability":{"type":["number","null"],"minimum":0,"maximum":1,"description":"Estimated probability of closing the deal (0-1)"},"recommendation":{"type":["string","null"],"description":"Actionable recommendation based on weakest scoring factor"},"explanation":{"type":"string","description":"Human-readable explanation of the overall score"}},"required":["score","factors","win_probability","recommendation","explanation"]},"IntelligencePricing":{"type":"object","description":"Response for GET /intelligence?type=pricing. Pricing intelligence by product.","properties":{"products":{"type":"array","items":{"type":"object","properties":{"product_id":{"type":"string"},"product_name":{"type":"string"},"deal_count":{"type":"integer"},"closed_count":{"type":"integer"},"close_rate":{"type":"number","description":"Fraction of deals that closed (0-1)"},"avg_price":{"type":"number"},"optimal_price_range":{"type":["object","null"],"properties":{"suggested":{"type":"number"}}},"price_sensitivity":{"type":"string","enum":["low","moderate","high","unknown"]}}}},"discount_analysis":{"type":"object","description":"Discount usage analysis across closed and cancelled deals"},"recommendation":{"type":["string","null"],"description":"Overall pricing recommendation based on historical data"}},"required":["products","discount_analysis","recommendation"]},"IntelligencePipeline":{"type":"object","description":"Response for GET /intelligence?type=pipeline. Pipeline analytics and conversion rates.","properties":{"pipeline":{"type":"object","description":"Deal counts and total values keyed by deal status","additionalProperties":{"type":"object","properties":{"count":{"type":"integer"},"total_value":{"type":"number"}},"required":["count","total_value"]}},"total_deals":{"type":"integer"},"conversion_rate":{"type":["number","null"],"description":"Overall win rate: closed / (closed + cancelled + expired) × 100"},"avg_days_to_close":{"type":["number","null"]},"avg_deal_value":{"type":"number"},"total_revenue":{"type":"number"},"active_pipeline_value":{"type":"number"},"forecasted_revenue":{"type":["number","null"]},"forecast_confidence":{"type":["number","null"]},"bottleneck":{"type":["string","null"],"description":"Pipeline stage with the highest drop-off rate"},"transitions":{"type":"object","description":"Stage-to-stage transition counts","additionalProperties":{"type":"integer"}}},"required":["pipeline","total_deals","active_pipeline_value"]},"IntelligenceRisk":{"type":"object","description":"Response for GET /intelligence?type=risk. Deal risk assessment.","properties":{"deal_id":{"type":"string"},"risk_level":{"type":"string","enum":["none","low","medium","high","critical","unknown"],"description":"Overall risk level for the deal"},"risk_score":{"type":"integer","minimum":0,"description":"Aggregate numeric risk score"},"risk_factors":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string","description":"Risk factor type (stall_risk, engagement_risk, price_risk, customer_risk)"},"severity":{"type":"string"},"severity_score":{"type":"integer"},"detail":{"type":"string"},"action":{"type":"string","description":"Recommended action to mitigate this risk factor"}}}},"recommended_actions":{"type":"array","items":{"type":"string"},"description":"Consolidated list of recommended actions"},"message":{"type":["string","null"],"description":"Informational message when data is insufficient or deal is in terminal state"}},"required":["deal_id","risk_level","risk_score","risk_factors","recommended_actions"]},"IntelligenceCloseForecast":{"type":"object","description":"Response for GET /intelligence?type=close_forecast. Predicted close dates for a deal.","properties":{"deal_id":{"type":"string"},"optimistic":{"type":["string","null"],"format":"date-time","description":"Optimistic (p25) close date estimate"},"expected":{"type":["string","null"],"format":"date-time","description":"Expected (average) close date estimate"},"pessimistic":{"type":["string","null"],"format":"date-time","description":"Pessimistic (p75) close date estimate"},"confidence":{"type":["number","null"],"minimum":0,"maximum":1},"factors":{"type":"array","description":"Per-stage duration factors used in the forecast","items":{"type":"object","properties":{"stage":{"type":"string"},"avg_days":{"type":"number"},"sample_size":{"type":"integer"}}}},"message":{"type":["string","null"]}},"required":["deal_id","optimistic","expected","pessimistic","confidence","factors"]},"IntelligenceForecastWindow":{"type":"object","description":"Forecast metrics for a specific time window (30, 60, or 90 days)","properties":{"days":{"type":"integer"},"weighted_value":{"type":"number","description":"Probability-weighted pipeline value"},"deal_count":{"type":"integer"},"at_risk_value":{"type":"number","description":"Total value of at-risk deals in this window"}},"required":["days","weighted_value","deal_count","at_risk_value"]},"IntelligencePipelineForecast":{"type":"object","description":"Response for GET /intelligence?type=pipeline_forecast. Revenue forecast across 30/60/90-day windows.","properties":{"windows":{"type":"object","description":"Forecast metrics keyed by window size (30, 60, 90)","properties":{"30":{"$ref":"#/components/schemas/IntelligenceForecastWindow"},"60":{"$ref":"#/components/schemas/IntelligenceForecastWindow"},"90":{"$ref":"#/components/schemas/IntelligenceForecastWindow"}}},"total_weighted_pipeline":{"type":"number"},"total_at_risk_value":{"type":"number"},"active_deals":{"type":"integer"},"closed_deals_analyzed":{"type":"integer"},"deals":{"type":"array","items":{"type":"object","properties":{"deal_id":{"type":"string"},"value":{"type":"number"},"win_probability":{"type":"number"},"weighted_value":{"type":"number"},"expected_days_to_close":{"type":"integer"},"risk_level":{"type":["string","null"]},"status":{"type":"string"}},"required":["deal_id","value","win_probability","weighted_value","expected_days_to_close","status"]}},"trend":{"type":["object","null"],"description":"Historical trend comparison data"},"generated_at":{"type":"string","format":"date-time"}},"required":["windows","total_weighted_pipeline","total_at_risk_value","active_deals","closed_deals_analyzed","deals","generated_at"]},"IntelligencePipelineDeals":{"type":"object","description":"Response for GET /intelligence?type=pipeline_deals. Deals in a specific pipeline stage with scores.","properties":{"stage":{"type":"string"},"deals":{"type":"array","items":{"type":"object","properties":{"deal_id":{"type":"string"},"title":{"type":"string"},"total":{"type":["number","null"]},"status":{"type":"string"},"created_at":{"type":"string","format":"date-time"},"customer_name":{"type":"string"},"score":{"type":["integer","null"],"minimum":0,"maximum":100},"win_probability":{"type":["number","null"],"minimum":0,"maximum":1},"days_since_update":{"type":"integer"}},"required":["deal_id","title","status","customer_name","days_since_update"]}},"count":{"type":"integer"}},"required":["stage","deals","count"]},"IntelligencePricingSuggestionsBulk":{"type":"object","description":"Response for GET /intelligence?type=pricing_suggestions_bulk. Bulk discount suggestions for active deals.","properties":{"suggestions":{"type":"array","items":{"type":"object","properties":{"deal_id":{"type":"string"},"title":{"type":"string"},"total":{"type":["number","null"]},"currency":{"type":"string"},"product_name":{"type":"string"},"current_discount":{"type":"number","description":"Current discount percentage"},"suggested_discount":{"type":"number","description":"Suggested discount percentage based on historical winners"},"avg_winning_discount":{"type":"number"},"win_probability":{"type":["number","null"]},"probability_lift":{"type":["number","null"],"description":"Estimated increase in win probability if discount is applied"},"score":{"type":["integer","null"]},"reason":{"type":"string"}},"required":["deal_id","title","product_name","current_discount","suggested_discount","reason"]}},"count":{"type":"integer"}},"required":["suggestions","count"]},"IntelligenceScoreHistory":{"type":"object","description":"Response for GET /intelligence?type=score_history. Historical score entries for a deal.","properties":{"history":{"type":"array","items":{"type":"object","properties":{"score":{"type":"integer","minimum":0,"maximum":100},"win_probability":{"type":"number","minimum":0,"maximum":1},"scored_at":{"type":"string","format":"date-time"}}}}},"required":["history"]},"IntelligenceConfig":{"type":"object","description":"Response for GET /intelligence?type=config. Tenant scoring configuration with factor weights and optional calibration thresholds.","properties":{"weights":{"type":"object","description":"Scoring factor weights (each 0-100; values should sum to 100)","properties":{"time_in_status":{"type":"integer","minimum":0,"maximum":100,"description":"Weight for time spent in current status"},"deal_value":{"type":"integer","minimum":0,"maximum":100,"description":"Weight for deal monetary value"},"line_items":{"type":"integer","minimum":0,"maximum":100,"description":"Weight for number and quality of line items"},"discount":{"type":"integer","minimum":0,"maximum":100,"description":"Weight for discount levels applied"},"customer_history":{"type":"integer","minimum":0,"maximum":100,"description":"Weight for customer engagement history"}},"required":["time_in_status","deal_value","line_items","discount","customer_history"]},"thresholds":{"type":"object","description":"Optional per-factor calibration thresholds. Null values indicate no override (defaults are used).","properties":{"time_in_status":{"type":"object","properties":{"ideal_hours":{"type":["number","null"],"description":"Ideal hours before penalising stale status; null uses system default"}}},"deal_value":{"type":"object","properties":{"ideal_value":{"type":["number","null"],"description":"Ideal deal value for full points; null uses median of closed deals"}}}}}},"required":["weights","thresholds"]},"IntelligencePricingSuggestion":{"type":"object","description":"Response for GET /intelligence?type=pricing_suggestion. Discount recommendation for a specific deal based on historical win patterns.","properties":{"suggestion":{"description":"Pricing suggestion object, or null if insufficient data to make a recommendation","oneOf":[{"type":"object","properties":{"should_discount":{"type":"boolean","description":"Whether a discount is recommended based on historical close patterns"},"recommended_discount":{"type":["number","null"],"minimum":0,"maximum":100,"description":"Recommended discount percentage (0-100), or null if discounting is not recommended"},"reason":{"type":"string","description":"Human-readable explanation of the recommendation"}},"required":["should_discount","recommended_discount","reason"]},{"type":"null"}]},"outcome_context":{"type":"object","description":"Additional context from historical deal outcomes enriching the suggestion"},"reason":{"type":"string","description":"Error or informational reason when suggestion is null (e.g. 'Deal has no line items')"}},"required":["suggestion"]},"IntelligenceOutcomeAnalytics":{"type":"object","description":"Response for GET /intelligence?type=outcome_analytics. Win/loss outcome breakdown with reason analysis, competitor data, and value comparisons.","properties":{"summary":{"type":"object","description":"High-level win/loss counts and rates","properties":{"total_terminal_deals":{"type":"integer","description":"Total closed + cancelled + expired deals"},"deals_with_outcome":{"type":"integer","description":"Deals with an explicit outcome recorded"},"recording_rate":{"type":"number","description":"Percentage of terminal deals with outcome recorded (0-100)"},"won":{"type":"integer","description":"Number of closed (won) deals"},"lost":{"type":"integer","description":"Number of cancelled (lost) deals"},"expired":{"type":"integer","description":"Number of expired deals"},"win_rate":{"type":["number","null"],"description":"Win rate as percentage 0-100; null when no won+lost data"}},"required":["total_terminal_deals","deals_with_outcome","recording_rate","won","lost","expired","win_rate"]},"loss_reasons":{"type":"array","description":"Breakdown of recorded loss reasons, sorted by count descending","items":{"type":"object","properties":{"reason":{"type":"string"},"count":{"type":"integer"},"avg_deal_value":{"type":"number"},"total_value":{"type":"number"},"min_value":{"type":"number"},"max_value":{"type":"number"},"percentage":{"type":"number","description":"Percentage of all losses (0-100)"}},"required":["reason","count","avg_deal_value","total_value","percentage"]}},"win_reasons":{"type":"array","description":"Breakdown of recorded win reasons, sorted by count descending","items":{"type":"object","properties":{"reason":{"type":"string"},"count":{"type":"integer"},"avg_deal_value":{"type":"number"},"total_value":{"type":"number"}},"required":["reason","count","avg_deal_value","total_value"]}},"competitor_analysis":{"type":"array","description":"Deals lost to specific competitors, sorted by deals_lost descending","items":{"type":"object","properties":{"competitor":{"type":"string"},"deals_lost":{"type":"integer"},"avg_deal_value":{"type":"number"},"total_value_lost":{"type":"number"}},"required":["competitor","deals_lost","avg_deal_value","total_value_lost"]}},"value_comparison":{"type":"object","description":"Average deal values and discount levels for won vs lost deals","properties":{"won_avg_value":{"type":["number","null"]},"lost_avg_value":{"type":["number","null"]},"won_avg_discount_pct":{"type":["number","null"],"description":"Average discount percentage on won deals (0-100)"},"lost_avg_discount_pct":{"type":["number","null"],"description":"Average discount percentage on lost deals (0-100)"}}},"insights":{"type":"array","description":"Actionable insights derived from outcome patterns","items":{"type":"object","properties":{"type":{"type":"string","description":"Insight category (e.g. price_sensitivity, competitor_threat)"},"severity":{"type":"string","enum":["low","medium","high"]},"message":{"type":"string"},"data":{"type":"object","description":"Type-specific supporting data"}},"required":["type","severity","message","data"]}}},"required":["summary","loss_reasons","win_reasons","competitor_analysis","value_comparison","insights"]},"IntelligenceScoreAccuracy":{"type":"object","description":"Response for GET /intelligence?type=score_accuracy. Score calibration metrics showing how well the scoring model predicts deal outcomes, with weight adjustment suggestions.","properties":{"overall_accuracy":{"type":["number","null"],"minimum":0,"maximum":100,"description":"Overall model accuracy percentage (0-100), or null if insufficient data"},"total_deals_analyzed":{"type":"integer","description":"Number of terminal deals used for calibration"},"calibration":{"type":"array","description":"Win rate breakdown by score range (five 20-point buckets)","items":{"type":"object","properties":{"score_range":{"type":"string","description":"Score bucket label, e.g. '0-20', '21-40', '41-60', '61-80', '81-100'"},"total_deals":{"type":"integer"},"won":{"type":"integer"},"lost":{"type":"integer"},"win_rate":{"type":["number","null"],"minimum":0,"maximum":100,"description":"Win rate percentage for this bucket, or null if no deals in range"},"avg_value":{"type":["number","null"],"description":"Average deal value in this bucket, or null if no deals"}},"required":["score_range","total_deals","won","lost"]}},"interpretation":{"type":"string","description":"Human-readable summary of calibration quality"},"weight_suggestions":{"type":"array","description":"Suggested weight adjustments to improve score accuracy","items":{"type":"object","properties":{"factor":{"type":"string","description":"Scoring factor name (e.g. time_in_status, deal_value, discount)"},"direction":{"type":"string","enum":["increase","decrease"]},"reason":{"type":"string","description":"Explanation for the suggested adjustment"}},"required":["factor","direction","reason"]}}},"required":["overall_accuracy","total_deals_analyzed","calibration","interpretation","weight_suggestions"]},"IntelligenceLossPatterns":{"type":"object","description":"Response for GET /intelligence?type=loss_patterns. Detected patterns in deal losses including discount thresholds, deal aging, and loss reason correlations.","properties":{"patterns":{"type":"array","description":"Detected loss patterns. Each entry has a type-specific data shape: discount_threshold/deal_aging/reason_value_correlation use an object; discount_analysis/deal_velocity use an array of breakdown records.","items":{"type":"object","properties":{"type":{"type":"string","enum":["discount_threshold","discount_analysis","deal_aging","deal_velocity","reason_value_correlation"],"description":"Pattern category"},"severity":{"type":"string","enum":["low","medium","high","info"]},"message":{"type":"string","description":"Human-readable description of the pattern"},"data":{"description":"Type-specific data. discount_threshold: {threshold_range, threshold_close_rate, baseline_close_rate, deals_in_range}. discount_analysis: array of {range, total_deals, close_rate, avg_value}. deal_aging: {aging_range, aged_close_rate, early_close_rate, deals_in_range}. deal_velocity: array of {range, total_deals, close_rate}. reason_value_correlation: {reason, reason_avg_value, won_avg_value, pct_difference, deal_count}."}},"required":["type","severity","message","data"]}}},"required":["patterns"]},"IntelligenceWinProbabilityCurve":{"type":"object","description":"Response for GET /intelligence?type=win_probability_curve. Calibrated win probability lookup table across ten score decile buckets.","properties":{"calibrated":{"type":"boolean","description":"Whether the curve could be calibrated from sufficient historical data"},"sample_size":{"type":"integer","description":"Total terminal deals used for calibration (only present when calibrated=true)"},"buckets":{"type":"array","description":"Ten score-decile buckets with empirical win probability (only present when calibrated=true)","items":{"type":"object","properties":{"score_range":{"type":"string","description":"Score range label, e.g. '0-10', '10-20', ..., '90-100'"},"midpoint":{"type":"integer","description":"Midpoint of the score range (5, 15, 25, ...)"},"win_probability":{"type":"number","minimum":0,"maximum":1,"description":"Empirical win probability for this bucket (0-1)"},"sample_size":{"type":"integer","description":"Number of terminal deals in this bucket"}},"required":["score_range","midpoint","win_probability","sample_size"]}},"reason":{"type":"string","description":"Reason string when calibrated=false (e.g. 'Insufficient historical data')"}},"required":["calibrated"]},"IntelligenceSuggestionAnalytics":{"type":"object","description":"Response for GET /intelligence?type=suggestion_analytics. Metrics on AI pricing suggestion acceptance rates, calibration quality, and deal outcome correlation.","properties":{"period_days":{"type":"integer","description":"Lookback window in days (default 90)"},"total_suggestions":{"type":"integer","description":"Total suggestions generated in the period"},"resolved":{"type":"integer","description":"Suggestions with a non-pending outcome"},"outcome_counts":{"type":"object","description":"Count of suggestions by outcome","properties":{"applied":{"type":"integer"},"ignored":{"type":"integer"},"dismissed":{"type":"integer"},"accepted_deal":{"type":"integer","description":"Deal closed after the suggestion was applied"},"rejected_deal":{"type":"integer","description":"Deal lost after the suggestion was applied"},"pending":{"type":"integer"}},"required":["applied","ignored","dismissed","accepted_deal","rejected_deal","pending"]},"acceptance_rate":{"type":["number","null"],"minimum":0,"maximum":1,"description":"Fraction of resolved suggestions that were applied or led to a closed deal (0-1)"},"by_type":{"type":"array","description":"Per-suggestion-type breakdown of acceptance","items":{"type":"object","properties":{"type":{"type":"string","description":"Suggestion type identifier"},"total":{"type":"integer"},"accepted":{"type":"integer"},"acceptance_rate":{"type":"number","minimum":0,"maximum":1},"avg_confidence":{"type":["integer","null"],"minimum":0,"maximum":100}},"required":["type","total","accepted","acceptance_rate"]}},"calibration":{"type":"array","description":"Confidence vs actual acceptance rate, bucketed in 20-point confidence intervals","items":{"type":"object","properties":{"confidence_bucket":{"type":"integer","description":"Bucket lower bound (0, 20, 40, 60, 80)"},"label":{"type":"string","description":"Display label, e.g. '0–19%', '20–39%'"},"total":{"type":"integer"},"accepted":{"type":"integer"},"actual_rate":{"type":"number","minimum":0,"maximum":1}},"required":["confidence_bucket","label","total","accepted","actual_rate"]}},"deal_correlation":{"description":"Correlation between applied suggestions and deal close rates; null when fewer than 3 suggestions have been applied","oneOf":[{"type":"object","properties":{"total_applied":{"type":"integer"},"deals_closed":{"type":"integer"},"close_rate":{"type":"number","minimum":0,"maximum":1}},"required":["total_applied","deals_closed","close_rate"]},{"type":"null"}]},"avg_price_deviation":{"type":["number","null"],"description":"Average absolute difference between suggested price and actual price; null if no price data"},"dismiss_reasons":{"type":"array","description":"Top-5 reasons merchants dismissed suggestions","items":{"type":"object","properties":{"reason":{"type":"string"},"count":{"type":"integer"}},"required":["reason","count"]}}},"required":["period_days","total_suggestions","resolved","outcome_counts","acceptance_rate","by_type","calibration","deal_correlation","avg_price_deviation","dismiss_reasons"]},"IntelligenceCounterTerms":{"type":"object","description":"Response for GET /intelligence?type=counter_terms. AI-generated counter-term suggestions for a deal negotiation, ranked by confidence.","properties":{"suggestions":{"type":"array","description":"Counter-term suggestions sorted by confidence descending","items":{"type":"object","properties":{"type":{"type":"string","description":"Suggestion strategy type (e.g. split_difference, discount_aggressive, counter_offer)"},"recommended_terms":{"type":"object","description":"Suggested deal terms to apply (merged with current terms)"},"confidence":{"type":"integer","minimum":0,"maximum":100,"description":"Confidence score 0-100, adjusted by historical acceptance rate"},"win_probability_delta":{"type":["number","null"],"description":"Projected increase in close probability from applying this suggestion"},"rationale":{"type":"string","description":"Human-readable explanation for this suggestion"},"risk_level":{"type":"string","enum":["low","medium","high"]},"risk_assessment":{"type":"string","description":"Details about the risk involved in this suggestion"},"acceptance_rate":{"type":["number","null"],"minimum":0,"maximum":1,"description":"Historical acceptance rate for this suggestion type (0-1), if available"}},"required":["type","recommended_terms","confidence","rationale","risk_level","risk_assessment"]}},"deal_id":{"type":"string","description":"Deal ID the suggestions are for"},"suggestion_id":{"type":["string","null"],"description":"Tracking ID for the learning loop; null when suggestions array is empty"},"data_quality":{"type":"string","enum":["none","low","medium","high"],"description":"Quality of historical data backing these suggestions"},"historical_deals":{"type":"integer","description":"Number of similar historical deals found"},"currency":{"type":"string","description":"Deal currency code, e.g. USD"},"reference_price":{"type":"number","description":"Original deal total used as the pricing baseline"},"current_proposed_price":{"type":["number","null"],"description":"Buyer's currently proposed price from current_terms, if provided"},"message":{"type":"string","description":"Error or informational message when suggestions array is empty"}},"required":["suggestions","deal_id","data_quality","historical_deals"]},"AgentWorkflow":{"type":"object","description":"An agent workflow for autonomous deal orchestration with step-based async execution","properties":{"workflow_id":{"type":"string","description":"Unique workflow identifier (wf_xxx)"},"intent":{"type":"string","enum":["purchase","sell","fulfill"],"description":"Workflow intent: purchase, sell, or fulfill"},"status":{"type":"string","enum":["planned","executing","negotiating","awaiting_approval","completed","failed","cancelled","degraded","dead_letter"],"description":"Current workflow status"},"delegation_id":{"type":"string","description":"Delegation ID the workflow operates under"},"constraints":{"type":"object","description":"Workflow constraints (budget, categories, negotiation settings, customer)"},"steps":{"type":"array","description":"Workflow execution steps (discover → select → create_deal → negotiate → finalize)","items":{"type":"object","properties":{"step":{"type":"string","description":"Step name (discover, select, create_deal, negotiate, finalize)"},"status":{"type":"string","description":"Step status (pending, completed)"},"completed_at":{"type":["string","null"],"format":"date-time"}}}},"current_step":{"type":["string","null"],"description":"Step currently being processed"},"completed_steps":{"type":"array","items":{"type":"string"},"description":"List of completed step names"},"next_step":{"type":["string","null"],"description":"Next step to be executed"},"delegation_check":{"type":"object","description":"Pre-validated delegation spending limits (includes reserved amounts)"},"reserved_budget":{"type":["number","null"],"description":"Estimated budget reserved at plan time (released on cancel/fail, converted to spend on completion)"},"reservation_id":{"type":["string","null"],"description":"Budget reservation ID for traceability"},"deal_id":{"type":["string","null"],"description":"Created deal ID (set after create_deal step)"},"result":{"type":["object","null"],"description":"Workflow result data including deal and product details"},"error_message":{"type":["string","null"],"description":"Error message if workflow failed"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":["string","null"],"format":"date-time"},"completed_at":{"type":["string","null"],"format":"date-time"}}},"AgentWorkflowListResponse":{"type":"object","description":"GET /agent-workflow with no action — paginated workflow list","properties":{"workflows":{"type":"array","items":{"$ref":"#/components/schemas/AgentWorkflow"}},"pagination":{"$ref":"#/components/schemas/Pagination"}},"required":["workflows","pagination"]},"AgentWorkflowApprovalStatusResponse":{"type":"object","description":"GET /agent-workflow?action=approval_status — approval token status for a specific workflow","properties":{"workflow_id":{"type":"string"},"workflow_status":{"type":"string","enum":["planned","executing","negotiating","awaiting_approval","completed","failed","cancelled","degraded","dead_letter"]},"token_status":{"type":"string","enum":["valid","expired","pending","not_applicable"],"description":"Current state of the approval token"},"token_present":{"type":"boolean"},"token_created_at":{"type":["string","null"],"format":"date-time"},"token_expires_at":{"type":["string","null"],"format":"date-time"},"time_remaining":{"type":["integer","null"],"description":"Seconds until token expiry (null if no token)"},"time_remaining_human":{"type":["string","null"],"description":"Human-readable remaining time, e.g. '2h30m'"},"approver_info":{"type":["object","null"],"description":"Approver identity and note (null if not yet approved)","properties":{"approved_by":{"type":"string"},"note":{"type":["string","null"]}}}},"required":["workflow_id","workflow_status","token_status","token_present"]},"AgentWorkflowPendingApprovalsResponse":{"type":"object","description":"GET /agent-workflow?action=pending_approvals — workflows awaiting approval","properties":{"workflows":{"type":"array","items":{"type":"object","properties":{"workflow_id":{"type":"string"},"delegation_id":{"type":"string"},"deal_id":{"type":["string","null"]},"deal_value":{"type":["number","null"]},"approval_threshold":{"type":"number"},"requested_at":{"type":"string","format":"date-time"},"token_expires_at":{"type":["string","null"],"format":"date-time"},"time_waiting":{"type":"integer","description":"Seconds this workflow has been waiting for approval"},"time_waiting_human":{"type":"string","description":"Human-readable wait time, e.g. '2h30m'"},"is_token_expired":{"type":"boolean"}},"required":["workflow_id","delegation_id","approval_threshold","requested_at","time_waiting","is_token_expired"]}},"pagination":{"$ref":"#/components/schemas/Pagination"}},"required":["workflows","pagination"]},"AgentWorkflowSpendingSummaryResponse":{"type":"object","description":"GET /agent-workflow?action=spending_summary — per-agent spending analytics. When `delegation_id` is provided, only that delegation contributes to the summary.","properties":{"period":{"type":"string","enum":["day","week","month"]},"agent_count":{"type":"integer"},"agents":{"type":"array","items":{"type":"object","properties":{"agent_key_id":{"type":"string"},"current_period":{"type":"object","properties":{"workflow_count":{"type":"integer"},"completed":{"type":"integer"},"failed":{"type":"integer"},"total_deal_value":{"type":"number"},"average_deal_value":{"type":"number"}}},"delegation":{"type":"object","properties":{"delegation_id":{"type":"string"},"available_today":{"type":"number"},"available_this_month":{"type":"number"},"spending_ceiling":{"type":"number"},"percent_used":{"type":"number"}}},"delegations":{"type":"array","items":{"type":"object"},"description":"All active delegations for this agent"}},"required":["agent_key_id"]}}},"required":["period","agent_count","agents"]},"AgentWorkflowAnomaliesResponse":{"type":"object","description":"GET /agent-workflow?action=anomalies — detected spending anomalies. When `delegation_id` is provided, only that delegation is evaluated.","properties":{"tenant_id":{"type":"string"},"checked_at":{"type":"string","format":"date-time"},"anomaly_count":{"type":"integer"},"anomalies":{"type":"array","items":{"type":"object","properties":{"anomaly_id":{"type":"string"},"agent_key_id":{"type":"string"},"type":{"type":"string","description":"Anomaly type, e.g. rapid_escalation, budget_spike"},"severity":{"type":"string","enum":["low","medium","high","critical"]},"workflow_id":{"type":["string","null"]},"deal_id":{"type":["string","null"]},"deal_value":{"type":["number","null"]},"context":{"type":"object","description":"Type-specific anomaly context"},"detected_at":{"type":"string","format":"date-time"},"resolved":{"type":"boolean"},"details":{"type":"object"}},"required":["anomaly_id","agent_key_id","type","severity","detected_at","resolved"]}}},"required":["checked_at","anomaly_count","anomalies"]},"AgentWorkflowAgentStatsResponse":{"type":"object","description":"GET /agent-workflow?action=agent_stats — detailed stats and trend data for a single agent key","properties":{"agent_key_id":{"type":"string"},"overall":{"type":"object","properties":{"total_workflows":{"type":"integer"},"completed":{"type":"integer"},"failed":{"type":"integer"},"cancelled":{"type":"integer"},"total_deals":{"type":"integer"},"success_rate":{"type":"number","description":"Percentage of workflows completed successfully"},"first_workflow":{"type":["string","null"],"format":"date-time"},"last_workflow":{"type":["string","null"],"format":"date-time"}}},"trend":{"type":"array","description":"Workflow counts grouped by day or week. The `date` key is always present regardless of granularity (YYYY-MM-DD for daily, YYYY-WW for weekly).","items":{"type":"object","properties":{"date":{"type":"string","description":"Period label: YYYY-MM-DD (daily) or YYYY-WW week number (weekly)"},"workflow_count":{"type":"integer"},"completed":{"type":"integer"},"failed":{"type":"integer"}}}},"granularity":{"type":"string","enum":["daily","weekly"]},"active_delegations":{"type":"array","description":"Delegations currently granted to this agent (not revoked, not expired)","items":{"type":"object","properties":{"delegation_id":{"type":"string"},"max_transaction_amount":{"type":["number","null"],"description":"Per-transaction spending cap (null = unlimited)"},"max_daily_amount":{"type":["number","null"],"description":"Daily spending cap (null = unlimited)"},"max_monthly_amount":{"type":["number","null"],"description":"Monthly spending cap (null = unlimited)"},"spent_today":{"type":"number","description":"Amount spent today against this delegation"},"spent_this_month":{"type":"number","description":"Amount spent this month against this delegation"},"available_today":{"type":["number","null"],"description":"Remaining daily budget (max_daily_amount - spent_today - reserved_today); null when no daily cap"},"available_this_month":{"type":["number","null"],"description":"Remaining monthly budget (max_monthly_amount - spent_this_month - reserved_this_month); null when no monthly cap"},"allowed_actions":{"type":"array","items":{"type":"string"},"description":"Actions this delegation permits"},"expires_at":{"type":["string","null"],"format":"date-time","description":"When the delegation expires (null = no expiry)"},"created_at":{"type":"string","format":"date-time"}}}},"recent_anomalies":{"type":"array","items":{"type":"object","properties":{"anomaly_id":{"type":"string"},"type":{"type":"string"},"severity":{"type":"string"},"workflow_id":{"type":["string","null"]},"deal_value":{"type":["number","null"]},"detected_at":{"type":"string","format":"date-time"},"resolved":{"type":"boolean"},"details":{"type":"object"}}}}},"required":["agent_key_id","overall","trend","granularity"]},"AgentWorkflowPlanResponse":{"type":"object","description":"POST /agent-workflow (no action) — newly planned workflow (201 Created)","properties":{"workflow_id":{"type":"string","description":"Unique workflow identifier (wf_xxx)"},"intent":{"type":"string","enum":["purchase","sell","fulfill"]},"status":{"type":"string","const":"planned"},"steps":{"type":"array","items":{"type":"object","properties":{"step":{"type":"string"},"status":{"type":"string"},"completed_at":{"type":["string","null"],"format":"date-time"}}}},"delegation_check":{"type":"object","description":"Pre-validated delegation spending limits including reserved amounts"},"reserved_budget":{"type":["number","null"],"description":"Estimated budget reserved at plan time"},"reservation_id":{"type":["string","null"],"description":"Budget reservation ID for traceability"},"created_at":{"type":"string","format":"date-time"},"price_deltas_warning":{"type":"array","description":"Price change warnings detected during planning (non-fatal)","items":{"type":"object"}}},"required":["workflow_id","intent","status","steps","created_at"]},"AgentWorkflowExecuteResponse":{"type":"object","description":"POST /agent-workflow?action=execute (normal path) — workflow queued for async execution","properties":{"workflow_id":{"type":"string"},"status":{"type":"string","const":"executing"},"current_step":{"type":"string","description":"First step being executed (e.g. discover)"},"steps":{"type":"array","items":{"type":"object"}},"job_id":{"type":"string","description":"Async job queue ID — poll job status or listen for agent.workflow.step_completed webhooks"}},"required":["workflow_id","status","job_id"]},"AgentWorkflowExecuteDegradedResponse":{"type":"object","description":"POST /agent-workflow?action=execute (degraded path) — circuit breaker open, workflow in degraded mode","properties":{"workflow_id":{"type":"string"},"status":{"type":"string","const":"degraded"},"reason":{"type":"string","description":"Circuit-breaker open reason"},"unavailable_services":{"type":"array","items":{"type":"string"},"description":"Services currently unavailable"},"circuit_breaker":{"type":"object","description":"Circuit breaker status details"},"steps":{"type":"array","items":{"type":"object"}}},"required":["workflow_id","status","reason","unavailable_services"]},"AgentWorkflowModifyResponse":{"type":"object","description":"POST /agent-workflow?action=modify — updated workflow with modifications_applied list","allOf":[{"$ref":"#/components/schemas/AgentWorkflow"},{"type":"object","properties":{"modifications_applied":{"type":"array","description":"List of modifications successfully applied (e.g. discount, metadata, approval_threshold)","items":{"type":"string"}}},"required":["modifications_applied"]}]},"AgentWorkflowApproveResponse":{"type":"object","description":"POST /agent-workflow?action=approve — workflow approved and resumed","properties":{"workflow_id":{"type":"string"},"status":{"type":"string","const":"executing"},"current_step":{"type":"string","description":"Step that was paused and is now resuming"},"approved_by":{"type":"string","description":"Approver identity (e.g. user:123 or admin)"},"job_id":{"type":"string","description":"Async job queue ID for the resumed workflow"}},"required":["workflow_id","status","approved_by","job_id"]},"AgentWorkflowDelegateApproveResponse":{"type":"object","description":"POST /agent-workflow?action=delegate_approve — workflow approved via agent delegation scope","properties":{"workflow_id":{"type":"string"},"status":{"type":"string","const":"executing"},"current_step":{"type":"string","description":"Step that was paused and is now resuming"},"approved_by":{"type":"string","description":"Approver identity in the format agent:{keyId}:delegation:{delegationId}"},"delegation_id":{"type":"string"},"delegation_chain":{"type":"array","description":"Chain of delegation IDs from original grantor to approving agent","items":{"type":"string"}},"deal_value":{"type":["number","null"],"description":"Deal value at time of approval (null if no deal created yet)"},"job_id":{"type":"string","description":"Async job queue ID for the resumed workflow"}},"required":["workflow_id","status","approved_by","delegation_id","delegation_chain","job_id"]},"AgentWorkflowResendApprovalResponse":{"type":"object","description":"POST /agent-workflow?action=resend_approval — approval notification re-sent","properties":{"workflow_id":{"type":"string"},"resend_number":{"type":"integer","description":"Cumulative resend count (1-based)"},"resends_remaining":{"type":"integer","description":"Remaining allowed resends"},"token_expires_at":{"type":"string","format":"date-time","description":"Expiry of the current approval token"},"approve_url":{"type":"string","description":"Deep-link URL for one-click approval (for webhook payloads)"},"reject_url":{"type":"string","description":"Deep-link URL for one-click rejection (for webhook payloads)"}},"required":["workflow_id","resend_number","resends_remaining","approve_url","reject_url"]},"AgentWorkflowEscalateApprovalResponse":{"type":"object","description":"POST /agent-workflow?action=escalate_approval — approval escalated to delegation grantor","properties":{"workflow_id":{"type":"string"},"escalation_reason":{"type":"string","description":"Reason provided for escalation"},"escalated_to":{"type":"object","description":"Target approver (delegation grantor)","properties":{"type":{"type":"string","description":"Approver type (e.g. user, team)"},"id":{"type":"string"}},"required":["type","id"]},"token_expires_at":{"type":"string","format":"date-time","description":"Expiry of the new approval token"},"approve_url":{"type":"string","description":"Deep-link URL for one-click approval (for webhook payloads)"},"reject_url":{"type":"string","description":"Deep-link URL for one-click rejection (for webhook payloads)"}},"required":["workflow_id","escalation_reason","escalated_to","approve_url","reject_url"]},"StateMachineResponse":{"type":"object","description":"Machine-readable state machine definitions for entity types","properties":{"schema_version":{"type":"string","description":"Version of the state machine schema format","examples":["1.0.0"]},"entity_types":{"type":"array","items":{"type":"string"},"description":"Available entity types","examples":[["deals","contracts"]]},"deals":{"$ref":"#/components/schemas/EntityStateMachine"},"contracts":{"$ref":"#/components/schemas/EntityStateMachine"}},"required":["schema_version","entity_types"]},"EntityStateMachine":{"type":"object","description":"State machine definition for a single entity type","properties":{"entity_type":{"type":"string","description":"The entity type this state machine applies to"},"initial_state":{"type":"string","description":"The initial state when an entity is created"},"states":{"type":"object","description":"Map of state name to state definition","additionalProperties":{"$ref":"#/components/schemas/StateDefinition"}}},"required":["entity_type","initial_state","states"]},"StateDefinition":{"type":"object","properties":{"terminal":{"type":"boolean","description":"Whether this is a terminal state (no outgoing transitions)"},"transitions":{"type":"array","items":{"$ref":"#/components/schemas/StateTransition"}}},"required":["terminal","transitions"]},"StateTransition":{"type":"object","properties":{"target":{"type":"string","description":"The target state of this transition"},"conditions":{"type":"array","description":"Business rule conditions that must be met","items":{"type":"object","properties":{"field":{"type":"string"},"check":{"type":"string"},"description":{"type":"string"}}}},"action":{"type":"object","description":"The API action required to perform this transition","properties":{"method":{"type":"string","enum":["POST","PATCH"]},"endpoint":{"type":"string"},"description":{"type":"string"}}},"required_scope":{"type":"string","description":"The API scope required to perform this transition"}},"required":["target","conditions","action","required_scope"]},"ValidTransitionsResponse":{"type":"object","description":"Context-aware valid transitions for a specific deal","properties":{"deal_id":{"type":"string","description":"The deal ID"},"current_status":{"type":"string","description":"The current status of the deal"},"transitions":{"type":"array","items":{"type":"object","properties":{"target":{"type":"string","description":"The target state"},"available":{"type":"boolean","description":"Whether this transition is currently available (all conditions met)"},"conditions":{"type":"array","items":{"type":"object","properties":{"description":{"type":"string"},"satisfied":{"type":"boolean"}}}},"action":{"type":"object","properties":{"method":{"type":"string"},"endpoint":{"type":"string"},"description":{"type":"string"}}}}}}},"required":["deal_id","current_status","transitions"]},"TeamMember":{"type":"object","properties":{"membership_id":{"type":"integer"},"user_id":{"type":"integer"},"name":{"type":"string"},"email":{"type":"string","format":"email"},"role":{"type":"string","enum":["owner","admin","member","viewer"]},"status":{"type":"string","enum":["active","invited","suspended"]},"invited_at":{"type":["string","null"],"format":"date-time"},"accepted_at":{"type":["string","null"],"format":"date-time"},"last_active":{"type":["string","null"],"format":"date-time"},"created_at":{"type":"string","format":"date-time"}}},"Booking":{"type":"object","description":"A booking for a service product time slot","properties":{"booking_id":{"type":"string","description":"Unique booking identifier","examples":["bkng_a1b2c3d4e5"]},"tenant_id":{"type":"string","description":"Tenant identifier"},"deal_id":{"type":["string","null"],"description":"Associated deal identifier"},"line_item_id":{"type":["string","null"],"description":"Associated deal line item identifier"},"product_id":{"type":"string","description":"Service product identifier"},"product_name":{"type":["string","null"],"description":"Product name (included in list and detail responses)"},"staff_id":{"type":"string","description":"Assigned staff member identifier"},"staff_name":{"type":["string","null"],"description":"Staff member name (included in list and detail responses)"},"customer_id":{"type":["string","null"],"description":"Customer identifier"},"customer_name":{"type":["string","null"],"description":"Customer full name"},"customer_email":{"type":["string","null"],"description":"Customer email address"},"customer_phone":{"type":["string","null"],"description":"Customer phone number"},"booking_date":{"type":"string","format":"date","description":"Date of the booking"},"start_time":{"type":"string","description":"Start time in HH:MM format (24-hour)","examples":["09:00"]},"end_time":{"type":"string","description":"End time in HH:MM format (24-hour)","examples":["10:00"]},"status":{"type":"string","enum":["held","confirmed","completed","cancelled","no_show"],"description":"Current booking status"},"hold_expires_at":{"type":["string","null"],"format":"date-time","description":"When the hold expires (only set when status is held)"},"notes":{"type":["string","null"],"description":"Optional booking notes"},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"}},"required":["booking_id","product_id","staff_id","booking_date","start_time","end_time","status"]},"Delegation":{"type":"object","properties":{"delegation_id":{"type":"string","description":"Unique delegation identifier","examples":["deleg_abc123def456"]},"tenant_id":{"type":"string","description":"Tenant context"},"grantor_type":{"type":"string","enum":["user","agent"],"description":"Whether the grantor is a human user or another agent"},"grantor_id":{"type":"string","description":"User ID or API key ID of the grantor"},"grantee_agent_key_id":{"type":"string","description":"API key ID receiving the delegation"},"max_transaction_amount":{"type":["number","null"],"description":"Maximum per-transaction spend (null = unlimited)"},"max_daily_amount":{"type":["number","null"],"description":"Maximum daily spend (null = unlimited)"},"max_monthly_amount":{"type":["number","null"],"description":"Maximum monthly spend (null = unlimited)"},"spent_today":{"type":"string","description":"Amount spent today under this delegation"},"spent_this_month":{"type":"string","description":"Amount spent this month under this delegation"},"reserved_today":{"type":"string","description":"Amount reserved today by planned workflows (not yet converted to spend)"},"reserved_this_month":{"type":"string","description":"Amount reserved this month by planned workflows (not yet converted to spend)"},"available_today":{"type":["string","null"],"description":"Available daily budget (max_daily_amount - spent_today - reserved_today). Null if no daily limit."},"available_this_month":{"type":["string","null"],"description":"Available monthly budget (max_monthly_amount - spent_this_month - reserved_this_month). Null if no monthly limit."},"allowed_actions":{"type":"array","items":{"type":"string"},"description":"Action scopes granted by this delegation (e.g. deals:write, agent:negotiate)"},"delegation_chain":{"type":"array","items":{"type":"string"},"description":"Parent delegation IDs for full traceability (e.g. [\"deleg_abc\", \"deleg_def\"])"},"expires_at":{"type":["string","null"],"format":"date-time","description":"When the delegation expires (null = no expiry)"},"revoked_at":{"type":["string","null"],"format":"date-time","description":"When the delegation was revoked (null = active)"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":["string","null"],"format":"date-time"},"description":{"type":["string","null"],"description":"Human-readable description of the delegation's purpose"},"approval_threshold":{"type":["number","null"],"description":"Transaction amount above which approval is required (null = no approval gate)"},"approval_steps":{"type":["array","null"],"items":{"type":"object"},"description":"Ordered list of approval step configurations (null = no multi-step approval)"},"approval_timeout":{"type":["integer","null"],"description":"Seconds to wait for approval before timing out (null = no timeout)"},"auto_approve_policy":{"type":["object","null"],"description":"Policy rules for automatic approval without human review (null = no auto-approval)"},"alert_threshold_pct":{"type":["integer","null"],"description":"Percentage of spending limit at which to send an alert (null = no alert)"}},"required":["delegation_id","tenant_id","grantor_type","grantor_id","grantee_agent_key_id","allowed_actions","delegation_chain"]},"DelegationSummary":{"type":"object","description":"Dashboard summary of delegation activity (action=summary)","properties":{"active_delegations":{"type":"integer","description":"Number of currently active delegations for this user"},"total_spent_today":{"type":"string","description":"Total amount spent today across all delegations (2 decimal string)"},"total_reserved_today":{"type":"string","description":"Total amount reserved today across all delegations (2 decimal string)"},"approaching_limit":{"type":"integer","description":"Number of delegations at or above 80% of their daily spending limit"},"recent_actions":{"type":"array","description":"Last 5 audit trail entries across all delegations","items":{"type":"object","properties":{"action":{"type":"string","description":"Audit action type (e.g. created, updated, signed)"},"entity_id":{"type":"string"},"created_at":{"type":"string","format":"date-time"}},"required":["action","entity_id","created_at"]}}},"required":["active_delegations","total_spent_today","total_reserved_today","approaching_limit","recent_actions"]},"DelegationAnalytics":{"type":"object","description":"Per-delegation analytics including spending breakdown, deals created, ROI metrics and 30-day chart (action=analytics)","properties":{"delegation":{"$ref":"#/components/schemas/Delegation"},"spending":{"type":"object","properties":{"spent_today":{"type":"string","description":"Amount spent today (2 decimal string)"},"spent_this_week":{"type":"string","description":"Amount spent this week (2 decimal string)"},"spent_this_month":{"type":"string","description":"Amount spent this month (2 decimal string)"},"reserved_today":{"type":"string","description":"Amount reserved today (2 decimal string)"},"lifetime_spend":{"type":"string","description":"Total lifetime spend under this delegation (2 decimal string)"},"avg_daily_spend":{"type":"string","description":"Average daily spend over the delegation lifetime (2 decimal string)"},"daily_utilization_pct":{"type":["number","null"],"description":"Percentage of daily limit consumed (null if no daily limit)"},"monthly_utilization_pct":{"type":["number","null"],"description":"Percentage of monthly limit consumed (null if no monthly limit)"}},"required":["spent_today","spent_this_week","spent_this_month","reserved_today","lifetime_spend","avg_daily_spend"]},"burn_rate":{"type":"object","properties":{"monthly_daily_rate":{"type":"string","description":"Average spend per day so far this month (2 decimal string)"},"monthly_days_remaining":{"type":["integer","null"],"description":"Estimated days until monthly limit is exhausted at current rate (null if no limit or zero burn)"},"projected_exhaustion_date":{"type":["string","null"],"format":"date","description":"Projected date the monthly limit will be exhausted (null if no limit or zero burn)"},"days_in_month":{"type":"integer","description":"Total number of days in the current month"},"days_elapsed":{"type":"integer","description":"Number of days elapsed so far this month"}},"required":["monthly_daily_rate","days_in_month","days_elapsed"]},"deals":{"type":"object","properties":{"count":{"type":"integer","description":"Total number of deals created under this delegation"},"total_value":{"type":"string","description":"Sum of all deal values (2 decimal string)"},"close_rate":{"type":"number","description":"Ratio of accepted/paid deals to total deals (0.0–1.0)"},"items":{"type":"array","items":{"type":"object","properties":{"deal_id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string"},"value":{"type":"string"},"customer_id":{"type":"string"},"created_at":{"type":"string","format":"date-time"}},"required":["deal_id","title","status","value","customer_id","created_at"]}}},"required":["count","total_value","close_rate","items"]},"roi":{"type":"object","properties":{"deal_value":{"type":"string","description":"Total value of all deals created (2 decimal string)"},"platform_cost":{"type":"string","description":"Total platform spend (lifetime_spend) (2 decimal string)"},"roi_ratio":{"type":["number","null"],"description":"deal_value / platform_cost ratio (null when cost is zero)"}},"required":["deal_value","platform_cost"]},"chart":{"type":"array","description":"Daily spend for the last 30 days","items":{"type":"object","properties":{"day":{"type":"string","format":"date","description":"Date in YYYY-MM-DD format"},"spend":{"type":"number","description":"Total spend on this day"}},"required":["day","spend"]}},"activity":{"type":"object","properties":{"total":{"type":"integer"},"offset":{"type":"integer"},"limit":{"type":"integer"},"items":{"type":"array","items":{"type":"object","properties":{"action":{"type":"string"},"entity_type":{"type":"string"},"entity_id":{"type":"string"},"created_at":{"type":"string","format":"date-time"},"outcome":{"type":"string","enum":["success","failure"]}},"required":["action","entity_type","entity_id","created_at","outcome"]}}},"required":["total","offset","limit","items"]}},"required":["delegation","spending","burn_rate","deals","roi","chart","activity"]},"DelegationActivity":{"type":"object","description":"Paginated, filterable audit trail for a delegation (action=activity)","properties":{"total":{"type":"integer","description":"Total number of matching audit entries"},"offset":{"type":"integer","description":"Current page offset"},"limit":{"type":"integer","description":"Maximum items per page"},"items":{"type":"array","items":{"type":"object","properties":{"action":{"type":"string","description":"Audit action type (e.g. deal_created, deal_signed)"},"entity_type":{"type":"string","description":"Entity type the action was taken on (e.g. deal, contract)"},"entity_id":{"type":"string","description":"ID of the affected entity"},"created_at":{"type":"string","format":"date-time"},"outcome":{"type":"string","enum":["success","failure"],"description":"Whether the action succeeded or failed"},"details":{"type":["object","null"],"description":"Additional action details from the audit trail (null if not available)"}},"required":["action","entity_type","entity_id","created_at","outcome"]}}},"required":["total","offset","limit","items"]},"DelegationPermissionCheck":{"type":"object","description":"Result of an agent permission check — validates the calling agent’s active delegation and returns its allowed actions (action=check)","properties":{"valid":{"type":"boolean","description":"Whether the calling agent has a valid, non-expired, non-revoked delegation"},"delegation_id":{"type":["string","null"],"description":"Active delegation ID (null if no valid delegation found)"},"allowed_actions":{"type":"array","items":{"type":"string"},"description":"Action scopes granted by the active delegation (empty array if invalid)"},"expires_at":{"type":["string","null"],"format":"date-time","description":"When the delegation expires (null if no expiry or no valid delegation)"},"reason":{"type":["string","null"],"description":"Human-readable reason when valid=false (null when valid=true)"}},"required":["valid","allowed_actions"]},"DelegationSpending":{"type":"object","description":"Spending totals and limit utilisation for a specific delegation (action=spending)","properties":{"delegation_id":{"type":"string","description":"Delegation identifier"},"spent_today":{"type":"number","description":"Amount spent today under this delegation"},"spent_this_month":{"type":"number","description":"Amount spent this month under this delegation"},"reserved_today":{"type":"number","description":"Amount reserved today by planned workflows"},"reserved_this_month":{"type":"number","description":"Amount reserved this month by planned workflows"},"available_today":{"type":["number","null"],"description":"Remaining daily budget (null if no daily limit)"},"available_this_month":{"type":["number","null"],"description":"Remaining monthly budget (null if no monthly limit)"},"max_transaction_amount":{"type":["number","null"],"description":"Maximum per-transaction spend limit (null if unlimited)"},"max_daily_amount":{"type":["number","null"],"description":"Maximum daily spend limit (null if unlimited)"},"max_monthly_amount":{"type":["number","null"],"description":"Maximum monthly spend limit (null if unlimited)"},"daily_utilization_pct":{"type":["number","null"],"description":"Percentage of daily limit consumed, 1 decimal place (null if no daily limit)"},"monthly_utilization_pct":{"type":["number","null"],"description":"Percentage of monthly limit consumed, 1 decimal place (null if no monthly limit)"}},"required":["delegation_id","spent_today","spent_this_month","reserved_today","reserved_this_month"]},"DelegationPendingProposals":{"type":"object","description":"Paginated list of pending delegation proposals targeting the authenticated agent (action=pending)","properties":{"proposals":{"type":"array","items":{"$ref":"#/components/schemas/DelegationProposal"}},"pagination":{"$ref":"#/components/schemas/Pagination"}},"required":["proposals","pagination"]},"DelegationVerification":{"type":"object","description":"Result of a delegation validity and chain integrity check (action=verify)","properties":{"valid":{"type":"boolean","description":"Whether the delegation and its entire chain are valid and active"},"reason":{"type":["string","null"],"description":"Human-readable reason when valid=false (null when valid=true). Examples: Delegation not found, Delegation has been revoked, Delegation has expired, Parent delegation {id} is no longer active"},"delegation":{"oneOf":[{"$ref":"#/components/schemas/Delegation"},{"type":"null"}],"description":"Full delegation object when valid=true, null when valid=false"}},"required":["valid"]},"NegotiationRound":{"type":"object","description":"A single round in a deal negotiation. propose and counter actions return this with optional delegation_budget. accept adds accepted_by. reject adds rejected_by and optionally rejection_reason. counter adds term_changes.","properties":{"negotiation_id":{"type":"string","description":"Unique identifier for this negotiation round (neg_*)"},"deal_id":{"type":"string","description":"Deal this negotiation belongs to"},"round_number":{"type":"integer","description":"Sequential round number starting at 1"},"proposer_type":{"type":"string","enum":["agent","user"],"description":"Whether the proposer is an agent (API key) or a user (session)"},"proposer_id":{"type":"string","description":"API key ID or user ID of the proposer"},"proposed_terms":{"type":"object","description":"Structured deal terms submitted in this round"},"message":{"type":["string","null"],"description":"Optional free-text message accompanying the proposal"},"status":{"type":"string","enum":["proposed","counter_proposed","accepted","rejected","expired"],"description":"Current status of this negotiation round"},"expires_at":{"type":["string","null"],"format":"date-time","description":"When this round expires (null if no expiry set)"},"created_at":{"type":"string","format":"date-time","description":"When this round was created"},"term_changes":{"type":"object","description":"Diff of term changes from the previous round (counter action only)"},"accepted_by":{"type":"object","description":"Who accepted the proposal (accept action only)","properties":{"type":{"type":"string","enum":["agent","user"]},"id":{"type":"string"}},"required":["type","id"]},"rejected_by":{"type":"object","description":"Who rejected the proposal (reject action only)","properties":{"type":{"type":"string","enum":["agent","user"]},"id":{"type":"string"}},"required":["type","id"]},"rejection_reason":{"type":"string","description":"Optional reason for rejection (reject action only, when reason was provided)"},"delegation_budget":{"type":"object","description":"Delegation spending budget metadata (present when request is made under an active delegation)","properties":{"remaining_budget":{"type":"number","description":"Remaining budget under the delegation"},"approaching_limit":{"type":"boolean","description":"True when accumulated spend would reach >=80% of any delegation limit"}},"required":["remaining_budget","approaching_limit"]}},"required":["negotiation_id","deal_id","round_number","proposer_type","proposer_id","proposed_terms","status","created_at"]},"NegotiationHistory":{"type":"object","description":"Full round-by-round negotiation history for a deal (GET /deal-negotiations default response)","properties":{"deal_id":{"type":"string","description":"Deal ID the history belongs to"},"rounds":{"type":"array","items":{"$ref":"#/components/schemas/NegotiationRound"},"description":"Ordered list of negotiation rounds, oldest first"},"total_rounds":{"type":"integer","description":"Total number of negotiation rounds"}},"required":["deal_id","rounds","total_rounds"]},"NegotiationIntelligence":{"type":"object","description":"Pricing intelligence for a deal, used to inform counter-offers (GET /deal-negotiations?action=intelligence)","properties":{"suggestion":{"description":"Pricing suggestion based on historical deal data, or null when insufficient data","oneOf":[{"type":"object","properties":{"should_discount":{"type":"boolean","description":"Whether applying a discount is recommended"},"recommended_discount":{"type":["number","null"],"description":"Recommended discount percentage (null when no specific discount is suggested)"},"reason":{"type":"string","description":"Human-readable rationale for the suggestion"}},"required":["should_discount","reason"]},{"type":"null"}]},"reason":{"type":"string","description":"Fallback message when suggestion is null (e.g. 'No tenant context available', 'Deal has no line items')"}}},"PricingSimulationItem":{"type":"object","description":"Per-product line-item breakdown returned by POST /simulate-pricing","properties":{"product_id":{"type":"string","description":"Product ID"},"product_name":{"type":"string","description":"Product display name"},"quantity":{"type":"integer","minimum":1,"description":"Quantity selected"},"base_price":{"type":"number","description":"Unit base price before options"},"options_total":{"type":"number","description":"Total option modifier price added to base"},"unit_price":{"type":"number","description":"Final unit price (base + options, clamped to ≥0)"},"line_total":{"type":"number","description":"unit_price × quantity"},"once_off_line_total":{"type":"number","description":"Once-off billing portion of line_total"},"recurring_line_total":{"type":"number","description":"Recurring billing portion of line_total"},"metered_line_total":{"type":"number","description":"Metered billing portion of line_total"},"tax_rate":{"type":"number","description":"Applicable tax rate as a decimal (e.g. 0.1 for 10%)"},"price_type":{"type":"string","description":"Product billing type (once_off, recurring, or metered)"},"option_ids":{"type":"array","items":{"type":"string"},"description":"Selected option IDs for this line item"},"options":{"type":"array","description":"Resolved option details with product-level price overrides applied","items":{"type":"object"}}},"required":["product_id","product_name","quantity","base_price","options_total","unit_price","line_total","once_off_line_total","recurring_line_total","metered_line_total","tax_rate","price_type","option_ids","options"]},"PricingSimulationResult":{"type":"object","description":"Full pricing simulation result returned by POST /simulate-pricing. No deals are created — all operations are read-only.","properties":{"items":{"type":"array","items":{"$ref":"#/components/schemas/PricingSimulationItem"},"description":"Per-product line-item breakdowns"},"subtotal":{"type":"number","description":"Cart subtotal before discounts and tax"},"bundle_discounts":{"type":"array","description":"Applied bundle discount rules","items":{"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"discount_type":{"type":"string","enum":["percentage","fixed"]},"discount_value":{"type":"number"},"matched_options":{"type":"array","items":{"type":"string"}},"discount_amount":{"type":"number"},"billing_type":{"type":"string"}},"required":["bundle_id","name","discount_type","discount_value","matched_options","discount_amount","billing_type"]}},"bundle_discount_total":{"type":"number","description":"Sum of all applied bundle discount amounts"},"promo_discount":{"type":"number","description":"Discount amount from the promo code (0 when no promo code was provided)"},"promo_details":{"description":"Applied promo code details, or null when no promo code was provided","oneOf":[{"type":"object","properties":{"code":{"type":"string","description":"Normalised promo code (uppercased)"},"discount_type":{"type":"string","enum":["percentage","fixed"]},"discount_value":{"type":"number","description":"Configured discount value (percentage points or fixed amount)"},"discount_amount":{"type":"number","description":"Actual monetary discount applied to this cart"}},"required":["code","discount_type","discount_value","discount_amount"]},{"type":"null"}]},"auto_discount_total":{"type":"number","description":"Sum of all applied auto-discount amounts (0 when no auto_discounts were provided)"},"auto_discounts_applied":{"type":"array","description":"Auto-discounts that were applied (may be fewer than input when min_subtotal is not met)","items":{"type":"object","properties":{"type":{"type":"string","enum":["percentage","fixed"]},"value":{"type":"number"},"description":{"type":"string"},"discount_amount":{"type":"number","description":"Computed monetary discount amount"}},"required":["type","value","description","discount_amount"]}},"tax_amount":{"type":"number","description":"Calculated tax on the post-discount total"},"total":{"type":"number","description":"Final cart total including all discounts and tax"},"currency":{"type":"string","pattern":"^[A-Z]{3}$","description":"ISO 4217 currency code"},"savings_vs_individual":{"type":"number","description":"Total savings vs purchasing each product individually (bundle_discount_total + promo_discount + auto_discount_total)"},"compatibility_errors":{"type":"array","items":{"type":"string"},"description":"Compatibility rule violations detected in this cart configuration"},"simulation_only":{"type":"boolean","const":true,"description":"Always true — this endpoint never creates deals"}},"required":["items","subtotal","bundle_discounts","bundle_discount_total","promo_discount","promo_details","auto_discount_total","auto_discounts_applied","tax_amount","total","currency","savings_vs_individual","compatibility_errors","simulation_only"]},"NegotiationAnalysis":{"type":"object","description":"Historical negotiation analytics returned by GET /simulate-pricing. Aggregates past deal negotiations to surface optimal opening discount strategies.","properties":{"period_days":{"type":"integer","description":"Lookback period analysed in days"},"total_negotiations":{"type":"integer","description":"Total number of negotiations found in the period"},"accepted_count":{"type":"integer","description":"Number of negotiations that resulted in an accepted deal"},"avg_discount_pct":{"type":["number","null"],"description":"Average discount percentage granted across accepted deals (null when no accepted deals exist)"},"avg_rounds":{"type":["number","null"],"description":"Average number of negotiation rounds before resolution (null when no negotiations exist)"},"success_rate_by_tier":{"type":"object","description":"Success rate broken down by discount tier (e.g. '0-5%', '5-10%', '10-20%', '20%+')","additionalProperties":{"type":"object","properties":{"count":{"type":"integer","description":"Total negotiations in this discount tier"},"accepted":{"type":"integer","description":"Accepted negotiations in this tier"},"success_rate":{"type":["number","null"],"description":"Acceptance rate for this tier (null when count is 0)"}},"required":["count","accepted","success_rate"]}},"suggested_opening_discount":{"description":"Recommended opening discount based on the tier with the highest historical success rate (requires ≥3 negotiations in a tier), or null when insufficient data","oneOf":[{"type":"object","properties":{"tier":{"type":"string","description":"Discount tier label (e.g. '5-10%')"},"success_rate":{"type":"number","description":"Historical acceptance rate for this tier"}},"required":["tier","success_rate"]},{"type":"null"}]},"data_quality":{"type":"string","enum":["good","limited","insufficient"],"description":"Data quality indicator: good ≥10 negotiations, limited ≥3, insufficient <3"}},"required":["period_days","total_negotiations","accepted_count","avg_discount_pct","avg_rounds","success_rate_by_tier","suggested_opening_discount","data_quality"]},"NegotiationSuggestions":{"type":"object","description":"AI-generated counter-proposal suggestions (POST /deal-negotiations?action=suggest)","properties":{"suggestions":{"type":"array","description":"Ranked list of counter-proposal suggestions, ordered by confidence descending","items":{"type":"object","properties":{"type":{"type":"string","description":"Suggestion strategy type (e.g. meet_halfway, historical_anchor, standard_discount)"},"confidence":{"type":"integer","minimum":0,"maximum":100,"description":"Confidence score 0-100; blended from historical win rates and pricing signals"},"recommended_terms":{"type":"object","description":"Suggested deal terms to use as the counter-proposal"},"win_probability_delta":{"type":["number","null"],"description":"Estimated change in win probability if this suggestion is applied"},"rationale":{"type":"string","description":"Human-readable explanation of why this suggestion is recommended"},"risk_level":{"type":"string","enum":["low","medium","high"],"description":"Risk level of applying this suggestion"},"risk_assessment":{"type":"string","description":"Detailed risk assessment narrative"},"acceptance_rate":{"type":"number","description":"Historical acceptance rate for this suggestion type (0.0–1.0), present when >=5 historical data points exist"}},"required":["type","confidence","recommended_terms","rationale","risk_level","risk_assessment"]}},"deal_id":{"type":"string","description":"Deal ID the suggestions were generated for"},"suggestion_id":{"type":["string","null"],"description":"Stored suggestion ID for the learning loop (null when no suggestions generated)"},"data_quality":{"type":"string","enum":["none","low","medium","high"],"description":"Quality of historical data used: none (no data), low (<10 deals), medium (10-50), high (50+)"},"historical_deals":{"type":"integer","description":"Number of historical deals used to generate suggestions"},"currency":{"type":"string","description":"Currency code for price values in suggestions"},"reference_price":{"type":["number","null"],"description":"Reference price derived from historical deal averages"},"current_proposed_price":{"type":["number","null"],"description":"Current proposed total from the latest negotiation round"}},"required":["suggestions","data_quality"]},"CreateDelegationRequest":{"type":"object","description":"Request body for creating a new agent delegation. When `allowed_actions` includes `sign`, `deals:sign`, or `contracts:sign`, the `signing_authority_acknowledged` field is required. This confirms the principal understands they are authorising an AI agent to execute legally binding agreements on their behalf — analogous to a commercial power of attorney. A `signing_authority_granted` audit event is recorded for the delegation.","properties":{"grantee_agent_key_id":{"type":"string","description":"API key ID to grant the delegation to"},"allowed_actions":{"type":"array","items":{"type":"string"},"description":"Action scopes to grant (e.g. [\"deals:write\", \"agent:negotiate\", \"deals:sign\"])"},"max_transaction_amount":{"type":"number","description":"Maximum per-transaction amount"},"max_daily_amount":{"type":"number","description":"Maximum daily spend"},"max_monthly_amount":{"type":"number","description":"Maximum monthly spend"},"expires_at":{"type":"string","format":"date-time","description":"Delegation expiry (must be in the future)"},"signing_authority_acknowledged":{"type":"boolean","description":"Required when `allowed_actions` includes `sign`, `deals:sign`, or `contracts:sign`. Must be `true`. Confirms the principal explicitly authorises the agent to execute legally binding agreements on their behalf. A `signing_authority_granted` audit event is recorded with timestamp and delegation context."},"description":{"type":"string","maxLength":500,"description":"Optional human-readable description for this delegation"},"approval_threshold":{"type":["number","null"],"minimum":0,"maximum":99999999.99,"description":"Transaction amount above which human approval is required before the agent can proceed"},"approval_steps":{"type":["object","null"],"description":"Structured approval workflow definition (e.g. sequential approvers, parallel gates). Maximum nesting depth of 3."},"approval_timeout":{"type":["integer","null"],"minimum":0,"maximum":86400,"description":"Seconds to wait for approval before timing out (0–86400). When elapsed the pending action is auto-rejected."},"auto_approve_policy":{"type":["object","null"],"description":"Policy rules that allow automatic approval without human intervention (e.g. trusted-counterparty list, low-risk product categories). Maximum nesting depth of 3."},"alert_threshold_pct":{"type":["integer","null"],"minimum":1,"maximum":100,"description":"Percentage of spending limit (1–100) at which a budget alert notification is triggered"}},"required":["grantee_agent_key_id","allowed_actions"],"if":{"properties":{"allowed_actions":{"contains":{"enum":["sign","deals:sign","contracts:sign"]}}},"required":["allowed_actions"]},"then":{"required":["signing_authority_acknowledged"],"properties":{"signing_authority_acknowledged":{"const":true}}}},"ProposeDelegationRequest":{"type":"object","description":"Request body for POST /delegations?action=propose — Agent A proposes a sub-delegation to Agent B. Note: uses target_api_key_id and proposed_actions, not grantee_agent_key_id and allowed_actions (those are for CreateDelegationRequest).","properties":{"target_api_key_id":{"type":"string","maxLength":255,"description":"API key ID of the target agent to propose the delegation to"},"proposed_actions":{"type":"array","items":{"type":"string"},"maxItems":50,"description":"Action scopes to propose (e.g. [\"deals:read\", \"agent:negotiate\"])"},"max_transaction_amount":{"type":"number","minimum":0,"maximum":99999999.99,"description":"Maximum per-transaction amount"},"max_daily_amount":{"type":"number","minimum":0,"maximum":99999999.99,"description":"Maximum daily spend"},"max_monthly_amount":{"type":"number","minimum":0,"maximum":99999999.99,"description":"Maximum monthly spend"},"proposed_duration_hours":{"type":"integer","minimum":1,"maximum":8760,"description":"Proposed delegation duration in hours (1–8760)"},"message":{"type":"string","maxLength":2000,"description":"Optional message explaining the proposal"}},"required":["target_api_key_id","proposed_actions"]},"Deal":{"type":"object","description":"Full deal object returned by single-deal GET, POST, and PATCH responses. List responses use DealListItem.","properties":{"deal_id":{"type":"string","description":"Unique deal identifier","examples":["deal_a1b2c3d4e5"]},"version":{"type":"integer","description":"Optimistic locking version. Incremented atomically on each update. Used as ETag value for concurrency control.","minimum":1,"examples":[1]},"customer_id":{"type":["string","null"],"description":"Associated customer ID. Null for deals created before customer info is collected (e.g. widget negotiation flow)."},"title":{"type":["string","null"],"description":"Deal title"},"description":{"type":["string","null"],"description":"Deal description"},"notes":{"type":["string","null"],"description":"Internal notes visible only to the seller"},"status":{"type":"string","enum":["draft","in_progress","pending_signature","awaiting_signatures","pending_payment","partially_accepted","closed","cancelled","expired"],"description":"Current deal status"},"currency":{"type":"string","description":"ISO 4217 currency code","examples":["AUD"]},"presentation_currency":{"type":"string","description":"Currency displayed to the buyer (ISO 4217)","examples":["JPY"]},"settlement_currency":{"type":"string","description":"Currency the seller receives settlement in (ISO 4217)","examples":["AUD"]},"fx_rate":{"type":["number","null"],"format":"double","description":"Locked FX rate from presentation to settlement currency at deal creation"},"fx_rate_locked_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the FX rate was locked"},"fx_rate_provider":{"type":["string","null"],"description":"Source of the FX rate (e.g. 'stripe', 'identity')"},"deposit_required":{"type":["string","null"],"description":"Required deposit amount (raw value from DB; see pricing.deposit_required for formatted object)"},"customer":{"$ref":"#/components/schemas/CustomerSummary"},"line_items":{"type":"array","items":{"$ref":"#/components/schemas/LineItem"},"description":"Line items in the deal"},"pricing":{"type":"object","description":"All monetary amounts for the deal, each expressed as an {amount, currency, formatted} object","properties":{"currency":{"type":"string","description":"Settlement currency (ISO 4217)"},"presentation_currency":{"type":"string","description":"Presentation currency (ISO 4217)"},"settlement_currency":{"type":"string","description":"Settlement currency (ISO 4217)"},"fx_rate":{"type":["number","null"],"format":"double","description":"FX rate applied to this deal"},"subtotal":{"$ref":"#/components/schemas/MoneyAmount","description":"Subtotal before discounts and tax"},"discounts":{"type":"array","items":{"$ref":"#/components/schemas/Discount"},"description":"Applied discounts"},"discount":{"$ref":"#/components/schemas/MoneyAmount","description":"Total discount amount"},"tax_rate":{"type":["number","null"],"format":"double","description":"Tax rate as decimal (e.g. 0.10 = 10%)"},"tax_amount":{"$ref":"#/components/schemas/MoneyAmount","description":"Calculated tax amount"},"total":{"$ref":"#/components/schemas/MoneyAmount","description":"Total amount including tax"},"deposit_required":{"$ref":"#/components/schemas/MoneyAmount","description":"Required deposit amount"},"deposit_collected":{"$ref":"#/components/schemas/MoneyAmount","description":"Deposit amount already collected"},"balance_due":{"$ref":"#/components/schemas/MoneyAmount","description":"Remaining balance due"}}},"terms":{"type":"object","description":"Contract documents and structured machine-readable terms","properties":{"document_id":{"type":["string","null"],"description":"Contract document ID"},"template_id":{"type":["string","null"],"description":"Contract template ID"},"contract_url":{"type":["string","null"],"description":"URL to contract document"},"agreed_at":{"type":["string","null"],"format":"date-time","description":"When terms were agreed"},"signature":{"type":["object","null"],"description":"Cryptographic signature data if the deal has been signed","$ref":"#/components/schemas/Signature"},"structured":{"type":["object","null"],"description":"Machine-readable structured deal terms. See GET /schema/deal-terms for the full schema.","$ref":"#/components/schemas/DealTerms"},"terms_schema_version":{"type":["string","null"],"description":"Version of the deal terms schema","examples":["1.0"]}}},"payment":{"type":"object","description":"Payment details for the deal","properties":{"processor":{"type":["string","null"],"description":"Payment processor used (e.g. 'stripe')"},"payment_intent_id":{"type":["string","null"],"description":"payment intent ID or equivalent"},"charge_id":{"type":["string","null"],"description":"Charge/transaction ID from the processor"},"status":{"type":["string","null"],"description":"Payment status (e.g. 'succeeded', 'pending')"},"amount":{"type":["string","null"],"description":"Amount paid"},"currency":{"type":"string","description":"Settlement currency (ISO 4217)"},"paid_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when payment was completed"}}},"escrow":{"oneOf":[{"$ref":"#/components/schemas/Escrow"},{"type":"null"}],"description":"Escrow details if this deal uses escrow payment"},"template":{"type":"object","description":"Deal template this deal was created from, if any","properties":{"template_id":{"type":["string","null"],"description":"Template ID"},"template_version":{"type":["integer","null"],"description":"Template version used"}}},"metadata":{"type":"object","description":"Arbitrary metadata key-value pairs"},"outcome":{"type":["object","null"],"description":"Deal outcome data (reason for closure, etc.)","properties":{"reason":{"type":"string","description":"Outcome reason code","enum":["price","competitor","timing","budget","fit","no_response","champion_left","terms","other"]},"notes":{"type":["string","null"],"description":"Free-text notes about the outcome"},"competitor_name":{"type":["string","null"],"description":"Competitor name (only set when reason is competitor)"},"recorded_at":{"type":"string","format":"date-time","description":"Timestamp when the outcome was recorded"},"recorded_by":{"type":["string","null"],"description":"User or API key ID that recorded the outcome"}},"required":["reason","recorded_at"]},"deal_score":{"oneOf":[{"type":"object","properties":{"score":{"type":["integer","null"],"minimum":0,"maximum":100,"description":"Overall deal health score (0-100), or null if insufficient data"},"factors":{"type":"object","additionalProperties":true,"description":"Scoring factor details keyed by factor name"},"win_probability":{"type":["number","null"],"format":"double","minimum":0,"maximum":1,"description":"Estimated probability of deal closing (0.0-1.0), or null if insufficient data"},"recommendation":{"type":["string","null"],"description":"AI-generated recommendation"},"explanation":{"type":"string","description":"Human-readable scoring explanation or reason for missing score"}},"required":["score","factors","win_probability","explanation"]},{"type":"null"}],"description":"AI-generated deal intelligence scoring"},"is_signed":{"type":"boolean","description":"Whether the deal has been cryptographically signed"},"signed_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the deal was signed"},"signature_valid":{"type":["boolean","null"],"description":"Whether the cryptographic signature is valid. Null if the deal has no signature."},"deal_hash":{"type":["string","null"],"description":"Cryptographic hash of the deal for tamper detection"},"verification_url":{"type":["string","null"],"format":"uri","description":"Public URL to verify the deal's authenticity"},"subscription":{"type":["object","null"],"description":"Subscription fields for recurring deals. Null for one-time deals.","properties":{"deal_type":{"type":"string","enum":["recurring"]},"billing_cycle":{"type":["string","null"],"description":"Billing interval (e.g. 'monthly', 'annual')"},"subscription_status":{"type":["string","null"],"description":"Current subscription status"},"next_billing_date":{"type":["string","null"],"format":"date-time"},"billing_period_start":{"type":["string","null"],"format":"date-time"},"billing_period_end":{"type":["string","null"],"format":"date-time"},"retry_count":{"type":"integer","description":"Number of billing retry attempts"},"renewal_count":{"type":"integer","description":"Number of successful renewals"},"parent_deal_id":{"type":["string","null"],"description":"Parent deal ID for renewal deals"}}},"deal_type":{"type":"string","enum":["one_time","recurring"],"default":"one_time","description":"Deal type: one_time for a single purchase, recurring for a subscription"},"billing_cycle":{"type":["string","null"],"enum":["monthly","quarterly","annual",null],"description":"Billing cycle for recurring deals. Null for one_time deals."},"tax_rate":{"type":["number","null"],"description":"Tax rate as a decimal (e.g. 0.10 = 10%). Also available nested under pricing.tax_rate."},"synced_from_offline":{"type":"boolean","description":"Whether this deal was created offline and synced later"},"created_offline_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the deal was created offline on the device"},"offline_device_id":{"type":["string","null"],"description":"Unique identifier of the device that created this deal offline"},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp (ISO 8601)"},"updated_at":{"type":["string","null"],"format":"date-time","description":"Last update timestamp (ISO 8601)"},"completed_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the deal was completed or closed"},"proration":{"type":["object","null"],"description":"Proration details included when a subscription is cancelled, changed, or has its billing cycle modified. Only present on POST /subscriptions responses for cancel, change, and change-cycle actions.","properties":{"prorated_amount":{"type":"number","description":"The prorated credit amount issued to the customer (cancel action)"},"proration_amount":{"type":"number","description":"The net proration adjustment amount (change and change-cycle actions)"},"remaining_days":{"type":"integer","description":"Number of days remaining in the current billing cycle"},"cycle_days":{"type":"integer","description":"Total number of days in the billing cycle"},"cycle_amount":{"type":"number","description":"The full cycle charge amount before proration (cancel action)"},"proration_factor":{"type":"number","description":"Fraction of the cycle remaining (remaining_days / cycle_days)"},"cycle_start":{"type":["string","null"],"format":"date","description":"Start date of the current billing cycle (cancel action)"},"cycle_end":{"type":["string","null"],"format":"date","description":"End date of the current billing cycle (cancel action)"},"credit_note_id":{"type":["string","null"],"description":"ID of the credit note issued for the proration (cancel action)"},"refund_id":{"type":["string","null"],"description":"payment refund ID if a refund was issued, null if a credit note was used instead (cancel action)"},"refund_status":{"type":["string","null"],"description":"Status of the proration credit: refunded or credit_note (cancel action)"},"currency":{"type":"string","description":"ISO 4217 currency code for the proration amounts (cancel action)"},"old_total":{"type":"number","description":"Previous subscription total before the change (change and change-cycle actions)"},"new_total":{"type":"number","description":"New subscription total after the change (change and change-cycle actions)"},"old_cycle":{"type":"string","description":"Previous billing cycle (change-cycle action)"},"new_cycle":{"type":"string","description":"New billing cycle (change-cycle action)"},"credit_amount":{"type":"number","description":"Credit amount applied when switching billing cycles (change-cycle action)"}}}},"required":["deal_id","version","status","currency","created_at"]},"DealListItem":{"type":"object","description":"Minimal deal object returned in list (GET /deals without a specific ID) responses. Includes flat customer fields, a formatted total, and signature status. Full pricing breakdown (subtotal, discount, tax, balance_due), deal_type, billing_cycle, and title are only available on the single-deal GET response.","properties":{"deal_id":{"type":"string","description":"Unique deal identifier","examples":["deal_a1b2c3d4e5"]},"version":{"type":"integer","description":"Optimistic locking version","minimum":1},"status":{"type":"string","enum":["draft","in_progress","pending_signature","awaiting_signatures","pending_payment","partially_accepted","closed","cancelled","expired"],"description":"Current deal status"},"customer_id":{"type":["string","null"],"description":"Associated customer ID. Null for deals created before customer info is collected (e.g. widget negotiation flow)."},"customer_name":{"type":["string","null"],"description":"Customer display name (flat field for list display)"},"customer_email":{"type":["string","null"],"format":"email","description":"Customer email address (flat field for list display)"},"customer_company":{"type":["string","null"],"description":"Customer company name (flat field for list display)"},"customer":{"type":"object","description":"Embedded customer summary (name, email, phone, company)","properties":{"name":{"type":["string","null"]},"email":{"type":["string","null"],"format":"email"},"phone":{"type":["string","null"]},"company":{"type":["string","null"]}}},"total":{"type":["string","null"],"description":"Total amount (raw decimal string)"},"total_formatted":{"type":"string","description":"Total amount formatted in the settlement currency (e.g. 'A$1,234.56')","examples":["A$1,234.56"]},"currency":{"type":"string","description":"ISO 4217 currency code","examples":["AUD"]},"presentation_currency":{"type":"string","description":"Currency displayed to the buyer (ISO 4217)","examples":["JPY"]},"settlement_currency":{"type":"string","description":"Currency the seller receives settlement in (ISO 4217)","examples":["AUD"]},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp (ISO 8601)"},"updated_at":{"type":["string","null"],"format":"date-time","description":"Last modification timestamp (ISO 8601); falls back to created_at if never updated"},"completed_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the deal was completed or closed"},"is_signed":{"type":"boolean","description":"Whether this deal has been signed"},"signature_status":{"type":"string","enum":["signed","unsigned"],"description":"Signature status of the deal"}},"required":["deal_id","version","status","currency","created_at"]},"MoneyAmount":{"type":"object","description":"A monetary amount expressed as a raw decimal string, its currency, and a locale-formatted string","properties":{"amount":{"type":"string","description":"Raw decimal amount string as stored in the database","examples":["1234.56"]},"currency":{"type":"string","description":"ISO 4217 currency code","examples":["AUD"]},"formatted":{"type":"string","description":"Human-readable formatted amount","examples":["A$1,234.56"]}},"required":["amount","currency","formatted"]},"CustomerSummary":{"type":"object","description":"Customer summary embedded in deal responses","properties":{"customer_id":{"type":"string"},"name":{"type":"string"},"email":{"type":"string","format":"email"},"phone":{"type":["string","null"]},"address":{"type":["string","null"]},"company":{"type":["string","null"]},"city":{"type":["string","null"]},"state":{"type":["string","null"]},"zip":{"type":["string","null"]},"country":{"type":["string","null"]}}},"LineItem":{"type":"object","properties":{"item_id":{"type":"string","description":"Unique line item identifier","examples":["item_a1b2"]},"product_id":{"type":["string","null"],"description":"Product ID if linked to a product"},"name":{"type":"string","description":"Item name"},"unit_price":{"type":"number","format":"double","description":"Price per unit"},"quantity":{"type":"integer","description":"Quantity"},"subtotal":{"type":"number","format":"double","description":"Line subtotal (unit_price * quantity)"},"price_type":{"type":"string","enum":["once_off","recurring","percentage","metered"],"description":"Pricing model for this line item","default":"once_off"},"billing_cycle":{"type":["string","null"],"enum":["monthly","quarterly","annual",null],"description":"Billing cycle when price_type is recurring"},"deal_id":{"type":"string","description":"Deal this line item belongs to"},"description":{"type":["string","null"],"description":"Item description"},"configuration":{"type":["object","null"],"description":"Product configuration selections"},"sort_order":{"type":"integer","description":"Display order"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}},"Discount":{"type":"object","properties":{"deal_id":{"type":"string","description":"Parent deal ID"},"type":{"type":"string","enum":["percentage","fixed"],"description":"Discount type"},"code":{"type":["string","null"],"description":"Promo or discount code"},"description":{"type":["string","null"],"description":"Human-readable description"},"value":{"type":"number","format":"double","description":"Raw discount input value (e.g. 10 for 10%)"},"amount":{"type":"number","format":"double","description":"Calculated discount amount in deal currency"},"created_at":{"type":"string","format":"date-time","description":"When the discount was applied"}}},"Customer":{"type":"object","properties":{"id":{"type":"integer","description":"Database ID"},"customer_id":{"type":"string","description":"Unique customer identifier","examples":["cust_a1b2c3d4e5"]},"version":{"type":"integer","description":"Optimistic locking version. Incremented atomically on each update.","minimum":1},"name":{"type":["string","null"],"description":"Customer name"},"email":{"type":["string","null"],"format":"email","description":"Email address"},"phone":{"type":["string","null"],"description":"Phone number in E.164 format"},"address":{"type":["string","null"],"description":"Street address"},"company":{"type":["string","null"],"description":"Company name"},"city":{"type":["string","null"],"description":"City"},"state":{"type":["string","null"],"description":"State or province"},"zip":{"type":["string","null"],"description":"Postal code"},"country":{"type":["string","null"],"description":"ISO country code"},"notes":{"type":["string","null"],"description":"Free-form notes"},"status":{"type":"string","enum":["active","inactive","archived"],"description":"Customer status"},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"},"deals":{"type":"array","description":"Deals linked to this customer. Included by default in single-customer responses.","items":{"type":"object","properties":{"deal_id":{"type":"string"},"status":{"type":"string"},"total":{"type":"number"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}}},"contracts":{"type":"array","description":"Contracts linked to this customer. Included by default in single-customer responses.","items":{"type":"object","properties":{"contract_id":{"type":"integer"},"title":{"type":"string"},"status":{"type":"string"},"value":{"type":"number"},"currency":{"type":"string"},"start_date":{"type":"string","format":"date"},"end_date":{"type":"string","format":"date"},"created_at":{"type":"string","format":"date-time"}}}},"communications":{"type":"array","description":"Communication log entries (email, SMS, voice) for this customer. Included by default in single-customer responses.","items":{"type":"object","properties":{"log_id":{"type":"string"},"type":{"type":"string","enum":["sms","voice","email"]},"direction":{"type":"string","enum":["outbound","inbound"]},"status":{"type":"string"},"subject":{"type":["string","null"]},"created_at":{"type":"string","format":"date-time"}}}},"activity_log":{"type":"array","description":"Recent activity log entries for this customer. Included by default in single-resource responses, absent in list responses.","items":{"type":"object","properties":{"log_id":{"type":"string","description":"Unique audit log entry ID"},"action":{"type":"string","description":"Action performed (e.g. created, updated, signed)"},"actor_type":{"type":"string","description":"Type of actor (e.g. user, api_key, system)"},"actor_id":{"type":["string","null"],"description":"Identifier of the actor"},"changes":{"type":["object","null"],"description":"JSON object describing field changes"},"created_at":{"type":"string","format":"date-time","description":"Timestamp of the audit event"}}}}},"required":["customer_id","status","created_at"]},"CustomerListItem":{"type":"object","description":"Customer object returned in list (GET /customers without a specific ID), POST /customers 201, and PATCH /customers 200 responses. Contains only the 16 flat fields returned by mapCustomerRecord(). Excludes nested sub-resources (deals, contracts, communications, activity_log) which are only present in single-customer GET responses.","properties":{"id":{"type":"integer","description":"Database ID"},"customer_id":{"type":"string","description":"Unique customer identifier","examples":["cust_a1b2c3d4e5"]},"version":{"type":"integer","description":"Optimistic locking version. Incremented atomically on each update.","minimum":1},"name":{"type":["string","null"],"description":"Customer name"},"email":{"type":["string","null"],"format":"email","description":"Email address"},"phone":{"type":["string","null"],"description":"Phone number in E.164 format"},"address":{"type":["string","null"],"description":"Street address"},"company":{"type":["string","null"],"description":"Company name"},"city":{"type":["string","null"],"description":"City"},"state":{"type":["string","null"],"description":"State or province"},"zip":{"type":["string","null"],"description":"Postal code"},"country":{"type":["string","null"],"description":"ISO country code"},"notes":{"type":["string","null"],"description":"Free-form notes"},"status":{"type":"string","enum":["active","inactive","archived"],"description":"Customer status"},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"}},"required":["customer_id","status","created_at"]},"PublishableCustomerReference":{"type":"object","description":"Minimal customer reference returned to publishable widget keys during checkout find-or-create. Excludes decrypted PII and internal CRM fields.","properties":{"id":{"type":"integer","description":"Database ID"},"customer_id":{"type":"string","description":"Unique customer identifier","examples":["cust_a1b2c3d4e5"]}},"required":["customer_id"]},"Product":{"type":"object","description":"Full product object returned by GET /products/{id} (single-product) responses. Extends ProductBase with nested collection resources: deals, activity_log, and inventory_movements. POST and PATCH responses use ProductBase (no nested collections). List responses use ProductListItem.","properties":{"id":{"type":"integer","description":"Database ID"},"product_id":{"type":"string","description":"Unique product identifier","examples":["prod_a1b2c3d4e5"]},"version":{"type":"integer","description":"Optimistic locking version. Incremented atomically on each update.","minimum":1},"family_id":{"type":["string","null"],"description":"Product family ID this product belongs to, or null"},"family":{"type":["object","null"],"description":"Resolved product family object, or null if no family is assigned","properties":{"family_id":{"type":"string","description":"Family identifier"},"name":{"type":"string","description":"Family name"}}},"name":{"type":"string","description":"Product name"},"description":{"type":["string","null"],"description":"Product description"},"learn_more_url":{"type":["string","null"],"format":"uri","maxLength":2048,"description":"URL shown as a 'Learn more' link in the widget detail panel"},"features":{"type":["array","null"],"items":{"type":"string"},"description":"Short selling-point bullet strings displayed on the product card and detail panel"},"sku":{"type":["string","null"],"description":"Stock keeping unit"},"price":{"type":"number","format":"double","description":"Selling price"},"base_price":{"type":"number","format":"double","description":"Base price before negotiation adjustments; falls back to price if not separately set"},"price_type":{"type":"string","enum":["once_off","recurring","percentage","metered"],"description":"Pricing model","default":"once_off"},"billing_cycle":{"type":["string","null"],"enum":["monthly","quarterly","annual",null],"description":"Billing cycle when price_type is recurring"},"cost":{"type":"number","format":"double","description":"Cost price"},"type":{"type":"string","description":"Product type (e.g. product, service)"},"unit":{"type":"string","description":"Unit of measure (e.g. unit, hour)"},"tax_rate":{"type":"number","format":"double","description":"Tax rate as decimal"},"pricing_model":{"type":"string","enum":["fixed","tiered","volume","usage"],"description":"Pricing model strategy","default":"fixed"},"category":{"type":["string","null"],"description":"Product category"},"status":{"type":"string","enum":["active","inactive","archived"],"description":"Product status"},"agent_discoverable":{"type":"boolean","description":"Whether this product is discoverable and purchasable by AI agents"},"stock_quantity":{"type":"integer","description":"Quantity on hand"},"track_inventory":{"type":"boolean","description":"Whether inventory tracking is enabled for this product"},"low_stock_threshold":{"type":["integer","null"],"description":"Stock level at which low-stock alerts are triggered, or null if not set"},"configuration_schema":{"type":["object","null"],"description":"Product configuration schema for widget rendering, merged with linked option groups. Null if not configured."},"metadata":{"type":["object","null"],"description":"Arbitrary key-value metadata (only in single-product response). Null if not set."},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"},"requires_booking":{"type":"boolean","description":"Whether this product requires a booking to purchase"},"session_duration":{"type":["integer","null"],"description":"Session length in minutes","minimum":5,"maximum":480},"buffer_time":{"type":["integer","null"],"description":"Buffer time between sessions in minutes","minimum":0,"maximum":120},"max_advance_days":{"type":"integer","description":"Maximum days in advance a booking can be made","minimum":1,"maximum":365,"default":90},"min_advance_hours":{"type":"integer","description":"Minimum hours lead time required for a booking","minimum":0,"maximum":168,"default":24},"allow_staff_selection":{"type":"boolean","description":"Whether customers can choose their preferred staff member","default":true},"deals":{"type":"array","items":{"type":"object","description":"Summary of a deal that includes this product, including line-item-level fields for this product.","properties":{"deal_id":{"type":"string"},"status":{"type":"string"},"total":{"type":"number"},"created_at":{"type":"string","format":"date-time"},"quantity":{"type":"number"},"unit_price":{"type":"number"},"subtotal":{"type":"number"},"customer_id":{"type":"string"},"customer_name":{"type":["string","null"]}}},"description":"Related deals for this product. Included by default in single-resource responses, absent in list responses."},"activity_log":{"type":"array","description":"Recent activity log entries for this product. Included by default in single-resource responses, absent in list responses.","items":{"type":"object","properties":{"log_id":{"type":"string","description":"Unique audit log entry ID"},"action":{"type":"string","description":"Action performed (e.g. created, updated, signed)"},"actor_type":{"type":"string","description":"Type of actor (e.g. user, api_key, system)"},"actor_id":{"type":["string","null"],"description":"Identifier of the actor"},"changes":{"type":["object","null"],"description":"JSON object describing field changes"},"created_at":{"type":"string","format":"date-time","description":"Timestamp of the audit event"}}}},"inventory_movements":{"type":"array","items":{"type":"object"},"description":"Recent inventory movements for this product. Included by default in single-resource responses for track_inventory products, absent otherwise."}},"required":["name","price","status"]},"ProductBase":{"type":"object","description":"Product object returned by POST /products (create) and PATCH /products/{id} (update) responses. Contains all scalar product fields plus the resolved family object. Nested collection resources (deals, activity_log, inventory_movements) are only included in GET single-product responses — see the Product schema.","properties":{"id":{"type":"integer","description":"Database ID"},"product_id":{"type":"string","description":"Unique product identifier","examples":["prod_a1b2c3d4e5"]},"version":{"type":"integer","description":"Optimistic locking version. Incremented atomically on each update.","minimum":1},"family_id":{"type":["string","null"],"description":"Product family ID this product belongs to, or null"},"family":{"type":["object","null"],"description":"Resolved product family object, or null if no family is assigned","properties":{"family_id":{"type":"string","description":"Family identifier"},"name":{"type":"string","description":"Family name"}}},"name":{"type":"string","description":"Product name"},"description":{"type":["string","null"],"description":"Product description"},"learn_more_url":{"type":["string","null"],"format":"uri","maxLength":2048,"description":"URL shown as a 'Learn more' link in the widget detail panel"},"features":{"type":["array","null"],"items":{"type":"string"},"description":"Short selling-point bullet strings displayed on the product card and detail panel"},"sku":{"type":["string","null"],"description":"Stock keeping unit"},"price":{"type":"number","format":"double","description":"Selling price"},"base_price":{"type":"number","format":"double","description":"Base price before negotiation adjustments; falls back to price if not separately set"},"price_type":{"type":"string","enum":["once_off","recurring","percentage","metered"],"description":"Pricing model","default":"once_off"},"billing_cycle":{"type":["string","null"],"enum":["monthly","quarterly","annual",null],"description":"Billing cycle when price_type is recurring"},"cost":{"type":"number","format":"double","description":"Cost price"},"type":{"type":"string","description":"Product type (e.g. product, service)"},"unit":{"type":"string","description":"Unit of measure (e.g. unit, hour)"},"tax_rate":{"type":"number","format":"double","description":"Tax rate as decimal"},"pricing_model":{"type":"string","enum":["fixed","tiered","volume","usage"],"description":"Pricing model strategy","default":"fixed"},"category":{"type":["string","null"],"description":"Product category"},"status":{"type":"string","enum":["active","inactive","archived"],"description":"Product status"},"agent_discoverable":{"type":"boolean","description":"Whether this product is discoverable and purchasable by AI agents"},"stock_quantity":{"type":"integer","description":"Quantity on hand"},"track_inventory":{"type":"boolean","description":"Whether inventory tracking is enabled for this product"},"low_stock_threshold":{"type":["integer","null"],"description":"Stock level at which low-stock alerts are triggered, or null if not set"},"requires_booking":{"type":"boolean","description":"Whether this product requires a booking to purchase"},"session_duration":{"type":["integer","null"],"description":"Session length in minutes","minimum":5,"maximum":480},"buffer_time":{"type":["integer","null"],"description":"Buffer time between sessions in minutes","minimum":0,"maximum":120},"max_advance_days":{"type":"integer","description":"Maximum days in advance a booking can be made","minimum":1,"maximum":365,"default":90},"min_advance_hours":{"type":"integer","description":"Minimum hours lead time required for a booking","minimum":0,"maximum":168,"default":24},"allow_staff_selection":{"type":"boolean","description":"Whether customers can choose their preferred staff member","default":true},"configuration_schema":{"type":["object","null"],"description":"Product configuration schema for widget rendering, merged with linked option groups. Null if not configured."},"metadata":{"type":["object","null"],"description":"Arbitrary key-value metadata. Null if not set."},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"}},"required":["name","price","status"]},"ProductListItem":{"type":"object","description":"Product object returned in list (GET /products without a specific ID) responses. Excludes cost, metadata, and the full family object; includes family_name string instead.","properties":{"id":{"type":"integer","description":"Database ID"},"product_id":{"type":"string","description":"Unique product identifier","examples":["prod_a1b2c3d4e5"]},"family_id":{"type":["string","null"],"description":"Product family ID this product belongs to, or null"},"family_name":{"type":["string","null"],"description":"Product family name (flat string, resolved from family_id), or null"},"name":{"type":"string","description":"Product name"},"description":{"type":["string","null"],"description":"Product description"},"learn_more_url":{"type":["string","null"],"format":"uri","maxLength":2048,"description":"URL shown as a 'Learn more' link in the widget detail panel"},"features":{"type":["array","null"],"items":{"type":"string"},"description":"Short selling-point bullet strings displayed on the product card and detail panel"},"sku":{"type":["string","null"],"description":"Stock keeping unit"},"price":{"type":"number","format":"double","description":"Selling price"},"base_price":{"type":"number","format":"double","description":"Base price before negotiation adjustments; falls back to price if not separately set"},"price_type":{"type":"string","enum":["once_off","recurring","percentage","metered"],"description":"Pricing model","default":"once_off"},"billing_cycle":{"type":["string","null"],"enum":["monthly","quarterly","annual",null],"description":"Billing cycle when price_type is recurring"},"type":{"type":"string","description":"Product type (e.g. product, service)"},"unit":{"type":"string","description":"Unit of measure (e.g. unit, hour)"},"tax_rate":{"type":"number","format":"double","description":"Tax rate as decimal"},"pricing_model":{"type":"string","enum":["fixed","tiered","volume","usage"],"description":"Pricing model strategy","default":"fixed"},"category":{"type":["string","null"],"description":"Product category"},"status":{"type":"string","enum":["active","inactive","archived"],"description":"Product status"},"agent_discoverable":{"type":"boolean","description":"Whether this product is discoverable and purchasable by AI agents"},"stock_quantity":{"type":"integer","description":"Quantity on hand"},"track_inventory":{"type":"boolean","description":"Whether inventory tracking is enabled for this product"},"low_stock_threshold":{"type":["integer","null"],"description":"Stock level at which low-stock alerts are triggered, or null if not set"},"configuration_schema":{"type":["object","null"],"description":"Product configuration schema for widget rendering, merged with linked option groups. Null if not configured."},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"}},"required":["name","price","status"]},"Contract":{"type":"object","properties":{"contract_id":{"type":"integer","description":"Contract ID"},"version":{"type":"integer","description":"Optimistic locking version. Incremented atomically on each update.","minimum":1},"customer_id":{"type":"string","description":"Associated customer ID"},"title":{"type":"string","description":"Contract title"},"description":{"type":["string","null"],"description":"Contract description"},"contract_number":{"type":"string","description":"Unique contract number"},"status":{"type":"string","enum":["draft","signed","pending","active","terminated","expired"],"description":"Current contract status"},"value":{"type":"number","format":"double","description":"Contract value"},"currency":{"type":"string","description":"ISO 4217 currency code"},"start_date":{"type":"string","format":"date","description":"Contract start date (YYYY-MM-DD)"},"end_date":{"type":"string","format":"date","description":"Contract end date (YYYY-MM-DD)"},"signed_date":{"type":["string","null"],"format":"date","description":"Date the contract was signed"},"renewal_type":{"type":"string","enum":["manual","auto","none"],"description":"Renewal type"},"payment_terms":{"type":["string","null"],"description":"Payment terms description"},"notes":{"type":["string","null"],"description":"Additional notes"},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"},"customer":{"type":["object","null"],"description":"Resolved customer details. Always included in single-contract responses.","properties":{"customer_id":{"type":"string","description":"Customer identifier"},"name":{"type":["string","null"],"description":"Customer display name (decrypted PII or company name)"},"email":{"type":["string","null"],"format":"email","description":"Customer email address (decrypted PII)"},"company":{"type":["string","null"],"description":"Company name"}}},"activity_log":{"type":"array","description":"Audit log entries for this contract. Included by default in single-contract responses; omit via field selection.","items":{"type":"object","properties":{"log_id":{"type":"string","description":"Unique audit log entry ID"},"action":{"type":"string","description":"Action performed (e.g. created, updated, signed)"},"actor_type":{"type":"string","description":"Type of actor (e.g. user, api_key, system)"},"actor_id":{"type":["string","null"],"description":"Identifier of the actor"},"changes":{"type":["object","null"],"description":"JSON object describing field changes"},"created_at":{"type":"string","format":"date-time","description":"Timestamp of the audit event"}}}},"renewal_terms":{"type":["object","null"],"description":"Structured renewal terms for this contract","additionalProperties":true},"renewal_count":{"type":"integer","description":"Number of times this contract has been renewed","minimum":0},"renewal_opted_out":{"type":"boolean","description":"Whether the customer has opted out of auto-renewal"},"parent_contract_id":{"type":["string","null"],"description":"ID of the parent contract if this is a renewal"},"signature":{"type":["object","null"],"description":"Cryptographic signature details. Included when the contract has a cryptographic signature.","properties":{"contract_hash":{"type":"string","description":"Hash of the contract content at time of signing"},"signer_type":{"type":["string","null"],"description":"Type of signer (e.g. customer, agent)"},"signer_id":{"type":["string","null"],"description":"Identifier of the signer"},"signature_method":{"type":["string","null"],"description":"Signature method used (e.g. ed25519)"},"signature_hash":{"type":["string","null"],"description":"Cryptographic signature hash"}}}},"required":["contract_id","customer_id","title","status","value","start_date","end_date"]},"ContractListItem":{"type":"object","description":"Contract object returned in list (GET /contracts without a specific ID) responses. Excludes nested customer object and activity_log array; includes customer_id for reference lookup.","properties":{"contract_id":{"type":"integer","description":"Contract ID"},"version":{"type":"integer","description":"Optimistic locking version. Incremented atomically on each update.","minimum":1},"customer_id":{"type":"string","description":"Associated customer ID"},"title":{"type":"string","description":"Contract title"},"description":{"type":["string","null"],"description":"Contract description"},"contract_number":{"type":"string","description":"Unique contract number"},"status":{"type":"string","enum":["draft","signed","pending","active","terminated","expired"],"description":"Current contract status"},"value":{"type":"number","format":"double","description":"Contract value"},"currency":{"type":"string","description":"ISO 4217 currency code"},"start_date":{"type":"string","format":"date","description":"Contract start date (YYYY-MM-DD)"},"end_date":{"type":"string","format":"date","description":"Contract end date (YYYY-MM-DD)"},"signed_date":{"type":["string","null"],"format":"date","description":"Date the contract was signed"},"renewal_type":{"type":"string","enum":["manual","auto","none"],"description":"Renewal type"},"payment_terms":{"type":["string","null"],"description":"Payment terms description"},"notes":{"type":["string","null"],"description":"Additional notes"},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"Last update timestamp"},"renewal_terms":{"type":["object","null"],"description":"Structured renewal terms for this contract","additionalProperties":true},"renewal_count":{"type":"integer","description":"Number of times this contract has been renewed","minimum":0},"renewal_opted_out":{"type":"boolean","description":"Whether the customer has opted out of auto-renewal"},"parent_contract_id":{"type":["string","null"],"description":"ID of the parent contract if this is a renewal"},"signature":{"type":["object","null"],"description":"Cryptographic signature details. Included when the contract has a cryptographic signature.","properties":{"contract_hash":{"type":"string","description":"Hash of the contract content at time of signing"},"signer_type":{"type":["string","null"],"description":"Type of signer (e.g. customer, agent)"},"signer_id":{"type":["string","null"],"description":"Identifier of the signer"},"signature_method":{"type":["string","null"],"description":"Signature method used (e.g. ed25519)"},"signature_hash":{"type":["string","null"],"description":"Cryptographic signature hash"}}}},"required":["contract_id","customer_id","title","status","value","start_date","end_date"]},"ApiKey":{"type":"object","properties":{"key_id":{"type":"string","description":"Unique key identifier"},"name":{"type":"string","description":"Human-readable key name"},"description":{"type":["string","null"],"description":"Key description"},"key_prefix":{"type":"string","description":"Visible prefix for key identification (e.g. sb_live_au_xxxx)"},"status":{"type":"string","enum":["active","revoked","expired"],"description":"Key status"},"scopes":{"type":"array","items":{"type":"string"},"description":"Authorized scopes"},"rate_limit":{"type":"integer","description":"Requests per minute"},"expires_at":{"type":["string","null"],"format":"date-time","description":"Expiration timestamp"},"last_used_at":{"type":["string","null"],"format":"date-time","description":"Last usage timestamp"},"key_type":{"type":"string","enum":["standard","publishable"],"description":"Key type: standard keys are secret server-side keys; publishable keys are safe to embed in client-side code"},"last_used_ip":{"type":["string","null"],"description":"IP address of last request (only returned by single-key GET, not the list endpoint)"},"last_rotated_at":{"type":["string","null"],"format":"date-time","description":"Timestamp of last key rotation, or null if never rotated"},"total_requests":{"type":"integer","description":"Total number of requests made with this key"},"allowed_origins":{"type":["array","null"],"items":{"type":"string"},"description":"CORS origin allowlist for publishable keys, or null if unrestricted"},"revoked_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the key was revoked, or null if still active (only returned by single-key GET, not the list endpoint)"},"created_at":{"type":"string","format":"date-time","description":"Creation timestamp"}},"required":["key_id","name","key_prefix","key_type","status","scopes","rate_limit","total_requests","created_at"]},"ApiKeyCreated":{"type":"object","description":"Response when creating a new API key. The `api_key` field is the full key value — it is only shown once.","properties":{"key_id":{"type":"string"},"api_key":{"type":"string","description":"Full API key value. Store securely — not shown again."},"key_prefix":{"type":"string"},"name":{"type":"string"},"scopes":{"type":"array","items":{"type":"string"}},"rate_limit":{"type":"integer"},"expires_at":{"type":["string","null"]},"allowed_origins":{"type":["array","null"],"items":{"type":"string"},"description":"Allowed CORS origins for this key. Null if unrestricted."}},"required":["key_id","api_key","key_prefix","name","scopes","rate_limit"]},"ApiKeyRotated":{"type":"object","description":"Response when rotating an API key. The `api_key` field is the new full key value — it is only shown once.","properties":{"key_id":{"type":"string"},"api_key":{"type":"string","description":"New full API key value. Store securely — not shown again."},"key_prefix":{"type":"string"},"last_rotated_at":{"type":"string","format":"date-time","description":"Timestamp when the key was rotated"}},"required":["key_id","api_key","key_prefix","last_rotated_at"]},"ApiKeyStats":{"type":"object","properties":{"key_id":{"type":"string"},"total_requests":{"type":"integer"},"total_success":{"type":"integer"},"total_errors":{"type":"integer"},"requests_by_endpoint":{"type":"object","additionalProperties":{"type":"integer"},"description":"Request counts grouped by endpoint path"},"requests_by_status":{"type":"object","additionalProperties":{"type":"integer"},"description":"Request counts grouped by HTTP status code"},"period":{"type":"object","properties":{"start_date":{"type":"string","format":"date"},"end_date":{"type":"string","format":"date"}},"required":["start_date","end_date"]}},"required":["key_id","total_requests","total_success","total_errors","period"]},"DealCreateRequest":{"type":"object","description":"Request body for creating a new deal","required":["title"],"properties":{"customer_id":{"type":"string","description":"Existing customer ID (optional — omit for widget negotiations or draft deals created before customer info is collected)"},"title":{"type":"string","description":"Deal title","maxLength":255},"description":{"type":"string","description":"Deal description","maxLength":65535},"currency":{"type":"string","description":"ISO 4217 currency code","default":"USD"},"presentation_currency":{"type":"string","description":"Currency displayed to the buyer (ISO 4217). Defaults to currency if not provided."},"settlement_currency":{"type":"string","description":"Currency the seller receives settlement in (ISO 4217). Defaults to currency if not provided."},"status":{"type":"string","enum":["draft","in_progress"],"default":"draft","description":"Initial deal status. Only safe initial statuses are permitted on creation; terminal statuses (closed, cancelled, expired) must be reached via state machine transitions."},"deal_type":{"type":"string","enum":["one_time","recurring"],"description":"Deal type"},"billing_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"Billing cycle. **Required** when deal_type is 'recurring'. Must be one of: monthly, quarterly, annual."},"notes":{"type":"string","description":"Internal notes","maxLength":65535},"metadata":{"type":"object","description":"Optional metadata key-value pairs"},"tax_rate":{"type":"number","minimum":0,"maximum":100,"description":"Tax rate as decimal (e.g. 0.10 for 10%). Values >= 1 are accepted for compatibility and auto-normalized (e.g. 10 -> 0.10); prefer decimal form."},"deposit_required":{"type":"number","minimum":0,"description":"Deposit amount required from the buyer. When set, payment-intent fallback charges this amount instead of the full total."},"template_id":{"type":"string","maxLength":255,"description":"ID of a deal template to create the deal from"}},"if":{"properties":{"deal_type":{"const":"recurring"}},"required":["deal_type"]},"then":{"required":["billing_cycle"]}},"DealAddItemRequest":{"type":"object","description":"Request body for adding a line item to a deal","properties":{"product_id":{"type":"string","description":"Product ID to link"},"name":{"type":"string","description":"Item name"},"unit_price":{"type":"number","format":"double","description":"Price per unit","minimum":0},"quantity":{"type":"integer","description":"Quantity","minimum":1,"default":1},"description":{"type":["string","null"],"description":"Item description"},"configuration":{"type":["object","null"],"description":"CPQ configuration with option selections. Drives the Configure-Price-Quote flow, linking product options to line items.","properties":{"option_ids":{"type":"array","items":{"type":"string"},"description":"Array of selected product option IDs"}}},"price_type":{"type":"string","description":"Billing model for this line item. Defaults to `once_off` if omitted.","enum":["once_off","recurring","metered"]},"billing_cycle":{"type":"string","description":"Billing frequency for recurring or metered line items. Required when `price_type` is `recurring` or `metered`.","enum":["monthly","quarterly","annual"]}},"required":["product_id","name","unit_price"]},"DealUpdateItemRequest":{"type":"object","description":"Request body for updating a line item in a deal (e.g. changing quantity or unit price). Requires item_id query parameter and at least one of quantity or unit_price.","properties":{"quantity":{"type":"integer","description":"New quantity for the line item","minimum":1},"unit_price":{"type":"number","description":"Override unit price for the line item","minimum":0}},"anyOf":[{"required":["quantity"]},{"required":["unit_price"]}]},"DealApplyDiscountRequest":{"type":"object","description":"Request body for applying a discount to a deal","properties":{"type":{"type":"string","enum":["percentage","fixed"],"description":"Discount type"},"value":{"type":"number","format":"double","description":"Discount value","minimum":0},"code":{"type":["string","null"],"description":"Promo or discount code for tracking. Used in activity logging and returned in API responses."},"description":{"type":["string","null"],"description":"Human-readable discount description"}},"required":["type","value"]},"DealSignRequest":{"type":"object","description":"Request body for cryptographically signing a deal. The deal must be in `pending_signature` status. Requires `deals:sign` scope (implied by `deals:write`). The `signature_data` and `signed_at` fields are always server-generated and cannot be set by the client. When `signer_customer_id` is provided, the caller must be authorized: session users must be tenant admins, API keys require the deal to belong to the specified customer, and delegations must include `deals:sign` in allowed_actions.\n\n**ETA Compliance (Human Signers):** `consent_to_sign: true` is required for all human (non-agent) signers. This captures explicit consent under the Electronic Transactions Act 1999 (Cth) s.10. This consent event is recorded as a discrete audit trail entry with timestamp and IP address.\n\n**Agent Signing:** When signing via delegation (API key + X-Delegation-ID header), `consent_to_sign` is not required — authority derives from the delegation chain (agency law). Agent signers must have trust level 2 (Established) or higher.","properties":{"signer_type":{"type":"string","enum":["user","customer","agent","api_key"],"description":"Type of signer"},"signer_id":{"type":"string","description":"Identifier of who is signing (user ID, customer ID, etc.)"},"signer_customer_id":{"type":["string","null"],"description":"Reference to customer record. When provided, authorization is validated: API key auth requires the deal to belong to this customer, delegation auth requires deals:sign in allowed_actions."},"consent_to_sign":{"type":"boolean","description":"Required for human (non-agent) signers. Confirms the signer consents to signing this document electronically under the Electronic Transactions Act 1999 (Cth). A `consent_to_sign_granted` audit event is recorded with IP address, user agent, and timestamp. Not required for agent signers (authority derived from delegation chain)."}}},"DealCreateConfiguredRequest":{"type":"object","description":"Request body for creating a fully configured deal atomically. Combines customer creation/matching, product validation, configuration checking, line item creation, and discount application in a single call. Requires either `deals:write` or `agent:execute` scope. Provide either items (explicit line items) or saved_config_id (load from saved configuration) — at least one is required.","properties":{"saved_config_id":{"type":"string","description":"Saved configuration short code or internal ID. If provided, items, currency, and customer info are inherited from the saved config. Prevents double-conversion — returns 409 if already converted."},"customer":{"type":"object","description":"Customer details. If email matches existing customer, that customer is used. Optional when saved_config_id is provided and the config has customer info.","properties":{"name":{"type":"string","description":"Customer name"},"email":{"type":"string","format":"email","description":"Customer email"},"phone":{"type":"string","description":"Phone number"},"company":{"type":"string","description":"Company name"}},"required":["name","email"]},"customer_id":{"type":"string","description":"Existing customer ID (alternative to customer object)"},"items":{"type":"array","description":"Line items with product configurations","minItems":1,"items":{"type":"object","properties":{"product_id":{"type":"string","description":"Product ID"},"quantity":{"type":"integer","minimum":1,"description":"Quantity (default: 1)"},"unit_price":{"type":"number","description":"Unit price override"},"name":{"type":"string","description":"Line item name override"},"configuration":{"type":"object","description":"Product configuration","properties":{"option_ids":{"type":"array","items":{"type":"string"},"description":"Selected option IDs"}}}},"required":["product_id"]}},"discounts":{"type":"array","description":"Discounts to apply","items":{"type":"object","properties":{"type":{"type":"string","enum":["fixed","percentage"]},"value":{"type":"number","exclusiveMinimum":0},"code":{"type":["string","null"],"description":"Promo or discount code for tracking"},"description":{"type":["string","null"],"description":"Human-readable discount description"}},"required":["type","value"]}},"template_id":{"type":"string","description":"Template ID for defaults"},"currency":{"type":"string","pattern":"^[A-Z]{3}$","description":"ISO 4217 currency"},"notes":{"type":"string","description":"Deal notes"},"metadata":{"type":"object","description":"Custom metadata"},"deal_type":{"type":"string","enum":["one_time","recurring"],"description":"Deal type (default: one_time)"},"billing_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"Billing cycle for recurring deals (required when deal_type is recurring)"},"dry_run":{"type":"boolean","description":"Validate without creating"},"title":{"type":"string","maxLength":255,"description":"Deal title override"},"auto_transition":{"type":"boolean","description":"Automatically transition deal after creation"},"deal_terms":{"type":"object","description":"Structured deal terms (max depth 5, max 32KB)"}},"required":[],"anyOf":[{"required":["items"]},{"required":["saved_config_id"]}]},"DealPartialAcceptRequest":{"type":"object","description":"Request body for partial acceptance of a deal. Removes rejected items, recalculates totals, transitions to 'partially_accepted' status, and fires a deal.partially_accepted webhook. The deal must be in 'in_progress' or 'pending_signature' status.","properties":{"accepted_items":{"type":"array","description":"Item IDs the buyer is keeping. Must contain at least one item.","items":{"type":"string"},"minItems":1},"rejected_items":{"type":"array","description":"Item IDs the buyer is rejecting. These will be removed from the deal and totals recalculated.","items":{"type":"string"}},"create_declined_deal":{"type":"boolean","description":"When true, rejected items are copied to a new cancelled deal for audit/reporting. Defaults to false."}},"required":["accepted_items"],"additionalProperties":false},"DealEscrowRequest":{"type":"object","description":"Request body for creating an escrow hold on a deal. Authorizes a payment intent with `capture_method: manual` — funds are held but not captured until all conditions are fulfilled or the escrow is released.","properties":{"amount":{"type":"number","format":"double","description":"Amount to hold in escrow. Defaults to `deposit_required` if set, otherwise the deal total.","minimum":0},"currency":{"type":"string","description":"ISO 4217 currency code. Defaults to the deal currency."},"conditions":{"type":"array","description":"Conditions that must be fulfilled before funds are released.","items":{"type":"object","properties":{"type":{"type":"string","description":"Condition type identifier (e.g. 'delivery', 'inspection', 'approval')"},"config":{"type":"object","description":"Condition-specific configuration","additionalProperties":true}},"required":["type"]}},"expires_in":{"type":"integer","description":"Seconds until the escrow hold expires. Defaults to 604800 (7 days).","minimum":1}},"required":["conditions"]},"DealReleaseEscrowRequest":{"type":"object","description":"Request body for releasing escrow funds to the seller. Captures the held PaymentIntent. Requires all conditions to be fulfilled or a manual override.","properties":[],"additionalProperties":false},"DealRefundEscrowRequest":{"type":"object","description":"Request body for refunding escrow funds back to the buyer. Cancels the held PaymentIntent and returns funds.","properties":{"reason":{"type":"string","description":"Reason for the refund. Defaults to 'manual'.","enum":["manual","condition_failed","deal_cancelled","fraud","duplicate"]}},"additionalProperties":false},"DealFulfillConditionRequest":{"type":"object","description":"Request body for marking an escrow condition as fulfilled. When all conditions are fulfilled, the escrow is eligible for release.","properties":{"condition_id":{"type":"string","description":"ID of the escrow condition to mark as fulfilled."},"met_by":{"type":["string","null"],"description":"Identifier of who fulfilled this condition (user ID, agent ID, or external reference)."}},"required":["condition_id"],"additionalProperties":false},"DealRevokeCredentialRequest":{"type":"object","description":"Request body for revoking the verifiable credential associated with a deal. Revoked credentials are immediately invalid and the revocation is published to the trust registry.","properties":{"reason":{"type":"string","description":"Reason for revocation. Defaults to 'manual'.","enum":["manual","deal_cancelled","fraud","expired","superseded"]}},"additionalProperties":false},"DealUnsignRequest":{"type":"object","description":"Request body for removing a signature from a deal, reverting it to unsigned state. This is a legally significant reversal — the audit trail records the removal along with the reason. Requires `deals:write` scope.","properties":{"reason":{"type":"string","description":"Reason for removing the signature. Recommended for audit compliance."}},"additionalProperties":false},"DealCancellationRequest":{"type":"object","description":"Optional cancellation metadata for `DELETE /deals` when cancelling a deal. The same fields are also accepted as query parameters for clients that cannot send a DELETE body.","properties":{"reason":{"type":"string","description":"Structured cancellation reason enforced by the server.","enum":["price","competitor","timing","budget","fit","no_response","champion_left","terms","other"]},"notes":{"type":["string","null"],"description":"Free-text notes about why the deal was cancelled."}},"additionalProperties":false},"DealRecordOutcomeRequest":{"type":"object","description":"Request body for recording a deal outcome (win or loss). Outcome data feeds into analytics, forecasting, and AI win-rate suggestions.","properties":{"reason":{"type":"string","description":"Outcome reason code. Use a win/loss reason slug from your configured outcome reasons.","minLength":1},"notes":{"type":["string","null"],"description":"Free-text notes about the outcome for internal reference."},"competitor_name":{"type":["string","null"],"description":"Name of the competitor that won the deal (for loss outcomes). Used in competitive analytics."}},"required":["reason"],"additionalProperties":false},"DealOutcomeResult":{"type":"object","description":"Response returned by the record-outcome action. Contains the deal ID, current status, and the recorded outcome details.","properties":{"deal_id":{"type":"string","description":"ID of the deal for which the outcome was recorded"},"status":{"type":"string","description":"Current deal status (e.g. closed, cancelled, expired)"},"outcome":{"type":"object","description":"The recorded outcome details","properties":{"reason":{"type":"string","description":"Outcome reason code","enum":["price","competitor","timing","budget","fit","no_response","champion_left","terms","other"]},"notes":{"type":["string","null"],"description":"Free-text notes about the outcome"},"competitor_name":{"type":["string","null"],"description":"Competitor name (only set when reason is competitor)"},"recorded_at":{"type":"string","format":"date-time","description":"Timestamp when the outcome was recorded"},"recorded_by":{"type":["string","null"],"description":"User or API key ID that recorded the outcome"}},"required":["reason"]}},"required":["deal_id","status","outcome"]},"DealCredentialRevocationResult":{"type":"object","description":"Response returned by the revoke_credential action. Contains the full credential record with updated revocation details.","properties":{"credential_id":{"type":"string","description":"Unique credential identifier"},"deal_id":{"type":"string","description":"Associated deal ID"},"status":{"type":"string","enum":["active","revoked"],"description":"Credential status — always revoked after this action"},"key_id":{"type":"string","description":"Signing key ID used to issue the credential"},"credential_hash":{"type":"string","description":"SHA-256 hash of the W3C Verifiable Credential payload"},"issued_at":{"type":"string","format":"date-time","description":"When the credential was originally issued"},"revoked_at":{"type":["string","null"],"format":"date-time","description":"When the credential was revoked"},"revocation_reason":{"type":["string","null"],"description":"Reason for revocation (e.g. manual, fraud)"},"credential":{"type":"object","description":"Full W3C Verifiable Credential payload","additionalProperties":true}},"required":["credential_id","deal_id","status"]},"DealSaveAsTemplateRequest":{"type":"object","description":"Request body for saving a deal as a reusable template. The template captures the deal's line items, pricing, terms, and configuration so new deals can be created from it.","properties":{"name":{"type":"string","description":"Name for the new template.","minLength":1,"maxLength":255},"description":{"type":["string","null"],"description":"Optional description of what this template is for."}},"required":["name"],"additionalProperties":false},"DealSetTermsRequest":{"type":"object","description":"Request body for setting structured deal terms. Terms define payment schedules, delivery conditions, obligations, SLAs, and more for machine-readable agent negotiation. Accepts either a {\"terms\": {...}} wrapper object or the DealTerms object directly as the request body.","properties":{"terms":{"$ref":"#/components/schemas/DealTerms"}}},"DealTerms":{"type":"object","description":"Machine-readable structured deal terms. Full JSON Schema available at GET /schema/deal-terms","additionalProperties":false,"properties":{"terms_schema_version":{"type":"string","description":"Schema version for forward compatibility","examples":["1.0"]},"payment_terms":{"type":"object","description":"Payment schedule and conditions","properties":{"type":{"type":"string","enum":["upfront","net_7","net_14","net_30","net_60","net_90","milestone","installment","upon_delivery","custom"]},"due_date":{"type":"string","format":"date-time"},"schedule":{"type":"array","items":{"type":"object","properties":{"label":{"type":"string"},"amount":{"type":"string","pattern":"^[0-9]+(\\.[0-9]{1,4})?$"},"percentage":{"type":"number","minimum":0,"maximum":100},"due_date":{"type":"string","format":"date-time"},"due_on_event":{"type":"string"},"status":{"type":"string","enum":["pending","invoiced","paid","overdue","waived"]}},"required":["label"]}},"late_fee":{"type":"object","properties":{"type":{"type":"string","enum":["percentage","fixed"]},"value":{"type":"string"},"grace_period_days":{"type":"integer","minimum":0}}}}},"delivery":{"type":"object","description":"Delivery method, timeline, and conditions","properties":{"method":{"type":"string","enum":["digital","physical","service","hybrid"]},"deadline":{"type":"string","format":"date-time"},"estimated_days":{"type":"integer","minimum":0},"conditions":{"type":"array","items":{"type":"object","properties":{"description":{"type":"string"},"required":{"type":"boolean"}},"required":["description"]}},"location":{"type":"string"}}},"obligations":{"type":"array","description":"Obligations each party must fulfill","items":{"type":"object","properties":{"party":{"type":"string","enum":["seller","buyer"]},"description":{"type":"string"},"deadline":{"type":"string","format":"date-time"},"status":{"type":"string","enum":["pending","fulfilled","waived","breached"]}},"required":["party","description"]}},"sla":{"type":"array","description":"Service Level Agreements","items":{"type":"object","properties":{"metric":{"type":"string"},"target":{"type":"string"},"measurement_period":{"type":"string"},"penalty":{"type":"object","properties":{"type":{"type":"string","enum":["credit_percentage","credit_fixed","termination_right"]},"value":{"type":"string"}}}},"required":["metric","target"]}},"acceptance":{"type":"object","description":"Acceptance criteria and review process","properties":{"criteria":{"type":"array","items":{"type":"object","properties":{"description":{"type":"string"},"verifiable":{"type":"boolean"}},"required":["description"]}},"review_period_days":{"type":"integer","minimum":0},"auto_accept":{"type":"boolean"}}},"warranty":{"type":"object","description":"Warranty or guarantee terms","properties":{"duration_days":{"type":"integer","minimum":0},"scope":{"type":"string"},"exclusions":{"type":"array","items":{"type":"string"}}}},"termination":{"type":"object","description":"Termination and cancellation conditions","properties":{"notice_period_days":{"type":"integer","minimum":0},"conditions":{"type":"array","items":{"type":"object","properties":{"trigger":{"type":"string"},"penalty":{"type":"string"}},"required":["trigger"]}},"refund_policy":{"type":"string","enum":["full","prorated","none","custom"]}}},"renewal":{"type":"object","description":"Renewal and extension terms","properties":{"type":{"type":"string","enum":["auto","manual","none"]},"period":{"type":"string","description":"ISO 8601 duration (e.g. P1Y, P6M)"},"price_adjustment":{"type":"string","enum":["fixed","cpi","negotiated","percentage"]},"price_adjustment_value":{"type":"string"},"notice_period_days":{"type":"integer","minimum":0}}},"custom_terms":{"type":"array","description":"Additional custom terms not covered by the standard schema","items":{"type":"object","properties":{"key":{"type":"string"},"label":{"type":"string"},"value":{"description":"String, number, or boolean value"}},"required":["key","label","value"]}}}},"DealUpdateRequest":{"type":"object","description":"Request body for updating a deal. To change deal status, use POST /deals?action=transition instead. Note: when the effective deal_type is 'recurring' (either set in this request or already on the existing deal), billing_cycle must also be present.","properties":{"customer_id":{"type":"string"},"title":{"type":"string","maxLength":255},"description":{"type":"string","maxLength":65535},"notes":{"type":"string","maxLength":65535},"deal_type":{"type":"string","enum":["one_time","recurring"],"description":"Deal type. When set to 'recurring', billing_cycle must be provided (either in this request or already set on the existing deal)."},"billing_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"Billing cycle. Required when the effective deal_type is 'recurring' — either because deal_type is set to 'recurring' in this request, or because the existing deal already has deal_type='recurring'."},"currency":{"type":"string"},"tax_rate":{"type":"number","format":"double","description":"Tax rate as decimal (e.g. 0.10 for 10%). Values >= 1 are accepted for compatibility and auto-normalized (e.g. 10 -> 0.10); prefer decimal form.","minimum":0,"maximum":100},"deposit_required":{"type":"number","format":"double","description":"Required deposit amount in the deal currency. Must be >= 0.","minimum":0},"metadata":{"type":"object"}}},"CustomerCreateRequest":{"type":"object","description":"Request body for creating a customer","properties":{"name":{"type":"string","maxLength":255,"description":"Customer name"},"email":{"type":"string","format":"email","description":"Email address (must be unique)"},"phone":{"type":"string","maxLength":50,"description":"Phone number (will be normalized to E.164 format)"},"address":{"type":"string","maxLength":1000},"company":{"type":"string","maxLength":255},"city":{"type":"string","maxLength":255},"state":{"type":"string","maxLength":255},"zip":{"type":"string","maxLength":20},"country":{"type":"string","maxLength":100,"description":"ISO country code"},"notes":{"type":"string","maxLength":65535},"status":{"type":"string","enum":["active","inactive","archived"],"default":"active"}},"required":["name","email"]},"CustomerUpdateRequest":{"type":"object","description":"Request body for updating a customer. All fields optional.","properties":{"name":{"type":"string","maxLength":255},"email":{"type":"string","format":"email"},"phone":{"type":"string","maxLength":50},"address":{"type":"string","maxLength":1000},"company":{"type":"string","maxLength":255},"city":{"type":"string","maxLength":255},"state":{"type":"string","maxLength":255},"zip":{"type":"string","maxLength":20},"country":{"type":"string","maxLength":100},"notes":{"type":"string","maxLength":65535},"status":{"type":"string","enum":["active","inactive","archived"]}}},"ProductCreateRequest":{"type":"object","description":"Request body for creating a product","properties":{"name":{"type":"string","description":"Product name"},"price":{"type":"number","format":"double","description":"Selling price","minimum":0,"maximum":99999999.99},"description":{"type":"string"},"sku":{"type":"string"},"price_type":{"type":"string","enum":["once_off","recurring","percentage","metered"],"default":"once_off"},"billing_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"Billing cycle. **Required** when price_type is 'recurring' or 'metered'. Must be one of: monthly, quarterly, annual."},"cost":{"type":"number","format":"double","default":0,"minimum":0,"maximum":99999999.99},"type":{"type":"string","enum":["product","service","subscription","bundle"],"default":"product"},"unit":{"type":"string","default":"unit"},"tax_rate":{"type":"number","format":"double","description":"Tax rate as decimal (e.g. 0.10 for 10%). Values >= 1 are accepted for compatibility and auto-normalized (e.g. 10 -> 0.10); prefer decimal form.","minimum":0,"maximum":100,"default":0},"category":{"type":"string"},"status":{"type":"string","enum":["active","inactive","archived"],"default":"active"},"stock_quantity":{"type":"integer","default":0},"track_inventory":{"type":"boolean","description":"Whether inventory is tracked for this product"},"low_stock_threshold":{"type":"integer","description":"Stock level at which low stock alerts are triggered","minimum":0},"pricing_model":{"type":"string","enum":["fixed","tiered","volume","usage"],"description":"Pricing model for this product"},"metadata":{"type":"object","description":"Optional metadata key-value pairs"},"configuration_schema":{"type":"object","description":"JSON schema defining configurable options for this product"},"family_id":{"type":"string","description":"Product family ID to associate this product with","maxLength":50},"requires_booking":{"type":"boolean","default":false,"description":"Whether this product requires a booking"},"session_duration":{"type":"integer","description":"Session length in minutes","minimum":5,"maximum":480},"buffer_time":{"type":"integer","description":"Buffer time between sessions in minutes","minimum":0,"maximum":120},"max_advance_days":{"type":"integer","description":"Maximum days in advance a booking can be made","minimum":1,"maximum":365,"default":90},"min_advance_hours":{"type":"integer","description":"Minimum hours lead time required for a booking","minimum":0,"maximum":168,"default":24},"allow_staff_selection":{"type":"boolean","description":"Whether customers can choose their preferred staff member","default":true},"learn_more_url":{"type":"string","maxLength":2048,"description":"URL linking to more information about the product"},"features":{"type":"array","items":{"type":"string"},"description":"List of product features"}},"required":["name","price"],"if":{"properties":{"price_type":{"enum":["recurring","metered"]}},"required":["price_type"]},"then":{"required":["billing_cycle"]}},"ProductUpdateRequest":{"type":"object","description":"Request body for updating a product. All fields optional.","properties":{"name":{"type":"string"},"price":{"type":"number","format":"double","minimum":0},"description":{"type":"string"},"sku":{"type":"string"},"price_type":{"type":"string","enum":["once_off","recurring","percentage","metered"]},"billing_cycle":{"type":"string","enum":["monthly","quarterly","annual"]},"cost":{"type":"number","format":"double"},"type":{"type":"string","enum":["product","service","subscription","bundle"]},"unit":{"type":"string"},"tax_rate":{"type":"number","format":"double","description":"Tax rate as decimal (e.g. 0.10 for 10%). Values >= 1 are accepted for compatibility and auto-normalized (e.g. 10 -> 0.10); prefer decimal form.","minimum":0,"maximum":100},"category":{"type":"string"},"status":{"type":"string","enum":["active","inactive","archived"]},"stock_quantity":{"type":"integer"},"track_inventory":{"type":"boolean"},"low_stock_threshold":{"type":"integer","minimum":0},"pricing_model":{"type":"string","enum":["fixed","tiered","volume","usage"]},"metadata":{"type":"object"},"configuration_schema":{"type":"object"},"family_id":{"type":"string","maxLength":50},"requires_booking":{"type":"boolean","default":false,"description":"Whether this product requires a booking"},"session_duration":{"type":"integer","description":"Session length in minutes","minimum":5,"maximum":480},"buffer_time":{"type":"integer","description":"Buffer time between sessions in minutes","minimum":0,"maximum":120},"max_advance_days":{"type":"integer","description":"Maximum days in advance a booking can be made","minimum":1,"maximum":365,"default":90},"min_advance_hours":{"type":"integer","description":"Minimum hours lead time required for a booking","minimum":0,"maximum":168,"default":24},"allow_staff_selection":{"type":"boolean","description":"Whether customers can choose their preferred staff member","default":true},"learn_more_url":{"type":"string","maxLength":2048,"description":"URL linking to more information about the product"},"features":{"type":"array","items":{"type":"string"},"description":"List of product features"}}},"ContractCreateRequest":{"type":"object","description":"Request body for creating a contract. When `deal_id` is provided, the fields `customer_id`, `title`, `value`, `start_date`, and `end_date` are auto-populated from the deal and become optional.","properties":{"deal_id":{"type":"string","description":"Deal ID to create a contract from. Auto-populates customer_id, title, value, currency, start_date, and end_date from the deal. Any of those fields may still be provided to override the deal-derived values."},"customer_id":{"type":"string","description":"Customer ID. Required unless `deal_id` is provided (auto-populated from deal)."},"title":{"type":"string","description":"Contract title. Required unless `deal_id` is provided (auto-populated from deal)."},"value":{"type":"number","format":"double","description":"Contract value. Required unless `deal_id` is provided (auto-populated from deal total).","minimum":0},"start_date":{"type":"string","format":"date","description":"Start date (YYYY-MM-DD). Required unless `deal_id` is provided (defaults to today)."},"end_date":{"type":"string","format":"date","description":"End date (YYYY-MM-DD, must be after start_date). Required unless `deal_id` is provided (defaults to one year from today)."},"description":{"type":"string"},"contract_number":{"type":"string"},"currency":{"type":"string","default":"USD"},"renewal_type":{"type":"string","enum":["manual","auto","none"],"default":"manual"},"payment_terms":{"type":"string"},"notes":{"type":"string"},"renewal_terms":{"type":"object","description":"Structured renewal terms (JSON)"}},"oneOf":[{"required":["deal_id"],"description":"Create from a deal — auto-populates customer_id, title, value, start_date, end_date."},{"required":["customer_id","title","value","start_date","end_date"],"description":"Create without a deal — all five core fields must be supplied explicitly."}]},"ContractUpdateRequest":{"type":"object","description":"Request body for updating a contract. All fields optional.","properties":{"title":{"type":"string"},"description":{"type":"string"},"value":{"type":"number","format":"double"},"currency":{"type":"string"},"start_date":{"type":"string","format":"date"},"end_date":{"type":"string","format":"date"},"renewal_type":{"type":"string","enum":["manual","auto","none"]},"payment_terms":{"type":"string"},"notes":{"type":"string"},"renewal_terms":{"type":"object","description":"Structured renewal terms (JSON)"},"customer_id":{"type":"string","description":"Reassign the contract to a different customer"},"contract_number":{"type":"string","description":"Update the contract reference number"}}},"ApiKeyCreateRequest":{"type":"object","description":"Request body for creating an API key","properties":{"name":{"type":"string","description":"Human-readable name for the key"},"description":{"type":"string"},"scopes":{"type":"array","items":{"type":"string","enum":["*","*:read","deals:read","deals:write","deals:sign","customers:read","customers:write","products:read","products:write","contracts:read","contracts:write","webhooks:read","webhooks:write","audit:export","agent:*","agent:discover","agent:negotiate","agent:execute","intelligence:read","intelligence:write","billing:read","billing:write","trust:read","trust:write","staff:read","staff:write","team:read","team:write","bookings:read","bookings:write","delegations:read","delegations:write","widgets:read","sandbox:read","sandbox:write","activity:read","activity:write","search:read"]},"default":["*"],"description":"Authorized scopes for the key"},"environment":{"type":"string","enum":["live","test"],"default":"live","description":"Key environment. Live keys use `sb_live_*` prefix, test keys use `sb_test_*`."},"rate_limit":{"type":"integer","default":1000,"description":"Requests per minute"},"expires_at":{"type":"string","format":"date-time","description":"Expiration timestamp (ISO 8601). Omit for no expiration."},"allowed_origins":{"type":"array","items":{"type":"string"},"description":"List of allowed origins for CORS restriction of this API key"}},"required":["name"]},"StructuredDealTerms":{"type":"object","description":"Machine-readable structured deal terms for agent-to-agent commerce","required":["pricing_model","payment_terms"],"properties":{"pricing_model":{"type":"string","enum":["fixed","per_unit","tiered","usage_based","subscription"],"description":"How pricing is calculated"},"payment_terms":{"type":"string","enum":["due_on_receipt","net_15","net_30","net_60","net_90","custom"],"description":"When payment is due"},"payment_schedule":{"type":"object","properties":{"frequency":{"type":"string","enum":["one_time","weekly","monthly","quarterly","annually"]},"installments":{"type":"integer","minimum":1}}},"delivery_timeline":{"type":"object","properties":{"value":{"type":"number","exclusiveMinimum":0},"unit":{"type":"string","enum":["hours","days","weeks","months"]},"description":{"type":"string"}}},"sla":{"type":"object","properties":{"uptime_percentage":{"type":"number","minimum":0,"maximum":100},"response_time_hours":{"type":"number","exclusiveMinimum":0},"resolution_time_hours":{"type":"number","exclusiveMinimum":0},"support_hours":{"type":"string"}}},"cancellation_policy":{"type":"object","properties":{"allowed":{"type":"boolean"},"notice_days":{"type":"integer","minimum":0},"penalty_percentage":{"type":"number","minimum":0,"maximum":100},"refund_policy":{"type":"string"}}},"warranty":{"type":"object","properties":{"included":{"type":"boolean"},"duration_days":{"type":"integer","minimum":0},"description":{"type":"string"}}},"auto_renew":{"type":"boolean","description":"Whether the deal automatically renews"},"custom_terms":{"type":"object","additionalProperties":true,"description":"Custom key-value pairs for domain-specific terms"}}},"Escrow":{"type":"object","description":"Escrow hold created for a deal. Funds are authorized on payment provider (capture_method: manual) but not captured until all release conditions are fulfilled.","properties":{"escrow_id":{"type":"string","description":"Unique escrow identifier (prefix: esc_)"},"deal_id":{"type":"string","description":"Associated deal ID"},"tenant_id":{"type":"string","description":"Tenant that owns this escrow"},"amount":{"type":"string","description":"Amount held in escrow as a decimal string (e.g. \"250.00\")"},"currency":{"type":"string","description":"ISO 4217 currency code"},"status":{"type":"string","enum":["held","released","refunded","expired"],"description":"Current escrow status"},"stripe_payment_intent_id":{"type":"string","description":"payment intent ID for the authorized hold"},"conditions":{"type":"array","description":"Release conditions that must be fulfilled before funds can be captured","items":{"type":"object","properties":{"condition_id":{"type":"string","description":"Unique condition identifier (prefix: cond_)"},"escrow_id":{"type":"string"},"condition_type":{"type":"string","enum":["signature_collected","delivery_confirmed","inspection_period_elapsed","manual_approval","api_callback"]},"condition_config":{"type":["object","null"]},"met_at":{"type":["string","null"],"format":"date-time"},"met_by":{"type":["string","null"]},"created_at":{"type":"string","format":"date-time"}}}},"conditions_summary":{"type":"object","description":"Aggregate counts of fulfilled vs total conditions","properties":{"total":{"type":"integer"},"met":{"type":"integer"},"remaining":{"type":"integer"},"all_met":{"type":"boolean"}}},"authorization":{"type":"object","description":"payment provider authorization window health","properties":{"last_authorized_at":{"type":["string","null"],"format":"date-time"},"auth_expires_at":{"type":["string","null"],"format":"date-time"},"auth_days_remaining":{"type":["number","null"]},"auth_status":{"type":["string","null"],"enum":["ok","warning","critical",null],"description":"Authorization health: ok (>3 days remaining), warning (1-3 days), critical (<1 day)"}}},"released_at":{"type":["string","null"],"format":"date-time"},"refunded_at":{"type":["string","null"],"format":"date-time"},"expires_at":{"type":"string","format":"date-time"},"last_authorized_at":{"type":["string","null"],"format":"date-time"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":["string","null"],"format":"date-time"}},"required":["escrow_id","deal_id","tenant_id","amount","currency","status","conditions","conditions_summary","created_at"]},"DealTemplate":{"type":"object","description":"Reusable deal template for programmatic offer generation","properties":{"template_id":{"type":"string"},"tenant_id":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"template_data":{"type":"object","description":"The full template payload (products, pricing, terms, etc.)"},"is_active":{"type":"boolean"},"version":{"type":"integer"},"usage_count":{"type":"integer","description":"Number of deals created from this template (included in list responses)"},"created_by":{"type":["integer","null"]},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}}},"DealTemplateListResponse":{"type":"object","properties":{"error":{"type":"boolean"},"success":{"type":"boolean"},"data":{"type":"object","properties":{"templates":{"type":"array","items":{"$ref":"#/components/schemas/DealTemplate"}},"pagination":{"type":"object","properties":{"total":{"type":"integer"},"limit":{"type":"integer"},"offset":{"type":"integer"},"count":{"type":"integer"}}}}}},"required":["error","success","data"]},"Webhook":{"type":"object","description":"A registered webhook endpoint","properties":{"webhook_id":{"type":"string","description":"Unique webhook identifier (wh_*)","examples":["wh_a1b2c3d4e5f6g7h8"]},"url":{"type":"string","format":"uri","description":"HTTPS endpoint URL"},"events":{"type":"array","items":{"$ref":"#/components/schemas/WebhookEventType"},"description":"Subscribed event types"},"description":{"type":["string","null"],"description":"Human-readable description"},"status":{"type":"string","enum":["active","paused","failed"],"description":"Current webhook status. 'failed' is set automatically when consecutive delivery failures reach the threshold."},"consecutive_failures":{"type":"integer","description":"Number of consecutive delivery failures"},"total_deliveries":{"type":"integer","description":"Total delivery attempts made"},"total_failures":{"type":"integer","description":"Total failed deliveries"},"last_triggered_at":{"type":["string","null"],"format":"date-time","description":"When the webhook was last triggered"},"last_failure_at":{"type":["string","null"],"format":"date-time","description":"When the last failure occurred"},"last_failure_reason":{"type":["string","null"],"description":"Error message from the last failure"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}},"required":["webhook_id","url","events","status","created_at"]},"WebhookEvent":{"type":"object","description":"A webhook event record with sequence number for cursor-based replay","properties":{"event_id":{"type":"string","description":"Unique event identifier (whe_*)"},"event_sequence":{"type":"integer","format":"int64","description":"Monotonically increasing sequence number per tenant"},"event_type":{"type":"string","description":"Event type (e.g. deal.created)"},"payload":{"type":"object","description":"Full event payload"},"status":{"type":"string","enum":["pending","delivered","partially_delivered","failed"],"description":"Aggregate delivery status"},"created_at":{"type":"string","format":"date-time"}},"required":["event_id","event_sequence","event_type","payload","status","created_at"]},"DeadLetterEntry":{"type":"object","description":"A failed webhook delivery that exhausted all retry attempts","properties":{"delivery_id":{"type":"string","description":"Unique delivery identifier (whd_*)"},"event_id":{"type":["string","null"],"description":"Associated event ID"},"webhook_id":{"type":"string","description":"Target webhook ID"},"webhook_url":{"type":["string","null"],"description":"Webhook endpoint URL"},"webhook_description":{"type":["string","null"]},"event_type":{"type":"string"},"payload":{"type":"object","description":"Original event payload"},"status":{"type":"string","const":"failed"},"attempts":{"type":"integer","description":"Total delivery attempts made"},"max_attempts":{"type":"integer","description":"Maximum attempts allowed"},"response_code":{"type":["integer","null"],"description":"Last HTTP response code"},"response_body":{"type":["string","null"],"description":"Last response body (truncated to 1000 chars)"},"error_message":{"type":["string","null"],"description":"Last error message"},"is_replay":{"type":"boolean","description":"Whether this was a replayed delivery"},"created_at":{"type":"string","format":"date-time"}},"required":["delivery_id","webhook_id","event_type","payload","status","attempts","max_attempts","created_at"]},"Pagination":{"type":"object","description":"Offset-based pagination metadata (returned when no cursor params are provided)","properties":{"total":{"type":"integer","description":"Total number of records available"},"limit":{"type":"integer","description":"Maximum results per page"},"offset":{"type":"integer","description":"Current offset"},"count":{"type":"integer","description":"Number of records in this response"}},"required":["total","limit","offset","count"]},"CursorPagination":{"type":"object","description":"Cursor-based pagination metadata (returned when ?after= or ?before= is provided). Cursors are opaque base64 strings — do not parse or construct them.","properties":{"has_more":{"type":"boolean","description":"Whether there are more records beyond this page"},"next_cursor":{"type":["string","null"],"description":"Opaque cursor to pass as ?after= for the next page. Null when there are no more records."},"prev_cursor":{"type":["string","null"],"description":"Opaque cursor to pass as ?before= to go back to the previous page. Null on the first page."}},"required":["has_more","next_cursor","prev_cursor"]},"ValidationResult":{"type":"object","description":"Data returned when validate_only=true. The request body is valid but no resource was created.","properties":{"valid":{"type":"boolean","const":true,"description":"Always true when validation passes"},"message":{"type":"string","example":"Validation passed"}},"required":["valid","message"]},"ValidationResponse":{"type":"object","description":"Response returned when validate_only=true. The request body was validated without persisting any data.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"$ref":"#/components/schemas/ValidationResult"}},"required":["error","success","data"]},"BatchResult":{"type":"object","description":"Result of a single operation within a batch request","properties":{"index":{"type":"integer","description":"Position of this operation in the original batch request (0-based)"},"status":{"type":"integer","description":"HTTP status code of the sub-operation (e.g. 200, 201, 204)"},"data":{"type":"object","description":"Response data from the sub-operation (varies by operation type)"}},"required":["index","status","data"]},"BatchResponse":{"type":"object","description":"Response envelope for POST /batch","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"results":{"type":"array","description":"Results for each operation in the batch, in order","items":{"$ref":"#/components/schemas/BatchResult"}},"total":{"type":"integer","description":"Total number of operations that completed successfully"}},"required":["results","total"]}},"required":["error","success","data"]},"BatchOperation":{"type":"object","description":"A single operation within a batch request","properties":{"method":{"type":"string","enum":["GET","POST","PATCH","DELETE"],"description":"HTTP method for this operation"},"resource":{"type":"string","enum":["deals","customers","products","contracts"],"description":"Resource type to operate on"},"id":{"type":"string","description":"Resource ID. Required for PATCH and DELETE operations."},"body":{"type":"object","additionalProperties":true,"description":"Request body for the operation. Required for POST and PATCH operations."},"version":{"type":"integer","description":"Resource version for optimistic locking. Optional; recommended for PATCH and DELETE to prevent concurrent modification conflicts."},"action":{"type":"string","description":"Optional action modifier for the operation."}},"required":["method","resource"]},"BatchRequest":{"type":"object","description":"Request body for POST /batch","properties":{"operations":{"type":"array","description":"List of operations to execute atomically. Maximum 25 operations per request.","minItems":1,"maxItems":25,"items":{"$ref":"#/components/schemas/BatchOperation"}}},"required":["operations"]},"WidgetValidateResponse":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"valid":{"type":"boolean","description":"Whether the configuration passes all validation rules (compatibility rules and, when text_values is supplied, text constraints)"},"errors":{"type":"array","items":{"type":"object","properties":{"rule_type":{"type":"string","enum":["requires","excludes","text_constraint","checkbox_group_required","checkbox_group_max","option_schema"],"description":"Type of rule violated. 'text_constraint' errors arise from required/max_length/pattern checks on text options; 'checkbox_group_required' and 'checkbox_group_max' from checkbox-group min/max selection constraints; 'option_schema' from option_ids that are not valid choices for the product; 'requires' and 'excludes' from compatibility rules."},"message":{"type":"string","description":"Human-readable description of the violation"},"rule_id":{"type":"string","description":"ID of the compatibility rule that was violated (present for requires/excludes errors)"},"source_option_id":{"type":"string","description":"ID of the option that triggered the rule (present for requires/excludes errors)"},"target_option_id":{"type":"string","description":"ID of the option referenced by the rule (present for requires/excludes errors)"},"option_id":{"type":"string","description":"Submitted option ID that failed schema validation (present for option_schema errors)"},"key":{"type":"string","description":"Option key that failed validation (present for text_constraint and checkbox-group errors)"},"code":{"type":"string","enum":["required","too_long","pattern_mismatch","min_selections","max_selections","invalid_option"],"description":"Machine-readable constraint code (present for text_constraint, checkbox-group, and option_schema errors)"}},"required":["rule_type","message"]},"description":"Validation error objects (empty when valid)"},"warnings":{"type":"array","items":{"type":"object","properties":{"rule_type":{"type":"string","enum":["requires","excludes","text_constraint"],"description":"Type of compatibility rule"},"message":{"type":"string","description":"Human-readable description of the warning"},"rule_id":{"type":"string","description":"ID of the compatibility rule that triggered the warning"},"source_option_id":{"type":"string","description":"ID of the option that triggered the rule"},"target_option_id":{"type":"string","description":"ID of the option referenced by the rule"}},"required":["rule_type","message"]},"description":"Non-blocking warning objects"},"price_adjustments":{"type":"array","description":"Price adjustments applied by includes_price compatibility rules","items":{"type":"object","properties":{"rule_id":{"type":"string","description":"ID of the compatibility rule that triggered the adjustment"},"option_id":{"type":"string","description":"ID of the option whose price was adjusted"},"adjusted_price":{"type":"number","description":"New price for the option (0 means included at no charge)"},"reason":{"type":"string","description":"Human-readable explanation of the price adjustment"}},"required":["rule_id","option_id","adjusted_price","reason"]}}},"required":["valid","errors","warnings","price_adjustments"]}},"required":["error","success","data"]},"WidgetPaymentPreviewCartItem":{"type":"object","properties":{"product_id":{"type":"string"},"option_ids":{"type":"array","items":{"type":"string","minLength":1}},"option_selections":{"type":"object","additionalProperties":{"oneOf":[{"type":"string","minLength":1},{"type":"array","items":{"type":"string","minLength":1}}]}},"quantity":{"type":"integer","minimum":1,"default":1}},"required":["product_id"]},"WidgetPaymentPreviewResponse":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"items":{"type":"array","description":"Per-item pricing breakdown for the previewed cart","items":{"$ref":"#/components/schemas/PricingSimulationItem"}},"subtotal":{"type":"number","description":"Pre-discount, pre-tax subtotal"},"discount":{"type":"number","description":"Combined bundle, promo, and auto-discount total"},"bundle_discounts":{"type":"array","description":"Applied bundle discount rules","items":{"type":"object","properties":{"bundle_id":{"type":"string"},"name":{"type":"string"},"discount_type":{"type":"string","enum":["percentage","fixed"]},"discount_value":{"type":"number"},"matched_options":{"type":"array","items":{"type":"string"}},"discount_amount":{"type":"number"},"billing_type":{"type":"string"}},"required":["bundle_id","name","discount_type","discount_value","matched_options","discount_amount","billing_type"]}},"bundle_discount_total":{"type":"number","description":"Sum of all applied bundle discount amounts"},"promo_discount":{"type":"number","description":"Discount amount applied by the promo code"},"promo_details":{"description":"Applied promo code details, or null when no promo code was applied","oneOf":[{"type":"object","properties":{"code":{"type":"string"},"discount_type":{"type":"string","enum":["percentage","fixed"]},"discount_value":{"type":"number"},"discount_amount":{"type":"number"}},"required":["code","discount_type","discount_value","discount_amount"]},{"type":"null"}]},"auto_discount_total":{"type":"number","description":"Sum of applied widget auto-discounts"},"auto_discounts_applied":{"type":"array","description":"Widget auto-discounts applied on the post-bundle subtotal","items":{"type":"object","properties":{"type":{"type":"string","enum":["percentage","fixed"]},"value":{"type":"number"},"description":{"type":"string"},"discount_amount":{"type":"number"}},"required":["type","value","description","discount_amount"]}},"compatibility_errors":{"type":"array","description":"Compatibility-rule violations detected while pricing the cart","items":{"type":"object"}},"tax":{"type":"number","description":"Tax amount calculated after bundle and promo/auto discounts"},"total":{"type":"number","description":"Final total (subtotal - discount + tax)"},"chargeAmount":{"type":"number","description":"Amount charged immediately (full total, or deposit amount if isDeposit is true)"},"isDeposit":{"type":"boolean","description":"True when chargeAmount is a deposit rather than the full total"},"currency":{"type":"string","description":"ISO 4217 currency code for all monetary values"}},"required":["items","subtotal","discount","bundle_discounts","bundle_discount_total","promo_discount","auto_discount_total","auto_discounts_applied","compatibility_errors","tax","total","chargeAmount","isDeposit","currency"]}},"required":["error","success","data"]},"SupportTicket":{"type":"object","description":"Support ticket record returned by the support ticket workflow.","properties":{"id":{"type":"integer"},"ticket_id":{"type":"string","description":"Stable support ticket identifier.","pattern":"^st_[a-f0-9]{20}$"},"tenant_id":{"type":["string","null"],"description":"Owning tenant ID, or null for system-admin-created tickets without tenant context."},"created_by_user_id":{"type":["integer","null"]},"created_by_email":{"type":["string","null"],"format":"email"},"created_by_name":{"type":["string","null"]},"requester_type":{"type":"string","enum":["tenant","admin"]},"category":{"type":"string","enum":["support","bug","feature","admin-node","billing","account"]},"priority":{"type":"string","enum":["low","normal","high","urgent"]},"title":{"type":"string","maxLength":180},"description":{"type":"string","maxLength":10000},"status":{"type":"string","enum":["pending","approved","queued","in_progress","completed","rejected"]},"worker_status":{"type":["string","null"]},"github_issue_number":{"type":["integer","null"]},"github_issue_url":{"type":["string","null"],"format":"uri"},"approved_by_user_id":{"type":["integer","null"]},"approved_at":{"type":["string","null"],"format":"date-time"},"rejection_reason":{"type":["string","null"]},"completed_at":{"type":["string","null"],"format":"date-time"},"metadata":{"type":"object","description":"Implementation-specific workflow metadata for approval and worker processing.","additionalProperties":true},"created_at":{"type":["string","null"],"format":"date-time"},"updated_at":{"type":["string","null"],"format":"date-time"}},"required":["id","ticket_id","tenant_id","created_by_user_id","created_by_email","created_by_name","requester_type","category","priority","title","description","status","worker_status","github_issue_number","github_issue_url","approved_by_user_id","approved_at","rejection_reason","completed_at","metadata","created_at","updated_at"]},"SupportTicketListResponse":{"type":"object","description":"Paginated support ticket list.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"tickets":{"type":"array","items":{"$ref":"#/components/schemas/SupportTicket"}},"pagination":{"$ref":"#/components/schemas/Pagination"}},"required":["tickets","pagination"]}},"required":["error","success","data"]},"SupportTicketWriteResponse":{"type":"object","description":"Single support ticket mutation response.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"ticket":{"$ref":"#/components/schemas/SupportTicket"}},"required":["ticket"]}},"required":["error","success","data"]},"SupportTicketCreateRequest":{"title":"SupportTicketCreateRequest","type":"object","description":"Default POST body for creating a support ticket.","additionalProperties":false,"required":["title","description"],"properties":{"title":{"type":"string","maxLength":180,"description":"Short support request title."},"description":{"type":"string","maxLength":10000,"description":"Detailed description of the issue or request."},"category":{"type":"string","enum":["support","bug","feature","admin-node","billing","account"],"default":"support"},"priority":{"type":"string","enum":["low","normal","high","urgent"],"default":"normal"},"tenant_id":{"type":"string","pattern":"^[A-Za-z0-9_.:-]{1,128}$","description":"Optional explicit tenant context for system-admin sessions."}}},"SupportTicketApproveRequest":{"title":"SupportTicketApproveRequest","type":"object","description":"Body for `action=approve`.","additionalProperties":false,"required":["ticket_id"],"properties":{"ticket_id":{"type":"string","pattern":"^st_[a-f0-9]{20}$"},"worker_labels":{"type":"array","description":"Optional worker labels attached to the downstream GitHub issue payload.","items":{"type":"string","pattern":"^[a-z0-9][a-z0-9-]{0,40}$"}},"note":{"type":"string","maxLength":1000}}},"SupportTicketRejectRequest":{"title":"SupportTicketRejectRequest","type":"object","description":"Body for `action=reject`.","additionalProperties":false,"required":["ticket_id","reason"],"properties":{"ticket_id":{"type":"string","pattern":"^st_[a-f0-9]{20}$"},"reason":{"type":"string","maxLength":2000}}},"SupportTicketCompleteRequest":{"title":"SupportTicketCompleteRequest","type":"object","description":"Body for `action=complete`.","additionalProperties":false,"required":["ticket_id"],"properties":{"ticket_id":{"type":"string","pattern":"^st_[a-f0-9]{20}$"},"note":{"type":"string","maxLength":1000}}},"SuccessResponse":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","description":"Response data (varies by endpoint; omitted when the operation has no return value)"}},"required":["error","success"]},"DashboardStatsResponse":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"counts":{"type":"object","description":"Total record counts across core entities","properties":{"customers":{"type":"integer","description":"Total number of customers"},"deals":{"type":"integer","description":"Total number of deals"},"products":{"type":"integer","description":"Total number of products"},"contracts":{"type":"integer","description":"Total number of contracts"}},"required":["customers","deals","products","contracts"]},"pipeline":{"type":"object","description":"Deal pipeline analytics including conversion rates, forecasts, and stage breakdowns","properties":{"pipeline":{"type":"object","description":"Deal counts and total value keyed by status (e.g. draft, in_progress, closed)","additionalProperties":{"type":"object","properties":{"count":{"type":"integer"},"total_value":{"type":"number"}}}},"total_deals":{"type":"integer","description":"Total deal count across all statuses"},"conversion_rate":{"type":["number","null"],"description":"Percentage of completed deals that were closed (0-100)"},"avg_days_to_close":{"type":["number","null"],"description":"Average days from deal creation to close"},"avg_deal_value":{"type":["number","null"],"description":"Average value of closed deals"},"total_revenue":{"type":["number","null"],"description":"Sum of all closed deal values"},"active_pipeline_value":{"type":"number","description":"Total value of all active (non-terminal) deals"},"forecasted_revenue":{"type":["number","null"],"description":"Projected revenue from active pipeline using historical conversion rate"},"forecast_confidence":{"type":["object","null"],"description":"Confidence interval for the revenue forecast"},"bottleneck":{"type":["object","null"],"description":"The pipeline stage with the most active deals","properties":{"status":{"type":"string"},"count":{"type":"integer"}}},"transitions":{"type":"object","description":"Deal status transition counts keyed by 'from → to' string","additionalProperties":{"type":"integer"}},"subscription_metrics":{"type":["object","null"],"description":"MRR, ARR, and churn metrics for subscription deals"},"outcome_summary":{"type":["object","null"],"description":"Top loss reasons and outcome breakdown for closed deals"}}},"revenue_series":{"type":"array","description":"Daily revenue totals for the last 30 days (closed deals only)","items":{"type":"object","properties":{"date":{"type":"string","format":"date","description":"Calendar date (YYYY-MM-DD)"},"total":{"type":"number","description":"Sum of deal totals closed on this date"},"count":{"type":"integer","description":"Number of deals closed on this date"}},"required":["date","total","count"]}},"attention":{"type":"object","description":"Items that require merchant attention (expiring or stale records)","properties":{"expiring_deals":{"type":"array","description":"Active deals expiring within the next 7 days","items":{"type":"object","properties":{"deal_id":{"type":"string"},"status":{"type":"string"},"total":{"type":"number"},"expires_at":{"type":"string","format":"date-time"},"customer_id":{"type":"string"}}}},"expiring_contracts":{"type":"array","description":"Active or signed contracts ending within the next 30 days","items":{"type":"object","properties":{"contract_id":{"type":"string"},"title":{"type":"string"},"status":{"type":"string"},"value":{"type":"number"},"end_date":{"type":"string","format":"date"},"customer_id":{"type":"string"}}}},"stale_deals":{"type":"array","description":"Active deals with no activity in the last 14 days","items":{"type":"object","properties":{"deal_id":{"type":"string"},"status":{"type":"string"},"total":{"type":"number"},"updated_at":{"type":"string","format":"date-time"},"customer_id":{"type":"string"}}}}},"required":["expiring_deals","expiring_contracts","stale_deals"]}},"required":["counts","pipeline","revenue_series","attention"]}},"required":["error","success","data"]},"PaymentIntentResponse":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"type":"object","properties":{"client_secret":{"type":"string","description":"payment intent client secret for frontend confirmation"},"payment_intent_id":{"type":"string","description":"payment intent ID"},"amount":{"type":"number","description":"Payment amount"},"currency":{"type":"string","description":"ISO 4217 currency code"}},"required":["client_secret","payment_intent_id","amount","currency"]}},"required":["error","success","data"]},"DeleteResponse":{"type":"object","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message"}},"required":["message"]}},"required":["error","success","data"]},"CustomerDeleteResponse":{"type":"object","description":"Response returned when a customer is permanently deleted","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message"},"customer_id":{"type":"string","description":"ID of the deleted customer"}},"required":["message","customer_id"]}},"required":["error","success","data"]},"DealDeleteResponse":{"type":"object","description":"Response returned when a deal is cancelled (soft) or permanently deleted (hard). All paths return the deal object as it was at the time of the operation.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message (e.g. 'Deal cancelled successfully' or 'Deal deleted successfully')"},"deal_id":{"type":"string","description":"ID of the affected deal"},"deal":{"$ref":"#/components/schemas/Deal","description":"The deal object as it existed before the operation. Always present: contains the cancelled state for soft-cancel, the pre-deletion state for hard delete, or the updated state for item removal."}},"required":["message","deal_id","deal"]}},"required":["error","success","data"]},"ProductDeleteResponse":{"type":"object","description":"Response returned when a product is permanently deleted","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message"},"product_id":{"type":"string","description":"ID of the deleted product"}},"required":["message","product_id"]}},"required":["error","success","data"]},"ContractDeleteResponse":{"type":"object","description":"Response returned when a contract is permanently deleted","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message"},"contract_id":{"type":"integer","description":"ID of the deleted contract"}},"required":["message","contract_id"]}},"required":["error","success","data"]},"WebhookDeleteResponse":{"type":"object","description":"Response returned when a webhook is permanently deleted","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message"},"webhook_id":{"type":"string","description":"ID of the deleted webhook"}},"required":["message","webhook_id"]}},"required":["error","success","data"]},"BundleRuleDeleteResponse":{"type":"object","description":"Response returned when a bundle pricing rule is permanently deleted","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message"},"bundle_id":{"type":"string","description":"ID of the deleted bundle rule"}},"required":["message","bundle_id"]}},"required":["error","success","data"]},"CompatibilityRuleDeleteResponse":{"type":"object","description":"Response returned when a compatibility rule is permanently deleted","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","description":"Success message"},"rule_id":{"type":"string","description":"ID of the deleted compatibility rule"}},"required":["message","rule_id"]}},"required":["error","success","data"]},"BundleRule":{"type":"object","description":"A bundle pricing rule that applies a discount when a qualifying combination of product options is selected","properties":{"bundle_id":{"type":"string","description":"Unique identifier for the bundle rule"},"product_id":{"type":["string","null"],"description":"Product this rule applies to, or null for rules that apply across all products"},"name":{"type":"string","description":"Display name for the bundle rule"},"discount_type":{"type":"string","enum":["fixed","percent"],"description":"Whether the discount is a fixed currency amount or a percentage"},"discount_value":{"type":"number","description":"Discount amount (currency units for fixed, 0-100 for percent)"},"min_options":{"type":"integer","description":"Minimum number of bundle options that must be selected to trigger the discount"},"is_active":{"type":"boolean","description":"Whether this bundle rule is currently active"},"created_at":{"type":"string","format":"date-time","description":"ISO 8601 timestamp when the rule was created"},"updated_at":{"type":"string","format":"date-time","description":"ISO 8601 timestamp when the rule was last updated"},"option_ids":{"type":"array","items":{"type":"string"},"description":"IDs of the product options that form this bundle"},"options":{"type":"array","items":{"type":"object","properties":{"option_id":{"type":"string","description":"Option identifier"},"option_name":{"type":"string","description":"Human-readable option name"}},"required":["option_id","option_name"]},"description":"Options included in this bundle with their display names"}},"required":["bundle_id","name","discount_type","discount_value","min_options","is_active","created_at","updated_at","option_ids","options"]},"BundleRuleResponse":{"type":"object","description":"Success response containing a single bundle pricing rule","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"bundle":{"$ref":"#/components/schemas/BundleRule"}},"required":["bundle"]}},"required":["error","success","data"]},"BundleRuleListResponse":{"type":"object","description":"Success response containing a paginated list of bundle pricing rules","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"bundles":{"type":"array","items":{"$ref":"#/components/schemas/BundleRule"},"description":"List of bundle pricing rules"},"pagination":{"type":"object","properties":{"total":{"type":"integer","description":"Total number of matching records"},"limit":{"type":"integer","description":"Maximum records returned per page"},"offset":{"type":"integer","description":"Number of records skipped"},"count":{"type":"integer","description":"Number of records in this response"}},"required":["total","limit","offset","count"]}},"required":["bundles","pagination"]}},"required":["error","success","data"]},"CompatibilityRule":{"type":"object","description":"A compatibility rule defining a requires, excludes, or includes_price relationship between two product options","properties":{"rule_id":{"type":"string","description":"Unique identifier for the compatibility rule"},"product_id":{"type":["string","null"],"description":"Product this rule applies to, or null for rules that apply across all products"},"source_option_id":{"type":"string","description":"The option that triggers this rule when selected"},"target_option_id":{"type":"string","description":"The option affected by this rule"},"rule_type":{"type":"string","enum":["requires","excludes","includes_price"],"description":"Type of compatibility relationship: requires (source forces target), excludes (source prevents target), includes_price (source adds target price)"},"message":{"type":["string","null"],"description":"Optional message shown to users when this rule is triggered"},"is_active":{"type":"boolean","description":"Whether this compatibility rule is currently enforced"},"created_at":{"type":"string","format":"date-time","description":"ISO 8601 timestamp when the rule was created"},"updated_at":{"type":"string","format":"date-time","description":"ISO 8601 timestamp when the rule was last updated"},"source_option_name":{"type":["string","null"],"description":"Display name of the source option"},"target_option_name":{"type":["string","null"],"description":"Display name of the target option"},"product_name":{"type":["string","null"],"description":"Display name of the product this rule is scoped to"}},"required":["rule_id","source_option_id","target_option_id","rule_type","is_active","created_at","updated_at"]},"CompatibilityRuleResponse":{"type":"object","description":"Success response containing a single compatibility rule","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"rule":{"$ref":"#/components/schemas/CompatibilityRule"}},"required":["rule"]}},"required":["error","success","data"]},"CompatibilityRuleListResponse":{"type":"object","description":"Success response containing a paginated list of compatibility rules","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"rules":{"type":"array","items":{"$ref":"#/components/schemas/CompatibilityRule"},"description":"List of compatibility rules"},"pagination":{"type":"object","properties":{"total":{"type":"integer","description":"Total number of matching records"},"limit":{"type":"integer","description":"Maximum records returned per page"},"offset":{"type":"integer","description":"Number of records skipped"},"count":{"type":"integer","description":"Number of records in this response"}},"required":["total","limit","offset","count"]}},"required":["rules","pagination"]}},"required":["error","success","data"]},"ConfigurationValidationError":{"type":"object","description":"Structured validation error returned when a selected option violates a compatibility rule","properties":{"rule_id":{"type":"string","description":"ID of the compatibility rule that was violated"},"rule_type":{"type":"string","enum":["requires","excludes"],"description":"Type of compatibility rule that failed validation"},"source_option_id":{"type":"string","description":"ID of the selected option that triggered the rule"},"target_option_id":{"type":"string","description":"ID of the option required or excluded by the rule"},"message":{"type":"string","description":"Human-readable validation message"}},"required":["rule_id","rule_type","source_option_id","target_option_id","message"]},"ConfigurationBundleWarning":{"type":"object","description":"Non-blocking bundle suggestion returned when the current selection is close to qualifying for a bundle discount","properties":{"type":{"type":"string","enum":["bundle_suggestion"],"description":"Warning type"},"bundle_id":{"type":"string","description":"ID of the suggested bundle rule"},"bundle_name":{"type":"string","description":"Display name of the suggested bundle"},"message":{"type":"string","description":"Human-readable suggestion message"},"missing_option_ids":{"type":"array","items":{"type":"string"},"description":"Option IDs still needed to qualify for the bundle"},"discount_type":{"type":"string","enum":["fixed","percent"],"description":"Whether the suggested bundle discount is fixed or percentage based"},"discount_value":{"type":"number","description":"Discount amount for the suggested bundle"}},"required":["type","bundle_id","bundle_name","message","missing_option_ids","discount_type","discount_value"]},"ConfigurationAppliedBundle":{"type":"object","description":"Bundle discount rule that qualifies for the selected configuration","properties":{"bundle_id":{"type":"string","description":"ID of the qualifying bundle rule"},"name":{"type":"string","description":"Display name of the qualifying bundle"},"discount_type":{"type":"string","enum":["fixed","percent"],"description":"Whether the bundle discount is fixed or percentage based"},"discount_value":{"type":"number","description":"Discount amount for the qualifying bundle"},"matched_options":{"type":"array","items":{"type":"string"},"description":"Selected option IDs that matched the bundle"},"matched_count":{"type":"integer","description":"Number of matched options"},"total_options":{"type":"integer","description":"Total number of options in the bundle"},"discount_amount":{"type":"number","description":"Calculated discount amount for this configuration"}},"required":["bundle_id","name","discount_type","discount_value","matched_options","matched_count","total_options","discount_amount"]},"ConfigurationPriceAdjustment":{"type":"object","description":"Price override applied by a compatibility rule such as includes_price","properties":{"rule_id":{"type":"string","description":"ID of the compatibility rule that applied the adjustment"},"option_id":{"type":"string","description":"ID of the option whose price was adjusted"},"adjusted_price":{"type":"number","description":"Adjusted option price"},"reason":{"type":"string","description":"Human-readable explanation for the adjustment"}},"required":["rule_id","option_id","adjusted_price","reason"]},"ErrorResponse":{"type":"object","description":"Structured error response with machine-readable recovery hints for AI agents","properties":{"error":{"type":"boolean","const":true},"code":{"type":"string","description":"Machine-readable error code in dotted notation (e.g. 'validation_error.invalid_fields', 'conflict.deal_already_closed')","examples":["validation_error.invalid_fields","not_found","conflict.deal_already_closed","authentication_error.invalid_credentials","rate_limited","internal_error"]},"category":{"type":"string","description":"Error category for programmatic error handling","enum":["validation_error","authentication_error","authorization_error","not_found","conflict","rate_limited","rate_limit","request_error","security_error","billing_error","server_error","config_error","transient_error","internal_error","billing"]},"message":{"type":"string","description":"Human-readable error message"},"recovery":{"type":"object","description":"Machine-readable recovery hints for AI agents and automated systems","properties":{"action":{"type":"string","description":"Recommended recovery action","enum":["fix_request","use_correct_method","use_valid_action","authenticate","check_permissions","check_resource_id","issue_credential","resolve_conflict","refetch_and_retry","retry","configure_payment_provider","contact_support","check_status","none","top_up_credit","wait_for_next_month","reduce_proposal_value","earn_higher_trust","deposit_usdc","wait_or_reduce_amount","contact_merchant"]},"retryable":{"type":"boolean","description":"Whether the request can be retried (possibly after a delay)"},"retry_after_seconds":{"type":"integer","description":"Recommended delay before retrying (only present when retryable is true)"},"max_retries":{"type":"integer","description":"Maximum recommended retry attempts"},"hint":{"type":"string","description":"Human-readable recovery guidance"}},"required":["action","retryable"]},"ref":{"type":"string","description":"Error trace ID for support correlation (present when Logger is available)"},"details":{"type":"object","description":"Additional error details","properties":{"fields":{"type":"object","description":"Field-level validation errors (for validation_error category)","additionalProperties":{"type":"object","properties":{"code":{"type":"string","description":"Field error code (e.g. 'required', 'invalid', 'invalid_value')"},"message":{"type":"string","description":"Human-readable field error message"},"allowed_values":{"type":"array","items":{"type":"string"},"description":"List of allowed values (when applicable)"}},"required":["code","message"]}}}}},"required":["error","code","category","message","recovery"]},"DelegationProposal":{"type":"object","description":"A single agent-to-agent delegation proposal","properties":{"id":{"type":"string","description":"Proposal ID (starts with dprop_)"},"proposal_id":{"type":"string","description":"Unique proposal identifier (alias for id, included when returned from listPendingProposals)"},"tenant_id":{"type":"string"},"proposer_api_key_id":{"type":"string","description":"API key ID of the agent making the proposal"},"target_api_key_id":{"type":"string","description":"API key ID of the agent being proposed to"},"parent_delegation_id":{"type":["string","null"]},"proposed_actions":{"type":"array","items":{"type":"string"},"description":"Action scopes requested in this proposal"},"proposed_spending_limits":{"type":["object","null"],"description":"Spending constraints requested in this proposal"},"proposed_duration_hours":{"type":["integer","null"],"description":"Requested delegation duration in hours (null = indefinite)"},"message":{"type":["string","null"],"description":"Optional message from the proposing agent"},"status":{"type":"string","enum":["pending","accepted","rejected","countered","expired"],"description":"Current state of the proposal"},"round":{"type":"integer","description":"Counter-proposal round number"},"previous_proposal_id":{"type":["string","null"],"description":"ID of the previous proposal this counters (null for initial proposals)"},"response_message":{"type":["string","null"],"description":"Message from the responding agent"},"expires_at":{"type":"string","format":"date-time","description":"When this proposal expires"},"created_at":{"type":"string","format":"date-time"},"resolved_at":{"type":["string","null"],"format":"date-time","description":"When the proposal was accepted, rejected or expired"},"proposer_trust_level":{"type":["integer","null"],"description":"Trust level of the proposing agent at time of listing (from AgentTrustService)"},"proposer_trust_label":{"type":["string","null"],"description":"Human-readable trust label for the proposing agent"}},"required":["proposer_api_key_id","target_api_key_id","proposed_actions","status","expires_at","created_at"]},"Site":{"type":"object","properties":{"site_id":{"type":"string","example":"site_a1b2c3d4e5f6"},"domain":{"type":"string","example":"mystore.com"},"name":{"type":"string","example":"My Store"},"status":{"type":"string","enum":["active","inactive","coming_soon"],"example":"coming_soon"},"analytics_enabled":{"type":"boolean","example":true},"created_at":{"type":["string","null"],"format":"date-time"},"updated_at":{"type":["string","null"],"format":"date-time"}},"required":["site_id","domain","name","status","analytics_enabled"]},"DealSettlement":{"type":"object","properties":{"id":{"type":"string","description":"Settlement ID (setl_...)"},"deal_id":{"type":"string"},"participant_id":{"type":"string"},"amount":{"type":"string","description":"Settlement amount (decimal string)"},"currency":{"type":"string","example":"USD"},"status":{"type":"string","enum":["pending","processing","settled","failed"],"description":"pending=awaiting execution; processing=transfer initiated; settled=complete; failed=transfer error"},"payment_method":{"type":"string","enum":["usdc","stripe","pending"],"description":"usdc for agent participants; stripe for merchant participants with payment account"},"stripe_transfer_id":{"type":["string","null"]},"usdc_tx_id":{"type":["string","null"]},"attempts":{"type":"integer"},"error_message":{"type":["string","null"]},"settled_at":{"type":["string","null"],"format":"date-time"},"created_at":{"type":"string","format":"date-time"},"participant":{"type":"object","properties":{"role":{"type":"string"},"scope_description":{"type":["string","null"]},"revenue_share_percent":{"type":["number","null"]},"agent_name":{"type":["string","null"]},"agent_key_id":{"type":["string","null"]},"is_agent":{"type":"boolean"}}}}},"StaffCreateRequest":{"type":"object","description":"Request body for creating a new staff member","required":["display_name"],"properties":{"display_name":{"type":"string","maxLength":255,"description":"Full display name of the staff member"},"title":{"type":"string","maxLength":255,"description":"Job title or role (e.g. Senior Consultant)"},"bio":{"type":"string","maxLength":65535,"description":"Short biography shown to customers"},"avatar_url":{"type":"string","maxLength":2048,"description":"URL of the staff member's profile photo"},"user_id":{"type":"string","maxLength":50,"description":"Linked tenant user account ID"},"status":{"type":"string","enum":["active","inactive"],"default":"active","description":"Availability status"},"max_daily_sessions":{"type":"integer","minimum":1,"maximum":100,"default":8,"description":"Maximum number of bookings the staff member can take per day"},"default_session_duration":{"type":"integer","minimum":5,"maximum":480,"default":60,"description":"Default booking duration in minutes"},"buffer_time":{"type":"integer","minimum":0,"maximum":240,"default":15,"description":"Gap in minutes between consecutive bookings"},"timezone":{"type":"string","maxLength":100,"default":"UTC","description":"IANA timezone identifier (e.g. America/New_York)"},"metadata":{"type":"object","description":"Arbitrary key-value metadata (max 3 levels deep, 4KB serialized)"},"schedule":{"type":"array","maxItems":7,"description":"Weekly recurring availability — one entry per active day","items":{"type":"object","properties":{"day_of_week":{"type":"integer","minimum":0,"maximum":6,"description":"0 = Sunday, 6 = Saturday"},"start_time":{"type":"string","pattern":"^([01]\\d|2[0-3]):([0-5]\\d)$","description":"Start time in HH:MM format"},"end_time":{"type":"string","pattern":"^([01]\\d|2[0-3]):([0-5]\\d)$","description":"End time in HH:MM format"},"is_available":{"type":"boolean"}},"required":["day_of_week"]}},"product_ids":{"type":"array","maxItems":100,"items":{"type":"string"},"description":"Product IDs this staff member is qualified to deliver"}}},"StaffUpdateRequest":{"type":"object","description":"Request body for updating an existing staff member (all fields optional)","properties":{"display_name":{"type":"string","maxLength":255,"description":"Full display name of the staff member"},"title":{"type":"string","maxLength":255,"description":"Job title or role"},"bio":{"type":"string","maxLength":65535,"description":"Short biography shown to customers"},"avatar_url":{"type":"string","maxLength":2048,"description":"URL of the staff member's profile photo"},"user_id":{"type":"string","maxLength":50,"description":"Linked tenant user account ID"},"status":{"type":"string","enum":["active","inactive"],"description":"Availability status"},"max_daily_sessions":{"type":"integer","minimum":1,"maximum":100,"description":"Maximum number of bookings per day"},"default_session_duration":{"type":"integer","minimum":5,"maximum":480,"description":"Default booking duration in minutes"},"buffer_time":{"type":"integer","minimum":0,"maximum":240,"description":"Gap in minutes between consecutive bookings"},"timezone":{"type":"string","maxLength":100,"description":"IANA timezone identifier"},"metadata":{"type":"object","description":"Arbitrary key-value metadata (max 3 levels deep, 4KB serialized)"},"schedule":{"type":"array","maxItems":7,"description":"Replace the weekly recurring availability schedule","items":{"type":"object","properties":{"day_of_week":{"type":"integer","minimum":0,"maximum":6},"start_time":{"type":"string","pattern":"^([01]\\d|2[0-3]):([0-5]\\d)$"},"end_time":{"type":"string","pattern":"^([01]\\d|2[0-3]):([0-5]\\d)$"},"is_available":{"type":"boolean"}},"required":["day_of_week"]}},"product_ids":{"type":"array","maxItems":100,"items":{"type":"string"},"description":"Replace all product assignments with this list"}}},"StaffScheduleActionRequest":{"type":"object","description":"Request body for POST /staff?action=schedule","required":["schedule"],"properties":{"schedule":{"type":"array","maxItems":7,"description":"Replacement weekly availability schedule","items":{"type":"object","properties":{"day_of_week":{"type":"integer","minimum":0,"maximum":6,"description":"0 = Sunday, 6 = Saturday"},"start_time":{"type":"string","pattern":"^([01]\\d|2[0-3]):([0-5]\\d)$","description":"Start time in HH:MM format"},"end_time":{"type":"string","pattern":"^([01]\\d|2[0-3]):([0-5]\\d)$","description":"End time in HH:MM format"},"is_available":{"type":"boolean","description":"Whether the staff member is available during this window"}},"required":["day_of_week","start_time","end_time"]}}}},"StaffOverrideActionRequest":{"type":"object","description":"Request body for POST /staff?action=override","required":["override_date"],"properties":{"override_date":{"type":"string","format":"date","pattern":"^\\d{4}-\\d{2}-\\d{2}$","description":"Date to override in YYYY-MM-DD format"},"start_time":{"type":"string","pattern":"^\\d{2}:\\d{2}$","description":"Custom start time in HH:MM format"},"end_time":{"type":"string","pattern":"^\\d{2}:\\d{2}$","description":"Custom end time in HH:MM format"},"is_available":{"type":"boolean","description":"Whether the staff member is available on the override date"},"reason":{"type":"string","maxLength":65535,"description":"Optional note describing the reason for the override"}}},"StaffAssignProductActionRequest":{"type":"object","description":"Request body for POST /staff?action=assign_product","required":["product_id"],"properties":{"product_id":{"type":"string","maxLength":255,"description":"Product ID to assign to the staff member"},"session_duration_override":{"type":"integer","minimum":5,"maximum":480,"description":"Optional per-product booking duration override in minutes"},"priority":{"type":"integer","minimum":0,"maximum":9999,"description":"Priority order when multiple staff members are assigned to the product"}}},"StaffOverrideUpdateRequest":{"type":"object","description":"Request body for PATCH /staff?action=override","required":["override_id"],"properties":{"override_id":{"type":"integer","description":"ID of the override to update when not supplied in the query string"},"override_date":{"type":"string","format":"date","pattern":"^\\d{4}-\\d{2}-\\d{2}$","description":"Updated override date in YYYY-MM-DD format"},"start_time":{"type":"string","pattern":"^\\d{2}:\\d{2}$","description":"Updated start time in HH:MM format"},"end_time":{"type":"string","pattern":"^\\d{2}:\\d{2}$","description":"Updated end time in HH:MM format"},"is_available":{"type":"boolean","description":"Updated availability flag for the override"},"reason":{"type":"string","maxLength":65535,"description":"Updated note describing the reason for the override"}}},"WidgetConfigItem":{"type":"object","description":"Widget configuration object returned in authenticated list responses","properties":{"widget_id":{"type":"string","description":"Unique widget identifier (wgt_*)"},"title":{"type":"string","description":"Widget display title"},"theme_color":{"type":"string","description":"Primary theme color as CSS hex (e.g. #2563eb)"},"currency":{"type":"string","enum":["USD","EUR","GBP","CAD","AUD","NZD","CHF","JPY","MXN","BRL"],"description":"ISO 4217 settlement currency code"},"display_currencies":{"type":"array","items":{"type":"string"},"description":"ISO 4217 currency codes available for buyer display conversion"},"products":{"type":"string","description":"Comma-separated product IDs available in the widget"},"cta_text":{"type":"string","description":"Custom call-to-action button label"},"step_1_name":{"type":"string","description":"Custom label for the Products step"},"step_2_name":{"type":"string","description":"Custom label for the Configure step"},"step_3_name":{"type":"string","description":"Custom label for the Summary step"},"step_4_name":{"type":"string","description":"Custom label for the Negotiate step (8-step flow)"},"step_5_name":{"type":"string","description":"Custom label for the Customer/Details step (8-step flow)"},"step_6_name":{"type":"string","description":"Custom label for the Terms step (8-step flow)"},"step_7_name":{"type":"string","description":"Custom label for the Payment step (8-step flow)"},"step_8_name":{"type":"string","description":"Custom label for the Confirmation step (8-step flow)"},"booking_step_name":{"type":"string","description":"Custom label for the Booking step when it is active"},"discount_step_name":{"type":"string","description":"Custom label for the Discount step when it is active"},"config_version":{"type":"integer","description":"Step-name mapping version: 1=legacy 5-step, 2=current 8-step"},"enable_promo_codes":{"type":"boolean","description":"Whether buyers can enter promotional codes"},"enable_discount_step":{"type":"boolean","description":"Whether the dedicated discount step is shown"},"auto_discounts":{"type":["object","null"],"description":"Automatic discount rules based on cart contents or quantity thresholds"},"contract_template_id":{"type":["string","null"],"description":"Contract template used for terms shown to buyers"},"deal_template_id":{"type":["string","null"],"description":"Deal template used to pre-populate the widget"},"enable_negotiation":{"type":"boolean","description":"Whether buyers can submit counter-offers"},"negotiation_mode":{"type":"string","enum":["price_only","item_selection","terms_only","full"],"description":"Negotiation scope"},"auto_accept_threshold":{"type":["number","null"],"description":"Percent tolerance for auto-accepting a counter-offer, where 5 means offers within 5% of the asking price (0-100)"},"locale":{"type":["string","null"],"description":"BCP 47 language tag for the widget UI (e.g. en, en-AU, es, de)"},"locale_overrides":{"type":["object","null"],"description":"Custom string overrides for widget i18n labels"},"show_social_proof":{"type":"boolean","description":"Whether social proof indicators are shown"},"show_smart_defaults":{"type":"boolean","description":"Whether AI-suggested smart defaults are pre-filled"},"social_proof_threshold":{"type":"integer","description":"Minimum completed deals before social proof is displayed"},"show_stock_quantity":{"type":"boolean","description":"Whether remaining stock quantity is shown"},"saved_config_ttl_days":{"type":"integer","description":"Days a buyer's saved configuration is retained (1-365)"},"payment_type":{"type":"string","enum":["full","deposit","quote"],"description":"Payment collection mode"},"deposit_type":{"type":"string","enum":["fixed","percentage"],"description":"Deposit calculation method"},"deposit_value":{"type":["number","null"],"description":"Deposit amount (fixed) or percentage (0-100)"},"deposit_note":{"type":["string","null"],"description":"Note about remaining balance shown to buyer"},"logo_url":{"type":["string","null"],"description":"Merchant logo URL displayed in the widget header"},"font_family":{"type":["string","null"],"description":"CSS font-family applied to widget text"},"custom_css":{"type":["string","null"],"description":"Custom CSS injected into the widget shadow DOM"},"dark_mode":{"type":"boolean","description":"Whether the widget renders in dark mode by default"},"border_radius":{"type":["integer","null"],"description":"Border radius in pixels applied to cards and buttons (0-16)"},"button_style":{"type":"string","enum":["filled","outlined","text"],"description":"Primary button visual style"},"product_selection_mode":{"type":"string","enum":["single","multiple"],"description":"Whether the widget allows selecting one or multiple products"},"analytics_mode":{"type":["string","null"],"description":"Analytics targets (gtm, ga4, segment, callback — comma-separated)"},"analytics_callback":{"type":["string","null"],"description":"Global JavaScript function name invoked with analytics events"},"analytics_consent":{"type":"boolean","description":"Whether analytics requires explicit buyer consent before firing"},"booking_config":{"type":["object","null"],"description":"Widget-level booking step configuration (enable_booking, staff_ids, duration, availability_source, custom_hours, buffer_time, max_advance_days, confirmation)"},"signature_mode":{"type":"string","enum":["checkbox","type","draw","digital"],"description":"Method used to capture buyer signature on the terms step"},"step_order":{"type":["string","null"],"description":"Comma-separated step names defining custom widget step order"},"skip_steps":{"type":["string","null"],"description":"Comma-separated step names omitted from the widget flow"},"site_id":{"type":"string","description":"ID of the site this widget is associated with"},"site_name":{"type":"string","description":"Display name of the associated site"},"site_domain":{"type":"string","description":"Domain of the associated site (e.g. example.com)"},"api_key":{"type":"string","description":"Publishable API key (sb_pub_*) for embedding this widget"},"api_key_id":{"type":"string","description":"ID of the associated publishable API key"},"api_key_prefix":{"type":["string","null"],"nullable":true,"description":"Prefix of the API key associated with this widget (first 16 chars followed by ...)"},"status":{"type":"string","enum":["active","inactive"],"description":"Widget status"},"created_at":{"type":"string","description":"ISO 8601 datetime when the widget was created"}}},"WidgetConfigSingle":{"allOf":[{"$ref":"#/components/schemas/WidgetConfigItem"},{"type":"object","description":"Additional fields present only in authenticated single-widget GET responses","properties":{"network_config":{"type":["object","null"],"description":"Widget network and retry configuration overrides (fetch_timeout, retry_max, retry_base_delay, retry_max_delay, retry_jitter, total_retry_budget, cache_products_ttl, cache_config_ttl, cache_assets_ttl, negotiate_poll_interval, negotiate_sse_timeout, heartbeat_interval, heartbeat_offline_interval, abandon_timeout). Values are milliseconds except retry_jitter; legacy aliases timeout_ms, retry_attempts, max_retries, retry_delay_ms, and cache_ttl_seconds are normalized for backward compatibility."},"step_conditions":{"type":["object","null"],"description":"Conditional step visibility rules keyed by step name (e.g. {\"terms\": {\"minTotal\": 1000}})"}}}]},"WidgetConfigUpdateResponse":{"type":"object","description":"Updated widget configuration returned after a successful PATCH. Contains all config fields but excludes site info and api_key (those do not change on update).","properties":{"widget_id":{"type":"string","description":"Unique widget identifier (wgt_*)"},"title":{"type":"string","description":"Widget display title"},"theme_color":{"type":"string","description":"Primary theme color as CSS hex (e.g. #2563eb)"},"currency":{"type":"string","enum":["USD","EUR","GBP","CAD","AUD","NZD","CHF","JPY","MXN","BRL"],"description":"ISO 4217 settlement currency code"},"display_currencies":{"type":"array","items":{"type":"string"},"description":"ISO 4217 currency codes available for buyer display conversion"},"products":{"type":"string","description":"Comma-separated product IDs available in the widget"},"cta_text":{"type":"string","description":"Custom call-to-action button label"},"step_1_name":{"type":"string","description":"Custom label for the Products step"},"step_2_name":{"type":"string","description":"Custom label for the Configure step"},"step_3_name":{"type":"string","description":"Custom label for the Summary step"},"step_4_name":{"type":"string","description":"Custom label for the Negotiate step (8-step flow)"},"step_5_name":{"type":"string","description":"Custom label for the Customer/Details step (8-step flow)"},"step_6_name":{"type":"string","description":"Custom label for the Terms step (8-step flow)"},"step_7_name":{"type":"string","description":"Custom label for the Payment step (8-step flow)"},"step_8_name":{"type":"string","description":"Custom label for the Confirmation step (8-step flow)"},"booking_step_name":{"type":"string","description":"Custom label for the Booking step when it is active"},"discount_step_name":{"type":"string","description":"Custom label for the Discount step when it is active"},"config_version":{"type":"integer","description":"Step-name mapping version: 1=legacy 5-step, 2=current 8-step"},"enable_promo_codes":{"type":"boolean","description":"Whether buyers can enter promotional codes"},"enable_discount_step":{"type":"boolean","description":"Whether the dedicated discount step is shown"},"auto_discounts":{"type":["object","null"],"description":"Automatic discount rules based on cart contents or quantity thresholds"},"contract_template_id":{"type":["string","null"],"description":"Contract template used for terms shown to buyers"},"deal_template_id":{"type":["string","null"],"description":"Deal template used to pre-populate the widget"},"enable_negotiation":{"type":"boolean","description":"Whether buyers can submit counter-offers"},"negotiation_mode":{"type":"string","enum":["price_only","item_selection","terms_only","full"],"description":"Negotiation scope"},"auto_accept_threshold":{"type":["number","null"],"description":"Percent tolerance for auto-accepting a counter-offer, where 5 means offers within 5% of the asking price (0-100)"},"locale":{"type":["string","null"],"description":"BCP 47 language tag for the widget UI (e.g. en, en-AU, es, de)"},"locale_overrides":{"type":["object","null"],"description":"Custom string overrides for widget i18n labels"},"show_social_proof":{"type":"boolean","description":"Whether social proof indicators are shown"},"show_smart_defaults":{"type":"boolean","description":"Whether AI-suggested smart defaults are pre-filled"},"social_proof_threshold":{"type":"integer","description":"Minimum completed deals before social proof is displayed"},"show_stock_quantity":{"type":"boolean","description":"Whether remaining stock quantity is shown"},"saved_config_ttl_days":{"type":"integer","description":"Days a buyer's saved configuration is retained (1-365)"},"payment_type":{"type":"string","enum":["full","deposit","quote"],"description":"Payment collection mode"},"deposit_type":{"type":"string","enum":["fixed","percentage"],"description":"Deposit calculation method"},"deposit_value":{"type":["number","null"],"description":"Deposit amount (fixed) or percentage (0-100)"},"deposit_note":{"type":["string","null"],"description":"Note about remaining balance shown to buyer"},"logo_url":{"type":["string","null"],"description":"Merchant logo URL displayed in the widget header"},"font_family":{"type":["string","null"],"description":"CSS font-family applied to widget text"},"custom_css":{"type":["string","null"],"description":"Custom CSS injected into the widget shadow DOM"},"dark_mode":{"type":"boolean","description":"Whether the widget renders in dark mode by default"},"border_radius":{"type":["integer","null"],"description":"Border radius in pixels applied to cards and buttons (0-16)"},"button_style":{"type":"string","enum":["filled","outlined","text"],"description":"Primary button visual style"},"product_selection_mode":{"type":"string","enum":["single","multiple"],"description":"Whether the widget allows selecting one or multiple products"},"analytics_mode":{"type":["string","null"],"description":"Analytics targets (gtm, ga4, segment, callback — comma-separated)"},"analytics_callback":{"type":["string","null"],"description":"Global JavaScript function name invoked with analytics events"},"analytics_consent":{"type":"boolean","description":"Whether analytics requires explicit buyer consent before firing"},"booking_config":{"type":["object","null"],"description":"Widget-level booking step configuration (enable_booking, staff_ids, duration, availability_source, custom_hours, buffer_time, max_advance_days, confirmation)"},"signature_mode":{"type":"string","enum":["checkbox","type","draw","digital"],"description":"Method used to capture buyer signature on the terms step"},"step_order":{"type":["string","null"],"description":"Comma-separated step names defining custom widget step order"},"skip_steps":{"type":["string","null"],"description":"Comma-separated step names omitted from the widget flow"},"network_config":{"type":["object","null"],"description":"Widget network and retry configuration overrides (fetch_timeout, retry_max, retry_base_delay, retry_max_delay, retry_jitter, total_retry_budget, cache_products_ttl, cache_config_ttl, cache_assets_ttl, negotiate_poll_interval, negotiate_sse_timeout, heartbeat_interval, heartbeat_offline_interval, abandon_timeout). Values are milliseconds except retry_jitter; legacy aliases timeout_ms, retry_attempts, max_retries, retry_delay_ms, and cache_ttl_seconds are normalized for backward compatibility."},"step_conditions":{"type":["object","null"],"description":"Conditional step visibility rules keyed by step name"}}},"WidgetConfigPublic":{"type":"object","properties":{"merchant_available":{"type":"boolean","description":"Whether the merchant has sufficient credit to accept new deals. False when credit balance is below deal cost."},"merchant_contact":{"type":["object","null"],"description":"Merchant contact info for buyer fallback when merchant_available is false.","properties":{"name":{"type":"string"},"email":{"type":"string"},"phone":{"type":"string"}}},"display_currencies":{"type":"array","items":{"type":"string"},"description":"ISO 4217 currency codes available for buyer display conversion in the widget"},"payment_type":{"type":"string","enum":["full","deposit","quote"],"description":"Payment collection mode"},"deposit_type":{"type":"string","enum":["fixed","percentage"],"description":"Deposit calculation method"},"deposit_value":{"type":["number","null"],"description":"Deposit amount (fixed) or percentage (0-100)"},"deposit_note":{"type":["string","null"],"description":"Note about remaining balance shown to buyer"},"deal_template_id":{"type":["string","null"],"description":"Deal template ID used to pre-populate the widget with template products and pricing"},"deal_template":{"type":["object","null"],"description":"Deal template data for pre-populating the widget. Included when deal_template_id is set and template is active.","properties":{"name":{"type":"string","description":"Template name, used as widget title fallback"},"template_data":{"type":"object","description":"Template configuration including line_items, discounts, terms, and metadata","properties":{"title":{"type":"string"},"currency":{"type":"string"},"line_items":{"type":"array","items":{"type":"object","properties":{"product_id":{"type":"string"},"name":{"type":"string"},"quantity":{"type":"integer"},"unit_price":{"type":"number"}}}},"discounts":{"type":"array","items":{"type":"object","properties":{"type":{"type":"string","enum":["fixed","percentage"]},"value":{"type":"number"}}}}}}}},"booking_config":{"type":["object","null"],"description":"Widget-level booking step configuration (enable_booking, staff_ids, duration, availability_source, custom_hours, buffer_time, max_advance_days, confirmation)"},"config_version":{"type":"integer","description":"Configuration version number for cache invalidation","default":1},"product_selection_mode":{"type":"string","enum":["single","multiple"],"description":"Whether the widget allows selecting one or multiple products","default":"single"},"ab_test":{"type":["object","null"],"description":"Active A/B test configuration, or null if no test is running","properties":{"ab_test_id":{"type":"string"},"api_key_a":{"type":"string"},"api_key_b":{"type":"string"},"weight_b":{"type":"number"},"widget_a_id":{"type":"string"},"widget_b_id":{"type":"string"}}},"widget_id":{"type":"string","description":"Unique identifier for this widget configuration"},"api_key":{"type":"string","description":"Publishable widget API key. Returned on public lookups so headless clients can hydrate their SDK client after resolving by widget_id."},"updated_at":{"type":"string","description":"MD5 content hash of the config. Changes whenever any field is updated. Used by the widget SDK to invalidate the product cache."},"title":{"type":"string","description":"Widget display title shown in the header"},"theme_color":{"type":"string","description":"Primary theme color as a CSS hex value (e.g. #2563eb)"},"currency":{"type":"string","description":"ISO 4217 settlement currency code (e.g. USD, AUD, EUR)"},"products":{"type":"string","description":"Comma-separated product IDs available for selection in the widget"},"cta_text":{"type":"string","description":"Custom call-to-action button label (e.g. 'Get Started', 'Buy Now')"},"step_1_name":{"type":"string","description":"Custom label for the Products step"},"step_2_name":{"type":"string","description":"Custom label for the Configure step"},"step_3_name":{"type":"string","description":"Custom label for the Summary step"},"step_4_name":{"type":"string","description":"Custom label for the Negotiate step (8-step flow)"},"step_5_name":{"type":"string","description":"Custom label for the Customer/Details step (8-step flow)"},"step_6_name":{"type":"string","description":"Custom label for the Terms step (8-step flow)"},"step_7_name":{"type":"string","description":"Custom label for the Payment step (8-step flow)"},"step_8_name":{"type":"string","description":"Custom label for the Confirmation step (8-step flow)"},"booking_step_name":{"type":"string","description":"Custom label for the Booking step when it is active"},"discount_step_name":{"type":"string","description":"Custom label for the Discount step when it is active"},"enable_promo_codes":{"type":"boolean","description":"Whether buyers can enter promotional codes in the widget"},"enable_discount_step":{"type":"boolean","description":"Whether the dedicated discount step is shown in the widget flow"},"auto_discounts":{"type":["object","null"],"description":"Automatic discount rules applied based on cart contents or quantity thresholds"},"contract_template_id":{"type":["string","null"],"description":"Contract template ID used to generate the terms agreement presented to buyers"},"enable_negotiation":{"type":"boolean","description":"Whether buyers can submit counter-offers and negotiate pricing"},"negotiation_mode":{"type":"string","enum":["price_only","item_selection","terms_only","full"],"description":"Negotiation scope: price_only allows price counter-offers only; full allows line item and terms changes"},"auto_accept_threshold":{"type":["number","null"],"description":"Minimum acceptable counter-offer percentage (0-100). Counter-offers at or above this threshold are auto-accepted."},"locale":{"type":["string","null"],"description":"BCP 47 language tag for the widget UI (e.g. en, en-AU, es, de, fr, ja)"},"locale_overrides":{"type":["object","null"],"description":"Custom string overrides for widget i18n labels keyed by dot-separated translation paths"},"show_social_proof":{"type":"boolean","description":"Whether social proof indicators (recent activity, buyer counts) are shown in the widget"},"show_smart_defaults":{"type":"boolean","description":"Whether AI-suggested smart defaults are pre-filled in the widget configuration step"},"social_proof_threshold":{"type":"integer","description":"Minimum number of completed deals before social proof indicators are displayed"},"show_stock_quantity":{"type":"boolean","description":"Whether remaining stock quantity is displayed alongside products"},"saved_config_ttl_days":{"type":"integer","description":"Number of days a buyer's saved widget configuration is retained before expiry"},"logo_url":{"type":["string","null"],"description":"Merchant logo URL displayed in the widget header"},"font_family":{"type":["string","null"],"description":"CSS font-family value applied to widget text (e.g. 'Inter', 'Georgia')"},"custom_css":{"type":["string","null"],"description":"Custom CSS injected into the widget shadow DOM for advanced styling"},"dark_mode":{"type":"boolean","description":"Whether the widget renders in dark mode by default"},"border_radius":{"type":["integer","null"],"description":"CSS border-radius in pixels applied to widget cards and buttons"},"button_style":{"type":"string","enum":["filled","outlined","text"],"description":"Primary button visual style variant","default":"filled"},"analytics_mode":{"type":["string","null"],"description":"Analytics event dispatch mode (e.g. gtm, custom, null to disable)"},"analytics_callback":{"type":["string","null"],"description":"Global JavaScript function name invoked with analytics events when analytics_mode is custom"},"analytics_consent":{"type":"boolean","description":"Whether analytics event tracking requires explicit buyer consent"},"network_config":{"type":["object","null"],"description":"Widget network and retry configuration overrides (fetch_timeout, retry_max, retry_base_delay, retry_max_delay, retry_jitter, total_retry_budget, cache_products_ttl, cache_config_ttl, cache_assets_ttl, negotiate_poll_interval, negotiate_sse_timeout, heartbeat_interval, heartbeat_offline_interval, abandon_timeout). Values are milliseconds except retry_jitter; legacy aliases timeout_ms, retry_attempts, max_retries, retry_delay_ms, and cache_ttl_seconds are normalized for backward compatibility."},"signature_mode":{"type":"string","enum":["checkbox","type","draw","digital"],"description":"Method used to capture buyer signature on the terms step","default":"checkbox"},"step_order":{"type":["string","null"],"description":"Comma-separated step names defining custom widget step ordering"},"skip_steps":{"type":["string","null"],"description":"Comma-separated step names to omit from the widget flow"},"step_conditions":{"type":["object","null"],"description":"Conditional visibility rules for steps keyed by step name"},"stripe_publishable_key":{"type":["string","null"],"description":"payment publishable key (pk_live_* or pk_test_*) used by the widget to initialise the payment form for payment collection"},"base_url":{"type":"string","description":"Regional API base URL used by the widget SDK for all API calls (e.g. https://api-au.salesbooth.com)"},"region":{"type":"string","description":"Tenant data residency region code (au, eu, us)"}}},"PaymentCreateIntentRequest":{"type":"object","title":"create-intent","deprecated":true,"description":"Deprecated: use POST /payment-intent instead. Retained for backward compatibility only. Request body for the legacy action=create-intent route on POST /payments.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The deal to create a PaymentIntent for.","maxLength":255},"amount":{"type":"number","description":"Override amount in currency units. Defaults to deal balance due.","minimum":0,"maximum":99999999.99},"currency":{"type":"string","description":"ISO 4217 currency code. Defaults to deal currency.","maxLength":3}},"additionalProperties":false},"PaymentConfirmRequest":{"type":"object","title":"confirm","description":"Request body for action=confirm. Confirms that a payment intent has succeeded.","required":["deal_id","payment_intent_id"],"properties":{"deal_id":{"type":"string","description":"The deal the payment belongs to.","maxLength":255},"payment_intent_id":{"type":"string","description":"The payment intent ID to confirm.","maxLength":255}},"additionalProperties":false},"PaymentCaptureRequest":{"type":"object","title":"capture","description":"Request body for action=capture. Captures a previously-authorized PaymentIntent.","required":["deal_id","payment_intent_id"],"properties":{"deal_id":{"type":"string","description":"The deal the payment belongs to.","maxLength":255},"payment_intent_id":{"type":"string","description":"The payment intent ID to capture.","maxLength":255},"amount_to_capture":{"type":"number","description":"Amount to capture in currency units. Defaults to the full authorized amount.","minimum":0,"maximum":99999999.99}},"additionalProperties":false},"PaymentRefundRequest":{"type":"object","title":"refund","description":"Request body for action=refund. Processes a partial or full refund for a deal.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The deal to refund payment for.","maxLength":255},"amount":{"type":"number","description":"Amount to refund in currency units. Defaults to the full payment amount.","minimum":0,"maximum":99999999.99},"reason":{"type":"string","description":"Reason for the refund.","maxLength":255}},"additionalProperties":false},"PaymentRecordManualRequest":{"type":"object","title":"record-manual","description":"Request body for action=record-manual. Records a manual (non-payment provider) payment against a deal.","required":["deal_id","amount","method"],"properties":{"deal_id":{"type":"string","description":"The deal to record the payment against.","maxLength":255},"amount":{"type":"number","description":"Amount received in currency units.","minimum":0.01,"maximum":99999999.99},"method":{"type":"string","description":"Payment method used.","enum":["cash","wire","cheque","bank_transfer","other"]},"reference":{"type":"string","description":"External reference or transaction ID.","maxLength":255},"notes":{"type":"string","description":"Additional notes about the payment.","maxLength":65535}},"additionalProperties":false},"PaymentChargeSavedMethodRequest":{"type":"object","title":"charge-saved-method","description":"Request body for action=charge-saved-method. Charges a customer's saved payment method off-session (agent use).","required":["deal_id","customer_id"],"properties":{"deal_id":{"type":"string","description":"The deal to charge payment for.","maxLength":255},"customer_id":{"type":"string","description":"The customer whose saved payment method to charge.","maxLength":255},"payment_method_id":{"type":"string","description":"Specific saved payment method ID to use. Defaults to the customer's default payment method.","maxLength":255}},"additionalProperties":false},"PaymentPollIntentRequest":{"type":"object","title":"poll-intent","description":"Request body for action=poll-intent. Polls a payment intent status without requiring a webhook.","required":["payment_intent_id"],"properties":{"payment_intent_id":{"type":"string","description":"The payment intent ID to poll.","maxLength":255}},"additionalProperties":false},"PaymentGenerateLinkRequest":{"type":"object","title":"generate-link","description":"Request body for action=generate-link. Generates a hosted checkout Session URL for customer self-payment.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The deal to generate a payment link for.","maxLength":255},"success_url":{"type":"string","description":"URL to redirect the customer to after successful payment.","maxLength":2048},"cancel_url":{"type":"string","description":"URL to redirect the customer to if they cancel the payment.","maxLength":2048}},"additionalProperties":false},"PaymentSaveSettingsRequest":{"type":"object","title":"save-settings","description":"Request body for action=save-settings. Saves payment method toggles and invoice settings.","properties":{"payment_methods":{"type":"object","description":"Payment method enable/disable toggles keyed by method name."},"invoice_settings":{"type":"object","description":"Invoice generation and delivery settings."}},"additionalProperties":false},"ActivityRuleUpdateRequest":{"type":"object","description":"Request body for updating a notification rule. All fields are optional; only provided fields are updated.","properties":{"name":{"type":"string","description":"Human-readable name for the rule"},"event_type":{"type":"string","description":"Event type pattern to match (e.g. 'deal.created', '*' for all events)"},"conditions":{"type":"object","description":"Optional filter conditions applied to matching events","additionalProperties":true},"channels":{"type":"array","description":"Notification delivery channels","items":{"type":"string","enum":["in_app","email","sms","webhook"]}},"webhook_url":{"type":"string","format":"uri","description":"Webhook URL to call when the rule matches (only used when channels includes 'webhook')"},"enabled":{"type":"boolean","description":"Whether the rule is active"}},"additionalProperties":false},"PreferencesUpdateRequest":{"type":"object","description":"Request body for updating user or tenant preferences. Use the ?scope query parameter to target user preferences (language, theme) or tenant preferences (recommendations_dismissed). Recognised keys must match the documented value types; unrecognised keys are ignored.","properties":{"language":{"type":"string","description":"Preferred display language (user scope only, e.g. 'en', 'fr')"},"theme":{"type":"string","description":"Preferred UI theme (user scope only, e.g. 'light', 'dark')"},"recommendations_dismissed":{"description":"Dismissed recommendation identifiers (tenant scope only)","oneOf":[{"type":"boolean"},{"type":"array","items":{"type":"string"}}]}},"additionalProperties":true},"ProfileUpdateRequest":{"type":"object","description":"Request body for updating the current user's profile. All fields are optional; only provided fields are updated.","properties":{"first_name":{"type":"string","description":"User's first name (cannot be empty if provided)"},"last_name":{"type":"string","description":"User's last name (cannot be empty if provided)"},"phone":{"type":"string","description":"User's phone number"}},"additionalProperties":false},"SiteBlock":{"type":"object","description":"A reusable content block belonging to a site.","required":["block_id","site_id","name","slug","content","status","sort_order"],"properties":{"block_id":{"type":"string","description":"Unique identifier for the block"},"site_id":{"type":"string","description":"ID of the site this block belongs to"},"name":{"type":"string","description":"Display name for the block"},"slug":{"type":"string","description":"URL-safe identifier for the block (unique within the site)"},"category":{"type":["string","null"],"description":"Category label used for organising blocks"},"content":{"type":"string","description":"HTML or structured content for the block"},"status":{"type":"string","enum":["active","draft","disabled"],"description":"Publication status of the block"},"description":{"type":["string","null"],"description":"Optional description of the block's purpose"},"sort_order":{"type":"integer","description":"Display order relative to other blocks in the same category"},"created_at":{"type":["string","null"],"description":"ISO 8601 timestamp of when the block was created"},"updated_at":{"type":["string","null"],"description":"ISO 8601 timestamp of when the block was last updated"}},"additionalProperties":false},"SiteBlockUpdateRequest":{"type":"object","description":"Request body for updating a site block. All fields are optional; only provided fields are updated.","properties":{"name":{"type":"string","description":"Display name for the block"},"slug":{"type":"string","description":"URL-safe identifier for the block (must be unique within the site)"},"category":{"type":"string","description":"Category label used for organising blocks"},"content":{"type":"string","description":"HTML or structured content for the block"},"status":{"type":"string","enum":["active","draft","disabled"],"description":"Publication status of the block"},"description":{"type":"string","description":"Optional description of the block's purpose"},"sort_order":{"type":"integer","description":"Display order relative to other blocks in the same category"}},"additionalProperties":false},"SitePage":{"type":"object","description":"A hosted site page belonging to a site.","required":["page_id","site_id","slug","title","status","is_homepage","version","created_at","updated_at"],"properties":{"page_id":{"type":"string","description":"Unique identifier for the page"},"site_id":{"type":"string","description":"ID of the site this page belongs to"},"slug":{"type":"string","description":"URL slug for the page"},"title":{"type":"string","description":"Page title"},"status":{"type":"string","enum":["published","draft","disabled"],"description":"Publication status of the page"},"is_homepage":{"type":"boolean","description":"Whether this page is the site's homepage"},"source":{"type":["string","null"],"description":"Rendered source content for the page"},"dev_source":{"type":["string","null"],"description":"Editable development source for the page"},"meta_title":{"type":["string","null"],"description":"SEO meta title for the page"},"meta_description":{"type":["string","null"],"description":"SEO meta description for the page"},"version":{"type":"integer","description":"Version number of the page revision"},"created_at":{"type":"string","format":"date-time","description":"ISO 8601 timestamp of when the page was created"},"updated_at":{"type":"string","format":"date-time","description":"ISO 8601 timestamp of when the page was last updated"},"published_at":{"type":["string","null"],"format":"date-time","description":"ISO 8601 timestamp of when the page was published, if published"}},"additionalProperties":false},"SubscriptionDetail":{"type":"object","description":"Composite subscription detail returned by GET /subscriptions?id={deal_id}. Contains the subscription billing metadata, the full deal object, renewal chain history, payment attempt history, and lifecycle events.","properties":{"subscription":{"type":"object","description":"Subscription billing metadata for the deal.","properties":{"deal_id":{"type":"string","description":"The subscription deal ID"},"root_deal_id":{"type":"string","description":"The root/original deal ID in the renewal chain (equals deal_id for the first deal in the chain)"},"deal_type":{"type":"string","const":"recurring","description":"Always 'recurring' for subscriptions"},"billing_cycle":{"type":["string","null"],"enum":["monthly","quarterly","annual",null],"description":"Billing cadence"},"subscription_status":{"type":["string","null"],"enum":["active","paused","cancelled","past_due","suspended",null],"description":"Current lifecycle status of the subscription"},"next_billing_date":{"type":["string","null"],"format":"date","description":"Date of the next scheduled billing charge"},"billing_period_start":{"type":["string","null"],"format":"date","description":"Start of the current billing period"},"billing_period_end":{"type":["string","null"],"format":"date","description":"End of the current billing period"},"retry_count":{"type":"integer","description":"Number of failed payment retry attempts in the current billing period"},"max_retry_attempts":{"type":"integer","description":"Maximum number of payment retries before the subscription is suspended (currently 3)"},"dunning_schedule":{"type":"array","items":{"type":"integer"},"description":"Days after the initial payment failure at which each retry attempt is scheduled (e.g. [1, 3, 7])"},"next_retry_at":{"type":["string","null"],"format":"date-time","description":"Timestamp of the next scheduled payment retry attempt (null when the subscription is not past-due)"},"renewal_count":{"type":"integer","description":"Total number of successful renewals since subscription creation"},"cancel_at_period_end":{"type":"boolean","description":"Whether the subscription is scheduled to cancel at the end of the current billing period"}},"required":["deal_id","root_deal_id","deal_type","retry_count","max_retry_attempts","dunning_schedule","renewal_count","cancel_at_period_end"]},"deal":{"$ref":"#/components/schemas/Deal"},"renewal_history":{"type":"array","description":"Ordered list of all deals in the renewal chain (root → latest renewal), sorted by renewal_count ascending","items":{"type":"object","properties":{"deal_id":{"type":"string","description":"Deal ID for this renewal cycle"},"status":{"type":["string","null"],"enum":["draft","in_progress","pending_payment","pending_signature","awaiting_signatures","partially_accepted","closed","cancelled","expired",null],"description":"Deal status"},"subscription_status":{"type":["string","null"],"enum":["active","paused","cancelled","past_due","suspended",null],"description":"Subscription lifecycle status for this renewal cycle"},"total":{"type":["number","null"],"description":"Total amount charged for this renewal cycle"},"renewal_count":{"type":["integer","null"],"description":"Renewal sequence number (0 = original deal, 1 = first renewal, etc.)"},"next_billing_date":{"type":["string","null"],"format":"date","description":"Next billing date associated with this renewal"},"created_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when this renewal deal was created"},"completed_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when this renewal deal was completed"}},"required":["deal_id"]}},"renewal_attempts":{"type":"array","description":"Payment attempt history from the subscription_renewals table, most recent first (up to 50 records)","items":{"type":"object","properties":{"renewal_id":{"type":"string","description":"Unique renewal attempt identifier"},"deal_id":{"type":"string","description":"The subscription deal this attempt belongs to"},"billing_period_start":{"type":["string","null"],"format":"date","description":"Billing period start date for this attempt"},"billing_period_end":{"type":["string","null"],"format":"date","description":"Billing period end date for this attempt"},"amount":{"type":["number","null"],"description":"Amount charged in this renewal attempt"},"currency":{"type":["string","null"],"maxLength":3,"description":"ISO 4217 currency code"},"payment_intent_id":{"type":["string","null"],"description":"payment intent ID for this attempt"},"renewal_deal_id":{"type":["string","null"],"description":"Deal ID created for this renewal cycle (if a new deal was generated)"},"status":{"type":"string","enum":["succeeded","failed","pending"],"description":"Outcome of this renewal attempt"},"attempt_number":{"type":["integer","null"],"description":"Attempt sequence number (1 = initial charge, 2+ = dunning retries)"},"error_message":{"type":["string","null"],"description":"Error message if the attempt failed"},"created_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when this attempt was recorded"}},"required":["renewal_id","deal_id","status"]}},"events":{"type":"array","description":"Subscription lifecycle events for this deal, most recent first (up to 50 records)","items":{"type":"object","properties":{"event_id":{"type":"string","description":"Unique event identifier"},"event_type":{"type":"string","description":"Type of subscription event (e.g. created, renewed, paused, resumed, cancelled, payment_failed, payment_retry_succeeded)"},"event_data":{"type":["object","null"],"description":"Additional data associated with the event (structure varies by event_type)"},"created_at":{"type":"string","format":"date-time","description":"Timestamp when the event was recorded"}},"required":["event_id","event_type","created_at"]}}},"required":["subscription","deal","renewal_history","renewal_attempts","events"]},"SubscriptionListItem":{"type":"object","description":"A subscription item returned by GET /subscriptions. Represents a recurring deal with subscription billing metadata.","properties":{"deal_id":{"type":"string","description":"Unique identifier for the deal"},"customer_id":{"type":"string","description":"Identifier of the customer associated with this subscription"},"status":{"type":"string","enum":["draft","in_progress","pending_payment","pending_signature","awaiting_signatures","partially_accepted","closed","cancelled","expired"],"description":"Deal status"},"deal_type":{"type":"string","const":"recurring","description":"Always 'recurring' for subscriptions"},"billing_cycle":{"type":["string","null"],"enum":["monthly","quarterly","annual",null],"description":"Billing cadence for the subscription"},"subscription_status":{"type":["string","null"],"enum":["active","paused","cancelled","past_due","suspended",null],"description":"Current lifecycle status of the subscription"},"next_billing_date":{"type":["string","null"],"format":"date","description":"Date of the next scheduled billing charge"},"billing_period_start":{"type":["string","null"],"format":"date","description":"Start date of the current billing period"},"billing_period_end":{"type":["string","null"],"format":"date","description":"End date of the current billing period"},"retry_count":{"type":["integer","null"],"description":"Number of payment retry attempts for the current billing period"},"renewal_count":{"type":["integer","null"],"description":"Total number of successful renewals since subscription creation"},"parent_deal_id":{"type":["string","null"],"description":"ID of the root/original subscription deal in the renewal chain"},"total":{"type":["string","null"],"description":"Raw decimal string from the database (e.g. \"449.00\"). Total amount charged per billing cycle."},"currency":{"type":["string","null"],"maxLength":3,"description":"ISO 4217 currency code"},"created_at":{"type":["string","null"],"format":"date-time","description":"Timestamp when the deal was created"},"customer_name":{"type":["string","null"],"description":"Display name of the customer"},"customer_email":{"type":["string","null"],"format":"email","description":"Email address of the customer"}},"required":["deal_id","customer_id","status","deal_type"]},"SubscriptionProrationPreview":{"type":"object","description":"Cycle-change proration preview returned by GET /subscriptions?id={deal_id}&preview_cycle={cycle}. Summarizes the current and requested billing cycles, projected totals, prorated delta, remaining days, next billing date, and currency without mutating the subscription.","properties":{"old_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"Current billing cycle on the subscription before the requested change"},"new_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"Requested new billing cycle being previewed"},"old_total":{"type":"number","description":"Current subscription total for the existing billing cycle"},"new_total":{"type":"number","description":"Projected subscription total for the requested billing cycle"},"proration_amount":{"type":"number","description":"Net proration adjustment amount for the remaining portion of the cycle"},"credit_amount":{"type":"number","description":"Unused credit from the current cycle applied toward the requested cycle change"},"remaining_days":{"type":"integer","description":"Number of days remaining until the current next_billing_date"},"new_next_billing_date":{"type":"string","format":"date","description":"Projected next billing date for the requested billing cycle"},"currency":{"type":"string","maxLength":3,"description":"ISO 4217 currency code for the previewed totals and proration amounts"}},"required":["old_cycle","new_cycle","old_total","new_total","proration_amount","credit_amount","remaining_days","new_next_billing_date","currency"]},"SubscriptionMeter":{"type":"object","description":"A usage meter added to a subscription for metered billing. Returned by POST /subscriptions with action=add-meter.","properties":{"meter_id":{"type":"string","description":"Unique meter identifier (e.g. mtr_abc123)"},"subscription_deal_id":{"type":"string","description":"The subscription deal this meter is attached to"},"metric_name":{"type":"string","description":"Name of the metric being tracked (e.g. api_calls, seats, storage_gb)"},"billing_model":{"type":"string","enum":["per_unit","tiered","volume"],"description":"Billing model for this meter"},"unit_price":{"type":"number","description":"Price per unit (for per_unit model)"},"included_quantity":{"type":"number","description":"Free units included in the base subscription before billing begins"},"tiers":{"type":["array","null"],"items":{"type":"object","properties":{"up_to":{"type":["number","null"],"description":"Upper bound for this tier (null = unlimited)"},"unit_price":{"type":"number","description":"Price per unit in this tier"}}},"description":"Pricing tiers (for tiered/volume billing models)"},"currency":{"type":"string","maxLength":3,"description":"ISO 4217 currency code for billing"},"status":{"type":"string","enum":["active","archived"],"description":"Meter status"}},"required":["meter_id","subscription_deal_id","metric_name","billing_model","status"]},"SubscriptionMeterArchived":{"type":"object","description":"Confirmation that a usage meter has been archived. Returned by POST /subscriptions with action=remove-meter.","properties":{"meter_id":{"type":"string","description":"The meter that was archived"},"status":{"type":"string","const":"archived","description":"Always 'archived'"}},"required":["meter_id","status"]},"SubscriptionUsageRecord":{"type":"object","description":"A recorded usage event for metered billing. Returned by POST /subscriptions with action=record-usage.","properties":{"usage_id":{"type":"string","description":"Unique usage record identifier"},"meter_id":{"type":"string","description":"The meter this usage was recorded against"},"deal_id":{"type":"string","description":"The subscription deal"},"metric_name":{"type":"string","description":"Name of the metric recorded"},"quantity":{"type":"number","description":"Usage quantity recorded"},"idempotency_key":{"type":["string","null"],"description":"Client-provided deduplication key"},"metadata":{"type":["object","null"],"description":"Optional metadata associated with this usage event"},"recorded_at":{"type":"string","format":"date-time","description":"Timestamp when the usage was recorded"},"billing_cycle_start":{"type":"string","format":"date","description":"Start of the billing cycle this usage is attributed to"},"billing_cycle_end":{"type":"string","format":"date","description":"End of the billing cycle this usage is attributed to"},"duplicate":{"type":"boolean","description":"True if this record was deduplicated via idempotency_key (existing record returned)"}},"required":["usage_id","meter_id","deal_id","metric_name","quantity","recorded_at"]},"SubscriptionUsageBatch":{"type":"object","description":"Batch usage recording result. Returned by POST /subscriptions with action=record-usage when a records array is supplied.","properties":{"records":{"type":"array","items":{"$ref":"#/components/schemas/SubscriptionUsageRecord"},"description":"Array of recorded usage entries, one per input record"},"count":{"type":"integer","description":"Number of usage records created"}},"required":["records","count"]},"SubscriptionAnalytics":{"type":"object","description":"Subscription analytics KPIs for the tenant, calculated over a 30-day window. Returned by GET /subscriptions?action=analytics.","properties":{"mrr":{"type":"number","description":"Monthly Recurring Revenue — all active subscription amounts normalized to a monthly figure regardless of billing cycle"},"arr":{"type":"number","description":"Annual Recurring Revenue (MRR × 12)"},"active_subscriptions":{"type":"integer","description":"Count of subscriptions currently in 'active' status"},"churn_rate":{"type":"number","description":"Percentage of subscriptions cancelled in the last 30 days relative to the starting subscription count"},"expansion_revenue":{"type":"number","description":"Net revenue gained from subscription upgrades (plan changes to higher-value plans) in the last 30 days"},"contraction_revenue":{"type":"number","description":"Net revenue lost from subscription downgrades (plan changes to lower-value plans) in the last 30 days"},"net_revenue_retention":{"type":"number","description":"Net Revenue Retention as a percentage ((current MRR / starting MRR) × 100), accounting for expansion, contraction, and churn"},"renewals_last_30_days":{"type":"integer","description":"Number of successful subscription renewals completed in the last 30 days"},"cancellations_last_30_days":{"type":"integer","description":"Number of subscription cancellations in the last 30 days"},"status_breakdown":{"type":"object","description":"Count of subscriptions keyed by subscription_status (active, paused, cancelled, past_due, suspended)","additionalProperties":{"type":"integer"}},"period":{"type":"string","const":"30_days","description":"The analytics window (always '30_days')"}},"required":["mrr","arr","active_subscriptions","churn_rate","expansion_revenue","contraction_revenue","net_revenue_retention","renewals_last_30_days","cancellations_last_30_days","status_breakdown","period"]},"SubscriptionUsageSummary":{"type":"object","description":"Current billing cycle usage summary for a specific subscription, including per-meter quantities and projected invoice total. Returned by GET /subscriptions?action=usage_summary&id={deal_id}.","properties":{"subscription_deal_id":{"type":"string","description":"The deal ID of the subscription"},"billing_cycle":{"type":"object","description":"Current billing cycle date range","properties":{"start":{"type":"string","format":"date","description":"Start date of the current billing cycle (YYYY-MM-DD)"},"end":{"type":"string","format":"date","description":"End date of the current billing cycle (YYYY-MM-DD)"}},"required":["start","end"]},"base_amount":{"type":"number","description":"Base subscription charge for the current cycle, excluding metered usage"},"meters":{"type":"array","description":"Per-meter usage breakdown for the current billing cycle","items":{"type":"object","properties":{"meter_id":{"type":"string","description":"Unique meter identifier"},"metric_name":{"type":"string","description":"Name of the metric being tracked (e.g. api_calls, seats, storage_gb)"},"billing_model":{"type":"string","enum":["per_unit","tiered","volume"],"description":"Billing model applied to this meter"},"total_quantity":{"type":"number","description":"Total units consumed in the current billing cycle"},"included_quantity":{"type":"number","description":"Units included in the base subscription before per-unit billing begins"},"billable_quantity":{"type":"number","description":"Units subject to usage charges (total_quantity minus included_quantity, minimum 0)"},"unit_price":{"type":"number","description":"Price per unit (applicable for per_unit billing model)"},"tiers":{"type":["array","null"],"description":"Pricing tiers (applicable for tiered or volume billing models)","items":{"type":"object","properties":{"up_to":{"type":["number","null"],"description":"Upper bound for this tier (null = unlimited)"},"unit_price":{"type":"number","description":"Price per unit in this tier"}}}},"charge":{"type":"number","description":"Calculated usage charge for this meter in the current cycle"},"currency":{"type":"string","maxLength":3,"description":"ISO 4217 currency code for this meter's charges"},"event_count":{"type":"integer","description":"Number of individual usage events recorded in the current cycle"}},"required":["meter_id","metric_name","billing_model","total_quantity","included_quantity","billable_quantity","charge","currency","event_count"]}},"total_usage_charges":{"type":"number","description":"Sum of all meter charges for the current billing cycle"},"projected_total":{"type":"number","description":"Projected total invoice amount for the current cycle (base_amount + total_usage_charges)"},"currency":{"type":"string","maxLength":3,"description":"ISO 4217 currency code for the subscription"}},"required":["subscription_deal_id","billing_cycle","base_amount","meters","total_usage_charges","projected_total","currency"]},"SubscriptionUsageHistory":{"type":"object","description":"Paginated list of historical usage records for a subscription, ordered most-recent first. Returned by GET /subscriptions?action=usage_history&id={deal_id}. Supports optional filtering by metric name and limit/offset pagination.","properties":{"records":{"type":"array","description":"Usage records, ordered by recorded_at descending","items":{"type":"object","properties":{"record_id":{"type":"string","description":"Unique usage record identifier"},"meter_id":{"type":"string","description":"The meter this usage was recorded against"},"metric_name":{"type":"string","description":"Name of the metric that was recorded"},"quantity":{"type":"number","description":"Usage quantity for this record"},"idempotency_key":{"type":["string","null"],"description":"Client-supplied deduplication key (if provided when the usage was recorded)"},"billing_cycle_start":{"type":"string","format":"date","description":"Start of the billing cycle this record is attributed to (YYYY-MM-DD)"},"billing_cycle_end":{"type":"string","format":"date","description":"End of the billing cycle this record is attributed to (YYYY-MM-DD)"},"metadata":{"type":["object","null"],"description":"Optional metadata that was supplied when the usage was recorded"},"recorded_at":{"type":"string","format":"date-time","description":"Timestamp when the usage event was recorded"}},"required":["record_id","meter_id","metric_name","quantity","billing_cycle_start","billing_cycle_end","recorded_at"]}},"total":{"type":"integer","description":"Total number of usage records matching the query (before pagination)"},"limit":{"type":"integer","description":"Page size used for this response (max 1000, default 100)"},"offset":{"type":"integer","description":"Offset applied to this response"}},"required":["records","total","limit","offset"]},"SubscriptionMeters":{"type":"object","description":"List of active usage meters attached to a subscription. Only meters with status='active' are returned. Returned by GET /subscriptions?action=meters&id={deal_id}.","properties":{"meters":{"type":"array","description":"Active meters for this subscription, ordered by creation time","items":{"type":"object","properties":{"meter_id":{"type":"string","description":"Unique meter identifier"},"metric_name":{"type":"string","description":"Name of the metric being tracked (e.g. api_calls, seats, storage_gb)"},"billing_model":{"type":"string","enum":["per_unit","tiered","volume"],"description":"Billing model applied to this meter"},"unit_price":{"type":"number","description":"Price per unit (applicable for per_unit billing model)"},"included_quantity":{"type":"number","description":"Free units included in the base subscription before per-unit billing begins"},"tiers":{"type":["array","null"],"description":"Pricing tiers (applicable for tiered or volume billing models)","items":{"type":"object","properties":{"up_to":{"type":["number","null"],"description":"Upper bound for this tier (null = unlimited)"},"unit_price":{"type":"number","description":"Price per unit in this tier"}}}},"currency":{"type":"string","maxLength":3,"description":"ISO 4217 currency code for this meter's charges"},"status":{"type":"string","const":"active","description":"Always 'active' — only active meters are returned by this action"},"created_at":{"type":"string","format":"date-time","description":"Timestamp when the meter was created"}},"required":["meter_id","metric_name","billing_model","status"]}}},"required":["meters"]},"OptionGroup":{"type":"object","description":"A configuration option group attached to a product, as returned by ProductConfigService::formatOptionGroup(). Each group contains a set of selectable options (returned separately as `options` when the product action=options endpoint embeds them).","properties":{"group_id":{"type":"string","description":"Unique option group identifier","examples":["grp_a1b2c3d4e5f6"]},"name":{"type":"string","description":"Display name of the option group"},"description":{"type":["string","null"],"description":"Optional description shown to the buyer"},"selection_type":{"type":"string","enum":["single","multiple"],"description":"Whether the buyer can select one or many options"},"is_required":{"type":"boolean","description":"Whether the buyer must make a selection before proceeding"},"min_selections":{"type":"integer","minimum":0,"description":"Minimum number of options that must be selected (for multiple selection_type)"},"max_selections":{"type":["integer","null"],"minimum":1,"description":"Maximum number of options that may be selected, or null for unlimited"},"display_style":{"type":"string","enum":["pills","cards","swatches","checkboxes","dropdown","text_input"],"description":"Visual presentation style used in the widget"},"sort_order":{"type":"integer","description":"Display ordering position (ascending)"},"status":{"type":"string","enum":["active","inactive"],"description":"Whether the group is active and shown in the widget"},"version":{"type":"integer","minimum":1,"description":"Optimistic locking version"},"created_at":{"type":"string","format":"date-time","description":"ISO 8601 creation timestamp"},"updated_at":{"type":"string","format":"date-time","description":"ISO 8601 last-update timestamp"}},"required":["group_id","name","selection_type","is_required","min_selections","max_selections","display_style","sort_order","status","version","created_at","updated_at"]},"StaffMember":{"type":"object","description":"A staff member record","properties":{"staff_id":{"type":"string","example":"stf_abc123def456"},"display_name":{"type":"string"},"title":{"type":["string","null"]},"status":{"type":"string","enum":["active","inactive"]},"avatar_url":{"type":["string","null"]},"max_daily_sessions":{"type":"integer","description":"Maximum bookings per day","example":8},"default_session_duration":{"type":"integer","description":"Default session duration in minutes","example":60},"buffer_time":{"type":"integer","description":"Buffer time between sessions in minutes","example":15},"timezone":{"type":"string","example":"UTC"},"created_at":{"type":"string","format":"date-time"},"bio":{"type":["string","null"],"description":"Staff bio — only present when fetching a single staff member"},"user_id":{"type":["string","null"],"description":"Linked user account ID — only present when fetching a single staff member"},"metadata":{"type":["object","null"],"description":"Arbitrary metadata — only present when fetching a single staff member"},"updated_at":{"type":"string","format":"date-time","description":"Only present when fetching a single staff member"},"schedule":{"type":"array","description":"Weekly schedule entries — only present when fetching a single staff member","items":{"type":"object","properties":{"day_of_week":{"type":"integer","minimum":0,"maximum":6,"description":"0 = Sunday, 6 = Saturday"},"start_time":{"type":"string","description":"Start time in HH:MM:SS format"},"end_time":{"type":"string","description":"End time in HH:MM:SS format"},"is_available":{"type":"boolean"}},"required":["day_of_week","is_available"]}},"overrides":{"type":"array","description":"Date-specific schedule overrides — only present when fetching a single staff member","items":{"type":"object","properties":{"override_date":{"type":"string","format":"date","description":"The specific date this override applies to (YYYY-MM-DD)"},"start_time":{"type":["string","null"],"description":"Start time in HH:MM:SS format; null when is_available is false"},"end_time":{"type":["string","null"],"description":"End time in HH:MM:SS format; null when is_available is false"},"is_available":{"type":"boolean"}},"required":["override_date","is_available"]}},"products":{"type":"array","description":"Product assignments — only present when fetching a single staff member","items":{"type":"object","properties":{"product_id":{"type":"string","description":"ID of the assigned product"},"product_name":{"type":["string","null"],"description":"Display name of the product"},"priority":{"type":"integer","description":"Sort priority — higher values appear first"},"session_duration_override":{"type":["integer","null"],"description":"Per-product session duration override in minutes; null uses the staff member's default"}},"required":["product_id","priority"]}}},"required":["staff_id","display_name","status","max_daily_sessions","default_session_duration","buffer_time","timezone","created_at"]},"StaffListResponse":{"type":"object","description":"Response from GET /staff (list mode — no id parameter). Returns a paginated array of staff members.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"staff":{"type":"array","items":{"$ref":"#/components/schemas/StaffMember"},"description":"Array of staff members matching the query"},"pagination":{"type":"object","description":"Pagination metadata","properties":{"total":{"type":"integer","description":"Total number of staff members matching the filter"},"limit":{"type":"integer","description":"Page size"},"offset":{"type":"integer","description":"Number of records skipped"},"count":{"type":"integer","description":"Number of records returned in this page"}},"required":["total","limit","offset","count"]}},"required":["staff","pagination"]}},"required":["error","success","data"]},"StaffDetailResponse":{"type":"object","description":"Response from GET /staff?id={id} (detail mode). Returns a single staff member with full details including schedule, overrides and product assignments.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"staff":{"$ref":"#/components/schemas/StaffMember"}},"required":["staff"]}},"required":["error","success","data"]},"StaffScheduleActionResponse":{"type":"object","description":"Response from POST /staff?action=schedule — returns the updated weekly schedule","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"schedule":{"type":"array","description":"The full updated weekly schedule entries","items":{"type":"object","properties":{"day_of_week":{"type":"integer","minimum":0,"maximum":6,"description":"0=Sunday … 6=Saturday"},"start_time":{"type":"string","description":"HH:MM format"},"end_time":{"type":"string","description":"HH:MM format"},"is_available":{"type":"boolean"}}}}},"required":["schedule"]}},"required":["error","success","data"]},"StaffWriteResponse":{"type":"object","description":"Response from POST /staff or PATCH /staff (no action) — returns the created or updated staff member","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"staff":{"$ref":"#/components/schemas/StaffMember"}},"required":["staff"]}},"required":["error","success","data"]},"StaffOverrideUpdateResponse":{"type":"object","description":"Response from PATCH /staff?action=override — returns the updated schedule override","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"override":{"type":"object","description":"The updated schedule override","properties":{"id":{"type":"integer","description":"Unique override ID"},"staff_id":{"type":"string","description":"Staff member ID"},"override_date":{"type":"string","format":"date","description":"The specific date this override applies to (YYYY-MM-DD)"},"start_time":{"type":["string","null"],"description":"Start time in HH:MM format; null when is_available is false"},"end_time":{"type":["string","null"],"description":"End time in HH:MM format; null when is_available is false"},"is_available":{"type":"boolean","description":"Whether the staff member is available on this date"},"reason":{"type":["string","null"],"description":"Optional reason for the override"}},"required":["id","staff_id","override_date","is_available"]}},"required":["override"]}},"required":["error","success","data"]},"AvailabilityResponse":{"type":"object","description":"Response from GET /availability. When `date` is provided returns `slots[]`; when `month` is provided returns `dates[]`.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"slots":{"type":"array","description":"Available time slots — present when `date` query param is used","items":{"type":"object","properties":{"start_time":{"type":"string","example":"09:00:00","description":"Slot start time in HH:MM:SS format (24-hour)"},"end_time":{"type":"string","example":"10:00:00","description":"Slot end time in HH:MM:SS format (24-hour)"},"staff_id":{"type":"string","example":"stf_abc123def456"},"staff_name":{"type":"string"},"duration":{"type":"integer","description":"Slot duration in minutes"}},"required":["start_time","end_time","staff_id","staff_name","duration"]}},"dates":{"type":"array","description":"Dates with at least one available slot — present when `month` query param is used","items":{"type":"string","format":"date","example":"2026-04-15"}},"date":{"type":"string","format":"date","description":"The requested date — present when `date` query param is used"},"month":{"type":"string","pattern":"^\\d{4}-\\d{2}$","description":"The requested month (YYYY-MM) — present when `month` query param is used"},"product_id":{"type":"string","description":"The product ID that was queried"},"message":{"type":"string","description":"Human-readable message (e.g. 'No staff assigned', 'Date is too soon')"}}}},"required":["error","success","data"]},"WebhookEventType":{"type":"string","description":"A supported webhook event type. Subscribe to these events when creating or updating a webhook endpoint.","enum":["deal.created","deal.status_changed","deal.closed","deal.fulfilled","deal.expired","deal.unsigned","deal.updated","deal.item_added","deal.item_removed","deal.item_updated","deal.discount_applied","deal.partially_accepted","deal.signature_added","deal.created_configured","deal.payment_received","deal.payment_failed","deal.payment_refunded","deal.payment_overdue","deal.negotiation_proposed","deal.negotiation_counter_proposed","deal.negotiation_accepted","deal.negotiation_rejected","negotiation.expired","negotiation.proposed","negotiation.countered","negotiation.accepted","negotiation.rejected","negotiation.suggestion_generated","contract.signed","contract.activated","contract.terminated","contract.tamper_detected","contract.auto_renewed","contract.renewal_failed","contract.renewal_opted_out","contract.renewal_upcoming","customer.created","customer.updated","customer.deleted","payment.received","escrow.created","escrow.released","escrow.refunded","escrow.condition_fulfilled","escrow.reauthorization_pending","escrow.reauthorized","escrow.reauthorization_failed","credential.issued","subscription.created","subscription.renewed","subscription.renewal_upcoming","subscription.paused","subscription.resumed","subscription.cancelled","subscription.upgraded","subscription.downgraded","subscription.changed","subscription.past_due","subscription.suspended","subscription.cycle_changed","subscription.payment_failed","subscription.payment_retried","subscription.proration_credit","subscription.meter_added","subscription.meter_removed","subscription.usage_recorded","subscription.usage_charges_applied","product_family.created","product_family.updated","product_family.deleted","option_group.created","option_group.updated","option_group.deleted","option.created","option.updated","option.deleted","compatibility_rule.created","compatibility_rule.updated","compatibility_rule.deleted","bundle_rule.created","bundle_rule.updated","bundle_rule.deleted","billing.low_balance","billing.credit_added","billing.credit_deducted","billing.auto_topup","billing.widget_degraded","tenant.trust_level_changed","tenant.trust_promoted","tenant.trust_level_decay_warning","service.circuit_opened","service.circuit_closed","circuit-breaker.backoff-increased","saved_config.created","saved_config.viewed","saved_config.converted","saved_config.expiring","saved_config.expired","security.csp_spike","agent.workflow.planned","agent.workflow.completed","agent.workflow.failed","agent.workflow.step_completed","agent.workflow.step_retried","agent.workflow.dead_lettered","agent.workflow.cancelled","agent.workflow.degraded","agent.workflow.approved","workflow.sell.proposal_received","workflow.fulfill.delivered","workflow.step_approved","agent.approval_required","agent.approval_resent","agent.approval_escalated","agent.trust.level_changed","agent.trust.abuse_detected","agent.trust.decay_warning","agent.trust.credential_issued","agent.trust.credential_presented","agent.trust.credential_revoked","agent.trust_cap_exceeded","agent.anomaly_detected","agent.spending_ceiling","system.job_dead_letter","job.completed","job.failed","queue.depth_alert","trust.demoted","trust.fraud_signal","booking.created","booking.cancelled","booking.completed","booking.no_show","booking.held","booking.hold_expired","booking.rescheduled","consent.expiring_soon","consent.expired","api_key.rotated","deal.settlement_initiated","deal.settlement_completed","deal.settlement_failed","deal.settlement_all_completed","deal.participant_invited","deal.participant_accepted","deal.participant_withdrawn","deal.participant_completed","deal.settlement_created","deal.signature_timeout","federation.settlement_completed","federation.settlement_failed","federation.escrow_disputed","federation.escrow_expired","portal.payment_completed","portal.contract_signed","portal.change_requested","encryption.rekey_completed","delegation.granted","delegation.revoked","delegation.proposed","delegation.accepted","delegation.rejected","delegation.countered","delegation.expired","delegation.budget_warning"]},"DealParticipant":{"type":"object","description":"A participant in a multi-agent deal","properties":{"id":{"type":"string","description":"Participant ID (part_...)"},"deal_id":{"type":"string"},"agent_api_key_id":{"type":"integer","description":"Internal API key ID of the agent"},"agent_name":{"type":["string","null"],"description":"Display name of the agent API key"},"agent_key_id":{"type":["string","null"],"description":"Public key_id identifier of the agent API key"},"delegation_id":{"type":["string","null"],"description":"Delegation ID if participant was invited via a delegation"},"role":{"type":"string","enum":["primary","subcontractor","reviewer","observer","required_signer"],"description":"primary=deal owner; subcontractor=blocks close until complete; reviewer=view+comment; observer=read-only; required_signer=must sign before close"},"scope_description":{"type":["string","null"],"description":"Description of this participant's assigned scope or responsibilities"},"line_item_ids":{"type":["array","null"],"items":{"type":"string"},"description":"Line item IDs assigned to this participant"},"revenue_share_percent":{"type":["number","null"],"minimum":0,"maximum":100,"description":"Percentage of deal revenue allocated to this participant"},"revenue_share_fixed":{"type":["number","null"],"minimum":0,"description":"Fixed amount of deal revenue allocated to this participant"},"status":{"type":"string","enum":["invited","accepted","active","completed","withdrawn"],"description":"Current lifecycle status of the participant"},"invited_at":{"type":"string","format":"date-time","description":"When the participant was invited"},"accepted_at":{"type":["string","null"],"format":"date-time","description":"When the participant accepted the invitation"},"completed_at":{"type":["string","null"],"format":"date-time","description":"When the participant marked their scope as complete"}},"required":["id","deal_id","agent_api_key_id","role","status","invited_at"]},"DealParticipantResponse":{"type":"object","description":"Response envelope for a single deal participant (invite, accept, complete, update, or remove actions)","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true},"data":{"$ref":"#/components/schemas/DealParticipant"}},"required":["error","success","data"]},"BillingTopupRequest":{"type":"object","title":"topup","description":"Request body for action=topup. Creates a hosted checkout session to add credits to the tenant account.","required":["amount","success_url","cancel_url"],"properties":{"amount":{"type":"number","description":"Top-up amount in USD. Must be between $5.00 and $10,000.00.","minimum":5,"maximum":10000,"example":50},"success_url":{"type":"string","description":"URL to redirect the user to after a successful payment.","maxLength":2048,"example":"https://app.example.com/billing?topup=success"},"cancel_url":{"type":"string","description":"URL to redirect the user to if they cancel the payment.","maxLength":2048,"example":"https://app.example.com/billing?topup=cancelled"}},"additionalProperties":false},"BillingAutoTopupRequest":{"type":"object","title":"auto-topup","description":"Request body for action=auto-topup. Enables or disables automatic credit top-up when balance falls low. When enabling, `amount` and `payment_method_id` are also required.","required":["enabled"],"properties":{"enabled":{"type":"boolean","description":"Whether to enable (true) or disable (false) automatic top-up."},"amount":{"type":"number","description":"Auto top-up amount in USD. Required when `enabled` is true. Must be at least $5.00.","minimum":5,"example":20},"payment_method_id":{"type":"string","description":"saved payment method ID to charge for auto top-ups. Required when `enabled` is true. Obtain a payment method by calling action=setup-intent first.","maxLength":255,"example":"pm_1OqLh2LkdIwHu7ixEBHGHpNK"}},"additionalProperties":false},"BillingSetupIntentRequest":{"type":"object","title":"setup-intent","description":"Request body for action=setup-intent. Creates a payment setup intent to save a payment method for future auto top-ups. No body fields are required.","properties":[],"additionalProperties":false},"BillingAlertSettingsRequest":{"type":"object","title":"alert-settings","description":"Request body for action=alert-settings. Updates low-balance alert thresholds and notification channel preferences. All fields are optional; omitted fields retain their current values.","properties":{"threshold":{"type":"number","description":"Credit balance threshold (in USD) below which alerts are triggered. Must be non-negative.","minimum":0,"example":10},"email_enabled":{"type":"boolean","description":"Whether to send low-balance alert emails."},"webhook_enabled":{"type":"boolean","description":"Whether to fire a webhook event on low-balance alerts."}},"additionalProperties":false},"BillingTopupResponse":{"type":"object","title":"topup","description":"Response data for action=topup. Contains a hosted checkout session URL the user should be redirected to in order to complete the credit top-up payment.","properties":{"checkout_url":{"type":["string","null"],"format":"uri","description":"hosted checkout session URL to redirect the user to. Null if the session could not be created."},"session_id":{"type":["string","null"],"description":"hosted checkout session ID. Can be used to verify payment completion via webhook."},"amount":{"type":"number","description":"The top-up amount in USD that was requested."}},"required":["checkout_url","session_id","amount"]},"BillingAutoTopupResponse":{"type":"object","title":"auto-topup","description":"Response data for action=auto-topup. Returns the updated auto top-up configuration. When enabling, includes the trust ceiling and current monthly usage; when disabling, only includes the enabled flag and a confirmation message.","properties":{"auto_topup_enabled":{"type":"boolean","description":"Whether automatic top-up is now enabled (true) or disabled (false)."},"auto_topup_amount":{"type":"number","description":"The configured auto top-up amount in USD. Only present when auto_topup_enabled is true."},"ceiling":{"type":["number","null"],"description":"Monthly spending ceiling in USD enforced by the tenant's current trust level. Null means no ceiling (Trust Level 5). Only present when auto_topup_enabled is true."},"monthly_used":{"type":"number","description":"Amount in USD already charged via auto top-up this calendar month. Only present when auto_topup_enabled is true."},"message":{"type":"string","description":"Human-readable confirmation message ('Auto top-up enabled' or 'Auto top-up disabled')."}},"required":["auto_topup_enabled","message"]},"BillingSetupIntentResponse":{"type":"object","title":"setup-intent","description":"Response data for action=setup-intent. Contains a payment setup intent client secret that must be passed to the payment form to collect and confirm the payment method. The resulting payment_method_id is then supplied to action=auto-topup.","properties":{"client_secret":{"type":["string","null"],"description":"payment setup intent client secret. Pass this to stripe.confirmCardSetup() to collect the payment method."},"setup_intent_id":{"type":["string","null"],"description":"payment setup intent ID (e.g. seti_...). Can be used for reconciliation and audit logging."}},"required":["client_secret","setup_intent_id"]},"BillingAlertSettingsResponse":{"type":"object","title":"alert-settings","description":"Response data for action=alert-settings. Returns the updated low-balance alert threshold and a confirmation message.","properties":{"threshold":{"type":"number","description":"The current low-balance alert threshold in USD after the update."},"message":{"type":"string","description":"Human-readable confirmation message ('Alert settings updated').","example":"Alert settings updated"}},"required":["threshold","message"]},"SubscriptionCreateRequest":{"type":"object","title":"create","description":"Request body for action=create. Activates recurring billing on a closed deal.","required":["deal_id","billing_cycle"],"properties":{"deal_id":{"type":"string","description":"The closed deal to activate recurring billing for.","maxLength":255},"billing_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"Billing cadence for the subscription."}},"additionalProperties":false},"SubscriptionRenewRequest":{"type":"object","title":"renew","description":"Request body for action=renew. Creates a renewal deal for the next billing period.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The subscription deal to renew.","maxLength":255}},"additionalProperties":false},"SubscriptionPauseRequest":{"type":"object","title":"pause","description":"Request body for action=pause. Pauses a subscription — no renewal deals will be generated until resumed.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The subscription deal to pause.","maxLength":255}},"additionalProperties":false},"SubscriptionResumeRequest":{"type":"object","title":"resume","description":"Request body for action=resume. Resumes a paused subscription.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The subscription deal to resume.","maxLength":255}},"additionalProperties":false},"SubscriptionCancelRequest":{"type":"object","title":"cancel","description":"Request body for action=cancel. Cancels a subscription immediately or at end of the current billing period.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The subscription deal to cancel.","maxLength":255},"end_of_period":{"type":"boolean","description":"When true, the subscription remains active until the end of the current billing period. When false (default), cancellation is immediate.","default":false},"reason":{"type":"string","description":"Optional cancellation reason.","maxLength":1000},"prorate":{"type":"boolean","default":true,"description":"When true and cancellation is immediate, calculates and applies a prorated credit for unused billing days. Refunded via payment provider if a captured payment exists, otherwise issued as a credit note. Has no effect when end_of_period is true."}},"additionalProperties":false},"SubscriptionChangeRequest":{"type":"object","title":"change","description":"Request body for action=change. Upgrades or downgrades a subscription with optional proration.","required":["deal_id","line_items"],"properties":{"deal_id":{"type":"string","description":"The subscription deal to change.","maxLength":255},"line_items":{"type":"array","description":"New line items for the subscription. Must contain at least one item.","minItems":1,"items":{"type":"object","required":["product_id","name","unit_price"],"properties":{"product_id":{"type":"string","description":"The product ID for this line item.","maxLength":255},"name":{"type":"string","description":"Display name for this line item.","maxLength":500},"quantity":{"type":"number","description":"Quantity of the product. Defaults to 1 if omitted.","minimum":1,"default":1},"unit_price":{"type":"number","description":"Price per unit in the subscription currency.","minimum":0}}}}},"additionalProperties":false},"SubscriptionChangeCycleRequest":{"type":"object","title":"change-cycle","description":"Request body for action=change-cycle. Switches the billing cycle (e.g. monthly to annual) with proration.","required":["deal_id","billing_cycle"],"properties":{"deal_id":{"type":"string","description":"The subscription deal whose billing cycle to change.","maxLength":255},"billing_cycle":{"type":"string","enum":["monthly","quarterly","annual"],"description":"The new billing cycle."}},"additionalProperties":false},"SubscriptionRetryPaymentRequest":{"type":"object","title":"retry-payment","description":"Request body for action=retry-payment. Retries payment for a past-due subscription.","required":["deal_id"],"properties":{"deal_id":{"type":"string","description":"The past-due subscription deal.","maxLength":255},"grace_days":{"type":"integer","description":"Grace period in days before the subscription is cancelled if payment still fails. 0 = reactivate immediately on success.","minimum":0,"maximum":365}},"additionalProperties":false},"SubscriptionAddMeterRequest":{"type":"object","title":"add-meter","description":"Request body for action=add-meter. Adds a usage meter to a subscription for metered billing.","required":["deal_id","metric_name"],"properties":{"deal_id":{"type":"string","description":"The subscription deal to add the meter to.","maxLength":255},"metric_name":{"type":"string","description":"Name of the usage metric to track (e.g. 'api_calls', 'seats', 'storage_gb').","maxLength":255},"billing_model":{"type":"string","enum":["per_unit","tiered","volume"],"description":"Billing model for this meter. Defaults to per_unit.","default":"per_unit"},"unit_price":{"type":"number","description":"Price charged per unit for per_unit billing; defaults to 0 when omitted. tiered and volume meters use tiers.","minimum":0},"included_quantity":{"type":"integer","description":"Number of free units included in the base subscription before metered charges apply.","minimum":0},"tiers":{"type":"array","description":"Tier definitions for tiered or volume billing models.","items":{"type":"object","properties":{"up_to":{"type":["number","null"],"description":"Upper bound for this tier. null means unlimited (last tier only)."},"unit_price":{"type":"number","description":"Price per unit in this tier.","minimum":0}}}},"currency":{"type":"string","description":"ISO 4217 currency code for this meter's charges. Defaults to the deal currency.","maxLength":3}},"additionalProperties":false},"SubscriptionRemoveMeterRequest":{"type":"object","title":"remove-meter","description":"Request body for action=remove-meter. Archives a usage meter. Note: deal_id is not required; identify the meter by meter_id.","required":["meter_id"],"properties":{"meter_id":{"type":"string","description":"The ID of the meter to archive.","maxLength":255}},"additionalProperties":false},"SubscriptionRecordUsageRequest":{"type":"object","title":"record-usage","description":"Request body for action=record-usage. Records a metered usage event (idempotent). Send either top-level metric_name+quantity for a single record, or a records array for batch recording.","oneOf":[{"required":["deal_id","metric_name","quantity"],"description":"Single usage record"},{"required":["deal_id","records"],"description":"Batch usage records"}],"properties":{"deal_id":{"type":"string","description":"The subscription deal to record usage for.","maxLength":255},"metric_name":{"type":"string","description":"Name of the metric to record usage for. Required when not using the records array.","maxLength":255},"quantity":{"type":"number","description":"Usage quantity to record. Must be a positive number. Required when not using the records array.","exclusiveMinimum":0},"idempotency_key":{"type":"string","description":"Client-provided key to prevent duplicate usage recording.","maxLength":255},"metadata":{"type":"object","description":"Arbitrary key-value pairs to store with this usage record. Must be an object; maximum serialised size is 64KB."},"records":{"type":"array","description":"Batch usage records. When provided, top-level metric_name and quantity are ignored.","minItems":1,"items":{"type":"object","required":["metric_name","quantity"],"properties":{"metric_name":{"type":"string","maxLength":255},"quantity":{"type":"number","exclusiveMinimum":0},"idempotency_key":{"type":"string","maxLength":255},"metadata":{"type":"object","description":"Arbitrary key-value pairs for this batch record. Must be an object; maximum serialised size is 64KB."}}}}},"additionalProperties":false},"TenantPublicKeyJwk":{"type":"object","description":"JSON Web Key representation of an Ed25519 signing key.","properties":{"kty":{"type":"string","const":"OKP","description":"Key type."},"crv":{"type":"string","const":"Ed25519","description":"Curve name."},"x":{"type":"string","description":"Base64url-encoded public key material."},"kid":{"type":"string","description":"Signing key identifier."}},"required":["kty","crv","x"]},"TenantPublicKeyRecord":{"type":"object","description":"Tenant signing key metadata and one or more public key encodings.","properties":{"key_id":{"type":"string","description":"Unique signing key identifier."},"algorithm":{"type":"string","description":"Signing algorithm used by this key.","enum":["ed25519"]},"key_version":{"type":"integer","description":"Monotonic key version for the tenant."},"status":{"type":"string","description":"Lifecycle status of this signing key.","enum":["active","rotated"]},"created_at":{"type":"string","format":"date-time","description":"Timestamp when the signing key was created."},"rotated_at":{"type":"string","format":"date-time","description":"Timestamp when the signing key was rotated. Present for rotated keys."},"public_key":{"type":"string","description":"Base64-encoded Ed25519 public key. Returned when `format=raw` or `format=all`."},"public_key_pem":{"type":"string","description":"PEM-encoded Ed25519 public key. Returned when `format=pem` or `format=all`."},"public_key_jwk":{"$ref":"#/components/schemas/TenantPublicKeyJwk"}},"required":["key_id","algorithm","key_version","status","created_at"]},"TenantPublicKeySingleResponseData":{"type":"object","description":"Single active or explicitly selected signing key. `tenant_id` is present when the key is fetched by tenant.","allOf":[{"$ref":"#/components/schemas/TenantPublicKeyRecord"},{"properties":{"tenant_id":{"type":"string","description":"Tenant whose active signing key was returned."}}}]},"TenantPublicKeyListResponseData":{"type":"object","description":"Tenant signing key history including the active key and any rotated keys.","properties":{"tenant_id":{"type":"string","description":"Tenant whose signing keys were returned."},"keys":{"type":"array","description":"Active and rotated signing keys for this tenant.","items":{"$ref":"#/components/schemas/TenantPublicKeyRecord"}}},"required":["tenant_id","keys"]},"Signature":{"type":"object","description":"Cryptographic signature recorded when a deal is signed by a customer or agent.","properties":{"signature_id":{"type":"string","description":"Unique identifier for this signature record"},"deal_id":{"type":"string","description":"ID of the deal this signature belongs to"},"signer_customer_id":{"type":["string","null"],"description":"Customer ID of the signer, if signed by a customer"},"signed_at":{"type":"string","format":"date-time","description":"ISO 8601 timestamp of when the deal was signed"},"ip_address":{"type":"string","description":"IP address of the signer at time of signing"},"user_agent":{"type":"string","description":"User-agent string of the browser or client used to sign"},"signature_data":{"type":"string","description":"Base64-encoded signature data captured during signing"},"deal_hash":{"type":["string","null"],"description":"Hash of the deal content at time of signing, present when cryptographic verification is enabled"},"signer_type":{"type":["string","null"],"description":"Type of signer (e.g. customer, agent), present when cryptographic verification is enabled"},"signer_id":{"type":["string","null"],"description":"Identifier of the signer, present when cryptographic verification is enabled"},"signature_method":{"type":["string","null"],"description":"Cryptographic method used (e.g. ed25519, hmac), present when cryptographic verification is enabled"},"signature_hash":{"type":["string","null"],"description":"Cryptographic signature hash, present when cryptographic verification is enabled"},"signature_algorithm":{"type":["string","null"],"description":"Algorithm used for signing (e.g. hmac, ed25519), present when cryptographic verification is enabled"},"verification_url":{"type":["string","null"],"description":"URL to verify the signature cryptographically, present when cryptographic verification is enabled"},"verification_hash":{"type":["string","null"],"description":"Simple verification hash, present when cryptographic verification is not enabled"}}},"ContractSignRequest":{"type":"object","description":"Request body for cryptographically signing a contract. Requires `contracts:write` scope. The `signer_type` must be one of the defined enum values; arbitrary strings are not accepted. When `signer_id` is provided it is capped at 255 characters. `consent_to_sign: true` is required for all human (non-agent) signers under the Electronic Transactions Act 1999 (Cth) s.10.","properties":{"signer_type":{"type":"string","enum":["user","customer","agent","api_key"],"description":"Type of signer. Defaults to `api_key` for API key auth or `user` for session auth."},"signer_id":{"type":"string","maxLength":255,"description":"Identifier of who is signing (user ID, customer ID, API key ID, etc.). Defaults to the authenticated entity."},"signature_method":{"type":"string","enum":["api_key_auth","session_auth","delegation_auth","customer_portal"],"description":"Method used to authenticate the signing action. Defaults to `api_key_auth` for API key auth or `session_auth` for session auth."},"consent_to_sign":{"type":"boolean","description":"Required for human (non-agent) signers. Confirms the signer consents to signing this document electronically under the Electronic Transactions Act 1999 (Cth). Not required for agent signers (authority derived from delegation chain)."}}},"StaffOverrideResponse":{"type":"object","description":"Response from POST /staff?id={id}&action=override — returns the created schedule override","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"override":{"type":"object","description":"The created schedule override","properties":{"id":{"type":"integer","description":"Unique override ID"},"staff_id":{"type":"string","description":"Staff member ID"},"override_date":{"type":"string","format":"date","description":"The specific date this override applies to (YYYY-MM-DD)"},"start_time":{"type":["string","null"],"description":"Start time in HH:MM format; null when is_available is false"},"end_time":{"type":["string","null"],"description":"End time in HH:MM format; null when is_available is false"},"is_available":{"type":"boolean","description":"Whether the staff member is available on this date"},"reason":{"type":["string","null"],"description":"Optional reason for the override"}},"required":["id","staff_id","override_date","is_available"]}},"required":["override"]}},"required":["error","success","data"]},"StaffAssignProductResponse":{"type":"object","description":"Response from POST /staff?id={id}&action=assign_product — confirms product assignment","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"message":{"type":"string","example":"Staff assigned to product"}},"required":["message"]}},"required":["error","success","data"]},"TrustStatusResponse":{"type":"object","description":"Response from GET /trust (default — no action parameter). Returns current trust level, score, ceiling, auto top-up info, and progress toward the next level.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"trust_level":{"type":"integer","description":"Current trust level (0-5)"},"trust_label":{"type":"string","description":"Human-readable trust level label"},"trust_score":{"type":"integer","description":"Numeric trust score accumulator"},"ceiling":{"type":["number","null"],"description":"Monthly auto top-up ceiling for current level"},"auto_topup":{"type":"object","properties":{"enabled":{"type":"boolean"},"amount":{"type":["number","null"]},"ceiling":{"type":["number","null"]},"monthly_used":{"type":"number"},"monthly_remaining":{"type":["number","null"]}}},"trust_level_changed_at":{"type":["string","null"],"format":"date-time","description":"Timestamp of the last trust level change"},"progress":{"type":"object","description":"Progress toward the next trust level.","properties":{"next_level":{"type":"integer"},"score_required":{"type":"integer"},"score_current":{"type":"integer"},"score_percent":{"type":"number"}}}},"required":["trust_level","trust_label","trust_score"]}},"required":["error","success","data"]},"TrustHistoryEntry":{"type":"object","description":"A single trust level change event.","properties":{"history_id":{"type":"string","description":"Unique identifier for this history entry"},"previous_level":{"type":"integer","description":"Trust level before this change"},"new_level":{"type":"integer","description":"Trust level after this change"},"previous_score":{"type":"integer","description":"Trust score before this change"},"new_score":{"type":"integer","description":"Trust score after this change"},"reason":{"type":["string","null"],"description":"Human-readable reason for the level change"},"trigger_type":{"type":["string","null"],"description":"What triggered the level change (e.g. promotion, demotion, manual)"},"actor_type":{"type":["string","null"],"description":"Type of actor that caused the change (e.g. system, staff)"},"actor_id":{"type":["string","null"],"description":"Identifier of the actor that caused the change"},"metadata":{"type":["object","null"],"description":"Additional event metadata"},"created_at":{"type":"string","format":"date-time","description":"When this level change occurred"}},"required":["history_id","previous_level","new_level","previous_score","new_score","created_at"]},"TrustHistoryResponse":{"type":"object","description":"Response from GET /trust?action=history. Returns a paginated list of trust level change events.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"entries":{"type":"array","items":{"$ref":"#/components/schemas/TrustHistoryEntry"},"description":"Paginated list of trust level change events"},"total":{"type":"integer","description":"Total number of history entries"},"limit":{"type":"integer","description":"Maximum number of entries returned per page"},"offset":{"type":"integer","description":"Offset used for this page"},"has_more":{"type":"boolean","description":"Whether there are more entries beyond this page"}},"required":["entries","total","limit","offset","has_more"]}},"required":["error","success","data"]},"TrustScoreHistoryEntry":{"type":"object","description":"A single trust score event (reward, penalty, or decay).","properties":{"id":{"type":"integer","description":"Unique identifier for this score event"},"event_type":{"type":"string","description":"Type of score event (e.g. deal_closed, dispute_opened, decay)"},"points":{"type":"integer","description":"Score points awarded (positive) or deducted (negative)"},"reason":{"type":["string","null"],"description":"Human-readable reason for this score change"},"reference_type":{"type":["string","null"],"description":"Type of the object that triggered this event (e.g. deal, contract)"},"reference_id":{"type":["string","null"],"description":"Identifier of the object that triggered this event"},"score_before":{"type":"integer","description":"Trust score before this event"},"score_after":{"type":"integer","description":"Trust score after this event"},"created_at":{"type":"string","format":"date-time","description":"When this score event occurred"}},"required":["id","event_type","points","score_before","score_after","created_at"]},"TrustScoreHistoryResponse":{"type":"object","description":"Response from GET /trust?action=score_history. Returns a paginated list of granular trust score events.","properties":{"error":{"type":"boolean","const":false},"success":{"type":"boolean","const":true,"description":"Always true for success responses"},"data":{"type":"object","properties":{"entries":{"type":"array","items":{"$ref":"#/components/schemas/TrustScoreHistoryEntry"},"description":"Paginated list of trust score events"},"total":{"type":"integer","description":"Total number of score events"},"limit":{"type":"integer","description":"Maximum number of entries returned per page"},"offset":{"type":"integer","description":"Offset used for this page"},"has_more":{"type":"boolean","description":"Whether there are more events beyond this page"}},"required":["entries","total","limit","offset","has_more"]}},"required":["error","success","data"]},"DealVerifyAuditResult":{"type":"object","description":"Result of verifying the audit chain integrity for a deal (action=verify_audit)","properties":{"entity_type":{"type":"string","example":"deal"},"entity_id":{"type":"string","example":"deal_abc123"},"status":{"type":"string","enum":["verified","tampered","no_entries"],"description":"verified=all entries intact; tampered=chain broken; no_entries=no audit log yet"},"message":{"type":"string"},"total_entries":{"type":"integer"},"verified_at":{"type":"string","format":"date-time"},"first_entry":{"type":"string","description":"Log ID of the first audit entry. Present when status=verified."},"last_entry":{"type":"string","description":"Log ID of the last audit entry. Present when status=verified."},"broken_at":{"type":"object","description":"Details of the first broken link in the chain. Present when status=tampered.","properties":{"entry_index":{"type":"integer"},"log_id":{"type":"string"},"reason":{"type":"string"}},"additionalProperties":true}},"required":["entity_type","entity_id","status","message","total_entries","verified_at"]},"DealAuditTrailEntry":{"type":"object","description":"Single immutable audit trail entry for a deal","properties":{"log_id":{"type":"string","description":"Unique audit log entry ID"},"entity_type":{"type":"string","description":"Type of entity audited"},"entity_id":{"type":"string","description":"ID of the audited entity"},"action":{"type":"string","description":"Action that was performed"},"actor_type":{"type":"string","description":"Type of actor who performed the action"},"actor_id":{"type":["string","null"],"description":"Identifier of the actor who performed the action"},"changes":{"type":["object","null"],"description":"Field-level changes recorded for this entry","additionalProperties":true},"snapshot":{"type":["object","null"],"description":"Full entity snapshot at time of action","additionalProperties":true},"previous_hash":{"type":["string","null"],"description":"SHA-256 hash of the previous entry in the chain"},"entry_hash":{"type":"string","description":"SHA-256 hash of this entry"},"created_at":{"type":"string","format":"date-time","description":"Timestamp when this audit entry was created"}},"required":["log_id","entity_type","entity_id","action","actor_type","actor_id","changes","snapshot","previous_hash","entry_hash","created_at"]},"DealAuditTrailResult":{"type":"object","description":"Paginated immutable audit trail for a deal (action=audit)","properties":{"entries":{"type":"array","description":"Audit trail entries in chronological order","items":{"$ref":"#/components/schemas/DealAuditTrailEntry"}},"pagination":{"$ref":"#/components/schemas/Pagination"}},"required":["entries","pagination"]},"DealCompareTermsResult":{"type":"object","description":"Structured comparison between the machine-readable terms of two deals (action=compare-terms)","properties":{"deal_id_1":{"type":"string"},"deal_id_2":{"type":"string"},"has_terms":{"type":"object","properties":{"deal_1":{"type":"boolean"},"deal_2":{"type":"boolean"}},"required":["deal_1","deal_2"]},"sections":{"type":"object","description":"Per-section comparison details keyed by structured terms section name.","additionalProperties":{"type":"object","properties":{"present_in":{"type":"array","items":{"type":"string","enum":["deal_1","deal_2"]}},"status":{"type":"string","enum":["both","deal_1_only","deal_2_only"]},"equivalent":{"type":"boolean"},"differences":{"type":"array","items":{"type":"object","properties":{"field":{"type":"string"},"deal_1":[],"deal_2":[]},"required":["field"]}},"deal_1_value":[],"deal_2_value":[]},"required":["present_in","differences"]}},"summary":{"type":"array","items":{"type":"string"}}},"required":["deal_id_1","deal_id_2","has_terms","sections","summary"]},"DealEscrowResult":{"type":"object","description":"Escrow status and conditions for a deal (action=escrow)","properties":{"escrow_id":{"type":"string","example":"esc_a1b2c3d4e5f6g7h8"},"deal_id":{"type":"string"},"tenant_id":{"type":"string"},"amount":{"type":"number"},"currency":{"type":"string","example":"AUD"},"status":{"type":"string","enum":["held","released","refunded","cancelled"]},"stripe_payment_intent_id":{"type":["string","null"]},"conditions":{"type":"array","items":{"type":"object","additionalProperties":true}},"conditions_summary":{"type":"object","properties":{"total":{"type":"integer"},"met":{"type":"integer"},"remaining":{"type":"integer"},"all_met":{"type":"boolean"}},"required":["total","met","remaining","all_met"]},"authorization":{"type":"object","properties":{"last_authorized_at":{"type":["string","null"]},"auth_expires_at":{"type":["string","null"]},"auth_days_remaining":{"type":["number","null"]},"auth_status":{"type":["string","null"],"enum":["ok","warning","critical",null],"description":"ok=7+ days; warning=1-3 days; critical=<1 day; null=not held"}}},"released_at":{"type":["string","null"],"format":"date-time"},"refunded_at":{"type":["string","null"],"format":"date-time"},"expires_at":{"type":["string","null"],"format":"date-time"},"last_authorized_at":{"type":["string","null"],"format":"date-time"},"created_at":{"type":"string","format":"date-time"},"updated_at":{"type":"string","format":"date-time"}},"required":["escrow_id","deal_id","amount","currency","status","conditions","conditions_summary","authorization"]},"DealCredentialResult":{"type":"object","description":"W3C Verifiable Credential record for a completed deal (action=credential)","properties":{"credential_id":{"type":"string"},"deal_id":{"type":"string"},"status":{"type":"string","enum":["active","revoked"]},"key_id":{"type":"string","description":"Signing key identifier (for key rotation tracking)"},"credential_hash":{"type":"string","description":"SHA-256 hash of the serialised credential"},"issued_at":{"type":"string","format":"date-time"},"revoked_at":{"type":["string","null"],"format":"date-time"},"revocation_reason":{"type":["string","null"]},"credential":{"type":"object","description":"Full W3C Verifiable Credential JSON-LD document including proof","additionalProperties":true}},"required":["credential_id","deal_id","status","key_id","credential_hash","issued_at","credential"]},"DealSigningCertificateResult":{"type":"object","description":"Structured signing certificate document summarising the deal signing event (action=signing_certificate)","properties":{"certificate_version":{"type":"string","example":"1.0"},"generated_at":{"type":"string","format":"date-time"},"legislation":{"type":"string","example":"Electronic Transactions Act 1999 (Cth) and state/territory equivalents"},"deal":{"type":"object","properties":{"deal_id":{"type":"string"},"title":{"type":["string","null"]},"status":{"type":"string"},"currency":{"type":"string"},"total":{"type":["number","null"]},"created_at":{"type":["string","null"]}},"required":["deal_id"]},"signers":{"type":"array","description":"All signature records collected for this deal","items":{"type":"object","properties":{"signature_id":{"type":"string"},"signer_type":{"type":"string"},"signer_id":{"type":["string","null"]},"signer_customer_id":{"type":["string","null"]},"signature_method":{"type":"string"},"signature_algorithm":{"type":"string"},"signature_hash":{"type":"string"},"deal_hash":{"type":"string"},"ip_address":{"type":["string","null"]},"user_agent":{"type":["string","null"]},"signed_at":{"type":"string","format":"date-time"},"is_agent_signer":{"type":"boolean"}}}},"consent_events":{"type":"array","description":"Audit-log events where signers granted consent to sign","items":{"type":"object","properties":{"actor_type":{"type":"string"},"actor_id":{"type":["string","null"]},"consented_at":{"type":"string"},"details":{"type":["object","null"],"additionalProperties":true}}}},"hash_chain_verification":{"type":"object","properties":{"status":{"type":"string"},"total_entries":{"type":"integer"},"verified_at":{"type":"string","format":"date-time"}},"required":["status","total_entries","verified_at"]},"note":{"type":"string"}},"required":["certificate_version","generated_at","deal","signers","consent_events","hash_chain_verification"]},"DealTermsResult":{"type":"object","description":"Structured machine-readable terms returned for a deal (action=terms)","properties":{"deal_id":{"type":"string"},"terms":{"type":["object","null"],"description":"Structured deal terms. Null when the deal has no machine-readable terms set.","$ref":"#/components/schemas/DealTerms"},"terms_schema_version":{"type":["string","null"],"description":"Schema version of the returned terms payload"}},"required":["deal_id","terms","terms_schema_version"]},"PaymentConnectProviderRequest":{"type":"object","title":"connect-provider","description":"Request body for action=connect-provider. Deprecated alias: action=connect-stripe. Initiates payment account onboarding.","properties":{"return_url":{"type":"string","format":"uri","description":"URL the merchant is redirected to after completing payment provider onboarding. Must use http or https. Defaults to the request origin + /settings/payments/."},"refresh_url":{"type":"string","format":"uri","description":"URL payment provider redirects to when the onboarding link expires or cannot be used. Must use http or https. Defaults to return_url base + /settings/payments/."}},"additionalProperties":false},"PaymentDisconnectProviderRequest":{"type":"object","title":"disconnect-provider","description":"Request body for action=disconnect-provider. Deprecated alias: action=disconnect-stripe. Disconnects the payment account. No body fields required.","additionalProperties":false}},"responses":{"BadRequest":{"description":"Bad request — invalid input or validation failure","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"validation_error":{"summary":"Field-level validation errors","value":{"error":true,"code":"validation_error.invalid_fields","category":"validation_error","message":"Validation failed","recovery":{"action":"fix_request","retryable":false,"hint":"Check the details.fields object for specific field errors."},"details":{"fields":{"email":{"code":"invalid","message":"Valid email is required"},"customer_id":{"code":"required","message":"Customer ID is required"}}}}},"bad_request":{"summary":"General bad request","value":{"error":true,"code":"validation_error.bad_request","category":"validation_error","message":"Invalid JSON in request body","recovery":{"action":"fix_request","retryable":false}}}}}}},"Unauthorized":{"description":"Authentication required — missing or invalid credentials","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"error":true,"code":"authentication_error.invalid_credentials","category":"authentication_error","message":"Unauthorized","recovery":{"action":"authenticate","retryable":false,"hint":"Provide valid authentication credentials."}}}}},"Forbidden":{"description":"Insufficient permissions — API key lacks required scope","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"error":true,"code":"authorization_error.insufficient_scope","category":"authorization_error","message":"This action requires the deals:write scope","recovery":{"action":"check_permissions","retryable":false,"hint":"Verify your API key has the required scopes."}}}}},"NotFound":{"description":"Resource not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"error":true,"code":"not_found","category":"not_found","message":"Deal deal_abc123 not found","recovery":{"action":"check_resource_id","retryable":false,"hint":"Verify the resource ID exists and you have access to it."}}}}},"RateLimited":{"description":"Rate limit exceeded","headers":{"X-RateLimit-Limit":{"description":"Maximum requests per minute","schema":{"type":"integer"}},"X-RateLimit-Remaining":{"description":"Remaining requests in current window","schema":{"type":"integer"}},"X-RateLimit-Reset":{"description":"Unix timestamp when the rate limit resets","schema":{"type":"integer"}},"Retry-After":{"description":"Seconds to wait before retrying","schema":{"type":"integer"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"error":true,"code":"rate_limited","category":"rate_limited","message":"Rate limit exceeded","recovery":{"action":"retry","retryable":true,"retry_after_seconds":60,"max_retries":3}}}}},"ServerError":{"description":"Internal server error","headers":{"Retry-After":{"description":"Seconds to wait before retrying (present on transient errors)","schema":{"type":"integer"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"internal_error":{"summary":"Non-retryable internal error","value":{"error":true,"code":"internal_error","category":"internal_error","message":"An internal error occurred.","recovery":{"action":"contact_support","retryable":false,"hint":"If this persists, contact support with the error reference."},"ref":"err_a1b2c3d4e5f6"}},"transient_error":{"summary":"Retryable transient error","value":{"error":true,"code":"transient_error","category":"transient_error","message":"Service temporarily unavailable","recovery":{"action":"retry","retryable":true,"retry_after_seconds":5,"max_retries":3}}}}}}},"Conflict":{"description":"Conflict — the resource is in a state that prevents this operation","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"examples":{"deal_already_closed":{"summary":"Deal is closed and immutable","value":{"error":true,"code":"conflict.deal_already_closed","category":"conflict","message":"Deal deal_abc123 is already closed and cannot be modified","recovery":{"action":"none","retryable":false,"hint":"Closed deals are immutable. Create a new deal if needed."}}},"invalid_state":{"summary":"Resource is in wrong state for operation","value":{"error":true,"code":"conflict.invalid_state","category":"conflict","message":"Deal must be in pending_signature status to sign (current: draft)","recovery":{"action":"check_status","retryable":false,"hint":"Transition the deal to pending_signature before signing."}}}}}}},"PreconditionFailed":{"description":"Precondition Failed — the resource has been modified since you last read it. The response includes the current resource state and an updated ETag so you can merge changes and retry.","headers":{"ETag":{"description":"Current resource version as a weak ETag","schema":{"type":"string","example":"W/\"4\""}}},"content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ErrorResponse"},{"type":"object","properties":{"data":{"description":"Current state of the resource for client-side merge"}}}]},"example":{"error":true,"code":"conflict.stale_version","category":"conflict","message":"Resource has been modified by another request. Refresh and retry.","recovery":{"action":"refetch_and_retry","retryable":true,"hint":"Read the current resource version from the response data, merge your changes, and retry with the new ETag."},"data":{"deal_id":"deal_abc123","version":4,"status":"in_progress"}}}}},"PreconditionRequired":{"description":"Precondition Required — the If-Match header is missing. PATCH requests require an If-Match header containing the resource's current ETag for optimistic locking.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"error":true,"code":"validation_error.precondition_required","category":"validation_error","message":"If-Match header is required","recovery":{"action":"fix_request","retryable":false,"hint":"Add an If-Match header with the resource ETag from a prior GET request."}}}}},"IdempotencyConflict":{"description":"Conflict — the same Idempotency-Key was used with a different request body. Generate a new key for different requests.","headers":{"Idempotency-Key":{"description":"Echo of the provided idempotency key","schema":{"type":"string"}}},"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"error":true,"code":"conflict.idempotency_key_reused","category":"conflict","message":"This idempotency key has already been used with a different request body","recovery":{"action":"fix_request","retryable":false,"hint":"Generate a new idempotency key for this request."}}}}},"MethodNotAllowed":{"description":"Method not allowed","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ErrorResponse"},{"type":"object","properties":{"code":{"type":"string","enum":["request_error.method_not_allowed"]}}}]},"example":{"error":true,"code":"request_error.method_not_allowed","category":"request_error","message":"Method not allowed","recovery":{"action":"fix_request","retryable":false}}}}},"PayloadTooLarge":{"description":"Request body too large","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ErrorResponse"},"example":{"error":true,"code":"validation_error.request_too_large","category":"validation_error","message":"Request body too large","recovery":{"action":"fix_request","retryable":false}}}}}}},"x-salesbooth-view":"agent"}