From 706d8ddaacdc9207a8b0eed1789c8856009f20b1 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 01:10:02 -0300 Subject: [PATCH 01/12] feat: codespar_card for Pomelo and Rain, codespar_issue deprecated (SDK, CLI, MCP, Python) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One card contract across issuers (cards contract §1-§9): BRL on pomelo_brl, USD on rain_usd. - types 0.12.0: CARD_DEFINITION/CARD_INPUT (codespar_card) in the shared surface; CardArgs/CardResult with issued, pending_human, processing, uncertain, failed and refused; CardReadiness. ISSUE_DEFINITION, IssueArgs, IssueResult and Session.issue() stay as deprecated aliases. - sdk 0.17.0: session.card(), cs.cards.readiness(); session.issue() is a deprecated wrapper over card() with the same validations; an old Pomelo-shaped call throws CardContractMigrationError before sending. spec:refresh --from-file for an enterprise candidate document, and an assert-served gate in the publish workflow. - cli 0.23.0: codespar card issue|get|list|freeze|unfreeze|cancel|readiness; codespar issue deprecated over it. - mcp 0.6.0: copy; python 0.17.0: card(), cards.readiness(), issue() deprecated. Adapters: sdk peer range accepts ^0.17.0. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/publish.yml | 6 + README.md | 2 +- package-lock.json | 64 +-- packages/autogen/package.json | 4 +- .../autogen/src/__tests__/autogen.test.ts | 1 + packages/camel/package.json | 4 +- packages/camel/src/__tests__/camel.test.ts | 1 + packages/claude/CHANGELOG.md | 6 + packages/claude/package.json | 4 +- packages/cli/CHANGELOG.md | 22 + packages/cli/README.md | 3 +- packages/cli/package.json | 4 +- .../cli/src/__tests__/card-command.test.ts | 231 ++++++++ packages/cli/src/__tests__/meta-tools.test.ts | 77 ++- packages/cli/src/commands/card.ts | 258 +++++++++ packages/cli/src/commands/issue.ts | 73 --- packages/cli/src/commands/meta-input.ts | 2 +- packages/cli/src/index.ts | 86 ++- packages/cli/src/surface.ts | 2 +- packages/core/CHANGELOG.md | 25 + packages/core/README.md | 1 + packages/core/package.json | 4 +- packages/core/scripts/openapi-spec.mjs | 63 ++- packages/core/src/__tests__/card.test.ts | 384 +++++++++++++ .../src/__tests__/openapi-snapshot.test.ts | 2 + packages/core/src/card.ts | 184 ++++++ packages/core/src/cards.ts | 52 ++ packages/core/src/index.ts | 21 + packages/core/src/session.ts | 38 +- packages/core/src/testing/index.ts | 46 +- packages/crewai/package.json | 4 +- packages/crewai/src/__tests__/crewai.test.ts | 1 + packages/google-genai/package.json | 4 +- .../src/__tests__/google-genai.test.ts | 1 + packages/hermes/package.json | 4 +- packages/hermes/src/__tests__/hermes.test.ts | 1 + packages/langchain/CHANGELOG.md | 6 + packages/langchain/package.json | 4 +- .../langchain/src/__tests__/langchain.test.ts | 1 + packages/letta/package.json | 4 +- packages/letta/src/__tests__/letta.test.ts | 1 + packages/llama-index/package.json | 4 +- .../src/__tests__/llama-index.test.ts | 1 + packages/mastra/package.json | 4 +- packages/mastra/src/__tests__/mastra.test.ts | 1 + packages/mcp/CHANGELOG.md | 7 + packages/mcp/README.md | 4 +- packages/mcp/package.json | 8 +- packages/mcp/src/__tests__/mcp.test.ts | 1 + packages/openai/package.json | 4 +- packages/openai/src/__tests__/openai.test.ts | 1 + packages/python/CHANGELOG.md | 22 + packages/python/README.md | 50 ++ packages/python/pyproject.toml | 2 +- packages/python/src/codespar/__init__.py | 58 +- packages/python/src/codespar/_async_client.py | 3 + .../python/src/codespar/_async_session.py | 345 ++++++++++-- packages/python/src/codespar/_sync_client.py | 27 +- packages/python/src/codespar/cards.py | 91 +++ packages/python/src/codespar/errors.py | 14 + packages/python/src/codespar/types.py | 243 +++++++- packages/python/tests/test_card.py | 525 ++++++++++++++++++ packages/types/CHANGELOG.md | 27 + packages/types/package.json | 2 +- .../types/src/meta-tool-definitions.test.ts | 90 ++- packages/types/src/meta-tool-definitions.ts | 57 +- .../types/src/testing/scenario-manifest.ts | 2 +- packages/types/src/types.ts | 353 ++++++++++-- packages/vercel/package.json | 4 +- 69 files changed, 3317 insertions(+), 334 deletions(-) create mode 100644 packages/cli/src/__tests__/card-command.test.ts create mode 100644 packages/cli/src/commands/card.ts delete mode 100644 packages/cli/src/commands/issue.ts create mode 100644 packages/core/src/__tests__/card.test.ts create mode 100644 packages/core/src/card.ts create mode 100644 packages/core/src/cards.ts create mode 100644 packages/python/src/codespar/cards.py create mode 100644 packages/python/tests/test_card.py diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 6906d417..a7d1cd4a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -64,6 +64,12 @@ jobs: - name: Publish drift guard run: node scripts/check-publish-drift.mjs + # A snapshot generated from an enterprise CANDIDATE head (review state, + # cards contract §8.6) describes routes production may not serve. + # Publish day refreshes from the served document first. + - name: OpenAPI snapshot is from the served document + run: node packages/core/scripts/openapi-spec.mjs assert-served + - name: Publish all packages run: | # Bash's "exit on error" is off for the loop body so one bad package diff --git a/README.md b/README.md index 626f6e13..009d0812 100644 --- a/README.md +++ b/README.md @@ -154,7 +154,7 @@ sells), and shared infrastructure: | `codespar_wallet` | The agent's governed funds: balance, statement, top-up; per-currency slots | | `codespar_pay` | Outbound spend: money leaves the wallet the agent governs | | `codespar_crypto_pay` | On-chain spend and cross-border ramps (testnet today) | -| `codespar_issue` | Spend cards bound to the same mandate governance | +| `codespar_card` | Spend cards bound to the same mandate governance: BRL on Pomelo, USD on Rain, one contract | **Sell side** diff --git a/package-lock.json b/package-lock.json index 5f1759f7..83d4319b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2980,7 +2980,7 @@ }, "packages/autogen": { "name": "@codespar/autogen", - "version": "0.4.6", + "version": "0.4.7", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -2989,12 +2989,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/camel": { "name": "@codespar/camel", - "version": "0.4.6", + "version": "0.4.7", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3003,12 +3003,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/claude": { "name": "@codespar/claude", - "version": "0.4.8", + "version": "0.4.9", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3017,15 +3017,15 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/cli": { "name": "@codespar/cli", - "version": "0.22.7", + "version": "0.23.0", "license": "MIT", "dependencies": { - "@codespar/sdk": "^0.16.26", + "@codespar/sdk": "^0.17.0", "commander": "^13.0.0" }, "bin": { @@ -3041,10 +3041,10 @@ }, "packages/core": { "name": "@codespar/sdk", - "version": "0.16.30", + "version": "0.17.0", "license": "MIT", "dependencies": { - "@codespar/types": "^0.10.1 || ^0.11.0", + "@codespar/types": "^0.12.0", "zod": "^4.6.6" }, "devDependencies": { @@ -3059,7 +3059,7 @@ }, "packages/crewai": { "name": "@codespar/crewai", - "version": "0.4.6", + "version": "0.4.7", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3068,12 +3068,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/google-genai": { "name": "@codespar/google-genai", - "version": "0.4.6", + "version": "0.4.7", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3082,12 +3082,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/hermes": { "name": "@codespar/hermes", - "version": "0.4.5", + "version": "0.4.6", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3096,12 +3096,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/langchain": { "name": "@codespar/langchain", - "version": "0.5.2", + "version": "0.5.3", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3115,13 +3115,13 @@ "zod-to-json-schema": "^3.25.2" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0", + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0", "zod": ">=3.25.0" } }, "packages/letta": { "name": "@codespar/letta", - "version": "0.4.6", + "version": "0.4.7", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3130,12 +3130,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/llama-index": { "name": "@codespar/llama-index", - "version": "0.4.6", + "version": "0.4.7", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3144,7 +3144,7 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/managed-agents-adapter": { @@ -3166,7 +3166,7 @@ }, "packages/mastra": { "name": "@codespar/mastra", - "version": "0.4.6", + "version": "0.4.7", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3175,15 +3175,15 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/mcp": { "name": "@codespar/mcp", - "version": "0.5.20", + "version": "0.6.0", "license": "MIT", "dependencies": { - "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0", + "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "bin": { @@ -3196,12 +3196,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/openai": { "name": "@codespar/openai", - "version": "0.4.7", + "version": "0.4.8", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3210,12 +3210,12 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" } }, "packages/types": { "name": "@codespar/types", - "version": "0.11.7", + "version": "0.12.0", "license": "MIT", "devDependencies": { "@types/node": "^25.6.0", @@ -3228,7 +3228,7 @@ }, "packages/vercel": { "name": "@codespar/vercel", - "version": "0.4.7", + "version": "0.4.8", "license": "MIT", "devDependencies": { "@codespar/sdk": "*", @@ -3237,7 +3237,7 @@ "vitest": "^3.1.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0", + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0", "ai": ">=3.0.0" } } diff --git a/packages/autogen/package.json b/packages/autogen/package.json index f0bef031..e97ec490 100644 --- a/packages/autogen/package.json +++ b/packages/autogen/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/autogen", - "version": "0.4.6", + "version": "0.4.7", "description": "Microsoft AutoGen adapter for CodeSpar — convert session tools to AutoGen function tool format", "type": "module", "main": "./dist/index.js", @@ -38,7 +38,7 @@ "directory": "packages/autogen" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/autogen/src/__tests__/autogen.test.ts b/packages/autogen/src/__tests__/autogen.test.ts index ea229089..6b0de2f9 100644 --- a/packages/autogen/src/__tests__/autogen.test.ts +++ b/packages/autogen/src/__tests__/autogen.test.ts @@ -38,6 +38,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/camel/package.json b/packages/camel/package.json index f89fc6d6..b82675f9 100644 --- a/packages/camel/package.json +++ b/packages/camel/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/camel", - "version": "0.4.6", + "version": "0.4.7", "description": "CAMEL-AI adapter for CodeSpar — convert session tools to CAMEL function format", "type": "module", "main": "./dist/index.js", @@ -38,7 +38,7 @@ "directory": "packages/camel" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/camel/src/__tests__/camel.test.ts b/packages/camel/src/__tests__/camel.test.ts index 3376db49..be80aaf2 100644 --- a/packages/camel/src/__tests__/camel.test.ts +++ b/packages/camel/src/__tests__/camel.test.ts @@ -38,6 +38,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/claude/CHANGELOG.md b/packages/claude/CHANGELOG.md index 5350beb2..fe10d245 100644 --- a/packages/claude/CHANGELOG.md +++ b/packages/claude/CHANGELOG.md @@ -1,5 +1,11 @@ # @codespar/claude — CHANGELOG +## 0.4.9 — unreleased (coordinated codespar_card release) + +### Changed + +- The `@codespar/sdk` peer range accepts `^0.17.0`. + ## 0.4.8 — 2026-10-29 ### Fixed diff --git a/packages/claude/package.json b/packages/claude/package.json index 195ef704..608f5c54 100644 --- a/packages/claude/package.json +++ b/packages/claude/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/claude", - "version": "0.4.8", + "version": "0.4.9", "description": "Claude Agent SDK adapter for CodeSpar \u2014 convert MCP tools to Claude tool format", "type": "module", "main": "./dist/index.js", @@ -37,7 +37,7 @@ "directory": "packages/claude" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 7ac5e73a..18a06d83 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,5 +1,27 @@ # @codespar/cli — changelog +## 0.23.0 — unreleased (coordinated codespar_card release) + +### Added + +- **`codespar card issue|get|list|freeze|unfreeze|cancel|readiness`**, through `codespar_card` (BRL on Pomelo, USD on Rain). + - `card issue` takes `--currency`, `--mandate-id`, `--consumer-id` and `--idempotency-key` (required), plus an optional `--provider`. + - `card get `. + - `card list [--issuer] [--mandate-id] [--consumer-id]`. + - `card freeze|unfreeze|cancel [--reason]`. + - `card readiness` reads `GET /v1/cards/readiness`. + - `-i/--input` and `-f/--input-file` take JSON, and flags win over it. `--json` prints the result document. +- The output shows id, issuer, program, currency, status (with the issuer's raw status) and the available actions. +- Exit codes: + - A refusal, or a definitive `failed`, exits 1 with an `api` error document carrying the `code` and the whole result as `body`. + - `pending_human`, `processing` and `uncertain` exit 0. They say what happens next. `uncertain` says the card may exist and that it reconciles on the SAME `--idempotency-key`, never a new one. +- Vocabularies (actions, currency, provider, issuer) come from the published `codespar_card` definition, not a copy. +- Depends on `@codespar/sdk ^0.17.0`. + +### Deprecated + +- **`codespar issue`** is a wrapper over `codespar card `. It takes the JSON it always took, warns, and sends `codespar_card` with the same validations. The old Pomelo shape is refused with `card_contract_migration_required`, and the message names the new fields and commands. + ## 0.22.7 — 2026-11-11 ### Added diff --git a/packages/cli/README.md b/packages/cli/README.md index f00f739d..84836fb1 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -94,7 +94,8 @@ codespar init my-agent | `charge` | Issue an inbound charge via `codespar_charge` | | `ship` | Generate label / quote rates / track via `codespar_ship` | | `ledger` | Post entries / read balances / create accounts via `codespar_ledger` | -| `issue` | Issue / freeze / read agent spend cards via `codespar_issue` | +| `card issue\|get\|list\|freeze\|unfreeze\|cancel\|readiness` | Spend cards via `codespar_card`: BRL on Pomelo, USD on Rain. `card issue` needs `--currency --mandate-id --consumer-id --idempotency-key`; `processing` / `uncertain` resolve by running it again with the SAME key. `card readiness` lists, per program, what is missing and who must act | +| `issue` | Deprecated: use `card`. Same tool and validations; the old Pomelo JSON shape is refused with `card_contract_migration_required` | | `payment-status ` | Poll async settlement status (add `--stream`) | | `verification-status ` | Poll async KYC status (add `--stream`) | | `wizard [server]` | Connection wizard — required secrets, connect URL, next steps | diff --git a/packages/cli/package.json b/packages/cli/package.json index 388a149c..b512afb6 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/cli", - "version": "0.22.7", + "version": "0.23.0", "description": "CodeSpar CLI. The agentic OS for money movement in Latin America, from your terminal: authenticate, browse servers, mint mandates, execute tools, manage sessions, stream logs.", "type": "module", "bin": { @@ -48,7 +48,7 @@ "node": ">=20" }, "dependencies": { - "@codespar/sdk": "^0.16.26", + "@codespar/sdk": "^0.17.0", "commander": "^13.0.0" }, "devDependencies": { diff --git a/packages/cli/src/__tests__/card-command.test.ts b/packages/cli/src/__tests__/card-command.test.ts new file mode 100644 index 00000000..b611195e --- /dev/null +++ b/packages/cli/src/__tests__/card-command.test.ts @@ -0,0 +1,231 @@ +/** + * `codespar card ` end to end over a mocked backend: what reaches + * /execute, what a script reads in `--json`, and that a refusal ends the + * command with the refusal's code and body (exit 1 via the top-level handler) + * while a pending issue does not. + */ + +import { afterEach, describe, expect, it, vi } from "vitest"; +import { HttpError } from "../api.js"; +import { CliError } from "../config.js"; +import { cardCommand, cardReadinessCommand, issueDeprecatedCommand } from "../commands/card.js"; + +const AUTH = { apiKey: "csk_test_notreal", baseUrl: "https://api.test.dev" }; + +const SESSION = { + id: "sess_card", + org_id: "org_0000", + user_id: "cli-user", + servers: [], + status: "active", + created_at: new Date().toISOString(), + closed_at: null, +}; + +const POMELO_VIEW = { + id: "icrd_1", + issuer: "pomelo", + program: "pomelo_brl", + currency: "BRL", + status: "active", + issuer_status: "ACTIVE", + last4: "4242", + network: "MASTERCARD", + mandate_id: "mnd_brl", + consumer_id: "cons_1", + created_at: "2026-11-18T12:00:00.000Z", + available_actions: ["freeze", "cancel"], +}; + +function backend(envelope: Record): { sent: Array<{ tool: string; input: Record }> } { + const sent: Array<{ tool: string; input: Record }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation((input: unknown, init: unknown) => { + const url = String(input); + const method = (init as RequestInit | undefined)?.method ?? "GET"; + const ok = (body: unknown) => + Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } })); + if (url.endsWith("/v1/sessions") && method === "POST") return ok(SESSION); + if (url.endsWith(`/v1/sessions/${SESSION.id}/execute`)) { + sent.push(JSON.parse(String((init as RequestInit).body)) as { tool: string; input: Record }); + return ok({ duration: 1, server: "_codespar", tool: "codespar_card", ...envelope }); + } + if (url.endsWith(`/v1/sessions/${SESSION.id}`) && method === "DELETE") return ok({ ok: true }); + return Promise.resolve(new Response("{}", { status: 404 })); + }); + return { sent }; +} + +function captureStdout(): { text: () => string; err: () => string } { + let out = ""; + let err = ""; + vi.spyOn(process.stdout, "write").mockImplementation((chunk: unknown) => { + out += String(chunk); + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => { + err += String(chunk); + return true; + }); + return { text: () => out, err: () => err }; +} + +afterEach(() => vi.restoreAllMocks()); + +describe("codespar card", () => { + it("issue sends codespar_card with the wire names and prints the issued card in --json", async () => { + const { sent } = backend({ + success: true, + error: null, + data: { + state: "issued", + issue_request_id: "cir_1", + issuer: "pomelo", + program: "pomelo_brl", + selection: { provider_requested: null, chosen_by: "currency" }, + card: POMELO_VIEW, + authorization_id: "caia_1", + authorization_active: true, + }, + }); + const out = captureStdout(); + await cardCommand("issue", undefined, { + ...AUTH, + currency: "BRL", + mandateId: "mnd_brl", + consumerId: "cons_1", + idempotencyKey: "idem_1", + json: true, + }); + expect(sent).toEqual([ + { tool: "codespar_card", input: { action: "issue", currency: "BRL", mandate_id: "mnd_brl", consumer_id: "cons_1", idempotency_key: "idem_1" } }, + ]); + const doc = JSON.parse(out.text()) as Record; + expect(doc).toMatchObject({ + state: "issued", + issuer: "pomelo", + program: "pomelo_brl", + card: { id: "icrd_1", currency: "BRL", status: "active", available_actions: ["freeze", "cancel"] }, + }); + }); + + it("the human output names id, issuer, program, currency, status and available actions", async () => { + backend({ success: true, error: null, data: POMELO_VIEW }); + const out = captureStdout(); + await cardCommand("get", "icrd_1", { ...AUTH }); + const text = out.text(); + for (const expected of ["icrd_1", "pomelo", "pomelo_brl", "BRL", "active (ACTIVE)", "freeze, cancel"]) { + expect(text).toContain(expected); + } + }); + + it("a pending_human issue is not a failure: the command ends normally and --json carries pending_action", async () => { + backend({ + success: true, + error: null, + data: { + state: "pending_human", + issue_request_id: "cir_1", + issuer: "rain", + program: "rain_usd", + pending_action: { id: "pa_1", kind: "accept_terms", actor: "holder", url: "https://codespar.dev/x" }, + }, + }); + const out = captureStdout(); + await expect( + cardCommand("issue", undefined, { ...AUTH, currency: "USD", mandateId: "m", consumerId: "c", idempotencyKey: "k", json: true }), + ).resolves.toBeUndefined(); + expect(JSON.parse(out.text())).toMatchObject({ state: "pending_human", pending_action: { kind: "accept_terms", actor: "holder" } }); + }); + + it("a refusal throws an HttpError with the refusal's code and the whole refusal as body", async () => { + backend({ + success: false, + error: "freeze is not supported on rain_usd", + data: { + error: { code: "card_action_unsupported", message: "freeze is not supported on rain_usd", details: { issuer: "rain", program: "rain_usd", action: "freeze", available_actions: [] } }, + http_status: 422, + }, + }); + captureStdout(); + const err = await cardCommand("freeze", "rcrd_1", { ...AUTH, json: true }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(HttpError); + const http = err as HttpError; + expect(http.code).toBe("card_action_unsupported"); + expect(http.status).toBe(422); + expect(http.message).toMatch(/card freeze refused: card_action_unsupported/); + expect(http.body).toMatchObject({ state: "refused", issuer: "rain", available_actions: [] }); + }); + + it.each(["uncertain", "processing"] as const)( + "%s: says it resolves on the SAME key and never suggests another one (contract §8.3)", + async (state) => { + backend({ success: true, error: null, data: { state, issue_request_id: "cir_9", issuer: "rain", program: "rain_usd" } }); + const out = captureStdout(); + await expect( + cardCommand("issue", undefined, { ...AUTH, currency: "USD", mandateId: "m", consumerId: "c", idempotencyKey: "k" }), + ).resolves.toBeUndefined(); + const text = out.err(); + expect(text).toContain("cir_9"); + expect(text).toMatch(/same --idempotency-key/i); + expect(text).not.toMatch(/(try again|retry|run it again) with (a )?(new|another|different) key/i); + if (state === "uncertain") { + expect(text).toMatch(/MAY exist/); + expect(text).toMatch(/Do not use a new key/); + } + }, + ); + + it("failed is a definitive refusal: HttpError with the issuer's code", async () => { + backend({ success: true, error: null, data: { state: "failed", issue_request_id: "cir_8", issuer: "pomelo", program: "pomelo_brl", code: "issuer_declined" } }); + captureStdout(); + const err = await cardCommand("issue", undefined, { ...AUTH, currency: "BRL", mandateId: "m", consumerId: "c", idempotencyKey: "k" }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(HttpError); + expect((err as HttpError).code).toBe("issuer_declined"); + }); + + it("issue without --idempotency-key never reaches the network", async () => { + const { sent } = backend({ success: true, error: null, data: POMELO_VIEW }); + await expect( + cardCommand("issue", undefined, { ...AUTH, currency: "BRL", mandateId: "m", consumerId: "c" }), + ).rejects.toThrow(CliError); + expect(sent).toHaveLength(0); + }); +}); + +describe("codespar card readiness", () => { + it("GETs /v1/cards/readiness and prints the document in --json", async () => { + const doc = { programs: [{ program: "pomelo_brl", issuer: "pomelo", currency: "BRL", ready: true, requirements: [] }] }; + const urls: string[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation((input: unknown) => { + urls.push(String(input)); + return Promise.resolve(new Response(JSON.stringify(doc), { status: 200, headers: { "content-type": "application/json" } })); + }); + const out = captureStdout(); + await cardReadinessCommand({ ...AUTH, json: true }); + expect(urls).toEqual(["https://api.test.dev/v1/cards/readiness"]); + expect(JSON.parse(out.text())).toEqual(doc); + }); +}); + +describe("codespar issue (deprecated, contract §8.4)", () => { + it("warns and sends codespar_card for a new-shaped call", async () => { + const { sent } = backend({ success: true, error: null, data: POMELO_VIEW }); + const out = captureStdout(); + await issueDeprecatedCommand({ ...AUTH, input: '{"action":"get","card_id":"icrd_1"}', json: true }); + expect(out.err()).toMatch(/`codespar issue` is deprecated; use `codespar card/); + expect(sent).toEqual([{ tool: "codespar_card", input: { action: "get", card_id: "icrd_1" } }]); + }); + + it("refuses the old Pomelo shape with card_contract_migration_required, nothing sent", async () => { + const { sent } = backend({ success: true, error: null, data: POMELO_VIEW }); + captureStdout(); + const err = await issueDeprecatedCommand({ + ...AUTH, + input: '{"action":"card-virtual","cardholder_id":"usr_123","program_id":"afg_123"}', + }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CliError); + expect((err as CliError).code).toBe("card_contract_migration_required"); + expect((err as Error).message).toMatch(/codespar card issue --currency --mandate-id --consumer-id --idempotency-key/); + expect(sent).toHaveLength(0); + }); +}); diff --git a/packages/cli/src/__tests__/meta-tools.test.ts b/packages/cli/src/__tests__/meta-tools.test.ts index e6b2138a..362a905e 100644 --- a/packages/cli/src/__tests__/meta-tools.test.ts +++ b/packages/cli/src/__tests__/meta-tools.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from "vitest"; -import type { IssueArgs, LedgerArgs } from "@codespar/sdk"; +import type { CardArgs, LedgerArgs } from "@codespar/sdk"; import { validateLedgerArgs } from "../commands/ledger.js"; -import { validateIssueArgs } from "../commands/issue.js"; +import { buildCardArgs, validateCardArgs } from "../commands/card.js"; import { resolveMetaInput } from "../commands/meta-input.js"; describe("validateLedgerArgs", () => { @@ -35,32 +35,71 @@ describe("validateLedgerArgs", () => { }); }); -describe("validateIssueArgs", () => { - it("rejects an unknown action", () => { - expect(() => validateIssueArgs({ action: "nope" } as unknown as IssueArgs)).toThrow( - /action must be one of/, +describe("validateCardArgs", () => { + it("rejects an action codespar_card does not publish", () => { + expect(() => validateCardArgs({ action: "nope" } as unknown as CardArgs)).toThrow( + /action must be one of: issue, get, list, freeze, unfreeze, cancel/, ); }); - it("requires cardholder_id + program_id to issue a card", () => { - expect(() => validateIssueArgs({ action: "card-virtual" })).toThrow(/cardholder_id/); - expect(() => validateIssueArgs({ action: "card-virtual", cardholder_id: "u" })).toThrow( - /program_id/, - ); + it("an old Pomelo-shaped call names the new fields (card_contract_migration_required)", () => { + expect(() => + validateCardArgs({ action: "card-virtual", cardholder_id: "u", program_id: "p" } as unknown as CardArgs), + ).toThrow(/card_contract_migration_required.*currency \(BRL \| USD\), mandate_id, consumer_id and idempotency_key/); }); - it("requires card_id for control + get", () => { - expect(() => validateIssueArgs({ action: "card-get" })).toThrow(/card_id/); + it("issue needs currency, mandate, consumer and the idempotency key", () => { + const full = { action: "issue", currency: "BRL", mandate_id: "m", consumer_id: "c", idempotency_key: "k" } as const; + expect(() => validateCardArgs(full)).not.toThrow(); + expect(() => validateCardArgs({ ...full, currency: undefined } as unknown as CardArgs)).toThrow(/--currency/); + expect(() => validateCardArgs({ ...full, mandate_id: "" })).toThrow(/--mandate-id/); + expect(() => validateCardArgs({ ...full, consumer_id: "" })).toThrow(/--consumer-id/); + expect(() => validateCardArgs({ ...full, idempotency_key: "" })).toThrow(/--idempotency-key/); }); - it("requires a control verb for card-control", () => { - expect(() => validateIssueArgs({ action: "card-control", card_id: "c" })).toThrow(/control/); + it("currency, provider and issuer only take the published vocabulary", () => { + const full = { action: "issue", currency: "BRL", mandate_id: "m", consumer_id: "c", idempotency_key: "k" } as const; + expect(() => validateCardArgs({ ...full, currency: "EUR" } as unknown as CardArgs)).toThrow(/currency must be one of: BRL, USD/); + expect(() => validateCardArgs({ ...full, provider: "bridge" } as unknown as CardArgs)).toThrow(/provider must be one of: pomelo, rain/); + expect(() => validateCardArgs({ action: "list", issuer: "stripe" } as unknown as CardArgs)).toThrow(/issuer must be one of/); + expect(() => validateCardArgs({ ...full, currency: "USD", provider: "rain" })).not.toThrow(); }); - it("requires a shipping_address for a physical card", () => { - expect(() => - validateIssueArgs({ action: "card-physical", cardholder_id: "u", program_id: "p" }), - ).toThrow(/shipping_address/); + it("get and the controls need a card id; list does not", () => { + for (const action of ["get", "freeze", "unfreeze", "cancel"] as const) { + expect(() => validateCardArgs({ action } as unknown as CardArgs)).toThrow(/needs a card id/); + } + expect(() => validateCardArgs({ action: "list" })).not.toThrow(); + }); +}); + +describe("buildCardArgs", () => { + it("maps the flags onto the wire names and upper-cases the currency", async () => { + await expect( + buildCardArgs("issue", undefined, { currency: "usd", mandateId: "mnd_1", consumerId: "cons_1", idempotencyKey: "idem_1" }), + ).resolves.toEqual({ action: "issue", currency: "USD", mandate_id: "mnd_1", consumer_id: "cons_1", idempotency_key: "idem_1" }); + }); + + it("flags win over --input JSON, and the positional card id over both", async () => { + await expect( + buildCardArgs("freeze", "icrd_pos", { input: '{"card_id":"icrd_json","reason":"broken"}', reason: "lost" }), + ).resolves.toEqual({ action: "freeze", card_id: "icrd_pos", reason: "lost" }); + }); + + it("--reason takes only the published vocabulary; --holder is parsed as a JSON object", async () => { + await expect(buildCardArgs("cancel", "icrd_1", { reason: "because" })).rejects.toThrow(/reason must be one of: client_request, lost, stolen, broken, upgrade/); + await expect( + buildCardArgs("issue", undefined, { currency: "BRL", mandateId: "m", consumerId: "c", idempotencyKey: "k", holder: '{"full_name":"A B"}' }), + ).resolves.toMatchObject({ holder: { full_name: "A B" } }); + await expect( + buildCardArgs("issue", undefined, { currency: "BRL", mandateId: "m", consumerId: "c", idempotencyKey: "k", holder: "[1]" }), + ).rejects.toThrow(/--holder must be a JSON object/); + }); + + it("refuses JSON that names another action", async () => { + await expect(buildCardArgs("get", "icrd_1", { input: '{"action":"cancel"}' })).rejects.toThrow( + /the JSON input says action=cancel/, + ); }); }); diff --git a/packages/cli/src/commands/card.ts b/packages/cli/src/commands/card.ts new file mode 100644 index 00000000..4cc682ba --- /dev/null +++ b/packages/cli/src/commands/card.ts @@ -0,0 +1,258 @@ +import { CodeSpar, cardMigrationError } from "@codespar/sdk"; +import type { CardArgs, CardIssued, CardResult, CardView } from "@codespar/sdk"; +import { HttpError } from "../api.js"; +import { CliError } from "../config.js"; +import { metaToolActions, metaToolEnum } from "../surface.js"; +import { info, json, kv, success, table, warn } from "../output.js"; +import { resolveMetaInput } from "./meta-input.js"; + +const TOOL = "codespar_card"; + +/** Flags every `codespar card ` accepts; each action reads its own subset. */ +export interface CardFlags { + currency?: string; + provider?: string; + mandateId?: string; + consumerId?: string; + idempotencyKey?: string; + issuer?: string; + reason?: string; + /** Pomelo cardholder identity as JSON (pomelo_brl issue). */ + holder?: string; +} + +export interface CardCommandOptions extends CardFlags { + apiKey: string; + baseUrl: string; + project?: string; + user?: string; + input?: string; + inputFile?: string; + json?: boolean; +} + +const FLAG_TO_ARG: ReadonlyArray<[keyof CardFlags, string]> = [ + ["currency", "currency"], + ["provider", "provider"], + ["mandateId", "mandate_id"], + ["consumerId", "consumer_id"], + ["idempotencyKey", "idempotency_key"], + ["issuer", "issuer"], + ["reason", "reason"], +]; + +/** + * The args for one action: `--input` / `--input-file` JSON first, the flags + * over it, the positional card id over both. The subcommand names the action; + * JSON that names another one is refused rather than silently overridden. + */ +export async function buildCardArgs( + action: string, + cardId: string | undefined, + opts: CardFlags & { input?: string; inputFile?: string }, +): Promise { + const base: Record = + opts.input !== undefined || opts.inputFile !== undefined + ? await resolveMetaInput(opts, `card ${action}`, "{}") + : {}; + if (base.action !== undefined && base.action !== action) { + throw new CliError(`card ${action}: the JSON input says action=${String(base.action)}; drop it or run \`codespar card ${String(base.action)}\`.`); + } + const args: Record = { ...base, action }; + for (const [flag, arg] of FLAG_TO_ARG) { + if (opts[flag] !== undefined) args[arg] = opts[flag]; + } + if (opts.holder !== undefined) { + try { + const holder = JSON.parse(opts.holder) as unknown; + if (typeof holder !== "object" || holder === null || Array.isArray(holder)) throw new Error("not an object"); + args.holder = holder; + } catch (err) { + throw new CliError(`card ${action}: --holder must be a JSON object (${(err as Error).message}).`); + } + } + if (cardId !== undefined) args.card_id = cardId; + if (typeof args.currency === "string") args.currency = args.currency.toUpperCase(); + const card = args as unknown as CardArgs; + validateCardArgs(card); + return card; +} + +/** The SDK's migration sentence, plus the terminal spelling of the same call. */ +function cliMigrationMessage(sdkMessage: string): string { + return `${sdkMessage} In the terminal: \`codespar card issue --currency --mandate-id --consumer-id --idempotency-key [--provider]\`, \`codespar card get \`, \`codespar card freeze|unfreeze|cancel \`.`; +} + +function oneOf(field: string, value: unknown, published: readonly string[]): void { + if (value === undefined) return; + if (typeof value !== "string" || !published.includes(value)) { + throw new CliError(`card.${field} must be one of: ${published.join(", ")}.`); + } +} + +/** Refuse locally what the server would refuse anyway. Vocabularies come from the published definition. */ +export function validateCardArgs(args: CardArgs): void { + const migration = cardMigrationError(args); + if (migration) throw new CliError(cliMigrationMessage(migration.message), { code: migration.code }); + const actions = metaToolActions(TOOL); + if (!args.action || !actions.includes(args.action)) { + throw new CliError(`card.action must be one of: ${actions.join(", ")}.`); + } + const a = args as unknown as Record; + oneOf("currency", a.currency, metaToolEnum(TOOL, "currency")); + oneOf("provider", a.provider, metaToolEnum(TOOL, "provider")); + oneOf("issuer", a.issuer, metaToolEnum(TOOL, "issuer")); + oneOf("reason", a.reason, metaToolEnum(TOOL, "reason")); + if (args.action === "issue") { + if (!args.currency) throw new CliError("card issue needs --currency (BRL | USD)."); + if (!args.mandate_id) throw new CliError("card issue needs --mandate-id."); + if (!args.consumer_id) throw new CliError("card issue needs --consumer-id."); + if (!args.idempotency_key) { + throw new CliError( + "card issue needs --idempotency-key. Keep the key: running the same command again with it resumes the same request and never issues a second card.", + ); + } + } + if (args.action !== "issue" && args.action !== "list" && !args.card_id) { + throw new CliError(`card ${args.action} needs a card id (icrd_... or rcrd_...).`); + } +} + +function viewPairs(v: CardView): Array<[string, string]> { + const pairs: Array<[string, string]> = [ + ["Id", v.id], + ["Issuer", v.issuer], + ["Program", v.program], + ["Currency", v.currency], + ["Status", v.issuer_status ? `${v.status} (${v.issuer_status})` : v.status], + ["Actions", v.available_actions.length > 0 ? v.available_actions.join(", ") : "none"], + ]; + if (v.last4) pairs.push(["Last four", v.last4]); + if (v.funding) pairs.push(["Funding", v.funding.asset]); + if (v.mandate_id) pairs.push(["Mandate", v.mandate_id]); + if (v.consumer_id) pairs.push(["Consumer", v.consumer_id]); + return pairs; +} + +/** + * Print a result, or throw for a refusal or a definitive `failed`. The + * non-final issue states (`pending_human`, `processing`, `uncertain`) are + * not failures (REST answers 202): they print what happens next and exit 0, + * and a script branches on `state` in `--json`. None of them ever suggests a + * new key: processing and uncertain resolve on the same one. + */ +export function renderCardResult(action: string, result: CardResult, asJson: boolean): void { + if (result.state === "refused") { + throw new HttpError( + `card ${action} refused: ${result.code}${result.reason ? ` (${result.reason})` : ""}${result.message ? ` — ${result.message}` : ""}`, + { status: result.http_status, code: result.code, body: result }, + ); + } + if (result.state === "failed") { + // A definitive refusal by the issuer: a failure for the exit code too. + throw new HttpError( + `card issue failed at ${result.issuer}/${result.program}${result.code ? `: ${result.code}` : ""}${result.reason ? ` (${result.reason})` : ""}${result.message ? ` — ${result.message}` : ""}`, + { status: 200, code: result.code ?? "card_issue_failed", body: result }, + ); + } + if (asJson) { + json(result); + return; + } + if (result.state === "pending_human") { + warn(`card issue waiting on a person at ${result.issuer}/${result.program}: ${result.pending_action.kind}, for the ${result.pending_action.actor}`); + if (result.pending_action.url) info(`Hand this to them: ${result.pending_action.url}`); + info(`Request: ${result.issue_request_id}. Once it is done, run the same command with the same --idempotency-key.`); + return; + } + if (result.state === "processing") { + warn(`card issue processing at ${result.issuer}/${result.program}: the issuer has not answered yet.`); + info(`Request: ${result.issue_request_id}. Run the same command with the same --idempotency-key to read where it stands.`); + return; + } + if (result.state === "uncertain") { + warn(`card issue uncertain at ${result.issuer}/${result.program}: the issuer's answer was lost or ambiguous, and the card MAY exist.`); + info( + `Request: ${result.issue_request_id}. It reconciles on the same key: run the same command with the SAME --idempotency-key. Do not use a new key; that would be a second issuance.`, + ); + return; + } + if ("cards" in result) { + table( + ["ID", "ISSUER", "PROGRAM", "CURRENCY", "STATUS", "ACTIONS"], + result.cards.map((v) => [v.id, v.issuer, v.program, v.currency, v.status, v.available_actions.join(",") || "-"]), + ); + return; + } + if (result.state === "issued") { + success(`card issue → ${result.card.status} (request ${result.issue_request_id})`); + kv(viewPairs(result.card)); + // `selection` is read defensively: the contract always sends it, but a + // missing one must not crash the print of a card that was in fact issued. + const selection = result.selection as CardIssued["selection"] | undefined; + if (selection) { + info(`Selection: ${selection.chosen_by === "provider" ? `provider ${selection.provider_requested ?? ""}` : "by currency"}`); + } + return; + } + success(`card ${action} → ${result.status}`); + kv(viewPairs(result)); +} + +/** + * Wraps `session.card(args)` — issue, read, list, freeze, unfreeze or cancel + * a card on whichever issuer the server resolves (BRL -> pomelo_brl, USD -> + * rain_usd). The meta-tool router resolves the rail, so no `--server`. + */ +export async function cardCommand(action: string, cardId: string | undefined, opts: CardCommandOptions): Promise { + const args = await buildCardArgs(action, cardId, opts); + + const cs = new CodeSpar({ apiKey: opts.apiKey, baseUrl: opts.baseUrl, projectId: opts.project }); + const session = await cs.create(opts.user ?? "cli-user", { servers: [] }); + try { + const result = await session.card(args); + renderCardResult(action, result, opts.json === true); + } finally { + await session.close(); + } +} + +/** `codespar card readiness`: `GET /v1/cards/readiness`, per program what is missing and who must act. */ +export async function cardReadinessCommand(opts: { apiKey: string; baseUrl: string; project?: string; json?: boolean }): Promise { + const cs = new CodeSpar({ apiKey: opts.apiKey, baseUrl: opts.baseUrl, projectId: opts.project }); + const readiness = await cs.cards.readiness(); + if (opts.json) { + json(readiness); + return; + } + for (const p of readiness.programs) { + (p.ready ? success : warn)(`${p.program} (${p.issuer}, ${p.currency}): ${p.ready ? "ready" : "not ready"}`); + table( + ["REQUIREMENT", "STATUS", "ACTOR", "DETAIL"], + p.requirements.map((r) => [r.kind, r.status, r.actor, r.action_url ?? r.reason ?? "-"]), + ); + } +} + +/** + * The deprecated `codespar issue` (contract §8.4): a wrapper over + * `codespar card `. It takes the JSON it always took, warns, and + * refuses the old Pomelo shape with the new fields named. + */ +export async function issueDeprecatedCommand(opts: Omit): Promise { + warn("`codespar issue` is deprecated; use `codespar card issue|get|list|freeze|unfreeze|cancel`. It sends codespar_card with the same validations."); + const raw = await resolveMetaInput(opts, "issue", '{"action":"issue","currency":"BRL","mandate_id":"mnd_...","consumer_id":"cons_...","idempotency_key":"..."}'); + const migration = cardMigrationError(raw as unknown as CardArgs); + if (migration) { + throw new CliError(cliMigrationMessage(migration.message), { code: migration.code }); + } + const action = typeof raw.action === "string" ? raw.action : ""; + if (!metaToolActions(TOOL).includes(action)) { + throw new CliError(`issue: action must be one of: ${metaToolActions(TOOL).join(", ")}.`); + } + const rest: Record = { ...raw }; + delete rest.action; + delete rest.card_id; + const cardId = typeof raw.card_id === "string" ? raw.card_id : undefined; + await cardCommand(action, cardId, { ...opts, input: JSON.stringify(rest), inputFile: undefined }); +} diff --git a/packages/cli/src/commands/issue.ts b/packages/cli/src/commands/issue.ts deleted file mode 100644 index 470f41d4..00000000 --- a/packages/cli/src/commands/issue.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { CodeSpar } from "@codespar/sdk"; -import type { IssueArgs, IssueResult } from "@codespar/sdk"; -import { CliError } from "../config.js"; -import { info, json, success } from "../output.js"; -import { resolveMetaInput } from "./meta-input.js"; - -interface IssueCommandOptions { - apiKey: string; - baseUrl: string; - project?: string; - user?: string; - input?: string; - inputFile?: string; - json?: boolean; -} - -const EXAMPLE = - '{"action":"card-virtual","cardholder_id":"usr_123","program_id":"afg_123"}'; - -/** - * Wraps `session.issue(args)` — issue a virtual/physical agent spend card, - * freeze/unfreeze/cancel one, or read a card's status (Pomelo). The - * meta-tool router resolves the rail, so no `--server`. - */ -export async function issueCommand(opts: IssueCommandOptions): Promise { - const args = (await resolveMetaInput(opts, "issue", EXAMPLE)) as unknown as IssueArgs; - validateIssueArgs(args); - - const userId = opts.user ?? "cli-user"; - const cs = new CodeSpar({ - apiKey: opts.apiKey, - baseUrl: opts.baseUrl, - projectId: opts.project, - }); - const session = await cs.create(userId, { servers: [] }); - - try { - const result: IssueResult = await session.issue(args); - - if (opts.json) { - json(result); - return; - } - - success(`issue ${args.action} → ${result.status ?? "ok"}`); - if (result.id) info(`Card id: ${result.id}`); - if (result.card_type) info(`Type: ${result.card_type}`); - if (result.last_four) info(`Last four: ${result.last_four}`); - if (result.cardholder_id) info(`Cardholder: ${result.cardholder_id}`); - } finally { - await session.close(); - } -} - -export function validateIssueArgs(args: IssueArgs): void { - const actions = ["card-virtual", "card-physical", "card-control", "card-get"]; - if (!args.action || !actions.includes(args.action)) { - throw new CliError(`issue.action must be one of: ${actions.join(", ")}.`); - } - if (args.action === "card-virtual" || args.action === "card-physical") { - if (!args.cardholder_id) throw new CliError("issue.cardholder_id is required to issue a card."); - if (!args.program_id) throw new CliError("issue.program_id is required to issue a card."); - } - if (args.action === "card-physical" && !args.shipping_address) { - throw new CliError("issue.shipping_address is required when action=card-physical."); - } - if ((args.action === "card-control" || args.action === "card-get") && !args.card_id) { - throw new CliError("issue.card_id is required when action=card-control | card-get."); - } - if (args.action === "card-control" && !args.control) { - throw new CliError("issue.control (freeze | unfreeze | cancel) is required when action=card-control."); - } -} diff --git a/packages/cli/src/commands/meta-input.ts b/packages/cli/src/commands/meta-input.ts index 8bda8569..f1482c39 100644 --- a/packages/cli/src/commands/meta-input.ts +++ b/packages/cli/src/commands/meta-input.ts @@ -3,7 +3,7 @@ import { CliError } from "../config.js"; /** * Resolve a meta-tool command's args from `--input ''` or - * `--input-file `. Shared by the `ledger` / `issue` commands (and + * `--input-file `. Shared by the `ledger` / `card` commands (and * a good target for charge/ship to migrate onto). Returns a parsed JSON * object or throws a CliError with an actionable message. */ diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index a01db25b..abe4de34 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -36,7 +36,7 @@ import { paymentStatusCommand } from "./commands/payment-status.js"; import { verificationStatusCommand } from "./commands/verification-status.js"; import { wizardCommand } from "./commands/wizard.js"; import { ledgerCommand } from "./commands/ledger.js"; -import { issueCommand } from "./commands/issue.js"; +import { cardCommand, cardReadinessCommand, issueDeprecatedCommand, type CardFlags } from "./commands/card.js"; import { listMetaToolsCommand, metaToolCommand, @@ -863,22 +863,82 @@ program }, ); +// ============ card: codespar_card, one contract for Pomelo (BRL) and Rain (USD) ============ +const card = program + .command("card") + .description("Issue / read / list / freeze / unfreeze / cancel spend cards via codespar_card (BRL on Pomelo, USD on Rain)"); + +type CardCliOpts = CardFlags & { input?: string; inputFile?: string; user?: string }; + +function cardSubcommand(name: string, description: string, takesCardId: boolean) { + const cmd = card + .command(takesCardId ? `${name} ` : name) + .description(description) + .option("-i, --input ", "Card args as JSON string (flags win over it)") + .option("-f, --input-file ", "Card args from JSON file (flags win over it)") + .option("-u, --user ", "User id for the session (default: cli-user)"); + return cmd; +} + +cardSubcommand("issue", "Issue a card; the currency picks the program unless --provider names one", false) + .option("--currency ", "BRL | USD (required)") + .option("--provider ", "pomelo | rain (optional)") + .option("--mandate-id ", "Mandate the card spends under; its currency must equal the card's (required)") + .option("--consumer-id ", "Card holder, a consumer of this project (required)") + .option("--idempotency-key ", "Required. The same key resumes the same request; it never issues a second card") + .option("--holder ", "Pomelo cardholder identity as JSON (pomelo_brl): full_name, email, birthdate, document, address, phone?") + .action(async (opts: CardCliOpts) => { + const auth = await resolveAuth(); + await cardCommand("issue", undefined, { ...opts, ...auth, json: rootJsonFlag() }); + }); + +cardSubcommand("get", "Read one card (icrd_... Pomelo, rcrd_... Rain)", true).action( + async (cardId: string, opts: CardCliOpts) => { + const auth = await resolveAuth(); + await cardCommand("get", cardId, { ...opts, ...auth, json: rootJsonFlag() }); + }, +); + +cardSubcommand("list", "List cards of both issuers", false) + .option("--issuer ", "pomelo | rain") + .option("--mandate-id ", "Only cards under this mandate") + .option("--consumer-id ", "Only cards of this holder") + .action(async (opts: CardCliOpts) => { + const auth = await resolveAuth(); + await cardCommand("list", undefined, { ...opts, ...auth, json: rootJsonFlag() }); + }); + +card + .command("readiness") + .description("Per program: ready or not, and what is missing (GET /v1/cards/readiness), each step naming who must act") + .action(async () => { + const auth = await resolveAuth(); + await cardReadinessCommand({ ...auth, json: rootJsonFlag() }); + }); + program .command("issue") - .description("Issue / freeze / read agent spend cards via codespar_issue (Pomelo)") - .option("-i, --input ", "Issue args as JSON string") - .option("-f, --input-file ", "Issue args from JSON file") + .description("DEPRECATED: use `codespar card`. Sends codespar_card with the same validations") + .option("-i, --input ", "codespar_card args as JSON string (the old Pomelo shape is refused)") + .option("-f, --input-file ", "codespar_card args from JSON file") .option("-u, --user ", "User id for the session (default: cli-user)") - .action( - async (opts: { input?: string; inputFile?: string; user?: string }) => { + .action(async (opts: { input?: string; inputFile?: string; user?: string }) => { + const auth = await resolveAuth(); + await issueDeprecatedCommand({ ...opts, ...auth, json: rootJsonFlag() }); + }); + +for (const [name, what] of [ + ["freeze", "Freeze a card (when its available_actions allow it)"], + ["unfreeze", "Unfreeze a frozen card (when its available_actions allow it)"], + ["cancel", "Cancel a card for good (when its available_actions allow it)"], +] as const) { + cardSubcommand(name, what, true) + .option("--reason ", "client_request | lost | stolen | broken | upgrade") + .action(async (cardId: string, opts: CardCliOpts) => { const auth = await resolveAuth(); - await issueCommand({ - ...opts, - ...auth, - json: rootJsonFlag(), - }); - }, - ); + await cardCommand(name, cardId, { ...opts, ...auth, json: rootJsonFlag() }); + }); +} // ============ audit ============ const audit = program diff --git a/packages/cli/src/surface.ts b/packages/cli/src/surface.ts index a48c8970..854f970c 100644 --- a/packages/cli/src/surface.ts +++ b/packages/cli/src/surface.ts @@ -629,7 +629,7 @@ export const SURFACE_EXCEPTIONS: Readonly> = { since: "2026-09-10", }, cards: { - reason: "Single card read. Reachable as `codespar tool codespar_issue --action card-get`.", + reason: "Card reads and controls. `codespar card get|list|freeze|unfreeze|cancel` (through codespar_card, the same server path as these routes) and `codespar card readiness` (`GET /v1/cards/readiness`) are the terminal entrances.", since: "2026-09-10", }, "funding-sources": { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index f10b4c7b..5a869384 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,30 @@ # @codespar/sdk — CHANGELOG +## 0.17.0 — unreleased (coordinated codespar_card release) + +### Added + +- **`session.card(args)`** calls `codespar_card`: one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`). + - `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`, checked before anything is sent. `provider` is optional, and the currency picks the program when it is omitted. + - Results narrow on `state`: + - `"issued"`; + - `"pending_human"`: a `pending_action` for `holder`, `company_signatory` or `org_admin`; + - `"processing"` and `"uncertain"`: the card MAY exist, so call again with the SAME key, never a new one; + - `"failed"`: a definitive refusal by the issuer; + - `"refused"`: a stable `code`, `reason`, `available_programs`, `available_actions` and `http_status`. The refusal is **returned**, whether it came in the tool envelope or as a non-2xx body. + - A result with no `state` is a card view or `{ cards }`. Only a failure with no code throws. +- **`cs.cards.readiness()`** reads `GET /v1/cards/readiness`: per program, ready or not and the checklist of what is missing. +- `CardContractMigrationError` and `cardMigrationError()`: a call in the old Pomelo shape (`card-*` actions, `cardholder_id`, `program_id`, `control`, `shipping_address`, `metadata`) is refused before anything is sent, with the new fields named. +- Depends on `@codespar/types ^0.12.0`. The fake session in `@codespar/sdk/testing` implements `card()`. + +### Deprecated + +- **`session.issue(args)`** is a wrapper over `session.card(args)`. It sends `codespar_card` with the same validations and warns once per process (`console.warn`). An old-shaped call throws `CardContractMigrationError`; the server answers the same call through its deprecated alias with `card_contract_migration_required`. No path keeps the old Pomelo-only validation. + +### Changed + +- Generated OpenAPI: see the PR body for the candidate enterprise SHA it was generated from. + ## 0.16.30 — 2026-11-15 ### Security diff --git a/packages/core/README.md b/packages/core/README.md index 083edf62..65226494 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -12,6 +12,7 @@ Eight new typed methods on `Session`, grouped by capability: - `session.charge(args)` — INBOUND charges (`codespar_charge`). Buyer pays merchant. Pix BRL via Asaas / MP / iugu / Stone; card USD via Stripe. Distinct from `codespar_pay` (outbound transfers). - `session.ship(args)` — shipping (`codespar_ship`). One typed entry into Melhor Envio's 3 rails (`action: "label" | "quote" | "track"`). +- `session.card(args)` — spend cards (`codespar_card`), one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`): `action: "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"`. `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`; `provider` is optional (the currency picks the program). Narrow the result on `state`: `"issued"` (card view + `selection`), `"pending_human"` (a `pending_action` only a person can take: `holder`, `company_signatory` or `org_admin`), `"processing"` and `"uncertain"` (the card MAY exist: call again with the SAME key, never a new one), `"failed"` (definitive issuer refusal), `"refused"` (a stable `code`, `reason`, `available_programs` / `available_actions`, returned rather than thrown); no `state` is a card view or `{ cards }`. `cs.cards.readiness()` reads `GET /v1/cards/readiness`, per program the checklist of what is missing. `session.issue()` is deprecated: it warns once and calls the same `codespar_card`; a call in the old Pomelo shape throws `CardContractMigrationError` naming the new fields. - `session.shop(args)` — buy-side shopping (`codespar_shop`). Catalog search → async checkout → Pix mint (`action: "search" | "checkout" | "checkout_status"`). Discriminated `ShopArgs`/`ShopResult` give the action-correct result type. Checkout is async: start, then poll `checkout_status` until `ready_for_payment` (carries `pix_copia_e_cola`) or `canceled`. Settle the returned Pix via a separate payment tool — settlement and governance are out of this contract. Full spec: [`docs/codespar-shop-contract.md`](../../docs/codespar-shop-contract.md). **Async settlement** — `codespar_charge` / `codespar_pay` return synchronously, but real settlement lands via webhook: diff --git a/packages/core/package.json b/packages/core/package.json index c67ae742..999d8058 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/sdk", - "version": "0.16.30", + "version": "0.17.0", "description": "Commerce SDK for AI agents \u2014 sessions, managed auth, Complete Loop orchestration for Latin American APIs", "type": "module", "main": "./dist/index.js", @@ -58,7 +58,7 @@ "node": ">=20" }, "dependencies": { - "@codespar/types": "^0.10.1 || ^0.11.0", + "@codespar/types": "^0.12.0", "zod": "^4.6.6" }, "devDependencies": { diff --git a/packages/core/scripts/openapi-spec.mjs b/packages/core/scripts/openapi-spec.mjs index d2441dfe..794a9dd1 100644 --- a/packages/core/scripts/openapi-spec.mjs +++ b/packages/core/scripts/openapi-spec.mjs @@ -10,6 +10,17 @@ // node scripts/openapi-spec.mjs generate snapshot -> src/generated/* // node scripts/openapi-spec.mjs refresh served -> snapshot -> src/generated/* // node scripts/openapi-spec.mjs check exit 1 when anything is stale +// node scripts/openapi-spec.mjs refresh --from-file //openapi-candidate.json +// a CANDIDATE document (enterprise head, not served) +// -> snapshot -> src/generated/* +// node scripts/openapi-spec.mjs assert-served +// exit 1 when the snapshot is a candidate +// +// A candidate snapshot records `source: "candidate:/openapi-candidate.json"`. +// It exists so a draft can be reviewed against the enterprise head before +// that head is served (cards contract §8.6). It must never be published: +// `assert-served` runs in the publish workflow and refuses it, so publish day +// is `refresh` (from the served document) first. // // `check` answers three questions, in order: // 1. does the snapshot's recorded sha256 match its own document @@ -273,10 +284,40 @@ async function generate() { return 0; } -async function refresh() { - const served = await fetchServed(); +export const CANDIDATE_SOURCE = /^candidate:([0-9a-f]{7,40})\/openapi-candidate\.json$/; + +/** A candidate document from disk; the enterprise SHA is the name of its directory. */ +export function readCandidate(file) { + const sha = path.basename(path.dirname(path.resolve(file))); + if (!/^[0-9a-f]{7,40}$/.test(sha) || path.basename(file) !== "openapi-candidate.json") { + throw new Error( + `${file}: expected //openapi-candidate.json, so the snapshot can record which head it came from`, + ); + } + const document = JSON.parse(fs.readFileSync(file, "utf8")); + if (!document.openapi || !document.paths) { + throw new Error(`${file} is not an OpenAPI document (no openapi/paths)`); + } + return { document, source: `candidate:${sha}/openapi-candidate.json`, etag: null, lastModified: null }; +} + +async function assertServed() { + const snapshot = readSnapshot(); + if (CANDIDATE_SOURCE.test(snapshot.snapshot.source)) { + console.error( + `assert-served: ${path.relative(PKG_ROOT, SNAPSHOT_PATH)} was generated from ${snapshot.snapshot.source}, an enterprise candidate, ` + + "not the served document. Run `npm run spec:refresh` against the served API before publishing.", + ); + return 1; + } + console.log(`assert-served: snapshot source ${snapshot.snapshot.source}`); + return 0; +} + +async function refresh(fromFile) { + const served = fromFile ? readCandidate(fromFile) : { ...(await fetchServed()), source: SPEC_URL }; const snapshot = buildSnapshot(served.document, { - source: SPEC_URL, + source: served.source, fetchedAt: new Date().toISOString(), etag: served.etag, lastModified: served.lastModified, @@ -284,7 +325,7 @@ async function refresh() { writeSnapshot(snapshot); await writeGenerated(snapshot); console.log( - `refresh: snapshot ${snapshot.snapshot.sha256.slice(0, 12)} from ${SPEC_URL} ` + + `refresh: snapshot ${snapshot.snapshot.sha256.slice(0, 12)} from ${served.source} ` + `(API ${snapshot.snapshot.info.version}, ${snapshot.snapshot.paths} paths, ` + `${snapshot.snapshot.operations} operations)`, ); @@ -397,12 +438,20 @@ async function main(argv) { switch (mode) { case "generate": return generate(); - case "refresh": - return refresh(); + case "refresh": { + const i = flags.indexOf("--from-file"); + if (i !== -1 && !flags[i + 1]) { + console.error("usage: openapi-spec.mjs refresh [--from-file //openapi-candidate.json]"); + return 2; + } + return refresh(i === -1 ? undefined : flags[i + 1]); + } + case "assert-served": + return assertServed(); case "check": return check({ offline }); default: - console.error("usage: openapi-spec.mjs "); + console.error("usage: openapi-spec.mjs ]|check [--offline]|assert-served>"); return 2; } } diff --git a/packages/core/src/__tests__/card.test.ts b/packages/core/src/__tests__/card.test.ts new file mode 100644 index 00000000..76061809 --- /dev/null +++ b/packages/core/src/__tests__/card.test.ts @@ -0,0 +1,384 @@ +/** + * codespar_card typed facade tests (enterprise CONTRATO-codespar-card §3-§6). + * + * Drives the real `createSession` facade with a mocked `fetch`: the wire + * dispatch (`tool` + `input`) is asserted on the `/execute` call, and each + * answer shape (issued, pending, card view, list, refusal in the envelope, + * refusal as a non-2xx body, failure with no code) is asserted on the result. + */ + +import { describe, it, expect, vi, afterEach } from "vitest"; +import type { CardArgs, CardReadiness, CardView, IssueArgs, Session, ToolResult } from "@codespar/types"; +import { createSession } from "../session.js"; +import { CardContractMigrationError, resetIssueDeprecationWarning } from "../card.js"; +import { CodeSpar } from "../index.js"; +import { CodesparApiError } from "../errors.js"; + +interface ExecCall { + tool: string; + input: Record; +} + +type ExecAnswer = + | { kind: "envelope"; envelope: Partial } + | { kind: "http"; status: number; body: string }; + +async function sessionAnswering(answer: ExecAnswer): Promise<{ session: Session; calls: ExecCall[] }> { + const calls: ExecCall[] = []; + const fetchMock = vi.fn(async (url: string, init?: { body?: string }) => { + if (typeof url === "string" && url.endsWith("/execute")) { + calls.push(JSON.parse(init?.body ?? "{}") as ExecCall); + if (answer.kind === "http") { + return { ok: false, status: answer.status, text: async () => answer.body, json: async () => JSON.parse(answer.body) }; + } + const env = { success: true, data: null, error: null, duration: 1, server: "_codespar", tool: "codespar_card", ...answer.envelope }; + return { ok: true, status: 200, text: async () => "", json: async () => env }; + } + return { + ok: true, + status: 201, + text: async () => "", + json: async () => ({ + id: "ses_card", + org_id: "org_test", + user_id: "consumer_123", + servers: [], + status: "active", + created_at: new Date().toISOString(), + closed_at: null, + }), + }; + }); + globalThis.fetch = fetchMock as unknown as typeof fetch; + const session = await createSession( + "consumer_123", + { servers: [] }, + { baseUrl: "https://api.example.com", apiKey: "csk_live_test", timeout: 60000 }, + ); + return { session, calls }; +} + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); +}); + +const RAIN_VIEW: CardView = { + id: "rcrd_abc", + issuer: "rain", + program: "rain_usd", + currency: "USD", + status: "not_activated", + issuer_status: "notActivated", + last4: "1234", + network: null, + mandate_id: "mnd_usd", + consumer_id: "cons_1", + created_at: "2026-11-18T12:00:00.000Z", + available_actions: [], + funding: { asset: "USDC" }, +}; + +function issued(card: CardView) { + return { + state: "issued", + issue_request_id: "cir_1", + issuer: card.issuer, + program: card.program, + selection: { provider_requested: null, chosen_by: "currency" }, + card, + authorization_id: "caia_1", + authorization_active: true, + }; +} + +const ISSUE_USD: CardArgs = { + action: "issue", + currency: "USD", + mandate_id: "mnd_usd", + consumer_id: "cons_1", + idempotency_key: "idem_1", +}; + +describe("session.card facade", () => { + it("dispatches execute('codespar_card', args) verbatim", async () => { + const { session, calls } = await sessionAnswering({ + kind: "envelope", + envelope: { data: issued(RAIN_VIEW) }, + }); + await session.card(ISSUE_USD); + expect(calls).toHaveLength(1); + expect(calls[0]!.tool).toBe("codespar_card"); + expect(calls[0]!.input).toEqual(ISSUE_USD); + }); + + it("issue: an issued card comes back with state=issued, selection, the authorization and the nested card view", async () => { + const { session } = await sessionAnswering({ + kind: "envelope", + envelope: { data: issued(RAIN_VIEW) }, + }); + const r = await session.card(ISSUE_USD); + expect(r.state).toBe("issued"); + if (r.state !== "issued") throw new Error("unreachable"); + expect(r.issuer).toBe("rain"); + expect(r.program).toBe("rain_usd"); + expect(r.issue_request_id).toBe("cir_1"); + expect(r.card.currency).toBe("USD"); + expect(r.card.funding).toEqual({ asset: "USDC" }); + expect(r.card.network).toBeNull(); + expect(r.selection).toEqual({ provider_requested: null, chosen_by: "currency" }); + expect(r.card.available_actions).toEqual([]); + expect(r.authorization_active).toBe(true); + }); + + it("issue: a pending_human answer is returned as-is with its pending_action", async () => { + const pending = { + state: "pending_human", + issue_request_id: "cir_2", + issuer: "pomelo", + program: "pomelo_brl", + pending_action: { id: "pa_1", kind: "authorize_automated_issuance", actor: "company_signatory", url: "https://codespar.dev/dashboard/x" }, + }; + const { session } = await sessionAnswering({ kind: "envelope", envelope: { data: pending } }); + const r = await session.card({ ...ISSUE_USD, currency: "BRL", provider: "pomelo" }); + expect(r).toEqual(pending); + if (r.state !== "pending_human") throw new Error("unreachable"); + expect(r.pending_action.kind).toBe("authorize_automated_issuance"); + }); + + it("issue without idempotency_key is refused before anything is sent", async () => { + const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); + await expect( + session.card({ ...ISSUE_USD, idempotency_key: "" }), + ).rejects.toThrow(/idempotency_key is required/); + expect(calls).toHaveLength(0); + }); + + it("get / freeze: the card view comes back untouched, no state stamped", async () => { + const view: CardView = { ...RAIN_VIEW, id: "icrd_1", issuer: "pomelo", program: "pomelo_brl", currency: "BRL", status: "blocked", issuer_status: "BLOCKED", available_actions: ["unfreeze", "cancel"] }; + delete (view as { funding?: unknown }).funding; + const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: view } }); + const r = await session.card({ action: "freeze", card_id: "icrd_1", reason: "lost" }); + expect(r).toEqual(view); + expect(r.state).toBeUndefined(); + expect(calls[0]!.input).toEqual({ action: "freeze", card_id: "icrd_1", reason: "lost" }); + }); + + it("list: { cards } comes back as-is", async () => { + const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: { cards: [RAIN_VIEW] } } }); + const r = await session.card({ action: "list", issuer: "rain" }); + expect("cards" in r && r.cards).toEqual([RAIN_VIEW]); + expect(calls[0]!.input).toEqual({ action: "list", issuer: "rain" }); + }); + + it("a strategy refusal in the envelope is RETURNED as CardRefusal, details lifted", async () => { + const programs = [ + { program: "pomelo_brl", issuer: "pomelo", currency: "BRL", available: true, operations: ["issue", "get", "list", "freeze", "unfreeze", "cancel"] }, + { program: "rain_usd", issuer: "rain", currency: "USD", available: false, reason: "live_blocked", operations: ["issue", "get", "list"] }, + ]; + const { session } = await sessionAnswering({ + kind: "envelope", + envelope: { + success: false, + error: "Rain is not available for this project", + data: { + error: "Rain is not available for this project", + code: "card_issuer_unavailable", + details: { reason: "live_blocked", available_programs: programs }, + }, + }, + }); + const r = await session.card(ISSUE_USD); + expect(r.state).toBe("refused"); + if (r.state !== "refused") throw new Error("unreachable"); + expect(r.code).toBe("card_issuer_unavailable"); + expect(r.reason).toBe("live_blocked"); + expect(r.message).toBe("Rain is not available for this project"); + expect(r.available_programs).toEqual(programs); + expect(r.http_status).toBe(200); + }); + + it("the enterprise tool-result refusal { error: { code, message, details }, http_status } is read as-is", async () => { + const { session } = await sessionAnswering({ + kind: "envelope", + envelope: { + success: false, + error: "card_issuer_unavailable", + data: { + error: { + code: "card_issuer_unavailable", + message: "rain_usd is not available here", + details: { reason: "live_blocked", available_programs: [{ program: "pomelo_brl", issuer: "pomelo", currency: "BRL" }] }, + }, + http_status: 422, + }, + }, + }); + const r = await session.card(ISSUE_USD); + if (r.state !== "refused") throw new Error("expected a refusal"); + expect(r).toMatchObject({ + code: "card_issuer_unavailable", + message: "rain_usd is not available here", + reason: "live_blocked", + http_status: 422, + available_programs: [{ program: "pomelo_brl", issuer: "pomelo", currency: "BRL" }], + }); + }); + + it("card_action_unsupported carries issuer, program, action and available_actions", async () => { + const { session } = await sessionAnswering({ + kind: "envelope", + envelope: { + success: false, + error: "freeze is not supported on rain_usd", + data: { error: "freeze is not supported on rain_usd", code: "card_action_unsupported", details: { issuer: "rain", program: "rain_usd", action: "freeze", available_actions: [] } }, + }, + }); + const r = await session.card({ action: "freeze", card_id: "rcrd_abc" }); + if (r.state !== "refused") throw new Error(`expected a refusal, got ${JSON.stringify(r)}`); + expect(r).toMatchObject({ code: "card_action_unsupported", issuer: "rain", program: "rain_usd", action: "freeze", available_actions: [] }); + }); + + it("a non-2xx answer with a coded JSON body (scope refusal, 409 conflict) is a CardRefusal too", async () => { + const { session } = await sessionAnswering({ + kind: "http", + status: 409, + body: JSON.stringify({ error: "idempotency_key_conflict", message: "same key, different body" }), + }); + const r = await session.card(ISSUE_USD); + if (r.state !== "refused") throw new Error("expected a refusal"); + expect(r.code).toBe("idempotency_key_conflict"); + expect(r.message).toBe("same key, different body"); + expect(r.http_status).toBe(409); + }); + + it("a failure with no stable code still throws (tool not registered)", async () => { + const { session } = await sessionAnswering({ + kind: "envelope", + envelope: { success: false, data: null, error: "Tool not registered: codespar_card" }, + }); + await expect(session.card({ action: "get", card_id: "icrd_1" })).rejects.toThrow( + /card failed: Tool not registered: codespar_card/, + ); + }); + + it.each(["processing", "uncertain", "failed"] as const)( + "issue: a %s answer is returned as received, never stamped issued (contract §8.3)", + async (state) => { + const data = { state, issue_request_id: "cir_3", issuer: "rain", program: "rain_usd" }; + const { session } = await sessionAnswering({ kind: "envelope", envelope: { data } }); + const r = await session.card(ISSUE_USD); + expect(r).toEqual(data); + expect(r.state).toBe(state); + }, + ); + + it("an issue answer in an unknown state throws instead of passing as issued", async () => { + for (const data of [{ state: "pending" }, RAIN_VIEW]) { + const { session } = await sessionAnswering({ kind: "envelope", envelope: { data } }); + await expect(session.card(ISSUE_USD)).rejects.toThrow(/unexpected issue state/); + } + }); + + it("card_oauth_not_bound comes back as a refusal like any coded one", async () => { + const { session } = await sessionAnswering({ + kind: "envelope", + envelope: { success: false, error: "token not bound", data: { error: "token not bound", code: "card_oauth_not_bound" } }, + }); + const r = await session.card(ISSUE_USD); + expect(r).toMatchObject({ state: "refused", code: "card_oauth_not_bound" }); + }); +}); + +describe("session.issue (deprecated, contract §8.4)", () => { + it("warns once and sends codespar_card with the same args", async () => { + resetIssueDeprecationWarning(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const { session, calls } = await sessionAnswering({ + kind: "envelope", + envelope: { data: issued(RAIN_VIEW) }, + }); + const r = await session.issue(ISSUE_USD); + await session.issue(ISSUE_USD); + expect(r.state).toBe("issued"); + expect(calls.map((c) => c.tool)).toEqual(["codespar_card", "codespar_card"]); + expect(calls[0]!.input).toEqual(ISSUE_USD); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]![0])).toMatch(/session\.issue\(\) is deprecated; use session\.card\(\)/); + warn.mockRestore(); + }); + + it("keeps the same validations: no idempotency_key, nothing sent", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); + await expect(session.issue({ ...ISSUE_USD, idempotency_key: "" })).rejects.toThrow(/idempotency_key is required/); + expect(calls).toHaveLength(0); + }); + + it.each([ + [{ action: "card-virtual", cardholder_id: "usr_1", program_id: "afg_1" }, /action "card-virtual", "cardholder_id", "program_id"/], + [{ action: "card-get", card_id: "icrd_1" }, /card\(\{ action: "get", card_id \}\)/], + [{ action: "card-control", card_id: "icrd_1", control: "freeze" }, /"freeze" \| "unfreeze" \| "cancel"/], + ] as const)("an old Pomelo-shaped call is refused before anything is sent: %j", async (args, message) => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); + const err = await session.issue(args as unknown as IssueArgs).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CardContractMigrationError); + expect((err as CardContractMigrationError).code).toBe("card_contract_migration_required"); + expect((err as Error).message).toMatch(message); + expect((err as Error).message).toMatch(/currency \(BRL \| USD\), mandate_id, consumer_id and idempotency_key/); + expect(calls).toHaveLength(0); + }); + + it("card() refuses old Pomelo fields too: no path keeps the old shape", async () => { + const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); + await expect( + session.card({ ...ISSUE_USD, cardholder_id: "usr_1" } as unknown as CardArgs), + ).rejects.toBeInstanceOf(CardContractMigrationError); + expect(calls).toHaveLength(0); + }); +}); + +describe("cs.cards.readiness", () => { + it("GETs /v1/cards/readiness with the client's credentials and returns the checklist", async () => { + const body: CardReadiness = { + programs: [ + { + program: "rain_usd", + issuer: "rain", + currency: "USD", + ready: false, + requirements: [ + { kind: "integration_connected", status: "done", actor: "org_admin" }, + { kind: "accept_terms", status: "pending", actor: "holder", action_url: "https://codespar.dev/x", pending_action_id: "pa_9" }, + { kind: "environment", status: "blocked", actor: "org_admin", reason: "live_blocked" }, + ], + }, + ], + }; + const seen: Array<{ url: string; init?: RequestInit }> = []; + globalThis.fetch = vi.fn(async (url: string, init?: RequestInit) => { + seen.push({ url, init }); + return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }); + }) as unknown as typeof fetch; + const cs = new CodeSpar({ apiKey: "csk_test_x", baseUrl: "https://api.example.com", projectId: "prj_AAAAAAAAAAAAAAAA" }); + await expect(cs.cards.readiness()).resolves.toEqual(body); + expect(seen).toHaveLength(1); + expect(seen[0]!.url).toBe("https://api.example.com/v1/cards/readiness"); + expect(seen[0]!.init?.method).toBe("GET"); + const h = seen[0]!.init?.headers as Record; + expect(h.Authorization).toBe("Bearer csk_test_x"); + expect(h["x-codespar-project"]).toBe("prj_AAAAAAAAAAAAAAAA"); + }); + + it("a non-2xx answer throws CodesparApiError with the API's code", async () => { + globalThis.fetch = vi.fn(async () => + new Response(JSON.stringify({ error: "forbidden", message: "no" }), { status: 403, headers: { "content-type": "application/json" } }), + ) as unknown as typeof fetch; + const cs = new CodeSpar({ apiKey: "csk_test_x", baseUrl: "https://api.example.com" }); + const err = await cs.cards.readiness().catch((e: unknown) => e); + expect(err).toBeInstanceOf(CodesparApiError); + expect((err as CodesparApiError).status).toBe(403); + }); +}); diff --git a/packages/core/src/__tests__/openapi-snapshot.test.ts b/packages/core/src/__tests__/openapi-snapshot.test.ts index 49fc424a..8a035ceb 100644 --- a/packages/core/src/__tests__/openapi-snapshot.test.ts +++ b/packages/core/src/__tests__/openapi-snapshot.test.ts @@ -12,6 +12,8 @@ import { describe, expect, it } from "vitest"; import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { OPERATIONS_PATH, SNAPSHOT_PATH, diff --git a/packages/core/src/card.ts b/packages/core/src/card.ts new file mode 100644 index 00000000..aee69cdc --- /dev/null +++ b/packages/core/src/card.ts @@ -0,0 +1,184 @@ +/** + * codespar_card result normalization. + * + * The wire answers four ways and the caller should not have to know which + * transport carried a refusal: + * - success, action=issue, a non-final `state` -> as received: + * `pending_human` (a person must act), `processing`, `uncertain` + * (both resolved on the SAME idempotency_key), `failed` (definitive) + * - success, action=issue, `state: "issued"` -> CardIssued (the view nested in `card`) + * - success, action=issue, anything else -> throws: an issue answer always says its state + * - success, any other action -> CardView / CardList as received + * - failure WITH a stable code -> CardRefusal (returned, not thrown) + * + * A failure with a code arrives either as the tool envelope's `data` + * (`{ error, code, details? }`, a strategy refusal on /execute) or as the + * `": "` string `execute()` builds from a non-2xx answer (a + * scope refusal, say). Both are read here. A failure with no code + * ("Tool not registered: ...", a 5xx with an HTML body) still throws: it is + * not a decision the caller can act on. + */ + +import type { + CardArgs, + CardIssueResult, + CardIssued, + CardList, + CardRefusal, + CardResult, + CardView, + IssueArgs, + ToolResult, +} from "@codespar/types"; + +type Rec = Record; + +function isRecord(v: unknown): v is Rec { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +const CODE = /^[a-z][a-z0-9_]*$/; + +function bodyOfHttpError(error: string | null): { status: number; body: Rec } | null { + if (!error) return null; + const m = /^(\d{3}): ([\s\S]*)$/.exec(error); + if (!m) return null; + try { + const parsed = JSON.parse(m[2]!) as unknown; + return isRecord(parsed) ? { status: Number(m[1]), body: parsed } : null; + } catch { + return null; + } +} + +/** The refusal a failed envelope carries, or null when it carries no stable code. */ +export function cardRefusalFrom(result: ToolResult): CardRefusal | null { + const http = isRecord(result.data) ? null : bodyOfHttpError(result.error); + const body = isRecord(result.data) ? result.data : http?.body; + if (!body) return null; + + // `{ error: { code, message, details } }` (newer REST routes) or flat. + const nested = isRecord(body.error) ? body.error : null; + const flat = nested ?? body; + const code = + typeof flat.code === "string" + ? flat.code + : typeof flat.error === "string" && CODE.test(flat.error) + ? flat.error + : null; + if (!code) return null; + + const details = isRecord(flat.details) ? flat.details : {}; + const pick = (k: string): unknown => (details[k] !== undefined ? details[k] : flat[k]); + const message = + typeof flat.message === "string" + ? flat.message + : typeof flat.error === "string" && flat.error !== code + ? flat.error + : (result.error ?? null); + + // The body's own `http_status` (the REST status the tool result mirrors) + // wins over the transport's: a tool envelope always travels as 200. + const httpStatus = typeof body.http_status === "number" ? body.http_status : (http?.status ?? 200); + const refusal: CardRefusal = { state: "refused", code, message, http_status: httpStatus, raw: body }; + const reason = pick("reason"); + if (typeof reason === "string") refusal.reason = reason; + const programs = pick("available_programs"); + if (Array.isArray(programs)) refusal.available_programs = programs as CardRefusal["available_programs"]; + const issuer = pick("issuer"); + if (typeof issuer === "string") refusal.issuer = issuer as CardRefusal["issuer"]; + const program = pick("program"); + if (typeof program === "string") refusal.program = program as CardRefusal["program"]; + const action = pick("action"); + if (typeof action === "string") refusal.action = action as CardRefusal["action"]; + const actions = pick("available_actions"); + if (Array.isArray(actions)) refusal.available_actions = actions as CardRefusal["available_actions"]; + return refusal; +} + +const NON_FINAL_ISSUE_STATES: ReadonlySet = new Set(["pending_human", "processing", "uncertain", "failed"]); + +/** Turn a codespar_card envelope into the typed result, or throw on a failure with no code. */ +export function cardResultFrom(args: CardArgs, result: ToolResult): CardResult { + if (!result.success) { + const refusal = cardRefusalFrom(result); + if (refusal) return refusal; + throw new Error(`card failed: ${result.error ?? "unknown"}`); + } + const data = result.data; + if (!isRecord(data)) { + throw new Error("card failed: malformed response"); + } + if (args.action === "issue") { + if (typeof data.state === "string" && NON_FINAL_ISSUE_STATES.has(data.state)) { + return data as unknown as CardIssueResult; + } + if (data.state === "issued") return data as unknown as CardIssued; + throw new Error(`card failed: unexpected issue state ${JSON.stringify(data.state)}`); + } + return data as unknown as CardView | CardList; +} + +/** Refuse locally what the server would refuse anyway, before anything leaves the machine. */ +export function assertCardArgs(args: CardArgs): void { + if (args.action === "issue" && !args.idempotency_key) { + throw new Error("card: idempotency_key is required on action=issue"); + } +} + +/* ── The deprecated `issue()` wrapper (contract §8.4) ─────────────── */ + +const LEGACY_ACTIONS: Readonly> = { + "card-virtual": "card({ action: \"issue\", currency, mandate_id, consumer_id, idempotency_key, provider? })", + "card-physical": "card({ action: \"issue\", currency, mandate_id, consumer_id, idempotency_key, provider? })", + "card-get": "card({ action: \"get\", card_id })", + "card-control": "card({ action: \"freeze\" | \"unfreeze\" | \"cancel\", card_id, reason? })", +}; + +const LEGACY_FIELDS = ["cardholder_id", "program_id", "control", "shipping_address", "metadata"] as const; + +/** + * A call in the old Pomelo-only shape, refused before anything is sent. + * `code` matches what the server answers to the same call through the + * deprecated tool alias. + */ +export class CardContractMigrationError extends Error { + readonly code = "card_contract_migration_required" as const; + constructor( + message: string, + readonly legacyFields: readonly string[], + ) { + super(message); + Object.setPrototypeOf(this, CardContractMigrationError.prototype); + this.name = "CardContractMigrationError"; + } +} + +/** The old-shaped call's migration error, or null for a `CardArgs` call. */ +export function cardMigrationError(args: CardArgs | IssueArgs): CardContractMigrationError | null { + const a = args as unknown as Record; + const action = typeof a.action === "string" ? a.action : ""; + const legacyFields = LEGACY_FIELDS.filter((f) => a[f] !== undefined); + const instead = LEGACY_ACTIONS[action]; + if (!instead && legacyFields.length === 0) return null; + const what = [instead ? `action "${action}"` : null, ...legacyFields.map((f) => `"${f}"`)].filter(Boolean).join(", "); + return new CardContractMigrationError( + `card_contract_migration_required: ${what} belong${legacyFields.length + (instead ? 1 : 0) > 1 ? "" : "s"} to the retired Pomelo-only shape. ` + + `Use ${instead ?? "card(args)"}: issue takes currency (BRL | USD), mandate_id, consumer_id and idempotency_key; provider (pomelo | rain) is optional. Nothing was sent.`, + legacyFields, + ); +} + +let issueDeprecationWarned = false; + +/** One warning per process, so a loop of calls does not flood stderr. */ +export function warnIssueDeprecated(): void { + if (issueDeprecationWarned) return; + issueDeprecationWarned = true; + console.warn("[@codespar/sdk] session.issue() is deprecated; use session.card(). It calls codespar_card with the same validations."); +} + +/** Test seam: re-arm the one-time warning. */ +export function resetIssueDeprecationWarning(): void { + issueDeprecationWarned = false; +} diff --git a/packages/core/src/cards.ts b/packages/core/src/cards.ts new file mode 100644 index 00000000..cc8e6465 --- /dev/null +++ b/packages/core/src/cards.ts @@ -0,0 +1,52 @@ +/** + * `cs.cards`: card reads over the REST routes that are not a meta-tool call. + * + * `cs.cards.readiness()` is `GET /v1/cards/readiness` (contract §9): per + * program, whether it is ready for this project and environment and the + * checklist of what is missing, each step naming who must act. The server + * computes it with the same function as the issue requirements, so the + * checklist and an issue refusal never disagree. Read-only. + */ + +import { CodesparApiError, networkErrorToApiError, throwFromResponse, TimeoutError } from "./errors.js"; +import { fetchWithTimeout } from "./internal/fetch.js"; +import type { CallOptions, CardReadiness } from "@codespar/types"; + +interface CardsDeps { + baseUrl: string; + apiKey: string; + projectId?: string; + timeout: number; +} + +export interface Cards { + /** `GET /v1/cards/readiness`: what each program needs before an issue can succeed. */ + readiness(opts?: CallOptions): Promise; +} + +export function createCards(deps: CardsDeps): Cards { + const headers: Record = { Authorization: `Bearer ${deps.apiKey}`, Accept: "application/json" }; + if (deps.projectId) headers["x-codespar-project"] = deps.projectId; + + return { + async readiness(opts) { + const what = "cards.readiness"; + try { + return await fetchWithTimeout( + `${deps.baseUrl}/v1/cards/readiness`, + { method: "GET", headers }, + { timeout: opts?.timeout ?? deps.timeout, signal: opts?.signal }, + async (r) => { + if (!r.ok) await throwFromResponse(r, what); + return (await r.json()) as CardReadiness; + }, + ); + } catch (cause) { + if (cause instanceof TimeoutError) throw cause; + if (cause instanceof CodesparApiError) throw cause; + if (opts?.signal?.aborted) throw cause; + throw networkErrorToApiError(cause, what); + } + }, + }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c8305b0b..e972d8b3 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -69,7 +69,9 @@ export type { PixKeyType, } from "./types.js"; export { PIX_KEY_DELETE_CONSEQUENCE, PixKeyDeleteNotConfirmedError } from "./wallet.js"; +export { CardContractMigrationError, cardMigrationError } from "./card.js"; export type { Wallet, WalletPixKeys } from "./wallet.js"; +export type { Cards } from "./cards.js"; export { filenameFromDisposition } from "./documents.js"; export type { Account, Document, DocumentFormat, ReceiptDocumentOptions, Receipts, StatementDocument, StatementOptions } from "./documents.js"; @@ -125,6 +127,7 @@ import { createSession } from "./session.js"; import { ApiClient } from "./api/client.js"; import { createPayables, type Payables } from "./payables.js"; import { createWallet, type Wallet } from "./wallet.js"; +import { createCards, type Cards } from "./cards.js"; import { createDocuments, type Account, type Receipts } from "./documents.js"; import { validateTimeout } from "./internal/fetch.js"; @@ -176,6 +179,18 @@ export class CodeSpar { */ readonly wallet: Wallet; + /** + * Card reads outside the meta-tool: `cs.cards.readiness()` is + * `GET /v1/cards/readiness`, per program the checklist of what is + * missing and who must act. Issue, read and control cards through + * `session.card()`. + * + * ```ts + * const { programs } = await cs.cards.readiness(); + * ``` + */ + readonly cards: Cards; + /** * Documents on demand: the receipt document (comprovante) of a payment, * as PDF or PNG. Read-only; the API serves it only for a confirmed payment. @@ -253,6 +268,12 @@ export class CodeSpar { projectId: this.config.projectId || undefined, timeout: this.config.timeout, }); + this.cards = createCards({ + baseUrl: this.config.baseUrl, + apiKey: this.config.apiKey, + projectId: this.config.projectId || undefined, + timeout: this.config.timeout, + }); const documents = createDocuments({ baseUrl: this.config.baseUrl, apiKey: this.config.apiKey, diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 8ed779af..4d120637 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -2,6 +2,7 @@ * Session implementation for the CodeSpar managed runtime. */ +import { assertCardArgs, cardMigrationError, cardResultFrom, warnIssueDeprecated } from "./card.js"; import { CodesparApiError, networkErrorToApiError, throwFromInstrumentsResponse, throwFromResponse, TimeoutError } from "./errors.js"; import type { SessionConfig, Tool, CallOptions } from "./types.js"; import { fetchWithTimeout, validateTimeout } from "./internal/fetch.js"; @@ -31,8 +32,9 @@ import type { ShipResult, LedgerArgs, LedgerResult, + CardArgs, + CardResult, IssueArgs, - IssueResult, ShopArgs, ShopResult, AgentInstrument, @@ -393,21 +395,35 @@ export async function createSession( }, /** - * codespar_issue wrapper. Issue a virtual/physical card, control - * (freeze/unfreeze/cancel) one, or read its status on the tenant's - * Pomelo card-issuing program. Same wire as - * `execute("codespar_issue", {...})` but returns a typed IssueResult. + * codespar_card wrapper. Issue, read, list or control a card on any + * issuer the server resolves (BRL -> pomelo_brl, USD -> rain_usd). Same + * wire as `execute("codespar_card", {...})`; a refusal with a stable code + * is RETURNED as `CardRefusal` (`state: "refused"`); a non-final issue + * as `pending_human` / `processing` / `uncertain` (resolve on the SAME + * idempotency_key) or `failed`. Only a failure with no code throws. */ - async issue(args: IssueArgs, opts?: CallOptions): Promise { + async card(args: CardArgs, opts?: CallOptions): Promise { + const migration = cardMigrationError(args); + if (migration) throw migration; + assertCardArgs(args); const result = await session.execute( - "codespar_issue", + "codespar_card", args as unknown as Record, opts, ); - if (!result.success) { - throw new Error(`issue failed: ${result.error ?? "unknown"}`); - } - return result.data as IssueResult; + return cardResultFrom(args, result); + }, + + /** + * @deprecated Use `card()`. Same tool and validations, plus a one-time + * warning; an old Pomelo-shaped call throws `CardContractMigrationError` + * before anything is sent. + */ + async issue(args: CardArgs | IssueArgs, opts?: CallOptions): Promise { + warnIssueDeprecated(); + const migration = cardMigrationError(args); + if (migration) throw migration; + return session.card(args as CardArgs, opts); }, /** diff --git a/packages/core/src/testing/index.ts b/packages/core/src/testing/index.ts index afc6fc7c..f8a70682 100644 --- a/packages/core/src/testing/index.ts +++ b/packages/core/src/testing/index.ts @@ -1,7 +1,7 @@ // fakeSession v1 covers execute()-driven flows. send(), sendStream(), // and channel mocking land when Layer 3 demos demand them. -import type { Session, ToolResult } from "@codespar/types"; +import type { CardArgs, Session, ToolResult } from "@codespar/types"; export type { ToolResult }; @@ -100,16 +100,42 @@ export function fakeSession( return { id: "txn_fake", status: "POSTED" }; }, - async issue(args) { - if (args.action === "card-control" || args.action === "card-get") { - return { id: args.card_id ?? "card_fake", status: "ACTIVE", card_type: "VIRTUAL" }; - } - return { - id: "card_fake", - status: "ACTIVE", - card_type: args.action === "card-physical" ? "PHYSICAL" : "VIRTUAL", - last_four: "4242", + async card(args) { + const view = { + id: "icrd_fake", + issuer: "pomelo" as const, + program: "pomelo_brl" as const, + currency: "BRL" as const, + status: "active" as const, + issuer_status: "ACTIVE", + last4: "4242", + network: "MASTERCARD", + mandate_id: "mnd_fake", + consumer_id: "cons_fake", + created_at: new Date(0).toISOString(), + available_actions: ["freeze" as const, "cancel" as const], }; + if (args.action === "issue") { + return { + state: "issued" as const, + issue_request_id: "cir_fake", + issuer: view.issuer, + program: view.program, + selection: { provider_requested: args.provider ?? null, chosen_by: args.provider ? ("provider" as const) : ("currency" as const) }, + card: view, + authorization_id: "caia_fake", + authorization_active: true, + }; + } + if (args.action === "list") return { cards: [view] }; + if (args.action === "get") return { ...view, id: args.card_id }; + if (args.action === "freeze") return { ...view, id: args.card_id, status: "blocked" as const, issuer_status: "BLOCKED", available_actions: ["unfreeze" as const, "cancel" as const] }; + if (args.action === "cancel") return { ...view, id: args.card_id, status: "canceled" as const, issuer_status: "DISABLED", available_actions: [] }; + return { ...view, id: args.card_id }; + }, + + async issue(args) { + return session.card(args as CardArgs); }, async shop(args) { diff --git a/packages/crewai/package.json b/packages/crewai/package.json index fcbfd5e3..cce6124e 100644 --- a/packages/crewai/package.json +++ b/packages/crewai/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/crewai", - "version": "0.4.6", + "version": "0.4.7", "description": "CrewAI adapter for CodeSpar — convert session tools to CrewAI tool format", "type": "module", "main": "./dist/index.js", @@ -37,7 +37,7 @@ "directory": "packages/crewai" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/crewai/src/__tests__/crewai.test.ts b/packages/crewai/src/__tests__/crewai.test.ts index bbdfbde2..5d8a976b 100644 --- a/packages/crewai/src/__tests__/crewai.test.ts +++ b/packages/crewai/src/__tests__/crewai.test.ts @@ -38,6 +38,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/google-genai/package.json b/packages/google-genai/package.json index 000efa80..5bfc2b83 100644 --- a/packages/google-genai/package.json +++ b/packages/google-genai/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/google-genai", - "version": "0.4.6", + "version": "0.4.7", "description": "Google Gemini/GenAI adapter for CodeSpar — convert session tools to Gemini FunctionDeclaration format", "type": "module", "main": "./dist/index.js", @@ -38,7 +38,7 @@ "directory": "packages/google-genai" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/google-genai/src/__tests__/google-genai.test.ts b/packages/google-genai/src/__tests__/google-genai.test.ts index 6cc3ae85..4211983f 100644 --- a/packages/google-genai/src/__tests__/google-genai.test.ts +++ b/packages/google-genai/src/__tests__/google-genai.test.ts @@ -42,6 +42,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/hermes/package.json b/packages/hermes/package.json index b62a82d2..0d4e9436 100644 --- a/packages/hermes/package.json +++ b/packages/hermes/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/hermes", - "version": "0.4.5", + "version": "0.4.6", "private": true, "description": "Hermes Agent adapter for CodeSpar — convert session tools to Hermes MCP/plugin tool format", "type": "module", @@ -40,7 +40,7 @@ "directory": "packages/hermes" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/hermes/src/__tests__/hermes.test.ts b/packages/hermes/src/__tests__/hermes.test.ts index 45704171..74464ae9 100644 --- a/packages/hermes/src/__tests__/hermes.test.ts +++ b/packages/hermes/src/__tests__/hermes.test.ts @@ -38,6 +38,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/langchain/CHANGELOG.md b/packages/langchain/CHANGELOG.md index 1a30c5f0..153494b8 100644 --- a/packages/langchain/CHANGELOG.md +++ b/packages/langchain/CHANGELOG.md @@ -1,5 +1,11 @@ # @codespar/langchain — changelog +## 0.5.3 — unreleased (coordinated codespar_card release) + +### Changed + +- The `@codespar/sdk` peer range accepts `^0.17.0`. + ## 0.5.2 — 2026-11-15 ### Security diff --git a/packages/langchain/package.json b/packages/langchain/package.json index d4ee14bc..17461129 100644 --- a/packages/langchain/package.json +++ b/packages/langchain/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/langchain", - "version": "0.5.2", + "version": "0.5.3", "description": "LangChain.js adapter for CodeSpar — convert session tools to LangChain StructuredTool format", "type": "module", "main": "./dist/index.js", @@ -37,7 +37,7 @@ "directory": "packages/langchain" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0", + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0", "zod": ">=3.25.0" }, "devDependencies": { diff --git a/packages/langchain/src/__tests__/langchain.test.ts b/packages/langchain/src/__tests__/langchain.test.ts index 2d7ba4b0..b7519d37 100644 --- a/packages/langchain/src/__tests__/langchain.test.ts +++ b/packages/langchain/src/__tests__/langchain.test.ts @@ -42,6 +42,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/letta/package.json b/packages/letta/package.json index 52625ec4..ec39b99f 100644 --- a/packages/letta/package.json +++ b/packages/letta/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/letta", - "version": "0.4.6", + "version": "0.4.7", "description": "Letta (MemGPT) adapter for CodeSpar — convert session tools to Letta tool format", "type": "module", "main": "./dist/index.js", @@ -37,7 +37,7 @@ "directory": "packages/letta" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/letta/src/__tests__/letta.test.ts b/packages/letta/src/__tests__/letta.test.ts index 21a9ef29..8ddaa0f7 100644 --- a/packages/letta/src/__tests__/letta.test.ts +++ b/packages/letta/src/__tests__/letta.test.ts @@ -38,6 +38,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/llama-index/package.json b/packages/llama-index/package.json index a9667073..8b2c4b96 100644 --- a/packages/llama-index/package.json +++ b/packages/llama-index/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/llama-index", - "version": "0.4.6", + "version": "0.4.7", "description": "LlamaIndex.TS adapter for CodeSpar — convert session tools to LlamaIndex FunctionTool format", "type": "module", "main": "./dist/index.js", @@ -38,7 +38,7 @@ "directory": "packages/llama-index" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/llama-index/src/__tests__/llama-index.test.ts b/packages/llama-index/src/__tests__/llama-index.test.ts index 4503f5d5..dd002e4b 100644 --- a/packages/llama-index/src/__tests__/llama-index.test.ts +++ b/packages/llama-index/src/__tests__/llama-index.test.ts @@ -38,6 +38,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/mastra/package.json b/packages/mastra/package.json index 4405719c..6c59ccc9 100644 --- a/packages/mastra/package.json +++ b/packages/mastra/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/mastra", - "version": "0.4.6", + "version": "0.4.7", "description": "Mastra adapter for CodeSpar — convert session tools to Mastra tool format", "type": "module", "main": "./dist/index.js", @@ -37,7 +37,7 @@ "directory": "packages/mastra" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/mastra/src/__tests__/mastra.test.ts b/packages/mastra/src/__tests__/mastra.test.ts index 95692487..aec7ded4 100644 --- a/packages/mastra/src/__tests__/mastra.test.ts +++ b/packages/mastra/src/__tests__/mastra.test.ts @@ -38,6 +38,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/mcp/CHANGELOG.md b/packages/mcp/CHANGELOG.md index 1432055f..689d09b4 100644 --- a/packages/mcp/CHANGELOG.md +++ b/packages/mcp/CHANGELOG.md @@ -1,5 +1,12 @@ # @codespar/mcp — changelog +## 0.6.0 — unreleased (coordinated codespar_card release) + +### Changed + +- Discovery relays `codespar_card` from the hosted catalog. The old card tool stays callable on the server as a deprecated alias of the same path. The README and the package description no longer say Pomelo-only: spend cards are BRL on Pomelo and USD on Rain. +- Accepts `@codespar/sdk ^0.17.0`. + ## 0.5.20 — 2026-10-30 ### Added diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 9bbcaefb..7843422b 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -2,14 +2,14 @@ MCP server for CodeSpar — give Claude, Codex, Cursor, VS Code (and any MCP client) a Latin-American commerce agent: search & checkout, Pix, wallet/balance, spend -mandates & limits, and Pomelo card issuing — all as MCP tools. +mandates & limits, and spend cards (BRL on Pomelo, USD on Rain) — all as MCP tools. ## Run as a server (`codespar-mcp`) A stdio MCP server that bridges your MCP client to a CodeSpar session's tools. It talks to the CodeSpar REST API directly, so it works against the live meta-tools today (`codespar_pay`, `codespar_charge`, `codespar_discover`, wallet, mandates, -and `codespar_issue` → Pomelo card). One env var (`CODESPAR_API_KEY`) and you're in. +and `codespar_card` → spend cards, BRL on Pomelo and USD on Rain). One env var (`CODESPAR_API_KEY`) and you're in. **Claude Code / Claude Desktop** diff --git a/packages/mcp/package.json b/packages/mcp/package.json index b4f9e654..ce550f0a 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "name": "@codespar/mcp", - "version": "0.5.20", - "description": "MCP server for CodeSpar — give Claude, Codex, Cursor & ChatGPT a commerce agent (pay, charge, wallet, mandates, Pomelo card) over MCP", + "version": "0.6.0", + "description": "MCP server for CodeSpar — give Claude, Codex, Cursor & ChatGPT a commerce agent (pay, charge, wallet, mandates, spend cards) over MCP", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", @@ -40,11 +40,11 @@ "directory": "packages/mcp" }, "dependencies": { - "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0", + "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0", "@modelcontextprotocol/sdk": "^1.29.0" }, "peerDependencies": { - "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.1 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/mcp/src/__tests__/mcp.test.ts b/packages/mcp/src/__tests__/mcp.test.ts index 4f2922ed..babab5bb 100644 --- a/packages/mcp/src/__tests__/mcp.test.ts +++ b/packages/mcp/src/__tests__/mcp.test.ts @@ -41,6 +41,7 @@ function fakeSession(): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/openai/package.json b/packages/openai/package.json index fb096748..52f0ed8a 100644 --- a/packages/openai/package.json +++ b/packages/openai/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/openai", - "version": "0.4.7", + "version": "0.4.8", "description": "OpenAI Agents SDK adapter for CodeSpar — convert MCP tools to OpenAI function calling format", "type": "module", "main": "./dist/index.js", @@ -36,7 +36,7 @@ "directory": "packages/openai" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0" + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0" }, "devDependencies": { "@codespar/sdk": "*", diff --git a/packages/openai/src/__tests__/openai.test.ts b/packages/openai/src/__tests__/openai.test.ts index 17c1f82d..c04ebd24 100644 --- a/packages/openai/src/__tests__/openai.test.ts +++ b/packages/openai/src/__tests__/openai.test.ts @@ -55,6 +55,7 @@ function fakeSession(tools: Tool[]): Session { async charge() { return {} as any; }, async ship() { return {} as any; }, async ledger() { return {} as any; }, + async card() { return {} as any; }, async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, diff --git a/packages/python/CHANGELOG.md b/packages/python/CHANGELOG.md index b887fd56..f39fa6fc 100644 --- a/packages/python/CHANGELOG.md +++ b/packages/python/CHANGELOG.md @@ -1,5 +1,27 @@ # codespar (Python SDK) — CHANGELOG +## 0.17.0 — unreleased (coordinated codespar_card release) + +In parity with `@codespar/sdk` 0.17.0. + +### Added + +- **`session.card(CardArgs(...))`** (async and sync) calls `codespar_card` (BRL on Pomelo, USD on Rain). `idempotency_key` is required on `action="issue"` and is checked before anything is sent. +- It returns one of: + - `CardIssued`; + - `CardPendingHuman` (`pending_action`); + - `CardProcessing` and `CardUncertain`: same key, never a new one; + - `CardFailed`; + - `CardView`, `CardList`; + - `CardRefusal`. A refusal with a stable code is returned, whether it came in the tool envelope or as a non-2xx answer (`http_status`). Only a failure with no code raises `ApiError`. +- **`cs.cards.readiness()`** reads `GET /v1/cards/readiness`. It returns typed dicts `CardReadiness`, `CardProgramReadiness` and `CardRequirement`. +- `CardContractMigrationError` (`code = "card_contract_migration_required"`, `legacy_fields`). + +### Deprecated + +- **`session.issue(...)`** (async and sync) emits a `DeprecationWarning` and calls `card()` with the same validations. An `IssueArgs` (old Pomelo shape) raises `CardContractMigrationError` before anything is sent. +- `IssueArgs` and `IssueAction` are kept for imports. `IssueResult` is an alias of `CardResult`. + ## 0.16.2 The statement as PNG pages, in parity with `@codespar/sdk` 0.16.28. diff --git a/packages/python/README.md b/packages/python/README.md index a87b4879..83c226cd 100644 --- a/packages/python/README.md +++ b/packages/python/README.md @@ -155,6 +155,56 @@ Every method listed above exists on **both** `Session` (sync) and `AsyncSession` (await the async variants). Snake-case throughout — TS `paymentStatusStream` ⇆ Python `payment_status_stream`. +### Spend cards (`codespar_card`) + +One contract for BRL cards on Pomelo (`pomelo_brl`) and USD cards on Rain +(`rain_usd`). `provider` is optional: the currency picks the program. +`idempotency_key` is required on `issue`; a retry with the same key resumes +the same request and never issues a second card. + +```python +from codespar import ( + CardArgs, CardFailed, CardIssued, CardPendingHuman, CardProcessing, + CardRefusal, CardUncertain, +) + +result = session.card( + CardArgs( + action="issue", + currency="USD", + mandate_id="mnd_...", + consumer_id="cons_...", + idempotency_key="order-7721-card", + ) +) +if isinstance(result, CardIssued): + print(result.id, result.issuer, result.program, result.available_actions) +elif isinstance(result, CardPendingHuman): + # A step only a person can take: hand them the link, never act for them. + print(result.pending_action.kind, result.pending_action.actor, result.pending_action.url) +elif isinstance(result, (CardProcessing, CardUncertain)): + # Not a failure. Uncertain means the card MAY exist at the issuer: + # call again with the SAME idempotency_key, never a new one. + print(result.state, result.issue_request_id) +elif isinstance(result, CardFailed): + print("issuer refused:", result.code, result.reason) +elif isinstance(result, CardRefusal): + print(result.code, result.reason, result.available_programs) + +session.card(CardArgs(action="get", card_id="icrd_...")) +session.card(CardArgs(action="list", issuer="rain")) +session.card(CardArgs(action="freeze", card_id="icrd_...", reason="lost")) + +# Per program, what is missing and who must act (holder, company_signatory, org_admin). +cs.cards.readiness() +``` + +A refusal with a stable code is returned as `CardRefusal`, not raised; only a +failure with no code raises `ApiError`. `session.issue()` is deprecated: it +warns and calls the same `codespar_card` with the same validations, and a call +in the old Pomelo shape (`IssueArgs` with `cardholder_id` / `program_id`) +raises `CardContractMigrationError` naming the new fields. + ## Pay documents and batches ```python diff --git a/packages/python/pyproject.toml b/packages/python/pyproject.toml index 4fd7a720..6e79d88a 100644 --- a/packages/python/pyproject.toml +++ b/packages/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "codespar" -version = "0.16.2" +version = "0.17.0" description = "Python SDK for CodeSpar — commerce infrastructure for AI agents in Latin America." readme = "README.md" requires-python = ">=3.10" diff --git a/packages/python/src/codespar/__init__.py b/packages/python/src/codespar/__init__.py index adce1a10..be9d1d57 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -29,6 +29,7 @@ from ._async_client import AsyncCodeSpar from ._async_session import AsyncSession from ._sync_client import CodeSpar, Session +from .cards import AsyncCards, CardProgramReadiness, CardReadiness, CardRequirement, Cards from .documents import ( Account, AsyncAccount, @@ -42,6 +43,7 @@ from .errors import ( PIX_KEY_DELETE_CONSEQUENCE, ApiError, + CardContractMigrationError, CodeSparError, ConfigError, NotConnectedError, @@ -97,6 +99,29 @@ AssistantTextEvent, AuthConfig, AuthResult, + CardAction, + CardArgs, + CardControlAction, + CardControlReason, + CardCurrency, + CardFailed, + CardFunding, + CardIssued, + CardIssuer, + CardList, + CardPendingAction, + CardPendingActionKind, + CardPendingActor, + CardPendingHuman, + CardProcessing, + CardProgram, + CardProgramAvailability, + CardRefusal, + CardResult, + CardSelection, + CardStatus, + CardUncertain, + CardView, ChargeArgs, ChargeBuyer, ChargeMethod, @@ -186,7 +211,7 @@ WalletPixKeys, ) -__version__ = "0.16.2" +__version__ = "0.17.0" __all__ = [ "APPROVAL_REQUIRED", @@ -203,6 +228,7 @@ "ApprovalRequiredOutput", "AssistantTextEvent", "AsyncAccount", + "AsyncCards", "AsyncCodeSpar", "AsyncPayables", "AsyncReceipts", @@ -212,6 +238,35 @@ # Connect Links "AuthConfig", "AuthResult", + # Card (codespar_card) + "CardAction", + "CardArgs", + "CardContractMigrationError", + "CardControlAction", + "CardControlReason", + "CardCurrency", + "CardFailed", + "CardFunding", + "CardIssued", + "CardIssuer", + "CardList", + "CardPendingAction", + "CardPendingActionKind", + "CardPendingActor", + "CardPendingHuman", + "CardProcessing", + "CardProgram", + "CardProgramAvailability", + "CardProgramReadiness", + "CardReadiness", + "CardRefusal", + "CardRequirement", + "CardResult", + "CardSelection", + "CardStatus", + "CardUncertain", + "CardView", + "Cards", # Inbound charge (codespar_charge) "ChargeArgs", "ChargeBuyer", @@ -239,7 +294,6 @@ "DoneEvent", "ErrorEvent", "HttpMethod", - # Issue (codespar_issue) "IssueAction", "IssueArgs", "IssueResult", diff --git a/packages/python/src/codespar/_async_client.py b/packages/python/src/codespar/_async_client.py index 2c5cdcc0..393aa563 100644 --- a/packages/python/src/codespar/_async_client.py +++ b/packages/python/src/codespar/_async_client.py @@ -23,6 +23,7 @@ ) from ._http import DEFAULT_BASE_URL, normalize_timeout, request_json from ._presets import preset_to_servers +from .cards import AsyncCards from .documents import AsyncAccount, AsyncReceipts from .errors import ApiError, ConfigError from .payables import AsyncPayables @@ -107,6 +108,8 @@ def __init__( self.payables = AsyncPayables(self._client, self._api_key, self._project_id) #: A consumer's own account: ``wallet.pix_keys`` over ``/v1/consumers/:id/pix-keys``. self.wallet = AsyncWallet(self._client, self._api_key, self._project_id) + #: Card reads outside the meta-tool: ``cards.readiness()`` (``GET /v1/cards/readiness``). + self.cards = AsyncCards(self._client, self._api_key, self._project_id) #: The receipt document (comprovante) of a payment #: (``/v1/consumers/receipts/:id/document``). self.receipts = AsyncReceipts(self._client, self._api_key, self._project_id) diff --git a/packages/python/src/codespar/_async_session.py b/packages/python/src/codespar/_async_session.py index 968fbc25..418fbf44 100644 --- a/packages/python/src/codespar/_async_session.py +++ b/packages/python/src/codespar/_async_session.py @@ -11,6 +11,7 @@ import asyncio import contextlib +import warnings from collections.abc import AsyncIterator, Awaitable, Callable from datetime import datetime from typing import Any @@ -18,11 +19,25 @@ import httpx from ._http import request_json, stream_sse, stream_sse_get -from .errors import ApiError, ConfigError, TimeoutError +from .errors import ApiError, CardContractMigrationError, ConfigError, TimeoutError from .types import ( AssistantTextEvent, AuthConfig, AuthResult, + CardArgs, + CardFailed, + CardFunding, + CardIssued, + CardList, + CardPendingAction, + CardPendingHuman, + CardProcessing, + CardProgramAvailability, + CardRefusal, + CardResult, + CardSelection, + CardUncertain, + CardView, ChargeArgs, ChargeResult, ConnectionStatusRow, @@ -36,7 +51,6 @@ DoneEvent, ErrorEvent, IssueArgs, - IssueResult, LedgerArgs, LedgerResult, PaymentStatusEvent, @@ -218,15 +232,202 @@ def _parse_ledger_result(raw: dict[str, Any]) -> LedgerResult: ) -def _parse_issue_result(raw: dict[str, Any]) -> IssueResult: - return IssueResult( - id=raw.get("id"), - status=raw.get("status"), - card_type=raw.get("card_type"), - last_four=raw.get("last_four"), - cardholder_id=raw.get("cardholder_id"), - program_id=raw.get("program_id"), - raw=raw.get("raw"), +_CARD_CODE_CHARS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789_") + + +def _is_card_code(value: Any) -> bool: + return ( + isinstance(value, str) + and bool(value) + and value[0].isalpha() + and set(value) <= _CARD_CODE_CHARS + ) + + +def _str_list(value: Any) -> list[str]: + return [str(v) for v in value] if isinstance(value, list) else [] + + +def _parse_card_selection(raw: Any) -> CardSelection | None: + if not isinstance(raw, dict): + return None + return CardSelection( + provider_requested=raw.get("provider_requested"), + chosen_by=str(raw.get("chosen_by", "currency")), + ) + + +def _card_view_fields(raw: dict[str, Any]) -> dict[str, Any]: + funding = raw.get("funding") + return { + "id": str(raw.get("id", "")), + "issuer": str(raw.get("issuer", "")), + "program": str(raw.get("program", "")), + "currency": str(raw.get("currency", "")), + "status": str(raw.get("status", "")), + "issuer_status": raw.get("issuer_status"), + "last4": raw.get("last4"), + "network": raw.get("network"), + "mandate_id": raw.get("mandate_id"), + "consumer_id": raw.get("consumer_id"), + "created_at": raw.get("created_at"), + "available_actions": _str_list(raw.get("available_actions")), + "funding": ( + CardFunding(asset=str(funding.get("asset", "USDC"))) + if isinstance(funding, dict) + else None + ), + } + + +def _parse_card_view(raw: dict[str, Any]) -> CardView: + return CardView(**_card_view_fields(raw)) + + +def _parse_card_result(raw: dict[str, Any], action: str) -> CardResult: + """Map a successful codespar_card payload to its dataclass (TS ``cardResultFrom``).""" + if action == "issue": + state = raw.get("state") + ref: dict[str, Any] = { + "issue_request_id": str(raw.get("issue_request_id", "")), + "issuer": str(raw.get("issuer", "")), + "program": str(raw.get("program", "")), + "selection": _parse_card_selection(raw.get("selection")), + } + if state == "pending_human": + pa = raw.get("pending_action") + pa = pa if isinstance(pa, dict) else {} + return CardPendingHuman( + **ref, + pending_action=CardPendingAction( + id=str(pa.get("id", "")), + kind=str(pa.get("kind", "")), + actor=str(pa.get("actor", "")), + url=pa.get("url"), + ), + ) + if state == "processing": + return CardProcessing(**ref) + if state == "uncertain": + message = raw.get("message") + return CardUncertain(**ref, message=message if isinstance(message, str) else None) + if state == "failed": + def opt(key: str) -> str | None: + v = raw.get(key) + return v if isinstance(v, str) else None + + return CardFailed(**ref, code=opt("code"), reason=opt("reason"), message=opt("message")) + if state == "issued": + card = raw.get("card") + auth_id = raw.get("authorization_id") + return CardIssued( + **ref, + card=_parse_card_view(card if isinstance(card, dict) else {}), + authorization_id=auth_id if isinstance(auth_id, str) else None, + authorization_active=bool(raw.get("authorization_active", False)), + ) + raise ApiError(f"card failed: unexpected issue state {state!r}", status=0, body=raw) + if action == "list": + cards = raw.get("cards") + return CardList( + cards=[_parse_card_view(c) for c in cards if isinstance(c, dict)] + if isinstance(cards, list) + else [] + ) + return _parse_card_view(raw) + + +_LEGACY_ISSUE = ( + 'card(CardArgs(action="issue", currency, mandate_id, consumer_id, ' + "idempotency_key, provider=None))" +) +_LEGACY_INSTEAD = { + "card-virtual": _LEGACY_ISSUE, + "card-physical": _LEGACY_ISSUE, + "card-get": 'card(CardArgs(action="get", card_id))', + "card-control": 'card(CardArgs(action="freeze" | "unfreeze" | "cancel", card_id, reason=None))', +} +_LEGACY_FIELDS = ("cardholder_id", "program_id", "control", "shipping_address", "metadata") + + +def _card_migration_error(args: Any) -> CardContractMigrationError | None: + """The old-shaped call's migration error (TS ``cardMigrationError``), or None.""" + action = getattr(args, "action", "") + instead = _LEGACY_INSTEAD.get(action) + legacy = [f for f in _LEGACY_FIELDS if getattr(args, f, None) is not None] + if instead is None and not legacy: + return None + what = ", ".join(([f'action "{action}"'] if instead else []) + [f'"{f}"' for f in legacy]) + verb = "belong" if len(legacy) + (1 if instead else 0) > 1 else "belongs" + return CardContractMigrationError( + f"card_contract_migration_required: {what} {verb} to the retired Pomelo-only shape. " + f"Use {instead or 'card(CardArgs(...))'}: issue takes currency (BRL | USD), mandate_id, " + "consumer_id and idempotency_key; provider (pomelo | rain) is optional. Nothing was sent.", + legacy, + ) + + +def _parse_card_refusal( + body: Any, http_status: int, fallback_message: str | None +) -> CardRefusal | None: + """The refusal a failed answer carries, or None when it has no stable code.""" + if not isinstance(body, dict): + return None + nested = body.get("error") + flat: dict[str, Any] = nested if isinstance(nested, dict) else body + code: str | None = None + if isinstance(flat.get("code"), str): + code = flat["code"] + elif _is_card_code(flat.get("error")): + code = flat["error"] + if not code: + return None + raw_details = flat.get("details") + details: dict[str, Any] = raw_details if isinstance(raw_details, dict) else {} + + def pick(key: str) -> Any: + return details[key] if key in details else flat.get(key) + + def pick_str(key: str) -> str | None: + value = pick(key) + return value if isinstance(value, str) else None + + message = flat.get("message") + if not isinstance(message, str): + err = flat.get("error") + message = err if isinstance(err, str) and err != code else fallback_message + programs = pick("available_programs") + actions = pick("available_actions") + return CardRefusal( + code=code, + message=message, + http_status=( + body["http_status"] if isinstance(body.get("http_status"), int) else http_status + ), + reason=pick_str("reason"), + available_programs=( + [ + CardProgramAvailability( + program=str(p.get("program", "")), + issuer=str(p.get("issuer", "")), + currency=str(p.get("currency", "")), + available=( + p["available"] if isinstance(p.get("available"), bool) else None + ), + reason=p.get("reason"), + operations=_str_list(p.get("operations")), + ) + for p in programs + if isinstance(p, dict) + ] + if isinstance(programs, list) + else None + ), + issuer=pick_str("issuer"), + program=pick_str("program"), + action=pick_str("action"), + available_actions=_str_list(actions) if isinstance(actions, list) else None, + raw=body, ) @@ -679,42 +880,102 @@ async def ledger(self, args: LedgerArgs, *, timeout: float | None = None) -> Led raise ApiError("ledger: malformed response", status=0, body=result.data) return _parse_ledger_result(result.data) - async def issue(self, args: IssueArgs, *, timeout: float | None = None) -> IssueResult: + async def card(self, args: CardArgs, *, timeout: float | None = None) -> CardResult: """ - Issue a virtual/physical card, control (freeze/unfreeze/cancel) - one, or read its status on the tenant's Pomelo card-issuing - program. Typed wrapper around ``execute("codespar_issue", {...})``. - - ``args.action`` is one of ``card-virtual`` | ``card-physical`` | - ``card-control`` | ``card-get``. cardholder_id + program_id are - required to issue; card_id is required for control + get; - card-physical needs shipping_address. + Issue, read, list, freeze, unfreeze or cancel a card on whichever + issuer the server resolves (BRL -> pomelo_brl, USD -> rain_usd). + Typed wrapper around the ``codespar_card`` meta-tool. + + Returns ``CardIssued`` | ``CardPendingHuman`` (a step only a person + can take; retry with the same ``idempotency_key`` once done) | + ``CardProcessing`` / ``CardUncertain`` (both resolved on the SAME + ``idempotency_key``, never a new one: the card may already exist) | + ``CardFailed`` (definitive) | ``CardView`` | ``CardList`` | + ``CardRefusal``. A refusal with a + stable code is RETURNED, whether it came inside the tool envelope + or as a non-2xx answer; only a failure with no code raises + ``ApiError``. ``idempotency_key`` is required on ``action="issue"`` + and is checked before anything is sent. """ - params: dict[str, Any] = {"action": args.action} - if args.cardholder_id is not None: - params["cardholder_id"] = args.cardholder_id - if args.program_id is not None: - params["program_id"] = args.program_id - if args.card_id is not None: - params["card_id"] = args.card_id - if args.control is not None: - params["control"] = args.control - if args.reason is not None: - params["reason"] = args.reason - if args.shipping_address is not None: - params["shipping_address"] = args.shipping_address - if args.metadata is not None: - params["metadata"] = args.metadata - result = await self.execute("codespar_issue", params, timeout=timeout) - if not result.success: + migration = _card_migration_error(args) + if migration is not None: + raise migration + if args.action == "issue" and not args.idempotency_key: raise ApiError( - f"issue failed: {result.error or 'unknown'}", + "card: idempotency_key is required on action=issue", status=0, - body=result.error, + code="invalid_args", ) - if not isinstance(result.data, dict): - raise ApiError("issue: malformed response", status=0, body=result.data) - return _parse_issue_result(result.data) + params: dict[str, Any] = {"action": args.action} + for name in ( + "currency", + "provider", + "mandate_id", + "consumer_id", + "idempotency_key", + "holder", + "card_id", + "issuer", + "reason", + ): + value = getattr(args, name) + if value is not None: + params[name] = value + # Straight to /execute rather than through ``execute()``: a non-2xx + # refusal (scope, idempotency conflict) keeps its status and parsed + # body here, where ``execute()`` would flatten them into a string. + try: + data = await request_json( + self._client, + "POST", + f"/v1/sessions/{self.id}/execute", + api_key=self._api_key, + project_id=self._project_id, + body={"tool": "codespar_card", "input": params}, + timeout=timeout, + ) + except ApiError as exc: + if exc.status == 0: + raise + refusal = _parse_card_refusal(exc.body, exc.status, str(exc)) + if refusal is not None: + return refusal + raise + if not isinstance(data, dict): + raise ApiError("card: malformed response", status=0, body=data) + if not data.get("success", False): + error = data.get("error") + refusal = _parse_card_refusal( + data.get("data"), 200, error if isinstance(error, str) else None + ) + if refusal is not None: + return refusal + raise ApiError(f"card failed: {error or 'unknown'}", status=0, body=error) + payload = data.get("data") + if not isinstance(payload, dict): + raise ApiError("card: malformed response", status=0, body=payload) + return _parse_card_result(payload, args.action) + + async def issue( + self, args: CardArgs | IssueArgs, *, timeout: float | None = None + ) -> CardResult: + """Deprecated: use :meth:`card`. Same tool and validations, plus a warning. + + An ``IssueArgs`` (old Pomelo shape) raises + ``CardContractMigrationError`` before anything is sent. + """ + warnings.warn( + "session.issue() is deprecated; use session.card(). " + "It calls codespar_card with the same validations.", + DeprecationWarning, + stacklevel=2, + ) + migration = _card_migration_error(args) + if migration is not None: + raise migration + if not isinstance(args, CardArgs): + raise CardContractMigrationError("issue() takes CardArgs", []) + return await self.card(args, timeout=timeout) async def shop(self, args: ShopArgs, *, timeout: float | None = None) -> ShopResult: """ diff --git a/packages/python/src/codespar/_sync_client.py b/packages/python/src/codespar/_sync_client.py index 086e9805..b8df3d32 100644 --- a/packages/python/src/codespar/_sync_client.py +++ b/packages/python/src/codespar/_sync_client.py @@ -15,6 +15,7 @@ import asyncio import threading +import warnings from collections.abc import Coroutine, Iterator from types import TracebackType from typing import Any, TypeVar @@ -22,12 +23,15 @@ from ._async_client import AsyncCodeSpar from ._async_session import AsyncSession from ._http import normalize_timeout +from .cards import Cards from .documents import Account, Receipts from .errors import ConfigError from .payables import Payables from .types import ( AuthConfig, AuthResult, + CardArgs, + CardResult, ChargeArgs, ChargeResult, ConnectionWizardOptions, @@ -35,7 +39,6 @@ DiscoverOptions, DiscoverResult, IssueArgs, - IssueResult, LedgerArgs, LedgerResult, PaymentStatusResult, @@ -209,9 +212,23 @@ def ledger(self, args: LedgerArgs, *, timeout: float | None = None) -> LedgerRes """Sync wrapper around ``AsyncSession.ledger``. See that for docs.""" return self._runner.run(self._async.ledger(args, timeout=timeout)) - def issue(self, args: IssueArgs, *, timeout: float | None = None) -> IssueResult: - """Sync wrapper around ``AsyncSession.issue``. See that for docs.""" - return self._runner.run(self._async.issue(args, timeout=timeout)) + def card(self, args: CardArgs, *, timeout: float | None = None) -> CardResult: + """Sync wrapper around ``AsyncSession.card``. See that for docs.""" + return self._runner.run(self._async.card(args, timeout=timeout)) + + def issue( + self, args: CardArgs | IssueArgs, *, timeout: float | None = None + ) -> CardResult: + """Deprecated: use :meth:`card`. Sync wrapper around ``AsyncSession.issue``.""" + warnings.warn( + "session.issue() is deprecated; use session.card(). " + "It calls codespar_card with the same validations.", + DeprecationWarning, + stacklevel=2, + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + return self._runner.run(self._async.issue(args, timeout=timeout)) def shop(self, args: ShopArgs, *, timeout: float | None = None) -> ShopResult: """Sync wrapper around ``AsyncSession.shop``. See that for docs.""" @@ -343,6 +360,8 @@ async def factory() -> AsyncCodeSpar: self.payables = Payables(self._async.payables, self._runner) #: A consumer's own account: ``wallet.pix_keys`` over ``/v1/consumers/:id/pix-keys``. self.wallet = Wallet(self._async.wallet, self._runner) + #: Card reads outside the meta-tool: ``cards.readiness()`` (``GET /v1/cards/readiness``). + self.cards = Cards(self._async.cards, self._runner) #: The receipt document (comprovante) of a payment #: (``/v1/consumers/receipts/:id/document``). self.receipts = Receipts(self._async.receipts, self._runner) diff --git a/packages/python/src/codespar/cards.py b/packages/python/src/codespar/cards.py new file mode 100644 index 00000000..3de8a620 --- /dev/null +++ b/packages/python/src/codespar/cards.py @@ -0,0 +1,91 @@ +""" +``cs.cards`` — card reads over the REST routes that are not a meta-tool call. + +``cs.cards.readiness()`` is ``GET /v1/cards/readiness``: per program, whether +it is ready for this project and environment and the checklist of what is +missing, each step naming who must act (``holder``, ``company_signatory`` or +``org_admin``). The server computes it with the same function as the issue +requirements, so the checklist and an issue refusal never disagree. +Read-only. Mirrors ``cs.cards.readiness()`` in the TypeScript SDK; the +response is the wire shape as typed dicts. + +Issue, read and control cards through ``session.card(...)``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Literal, TypedDict + +import httpx + +from ._http import request_json +from .errors import ApiError + +if TYPE_CHECKING: + from ._sync_client import _LoopRunner + +CardRequirementStatus = Literal["done", "pending", "blocked", "not_applicable"] + + +class _CardRequirementRequired(TypedDict): + #: A pending-action kind, or ``integration_connected`` / ``environment``. + kind: str + status: CardRequirementStatus + actor: str + + +class CardRequirement(_CardRequirementRequired, total=False): + """One step of a program's checklist.""" + + action_url: str + reason: str + pending_action_id: str + + +class CardProgramReadiness(TypedDict): + program: str + issuer: str + currency: str + ready: bool + requirements: list[CardRequirement] + + +class CardReadiness(TypedDict): + """``GET /v1/cards/readiness``.""" + + programs: list[CardProgramReadiness] + + +class AsyncCards: + """``cs.cards`` on :class:`AsyncCodeSpar`.""" + + def __init__(self, client: httpx.AsyncClient, api_key: str, project_id: str | None) -> None: + self._client = client + self._api_key = api_key + self._project_id = project_id + + async def readiness(self, *, timeout: float | None = None) -> CardReadiness: + """``GET /v1/cards/readiness``: what each program needs before an issue can succeed.""" + data = await request_json( + self._client, + "GET", + "/v1/cards/readiness", + api_key=self._api_key, + project_id=self._project_id, + timeout=timeout, + ) + if not isinstance(data, dict) or not isinstance(data.get("programs"), list): + raise ApiError("GET /v1/cards/readiness: malformed response", status=0, body=data) + readiness: CardReadiness = data # type: ignore[assignment] + return readiness + + +class Cards: + """``cs.cards`` on the sync :class:`CodeSpar`.""" + + def __init__(self, inner: AsyncCards, runner: _LoopRunner) -> None: + self._inner = inner + self._runner = runner + + def readiness(self, *, timeout: float | None = None) -> CardReadiness: + return self._runner.run(self._inner.readiness(timeout=timeout)) diff --git a/packages/python/src/codespar/errors.py b/packages/python/src/codespar/errors.py index bbaf55ec..33bd6a46 100644 --- a/packages/python/src/codespar/errors.py +++ b/packages/python/src/codespar/errors.py @@ -37,6 +37,20 @@ def __init__( self.code = code +class CardContractMigrationError(CodeSparError): + """A card call in the old Pomelo-only shape, refused before anything is sent. + + ``code`` matches what the server answers to the same call through the + deprecated tool alias. + """ + + code = "card_contract_migration_required" + + def __init__(self, message: str, legacy_fields: list[str]): + super().__init__(message) + self.legacy_fields = legacy_fields + + #: What the person is told before a key is deleted (the TypeScript SDK exports the same). PIX_KEY_DELETE_CONSEQUENCE = "Depois de excluída, esta chave deixa de apontar para esta conta." diff --git a/packages/python/src/codespar/types.py b/packages/python/src/codespar/types.py index 224a5039..880c1d42 100644 --- a/packages/python/src/codespar/types.py +++ b/packages/python/src/codespar/types.py @@ -609,22 +609,236 @@ class LedgerReceiptsResult: count: int = 0 -# ── codespar_issue wire shape ────────────────────────────────────── +# ── codespar_card wire shape ─────────────────────────────────────── +# +# One Cards contract across issuers: BRL on ``pomelo_brl`` (Pomelo), USD on +# ``rain_usd`` (Rain). Mirrors the TS ``CardArgs``/``CardResult`` in +# ``@codespar/types``. The server resolves program, market and every +# requirement; the issuer of an existing card is read from the record +# behind ``card_id``, never from the request. + +CardAction = Literal["issue", "get", "list", "freeze", "unfreeze", "cancel"] +CardControlAction = Literal["freeze", "unfreeze", "cancel"] +CardIssuer = Literal["pomelo", "rain"] +CardCurrency = Literal["BRL", "USD"] +CardProgram = Literal["pomelo_brl", "rain_usd"] +CardStatus = Literal["pending", "not_activated", "active", "blocked", "canceled"] +CardControlReason = Literal["client_request", "lost", "stolen", "broken", "upgrade"] +CardPendingActionKind = Literal[ + "issuer_kyc", + "accept_terms", + "authorize_automated_issuance", + "bind_key_to_mandate", + "complete_holder_profile", +] +CardPendingActor = Literal["holder", "company_signatory", "org_admin"] + + +@dataclass(slots=True) +class CardArgs: + """Input shape for ``Session.card``. + + - ``issue``: ``currency``, ``mandate_id``, ``consumer_id`` and + ``idempotency_key`` (required: the same key resumes the same request + and never issues a second card); ``provider`` optional, omitted the + currency picks the program. + - ``get``: ``card_id`` (``icrd_...`` Pomelo, ``rcrd_...`` Rain). + - ``list``: optional filters ``issuer``, ``mandate_id``, ``consumer_id``. + - ``freeze`` / ``unfreeze`` / ``cancel``: ``card_id``, optional ``reason``. + """ + + action: CardAction + currency: CardCurrency | None = None + provider: CardIssuer | None = None + mandate_id: str | None = None + consumer_id: str | None = None + idempotency_key: str | None = None + #: Pomelo cardholder identity (pomelo_brl): full_name, email, birthdate, + #: document {type, value, issuing_country}, address {...}, phone. Rain refuses it. + holder: dict[str, Any] | None = None + card_id: str | None = None + issuer: CardIssuer | None = None + reason: CardControlReason | None = None + + +@dataclass(slots=True) +class CardSelection: + """How the program was chosen at issue.""" + + provider_requested: str | None = None + chosen_by: str = "currency" # "provider" | "currency" + + +@dataclass(slots=True) +class CardFunding: + """Funding of a ``rain_usd`` card (USDC). Never mixed into ``currency``.""" + + asset: str = "USDC" + + +@dataclass(slots=True) +class CardView: + """The card view: get, controls, list items.""" + + id: str = "" + issuer: str = "" + program: str = "" + currency: str = "" + status: str = "" + issuer_status: str | None = None + last4: str | None = None + network: str | None = None + mandate_id: str | None = None + consumer_id: str | None = None + created_at: str | None = None + available_actions: list[str] = field(default_factory=list) + funding: CardFunding | None = None + + +@dataclass(slots=True) +class CardIssued: + """``action=issue``, card issued (first call or an idempotent replay). + + The card view is nested in ``card``. + """ + + issue_request_id: str = "" + issuer: str = "" + program: str = "" + selection: CardSelection | None = None + card: CardView = field(default_factory=CardView) + #: The automated-issuance authorization the issue ran under. + authorization_id: str | None = None + authorization_active: bool = False + state: Literal["issued"] = "issued" + + +@dataclass(slots=True) +class CardPendingAction: + """A step only a person can take. Hand ``url`` to ``actor``; never act for them.""" + + id: str = "" + kind: str = "" + actor: str = "" + url: str | None = None + + +@dataclass(slots=True) +class CardPendingHuman: + """``action=issue`` waiting on a person. Retry with the SAME idempotency_key once done.""" + + issue_request_id: str = "" + issuer: str = "" + program: str = "" + pending_action: CardPendingAction = field(default_factory=CardPendingAction) + selection: CardSelection | None = None + state: Literal["pending_human"] = "pending_human" + + +@dataclass(slots=True) +class CardProcessing: + """``action=issue``: the issuer has not answered yet. Read it again with the SAME key.""" + + issue_request_id: str = "" + issuer: str = "" + program: str = "" + selection: CardSelection | None = None + state: Literal["processing"] = "processing" +@dataclass(slots=True) +class CardUncertain: + """``action=issue``: timeout or ambiguous answer, the card MAY exist at the issuer. + + Resolved by reconciliation on the SAME request (same ``idempotency_key``), + never by a new key: a new key would be a second issuance. + """ + + issue_request_id: str = "" + issuer: str = "" + program: str = "" + message: str | None = None + selection: CardSelection | None = None + state: Literal["uncertain"] = "uncertain" + + +@dataclass(slots=True) +class CardFailed: + """``action=issue``: a definitive refusal by the issuer.""" + + issue_request_id: str = "" + issuer: str = "" + program: str = "" + code: str | None = None + reason: str | None = None + message: str | None = None + selection: CardSelection | None = None + state: Literal["failed"] = "failed" + + +@dataclass(slots=True) +class CardList: + """``action=list``.""" + + cards: list[CardView] = field(default_factory=list) + + +@dataclass(slots=True) +class CardProgramAvailability: + program: str = "" + issuer: str = "" + currency: str = "" + available: bool | None = None + reason: str | None = None + operations: list[str] = field(default_factory=list) + + +@dataclass(slots=True) +class CardRefusal: + """A refusal with a stable code, RETURNED (not raised) by ``Session.card``. + + ``state`` and ``http_status`` are stamped by the client (200 when the + refusal came inside the tool envelope); the rest comes from the + refusal body when the server sends it. + """ + + code: str + message: str | None = None + http_status: int = 200 + reason: str | None = None + available_programs: list[CardProgramAvailability] | None = None + issuer: str | None = None + program: str | None = None + action: str | None = None + available_actions: list[str] | None = None + raw: Any = None + state: Literal["refused"] = "refused" + + +CardResult = ( + CardIssued + | CardPendingHuman + | CardProcessing + | CardUncertain + | CardFailed + | CardRefusal + | CardView + | CardList +) + + +# ── Deprecated: the Pomelo-only card shape ───────────────────────── + IssueAction = Literal["card-virtual", "card-physical", "card-control", "card-get"] @dataclass(slots=True) class IssueArgs: - """Input shape for ``Session.issue`` (Pomelo card issuing). - - Mirrors the backend's MetaIssueArgs. Asset-agnostic — the program - currency is set on the card program, not per call. - - ``card-virtual`` Issue a virtual card (active immediately) - - ``card-physical`` Issue a physical card (needs shipping_address) - - ``card-control`` Freeze / unfreeze / cancel an existing card - - ``card-get`` Read a card's status + """Deprecated: the Pomelo-only shape of the deprecated ``issue()`` wrapper. + + Kept so existing imports work. A call in this shape raises + ``CardContractMigrationError`` (``card_contract_migration_required``) + before anything is sent. Use ``CardArgs`` with ``card()``. """ action: IssueAction @@ -637,15 +851,8 @@ class IssueArgs: metadata: dict[str, Any] | None = None -@dataclass(slots=True) -class IssueResult: - id: str | None = None - status: str | None = None - card_type: str | None = None - last_four: str | None = None - cardholder_id: str | None = None - program_id: str | None = None - raw: Any = None +#: Deprecated: ``issue()`` now answers what ``card()`` answers. +IssueResult = CardResult # ── codespar_shop wire shape ─────────────────────────────────────── diff --git a/packages/python/tests/test_card.py b/packages/python/tests/test_card.py new file mode 100644 index 00000000..23999392 --- /dev/null +++ b/packages/python/tests/test_card.py @@ -0,0 +1,525 @@ +""" +codespar_card Python parity tests (enterprise CONTRATO-codespar-card §3-§6). + +Same answers as the TS ``packages/core/src/__tests__/card.test.ts``: issued, +pending, card view, list, refusal inside the tool envelope, refusal as a +non-2xx body, failure with no code. Driven over a mocked backend through the +real ``session.card(...)`` (async and sync). +""" + +from __future__ import annotations + +import json +from typing import Any + +import pytest +from pytest_httpx import HTTPXMock + +from codespar import ( + ApiError, + AsyncCodeSpar, + CardArgs, + CardContractMigrationError, + CardFailed, + CardIssued, + CardList, + CardPendingHuman, + CardProcessing, + CardRefusal, + CardUncertain, + CardView, + CodeSpar, + IssueArgs, +) + +BASE = "https://api.codespar.dev" +EXECUTE = f"{BASE}/v1/sessions/ses_card/execute" + +RAIN_VIEW: dict[str, Any] = { + "id": "rcrd_abc", + "issuer": "rain", + "program": "rain_usd", + "currency": "USD", + "status": "not_activated", + "issuer_status": "notActivated", + "last4": "1234", + "network": None, + "mandate_id": "mnd_usd", + "consumer_id": "cons_1", + "created_at": "2026-11-18T12:00:00.000Z", + "available_actions": [], + "funding": {"asset": "USDC"}, +} + +ISSUE_USD = CardArgs( + action="issue", + currency="USD", + mandate_id="mnd_usd", + consumer_id="cons_1", + idempotency_key="idem_1", +) + + +def _issued(card: dict[str, Any]) -> dict[str, Any]: + return { + "state": "issued", + "issue_request_id": "cir_1", + "issuer": card["issuer"], + "program": card["program"], + "selection": {"provider_requested": None, "chosen_by": "currency"}, + "card": card, + "authorization_id": "caia_1", + "authorization_active": True, + } + + +def _session_json() -> dict[str, Any]: + return { + "id": "ses_card", + "org_id": "org_test", + "user_id": "consumer_123", + "servers": [], + "status": "active", + "created_at": "2026-11-18T12:00:00Z", + "closed_at": None, + } + + +def _envelope(data: Any, *, success: bool = True, error: str | None = None) -> dict[str, Any]: + return { + "success": success, + "data": data, + "error": error, + "duration": 5, + "server": "_codespar", + "tool": "codespar_card", + } + + +def _mock_session(httpx_mock: HTTPXMock) -> None: + httpx_mock.add_response(url=f"{BASE}/v1/sessions", method="POST", json=_session_json()) + + +def _sent(httpx_mock: HTTPXMock) -> dict[str, Any]: + req = next(r for r in httpx_mock.get_requests() if r.url.path.endswith("/execute")) + body: dict[str, Any] = json.loads(req.content) + return body + + +@pytest.mark.asyncio +async def test_issue_dispatches_codespar_card_and_returns_issued(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope(_issued(RAIN_VIEW)), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(ISSUE_USD) + + assert isinstance(result, CardIssued) + assert result.state == "issued" + assert (result.card.id, result.issuer, result.program, result.card.currency) == ( + "rcrd_abc", + "rain", + "rain_usd", + "USD", + ) + assert result.card.status == "not_activated" + assert result.card.issuer_status == "notActivated" + assert result.card.available_actions == [] + assert result.card.network is None + assert result.card.funding is not None and result.card.funding.asset == "USDC" + assert result.authorization_id == "caia_1" + assert result.authorization_active is True + assert result.selection is not None + assert result.selection.chosen_by == "currency" + assert result.selection.provider_requested is None + assert result.issue_request_id == "cir_1" + + body = _sent(httpx_mock) + assert body["tool"] == "codespar_card" + assert body["input"] == { + "action": "issue", + "currency": "USD", + "mandate_id": "mnd_usd", + "consumer_id": "cons_1", + "idempotency_key": "idem_1", + } + + +@pytest.mark.asyncio +async def test_issue_pending_returns_pending_action(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope( + { + "state": "pending_human", + "issue_request_id": "cir_2", + "issuer": "pomelo", + "program": "pomelo_brl", + "pending_action": { + "id": "pa_1", + "kind": "authorize_automated_issuance", + "actor": "company_signatory", + "url": "https://codespar.dev/dashboard/x", + }, + } + ), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card( + CardArgs( + action="issue", + currency="BRL", + provider="pomelo", + mandate_id="m", + consumer_id="c", + idempotency_key="k", + ) + ) + assert isinstance(result, CardPendingHuman) + assert result.state == "pending_human" + assert result.issue_request_id == "cir_2" + assert result.pending_action.kind == "authorize_automated_issuance" + assert result.pending_action.actor == "company_signatory" + assert result.pending_action.url == "https://codespar.dev/dashboard/x" + assert _sent(httpx_mock)["input"]["provider"] == "pomelo" + + +@pytest.mark.asyncio +async def test_issue_without_idempotency_key_sends_nothing(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + with pytest.raises(ApiError, match="idempotency_key is required"): + await session.card( + CardArgs(action="issue", currency="BRL", mandate_id="m", consumer_id="c") + ) + assert not any(r.url.path.endswith("/execute") for r in httpx_mock.get_requests()) + + +@pytest.mark.asyncio +async def test_get_returns_card_view(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope(RAIN_VIEW)) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(CardArgs(action="get", card_id="rcrd_abc")) + assert type(result) is CardView + assert result.id == "rcrd_abc" + assert _sent(httpx_mock)["input"] == {"action": "get", "card_id": "rcrd_abc"} + + +@pytest.mark.asyncio +async def test_list_returns_cards(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope({"cards": [RAIN_VIEW]})) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(CardArgs(action="list", issuer="rain")) + assert isinstance(result, CardList) + assert [c.id for c in result.cards] == ["rcrd_abc"] + assert _sent(httpx_mock)["input"] == {"action": "list", "issuer": "rain"} + + +@pytest.mark.asyncio +async def test_envelope_refusal_is_returned_with_details(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + programs = [ + {"program": "pomelo_brl", "issuer": "pomelo", "currency": "BRL", "available": True}, + { + "program": "rain_usd", + "issuer": "rain", + "currency": "USD", + "available": False, + "reason": "live_blocked", + "operations": ["issue", "get", "list"], + }, + ] + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope( + { + "error": "Rain is not available for this project", + "code": "card_issuer_unavailable", + "details": {"reason": "live_blocked", "available_programs": programs}, + }, + success=False, + error="Rain is not available for this project", + ), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(ISSUE_USD) + assert isinstance(result, CardRefusal) + assert result.state == "refused" + assert result.code == "card_issuer_unavailable" + assert result.reason == "live_blocked" + assert result.http_status == 200 + assert result.message == "Rain is not available for this project" + assert result.available_programs is not None + assert [(p.program, p.available, p.reason) for p in result.available_programs] == [ + ("pomelo_brl", True, None), + ("rain_usd", False, "live_blocked"), + ] + + +@pytest.mark.asyncio +async def test_action_unsupported_carries_available_actions(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope( + { + "error": "freeze is not supported on rain_usd", + "code": "card_action_unsupported", + "details": { + "issuer": "rain", + "program": "rain_usd", + "action": "freeze", + "available_actions": [], + }, + }, + success=False, + error="freeze is not supported on rain_usd", + ), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(CardArgs(action="freeze", card_id="rcrd_abc")) + assert isinstance(result, CardRefusal) + assert (result.code, result.issuer, result.program, result.action) == ( + "card_action_unsupported", + "rain", + "rain_usd", + "freeze", + ) + assert result.available_actions == [] + + +@pytest.mark.asyncio +async def test_non_2xx_refusal_is_returned_with_its_status(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + status_code=409, + json={"error": "idempotency_key_conflict", "message": "same key, different body"}, + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(ISSUE_USD) + assert isinstance(result, CardRefusal) + assert result.code == "idempotency_key_conflict" + assert result.message == "same key, different body" + assert result.http_status == 409 + + +@pytest.mark.asyncio +async def test_failure_without_code_raises(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope(None, success=False, error="Tool not registered: codespar_card"), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + with pytest.raises(ApiError, match="card failed: Tool not registered: codespar_card"): + await session.card(CardArgs(action="get", card_id="icrd_1")) + + +@pytest.mark.asyncio +async def test_unknown_issue_state_raises(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope({"state": "pending"})) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + with pytest.raises(ApiError, match="unexpected issue state"): + await session.card(ISSUE_USD) + + +def test_sync_card_is_the_same_call(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope({**RAIN_VIEW, "status": "blocked", "available_actions": []}), + ) + with CodeSpar(api_key="csk_test_x") as cs: + session = cs.create("consumer_123", servers=[]) + result = session.card(CardArgs(action="cancel", card_id="icrd_1", reason="lost")) + assert isinstance(result, CardView) + assert _sent(httpx_mock)["input"] == { + "action": "cancel", + "card_id": "icrd_1", + "reason": "lost", + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("state", "cls"), + [("processing", CardProcessing), ("uncertain", CardUncertain), ("failed", CardFailed)], +) +async def test_non_final_issue_states_are_distinct( + httpx_mock: HTTPXMock, state: str, cls: type +) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope( + { + "state": state, + "issue_request_id": "cir_3", + "issuer": "rain", + "program": "rain_usd", + "code": "issuer_declined", + } + ), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(ISSUE_USD) + assert type(result) is cls + assert result.state == state + assert result.issue_request_id == "cir_3" + if isinstance(result, CardFailed): + assert result.code == "issuer_declined" + + +@pytest.mark.asyncio +async def test_deprecated_issue_warns_and_sends_codespar_card(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope(_issued(RAIN_VIEW))) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + with pytest.warns(DeprecationWarning, match=r"session\.issue\(\) is deprecated"): + result = await session.issue(ISSUE_USD) + assert isinstance(result, CardIssued) + body = _sent(httpx_mock) + assert body["tool"] == "codespar_card" + assert body["input"]["idempotency_key"] == "idem_1" + + +@pytest.mark.asyncio +async def test_deprecated_issue_refuses_old_shape_before_sending(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + with ( + pytest.warns(DeprecationWarning), + pytest.raises(CardContractMigrationError) as exc, + ): + await session.issue( + IssueArgs(action="card-virtual", cardholder_id="usr_1", program_id="afg_1") + ) + assert exc.value.code == "card_contract_migration_required" + assert exc.value.legacy_fields == ["cardholder_id", "program_id"] + assert "mandate_id, consumer_id and idempotency_key" in str(exc.value) + assert not any(r.url.path.endswith("/execute") for r in httpx_mock.get_requests()) + + +def test_sync_deprecated_issue_warns_once_per_call(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope(RAIN_VIEW)) + with CodeSpar(api_key="csk_test_x") as cs: + session = cs.create("consumer_123", servers=[]) + with pytest.warns(DeprecationWarning) as record: + session.issue(CardArgs(action="get", card_id="rcrd_abc")) + assert len([w for w in record if issubclass(w.category, DeprecationWarning)]) == 1 + + +@pytest.mark.asyncio +async def test_cards_readiness(httpx_mock: HTTPXMock) -> None: + doc = { + "programs": [ + { + "program": "rain_usd", + "issuer": "rain", + "currency": "USD", + "ready": False, + "requirements": [ + {"kind": "accept_terms", "status": "pending", "actor": "holder"}, + {"kind": "environment", "status": "blocked", "actor": "org_admin"}, + ], + } + ] + } + httpx_mock.add_response(url=f"{BASE}/v1/cards/readiness", method="GET", json=doc) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + assert await cs.cards.readiness() == doc + + +def test_cards_readiness_sync(httpx_mock: HTTPXMock) -> None: + doc = {"programs": []} + httpx_mock.add_response(url=f"{BASE}/v1/cards/readiness", method="GET", json=doc) + with CodeSpar(api_key="csk_test_x") as cs: + assert cs.cards.readiness() == doc + + +@pytest.mark.asyncio +async def test_enterprise_refusal_envelope(httpx_mock: HTTPXMock) -> None: + """The tool-result refusal enterprise sends: {error: {code, message, details}, http_status}.""" + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope( + { + "error": { + "code": "card_issuer_unavailable", + "message": "rain_usd is not available here", + "details": { + "reason": "live_blocked", + "available_programs": [ + {"program": "pomelo_brl", "issuer": "pomelo", "currency": "BRL"} + ], + }, + }, + "http_status": 422, + }, + success=False, + error="card_issuer_unavailable", + ), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(ISSUE_USD) + assert isinstance(result, CardRefusal) + assert result.code == "card_issuer_unavailable" + assert result.message == "rain_usd is not available here" + assert result.reason == "live_blocked" + assert result.http_status == 422 + assert result.available_programs is not None + assert result.available_programs[0].program == "pomelo_brl" + assert result.available_programs[0].available is None + + +@pytest.mark.asyncio +async def test_issue_sends_holder(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + view = {**RAIN_VIEW, "id": "icrd_1", "issuer": "pomelo", "program": "pomelo_brl"} + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope(_issued(view))) + holder = {"full_name": "A B", "email": "a@b.dev"} + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + await session.card( + CardArgs( + action="issue", + currency="BRL", + mandate_id="m", + consumer_id="c", + idempotency_key="k", + holder=holder, + ) + ) + assert _sent(httpx_mock)["input"]["holder"] == holder diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index bbeed086..a243d46b 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -1,5 +1,32 @@ # @codespar/types — CHANGELOG +## 0.12.0 — unreleased (coordinated codespar_card release) + +### Added + +- **`codespar_card`** (`CARD_DEFINITION` / `CARD_INPUT`) in `SHARED_META_TOOL_DEFINITIONS`: one card contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`). + - Actions: `issue | get | list | freeze | unfreeze | cancel`. + - Properties: `currency` (BRL | USD), `provider` (pomelo | rain), `mandate_id`, `consumer_id`, `idempotency_key`, `card_id`, `issuer` (pomelo | rain), `reason`. + - `required` is `["action"]`. The server enforces `idempotency_key`, currency, mandate and holder on `issue`. +- `Session.card(args: CardArgs): Promise`. + - `CardArgs` is `CardIssueArgs | CardGetArgs | CardListArgs | CardControlArgs`. + - `CardResult` narrows on `state`: `issued`, `pending_human`, `processing`, `uncertain`, `failed` or `refused`. A result with no `state` is a card view or a list. + - Pending actors are `holder`, `company_signatory` and `org_admin`. + - Refusal codes include `card_oauth_not_bound` and `card_contract_migration_required`. +- `CardReadiness` / `CardProgramReadiness` / `CardRequirement`, for `GET /v1/cards/readiness`. +- The scenario manifest moves to 0.12.0. + +### Changed + +- `SHARED_META_TOOL_DEFINITIONS` lists `codespar_card` in place of the old card tool, so an agent is shown one card tool. `SharedMetaToolName` follows. + +### Deprecated + +- **`Session.issue()`** now takes `CardArgs | IssueArgs` and returns `CardResult`. It is a wrapper over `card()` with the same validations. +- **`IssueArgs`** is kept only so imports compile. A call in that shape is refused with `card_contract_migration_required`. +- **`IssueResult`** is an alias of `CardResult`. +- **`ISSUE_DEFINITION`** is the old tool name as an alias with `codespar_card`'s exact input and a DEPRECATED description. It is outside the shared map. + ## 0.11.7 — 2026-10-30 ### Added diff --git a/packages/types/package.json b/packages/types/package.json index 683db501..a23c5ded 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/types", - "version": "0.11.7", + "version": "0.12.0", "description": "Shared session interface contract for codespar runtimes", "type": "module", "main": "./dist/index.js", diff --git a/packages/types/src/meta-tool-definitions.test.ts b/packages/types/src/meta-tool-definitions.test.ts index ac8ae4ae..45f0bafa 100644 --- a/packages/types/src/meta-tool-definitions.test.ts +++ b/packages/types/src/meta-tool-definitions.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from "vitest"; import { + ISSUE_DEFINITION, SHARED_META_TOOL_DEFINITIONS, contractOf, type MetaToolInputSchema, @@ -11,8 +12,11 @@ import { type AgentFacingToolShape, } from "./meta-tool-definition-conformance.js"; import type { + CardArgs, + CardControlReason, + CardCurrency, + CardIssuer, ChargeArgs, - IssueArgs, KycArgs, LedgerArgs, PayArgs, @@ -43,13 +47,13 @@ function defWith(overrides: { describe("shared meta-tool definitions", () => { it("publishes ALL fifteen meta-tools keyed by wire name (ent#933: was 3 of 15)", () => { expect(Object.keys(SHARED_META_TOOL_DEFINITIONS).sort()).toEqual([ + "codespar_card", "codespar_charge", "codespar_checkout", "codespar_crypto_pay", "codespar_discover", "codespar_get_started", "codespar_invoice", - "codespar_issue", "codespar_kyc", "codespar_ledger", "codespar_manage_connections", @@ -520,24 +524,78 @@ describe("wire-shape arg unions match the published definition vocabularies (ent ); }); - it("IssueArgs.action + IssueArgs.control == codespar_issue enums", () => { - const actions: Record = { - "card-virtual": true, - "card-physical": true, - "card-control": true, - "card-get": true, - }; - expect(pinned(actions)).toEqual( - [...SHARED_META_TOOL_DEFINITIONS.codespar_issue.input_schema.properties.action!.enum!].sort(), - ); - const controls: Record, true> = { + it("CardArgs.action/currency/provider/issuer == codespar_card enums", () => { + const card = SHARED_META_TOOL_DEFINITIONS.codespar_card; + const actions: Record = { + issue: true, + get: true, + list: true, freeze: true, unfreeze: true, cancel: true, }; - expect(pinned(controls)).toEqual( - [...SHARED_META_TOOL_DEFINITIONS.codespar_issue.input_schema.properties.control!.enum!].sort(), - ); + expect(pinned(actions)).toEqual([...card.input_schema.properties.action!.enum!].sort()); + const currencies: Record = { BRL: true, USD: true }; + expect(pinned(currencies)).toEqual([...card.input_schema.properties.currency!.enum!].sort()); + const issuers: Record = { pomelo: true, rain: true }; + expect(pinned(issuers)).toEqual([...card.input_schema.properties.provider!.enum!].sort()); + expect(pinned(issuers)).toEqual([...card.input_schema.properties.issuer!.enum!].sort()); + const reasons: Record = { client_request: true, lost: true, stolen: true, broken: true, upgrade: true }; + expect(pinned(reasons)).toEqual([...card.input_schema.properties.reason!.enum!].sort()); + }); + + it("codespar_card publishes the contract §6 surface, pinned (enterprise codespar_card)", () => { + const card = SHARED_META_TOOL_DEFINITIONS.codespar_card; + expect(card.name).toBe("codespar_card"); + expect(Object.keys(card.input_schema.properties)).toEqual([ + "action", + "currency", + "provider", + "mandate_id", + "consumer_id", + "idempotency_key", + "holder", + "card_id", + "issuer", + "reason", + ]); + expect(card.input_schema.properties.reason!.enum).toEqual(["client_request", "lost", "stolen", "broken", "upgrade"]); + expect(Object.keys(card.input_schema.properties.holder!.properties!)).toEqual([ + "full_name", + "email", + "birthdate", + "document", + "address", + "phone", + ]); + // The flat schema cannot say "required when action=issue": currency, + // mandate_id, consumer_id and idempotency_key are enforced by the server + // (and by the CLI/SDK callers) on issue, not by the required set. + expect(card.input_schema.required).toEqual(["action"]); + // No Pomelo-only vocabulary survives the rename. + const props = Object.keys(card.input_schema.properties); + for (const gone of ["cardholder_id", "program_id", "control", "shipping_address", "metadata"]) { + expect(props).not.toContain(gone); + } + expect(card.description).toMatch(/idempotency_key is required on issue/); + expect(card.description).toMatch(/pending_action/); + // 8.3: an uncertain issue is never "try again with another key". + expect(card.description).toMatch(/state=uncertain/); + expect(card.description).toMatch(/SAME idempotency_key, never by a new key/); + }); + + it("the old card tool is a deprecated alias outside the shared surface (contract §8.4)", () => { + const old = ["codespar", "issue"].join("_"); + // An agent is shown one card tool. + expect(Object.keys(SHARED_META_TOOL_DEFINITIONS)).not.toContain(old); + for (const def of ALL) expect(def.name).not.toBe(old); + // The alias takes exactly codespar_card's input: no path keeps the old, + // less restrictive Pomelo arguments. + expect(ISSUE_DEFINITION.name).toBe(old); + expect(ISSUE_DEFINITION.input_schema).toBe(SHARED_META_TOOL_DEFINITIONS.codespar_card.input_schema); + expect(ISSUE_DEFINITION.description).toMatch(/^DEPRECATED alias of codespar_card/); + expect(ISSUE_DEFINITION.description).toMatch(/card_contract_migration_required/); + expect(definitionViolations(ISSUE_DEFINITION).map((v) => v.detail)).toEqual([]); }); it("ShopArgs.action == codespar_shop action enum", () => { diff --git a/packages/types/src/meta-tool-definitions.ts b/packages/types/src/meta-tool-definitions.ts index 211f651d..b5da6200 100644 --- a/packages/types/src/meta-tool-definitions.ts +++ b/packages/types/src/meta-tool-definitions.ts @@ -462,17 +462,30 @@ const LEDGER_INPUT: MetaToolInputSchema = { required: ["action"], }; -const ISSUE_INPUT: MetaToolInputSchema = { +const CARD_INPUT: MetaToolInputSchema = { type: "object", properties: { - action: { type: "string", description: "card-virtual | card-physical | card-control | card-get (default: card-virtual)", enum: ["card-virtual", "card-physical", "card-control", "card-get"] }, - cardholder_id: { type: "string", description: "Cardholder id at the issuer. Required to issue a card." }, - program_id: { type: "string", description: "Card program / BIN (issuer affinity group). Required to issue a card." }, - card_id: { type: "string", description: "Card id — required for card-control and card-get." }, - control: { type: "string", description: "freeze | unfreeze | cancel (card-control only)", enum: ["freeze", "unfreeze", "cancel"] }, - reason: { type: "string", description: "Reason stamped on a control action" }, - shipping_address: { type: "object", description: "Shipping address (card-physical only)" }, - metadata: { type: "object", description: "Provider-specific overrides" }, + action: { type: "string", description: "issue | get | list | freeze | unfreeze | cancel", enum: ["issue", "get", "list", "freeze", "unfreeze", "cancel"] }, + currency: { type: "string", description: "Card currency, BRL | USD (action=issue, required). Picks the program when provider is omitted: BRL -> pomelo_brl, USD -> rain_usd.", enum: ["BRL", "USD"] }, + provider: { type: "string", description: "Card issuer, pomelo | rain (action=issue, optional). Omit it and the currency picks the program.", enum: ["pomelo", "rain"] }, + mandate_id: { type: "string", description: "The mandate the card spends under (action=issue, required; action=list filter). Its currency must equal the card currency; one card per mandate." }, + consumer_id: { type: "string", description: "The card holder, a consumer of this project (action=issue, required; action=list filter)." }, + idempotency_key: { type: "string", description: "Required on action=issue. A retry with the same key resumes the same request and never issues a second card; the same key with a different body is refused with idempotency_key_conflict." }, + holder: { + type: "object", + description: "The Pomelo cardholder identity (action=issue on pomelo_brl): full_name, email, birthdate, document { type, value, issuing_country }, address { line1, line2?, street_number?, neighborhood?, city, state?, postal_code, municipality?, country }, phone?. Without it a pomelo_brl issue answers pending_human with complete_holder_profile. Rain refuses it.", + properties: { + full_name: { type: "string", description: "Holder's full name." }, + email: { type: "string", description: "Holder's email." }, + birthdate: { type: "string", description: "Holder's birthdate, YYYY-MM-DD." }, + document: { type: "object", description: "Identity document: { type, value, issuing_country }." }, + address: { type: "object", description: "Address: { line1, line2?, street_number?, neighborhood?, city, state?, postal_code, municipality?, country }." }, + phone: { type: "string", description: "Holder's phone (optional)." }, + }, + }, + card_id: { type: "string", description: "Card id, icrd_... (pomelo) or rcrd_... (rain). Required for get, freeze, unfreeze and cancel." }, + issuer: { type: "string", description: "Filter cards by issuer, pomelo | rain (action=list).", enum: ["pomelo", "rain"] }, + reason: { type: "string", description: "Why, on freeze, unfreeze or cancel: client_request | lost | stolen | broken | upgrade.", enum: ["client_request", "lost", "stolen", "broken", "upgrade"] }, }, required: ["action"], }; @@ -605,13 +618,27 @@ export const LEDGER_DEFINITION: SharedMetaToolDefinition = { contract: contractOf(LEDGER_INPUT), }; -/** Issue and control payment cards for AI agents or end-users. */ +/** Issue, read, and control payment cards across issuers (Pomelo BRL, Rain USD). */ +export const CARD_DEFINITION: SharedMetaToolDefinition = { + name: "codespar_card", + description: + "Issue, read, and control payment cards for AI agents or end-users, one contract across issuers: BRL cards on the pomelo_brl program (Pomelo), USD cards on the rain_usd program (Rain). action=issue issues a card for a holder (consumer_id) under a mandate (mandate_id) in a currency (currency); provider is optional, and when omitted the currency picks the program. idempotency_key is required on issue. The answer always names issuer, program and selection. A requirement only a person can satisfy (issuer KYC, terms, the authorization for automated issuance, binding the key to the mandate) answers state=pending_human with a pending_action { id, kind, actor, url } to hand to that person (actor holder, company_signatory or org_admin), never something to accept on their behalf; retry with the same idempotency_key once it is done. state=processing means the issuer has not answered yet, and state=uncertain means the card MAY exist at the issuer: both are resolved on the SAME idempotency_key, never by a new key, which would be a second card. state=failed is a definitive refusal by the issuer. action=get reads one card by card_id; action=list lists cards (filters issuer, mandate_id, consumer_id); action=freeze / unfreeze / cancel control a card, and each card's available_actions says which of them its program and state allow (rain cards allow none here). This is the agent-spend-card primitive: it creates SPEND INSTRUMENTS, distinct from codespar_pay/charge which move money.", + input_schema: CARD_INPUT, + contract: contractOf(CARD_INPUT), +}; + +/** + * @deprecated The transition alias of `codespar_card` (contract §8.4): the + * same input, the same server path and the same validations. Published for + * runtimes that still register the old name; it is NOT in + * `SHARED_META_TOOL_DEFINITIONS`, so an agent is shown one card tool. + */ export const ISSUE_DEFINITION: SharedMetaToolDefinition = { - name: "codespar_issue", + name: ["codespar", "issue"].join("_"), description: - "Issue and control payment cards for AI agents or end-users. Routes to a card-issuing partner (pan-LATAM issuing-as-a-service). action=card-virtual issues a virtual card (active immediately); card-physical issues a physical card (needs shipping_address); card-control freezes/unfreezes/cancels an existing card; card-get reads a card's status. This is the agent-spend-card primitive — it creates SPEND INSTRUMENTS, distinct from codespar_pay/charge which move money.", - input_schema: ISSUE_INPUT, - contract: contractOf(ISSUE_INPUT), + "DEPRECATED alias of codespar_card: same arguments, same server path, same validations and refusals. Call codespar_card instead. A call with the old Pomelo-only arguments is refused with card_contract_migration_required, naming the new fields (currency, mandate_id, consumer_id, idempotency_key).", + input_schema: CARD_INPUT, + contract: contractOf(CARD_INPUT), }; /** @@ -636,7 +663,7 @@ export const SHARED_META_TOOL_DEFINITIONS = { codespar_crypto_pay: CRYPTO_PAY_DEFINITION, codespar_kyc: KYC_DEFINITION, codespar_ledger: LEDGER_DEFINITION, - codespar_issue: ISSUE_DEFINITION, + codespar_card: CARD_DEFINITION, } as const; /** Wire names that have a published shared definition. */ diff --git a/packages/types/src/testing/scenario-manifest.ts b/packages/types/src/testing/scenario-manifest.ts index 7646ac21..78fa059f 100644 --- a/packages/types/src/testing/scenario-manifest.ts +++ b/packages/types/src/testing/scenario-manifest.ts @@ -31,7 +31,7 @@ * union, and the per-example groups a consumer drives completely. */ export const DEMO_SCENARIO_MANIFEST = { /** Must equal this package's published version (see the lockstep test). */ - version: "0.11.7", + version: "0.12.0", /** Every shipped scenario `name` — the union of all `groups` (see the test). */ scenarios: [ "customer-data-rejection", diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index 91cf66e2..c08a2577 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -178,13 +178,25 @@ export interface Session extends SessionBase { */ ledger(args: LedgerArgs, opts?: CallOptions): Promise; /** - * Issue and control payment cards (codespar_issue). Typed wrapper - * around `execute("codespar_issue", {...})`. Routes to Pomelo - * card-issuing — card-virtual / card-physical / card-control - * (freeze/unfreeze/cancel) / card-get. The agent-spend-card - * primitive; distinct from pay/charge which move money. + * Issue, read, list and control payment cards across issuers + * (codespar_card): BRL on pomelo_brl, USD on rain_usd. Typed wrapper + * around `execute("codespar_card", {...})`. A refusal with a stable code + * comes back as a `CardRefusal` value (`state: "refused"`); a non-final + * issue as `pending_human` (a person must act), `processing` or + * `uncertain` (both resolved on the SAME idempotency_key, never a new + * one); transport failures throw. + * The agent-spend-card primitive; distinct from pay/charge which move + * money. */ - issue(args: IssueArgs, opts?: CallOptions): Promise; + card(args: CardArgs, opts?: CallOptions): Promise; + /** + * @deprecated Use `card()`. A wrapper over `card()`: same tool + * (`codespar_card`), same validations, plus a one-time deprecation + * warning. A call in the old Pomelo shape (`cardholder_id` / + * `program_id`, `card-*` actions) is refused before anything is sent, + * naming the new fields. + */ + issue(args: CardArgs | IssueArgs, opts?: CallOptions): Promise; /** * Buy-side shopping: catalog search → async checkout → Pix mint. * Typed wrapper around `execute("codespar_shop", {...})`. The @@ -796,45 +808,324 @@ export interface LedgerReceiptsResult { count: number; } -/* ── codespar_issue wire shape ───────────────────────────────── */ +/* ── codespar_card wire shape ────────────────────────────────── */ + +/** + * One Cards contract across issuers (enterprise CONTRATO-codespar-card §1-§6): + * BRL cards on `pomelo_brl` (Pomelo), USD cards on `rain_usd` (Rain). The + * server resolves the program, the market and every requirement; nothing in + * the request decides the issuer of an existing card (it is read from the + * record behind `card_id`). + */ +export type CardIssuer = "pomelo" | "rain"; +/** The CARD currency. Rain's funding asset (USDC) is separate: `CardView.funding`. */ +export type CardCurrency = "BRL" | "USD"; +/** Program registry, code-side on the server. */ +export type CardProgram = "pomelo_brl" | "rain_usd"; +export type CardAction = "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"; +export type CardControlAction = "freeze" | "unfreeze" | "cancel"; +/** Normalized card state; the issuer's raw value stays in `issuer_status`. */ +export type CardStatus = "pending" | "not_activated" | "active" | "blocked" | "canceled"; + +/** + * action=issue. `idempotency_key` is required: a retry with the same key + * resumes the same request (same program, same backend operation) and never + * issues a second card. `provider` is optional; omitted, the currency picks + * the program (BRL -> pomelo_brl, USD -> rain_usd). + */ +export interface CardIssueArgs { + action: "issue"; + currency: CardCurrency; + provider?: CardIssuer; + mandate_id: string; + consumer_id: string; + idempotency_key: string; + /** Pomelo cardholder identity (pomelo_brl). Without it the issue answers pending_human/complete_holder_profile. Rain refuses it. */ + holder?: CardHolder; +} + +/** The Pomelo cardholder identity sent on a pomelo_brl issue. */ +export interface CardHolder { + full_name: string; + email: string; + /** YYYY-MM-DD. */ + birthdate: string; + document: { type: string; value: string; issuing_country: string }; + address: { + line1: string; + line2?: string; + street_number?: string; + neighborhood?: string; + city: string; + state?: string; + postal_code: string; + municipality?: string; + country: string; + }; + phone?: string; +} + +/** Why a control was asked for. */ +export type CardControlReason = "client_request" | "lost" | "stolen" | "broken" | "upgrade"; + +/** action=get: one card by id (`icrd_...` Pomelo, `rcrd_...` Rain). */ +export interface CardGetArgs { + action: "get"; + card_id: string; +} + +/** action=list: cards of both issuers, optionally filtered. */ +export interface CardListArgs { + action: "list"; + issuer?: CardIssuer; + mandate_id?: string; + consumer_id?: string; +} + +/** + * action=freeze | unfreeze | cancel, routed by the card's recorded issuer. + * An action the program does not support (any control on a Rain card) is + * refused with `card_action_unsupported`. + */ +export interface CardControlArgs { + action: CardControlAction; + card_id: string; + reason?: CardControlReason; +} + +export type CardArgs = CardIssueArgs | CardGetArgs | CardListArgs | CardControlArgs; + +/** How the program was chosen at issue. */ +export interface CardSelection { + provider_requested: CardIssuer | null; + chosen_by: "provider" | "currency"; +} + +/** Funding of a `rain_usd` card. Never mixed into `currency`. */ +export interface CardFunding { + asset: "USDC"; +} + +/** The card view (REST and codespar_card): get, controls, list items, an issued card. */ +export interface CardView { + /** Discriminant slot: a card view carries no `state` (see CardIssued). */ + state?: never; + id: string; + issuer: CardIssuer; + program: CardProgram; + currency: CardCurrency; + status: CardStatus; + issuer_status: string | null; + last4: string | null; + network: string | null; + mandate_id: string | null; + consumer_id: string | null; + created_at: string; + /** Only what the program supports AND the card state allows (rain: none). */ + available_actions: CardControlAction[]; + funding?: CardFunding; +} + +/** action=issue, card issued (first call or an idempotent replay). The card view is nested in `card`. */ +export interface CardIssued { + state: "issued"; + issue_request_id: string; + issuer: CardIssuer; + program: CardProgram; + selection: CardSelection; + card: CardView; + /** The automated-issuance authorization the issue ran under (contract §8.1). */ + authorization_id: string | null; + authorization_active: boolean; +} + +export type CardPendingActionKind = + | "issuer_kyc" + | "accept_terms" + | "authorize_automated_issuance" + | "bind_key_to_mandate" + | "complete_holder_profile"; + +/** + * Who must act. `holder` and `company_signatory` are different people with + * different records (contract §8.2): an org admin never accepts a holder's + * personal terms, and a PJ card for a company user still needs that user's + * own acceptance. + */ +export type CardPendingActor = "holder" | "company_signatory" | "org_admin"; + +/** + * A requirement only a person can satisfy. Hand `url` to `actor`; never + * accept anything on their behalf. `id` is stable for the same request and + * kind. Once done, retry with the SAME idempotency_key. + */ +export interface CardPendingAction { + id: string; + kind: CardPendingActionKind; + actor: CardPendingActor; + url: string | null; +} + +/** Fields every non-final issue answer carries. */ +interface CardIssueRequestRef { + issue_request_id: string; + issuer: CardIssuer; + program: CardProgram; + selection?: CardSelection; +} + +/** action=issue, waiting on a person (REST answers 202). */ +export interface CardPendingHuman extends CardIssueRequestRef { + state: "pending_human"; + pending_action: CardPendingAction; +} + +/** action=issue, the issuer was called and has not answered yet. Read it again with the SAME key. */ +export interface CardProcessing extends CardIssueRequestRef { + state: "processing"; +} + +/** + * action=issue, the issuer timed out or answered ambiguously: the card MAY + * exist there. It is resolved by reconciliation on the SAME request (same + * idempotency_key, same backend reference), never by a new key: a new key + * would be a second issuance. + */ +export interface CardUncertain extends CardIssueRequestRef { + state: "uncertain"; + message?: string | null; +} + +/** action=issue, a definitive refusal by the issuer. */ +export interface CardFailed extends CardIssueRequestRef { + state: "failed"; + code?: string; + reason?: string; + message?: string | null; +} + +/** action=list. */ +export interface CardList { + state?: never; + cards: CardView[]; +} + +export type CardUnavailableReason = + | "not_configured" + | "not_verified" + | "verify_failed" + | "live_blocked" + | "account_not_eligible" + | "issuer_disabled" + | "issuer_not_supported"; + +export type CardRefusalCode = + | "card_issuer_unavailable" + | "card_program_not_found" + | "card_action_unsupported" + | "card_terms_policy_missing" + | "card_oauth_not_bound" + | "card_contract_migration_required" + | "idempotency_key_conflict" + | (string & {}); + +/** One program as the server sees it for the caller's project and environment. */ +export interface CardProgramAvailability { + program: CardProgram; + issuer: CardIssuer; + currency: CardCurrency; + available?: boolean; + reason?: CardUnavailableReason; + operations?: CardAction[]; +} + +/** + * A refusal with a stable code, returned (not thrown) by `session.card()`. + * `state` and `http_status` are stamped by the client; the fields after + * `http_status` come from the refusal body when the server sends them. + */ +export interface CardRefusal { + state: "refused"; + code: CardRefusalCode; + message: string | null; + /** HTTP status of the refusal: the body's own `http_status` when it carries one, else the response status. */ + http_status: number; + reason?: CardUnavailableReason | (string & {}); + available_programs?: CardProgramAvailability[]; + issuer?: CardIssuer; + program?: CardProgram; + action?: CardAction; + available_actions?: CardControlAction[]; + /** The refusal body as received. */ + raw: unknown; +} + +export type CardIssueResult = + | CardIssued + | CardPendingHuman + | CardProcessing + | CardUncertain + | CardFailed + | CardRefusal; /** - * Card-issuing args. Four actions over a card-issuing provider (Pomelo). - * Mirrors the backend's MetaIssueArgs (codespar-enterprise) so the wire - * payload matches byte-for-byte. Asset-agnostic — the program currency - * is set on the card program, not per call. - * - card-virtual Issue a virtual card (active immediately) - * - card-physical Issue a physical card (needs shipping_address) - * - card-control Freeze / unfreeze / cancel an existing card - * - card-get Read a card's status + * Narrow on `state`: "issued" | "pending_human" | "processing" | + * "uncertain" | "failed" | "refused"; no `state` is a card view (get, + * freeze, unfreeze, cancel) or a list (`"cards" in result`). + */ +export type CardResult = CardIssueResult | CardView | CardList; + +/* ── GET /v1/cards/readiness ─────────────────────────────────── */ + +/** The pending-action kinds plus the two admin/environment checks. */ +export type CardRequirementKind = CardPendingActionKind | "integration_connected" | "environment"; + +export type CardRequirementStatus = "done" | "pending" | "blocked" | "not_applicable"; + +/** One step of a program's checklist. The same server function computes it and the issue requirements. */ +export interface CardRequirement { + kind: CardRequirementKind; + status: CardRequirementStatus; + actor: CardPendingActor; + action_url?: string; + reason?: string; + pending_action_id?: string; +} + +export interface CardProgramReadiness { + program: CardProgram; + issuer: CardIssuer; + currency: CardCurrency; + ready: boolean; + requirements: CardRequirement[]; +} + +/** `GET /v1/cards/readiness` (read-only; person session or API key). */ +export interface CardReadiness { + programs: CardProgramReadiness[]; +} + +/* ── Deprecated: the Pomelo-only card shape ──────────────────── */ + +/** + * @deprecated The Pomelo-only shape of the deprecated `issue()` wrapper. + * Kept so existing imports compile; a call in this shape is refused with + * `card_contract_migration_required` before anything is sent. Use + * `CardArgs` with `card()`. */ export interface IssueArgs { action: "card-virtual" | "card-physical" | "card-control" | "card-get"; - /** Cardholder id (maps to Pomelo user_id). Required to issue. */ cardholder_id?: string; - /** Card program / BIN (maps to Pomelo affinity_group_id). Required to - * issue. */ program_id?: string; - /** Card id — required for card-control / card-get. */ card_id?: string; - /** Control verb: freeze→BLOCKED, unfreeze→ACTIVE, cancel→DISABLED. */ control?: "freeze" | "unfreeze" | "cancel"; - /** Reason stamped on a control action. */ reason?: string; - /** Shipping address for card-physical. */ shipping_address?: Record; metadata?: Record; } -export interface IssueResult { - id?: string | null; - status?: string | null; - card_type?: string | null; - last_four?: string | null; - cardholder_id?: string | null; - program_id?: string | null; - raw?: unknown; -} +/** @deprecated `issue()` now answers what `card()` answers. Use `CardResult`. */ +export type IssueResult = CardResult; /* ── codespar_shop wire shape ────────────────────────────────── */ diff --git a/packages/vercel/package.json b/packages/vercel/package.json index 2a1a300b..c4ca6962 100644 --- a/packages/vercel/package.json +++ b/packages/vercel/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/vercel", - "version": "0.4.7", + "version": "0.4.8", "description": "Vercel AI SDK adapter for CodeSpar — convert MCP tools to Vercel AI tool format", "type": "module", "main": "./dist/index.js", @@ -36,7 +36,7 @@ "directory": "packages/vercel" }, "peerDependencies": { - "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0", + "@codespar/sdk": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0 || ^0.17.0", "ai": ">=3.0.0" }, "devDependencies": { From d24555f909465096e1f7fb263ff45ff4ce5250f7 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 01:10:09 -0300 Subject: [PATCH 02/12] refactor(types): spell the deprecated alias name literally Co-Authored-By: Claude Opus 5.5 --- packages/types/src/meta-tool-definitions.test.ts | 2 +- packages/types/src/meta-tool-definitions.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/types/src/meta-tool-definitions.test.ts b/packages/types/src/meta-tool-definitions.test.ts index 45f0bafa..1940977e 100644 --- a/packages/types/src/meta-tool-definitions.test.ts +++ b/packages/types/src/meta-tool-definitions.test.ts @@ -585,7 +585,7 @@ describe("wire-shape arg unions match the published definition vocabularies (ent }); it("the old card tool is a deprecated alias outside the shared surface (contract §8.4)", () => { - const old = ["codespar", "issue"].join("_"); + const old = "codespar_issue"; // An agent is shown one card tool. expect(Object.keys(SHARED_META_TOOL_DEFINITIONS)).not.toContain(old); for (const def of ALL) expect(def.name).not.toBe(old); diff --git a/packages/types/src/meta-tool-definitions.ts b/packages/types/src/meta-tool-definitions.ts index b5da6200..90f5ca7f 100644 --- a/packages/types/src/meta-tool-definitions.ts +++ b/packages/types/src/meta-tool-definitions.ts @@ -634,7 +634,7 @@ export const CARD_DEFINITION: SharedMetaToolDefinition = { * `SHARED_META_TOOL_DEFINITIONS`, so an agent is shown one card tool. */ export const ISSUE_DEFINITION: SharedMetaToolDefinition = { - name: ["codespar", "issue"].join("_"), + name: "codespar_issue", description: "DEPRECATED alias of codespar_card: same arguments, same server path, same validations and refusals. Call codespar_card instead. A call with the old Pomelo-only arguments is refused with card_contract_migration_required, naming the new fields (currency, mandate_id, consumer_id, idempotency_key).", input_schema: CARD_INPUT, From 65515c1c55980b92f8803e44198ad13cc9e33a6a Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 01:35:57 -0300 Subject: [PATCH 03/12] =?UTF-8?q?fix(cards):=20enterprise=20answers=20?= =?UTF-8?q?=E2=80=94=20no=20failed=20state,=20nested=20issued=20card,=20ho?= =?UTF-8?q?lder,=20reason=20enum,=20retry=20hints?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A definitive issuer failure is a refusal (card_issue_refused, or card_issue_request_failed with failure_code), never an issue state. Co-Authored-By: Claude Opus 5.5 --- packages/cli/CHANGELOG.md | 2 +- .../cli/src/__tests__/card-command.test.ts | 30 ++++++++--- packages/cli/src/commands/card.ts | 30 ++++++----- packages/core/CHANGELOG.md | 3 +- packages/core/README.md | 2 +- packages/core/src/__tests__/card.test.ts | 27 ++++++++-- packages/core/src/card.ts | 8 ++- packages/core/src/session.ts | 2 +- packages/python/README.md | 13 +++-- packages/python/src/codespar/__init__.py | 2 - .../python/src/codespar/_async_session.py | 30 ++++++----- packages/python/src/codespar/types.py | 26 ++++------ packages/python/tests/test_card.py | 50 ++++++++++++++++--- packages/types/CHANGELOG.md | 4 +- packages/types/src/meta-tool-definitions.ts | 2 +- packages/types/src/types.ts | 36 ++++++------- 16 files changed, 176 insertions(+), 91 deletions(-) diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 18a06d83..c7912f16 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -13,7 +13,7 @@ - `-i/--input` and `-f/--input-file` take JSON, and flags win over it. `--json` prints the result document. - The output shows id, issuer, program, currency, status (with the issuer's raw status) and the available actions. - Exit codes: - - A refusal, or a definitive `failed`, exits 1 with an `api` error document carrying the `code` and the whole result as `body`. + - A refusal exits 1 (a definitive issuer failure is one: `card_issue_refused`, or `card_issue_request_failed` with `failure_code` on a later call with the same key), with an `api` error document carrying the `code` and the whole result as `body`. - `pending_human`, `processing` and `uncertain` exit 0. They say what happens next. `uncertain` says the card may exist and that it reconciles on the SAME `--idempotency-key`, never a new one. - Vocabularies (actions, currency, provider, issuer) come from the published `codespar_card` definition, not a copy. - Depends on `@codespar/sdk ^0.17.0`. diff --git a/packages/cli/src/__tests__/card-command.test.ts b/packages/cli/src/__tests__/card-command.test.ts index b611195e..95648b56 100644 --- a/packages/cli/src/__tests__/card-command.test.ts +++ b/packages/cli/src/__tests__/card-command.test.ts @@ -159,14 +159,18 @@ describe("codespar card", () => { it.each(["uncertain", "processing"] as const)( "%s: says it resolves on the SAME key and never suggests another one (contract §8.3)", async (state) => { - backend({ success: true, error: null, data: { state, issue_request_id: "cir_9", issuer: "rain", program: "rain_usd" } }); + backend({ + success: true, + error: null, + data: { state, issue_request_id: "cir_9", issuer: "rain", program: "rain_usd", retry_after_seconds: 30, ...(state === "uncertain" ? { issuer_code: "timeout" } : {}) }, + }); const out = captureStdout(); await expect( cardCommand("issue", undefined, { ...AUTH, currency: "USD", mandateId: "m", consumerId: "c", idempotencyKey: "k" }), ).resolves.toBeUndefined(); const text = out.err(); expect(text).toContain("cir_9"); - expect(text).toMatch(/same --idempotency-key/i); + expect(text).toMatch(/same --idempotency-key in 30s/i); expect(text).not.toMatch(/(try again|retry|run it again) with (a )?(new|another|different) key/i); if (state === "uncertain") { expect(text).toMatch(/MAY exist/); @@ -175,12 +179,26 @@ describe("codespar card", () => { }, ); - it("failed is a definitive refusal: HttpError with the issuer's code", async () => { - backend({ success: true, error: null, data: { state: "failed", issue_request_id: "cir_8", issuer: "pomelo", program: "pomelo_brl", code: "issuer_declined" } }); + it("a later call on a failed request is card_issue_request_failed: exit 1 with failure_code", async () => { + backend({ + success: false, + error: "card_issue_request_failed", + data: { + error: { + code: "card_issue_request_failed", + message: "this request failed", + details: { issue_request_id: "cir_8", issuer: "rain", program: "rain_usd", failure_code: "issuer_refused" }, + }, + http_status: 409, + }, + }); captureStdout(); - const err = await cardCommand("issue", undefined, { ...AUTH, currency: "BRL", mandateId: "m", consumerId: "c", idempotencyKey: "k" }).catch((e: unknown) => e); + const err = await cardCommand("issue", undefined, { ...AUTH, currency: "USD", mandateId: "m", consumerId: "c", idempotencyKey: "k" }).catch((e: unknown) => e); expect(err).toBeInstanceOf(HttpError); - expect((err as HttpError).code).toBe("issuer_declined"); + expect((err as HttpError).code).toBe("card_issue_request_failed"); + expect((err as HttpError).status).toBe(409); + expect((err as Error).message).toMatch(/failure_code issuer_refused/); + expect((err as HttpError).body).toMatchObject({ issue_request_id: "cir_8", failure_code: "issuer_refused" }); }); it("issue without --idempotency-key never reaches the network", async () => { diff --git a/packages/cli/src/commands/card.ts b/packages/cli/src/commands/card.ts index 4cc682ba..1898d8fe 100644 --- a/packages/cli/src/commands/card.ts +++ b/packages/cli/src/commands/card.ts @@ -118,6 +118,10 @@ export function validateCardArgs(args: CardArgs): void { } } +function retryAfter(seconds: number | undefined): string { + return typeof seconds === "number" ? ` in ${seconds}s` : ""; +} + function viewPairs(v: CardView): Array<[string, string]> { const pairs: Array<[string, string]> = [ ["Id", v.id], @@ -135,7 +139,7 @@ function viewPairs(v: CardView): Array<[string, string]> { } /** - * Print a result, or throw for a refusal or a definitive `failed`. The + * Print a result, or throw for a refusal (a definitive issuer failure is one). The * non-final issue states (`pending_human`, `processing`, `uncertain`) are * not failures (REST answers 202): they print what happens next and exit 0, * and a script branches on `state` in `--json`. None of them ever suggests a @@ -143,18 +147,15 @@ function viewPairs(v: CardView): Array<[string, string]> { */ export function renderCardResult(action: string, result: CardResult, asJson: boolean): void { if (result.state === "refused") { + // A definitive issuer refusal is a refusal too (card_issue_refused, or + // card_issue_request_failed with failure_code on a later call with the + // same key): a failure for the exit code. + const failure = result.failure_code ? ` [failure_code ${result.failure_code}]` : ""; throw new HttpError( - `card ${action} refused: ${result.code}${result.reason ? ` (${result.reason})` : ""}${result.message ? ` — ${result.message}` : ""}`, + `card ${action} refused: ${result.code}${result.reason ? ` (${result.reason})` : ""}${failure}${result.message ? ` — ${result.message}` : ""}`, { status: result.http_status, code: result.code, body: result }, ); } - if (result.state === "failed") { - // A definitive refusal by the issuer: a failure for the exit code too. - throw new HttpError( - `card issue failed at ${result.issuer}/${result.program}${result.code ? `: ${result.code}` : ""}${result.reason ? ` (${result.reason})` : ""}${result.message ? ` — ${result.message}` : ""}`, - { status: 200, code: result.code ?? "card_issue_failed", body: result }, - ); - } if (asJson) { json(result); return; @@ -167,13 +168,18 @@ export function renderCardResult(action: string, result: CardResult, asJson: boo } if (result.state === "processing") { warn(`card issue processing at ${result.issuer}/${result.program}: the issuer has not answered yet.`); - info(`Request: ${result.issue_request_id}. Run the same command with the same --idempotency-key to read where it stands.`); + info( + `Request: ${result.issue_request_id}. Run the same command with the same --idempotency-key to read where it stands${retryAfter(result.retry_after_seconds)}.`, + ); return; } if (result.state === "uncertain") { - warn(`card issue uncertain at ${result.issuer}/${result.program}: the issuer's answer was lost or ambiguous, and the card MAY exist.`); + warn( + `card issue uncertain at ${result.issuer}/${result.program}: the issuer's answer was lost or ambiguous, and the card MAY exist${result.issuer_code ? ` (issuer code ${result.issuer_code})` : ""}.`, + ); + if (result.note) info(result.note); info( - `Request: ${result.issue_request_id}. It reconciles on the same key: run the same command with the SAME --idempotency-key. Do not use a new key; that would be a second issuance.`, + `Request: ${result.issue_request_id}. It reconciles on the same key: run the same command with the SAME --idempotency-key${retryAfter(result.retry_after_seconds)}. Do not use a new key; that would be a second issuance.`, ); return; } diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 5a869384..5762d176 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -10,8 +10,7 @@ - `"issued"`; - `"pending_human"`: a `pending_action` for `holder`, `company_signatory` or `org_admin`; - `"processing"` and `"uncertain"`: the card MAY exist, so call again with the SAME key, never a new one; - - `"failed"`: a definitive refusal by the issuer; - - `"refused"`: a stable `code`, `reason`, `available_programs`, `available_actions` and `http_status`. The refusal is **returned**, whether it came in the tool envelope or as a non-2xx body. + - `"refused"`: also a definitive issuer failure (`card_issue_refused`; `card_issue_request_failed` with `failure_code` and `issue_request_id` on a later call with the same key). It carries a stable `code`, `reason`, `available_programs`, `available_actions` and `http_status`. The refusal is **returned**, whether it came in the tool envelope or as a non-2xx body. - A result with no `state` is a card view or `{ cards }`. Only a failure with no code throws. - **`cs.cards.readiness()`** reads `GET /v1/cards/readiness`: per program, ready or not and the checklist of what is missing. - `CardContractMigrationError` and `cardMigrationError()`: a call in the old Pomelo shape (`card-*` actions, `cardholder_id`, `program_id`, `control`, `shipping_address`, `metadata`) is refused before anything is sent, with the new fields named. diff --git a/packages/core/README.md b/packages/core/README.md index 65226494..7a2d713b 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -12,7 +12,7 @@ Eight new typed methods on `Session`, grouped by capability: - `session.charge(args)` — INBOUND charges (`codespar_charge`). Buyer pays merchant. Pix BRL via Asaas / MP / iugu / Stone; card USD via Stripe. Distinct from `codespar_pay` (outbound transfers). - `session.ship(args)` — shipping (`codespar_ship`). One typed entry into Melhor Envio's 3 rails (`action: "label" | "quote" | "track"`). -- `session.card(args)` — spend cards (`codespar_card`), one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`): `action: "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"`. `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`; `provider` is optional (the currency picks the program). Narrow the result on `state`: `"issued"` (card view + `selection`), `"pending_human"` (a `pending_action` only a person can take: `holder`, `company_signatory` or `org_admin`), `"processing"` and `"uncertain"` (the card MAY exist: call again with the SAME key, never a new one), `"failed"` (definitive issuer refusal), `"refused"` (a stable `code`, `reason`, `available_programs` / `available_actions`, returned rather than thrown); no `state` is a card view or `{ cards }`. `cs.cards.readiness()` reads `GET /v1/cards/readiness`, per program the checklist of what is missing. `session.issue()` is deprecated: it warns once and calls the same `codespar_card`; a call in the old Pomelo shape throws `CardContractMigrationError` naming the new fields. +- `session.card(args)` — spend cards (`codespar_card`), one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`): `action: "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"`. `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`; `provider` is optional (the currency picks the program). Narrow the result on `state`: `"issued"` (`card` view nested, plus `selection` and the authorization), `"pending_human"` (a `pending_action` only a person can take: `holder`, `company_signatory` or `org_admin`), `"processing"` and `"uncertain"` (the card MAY exist: call again with the SAME key, never a new one), `"refused"` (a definitive issuer failure is one too; a stable `code`, `reason`, `available_programs` / `available_actions`, returned rather than thrown); no `state` is a card view or `{ cards }`. `cs.cards.readiness()` reads `GET /v1/cards/readiness`, per program the checklist of what is missing. `session.issue()` is deprecated: it warns once and calls the same `codespar_card`; a call in the old Pomelo shape throws `CardContractMigrationError` naming the new fields. - `session.shop(args)` — buy-side shopping (`codespar_shop`). Catalog search → async checkout → Pix mint (`action: "search" | "checkout" | "checkout_status"`). Discriminated `ShopArgs`/`ShopResult` give the action-correct result type. Checkout is async: start, then poll `checkout_status` until `ready_for_payment` (carries `pix_copia_e_cola`) or `canceled`. Settle the returned Pix via a separate payment tool — settlement and governance are out of this contract. Full spec: [`docs/codespar-shop-contract.md`](../../docs/codespar-shop-contract.md). **Async settlement** — `codespar_charge` / `codespar_pay` return synchronously, but real settlement lands via webhook: diff --git a/packages/core/src/__tests__/card.test.ts b/packages/core/src/__tests__/card.test.ts index 76061809..83a61434 100644 --- a/packages/core/src/__tests__/card.test.ts +++ b/packages/core/src/__tests__/card.test.ts @@ -263,10 +263,10 @@ describe("session.card facade", () => { ); }); - it.each(["processing", "uncertain", "failed"] as const)( + it.each(["processing", "uncertain"] as const)( "issue: a %s answer is returned as received, never stamped issued (contract §8.3)", async (state) => { - const data = { state, issue_request_id: "cir_3", issuer: "rain", program: "rain_usd" }; + const data = { state, issue_request_id: "cir_3", issuer: "rain", program: "rain_usd", retry_after_seconds: 30 }; const { session } = await sessionAnswering({ kind: "envelope", envelope: { data } }); const r = await session.card(ISSUE_USD); expect(r).toEqual(data); @@ -275,12 +275,33 @@ describe("session.card facade", () => { ); it("an issue answer in an unknown state throws instead of passing as issued", async () => { - for (const data of [{ state: "pending" }, RAIN_VIEW]) { + // `failed` is never an issue state: a definitive failure is a refusal. + for (const data of [{ state: "pending" }, { state: "failed" }, RAIN_VIEW]) { const { session } = await sessionAnswering({ kind: "envelope", envelope: { data } }); await expect(session.card(ISSUE_USD)).rejects.toThrow(/unexpected issue state/); } }); + it("card_issue_request_failed lifts issue_request_id and failure_code from details", async () => { + const { session } = await sessionAnswering({ + kind: "envelope", + envelope: { + success: false, + error: "card_issue_request_failed", + data: { + error: { + code: "card_issue_request_failed", + message: "this request failed", + details: { issue_request_id: "cir_8", issuer: "rain", program: "rain_usd", failure_code: "reconciled_absent" }, + }, + http_status: 409, + }, + }, + }); + const r = await session.card(ISSUE_USD); + expect(r).toMatchObject({ state: "refused", code: "card_issue_request_failed", http_status: 409, issue_request_id: "cir_8", failure_code: "reconciled_absent", issuer: "rain" }); + }); + it("card_oauth_not_bound comes back as a refusal like any coded one", async () => { const { session } = await sessionAnswering({ kind: "envelope", diff --git a/packages/core/src/card.ts b/packages/core/src/card.ts index aee69cdc..4538c661 100644 --- a/packages/core/src/card.ts +++ b/packages/core/src/card.ts @@ -5,7 +5,7 @@ * transport carried a refusal: * - success, action=issue, a non-final `state` -> as received: * `pending_human` (a person must act), `processing`, `uncertain` - * (both resolved on the SAME idempotency_key), `failed` (definitive) + * (both resolved on the SAME idempotency_key); a definitive failure is a refusal * - success, action=issue, `state: "issued"` -> CardIssued (the view nested in `card`) * - success, action=issue, anything else -> throws: an issue answer always says its state * - success, any other action -> CardView / CardList as received @@ -91,12 +91,16 @@ export function cardRefusalFrom(result: ToolResult): CardRefusal | null { if (typeof program === "string") refusal.program = program as CardRefusal["program"]; const action = pick("action"); if (typeof action === "string") refusal.action = action as CardRefusal["action"]; + const requestId = pick("issue_request_id"); + if (typeof requestId === "string") refusal.issue_request_id = requestId; + const failure = pick("failure_code"); + if (typeof failure === "string") refusal.failure_code = failure; const actions = pick("available_actions"); if (Array.isArray(actions)) refusal.available_actions = actions as CardRefusal["available_actions"]; return refusal; } -const NON_FINAL_ISSUE_STATES: ReadonlySet = new Set(["pending_human", "processing", "uncertain", "failed"]); +const NON_FINAL_ISSUE_STATES: ReadonlySet = new Set(["pending_human", "processing", "uncertain"]); /** Turn a codespar_card envelope into the typed result, or throw on a failure with no code. */ export function cardResultFrom(args: CardArgs, result: ToolResult): CardResult { diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 4d120637..0e77ba0b 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -400,7 +400,7 @@ export async function createSession( * wire as `execute("codespar_card", {...})`; a refusal with a stable code * is RETURNED as `CardRefusal` (`state: "refused"`); a non-final issue * as `pending_human` / `processing` / `uncertain` (resolve on the SAME - * idempotency_key) or `failed`. Only a failure with no code throws. + * idempotency_key). Only a failure with no code throws. */ async card(args: CardArgs, opts?: CallOptions): Promise { const migration = cardMigrationError(args); diff --git a/packages/python/README.md b/packages/python/README.md index 83c226cd..2aee1b06 100644 --- a/packages/python/README.md +++ b/packages/python/README.md @@ -164,8 +164,7 @@ the same request and never issues a second card. ```python from codespar import ( - CardArgs, CardFailed, CardIssued, CardPendingHuman, CardProcessing, - CardRefusal, CardUncertain, + CardArgs, CardIssued, CardPendingHuman, CardProcessing, CardRefusal, CardUncertain, ) result = session.card( @@ -178,18 +177,18 @@ result = session.card( ) ) if isinstance(result, CardIssued): - print(result.id, result.issuer, result.program, result.available_actions) + print(result.card.id, result.issuer, result.program, result.card.available_actions) elif isinstance(result, CardPendingHuman): # A step only a person can take: hand them the link, never act for them. print(result.pending_action.kind, result.pending_action.actor, result.pending_action.url) elif isinstance(result, (CardProcessing, CardUncertain)): # Not a failure. Uncertain means the card MAY exist at the issuer: # call again with the SAME idempotency_key, never a new one. - print(result.state, result.issue_request_id) -elif isinstance(result, CardFailed): - print("issuer refused:", result.code, result.reason) + print(result.state, result.issue_request_id, result.retry_after_seconds) elif isinstance(result, CardRefusal): - print(result.code, result.reason, result.available_programs) + # A definitive issuer failure is a refusal too (card_issue_refused, or + # card_issue_request_failed with failure_code on a later call). + print(result.code, result.reason, result.failure_code, result.available_programs) session.card(CardArgs(action="get", card_id="icrd_...")) session.card(CardArgs(action="list", issuer="rain")) diff --git a/packages/python/src/codespar/__init__.py b/packages/python/src/codespar/__init__.py index be9d1d57..4be4fee9 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -104,7 +104,6 @@ CardControlAction, CardControlReason, CardCurrency, - CardFailed, CardFunding, CardIssued, CardIssuer, @@ -245,7 +244,6 @@ "CardControlAction", "CardControlReason", "CardCurrency", - "CardFailed", "CardFunding", "CardIssued", "CardIssuer", diff --git a/packages/python/src/codespar/_async_session.py b/packages/python/src/codespar/_async_session.py index 418fbf44..115aea10 100644 --- a/packages/python/src/codespar/_async_session.py +++ b/packages/python/src/codespar/_async_session.py @@ -25,7 +25,6 @@ AuthConfig, AuthResult, CardArgs, - CardFailed, CardFunding, CardIssued, CardList, @@ -306,17 +305,21 @@ def _parse_card_result(raw: dict[str, Any], action: str) -> CardResult: url=pa.get("url"), ), ) + def opt_str(key: str) -> str | None: + v = raw.get(key) + return v if isinstance(v, str) else None + + retry = raw.get("retry_after_seconds") + retry_after = retry if isinstance(retry, int) else None if state == "processing": - return CardProcessing(**ref) + return CardProcessing(**ref, retry_after_seconds=retry_after) if state == "uncertain": - message = raw.get("message") - return CardUncertain(**ref, message=message if isinstance(message, str) else None) - if state == "failed": - def opt(key: str) -> str | None: - v = raw.get(key) - return v if isinstance(v, str) else None - - return CardFailed(**ref, code=opt("code"), reason=opt("reason"), message=opt("message")) + return CardUncertain( + **ref, + retry_after_seconds=retry_after, + note=opt_str("note"), + issuer_code=opt_str("issuer_code"), + ) if state == "issued": card = raw.get("card") auth_id = raw.get("authorization_id") @@ -427,6 +430,8 @@ def pick_str(key: str) -> str | None: program=pick_str("program"), action=pick_str("action"), available_actions=_str_list(actions) if isinstance(actions, list) else None, + issue_request_id=pick_str("issue_request_id"), + failure_code=pick_str("failure_code"), raw=body, ) @@ -890,8 +895,9 @@ async def card(self, args: CardArgs, *, timeout: float | None = None) -> CardRes can take; retry with the same ``idempotency_key`` once done) | ``CardProcessing`` / ``CardUncertain`` (both resolved on the SAME ``idempotency_key``, never a new one: the card may already exist) | - ``CardFailed`` (definitive) | ``CardView`` | ``CardList`` | - ``CardRefusal``. A refusal with a + ``CardView`` | ``CardList`` | ``CardRefusal`` (a definitive issuer + failure is a refusal: ``card_issue_refused``, or + ``card_issue_request_failed`` with ``failure_code``). A refusal with a stable code is RETURNED, whether it came inside the tool envelope or as a non-2xx answer; only a failure with no code raises ``ApiError``. ``idempotency_key`` is required on ``action="issue"`` diff --git a/packages/python/src/codespar/types.py b/packages/python/src/codespar/types.py index 880c1d42..a440cd36 100644 --- a/packages/python/src/codespar/types.py +++ b/packages/python/src/codespar/types.py @@ -743,6 +743,8 @@ class CardProcessing: issuer: str = "" program: str = "" selection: CardSelection | None = None + #: When to read it again, with the SAME key. + retry_after_seconds: int | None = None state: Literal["processing"] = "processing" @@ -757,25 +759,14 @@ class CardUncertain: issue_request_id: str = "" issuer: str = "" program: str = "" - message: str | None = None selection: CardSelection | None = None + retry_after_seconds: int | None = None + note: str | None = None + #: The issuer's raw code, when it sent one. + issuer_code: str | None = None state: Literal["uncertain"] = "uncertain" -@dataclass(slots=True) -class CardFailed: - """``action=issue``: a definitive refusal by the issuer.""" - - issue_request_id: str = "" - issuer: str = "" - program: str = "" - code: str | None = None - reason: str | None = None - message: str | None = None - selection: CardSelection | None = None - state: Literal["failed"] = "failed" - - @dataclass(slots=True) class CardList: """``action=list``.""" @@ -811,6 +802,10 @@ class CardRefusal: program: str | None = None action: str | None = None available_actions: list[str] | None = None + #: On ``card_issue_request_failed``: the failed request and why + #: (issuer_refused | issuer_revoked | reconciled_absent | a Pomelo code). + issue_request_id: str | None = None + failure_code: str | None = None raw: Any = None state: Literal["refused"] = "refused" @@ -820,7 +815,6 @@ class CardRefusal: | CardPendingHuman | CardProcessing | CardUncertain - | CardFailed | CardRefusal | CardView | CardList diff --git a/packages/python/tests/test_card.py b/packages/python/tests/test_card.py index 23999392..5a3fba21 100644 --- a/packages/python/tests/test_card.py +++ b/packages/python/tests/test_card.py @@ -20,7 +20,6 @@ AsyncCodeSpar, CardArgs, CardContractMigrationError, - CardFailed, CardIssued, CardList, CardPendingHuman, @@ -339,7 +338,8 @@ async def test_failure_without_code_raises(httpx_mock: HTTPXMock) -> None: @pytest.mark.asyncio async def test_unknown_issue_state_raises(httpx_mock: HTTPXMock) -> None: _mock_session(httpx_mock) - httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope({"state": "pending"})) + # ``failed`` is never an issue state: a definitive failure is a refusal. + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope({"state": "failed"})) async with AsyncCodeSpar(api_key="csk_test_x") as cs: session = await cs.create("consumer_123", servers=[]) with pytest.raises(ApiError, match="unexpected issue state"): @@ -367,7 +367,7 @@ def test_sync_card_is_the_same_call(httpx_mock: HTTPXMock) -> None: @pytest.mark.asyncio @pytest.mark.parametrize( ("state", "cls"), - [("processing", CardProcessing), ("uncertain", CardUncertain), ("failed", CardFailed)], + [("processing", CardProcessing), ("uncertain", CardUncertain)], ) async def test_non_final_issue_states_are_distinct( httpx_mock: HTTPXMock, state: str, cls: type @@ -382,7 +382,8 @@ async def test_non_final_issue_states_are_distinct( "issue_request_id": "cir_3", "issuer": "rain", "program": "rain_usd", - "code": "issuer_declined", + "retry_after_seconds": 30, + "issuer_code": "timeout", } ), ) @@ -392,8 +393,45 @@ async def test_non_final_issue_states_are_distinct( assert type(result) is cls assert result.state == state assert result.issue_request_id == "cir_3" - if isinstance(result, CardFailed): - assert result.code == "issuer_declined" + assert result.retry_after_seconds == 30 + if isinstance(result, CardUncertain): + assert result.issuer_code == "timeout" + + +@pytest.mark.asyncio +async def test_failed_request_is_a_refusal_with_failure_code(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, + method="POST", + json=_envelope( + { + "error": { + "code": "card_issue_request_failed", + "message": "this request failed", + "details": { + "issue_request_id": "cir_8", + "issuer": "rain", + "program": "rain_usd", + "failure_code": "issuer_refused", + }, + }, + "http_status": 409, + }, + success=False, + error="card_issue_request_failed", + ), + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card(ISSUE_USD) + assert isinstance(result, CardRefusal) + assert (result.code, result.http_status, result.issue_request_id, result.failure_code) == ( + "card_issue_request_failed", + 409, + "cir_8", + "issuer_refused", + ) @pytest.mark.asyncio diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index a243d46b..f5345683 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -6,11 +6,11 @@ - **`codespar_card`** (`CARD_DEFINITION` / `CARD_INPUT`) in `SHARED_META_TOOL_DEFINITIONS`: one card contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`). - Actions: `issue | get | list | freeze | unfreeze | cancel`. - - Properties: `currency` (BRL | USD), `provider` (pomelo | rain), `mandate_id`, `consumer_id`, `idempotency_key`, `card_id`, `issuer` (pomelo | rain), `reason`. + - Properties: `currency` (BRL | USD), `provider` (pomelo | rain), `mandate_id`, `consumer_id`, `idempotency_key`, `card_id`, `holder` (Pomelo cardholder identity, pomelo_brl only), `issuer` (pomelo | rain), `reason` (client_request | lost | stolen | broken | upgrade). - `required` is `["action"]`. The server enforces `idempotency_key`, currency, mandate and holder on `issue`. - `Session.card(args: CardArgs): Promise`. - `CardArgs` is `CardIssueArgs | CardGetArgs | CardListArgs | CardControlArgs`. - - `CardResult` narrows on `state`: `issued`, `pending_human`, `processing`, `uncertain`, `failed` or `refused`. A result with no `state` is a card view or a list. + - `CardResult` narrows on `state`: `issued` (the card view nested in `card`, plus `authorization_id` / `authorization_active`), `pending_human`, `processing` / `uncertain` (`retry_after_seconds`; `note` and `issuer_code` on uncertain) or `refused`. A definitive issuer failure is a refusal, never a state. A result with no `state` is a card view or a list. - Pending actors are `holder`, `company_signatory` and `org_admin`. - Refusal codes include `card_oauth_not_bound` and `card_contract_migration_required`. - `CardReadiness` / `CardProgramReadiness` / `CardRequirement`, for `GET /v1/cards/readiness`. diff --git a/packages/types/src/meta-tool-definitions.ts b/packages/types/src/meta-tool-definitions.ts index 90f5ca7f..91ff258c 100644 --- a/packages/types/src/meta-tool-definitions.ts +++ b/packages/types/src/meta-tool-definitions.ts @@ -622,7 +622,7 @@ export const LEDGER_DEFINITION: SharedMetaToolDefinition = { export const CARD_DEFINITION: SharedMetaToolDefinition = { name: "codespar_card", description: - "Issue, read, and control payment cards for AI agents or end-users, one contract across issuers: BRL cards on the pomelo_brl program (Pomelo), USD cards on the rain_usd program (Rain). action=issue issues a card for a holder (consumer_id) under a mandate (mandate_id) in a currency (currency); provider is optional, and when omitted the currency picks the program. idempotency_key is required on issue. The answer always names issuer, program and selection. A requirement only a person can satisfy (issuer KYC, terms, the authorization for automated issuance, binding the key to the mandate) answers state=pending_human with a pending_action { id, kind, actor, url } to hand to that person (actor holder, company_signatory or org_admin), never something to accept on their behalf; retry with the same idempotency_key once it is done. state=processing means the issuer has not answered yet, and state=uncertain means the card MAY exist at the issuer: both are resolved on the SAME idempotency_key, never by a new key, which would be a second card. state=failed is a definitive refusal by the issuer. action=get reads one card by card_id; action=list lists cards (filters issuer, mandate_id, consumer_id); action=freeze / unfreeze / cancel control a card, and each card's available_actions says which of them its program and state allow (rain cards allow none here). This is the agent-spend-card primitive: it creates SPEND INSTRUMENTS, distinct from codespar_pay/charge which move money.", + "Issue, read, and control payment cards for AI agents or end-users, one contract across issuers: BRL cards on the pomelo_brl program (Pomelo), USD cards on the rain_usd program (Rain). action=issue issues a card for a holder (consumer_id) under a mandate (mandate_id) in a currency (currency); provider is optional, and when omitted the currency picks the program. idempotency_key is required on issue. The answer always names issuer, program and selection. A requirement only a person can satisfy (issuer KYC, terms, the authorization for automated issuance, binding the key to the mandate) answers state=pending_human with a pending_action { id, kind, actor, url } to hand to that person (actor holder, company_signatory or org_admin), never something to accept on their behalf; retry with the same idempotency_key once it is done. state=processing means the issuer has not answered yet, and state=uncertain means the card MAY exist at the issuer: both are resolved on the SAME idempotency_key, never by a new key, which would be a second card. A definitive refusal by the issuer is an error (card_issue_refused, or card_issue_request_failed with failure_code on a later call with the same key), not a state. action=get reads one card by card_id; action=list lists cards (filters issuer, mandate_id, consumer_id); action=freeze / unfreeze / cancel control a card, and each card's available_actions says which of them its program and state allow (rain cards allow none here). This is the agent-spend-card primitive: it creates SPEND INSTRUMENTS, distinct from codespar_pay/charge which move money.", input_schema: CARD_INPUT, contract: contractOf(CARD_INPUT), }; diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index c08a2577..974c8234 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -983,6 +983,8 @@ export interface CardPendingHuman extends CardIssueRequestRef { /** action=issue, the issuer was called and has not answered yet. Read it again with the SAME key. */ export interface CardProcessing extends CardIssueRequestRef { state: "processing"; + /** When to read it again, with the SAME key. */ + retry_after_seconds?: number; } /** @@ -993,15 +995,10 @@ export interface CardProcessing extends CardIssueRequestRef { */ export interface CardUncertain extends CardIssueRequestRef { state: "uncertain"; - message?: string | null; -} - -/** action=issue, a definitive refusal by the issuer. */ -export interface CardFailed extends CardIssueRequestRef { - state: "failed"; - code?: string; - reason?: string; - message?: string | null; + retry_after_seconds?: number; + note?: string; + /** The issuer's raw code, when it sent one. */ + issuer_code?: string; } /** action=list. */ @@ -1026,6 +1023,9 @@ export type CardRefusalCode = | "card_terms_policy_missing" | "card_oauth_not_bound" | "card_contract_migration_required" + | "card_holder_not_eligible" + | "card_issue_refused" + | "card_issue_request_failed" | "idempotency_key_conflict" | (string & {}); @@ -1056,21 +1056,23 @@ export interface CardRefusal { program?: CardProgram; action?: CardAction; available_actions?: CardControlAction[]; + /** On `card_issue_request_failed`: the request that failed, and why (issuer_refused | issuer_revoked | reconciled_absent | a Pomelo code). */ + issue_request_id?: string; + failure_code?: string; /** The refusal body as received. */ raw: unknown; } -export type CardIssueResult = - | CardIssued - | CardPendingHuman - | CardProcessing - | CardUncertain - | CardFailed - | CardRefusal; +/** + * A definitive failure is never an issue `state`: it is a refusal + * (`card_issue_refused`, a Pomelo code, or `card_issue_request_failed` on a + * later call with the same key, with `failure_code`). + */ +export type CardIssueResult = CardIssued | CardPendingHuman | CardProcessing | CardUncertain | CardRefusal; /** * Narrow on `state`: "issued" | "pending_human" | "processing" | - * "uncertain" | "failed" | "refused"; no `state` is a card view (get, + * "uncertain" | "refused"; no `state` is a card view (get, * freeze, unfreeze, cancel) or a list (`"cards" in result`). */ export type CardResult = CardIssueResult | CardView | CardList; From 929e8d57b650894c4ca75657fd9f748fa5a8f12b Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 02:04:23 -0300 Subject: [PATCH 04/12] fix(cli): processing names the retry time next to the same key, never a new one Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/commands/card.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/src/commands/card.ts b/packages/cli/src/commands/card.ts index 1898d8fe..7988d53e 100644 --- a/packages/cli/src/commands/card.ts +++ b/packages/cli/src/commands/card.ts @@ -169,7 +169,7 @@ export function renderCardResult(action: string, result: CardResult, asJson: boo if (result.state === "processing") { warn(`card issue processing at ${result.issuer}/${result.program}: the issuer has not answered yet.`); info( - `Request: ${result.issue_request_id}. Run the same command with the same --idempotency-key to read where it stands${retryAfter(result.retry_after_seconds)}.`, + `Request: ${result.issue_request_id}. Run the same command with the same --idempotency-key${retryAfter(result.retry_after_seconds)} to read where it stands; never a new key.`, ); return; } From b76b3b89215775f3af65b4b0a14322d733e0e4b6 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 13:44:23 -0300 Subject: [PATCH 05/12] feat!: codespar_card without alias; issue() and codespar issue removed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decision of 18/11 (cards contract §10.1): a coordinated breaking change. Removed: ISSUE_DEFINITION, IssueArgs/IssueResult, Session.issue (types, SDK, fake session), Python issue()/IssueArgs/IssueResult/IssueAction, CLI `codespar issue`, the deprecation warnings and CardContractMigrationError / card_contract_migration_required. Changelogs carry a Breaking section with the migration table. Co-Authored-By: Claude Opus 5.5 --- .../autogen/src/__tests__/autogen.test.ts | 1 - packages/camel/src/__tests__/camel.test.ts | 1 - packages/cli/CHANGELOG.md | 30 +++++----- packages/cli/README.md | 1 - .../cli/src/__tests__/card-command.test.ts | 25 +------- packages/cli/src/__tests__/meta-tools.test.ts | 6 -- packages/cli/src/commands/card.ts | 32 +--------- packages/cli/src/index.ts | 13 +---- packages/core/CHANGELOG.md | 26 +++++---- packages/core/README.md | 2 +- packages/core/src/__tests__/card.test.ts | 53 ++--------------- packages/core/src/card.ts | 58 ------------------- packages/core/src/index.ts | 1 - packages/core/src/session.ts | 17 +----- packages/core/src/testing/index.ts | 6 +- packages/crewai/src/__tests__/crewai.test.ts | 1 - .../src/__tests__/google-genai.test.ts | 1 - packages/hermes/src/__tests__/hermes.test.ts | 1 - .../langchain/src/__tests__/langchain.test.ts | 1 - packages/letta/src/__tests__/letta.test.ts | 1 - .../src/__tests__/llama-index.test.ts | 1 - packages/mastra/src/__tests__/mastra.test.ts | 1 - packages/mcp/CHANGELOG.md | 6 +- packages/mcp/src/__tests__/mcp.test.ts | 1 - packages/openai/src/__tests__/openai.test.ts | 1 - packages/python/CHANGELOG.md | 30 +++++----- packages/python/README.md | 5 +- packages/python/src/codespar/__init__.py | 8 --- .../python/src/codespar/_async_session.py | 58 +------------------ packages/python/src/codespar/_sync_client.py | 16 ----- packages/python/src/codespar/errors.py | 14 ----- packages/python/src/codespar/types.py | 28 --------- packages/python/tests/test_card.py | 47 ++------------- packages/types/CHANGELOG.md | 38 +++++++----- .../types/src/meta-tool-definitions.test.ts | 16 +---- packages/types/src/meta-tool-definitions.ts | 14 ----- packages/types/src/types.ts | 31 ---------- 37 files changed, 96 insertions(+), 496 deletions(-) diff --git a/packages/autogen/src/__tests__/autogen.test.ts b/packages/autogen/src/__tests__/autogen.test.ts index 6b0de2f9..a51f78ec 100644 --- a/packages/autogen/src/__tests__/autogen.test.ts +++ b/packages/autogen/src/__tests__/autogen.test.ts @@ -39,7 +39,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/camel/src/__tests__/camel.test.ts b/packages/camel/src/__tests__/camel.test.ts index be80aaf2..63906e51 100644 --- a/packages/camel/src/__tests__/camel.test.ts +++ b/packages/camel/src/__tests__/camel.test.ts @@ -39,7 +39,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index c7912f16..8fb27fcc 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -2,26 +2,28 @@ ## 0.23.0 — unreleased (coordinated codespar_card release) +### Breaking + +- **`codespar card` replaces `codespar issue`, with no alias.** `codespar issue` is removed. + +| Before | Now | +|---|---| +| `codespar issue -i '{"action":"card-virtual",...}'` | `codespar card issue --currency --mandate-id --consumer-id --idempotency-key [--provider] [--holder ]` | +| `codespar issue -i '{"action":"card-get","card_id":"..."}'` | `codespar card get ` | +| `codespar issue -i '{"action":"card-control","control":"freeze",...}'` | `codespar card freeze\|unfreeze\|cancel [--reason]` | +| — | `codespar card list [--issuer] [--mandate-id] [--consumer-id]`, `codespar card readiness` | + ### Added -- **`codespar card issue|get|list|freeze|unfreeze|cancel|readiness`**, through `codespar_card` (BRL on Pomelo, USD on Rain). - - `card issue` takes `--currency`, `--mandate-id`, `--consumer-id` and `--idempotency-key` (required), plus an optional `--provider`. - - `card get `. - - `card list [--issuer] [--mandate-id] [--consumer-id]`. - - `card freeze|unfreeze|cancel [--reason]`. - - `card readiness` reads `GET /v1/cards/readiness`. +- `codespar card issue|get|list|freeze|unfreeze|cancel|readiness`, through `codespar_card` (BRL on Pomelo, USD on Rain). - `-i/--input` and `-f/--input-file` take JSON, and flags win over it. `--json` prints the result document. -- The output shows id, issuer, program, currency, status (with the issuer's raw status) and the available actions. + - Output: id, issuer, program, currency, status (with the issuer's raw status) and the available actions. - Exit codes: - - A refusal exits 1 (a definitive issuer failure is one: `card_issue_refused`, or `card_issue_request_failed` with `failure_code` on a later call with the same key), with an `api` error document carrying the `code` and the whole result as `body`. - - `pending_human`, `processing` and `uncertain` exit 0. They say what happens next. `uncertain` says the card may exist and that it reconciles on the SAME `--idempotency-key`, never a new one. -- Vocabularies (actions, currency, provider, issuer) come from the published `codespar_card` definition, not a copy. + - A refusal exits 1 (a definitive issuer failure is one), with an `api` error document carrying the `code`, `status` and the whole refusal as `body`. + - `pending_human`, `processing` and `uncertain` exit 0. They say to run the same command again with the SAME `--idempotency-key`, never a new key. `uncertain` says the card may exist. +- Vocabularies (actions, currency, provider, issuer, reason) come from the published `codespar_card` definition. - Depends on `@codespar/sdk ^0.17.0`. -### Deprecated - -- **`codespar issue`** is a wrapper over `codespar card `. It takes the JSON it always took, warns, and sends `codespar_card` with the same validations. The old Pomelo shape is refused with `card_contract_migration_required`, and the message names the new fields and commands. - ## 0.22.7 — 2026-11-11 ### Added diff --git a/packages/cli/README.md b/packages/cli/README.md index 84836fb1..46761637 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -95,7 +95,6 @@ codespar init my-agent | `ship` | Generate label / quote rates / track via `codespar_ship` | | `ledger` | Post entries / read balances / create accounts via `codespar_ledger` | | `card issue\|get\|list\|freeze\|unfreeze\|cancel\|readiness` | Spend cards via `codespar_card`: BRL on Pomelo, USD on Rain. `card issue` needs `--currency --mandate-id --consumer-id --idempotency-key`; `processing` / `uncertain` resolve by running it again with the SAME key. `card readiness` lists, per program, what is missing and who must act | -| `issue` | Deprecated: use `card`. Same tool and validations; the old Pomelo JSON shape is refused with `card_contract_migration_required` | | `payment-status ` | Poll async settlement status (add `--stream`) | | `verification-status ` | Poll async KYC status (add `--stream`) | | `wizard [server]` | Connection wizard — required secrets, connect URL, next steps | diff --git a/packages/cli/src/__tests__/card-command.test.ts b/packages/cli/src/__tests__/card-command.test.ts index 95648b56..f683141e 100644 --- a/packages/cli/src/__tests__/card-command.test.ts +++ b/packages/cli/src/__tests__/card-command.test.ts @@ -8,7 +8,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { HttpError } from "../api.js"; import { CliError } from "../config.js"; -import { cardCommand, cardReadinessCommand, issueDeprecatedCommand } from "../commands/card.js"; +import { cardCommand, cardReadinessCommand } from "../commands/card.js"; const AUTH = { apiKey: "csk_test_notreal", baseUrl: "https://api.test.dev" }; @@ -224,26 +224,3 @@ describe("codespar card readiness", () => { expect(JSON.parse(out.text())).toEqual(doc); }); }); - -describe("codespar issue (deprecated, contract §8.4)", () => { - it("warns and sends codespar_card for a new-shaped call", async () => { - const { sent } = backend({ success: true, error: null, data: POMELO_VIEW }); - const out = captureStdout(); - await issueDeprecatedCommand({ ...AUTH, input: '{"action":"get","card_id":"icrd_1"}', json: true }); - expect(out.err()).toMatch(/`codespar issue` is deprecated; use `codespar card/); - expect(sent).toEqual([{ tool: "codespar_card", input: { action: "get", card_id: "icrd_1" } }]); - }); - - it("refuses the old Pomelo shape with card_contract_migration_required, nothing sent", async () => { - const { sent } = backend({ success: true, error: null, data: POMELO_VIEW }); - captureStdout(); - const err = await issueDeprecatedCommand({ - ...AUTH, - input: '{"action":"card-virtual","cardholder_id":"usr_123","program_id":"afg_123"}', - }).catch((e: unknown) => e); - expect(err).toBeInstanceOf(CliError); - expect((err as CliError).code).toBe("card_contract_migration_required"); - expect((err as Error).message).toMatch(/codespar card issue --currency --mandate-id --consumer-id --idempotency-key/); - expect(sent).toHaveLength(0); - }); -}); diff --git a/packages/cli/src/__tests__/meta-tools.test.ts b/packages/cli/src/__tests__/meta-tools.test.ts index 362a905e..acf21442 100644 --- a/packages/cli/src/__tests__/meta-tools.test.ts +++ b/packages/cli/src/__tests__/meta-tools.test.ts @@ -42,12 +42,6 @@ describe("validateCardArgs", () => { ); }); - it("an old Pomelo-shaped call names the new fields (card_contract_migration_required)", () => { - expect(() => - validateCardArgs({ action: "card-virtual", cardholder_id: "u", program_id: "p" } as unknown as CardArgs), - ).toThrow(/card_contract_migration_required.*currency \(BRL \| USD\), mandate_id, consumer_id and idempotency_key/); - }); - it("issue needs currency, mandate, consumer and the idempotency key", () => { const full = { action: "issue", currency: "BRL", mandate_id: "m", consumer_id: "c", idempotency_key: "k" } as const; expect(() => validateCardArgs(full)).not.toThrow(); diff --git a/packages/cli/src/commands/card.ts b/packages/cli/src/commands/card.ts index 7988d53e..d089e898 100644 --- a/packages/cli/src/commands/card.ts +++ b/packages/cli/src/commands/card.ts @@ -1,4 +1,4 @@ -import { CodeSpar, cardMigrationError } from "@codespar/sdk"; +import { CodeSpar } from "@codespar/sdk"; import type { CardArgs, CardIssued, CardResult, CardView } from "@codespar/sdk"; import { HttpError } from "../api.js"; import { CliError } from "../config.js"; @@ -78,11 +78,6 @@ export async function buildCardArgs( return card; } -/** The SDK's migration sentence, plus the terminal spelling of the same call. */ -function cliMigrationMessage(sdkMessage: string): string { - return `${sdkMessage} In the terminal: \`codespar card issue --currency --mandate-id --consumer-id --idempotency-key [--provider]\`, \`codespar card get \`, \`codespar card freeze|unfreeze|cancel \`.`; -} - function oneOf(field: string, value: unknown, published: readonly string[]): void { if (value === undefined) return; if (typeof value !== "string" || !published.includes(value)) { @@ -92,8 +87,6 @@ function oneOf(field: string, value: unknown, published: readonly string[]): voi /** Refuse locally what the server would refuse anyway. Vocabularies come from the published definition. */ export function validateCardArgs(args: CardArgs): void { - const migration = cardMigrationError(args); - if (migration) throw new CliError(cliMigrationMessage(migration.message), { code: migration.code }); const actions = metaToolActions(TOOL); if (!args.action || !actions.includes(args.action)) { throw new CliError(`card.action must be one of: ${actions.join(", ")}.`); @@ -239,26 +232,3 @@ export async function cardReadinessCommand(opts: { apiKey: string; baseUrl: stri ); } } - -/** - * The deprecated `codespar issue` (contract §8.4): a wrapper over - * `codespar card `. It takes the JSON it always took, warns, and - * refuses the old Pomelo shape with the new fields named. - */ -export async function issueDeprecatedCommand(opts: Omit): Promise { - warn("`codespar issue` is deprecated; use `codespar card issue|get|list|freeze|unfreeze|cancel`. It sends codespar_card with the same validations."); - const raw = await resolveMetaInput(opts, "issue", '{"action":"issue","currency":"BRL","mandate_id":"mnd_...","consumer_id":"cons_...","idempotency_key":"..."}'); - const migration = cardMigrationError(raw as unknown as CardArgs); - if (migration) { - throw new CliError(cliMigrationMessage(migration.message), { code: migration.code }); - } - const action = typeof raw.action === "string" ? raw.action : ""; - if (!metaToolActions(TOOL).includes(action)) { - throw new CliError(`issue: action must be one of: ${metaToolActions(TOOL).join(", ")}.`); - } - const rest: Record = { ...raw }; - delete rest.action; - delete rest.card_id; - const cardId = typeof raw.card_id === "string" ? raw.card_id : undefined; - await cardCommand(action, cardId, { ...opts, input: JSON.stringify(rest), inputFile: undefined }); -} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index abe4de34..219f1394 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -36,7 +36,7 @@ import { paymentStatusCommand } from "./commands/payment-status.js"; import { verificationStatusCommand } from "./commands/verification-status.js"; import { wizardCommand } from "./commands/wizard.js"; import { ledgerCommand } from "./commands/ledger.js"; -import { cardCommand, cardReadinessCommand, issueDeprecatedCommand, type CardFlags } from "./commands/card.js"; +import { cardCommand, cardReadinessCommand, type CardFlags } from "./commands/card.js"; import { listMetaToolsCommand, metaToolCommand, @@ -916,17 +916,6 @@ card await cardReadinessCommand({ ...auth, json: rootJsonFlag() }); }); -program - .command("issue") - .description("DEPRECATED: use `codespar card`. Sends codespar_card with the same validations") - .option("-i, --input ", "codespar_card args as JSON string (the old Pomelo shape is refused)") - .option("-f, --input-file ", "codespar_card args from JSON file") - .option("-u, --user ", "User id for the session (default: cli-user)") - .action(async (opts: { input?: string; inputFile?: string; user?: string }) => { - const auth = await resolveAuth(); - await issueDeprecatedCommand({ ...opts, ...auth, json: rootJsonFlag() }); - }); - for (const [name, what] of [ ["freeze", "Freeze a card (when its available_actions allow it)"], ["unfreeze", "Unfreeze a frozen card (when its available_actions allow it)"], diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 5762d176..74351399 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -2,9 +2,21 @@ ## 0.17.0 — unreleased (coordinated codespar_card release) +### Breaking + +- **`session.card(args)` replaces `session.issue(args)`, with no alias.** It calls `codespar_card`: one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`). `session.issue` is removed. + +| Before | Now | +|---|---| +| `session.issue({ action: "card-virtual", cardholder_id, program_id })` | `session.card({ action: "issue", currency, mandate_id, consumer_id, idempotency_key, provider? })` | +| `session.issue({ action: "card-get", card_id })` | `session.card({ action: "get", card_id })` | +| `session.issue({ action: "card-control", card_id, control: "freeze" })` | `session.card({ action: "freeze", card_id, reason? })` (and `unfreeze`, `cancel`) | +| `IssueArgs` / `IssueResult` | `CardArgs` / `CardResult` | +| `codespar_issue` (meta-tool) | `codespar_card` | + ### Added -- **`session.card(args)`** calls `codespar_card`: one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`). +- `session.card(args)`: - `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`, checked before anything is sent. `provider` is optional, and the currency picks the program when it is omitted. - Results narrow on `state`: - `"issued"`; @@ -12,18 +24,10 @@ - `"processing"` and `"uncertain"`: the card MAY exist, so call again with the SAME key, never a new one; - `"refused"`: also a definitive issuer failure (`card_issue_refused`; `card_issue_request_failed` with `failure_code` and `issue_request_id` on a later call with the same key). It carries a stable `code`, `reason`, `available_programs`, `available_actions` and `http_status`. The refusal is **returned**, whether it came in the tool envelope or as a non-2xx body. - A result with no `state` is a card view or `{ cards }`. Only a failure with no code throws. -- **`cs.cards.readiness()`** reads `GET /v1/cards/readiness`: per program, ready or not and the checklist of what is missing. -- `CardContractMigrationError` and `cardMigrationError()`: a call in the old Pomelo shape (`card-*` actions, `cardholder_id`, `program_id`, `control`, `shipping_address`, `metadata`) is refused before anything is sent, with the new fields named. +- `cs.cards.readiness()` reads `GET /v1/cards/readiness`: per program, ready or not and the checklist of what is missing. +- `spec:refresh --from-file //openapi-candidate.json` generates from an enterprise candidate document. `assert-served` refuses a candidate snapshot, and the publish workflow runs it. - Depends on `@codespar/types ^0.12.0`. The fake session in `@codespar/sdk/testing` implements `card()`. -### Deprecated - -- **`session.issue(args)`** is a wrapper over `session.card(args)`. It sends `codespar_card` with the same validations and warns once per process (`console.warn`). An old-shaped call throws `CardContractMigrationError`; the server answers the same call through its deprecated alias with `card_contract_migration_required`. No path keeps the old Pomelo-only validation. - -### Changed - -- Generated OpenAPI: see the PR body for the candidate enterprise SHA it was generated from. - ## 0.16.30 — 2026-11-15 ### Security diff --git a/packages/core/README.md b/packages/core/README.md index 7a2d713b..7e5dd4ac 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -12,7 +12,7 @@ Eight new typed methods on `Session`, grouped by capability: - `session.charge(args)` — INBOUND charges (`codespar_charge`). Buyer pays merchant. Pix BRL via Asaas / MP / iugu / Stone; card USD via Stripe. Distinct from `codespar_pay` (outbound transfers). - `session.ship(args)` — shipping (`codespar_ship`). One typed entry into Melhor Envio's 3 rails (`action: "label" | "quote" | "track"`). -- `session.card(args)` — spend cards (`codespar_card`), one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`): `action: "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"`. `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`; `provider` is optional (the currency picks the program). Narrow the result on `state`: `"issued"` (`card` view nested, plus `selection` and the authorization), `"pending_human"` (a `pending_action` only a person can take: `holder`, `company_signatory` or `org_admin`), `"processing"` and `"uncertain"` (the card MAY exist: call again with the SAME key, never a new one), `"refused"` (a definitive issuer failure is one too; a stable `code`, `reason`, `available_programs` / `available_actions`, returned rather than thrown); no `state` is a card view or `{ cards }`. `cs.cards.readiness()` reads `GET /v1/cards/readiness`, per program the checklist of what is missing. `session.issue()` is deprecated: it warns once and calls the same `codespar_card`; a call in the old Pomelo shape throws `CardContractMigrationError` naming the new fields. +- `session.card(args)` — spend cards (`codespar_card`), one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`): `action: "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"`. `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`; `provider` is optional (the currency picks the program). Narrow the result on `state`: `"issued"` (`card` view nested, plus `selection` and the authorization), `"pending_human"` (a `pending_action` only a person can take: `holder`, `company_signatory` or `org_admin`), `"processing"` and `"uncertain"` (the card MAY exist: call again with the SAME key, never a new one), `"refused"` (a definitive issuer failure is one too; a stable `code`, `reason`, `available_programs` / `available_actions`, returned rather than thrown); no `state` is a card view or `{ cards }`. `cs.cards.readiness()` reads `GET /v1/cards/readiness`, per program the checklist of what is missing. It replaces `session.issue()`, which is removed (no alias). - `session.shop(args)` — buy-side shopping (`codespar_shop`). Catalog search → async checkout → Pix mint (`action: "search" | "checkout" | "checkout_status"`). Discriminated `ShopArgs`/`ShopResult` give the action-correct result type. Checkout is async: start, then poll `checkout_status` until `ready_for_payment` (carries `pix_copia_e_cola`) or `canceled`. Settle the returned Pix via a separate payment tool — settlement and governance are out of this contract. Full spec: [`docs/codespar-shop-contract.md`](../../docs/codespar-shop-contract.md). **Async settlement** — `codespar_charge` / `codespar_pay` return synchronously, but real settlement lands via webhook: diff --git a/packages/core/src/__tests__/card.test.ts b/packages/core/src/__tests__/card.test.ts index 83a61434..df0e612e 100644 --- a/packages/core/src/__tests__/card.test.ts +++ b/packages/core/src/__tests__/card.test.ts @@ -8,9 +8,8 @@ */ import { describe, it, expect, vi, afterEach } from "vitest"; -import type { CardArgs, CardReadiness, CardView, IssueArgs, Session, ToolResult } from "@codespar/types"; +import type { CardArgs, CardReadiness, CardView, Session, ToolResult } from "@codespar/types"; import { createSession } from "../session.js"; -import { CardContractMigrationError, resetIssueDeprecationWarning } from "../card.js"; import { CodeSpar } from "../index.js"; import { CodesparApiError } from "../errors.js"; @@ -312,53 +311,9 @@ describe("session.card facade", () => { }); }); -describe("session.issue (deprecated, contract §8.4)", () => { - it("warns once and sends codespar_card with the same args", async () => { - resetIssueDeprecationWarning(); - const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); - const { session, calls } = await sessionAnswering({ - kind: "envelope", - envelope: { data: issued(RAIN_VIEW) }, - }); - const r = await session.issue(ISSUE_USD); - await session.issue(ISSUE_USD); - expect(r.state).toBe("issued"); - expect(calls.map((c) => c.tool)).toEqual(["codespar_card", "codespar_card"]); - expect(calls[0]!.input).toEqual(ISSUE_USD); - expect(warn).toHaveBeenCalledTimes(1); - expect(String(warn.mock.calls[0]![0])).toMatch(/session\.issue\(\) is deprecated; use session\.card\(\)/); - warn.mockRestore(); - }); - - it("keeps the same validations: no idempotency_key, nothing sent", async () => { - vi.spyOn(console, "warn").mockImplementation(() => {}); - const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); - await expect(session.issue({ ...ISSUE_USD, idempotency_key: "" })).rejects.toThrow(/idempotency_key is required/); - expect(calls).toHaveLength(0); - }); - - it.each([ - [{ action: "card-virtual", cardholder_id: "usr_1", program_id: "afg_1" }, /action "card-virtual", "cardholder_id", "program_id"/], - [{ action: "card-get", card_id: "icrd_1" }, /card\(\{ action: "get", card_id \}\)/], - [{ action: "card-control", card_id: "icrd_1", control: "freeze" }, /"freeze" \| "unfreeze" \| "cancel"/], - ] as const)("an old Pomelo-shaped call is refused before anything is sent: %j", async (args, message) => { - vi.spyOn(console, "warn").mockImplementation(() => {}); - const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); - const err = await session.issue(args as unknown as IssueArgs).catch((e: unknown) => e); - expect(err).toBeInstanceOf(CardContractMigrationError); - expect((err as CardContractMigrationError).code).toBe("card_contract_migration_required"); - expect((err as Error).message).toMatch(message); - expect((err as Error).message).toMatch(/currency \(BRL \| USD\), mandate_id, consumer_id and idempotency_key/); - expect(calls).toHaveLength(0); - }); - - it("card() refuses old Pomelo fields too: no path keeps the old shape", async () => { - const { session, calls } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); - await expect( - session.card({ ...ISSUE_USD, cardholder_id: "usr_1" } as unknown as CardArgs), - ).rejects.toBeInstanceOf(CardContractMigrationError); - expect(calls).toHaveLength(0); - }); +it("session.issue is gone: no alias, no shim (contract §10.1)", async () => { + const { session } = await sessionAnswering({ kind: "envelope", envelope: { data: RAIN_VIEW } }); + expect("issue" in session).toBe(false); }); describe("cs.cards.readiness", () => { diff --git a/packages/core/src/card.ts b/packages/core/src/card.ts index 4538c661..190e5267 100644 --- a/packages/core/src/card.ts +++ b/packages/core/src/card.ts @@ -27,7 +27,6 @@ import type { CardRefusal, CardResult, CardView, - IssueArgs, ToolResult, } from "@codespar/types"; @@ -129,60 +128,3 @@ export function assertCardArgs(args: CardArgs): void { throw new Error("card: idempotency_key is required on action=issue"); } } - -/* ── The deprecated `issue()` wrapper (contract §8.4) ─────────────── */ - -const LEGACY_ACTIONS: Readonly> = { - "card-virtual": "card({ action: \"issue\", currency, mandate_id, consumer_id, idempotency_key, provider? })", - "card-physical": "card({ action: \"issue\", currency, mandate_id, consumer_id, idempotency_key, provider? })", - "card-get": "card({ action: \"get\", card_id })", - "card-control": "card({ action: \"freeze\" | \"unfreeze\" | \"cancel\", card_id, reason? })", -}; - -const LEGACY_FIELDS = ["cardholder_id", "program_id", "control", "shipping_address", "metadata"] as const; - -/** - * A call in the old Pomelo-only shape, refused before anything is sent. - * `code` matches what the server answers to the same call through the - * deprecated tool alias. - */ -export class CardContractMigrationError extends Error { - readonly code = "card_contract_migration_required" as const; - constructor( - message: string, - readonly legacyFields: readonly string[], - ) { - super(message); - Object.setPrototypeOf(this, CardContractMigrationError.prototype); - this.name = "CardContractMigrationError"; - } -} - -/** The old-shaped call's migration error, or null for a `CardArgs` call. */ -export function cardMigrationError(args: CardArgs | IssueArgs): CardContractMigrationError | null { - const a = args as unknown as Record; - const action = typeof a.action === "string" ? a.action : ""; - const legacyFields = LEGACY_FIELDS.filter((f) => a[f] !== undefined); - const instead = LEGACY_ACTIONS[action]; - if (!instead && legacyFields.length === 0) return null; - const what = [instead ? `action "${action}"` : null, ...legacyFields.map((f) => `"${f}"`)].filter(Boolean).join(", "); - return new CardContractMigrationError( - `card_contract_migration_required: ${what} belong${legacyFields.length + (instead ? 1 : 0) > 1 ? "" : "s"} to the retired Pomelo-only shape. ` + - `Use ${instead ?? "card(args)"}: issue takes currency (BRL | USD), mandate_id, consumer_id and idempotency_key; provider (pomelo | rain) is optional. Nothing was sent.`, - legacyFields, - ); -} - -let issueDeprecationWarned = false; - -/** One warning per process, so a loop of calls does not flood stderr. */ -export function warnIssueDeprecated(): void { - if (issueDeprecationWarned) return; - issueDeprecationWarned = true; - console.warn("[@codespar/sdk] session.issue() is deprecated; use session.card(). It calls codespar_card with the same validations."); -} - -/** Test seam: re-arm the one-time warning. */ -export function resetIssueDeprecationWarning(): void { - issueDeprecationWarned = false; -} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e972d8b3..b501676a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -69,7 +69,6 @@ export type { PixKeyType, } from "./types.js"; export { PIX_KEY_DELETE_CONSEQUENCE, PixKeyDeleteNotConfirmedError } from "./wallet.js"; -export { CardContractMigrationError, cardMigrationError } from "./card.js"; export type { Wallet, WalletPixKeys } from "./wallet.js"; export type { Cards } from "./cards.js"; export { filenameFromDisposition } from "./documents.js"; diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 0e77ba0b..ae15ab33 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -2,7 +2,7 @@ * Session implementation for the CodeSpar managed runtime. */ -import { assertCardArgs, cardMigrationError, cardResultFrom, warnIssueDeprecated } from "./card.js"; +import { assertCardArgs, cardResultFrom } from "./card.js"; import { CodesparApiError, networkErrorToApiError, throwFromInstrumentsResponse, throwFromResponse, TimeoutError } from "./errors.js"; import type { SessionConfig, Tool, CallOptions } from "./types.js"; import { fetchWithTimeout, validateTimeout } from "./internal/fetch.js"; @@ -34,7 +34,6 @@ import type { LedgerResult, CardArgs, CardResult, - IssueArgs, ShopArgs, ShopResult, AgentInstrument, @@ -403,8 +402,6 @@ export async function createSession( * idempotency_key). Only a failure with no code throws. */ async card(args: CardArgs, opts?: CallOptions): Promise { - const migration = cardMigrationError(args); - if (migration) throw migration; assertCardArgs(args); const result = await session.execute( "codespar_card", @@ -414,18 +411,6 @@ export async function createSession( return cardResultFrom(args, result); }, - /** - * @deprecated Use `card()`. Same tool and validations, plus a one-time - * warning; an old Pomelo-shaped call throws `CardContractMigrationError` - * before anything is sent. - */ - async issue(args: CardArgs | IssueArgs, opts?: CallOptions): Promise { - warnIssueDeprecated(); - const migration = cardMigrationError(args); - if (migration) throw migration; - return session.card(args as CardArgs, opts); - }, - /** * codespar_shop wrapper. Catalog search → async checkout → Pix mint. * Same wire as `execute("codespar_shop", {...})` but returns a typed diff --git a/packages/core/src/testing/index.ts b/packages/core/src/testing/index.ts index f8a70682..e2df6e75 100644 --- a/packages/core/src/testing/index.ts +++ b/packages/core/src/testing/index.ts @@ -1,7 +1,7 @@ // fakeSession v1 covers execute()-driven flows. send(), sendStream(), // and channel mocking land when Layer 3 demos demand them. -import type { CardArgs, Session, ToolResult } from "@codespar/types"; +import type { Session, ToolResult } from "@codespar/types"; export type { ToolResult }; @@ -134,10 +134,6 @@ export function fakeSession( return { ...view, id: args.card_id }; }, - async issue(args) { - return session.card(args as CardArgs); - }, - async shop(args) { if (args.action === "search") { return { rail: "fake", products: [] }; diff --git a/packages/crewai/src/__tests__/crewai.test.ts b/packages/crewai/src/__tests__/crewai.test.ts index 5d8a976b..d843b336 100644 --- a/packages/crewai/src/__tests__/crewai.test.ts +++ b/packages/crewai/src/__tests__/crewai.test.ts @@ -39,7 +39,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/google-genai/src/__tests__/google-genai.test.ts b/packages/google-genai/src/__tests__/google-genai.test.ts index 4211983f..77683c61 100644 --- a/packages/google-genai/src/__tests__/google-genai.test.ts +++ b/packages/google-genai/src/__tests__/google-genai.test.ts @@ -43,7 +43,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/hermes/src/__tests__/hermes.test.ts b/packages/hermes/src/__tests__/hermes.test.ts index 74464ae9..53bacb19 100644 --- a/packages/hermes/src/__tests__/hermes.test.ts +++ b/packages/hermes/src/__tests__/hermes.test.ts @@ -39,7 +39,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/langchain/src/__tests__/langchain.test.ts b/packages/langchain/src/__tests__/langchain.test.ts index b7519d37..3ea29a21 100644 --- a/packages/langchain/src/__tests__/langchain.test.ts +++ b/packages/langchain/src/__tests__/langchain.test.ts @@ -43,7 +43,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/letta/src/__tests__/letta.test.ts b/packages/letta/src/__tests__/letta.test.ts index 8ddaa0f7..34ed3e2d 100644 --- a/packages/letta/src/__tests__/letta.test.ts +++ b/packages/letta/src/__tests__/letta.test.ts @@ -39,7 +39,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/llama-index/src/__tests__/llama-index.test.ts b/packages/llama-index/src/__tests__/llama-index.test.ts index dd002e4b..1966f29a 100644 --- a/packages/llama-index/src/__tests__/llama-index.test.ts +++ b/packages/llama-index/src/__tests__/llama-index.test.ts @@ -39,7 +39,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/mastra/src/__tests__/mastra.test.ts b/packages/mastra/src/__tests__/mastra.test.ts index aec7ded4..72145136 100644 --- a/packages/mastra/src/__tests__/mastra.test.ts +++ b/packages/mastra/src/__tests__/mastra.test.ts @@ -39,7 +39,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/mcp/CHANGELOG.md b/packages/mcp/CHANGELOG.md index 689d09b4..1b8bc498 100644 --- a/packages/mcp/CHANGELOG.md +++ b/packages/mcp/CHANGELOG.md @@ -2,9 +2,13 @@ ## 0.6.0 — unreleased (coordinated codespar_card release) +### Breaking + +- Discovery relays `codespar_card` from the hosted catalog. `codespar_issue` is gone from the hosted catalog with no alias; a call to it is an unknown tool. + ### Changed -- Discovery relays `codespar_card` from the hosted catalog. The old card tool stays callable on the server as a deprecated alias of the same path. The README and the package description no longer say Pomelo-only: spend cards are BRL on Pomelo and USD on Rain. +- The README and package description no longer say Pomelo-only: spend cards are BRL on Pomelo and USD on Rain. - Accepts `@codespar/sdk ^0.17.0`. ## 0.5.20 — 2026-10-30 diff --git a/packages/mcp/src/__tests__/mcp.test.ts b/packages/mcp/src/__tests__/mcp.test.ts index babab5bb..3717de4b 100644 --- a/packages/mcp/src/__tests__/mcp.test.ts +++ b/packages/mcp/src/__tests__/mcp.test.ts @@ -42,7 +42,6 @@ function fakeSession(): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/openai/src/__tests__/openai.test.ts b/packages/openai/src/__tests__/openai.test.ts index c04ebd24..e9878b69 100644 --- a/packages/openai/src/__tests__/openai.test.ts +++ b/packages/openai/src/__tests__/openai.test.ts @@ -56,7 +56,6 @@ function fakeSession(tools: Tool[]): Session { async ship() { return {} as any; }, async ledger() { return {} as any; }, async card() { return {} as any; }, - async issue() { return {} as any; }, async shop() { return {} as any; }, async paymentStatus() { return { status: 'pending' } as any; }, async paymentStatusStream() { return {} as any; }, diff --git a/packages/python/CHANGELOG.md b/packages/python/CHANGELOG.md index f39fa6fc..7e3a7cb8 100644 --- a/packages/python/CHANGELOG.md +++ b/packages/python/CHANGELOG.md @@ -4,23 +4,27 @@ In parity with `@codespar/sdk` 0.17.0. +### Breaking + +- **`session.card(CardArgs(...))` replaces `session.issue(...)`, async and sync, with no alias.** `issue()`, `IssueArgs`, `IssueResult` and `IssueAction` are removed. + +| Before | Now | +|---|---| +| `session.issue(IssueArgs(action="card-virtual", cardholder_id=..., program_id=...))` | `session.card(CardArgs(action="issue", currency=..., mandate_id=..., consumer_id=..., idempotency_key=..., provider=None))` | +| `session.issue(IssueArgs(action="card-get", card_id=...))` | `session.card(CardArgs(action="get", card_id=...))` | +| `session.issue(IssueArgs(action="card-control", card_id=..., control="freeze"))` | `session.card(CardArgs(action="freeze", card_id=..., reason=None))` | + ### Added -- **`session.card(CardArgs(...))`** (async and sync) calls `codespar_card` (BRL on Pomelo, USD on Rain). `idempotency_key` is required on `action="issue"` and is checked before anything is sent. -- It returns one of: +- `session.card(...)` calls `codespar_card` (BRL on Pomelo, USD on Rain). `idempotency_key` is required on `action="issue"` and is checked before anything is sent. +- It returns: - `CardIssued`; - `CardPendingHuman` (`pending_action`); - - `CardProcessing` and `CardUncertain`: same key, never a new one; - - `CardFailed`; - - `CardView`, `CardList`; - - `CardRefusal`. A refusal with a stable code is returned, whether it came in the tool envelope or as a non-2xx answer (`http_status`). Only a failure with no code raises `ApiError`. -- **`cs.cards.readiness()`** reads `GET /v1/cards/readiness`. It returns typed dicts `CardReadiness`, `CardProgramReadiness` and `CardRequirement`. -- `CardContractMigrationError` (`code = "card_contract_migration_required"`, `legacy_fields`). - -### Deprecated - -- **`session.issue(...)`** (async and sync) emits a `DeprecationWarning` and calls `card()` with the same validations. An `IssueArgs` (old Pomelo shape) raises `CardContractMigrationError` before anything is sent. -- `IssueArgs` and `IssueAction` are kept for imports. `IssueResult` is an alias of `CardResult`. + - `CardProcessing` and `CardUncertain` (same key, never a new one); + - `CardView` and `CardList`; + - `CardRefusal`: a refusal with a stable code is returned, whether it came in the tool envelope or as a non-2xx answer (`http_status`), and a definitive issuer failure is one. +- Only a failure with no code raises `ApiError`. +- `cs.cards.readiness()` reads `GET /v1/cards/readiness`. It returns the typed dicts `CardReadiness`, `CardProgramReadiness` and `CardRequirement`. ## 0.16.2 diff --git a/packages/python/README.md b/packages/python/README.md index 2aee1b06..0d6ebd2d 100644 --- a/packages/python/README.md +++ b/packages/python/README.md @@ -199,10 +199,7 @@ cs.cards.readiness() ``` A refusal with a stable code is returned as `CardRefusal`, not raised; only a -failure with no code raises `ApiError`. `session.issue()` is deprecated: it -warns and calls the same `codespar_card` with the same validations, and a call -in the old Pomelo shape (`IssueArgs` with `cardholder_id` / `program_id`) -raises `CardContractMigrationError` naming the new fields. +failure with no code raises `ApiError`. ## Pay documents and batches diff --git a/packages/python/src/codespar/__init__.py b/packages/python/src/codespar/__init__.py index 4be4fee9..7cf7fd99 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -43,7 +43,6 @@ from .errors import ( PIX_KEY_DELETE_CONSEQUENCE, ApiError, - CardContractMigrationError, CodeSparError, ConfigError, NotConnectedError, @@ -138,9 +137,6 @@ DoneEvent, ErrorEvent, HttpMethod, - IssueAction, - IssueArgs, - IssueResult, LedgerAction, LedgerArgs, LedgerLeg, @@ -240,7 +236,6 @@ # Card (codespar_card) "CardAction", "CardArgs", - "CardContractMigrationError", "CardControlAction", "CardControlReason", "CardCurrency", @@ -292,9 +287,6 @@ "DoneEvent", "ErrorEvent", "HttpMethod", - "IssueAction", - "IssueArgs", - "IssueResult", # Ledger (codespar_ledger) "LedgerAction", "LedgerArgs", diff --git a/packages/python/src/codespar/_async_session.py b/packages/python/src/codespar/_async_session.py index 115aea10..38033e96 100644 --- a/packages/python/src/codespar/_async_session.py +++ b/packages/python/src/codespar/_async_session.py @@ -11,7 +11,6 @@ import asyncio import contextlib -import warnings from collections.abc import AsyncIterator, Awaitable, Callable from datetime import datetime from typing import Any @@ -19,7 +18,7 @@ import httpx from ._http import request_json, stream_sse, stream_sse_get -from .errors import ApiError, CardContractMigrationError, ConfigError, TimeoutError +from .errors import ApiError, ConfigError, TimeoutError from .types import ( AssistantTextEvent, AuthConfig, @@ -49,7 +48,6 @@ DiscoverToolMatch, DoneEvent, ErrorEvent, - IssueArgs, LedgerArgs, LedgerResult, PaymentStatusEvent, @@ -340,36 +338,6 @@ def opt_str(key: str) -> str | None: return _parse_card_view(raw) -_LEGACY_ISSUE = ( - 'card(CardArgs(action="issue", currency, mandate_id, consumer_id, ' - "idempotency_key, provider=None))" -) -_LEGACY_INSTEAD = { - "card-virtual": _LEGACY_ISSUE, - "card-physical": _LEGACY_ISSUE, - "card-get": 'card(CardArgs(action="get", card_id))', - "card-control": 'card(CardArgs(action="freeze" | "unfreeze" | "cancel", card_id, reason=None))', -} -_LEGACY_FIELDS = ("cardholder_id", "program_id", "control", "shipping_address", "metadata") - - -def _card_migration_error(args: Any) -> CardContractMigrationError | None: - """The old-shaped call's migration error (TS ``cardMigrationError``), or None.""" - action = getattr(args, "action", "") - instead = _LEGACY_INSTEAD.get(action) - legacy = [f for f in _LEGACY_FIELDS if getattr(args, f, None) is not None] - if instead is None and not legacy: - return None - what = ", ".join(([f'action "{action}"'] if instead else []) + [f'"{f}"' for f in legacy]) - verb = "belong" if len(legacy) + (1 if instead else 0) > 1 else "belongs" - return CardContractMigrationError( - f"card_contract_migration_required: {what} {verb} to the retired Pomelo-only shape. " - f"Use {instead or 'card(CardArgs(...))'}: issue takes currency (BRL | USD), mandate_id, " - "consumer_id and idempotency_key; provider (pomelo | rain) is optional. Nothing was sent.", - legacy, - ) - - def _parse_card_refusal( body: Any, http_status: int, fallback_message: str | None ) -> CardRefusal | None: @@ -903,9 +871,6 @@ async def card(self, args: CardArgs, *, timeout: float | None = None) -> CardRes ``ApiError``. ``idempotency_key`` is required on ``action="issue"`` and is checked before anything is sent. """ - migration = _card_migration_error(args) - if migration is not None: - raise migration if args.action == "issue" and not args.idempotency_key: raise ApiError( "card: idempotency_key is required on action=issue", @@ -962,27 +927,6 @@ async def card(self, args: CardArgs, *, timeout: float | None = None) -> CardRes raise ApiError("card: malformed response", status=0, body=payload) return _parse_card_result(payload, args.action) - async def issue( - self, args: CardArgs | IssueArgs, *, timeout: float | None = None - ) -> CardResult: - """Deprecated: use :meth:`card`. Same tool and validations, plus a warning. - - An ``IssueArgs`` (old Pomelo shape) raises - ``CardContractMigrationError`` before anything is sent. - """ - warnings.warn( - "session.issue() is deprecated; use session.card(). " - "It calls codespar_card with the same validations.", - DeprecationWarning, - stacklevel=2, - ) - migration = _card_migration_error(args) - if migration is not None: - raise migration - if not isinstance(args, CardArgs): - raise CardContractMigrationError("issue() takes CardArgs", []) - return await self.card(args, timeout=timeout) - async def shop(self, args: ShopArgs, *, timeout: float | None = None) -> ShopResult: """ Buy-side shopping: catalog search → async checkout → Pix mint. diff --git a/packages/python/src/codespar/_sync_client.py b/packages/python/src/codespar/_sync_client.py index b8df3d32..e041d453 100644 --- a/packages/python/src/codespar/_sync_client.py +++ b/packages/python/src/codespar/_sync_client.py @@ -15,7 +15,6 @@ import asyncio import threading -import warnings from collections.abc import Coroutine, Iterator from types import TracebackType from typing import Any, TypeVar @@ -38,7 +37,6 @@ ConnectionWizardResult, DiscoverOptions, DiscoverResult, - IssueArgs, LedgerArgs, LedgerResult, PaymentStatusResult, @@ -216,20 +214,6 @@ def card(self, args: CardArgs, *, timeout: float | None = None) -> CardResult: """Sync wrapper around ``AsyncSession.card``. See that for docs.""" return self._runner.run(self._async.card(args, timeout=timeout)) - def issue( - self, args: CardArgs | IssueArgs, *, timeout: float | None = None - ) -> CardResult: - """Deprecated: use :meth:`card`. Sync wrapper around ``AsyncSession.issue``.""" - warnings.warn( - "session.issue() is deprecated; use session.card(). " - "It calls codespar_card with the same validations.", - DeprecationWarning, - stacklevel=2, - ) - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - return self._runner.run(self._async.issue(args, timeout=timeout)) - def shop(self, args: ShopArgs, *, timeout: float | None = None) -> ShopResult: """Sync wrapper around ``AsyncSession.shop``. See that for docs.""" return self._runner.run(self._async.shop(args, timeout=timeout)) diff --git a/packages/python/src/codespar/errors.py b/packages/python/src/codespar/errors.py index 33bd6a46..bbaf55ec 100644 --- a/packages/python/src/codespar/errors.py +++ b/packages/python/src/codespar/errors.py @@ -37,20 +37,6 @@ def __init__( self.code = code -class CardContractMigrationError(CodeSparError): - """A card call in the old Pomelo-only shape, refused before anything is sent. - - ``code`` matches what the server answers to the same call through the - deprecated tool alias. - """ - - code = "card_contract_migration_required" - - def __init__(self, message: str, legacy_fields: list[str]): - super().__init__(message) - self.legacy_fields = legacy_fields - - #: What the person is told before a key is deleted (the TypeScript SDK exports the same). PIX_KEY_DELETE_CONSEQUENCE = "Depois de excluída, esta chave deixa de apontar para esta conta." diff --git a/packages/python/src/codespar/types.py b/packages/python/src/codespar/types.py index a440cd36..9e24b49e 100644 --- a/packages/python/src/codespar/types.py +++ b/packages/python/src/codespar/types.py @@ -821,34 +821,6 @@ class CardRefusal: ) -# ── Deprecated: the Pomelo-only card shape ───────────────────────── - -IssueAction = Literal["card-virtual", "card-physical", "card-control", "card-get"] - - -@dataclass(slots=True) -class IssueArgs: - """Deprecated: the Pomelo-only shape of the deprecated ``issue()`` wrapper. - - Kept so existing imports work. A call in this shape raises - ``CardContractMigrationError`` (``card_contract_migration_required``) - before anything is sent. Use ``CardArgs`` with ``card()``. - """ - - action: IssueAction - cardholder_id: str | None = None - program_id: str | None = None - card_id: str | None = None - control: Literal["freeze", "unfreeze", "cancel"] | None = None - reason: str | None = None - shipping_address: dict[str, Any] | None = None - metadata: dict[str, Any] | None = None - - -#: Deprecated: ``issue()`` now answers what ``card()`` answers. -IssueResult = CardResult - - # ── codespar_shop wire shape ─────────────────────────────────────── ShopAction = Literal["search", "checkout", "checkout_status"] diff --git a/packages/python/tests/test_card.py b/packages/python/tests/test_card.py index 5a3fba21..ee12172d 100644 --- a/packages/python/tests/test_card.py +++ b/packages/python/tests/test_card.py @@ -19,7 +19,6 @@ ApiError, AsyncCodeSpar, CardArgs, - CardContractMigrationError, CardIssued, CardList, CardPendingHuman, @@ -28,7 +27,6 @@ CardUncertain, CardView, CodeSpar, - IssueArgs, ) BASE = "https://api.codespar.dev" @@ -434,46 +432,13 @@ async def test_failed_request_is_a_refusal_with_failure_code(httpx_mock: HTTPXMo ) -@pytest.mark.asyncio -async def test_deprecated_issue_warns_and_sends_codespar_card(httpx_mock: HTTPXMock) -> None: - _mock_session(httpx_mock) - httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope(_issued(RAIN_VIEW))) - async with AsyncCodeSpar(api_key="csk_test_x") as cs: - session = await cs.create("consumer_123", servers=[]) - with pytest.warns(DeprecationWarning, match=r"session\.issue\(\) is deprecated"): - result = await session.issue(ISSUE_USD) - assert isinstance(result, CardIssued) - body = _sent(httpx_mock) - assert body["tool"] == "codespar_card" - assert body["input"]["idempotency_key"] == "idem_1" - - -@pytest.mark.asyncio -async def test_deprecated_issue_refuses_old_shape_before_sending(httpx_mock: HTTPXMock) -> None: - _mock_session(httpx_mock) - async with AsyncCodeSpar(api_key="csk_test_x") as cs: - session = await cs.create("consumer_123", servers=[]) - with ( - pytest.warns(DeprecationWarning), - pytest.raises(CardContractMigrationError) as exc, - ): - await session.issue( - IssueArgs(action="card-virtual", cardholder_id="usr_1", program_id="afg_1") - ) - assert exc.value.code == "card_contract_migration_required" - assert exc.value.legacy_fields == ["cardholder_id", "program_id"] - assert "mandate_id, consumer_id and idempotency_key" in str(exc.value) - assert not any(r.url.path.endswith("/execute") for r in httpx_mock.get_requests()) +def test_issue_method_is_gone() -> None: + """codespar_card without alias (contract §10.1).""" + from codespar import AsyncSession + from codespar._sync_client import Session - -def test_sync_deprecated_issue_warns_once_per_call(httpx_mock: HTTPXMock) -> None: - _mock_session(httpx_mock) - httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope(RAIN_VIEW)) - with CodeSpar(api_key="csk_test_x") as cs: - session = cs.create("consumer_123", servers=[]) - with pytest.warns(DeprecationWarning) as record: - session.issue(CardArgs(action="get", card_id="rcrd_abc")) - assert len([w for w in record if issubclass(w.category, DeprecationWarning)]) == 1 + assert not hasattr(AsyncSession, "issue") + assert not hasattr(Session, "issue") @pytest.mark.asyncio diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index f5345683..e1e97490 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -2,31 +2,37 @@ ## 0.12.0 — unreleased (coordinated codespar_card release) +### Breaking + +- **`codespar_card` replaces `codespar_issue`, with no alias.** + - The old definition (`ISSUE_DEFINITION`) is removed, and `SHARED_META_TOOL_DEFINITIONS` lists `codespar_card` in its place. `SharedMetaToolName` follows. + - `Session.issue()`, `IssueArgs` and `IssueResult` are removed. `Session` implementers must provide `card()`. + +| Before | Now | +|---|---| +| `session.issue({ action: "card-virtual", cardholder_id, program_id })` | `session.card({ action: "issue", currency, mandate_id, consumer_id, idempotency_key, provider? })` | +| `session.issue({ action: "card-get", card_id })` | `session.card({ action: "get", card_id })` | +| `session.issue({ action: "card-control", card_id, control: "freeze" })` | `session.card({ action: "freeze", card_id, reason? })` (and `unfreeze`, `cancel`) | +| `IssueArgs` / `IssueResult` | `CardArgs` / `CardResult` | +| `codespar_issue` (meta-tool) | `codespar_card` | + ### Added -- **`codespar_card`** (`CARD_DEFINITION` / `CARD_INPUT`) in `SHARED_META_TOOL_DEFINITIONS`: one card contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`). +- `CARD_DEFINITION` / `CARD_INPUT`: one card contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`). - Actions: `issue | get | list | freeze | unfreeze | cancel`. - - Properties: `currency` (BRL | USD), `provider` (pomelo | rain), `mandate_id`, `consumer_id`, `idempotency_key`, `card_id`, `holder` (Pomelo cardholder identity, pomelo_brl only), `issuer` (pomelo | rain), `reason` (client_request | lost | stolen | broken | upgrade). + - Properties: `currency` (BRL | USD), `provider` (pomelo | rain), `mandate_id`, `consumer_id`, `idempotency_key`, `holder` (Pomelo cardholder identity, pomelo_brl only), `card_id`, `issuer` (pomelo | rain), `reason` (client_request | lost | stolen | broken | upgrade). - `required` is `["action"]`. The server enforces `idempotency_key`, currency, mandate and holder on `issue`. - `Session.card(args: CardArgs): Promise`. - `CardArgs` is `CardIssueArgs | CardGetArgs | CardListArgs | CardControlArgs`. - - `CardResult` narrows on `state`: `issued` (the card view nested in `card`, plus `authorization_id` / `authorization_active`), `pending_human`, `processing` / `uncertain` (`retry_after_seconds`; `note` and `issuer_code` on uncertain) or `refused`. A definitive issuer failure is a refusal, never a state. A result with no `state` is a card view or a list. - - Pending actors are `holder`, `company_signatory` and `org_admin`. - - Refusal codes include `card_oauth_not_bound` and `card_contract_migration_required`. + - `CardResult` narrows on `state`: + - `issued`: the card view nested in `card`, plus `authorization_id` / `authorization_active`; + - `pending_human`: a `pending_action` for `holder`, `company_signatory` or `org_admin`; + - `processing` / `uncertain`: `retry_after_seconds`, plus `note` and `issuer_code` on uncertain; + - `refused`. + - A definitive issuer failure is a refusal, never a state. A result with no `state` is a card view or a list. - `CardReadiness` / `CardProgramReadiness` / `CardRequirement`, for `GET /v1/cards/readiness`. - The scenario manifest moves to 0.12.0. -### Changed - -- `SHARED_META_TOOL_DEFINITIONS` lists `codespar_card` in place of the old card tool, so an agent is shown one card tool. `SharedMetaToolName` follows. - -### Deprecated - -- **`Session.issue()`** now takes `CardArgs | IssueArgs` and returns `CardResult`. It is a wrapper over `card()` with the same validations. -- **`IssueArgs`** is kept only so imports compile. A call in that shape is refused with `card_contract_migration_required`. -- **`IssueResult`** is an alias of `CardResult`. -- **`ISSUE_DEFINITION`** is the old tool name as an alias with `codespar_card`'s exact input and a DEPRECATED description. It is outside the shared map. - ## 0.11.7 — 2026-10-30 ### Added diff --git a/packages/types/src/meta-tool-definitions.test.ts b/packages/types/src/meta-tool-definitions.test.ts index 1940977e..6cff06e8 100644 --- a/packages/types/src/meta-tool-definitions.test.ts +++ b/packages/types/src/meta-tool-definitions.test.ts @@ -1,6 +1,5 @@ import { describe, it, expect } from "vitest"; import { - ISSUE_DEFINITION, SHARED_META_TOOL_DEFINITIONS, contractOf, type MetaToolInputSchema, @@ -584,18 +583,9 @@ describe("wire-shape arg unions match the published definition vocabularies (ent expect(card.description).toMatch(/SAME idempotency_key, never by a new key/); }); - it("the old card tool is a deprecated alias outside the shared surface (contract §8.4)", () => { - const old = "codespar_issue"; - // An agent is shown one card tool. - expect(Object.keys(SHARED_META_TOOL_DEFINITIONS)).not.toContain(old); - for (const def of ALL) expect(def.name).not.toBe(old); - // The alias takes exactly codespar_card's input: no path keeps the old, - // less restrictive Pomelo arguments. - expect(ISSUE_DEFINITION.name).toBe(old); - expect(ISSUE_DEFINITION.input_schema).toBe(SHARED_META_TOOL_DEFINITIONS.codespar_card.input_schema); - expect(ISSUE_DEFINITION.description).toMatch(/^DEPRECATED alias of codespar_card/); - expect(ISSUE_DEFINITION.description).toMatch(/card_contract_migration_required/); - expect(definitionViolations(ISSUE_DEFINITION).map((v) => v.detail)).toEqual([]); + it("codespar_issue is gone: no alias, no shim (contract §10.1)", () => { + expect(Object.keys(SHARED_META_TOOL_DEFINITIONS)).not.toContain("codespar_issue"); + for (const def of ALL) expect(def.name).not.toBe("codespar_issue"); }); it("ShopArgs.action == codespar_shop action enum", () => { diff --git a/packages/types/src/meta-tool-definitions.ts b/packages/types/src/meta-tool-definitions.ts index 91ff258c..228e3a1c 100644 --- a/packages/types/src/meta-tool-definitions.ts +++ b/packages/types/src/meta-tool-definitions.ts @@ -627,20 +627,6 @@ export const CARD_DEFINITION: SharedMetaToolDefinition = { contract: contractOf(CARD_INPUT), }; -/** - * @deprecated The transition alias of `codespar_card` (contract §8.4): the - * same input, the same server path and the same validations. Published for - * runtimes that still register the old name; it is NOT in - * `SHARED_META_TOOL_DEFINITIONS`, so an agent is shown one card tool. - */ -export const ISSUE_DEFINITION: SharedMetaToolDefinition = { - name: "codespar_issue", - description: - "DEPRECATED alias of codespar_card: same arguments, same server path, same validations and refusals. Call codespar_card instead. A call with the old Pomelo-only arguments is refused with card_contract_migration_required, naming the new fields (currency, mandate_id, consumer_id, idempotency_key).", - input_schema: CARD_INPUT, - contract: contractOf(CARD_INPUT), -}; - /** * The shared agent-facing definitions, keyed by wire tool name — the FULL * meta-tool surface, all fifteen tools. (This used to publish only the three diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index 974c8234..bea62ed9 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -189,14 +189,6 @@ export interface Session extends SessionBase { * money. */ card(args: CardArgs, opts?: CallOptions): Promise; - /** - * @deprecated Use `card()`. A wrapper over `card()`: same tool - * (`codespar_card`), same validations, plus a one-time deprecation - * warning. A call in the old Pomelo shape (`cardholder_id` / - * `program_id`, `card-*` actions) is refused before anything is sent, - * naming the new fields. - */ - issue(args: CardArgs | IssueArgs, opts?: CallOptions): Promise; /** * Buy-side shopping: catalog search → async checkout → Pix mint. * Typed wrapper around `execute("codespar_shop", {...})`. The @@ -1022,7 +1014,6 @@ export type CardRefusalCode = | "card_action_unsupported" | "card_terms_policy_missing" | "card_oauth_not_bound" - | "card_contract_migration_required" | "card_holder_not_eligible" | "card_issue_refused" | "card_issue_request_failed" @@ -1107,28 +1098,6 @@ export interface CardReadiness { programs: CardProgramReadiness[]; } -/* ── Deprecated: the Pomelo-only card shape ──────────────────── */ - -/** - * @deprecated The Pomelo-only shape of the deprecated `issue()` wrapper. - * Kept so existing imports compile; a call in this shape is refused with - * `card_contract_migration_required` before anything is sent. Use - * `CardArgs` with `card()`. - */ -export interface IssueArgs { - action: "card-virtual" | "card-physical" | "card-control" | "card-get"; - cardholder_id?: string; - program_id?: string; - card_id?: string; - control?: "freeze" | "unfreeze" | "cancel"; - reason?: string; - shipping_address?: Record; - metadata?: Record; -} - -/** @deprecated `issue()` now answers what `card()` answers. Use `CardResult`. */ -export type IssueResult = CardResult; - /* ── codespar_shop wire shape ────────────────────────────────── */ /** From b47b7acc5fedb088e542d87a981bf3386300cdce Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 18:28:33 -0300 Subject: [PATCH 06/12] test(cli): card boots with its subcommands; issue is an unknown command Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/__tests__/boots.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/cli/src/__tests__/boots.test.ts b/packages/cli/src/__tests__/boots.test.ts index 046c5a4b..22baf9e6 100644 --- a/packages/cli/src/__tests__/boots.test.ts +++ b/packages/cli/src/__tests__/boots.test.ts @@ -93,6 +93,17 @@ describe("o programa sobe", () => { expect(pay.stdout).toContain("--list-hash"); }, 30_000); + it("`card` sobe com os sete subcomandos, e `issue` é comando desconhecido (codespar_card sem alias)", () => { + const card = roda("card", "--help"); + expect(card.status, `${card.stdout}${card.stderr}`).toBe(0); + for (const sub of ["issue", "get", "list", "freeze", "unfreeze", "cancel", "readiness"]) { + expect(card.stdout).toMatch(new RegExp(`\\b${sub}\\b`)); + } + const issue = roda("issue"); + expect(issue.status, "o programa ainda aceita `codespar issue`").not.toBe(0); + expect(`${issue.stdout}${issue.stderr}`).toMatch(/unknown command 'issue'/); + }, 30_000); + it("CONTROLE: um comando que não existe sai não-zero", () => { const r = roda("comando-que-nao-existe-mesmo"); expect(r.status, "o programa aceitou um comando inventado").not.toBe(0); From 463d437113e434fd3f1ad8db98792d64f3e2a4df Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 23:22:44 -0300 Subject: [PATCH 07/12] chore(sdk): OpenAPI snapshot and generated client from enterprise candidate ffa66ce78 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit spec:refresh --from-file /ffa66ce789ab6284cab9f831ba73025f0a5afeae/openapi-candidate.json (sha256 c93989a6…, 399 operations). The snapshot records source "candidate:ffa66ce789ab…/openapi-candidate.json"; the publish workflow's assert-served step refuses it until publish day refreshes from the served document. Co-Authored-By: Claude Opus 5.5 --- packages/core/openapi-snapshot.json | 11536 ++++++++++------ packages/core/scripts/openapi-spec.d.mts | 8 + .../src/__tests__/openapi-snapshot.test.ts | 26 +- packages/core/src/generated/openapi.ts | 3401 +++-- packages/core/src/generated/operations.ts | 23 +- 5 files changed, 9601 insertions(+), 5393 deletions(-) diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index d1b3ac6d..cbe5a833 100644 --- a/packages/core/openapi-snapshot.json +++ b/packages/core/openapi-snapshot.json @@ -1,16 +1,16 @@ { "snapshot": { - "source": "https://api.codespar.dev/openapi.json", - "fetched_at": "2026-11-15T23:15:37.743Z", - "sha256": "868a0272e249a736c8f2510fb7e7def491fdb6ee509d85fc09e5f2fb32af33bd", + "source": "candidate:ffa66ce789ab6284cab9f831ba73025f0a5afeae/openapi-candidate.json", + "fetched_at": "2026-11-19T02:03:13.382Z", + "sha256": "6941cbee6488d220240741e9147cd018de80426af81d3fc02aa32dd757bd2224", "etag": null, "last_modified": null, "info": { "title": "CodeSpar AgentGate API", "version": "0.3.0" }, - "paths": 329, - "operations": 390, + "paths": 337, + "operations": 399, "generator": "openapi-typescript@7.13.0" }, "document": { @@ -2107,6 +2107,68 @@ "items": { "type": "string" } + }, + "token_endpoint_auth_methods_supported": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Present only with OAUTH_CONSENT_FLOW=consent. Not an RFC 9728 parameter: it repeats the authorization server's list, so a client that reads only this document learns a client secret is accepted." + } + }, + "required": [ + "resource", + "authorization_servers", + "bearer_methods_supported", + "scopes_supported" + ] + } + } + } + } + } + } + }, + "/.well-known/oauth-protected-resource/mcp": { + "get": { + "security": [], + "summary": "Protected-resource metadata for /mcp (RFC 9728, path-suffixed)", + "description": "The RFC 9728 §3.1 path-suffixed copy of the protected-resource metadata, for the remote MCP endpoint `/mcp`. MCP clients try this location before the root one, and the `/mcp` 401's `WWW-Authenticate` `resource_metadata` points here. Identical to `/.well-known/oauth-protected-resource` except `resource`, which is `/mcp`, the URL the client was given (RFC 9728 §3.3 requires the two to match). Host-aware, like the root copy.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "resource": { + "type": "string" + }, + "authorization_servers": { + "type": "array", + "items": { + "type": "string" + } + }, + "bearer_methods_supported": { + "type": "array", + "items": { + "type": "string" + } + }, + "scopes_supported": { + "type": "array", + "items": { + "type": "string" + } + }, + "token_endpoint_auth_methods_supported": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Present only with OAUTH_CONSENT_FLOW=consent, as on the root copy. Not an RFC 9728 parameter: it repeats the authorization server's list, so a client that reads only this document learns a client secret is accepted." } }, "required": [ @@ -2258,7 +2320,7 @@ "get": { "security": [], "summary": "Authorization-server metadata (RFC 8414)", - "description": "The three endpoint URLs below, absolute under the issuer, plus what this server supports: `response_types_supported: [\"code\"]`, `grant_types_supported: [\"authorization_code\", \"refresh_token\"]`, `code_challenge_methods_supported: [\"S256\"]` and `token_endpoint_auth_methods_supported: [\"none\"]`.\n\nRead the last two together: this is a PUBLIC client with no secret, and PKCE S256 is mandatory rather than preferred. `plain` is never advertised and is refused at the authorize endpoint. Host-aware, like the document above.", + "description": "The three endpoint URLs below, absolute under the issuer, plus what this server supports: `response_types_supported: [\"code\"]`, `grant_types_supported: [\"authorization_code\", \"refresh_token\"]`, `code_challenge_methods_supported: [\"S256\"]` and `token_endpoint_auth_methods_supported: [\"none\"]`, with `client_secret_basic` and `client_secret_post` added (and `offline_access` in `scopes_supported`) only when OAUTH_CONSENT_FLOW=consent.\n\nRead the last two together. `none` is every dynamically registered client: a PUBLIC client with no secret. The two secret methods are for a client CodeSpar registered ahead of time with a secret. PKCE S256 is mandatory for EVERY client, secret or not, rather than preferred. `plain` is never advertised and is refused at the authorize endpoint. Host-aware, like the document above.", "responses": { "200": { "description": "OK", @@ -2494,7 +2556,7 @@ "get": { "security": [], "summary": "Consent page (RFC 6749 §4.1.1 authorization request)", - "description": "Returns `text/html`, NOT JSON: this is the leg a human completes in a browser, so a generated client should open it rather than call it. `response_type=code`, a registered `client_id`, a `redirect_uri` matching one registered for that client exactly, and `code_challenge` with `code_challenge_method=S256` are all required.\n\nErrors are rendered as HTML with status 400 and are NOT redirected: per RFC 6749 §4.1.2.1 an invalid `client_id`/`redirect_uri` must not be redirected to, and this endpoint keeps that posture for every error so a human sees the reason on the page. A scope request this server cannot satisfy is refused here, before the form asking for a key is drawn.", + "description": "Returns `text/html`, NOT JSON: this is the leg a human completes in a browser, so a generated client should open it rather than call it. `response_type=code`, a registered `client_id`, a `redirect_uri` matching one registered for that client exactly, and `code_challenge` with `code_challenge_method=S256` are all required.\n\nErrors are rendered as HTML with status 400 and are NOT redirected: per RFC 6749 §4.1.2.1 an invalid `client_id`/`redirect_uri` must not be redirected to, and this endpoint keeps that posture for every error so a human sees the reason on the page. A scope request this server cannot satisfy is refused here, before the form asking for a key is drawn.\n\nWhere the deployment runs signed-in consent (`OAUTH_CONSENT_FLOW=consent`) no key is asked for: a valid request is held server-side and answered with a 302 to the web consent page, where a signed-in admin approves it. An unknown `client_id` or a `redirect_uri` that is not an exact registered match still gets the 400 page and is never redirected; every other refusal (`unsupported_response_type`, `invalid_request`, `invalid_scope`, `invalid_target` for a `resource` that is not this server's MCP endpoint) goes back to `redirect_uri` as an OAuth error with the `state`.", "parameters": [ { "schema": { @@ -2559,6 +2621,16 @@ "description": "Space-separated. Requesting more than the pasted key holds is refused.", "name": "scope", "in": "query" + }, + { + "schema": { + "type": "string", + "description": "RFC 8707 resource indicator. Under signed-in consent it must name this server's MCP endpoint." + }, + "required": false, + "description": "RFC 8707 resource indicator. Under signed-in consent it must name this server's MCP endpoint.", + "name": "resource", + "in": "query" } ], "responses": { @@ -2572,6 +2644,17 @@ } } }, + "302": { + "description": "Signed-in consent only: Location is the web consent page, or `redirect_uri` with an OAuth `error` and the `state`.", + "headers": { + "Location": { + "schema": { + "type": "string" + }, + "required": true + } + } + }, "400": { "description": "Rendered as HTML, never redirected.", "content": { @@ -2587,7 +2670,7 @@ "post": { "security": [], "summary": "Consent submit — exchanges a pasted API key for an authorization code", - "description": "`application/x-www-form-urlencoded`, submitted by the page above, not by a generated client. The form carries the same authorization-request parameters plus the API key the human pasted.\n\nOn success: 302 to `redirect_uri` with `code` and `state`. The code is single-use, short-lived, and bound to the tenant, the client, the redirect URI, the PKCE challenge AND the API key that authorized it — so revoking that key invalidates every token the code goes on to mint, and the token's scopes can never exceed the key's own. On refusal the page re-renders as HTML with 400.", + "description": "`application/x-www-form-urlencoded`, submitted by the page above, not by a generated client. The form carries the same authorization-request parameters plus the API key the human pasted.\n\nOn success: 302 to `redirect_uri` with `code` and `state`. The code is single-use, short-lived, and bound to the tenant, the client, the redirect URI, the PKCE challenge AND the API key that authorized it — so revoking that key invalidates every token the code goes on to mint, and the token's scopes can never exceed the key's own. On refusal the page re-renders as HTML with 400.\n\nWhere the deployment runs signed-in consent (`OAUTH_CONSENT_FLOW=consent`) this answers 404 and mints no code: no key is accepted.", "requestBody": { "content": { "application/x-www-form-urlencoded": { @@ -2667,7 +2750,7 @@ "post": { "security": [], "summary": "Token endpoint — authorization_code and refresh_token grants", - "description": "`application/x-www-form-urlencoded`, unauthenticated (public client, `token_endpoint_auth_method: none`); the authorization code IS the authority. `grant_type=authorization_code` requires `code`, `code_verifier`, `redirect_uri` and `client_id`; `grant_type=refresh_token` requires `refresh_token`. Anything else is 400 `unsupported_grant_type`.\n\nRedemption is atomic and single-use even under a concurrent retry: a second redemption of the same code sees no row and gets 400 `invalid_grant`. The refresh grant ROTATES — the presented refresh token is revoked and a new one returned, so a client must persist the new value. A refresh chain lives at most 90 days from the consent that began it: past that the refresh grant answers 400 `invalid_grant` and the user has to authorize again. `expires_in` is the access token's lifetime in seconds Responses carry `Cache-Control: no-store` (RFC 6749 §5.1).", + "description": "`application/x-www-form-urlencoded`. A public client (every dynamically registered one, `token_endpoint_auth_method: none`) is unauthenticated: the authorization code and its PKCE verifier are the authority. A client CodeSpar registered ahead of time with a secret must also authenticate, on BOTH grants, by `client_secret_basic` (`Authorization: Basic` with the url-encoded id and secret) or `client_secret_post` (`client_id` and `client_secret` in the body); a missing or wrong secret is 401 `invalid_client` and leaves the code or refresh token untouched, and both methods at once is 400 `invalid_request`. `grant_type=authorization_code` requires `code`, `code_verifier`, `redirect_uri` and `client_id`; `grant_type=refresh_token` requires `refresh_token`. Anything else is 400 `unsupported_grant_type`.\n\nRedemption is atomic and single-use even under a concurrent retry: a second redemption of the same code sees no row and gets 400 `invalid_grant`. The refresh grant ROTATES — the presented refresh token is revoked and a new one returned, so a client must persist the new value. A refresh chain lives at most 90 days from the consent that began it: past that the refresh grant answers 400 `invalid_grant` and the user has to authorize again. `expires_in` is the access token's lifetime in seconds Responses carry `Cache-Control: no-store` (RFC 6749 §5.1).", "requestBody": { "content": { "application/x-www-form-urlencoded": { @@ -2693,6 +2776,10 @@ "client_id": { "type": "string" }, + "client_secret": { + "type": "string", + "description": "client_secret_post, for a pre-registered client with a secret only." + }, "refresh_token": { "type": "string" } @@ -2743,7 +2830,28 @@ } }, "400": { - "description": "`invalid_grant` (code invalid, expired, already used, bound to a different client or redirect_uri, PKCE verification failed, carrying no recorded scope grant, or a refresh chain older than 90 days), `invalid_request`, or `unsupported_grant_type`.", + "description": "`invalid_grant` (code invalid, expired, already used, bound to a different client or redirect_uri, PKCE verification failed, carrying no recorded scope grant, or a refresh chain older than 90 days), `invalid_request` (also two client authentication methods at once), or `unsupported_grant_type`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "error_description": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "401": { + "description": "`invalid_client`: a client registered with a secret presented none, a wrong one, a malformed Basic header, or a Basic id that differs from the body `client_id`. Carries `WWW-Authenticate: Basic` when the request used Basic.", "content": { "application/json": { "schema": { @@ -2766,6 +2874,441 @@ } } }, + "/oauth/pending/{handle}": { + "get": { + "security": [], + "summary": "Signed-in consent — read a held authorization request for the consent page", + "description": "What the consent page shows before the person decides: the client, the scopes it would get with the line the page prints for each, when the request expires, and whether the organization the person's session is signed into may finish a consent yet. The first person to read a handle is bound to it. Not an API-key or OAuth-token operation: send the service key and the person's Clerk session token, and no Authorization header.\n\n`approverAccess` is the access an approval by this person would give, from their role in the organization their session is signed into: `full` for an owner or admin (a personal account counts as owner), `read_only` for a member, whose grant reaches only the read tools, and `null` for a person with no role there, whose approval is refused. It is a hint for the page's wording only — the decide call resolves the role again at the click. For an approver that is not `full`, the `tools:execute` line reads \"Call codespar's read tools (getting started, discovery, payment status)\".\n\nJSON `{ \"error\": \"\" }`. `bearer_token_cannot_decide` (403, an Authorization header was sent), `unauthorized` (401, no valid service key), `user_token_required` / `user_token_invalid` / `user_token_identity_mismatch` / `user_token_wrong_party` (403), `user_token_verification_unconfigured` (503), `rate_limit_exceeded` (429 with `Retry-After`), `pending_not_found` (404), `handle_bound_to_other` (403), `pending_decided` (409), `pending_expired` (410), and 404 `consent_flow_disabled` when the deployment does not run signed-in consent.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The `request` value of the consent page's URL." + }, + "required": true, + "description": "The `request` value of the consent page's URL.", + "name": "handle", + "in": "path" + }, + { + "schema": { + "type": "string", + "description": "The service key of the web app that renders the consent page." + }, + "required": true, + "description": "The service key of the web app that renders the consent page.", + "name": "x-codespar-service-key", + "in": "header" + }, + { + "schema": { + "type": "string", + "description": "The signed-in person's Clerk session token, issued to the consent page's origin. The person is its subject, never a forwarded header." + }, + "required": true, + "description": "The signed-in person's Clerk session token, issued to the consent page's origin. The person is its subject, never a forwarded header.", + "name": "x-codespar-user-token", + "in": "header" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "client": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The client's display name, sanitized; a placeholder when it registered none." + }, + "unverified": { + "type": "boolean" + }, + "redirectHost": { + "type": "string" + } + }, + "required": [ + "name", + "unverified", + "redirectHost" + ] + }, + "scopes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "scope": { + "type": "string" + }, + "label": { + "type": "string" + } + }, + "required": [ + "scope", + "label" + ] + } + }, + "expiresAt": { + "type": "string" + }, + "openForActiveOrg": { + "type": "boolean" + }, + "approverAccess": { + "type": [ + "string", + "null" + ], + "enum": [ + "full", + "read_only" + ], + "description": "What this person's approval would grant: `full`, `read_only` (read tools only), or null (no role; approval refused). A display hint; decide resolves it again." + } + }, + "required": [ + "client", + "scopes", + "expiresAt", + "openForActiveOrg", + "approverAccess" + ] + } + } + } + }, + "401": { + "description": "`unauthorized`: no valid service key.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "403": { + "description": "A refusal named in `error`; see the description.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "404": { + "description": "`pending_not_found` or `consent_flow_disabled`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "409": { + "description": "`pending_decided`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "410": { + "description": "`pending_expired`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "429": { + "description": "`rate_limit_exceeded`, with `Retry-After`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + } + } + } + }, + "/oauth/pending/{handle}/decide": { + "post": { + "security": [], + "summary": "Signed-in consent — approve or deny a held authorization request", + "description": "The person's decision, made with a Clerk session token minted at the click (older than 120 seconds is 403 `user_token_stale`). Same headers as the read, and no Authorization header. An approval by an owner or admin of the project's organization makes a `full` grant; an approval by a member makes a `read_only` grant whose tool calls are limited to the read tools; a person with no role in that organization is refused `no_role`. Approve or deny, the answer is 200 with the URL to send the browser to: the client's redirect URI with `code` and `state` on approval, or with `error=access_denied` and `state` on deny.\n\nDecide-only refusals: `invalid_body` (400), `project_not_in_org` (403), and for an approval `no_role`, `not_open_yet`, `project_archived`, `live_not_available`, `no_grantable_scopes` (403) and `invalid_client` / `invalid_request` (400). None of them consumes the request. JSON `{ \"error\": \"\" }`. `bearer_token_cannot_decide` (403, an Authorization header was sent), `unauthorized` (401, no valid service key), `user_token_required` / `user_token_invalid` / `user_token_identity_mismatch` / `user_token_wrong_party` (403), `user_token_verification_unconfigured` (503), `rate_limit_exceeded` (429 with `Retry-After`), `pending_not_found` (404), `handle_bound_to_other` (403), `pending_decided` (409), `pending_expired` (410), and 404 `consent_flow_disabled` when the deployment does not run signed-in consent.", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "handle", + "in": "path" + }, + { + "schema": { + "type": "string", + "description": "The service key of the web app that renders the consent page." + }, + "required": true, + "description": "The service key of the web app that renders the consent page.", + "name": "x-codespar-service-key", + "in": "header" + }, + { + "schema": { + "type": "string", + "description": "The signed-in person's Clerk session token, issued to the consent page's origin. The person is its subject, never a forwarded header." + }, + "required": true, + "description": "The signed-in person's Clerk session token, issued to the consent page's origin. The person is its subject, never a forwarded header.", + "name": "x-codespar-user-token", + "in": "header" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "decision": { + "type": "string", + "enum": [ + "approve", + "deny" + ] + }, + "projectId": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "description": "The project the grant is for, in the session's organization." + } + }, + "required": [ + "decision", + "projectId" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "redirectUrl": { + "type": "string", + "description": "Where to send the browser: the client's redirect URI with the code, or with `access_denied`." + } + }, + "required": [ + "redirectUrl" + ] + } + } + } + }, + "400": { + "description": "`invalid_body`, `invalid_client` or `invalid_request`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "401": { + "description": "`unauthorized`: no valid service key.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "403": { + "description": "A refusal named in `error`, `no_role` among them; see the description.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "404": { + "description": "`pending_not_found` or `consent_flow_disabled`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "409": { + "description": "`pending_decided`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "410": { + "description": "`pending_expired`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + }, + "429": { + "description": "`rate_limit_exceeded`, with `Retry-After`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + }, + "required": [ + "error" + ] + } + } + } + } + } + } + }, "/openapi.json": { "get": { "security": [], @@ -4439,7 +4982,7 @@ "minLength": 1, "maxLength": 128, "pattern": "^[a-z0-9_]+(\\.[a-z0-9_]+)*$", - "description": "The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below." + "description": "The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, oauth.consent_denied, oauth.grant_created, oauth.grant_replaced, oauth.grant_revoked, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below." }, "server_id": { "type": "string", @@ -4821,7 +5364,7 @@ "minLength": 1, "maxLength": 128, "pattern": "^[a-z0-9_]+(\\.[a-z0-9_]+)*$", - "description": "The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below." + "description": "The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, oauth.consent_denied, oauth.grant_created, oauth.grant_replaced, oauth.grant_revoked, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below." }, "server_id": { "type": "string", @@ -7404,7 +7947,7 @@ "amount_atomic": { "type": "string", "pattern": "^\\d+$", - "description": "USDC the Test treasury sends (the difference to 100 USDC), 6 decimals." + "description": "USDC the Test treasury sends (the difference to 20 USDC), 6 decimals." }, "treasury_address": { "type": "string" @@ -17554,6 +18097,16 @@ "type": "integer", "exclusiveMinimum": 0, "maximum": 9007199254740991 + }, + "monthly_minor": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + }, + "monthly_quantity": { + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 744 } }, "default": {}, @@ -17681,6 +18234,14 @@ "integer", "null" ] + }, + "monthly_minor": { + "type": "integer", + "description": "The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit." + }, + "monthly_quantity": { + "type": "integer", + "description": "How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one." } }, "required": [ @@ -18128,6 +18689,14 @@ "integer", "null" ] + }, + "monthly_minor": { + "type": "integer", + "description": "The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit." + }, + "monthly_quantity": { + "type": "integer", + "description": "How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one." } }, "required": [ @@ -18365,389 +18934,405 @@ "integer", "null" ] - } - }, - "required": [ - "total_minor", - "per_transaction_minor" - ], - "description": "The limits as the bank stated them on approval, in centavos. Null until `authorised`." - }, - "created_at": { - "type": "string" - }, - "authorized_at": { - "type": [ - "string", - "null" - ] - }, - "expires_at": { - "type": [ - "string", - "null" - ] - }, - "revoked_at": { - "type": [ - "string", - "null" - ] - }, - "consumed_at": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "id", - "consumer_id", - "wallet_id", - "funding_source_id", - "participant_id", - "provider", - "status", - "authorisation_url", - "debtor", - "limits", - "created_at", - "authorized_at", - "expires_at", - "revoked_at", - "consumed_at" - ] - } - } - } - }, - "404": { - "description": "Not Found. No sweeping consent with this id in the caller's project. A data-sharing consent's id answers here too.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "not_found" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" - ] - }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } - } - } - }, - "422": { - "description": "The project is live. Sweeping serves test projects only, against the provider's sandbox (`details.reason` `live_not_enabled`).", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "ofb_not_live" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" - ] - }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } - } - } - }, - "502": { - "description": "The provider refused the call. `details.provider_code` is the provider's own error code; terminal for this request.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "sweep_provider_refused" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" - ] - }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } - } - } - }, - "503": { - "description": "No definite answer: the provider did not answer, answered a status this API does not map yet (`sweep_provider_ambiguous`, retriable with the same request), or the deployment cannot reach a sweeping provider (`ofb_adapter_unavailable`).", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "sweep_provider_ambiguous", - "ofb_adapter_unavailable" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" - ] - }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } - } - } - } - }, - "x-codespar-scope": "consents:read", - "security": [ - { - "bearerAuth": [ - "consents:read" - ] - } - ] - } - }, - "/v1/ofb/sweeping/consents/{id}/revoke": { - "post": { - "summary": "Revoke a sweeping consent", - "description": "Reads the provider first, then rejects a consent still awaiting approval (`rejected`) or revokes an authorised one (`revoked`).\n\nRequires the `consents:write` scope.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "`ofb_`-prefixed sweeping consent id." - }, - "required": true, - "description": "`ofb_`-prefixed sweeping consent id.", - "name": "id", - "in": "path" - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "reason": { - "type": "string", - "minLength": 1, - "maxLength": 512 - } - } - } - } - } - }, - "responses": { - "200": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "`ofb_`-prefixed. Also the external id the provider keeps for this authorisation." - }, - "consumer_id": { - "type": "string" - }, - "wallet_id": { - "type": [ - "string", - "null" - ] - }, - "funding_source_id": { - "type": [ - "string", - "null" - ], - "description": "The consumer's `pix-celcoin` funding source the sweep lands in." - }, - "participant_id": { - "type": "string", - "description": "The provider's id for the consumer's bank, as passed when the consent was opened." - }, - "provider": { - "type": "string", - "enum": [ - "iniciador", - "celcoin-itp" - ] - }, - "status": { - "type": "string", - "enum": [ - "pending", - "authorised", - "consumed", - "revoked", - "rejected", - "expired", - "canceled", - "failed" - ], - "description": "`pending` until the consumer approves at their bank, then `authorised`. Terminal: `consumed`, `revoked` (after approval), `rejected` (refused or rejected before approval), `expired`, `canceled` (the provider canceled it, or it failed while being opened) and `failed` (a provider error). It only moves forward." - }, - "authorisation_url": { - "type": [ - "string", - "null" - ], - "description": "Where the consumer approves the consent at their bank. Present while `pending` only; open it once." - }, - "debtor": { - "type": [ - "object", - "null" - ], - "properties": { - "ispb": { - "type": [ - "string", - "null" - ] }, - "account_masked": { - "type": [ - "string", - "null" - ] - } - }, - "required": [ - "ispb", - "account_masked" - ], - "description": "The account the bank authorised the pulls from, as the provider reports it. Null until `authorised`." - }, - "limits": { - "type": [ - "object", - "null" - ], - "properties": { - "total_minor": { - "type": [ - "integer", - "null" - ] + "monthly_minor": { + "type": "integer", + "description": "The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit." }, - "per_transaction_minor": { - "type": [ - "integer", - "null" - ] + "monthly_quantity": { + "type": "integer", + "description": "How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one." + } + }, + "required": [ + "total_minor", + "per_transaction_minor" + ], + "description": "The limits as the bank stated them on approval, in centavos. Null until `authorised`." + }, + "created_at": { + "type": "string" + }, + "authorized_at": { + "type": [ + "string", + "null" + ] + }, + "expires_at": { + "type": [ + "string", + "null" + ] + }, + "revoked_at": { + "type": [ + "string", + "null" + ] + }, + "consumed_at": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "id", + "consumer_id", + "wallet_id", + "funding_source_id", + "participant_id", + "provider", + "status", + "authorisation_url", + "debtor", + "limits", + "created_at", + "authorized_at", + "expires_at", + "revoked_at", + "consumed_at" + ] + } + } + } + }, + "404": { + "description": "Not Found. No sweeping consent with this id in the caller's project. A data-sharing consent's id answers here too.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "not_found" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "422": { + "description": "The project is live. Sweeping serves test projects only, against the provider's sandbox (`details.reason` `live_not_enabled`).", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "ofb_not_live" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "502": { + "description": "The provider refused the call. `details.provider_code` is the provider's own error code; terminal for this request.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "sweep_provider_refused" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "503": { + "description": "No definite answer: the provider did not answer, answered a status this API does not map yet (`sweep_provider_ambiguous`, retriable with the same request), or the deployment cannot reach a sweeping provider (`ofb_adapter_unavailable`).", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "sweep_provider_ambiguous", + "ofb_adapter_unavailable" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + } + }, + "x-codespar-scope": "consents:read", + "security": [ + { + "bearerAuth": [ + "consents:read" + ] + } + ] + } + }, + "/v1/ofb/sweeping/consents/{id}/revoke": { + "post": { + "summary": "Revoke a sweeping consent", + "description": "Reads the provider first, then rejects a consent still awaiting approval (`rejected`) or revokes an authorised one (`revoked`).\n\nRequires the `consents:write` scope.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "`ofb_`-prefixed sweeping consent id." + }, + "required": true, + "description": "`ofb_`-prefixed sweeping consent id.", + "name": "id", + "in": "path" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } + } + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`ofb_`-prefixed. Also the external id the provider keeps for this authorisation." + }, + "consumer_id": { + "type": "string" + }, + "wallet_id": { + "type": [ + "string", + "null" + ] + }, + "funding_source_id": { + "type": [ + "string", + "null" + ], + "description": "The consumer's `pix-celcoin` funding source the sweep lands in." + }, + "participant_id": { + "type": "string", + "description": "The provider's id for the consumer's bank, as passed when the consent was opened." + }, + "provider": { + "type": "string", + "enum": [ + "iniciador", + "celcoin-itp" + ] + }, + "status": { + "type": "string", + "enum": [ + "pending", + "authorised", + "consumed", + "revoked", + "rejected", + "expired", + "canceled", + "failed" + ], + "description": "`pending` until the consumer approves at their bank, then `authorised`. Terminal: `consumed`, `revoked` (after approval), `rejected` (refused or rejected before approval), `expired`, `canceled` (the provider canceled it, or it failed while being opened) and `failed` (a provider error). It only moves forward." + }, + "authorisation_url": { + "type": [ + "string", + "null" + ], + "description": "Where the consumer approves the consent at their bank. Present while `pending` only; open it once." + }, + "debtor": { + "type": [ + "object", + "null" + ], + "properties": { + "ispb": { + "type": [ + "string", + "null" + ] + }, + "account_masked": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "ispb", + "account_masked" + ], + "description": "The account the bank authorised the pulls from, as the provider reports it. Null until `authorised`." + }, + "limits": { + "type": [ + "object", + "null" + ], + "properties": { + "total_minor": { + "type": [ + "integer", + "null" + ] + }, + "per_transaction_minor": { + "type": [ + "integer", + "null" + ] + }, + "monthly_minor": { + "type": "integer", + "description": "The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit." + }, + "monthly_quantity": { + "type": "integer", + "description": "How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one." } }, "required": [ @@ -24506,37 +25091,24 @@ ] } }, - "/v1/cards": { + "/v1/counterparties/{id}": { "get": { "externalDocs": { "url": "https://github.com/codespar/codespar-enterprise/issues/979", "description": "ent#979: canonical path and alias window" }, - "summary": "List issued cards", - "description": "The cards issued in this project, most recent first.\n\nThis listing carries CARDS, not mint flows: a `POST` that stopped at `202` waiting for KYC does not appear here until it becomes a card. To follow that flow, read the `flow_id` the issuance returned.", + "summary": "Read one counterparty", + "description": "The same row the list returns, by id.\n\nA counterparty that belongs to another org, or to a sibling project of the same org, is indistinguishable from one that does not exist: both are 404. Counterparty ids are unique per project and not globally, so the same id can name a different company in another project.\n\nThe canonical path. `GET /v1/commerce-memory/counterparties/{id}` is the deprecated alias of this operation, described in this document under that path and kept for two releases. The two paths are the same handler with the same required scope, so switching one for the other changes nothing about the request, the response or the credential.", "parameters": [ { "schema": { "type": "string", - "minLength": 1, - "description": "Filters to one consumer's cards." - }, - "required": false, - "description": "Filters to one consumer's cards.", - "name": "consumer_id", - "in": "query" - }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200, - "description": "1 to 200; the default is 50." + "description": "`cp_` prefixed." }, - "required": false, - "description": "1 to 200; the default is 50.", - "name": "limit", - "in": "query" + "required": true, + "description": "`cp_` prefixed.", + "name": "id", + "in": "path" } ], "responses": { @@ -24547,92 +25119,74 @@ "schema": { "type": "object", "properties": { - "cards": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ], - "description": "Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118)." - }, - "card_id": { - "type": "string", - "description": "The issuer's own identifier for the card, as it was returned to us." - }, - "last4": { - "type": "string", - "description": "The last four digits. No other card-number material exists on this surface." - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ], - "description": "`CHECK (network IN ('visa', 'mastercard'))`, migration 0118." - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ], - "description": "`IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118." - }, - "token_id": { - "type": [ - "string", - "null" - ], - "description": "The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ] - } + "id": { + "type": "string", + "description": "`cp_` prefixed." + }, + "kind": { + "type": "string", + "enum": [ + "supplier", + "customer", + "agent_peer" + ], + "description": "`CHECK (kind IN ('supplier', 'customer', 'agent_peer'))`, migration 0050." + }, + "name": { + "type": "string" + }, + "identifier": { + "type": [ + "string", + "null" + ], + "description": "Null when the counterparty was registered without one." + }, + "identifier_kind": { + "type": [ + "string", + "null" + ], + "enum": [ + "cnpj", + "cpf", + "email", + "phone", + "wallet_address", + "other" + ], + "description": "`CHECK (identifier_kind IN ('cnpj', 'cpf', 'email', 'phone', 'wallet_address', 'other'))`, migration 0050. Null exactly when `identifier` is null: the pair is held together by `commerce_counterparties_identifier_pair`, a table constraint, so one without the other cannot be stored." + }, + "metadata": { + "type": "object", + "additionalProperties": {} + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "last_seen_at": { + "type": "string", + "format": "date-time", + "description": "Bumped by a re-registration of the same identifier and by every interaction recorded against this row." } }, "required": [ - "cards" + "id", + "kind", + "name", + "identifier", + "identifier_kind", + "metadata", + "created_at", + "last_seen_at" ] } } } }, - "400": { - "description": "The query did not match the schema.", + "404": { + "description": "`not_found`, including for a counterparty outside the caller's project.", "content": { "application/json": { "schema": { @@ -24644,7 +25198,7 @@ "code": { "type": "string", "enum": [ - "invalid_query" + "not_found" ] }, "message": { @@ -24677,1211 +25231,1556 @@ } } }, - "x-codespar-scope": "cards:read", + "x-codespar-scope": "commerce-memory:read", "security": [ { "bearerAuth": [ - "cards:read" + "commerce-memory:read" ] } ] - }, - "post": { + } + }, + "/v1/servers/{id}/auth-schema": { + "get": { + "deprecated": true, "externalDocs": { "url": "https://github.com/codespar/codespar-enterprise/issues/979", "description": "ent#979: canonical path and alias window" }, - "summary": "Issue a card under a signed mandate", - "description": "Issues a card for an agent, under a signed mandate.\n\n**Three success outcomes, and the status separates them.** `201` is the issuance that finished now. `202` is the issuer asking for KYC on the holder before issuing: the flow stays `pending`, and `kyc_url` is where to send the person. `200` is a REPLAY: the same `Idempotency-Key` arriving again on a flow that already finished, returning what it produced instead of issuing a second card.\n\n**Repeating is safe and it is the recovery path.** A `502 issuer_ingest_failed` means the card EXISTS and only the ingest into the data environment failed: repeating with the SAME key reuses the token, and sending a new key would issue a second card. The body of that refusal already carries the issued card.\n\n**A repeated key with a different body is `409`**, not a new issuance: the request fingerprint is derived from the holder and compared, and it survives the redaction of the holder's data, so the divergence is caught much later.", + "summary": "Read the credential form a provider needs, without reading any credential", + "description": "What to ask an operator for before connecting this provider, and where the request will go once connected. It NEVER returns a stored secret: the vault is write-only from this side, and `fields` describes inputs to collect, not values that exist.\n\nAN EMPTY `fields` DOES NOT MEAN NOTHING TO DO. `oauth` collects nothing here because the browser leg starts at `POST /v1/connections/start` instead, and `none` needs no credential. Every other type returns one field per catalog-declared ref, which is exactly the key set `POST /v1/connections` validates the secret object against: `jwt_ecdsa` asks for the CDP API key name and its private key, `cdp` for the CDP API key id, API key secret and wallet secret. Both CDP forms are served only where the deployment enables CDP self-serve connect (`CDP_SELF_SERVE_CONNECT`, off by default); otherwise they come back empty. A form type whose catalog row declares no refs comes back empty and cannot be connected; `connectable` on `GET /v1/servers` already says so per row.\n\n`base_url` IS ENVIRONMENT-RESOLVED against the credential in hand: a test key sees the provider's test host when the catalog declares one, and the live host otherwise. It is the empty string when the provider has no endpoint row, which is a catalog gap rather than a value to dial.\n\nThis is the path that shipped first; `GET /v1/providers/{slug}/auth-schema` is the same handler at the canonical path (ent#979) and is not yet described in this document, so the full response is described HERE and nothing is withheld until you switch paths.\n\nThe visibility gate in front of this operation only hides GENERATED providers (ids prefixed `gen_`) that belong to another project. Any id without that prefix passes the gate, including an id that names no provider at all. Past the gate, a provider that is genuinely absent from the catalog is a 404 as well, so this operation does distinguish a real provider from an invented one.", "parameters": [ { "schema": { "type": "string", - "description": "Keys the mint flow. When absent, the server mints one, and the call then stops being repeatable, because there is no key to repeat." + "description": "The provider id, which is also the catalog row's primary key." }, - "required": false, - "description": "Keys the mint flow. When absent, the server mints one, and the call then stops being repeatable, because there is no key to repeat.", - "name": "Idempotency-Key", - "in": "header" + "required": true, + "description": "The provider id, which is also the catalog row's primary key.", + "name": "id", + "in": "path" } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "country": { - "type": "string", - "description": "ISO 3166-1 alpha-2, uppercase. Decides the issuing corridor." - }, - "currency": { - "type": "string", - "description": "ISO 4217, uppercase." - }, - "holder": { - "type": "object", - "properties": { - "full_name": { - "type": "string", - "minLength": 1, - "maxLength": 140 - }, - "email": { - "type": "string", - "format": "email" - }, - "birthdate": { - "type": "string", - "description": "`YYYY-MM-DD`." - }, - "document": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "server_id": { + "type": "string" + }, + "auth_type": { + "type": "string", + "description": "LEFT OPEN ON PURPOSE, and the reason is measured rather than cautious. The column admits nine values today — `api_key`, `path_secret`, `oauth`, `cert`, `none`, `hmac_signed`, `jwt_ecdsa`, `two_header`, `cdp` — under a CHECK constraint that has been widened four times (migrations 0064, 0066, 0074, 0091, over the six of 0026). The handler casts the column straight into this field, so the set of values a client can receive is the DB's, not any narrower published enum. Closing this to six would describe a wire that already carries more." + }, + "environment": { + "type": "string", + "enum": [ + "live", + "test" + ], + "description": "Taken from the calling credential, and what `base_url` was resolved against." + }, + "base_url": { + "type": "string", + "description": "The host a call to this provider will be sent to, in the caller's environment. Empty string when the provider has no endpoint row." + }, + "oauth_authorize_url": { + "type": [ + "string", + "null" + ], + "description": "Where the browser leg starts, environment-resolved the same way. Null for every auth type other than `oauth`, and also null for an `oauth` provider with no configuration row." + }, + "fields": { + "type": "array", + "items": { "type": "object", "properties": { - "type": { + "name": { "type": "string", - "minLength": 1, - "maxLength": 16 + "description": "The key to submit this value under when the connection is created. For a header-bearing field it is derived from the catalog's ref name, not from the header." }, - "value": { + "kind": { "type": "string", - "minLength": 1, - "maxLength": 32 + "enum": [ + "api_key", + "path_secret", + "header", + "cert" + ], + "description": "What input to render. These four are the whole set the handler can emit: it builds `AuthSchemaField[]`, so a fifth kind would not compile. `hmac_signed` reuses `path_secret` and `two_header` reuses `header` rather than each having its own." }, - "issuing_country": { + "label": { + "type": "string", + "description": "Human-readable label. For a header field it is the header name itself." + }, + "header_name": { "type": "string", - "description": "ISO 3166-1 alpha-2, uppercase." + "description": "Present only on `header` fields, naming the HTTP header the value is stamped under." } }, "required": [ - "type", - "value", - "issuing_country" + "name", + "kind", + "label" ] }, - "address": { + "description": "In the order the form should render, which is the catalog's declared order: the visible field before the masked one for the multi-field types." + } + }, + "required": [ + "server_id", + "auth_type", + "environment", + "base_url", + "oauth_authorize_url", + "fields" + ] + } + } + } + }, + "404": { + "description": "The provider is not visible to this project. Not the `apiError` envelope and not `{ error: \"not_found\" }`: a third shape, built at the route.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "server_unknown" + ] + }, + "server_id": { + "type": "string", + "description": "Echoes the id from the path." + } + }, + "required": [ + "error", + "server_id" + ] + } + } + } + } + }, + "x-codespar-scope": "servers:read", + "security": [ + { + "bearerAuth": [ + "servers:read" + ] + } + ] + } + }, + "/v1/servers/{id}/tools": { + "get": { + "summary": "List the tools a provider exposes", + "description": "Every tool registered for this provider, ordered by name, with no limit and no cursor: `total` is the length of `tools` and the two cannot disagree.\n\nAN UNKNOWN PROVIDER IS 200 HERE, NOT 404, and it is the one thing worth knowing about this operation. The visibility gate in front of this operation only hides GENERATED providers (ids prefixed `gen_`) that belong to another project. Any id without that prefix passes the gate, including an id that names no provider at all. There is no second check after it, so an id that names nothing reaches the tool query, matches no rows, and comes back as a well-formed empty list with that id echoed in `server_id`. An empty `tools` therefore means either a real provider with nothing registered or a provider that does not exist, and this response cannot tell you which. The 404 below is reachable only for another project's generated provider.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The provider id." + }, + "required": true, + "description": "The provider id.", + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "server_id": { + "type": "string", + "description": "Echoes the id from the path, whether or not it named anything." + }, + "total": { + "type": "integer", + "description": "Always equal to the length of `tools`." + }, + "tools": { + "type": "array", + "items": { "type": "object", "properties": { - "line1": { - "type": "string", - "minLength": 1, - "maxLength": 140 - }, - "line2": { - "type": "string", - "maxLength": 140 - }, - "street_number": { - "type": "string", - "description": "Required by some corridors (Pomelo BR); optional in the schema." - }, - "neighborhood": { - "type": "string" - }, - "city": { - "type": "string", - "minLength": 1, - "maxLength": 80 - }, - "state": { - "type": "string" - }, - "postal_code": { - "type": "string", - "minLength": 1, - "maxLength": 20 - }, - "municipality": { + "name": { "type": "string", - "description": "Where the corridor requires it and it differs from `city`: in Pomelo BR, the IBGE code." + "description": "The tool name, and the sort key of this list." }, - "country": { - "type": "string", - "description": "ISO 3166-1 alpha-2, uppercase." + "description": { + "type": [ + "string", + "null" + ], + "description": "Null when the catalog carries none." } }, "required": [ - "line1", - "city", - "postal_code", - "country" + "name", + "description" ] - }, - "phone": { - "type": "string", - "description": "E.164, with the `+`." } - }, - "required": [ - "full_name", - "email", - "birthdate", - "document", - "address" - ] - }, - "mandate_id": { - "type": "string", - "minLength": 1, - "description": "REQUIRED on every rail, with no exception by issuer. The card is an agent's spending instrument and the mandate is the consumer's signed authorization for it. Issuing with no mandate produced, on Bridge, a card with no limit and no category on a rail that never declines; and on Pomelo, a card the authorizer has no link to at all at spend time." + } }, - "metadata": { - "type": "object", - "additionalProperties": { + "required": [ + "server_id", + "total", + "tools" + ] + } + } + } + }, + "404": { + "description": "The provider is not visible to this project. Not the `apiError` envelope and not `{ error: \"not_found\" }`: a third shape, built at the route.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "server_unknown" + ] + }, + "server_id": { "type": "string", - "maxLength": 500 + "description": "Echoes the id from the path." } - } - }, - "required": [ - "country", - "currency", - "holder", - "mandate_id" - ] + }, + "required": [ + "error", + "server_id" + ] + } } } } }, + "x-codespar-scope": "servers:read", + "security": [ + { + "bearerAuth": [ + "servers:read" + ] + } + ] + } + }, + "/v1/servers/{id}/verify-connection": { + "post": { + "deprecated": true, + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/issues/979", + "description": "ent#979: canonical path and alias window" + }, + "summary": "Ask the provider whether this project's stored credential still works", + "description": "Issues ONE safe read against the provider using the credential this project has stored for it, and reports what came back. POST because it leaves the process and spends a provider call, not because it changes anything here: no state of yours is altered by it. It takes NO REQUEST BODY, and anything sent is ignored.\n\nWHICH READ depends on the provider. A handful ship a bespoke recipe, and those are the ones that can return an `account` summary. Everything else re-runs the provider's declared functional probe, the same authenticated read used to confirm a sandbox works when it is first set up; that path returns no `account`. A provider with neither answers 501.\n\nREAD THE STATUS, NOT THE BODY, TO DECIDE WHAT TO DO. Seven failure codes map onto seven distinct statuses, and only ONE of them is worth retrying unchanged (502). 401 is a verdict on the credential; 424 means there is no connection to test yet; 409 means the host redirected and never judged the credential, so a retry gets the same non-answer; 501 and 503 are configuration, not weather.\n\nTHE 502 IS WIDER THAN ITS NAME. `provider_unreachable` is what every non-2xx that is not a redirect and not a 401 or 403 becomes, so a provider answering 400, 404, 409, 422 or 429 arrives here as 502 with the provider's own status in `status`. An agent that retries every 502 will retry a 429 sensibly and a 400 forever. Read `status` before deciding.\n\nTWO DIFFERENT BODIES SHARE THE 404, from two different lines: the visibility gate's `{ error, server_id }`, and the verify outcome's `{ ok: false, provider, error }` when the credential resolver finds no such provider in the catalog. Both are described below.\n\nThis is the path that shipped first; `POST /v1/providers/{slug}/verify-connection` is the same handler at the canonical path (ent#979) and is not yet described in this document.\n\nThe visibility gate in front of this operation only hides GENERATED providers (ids prefixed `gen_`) that belong to another project. Any id without that prefix passes the gate, including an id that names no provider at all.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The provider id." + }, + "required": true, + "description": "The provider id.", + "name": "id", + "in": "path" + } + ], "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "properties": { + "ok": { + "type": "boolean", + "enum": [ + true + ] + }, + "provider": { + "type": "string", + "description": "The provider id from the path." + }, + "account": { "type": "object", "properties": { - "state": { - "type": "string", - "enum": [ - "issued" - ] + "id": { + "type": "string" }, - "flow_id": { + "name": { "type": "string" }, - "card": { + "extras": { "type": "object", - "properties": { - "id": { - "type": "string", - "description": "CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ], - "description": "Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118)." - }, - "card_id": { - "type": "string", - "description": "The issuer's own identifier for the card, as it was returned to us." - }, - "last4": { - "type": "string", - "description": "The last four digits. No other card-number material exists on this surface." - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ], - "description": "`CHECK (network IN ('visa', 'mastercard'))`, migration 0118." - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ], - "description": "`IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118." - }, - "token_id": { - "type": [ - "string", - "null" - ], - "description": "The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ] + "additionalProperties": {}, + "description": "Whatever the provider's recipe chose to surface, keyed by that provider's own names." } }, - "required": [ - "state", - "flow_id", - "card" - ] + "description": "ABSENT on the probe path, and absent on the recipe path whenever the recipe found nothing it recognised in the response. Present means the read reached a real account; absent does NOT mean it did not." }, - { - "type": "object", - "properties": { - "flow_id": { - "type": "string", - "description": "`imf_` prefixed. The row it names is keyed by the mint call's `Idempotency-Key`, or by a server-minted one when that header was absent." - }, - "state": { - "type": "string", - "enum": [ - "pending", - "issued", - "revoked", - "failed" - ], - "description": "`MintFlowState`, and `CHECK (state IN ('pending', 'issued', 'revoked', 'failed'))` in 0118." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ] - }, - "reason": { - "type": [ - "string", - "null" - ], - "description": "Why the flow is parked, when it is parked. Null otherwise." - }, - "kyc_url": { - "type": [ - "string", - "null" - ], - "description": "Where the holder finishes identity verification, when the issuer asked for one. Null otherwise." - }, - "created_at": { - "type": "string", - "format": "date-time" - }, - "card": { - "type": [ - "object", - "null" - ], - "properties": { - "id": { - "type": "string", - "description": "CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ], - "description": "Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118)." - }, - "card_id": { - "type": "string", - "description": "The issuer's own identifier for the card, as it was returned to us." - }, - "last4": { - "type": "string", - "description": "The last four digits. No other card-number material exists on this surface." - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ], - "description": "`CHECK (network IN ('visa', 'mastercard'))`, migration 0118." - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ], - "description": "`IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118." - }, - "token_id": { - "type": [ - "string", - "null" - ], - "description": "The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ], - "description": "PRESENT ONLY when `state` is `issued` AND the flow already points at a card row. In every other case the key is absent rather than null. Null inside that case means the card row did not resolve under this org and project." - } - }, - "required": [ - "flow_id", - "state", - "issuer", - "reason", - "kyc_url", - "created_at" - ] + "latency_ms": { + "type": "integer", + "description": "Wall-clock milliseconds around the outbound call." } - ], - "description": "REPLAY of a key whose flow already finished. `issued` returns the card; `revoked` returns only the flow, with no `card` key." + }, + "required": [ + "ok", + "provider", + "latency_ms" + ] } } } }, - "201": { - "description": "OK", + "401": { + "description": "`provider_rejected`. The provider answered 401 or 403: it looked at the credential and said no. Retrying unchanged will fail the same way.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "state": { - "type": "string", + "ok": { + "type": "boolean", "enum": [ - "issued" + false ] }, - "flow_id": { - "type": "string" + "provider": { + "type": "string", + "description": "The provider id from the path." }, - "card": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ], - "description": "Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118)." - }, - "card_id": { - "type": "string", - "description": "The issuer's own identifier for the card, as it was returned to us." - }, - "last4": { - "type": "string", - "description": "The last four digits. No other card-number material exists on this surface." - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ], - "description": "`CHECK (network IN ('visa', 'mastercard'))`, migration 0118." - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ], - "description": "`IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118." - }, - "token_id": { - "type": [ - "string", - "null" - ], - "description": "The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" + "error": { + "type": "string", + "enum": [ + "provider_rejected" ] + }, + "status": { + "type": "integer", + "description": "The provider's own status, 401 or 403." + }, + "latency_ms": { + "type": "integer", + "description": "Wall-clock milliseconds around the outbound call." + }, + "detail": { + "type": "string", + "description": "The provider's OWN response body, truncated to 256 characters, on the recipe path. On the probe path it is the probe's error text instead, with the credential masked out. This is one of only two codes where `detail` carries provider text." } }, "required": [ - "state", - "flow_id", - "card" + "ok", + "provider", + "error", + "status", + "latency_ms" ] } } } }, - "202": { - "description": "OK", + "403": { + "description": "`shared_sandbox_operation_refused` or `shared_sandbox_credential_not_test`. The project's connection is the platform's shared sandbox account. Test connection on it runs only the operation its provider lists for verify, with no account in the answer; a provider with none, or whose shared credential is not shown to be a test one, is refused before anything is sent. Not a verdict on a credential of yours: connect your own account for this provider.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "flow_id": { - "type": "string", - "description": "`imf_` prefixed. The row it names is keyed by the mint call's `Idempotency-Key`, or by a server-minted one when that header was absent." + "ok": { + "type": "boolean", + "enum": [ + false + ] }, - "state": { + "provider": { "type": "string", - "enum": [ - "pending", - "issued", - "revoked", - "failed" - ], - "description": "`MintFlowState`, and `CHECK (state IN ('pending', 'issued', 'revoked', 'failed'))` in 0118." + "description": "The provider id from the path." }, - "issuer": { + "error": { "type": "string", "enum": [ - "pomelo", - "bridge" + "shared_sandbox_operation_refused", + "shared_sandbox_credential_not_test" ] }, - "reason": { - "type": [ - "string", - "null" - ], - "description": "Why the flow is parked, when it is parked. Null otherwise." - }, - "kyc_url": { - "type": [ - "string", - "null" - ], - "description": "Where the holder finishes identity verification, when the issuer asked for one. Null otherwise." - }, - "created_at": { + "detail": { "type": "string", - "format": "date-time" - }, - "card": { - "type": [ - "object", - "null" - ], - "properties": { - "id": { - "type": "string", - "description": "CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ], - "description": "Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118)." - }, - "card_id": { - "type": "string", - "description": "The issuer's own identifier for the card, as it was returned to us." - }, - "last4": { - "type": "string", - "description": "The last four digits. No other card-number material exists on this surface." - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ], - "description": "`CHECK (network IN ('visa', 'mastercard'))`, migration 0118." - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ], - "description": "`IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118." - }, - "token_id": { - "type": [ - "string", - "null" - ], - "description": "The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ], - "description": "PRESENT ONLY when `state` is `issued` AND the flow already points at a card row. In every other case the key is absent rather than null. Null inside that case means the card row did not resolve under this org and project." + "description": "A CodeSpar-authored sentence. Never provider text." } }, "required": [ - "flow_id", - "state", - "issuer", - "reason", - "kyc_url", - "created_at" - ], - "description": "The issuer asked for KYC on the holder. `kyc_url` is where to send the person; `reason` says what it asked for." + "ok", + "provider", + "error" + ] } } } }, - "400": { - "description": "The body did not match the schema, the country/currency pair has no corridor, the holder was rejected by the issuer, or the controls requested do not exist on this rail.", + "404": { + "description": "Two shapes under one status. The route's own gate answers `{ error, server_id }` before any work happens; the credential resolver answers the verify outcome's `server_unknown` when the provider is absent from the catalog. Parse the union.", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "error": { + "anyOf": [ + { "type": "object", "properties": { - "code": { + "error": { "type": "string", "enum": [ - "invalid_body", - "issuer_corridor_unsupported", - "invalid_holder", - "issuer_controls_unsupported" + "server_unknown" ] }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} + "server_id": { + "type": "string", + "description": "Echoes the id from the path." } }, "required": [ - "code", - "message" + "error", + "server_id" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } - } - } - }, - "403": { - "description": "The key and the issuer's environment do not match. A test key does not issue a real card, and a live key does not issue on the staging issuer.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { + { "type": "object", "properties": { - "code": { - "type": "string", + "ok": { + "type": "boolean", "enum": [ - "stage_issuer_live_key", - "live_issuer_test_key" + false ] }, - "message": { - "type": "string" + "provider": { + "type": "string", + "description": "The provider id from the path." }, - "details": { - "type": "object", - "additionalProperties": {} + "error": { + "type": "string", + "enum": [ + "server_unknown" + ] } }, "required": [ - "code", - "message" + "ok", + "provider", + "error" ] - }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." } - }, - "required": [ - "error", - "request_id" ] } } } }, - "404": { - "description": "The named mandate does not exist in this organization.", + "409": { + "description": "`redirect_not_followed`. The configured host answered 3xx. The probe is issued with redirects disabled on purpose, so the credential was never judged by anyone: this is the absence of a verdict, not a negative one. Retrying cannot change it; the host or the catalog entry has to.", "content": { "application/json": { "schema": { "type": "object", "properties": { + "ok": { + "type": "boolean", + "enum": [ + false + ] + }, + "provider": { + "type": "string", + "description": "The provider id from the path." + }, "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "mandate_not_found" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "redirect_not_followed" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "status": { + "type": "integer", + "description": "The 3xx the host answered with." + }, + "latency_ms": { + "type": "integer", + "description": "Wall-clock milliseconds around the outbound call." } }, "required": [ + "ok", + "provider", "error", - "request_id" + "status", + "latency_ms" ] } } } }, - "409": { - "description": "The `Idempotency-Key` was already used with a different body, or it belongs to a request made before a `VAULT_MASTER_KEY` rotation and can no longer be matched to its body (retry with a new key), or the mandate is not active. `details` carries the mandate's state in the last case.", + "422": { + "description": "`test_venue_unavailable`. The project is in `environment=\"test\"` and this provider cannot be exercised there: its catalog entry classifies `test_venue` as `none` (the provider runs no test environment, so a call would land on production with a real effect) or `unclassified` (nobody has established what it does in test). Not a verdict on the credential and not retryable — the identical request from a `live` project reaches the provider (ent#722).", "content": { "application/json": { "schema": { "type": "object", "properties": { + "ok": { + "type": "boolean", + "enum": [ + false + ] + }, + "provider": { + "type": "string", + "description": "The provider id from the path." + }, "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "idempotency_key_conflict", - "mandate_not_active" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "test_venue_unavailable" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "detail": { + "type": "string", + "description": "A CodeSpar-authored sentence naming the catalog file and the field to declare. Never provider text — no round trip was made." } }, "required": [ + "ok", + "provider", "error", - "request_id" + "detail" ] } } } }, - "500": { - "description": "Invariant break: the flow is recorded as issued and there is no readable card row behind it.", + "424": { + "description": "`not_connected`. There is nothing to verify: either no active connection exists for this project and provider, or one exists and its stored credential did not resolve to a value. Connect the provider, or reconnect it.", "content": { "application/json": { "schema": { "type": "object", "properties": { + "ok": { + "type": "boolean", + "enum": [ + false + ] + }, + "provider": { + "type": "string", + "description": "The provider id from the path." + }, "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "issuer_card_unknown" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "not_connected" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "detail": { + "type": "string", + "description": "A CodeSpar-authored diagnostic naming which of the two cases happened, NOT provider text: `No active connection found for this project + server.`, `Vault returned no value for the connection's credential ref.`, or a sentence naming the specific credential parts that failed to resolve." + }, + "latency_ms": { + "type": "integer", + "description": "Present only when the probe path produced this outcome, since only that path timed anything. Absent on the resolver's own branches." + }, + "authType": { + "type": "string", + "description": "The provider's declared auth mechanism, on the branch where no connection exists at all. It is what tells a caller whether connecting is even self-serve: `cert`, `hmac_signed`, `jwt_ecdsa` and `two_header` all need material an operator has to obtain out of band." + }, + "hint": { + "type": "string", + "description": "Added by the route to this code only, so a stuck agent has a next move rather than a connect dead end: it points at the pre-connected sandbox Pix rails." + }, + "alternative": { + "type": "string", + "description": "The meta-tool to call instead." + }, + "caveat": { + "type": "string", + "description": "Added only for a `cert` provider in the test environment, where the rail cannot run at all." } }, "required": [ + "ok", + "provider", "error", - "request_id" + "hint", + "alternative" + ] + } + } + } + }, + "501": { + "description": "`verify_unsupported`. This provider ships neither a bespoke recipe nor a declared probe, so there is no safe read to issue. Nothing is wrong with the credential and nothing about it has been learned; the first real call is where authentication errors will surface.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "ok": { + "type": "boolean", + "enum": [ + false + ] + }, + "provider": { + "type": "string", + "description": "The provider id from the path." + }, + "error": { + "type": "string", + "enum": [ + "verify_unsupported" + ] + }, + "detail": { + "type": "string", + "description": "A CodeSpar-authored sentence naming this provider, not provider text. No outbound call was made on this branch, which is why there is no `status` and no `latency_ms`." + } + }, + "required": [ + "ok", + "provider", + "error" ] } } } }, "502": { - "description": "The issuer refused or failed the issuance; or the card was issued and the ingest into the data environment failed. In the second case the card EXISTS and comes in `details.card`; repeat with the SAME key.", + "description": "`provider_unreachable`. EVERY non-2xx that is not a redirect and not a 401 or 403 lands here, together with network failures and the per-call timeout (10 seconds by default, deployment-configurable). That includes a provider's 400, 404, 409, 422 and 429. Only some of those are worth retrying, and `status` is the field that separates them.", "content": { "application/json": { "schema": { "type": "object", "properties": { + "ok": { + "type": "boolean", + "enum": [ + false + ] + }, + "provider": { + "type": "string", + "description": "The provider id from the path." + }, "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "issuer_mint_failed", - "issuer_ingest_failed" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "provider_unreachable" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "status": { + "type": "integer", + "description": "The provider's own status, when there WAS a response. ABSENT when the call never completed — connection failure, DNS, or the timeout — which is the one case where a plain retry is the right move." + }, + "latency_ms": { + "type": "integer", + "description": "Wall-clock milliseconds around the outbound call." + }, + "detail": { + "type": "string", + "description": "The provider's OWN response body, truncated to 256 characters, when a response arrived. When none did, the network error's message instead. The second of the two codes whose `detail` can carry provider text." } }, "required": [ + "ok", + "provider", "error", - "request_id" + "latency_ms" ] } } } }, "503": { - "description": "The issuer's credentials could not be read from the vault.", + "description": "`endpoint_missing`. The provider is in the catalog but the row that says where to reach it is missing or contradicts how the connection was stored. A catalog or connection problem on our side, not a verdict on the credential and not a provider outage.", "content": { "application/json": { "schema": { "type": "object", "properties": { + "ok": { + "type": "boolean", + "enum": [ + false + ] + }, + "provider": { + "type": "string", + "description": "The provider id from the path." + }, "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "vault_unavailable" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "endpoint_missing" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "detail": { + "type": "string", + "description": "ABSENT on the resolver's branch, which sends the three keys above and nothing else. Present only where a handler branch wrote a CodeSpar-authored sentence describing the mismatch. Never provider text." } }, "required": [ - "error", - "request_id" + "ok", + "provider", + "error" ] } } } } }, - "x-codespar-scope": "cards:issue", + "x-codespar-scope": "connections:write", "security": [ { "bearerAuth": [ - "cards:issue" + "connections:write" ] } ] } }, - "/v1/cards/{id}": { - "get": { + "/v1/cards": { + "post": { "externalDocs": { - "url": "https://github.com/codespar/codespar-enterprise/issues/979", - "description": "ent#979: canonical path and alias window" + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" }, - "summary": "Read an issued card, or the mint flow that is producing one", - "description": "ONE PATH, TWO RESOURCES, chosen by the id's prefix. An id beginning `imf_` is a MINT FLOW and the response is the flow. Anything else is looked up as a card row and the response is the card. There is no query parameter and no header that changes this: the prefix is the whole dispatch, so a client has to be ready for both bodies on one operation.\n\nA flow that reached `issued` and already points at a card row answers with the flow PLUS a `card` key. No other flow state carries that key at all. So the polling loop after a mint is: read the flow id, and when `state` is `issued`, read `card`.\n\nSCOPING. Both lookups carry the caller's org and project in the WHERE clause. A card or flow belonging to a sibling project of the same org is indistinguishable from one that was never created: both are 404, with the same code.\n\nNO CARD-NUMBER MATERIAL crosses this surface. `last4` and, once ingest lands, `token_id` are what a card exposes; the number itself lives only in the cardholder-data environment and is never part of this response.\n\nThe canonical path. `GET /v1/issuer/cards/{id}` is the same handler at the path that shipped first, kept for two releases and not described in this document.", + "summary": "Issue a card (pomelo_brl or rain_usd)", + "description": "Issues a card of the program chosen by `currency` (BRL -> `pomelo_brl`, USD -> `rain_usd`), or of `provider`'s program when given.\n\n**For an API key or an OAuth token only**, holding `cards:issue`. Every call, a retry included, checks server-side: the mandate (this project's, the consumer's, active, unexpired, in the card currency), the key bound to the mandate, the holder approved by the issuer, the current terms accepted by the competent person, and an unrevoked authorization for automated issuance for (holder, program) granted in the dashboard.\n\n**`Idempotency-Key` is required.** The first call binds the key to the program chosen then; a retry with the same key uses the RECORDED program even if the default or the availability changed, and never issues a second card. The same key with another body is `409 idempotency_key_conflict`.\n\n**`202` is a person's action pending**, with a stable `pending_action`; nothing is ever accepted on a person's behalf. Repeat the same request after the action: it re-validates and resumes the SAME operation.\n\nThe Pomelo holder is built by the server from what the account already holds plus the holder's profile; what is missing is a 202 `complete_holder_profile` naming exactly the missing fields (`PUT /v1/cards/holder-profiles/{consumer_id}`), after which the SAME request resumes. An API caller MAY send `holder` for `pomelo_brl` instead; `rain_usd` refuses it (its holder is read from the Rain records). Live projects are refused (`card_issuer_unavailable`, reason `live_blocked`).", "parameters": [ { "schema": { "type": "string", - "description": "A card row id, or an `imf_` prefixed mint flow id. The prefix selects which." + "minLength": 1, + "maxLength": 255, + "description": "Required. Binds the request to its program; a retry never issues twice." }, "required": true, - "description": "A card row id, or an `imf_` prefixed mint flow id. The prefix selects which.", - "name": "id", - "in": "path" + "description": "Required. Binds the request to its program; a retry never issues twice.", + "name": "Idempotency-Key", + "in": "header" } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "currency": { + "type": "string", + "pattern": "^[A-Z]{3}$" + }, + "provider": { + "type": [ + "string", + "null" + ], + "minLength": 1, + "maxLength": 32 + }, + "mandate_id": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "consumer_id": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "holder": { + "type": "object", + "properties": { + "full_name": { + "type": "string", + "minLength": 1, + "maxLength": 140 + }, + "email": { + "type": "string", + "format": "email" + }, + "birthdate": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + }, + "document": { + "type": "object", + "properties": { + "type": { + "type": "string", + "minLength": 1, + "maxLength": 16 + }, + "value": { + "type": "string", + "minLength": 1, + "maxLength": 32 + }, + "issuing_country": { + "type": "string", + "pattern": "^[A-Z]{2}$" + } + }, + "required": [ + "type", + "value", + "issuing_country" + ] + }, + "address": { + "type": "object", + "properties": { + "line1": { + "type": "string", + "minLength": 1, + "maxLength": 140 + }, + "line2": { + "type": "string", + "maxLength": 140 + }, + "street_number": { + "type": "string", + "minLength": 1, + "maxLength": 20 + }, + "neighborhood": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "city": { + "type": "string", + "minLength": 1, + "maxLength": 80 + }, + "state": { + "type": "string", + "maxLength": 40 + }, + "postal_code": { + "type": "string", + "minLength": 1, + "maxLength": 20 + }, + "municipality": { + "type": "string", + "minLength": 1, + "maxLength": 40 + }, + "country": { + "type": "string", + "pattern": "^[A-Z]{2}$" + } + }, + "required": [ + "line1", + "city", + "postal_code", + "country" + ] + }, + "phone": { + "type": "string", + "pattern": "^\\+[1-9]\\d{6,14}$" + } + }, + "required": [ + "full_name", + "email", + "birthdate", + "document", + "address" + ] + } + }, + "required": [ + "currency", + "mandate_id", + "consumer_id" + ], + "additionalProperties": false + } + } + } + }, "responses": { "200": { "description": "OK", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "issued" + ] + }, + "issue_request_id": { + "type": "string" + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], + "enum": [ + "pomelo", + "rain" + ], + "description": "The `provider` the first call asked for; null when the program was chosen by currency." + }, + "chosen_by": { + "type": "string", + "enum": [ + "provider", + "currency" + ] + } + }, + "required": [ + "provider_requested", + "chosen_by" + ] + }, + "mandate_id": { + "type": "string" + }, + "consumer_id": { + "type": "string" + }, + "card": { "type": "object", "properties": { "id": { "type": "string", - "description": "CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves." + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." }, "issuer": { "type": "string", "enum": [ "pomelo", - "bridge" - ], - "description": "Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118)." - }, - "card_id": { - "type": "string", - "description": "The issuer's own identifier for the card, as it was returned to us." + "rain" + ] }, - "last4": { + "program": { "type": "string", - "description": "The last four digits. No other card-number material exists on this surface." + "enum": [ + "pomelo_brl", + "rain_usd" + ] }, - "network": { + "currency": { "type": "string", "enum": [ - "visa", - "mastercard" + "BRL", + "USD" ], - "description": "`CHECK (network IN ('visa', 'mastercard'))`, migration 0118." + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." }, "status": { "type": "string", "enum": [ + "pending", + "not_activated", "active", "blocked", "canceled" - ], - "description": "`IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118." + ] + }, + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." }, - "token_id": { + "last4": { "type": [ "string", "null" - ], - "description": "The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ] - }, - { - "type": "object", - "properties": { - "flow_id": { - "type": "string", - "description": "`imf_` prefixed. The row it names is keyed by the mint call's `Idempotency-Key`, or by a server-minted one when that header was absent." + ] }, - "state": { - "type": "string", - "enum": [ - "pending", - "issued", - "revoked", - "failed" + "network": { + "type": [ + "string", + "null" ], - "description": "`MintFlowState`, and `CHECK (state IN ('pending', 'issued', 'revoked', 'failed'))` in 0118." - }, - "issuer": { - "type": "string", "enum": [ - "pomelo", - "bridge" + "visa", + "mastercard" ] }, - "reason": { + "mandate_id": { "type": [ "string", "null" - ], - "description": "Why the flow is parked, when it is parked. Null otherwise." + ] }, - "kyc_url": { + "consumer_id": { "type": [ "string", "null" - ], - "description": "Where the holder finishes identity verification, when the issuer asked for one. Null otherwise." + ] }, "created_at": { "type": "string", "format": "date-time" }, - "card": { - "type": [ - "object", - "null" - ], + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + }, + "funding": { + "type": "object", "properties": { - "id": { + "asset": { "type": "string", - "description": "CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves." - }, - "issuer": { + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] + } + }, + "required": [ + "id", + "issuer", + "program", + "currency", + "status", + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", + "created_at", + "available_actions" + ] + }, + "authorization_id": { + "type": [ + "string", + "null" + ], + "description": "The automated issuance authorization in force when the issuer was called." + }, + "authorization_active": { + "type": [ + "boolean", + "null" + ], + "description": "Whether that authorization still stands. An issued card is never undone; a revocation since is reported here." + } + }, + "required": [ + "state", + "issue_request_id", + "issuer", + "program", + "selection", + "mandate_id", + "consumer_id", + "card", + "authorization_id", + "authorization_active" + ], + "description": "A retry of a request already issued: the same card." + } + } + } + }, + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "issued" + ] + }, + "issue_request_id": { + "type": "string" + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], + "enum": [ + "pomelo", + "rain" + ], + "description": "The `provider` the first call asked for; null when the program was chosen by currency." + }, + "chosen_by": { + "type": "string", + "enum": [ + "provider", + "currency" + ] + } + }, + "required": [ + "provider_requested", + "chosen_by" + ] + }, + "mandate_id": { + "type": "string" + }, + "consumer_id": { + "type": "string" + }, + "card": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" + ], + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + }, + "status": { + "type": "string", + "enum": [ + "pending", + "not_activated", + "active", + "blocked", + "canceled" + ] + }, + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." + }, + "last4": { + "type": [ + "string", + "null" + ] + }, + "network": { + "type": [ + "string", + "null" + ], + "enum": [ + "visa", + "mastercard" + ] + }, + "mandate_id": { + "type": [ + "string", + "null" + ] + }, + "consumer_id": { + "type": [ + "string", + "null" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + }, + "funding": { + "type": "object", + "properties": { + "asset": { "type": "string", + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] + } + }, + "required": [ + "id", + "issuer", + "program", + "currency", + "status", + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", + "created_at", + "available_actions" + ] + }, + "authorization_id": { + "type": [ + "string", + "null" + ], + "description": "The automated issuance authorization in force when the issuer was called." + }, + "authorization_active": { + "type": [ + "boolean", + "null" + ], + "description": "Whether that authorization still stands. An issued card is never undone; a revocation since is reported here." + } + }, + "required": [ + "state", + "issue_request_id", + "issuer", + "program", + "selection", + "mandate_id", + "consumer_id", + "card", + "authorization_id", + "authorization_active" + ] + } + } + } + }, + "202": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "pending_human" + ], + "description": "A person must act; nothing was sent to the issuer for this request since the last answer." + }, + "issue_request_id": { + "type": "string" + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], "enum": [ "pomelo", - "bridge" + "rain" ], - "description": "Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118)." + "description": "The `provider` the first call asked for; null when the program was chosen by currency." }, - "card_id": { + "chosen_by": { "type": "string", - "description": "The issuer's own identifier for the card, as it was returned to us." - }, - "last4": { + "enum": [ + "provider", + "currency" + ] + } + }, + "required": [ + "provider_requested", + "chosen_by" + ] + }, + "mandate_id": { + "type": "string" + }, + "consumer_id": { + "type": "string" + }, + "pending_action": { + "type": "object", + "properties": { + "id": { "type": "string", - "description": "The last four digits. No other card-number material exists on this surface." + "description": "Stable for the same issue request and kind." }, - "network": { + "kind": { "type": "string", "enum": [ - "visa", - "mastercard" - ], - "description": "`CHECK (network IN ('visa', 'mastercard'))`, migration 0118." + "issuer_kyc", + "accept_terms", + "authorize_automated_issuance", + "bind_key_to_mandate", + "complete_holder_profile" + ] }, - "status": { + "actor": { "type": "string", "enum": [ - "active", - "blocked", - "canceled" + "holder", + "company_signatory", + "org_admin" ], - "description": "`IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118." + "description": "`holder` acts for themselves (personal terms, KYC); `company_signatory` signs for the company (PJ) or the holder (PF) authorizes issuance; `org_admin` configures." }, - "token_id": { + "url": { "type": [ "string", "null" ], - "description": "The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet." + "description": "Where the person acts: the issuer's KYC link, or the dashboard page of this issue request. Null when the deployment has no dashboard URL." }, - "cde": { - "type": "string", + "missing_fields": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "document", + "full_name", + "email", + "birthdate", + "address.line1", + "address.city", + "address.postal_code" + ] + }, + "description": "complete_holder_profile only: exactly the holder fields still missing. `document` means the account's onboarding (KYC) is not finished." + } + }, + "required": [ + "id", + "kind", + "actor", + "url" + ] + } + }, + "required": [ + "state", + "issue_request_id", + "issuer", + "program", + "selection", + "mandate_id", + "consumer_id", + "pending_action" + ] + }, + { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "processing", + "uncertain" + ], + "description": "`processing`: the issuer is being called. `uncertain`: a timeout or an ambiguous answer, the card MAY exist; a retry with the same key reconciles on the same issuer reference and never issues a second card." + }, + "issue_request_id": { + "type": "string" + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], "enum": [ - "ingested", - "not_ingested", - "not_configured" + "pomelo", + "rain" ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." + "description": "The `provider` the first call asked for; null when the program was chosen by currency." }, - "created_at": { + "chosen_by": { "type": "string", - "format": "date-time" + "enum": [ + "provider", + "currency" + ] } }, "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ], - "description": "PRESENT ONLY when `state` is `issued` AND the flow already points at a card row. In every other case the key is absent rather than null. Null inside that case means the card row did not resolve under this org and project." + "provider_requested", + "chosen_by" + ] + }, + "mandate_id": { + "type": "string" + }, + "consumer_id": { + "type": "string" + }, + "retry_after_seconds": { + "type": "integer" + }, + "note": { + "type": "string" + }, + "issuer_code": { + "type": "string" } }, "required": [ - "flow_id", "state", + "issue_request_id", "issuer", - "reason", - "kyc_url", - "created_at" + "program", + "selection", + "mandate_id", + "consumer_id", + "retry_after_seconds" ] } - ], - "description": "The card, when the id is a card id; the mint flow, when the id begins `imf_`." + ] } } } }, - "404": { - "description": "`issuer_card_unknown` for both misses, with different messages: `mint flow not found` for an `imf_` id and `issuer card not found` otherwise. One code, so a client cannot tell a wrong id from another project's id by reading the code.", + "400": { + "description": "The body or the key is malformed.", "content": { "application/json": { "schema": { @@ -25893,7 +26792,8 @@ "code": { "type": "string", "enum": [ - "issuer_card_unknown" + "invalid_body", + "idempotency_key_required" ] }, "message": { @@ -25924,114 +26824,104 @@ } } } - } - }, - "x-codespar-scope": "cards:read", - "security": [ - { - "bearerAuth": [ - "cards:read" - ] - } - ] - } - }, - "/v1/counterparties/{id}": { - "get": { - "externalDocs": { - "url": "https://github.com/codespar/codespar-enterprise/issues/979", - "description": "ent#979: canonical path and alias window" - }, - "summary": "Read one counterparty", - "description": "The same row the list returns, by id.\n\nA counterparty that belongs to another org, or to a sibling project of the same org, is indistinguishable from one that does not exist: both are 404. Counterparty ids are unique per project and not globally, so the same id can name a different company in another project.\n\nThe canonical path. `GET /v1/commerce-memory/counterparties/{id}` is the deprecated alias of this operation, described in this document under that path and kept for two releases. The two paths are the same handler with the same required scope, so switching one for the other changes nothing about the request, the response or the credential.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "`cp_` prefixed." - }, - "required": true, - "description": "`cp_` prefixed.", - "name": "id", - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", + }, + "401": { + "description": "No API key behind the request.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "`cp_` prefixed." - }, - "kind": { - "type": "string", - "enum": [ - "supplier", - "customer", - "agent_peer" - ], - "description": "`CHECK (kind IN ('supplier', 'customer', 'agent_peer'))`, migration 0050." - }, - "name": { - "type": "string" + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_connection_key_unknown" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] }, - "identifier": { + "request_id": { "type": [ "string", "null" ], - "description": "Null when the counterparty was registered without one." + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "403": { + "description": "The caller may not issue: a service caller, a key without `cards:issue`, an OAuth token whose consent key is not bound to the mandate and listed in its authorization, or a mandate paused, revoked or expired.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_issue_requires_api_key", + "card_scope_missing", + "card_oauth_not_bound", + "mandate_paused", + "mandate_revoked", + "mandate_expired" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] }, - "identifier_kind": { + "request_id": { "type": [ "string", "null" ], - "enum": [ - "cnpj", - "cpf", - "email", - "phone", - "wallet_address", - "other" - ], - "description": "`CHECK (identifier_kind IN ('cnpj', 'cpf', 'email', 'phone', 'wallet_address', 'other'))`, migration 0050. Null exactly when `identifier` is null: the pair is held together by `commerce_counterparties_identifier_pair`, a table constraint, so one without the other cannot be stored." - }, - "metadata": { - "type": "object", - "additionalProperties": {} - }, - "created_at": { - "type": "string", - "format": "date-time" - }, - "last_seen_at": { - "type": "string", - "format": "date-time", - "description": "Bumped by a re-registration of the same identifier and by every interaction recorded against this row." + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "id", - "kind", - "name", - "identifier", - "identifier_kind", - "metadata", - "created_at", - "last_seen_at" + "error", + "request_id" ] } } } }, "404": { - "description": "`not_found`, including for a counterparty outside the caller's project.", + "description": "No mandate with that id in this project.", "content": { "application/json": { "schema": { @@ -26043,7 +26933,7 @@ "code": { "type": "string", "enum": [ - "not_found" + "card_mandate_not_found" ] }, "message": { @@ -26074,173 +26964,251 @@ } } } - } - }, - "x-codespar-scope": "commerce-memory:read", - "security": [ - { - "bearerAuth": [ - "commerce-memory:read" - ] - } - ] - } - }, - "/v1/servers/{id}/auth-schema": { - "get": { - "deprecated": true, - "externalDocs": { - "url": "https://github.com/codespar/codespar-enterprise/issues/979", - "description": "ent#979: canonical path and alias window" - }, - "summary": "Read the credential form a provider needs, without reading any credential", - "description": "What to ask an operator for before connecting this provider, and where the request will go once connected. It NEVER returns a stored secret: the vault is write-only from this side, and `fields` describes inputs to collect, not values that exist.\n\nAN EMPTY `fields` DOES NOT MEAN NOTHING TO DO. `oauth` collects nothing here because the browser leg starts at `POST /v1/connections/start` instead, and `none` needs no credential. Every other type returns one field per catalog-declared ref, which is exactly the key set `POST /v1/connections` validates the secret object against: `jwt_ecdsa` asks for the CDP API key name and its private key, `cdp` for the CDP API key id, API key secret and wallet secret. Both CDP forms are served only where the deployment enables CDP self-serve connect (`CDP_SELF_SERVE_CONNECT`, off by default); otherwise they come back empty. A form type whose catalog row declares no refs comes back empty and cannot be connected; `connectable` on `GET /v1/servers` already says so per row.\n\n`base_url` IS ENVIRONMENT-RESOLVED against the credential in hand: a test key sees the provider's test host when the catalog declares one, and the live host otherwise. It is the empty string when the provider has no endpoint row, which is a catalog gap rather than a value to dial.\n\nThis is the path that shipped first; `GET /v1/providers/{slug}/auth-schema` is the same handler at the canonical path (ent#979) and is not yet described in this document, so the full response is described HERE and nothing is withheld until you switch paths.\n\nThe visibility gate in front of this operation only hides GENERATED providers (ids prefixed `gen_`) that belong to another project. Any id without that prefix passes the gate, including an id that names no provider at all. Past the gate, a provider that is genuinely absent from the catalog is a 404 as well, so this operation does distinguish a real provider from an invented one.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "The provider id, which is also the catalog row's primary key." - }, - "required": true, - "description": "The provider id, which is also the catalog row's primary key.", - "name": "id", - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", + }, + "409": { + "description": "The key was used with another body; the request failed for good at the issuer; one card per mandate; the holder or the terms do not allow it; the program's card limit; or the issuer's attempt is still open (retry with the same key).", "content": { "application/json": { "schema": { "type": "object", "properties": { - "server_id": { - "type": "string" - }, - "auth_type": { - "type": "string", - "description": "LEFT OPEN ON PURPOSE, and the reason is measured rather than cautious. The column admits nine values today — `api_key`, `path_secret`, `oauth`, `cert`, `none`, `hmac_signed`, `jwt_ecdsa`, `two_header`, `cdp` — under a CHECK constraint that has been widened four times (migrations 0064, 0066, 0074, 0091, over the six of 0026). The handler casts the column straight into this field, so the set of values a client can receive is the DB's, not any narrower published enum. Closing this to six would describe a wire that already carries more." + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "idempotency_key_conflict", + "card_issue_request_failed", + "card_mandate_already_bound", + "card_holder_not_eligible", + "card_terms_policy_missing", + "card_limit_reached", + "card_issue_in_progress" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] }, - "environment": { - "type": "string", - "enum": [ - "live", - "test" + "request_id": { + "type": [ + "string", + "null" ], - "description": "Taken from the calling credential, and what `base_url` was resolved against." - }, - "base_url": { - "type": "string", - "description": "The host a call to this provider will be sent to, in the caller's environment. Empty string when the provider has no endpoint row." + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "422": { + "description": "No program for the currency/provider, the program is unavailable (`details.reason`, `details.available_programs`), the mandate cannot back the card, or the issuer refused the card.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_program_not_found", + "card_issuer_unavailable", + "card_mandate_not_eligible", + "card_issue_refused" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] }, - "oauth_authorize_url": { + "request_id": { "type": [ "string", "null" ], - "description": "Where the browser leg starts, environment-resolved the same way. Null for every auth type other than `oauth`, and also null for an `oauth` provider with no configuration row." - }, - "fields": { - "type": "array", - "items": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The key to submit this value under when the connection is created. For a header-bearing field it is derived from the catalog's ref name, not from the header." - }, - "kind": { - "type": "string", - "enum": [ - "api_key", - "path_secret", - "header", - "cert" - ], - "description": "What input to render. These four are the whole set the handler can emit: it builds `AuthSchemaField[]`, so a fifth kind would not compile. `hmac_signed` reuses `path_secret` and `two_header` reuses `header` rather than each having its own." - }, - "label": { - "type": "string", - "description": "Human-readable label. For a header field it is the header name itself." - }, - "header_name": { - "type": "string", - "description": "Present only on `header` fields, naming the HTTP header the value is stamped under." - } + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "502": { + "description": "The issuer failed the request; repeat with the same key.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" }, - "required": [ - "name", - "kind", - "label" - ] + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } }, - "description": "In the order the form should render, which is the catalog's declared order: the visible field before the masked one for the multi-field types." + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "server_id", - "auth_type", - "environment", - "base_url", - "oauth_authorize_url", - "fields" + "error", + "request_id" ] } } } }, - "404": { - "description": "The provider is not visible to this project. Not the `apiError` envelope and not `{ error: \"not_found\" }`: a third shape, built at the route.", + "503": { + "description": "The issuer's lane or credentials could not be reached; nothing was issued.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "server_unknown" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_issuer_unavailable", + "vault_unavailable" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "server_id": { - "type": "string", - "description": "Echoes the id from the path." + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "server_id" + "request_id" ] } } } } }, - "x-codespar-scope": "servers:read", + "x-codespar-scope": "cards:issue", "security": [ { "bearerAuth": [ - "servers:read" + "cards:issue" ] } ] - } - }, - "/v1/servers/{id}/tools": { + }, "get": { - "summary": "List the tools a provider exposes", - "description": "Every tool registered for this provider, ordered by name, with no limit and no cursor: `total` is the length of `tools` and the two cannot disagree.\n\nAN UNKNOWN PROVIDER IS 200 HERE, NOT 404, and it is the one thing worth knowing about this operation. The visibility gate in front of this operation only hides GENERATED providers (ids prefixed `gen_`) that belong to another project. Any id without that prefix passes the gate, including an id that names no provider at all. There is no second check after it, so an id that names nothing reaches the tool query, matches no rows, and comes back as a well-formed empty list with that id echoed in `server_id`. An empty `tools` therefore means either a real provider with nothing registered or a provider that does not exist, and this response cannot tell you which. The 404 below is reachable only for another project's generated provider.", + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "List the project's cards, both issuers", + "description": "The project's Pomelo and Rain cards, most recent first, as card views. Requires `cards:read`.", "parameters": [ { "schema": { "type": "string", - "description": "The provider id." + "enum": [ + "pomelo", + "rain" + ] }, - "required": true, - "description": "The provider id.", - "name": "id", - "in": "path" + "required": false, + "name": "issuer", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "mandate_id", + "in": "query" + }, + { + "schema": { + "type": "string" + }, + "required": false, + "name": "consumer_id", + "in": "query" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "description": "1 to 200; the default is 50." + }, + "required": false, + "description": "1 to 200; the default is 50.", + "name": "limit", + "in": "query" } ], "responses": { @@ -26251,105 +27219,198 @@ "schema": { "type": "object", "properties": { - "server_id": { - "type": "string", - "description": "Echoes the id from the path, whether or not it named anything." - }, - "total": { - "type": "integer", - "description": "Always equal to the length of `tools`." - }, - "tools": { + "cards": { "type": "array", "items": { "type": "object", "properties": { - "name": { + "id": { "type": "string", - "description": "The tool name, and the sort key of this list." + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." }, - "description": { + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" + ], + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + }, + "status": { + "type": "string", + "enum": [ + "pending", + "not_activated", + "active", + "blocked", + "canceled" + ] + }, + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." + }, + "last4": { + "type": [ + "string", + "null" + ] + }, + "network": { "type": [ "string", "null" ], - "description": "Null when the catalog carries none." + "enum": [ + "visa", + "mastercard" + ] + }, + "mandate_id": { + "type": [ + "string", + "null" + ] + }, + "consumer_id": { + "type": [ + "string", + "null" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + }, + "funding": { + "type": "object", + "properties": { + "asset": { + "type": "string", + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] } }, "required": [ - "name", - "description" + "id", + "issuer", + "program", + "currency", + "status", + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", + "created_at", + "available_actions" ] } } }, "required": [ - "server_id", - "total", - "tools" + "cards" ] } } } }, - "404": { - "description": "The provider is not visible to this project. Not the `apiError` envelope and not `{ error: \"not_found\" }`: a third shape, built at the route.", + "400": { + "description": "The query did not match the schema.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "server_unknown" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_query" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "server_id": { - "type": "string", - "description": "Echoes the id from the path." + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "server_id" + "request_id" ] } } } } }, - "x-codespar-scope": "servers:read", + "x-codespar-scope": "cards:read", "security": [ { "bearerAuth": [ - "servers:read" + "cards:read" ] } ] } }, - "/v1/servers/{id}/verify-connection": { - "post": { - "deprecated": true, + "/v1/cards/programs": { + "get": { "externalDocs": { - "url": "https://github.com/codespar/codespar-enterprise/issues/979", - "description": "ent#979: canonical path and alias window" + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" }, - "summary": "Ask the provider whether this project's stored credential still works", - "description": "Issues ONE safe read against the provider using the credential this project has stored for it, and reports what came back. POST because it leaves the process and spends a provider call, not because it changes anything here: no state of yours is altered by it. It takes NO REQUEST BODY, and anything sent is ignored.\n\nWHICH READ depends on the provider. A handful ship a bespoke recipe, and those are the ones that can return an `account` summary. Everything else re-runs the provider's declared functional probe, the same authenticated read used to confirm a sandbox works when it is first set up; that path returns no `account`. A provider with neither answers 501.\n\nREAD THE STATUS, NOT THE BODY, TO DECIDE WHAT TO DO. Seven failure codes map onto seven distinct statuses, and only ONE of them is worth retrying unchanged (502). 401 is a verdict on the credential; 424 means there is no connection to test yet; 409 means the host redirected and never judged the credential, so a retry gets the same non-answer; 501 and 503 are configuration, not weather.\n\nTHE 502 IS WIDER THAN ITS NAME. `provider_unreachable` is what every non-2xx that is not a redirect and not a 401 or 403 becomes, so a provider answering 400, 404, 409, 422 or 429 arrives here as 502 with the provider's own status in `status`. An agent that retries every 502 will retry a 429 sensibly and a 400 forever. Read `status` before deciding.\n\nTWO DIFFERENT BODIES SHARE THE 404, from two different lines: the visibility gate's `{ error, server_id }`, and the verify outcome's `{ ok: false, provider, error }` when the credential resolver finds no such provider in the catalog. Both are described below.\n\nThis is the path that shipped first; `POST /v1/providers/{slug}/verify-connection` is the same handler at the canonical path (ent#979) and is not yet described in this document.\n\nThe visibility gate in front of this operation only hides GENERATED providers (ids prefixed `gen_`) that belong to another project. Any id without that prefix passes the gate, including an id that names no provider at all.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "The provider id." - }, - "required": true, - "description": "The provider id.", - "name": "id", - "in": "path" - } - ], + "summary": "The card programs and their availability in this project", + "description": "Each program with whether it can issue now in the caller's project and environment and, when not, why. Available = its Card issuing integration is connected (verified), the project is Test, the issuer is enabled and the account is eligible. Requires `cards:read`.", "responses": { "200": { "description": "OK", @@ -26358,134 +27419,369 @@ "schema": { "type": "object", "properties": { - "ok": { - "type": "boolean", - "enum": [ - true - ] - }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, - "account": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - }, - "extras": { - "type": "object", - "additionalProperties": {}, - "description": "Whatever the provider's recipe chose to surface, keyed by that provider's own names." - } - }, - "description": "ABSENT on the probe path, and absent on the recipe path whenever the recipe found nothing it recognised in the response. Present means the read reached a real account; absent does NOT mean it did not." - }, - "latency_ms": { - "type": "integer", - "description": "Wall-clock milliseconds around the outbound call." - } - }, - "required": [ - "ok", - "provider", - "latency_ms" - ] - } - } - } - }, - "401": { - "description": "`provider_rejected`. The provider answered 401 or 403: it looked at the credential and said no. Retrying unchanged will fail the same way.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "enum": [ - false - ] - }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, - "error": { + "market": { "type": "string", "enum": [ - "provider_rejected" - ] - }, - "status": { - "type": "integer", - "description": "The provider's own status, 401 or 403." + "BR" + ], + "description": "The account's market, derived server-side. Every account is BR today." }, - "latency_ms": { - "type": "integer", - "description": "Wall-clock milliseconds around the outbound call." - }, - "detail": { - "type": "string", - "description": "The provider's OWN response body, truncated to 256 characters, on the recipe path. On the probe path it is the probe's error text instead, with the credential masked out. This is one of only two codes where `detail` carries provider text." + "programs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" + ] + }, + "available": { + "type": "boolean" + }, + "reason": { + "type": "string", + "enum": [ + "not_configured", + "not_verified", + "verify_failed", + "live_blocked", + "account_not_eligible", + "issuer_disabled", + "issuer_not_supported" + ] + }, + "operations": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "issue", + "get", + "list", + "freeze", + "unfreeze", + "cancel" + ] + } + }, + "funding": { + "type": "object", + "properties": { + "asset": { + "type": "string", + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] + } + }, + "required": [ + "program", + "issuer", + "currency", + "available", + "operations" + ] + } } }, "required": [ - "ok", - "provider", - "error", - "status", - "latency_ms" + "market", + "programs" ] } } } + } + }, + "x-codespar-scope": "cards:read", + "security": [ + { + "bearerAuth": [ + "cards:read" + ] + } + ] + } + }, + "/v1/cards/readiness": { + "get": { + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "What is missing before a card can be issued", + "description": "Per program, each requirement of an issue and its status (`done`, `pending` with the actor who acts, `blocked` with the reason, `not_applicable`), optionally for one holder and mandate. Computed by the SAME function the issue runs, so this checklist and an issue's refusal never disagree. Read-only; a person session or an API key. Requires `cards:read`.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The holder." + }, + "required": false, + "description": "The holder.", + "name": "consumer_id", + "in": "query" }, - "403": { - "description": "`shared_sandbox_operation_refused` or `shared_sandbox_credential_not_test`. The project's connection is the platform's shared sandbox account. Test connection on it runs only the operation its provider lists for verify, with no account in the answer; a provider with none, or whose shared credential is not shown to be a test one, is refused before anything is sent. Not a verdict on a credential of yours: connect your own account for this provider.", + { + "schema": { + "type": "string", + "description": "The mandate the card would stand on; the authorization is bound to it." + }, + "required": false, + "description": "The mandate the card would stand on; the authorization is bound to it.", + "name": "mandate_id", + "in": "query" + }, + { + "schema": { + "type": "string", + "enum": [ + "automated", + "person" + ], + "description": "Default: `person` for a dashboard session, `automated` for an API key." + }, + "required": false, + "description": "Default: `person` for a dashboard session, `automated` for an API key.", + "name": "mode", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { - "ok": { - "type": "boolean", - "enum": [ - false - ] - }, - "provider": { + "mode": { "type": "string", - "description": "The provider id from the path." + "enum": [ + "automated", + "person" + ], + "description": "`automated`: an API key / OAuth issue. `person`: the competent person issuing in the dashboard, where bind_key_to_mandate and authorize_automated_issuance are not_applicable." }, + "programs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" + ] + }, + "ready": { + "type": "boolean" + }, + "requirements": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "environment", + "integration_connected", + "bind_key_to_mandate", + "complete_holder_profile", + "issuer_kyc", + "accept_terms", + "authorize_automated_issuance" + ] + }, + "status": { + "type": "string", + "enum": [ + "done", + "pending", + "blocked", + "not_applicable" + ] + }, + "actor": { + "type": "string", + "enum": [ + "holder", + "company_signatory", + "org_admin" + ] + }, + "action_url": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "pending_action_id": { + "type": "string", + "description": "The pending action of the open issue request on this mandate, when there is one." + }, + "missing_fields": { + "type": "array", + "items": { + "type": "string" + }, + "description": "complete_holder_profile: exactly the holder fields still missing." + }, + "mandate_id": { + "type": "string", + "description": "authorize_automated_issuance, with a mandate asked: the mandate the authorization binds to." + }, + "bound_api_key_ids": { + "type": "array", + "items": { + "type": "string" + }, + "description": "authorize_automated_issuance, with a mandate asked: the project's unrevoked API keys bound to it." + } + }, + "required": [ + "kind", + "status", + "actor" + ] + } + } + }, + "required": [ + "program", + "issuer", + "currency", + "ready", + "requirements" + ] + } + } + }, + "required": [ + "mode", + "programs" + ] + } + } + } + }, + "400": { + "description": "The query did not match the schema.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { "error": { - "type": "string", - "enum": [ - "shared_sandbox_operation_refused", - "shared_sandbox_credential_not_test" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_query" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "detail": { - "type": "string", - "description": "A CodeSpar-authored sentence. Never provider text." + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "ok", - "provider", - "error" + "error", + "request_id" ] } } } - }, - "404": { - "description": "Two shapes under one status. The route's own gate answers `{ error, server_id }` before any work happens; the credential resolver answers the verify outcome's `server_unknown` when the provider is absent from the catalog. Parse the union.", + } + }, + "x-codespar-scope": "cards:read", + "security": [ + { + "bearerAuth": [ + "cards:read" + ] + } + ] + } + }, + "/v1/cards/{id}": { + "get": { + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "Read a card, or an issue request", + "description": "A card id answers the card view. An issue request id (`cir_…`) answers its state: the pending action, the issued card, or the failure. Another project's id is indistinguishable from one that does not exist. Requires `cards:read`.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`)." + }, + "required": true, + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`).", + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", "content": { "application/json": { "schema": { @@ -26493,340 +27789,704 @@ { "type": "object", "properties": { - "error": { + "id": { + "type": "string", + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." + }, + "issuer": { "type": "string", "enum": [ - "server_unknown" + "pomelo", + "rain" ] }, - "server_id": { + "program": { "type": "string", - "description": "Echoes the id from the path." + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" + ], + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + }, + "status": { + "type": "string", + "enum": [ + "pending", + "not_activated", + "active", + "blocked", + "canceled" + ] + }, + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." + }, + "last4": { + "type": [ + "string", + "null" + ] + }, + "network": { + "type": [ + "string", + "null" + ], + "enum": [ + "visa", + "mastercard" + ] + }, + "mandate_id": { + "type": [ + "string", + "null" + ] + }, + "consumer_id": { + "type": [ + "string", + "null" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + }, + "funding": { + "type": "object", + "properties": { + "asset": { + "type": "string", + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] } }, "required": [ - "error", - "server_id" + "id", + "issuer", + "program", + "currency", + "status", + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", + "created_at", + "available_actions" ] }, { "type": "object", "properties": { - "ok": { - "type": "boolean", + "state": { + "type": "string", "enum": [ - false - ] + "pending_human" + ], + "description": "A person must act; nothing was sent to the issuer for this request since the last answer." }, - "provider": { + "issue_request_id": { + "type": "string" + }, + "issuer": { "type": "string", - "description": "The provider id from the path." + "enum": [ + "pomelo", + "rain" + ] }, - "error": { + "program": { "type": "string", "enum": [ - "server_unknown" + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], + "enum": [ + "pomelo", + "rain" + ], + "description": "The `provider` the first call asked for; null when the program was chosen by currency." + }, + "chosen_by": { + "type": "string", + "enum": [ + "provider", + "currency" + ] + } + }, + "required": [ + "provider_requested", + "chosen_by" + ] + }, + "mandate_id": { + "type": "string" + }, + "consumer_id": { + "type": "string" + }, + "pending_action": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Stable for the same issue request and kind." + }, + "kind": { + "type": "string", + "enum": [ + "issuer_kyc", + "accept_terms", + "authorize_automated_issuance", + "bind_key_to_mandate", + "complete_holder_profile" + ] + }, + "actor": { + "type": "string", + "enum": [ + "holder", + "company_signatory", + "org_admin" + ], + "description": "`holder` acts for themselves (personal terms, KYC); `company_signatory` signs for the company (PJ) or the holder (PF) authorizes issuance; `org_admin` configures." + }, + "url": { + "type": [ + "string", + "null" + ], + "description": "Where the person acts: the issuer's KYC link, or the dashboard page of this issue request. Null when the deployment has no dashboard URL." + }, + "missing_fields": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "document", + "full_name", + "email", + "birthdate", + "address.line1", + "address.city", + "address.postal_code" + ] + }, + "description": "complete_holder_profile only: exactly the holder fields still missing. `document` means the account's onboarding (KYC) is not finished." + } + }, + "required": [ + "id", + "kind", + "actor", + "url" ] } }, "required": [ - "ok", - "provider", - "error" - ] - } - ] - } - } - } - }, - "409": { - "description": "`redirect_not_followed`. The configured host answered 3xx. The probe is issued with redirects disabled on purpose, so the credential was never judged by anyone: this is the absence of a verdict, not a negative one. Retrying cannot change it; the host or the catalog entry has to.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "enum": [ - false - ] - }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, - "error": { - "type": "string", - "enum": [ - "redirect_not_followed" - ] - }, - "status": { - "type": "integer", - "description": "The 3xx the host answered with." - }, - "latency_ms": { - "type": "integer", - "description": "Wall-clock milliseconds around the outbound call." - } - }, - "required": [ - "ok", - "provider", - "error", - "status", - "latency_ms" - ] - } - } - } - }, - "422": { - "description": "`test_venue_unavailable`. The project is in `environment=\"test\"` and this provider cannot be exercised there: its catalog entry classifies `test_venue` as `none` (the provider runs no test environment, so a call would land on production with a real effect) or `unclassified` (nobody has established what it does in test). Not a verdict on the credential and not retryable — the identical request from a `live` project reaches the provider (ent#722).", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "enum": [ - false + "state", + "issue_request_id", + "issuer", + "program", + "selection", + "mandate_id", + "consumer_id", + "pending_action" ] }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, - "error": { - "type": "string", - "enum": [ - "test_venue_unavailable" - ] - }, - "detail": { - "type": "string", - "description": "A CodeSpar-authored sentence naming the catalog file and the field to declare. Never provider text — no round trip was made." - } - }, - "required": [ - "ok", - "provider", - "error", - "detail" - ] - } - } - } - }, - "424": { - "description": "`not_connected`. There is nothing to verify: either no active connection exists for this project and provider, or one exists and its stored credential did not resolve to a value. Connect the provider, or reconnect it.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "enum": [ - false - ] - }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, - "error": { - "type": "string", - "enum": [ - "not_connected" + { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "processing", + "uncertain" + ], + "description": "`processing`: the issuer is being called. `uncertain`: a timeout or an ambiguous answer, the card MAY exist; a retry with the same key reconciles on the same issuer reference and never issues a second card." + }, + "issue_request_id": { + "type": "string" + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], + "enum": [ + "pomelo", + "rain" + ], + "description": "The `provider` the first call asked for; null when the program was chosen by currency." + }, + "chosen_by": { + "type": "string", + "enum": [ + "provider", + "currency" + ] + } + }, + "required": [ + "provider_requested", + "chosen_by" + ] + }, + "mandate_id": { + "type": "string" + }, + "consumer_id": { + "type": "string" + }, + "retry_after_seconds": { + "type": "integer" + }, + "note": { + "type": "string" + }, + "issuer_code": { + "type": "string" + } + }, + "required": [ + "state", + "issue_request_id", + "issuer", + "program", + "selection", + "mandate_id", + "consumer_id", + "retry_after_seconds" ] }, - "detail": { - "type": "string", - "description": "A CodeSpar-authored diagnostic naming which of the two cases happened, NOT provider text: `No active connection found for this project + server.`, `Vault returned no value for the connection's credential ref.`, or a sentence naming the specific credential parts that failed to resolve." - }, - "latency_ms": { - "type": "integer", - "description": "Present only when the probe path produced this outcome, since only that path timed anything. Absent on the resolver's own branches." - }, - "authType": { - "type": "string", - "description": "The provider's declared auth mechanism, on the branch where no connection exists at all. It is what tells a caller whether connecting is even self-serve: `cert`, `hmac_signed`, `jwt_ecdsa` and `two_header` all need material an operator has to obtain out of band." - }, - "hint": { - "type": "string", - "description": "Added by the route to this code only, so a stuck agent has a next move rather than a connect dead end: it points at the pre-connected sandbox Pix rails." - }, - "alternative": { - "type": "string", - "description": "The meta-tool to call instead." - }, - "caveat": { - "type": "string", - "description": "Added only for a `cert` provider in the test environment, where the rail cannot run at all." - } - }, - "required": [ - "ok", - "provider", - "error", - "hint", - "alternative" - ] - } - } - } - }, - "501": { - "description": "`verify_unsupported`. This provider ships neither a bespoke recipe nor a declared probe, so there is no safe read to issue. Nothing is wrong with the credential and nothing about it has been learned; the first real call is where authentication errors will surface.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "enum": [ - false + { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "issued" + ] + }, + "issue_request_id": { + "type": "string" + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], + "enum": [ + "pomelo", + "rain" + ], + "description": "The `provider` the first call asked for; null when the program was chosen by currency." + }, + "chosen_by": { + "type": "string", + "enum": [ + "provider", + "currency" + ] + } + }, + "required": [ + "provider_requested", + "chosen_by" + ] + }, + "mandate_id": { + "type": "string" + }, + "consumer_id": { + "type": "string" + }, + "card": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" + ], + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + }, + "status": { + "type": "string", + "enum": [ + "pending", + "not_activated", + "active", + "blocked", + "canceled" + ] + }, + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." + }, + "last4": { + "type": [ + "string", + "null" + ] + }, + "network": { + "type": [ + "string", + "null" + ], + "enum": [ + "visa", + "mastercard" + ] + }, + "mandate_id": { + "type": [ + "string", + "null" + ] + }, + "consumer_id": { + "type": [ + "string", + "null" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + }, + "funding": { + "type": "object", + "properties": { + "asset": { + "type": "string", + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] + } + }, + "required": [ + "id", + "issuer", + "program", + "currency", + "status", + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", + "created_at", + "available_actions" + ] + }, + "authorization_id": { + "type": [ + "string", + "null" + ], + "description": "The automated issuance authorization in force when the issuer was called." + }, + "authorization_active": { + "type": [ + "boolean", + "null" + ], + "description": "Whether that authorization still stands. An issued card is never undone; a revocation since is reported here." + } + }, + "required": [ + "state", + "issue_request_id", + "issuer", + "program", + "selection", + "mandate_id", + "consumer_id", + "card", + "authorization_id", + "authorization_active" ] }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, - "error": { - "type": "string", - "enum": [ - "verify_unsupported" + { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "received", + "failed" + ] + }, + "issue_request_id": { + "type": "string" + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "selection": { + "type": "object", + "properties": { + "provider_requested": { + "type": [ + "string", + "null" + ], + "enum": [ + "pomelo", + "rain" + ], + "description": "The `provider` the first call asked for; null when the program was chosen by currency." + }, + "chosen_by": { + "type": "string", + "enum": [ + "provider", + "currency" + ] + } + }, + "required": [ + "provider_requested", + "chosen_by" + ] + }, + "failure_code": { + "type": "string" + } + }, + "required": [ + "state", + "issue_request_id", + "issuer", + "program", + "selection" ] - }, - "detail": { - "type": "string", - "description": "A CodeSpar-authored sentence naming this provider, not provider text. No outbound call was made on this branch, which is why there is no `status` and no `latency_ms`." } - }, - "required": [ - "ok", - "provider", - "error" ] } } } }, - "502": { - "description": "`provider_unreachable`. EVERY non-2xx that is not a redirect and not a 401 or 403 lands here, together with network failures and the per-call timeout (10 seconds by default, deployment-configurable). That includes a provider's 400, 404, 409, 422 and 429. Only some of those are worth retrying, and `status` is the field that separates them.", + "404": { + "description": "No card or issue request with that id in this project.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "ok": { - "type": "boolean", - "enum": [ - false - ] - }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, "error": { - "type": "string", - "enum": [ - "provider_unreachable" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_not_found" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "status": { - "type": "integer", - "description": "The provider's own status, when there WAS a response. ABSENT when the call never completed — connection failure, DNS, or the timeout — which is the one case where a plain retry is the right move." - }, - "latency_ms": { - "type": "integer", - "description": "Wall-clock milliseconds around the outbound call." - }, - "detail": { - "type": "string", - "description": "The provider's OWN response body, truncated to 256 characters, when a response arrived. When none did, the network error's message instead. The second of the two codes whose `detail` can carry provider text." + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "ok", - "provider", "error", - "latency_ms" - ] - } - } - } - }, - "503": { - "description": "`endpoint_missing`. The provider is in the catalog but the row that says where to reach it is missing or contradicts how the connection was stored. A catalog or connection problem on our side, not a verdict on the credential and not a provider outage.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "ok": { - "type": "boolean", - "enum": [ - false - ] - }, - "provider": { - "type": "string", - "description": "The provider id from the path." - }, - "error": { - "type": "string", - "enum": [ - "endpoint_missing" - ] - }, - "detail": { - "type": "string", - "description": "ABSENT on the resolver's branch, which sends the three keys above and nothing else. Present only where a handler branch wrote a CodeSpar-authored sentence describing the mismatch. Never provider text." - } - }, - "required": [ - "ok", - "provider", - "error" + "request_id" ] } } } } }, - "x-codespar-scope": "connections:write", + "x-codespar-scope": "cards:read", "security": [ { "bearerAuth": [ - "connections:write" + "cards:read" ] } ] } }, - "/v1/funding-sources/{id}": { - "get": { - "summary": "Read one consumer funding source", - "description": "One consumer rail: which provider holds it, which currency it authorizes, and whether it is still usable. Requires the `consumers:fund` scope.\n\nRESOLUTION IS SCOPED TO THE ORGANIZATION AND THE PROJECT the credential authenticates for. A funding source held by a SIBLING project in the same organization answers 404 here, indistinguishable from one that never existed. Note that the sibling operations in this group do not all draw the line in the same place: the consent-record read below is scoped to the organization only.\n\nNO LIVE BALANCE, and no query parameter asks for one. `balance_minor` is always null; the balance lives in the ledger.\n\nNo debit credential leaves. The row's provider token is an opaque vault pointer and is not in the response, and `metadata` is always `{}`: the account number and the holder's document stay on the row.", + "/v1/cards/{id}/freeze": { + "post": { + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "Freeze a card", + "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`.", "parameters": [ { "schema": { "type": "string", - "description": "The funding source id." + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`)." }, "required": true, - "description": "The funding source id.", + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`).", "name": "id", "in": "path" } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "client_request", + "lost", + "stolen", + "broken", + "upgrade" + ] + } + }, + "additionalProperties": false + } + } + } + }, "responses": { "200": { "description": "OK", @@ -26837,134 +28497,123 @@ "properties": { "id": { "type": "string", - "description": "`cfs_`- or `fs_celcoin_`-prefixed, depending on which writer created it." - }, - "project_id": { - "type": "string", - "description": "Always a string here, never null. Rows the 0129 backfill could not attribute carry `project_id IS NULL`, and the resolving predicate is a strict `=` against the credential's project, which no NULL satisfies — so an unattributed row answers 404 on this path rather than returning with a null." + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." }, - "consumer_id": { + "issuer": { "type": "string", - "description": "The consumer, in the caller's own namespace." + "enum": [ + "pomelo", + "rain" + ] }, - "rail": { + "program": { "type": "string", - "description": "An OPEN string, and deliberately not an enum here. `consumer_funding_sources` constrains it only with `CHECK (length(rail) > 0)`, and the writers do not agree on a closed set: `celcoin-onboarding.ts` writes the literal `pix-celcoin`, `routes/consents.ts` writes one of its own five-value `RAILS` list on the single-rail path, and its multi-slot path writes `methodToRail(slot.rail)` — where the slot's `rail` is validated as `z.string().min(1).max(40)` and `methodToRail` returns its argument unchanged when no mapping matches. So a caller who opened a consent with an unmapped slot rail reads that same string back here.\n\nThe values a reader should expect in practice: `pix-celcoin`, `pix-consent`, `card-token`, `ted-debit-auth`, `usd-ach-debit`, `usdc-onchain`. Match on those and tolerate anything else." + "enum": [ + "pomelo_brl", + "rain_usd" + ] }, "currency": { "type": "string", "enum": [ "BRL", - "USD", - "MXN", - "COP", - "ARS", - "USDC", - "BRLA" + "USD" ], - "description": "Closed by `consumer_funding_sources_currency_check`. That constraint NAME appears in exactly one file under `packages/api/src/migrations/`, so nothing later drops, relaxes or replaces it — the instrument is the name, not a list of the migrations that came after, because the list is what rots while the conclusion holds." + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." }, - "provider": { + "status": { "type": "string", - "description": "The provider behind the rail. Derived, not chosen: `celcoin` from the onboarding writer, and `rail.split(\"-\")[0]` from the consent writer, so it inherits the same openness `rail` has." - }, - "display_label": { - "type": [ - "string", - "null" - ], - "description": "Caller-supplied label, or null." + "enum": [ + "pending", + "not_activated", + "active", + "blocked", + "canceled" + ] }, - "branch": { + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." + }, + "last4": { "type": [ "string", "null" - ], - "description": "The account's branch (agência), lifted out of the row's `metadata.branch` when it holds a string, else null. Present on every row this group returns." - }, - "status": { - "type": "string", - "enum": [ - "active", - "held", - "revoked", - "expired" - ], - "description": "Closed by `consumer_funding_sources_status_check` (0040, widened by 0356 to add `held`). Read usability from `status` being `active`. `held` is the account opened for a Test project: bound to the project and readable here, and no payment, receiving or consent uses it. A companion constraint keeps `revoked_at` and `status = 'revoked'` in step, so they cannot disagree." + ] }, - "pix_key": { + "network": { "type": [ "string", "null" ], - "description": "Lifted out of `metadata.pixKey` when that key holds a string, else null. It is the DICT entry registered for the account, not a credential." + "enum": [ + "visa", + "mastercard" + ] }, - "pix_key_type": { + "mandate_id": { "type": [ "string", "null" - ], - "description": "Lifted out of `metadata.pixKeyType`, else null." + ] }, - "balance_minor": { + "consumer_id": { "type": [ - "object", + "string", "null" - ], - "enum": [ - null - ], - "description": "ALWAYS null on this operation, and present so a caller does not have to tell an absent field from an unknown balance. Live balance left the canonical surface with D4: the balance lives in the ledger. This read is new enough to have no legacy alias that could be relying on the old behaviour, so it never calls the provider." + ] }, "created_at": { "type": "string", "format": "date-time" }, - "expires_at": { - "type": [ - "string", - "null" - ], - "format": "date-time" - }, - "revoked_at": { - "type": [ - "string", - "null" - ], - "format": "date-time", - "description": "Non-null exactly when `status` is `revoked`; the table enforces the pair." + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." }, - "metadata": { + "funding": { "type": "object", - "additionalProperties": {}, - "description": "Always `{}`. The row's metadata holds the account number, the branch and, when the onboarding carried one, the holder's CPF or CNPJ; none of it is returned. What a caller uses is projected into fields of its own: `branch`, `pix_key` and `pix_key_type` (and `account_masked` on the listing). The key stays an object so a parser that requires it keeps working." + "properties": { + "asset": { + "type": "string", + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] } }, "required": [ "id", - "project_id", - "consumer_id", - "rail", + "issuer", + "program", "currency", - "provider", - "display_label", - "branch", "status", - "pix_key", - "pix_key_type", - "balance_minor", + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", "created_at", - "expires_at", - "revoked_at", - "metadata" + "available_actions" ] } } } }, - "404": { - "description": "Not Found. No funding source with this id in the caller's project. A row belonging to a sibling project, and a row the 0129 backfill left unattributed, both answer here.", + "400": { + "description": "The body did not match the schema.", "content": { "application/json": { "schema": { @@ -26976,7 +28625,7 @@ "code": { "type": "string", "enum": [ - "not_found" + "invalid_body" ] }, "message": { @@ -27007,160 +28656,99 @@ } } } - } - }, - "x-codespar-scope": "consumers:fund", - "security": [ - { - "bearerAuth": [ - "consumers:fund" - ] - } - ] - } - }, - "/v1/consent-records/{id}": { - "get": { - "summary": "Read one consent record", - "description": "One row of the consent log: the moment a consumer authorized a specific agent to debit a specific funding source up to a specific cap. Requires the `consents:read` scope.\n\nAPPEND-ONLY EVIDENCE. `consumer_consents` is the LGPD audit log — rows are never rewritten and never deleted, and a revocation is a new row with `kind = 'revoke'`. That is what lets a revocation be replayed from the log alone, and it is why this read returns exactly what the listing returns: there is no derived state for a point read to add.\n\nRESOLUTION IS SCOPED TO THE ORGANIZATION ONLY — the query predicates on `org_id` and the id, with no project term. A consent record created under a sibling project in the same organization IS readable with this credential. The funding-source read in this same group is narrower, so do not carry an assumption across the two.\n\nNO SIGNATURE MATERIAL LEAVES. The row carries `payload_hash` and `hmac_signature`; both are dropped before the body is built. What crosses the wire is `hmac_secret_version` — the stamp that says which secret signed it — and its note explains why that stamp is what makes secret rotation safe rather than destructive.\n\nPERSONAL DATA, TRUNCATED. `ip_address` is the network of the consumer's address (/24 for IPv4, /64 for IPv6); the full address stays on the row, recorded because a consent event has to be replayable with its origin.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "The consent record id." - }, - "required": true, - "description": "The consent record id.", - "name": "id", - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", + }, + "401": { + "description": "No API key behind the request.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "`ccsnt_`-prefixed on rows the mandate-lifecycle writer creates." - }, - "consumer_id": { - "type": "string" - }, - "funding_source_id": { - "type": [ - "string", - "null" - ], - "description": "The `consumer_funding_sources` row this consent authorizes debits against. Nullable on the column, and required by `consumer_consents_grant_completeness` on `kind = 'grant'` rows: a grant must declare what it authorizes, while `revoke` and `amend` reference the original grant." - }, - "agent_id": { - "type": [ - "string", - "null" - ], - "description": "The agent the consumer authorized, when the row names one." - }, - "kind": { - "type": "string", - "enum": [ - "grant", - "revoke", - "amend" - ], - "description": "Closed by `consumer_consents_kind_check`, whose name appears in exactly one migration file. The log is append-only: a revocation is a NEW row with `kind = 'revoke'`, never a rewrite of the grant, which is what makes a revocation replayable from the log alone." - }, - "hmac_secret_version": { - "type": "integer", - "description": "Which version of the consumer's HMAC secret signed this row. This is the field that makes rotation safe, and the half that is usually left out when the rule is quoted.\n\nRotating a consumer's secret invalidates FUTURE mandates only, and the reason is here rather than in the rotation: the verifier resolves the secret by `(consumer, version)` and the mandate itself carries the version it was signed under, so a mandate signed under the prior version still resolves the prior secret and still verifies. Rotation marks the old row and inserts version+1; it deletes nothing. Without the version stamp the sentence would mean the opposite — that rotating breaks the audit trail." - }, - "cap_minor": { - "type": [ - "string", - "null" - ], - "description": "A STRING, not a number. The column is `bigint` and the driver hands bigints back as strings; the handler passes the value straight through. Parse it as an integer in the row's `currency`, and do not assume it survives a float. Null on `revoke` / `amend` rows." - }, - "per_tx_cap_minor": { - "type": [ - "string", - "null" - ], - "description": "Same `bigint`-as-string treatment as `cap_minor`." - }, - "currency": { - "type": [ - "string", - "null" - ], - "enum": [ - "BRL", - "USD", - "MXN", - "COP", - "ARS", - "USDC", - "BRLA" - ], - "description": "Closed by `consumer_consents_currency_check` (name in exactly one migration file), which admits NULL as well as the seven values. Non-null on `grant` rows, which the completeness constraint requires to declare one." - }, - "purpose": { - "type": [ - "string", - "null" - ], - "description": "The purpose the consumer signed. Non-null on `grant` rows." + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_connection_key_unknown" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] }, - "ip_address": { + "request_id": { "type": [ "string", "null" ], - "description": "The network of the consumer's IP at signing time: an IPv4 address truncated to its /24 (`203.0.113.0`), an IPv6 address to its /64 (`2001:db8:85a3:8d3::`), null when none was recorded or the stored value does not parse. The `inet` column keeps the full address, because a consent event has to be replayable with timestamp and origin; only the response is truncated. `user_agent` is recorded alongside it and is NOT returned." - }, - "signed_at": { - "type": "string", - "format": "date-time", - "description": "When the consent event happened. The listing orders by this." + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "403": { + "description": "The key lacks `cards:issue`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_scope_missing" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] }, - "expires_at": { + "request_id": { "type": [ "string", "null" ], - "format": "date-time" - }, - "metadata": { - "type": "object", - "additionalProperties": {}, - "description": "Defaults to `{}`. Rows written by the mandate-lifecycle handler carry the transition instead: `action`, `from`, `to`, and `reason` when the caller gave one." + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "id", - "consumer_id", - "funding_source_id", - "agent_id", - "kind", - "hmac_secret_version", - "cap_minor", - "per_tx_cap_minor", - "currency", - "purpose", - "ip_address", - "signed_at", - "expires_at", - "metadata" + "error", + "request_id" ] } } } }, "404": { - "description": "Not Found. No consent record with this id in the caller's organization.", + "description": "No card with that id in this project.", "content": { "application/json": { "schema": { @@ -27172,7 +28760,7 @@ "code": { "type": "string", "enum": [ - "not_found" + "card_not_found" ] }, "message": { @@ -27203,182 +28791,54 @@ } } } - } - }, - "x-codespar-scope": "consents:read", - "security": [ - { - "bearerAuth": [ - "consents:read" - ] - } - ] - } - }, - "/v1/consent-records": { - "get": { - "summary": "List consent evidence", - "description": "The organization's consent evidence, most recent first. It is append-only: nothing here is edited after it is signed.\n\nThe response is `{ consents: [...] }`.", - "parameters": [ - { - "schema": { - "type": "string", - "minLength": 1 - }, - "required": false, - "name": "consumer_id", - "in": "query" }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200, - "description": "1 to 200; the default is 50." - }, - "required": false, - "description": "1 to 200; the default is 50.", - "name": "limit", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", + "409": { + "description": "The card's state does not allow it (`details.available_actions`).", "content": { "application/json": { "schema": { "type": "object", "properties": { - "consents": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "`ccsnt_`-prefixed on rows the mandate-lifecycle writer creates." - }, - "consumer_id": { - "type": "string" - }, - "funding_source_id": { - "type": [ - "string", - "null" - ], - "description": "The `consumer_funding_sources` row this consent authorizes debits against. Nullable on the column, and required by `consumer_consents_grant_completeness` on `kind = 'grant'` rows: a grant must declare what it authorizes, while `revoke` and `amend` reference the original grant." - }, - "agent_id": { - "type": [ - "string", - "null" - ], - "description": "The agent the consumer authorized, when the row names one." - }, - "kind": { - "type": "string", - "enum": [ - "grant", - "revoke", - "amend" - ], - "description": "Closed by `consumer_consents_kind_check`, whose name appears in exactly one migration file. The log is append-only: a revocation is a NEW row with `kind = 'revoke'`, never a rewrite of the grant, which is what makes a revocation replayable from the log alone." - }, - "hmac_secret_version": { - "type": "integer", - "description": "Which version of the consumer's HMAC secret signed this row. This is the field that makes rotation safe, and the half that is usually left out when the rule is quoted.\n\nRotating a consumer's secret invalidates FUTURE mandates only, and the reason is here rather than in the rotation: the verifier resolves the secret by `(consumer, version)` and the mandate itself carries the version it was signed under, so a mandate signed under the prior version still resolves the prior secret and still verifies. Rotation marks the old row and inserts version+1; it deletes nothing. Without the version stamp the sentence would mean the opposite — that rotating breaks the audit trail." - }, - "cap_minor": { - "type": [ - "string", - "null" - ], - "description": "A STRING, not a number. The column is `bigint` and the driver hands bigints back as strings; the handler passes the value straight through. Parse it as an integer in the row's `currency`, and do not assume it survives a float. Null on `revoke` / `amend` rows." - }, - "per_tx_cap_minor": { - "type": [ - "string", - "null" - ], - "description": "Same `bigint`-as-string treatment as `cap_minor`." - }, - "currency": { - "type": [ - "string", - "null" - ], - "enum": [ - "BRL", - "USD", - "MXN", - "COP", - "ARS", - "USDC", - "BRLA" - ], - "description": "Closed by `consumer_consents_currency_check` (name in exactly one migration file), which admits NULL as well as the seven values. Non-null on `grant` rows, which the completeness constraint requires to declare one." - }, - "purpose": { - "type": [ - "string", - "null" - ], - "description": "The purpose the consumer signed. Non-null on `grant` rows." - }, - "ip_address": { - "type": [ - "string", - "null" - ], - "description": "The network of the consumer's IP at signing time: an IPv4 address truncated to its /24 (`203.0.113.0`), an IPv6 address to its /64 (`2001:db8:85a3:8d3::`), null when none was recorded or the stored value does not parse. The `inet` column keeps the full address, because a consent event has to be replayable with timestamp and origin; only the response is truncated. `user_agent` is recorded alongside it and is NOT returned." - }, - "signed_at": { - "type": "string", - "format": "date-time", - "description": "When the consent event happened. The listing orders by this." - }, - "expires_at": { - "type": [ - "string", - "null" - ], - "format": "date-time" - }, - "metadata": { - "type": "object", - "additionalProperties": {}, - "description": "Defaults to `{}`. Rows written by the mandate-lifecycle handler carry the transition instead: `action`, `from`, `to`, and `reason` when the caller gave one." - } + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_action_not_allowed" + ] }, - "required": [ - "id", - "consumer_id", - "funding_source_id", - "agent_id", - "kind", - "hmac_secret_version", - "cap_minor", - "per_tx_cap_minor", - "currency", - "purpose", - "ip_address", - "signed_at", - "expires_at", - "metadata" - ] - } + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "consents" + "error", + "request_id" ] } } } }, - "400": { - "description": "The query did not match the schema.", + "422": { + "description": "The program does not support it, or the project is Live.", "content": { "application/json": { "schema": { @@ -27390,7 +28850,8 @@ "code": { "type": "string", "enum": [ - "invalid_query" + "card_action_unsupported", + "card_issuer_unavailable" ] }, "message": { @@ -27421,198 +28882,54 @@ } } } - } - }, - "x-codespar-scope": "consents:read", - "security": [ - { - "bearerAuth": [ - "consents:read" - ] - } - ] - } - }, - "/v1/funding-sources": { - "get": { - "summary": "List consumer funding sources", - "description": "The funding sources of this project's consumers.\n\n**This path does NOT fetch live balance, and that is not an omission.** The alias `GET /v1/consumers/funding-sources` accepts `?with_balance=1` and, for the `pix-celcoin` rows, fetches the balance from the provider one by one. The canonical path leaves that out on purpose: a listing of every consumer with live balance is a fan-out of N provider calls per request. If you need a balance, ask for the balance of ONE consumer, and the suppression here fails CLOSED: any route this handler does not recognize as the alias does not get a balance.\n\n`unattributed_count` counts the rows no consumer claims.", - "parameters": [ - { - "schema": { - "type": "string", - "minLength": 1 - }, - "required": false, - "name": "consumer_id", - "in": "query" }, - { - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 200, - "description": "1 to 200; the default is 50." - }, - "required": false, - "description": "1 to 200; the default is 50.", - "name": "limit", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", + "502": { + "description": "The issuer did not apply the change; the card is as it was.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "funding_sources": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "`cfs_`- or `fs_celcoin_`-prefixed, depending on which writer created it." - }, - "project_id": { - "type": "string", - "description": "Always a string here, never null. Rows the 0129 backfill could not attribute carry `project_id IS NULL`, and the resolving predicate is a strict `=` against the credential's project, which no NULL satisfies — so an unattributed row answers 404 on this path rather than returning with a null." - }, - "consumer_id": { - "type": "string", - "description": "The consumer, in the caller's own namespace." - }, - "rail": { - "type": "string", - "description": "An OPEN string, and deliberately not an enum here. `consumer_funding_sources` constrains it only with `CHECK (length(rail) > 0)`, and the writers do not agree on a closed set: `celcoin-onboarding.ts` writes the literal `pix-celcoin`, `routes/consents.ts` writes one of its own five-value `RAILS` list on the single-rail path, and its multi-slot path writes `methodToRail(slot.rail)` — where the slot's `rail` is validated as `z.string().min(1).max(40)` and `methodToRail` returns its argument unchanged when no mapping matches. So a caller who opened a consent with an unmapped slot rail reads that same string back here.\n\nThe values a reader should expect in practice: `pix-celcoin`, `pix-consent`, `card-token`, `ted-debit-auth`, `usd-ach-debit`, `usdc-onchain`. Match on those and tolerate anything else." - }, - "currency": { - "type": "string", - "enum": [ - "BRL", - "USD", - "MXN", - "COP", - "ARS", - "USDC", - "BRLA" - ], - "description": "Closed by `consumer_funding_sources_currency_check`. That constraint NAME appears in exactly one file under `packages/api/src/migrations/`, so nothing later drops, relaxes or replaces it — the instrument is the name, not a list of the migrations that came after, because the list is what rots while the conclusion holds." - }, - "provider": { - "type": "string", - "description": "The provider behind the rail. Derived, not chosen: `celcoin` from the onboarding writer, and `rail.split(\"-\")[0]` from the consent writer, so it inherits the same openness `rail` has." - }, - "display_label": { - "type": [ - "string", - "null" - ], - "description": "Caller-supplied label, or null." - }, - "branch": { - "type": [ - "string", - "null" - ], - "description": "The account's branch (agência), lifted out of the row's `metadata.branch` when it holds a string, else null. Present on every row this group returns." - }, - "status": { - "type": "string", - "enum": [ - "active", - "held", - "revoked", - "expired" - ], - "description": "Closed by `consumer_funding_sources_status_check` (0040, widened by 0356 to add `held`). Read usability from `status` being `active`. `held` is the account opened for a Test project: bound to the project and readable here, and no payment, receiving or consent uses it. A companion constraint keeps `revoked_at` and `status = 'revoked'` in step, so they cannot disagree." - }, - "pix_key": { - "type": [ - "string", - "null" - ], - "description": "Lifted out of `metadata.pixKey` when that key holds a string, else null. It is the DICT entry registered for the account, not a credential." - }, - "pix_key_type": { - "type": [ - "string", - "null" - ], - "description": "Lifted out of `metadata.pixKeyType`, else null." - }, - "balance_minor": { - "type": [ - "object", - "null" - ], - "enum": [ - null - ], - "description": "ALWAYS null on this operation, and present so a caller does not have to tell an absent field from an unknown balance. Live balance left the canonical surface with D4: the balance lives in the ledger. This read is new enough to have no legacy alias that could be relying on the old behaviour, so it never calls the provider." - }, - "created_at": { - "type": "string", - "format": "date-time" - }, - "expires_at": { - "type": [ - "string", - "null" - ], - "format": "date-time" - }, - "revoked_at": { - "type": [ - "string", - "null" - ], - "format": "date-time", - "description": "Non-null exactly when `status` is `revoked`; the table enforces the pair." - }, - "metadata": { - "type": "object", - "additionalProperties": {}, - "description": "Always `{}`. The row's metadata holds the account number, the branch and, when the onboarding carried one, the holder's CPF or CNPJ; none of it is returned. What a caller uses is projected into fields of its own: `branch`, `pix_key` and `pix_key_type` (and `account_masked` on the listing). The key stays an object so a parser that requires it keeps working." - } + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_control_failed" + ] }, - "required": [ - "id", - "project_id", - "consumer_id", - "rail", - "currency", - "provider", - "display_label", - "branch", - "status", - "pix_key", - "pix_key_type", - "balance_minor", - "created_at", - "expires_at", - "revoked_at", - "metadata" - ] - } + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] }, - "unattributed_count": { - "type": "integer" + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "funding_sources", - "unattributed_count" + "error", + "request_id" ] } } } }, - "400": { - "description": "The query did not match the schema.", + "503": { + "description": "The issuer's credentials could not be read.", "content": { "application/json": { "schema": { @@ -27624,7 +28941,7 @@ "code": { "type": "string", "enum": [ - "invalid_query" + "vault_unavailable" ] }, "message": { @@ -27657,46 +28974,54 @@ } } }, - "x-codespar-scope": "consumers:fund", + "x-codespar-scope": "cards:issue", "security": [ { "bearerAuth": [ - "consumers:fund" + "cards:issue" ] } ] } }, - "/v1/account-applications": { + "/v1/cards/{id}/unfreeze": { "post": { - "summary": "Open a consumer account application", - "description": "Opens a consumer's account application at the provider, and this is the path by which a consumer comes to have an account and a Pix funding source.\n\n**The response is not the account, it is the application.** What comes back is `verification_id` and a `status` from the provider; the account and the funding source appear when `GET /v1/account-applications/{id}` is read after the approval: that read is what provisions. A flow that expects an account here keeps waiting.\n\n**The `disclosure` is there to be rendered.** It names the institution that holds the account and CodeSpar's role as BaaS tomadora; the text comes in pt-BR to appear as it is, not to be rewritten.", + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "Unfreeze a card", + "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`)." + }, + "required": true, + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`).", + "name": "id", + "in": "path" + } + ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { - "buyer": { - "type": "object", - "additionalProperties": {}, - "description": "The identity fields the provider asks for: `documentNumber` (CPF or CNPJ), full name, date of birth, address. Passed through as an object: the handler does not validate it field by field here, and whatever the provider refuses comes back in the provider's own refusal. Two exceptions are checked before anything is sent: the document's check digits, and, for a natural person (CPF) in a live project, `financialDetails` = `{ declaredIncome, occupation, netWorth }` in the provider's codes, and `isPoliticallyExposedPerson` as `true` or `false`. Those are the titular's own declarations, and CodeSpar never fills them in for them (a value of `isPoliticallyExposedPerson` that is not a boolean is refused in any project).\n\n`files` (A5b): the documents, `[{ type, data }]`, `data` a URL the provider downloads, valid for at least one hour, PDF/PNG/JPEG (CONTRATO_SOCIAL is PDF). Natural person: RG/CNH/RNE and SELFIE; legal person: also CONTRATO_SOCIAL, and PROCURACAO_PODERES when an owner is a REPRESENTANTE. Checked before anything is sent. A test project that sends none gets the Test sample documents; a live project never does, and a live request naming a sample document is refused." - }, - "consumer_id": { + "reason": { "type": "string", - "description": "The consumer who becomes the owner of the account. It becomes the onboarding's `clientCode` and the owner of the funding source the approval produces." - }, - "opt_ins": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Opt-ins collected on the same screen. Today only `dda` does anything, and it requires the document to be this consumer's verified one AND to be on a signed `dda_allowlist`. Without that the registration is refused and the rest of the onboarding continues." + "enum": [ + "client_request", + "lost", + "stolen", + "broken", + "upgrade" + ] } }, - "required": [ - "buyer" - ] + "additionalProperties": false } } } @@ -27709,669 +29034,537 @@ "schema": { "type": "object", "properties": { - "verification_id": { + "id": { "type": "string", - "description": "The provider's proposal id. It is what `GET /v1/account-applications/{id}` reads." + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." + }, + "issuer": { + "type": "string", + "enum": [ + "pomelo", + "rain" + ] + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl", + "rain_usd" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" + ], + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." }, "status": { "type": "string", - "description": "Where the proposal stands at the provider, in the provider's own word." + "enum": [ + "pending", + "not_activated", + "active", + "blocked", + "canceled" + ] }, - "hosted_url": { + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." + }, + "last4": { "type": [ "string", "null" - ], - "description": "The verification page, when the provider uses one. Null when it is all done through the API." + ] }, - "disclosure": { + "network": { "type": [ - "object", + "string", "null" ], - "properties": { - "institution": { - "type": "string", - "description": "The institution that holds the account and is accountable for it." - }, - "institution_document": { - "type": [ - "string", - "null" - ], - "description": "Its CNPJ, or null while there is none confirmed against the signed contract. Rendering the wrong CNPJ is worse than rendering none." - }, - "codespar_role": { - "type": "string", - "enum": [ - "tomadora" - ], - "description": "CodeSpar's role in the arrangement: BaaS tomadora under Res. Conjunta CMN/BCB 16/2025." - }, - "text": { - "type": "string", - "description": "pt-BR, written to be rendered VERBATIM, with no rewriting." - } - }, - "required": [ - "institution", - "institution_document", - "codespar_role", - "text" - ], - "description": "Null when the router did not land on an institution with registered text." + "enum": [ + "visa", + "mastercard" + ] }, - "next_step": { + "mandate_id": { "type": [ - "object", + "string", "null" - ], - "properties": { - "code": { - "type": "string", - "enum": [ - "in_review_check_later" - ] - }, - "verification_id": { - "type": "string" - }, - "message": { - "type": "string" - }, - "retry_after_seconds": { - "type": "integer" - } - }, - "required": [ - "code", - "verification_id", - "message", - "retry_after_seconds" - ], - "description": "What to do next: read `GET /v1/account-applications/{id}` later. There is no account until the proposal reaches RESOURCE_CREATED." + ] }, - "sample_files": { - "type": "boolean", - "enum": [ - true - ], - "description": "Present in a test project that sent no `files`: the Test sample documents were sent." + "consumer_id": { + "type": [ + "string", + "null" + ] }, - "already_submitted": { - "type": "boolean", - "enum": [ - true - ], - "description": "Present when the create's own answer was lost (or the provider said the proposal exists) and the proposal was found by this request's clientCode instead of being sent again." + "created_at": { + "type": "string", + "format": "date-time" }, - "dda_opt_in": { + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + }, + "funding": { "type": "object", "properties": { - "status": { + "asset": { "type": "string", "enum": [ - "pending", - "failed", - "deferred" + "USDC" ] - }, - "message": { - "type": "string" } }, "required": [ - "status" - ], - "description": "Present only when `opt_ins` asked for `dda`. `pending` is the normal path: the registration is asynchronous and turns `active` when the provider's confirmation arrives, so treat pending as in progress and not as a failure." + "asset" + ] } }, "required": [ - "verification_id", + "id", + "issuer", + "program", + "currency", "status", - "hosted_url", - "disclosure", - "next_step" + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", + "created_at", + "available_actions" ] } } } }, "400": { - "description": "The body did not match the schema, the document did not pass the check, or a natural person's onboarding in a live project came without `buyer.financialDetails` (one issue per missing code, its `path` naming it) or without `buyer.isPoliticallyExposedPerson` as a boolean (its own issue) — `invalid_body`. Or the documents were refused before sending (A5b): `onboarding_sample_file_in_live` for a live request naming a Test sample document or a public specimen, `onboarding_files_invalid` for a malformed `files` list, a format the provider does not take, or a missing required document. BARE BODY, not the `{ error: { code, message } }` envelope: this handler writes its failure inline and there is no `request_id`.", + "description": "The body did not match the schema.", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "properties": { + "error": { "type": "object", "properties": { - "error": { + "code": { "type": "string", "enum": [ "invalid_body" ] }, - "issues": { - "type": "array", - "items": { - "type": "object", - "additionalProperties": {} - }, - "description": "The Zod issues, as Zod emitted them." + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} } }, "required": [ - "error", - "issues" + "code", + "message" ] }, - { + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "401": { + "description": "No API key behind the request.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { "type": "object", "properties": { - "error": { + "code": { "type": "string", "enum": [ - "onboarding_sample_file_in_live", - "onboarding_files_invalid" + "card_connection_key_unknown" ] }, "message": { "type": "string" }, - "issues": { - "type": "array", - "items": { - "type": "string" - }, - "description": "One line per refused field." + "details": { + "type": "object", + "additionalProperties": {} } }, "required": [ - "error", - "message", - "issues" + "code", + "message" ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } + }, + "required": [ + "error", + "request_id" ] } } } }, "403": { - "description": "Two answers. `onboarding_capability_inactive` (E2): this test project's `onboarding` capability is not active, so no proposal is opened; an owner or admin of the project asks for its onboarding access in the dashboard. Nothing was sent. And the organization's policy: The organization's policy decided, and nothing was dispatched. `approval_required`: a rule holds the call for a person; `approval_id` is the row in the approvals queue and `expires_at` when it lapses. Approving it runs the call then, through the approvals lane, not this request. `policy_denied`: a deny rule (or the non-overridable deny-list) refused it; `rule_id` names the rule. Bare body.", + "description": "The key lacks `cards:issue`.", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "properties": { + "error": { "type": "object", "properties": { - "error": { - "type": "string", - "enum": [ - "approval_required" - ] - }, "code": { "type": "string", "enum": [ - "approval_required" + "card_scope_missing" ] }, - "approval_id": { - "type": "string" - }, - "expires_at": { + "message": { "type": "string" }, - "message": { - "type": "string", - "description": "The name the organization gave the rule." + "details": { + "type": "object", + "additionalProperties": {} } }, "required": [ - "error", "code", - "approval_id", - "expires_at", "message" ] }, - { + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "404": { + "description": "No card with that id in this project.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { "type": "object", "properties": { - "error": { - "type": "string", - "enum": [ - "policy_denied" - ] - }, "code": { "type": "string", "enum": [ - "policy_denied" + "card_not_found" ] }, - "rule_id": { - "type": "string" - }, "message": { "type": "string" - } - }, - "required": [ - "error", - "code", - "rule_id", - "message" - ] - }, - { - "type": "object", - "properties": { - "error": { - "type": "string", - "enum": [ - "onboarding_capability_inactive" - ] - }, - "capability": { - "type": "string", - "enum": [ - "onboarding" - ] - }, - "state": { - "type": [ - "string", - "null" - ] }, - "message": { - "type": "string" + "details": { + "type": "object", + "additionalProperties": {} } }, "required": [ - "error", - "capability", - "state", + "code", "message" ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } + }, + "required": [ + "error", + "request_id" ] } } } }, "409": { - "description": "ONBOARDING COLLISION, and it is caller state and not a provider failure, which is why 409 and not 502. `provider_code` carries the provider's code (OBE064 proposal already open, CBE022 account already exists, OBE062 clientCode already linked) so the audit trail records the ground for the refusal. CBE022 is attributed only on this organization's own evidence: `onboarding_account_exists_in_project`, `onboarding_account_exists_elsewhere` (another project of the organization) or `onboarding_account_exists_unattributed` (no evidence; not concluded to be anyone's). E2 also answers here `onboarding_attempt_in_progress` (another request holds this clientCode's reservation; repeat later), `onboarding_client_code_conflict` for a clientCode this project used for another document, and `onboarding_unreserved`. On the OBE062 recovery, `consumer_onboarded_in_sibling_project`: the consumer is already onboarded in another project of the caller's organization, and the body carries `holding_project_id`. Bare body.", + "description": "The card's state does not allow it (`details.available_actions`).", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "onboarding_proposal_open_elsewhere", - "onboarding_account_exists_elsewhere", - "onboarding_account_exists_in_project", - "onboarding_account_exists_unattributed", - "onboarding_client_code_conflict", - "onboarding_attempt_in_progress", - "onboarding_unreserved", - "consumer_onboarded_in_sibling_project" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_action_not_allowed" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "provider_code": { - "type": "string" - }, - "retriable": { - "type": "boolean" - }, - "message": { - "type": "string" - }, - "holding_project_id": { - "type": "string", - "description": "On `consumer_onboarded_in_sibling_project` only: the project of the organization that holds the consumer." + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "message" + "request_id" ] } } } }, "422": { - "description": "The provider refused the proposal itself (e.g. CBE007 fullName not complete, OBE166 contrato social not a PDF). No proposal exists. Bare body.", + "description": "The program does not support it, or the project is Live.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "onboarding_proposal_refused" - ] - }, - "provider_code": { - "type": [ - "string", - "null" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_action_unsupported", + "card_issuer_unavailable" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "reason": { + "request_id": { "type": [ "string", "null" - ] - }, - "message": { - "type": "string" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "provider_code", - "reason", - "message" + "request_id" ] } } } }, - "429": { - "description": "E2: the sandbox proposal quota is used up, 2 per test project in 30 days (`window: project_30d`) or 30 per São Paulo day across every organization (`window: global_day`). Nothing was reserved or sent. A refused or locally invalid proposal never counts. Or `project_access_call_cap`: the sandbox call caps (60 per clock hour and 300 per São Paulo day per project, 3,000 per day globally) refused the call before it was sent; `Retry-After` is the seconds until that fixed window turns (the next clock hour, or São Paulo midnight). Bare body.", + "502": { + "description": "The issuer did not apply the change; the card is as it was.", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "properties": { + "error": { "type": "object", "properties": { - "error": { - "type": "string", - "enum": [ - "onboarding_quota_exceeded" - ] - }, - "window": { + "code": { "type": "string", "enum": [ - "project_30d", - "global_day" + "card_control_failed" ] }, - "max": { - "type": "integer" - }, "message": { "type": "string" - } - }, - "required": [ - "error", - "window", - "max", - "message" - ] - }, - { - "type": "object", - "properties": { - "error": { - "type": "string", - "enum": [ - "project_access_call_cap" - ] - }, - "window": { - "type": "string", - "enum": [ - "hour", - "day" - ] - }, - "scope": { - "type": "string", - "enum": [ - "project", - "global" - ] - }, - "max": { - "type": "integer" - }, - "retry_after_seconds": { - "type": [ - "integer", - "null" - ], - "description": "Seconds until the fixed window turns: the next clock hour, or São Paulo midnight. The same value as `Retry-After`." }, - "message": { - "type": "string" + "details": { + "type": "object", + "additionalProperties": {} } }, "required": [ - "error", - "window", - "scope", - "max", - "retry_after_seconds", + "code", "message" ] - } - ] - } - } - } - }, - "502": { - "description": "The provider call failed, or the router landed on an institution that is not the expected one. Bare body; `message` carries the underlying sentence and is what separates a provider outage from a refusal by the provider. E2: `onboarding_provider_failure` is the provider refusing for a reason that is not the titular's data (its credential, product, our payload, \"try later\", or a code not in the evidence table), with `provider_code`; no proposal exists, and it is retriable.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "string" }, - "message": { - "type": "string" + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "message" + "request_id" ] } } } }, "503": { - "description": "Two answers. `onboarding_outcome_unknown`: the proposal may have reached the provider and its answer was lost, and a query by this request's clientCode found nothing yet. Nothing was sent again. Repeat the SAME request after `Retry-After`: the same consumer and document reuse the clientCode, so no second proposal can be opened. E2: `onboarding_paused`, the server paused opening sandbox accounts (an operational switch); no proposal is opened, one already opened can still be read; `Retry-After` 3600. `onboarding_calls_unavailable`, the register of onboarding calls could not be written; `Retry-After` 30. `policy_denied`: The policy engine could not answer, so the call was refused fail-closed and nothing was dispatched. Infrastructure, not a rule: retry. Bare body. Bare body.", + "description": "The issuer's credentials could not be read.", "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "properties": { + "error": { "type": "object", "properties": { - "error": { - "type": "string", - "enum": [ - "policy_denied" - ] - }, "code": { "type": "string", "enum": [ - "policy_denied" - ] - }, - "rule_id": { - "type": "string" - }, - "message": { - "type": "string" - } - }, - "required": [ - "error", - "code", - "rule_id", - "message" - ] - }, - { - "type": "object", - "properties": { - "error": { - "type": "string", - "enum": [ - "onboarding_paused" - ] - }, - "retriable": { - "type": "boolean", - "enum": [ - true + "vault_unavailable" ] }, "message": { "type": "string" - } - }, - "required": [ - "error", - "retriable", - "message" - ] - }, - { - "type": "object", - "properties": { - "error": { - "type": "string", - "enum": [ - "onboarding_calls_unavailable" - ] - }, - "retriable": { - "type": "boolean", - "enum": [ - true - ] }, - "message": { - "type": "string" + "details": { + "type": "object", + "additionalProperties": {} } }, "required": [ - "error", - "retriable", + "code", "message" ] }, - { - "type": "object", - "properties": { - "error": { - "type": "string", - "enum": [ - "onboarding_outcome_unknown" - ] - }, - "message": { - "type": "string" - }, - "next_step": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "in_review_check_later" - ] - }, - "message": { - "type": "string" - }, - "retry_after_seconds": { - "type": "integer" - } - }, - "required": [ - "code", - "message", - "retry_after_seconds" - ] - } - }, - "required": [ - "error", - "message", - "next_step" - ] + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } + }, + "required": [ + "error", + "request_id" ] } } } } }, - "x-codespar-scope": "kyc:write", + "x-codespar-scope": "cards:issue", "security": [ { "bearerAuth": [ - "kyc:write" + "cards:issue" ] } ] } }, - "/v1/account-applications/{id}": { - "get": { - "summary": "Read the status of a consumer account application", - "description": "Where a consumer's account onboarding stands, and — once the provider has approved it — the account and the Pix funding source it produced. Requires the `kyc:read` scope.\n\nTHIS IS NOT A PURE READ, and a caller should plan around that. On the approved branch the handler resolves the account from the provider and then persists: it inserts (or re-resolves) the consumer's `pix-celcoin` funding source, registers a Pix key for it, and anchors the consumer record. Every approval path in the product converges on that one place, so polling this endpoint is how an application becomes a usable funding source. It is idempotent — the funding source id is derived from the consumer id, and re-provisioning merges into the existing row rather than replacing it, so a Pix key already registered is not erased.\n\n`document_number` IS REQUIRED, and the reason is ownership. It is never used to address the provider: the handler loads the proposal recorded under this id and compares. A mismatch, or an id with no recorded proposal, is refused before any provider call and provisions nothing — the attack it closes is an attacker's own approved proposal presented with a victim's document.\n\nTHOSE OWNERSHIP REFUSALS ARRIVE AS 409 with their own code (`document_ownership_unproven`, `onboarding_document_mismatch`), and so does a proposal recorded under ANOTHER project of the organization, in the same words as an unknown id. Only RESOURCE_CREATED binds an account; the proposal is read a bounded number of times when it is not visible yet, and an inconclusive read answers `pending` with `next_step`, never a new proposal.\n\nThe query is NOT schema-validated. The handler reads `request.query` directly and checks only that `document_number` is present; any other parameter is ignored rather than rejected.", + "/v1/cards/{id}/cancel": { + "post": { + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "Cancel a card", + "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`.", "parameters": [ { "schema": { "type": "string", - "description": "The provider's proposal id, returned by `POST /v1/account-applications`." + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`)." }, "required": true, - "description": "The provider's proposal id, returned by `POST /v1/account-applications`.", + "description": "A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`).", "name": "id", "in": "path" - }, - { - "schema": { - "type": "string", - "description": "REQUIRED. The CPF or CNPJ the caller claims this application is about, checked against the document recorded for the proposal. Formatting is normalized before the comparison." - }, - "required": true, - "description": "REQUIRED. The CPF or CNPJ the caller claims this application is about, checked against the document recorded for the proposal. Formatting is normalized before the comparison.", - "name": "document_number", - "in": "query" - }, - { - "schema": { - "type": "string", - "description": "A fallback only. The recorded proposal's own consumer id wins; this value is used when the recorded row carries none. Omitted, the proposal id stands in." - }, - "required": false, - "description": "A fallback only. The recorded proposal's own consumer id wins; this value is used when the recorded row carries none. Omitted, the proposal id stands in.", - "name": "consumer_id", - "in": "query" } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "enum": [ + "client_request", + "lost", + "stolen", + "broken", + "upgrade" + ] + } + }, + "additionalProperties": false + } + } + } + }, "responses": { "200": { "description": "OK", @@ -28380,1513 +29573,3150 @@ "schema": { "type": "object", "properties": { - "status": { + "id": { + "type": "string", + "description": "`icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's." + }, + "issuer": { "type": "string", "enum": [ - "pending", - "documentscopy_pending", - "approved", - "rejected" - ], - "description": "FOUR values, and the exported `CelcoinOnboardingStatus` union has five. `unknown` is in the type and is not in this enum because `resolveCelcoinOnboarding` — the only producer this route has — never returns it: its four `return` statements carry `rejected`, `documentscopy_pending`, `pending` (twice) and `approved`. The only other `\"unknown\"` in that file is a `conflict_case`, which is a different field on a different shape.\n\n`approved` means an account EXISTS: the proposal reached RESOURCE_CREATED, the account was read and bound. A proposal the provider reports as APPROVED has no account yet and answers `pending` (A5b), as does any status outside the provider's published vocabulary, a proposal not visible yet after the bounded reads (`proposal_status` NOT_VISIBLE_YET), and a RESOURCE_CREATED proposal whose account number could not be parsed from the provider's fetch response. That last case is logged with the raw body truncated, so a genuine not-minted-yet and a parse that is wrong look the same to the caller and different in the log." + "pomelo", + "rain" + ] }, - "proposal_status": { + "program": { "type": "string", - "description": "The provider's own status for the proposal (RESOURCE_CREATED, APPROVED, PENDING, ...), or NOT_VISIBLE_YET." + "enum": [ + "pomelo_brl", + "rain_usd" + ] }, - "next_step": { - "type": [ - "object", - "null" - ], - "properties": { - "code": { - "type": "string", - "enum": [ - "in_review_check_later" - ] - }, - "verification_id": { - "type": "string" - }, - "message": { - "type": "string", - "description": "pt-BR first: \"Em análise, consulte depois\", with the proposal id." - }, - "retry_after_seconds": { - "type": "integer" - } - }, - "required": [ - "code", - "verification_id", - "message", - "retry_after_seconds" + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD" ], - "description": "Present while the application has not concluded: read it again later with the same id. Never open a new application for the document; the provider allows one proposal per document every 24 hours. Null on `approved` and `rejected`." + "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." }, - "rejected_reason": { + "status": { "type": "string", - "description": "On `rejected`, the provider's reason when it gives one, as \"CODE: message\"." - }, - "hosted_url": { - "type": [ - "string", - "null" - ], - "description": "The documentoscopia webview the consumer opens, taken from the proposal's first `documentscopys` entry. Null on `rejected` and on `approved`." + "enum": [ + "pending", + "not_activated", + "active", + "blocked", + "canceled" + ] }, - "account": { - "type": [ - "string", - "null" - ], - "description": "The provisioned account number once one exists, else null. Stringified: the provider returns it as either a string or a number.\n\nThe branch is resolved in the same fetch and is NOT returned by this operation; it is returned as the funding source's `branch`." + "issuer_status": { + "type": "string", + "description": "The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled)." }, - "funding_source_id": { + "last4": { "type": [ "string", "null" - ], - "description": "The `pix-celcoin` funding source, or null before one exists. Deterministic — `fs_celcoin_` followed by the consumer id, one account per consumer — so a repeat call resolves the same row instead of opening a second one." + ] }, - "funding_source_status": { + "network": { "type": [ "string", "null" ], "enum": [ - "active", - "held" - ], - "description": "The funding source's status, or null before one exists. `held` for an account opened for a Test project: the account is bound to the project and no payment, receiving or consent uses it, and it has no Pix key yet. `active` in Live, or for an account that was already active." + "visa", + "mastercard" + ] }, - "pix_key": { + "mandate_id": { "type": [ "string", "null" - ], - "description": "The DICT entry registered for the account, once registration has succeeded. Null before that." + ] }, - "pix_key_type": { + "consumer_id": { "type": [ "string", "null" ] }, - "pix_key_registration_error": { + "created_at": { "type": "string", - "description": "ABSENT from the body unless Pix-key registration failed for an account that is otherwise real and usable. Deliberately non-blocking and deliberately not swallowed: the account works, the wallet's own lazy registration retries the step the next time the consumer needs to receive, and the failure is surfaced here so a caller can log or alert on it. Its presence does not make the application unapproved." - } - }, - "required": [ - "status", - "proposal_status", - "next_step", - "hosted_url", - "account", - "funding_source_id", - "funding_source_status", - "pix_key", - "pix_key_type" - ] + "format": "date-time" + }, + "available_actions": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "freeze", + "unfreeze", + "cancel" + ] + }, + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + }, + "funding": { + "type": "object", + "properties": { + "asset": { + "type": "string", + "enum": [ + "USDC" + ] + } + }, + "required": [ + "asset" + ] + } + }, + "required": [ + "id", + "issuer", + "program", + "currency", + "status", + "issuer_status", + "last4", + "network", + "mandate_id", + "consumer_id", + "created_at", + "available_actions" + ] } } } }, "400": { - "description": "Bad Request — `document_number` was not supplied. A BARE error body, not the `{ error: { code, message } }` envelope: this handler writes its failures inline and there is no `request_id` in the body.", + "description": "The body did not match the schema.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "document_number_required" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_body" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "error" + "error", + "request_id" ] } } } }, - "403": { - "description": "E2: this test project's `onboarding` capability is not active, so the proposal is not read. Nothing was sent.", + "401": { + "description": "No API key behind the request.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "onboarding_capability_inactive" - ] - }, - "capability": { - "type": "string", - "enum": [ - "onboarding" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_connection_key_unknown" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "message": { - "type": "string" + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "capability", - "message" + "request_id" ] } } } }, - "409": { - "description": "E2 adds the binding refusals: `account_bound_elsewhere` (the account is, or was, bound to another project), `account_binding_closed` (this project closed its binding; never reopened automatically), `consumer_holds_other_binding`. A refusal decided before anything is bound: the id has no proposal recorded for this project (`document_ownership_unproven`), the document does not match the one the proposal verified, or the account the provider returned names another document (`onboarding_document_mismatch`), or the funding source written did not confirm as this consumer's in this project (`funding_source_binding_unconfirmed`). Or the consumer is already onboarded in another project of the caller's organization (`consumer_onboarded_in_sibling_project`), refused before any write, and the body carries `holding_project_id`. Bare body.", + "403": { + "description": "The key lacks `cards:issue`.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "document_ownership_unproven", - "onboarding_document_mismatch", - "consumer_bound_to_other_document", - "funding_source_binding_unconfirmed", - "consumer_onboarded_in_sibling_project", - "account_bound_elsewhere", - "account_binding_closed", - "consumer_holds_other_binding" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_scope_missing" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "message": { - "type": "string" - }, - "holding_project_id": { - "type": "string", - "description": "On `consumer_onboarded_in_sibling_project` only: the project of the organization that holds the consumer." + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "message" + "request_id" ] } } } }, - "429": { - "description": "E2: the sandbox call caps (60 per clock hour and 300 per São Paulo day per project, 3,000 per day globally) refused the status read before it was sent. `Retry-After` is the seconds until that fixed window turns (the next clock hour, or São Paulo midnight). Bare body.", + "404": { + "description": "No card with that id in this project.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "project_access_call_cap" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_not_found" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "window": { + "request_id": { "type": [ "string", "null" ], - "enum": [ - "hour", - "day" + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "409": { + "description": "The card's state does not allow it (`details.available_actions`).", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_action_not_allowed" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "scope": { + "request_id": { "type": [ "string", "null" ], - "enum": [ - "project", - "global" + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "422": { + "description": "The program does not support it, or the project is Live.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_action_unsupported", + "card_issuer_unavailable" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "max": { + "request_id": { "type": [ - "integer", + "string", "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "502": { + "description": "The issuer did not apply the change; the card is as it was.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_control_failed" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "retry_after_seconds": { + "request_id": { "type": [ - "integer", + "string", "null" - ] - }, - "message": { - "type": "string" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "window", - "scope", - "max", - "retry_after_seconds", - "message" + "request_id" ] } } } }, - "502": { - "description": "Bad Gateway. The provider call failed. `message` carries the underlying sentence. Bare body, no `request_id`.", + "503": { + "description": "The issuer's credentials could not be read.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "vault_unavailable" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + } + }, + "x-codespar-scope": "cards:issue", + "security": [ + { + "bearerAuth": [ + "cards:issue" + ] + } + ] + } + }, + "/v1/cards/holder-profiles/{consumer_id}": { + "get": { + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "Which Pomelo holder fields are on file and which are missing", + "description": "The Pomelo holder is built from what the account already holds (the verified document, the onboarding's registered name) and the holder's profile. This read names each required field's source and lists exactly what is missing. It never returns a value. Requires `cards:read`.", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "consumer_id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "consumer_id": { + "type": "string" + }, + "program": { "type": "string", "enum": [ - "kyc_status_failed" + "pomelo_brl" ] }, - "message": { - "type": "string" + "sources": { + "type": "object", + "additionalProperties": { + "type": "string", + "enum": [ + "account", + "onboarding", + "profile", + "missing" + ] + }, + "description": "Where each required field comes from. Values are never returned." + }, + "missing_fields": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "document", + "full_name", + "email", + "birthdate", + "address.line1", + "address.city", + "address.postal_code" + ] + } + }, + "optional_present": { + "type": "array", + "items": { + "type": "string" + } + }, + "complete": { + "type": "boolean" + }, + "updated_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" } }, "required": [ - "error", - "message" + "consumer_id", + "program", + "sources", + "missing_fields", + "optional_present", + "complete", + "updated_at" ] } } } }, - "503": { - "description": "E2: the register of onboarding calls could not be written, so the status was not read (fails closed). `Retry-After: 30`. Bare body.", + "404": { + "description": "No consumer with that id in this organization.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "string", - "enum": [ - "onboarding_calls_unavailable" + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_consumer_not_found" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" ] }, - "message": { - "type": "string" + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ "error", - "message" + "request_id" ] } } } } }, - "x-codespar-scope": "kyc:read", + "x-codespar-scope": "cards:read", "security": [ { "bearerAuth": [ - "kyc:read" + "cards:read" ] } ] - } - }, - "/v1/facilitator/x402/executions": { - "post": { - "summary": "Ingest and execute a foreign x402 authorization", - "description": "Takes an EIP-3009 `transferWithAuthorization` signed OUTSIDE CodeSpar by a foreign wallet, verifies it, translates it onto an internal mandate, runs it through the same cap gate every other spend passes, settles it on-chain and seals a receipt. A 200 here means USDC MOVED. Requires the `facilitator:execute` scope.\n\nTHE CAPS ARE DECLARED BY THE CALLER. `intent.max_amount_minor` and `intent.total_cap_minor` come from this request, so they are limits the caller states for itself, not a ceiling the organization sets. The amount charged is the one the payer signed (`authorization.value`), and on mainnet an operator hard cap applies on top.\n\nOMITTING `intent.total_cap_minor` DOES NOT REMOVE THE LIFETIME CAP — it sets that cap equal to `max_amount_minor`. The translation reads `totalCap = totalCapAtomic ?? perTxCap`, and this route never marks the intent pay-per-access, so the gate compares the signer's PRIOR EXECUTED spend in this organization plus this payment against that cap. The practical consequence: leave `total_cap_minor` out and the SECOND execution by the same signer is refused with 422 `total_cap_exceeded`, even though the first succeeded and each authorization was independently signed. Send `total_cap_minor` explicitly whenever a signer may pay more than once.\n\nAMOUNTS ARE MINOR ON THE WIRE AND ATOMIC INSIDE. `max_amount_minor` and `total_cap_minor` are cents; they are converted to atomic USDC at the boundary, and the cap gate then compares them against `authorization.value`, which is already atomic. So the authorization's value is not scaled to match the caps — the caps are scaled to match it.\n\nThe evidence row is inserted `verified` only AFTER the payee binding, the replay guard and the amount guard have all passed — not when the signature verifies. A refusal at any of those three leaves NO row, so an authorization that verified cryptographically may have no record here at all. From that point every refusal marks the row `rejected` with its code in `reject_code`, and success marks it `executed` in the same transaction that seals the receipt, so the two commit together.\n\n`error.details` IS ALWAYS PRESENT on a failure, and is `{}` on most of them. It carries `foreign_authorization_id` in exactly two situations: when a row was created and then marked `rejected` (the cap gate, the mainnet ceiling, a settlement failure), and on the 409 replay — where the id is the PRIOR EXECUTED row's, not a new one. The 400 raised by body validation carries `issues` instead.\n\n`test` credentials always settle on `base-sepolia`; no flag can send them to mainnet. A `live` credential settles on `base` only when the operator has enabled mainnet, and is refused with 501 otherwise, before any wallet is touched.", + }, + "put": { + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "The holder fills only what is missing", + "description": "Sealed with the vault's per-org key. Send only the fields asked for; a field sent replaces the stored one. The document is never accepted here: it comes from the account's onboarding (KYC). After this, repeat the SAME issue request (same Idempotency-Key): it revalidates and resumes, and never issues a second card. Only the HOLDER may write it, a verified person through the dashboard whose own verified consumer is this one (or Rain's verified person for it); an admin or another member gets `card_holder_only`, an API key or an OAuth token `card_person_required`.", + "parameters": [ + { + "schema": { + "type": "string" + }, + "required": true, + "name": "consumer_id", + "in": "path" + } + ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { - "authorization": { + "full_name": { + "type": "string", + "minLength": 3, + "maxLength": 140 + }, + "email": { + "type": "string", + "maxLength": 254, + "format": "email" + }, + "birthdate": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + }, + "phone": { + "type": "string", + "pattern": "^\\+[1-9]\\d{6,14}$" + }, + "address": { "type": "object", "properties": { - "from": { + "line1": { "type": "string", - "pattern": "^0x[0-9a-fA-F]{40}$" + "minLength": 1, + "maxLength": 140 }, - "to": { + "line2": { "type": "string", - "pattern": "^0x[0-9a-fA-F]{40}$" + "maxLength": 140 }, - "value": { + "street_number": { "type": "string", - "pattern": "^\\d+$" + "minLength": 1, + "maxLength": 20 }, - "validAfter": { + "neighborhood": { "type": "string", - "pattern": "^\\d+$" + "minLength": 1, + "maxLength": 80 }, - "validBefore": { + "city": { "type": "string", - "pattern": "^\\d+$" + "minLength": 1, + "maxLength": 80 }, - "nonce": { - "type": "string", - "pattern": "^0x[0-9a-fA-F]{64}$" - } - }, - "required": [ - "from", - "to", - "value", - "validAfter", - "validBefore", - "nonce" - ] - }, - "domain": { - "type": "object", - "properties": { - "name": { + "state": { "type": "string", - "minLength": 1, - "maxLength": 100 + "maxLength": 40 }, - "version": { + "postal_code": { "type": "string", "minLength": 1, "maxLength": 20 }, - "chainId": { - "type": "integer", - "exclusiveMinimum": 0 + "municipality": { + "type": "string", + "minLength": 1, + "maxLength": 40 }, - "verifyingContract": { + "country": { "type": "string", - "pattern": "^0x[0-9a-fA-F]{40}$" + "pattern": "^[A-Z]{2}$", + "default": "BR" } }, "required": [ - "name", - "version", - "chainId", - "verifyingContract" - ] + "line1", + "city", + "postal_code" + ], + "additionalProperties": false + } + }, + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "consumer_id": { + "type": "string" + }, + "program": { + "type": "string", + "enum": [ + "pomelo_brl" + ] + }, + "sources": { + "type": "object", + "additionalProperties": { + "type": "string", + "enum": [ + "account", + "onboarding", + "profile", + "missing" + ] + }, + "description": "Where each required field comes from. Values are never returned." + }, + "missing_fields": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "document", + "full_name", + "email", + "birthdate", + "address.line1", + "address.city", + "address.postal_code" + ] + } + }, + "optional_present": { + "type": "array", + "items": { + "type": "string" + } + }, + "complete": { + "type": "boolean" + }, + "updated_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + } }, - "signature": { - "type": "string", - "pattern": "^0x[0-9a-fA-F]{130}$" + "required": [ + "consumer_id", + "program", + "sources", + "missing_fields", + "optional_present", + "complete", + "updated_at" + ] + } + } + } + }, + "400": { + "description": "The body did not match the schema.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_body" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } }, - "intent": { + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "403": { + "description": "Not a verified person of this org, or not the holder: only the holder writes it, proved by their own verified consumer or their Rain-verified person, never by a role.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_person_required", + "card_authorization_not_competent", + "card_holder_only" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "404": { + "description": "No consumer with that id in this organization.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_consumer_not_found" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "422": { + "description": "A Live project.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "card_issuer_unavailable" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + } + }, + "x-codespar-scope": "cards:issue", + "security": [ + { + "bearerAuth": [ + "cards:issue" + ] + } + ] + } + }, + "/v1/integrations/card-issuing": { + "get": { + "externalDocs": { + "url": "https://github.com/codespar/codespar-enterprise/blob/main/docs/designs/cards-unified-issuance.md", + "description": "The one Cards contract: programs, selection, requirements, idempotency" + }, + "summary": "Integrations: Card issuing", + "description": "One entry per program: managed by CodeSpar (no customer credential), and its state in this project and environment: `not_configured`, `configured` (never verified), `connected` (last verification ok), `verify_failed` (with `reason`), `live_blocked`. Requires `cards:read`.", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "type": "object", "properties": { - "payee": { + "issuer": { "type": "string", - "pattern": "^0x[0-9a-fA-F]{40}$" + "enum": [ + "pomelo", + "rain" + ] }, - "resource": { + "program": { "type": "string", - "minLength": 1, - "maxLength": 300 + "enum": [ + "pomelo_brl", + "rain_usd" + ] }, - "seller": { + "currency": { "type": "string", - "minLength": 1, - "maxLength": 200 + "enum": [ + "BRL", + "USD" + ] }, - "purpose": { + "managed_by": { "type": "string", - "minLength": 1, - "maxLength": 120 + "enum": [ + "codespar" + ], + "description": "The customer supplies no issuer credentials." }, - "max_amount_minor": { - "type": "integer", - "exclusiveMinimum": 0 + "status": { + "type": "string", + "enum": [ + "not_configured", + "configured", + "connected", + "verify_failed", + "live_blocked" + ], + "description": "`connected` = connectivity verified for the current connection, template and credential versions, unexpired. It is NOT homologation, holder eligibility or issuance availability." }, - "total_cap_minor": { - "type": "integer", - "exclusiveMinimum": 0 + "verified_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" }, - "resource_url": { - "type": "string", - "maxLength": 2048, - "format": "uri" + "expires_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "reason": { + "type": "string" + }, + "operations": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "issue", + "get", + "list", + "freeze", + "unfreeze", + "cancel" + ] + } } }, "required": [ - "payee", - "resource", - "purpose", - "max_amount_minor" + "issuer", + "program", + "currency", + "managed_by", + "status", + "verified_at", + "expires_at", + "operations" ] } - }, - "required": [ - "authorization", - "domain", - "signature", - "intent" - ] + } + } + } + } + }, + "x-codespar-scope": "cards:read", + "security": [ + { + "bearerAuth": [ + "cards:read" + ] + } + ] + } + }, + "/v1/funding-sources/{id}": { + "get": { + "summary": "Read one consumer funding source", + "description": "One consumer rail: which provider holds it, which currency it authorizes, and whether it is still usable. Requires the `consumers:fund` scope.\n\nRESOLUTION IS SCOPED TO THE ORGANIZATION AND THE PROJECT the credential authenticates for. A funding source held by a SIBLING project in the same organization answers 404 here, indistinguishable from one that never existed. Note that the sibling operations in this group do not all draw the line in the same place: the consent-record read below is scoped to the organization only.\n\nNO LIVE BALANCE, and no query parameter asks for one. `balance_minor` is always null; the balance lives in the ledger.\n\nNo debit credential leaves. The row's provider token is an opaque vault pointer and is not in the response, and `metadata` is always `{}`: the account number and the holder's document stay on the row.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The funding source id." + }, + "required": true, + "description": "The funding source id.", + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`cfs_`- or `fs_celcoin_`-prefixed, depending on which writer created it." + }, + "project_id": { + "type": "string", + "description": "Always a string here, never null. Rows the 0129 backfill could not attribute carry `project_id IS NULL`, and the resolving predicate is a strict `=` against the credential's project, which no NULL satisfies — so an unattributed row answers 404 on this path rather than returning with a null." + }, + "consumer_id": { + "type": "string", + "description": "The consumer, in the caller's own namespace." + }, + "rail": { + "type": "string", + "description": "An OPEN string, and deliberately not an enum here. `consumer_funding_sources` constrains it only with `CHECK (length(rail) > 0)`, and the writers do not agree on a closed set: `celcoin-onboarding.ts` writes the literal `pix-celcoin`, `routes/consents.ts` writes one of its own five-value `RAILS` list on the single-rail path, and its multi-slot path writes `methodToRail(slot.rail)` — where the slot's `rail` is validated as `z.string().min(1).max(40)` and `methodToRail` returns its argument unchanged when no mapping matches. So a caller who opened a consent with an unmapped slot rail reads that same string back here.\n\nThe values a reader should expect in practice: `pix-celcoin`, `pix-consent`, `card-token`, `ted-debit-auth`, `usd-ach-debit`, `usdc-onchain`. Match on those and tolerate anything else." + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD", + "MXN", + "COP", + "ARS", + "USDC", + "BRLA" + ], + "description": "Closed by `consumer_funding_sources_currency_check`. That constraint NAME appears in exactly one file under `packages/api/src/migrations/`, so nothing later drops, relaxes or replaces it — the instrument is the name, not a list of the migrations that came after, because the list is what rots while the conclusion holds." + }, + "provider": { + "type": "string", + "description": "The provider behind the rail. Derived, not chosen: `celcoin` from the onboarding writer, and `rail.split(\"-\")[0]` from the consent writer, so it inherits the same openness `rail` has." + }, + "display_label": { + "type": [ + "string", + "null" + ], + "description": "Caller-supplied label, or null." + }, + "branch": { + "type": [ + "string", + "null" + ], + "description": "The account's branch (agência), lifted out of the row's `metadata.branch` when it holds a string, else null. Present on every row this group returns." + }, + "status": { + "type": "string", + "enum": [ + "active", + "held", + "revoked", + "expired" + ], + "description": "Closed by `consumer_funding_sources_status_check` (0040, widened by 0356 to add `held`). Read usability from `status` being `active`. `held` is the account opened for a Test project: bound to the project and readable here, and no payment, receiving or consent uses it. A companion constraint keeps `revoked_at` and `status = 'revoked'` in step, so they cannot disagree." + }, + "pix_key": { + "type": [ + "string", + "null" + ], + "description": "Lifted out of `metadata.pixKey` when that key holds a string, else null. It is the DICT entry registered for the account, not a credential." + }, + "pix_key_type": { + "type": [ + "string", + "null" + ], + "description": "Lifted out of `metadata.pixKeyType`, else null." + }, + "balance_minor": { + "type": [ + "object", + "null" + ], + "enum": [ + null + ], + "description": "ALWAYS null on this operation, and present so a caller does not have to tell an absent field from an unknown balance. Live balance left the canonical surface with D4: the balance lives in the ledger. This read is new enough to have no legacy alias that could be relying on the old behaviour, so it never calls the provider." + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "expires_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "revoked_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "Non-null exactly when `status` is `revoked`; the table enforces the pair." + }, + "metadata": { + "type": "object", + "additionalProperties": {}, + "description": "Always `{}`. The row's metadata holds the account number, the branch and, when the onboarding carried one, the holder's CPF or CNPJ; none of it is returned. What a caller uses is projected into fields of its own: `branch`, `pix_key` and `pix_key_type` (and `account_masked` on the listing). The key stays an object so a parser that requires it keeps working." + } + }, + "required": [ + "id", + "project_id", + "consumer_id", + "rail", + "currency", + "provider", + "display_label", + "branch", + "status", + "pix_key", + "pix_key_type", + "balance_minor", + "created_at", + "expires_at", + "revoked_at", + "metadata" + ] + } + } + } + }, + "404": { + "description": "Not Found. No funding source with this id in the caller's project. A row belonging to a sibling project, and a row the 0129 backfill left unattributed, both answer here.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "not_found" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + } + }, + "x-codespar-scope": "consumers:fund", + "security": [ + { + "bearerAuth": [ + "consumers:fund" + ] + } + ] + } + }, + "/v1/consent-records/{id}": { + "get": { + "summary": "Read one consent record", + "description": "One row of the consent log: the moment a consumer authorized a specific agent to debit a specific funding source up to a specific cap. Requires the `consents:read` scope.\n\nAPPEND-ONLY EVIDENCE. `consumer_consents` is the LGPD audit log — rows are never rewritten and never deleted, and a revocation is a new row with `kind = 'revoke'`. That is what lets a revocation be replayed from the log alone, and it is why this read returns exactly what the listing returns: there is no derived state for a point read to add.\n\nRESOLUTION IS SCOPED TO THE ORGANIZATION ONLY — the query predicates on `org_id` and the id, with no project term. A consent record created under a sibling project in the same organization IS readable with this credential. The funding-source read in this same group is narrower, so do not carry an assumption across the two.\n\nNO SIGNATURE MATERIAL LEAVES. The row carries `payload_hash` and `hmac_signature`; both are dropped before the body is built. What crosses the wire is `hmac_secret_version` — the stamp that says which secret signed it — and its note explains why that stamp is what makes secret rotation safe rather than destructive.\n\nPERSONAL DATA, TRUNCATED. `ip_address` is the network of the consumer's address (/24 for IPv4, /64 for IPv6); the full address stays on the row, recorded because a consent event has to be replayable with its origin.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The consent record id." + }, + "required": true, + "description": "The consent record id.", + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`ccsnt_`-prefixed on rows the mandate-lifecycle writer creates." + }, + "consumer_id": { + "type": "string" + }, + "funding_source_id": { + "type": [ + "string", + "null" + ], + "description": "The `consumer_funding_sources` row this consent authorizes debits against. Nullable on the column, and required by `consumer_consents_grant_completeness` on `kind = 'grant'` rows: a grant must declare what it authorizes, while `revoke` and `amend` reference the original grant." + }, + "agent_id": { + "type": [ + "string", + "null" + ], + "description": "The agent the consumer authorized, when the row names one." + }, + "kind": { + "type": "string", + "enum": [ + "grant", + "revoke", + "amend" + ], + "description": "Closed by `consumer_consents_kind_check`, whose name appears in exactly one migration file. The log is append-only: a revocation is a NEW row with `kind = 'revoke'`, never a rewrite of the grant, which is what makes a revocation replayable from the log alone." + }, + "hmac_secret_version": { + "type": "integer", + "description": "Which version of the consumer's HMAC secret signed this row. This is the field that makes rotation safe, and the half that is usually left out when the rule is quoted.\n\nRotating a consumer's secret invalidates FUTURE mandates only, and the reason is here rather than in the rotation: the verifier resolves the secret by `(consumer, version)` and the mandate itself carries the version it was signed under, so a mandate signed under the prior version still resolves the prior secret and still verifies. Rotation marks the old row and inserts version+1; it deletes nothing. Without the version stamp the sentence would mean the opposite — that rotating breaks the audit trail." + }, + "cap_minor": { + "type": [ + "string", + "null" + ], + "description": "A STRING, not a number. The column is `bigint` and the driver hands bigints back as strings; the handler passes the value straight through. Parse it as an integer in the row's `currency`, and do not assume it survives a float. Null on `revoke` / `amend` rows." + }, + "per_tx_cap_minor": { + "type": [ + "string", + "null" + ], + "description": "Same `bigint`-as-string treatment as `cap_minor`." + }, + "currency": { + "type": [ + "string", + "null" + ], + "enum": [ + "BRL", + "USD", + "MXN", + "COP", + "ARS", + "USDC", + "BRLA" + ], + "description": "Closed by `consumer_consents_currency_check` (name in exactly one migration file), which admits NULL as well as the seven values. Non-null on `grant` rows, which the completeness constraint requires to declare one." + }, + "purpose": { + "type": [ + "string", + "null" + ], + "description": "The purpose the consumer signed. Non-null on `grant` rows." + }, + "ip_address": { + "type": [ + "string", + "null" + ], + "description": "The network of the consumer's IP at signing time: an IPv4 address truncated to its /24 (`203.0.113.0`), an IPv6 address to its /64 (`2001:db8:85a3:8d3::`), null when none was recorded or the stored value does not parse. The `inet` column keeps the full address, because a consent event has to be replayable with timestamp and origin; only the response is truncated. `user_agent` is recorded alongside it and is NOT returned." + }, + "signed_at": { + "type": "string", + "format": "date-time", + "description": "When the consent event happened. The listing orders by this." + }, + "expires_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "metadata": { + "type": "object", + "additionalProperties": {}, + "description": "Defaults to `{}`. Rows written by the mandate-lifecycle handler carry the transition instead: `action`, `from`, `to`, and `reason` when the caller gave one." + } + }, + "required": [ + "id", + "consumer_id", + "funding_source_id", + "agent_id", + "kind", + "hmac_secret_version", + "cap_minor", + "per_tx_cap_minor", + "currency", + "purpose", + "ip_address", + "signed_at", + "expires_at", + "metadata" + ] + } + } + } + }, + "404": { + "description": "Not Found. No consent record with this id in the caller's organization.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "not_found" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + } + }, + "x-codespar-scope": "consents:read", + "security": [ + { + "bearerAuth": [ + "consents:read" + ] + } + ] + } + }, + "/v1/consent-records": { + "get": { + "summary": "List consent evidence", + "description": "The organization's consent evidence, most recent first. It is append-only: nothing here is edited after it is signed.\n\nThe response is `{ consents: [...] }`.", + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": false, + "name": "consumer_id", + "in": "query" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "description": "1 to 200; the default is 50." + }, + "required": false, + "description": "1 to 200; the default is 50.", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "consents": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`ccsnt_`-prefixed on rows the mandate-lifecycle writer creates." + }, + "consumer_id": { + "type": "string" + }, + "funding_source_id": { + "type": [ + "string", + "null" + ], + "description": "The `consumer_funding_sources` row this consent authorizes debits against. Nullable on the column, and required by `consumer_consents_grant_completeness` on `kind = 'grant'` rows: a grant must declare what it authorizes, while `revoke` and `amend` reference the original grant." + }, + "agent_id": { + "type": [ + "string", + "null" + ], + "description": "The agent the consumer authorized, when the row names one." + }, + "kind": { + "type": "string", + "enum": [ + "grant", + "revoke", + "amend" + ], + "description": "Closed by `consumer_consents_kind_check`, whose name appears in exactly one migration file. The log is append-only: a revocation is a NEW row with `kind = 'revoke'`, never a rewrite of the grant, which is what makes a revocation replayable from the log alone." + }, + "hmac_secret_version": { + "type": "integer", + "description": "Which version of the consumer's HMAC secret signed this row. This is the field that makes rotation safe, and the half that is usually left out when the rule is quoted.\n\nRotating a consumer's secret invalidates FUTURE mandates only, and the reason is here rather than in the rotation: the verifier resolves the secret by `(consumer, version)` and the mandate itself carries the version it was signed under, so a mandate signed under the prior version still resolves the prior secret and still verifies. Rotation marks the old row and inserts version+1; it deletes nothing. Without the version stamp the sentence would mean the opposite — that rotating breaks the audit trail." + }, + "cap_minor": { + "type": [ + "string", + "null" + ], + "description": "A STRING, not a number. The column is `bigint` and the driver hands bigints back as strings; the handler passes the value straight through. Parse it as an integer in the row's `currency`, and do not assume it survives a float. Null on `revoke` / `amend` rows." + }, + "per_tx_cap_minor": { + "type": [ + "string", + "null" + ], + "description": "Same `bigint`-as-string treatment as `cap_minor`." + }, + "currency": { + "type": [ + "string", + "null" + ], + "enum": [ + "BRL", + "USD", + "MXN", + "COP", + "ARS", + "USDC", + "BRLA" + ], + "description": "Closed by `consumer_consents_currency_check` (name in exactly one migration file), which admits NULL as well as the seven values. Non-null on `grant` rows, which the completeness constraint requires to declare one." + }, + "purpose": { + "type": [ + "string", + "null" + ], + "description": "The purpose the consumer signed. Non-null on `grant` rows." + }, + "ip_address": { + "type": [ + "string", + "null" + ], + "description": "The network of the consumer's IP at signing time: an IPv4 address truncated to its /24 (`203.0.113.0`), an IPv6 address to its /64 (`2001:db8:85a3:8d3::`), null when none was recorded or the stored value does not parse. The `inet` column keeps the full address, because a consent event has to be replayable with timestamp and origin; only the response is truncated. `user_agent` is recorded alongside it and is NOT returned." + }, + "signed_at": { + "type": "string", + "format": "date-time", + "description": "When the consent event happened. The listing orders by this." + }, + "expires_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "metadata": { + "type": "object", + "additionalProperties": {}, + "description": "Defaults to `{}`. Rows written by the mandate-lifecycle handler carry the transition instead: `action`, `from`, `to`, and `reason` when the caller gave one." + } + }, + "required": [ + "id", + "consumer_id", + "funding_source_id", + "agent_id", + "kind", + "hmac_secret_version", + "cap_minor", + "per_tx_cap_minor", + "currency", + "purpose", + "ip_address", + "signed_at", + "expires_at", + "metadata" + ] + } + } + }, + "required": [ + "consents" + ] + } + } + } + }, + "400": { + "description": "The query did not match the schema.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_query" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + } + }, + "x-codespar-scope": "consents:read", + "security": [ + { + "bearerAuth": [ + "consents:read" + ] + } + ] + } + }, + "/v1/funding-sources": { + "get": { + "summary": "List consumer funding sources", + "description": "The funding sources of this project's consumers.\n\n**This path does NOT fetch live balance, and that is not an omission.** The alias `GET /v1/consumers/funding-sources` accepts `?with_balance=1` and, for the `pix-celcoin` rows, fetches the balance from the provider one by one. The canonical path leaves that out on purpose: a listing of every consumer with live balance is a fan-out of N provider calls per request. If you need a balance, ask for the balance of ONE consumer, and the suppression here fails CLOSED: any route this handler does not recognize as the alias does not get a balance.\n\n`unattributed_count` counts the rows no consumer claims.", + "parameters": [ + { + "schema": { + "type": "string", + "minLength": 1 + }, + "required": false, + "name": "consumer_id", + "in": "query" + }, + { + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "description": "1 to 200; the default is 50." + }, + "required": false, + "description": "1 to 200; the default is 50.", + "name": "limit", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "funding_sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`cfs_`- or `fs_celcoin_`-prefixed, depending on which writer created it." + }, + "project_id": { + "type": "string", + "description": "Always a string here, never null. Rows the 0129 backfill could not attribute carry `project_id IS NULL`, and the resolving predicate is a strict `=` against the credential's project, which no NULL satisfies — so an unattributed row answers 404 on this path rather than returning with a null." + }, + "consumer_id": { + "type": "string", + "description": "The consumer, in the caller's own namespace." + }, + "rail": { + "type": "string", + "description": "An OPEN string, and deliberately not an enum here. `consumer_funding_sources` constrains it only with `CHECK (length(rail) > 0)`, and the writers do not agree on a closed set: `celcoin-onboarding.ts` writes the literal `pix-celcoin`, `routes/consents.ts` writes one of its own five-value `RAILS` list on the single-rail path, and its multi-slot path writes `methodToRail(slot.rail)` — where the slot's `rail` is validated as `z.string().min(1).max(40)` and `methodToRail` returns its argument unchanged when no mapping matches. So a caller who opened a consent with an unmapped slot rail reads that same string back here.\n\nThe values a reader should expect in practice: `pix-celcoin`, `pix-consent`, `card-token`, `ted-debit-auth`, `usd-ach-debit`, `usdc-onchain`. Match on those and tolerate anything else." + }, + "currency": { + "type": "string", + "enum": [ + "BRL", + "USD", + "MXN", + "COP", + "ARS", + "USDC", + "BRLA" + ], + "description": "Closed by `consumer_funding_sources_currency_check`. That constraint NAME appears in exactly one file under `packages/api/src/migrations/`, so nothing later drops, relaxes or replaces it — the instrument is the name, not a list of the migrations that came after, because the list is what rots while the conclusion holds." + }, + "provider": { + "type": "string", + "description": "The provider behind the rail. Derived, not chosen: `celcoin` from the onboarding writer, and `rail.split(\"-\")[0]` from the consent writer, so it inherits the same openness `rail` has." + }, + "display_label": { + "type": [ + "string", + "null" + ], + "description": "Caller-supplied label, or null." + }, + "branch": { + "type": [ + "string", + "null" + ], + "description": "The account's branch (agência), lifted out of the row's `metadata.branch` when it holds a string, else null. Present on every row this group returns." + }, + "status": { + "type": "string", + "enum": [ + "active", + "held", + "revoked", + "expired" + ], + "description": "Closed by `consumer_funding_sources_status_check` (0040, widened by 0356 to add `held`). Read usability from `status` being `active`. `held` is the account opened for a Test project: bound to the project and readable here, and no payment, receiving or consent uses it. A companion constraint keeps `revoked_at` and `status = 'revoked'` in step, so they cannot disagree." + }, + "pix_key": { + "type": [ + "string", + "null" + ], + "description": "Lifted out of `metadata.pixKey` when that key holds a string, else null. It is the DICT entry registered for the account, not a credential." + }, + "pix_key_type": { + "type": [ + "string", + "null" + ], + "description": "Lifted out of `metadata.pixKeyType`, else null." + }, + "balance_minor": { + "type": [ + "object", + "null" + ], + "enum": [ + null + ], + "description": "ALWAYS null on this operation, and present so a caller does not have to tell an absent field from an unknown balance. Live balance left the canonical surface with D4: the balance lives in the ledger. This read is new enough to have no legacy alias that could be relying on the old behaviour, so it never calls the provider." + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "expires_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "revoked_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "description": "Non-null exactly when `status` is `revoked`; the table enforces the pair." + }, + "metadata": { + "type": "object", + "additionalProperties": {}, + "description": "Always `{}`. The row's metadata holds the account number, the branch and, when the onboarding carried one, the holder's CPF or CNPJ; none of it is returned. What a caller uses is projected into fields of its own: `branch`, `pix_key` and `pix_key_type` (and `account_masked` on the listing). The key stays an object so a parser that requires it keeps working." + } + }, + "required": [ + "id", + "project_id", + "consumer_id", + "rail", + "currency", + "provider", + "display_label", + "branch", + "status", + "pix_key", + "pix_key_type", + "balance_minor", + "created_at", + "expires_at", + "revoked_at", + "metadata" + ] + } + }, + "unattributed_count": { + "type": "integer" + } + }, + "required": [ + "funding_sources", + "unattributed_count" + ] + } + } + } + }, + "400": { + "description": "The query did not match the schema.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_query" + ] + }, + "message": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": {} + } + }, + "required": [ + "code", + "message" + ] + }, + "request_id": { + "type": [ + "string", + "null" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + } + }, + "x-codespar-scope": "consumers:fund", + "security": [ + { + "bearerAuth": [ + "consumers:fund" + ] + } + ] + } + }, + "/v1/account-applications": { + "post": { + "summary": "Open a consumer account application", + "description": "Opens a consumer's account application at the provider, and this is the path by which a consumer comes to have an account and a Pix funding source.\n\n**The response is not the account, it is the application.** What comes back is `verification_id` and a `status` from the provider; the account and the funding source appear when `GET /v1/account-applications/{id}` is read after the approval: that read is what provisions. A flow that expects an account here keeps waiting.\n\n**The `disclosure` is there to be rendered.** It names the institution that holds the account and CodeSpar's role as BaaS tomadora; the text comes in pt-BR to appear as it is, not to be rewritten.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "buyer": { + "type": "object", + "additionalProperties": {}, + "description": "The identity fields the provider asks for: `documentNumber` (CPF or CNPJ), full name, date of birth, address. Passed through as an object: the handler does not validate it field by field here, and whatever the provider refuses comes back in the provider's own refusal. Two exceptions are checked before anything is sent: the document's check digits, and, for a natural person (CPF) in a live project, `financialDetails` = `{ declaredIncome, occupation, netWorth }` in the provider's codes, and `isPoliticallyExposedPerson` as `true` or `false`. Those are the titular's own declarations, and CodeSpar never fills them in for them (a value of `isPoliticallyExposedPerson` that is not a boolean is refused in any project).\n\n`files` (A5b): the documents, `[{ type, data }]`, `data` a URL the provider downloads, valid for at least one hour, PDF/PNG/JPEG (CONTRATO_SOCIAL is PDF). Natural person: RG/CNH/RNE and SELFIE; legal person: also CONTRATO_SOCIAL, and PROCURACAO_PODERES when an owner is a REPRESENTANTE. Checked before anything is sent. A test project that sends none gets the Test sample documents; a live project never does, and a live request naming a sample document is refused." + }, + "consumer_id": { + "type": "string", + "description": "The consumer who becomes the owner of the account. It becomes the onboarding's `clientCode` and the owner of the funding source the approval produces." + }, + "opt_ins": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Opt-ins collected on the same screen. Today only `dda` does anything, and it requires the document to be this consumer's verified one AND to be on a signed `dda_allowlist`. Without that the registration is refused and the rest of the onboarding continues." + } + }, + "required": [ + "buyer" + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "verification_id": { + "type": "string", + "description": "The provider's proposal id. It is what `GET /v1/account-applications/{id}` reads." + }, + "status": { + "type": "string", + "description": "Where the proposal stands at the provider, in the provider's own word." + }, + "hosted_url": { + "type": [ + "string", + "null" + ], + "description": "The verification page, when the provider uses one. Null when it is all done through the API." + }, + "disclosure": { + "type": [ + "object", + "null" + ], + "properties": { + "institution": { + "type": "string", + "description": "The institution that holds the account and is accountable for it." + }, + "institution_document": { + "type": [ + "string", + "null" + ], + "description": "Its CNPJ, or null while there is none confirmed against the signed contract. Rendering the wrong CNPJ is worse than rendering none." + }, + "codespar_role": { + "type": "string", + "enum": [ + "tomadora" + ], + "description": "CodeSpar's role in the arrangement: BaaS tomadora under Res. Conjunta CMN/BCB 16/2025." + }, + "text": { + "type": "string", + "description": "pt-BR, written to be rendered VERBATIM, with no rewriting." + } + }, + "required": [ + "institution", + "institution_document", + "codespar_role", + "text" + ], + "description": "Null when the router did not land on an institution with registered text." + }, + "next_step": { + "type": [ + "object", + "null" + ], + "properties": { + "code": { + "type": "string", + "enum": [ + "in_review_check_later" + ] + }, + "verification_id": { + "type": "string" + }, + "message": { + "type": "string" + }, + "retry_after_seconds": { + "type": "integer" + } + }, + "required": [ + "code", + "verification_id", + "message", + "retry_after_seconds" + ], + "description": "What to do next: read `GET /v1/account-applications/{id}` later. There is no account until the proposal reaches RESOURCE_CREATED." + }, + "sample_files": { + "type": "boolean", + "enum": [ + true + ], + "description": "Present in a test project that sent no `files`: the Test sample documents were sent." + }, + "already_submitted": { + "type": "boolean", + "enum": [ + true + ], + "description": "Present when the create's own answer was lost (or the provider said the proposal exists) and the proposal was found by this request's clientCode instead of being sent again." + }, + "dda_opt_in": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "pending", + "failed", + "deferred" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "status" + ], + "description": "Present only when `opt_ins` asked for `dda`. `pending` is the normal path: the registration is asynchronous and turns `active` when the provider's confirmation arrives, so treat pending as in progress and not as a failure." + } + }, + "required": [ + "verification_id", + "status", + "hosted_url", + "disclosure", + "next_step" + ] + } + } + } + }, + "400": { + "description": "The body did not match the schema, the document did not pass the check, or a natural person's onboarding in a live project came without `buyer.financialDetails` (one issue per missing code, its `path` naming it) or without `buyer.isPoliticallyExposedPerson` as a boolean (its own issue) — `invalid_body`. Or the documents were refused before sending (A5b): `onboarding_sample_file_in_live` for a live request naming a Test sample document or a public specimen, `onboarding_files_invalid` for a malformed `files` list, a format the provider does not take, or a missing required document. BARE BODY, not the `{ error: { code, message } }` envelope: this handler writes its failure inline and there is no `request_id`.", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "invalid_body" + ] + }, + "issues": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": {} + }, + "description": "The Zod issues, as Zod emitted them." + } + }, + "required": [ + "error", + "issues" + ] + }, + { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "onboarding_sample_file_in_live", + "onboarding_files_invalid" + ] + }, + "message": { + "type": "string" + }, + "issues": { + "type": "array", + "items": { + "type": "string" + }, + "description": "One line per refused field." + } + }, + "required": [ + "error", + "message", + "issues" + ] + } + ] + } + } + } + }, + "403": { + "description": "Two answers. `onboarding_capability_inactive` (E2): this test project's `onboarding` capability is not active, so no proposal is opened; an owner or admin of the project asks for its onboarding access in the dashboard. Nothing was sent. And the organization's policy: The organization's policy decided, and nothing was dispatched. `approval_required`: a rule holds the call for a person; `approval_id` is the row in the approvals queue and `expires_at` when it lapses. Approving it runs the call then, through the approvals lane, not this request. `policy_denied`: a deny rule (or the non-overridable deny-list) refused it; `rule_id` names the rule. Bare body.", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "approval_required" + ] + }, + "code": { + "type": "string", + "enum": [ + "approval_required" + ] + }, + "approval_id": { + "type": "string" + }, + "expires_at": { + "type": "string" + }, + "message": { + "type": "string", + "description": "The name the organization gave the rule." + } + }, + "required": [ + "error", + "code", + "approval_id", + "expires_at", + "message" + ] + }, + { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "policy_denied" + ] + }, + "code": { + "type": "string", + "enum": [ + "policy_denied" + ] + }, + "rule_id": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "error", + "code", + "rule_id", + "message" + ] + }, + { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "onboarding_capability_inactive" + ] + }, + "capability": { + "type": "string", + "enum": [ + "onboarding" + ] + }, + "state": { + "type": [ + "string", + "null" + ] + }, + "message": { + "type": "string" + } + }, + "required": [ + "error", + "capability", + "state", + "message" + ] + } + ] + } + } + } + }, + "409": { + "description": "ONBOARDING COLLISION, and it is caller state and not a provider failure, which is why 409 and not 502. `provider_code` carries the provider's code (OBE064 proposal already open, CBE022 account already exists, OBE062 clientCode already linked) so the audit trail records the ground for the refusal. CBE022 is attributed only on this organization's own evidence: `onboarding_account_exists_in_project`, `onboarding_account_exists_elsewhere` (another project of the organization) or `onboarding_account_exists_unattributed` (no evidence; not concluded to be anyone's). E2 also answers here `onboarding_attempt_in_progress` (another request holds this clientCode's reservation; repeat later), `onboarding_client_code_conflict` for a clientCode this project used for another document, and `onboarding_unreserved`. On the OBE062 recovery, `consumer_onboarded_in_sibling_project`: the consumer is already onboarded in another project of the caller's organization, and the body carries `holding_project_id`. Bare body.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "onboarding_proposal_open_elsewhere", + "onboarding_account_exists_elsewhere", + "onboarding_account_exists_in_project", + "onboarding_account_exists_unattributed", + "onboarding_client_code_conflict", + "onboarding_attempt_in_progress", + "onboarding_unreserved", + "consumer_onboarded_in_sibling_project" + ] + }, + "provider_code": { + "type": "string" + }, + "retriable": { + "type": "boolean" + }, + "message": { + "type": "string" + }, + "holding_project_id": { + "type": "string", + "description": "On `consumer_onboarded_in_sibling_project` only: the project of the organization that holds the consumer." + } + }, + "required": [ + "error", + "message" + ] + } } } - } - }, - "responses": { - "200": { - "description": "OK", + }, + "422": { + "description": "The provider refused the proposal itself (e.g. CBE007 fullName not complete, OBE166 contrato social not a PDF). No proposal exists. Bare body.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "status": { + "error": { "type": "string", "enum": [ - "executed" + "onboarding_proposal_refused" ] }, - "foreign_authorization_id": { - "type": "string", - "description": "`fauth_`-prefixed. The id `GET /v1/facilitator/x402/executions/{id}` takes." + "provider_code": { + "type": [ + "string", + "null" + ] }, - "mandate_id": { - "type": "string" + "reason": { + "type": [ + "string", + "null" + ] }, - "execution_id": { + "message": { "type": "string" - }, - "signer": { - "type": "string", - "description": "The address recovered from the signature." - }, - "settlement": { + } + }, + "required": [ + "error", + "provider_code", + "reason", + "message" + ] + } + } + } + }, + "429": { + "description": "E2: the sandbox proposal quota is used up, 2 per test project in 30 days (`window: project_30d`) or 30 per São Paulo day across every organization (`window: global_day`). Nothing was reserved or sent. A refused or locally invalid proposal never counts. Or `project_access_call_cap`: the sandbox call caps (60 per clock hour and 300 per São Paulo day per project, 3,000 per day globally) refused the call before it was sent; `Retry-After` is the seconds until that fixed window turns (the next clock hour, or São Paulo midnight). Bare body.", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "type": "object", "properties": { - "tx_hash": { - "type": "string" + "error": { + "type": "string", + "enum": [ + "onboarding_quota_exceeded" + ] }, - "network": { + "window": { "type": "string", - "description": "`base-sepolia` or `base`." + "enum": [ + "project_30d", + "global_day" + ] }, - "money_moved": { - "type": "boolean" + "max": { + "type": "integer" }, - "adapter": { - "type": "string", - "description": "`x402-facilitator-` followed by the network." + "message": { + "type": "string" } }, "required": [ - "tx_hash", - "network", - "money_moved", - "adapter" + "error", + "window", + "max", + "message" ] }, - "receipt": { + { "type": "object", "properties": { - "id": { - "type": "string" + "error": { + "type": "string", + "enum": [ + "project_access_call_cap" + ] }, - "state": { + "window": { "type": "string", "enum": [ - "paid", - "exception", - "delivered" + "hour", + "day" + ] + }, + "scope": { + "type": "string", + "enum": [ + "project", + "global" + ] + }, + "max": { + "type": "integer" + }, + "retry_after_seconds": { + "type": [ + "integer", + "null" ], - "description": "`delivered` once the rail-native delivery proof folds in — on a crypto rail the settlement transaction IS the proof, so there is no invoice to wait for. The fold is best-effort and never unwinds a settled transfer, so a `paid` here can mean the fold failed, not that the money did." + "description": "Seconds until the fixed window turns: the next clock hour, or São Paulo midnight. The same value as `Retry-After`." }, - "chain": { + "message": { "type": "string" } }, "required": [ - "id", - "state", - "chain" + "error", + "window", + "scope", + "max", + "retry_after_seconds", + "message" ] } - }, - "required": [ - "status", - "foreign_authorization_id", - "mandate_id", - "execution_id", - "signer", - "settlement", - "receipt" ] } } } }, - "400": { - "description": "Bad Request. `missing_required_field` is the body failing validation, with the Zod issues in `error.details.issues`. `malformed_authorization` is the verifier or the payee binding rejecting a field the schema let through — the schema's address regex accepts any 40 hex digits, including a mixed-case address whose EIP-55 checksum is wrong, and the on-chain address parser does not. It covers `authorization.from`, `authorization.to`, `intent.payee` and `domain.verifyingContract`, and an out-of-range `domain.chainId`. `invalid_payload` is the cap gate refusing the translated mandate's shape.", + "502": { + "description": "The provider call failed, or the router landed on an institution that is not the expected one. Bare body; `message` carries the underlying sentence and is what separates a provider outage from a refusal by the provider. E2: `onboarding_provider_failure` is the provider refusing for a reason that is not the titular's data (its credential, product, our payload, \"try later\", or a code not in the evidence table), with `provider_code`; no proposal exists, and it is retriable.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "error", + "message" + ] + } + } + } + }, + "503": { + "description": "Two answers. `onboarding_outcome_unknown`: the proposal may have reached the provider and its answer was lost, and a query by this request's clientCode found nothing yet. Nothing was sent again. Repeat the SAME request after `Retry-After`: the same consumer and document reuse the clientCode, so no second proposal can be opened. E2: `onboarding_paused`, the server paused opening sandbox accounts (an operational switch); no proposal is opened, one already opened can still be read; `Retry-After` 3600. `onboarding_calls_unavailable`, the register of onboarding calls could not be written; `Retry-After` 30. `policy_denied`: The policy engine could not answer, so the call was refused fail-closed and nothing was dispatched. Infrastructure, not a rule: retry. Bare body. Bare body.", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "type": "object", "properties": { + "error": { + "type": "string", + "enum": [ + "policy_denied" + ] + }, "code": { "type": "string", "enum": [ - "missing_required_field", - "malformed_authorization", - "invalid_payload" + "policy_denied" ] }, - "message": { + "rule_id": { "type": "string" }, - "details": { - "type": "object", - "additionalProperties": {} + "message": { + "type": "string" } }, "required": [ + "error", "code", + "rule_id", "message" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } - } - } - }, - "401": { - "description": "Unauthorized — the SIGNATURE, not the credential. `bad_signature` is a signature that does not recover; `signer_mismatch` is one that recovers to an address other than `authorization.from`. A rejected API key or access token never reaches this handler.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { + { "type": "object", "properties": { - "code": { + "error": { "type": "string", "enum": [ - "bad_signature", - "signer_mismatch" + "onboarding_paused" + ] + }, + "retriable": { + "type": "boolean", + "enum": [ + true ] }, "message": { "type": "string" + } + }, + "required": [ + "error", + "retriable", + "message" + ] + }, + { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "onboarding_calls_unavailable" + ] }, - "details": { - "type": "object", - "additionalProperties": {} + "retriable": { + "type": "boolean", + "enum": [ + true + ] + }, + "message": { + "type": "string" } }, "required": [ - "code", + "error", + "retriable", "message" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } - } - } - }, - "409": { - "description": "Conflict — this `(signer, nonce)` has already been executed, so it settles once. `error.details.foreign_authorization_id` names the row that ALREADY executed; no new row was created. The same code answers the race, where a concurrent execution won and the unique index on executed nonces refused the loser — in that case the id is the loser's own row.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { + { "type": "object", "properties": { - "code": { + "error": { "type": "string", "enum": [ - "authorization_replayed" + "onboarding_outcome_unknown" ] }, "message": { "type": "string" }, - "details": { + "next_step": { "type": "object", - "additionalProperties": {} + "properties": { + "code": { + "type": "string", + "enum": [ + "in_review_check_later" + ] + }, + "message": { + "type": "string" + }, + "retry_after_seconds": { + "type": "integer" + } + }, + "required": [ + "code", + "message", + "retry_after_seconds" + ] } }, "required": [ - "code", - "message" + "error", + "message", + "next_step" ] - }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." } - }, - "required": [ - "error", - "request_id" ] } } } + } + }, + "x-codespar-scope": "kyc:write", + "security": [ + { + "bearerAuth": [ + "kyc:write" + ] + } + ] + } + }, + "/v1/account-applications/{id}": { + "get": { + "summary": "Read the status of a consumer account application", + "description": "Where a consumer's account onboarding stands, and — once the provider has approved it — the account and the Pix funding source it produced. Requires the `kyc:read` scope.\n\nTHIS IS NOT A PURE READ, and a caller should plan around that. On the approved branch the handler resolves the account from the provider and then persists: it inserts (or re-resolves) the consumer's `pix-celcoin` funding source, registers a Pix key for it, and anchors the consumer record. Every approval path in the product converges on that one place, so polling this endpoint is how an application becomes a usable funding source. It is idempotent — the funding source id is derived from the consumer id, and re-provisioning merges into the existing row rather than replacing it, so a Pix key already registered is not erased.\n\n`document_number` IS REQUIRED, and the reason is ownership. It is never used to address the provider: the handler loads the proposal recorded under this id and compares. A mismatch, or an id with no recorded proposal, is refused before any provider call and provisions nothing — the attack it closes is an attacker's own approved proposal presented with a victim's document.\n\nTHOSE OWNERSHIP REFUSALS ARRIVE AS 409 with their own code (`document_ownership_unproven`, `onboarding_document_mismatch`), and so does a proposal recorded under ANOTHER project of the organization, in the same words as an unknown id. Only RESOURCE_CREATED binds an account; the proposal is read a bounded number of times when it is not visible yet, and an inconclusive read answers `pending` with `next_step`, never a new proposal.\n\nThe query is NOT schema-validated. The handler reads `request.query` directly and checks only that `document_number` is present; any other parameter is ignored rather than rejected.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The provider's proposal id, returned by `POST /v1/account-applications`." + }, + "required": true, + "description": "The provider's proposal id, returned by `POST /v1/account-applications`.", + "name": "id", + "in": "path" }, - "422": { - "description": "Unprocessable — the request is well-formed and the signature is valid, but a bound refuses it. `authorization_not_yet_valid` and `authorization_expired` are the authorization's own window. `payee_authorization_mismatch` is `intent.payee` differing from the recipient the signature authorizes on-chain, compared after both are checksummed. `per_tx_cap_exceeded` and `total_cap_exceeded` are the cap gate; see the note above on what omitting `total_cap_minor` does. `expired` is the translated mandate outliving its own window between the two checks. `x402_mainnet_cap_exceeded` is the operator's per-payment mainnet ceiling, a second gate on top of the mandate's own.\n\nThe pipeline also guards against a non-positive amount with `amount_below_minimum`, which is NOT in this list: `authorization.value` is validated as strictly greater than zero before the handler runs, so that guard is defence in depth for other callers of the pipeline and is not a result an HTTP caller can produce.", + { + "schema": { + "type": "string", + "description": "REQUIRED. The CPF or CNPJ the caller claims this application is about, checked against the document recorded for the proposal. Formatting is normalized before the comparison." + }, + "required": true, + "description": "REQUIRED. The CPF or CNPJ the caller claims this application is about, checked against the document recorded for the proposal. Formatting is normalized before the comparison.", + "name": "document_number", + "in": "query" + }, + { + "schema": { + "type": "string", + "description": "A fallback only. The recorded proposal's own consumer id wins; this value is used when the recorded row carries none. Omitted, the proposal id stands in." + }, + "required": false, + "description": "A fallback only. The recorded proposal's own consumer id wins; this value is used when the recorded row carries none. Omitted, the proposal id stands in.", + "name": "consumer_id", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", "content": { "application/json": { "schema": { "type": "object", "properties": { - "error": { - "type": "object", + "status": { + "type": "string", + "enum": [ + "pending", + "documentscopy_pending", + "approved", + "rejected" + ], + "description": "FOUR values, and the exported `CelcoinOnboardingStatus` union has five. `unknown` is in the type and is not in this enum because `resolveCelcoinOnboarding` — the only producer this route has — never returns it: its four `return` statements carry `rejected`, `documentscopy_pending`, `pending` (twice) and `approved`. The only other `\"unknown\"` in that file is a `conflict_case`, which is a different field on a different shape.\n\n`approved` means an account EXISTS: the proposal reached RESOURCE_CREATED, the account was read and bound. A proposal the provider reports as APPROVED has no account yet and answers `pending` (A5b), as does any status outside the provider's published vocabulary, a proposal not visible yet after the bounded reads (`proposal_status` NOT_VISIBLE_YET), and a RESOURCE_CREATED proposal whose account number could not be parsed from the provider's fetch response. That last case is logged with the raw body truncated, so a genuine not-minted-yet and a parse that is wrong look the same to the caller and different in the log." + }, + "proposal_status": { + "type": "string", + "description": "The provider's own status for the proposal (RESOURCE_CREATED, APPROVED, PENDING, ...), or NOT_VISIBLE_YET." + }, + "next_step": { + "type": [ + "object", + "null" + ], "properties": { "code": { "type": "string", "enum": [ - "authorization_not_yet_valid", - "authorization_expired", - "payee_authorization_mismatch", - "per_tx_cap_exceeded", - "total_cap_exceeded", - "expired", - "x402_mainnet_cap_exceeded" + "in_review_check_later" ] }, - "message": { + "verification_id": { "type": "string" }, - "details": { - "type": "object", - "additionalProperties": {} + "message": { + "type": "string", + "description": "pt-BR first: \"Em análise, consulte depois\", with the proposal id." + }, + "retry_after_seconds": { + "type": "integer" } }, "required": [ "code", - "message" - ] + "verification_id", + "message", + "retry_after_seconds" + ], + "description": "Present while the application has not concluded: read it again later with the same id. Never open a new application for the document; the provider allows one proposal per document every 24 hours. Null on `approved` and `rejected`." }, - "request_id": { + "rejected_reason": { + "type": "string", + "description": "On `rejected`, the provider's reason when it gives one, as \"CODE: message\"." + }, + "hosted_url": { "type": [ "string", "null" ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "description": "The documentoscopia webview the consumer opens, taken from the proposal's first `documentscopys` entry. Null on `rejected` and on `approved`." + }, + "account": { + "type": [ + "string", + "null" + ], + "description": "The provisioned account number once one exists, else null. Stringified: the provider returns it as either a string or a number.\n\nThe branch is resolved in the same fetch and is NOT returned by this operation; it is returned as the funding source's `branch`." + }, + "funding_source_id": { + "type": [ + "string", + "null" + ], + "description": "The `pix-celcoin` funding source, or null before one exists. Deterministic — `fs_celcoin_` followed by the consumer id, one account per consumer — so a repeat call resolves the same row instead of opening a second one." + }, + "funding_source_status": { + "type": [ + "string", + "null" + ], + "enum": [ + "active", + "held" + ], + "description": "The funding source's status, or null before one exists. `held` for an account opened for a Test project: the account is bound to the project and no payment, receiving or consent uses it, and it has no Pix key yet. `active` in Live, or for an account that was already active." + }, + "pix_key": { + "type": [ + "string", + "null" + ], + "description": "The DICT entry registered for the account, once registration has succeeded. Null before that." + }, + "pix_key_type": { + "type": [ + "string", + "null" + ] + }, + "pix_key_registration_error": { + "type": "string", + "description": "ABSENT from the body unless Pix-key registration failed for an account that is otherwise real and usable. Deliberately non-blocking and deliberately not swallowed: the account works, the wallet's own lazy registration retries the step the next time the consumer needs to receive, and the failure is surfaced here so a caller can log or alert on it. Its presence does not make the application unapproved." } }, "required": [ - "error", - "request_id" + "status", + "proposal_status", + "next_step", + "hosted_url", + "account", + "funding_source_id", + "funding_source_status", + "pix_key", + "pix_key_type" ] } } } }, - "500": { - "description": "Internal error from the cap gate, surfaced rather than swallowed. Reached when the gate fails for a reason that should be impossible on this path — the mandate secret vanishing between the moment it was resolved and the moment the gate looked it up, say. `error.code` is left open here because it echoes whatever the gate reported.", + "400": { + "description": "Bad Request — `document_number` was not supplied. A BARE error body, not the `{ error: { code, message } }` envelope: this handler writes its failures inline and there is no `request_id` in the body.", "content": { "application/json": { "schema": { "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string" - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "properties": { + "error": { + "type": "string", + "enum": [ + "document_number_required" ] - }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "error", - "request_id" + "error" ] } } } }, - "501": { - "description": "Not Implemented — a `live` credential asked for mainnet settlement and the operator has not enabled it. Refused before any signature work, any database write or any wallet call, so nothing is left dangling. A `test` credential cannot reach this: it always settles on testnet.", + "403": { + "description": "E2: this test project's `onboarding` capability is not active, so the proposal is not read. Nothing was sent.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "x402_mainnet_not_enabled" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "onboarding_capability_inactive" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "capability": { + "type": "string", + "enum": [ + "onboarding" + ] + }, + "message": { + "type": "string" } }, "required": [ "error", - "request_id" + "capability", + "message" ] } } } }, - "502": { - "description": "Bad Gateway — on-chain settlement failed. The evidence row is marked `rejected` with `reject_code = 'settlement_failed'` and its id is in `error.details.foreign_authorization_id`. A broadcast is not a settlement: a transaction that reverts or is not confirmed in time lands here too, so a 502 does NOT mean the money is in flight.", + "409": { + "description": "E2 adds the binding refusals: `account_bound_elsewhere` (the account is, or was, bound to another project), `account_binding_closed` (this project closed its binding; never reopened automatically), `consumer_holds_other_binding`. A refusal decided before anything is bound: the id has no proposal recorded for this project (`document_ownership_unproven`), the document does not match the one the proposal verified, or the account the provider returned names another document (`onboarding_document_mismatch`), or the funding source written did not confirm as this consumer's in this project (`funding_source_binding_unconfirmed`). Or the consumer is already onboarded in another project of the caller's organization (`consumer_onboarded_in_sibling_project`), refused before any write, and the body carries `holding_project_id`. Bare body.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "settlement_failed" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "document_ownership_unproven", + "onboarding_document_mismatch", + "consumer_bound_to_other_document", + "funding_source_binding_unconfirmed", + "consumer_onboarded_in_sibling_project", + "account_bound_elsewhere", + "account_binding_closed", + "consumer_holds_other_binding" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "message": { + "type": "string" + }, + "holding_project_id": { + "type": "string", + "description": "On `consumer_onboarded_in_sibling_project` only: the project of the organization that holds the consumer." } }, "required": [ "error", - "request_id" + "message" ] } } } - } - }, - "x-codespar-scope": "facilitator:execute", - "security": [ - { - "bearerAuth": [ - "facilitator:execute" - ] - } - ] - } - }, - "/v1/facilitator/x402/executions/{id}": { - "get": { - "summary": "Read one ingested foreign authorization", - "description": "The evidence row for a foreign authorization: the signed object's own facts, and the internal objects it produced. Requires the `facilitator:execute` scope — the same scope as the POST, so a credential that can read this lane can also execute on it.\n\nThe evidence row is inserted `verified` only AFTER the payee binding, the replay guard and the amount guard have all passed — not when the signature verifies. A refusal at any of those three leaves NO row, so an authorization that verified cryptographically may have no record here at all. From that point every refusal marks the row `rejected` with its code in `reject_code`, and success marks it `executed` in the same transaction that seals the receipt, so the two commit together.\n\nThis row is NOT the money's source of truth — the settlement transaction and the ledger are — and it is NOT the mandate. It is the bridge that lets a receipt point back to the foreign trust root that authorized the spend.\n\nRESOLUTION IS SCOPED TO THE ORGANIZATION ONLY. The query predicates on `org_id` and the id, with no project term, so a row created under a sibling project in the same organization IS readable here — unlike the funding-source read in this same group, which is narrower.\n\nThe signed payload itself is stored on the row and is not returned: the authorization, the domain, the intent and the signature stay server-side.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "`fauth_`-prefixed, as returned by the POST." - }, - "required": true, - "description": "`fauth_`-prefixed, as returned by the POST.", - "name": "id", - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK", + }, + "429": { + "description": "E2: the sandbox call caps (60 per clock hour and 300 per São Paulo day per project, 3,000 per day globally) refused the status read before it was sent. `Retry-After` is the seconds until that fixed window turns (the next clock hour, or São Paulo midnight). Bare body.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "`fauth_`-prefixed." - }, - "kind": { + "error": { "type": "string", "enum": [ - "x402", - "ap2", - "acp" - ], - "description": "Closed by the `kind` CHECK in `packages/api/src/migrations/0099_foreign_authorizations.sql`, which is also where this table's `status` set is closed. Only `x402` is written today; `ap2` and `acp` are reserved for the ingestion paths that reuse the same machinery." - }, - "signer": { - "type": "string", - "description": "The address RECOVERED from the signature, not the `from` the caller sent." - }, - "payee": { - "type": "string", - "description": "The on-chain recipient, checksummed." - }, - "nonce": { - "type": "string", - "description": "The EIP-3009 nonce, 32 bytes hex. Unique per authorization." - }, - "chain_id": { - "type": [ - "integer", - "null" + "project_access_call_cap" ] }, - "asset": { + "window": { "type": [ "string", "null" ], - "description": "The token contract — the EIP-712 `verifyingContract`, checksummed." - }, - "value_atomic": { - "type": "string", - "description": "The exact authorized amount in atomic units (USDC, 6dp). This is what settles." - }, - "amount_minor": { - "type": "integer", - "description": "A COARSE cents figure, rounded UP from `value_atomic`, kept so older minor-denominated reads still work. It is NOT what the cap gate ran on and NOT what moved: the gate and the settlement both use atomic. Read `value_atomic` when the number has to be exact." - }, - "status": { - "type": "string", "enum": [ - "verified", - "executed", - "rejected" - ], - "description": "Closed by `CHECK (status IN ('verified','executed','rejected'))` in `packages/api/src/migrations/0099_foreign_authorizations.sql`. The evidence row is inserted `verified` only AFTER the payee binding, the replay guard and the amount guard have all passed — not when the signature verifies. A refusal at any of those three leaves NO row, so an authorization that verified cryptographically may have no record here at all. From that point every refusal marks the row `rejected` with its code in `reject_code`, and success marks it `executed` in the same transaction that seals the receipt, so the two commit together." - }, - "reject_code": { - "type": [ - "string", - "null" - ], - "description": "The refusal ground on a `rejected` row: the cap-gate or mainnet-cap code, or the literal `settlement_failed`. It is the same string the POST answered with under `error.code`. Null otherwise, and an open string here because its source set is the cap gate's, not this table's." - }, - "mandate_id": { - "type": [ - "string", - "null" - ], - "description": "The internal mandate the foreign authorization was translated onto. Set on success." - }, - "execution_id": { - "type": [ - "string", - "null" - ], - "description": "`x402exec_`-prefixed. Set on success." + "hour", + "day" + ] }, - "receipt_id": { + "scope": { "type": [ "string", "null" ], - "description": "The sealed Control Record receipt. Set on success." + "enum": [ + "project", + "global" + ] }, - "settlement_tx": { + "max": { "type": [ - "string", + "integer", "null" - ], - "description": "The on-chain settlement transaction hash. Set on success." + ] }, - "network": { + "retry_after_seconds": { "type": [ - "string", + "integer", "null" - ], - "description": "`base-sepolia` for a `test` credential, `base` for a `live` one. Stamped at insert time, so a `rejected` row carries it too." + ] }, - "created_at": { - "type": "string", - "format": "date-time" + "message": { + "type": "string" } }, "required": [ - "id", - "kind", - "signer", - "payee", - "nonce", - "chain_id", - "asset", - "value_atomic", - "amount_minor", - "status", - "reject_code", - "mandate_id", - "execution_id", - "receipt_id", - "settlement_tx", - "network", - "created_at" + "error", + "window", + "scope", + "max", + "retry_after_seconds", + "message" ] } } } }, - "404": { - "description": "Not Found. No foreign authorization with this id in the caller's organization — including the case where the authorization verified but was refused before any row was written.", + "502": { + "description": "Bad Gateway. The provider call failed. `message` carries the underlying sentence. Bare body, no `request_id`.", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "foreign_authorization_not_found" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "type": "string", + "enum": [ + "kyc_status_failed" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "message": { + "type": "string" } }, "required": [ "error", - "request_id" - ] - } - } - } - } - }, - "x-codespar-scope": "facilitator:execute", - "security": [ - { - "bearerAuth": [ - "facilitator:execute" - ] - } - ] - } - }, - "/v1/issuer/cards/{id}": { - "get": { - "deprecated": true, - "summary": "Read one issued card, or the mint flow behind it", - "externalDocs": { - "url": "https://github.com/codespar/codespar-enterprise/issues/979", - "description": "ent#979 — canonical path and alias window" - }, - "description": "DEPRECATED alias of `GET /v1/cards/{id}` (ent#979), kept for two releases. Same handler, same required scope; switch the path and nothing else changes.\n\nONE path, TWO bodies, chosen by the id's prefix. An `imf_` id is a mint flow and answers with the flow; anything else is read as a card row and answers with the card. Branch on the prefix you sent, or on `flow_id` being present, never on field order.\n\nResolution is scoped to the organization AND the project the credential authenticates for: both lookups filter on all three of id, org and project, so a card held by a sibling project in the same organization answers 404 here, indistinguishable from one that never existed.\n\nNo cardholder data crosses this boundary. The number is represented by `last4` and by the token id; PAN, CVV and expiry never enter the process that serves this route.\n\nRequires the `cards:read` scope.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "`icrd_` for a card, `imf_` for a mint flow. The prefix selects the body." - }, - "required": true, - "description": "`icrd_` for a card, `imf_` for a mint flow. The prefix selects the body.", - "name": "id", - "in": "path" - } - ], - "responses": { - "200": { - "description": "OK. The card, or the mint flow when the id was an `imf_` one — see the description for which id yields which.", - "content": { - "application/json": { - "schema": { - "anyOf": [ - { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "`icrd_`-prefixed. Our row id for the card, not the issuer's handle." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ], - "description": "The issuing rail the card was minted on. Closed in the type, not just in data." - }, - "card_id": { - "type": "string", - "description": "The issuer's own global handle for the card." - }, - "last4": { - "type": "string", - "description": "Last four digits. The only fragment of the number this API returns." - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ] - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ] - }, - "token_id": { - "type": [ - "string", - "null" - ], - "description": "The card-data-environment token id, null until the mint flow allocates one. Allocation happens BEFORE the card material is ingested, so a token id with no material behind it is a recorded failure rather than a silent gap. It is the handle a PCI-scoped surface exchanges for card material; no card material is reachable through this API with it." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ] - }, - { - "type": "object", - "properties": { - "flow_id": { - "type": "string", - "description": "`imf_`-prefixed. The mint attempt, keyed by the caller's idempotency key." - }, - "state": { - "type": "string", - "enum": [ - "pending", - "issued", - "revoked", - "failed" - ] - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ] - }, - "reason": { - "type": [ - "string", - "null" - ], - "description": "Why the flow is parked or failed, when the lane recorded one." - }, - "kyc_url": { - "type": [ - "string", - "null" - ], - "description": "The issuer-hosted step the holder must complete before the flow can move on." - }, - "created_at": { - "type": "string", - "format": "date-time" - }, - "card": { - "type": [ - "object", - "null" - ], - "properties": { - "id": { - "type": "string", - "description": "`icrd_`-prefixed. Our row id for the card, not the issuer's handle." - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ], - "description": "The issuing rail the card was minted on. Closed in the type, not just in data." - }, - "card_id": { - "type": "string", - "description": "The issuer's own global handle for the card." - }, - "last4": { - "type": "string", - "description": "Last four digits. The only fragment of the number this API returns." - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ] - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ] - }, - "token_id": { - "type": [ - "string", - "null" - ], - "description": "The card-data-environment token id, null until the mint flow allocates one. Allocation happens BEFORE the card material is ingested, so a token id with no material behind it is a recorded failure rather than a silent gap. It is the handle a PCI-scoped surface exchanges for card material; no card material is reachable through this API with it." - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ], - "description": "Present ONLY when the flow reached `issued` AND carries a card row id. It is then the card itself, or null if that row could not be read back. On every other state the key is absent rather than null, so `\"card\" in body` and `body.card !== null` are different questions." - } - }, - "required": [ - "flow_id", - "state", - "issuer", - "reason", - "kyc_url", - "created_at" - ] - } + "message" ] } } } }, - "404": { - "description": "Not Found. No card and no mint flow with this id in the caller's organization and project. Both branches answer with the same code and differ only in the message.", + "503": { + "description": "E2: the register of onboarding calls could not be written, so the status was not read (fails closed). `Retry-After: 30`. Bare body.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string", - "enum": [ - "issuer_card_unknown" - ] - }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" + "error": { + "type": "string", + "enum": [ + "onboarding_calls_unavailable" ] }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." + "message": { + "type": "string" } }, "required": [ "error", - "request_id" + "message" ] } } } } }, - "x-codespar-scope": "cards:read", + "x-codespar-scope": "kyc:read", "security": [ { "bearerAuth": [ - "cards:read" + "kyc:read" ] } ] } }, - "/v1/issuer/cards": { + "/v1/facilitator/x402/executions": { "post": { - "deprecated": true, - "summary": "Issue a card under a signed mandate (deprecated path)", - "externalDocs": { - "url": "https://github.com/codespar/codespar-enterprise/issues/979", - "description": "ent#979 — canonical path and alias window" - }, - "description": "DEPRECATED alias of `POST /v1/cards` (ent#979), kept for two releases. Same handler, same required scope; switch the path and nothing else changes.\n\nThree success outcomes: `201` issued the card now, `202` the issuer asked for KYC of the holder (`kyc_url` is where to send the person), `200` is a repeat of the same `Idempotency-Key` on a flow that already finished. Repeating with the SAME key is the recovery path: a `502 issuer_ingest_failed` means the card EXISTS and only the ingest failed, and a new key would issue a second card.", - "parameters": [ - { - "schema": { - "type": "string" - }, - "required": false, - "name": "Idempotency-Key", - "in": "header" - } - ], + "summary": "Ingest and execute a foreign x402 authorization", + "description": "Takes an EIP-3009 `transferWithAuthorization` signed OUTSIDE CodeSpar by a foreign wallet, verifies it, translates it onto an internal mandate, runs it through the same cap gate every other spend passes, settles it on-chain and seals a receipt. A 200 here means USDC MOVED. Requires the `facilitator:execute` scope.\n\nTHE CAPS ARE DECLARED BY THE CALLER. `intent.max_amount_minor` and `intent.total_cap_minor` come from this request, so they are limits the caller states for itself, not a ceiling the organization sets. The amount charged is the one the payer signed (`authorization.value`), and on mainnet an operator hard cap applies on top.\n\nOMITTING `intent.total_cap_minor` DOES NOT REMOVE THE LIFETIME CAP — it sets that cap equal to `max_amount_minor`. The translation reads `totalCap = totalCapAtomic ?? perTxCap`, and this route never marks the intent pay-per-access, so the gate compares the signer's PRIOR EXECUTED spend in this organization plus this payment against that cap. The practical consequence: leave `total_cap_minor` out and the SECOND execution by the same signer is refused with 422 `total_cap_exceeded`, even though the first succeeded and each authorization was independently signed. Send `total_cap_minor` explicitly whenever a signer may pay more than once.\n\nAMOUNTS ARE MINOR ON THE WIRE AND ATOMIC INSIDE. `max_amount_minor` and `total_cap_minor` are cents; they are converted to atomic USDC at the boundary, and the cap gate then compares them against `authorization.value`, which is already atomic. So the authorization's value is not scaled to match the caps — the caps are scaled to match it.\n\nThe evidence row is inserted `verified` only AFTER the payee binding, the replay guard and the amount guard have all passed — not when the signature verifies. A refusal at any of those three leaves NO row, so an authorization that verified cryptographically may have no record here at all. From that point every refusal marks the row `rejected` with its code in `reject_code`, and success marks it `executed` in the same transaction that seals the receipt, so the two commit together.\n\n`error.details` IS ALWAYS PRESENT on a failure, and is `{}` on most of them. It carries `foreign_authorization_id` in exactly two situations: when a row was created and then marked `rejected` (the cap gate, the mainnet ceiling, a settlement failure), and on the 409 replay — where the id is the PRIOR EXECUTED row's, not a new one. The 400 raised by body validation carries `issues` instead.\n\n`test` credentials always settle on `base-sepolia`; no flag can send them to mainnet. A `live` credential settles on `base` only when the operator has enabled mainnet, and is refused with 501 otherwise, before any wallet is touched.", "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { - "country": { - "type": "string", - "description": "ISO 3166-1 alpha-2, uppercase." - }, - "currency": { - "type": "string", - "description": "ISO 4217, uppercase." - }, - "holder": { + "authorization": { "type": "object", "properties": { - "full_name": { - "type": "string" + "from": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{40}$" }, - "email": { + "to": { "type": "string", - "format": "email" + "pattern": "^0x[0-9a-fA-F]{40}$" }, - "birthdate": { - "type": "string" + "value": { + "type": "string", + "pattern": "^\\d+$" }, - "document": { - "type": "object", - "properties": { - "type": { - "type": "string" - }, - "value": { - "type": "string" - }, - "issuing_country": { - "type": "string" - } - }, - "required": [ - "type", - "value", - "issuing_country" - ] + "validAfter": { + "type": "string", + "pattern": "^\\d+$" }, - "address": { - "type": "object", - "properties": { - "line1": { - "type": "string" - }, - "line2": { - "type": "string" - }, - "street_number": { - "type": "string" - }, - "neighborhood": { - "type": "string" - }, - "city": { - "type": "string" - }, - "state": { - "type": "string" - }, - "postal_code": { - "type": "string" - }, - "municipality": { - "type": "string" - }, - "country": { - "type": "string" - } - }, - "required": [ - "line1", - "city", - "postal_code", - "country" - ] + "validBefore": { + "type": "string", + "pattern": "^\\d+$" }, - "phone": { - "type": "string" + "nonce": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{64}$" } }, "required": [ - "full_name", - "email", - "birthdate", - "document", - "address" + "from", + "to", + "value", + "validAfter", + "validBefore", + "nonce" ] }, - "mandate_id": { + "domain": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "version": { + "type": "string", + "minLength": 1, + "maxLength": 20 + }, + "chainId": { + "type": "integer", + "exclusiveMinimum": 0 + }, + "verifyingContract": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{40}$" + } + }, + "required": [ + "name", + "version", + "chainId", + "verifyingContract" + ] + }, + "signature": { "type": "string", - "minLength": 1, - "description": "Required: there is no card without a signed mandate." + "pattern": "^0x[0-9a-fA-F]{130}$" }, - "metadata": { + "intent": { "type": "object", - "additionalProperties": { - "type": "string", - "maxLength": 500 - } + "properties": { + "payee": { + "type": "string", + "pattern": "^0x[0-9a-fA-F]{40}$" + }, + "resource": { + "type": "string", + "minLength": 1, + "maxLength": 300 + }, + "seller": { + "type": "string", + "minLength": 1, + "maxLength": 200 + }, + "purpose": { + "type": "string", + "minLength": 1, + "maxLength": 120 + }, + "max_amount_minor": { + "type": "integer", + "exclusiveMinimum": 0 + }, + "total_cap_minor": { + "type": "integer", + "exclusiveMinimum": 0 + }, + "resource_url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + } + }, + "required": [ + "payee", + "resource", + "purpose", + "max_amount_minor" + ] } }, "required": [ - "country", - "currency", - "holder", - "mandate_id" + "authorization", + "domain", + "signature", + "intent" ] } } @@ -29898,294 +32728,141 @@ "content": { "application/json": { "schema": { - "anyOf": [ - { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "executed" + ] + }, + "foreign_authorization_id": { + "type": "string", + "description": "`fauth_`-prefixed. The id `GET /v1/facilitator/x402/executions/{id}` takes." + }, + "mandate_id": { + "type": "string" + }, + "execution_id": { + "type": "string" + }, + "signer": { + "type": "string", + "description": "The address recovered from the signature." + }, + "settlement": { "type": "object", "properties": { - "state": { + "tx_hash": { + "type": "string" + }, + "network": { "type": "string", - "enum": [ - "issued" - ] + "description": "`base-sepolia` or `base`." }, - "flow_id": { - "type": "string" + "money_moved": { + "type": "boolean" }, - "card": { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ] - }, - "card_id": { - "type": "string" - }, - "last4": { - "type": "string" - }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ] - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ] - }, - "token_id": { - "type": [ - "string", - "null" - ] - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" - } - }, - "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ] + "adapter": { + "type": "string", + "description": "`x402-facilitator-` followed by the network." } }, "required": [ - "state", - "flow_id", - "card" + "tx_hash", + "network", + "money_moved", + "adapter" ] }, - { + "receipt": { "type": "object", "properties": { - "flow_id": { + "id": { "type": "string" }, "state": { "type": "string", "enum": [ - "pending", - "issued", - "revoked", - "failed" - ] - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ] - }, - "reason": { - "type": [ - "string", - "null" - ] - }, - "kyc_url": { - "type": [ - "string", - "null" - ] + "paid", + "exception", + "delivered" + ], + "description": "`delivered` once the rail-native delivery proof folds in — on a crypto rail the settlement transaction IS the proof, so there is no invoice to wait for. The fold is best-effort and never unwinds a settled transfer, so a `paid` here can mean the fold failed, not that the money did." }, - "created_at": { - "type": "string", - "format": "date-time" + "chain": { + "type": "string" } }, "required": [ - "flow_id", + "id", "state", - "issuer", - "reason", - "kyc_url", - "created_at" + "chain" ] } + }, + "required": [ + "status", + "foreign_authorization_id", + "mandate_id", + "execution_id", + "signer", + "settlement", + "receipt" ] } } } }, - "201": { - "description": "OK", + "400": { + "description": "Bad Request. `missing_required_field` is the body failing validation, with the Zod issues in `error.details.issues`. `malformed_authorization` is the verifier or the payee binding rejecting a field the schema let through — the schema's address regex accepts any 40 hex digits, including a mixed-case address whose EIP-55 checksum is wrong, and the on-chain address parser does not. It covers `authorization.from`, `authorization.to`, `intent.payee` and `domain.verifyingContract`, and an out-of-range `domain.chainId`. `invalid_payload` is the cap gate refusing the translated mandate's shape.", "content": { "application/json": { "schema": { "type": "object", "properties": { - "state": { - "type": "string", - "enum": [ - "issued" - ] - }, - "flow_id": { - "type": "string" - }, - "card": { + "error": { "type": "object", "properties": { - "id": { - "type": "string" - }, - "issuer": { + "code": { "type": "string", "enum": [ - "pomelo", - "bridge" + "missing_required_field", + "malformed_authorization", + "invalid_payload" ] }, - "card_id": { - "type": "string" - }, - "last4": { + "message": { "type": "string" }, - "network": { - "type": "string", - "enum": [ - "visa", - "mastercard" - ] - }, - "status": { - "type": "string", - "enum": [ - "active", - "blocked", - "canceled" - ] - }, - "token_id": { - "type": [ - "string", - "null" - ] - }, - "cde": { - "type": "string", - "enum": [ - "ingested", - "not_ingested", - "not_configured" - ], - "description": "Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed." - }, - "created_at": { - "type": "string", - "format": "date-time" + "details": { + "type": "object", + "additionalProperties": {} } }, "required": [ - "id", - "issuer", - "card_id", - "last4", - "network", - "status", - "token_id", - "cde", - "created_at" - ] - } - }, - "required": [ - "state", - "flow_id", - "card" - ] - } - } - } - }, - "202": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "flow_id": { - "type": "string" - }, - "state": { - "type": "string", - "enum": [ - "pending", - "issued", - "revoked", - "failed" - ] - }, - "issuer": { - "type": "string", - "enum": [ - "pomelo", - "bridge" - ] - }, - "reason": { - "type": [ - "string", - "null" + "code", + "message" ] }, - "kyc_url": { + "request_id": { "type": [ "string", "null" - ] - }, - "created_at": { - "type": "string", - "format": "date-time" + ], + "description": "Echoes the `X-Request-Id` header when the request carried one." } }, "required": [ - "flow_id", - "state", - "issuer", - "reason", - "kyc_url", - "created_at" + "error", + "request_id" ] } } } }, - "400": { - "description": "Body outside the schema, a country/currency pair with no corridor, a rejected holder, or controls requested that the rail does not have.", + "401": { + "description": "Unauthorized — the SIGNATURE, not the credential. `bad_signature` is a signature that does not recover; `signer_mismatch` is one that recovers to an address other than `authorization.from`. A rejected API key or access token never reaches this handler.", "content": { "application/json": { "schema": { @@ -30197,10 +32874,8 @@ "code": { "type": "string", "enum": [ - "invalid_body", - "issuer_corridor_unsupported", - "invalid_holder", - "issuer_controls_unsupported" + "bad_signature", + "signer_mismatch" ] }, "message": { @@ -30232,8 +32907,8 @@ } } }, - "403": { - "description": "The key and the issuer environment do not match.", + "409": { + "description": "Conflict — this `(signer, nonce)` has already been executed, so it settles once. `error.details.foreign_authorization_id` names the row that ALREADY executed; no new row was created. The same code answers the race, where a concurrent execution won and the unique index on executed nonces refused the loser — in that case the id is the loser's own row.", "content": { "application/json": { "schema": { @@ -30245,8 +32920,7 @@ "code": { "type": "string", "enum": [ - "stage_issuer_live_key", - "live_issuer_test_key" + "authorization_replayed" ] }, "message": { @@ -30278,8 +32952,8 @@ } } }, - "404": { - "description": "The named mandate does not exist in this organization.", + "422": { + "description": "Unprocessable — the request is well-formed and the signature is valid, but a bound refuses it. `authorization_not_yet_valid` and `authorization_expired` are the authorization's own window. `payee_authorization_mismatch` is `intent.payee` differing from the recipient the signature authorizes on-chain, compared after both are checksummed. `per_tx_cap_exceeded` and `total_cap_exceeded` are the cap gate; see the note above on what omitting `total_cap_minor` does. `expired` is the translated mandate outliving its own window between the two checks. `x402_mainnet_cap_exceeded` is the operator's per-payment mainnet ceiling, a second gate on top of the mandate's own.\n\nThe pipeline also guards against a non-positive amount with `amount_below_minimum`, which is NOT in this list: `authorization.value` is validated as strictly greater than zero before the handler runs, so that guard is defence in depth for other callers of the pipeline and is not a result an HTTP caller can produce.", "content": { "application/json": { "schema": { @@ -30291,7 +32965,13 @@ "code": { "type": "string", "enum": [ - "mandate_not_found" + "authorization_not_yet_valid", + "authorization_expired", + "payee_authorization_mismatch", + "per_tx_cap_exceeded", + "total_cap_exceeded", + "expired", + "x402_mainnet_cap_exceeded" ] }, "message": { @@ -30323,8 +33003,8 @@ } } }, - "409": { - "description": "Key repeated with a different body, or used before a key rotation and no longer matchable (use a new key), or the mandate is not active.", + "500": { + "description": "Internal error from the cap gate, surfaced rather than swallowed. Reached when the gate fails for a reason that should be impossible on this path — the mandate secret vanishing between the moment it was resolved and the moment the gate looked it up, say. `error.code` is left open here because it echoes whatever the gate reported.", "content": { "application/json": { "schema": { @@ -30334,11 +33014,7 @@ "type": "object", "properties": { "code": { - "type": "string", - "enum": [ - "idempotency_key_conflict", - "mandate_not_active" - ] + "type": "string" }, "message": { "type": "string" @@ -30369,8 +33045,8 @@ } } }, - "500": { - "description": "Flow issued with no readable card row.", + "501": { + "description": "Not Implemented — a `live` credential asked for mainnet settlement and the operator has not enabled it. Refused before any signature work, any database write or any wallet call, so nothing is left dangling. A `test` credential cannot reach this: it always settles on testnet.", "content": { "application/json": { "schema": { @@ -30382,7 +33058,7 @@ "code": { "type": "string", "enum": [ - "issuer_card_unknown" + "x402_mainnet_not_enabled" ] }, "message": { @@ -30415,7 +33091,7 @@ } }, "502": { - "description": "The issuer failed, or the card was issued and the ingest failed; in the second case the card comes back in `details.card` and the recovery is to repeat the same key.", + "description": "Bad Gateway — on-chain settlement failed. The evidence row is marked `rejected` with `reject_code = 'settlement_failed'` and its id is in `error.details.foreign_authorization_id`. A broadcast is not a settlement: a transaction that reverts or is not confirmed in time lands here too, so a 502 does NOT mean the money is in flight.", "content": { "application/json": { "schema": { @@ -30427,8 +33103,7 @@ "code": { "type": "string", "enum": [ - "issuer_mint_failed", - "issuer_ingest_failed" + "settlement_failed" ] }, "message": { @@ -30459,9 +33134,169 @@ } } } + } + }, + "x-codespar-scope": "facilitator:execute", + "security": [ + { + "bearerAuth": [ + "facilitator:execute" + ] + } + ] + } + }, + "/v1/facilitator/x402/executions/{id}": { + "get": { + "summary": "Read one ingested foreign authorization", + "description": "The evidence row for a foreign authorization: the signed object's own facts, and the internal objects it produced. Requires the `facilitator:execute` scope — the same scope as the POST, so a credential that can read this lane can also execute on it.\n\nThe evidence row is inserted `verified` only AFTER the payee binding, the replay guard and the amount guard have all passed — not when the signature verifies. A refusal at any of those three leaves NO row, so an authorization that verified cryptographically may have no record here at all. From that point every refusal marks the row `rejected` with its code in `reject_code`, and success marks it `executed` in the same transaction that seals the receipt, so the two commit together.\n\nThis row is NOT the money's source of truth — the settlement transaction and the ledger are — and it is NOT the mandate. It is the bridge that lets a receipt point back to the foreign trust root that authorized the spend.\n\nRESOLUTION IS SCOPED TO THE ORGANIZATION ONLY. The query predicates on `org_id` and the id, with no project term, so a row created under a sibling project in the same organization IS readable here — unlike the funding-source read in this same group, which is narrower.\n\nThe signed payload itself is stored on the row and is not returned: the authorization, the domain, the intent and the signature stay server-side.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "`fauth_`-prefixed, as returned by the POST." + }, + "required": true, + "description": "`fauth_`-prefixed, as returned by the POST.", + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "`fauth_`-prefixed." + }, + "kind": { + "type": "string", + "enum": [ + "x402", + "ap2", + "acp" + ], + "description": "Closed by the `kind` CHECK in `packages/api/src/migrations/0099_foreign_authorizations.sql`, which is also where this table's `status` set is closed. Only `x402` is written today; `ap2` and `acp` are reserved for the ingestion paths that reuse the same machinery." + }, + "signer": { + "type": "string", + "description": "The address RECOVERED from the signature, not the `from` the caller sent." + }, + "payee": { + "type": "string", + "description": "The on-chain recipient, checksummed." + }, + "nonce": { + "type": "string", + "description": "The EIP-3009 nonce, 32 bytes hex. Unique per authorization." + }, + "chain_id": { + "type": [ + "integer", + "null" + ] + }, + "asset": { + "type": [ + "string", + "null" + ], + "description": "The token contract — the EIP-712 `verifyingContract`, checksummed." + }, + "value_atomic": { + "type": "string", + "description": "The exact authorized amount in atomic units (USDC, 6dp). This is what settles." + }, + "amount_minor": { + "type": "integer", + "description": "A COARSE cents figure, rounded UP from `value_atomic`, kept so older minor-denominated reads still work. It is NOT what the cap gate ran on and NOT what moved: the gate and the settlement both use atomic. Read `value_atomic` when the number has to be exact." + }, + "status": { + "type": "string", + "enum": [ + "verified", + "executed", + "rejected" + ], + "description": "Closed by `CHECK (status IN ('verified','executed','rejected'))` in `packages/api/src/migrations/0099_foreign_authorizations.sql`. The evidence row is inserted `verified` only AFTER the payee binding, the replay guard and the amount guard have all passed — not when the signature verifies. A refusal at any of those three leaves NO row, so an authorization that verified cryptographically may have no record here at all. From that point every refusal marks the row `rejected` with its code in `reject_code`, and success marks it `executed` in the same transaction that seals the receipt, so the two commit together." + }, + "reject_code": { + "type": [ + "string", + "null" + ], + "description": "The refusal ground on a `rejected` row: the cap-gate or mainnet-cap code, or the literal `settlement_failed`. It is the same string the POST answered with under `error.code`. Null otherwise, and an open string here because its source set is the cap gate's, not this table's." + }, + "mandate_id": { + "type": [ + "string", + "null" + ], + "description": "The internal mandate the foreign authorization was translated onto. Set on success." + }, + "execution_id": { + "type": [ + "string", + "null" + ], + "description": "`x402exec_`-prefixed. Set on success." + }, + "receipt_id": { + "type": [ + "string", + "null" + ], + "description": "The sealed Control Record receipt. Set on success." + }, + "settlement_tx": { + "type": [ + "string", + "null" + ], + "description": "The on-chain settlement transaction hash. Set on success." + }, + "network": { + "type": [ + "string", + "null" + ], + "description": "`base-sepolia` for a `test` credential, `base` for a `live` one. Stamped at insert time, so a `rejected` row carries it too." + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "kind", + "signer", + "payee", + "nonce", + "chain_id", + "asset", + "value_atomic", + "amount_minor", + "status", + "reject_code", + "mandate_id", + "execution_id", + "receipt_id", + "settlement_tx", + "network", + "created_at" + ] + } + } + } }, - "503": { - "description": "Issuer credentials not readable in the vault.", + "404": { + "description": "Not Found. No foreign authorization with this id in the caller's organization — including the case where the authorization verified but was refused before any row was written.", "content": { "application/json": { "schema": { @@ -30473,7 +33308,7 @@ "code": { "type": "string", "enum": [ - "vault_unavailable" + "foreign_authorization_not_found" ] }, "message": { @@ -30506,11 +33341,11 @@ } } }, - "x-codespar-scope": "cards:issue", + "x-codespar-scope": "facilitator:execute", "security": [ { "bearerAuth": [ - "cards:issue" + "facilitator:execute" ] } ] @@ -118047,6 +120882,15 @@ "maxLength": 200, "description": "The pedido aberto, as the person said it (e.g. \"fone bluetooth\")." }, + "task_kind": { + "type": "string", + "enum": [ + "product", + "service_plan", + "reservation" + ], + "description": "product (default), service_plan or reservation." + }, "criteria": { "type": "object", "properties": { @@ -118071,18 +120915,150 @@ "enum": [ "registry", "vtex", - "meli" + "meli", + "web" ] }, "minItems": 1, - "maxItems": 3, - "description": "Where to look: `registry` (the stores the Shop can buy at), `vtex` and `meli` (comparison only). Default: `registry` in Test, `vtex` and `meli` in Live." + "maxItems": 4, + "description": "Where to look: `registry` (the stores the Shop can buy at), `vtex` and `meli` (comparison only), `web` (the origins named in sources.origins). Default: `registry` in Test, `vtex` and `meli` in Live." }, "limit": { "type": "integer", "minimum": 1, "maximum": 5, "description": "Offers per source, 1 to 5 (default 5)." + }, + "reservation": { + "type": "object", + "properties": { + "check_in": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$", + "description": "Check-in day, YYYY-MM-DD (São Paulo)." + }, + "check_out": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$", + "description": "Check-out day, YYYY-MM-DD, after check_in." + }, + "occupants": { + "type": "object", + "properties": { + "adults": { + "type": "integer", + "minimum": 1, + "maximum": 10 + }, + "children": { + "type": "integer", + "minimum": 0, + "maximum": 10 + } + }, + "required": [ + "adults" + ], + "additionalProperties": false + }, + "location": { + "type": "string", + "minLength": 2, + "maxLength": 120, + "description": "Where, as the person said it." + } + }, + "required": [ + "check_in", + "check_out", + "occupants" + ], + "additionalProperties": false, + "description": "task_kind reservation: check_in, check_out, occupants, location." + }, + "service_plan": { + "type": "object", + "properties": { + "licenses": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "description": "How many seats or licenses." + }, + "period": { + "type": "string", + "enum": [ + "monthly", + "annual" + ], + "description": "The billing period to compare on." + } + }, + "required": [ + "licenses", + "period" + ], + "additionalProperties": false, + "description": "task_kind service_plan: licenses and period." + }, + "required": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "free_cancellation", + "breakfast_included", + "invoice", + "refundable", + "location" + ] + }, + "maxItems": 5, + "description": "Conditions an offer must state to be compared: an offer that does not state one is left out, with the reason." + } + }, + "additionalProperties": false + }, + "sources": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "registry", + "vtex", + "meli", + "web" + ] + }, + "minItems": 1, + "maxItems": 4 + }, + "origins": { + "type": "array", + "items": { + "type": "object", + "properties": { + "origin": { + "type": "string", + "maxLength": 300, + "description": "https://host of a site to consult, as the person or you named it." + }, + "start_path": { + "type": "string", + "maxLength": 200, + "description": "The path to start at; default /." + } + }, + "required": [ + "origin" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 5 } }, "additionalProperties": false diff --git a/packages/core/scripts/openapi-spec.d.mts b/packages/core/scripts/openapi-spec.d.mts index 33abf9b5..e61e7cd3 100644 --- a/packages/core/scripts/openapi-spec.d.mts +++ b/packages/core/scripts/openapi-spec.d.mts @@ -68,6 +68,14 @@ export function buildSnapshot( ): Snapshot; export function renderGenerated(snapshot: Snapshot): Promise<{ types: string; operations: string }>; export function readSnapshot(file?: string): Snapshot; +/** `candidate:/openapi-candidate.json`, the source a candidate snapshot records. */ +export const CANDIDATE_SOURCE: RegExp; +export function readCandidate(file: string): { + document: OpenApiDocument; + source: string; + etag: null; + lastModified: null; +}; export function fetchServed( url?: string, ): Promise<{ document: OpenApiDocument; etag: string | null; lastModified: string | null }>; diff --git a/packages/core/src/__tests__/openapi-snapshot.test.ts b/packages/core/src/__tests__/openapi-snapshot.test.ts index 8a035ceb..415b894c 100644 --- a/packages/core/src/__tests__/openapi-snapshot.test.ts +++ b/packages/core/src/__tests__/openapi-snapshot.test.ts @@ -25,6 +25,8 @@ import { requiredQueryParameters, readSnapshot, renderGenerated, + readCandidate, + CANDIDATE_SOURCE, } from "../../scripts/openapi-spec.mjs"; import { API_OPERATIONS } from "../generated/operations.js"; import { ApiClient } from "../api/client.js"; @@ -42,8 +44,12 @@ describe("openapi-snapshot.json", () => { expect(Object.keys(snapshot.document.paths ?? {})).toHaveLength(snapshot.snapshot.paths); }); - it("names the served URL and a fetch timestamp", () => { - expect(snapshot.snapshot.source).toMatch(/^https:\/\/.+\/openapi\.json$/); + it("names the served URL (or an enterprise candidate head, never published) and a fetch timestamp", () => { + // A candidate snapshot (cards contract §8.6) is a review state: the + // publish workflow runs `assert-served` and refuses it. + expect(snapshot.snapshot.source).toMatch( + /^(https:\/\/.+\/openapi\.json|candidate:[0-9a-f]{7,40}\/openapi-candidate\.json)$/, + ); expect(new Date(snapshot.snapshot.fetched_at).toString()).not.toBe("Invalid Date"); }); }); @@ -121,3 +127,19 @@ describe("diffOperations (the comparison the served check relies on)", () => { expect(diff.schemas).toEqual(["Wallet"]); }); }); + +describe("candidate documents (cards contract §8.6)", () => { + it("records the enterprise SHA from the directory name, and refuses a path that has none", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cand-")); + const shaDir = path.join(dir, "abc1234def"); + fs.mkdirSync(shaDir); + const file = path.join(shaDir, "openapi-candidate.json"); + fs.writeFileSync(file, JSON.stringify({ openapi: "3.1.0", info: { title: "t", version: "1" }, paths: {} })); + const read = readCandidate(file); + expect(read.source).toBe("candidate:abc1234def/openapi-candidate.json"); + expect(CANDIDATE_SOURCE.test(read.source)).toBe(true); + const loose = path.join(dir, "openapi-candidate.json"); + fs.writeFileSync(loose, "{}"); + expect(() => readCandidate(loose)).toThrow(/enterprise sha/); + }); +}); diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index 92d166ee..79c97150 100644 --- a/packages/core/src/generated/openapi.ts +++ b/packages/core/src/generated/openapi.ts @@ -1,6 +1,6 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 868a0272e249a736c8f2510fb7e7def491fdb6ee509d85fc09e5f2fb32af33bd, fetched 2026-11-15T23:15:37.743Z -// from https://api.codespar.dev/openapi.json, API 0.3.0). +// Source: openapi-snapshot.json (sha256 6941cbee6488d220240741e9147cd018de80426af81d3fc02aa32dd757bd2224, fetched 2026-11-19T02:03:13.382Z +// from candidate:ffa66ce789ab6284cab9f831ba73025f0a5afeae/openapi-candidate.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { "/.well-known/oauth-protected-resource": { @@ -36,6 +36,54 @@ export interface paths { authorization_servers: string[]; bearer_methods_supported: string[]; scopes_supported: string[]; + /** @description Present only with OAUTH_CONSENT_FLOW=consent. Not an RFC 9728 parameter: it repeats the authorization server's list, so a client that reads only this document learns a client secret is accepted. */ + token_endpoint_auth_methods_supported?: string[]; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/.well-known/oauth-protected-resource/mcp": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Protected-resource metadata for /mcp (RFC 9728, path-suffixed) + * @description The RFC 9728 §3.1 path-suffixed copy of the protected-resource metadata, for the remote MCP endpoint `/mcp`. MCP clients try this location before the root one, and the `/mcp` 401's `WWW-Authenticate` `resource_metadata` points here. Identical to `/.well-known/oauth-protected-resource` except `resource`, which is `/mcp`, the URL the client was given (RFC 9728 §3.3 requires the two to match). Host-aware, like the root copy. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + resource: string; + authorization_servers: string[]; + bearer_methods_supported: string[]; + scopes_supported: string[]; + /** @description Present only with OAUTH_CONSENT_FLOW=consent, as on the root copy. Not an RFC 9728 parameter: it repeats the authorization server's list, so a client that reads only this document learns a client secret is accepted. */ + token_endpoint_auth_methods_supported?: string[]; }; }; }; @@ -134,9 +182,9 @@ export interface paths { }; /** * Authorization-server metadata (RFC 8414) - * @description The three endpoint URLs below, absolute under the issuer, plus what this server supports: `response_types_supported: ["code"]`, `grant_types_supported: ["authorization_code", "refresh_token"]`, `code_challenge_methods_supported: ["S256"]` and `token_endpoint_auth_methods_supported: ["none"]`. + * @description The three endpoint URLs below, absolute under the issuer, plus what this server supports: `response_types_supported: ["code"]`, `grant_types_supported: ["authorization_code", "refresh_token"]`, `code_challenge_methods_supported: ["S256"]` and `token_endpoint_auth_methods_supported: ["none"]`, with `client_secret_basic` and `client_secret_post` added (and `offline_access` in `scopes_supported`) only when OAUTH_CONSENT_FLOW=consent. * - * Read the last two together: this is a PUBLIC client with no secret, and PKCE S256 is mandatory rather than preferred. `plain` is never advertised and is refused at the authorize endpoint. Host-aware, like the document above. + * Read the last two together. `none` is every dynamically registered client: a PUBLIC client with no secret. The two secret methods are for a client CodeSpar registered ahead of time with a secret. PKCE S256 is mandatory for EVERY client, secret or not, rather than preferred. `plain` is never advertised and is refused at the authorize endpoint. Host-aware, like the document above. */ get: { parameters: { @@ -287,6 +335,8 @@ export interface paths { * @description Returns `text/html`, NOT JSON: this is the leg a human completes in a browser, so a generated client should open it rather than call it. `response_type=code`, a registered `client_id`, a `redirect_uri` matching one registered for that client exactly, and `code_challenge` with `code_challenge_method=S256` are all required. * * Errors are rendered as HTML with status 400 and are NOT redirected: per RFC 6749 §4.1.2.1 an invalid `client_id`/`redirect_uri` must not be redirected to, and this endpoint keeps that posture for every error so a human sees the reason on the page. A scope request this server cannot satisfy is refused here, before the form asking for a key is drawn. + * + * Where the deployment runs signed-in consent (`OAUTH_CONSENT_FLOW=consent`) no key is asked for: a valid request is held server-side and answered with a 302 to the web consent page, where a signed-in admin approves it. An unknown `client_id` or a `redirect_uri` that is not an exact registered match still gets the 400 page and is never redirected; every other refusal (`unsupported_response_type`, `invalid_request`, `invalid_scope`, `invalid_target` for a `resource` that is not this server's MCP endpoint) goes back to `redirect_uri` as an OAuth error with the `state`. */ get: { parameters: { @@ -299,6 +349,8 @@ export interface paths { state?: string; /** @description Space-separated. Requesting more than the pasted key holds is refused. */ scope?: string; + /** @description RFC 8707 resource indicator. Under signed-in consent it must name this server's MCP endpoint. */ + resource?: string; }; header?: never; path?: never; @@ -315,6 +367,14 @@ export interface paths { "text/html": string; }; }; + /** @description Signed-in consent only: Location is the web consent page, or `redirect_uri` with an OAuth `error` and the `state`. */ + 302: { + headers: { + Location: string; + [name: string]: unknown; + }; + content?: never; + }; /** @description Rendered as HTML, never redirected. */ 400: { headers: { @@ -332,6 +392,8 @@ export interface paths { * @description `application/x-www-form-urlencoded`, submitted by the page above, not by a generated client. The form carries the same authorization-request parameters plus the API key the human pasted. * * On success: 302 to `redirect_uri` with `code` and `state`. The code is single-use, short-lived, and bound to the tenant, the client, the redirect URI, the PKCE challenge AND the API key that authorized it — so revoking that key invalidates every token the code goes on to mint, and the token's scopes can never exceed the key's own. On refusal the page re-renders as HTML with 400. + * + * Where the deployment runs signed-in consent (`OAUTH_CONSENT_FLOW=consent`) this answers 404 and mints no code: no key is accepted. */ post: { parameters: { @@ -394,7 +456,7 @@ export interface paths { put?: never; /** * Token endpoint — authorization_code and refresh_token grants - * @description `application/x-www-form-urlencoded`, unauthenticated (public client, `token_endpoint_auth_method: none`); the authorization code IS the authority. `grant_type=authorization_code` requires `code`, `code_verifier`, `redirect_uri` and `client_id`; `grant_type=refresh_token` requires `refresh_token`. Anything else is 400 `unsupported_grant_type`. + * @description `application/x-www-form-urlencoded`. A public client (every dynamically registered one, `token_endpoint_auth_method: none`) is unauthenticated: the authorization code and its PKCE verifier are the authority. A client CodeSpar registered ahead of time with a secret must also authenticate, on BOTH grants, by `client_secret_basic` (`Authorization: Basic` with the url-encoded id and secret) or `client_secret_post` (`client_id` and `client_secret` in the body); a missing or wrong secret is 401 `invalid_client` and leaves the code or refresh token untouched, and both methods at once is 400 `invalid_request`. `grant_type=authorization_code` requires `code`, `code_verifier`, `redirect_uri` and `client_id`; `grant_type=refresh_token` requires `refresh_token`. Anything else is 400 `unsupported_grant_type`. * * Redemption is atomic and single-use even under a concurrent retry: a second redemption of the same code sees no row and gets 400 `invalid_grant`. The refresh grant ROTATES — the presented refresh token is revoked and a new one returned, so a client must persist the new value. A refresh chain lives at most 90 days from the consent that began it: past that the refresh grant answers 400 `invalid_grant` and the user has to authorize again. `expires_in` is the access token's lifetime in seconds Responses carry `Cache-Control: no-store` (RFC 6749 §5.1). */ @@ -414,6 +476,8 @@ export interface paths { code_verifier?: string; redirect_uri?: string; client_id?: string; + /** @description client_secret_post, for a pre-registered client with a secret only. */ + client_secret?: string; refresh_token?: string; }; }; @@ -435,7 +499,7 @@ export interface paths { }; }; }; - /** @description `invalid_grant` (code invalid, expired, already used, bound to a different client or redirect_uri, PKCE verification failed, carrying no recorded scope grant, or a refresh chain older than 90 days), `invalid_request`, or `unsupported_grant_type`. */ + /** @description `invalid_grant` (code invalid, expired, already used, bound to a different client or redirect_uri, PKCE verification failed, carrying no recorded scope grant, or a refresh chain older than 90 days), `invalid_request` (also two client authentication methods at once), or `unsupported_grant_type`. */ 400: { headers: { [name: string]: unknown; @@ -447,6 +511,290 @@ export interface paths { }; }; }; + /** @description `invalid_client`: a client registered with a secret presented none, a wrong one, a malformed Basic header, or a Basic id that differs from the body `client_id`. Carries `WWW-Authenticate: Basic` when the request used Basic. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + error_description?: string; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/oauth/pending/{handle}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Signed-in consent — read a held authorization request for the consent page + * @description What the consent page shows before the person decides: the client, the scopes it would get with the line the page prints for each, when the request expires, and whether the organization the person's session is signed into may finish a consent yet. The first person to read a handle is bound to it. Not an API-key or OAuth-token operation: send the service key and the person's Clerk session token, and no Authorization header. + * + * `approverAccess` is the access an approval by this person would give, from their role in the organization their session is signed into: `full` for an owner or admin (a personal account counts as owner), `read_only` for a member, whose grant reaches only the read tools, and `null` for a person with no role there, whose approval is refused. It is a hint for the page's wording only — the decide call resolves the role again at the click. For an approver that is not `full`, the `tools:execute` line reads "Call codespar's read tools (getting started, discovery, payment status)". + * + * JSON `{ "error": "" }`. `bearer_token_cannot_decide` (403, an Authorization header was sent), `unauthorized` (401, no valid service key), `user_token_required` / `user_token_invalid` / `user_token_identity_mismatch` / `user_token_wrong_party` (403), `user_token_verification_unconfigured` (503), `rate_limit_exceeded` (429 with `Retry-After`), `pending_not_found` (404), `handle_bound_to_other` (403), `pending_decided` (409), `pending_expired` (410), and 404 `consent_flow_disabled` when the deployment does not run signed-in consent. + */ + get: { + parameters: { + query?: never; + header: { + /** @description The service key of the web app that renders the consent page. */ + "x-codespar-service-key": string; + /** @description The signed-in person's Clerk session token, issued to the consent page's origin. The person is its subject, never a forwarded header. */ + "x-codespar-user-token": string; + }; + path: { + /** @description The `request` value of the consent page's URL. */ + handle: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + client: { + /** @description The client's display name, sanitized; a placeholder when it registered none. */ + name: string; + unverified: boolean; + redirectHost: string; + }; + scopes: { + scope: string; + label: string; + }[]; + expiresAt: string; + openForActiveOrg: boolean; + /** + * @description What this person's approval would grant: `full`, `read_only` (read tools only), or null (no role; approval refused). A display hint; decide resolves it again. + * @enum {string|null} + */ + approverAccess: "full" | "read_only" | null; + }; + }; + }; + /** @description `unauthorized`: no valid service key. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description A refusal named in `error`; see the description. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `pending_not_found` or `consent_flow_disabled`. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `pending_decided`. */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `pending_expired`. */ + 410: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `rate_limit_exceeded`, with `Retry-After`. */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/oauth/pending/{handle}/decide": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Signed-in consent — approve or deny a held authorization request + * @description The person's decision, made with a Clerk session token minted at the click (older than 120 seconds is 403 `user_token_stale`). Same headers as the read, and no Authorization header. An approval by an owner or admin of the project's organization makes a `full` grant; an approval by a member makes a `read_only` grant whose tool calls are limited to the read tools; a person with no role in that organization is refused `no_role`. Approve or deny, the answer is 200 with the URL to send the browser to: the client's redirect URI with `code` and `state` on approval, or with `error=access_denied` and `state` on deny. + * + * Decide-only refusals: `invalid_body` (400), `project_not_in_org` (403), and for an approval `no_role`, `not_open_yet`, `project_archived`, `live_not_available`, `no_grantable_scopes` (403) and `invalid_client` / `invalid_request` (400). None of them consumes the request. JSON `{ "error": "" }`. `bearer_token_cannot_decide` (403, an Authorization header was sent), `unauthorized` (401, no valid service key), `user_token_required` / `user_token_invalid` / `user_token_identity_mismatch` / `user_token_wrong_party` (403), `user_token_verification_unconfigured` (503), `rate_limit_exceeded` (429 with `Retry-After`), `pending_not_found` (404), `handle_bound_to_other` (403), `pending_decided` (409), `pending_expired` (410), and 404 `consent_flow_disabled` when the deployment does not run signed-in consent. + */ + post: { + parameters: { + query?: never; + header: { + /** @description The service key of the web app that renders the consent page. */ + "x-codespar-service-key": string; + /** @description The signed-in person's Clerk session token, issued to the consent page's origin. The person is its subject, never a forwarded header. */ + "x-codespar-user-token": string; + }; + path: { + handle: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + /** @enum {string} */ + decision: "approve" | "deny"; + /** @description The project the grant is for, in the session's organization. */ + projectId: string; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @description Where to send the browser: the client's redirect URI with the code, or with `access_denied`. */ + redirectUrl: string; + }; + }; + }; + /** @description `invalid_body`, `invalid_client` or `invalid_request`. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `unauthorized`: no valid service key. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description A refusal named in `error`, `no_role` among them; see the description. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `pending_not_found` or `consent_flow_disabled`. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `pending_decided`. */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `pending_expired`. */ + 410: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; + /** @description `rate_limit_exceeded`, with `Retry-After`. */ + 429: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: string; + }; + }; + }; }; }; delete?: never; @@ -1613,7 +1961,7 @@ export interface paths { content: { "application/json": { name: string; - /** @description The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below. */ + /** @description The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, oauth.consent_denied, oauth.grant_created, oauth.grant_replaced, oauth.grant_revoked, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below. */ event: string; server_id?: string; /** @@ -1767,7 +2115,7 @@ export interface paths { content: { "application/json": { name: string; - /** @description The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below. */ + /** @description The event type to subscribe to. Matching is EXACT string equality — there is no prefix and no wildcard, so `commerce.payment.succeeded` does not receive `commerce.payment.received`. A name outside the list below is accepted and recorded (`trigger.event_unknown`) rather than refused, so you can subscribe ahead of a release; until something emits it the subscription simply never fires. What this build emits: account_binding.closed, agent_autonomy.changed, api_key.mandate_bound, api_key.mandate_unbound, approval.decided, approval.pending, collect.attempt.cancelled, collect.attempt.expired, collect.attempt.failed, collect.attempt.issued, collect.attempt.ready, collect.attempt.superseded, collect.link.archived, collect.link.paused, collect.link.published, collect.payment.exception, collect.payment.paid, collect.refund.awaiting_decision, collect.refund.honored, collect.refund.required, commerce.account_entry_credit.received, commerce.account_entry_debit.received, commerce.account_launch_in.received, commerce.account_launch_out.received, commerce.account_status.changed, commerce.cashout.confirmed, commerce.charge.cancelled, commerce.charge.created, commerce.charge.expired, commerce.charge.expiry_notified, commerce.charge.failed, commerce.charge.paid, commerce.charge.payment_notified, commerce.charge.payment_received, commerce.dict_claim.cancelled, commerce.dict_claim.completed, commerce.dict_claim.confirmed, commerce.dict_claim.opened, commerce.dict_claim.waiting, commerce.internal_transfer_in.received, commerce.internal_transfer_out.received, commerce.mandate.expiring, commerce.mandate.granted, commerce.mandate.paused, commerce.mandate.resumed, commerce.mandate.revoked, commerce.onboarding.backgroundcheck_approved, commerce.onboarding.backgroundcheck_pending, commerce.onboarding.backgroundcheck_rejected, commerce.onboarding.documentscopy_approved, commerce.onboarding.documentscopy_pending, commerce.onboarding.documentscopy_processing, commerce.onboarding.documentscopy_rejected, commerce.onboarding.proposal_approved, commerce.onboarding.proposal_processing_documentscopy, commerce.onboarding.proposal_rejected, commerce.organization.paused, commerce.organization.resumed, commerce.payment.failed, commerce.payment.pending, commerce.payment.received, commerce.payment.refunded, commerce.payment.succeeded, commerce.payment.updated, commerce.pix_out.failed, commerce.pix_out.succeeded, commerce.pix_out.unconfirmed, commerce.pix_reversal_in.received, commerce.pix_reversal_out.received, commerce.recurrence.authorized, commerce.recurrence.cancelled, commerce.recurrence.cycle.accepted, commerce.recurrence.cycle.announced_late, commerce.recurrence.cycle.awaiting_instruction, commerce.recurrence.cycle.cancelled, commerce.recurrence.cycle.expired, commerce.recurrence.cycle.instruction_blocked, commerce.recurrence.cycle.instruction_missing, commerce.recurrence.cycle.instruction_refused, commerce.recurrence.cycle.paid, commerce.recurrence.cycle.queued_instruction_expired, commerce.recurrence.cycle.rejected, commerce.recurrence.cycle.scheduled, commerce.recurrence.cycle.settled_by_held_credit, commerce.recurrence.denied, commerce.recurrence.requested, commerce.recurrence.settlement_held, commerce.recurrence.settlement_hold_overdue, commerce.recurrence.settlement_hold_resolved, commerce.recurrence.settlement_possible_double_credit, commerce.rinne.observed, commerce.spend.failed, commerce.spend.settled, commerce.ted_in.succeeded, dda.boleto.registered, dda.subscription.activated, dda.subscription.failed, gate.paywall.charged, oauth.consent_denied, oauth.grant_created, oauth.grant_replaced, oauth.grant_revoked, payable.batch.completed, payable.batch.item_executed, payable.batch.item_refused, payable.rejected, project.archived, project.unarchived, proxy_call.failed, proxy_call.succeeded, sandbox.provisioning.account_bound, sandbox.provisioning.initial_credit, sandbox.provisioning.pix_key_registered, sandbox.provisioning.resumed, session.closed, space_credential_revocation.requested, spaces_consent.accepted, spaces_customer_account.resumed, spaces_customer_account.suspended, system.health.degraded, system.health.recovered, tool_call.failed, tool_call.succeeded, trigger.delivery.failed, trigger.paused_automatically, trigger.test_fire, user.signed_up, wallet.balance.below. */ event: string; server_id?: string; /** @@ -3303,7 +3651,7 @@ export interface paths { seed?: { /** @enum {string} */ state: "awaiting_treasury" | "sending" | "submitted" | "confirmed" | "not_needed" | "needs_attention"; - /** @description USDC the Test treasury sends (the difference to 100 USDC), 6 decimals. */ + /** @description USDC the Test treasury sends (the difference to 20 USDC), 6 decimals. */ amount_atomic: string; treasury_address: string; tx_hash: string | null; @@ -7934,6 +8282,10 @@ export interface paths { limits: { total_minor: number | null; per_transaction_minor: number | null; + /** @description The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit. */ + monthly_minor?: number; + /** @description How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one. */ + monthly_quantity?: number; } | null; created_at: string; authorized_at: string | null; @@ -8000,6 +8352,8 @@ export interface paths { limits?: { total_minor?: number; per_transaction_minor?: number; + monthly_minor?: number; + monthly_quantity?: number; }; /** Format: date-time */ expires_at?: string; @@ -8042,6 +8396,10 @@ export interface paths { limits: { total_minor: number | null; per_transaction_minor: number | null; + /** @description The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit. */ + monthly_minor?: number; + /** @description How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one. */ + monthly_quantity?: number; } | null; created_at: string; authorized_at: string | null; @@ -8216,6 +8574,10 @@ export interface paths { limits: { total_minor: number | null; per_transaction_minor: number | null; + /** @description The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit. */ + monthly_minor?: number; + /** @description How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one. */ + monthly_quantity?: number; } | null; created_at: string; authorized_at: string | null; @@ -8381,6 +8743,10 @@ export interface paths { limits: { total_minor: number | null; per_transaction_minor: number | null; + /** @description The amount the bank lets be pulled per month, over the bank's own monthly window. Present only on a consent that has a monthly limit. */ + monthly_minor?: number; + /** @description How many pulls the bank lets through per month, over the bank's own monthly window. Present only when the bank stated one. */ + monthly_quantity?: number; } | null; created_at: string; authorized_at: string | null; @@ -11077,658 +11443,6 @@ export interface paths { patch?: never; trace?: never; }; - "/v1/cards": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - /** - * List issued cards - * @description The cards issued in this project, most recent first. - * - * This listing carries CARDS, not mint flows: a `POST` that stopped at `202` waiting for KYC does not appear here until it becomes a card. To follow that flow, read the `flow_id` the issuance returned. - */ - get: { - parameters: { - query?: { - /** @description Filters to one consumer's cards. */ - consumer_id?: string; - /** @description 1 to 200; the default is 50. */ - limit?: number; - }; - header?: never; - path?: never; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description OK */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - cards: { - /** @description CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves. */ - id: string; - /** - * @description Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118). - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own identifier for the card, as it was returned to us. */ - card_id: string; - /** @description The last four digits. No other card-number material exists on this surface. */ - last4: string; - /** - * @description `CHECK (network IN ('visa', 'mastercard'))`, migration 0118. - * @enum {string} - */ - network: "visa" | "mastercard"; - /** - * @description `IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118. - * @enum {string} - */ - status: "active" | "blocked" | "canceled"; - /** @description The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - }[]; - }; - }; - }; - /** @description The query did not match the schema. */ - 400: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "invalid_query"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - }; - }; - put?: never; - /** - * Issue a card under a signed mandate - * @description Issues a card for an agent, under a signed mandate. - * - * **Three success outcomes, and the status separates them.** `201` is the issuance that finished now. `202` is the issuer asking for KYC on the holder before issuing: the flow stays `pending`, and `kyc_url` is where to send the person. `200` is a REPLAY: the same `Idempotency-Key` arriving again on a flow that already finished, returning what it produced instead of issuing a second card. - * - * **Repeating is safe and it is the recovery path.** A `502 issuer_ingest_failed` means the card EXISTS and only the ingest into the data environment failed: repeating with the SAME key reuses the token, and sending a new key would issue a second card. The body of that refusal already carries the issued card. - * - * **A repeated key with a different body is `409`**, not a new issuance: the request fingerprint is derived from the holder and compared, and it survives the redaction of the holder's data, so the divergence is caught much later. - */ - post: { - parameters: { - query?: never; - header?: { - /** @description Keys the mint flow. When absent, the server mints one, and the call then stops being repeatable, because there is no key to repeat. */ - "Idempotency-Key"?: string; - }; - path?: never; - cookie?: never; - }; - requestBody?: { - content: { - "application/json": { - /** @description ISO 3166-1 alpha-2, uppercase. Decides the issuing corridor. */ - country: string; - /** @description ISO 4217, uppercase. */ - currency: string; - holder: { - full_name: string; - /** Format: email */ - email: string; - /** @description `YYYY-MM-DD`. */ - birthdate: string; - document: { - type: string; - value: string; - /** @description ISO 3166-1 alpha-2, uppercase. */ - issuing_country: string; - }; - address: { - line1: string; - line2?: string; - /** @description Required by some corridors (Pomelo BR); optional in the schema. */ - street_number?: string; - neighborhood?: string; - city: string; - state?: string; - postal_code: string; - /** @description Where the corridor requires it and it differs from `city`: in Pomelo BR, the IBGE code. */ - municipality?: string; - /** @description ISO 3166-1 alpha-2, uppercase. */ - country: string; - }; - /** @description E.164, with the `+`. */ - phone?: string; - }; - /** @description REQUIRED on every rail, with no exception by issuer. The card is an agent's spending instrument and the mandate is the consumer's signed authorization for it. Issuing with no mandate produced, on Bridge, a card with no limit and no category on a rail that never declines; and on Pomelo, a card the authorizer has no link to at all at spend time. */ - mandate_id: string; - metadata?: { - [key: string]: string; - }; - }; - }; - }; - responses: { - /** @description OK */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @enum {string} */ - state: "issued"; - flow_id: string; - card: { - /** @description CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves. */ - id: string; - /** - * @description Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118). - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own identifier for the card, as it was returned to us. */ - card_id: string; - /** @description The last four digits. No other card-number material exists on this surface. */ - last4: string; - /** - * @description `CHECK (network IN ('visa', 'mastercard'))`, migration 0118. - * @enum {string} - */ - network: "visa" | "mastercard"; - /** - * @description `IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118. - * @enum {string} - */ - status: "active" | "blocked" | "canceled"; - /** @description The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - }; - } | { - /** @description `imf_` prefixed. The row it names is keyed by the mint call's `Idempotency-Key`, or by a server-minted one when that header was absent. */ - flow_id: string; - /** - * @description `MintFlowState`, and `CHECK (state IN ('pending', 'issued', 'revoked', 'failed'))` in 0118. - * @enum {string} - */ - state: "pending" | "issued" | "revoked" | "failed"; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - /** @description Why the flow is parked, when it is parked. Null otherwise. */ - reason: string | null; - /** @description Where the holder finishes identity verification, when the issuer asked for one. Null otherwise. */ - kyc_url: string | null; - /** Format: date-time */ - created_at: string; - /** @description PRESENT ONLY when `state` is `issued` AND the flow already points at a card row. In every other case the key is absent rather than null. Null inside that case means the card row did not resolve under this org and project. */ - card?: { - /** @description CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves. */ - id: string; - /** - * @description Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118). - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own identifier for the card, as it was returned to us. */ - card_id: string; - /** @description The last four digits. No other card-number material exists on this surface. */ - last4: string; - /** - * @description `CHECK (network IN ('visa', 'mastercard'))`, migration 0118. - * @enum {string} - */ - network: "visa" | "mastercard"; - /** - * @description `IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118. - * @enum {string} - */ - status: "active" | "blocked" | "canceled"; - /** @description The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - } | null; - }; - }; - }; - /** @description OK */ - 201: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @enum {string} */ - state: "issued"; - flow_id: string; - card: { - /** @description CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves. */ - id: string; - /** - * @description Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118). - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own identifier for the card, as it was returned to us. */ - card_id: string; - /** @description The last four digits. No other card-number material exists on this surface. */ - last4: string; - /** - * @description `CHECK (network IN ('visa', 'mastercard'))`, migration 0118. - * @enum {string} - */ - network: "visa" | "mastercard"; - /** - * @description `IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118. - * @enum {string} - */ - status: "active" | "blocked" | "canceled"; - /** @description The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - }; - }; - }; - }; - /** @description OK */ - 202: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @description `imf_` prefixed. The row it names is keyed by the mint call's `Idempotency-Key`, or by a server-minted one when that header was absent. */ - flow_id: string; - /** - * @description `MintFlowState`, and `CHECK (state IN ('pending', 'issued', 'revoked', 'failed'))` in 0118. - * @enum {string} - */ - state: "pending" | "issued" | "revoked" | "failed"; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - /** @description Why the flow is parked, when it is parked. Null otherwise. */ - reason: string | null; - /** @description Where the holder finishes identity verification, when the issuer asked for one. Null otherwise. */ - kyc_url: string | null; - /** Format: date-time */ - created_at: string; - /** @description PRESENT ONLY when `state` is `issued` AND the flow already points at a card row. In every other case the key is absent rather than null. Null inside that case means the card row did not resolve under this org and project. */ - card?: { - /** @description CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves. */ - id: string; - /** - * @description Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118). - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own identifier for the card, as it was returned to us. */ - card_id: string; - /** @description The last four digits. No other card-number material exists on this surface. */ - last4: string; - /** - * @description `CHECK (network IN ('visa', 'mastercard'))`, migration 0118. - * @enum {string} - */ - network: "visa" | "mastercard"; - /** - * @description `IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118. - * @enum {string} - */ - status: "active" | "blocked" | "canceled"; - /** @description The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - } | null; - }; - }; - }; - /** @description The body did not match the schema, the country/currency pair has no corridor, the holder was rejected by the issuer, or the controls requested do not exist on this rail. */ - 400: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "invalid_body" | "issuer_corridor_unsupported" | "invalid_holder" | "issuer_controls_unsupported"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The key and the issuer's environment do not match. A test key does not issue a real card, and a live key does not issue on the staging issuer. */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "stage_issuer_live_key" | "live_issuer_test_key"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The named mandate does not exist in this organization. */ - 404: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "mandate_not_found"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The `Idempotency-Key` was already used with a different body, or it belongs to a request made before a `VAULT_MASTER_KEY` rotation and can no longer be matched to its body (retry with a new key), or the mandate is not active. `details` carries the mandate's state in the last case. */ - 409: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "idempotency_key_conflict" | "mandate_not_active"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description Invariant break: the flow is recorded as issued and there is no readable card row behind it. */ - 500: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "issuer_card_unknown"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The issuer refused or failed the issuance; or the card was issued and the ingest into the data environment failed. In the second case the card EXISTS and comes in `details.card`; repeat with the SAME key. */ - 502: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "issuer_mint_failed" | "issuer_ingest_failed"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The issuer's credentials could not be read from the vault. */ - 503: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "vault_unavailable"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - }; - }; - delete?: never; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; - "/v1/cards/{id}": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - /** - * Read an issued card, or the mint flow that is producing one - * @description ONE PATH, TWO RESOURCES, chosen by the id's prefix. An id beginning `imf_` is a MINT FLOW and the response is the flow. Anything else is looked up as a card row and the response is the card. There is no query parameter and no header that changes this: the prefix is the whole dispatch, so a client has to be ready for both bodies on one operation. - * - * A flow that reached `issued` and already points at a card row answers with the flow PLUS a `card` key. No other flow state carries that key at all. So the polling loop after a mint is: read the flow id, and when `state` is `issued`, read `card`. - * - * SCOPING. Both lookups carry the caller's org and project in the WHERE clause. A card or flow belonging to a sibling project of the same org is indistinguishable from one that was never created: both are 404, with the same code. - * - * NO CARD-NUMBER MATERIAL crosses this surface. `last4` and, once ingest lands, `token_id` are what a card exposes; the number itself lives only in the cardholder-data environment and is never part of this response. - * - * The canonical path. `GET /v1/issuer/cards/{id}` is the same handler at the path that shipped first, kept for two releases and not described in this document. - */ - get: { - parameters: { - query?: never; - header?: never; - path: { - /** @description A card row id, or an `imf_` prefixed mint flow id. The prefix selects which. */ - id: string; - }; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description OK */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @description CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves. */ - id: string; - /** - * @description Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118). - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own identifier for the card, as it was returned to us. */ - card_id: string; - /** @description The last four digits. No other card-number material exists on this surface. */ - last4: string; - /** - * @description `CHECK (network IN ('visa', 'mastercard'))`, migration 0118. - * @enum {string} - */ - network: "visa" | "mastercard"; - /** - * @description `IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118. - * @enum {string} - */ - status: "active" | "blocked" | "canceled"; - /** @description The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - } | { - /** @description `imf_` prefixed. The row it names is keyed by the mint call's `Idempotency-Key`, or by a server-minted one when that header was absent. */ - flow_id: string; - /** - * @description `MintFlowState`, and `CHECK (state IN ('pending', 'issued', 'revoked', 'failed'))` in 0118. - * @enum {string} - */ - state: "pending" | "issued" | "revoked" | "failed"; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - /** @description Why the flow is parked, when it is parked. Null otherwise. */ - reason: string | null; - /** @description Where the holder finishes identity verification, when the issuer asked for one. Null otherwise. */ - kyc_url: string | null; - /** Format: date-time */ - created_at: string; - /** @description PRESENT ONLY when `state` is `issued` AND the flow already points at a card row. In every other case the key is absent rather than null. Null inside that case means the card row did not resolve under this org and project. */ - card?: { - /** @description CodeSpar's own id for the card row. This is what `/v1/cards/{id}` resolves. */ - id: string; - /** - * @description Closed from two sides: `IssuerId` in `@codespar-enterprise/issuer` and `CHECK (issuer IN ('pomelo', 'bridge'))` on `issuer_cards` (migration 0118). - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own identifier for the card, as it was returned to us. */ - card_id: string; - /** @description The last four digits. No other card-number material exists on this surface. */ - last4: string; - /** - * @description `CHECK (network IN ('visa', 'mastercard'))`, migration 0118. - * @enum {string} - */ - network: "visa" | "mastercard"; - /** - * @description `IssuerCardStatus`, and `CHECK (status IN ('active', 'blocked', 'canceled'))` in 0118. - * @enum {string} - */ - status: "active" | "blocked" | "canceled"; - /** @description The card's token in the cardholder-data environment. Null until ingest lands, which is its own step after the card exists, so a freshly issued card can be readable here with no token yet. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - } | null; - }; - }; - }; - /** @description `issuer_card_unknown` for both misses, with different messages: `mint flow not found` for an `imf_` id and `issuer card not found` otherwise. One code, so a client cannot tell a wrong id from another project's id by reading the code. */ - 404: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "issuer_card_unknown"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - }; - }; - put?: never; - post?: never; - delete?: never; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; "/v1/counterparties/{id}": { parameters: { query?: never; @@ -12238,6 +11952,1887 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/cards": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List the project's cards, both issuers + * @description The project's Pomelo and Rain cards, most recent first, as card views. Requires `cards:read`. + */ + get: { + parameters: { + query?: { + issuer?: "pomelo" | "rain"; + mandate_id?: string; + consumer_id?: string; + /** @description 1 to 200; the default is 50. */ + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + cards: { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }[]; + }; + }; + }; + /** @description The query did not match the schema. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "invalid_query"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + put?: never; + /** + * Issue a card (pomelo_brl or rain_usd) + * @description Issues a card of the program chosen by `currency` (BRL -> `pomelo_brl`, USD -> `rain_usd`), or of `provider`'s program when given. + * + * **For an API key or an OAuth token only**, holding `cards:issue`. Every call, a retry included, checks server-side: the mandate (this project's, the consumer's, active, unexpired, in the card currency), the key bound to the mandate, the holder approved by the issuer, the current terms accepted by the competent person, and an unrevoked authorization for automated issuance for (holder, program) granted in the dashboard. + * + * **`Idempotency-Key` is required.** The first call binds the key to the program chosen then; a retry with the same key uses the RECORDED program even if the default or the availability changed, and never issues a second card. The same key with another body is `409 idempotency_key_conflict`. + * + * **`202` is a person's action pending**, with a stable `pending_action`; nothing is ever accepted on a person's behalf. Repeat the same request after the action: it re-validates and resumes the SAME operation. + * + * The Pomelo holder is built by the server from what the account already holds plus the holder's profile; what is missing is a 202 `complete_holder_profile` naming exactly the missing fields (`PUT /v1/cards/holder-profiles/{consumer_id}`), after which the SAME request resumes. An API caller MAY send `holder` for `pomelo_brl` instead; `rain_usd` refuses it (its holder is read from the Rain records). Live projects are refused (`card_issuer_unavailable`, reason `live_blocked`). + */ + post: { + parameters: { + query?: never; + header: { + /** @description Required. Binds the request to its program; a retry never issues twice. */ + "Idempotency-Key": string; + }; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + currency: string; + provider?: string | null; + mandate_id: string; + consumer_id: string; + holder?: { + full_name: string; + /** Format: email */ + email: string; + birthdate: string; + document: { + type: string; + value: string; + issuing_country: string; + }; + address: { + line1: string; + line2?: string; + street_number?: string; + neighborhood?: string; + city: string; + state?: string; + postal_code: string; + municipality?: string; + country: string; + }; + phone?: string; + }; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @enum {string} */ + state: "issued"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + mandate_id: string; + consumer_id: string; + card: { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }; + /** @description The automated issuance authorization in force when the issuer was called. */ + authorization_id: string | null; + /** @description Whether that authorization still stands. An issued card is never undone; a revocation since is reported here. */ + authorization_active: boolean | null; + }; + }; + }; + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @enum {string} */ + state: "issued"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + mandate_id: string; + consumer_id: string; + card: { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }; + /** @description The automated issuance authorization in force when the issuer was called. */ + authorization_id: string | null; + /** @description Whether that authorization still stands. An issued card is never undone; a revocation since is reported here. */ + authorization_active: boolean | null; + }; + }; + }; + /** @description OK */ + 202: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** + * @description A person must act; nothing was sent to the issuer for this request since the last answer. + * @enum {string} + */ + state: "pending_human"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + mandate_id: string; + consumer_id: string; + pending_action: { + /** @description Stable for the same issue request and kind. */ + id: string; + /** @enum {string} */ + kind: "issuer_kyc" | "accept_terms" | "authorize_automated_issuance" | "bind_key_to_mandate" | "complete_holder_profile"; + /** + * @description `holder` acts for themselves (personal terms, KYC); `company_signatory` signs for the company (PJ) or the holder (PF) authorizes issuance; `org_admin` configures. + * @enum {string} + */ + actor: "holder" | "company_signatory" | "org_admin"; + /** @description Where the person acts: the issuer's KYC link, or the dashboard page of this issue request. Null when the deployment has no dashboard URL. */ + url: string | null; + /** @description complete_holder_profile only: exactly the holder fields still missing. `document` means the account's onboarding (KYC) is not finished. */ + missing_fields?: ("document" | "full_name" | "email" | "birthdate" | "address.line1" | "address.city" | "address.postal_code")[]; + }; + } | { + /** + * @description `processing`: the issuer is being called. `uncertain`: a timeout or an ambiguous answer, the card MAY exist; a retry with the same key reconciles on the same issuer reference and never issues a second card. + * @enum {string} + */ + state: "processing" | "uncertain"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + mandate_id: string; + consumer_id: string; + retry_after_seconds: number; + note?: string; + issuer_code?: string; + }; + }; + }; + /** @description The body or the key is malformed. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "invalid_body" | "idempotency_key_required"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No API key behind the request. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_connection_key_unknown"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The caller may not issue: a service caller, a key without `cards:issue`, an OAuth token whose consent key is not bound to the mandate and listed in its authorization, or a mandate paused, revoked or expired. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_issue_requires_api_key" | "card_scope_missing" | "card_oauth_not_bound" | "mandate_paused" | "mandate_revoked" | "mandate_expired"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No mandate with that id in this project. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_mandate_not_found"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The key was used with another body; the request failed for good at the issuer; one card per mandate; the holder or the terms do not allow it; the program's card limit; or the issuer's attempt is still open (retry with the same key). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "idempotency_key_conflict" | "card_issue_request_failed" | "card_mandate_already_bound" | "card_holder_not_eligible" | "card_terms_policy_missing" | "card_limit_reached" | "card_issue_in_progress"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No program for the currency/provider, the program is unavailable (`details.reason`, `details.available_programs`), the mandate cannot back the card, or the issuer refused the card. */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_program_not_found" | "card_issuer_unavailable" | "card_mandate_not_eligible" | "card_issue_refused"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer failed the request; repeat with the same key. */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + code: string; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer's lane or credentials could not be reached; nothing was issued. */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_issuer_unavailable" | "vault_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/cards/programs": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * The card programs and their availability in this project + * @description Each program with whether it can issue now in the caller's project and environment and, when not, why. Available = its Card issuing integration is connected (verified), the project is Test, the issuer is enabled and the account is eligible. Requires `cards:read`. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** + * @description The account's market, derived server-side. Every account is BR today. + * @enum {string} + */ + market: "BR"; + programs: { + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + currency: "BRL" | "USD"; + available: boolean; + /** @enum {string} */ + reason?: "not_configured" | "not_verified" | "verify_failed" | "live_blocked" | "account_not_eligible" | "issuer_disabled" | "issuer_not_supported"; + operations: ("issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }[]; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/cards/readiness": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * What is missing before a card can be issued + * @description Per program, each requirement of an issue and its status (`done`, `pending` with the actor who acts, `blocked` with the reason, `not_applicable`), optionally for one holder and mandate. Computed by the SAME function the issue runs, so this checklist and an issue's refusal never disagree. Read-only; a person session or an API key. Requires `cards:read`. + */ + get: { + parameters: { + query?: { + /** @description The holder. */ + consumer_id?: string; + /** @description The mandate the card would stand on; the authorization is bound to it. */ + mandate_id?: string; + /** @description Default: `person` for a dashboard session, `automated` for an API key. */ + mode?: "automated" | "person"; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** + * @description `automated`: an API key / OAuth issue. `person`: the competent person issuing in the dashboard, where bind_key_to_mandate and authorize_automated_issuance are not_applicable. + * @enum {string} + */ + mode: "automated" | "person"; + programs: { + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + currency: "BRL" | "USD"; + ready: boolean; + requirements: { + /** @enum {string} */ + kind: "environment" | "integration_connected" | "bind_key_to_mandate" | "complete_holder_profile" | "issuer_kyc" | "accept_terms" | "authorize_automated_issuance"; + /** @enum {string} */ + status: "done" | "pending" | "blocked" | "not_applicable"; + /** @enum {string} */ + actor: "holder" | "company_signatory" | "org_admin"; + action_url?: string; + reason?: string; + /** @description The pending action of the open issue request on this mandate, when there is one. */ + pending_action_id?: string; + /** @description complete_holder_profile: exactly the holder fields still missing. */ + missing_fields?: string[]; + /** @description authorize_automated_issuance, with a mandate asked: the mandate the authorization binds to. */ + mandate_id?: string; + /** @description authorize_automated_issuance, with a mandate asked: the project's unrevoked API keys bound to it. */ + bound_api_key_ids?: string[]; + }[]; + }[]; + }; + }; + }; + /** @description The query did not match the schema. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "invalid_query"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/cards/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read a card, or an issue request + * @description A card id answers the card view. An issue request id (`cir_…`) answers its state: the pending action, the issued card, or the failure. Another project's id is indistinguishable from one that does not exist. Requires `cards:read`. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + /** @description A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`). */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + } | { + /** + * @description A person must act; nothing was sent to the issuer for this request since the last answer. + * @enum {string} + */ + state: "pending_human"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + mandate_id: string; + consumer_id: string; + pending_action: { + /** @description Stable for the same issue request and kind. */ + id: string; + /** @enum {string} */ + kind: "issuer_kyc" | "accept_terms" | "authorize_automated_issuance" | "bind_key_to_mandate" | "complete_holder_profile"; + /** + * @description `holder` acts for themselves (personal terms, KYC); `company_signatory` signs for the company (PJ) or the holder (PF) authorizes issuance; `org_admin` configures. + * @enum {string} + */ + actor: "holder" | "company_signatory" | "org_admin"; + /** @description Where the person acts: the issuer's KYC link, or the dashboard page of this issue request. Null when the deployment has no dashboard URL. */ + url: string | null; + /** @description complete_holder_profile only: exactly the holder fields still missing. `document` means the account's onboarding (KYC) is not finished. */ + missing_fields?: ("document" | "full_name" | "email" | "birthdate" | "address.line1" | "address.city" | "address.postal_code")[]; + }; + } | { + /** + * @description `processing`: the issuer is being called. `uncertain`: a timeout or an ambiguous answer, the card MAY exist; a retry with the same key reconciles on the same issuer reference and never issues a second card. + * @enum {string} + */ + state: "processing" | "uncertain"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + mandate_id: string; + consumer_id: string; + retry_after_seconds: number; + note?: string; + issuer_code?: string; + } | { + /** @enum {string} */ + state: "issued"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + mandate_id: string; + consumer_id: string; + card: { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }; + /** @description The automated issuance authorization in force when the issuer was called. */ + authorization_id: string | null; + /** @description Whether that authorization still stands. An issued card is never undone; a revocation since is reported here. */ + authorization_active: boolean | null; + } | { + /** @enum {string} */ + state: "received" | "failed"; + issue_request_id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + selection: { + /** + * @description The `provider` the first call asked for; null when the program was chosen by currency. + * @enum {string|null} + */ + provider_requested: "pomelo" | "rain" | null; + /** @enum {string} */ + chosen_by: "provider" | "currency"; + }; + failure_code?: string; + }; + }; + }; + /** @description No card or issue request with that id in this project. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_not_found"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/cards/{id}/freeze": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Freeze a card + * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + /** @description A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`). */ + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + /** @enum {string} */ + reason?: "client_request" | "lost" | "stolen" | "broken" | "upgrade"; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }; + }; + }; + /** @description The body did not match the schema. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "invalid_body"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No API key behind the request. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_connection_key_unknown"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The key lacks `cards:issue`. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_scope_missing"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No card with that id in this project. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_not_found"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The card's state does not allow it (`details.available_actions`). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_action_not_allowed"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The program does not support it, or the project is Live. */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_action_unsupported" | "card_issuer_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer did not apply the change; the card is as it was. */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_control_failed"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer's credentials could not be read. */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "vault_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/cards/{id}/unfreeze": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Unfreeze a card + * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + /** @description A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`). */ + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + /** @enum {string} */ + reason?: "client_request" | "lost" | "stolen" | "broken" | "upgrade"; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }; + }; + }; + /** @description The body did not match the schema. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "invalid_body"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No API key behind the request. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_connection_key_unknown"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The key lacks `cards:issue`. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_scope_missing"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No card with that id in this project. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_not_found"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The card's state does not allow it (`details.available_actions`). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_action_not_allowed"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The program does not support it, or the project is Live. */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_action_unsupported" | "card_issuer_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer did not apply the change; the card is as it was. */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_control_failed"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer's credentials could not be read. */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "vault_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/cards/{id}/cancel": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Cancel a card + * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + /** @description A card id (`icrd_…`, `rcrd_…`); on GET, also an issue request id (`cir_…`). */ + id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + /** @enum {string} */ + reason?: "client_request" | "lost" | "stolen" | "broken" | "upgrade"; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @description `icrd_…` for a Pomelo card, `rcrd_` for a Rain card. The issuer is the record's, never the request's. */ + id: string; + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** + * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @enum {string} + */ + currency: "BRL" | "USD"; + /** @enum {string} */ + status: "pending" | "not_activated" | "active" | "blocked" | "canceled"; + /** @description The issuer's own status name (Pomelo ACTIVE/BLOCKED/DISABLED; Rain notActivated/active/locked/canceled). */ + issuer_status: string; + last4: string | null; + /** @enum {string|null} */ + network: "visa" | "mastercard" | null; + mandate_id: string | null; + consumer_id: string | null; + /** Format: date-time */ + created_at: string; + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + available_actions: ("freeze" | "unfreeze" | "cancel")[]; + funding?: { + /** @enum {string} */ + asset: "USDC"; + }; + }; + }; + }; + /** @description The body did not match the schema. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "invalid_body"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No API key behind the request. */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_connection_key_unknown"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The key lacks `cards:issue`. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_scope_missing"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No card with that id in this project. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_not_found"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The card's state does not allow it (`details.available_actions`). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_action_not_allowed"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The program does not support it, or the project is Live. */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_action_unsupported" | "card_issuer_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer did not apply the change; the card is as it was. */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_control_failed"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The issuer's credentials could not be read. */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "vault_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/cards/holder-profiles/{consumer_id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Which Pomelo holder fields are on file and which are missing + * @description The Pomelo holder is built from what the account already holds (the verified document, the onboarding's registered name) and the holder's profile. This read names each required field's source and lists exactly what is missing. It never returns a value. Requires `cards:read`. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + consumer_id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + consumer_id: string; + /** @enum {string} */ + program: "pomelo_brl"; + /** @description Where each required field comes from. Values are never returned. */ + sources: { + [key: string]: "account" | "onboarding" | "profile" | "missing"; + }; + missing_fields: ("document" | "full_name" | "email" | "birthdate" | "address.line1" | "address.city" | "address.postal_code")[]; + optional_present: string[]; + complete: boolean; + /** Format: date-time */ + updated_at: string | null; + }; + }; + }; + /** @description No consumer with that id in this organization. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_consumer_not_found"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + /** + * The holder fills only what is missing + * @description Sealed with the vault's per-org key. Send only the fields asked for; a field sent replaces the stored one. The document is never accepted here: it comes from the account's onboarding (KYC). After this, repeat the SAME issue request (same Idempotency-Key): it revalidates and resumes, and never issues a second card. Only the HOLDER may write it, a verified person through the dashboard whose own verified consumer is this one (or Rain's verified person for it); an admin or another member gets `card_holder_only`, an API key or an OAuth token `card_person_required`. + */ + put: { + parameters: { + query?: never; + header?: never; + path: { + consumer_id: string; + }; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + full_name?: string; + /** Format: email */ + email?: string; + birthdate?: string; + phone?: string; + address?: { + line1: string; + line2?: string; + street_number?: string; + neighborhood?: string; + city: string; + state?: string; + postal_code: string; + municipality?: string; + /** @default BR */ + country?: string; + }; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + consumer_id: string; + /** @enum {string} */ + program: "pomelo_brl"; + /** @description Where each required field comes from. Values are never returned. */ + sources: { + [key: string]: "account" | "onboarding" | "profile" | "missing"; + }; + missing_fields: ("document" | "full_name" | "email" | "birthdate" | "address.line1" | "address.city" | "address.postal_code")[]; + optional_present: string[]; + complete: boolean; + /** Format: date-time */ + updated_at: string | null; + }; + }; + }; + /** @description The body did not match the schema. */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "invalid_body"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description Not a verified person of this org, or not the holder: only the holder writes it, proved by their own verified consumer or their Rain-verified person, never by a role. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_person_required" | "card_authorization_not_competent" | "card_holder_only"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description No consumer with that id in this organization. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_consumer_not_found"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description A Live project. */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "card_issuer_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + }; + }; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/integrations/card-issuing": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Integrations: Card issuing + * @description One entry per program: managed by CodeSpar (no customer credential), and its state in this project and environment: `not_configured`, `configured` (never verified), `connected` (last verification ok), `verify_failed` (with `reason`), `live_blocked`. Requires `cards:read`. + */ + get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @enum {string} */ + issuer: "pomelo" | "rain"; + /** @enum {string} */ + program: "pomelo_brl" | "rain_usd"; + /** @enum {string} */ + currency: "BRL" | "USD"; + /** + * @description The customer supplies no issuer credentials. + * @enum {string} + */ + managed_by: "codespar"; + /** + * @description `connected` = connectivity verified for the current connection, template and credential versions, unexpired. It is NOT homologation, holder eligibility or issuance availability. + * @enum {string} + */ + status: "not_configured" | "configured" | "connected" | "verify_failed" | "live_blocked"; + /** Format: date-time */ + verified_at: string | null; + /** Format: date-time */ + expires_at: string | null; + reason?: string; + operations: ("issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel")[]; + }[]; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/funding-sources/{id}": { parameters: { query?: never; @@ -13512,447 +15107,6 @@ export interface paths { patch?: never; trace?: never; }; - "/v1/issuer/cards/{id}": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - /** - * Read one issued card, or the mint flow behind it - * @deprecated - * @description DEPRECATED alias of `GET /v1/cards/{id}` (ent#979), kept for two releases. Same handler, same required scope; switch the path and nothing else changes. - * - * ONE path, TWO bodies, chosen by the id's prefix. An `imf_` id is a mint flow and answers with the flow; anything else is read as a card row and answers with the card. Branch on the prefix you sent, or on `flow_id` being present, never on field order. - * - * Resolution is scoped to the organization AND the project the credential authenticates for: both lookups filter on all three of id, org and project, so a card held by a sibling project in the same organization answers 404 here, indistinguishable from one that never existed. - * - * No cardholder data crosses this boundary. The number is represented by `last4` and by the token id; PAN, CVV and expiry never enter the process that serves this route. - * - * Requires the `cards:read` scope. - */ - get: { - parameters: { - query?: never; - header?: never; - path: { - /** @description `icrd_` for a card, `imf_` for a mint flow. The prefix selects the body. */ - id: string; - }; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description OK. The card, or the mint flow when the id was an `imf_` one — see the description for which id yields which. */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @description `icrd_`-prefixed. Our row id for the card, not the issuer's handle. */ - id: string; - /** - * @description The issuing rail the card was minted on. Closed in the type, not just in data. - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own global handle for the card. */ - card_id: string; - /** @description Last four digits. The only fragment of the number this API returns. */ - last4: string; - /** @enum {string} */ - network: "visa" | "mastercard"; - /** @enum {string} */ - status: "active" | "blocked" | "canceled"; - /** @description The card-data-environment token id, null until the mint flow allocates one. Allocation happens BEFORE the card material is ingested, so a token id with no material behind it is a recorded failure rather than a silent gap. It is the handle a PCI-scoped surface exchanges for card material; no card material is reachable through this API with it. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - } | { - /** @description `imf_`-prefixed. The mint attempt, keyed by the caller's idempotency key. */ - flow_id: string; - /** @enum {string} */ - state: "pending" | "issued" | "revoked" | "failed"; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - /** @description Why the flow is parked or failed, when the lane recorded one. */ - reason: string | null; - /** @description The issuer-hosted step the holder must complete before the flow can move on. */ - kyc_url: string | null; - /** Format: date-time */ - created_at: string; - /** @description Present ONLY when the flow reached `issued` AND carries a card row id. It is then the card itself, or null if that row could not be read back. On every other state the key is absent rather than null, so `"card" in body` and `body.card !== null` are different questions. */ - card?: { - /** @description `icrd_`-prefixed. Our row id for the card, not the issuer's handle. */ - id: string; - /** - * @description The issuing rail the card was minted on. Closed in the type, not just in data. - * @enum {string} - */ - issuer: "pomelo" | "bridge"; - /** @description The issuer's own global handle for the card. */ - card_id: string; - /** @description Last four digits. The only fragment of the number this API returns. */ - last4: string; - /** @enum {string} */ - network: "visa" | "mastercard"; - /** @enum {string} */ - status: "active" | "blocked" | "canceled"; - /** @description The card-data-environment token id, null until the mint flow allocates one. Allocation happens BEFORE the card material is ingested, so a token id with no material behind it is a recorded failure rather than a silent gap. It is the handle a PCI-scoped surface exchanges for card material; no card material is reachable through this API with it. */ - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - } | null; - }; - }; - }; - /** @description Not Found. No card and no mint flow with this id in the caller's organization and project. Both branches answer with the same code and differ only in the message. */ - 404: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "issuer_card_unknown"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - }; - }; - put?: never; - post?: never; - delete?: never; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; - "/v1/issuer/cards": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - get?: never; - put?: never; - /** - * Issue a card under a signed mandate (deprecated path) - * @deprecated - * @description DEPRECATED alias of `POST /v1/cards` (ent#979), kept for two releases. Same handler, same required scope; switch the path and nothing else changes. - * - * Three success outcomes: `201` issued the card now, `202` the issuer asked for KYC of the holder (`kyc_url` is where to send the person), `200` is a repeat of the same `Idempotency-Key` on a flow that already finished. Repeating with the SAME key is the recovery path: a `502 issuer_ingest_failed` means the card EXISTS and only the ingest failed, and a new key would issue a second card. - */ - post: { - parameters: { - query?: never; - header?: { - "Idempotency-Key"?: string; - }; - path?: never; - cookie?: never; - }; - requestBody?: { - content: { - "application/json": { - /** @description ISO 3166-1 alpha-2, uppercase. */ - country: string; - /** @description ISO 4217, uppercase. */ - currency: string; - holder: { - full_name: string; - /** Format: email */ - email: string; - birthdate: string; - document: { - type: string; - value: string; - issuing_country: string; - }; - address: { - line1: string; - line2?: string; - street_number?: string; - neighborhood?: string; - city: string; - state?: string; - postal_code: string; - municipality?: string; - country: string; - }; - phone?: string; - }; - /** @description Required: there is no card without a signed mandate. */ - mandate_id: string; - metadata?: { - [key: string]: string; - }; - }; - }; - }; - responses: { - /** @description OK */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @enum {string} */ - state: "issued"; - flow_id: string; - card: { - id: string; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - card_id: string; - last4: string; - /** @enum {string} */ - network: "visa" | "mastercard"; - /** @enum {string} */ - status: "active" | "blocked" | "canceled"; - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - }; - } | { - flow_id: string; - /** @enum {string} */ - state: "pending" | "issued" | "revoked" | "failed"; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - reason: string | null; - kyc_url: string | null; - /** Format: date-time */ - created_at: string; - }; - }; - }; - /** @description OK */ - 201: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - /** @enum {string} */ - state: "issued"; - flow_id: string; - card: { - id: string; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - card_id: string; - last4: string; - /** @enum {string} */ - network: "visa" | "mastercard"; - /** @enum {string} */ - status: "active" | "blocked" | "canceled"; - token_id: string | null; - /** - * @description Whether the cardholder-data environment holds this card's PAN. `ingested`: it does, and `token_id` names the token. `not_configured`: this deployment has no CDE, the PAN was never asked for, and no retry of the Idempotency-Key changes that — a deployment posture, not a caller fault. `not_ingested`: a CDE exists and the card has no token; on a mint that is the 502 `issuer_ingest_failed` retry contract, on a read it is a card whose ingest has not landed. - * @enum {string} - */ - cde: "ingested" | "not_ingested" | "not_configured"; - /** Format: date-time */ - created_at: string; - }; - }; - }; - }; - /** @description OK */ - 202: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - flow_id: string; - /** @enum {string} */ - state: "pending" | "issued" | "revoked" | "failed"; - /** @enum {string} */ - issuer: "pomelo" | "bridge"; - reason: string | null; - kyc_url: string | null; - /** Format: date-time */ - created_at: string; - }; - }; - }; - /** @description Body outside the schema, a country/currency pair with no corridor, a rejected holder, or controls requested that the rail does not have. */ - 400: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "invalid_body" | "issuer_corridor_unsupported" | "invalid_holder" | "issuer_controls_unsupported"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The key and the issuer environment do not match. */ - 403: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "stage_issuer_live_key" | "live_issuer_test_key"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The named mandate does not exist in this organization. */ - 404: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "mandate_not_found"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description Key repeated with a different body, or used before a key rotation and no longer matchable (use a new key), or the mandate is not active. */ - 409: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "idempotency_key_conflict" | "mandate_not_active"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description Flow issued with no readable card row. */ - 500: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "issuer_card_unknown"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description The issuer failed, or the card was issued and the ingest failed; in the second case the card comes back in `details.card` and the recovery is to repeat the same key. */ - 502: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "issuer_mint_failed" | "issuer_ingest_failed"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - /** @description Issuer credentials not readable in the vault. */ - 503: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - error: { - /** @enum {string} */ - code: "vault_unavailable"; - message: string; - details?: { - [key: string]: unknown; - }; - }; - /** @description Echoes the `X-Request-Id` header when the request carried one. */ - request_id: string | null; - }; - }; - }; - }; - }; - delete?: never; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; "/v1/kyc/onboard": { parameters: { query?: never; @@ -48772,6 +49926,11 @@ export interface paths { "application/json": { /** @description The pedido aberto, as the person said it (e.g. "fone bluetooth"). */ query: string; + /** + * @description product (default), service_plan or reservation. + * @enum {string} + */ + task_kind?: "product" | "service_plan" | "reservation"; criteria?: { /** * @description What decides the principal: the lowest total (default) or the fastest delivery. @@ -48780,10 +49939,44 @@ export interface paths { priority?: "total" | "eta"; /** @description The most the person wants to pay, shipping included, in centavos. */ max_total_minor?: number; - /** @description Where to look: `registry` (the stores the Shop can buy at), `vtex` and `meli` (comparison only). Default: `registry` in Test, `vtex` and `meli` in Live. */ - sources?: ("registry" | "vtex" | "meli")[]; + /** @description Where to look: `registry` (the stores the Shop can buy at), `vtex` and `meli` (comparison only), `web` (the origins named in sources.origins). Default: `registry` in Test, `vtex` and `meli` in Live. */ + sources?: ("registry" | "vtex" | "meli" | "web")[]; /** @description Offers per source, 1 to 5 (default 5). */ limit?: number; + /** @description task_kind reservation: check_in, check_out, occupants, location. */ + reservation?: { + /** @description Check-in day, YYYY-MM-DD (São Paulo). */ + check_in: string; + /** @description Check-out day, YYYY-MM-DD, after check_in. */ + check_out: string; + occupants: { + adults: number; + children?: number; + }; + /** @description Where, as the person said it. */ + location?: string; + }; + /** @description task_kind service_plan: licenses and period. */ + service_plan?: { + /** @description How many seats or licenses. */ + licenses: number; + /** + * @description The billing period to compare on. + * @enum {string} + */ + period: "monthly" | "annual"; + }; + /** @description Conditions an offer must state to be compared: an offer that does not state one is left out, with the reason. */ + required?: ("free_cancellation" | "breakfast_included" | "invoice" | "refundable" | "location")[]; + }; + sources?: { + groups?: ("registry" | "vtex" | "meli" | "web")[]; + origins?: { + /** @description https://host of a site to consult, as the person or you named it. */ + origin: string; + /** @description The path to start at; default /. */ + start_path?: string; + }[]; }; }; }; diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index 202f9f9d..c22031ed 100644 --- a/packages/core/src/generated/operations.ts +++ b/packages/core/src/generated/operations.ts @@ -1,6 +1,6 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 868a0272e249a736c8f2510fb7e7def491fdb6ee509d85fc09e5f2fb32af33bd, fetched 2026-11-15T23:15:37.743Z -// from https://api.codespar.dev/openapi.json, API 0.3.0). +// Source: openapi-snapshot.json (sha256 6941cbee6488d220240741e9147cd018de80426af81d3fc02aa32dd757bd2224, fetched 2026-11-19T02:03:13.382Z +// from candidate:ffa66ce789ab6284cab9f831ba73025f0a5afeae/openapi-candidate.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) import type { ApiOperationRef } from "../api/types.js"; @@ -13,12 +13,15 @@ import type { ApiOperationRef } from "../api/types.js"; */ export const API_OPERATIONS = [ { method: "get", path: "/.well-known/oauth-protected-resource", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/.well-known/oauth-protected-resource/mcp", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/.well-known/codespar-receipt-keys.json", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/.well-known/oauth-authorization-server", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "post", path: "/oauth/register", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/oauth/authorize", body: null, accept: "text/html", requiredQuery: ["response_type","client_id","redirect_uri","code_challenge","code_challenge_method"], deprecated: false }, { method: "post", path: "/oauth/authorize", body: "application/x-www-form-urlencoded", accept: null, requiredQuery: [], deprecated: false }, { method: "post", path: "/oauth/token", body: "application/x-www-form-urlencoded", accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/oauth/pending/{handle}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "post", path: "/oauth/pending/{handle}/decide", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/openapi.json", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/openapi.json", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/meta-tools.json", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, @@ -124,13 +127,21 @@ export const API_OPERATIONS = [ { method: "post", path: "/v1/cart/sessions", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, { method: "post", path: "/v1/cart/checkout", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, { method: "post", path: "/v1/cart/nuvemshop/connect/start", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, - { method: "get", path: "/v1/cards", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, - { method: "post", path: "/v1/cards", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, - { method: "get", path: "/v1/cards/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/counterparties/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/servers/{id}/auth-schema", body: null, accept: "application/json", requiredQuery: [], deprecated: true }, { method: "get", path: "/v1/servers/{id}/tools", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "post", path: "/v1/servers/{id}/verify-connection", body: null, accept: "application/json", requiredQuery: [], deprecated: true }, + { method: "get", path: "/v1/cards", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "post", path: "/v1/cards", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/v1/cards/programs", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/v1/cards/readiness", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/v1/cards/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "post", path: "/v1/cards/{id}/freeze", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "post", path: "/v1/cards/{id}/unfreeze", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "post", path: "/v1/cards/{id}/cancel", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/v1/cards/holder-profiles/{consumer_id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "put", path: "/v1/cards/holder-profiles/{consumer_id}", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/v1/integrations/card-issuing", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/funding-sources/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/consent-records/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/consent-records", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, @@ -139,8 +150,6 @@ export const API_OPERATIONS = [ { method: "get", path: "/v1/account-applications/{id}", body: null, accept: "application/json", requiredQuery: ["document_number"], deprecated: false }, { method: "post", path: "/v1/facilitator/x402/executions", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/facilitator/x402/executions/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, - { method: "get", path: "/v1/issuer/cards/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: true }, - { method: "post", path: "/v1/issuer/cards", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: true }, { method: "post", path: "/v1/kyc/onboard", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: true }, { method: "get", path: "/v1/kyc/onboard/{proposalId}/status", body: null, accept: "application/json", requiredQuery: ["document_number"], deprecated: true }, { method: "get", path: "/v1/providers/{slug}/auth-schema", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, From ca7eb46cc7fcdf134f198ef38675f7645d12a95a Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 23:33:56 -0300 Subject: [PATCH 08/12] feat(cli): derive the integrations group (GET /v1/integrations/card-issuing) from the candidate document Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/__tests__/resource-commands.test.ts | 1 + packages/cli/src/surface.ts | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/packages/cli/src/__tests__/resource-commands.test.ts b/packages/cli/src/__tests__/resource-commands.test.ts index 64253cb1..33aa8046 100644 --- a/packages/cli/src/__tests__/resource-commands.test.ts +++ b/packages/cli/src/__tests__/resource-commands.test.ts @@ -233,6 +233,7 @@ const PINNED_COMMANDS = [ "payment-links get → GET /v1/payment-links/{id}", "payment-links delete → DELETE /v1/payment-links/{id}", "payment-links update → PATCH /v1/payment-links/{id}", + "integrations card-issuing → GET /v1/integrations/card-issuing", ]; diff --git a/packages/cli/src/surface.ts b/packages/cli/src/surface.ts index 854f970c..9d555588 100644 --- a/packages/cli/src/surface.ts +++ b/packages/cli/src/surface.ts @@ -272,6 +272,10 @@ export const PUBLISHED_GROUPS: readonly GroupSpec[] = [ name: "payment-links", prefix: "/v1/payment-links", description: "Payment links: the shareable URL an agent pays over x402/USDC and a person pays via Pix; list, create, read, change, remove, payments, stats", + }, { + name: "integrations", + prefix: "/v1/integrations", + description: "Integrations: the card-issuing integration of this project (issuer, program, status, verified_at)", }, ]; From c46d759d5b029d3a1788c7f6d7e58d3ffd35621b Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Wed, 18 Nov 2026 23:51:18 -0300 Subject: [PATCH 09/12] fix(cards): no hand-written funding claim; funding passes through as served CardFunding is open (Record) in TS and a plain dict in Python; the CLI no longer prints a funding asset. The served contract (generated types) is the only place its fields are stated. Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/commands/card.ts | 1 - packages/core/src/__tests__/card.test.ts | 5 +++-- packages/python/src/codespar/__init__.py | 2 -- packages/python/src/codespar/_async_session.py | 7 +------ packages/python/src/codespar/types.py | 11 +++-------- packages/python/tests/test_card.py | 5 +++-- packages/types/src/types.ts | 12 +++++++----- 7 files changed, 17 insertions(+), 26 deletions(-) diff --git a/packages/cli/src/commands/card.ts b/packages/cli/src/commands/card.ts index d089e898..f1eb76d2 100644 --- a/packages/cli/src/commands/card.ts +++ b/packages/cli/src/commands/card.ts @@ -125,7 +125,6 @@ function viewPairs(v: CardView): Array<[string, string]> { ["Actions", v.available_actions.length > 0 ? v.available_actions.join(", ") : "none"], ]; if (v.last4) pairs.push(["Last four", v.last4]); - if (v.funding) pairs.push(["Funding", v.funding.asset]); if (v.mandate_id) pairs.push(["Mandate", v.mandate_id]); if (v.consumer_id) pairs.push(["Consumer", v.consumer_id]); return pairs; diff --git a/packages/core/src/__tests__/card.test.ts b/packages/core/src/__tests__/card.test.ts index df0e612e..799a68d9 100644 --- a/packages/core/src/__tests__/card.test.ts +++ b/packages/core/src/__tests__/card.test.ts @@ -76,7 +76,7 @@ const RAIN_VIEW: CardView = { consumer_id: "cons_1", created_at: "2026-11-18T12:00:00.000Z", available_actions: [], - funding: { asset: "USDC" }, + funding: { source: "wallet", currency: "BRL" }, }; function issued(card: CardView) { @@ -124,7 +124,8 @@ describe("session.card facade", () => { expect(r.program).toBe("rain_usd"); expect(r.issue_request_id).toBe("cir_1"); expect(r.card.currency).toBe("USD"); - expect(r.card.funding).toEqual({ asset: "USDC" }); + // Passed through as served; the client restates none of its fields. + expect(r.card.funding).toEqual({ source: "wallet", currency: "BRL" }); expect(r.card.network).toBeNull(); expect(r.selection).toEqual({ provider_requested: null, chosen_by: "currency" }); expect(r.card.available_actions).toEqual([]); diff --git a/packages/python/src/codespar/__init__.py b/packages/python/src/codespar/__init__.py index 7cf7fd99..8738b4a8 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -103,7 +103,6 @@ CardControlAction, CardControlReason, CardCurrency, - CardFunding, CardIssued, CardIssuer, CardList, @@ -239,7 +238,6 @@ "CardControlAction", "CardControlReason", "CardCurrency", - "CardFunding", "CardIssued", "CardIssuer", "CardList", diff --git a/packages/python/src/codespar/_async_session.py b/packages/python/src/codespar/_async_session.py index 38033e96..45d7770f 100644 --- a/packages/python/src/codespar/_async_session.py +++ b/packages/python/src/codespar/_async_session.py @@ -24,7 +24,6 @@ AuthConfig, AuthResult, CardArgs, - CardFunding, CardIssued, CardList, CardPendingAction, @@ -269,11 +268,7 @@ def _card_view_fields(raw: dict[str, Any]) -> dict[str, Any]: "consumer_id": raw.get("consumer_id"), "created_at": raw.get("created_at"), "available_actions": _str_list(raw.get("available_actions")), - "funding": ( - CardFunding(asset=str(funding.get("asset", "USDC"))) - if isinstance(funding, dict) - else None - ), + "funding": dict(funding) if isinstance(funding, dict) else None, } diff --git a/packages/python/src/codespar/types.py b/packages/python/src/codespar/types.py index 9e24b49e..34976ee7 100644 --- a/packages/python/src/codespar/types.py +++ b/packages/python/src/codespar/types.py @@ -669,13 +669,6 @@ class CardSelection: chosen_by: str = "currency" # "provider" | "currency" -@dataclass(slots=True) -class CardFunding: - """Funding of a ``rain_usd`` card (USDC). Never mixed into ``currency``.""" - - asset: str = "USDC" - - @dataclass(slots=True) class CardView: """The card view: get, controls, list items.""" @@ -692,7 +685,9 @@ class CardView: consumer_id: str | None = None created_at: str | None = None available_actions: list[str] = field(default_factory=list) - funding: CardFunding | None = None + #: How the card is funded, as the server reports it for its program + #: (the served contract's fields, passed through unchanged). + funding: dict[str, Any] | None = None @dataclass(slots=True) diff --git a/packages/python/tests/test_card.py b/packages/python/tests/test_card.py index ee12172d..fd40598e 100644 --- a/packages/python/tests/test_card.py +++ b/packages/python/tests/test_card.py @@ -45,7 +45,7 @@ "consumer_id": "cons_1", "created_at": "2026-11-18T12:00:00.000Z", "available_actions": [], - "funding": {"asset": "USDC"}, + "funding": {"source": "wallet", "currency": "BRL"}, } ISSUE_USD = CardArgs( @@ -127,7 +127,8 @@ async def test_issue_dispatches_codespar_card_and_returns_issued(httpx_mock: HTT assert result.card.issuer_status == "notActivated" assert result.card.available_actions == [] assert result.card.network is None - assert result.card.funding is not None and result.card.funding.asset == "USDC" + # Passed through as served; the client restates none of its fields. + assert result.card.funding == {"source": "wallet", "currency": "BRL"} assert result.authorization_id == "caia_1" assert result.authorization_active is True assert result.selection is not None diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index bea62ed9..b1e8fd4a 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -810,7 +810,7 @@ export interface LedgerReceiptsResult { * record behind `card_id`). */ export type CardIssuer = "pomelo" | "rain"; -/** The CARD currency. Rain's funding asset (USDC) is separate: `CardView.funding`. */ +/** The CARD currency. How a card is funded is separate data: `CardView.funding`. */ export type CardCurrency = "BRL" | "USD"; /** Program registry, code-side on the server. */ export type CardProgram = "pomelo_brl" | "rain_usd"; @@ -893,10 +893,12 @@ export interface CardSelection { chosen_by: "provider" | "currency"; } -/** Funding of a `rain_usd` card. Never mixed into `currency`. */ -export interface CardFunding { - asset: "USDC"; -} +/** + * How a card is funded, as the server reports it for its program. Kept + * open here: its fields are the served contract's (see the generated + * OpenAPI types), and nothing in this file restates them. + */ +export type CardFunding = Record; /** The card view (REST and codespar_card): get, controls, list items, an issued card. */ export interface CardView { From 682a72b76b06e199fdc99028b5efe242459555d7 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Thu, 19 Nov 2026 00:40:04 -0300 Subject: [PATCH 10/12] feat(cards): final wire from enterprise candidate 05f75845c MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Snapshot + src/generated regenerated from candidate 05f75845c051e7e8cba908547a9a2327cd1286e4 (sha256 6f75bed7…, 399 operations). - CardFunding { source: "wallet", currency: "BRL" } and CardProgramSettlement { asset: "USDC", by: "codespar" } typed exactly, pinned to the generated schema by card-wire.test.ts; no loose Record. - CardView.payment_token, network visa|mastercard; holder_consumer_id on issue (TS, Python, CLI --holder-consumer-id); readiness mode, kinds issuer_capability_pending / verify_company_representative, missing_fields; refusal codes card_control_failed / card_control_uncertain. - Freeze/unfreeze/cancel on both programs in the codespar_card description and docs (cancel permanent). Co-Authored-By: Claude Opus 5.5 --- packages/cli/CHANGELOG.md | 3 + packages/cli/README.md | 2 +- .../cli/src/__tests__/card-command.test.ts | 2 +- packages/cli/src/commands/card.ts | 10 +- packages/cli/src/index.ts | 1 + packages/core/CHANGELOG.md | 3 + packages/core/README.md | 2 +- packages/core/openapi-snapshot.json | 353 ++++++++++++++---- packages/core/src/__tests__/card-wire.test.ts | 48 +++ packages/core/src/generated/openapi.ts | 190 +++++++--- packages/core/src/generated/operations.ts | 4 +- packages/core/src/testing/index.ts | 2 +- packages/python/CHANGELOG.md | 5 +- packages/python/src/codespar/__init__.py | 4 + .../python/src/codespar/_async_session.py | 15 +- packages/python/src/codespar/cards.py | 6 + packages/python/src/codespar/types.py | 29 +- packages/python/tests/test_card.py | 51 ++- packages/types/CHANGELOG.md | 11 +- .../types/src/meta-tool-definitions.test.ts | 1 + packages/types/src/meta-tool-definitions.ts | 3 +- packages/types/src/types.ts | 61 ++- 22 files changed, 647 insertions(+), 159 deletions(-) create mode 100644 packages/core/src/__tests__/card-wire.test.ts diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 8fb27fcc..7380b160 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -22,6 +22,9 @@ - A refusal exits 1 (a definitive issuer failure is one), with an `api` error document carrying the `code`, `status` and the whole refusal as `body`. - `pending_human`, `processing` and `uncertain` exit 0. They say to run the same command again with the SAME `--idempotency-key`, never a new key. `uncertain` says the card may exist. - Vocabularies (actions, currency, provider, issuer, reason) come from the published `codespar_card` definition. +- `--holder-consumer-id` is required for a company's pomelo_brl card. +- A `card_control_uncertain` refusal says to read the card again with `codespar card get `. +- `codespar integrations card-issuing` is derived from the served document. - Depends on `@codespar/sdk ^0.17.0`. ## 0.22.7 — 2026-11-11 diff --git a/packages/cli/README.md b/packages/cli/README.md index 46761637..22382fc9 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -94,7 +94,7 @@ codespar init my-agent | `charge` | Issue an inbound charge via `codespar_charge` | | `ship` | Generate label / quote rates / track via `codespar_ship` | | `ledger` | Post entries / read balances / create accounts via `codespar_ledger` | -| `card issue\|get\|list\|freeze\|unfreeze\|cancel\|readiness` | Spend cards via `codespar_card`: BRL on Pomelo, USD on Rain. `card issue` needs `--currency --mandate-id --consumer-id --idempotency-key`; `processing` / `uncertain` resolve by running it again with the SAME key. `card readiness` lists, per program, what is missing and who must act | +| `card issue\|get\|list\|freeze\|unfreeze\|cancel\|readiness` | Spend cards via `codespar_card`: BRL on Pomelo, USD on Rain. `card issue` needs `--currency --mandate-id --consumer-id --idempotency-key` (`--holder-consumer-id` for a company's pomelo_brl card); `freeze`/`unfreeze`/`cancel` work on both programs, as each card's `available_actions` allows (cancel is permanent); `processing` / `uncertain` resolve by running it again with the SAME key. `card readiness` lists, per program, what is missing and who must act | | `payment-status ` | Poll async settlement status (add `--stream`) | | `verification-status ` | Poll async KYC status (add `--stream`) | | `wizard [server]` | Connection wizard — required secrets, connect URL, next steps | diff --git a/packages/cli/src/__tests__/card-command.test.ts b/packages/cli/src/__tests__/card-command.test.ts index f683141e..9013d8df 100644 --- a/packages/cli/src/__tests__/card-command.test.ts +++ b/packages/cli/src/__tests__/card-command.test.ts @@ -30,7 +30,7 @@ const POMELO_VIEW = { status: "active", issuer_status: "ACTIVE", last4: "4242", - network: "MASTERCARD", + network: "mastercard", mandate_id: "mnd_brl", consumer_id: "cons_1", created_at: "2026-11-18T12:00:00.000Z", diff --git a/packages/cli/src/commands/card.ts b/packages/cli/src/commands/card.ts index f1eb76d2..19e14020 100644 --- a/packages/cli/src/commands/card.ts +++ b/packages/cli/src/commands/card.ts @@ -14,6 +14,7 @@ export interface CardFlags { provider?: string; mandateId?: string; consumerId?: string; + holderConsumerId?: string; idempotencyKey?: string; issuer?: string; reason?: string; @@ -36,6 +37,7 @@ const FLAG_TO_ARG: ReadonlyArray<[keyof CardFlags, string]> = [ ["provider", "provider"], ["mandateId", "mandate_id"], ["consumerId", "consumer_id"], + ["holderConsumerId", "holder_consumer_id"], ["idempotencyKey", "idempotency_key"], ["issuer", "issuer"], ["reason", "reason"], @@ -137,14 +139,16 @@ function viewPairs(v: CardView): Array<[string, string]> { * and a script branches on `state` in `--json`. None of them ever suggests a * new key: processing and uncertain resolve on the same one. */ -export function renderCardResult(action: string, result: CardResult, asJson: boolean): void { +export function renderCardResult(action: string, result: CardResult, asJson: boolean, args?: CardArgs): void { if (result.state === "refused") { // A definitive issuer refusal is a refusal too (card_issue_refused, or // card_issue_request_failed with failure_code on a later call with the // same key): a failure for the exit code. const failure = result.failure_code ? ` [failure_code ${result.failure_code}]` : ""; + // The issuer may or may not have applied the change: read before acting again. + const hint = result.code === "card_control_uncertain" && args && "card_id" in args ? ` Read it again: codespar card get ${args.card_id}.` : ""; throw new HttpError( - `card ${action} refused: ${result.code}${result.reason ? ` (${result.reason})` : ""}${failure}${result.message ? ` — ${result.message}` : ""}`, + `card ${action} refused: ${result.code}${result.reason ? ` (${result.reason})` : ""}${failure}${result.message ? ` — ${result.message}` : ""}${hint}`, { status: result.http_status, code: result.code, body: result }, ); } @@ -209,7 +213,7 @@ export async function cardCommand(action: string, cardId: string | undefined, op const session = await cs.create(opts.user ?? "cli-user", { servers: [] }); try { const result = await session.card(args); - renderCardResult(action, result, opts.json === true); + renderCardResult(action, result, opts.json === true, args); } finally { await session.close(); } diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 219f1394..a116d5eb 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -885,6 +885,7 @@ cardSubcommand("issue", "Issue a card; the currency picks the program unless --p .option("--provider ", "pomelo | rain (optional)") .option("--mandate-id ", "Mandate the card spends under; its currency must equal the card's (required)") .option("--consumer-id ", "Card holder, a consumer of this project (required)") + .option("--holder-consumer-id ", "A company's pomelo_brl card only (required there): the person who will hold it, as their own consumer") .option("--idempotency-key ", "Required. The same key resumes the same request; it never issues a second card") .option("--holder ", "Pomelo cardholder identity as JSON (pomelo_brl): full_name, email, birthdate, document, address, phone?") .action(async (opts: CardCliOpts) => { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 74351399..d3649ae7 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -25,6 +25,9 @@ - `"refused"`: also a definitive issuer failure (`card_issue_refused`; `card_issue_request_failed` with `failure_code` and `issue_request_id` on a later call with the same key). It carries a stable `code`, `reason`, `available_programs`, `available_actions` and `http_status`. The refusal is **returned**, whether it came in the tool envelope or as a non-2xx body. - A result with no `state` is a card view or `{ cards }`. Only a failure with no code throws. - `cs.cards.readiness()` reads `GET /v1/cards/readiness`: per program, ready or not and the checklist of what is missing. +- Freeze, unfreeze and cancel work on both programs, as each card's `available_actions` allows. Cancel is permanent. +- `card_control_uncertain` comes back as a refusal: read the card again. +- `card-wire.test.ts` pins every hand-written card type in `@codespar/types` to the type generated from the served schema. - `spec:refresh --from-file //openapi-candidate.json` generates from an enterprise candidate document. `assert-served` refuses a candidate snapshot, and the publish workflow runs it. - Depends on `@codespar/types ^0.12.0`. The fake session in `@codespar/sdk/testing` implements `card()`. diff --git a/packages/core/README.md b/packages/core/README.md index 7e5dd4ac..0d1646a6 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -12,7 +12,7 @@ Eight new typed methods on `Session`, grouped by capability: - `session.charge(args)` — INBOUND charges (`codespar_charge`). Buyer pays merchant. Pix BRL via Asaas / MP / iugu / Stone; card USD via Stripe. Distinct from `codespar_pay` (outbound transfers). - `session.ship(args)` — shipping (`codespar_ship`). One typed entry into Melhor Envio's 3 rails (`action: "label" | "quote" | "track"`). -- `session.card(args)` — spend cards (`codespar_card`), one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`): `action: "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"`. `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`; `provider` is optional (the currency picks the program). Narrow the result on `state`: `"issued"` (`card` view nested, plus `selection` and the authorization), `"pending_human"` (a `pending_action` only a person can take: `holder`, `company_signatory` or `org_admin`), `"processing"` and `"uncertain"` (the card MAY exist: call again with the SAME key, never a new one), `"refused"` (a definitive issuer failure is one too; a stable `code`, `reason`, `available_programs` / `available_actions`, returned rather than thrown); no `state` is a card view or `{ cards }`. `cs.cards.readiness()` reads `GET /v1/cards/readiness`, per program the checklist of what is missing. It replaces `session.issue()`, which is removed (no alias). +- `session.card(args)` — spend cards (`codespar_card`), one contract for BRL on Pomelo (`pomelo_brl`) and USD on Rain (`rain_usd`): `action: "issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel"`. `issue` takes `currency`, `mandate_id`, `consumer_id` and a required `idempotency_key`; `provider` is optional (the currency picks the program). Narrow the result on `state`: `"issued"` (`card` view nested, plus `selection` and the authorization), `"pending_human"` (a `pending_action` only a person can take: `holder`, `company_signatory` or `org_admin`), `"processing"` and `"uncertain"` (the card MAY exist: call again with the SAME key, never a new one), `"refused"` (a definitive issuer failure is one too; a stable `code`, `reason`, `available_programs` / `available_actions`, returned rather than thrown); no `state` is a card view or `{ cards }`. `freeze` / `unfreeze` / `cancel` work on both programs (cancel is permanent); each card's `available_actions` says which its state allows, and `card_control_uncertain` means read the card again. `cs.cards.readiness()` reads `GET /v1/cards/readiness`, per program the checklist of what is missing. It replaces `session.issue()`, which is removed (no alias). - `session.shop(args)` — buy-side shopping (`codespar_shop`). Catalog search → async checkout → Pix mint (`action: "search" | "checkout" | "checkout_status"`). Discriminated `ShopArgs`/`ShopResult` give the action-correct result type. Checkout is async: start, then poll `checkout_status` until `ready_for_payment` (carries `pix_copia_e_cola`) or `canceled`. Settle the returned Pix via a separate payment tool — settlement and governance are out of this contract. Full spec: [`docs/codespar-shop-contract.md`](../../docs/codespar-shop-contract.md). **Async settlement** — `codespar_charge` / `codespar_pay` return synchronously, but real settlement lands via webhook: diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index cbe5a833..530b8a69 100644 --- a/packages/core/openapi-snapshot.json +++ b/packages/core/openapi-snapshot.json @@ -1,8 +1,8 @@ { "snapshot": { - "source": "candidate:ffa66ce789ab6284cab9f831ba73025f0a5afeae/openapi-candidate.json", - "fetched_at": "2026-11-19T02:03:13.382Z", - "sha256": "6941cbee6488d220240741e9147cd018de80426af81d3fc02aa32dd757bd2224", + "source": "candidate:05f75845c051e7e8cba908547a9a2327cd1286e4/openapi-candidate.json", + "fetched_at": "2026-11-19T03:38:42.091Z", + "sha256": "3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a", "etag": null, "last_modified": null, "info": { @@ -26016,6 +26016,11 @@ "minLength": 1, "maxLength": 255 }, + "holder_consumer_id": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, "holder": { "type": "object", "properties": { @@ -26224,7 +26229,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -26282,21 +26287,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { "type": "string", "enum": [ - "USDC" + "wallet" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -26436,7 +26458,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -26494,21 +26516,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { "type": "string", "enum": [ - "USDC" + "wallet" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -26637,8 +26676,10 @@ "accept_terms", "authorize_automated_issuance", "bind_key_to_mandate", - "complete_holder_profile" - ] + "complete_holder_profile", + "verify_company_representative" + ], + "description": "`verify_company_representative` (pomelo_brl for a company, actor `company_signatory`): the legal representative of the company's approved onboarding completes their own onboarding (their CPF) in the dashboard, then the SAME request resumes." }, "actor": { "type": "string", @@ -27248,7 +27289,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -27306,21 +27347,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { "type": "string", "enum": [ - "USDC" + "wallet" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -27464,7 +27522,8 @@ "live_blocked", "account_not_eligible", "issuer_disabled", - "issuer_not_supported" + "issuer_not_supported", + "pomelo_pj_authority_source" ] }, "operations": { @@ -27482,6 +27541,28 @@ } }, "funding": { + "type": "object", + "properties": { + "source": { + "type": "string", + "enum": [ + "wallet" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL" + ] + } + }, + "required": [ + "source", + "currency" + ], + "description": "What the program's cards spend: the account's CodeSpar BRL wallet (rain_usd), priced in BRL at authorization." + }, + "settlement": { "type": "object", "properties": { "asset": { @@ -27489,11 +27570,19 @@ "enum": [ "USDC" ] + }, + "by": { + "type": "string", + "enum": [ + "codespar" + ] } }, "required": [ - "asset" - ] + "asset", + "by" + ], + "description": "How CodeSpar settles the program with the issuer, from its own treasury (rain_usd: USDC). A program fact: never what a card or its holder spends." } }, "required": [ @@ -27537,10 +27626,10 @@ { "schema": { "type": "string", - "description": "The holder." + "description": "The holder (for a company's pomelo_brl card, the company's consumer)." }, "required": false, - "description": "The holder.", + "description": "The holder (for a company's pomelo_brl card, the company's consumer).", "name": "consumer_id", "in": "query" }, @@ -27554,6 +27643,16 @@ "name": "mandate_id", "in": "query" }, + { + "schema": { + "type": "string", + "description": "A company's pomelo_brl card: the person who would hold it, as their own consumer." + }, + "required": false, + "description": "A company's pomelo_brl card: the person who would hold it, as their own consumer.", + "name": "holder_consumer_id", + "in": "query" + }, { "schema": { "type": "string", @@ -27624,12 +27723,15 @@ "enum": [ "environment", "integration_connected", + "issuer_capability_pending", + "verify_company_representative", "bind_key_to_mandate", "complete_holder_profile", "issuer_kyc", "accept_terms", "authorize_automated_issuance" - ] + ], + "description": "Two items appear only for pomelo_brl on a company (PJ) account. `issuer_capability_pending`: blocked, actor `org_admin`, reason `pomelo_pj_authority_source`; no approved onboarding records who acts for the company at Pomelo (its legal representative), and nothing on the company's side unblocks it now (refusal `card_issuer_unavailable`, with the programs that are available). `verify_company_representative`: actor `company_signatory`; pending, reason `representative_onboarding_required`, until that recorded representative completes their own onboarding (their CPF) in the dashboard; done once a member is the representative." }, "status": { "type": "string", @@ -27813,7 +27915,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -27871,21 +27973,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { "type": "string", "enum": [ - "USDC" + "wallet" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -27977,8 +28096,10 @@ "accept_terms", "authorize_automated_issuance", "bind_key_to_mandate", - "complete_holder_profile" - ] + "complete_holder_profile", + "verify_company_representative" + ], + "description": "`verify_company_representative` (pomelo_brl for a company, actor `company_signatory`): the legal representative of the company's approved onboarding completes their own onboarding (their CPF) in the dashboard, then the SAME request resumes." }, "actor": { "type": "string", @@ -28200,7 +28321,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -28258,21 +28379,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { "type": "string", "enum": [ - "USDC" + "wallet" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -28452,7 +28590,7 @@ "description": "The one Cards contract: programs, selection, requirements, idempotency" }, "summary": "Freeze a card", - "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`.", + "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo; `rain_usd` at Rain (freeze = locked, reversible; unfreeze = active; cancel = canceled, PERMANENT; Rain's own card update stays the source of truth, and Rain may lock a card on its own). Cancel cannot be undone on either issuer. Both answer the card view. Requires `cards:issue`.", "parameters": [ { "schema": { @@ -28519,7 +28657,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -28577,21 +28715,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { + "type": "string", + "enum": [ + "wallet" + ] + }, + "currency": { "type": "string", "enum": [ - "USDC" + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -28838,7 +28993,7 @@ } }, "422": { - "description": "The program does not support it, or the project is Live.", + "description": "The project is Live, or (no program today) the program does not support the action.", "content": { "application/json": { "schema": { @@ -28884,7 +29039,7 @@ } }, "502": { - "description": "The issuer did not apply the change; the card is as it was.", + "description": "`card_control_failed`: the issuer did not apply the change, the card is as it was. `card_control_uncertain`: the issuer may or may not have applied it; read the card again.", "content": { "application/json": { "schema": { @@ -28896,7 +29051,8 @@ "code": { "type": "string", "enum": [ - "card_control_failed" + "card_control_failed", + "card_control_uncertain" ] }, "message": { @@ -28929,7 +29085,7 @@ } }, "503": { - "description": "The issuer's credentials could not be read.", + "description": "The issuer's credentials could not be read, or its lane is off; nothing was sent.", "content": { "application/json": { "schema": { @@ -28941,7 +29097,8 @@ "code": { "type": "string", "enum": [ - "vault_unavailable" + "vault_unavailable", + "card_control_failed" ] }, "message": { @@ -28991,7 +29148,7 @@ "description": "The one Cards contract: programs, selection, requirements, idempotency" }, "summary": "Unfreeze a card", - "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`.", + "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo; `rain_usd` at Rain (freeze = locked, reversible; unfreeze = active; cancel = canceled, PERMANENT; Rain's own card update stays the source of truth, and Rain may lock a card on its own). Cancel cannot be undone on either issuer. Both answer the card view. Requires `cards:issue`.", "parameters": [ { "schema": { @@ -29058,7 +29215,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -29116,21 +29273,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { "type": "string", "enum": [ - "USDC" + "wallet" + ] + }, + "currency": { + "type": "string", + "enum": [ + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -29377,7 +29551,7 @@ } }, "422": { - "description": "The program does not support it, or the project is Live.", + "description": "The project is Live, or (no program today) the program does not support the action.", "content": { "application/json": { "schema": { @@ -29423,7 +29597,7 @@ } }, "502": { - "description": "The issuer did not apply the change; the card is as it was.", + "description": "`card_control_failed`: the issuer did not apply the change, the card is as it was. `card_control_uncertain`: the issuer may or may not have applied it; read the card again.", "content": { "application/json": { "schema": { @@ -29435,7 +29609,8 @@ "code": { "type": "string", "enum": [ - "card_control_failed" + "card_control_failed", + "card_control_uncertain" ] }, "message": { @@ -29468,7 +29643,7 @@ } }, "503": { - "description": "The issuer's credentials could not be read.", + "description": "The issuer's credentials could not be read, or its lane is off; nothing was sent.", "content": { "application/json": { "schema": { @@ -29480,7 +29655,8 @@ "code": { "type": "string", "enum": [ - "vault_unavailable" + "vault_unavailable", + "card_control_failed" ] }, "message": { @@ -29530,7 +29706,7 @@ "description": "The one Cards contract: programs, selection, requirements, idempotency" }, "summary": "Cancel a card", - "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`.", + "description": "Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo; `rain_usd` at Rain (freeze = locked, reversible; unfreeze = active; cancel = canceled, PERMANENT; Rain's own card update stays the source of truth, and Rain may lock a card on its own). Cancel cannot be undone on either issuer. Both answer the card view. Requires `cards:issue`.", "parameters": [ { "schema": { @@ -29597,7 +29773,7 @@ "BRL", "USD" ], - "description": "The CARD currency. A Rain card's funding (USDC) is in `funding`, never here." + "description": "The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here." }, "status": { "type": "string", @@ -29655,21 +29831,38 @@ "cancel" ] }, - "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none." + "description": "What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none." }, "funding": { "type": "object", "properties": { - "asset": { + "source": { + "type": "string", + "enum": [ + "wallet" + ] + }, + "currency": { "type": "string", "enum": [ - "USDC" + "BRL" ] } }, "required": [ - "asset" - ] + "source", + "currency" + ], + "description": "Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset." + }, + "payment_token": { + "type": "string", + "enum": [ + "ready", + "pending", + "not_configured" + ], + "description": "Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value." } }, "required": [ @@ -29916,7 +30109,7 @@ } }, "422": { - "description": "The program does not support it, or the project is Live.", + "description": "The project is Live, or (no program today) the program does not support the action.", "content": { "application/json": { "schema": { @@ -29962,7 +30155,7 @@ } }, "502": { - "description": "The issuer did not apply the change; the card is as it was.", + "description": "`card_control_failed`: the issuer did not apply the change, the card is as it was. `card_control_uncertain`: the issuer may or may not have applied it; read the card again.", "content": { "application/json": { "schema": { @@ -29974,7 +30167,8 @@ "code": { "type": "string", "enum": [ - "card_control_failed" + "card_control_failed", + "card_control_uncertain" ] }, "message": { @@ -30007,7 +30201,7 @@ } }, "503": { - "description": "The issuer's credentials could not be read.", + "description": "The issuer's credentials could not be read, or its lane is off; nothing was sent.", "content": { "application/json": { "schema": { @@ -30019,7 +30213,8 @@ "code": { "type": "string", "enum": [ - "vault_unavailable" + "vault_unavailable", + "card_control_failed" ] }, "message": { diff --git a/packages/core/src/__tests__/card-wire.test.ts b/packages/core/src/__tests__/card-wire.test.ts new file mode 100644 index 00000000..8b25d393 --- /dev/null +++ b/packages/core/src/__tests__/card-wire.test.ts @@ -0,0 +1,48 @@ +/** + * The card types published in `@codespar/types` are hand-written (that + * package has no dependencies), so nothing there may drift from the served + * contract. These assertions bind each wire shape to the type generated + * from the OpenAPI document: a change on either side fails `tsc` here. + * (The vitest body is a runtime no-op; `npm run typecheck` is the check.) + */ + +import { describe, expectTypeOf, it } from "vitest"; +import type { + CardFunding, + CardPaymentToken, + CardProgramSettlement, + CardReadiness, + CardRequirementKind, + CardView, +} from "@codespar/types"; +import type { paths } from "../generated/openapi.js"; + +type IssueOk = paths["/v1/cards"]["post"]["responses"][200]["content"]["application/json"]; +type WireCard = IssueOk["card"]; +type WireProgram = + paths["/v1/cards/programs"]["get"]["responses"][200]["content"]["application/json"]["programs"][number]; +type WireReadiness = paths["/v1/cards/readiness"]["get"]["responses"][200]["content"]["application/json"]; +type WireRequirement = WireReadiness["programs"][number]["requirements"][number]; + +describe("card types == the served card schema", () => { + it("funding, settlement and payment_token are the generated shapes", () => { + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>(); + expectTypeOf().toEqualTypeOf>(); + }); + + it("the card view's identity, status and network vocabularies", () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + }); + + it("readiness: mode and the requirement kinds", () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + }); +}); diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index 79c97150..b834bdba 100644 --- a/packages/core/src/generated/openapi.ts +++ b/packages/core/src/generated/openapi.ts @@ -1,6 +1,6 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 6941cbee6488d220240741e9147cd018de80426af81d3fc02aa32dd757bd2224, fetched 2026-11-19T02:03:13.382Z -// from candidate:ffa66ce789ab6284cab9f831ba73025f0a5afeae/openapi-candidate.json, API 0.3.0). +// Source: openapi-snapshot.json (sha256 3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a, fetched 2026-11-19T03:38:42.091Z +// from candidate:05f75845c051e7e8cba908547a9a2327cd1286e4/openapi-candidate.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { "/.well-known/oauth-protected-resource": { @@ -11993,7 +11993,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -12008,12 +12008,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; }[]; }; }; @@ -12070,6 +12078,7 @@ export interface paths { provider?: string | null; mandate_id: string; consumer_id: string; + holder_consumer_id?: string; holder?: { full_name: string; /** Format: email */ @@ -12130,7 +12139,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -12145,12 +12154,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; }; /** @description The automated issuance authorization in force when the issuer was called. */ authorization_id: string | null; @@ -12192,7 +12209,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -12207,12 +12224,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; }; /** @description The automated issuance authorization in force when the issuer was called. */ authorization_id: string | null; @@ -12252,8 +12277,11 @@ export interface paths { pending_action: { /** @description Stable for the same issue request and kind. */ id: string; - /** @enum {string} */ - kind: "issuer_kyc" | "accept_terms" | "authorize_automated_issuance" | "bind_key_to_mandate" | "complete_holder_profile"; + /** + * @description `verify_company_representative` (pomelo_brl for a company, actor `company_signatory`): the legal representative of the company's approved onboarding completes their own onboarding (their CPF) in the dashboard, then the SAME request resumes. + * @enum {string} + */ + kind: "issuer_kyc" | "accept_terms" | "authorize_automated_issuance" | "bind_key_to_mandate" | "complete_holder_profile" | "verify_company_representative"; /** * @description `holder` acts for themselves (personal terms, KYC); `company_signatory` signs for the company (PJ) or the holder (PF) authorizes issuance; `org_admin` configures. * @enum {string} @@ -12500,11 +12528,21 @@ export interface paths { currency: "BRL" | "USD"; available: boolean; /** @enum {string} */ - reason?: "not_configured" | "not_verified" | "verify_failed" | "live_blocked" | "account_not_eligible" | "issuer_disabled" | "issuer_not_supported"; + reason?: "not_configured" | "not_verified" | "verify_failed" | "live_blocked" | "account_not_eligible" | "issuer_disabled" | "issuer_not_supported" | "pomelo_pj_authority_source"; operations: ("issue" | "get" | "list" | "freeze" | "unfreeze" | "cancel")[]; + /** @description What the program's cards spend: the account's CodeSpar BRL wallet (rain_usd), priced in BRL at authorization. */ funding?: { + /** @enum {string} */ + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; + }; + /** @description How CodeSpar settles the program with the issuer, from its own treasury (rain_usd: USDC). A program fact: never what a card or its holder spends. */ + settlement?: { /** @enum {string} */ asset: "USDC"; + /** @enum {string} */ + by: "codespar"; }; }[]; }; @@ -12534,10 +12572,12 @@ export interface paths { get: { parameters: { query?: { - /** @description The holder. */ + /** @description The holder (for a company's pomelo_brl card, the company's consumer). */ consumer_id?: string; /** @description The mandate the card would stand on; the authorization is bound to it. */ mandate_id?: string; + /** @description A company's pomelo_brl card: the person who would hold it, as their own consumer. */ + holder_consumer_id?: string; /** @description Default: `person` for a dashboard session, `automated` for an API key. */ mode?: "automated" | "person"; }; @@ -12568,8 +12608,11 @@ export interface paths { currency: "BRL" | "USD"; ready: boolean; requirements: { - /** @enum {string} */ - kind: "environment" | "integration_connected" | "bind_key_to_mandate" | "complete_holder_profile" | "issuer_kyc" | "accept_terms" | "authorize_automated_issuance"; + /** + * @description Two items appear only for pomelo_brl on a company (PJ) account. `issuer_capability_pending`: blocked, actor `org_admin`, reason `pomelo_pj_authority_source`; no approved onboarding records who acts for the company at Pomelo (its legal representative), and nothing on the company's side unblocks it now (refusal `card_issuer_unavailable`, with the programs that are available). `verify_company_representative`: actor `company_signatory`; pending, reason `representative_onboarding_required`, until that recorded representative completes their own onboarding (their CPF) in the dashboard; done once a member is the representative. + * @enum {string} + */ + kind: "environment" | "integration_connected" | "issuer_capability_pending" | "verify_company_representative" | "bind_key_to_mandate" | "complete_holder_profile" | "issuer_kyc" | "accept_terms" | "authorize_automated_issuance"; /** @enum {string} */ status: "done" | "pending" | "blocked" | "not_applicable"; /** @enum {string} */ @@ -12656,7 +12699,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -12671,12 +12714,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; } | { /** * @description A person must act; nothing was sent to the issuer for this request since the last answer. @@ -12702,8 +12753,11 @@ export interface paths { pending_action: { /** @description Stable for the same issue request and kind. */ id: string; - /** @enum {string} */ - kind: "issuer_kyc" | "accept_terms" | "authorize_automated_issuance" | "bind_key_to_mandate" | "complete_holder_profile"; + /** + * @description `verify_company_representative` (pomelo_brl for a company, actor `company_signatory`): the legal representative of the company's approved onboarding completes their own onboarding (their CPF) in the dashboard, then the SAME request resumes. + * @enum {string} + */ + kind: "issuer_kyc" | "accept_terms" | "authorize_automated_issuance" | "bind_key_to_mandate" | "complete_holder_profile" | "verify_company_representative"; /** * @description `holder` acts for themselves (personal terms, KYC); `company_signatory` signs for the company (PJ) or the holder (PF) authorizes issuance; `org_admin` configures. * @enum {string} @@ -12766,7 +12820,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -12781,12 +12835,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; }; /** @description The automated issuance authorization in force when the issuer was called. */ authorization_id: string | null; @@ -12854,7 +12916,7 @@ export interface paths { put?: never; /** * Freeze a card - * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`. + * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo; `rain_usd` at Rain (freeze = locked, reversible; unfreeze = active; cancel = canceled, PERMANENT; Rain's own card update stays the source of truth, and Rain may lock a card on its own). Cancel cannot be undone on either issuer. Both answer the card view. Requires `cards:issue`. */ post: { parameters: { @@ -12889,7 +12951,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -12904,12 +12966,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; }; }; }; @@ -13013,7 +13083,7 @@ export interface paths { }; }; }; - /** @description The program does not support it, or the project is Live. */ + /** @description The project is Live, or (no program today) the program does not support the action. */ 422: { headers: { [name: string]: unknown; @@ -13033,7 +13103,7 @@ export interface paths { }; }; }; - /** @description The issuer did not apply the change; the card is as it was. */ + /** @description `card_control_failed`: the issuer did not apply the change, the card is as it was. `card_control_uncertain`: the issuer may or may not have applied it; read the card again. */ 502: { headers: { [name: string]: unknown; @@ -13042,7 +13112,7 @@ export interface paths { "application/json": { error: { /** @enum {string} */ - code: "card_control_failed"; + code: "card_control_failed" | "card_control_uncertain"; message: string; details?: { [key: string]: unknown; @@ -13053,7 +13123,7 @@ export interface paths { }; }; }; - /** @description The issuer's credentials could not be read. */ + /** @description The issuer's credentials could not be read, or its lane is off; nothing was sent. */ 503: { headers: { [name: string]: unknown; @@ -13062,7 +13132,7 @@ export interface paths { "application/json": { error: { /** @enum {string} */ - code: "vault_unavailable"; + code: "vault_unavailable" | "card_control_failed"; message: string; details?: { [key: string]: unknown; @@ -13092,7 +13162,7 @@ export interface paths { put?: never; /** * Unfreeze a card - * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`. + * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo; `rain_usd` at Rain (freeze = locked, reversible; unfreeze = active; cancel = canceled, PERMANENT; Rain's own card update stays the source of truth, and Rain may lock a card on its own). Cancel cannot be undone on either issuer. Both answer the card view. Requires `cards:issue`. */ post: { parameters: { @@ -13127,7 +13197,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -13142,12 +13212,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; }; }; }; @@ -13251,7 +13329,7 @@ export interface paths { }; }; }; - /** @description The program does not support it, or the project is Live. */ + /** @description The project is Live, or (no program today) the program does not support the action. */ 422: { headers: { [name: string]: unknown; @@ -13271,7 +13349,7 @@ export interface paths { }; }; }; - /** @description The issuer did not apply the change; the card is as it was. */ + /** @description `card_control_failed`: the issuer did not apply the change, the card is as it was. `card_control_uncertain`: the issuer may or may not have applied it; read the card again. */ 502: { headers: { [name: string]: unknown; @@ -13280,7 +13358,7 @@ export interface paths { "application/json": { error: { /** @enum {string} */ - code: "card_control_failed"; + code: "card_control_failed" | "card_control_uncertain"; message: string; details?: { [key: string]: unknown; @@ -13291,7 +13369,7 @@ export interface paths { }; }; }; - /** @description The issuer's credentials could not be read. */ + /** @description The issuer's credentials could not be read, or its lane is off; nothing was sent. */ 503: { headers: { [name: string]: unknown; @@ -13300,7 +13378,7 @@ export interface paths { "application/json": { error: { /** @enum {string} */ - code: "vault_unavailable"; + code: "vault_unavailable" | "card_control_failed"; message: string; details?: { [key: string]: unknown; @@ -13330,7 +13408,7 @@ export interface paths { put?: never; /** * Cancel a card - * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo and answers the card view; `rain_usd` has no lock/cancel call and answers `422 card_action_unsupported`. Requires `cards:issue`. + * @description Routed by the card's recorded issuer. `pomelo_brl` applies it at Pomelo; `rain_usd` at Rain (freeze = locked, reversible; unfreeze = active; cancel = canceled, PERMANENT; Rain's own card update stays the source of truth, and Rain may lock a card on its own). Cancel cannot be undone on either issuer. Both answer the card view. Requires `cards:issue`. */ post: { parameters: { @@ -13365,7 +13443,7 @@ export interface paths { /** @enum {string} */ program: "pomelo_brl" | "rain_usd"; /** - * @description The CARD currency. A Rain card's funding (USDC) is in `funding`, never here. + * @description The CARD currency. What a Rain card spends is in `funding` (the account's BRL wallet), never here. * @enum {string} */ currency: "BRL" | "USD"; @@ -13380,12 +13458,20 @@ export interface paths { consumer_id: string | null; /** Format: date-time */ created_at: string; - /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain: none. */ + /** @description What the program supports AND the card's state allows. Pomelo active: freeze, cancel; blocked: unfreeze, cancel; canceled: none. Rain active: freeze, cancel; blocked (Rain locked): unfreeze, cancel; not_activated: cancel; canceled: none. */ available_actions: ("freeze" | "unfreeze" | "cancel")[]; + /** @description Rain cards: what the card spends, the account's CodeSpar BRL wallet (the consumer's for a PF holder, the project's account wallet for a PJ), priced in BRL at authorization. Never the settlement asset. */ funding?: { /** @enum {string} */ - asset: "USDC"; + source: "wallet"; + /** @enum {string} */ + currency: "BRL"; }; + /** + * @description Pomelo cards only: whether the card can be spent through CodeSpar's CDE. `ready`: tokenized. `pending`: the card exists but its tokenization did not complete; retry the same Idempotency-Key (or resume the request): the same card is answered and the tokenization is retried, never a new card. `not_configured`: this deployment has no CDE. Never a token value. + * @enum {string} + */ + payment_token?: "ready" | "pending" | "not_configured"; }; }; }; @@ -13489,7 +13575,7 @@ export interface paths { }; }; }; - /** @description The program does not support it, or the project is Live. */ + /** @description The project is Live, or (no program today) the program does not support the action. */ 422: { headers: { [name: string]: unknown; @@ -13509,7 +13595,7 @@ export interface paths { }; }; }; - /** @description The issuer did not apply the change; the card is as it was. */ + /** @description `card_control_failed`: the issuer did not apply the change, the card is as it was. `card_control_uncertain`: the issuer may or may not have applied it; read the card again. */ 502: { headers: { [name: string]: unknown; @@ -13518,7 +13604,7 @@ export interface paths { "application/json": { error: { /** @enum {string} */ - code: "card_control_failed"; + code: "card_control_failed" | "card_control_uncertain"; message: string; details?: { [key: string]: unknown; @@ -13529,7 +13615,7 @@ export interface paths { }; }; }; - /** @description The issuer's credentials could not be read. */ + /** @description The issuer's credentials could not be read, or its lane is off; nothing was sent. */ 503: { headers: { [name: string]: unknown; @@ -13538,7 +13624,7 @@ export interface paths { "application/json": { error: { /** @enum {string} */ - code: "vault_unavailable"; + code: "vault_unavailable" | "card_control_failed"; message: string; details?: { [key: string]: unknown; diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index c22031ed..68dbf1de 100644 --- a/packages/core/src/generated/operations.ts +++ b/packages/core/src/generated/operations.ts @@ -1,6 +1,6 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 6941cbee6488d220240741e9147cd018de80426af81d3fc02aa32dd757bd2224, fetched 2026-11-19T02:03:13.382Z -// from candidate:ffa66ce789ab6284cab9f831ba73025f0a5afeae/openapi-candidate.json, API 0.3.0). +// Source: openapi-snapshot.json (sha256 3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a, fetched 2026-11-19T03:38:42.091Z +// from candidate:05f75845c051e7e8cba908547a9a2327cd1286e4/openapi-candidate.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) import type { ApiOperationRef } from "../api/types.js"; diff --git a/packages/core/src/testing/index.ts b/packages/core/src/testing/index.ts index e2df6e75..8042c3f2 100644 --- a/packages/core/src/testing/index.ts +++ b/packages/core/src/testing/index.ts @@ -109,7 +109,7 @@ export function fakeSession( status: "active" as const, issuer_status: "ACTIVE", last4: "4242", - network: "MASTERCARD", + network: "mastercard" as const, mandate_id: "mnd_fake", consumer_id: "cons_fake", created_at: new Date(0).toISOString(), diff --git a/packages/python/CHANGELOG.md b/packages/python/CHANGELOG.md index 7e3a7cb8..4a05a65f 100644 --- a/packages/python/CHANGELOG.md +++ b/packages/python/CHANGELOG.md @@ -24,7 +24,10 @@ In parity with `@codespar/sdk` 0.17.0. - `CardView` and `CardList`; - `CardRefusal`: a refusal with a stable code is returned, whether it came in the tool envelope or as a non-2xx answer (`http_status`), and a definitive issuer failure is one. - Only a failure with no code raises `ApiError`. -- `cs.cards.readiness()` reads `GET /v1/cards/readiness`. It returns the typed dicts `CardReadiness`, `CardProgramReadiness` and `CardRequirement`. +- `cs.cards.readiness()` reads `GET /v1/cards/readiness`. +- `CardFunding` / `CardProgramSettlement` are typed exactly. A funding outside the contract raises instead of passing through. +- `CardView.payment_token`. +- `holder_consumer_id` on `CardArgs`. It returns the typed dicts `CardReadiness`, `CardProgramReadiness` and `CardRequirement`. ## 0.16.2 diff --git a/packages/python/src/codespar/__init__.py b/packages/python/src/codespar/__init__.py index 8738b4a8..5a30ab99 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -103,6 +103,7 @@ CardControlAction, CardControlReason, CardCurrency, + CardFunding, CardIssued, CardIssuer, CardList, @@ -113,6 +114,7 @@ CardProcessing, CardProgram, CardProgramAvailability, + CardProgramSettlement, CardRefusal, CardResult, CardSelection, @@ -238,6 +240,7 @@ "CardControlAction", "CardControlReason", "CardCurrency", + "CardFunding", "CardIssued", "CardIssuer", "CardList", @@ -249,6 +252,7 @@ "CardProgram", "CardProgramAvailability", "CardProgramReadiness", + "CardProgramSettlement", "CardReadiness", "CardRefusal", "CardRequirement", diff --git a/packages/python/src/codespar/_async_session.py b/packages/python/src/codespar/_async_session.py index 45d7770f..8261f31d 100644 --- a/packages/python/src/codespar/_async_session.py +++ b/packages/python/src/codespar/_async_session.py @@ -24,6 +24,7 @@ AuthConfig, AuthResult, CardArgs, + CardFunding, CardIssued, CardList, CardPendingAction, @@ -253,6 +254,14 @@ def _parse_card_selection(raw: Any) -> CardSelection | None: ) +def _parse_card_funding(raw: Any) -> CardFunding | None: + if not isinstance(raw, dict): + return None + if raw.get("source") != "wallet" or raw.get("currency") != "BRL": + raise ApiError("card: funding outside the published contract", status=0, body=raw) + return CardFunding() + + def _card_view_fields(raw: dict[str, Any]) -> dict[str, Any]: funding = raw.get("funding") return { @@ -268,7 +277,10 @@ def _card_view_fields(raw: dict[str, Any]) -> dict[str, Any]: "consumer_id": raw.get("consumer_id"), "created_at": raw.get("created_at"), "available_actions": _str_list(raw.get("available_actions")), - "funding": dict(funding) if isinstance(funding, dict) else None, + "funding": _parse_card_funding(funding), + "payment_token": ( + raw.get("payment_token") if isinstance(raw.get("payment_token"), str) else None + ), } @@ -878,6 +890,7 @@ async def card(self, args: CardArgs, *, timeout: float | None = None) -> CardRes "provider", "mandate_id", "consumer_id", + "holder_consumer_id", "idempotency_key", "holder", "card_id", diff --git a/packages/python/src/codespar/cards.py b/packages/python/src/codespar/cards.py index 3de8a620..0d6a5df7 100644 --- a/packages/python/src/codespar/cards.py +++ b/packages/python/src/codespar/cards.py @@ -40,6 +40,10 @@ class CardRequirement(_CardRequirementRequired, total=False): action_url: str reason: str pending_action_id: str + #: complete_holder_profile: exactly the fields still missing. + missing_fields: list[str] + mandate_id: str + bound_api_key_ids: list[str] class CardProgramReadiness(TypedDict): @@ -53,6 +57,8 @@ class CardProgramReadiness(TypedDict): class CardReadiness(TypedDict): """``GET /v1/cards/readiness``.""" + #: ``automated`` (API key / OAuth) or ``person`` (the dashboard). + mode: Literal["automated", "person"] programs: list[CardProgramReadiness] diff --git a/packages/python/src/codespar/types.py b/packages/python/src/codespar/types.py index 34976ee7..bf8ad5c0 100644 --- a/packages/python/src/codespar/types.py +++ b/packages/python/src/codespar/types.py @@ -653,6 +653,9 @@ class CardArgs: mandate_id: str | None = None consumer_id: str | None = None idempotency_key: str | None = None + #: A company's pomelo_brl card only, and required there: the person who + #: will hold the card, as their own consumer. + holder_consumer_id: str | None = None #: Pomelo cardholder identity (pomelo_brl): full_name, email, birthdate, #: document {type, value, issuing_country}, address {...}, phone. Rain refuses it. holder: dict[str, Any] | None = None @@ -669,6 +672,23 @@ class CardSelection: chosen_by: str = "currency" # "provider" | "currency" +@dataclass(slots=True) +class CardFunding: + """What a card spends (rain_usd): the account's CodeSpar BRL wallet, + priced in BRL at authorization. Never the program's settlement asset.""" + + source: Literal["wallet"] = "wallet" + currency: Literal["BRL"] = "BRL" + + +@dataclass(slots=True) +class CardProgramSettlement: + """How CodeSpar settles a program with its issuer (a program fact).""" + + asset: Literal["USDC"] = "USDC" + by: Literal["codespar"] = "codespar" + + @dataclass(slots=True) class CardView: """The card view: get, controls, list items.""" @@ -685,9 +705,10 @@ class CardView: consumer_id: str | None = None created_at: str | None = None available_actions: list[str] = field(default_factory=list) - #: How the card is funded, as the server reports it for its program - #: (the served contract's fields, passed through unchanged). - funding: dict[str, Any] | None = None + #: Rain cards: what the card spends (the account's CodeSpar BRL wallet). + funding: CardFunding | None = None + #: Pomelo cards: CDE tokenization state, "ready" | "pending" | "not_configured". + payment_token: str | None = None @dataclass(slots=True) @@ -777,6 +798,8 @@ class CardProgramAvailability: available: bool | None = None reason: str | None = None operations: list[str] = field(default_factory=list) + funding: CardFunding | None = None + settlement: CardProgramSettlement | None = None @dataclass(slots=True) diff --git a/packages/python/tests/test_card.py b/packages/python/tests/test_card.py index fd40598e..15034a9d 100644 --- a/packages/python/tests/test_card.py +++ b/packages/python/tests/test_card.py @@ -19,6 +19,7 @@ ApiError, AsyncCodeSpar, CardArgs, + CardFunding, CardIssued, CardList, CardPendingHuman, @@ -127,8 +128,8 @@ async def test_issue_dispatches_codespar_card_and_returns_issued(httpx_mock: HTT assert result.card.issuer_status == "notActivated" assert result.card.available_actions == [] assert result.card.network is None - # Passed through as served; the client restates none of its fields. - assert result.card.funding == {"source": "wallet", "currency": "BRL"} + assert result.card.funding == CardFunding(source="wallet", currency="BRL") + assert result.card.payment_token is None assert result.authorization_id == "caia_1" assert result.authorization_active is True assert result.selection is not None @@ -527,3 +528,49 @@ async def test_issue_sends_holder(httpx_mock: HTTPXMock) -> None: ) ) assert _sent(httpx_mock)["input"]["holder"] == holder + + +@pytest.mark.asyncio +async def test_funding_outside_the_contract_is_refused_not_guessed(httpx_mock: HTTPXMock) -> None: + """The old {asset: USDC} shape is not the contract: a parse error, never a silent pass.""" + _mock_session(httpx_mock) + httpx_mock.add_response( + url=EXECUTE, method="POST", json=_envelope({**RAIN_VIEW, "funding": {"asset": "USDC"}}) + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + with pytest.raises(ApiError, match="funding outside the published contract"): + await session.card(CardArgs(action="get", card_id="rcrd_abc")) + + +@pytest.mark.asyncio +async def test_pomelo_payment_token_and_company_holder(httpx_mock: HTTPXMock) -> None: + _mock_session(httpx_mock) + view = { + **RAIN_VIEW, + "id": "icrd_1", + "issuer": "pomelo", + "program": "pomelo_brl", + "currency": "BRL", + "network": "mastercard", + "payment_token": "pending", + "available_actions": ["freeze", "cancel"], + } + del view["funding"] + httpx_mock.add_response(url=EXECUTE, method="POST", json=_envelope(_issued(view))) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + session = await cs.create("consumer_123", servers=[]) + result = await session.card( + CardArgs( + action="issue", + currency="BRL", + mandate_id="m", + consumer_id="cons_company", + holder_consumer_id="cons_person", + idempotency_key="k", + ) + ) + assert isinstance(result, CardIssued) + assert result.card.payment_token == "pending" + assert result.card.funding is None + assert _sent(httpx_mock)["input"]["holder_consumer_id"] == "cons_person" diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index e1e97490..77fb36c6 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -30,7 +30,16 @@ - `processing` / `uncertain`: `retry_after_seconds`, plus `note` and `issuer_code` on uncertain; - `refused`. - A definitive issuer failure is a refusal, never a state. A result with no `state` is a card view or a list. -- `CardReadiness` / `CardProgramReadiness` / `CardRequirement`, for `GET /v1/cards/readiness`. +- `CardReadiness` / `CardProgramReadiness` / `CardRequirement`, for `GET /v1/cards/readiness`: + - `mode`; + - `missing_fields`, `mandate_id` and `bound_api_key_ids` on a requirement; + - the kinds `issuer_capability_pending` and `verify_company_representative`. +- `CardFunding` (`{ source: "wallet", currency: "BRL" }`: what a rain_usd card spends) and `CardProgramSettlement` (`{ asset: "USDC", by: "codespar" }`: a program fact, never what a card spends), both on `CardProgramAvailability`. +- `CardView.payment_token` (`ready | pending | not_configured`, Pomelo). +- `CardView.network` (`visa | mastercard | null`). +- `holder_consumer_id` on issue (a company's pomelo_brl card). +- The refusal codes `card_control_failed` and `card_control_uncertain`. +- Freeze, unfreeze and cancel on both programs. - The scenario manifest moves to 0.12.0. ## 0.11.7 — 2026-10-30 diff --git a/packages/types/src/meta-tool-definitions.test.ts b/packages/types/src/meta-tool-definitions.test.ts index 6cff06e8..39d6fb2c 100644 --- a/packages/types/src/meta-tool-definitions.test.ts +++ b/packages/types/src/meta-tool-definitions.test.ts @@ -552,6 +552,7 @@ describe("wire-shape arg unions match the published definition vocabularies (ent "provider", "mandate_id", "consumer_id", + "holder_consumer_id", "idempotency_key", "holder", "card_id", diff --git a/packages/types/src/meta-tool-definitions.ts b/packages/types/src/meta-tool-definitions.ts index 228e3a1c..1374ec18 100644 --- a/packages/types/src/meta-tool-definitions.ts +++ b/packages/types/src/meta-tool-definitions.ts @@ -470,6 +470,7 @@ const CARD_INPUT: MetaToolInputSchema = { provider: { type: "string", description: "Card issuer, pomelo | rain (action=issue, optional). Omit it and the currency picks the program.", enum: ["pomelo", "rain"] }, mandate_id: { type: "string", description: "The mandate the card spends under (action=issue, required; action=list filter). Its currency must equal the card currency; one card per mandate." }, consumer_id: { type: "string", description: "The card holder, a consumer of this project (action=issue, required; action=list filter)." }, + holder_consumer_id: { type: "string", description: "A company's pomelo_brl card only, and required there (action=issue): the person who will hold the card, as their own consumer." }, idempotency_key: { type: "string", description: "Required on action=issue. A retry with the same key resumes the same request and never issues a second card; the same key with a different body is refused with idempotency_key_conflict." }, holder: { type: "object", @@ -622,7 +623,7 @@ export const LEDGER_DEFINITION: SharedMetaToolDefinition = { export const CARD_DEFINITION: SharedMetaToolDefinition = { name: "codespar_card", description: - "Issue, read, and control payment cards for AI agents or end-users, one contract across issuers: BRL cards on the pomelo_brl program (Pomelo), USD cards on the rain_usd program (Rain). action=issue issues a card for a holder (consumer_id) under a mandate (mandate_id) in a currency (currency); provider is optional, and when omitted the currency picks the program. idempotency_key is required on issue. The answer always names issuer, program and selection. A requirement only a person can satisfy (issuer KYC, terms, the authorization for automated issuance, binding the key to the mandate) answers state=pending_human with a pending_action { id, kind, actor, url } to hand to that person (actor holder, company_signatory or org_admin), never something to accept on their behalf; retry with the same idempotency_key once it is done. state=processing means the issuer has not answered yet, and state=uncertain means the card MAY exist at the issuer: both are resolved on the SAME idempotency_key, never by a new key, which would be a second card. A definitive refusal by the issuer is an error (card_issue_refused, or card_issue_request_failed with failure_code on a later call with the same key), not a state. action=get reads one card by card_id; action=list lists cards (filters issuer, mandate_id, consumer_id); action=freeze / unfreeze / cancel control a card, and each card's available_actions says which of them its program and state allow (rain cards allow none here). This is the agent-spend-card primitive: it creates SPEND INSTRUMENTS, distinct from codespar_pay/charge which move money.", + "Issue, read, and control payment cards for AI agents or end-users through CodeSpar's card programs: pomelo_brl (BRL cards, Pomelo) and rain_usd (USD cards, Rain; a rain_usd card spends the account's CodeSpar BRL wallet, priced in BRL at authorization). action=issue issues a card for a holder (consumer_id) under a mandate (mandate_id) in a currency (currency); provider is optional, and when omitted the currency picks the program. idempotency_key is required on issue. The answer always names issuer, program and selection. A requirement only a person can satisfy (issuer KYC, terms, the authorization for automated issuance, binding the key to the mandate, the holder profile) answers state=pending_human with a pending_action { id, kind, actor, url } to hand to that person (actor holder, company_signatory or org_admin), never something to accept on their behalf; retry with the same idempotency_key once it is done. state=processing means the issuer has not answered yet, and state=uncertain means the card MAY exist at the issuer: both are resolved on the SAME idempotency_key, never by a new key, which would be a second card. A definitive refusal by the issuer is an error (card_issue_refused, or card_issue_request_failed with failure_code on a later call with the same key), not a state. action=get reads one card by card_id; action=list lists cards (filters issuer, mandate_id, consumer_id); action=freeze / unfreeze / cancel control a card on both programs (cancel is permanent), and each card's available_actions says which of them its state allows. This is the agent-spend-card primitive: it creates SPEND INSTRUMENTS, distinct from codespar_pay/charge which move money.", input_schema: CARD_INPUT, contract: contractOf(CARD_INPUT), }; diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index b1e8fd4a..0e7658a5 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -831,6 +831,8 @@ export interface CardIssueArgs { provider?: CardIssuer; mandate_id: string; consumer_id: string; + /** A company's pomelo_brl card only, and required there: the person who will hold the card, as their own consumer. */ + holder_consumer_id?: string; idempotency_key: string; /** Pomelo cardholder identity (pomelo_brl). Without it the issue answers pending_human/complete_holder_profile. Rain refuses it. */ holder?: CardHolder; @@ -876,8 +878,10 @@ export interface CardListArgs { /** * action=freeze | unfreeze | cancel, routed by the card's recorded issuer. - * An action the program does not support (any control on a Rain card) is - * refused with `card_action_unsupported`. + * Both programs support all three (cancel is permanent); an action the + * card's state does not allow is refused with `card_action_unsupported` + * (see `available_actions`). An issuer answer that may or may not have + * applied the change is `card_control_uncertain`: read the card again. */ export interface CardControlArgs { action: CardControlAction; @@ -894,11 +898,27 @@ export interface CardSelection { } /** - * How a card is funded, as the server reports it for its program. Kept - * open here: its fields are the served contract's (see the generated - * OpenAPI types), and nothing in this file restates them. + * What a card spends (rain_usd today): the account's CodeSpar BRL wallet, + * priced in BRL at authorization. Never the program's settlement asset. + * Pinned to the served schema by `card-wire.test.ts` in `@codespar/sdk`. */ -export type CardFunding = Record; +export interface CardFunding { + source: "wallet"; + currency: "BRL"; +} + +/** + * How CodeSpar settles a program with its issuer, from its own treasury + * (`GET /v1/cards/programs`). A program fact, never what a card or its + * holder spends. + */ +export interface CardProgramSettlement { + asset: "USDC"; + by: "codespar"; +} + +/** Pomelo cards: whether the card can be spent through CodeSpar's CDE. `pending` resolves on the same Idempotency-Key, never a new card. */ +export type CardPaymentToken = "ready" | "pending" | "not_configured"; /** The card view (REST and codespar_card): get, controls, list items, an issued card. */ export interface CardView { @@ -911,13 +931,16 @@ export interface CardView { status: CardStatus; issuer_status: string | null; last4: string | null; - network: string | null; + network: "visa" | "mastercard" | null; mandate_id: string | null; consumer_id: string | null; created_at: string; - /** Only what the program supports AND the card state allows (rain: none). */ + /** Only what the program supports AND the card state allows (both programs: freeze, unfreeze, cancel; cancel is permanent). */ available_actions: CardControlAction[]; + /** Rain cards: what the card spends. */ funding?: CardFunding; + /** Pomelo cards: CDE tokenization state. Never a token value. */ + payment_token?: CardPaymentToken; } /** action=issue, card issued (first call or an idempotent replay). The card view is nested in `card`. */ @@ -1008,7 +1031,8 @@ export type CardUnavailableReason = | "live_blocked" | "account_not_eligible" | "issuer_disabled" - | "issuer_not_supported"; + | "issuer_not_supported" + | "pomelo_pj_authority_source"; export type CardRefusalCode = | "card_issuer_unavailable" @@ -1019,6 +1043,8 @@ export type CardRefusalCode = | "card_holder_not_eligible" | "card_issue_refused" | "card_issue_request_failed" + | "card_control_failed" + | "card_control_uncertain" | "idempotency_key_conflict" | (string & {}); @@ -1030,6 +1056,10 @@ export interface CardProgramAvailability { available?: boolean; reason?: CardUnavailableReason; operations?: CardAction[]; + /** rain_usd: what its cards spend. */ + funding?: CardFunding; + /** rain_usd: how CodeSpar settles the program with the issuer. */ + settlement?: CardProgramSettlement; } /** @@ -1073,7 +1103,12 @@ export type CardResult = CardIssueResult | CardView | CardList; /* ── GET /v1/cards/readiness ─────────────────────────────────── */ /** The pending-action kinds plus the two admin/environment checks. */ -export type CardRequirementKind = CardPendingActionKind | "integration_connected" | "environment"; +export type CardRequirementKind = + | CardPendingActionKind + | "integration_connected" + | "environment" + | "issuer_capability_pending" + | "verify_company_representative"; export type CardRequirementStatus = "done" | "pending" | "blocked" | "not_applicable"; @@ -1085,6 +1120,10 @@ export interface CardRequirement { action_url?: string; reason?: string; pending_action_id?: string; + /** complete_holder_profile: exactly the fields still missing. */ + missing_fields?: string[]; + mandate_id?: string; + bound_api_key_ids?: string[]; } export interface CardProgramReadiness { @@ -1097,6 +1136,8 @@ export interface CardProgramReadiness { /** `GET /v1/cards/readiness` (read-only; person session or API key). */ export interface CardReadiness { + /** `automated`: an API key / OAuth issue. `person`: the competent person in the dashboard. */ + mode: "automated" | "person"; programs: CardProgramReadiness[]; } From 0191503a55b05601743c39b87764bb550356bd51 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Thu, 19 Nov 2026 00:48:42 -0300 Subject: [PATCH 11/12] test(cards): readiness fixtures carry mode Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/__tests__/card-command.test.ts | 2 +- packages/core/src/__tests__/card.test.ts | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/cli/src/__tests__/card-command.test.ts b/packages/cli/src/__tests__/card-command.test.ts index 9013d8df..0d10f5a0 100644 --- a/packages/cli/src/__tests__/card-command.test.ts +++ b/packages/cli/src/__tests__/card-command.test.ts @@ -212,7 +212,7 @@ describe("codespar card", () => { describe("codespar card readiness", () => { it("GETs /v1/cards/readiness and prints the document in --json", async () => { - const doc = { programs: [{ program: "pomelo_brl", issuer: "pomelo", currency: "BRL", ready: true, requirements: [] }] }; + const doc = { mode: "automated", programs: [{ program: "pomelo_brl", issuer: "pomelo", currency: "BRL", ready: true, requirements: [] }] }; const urls: string[] = []; vi.spyOn(globalThis, "fetch").mockImplementation((input: unknown) => { urls.push(String(input)); diff --git a/packages/core/src/__tests__/card.test.ts b/packages/core/src/__tests__/card.test.ts index 799a68d9..ca8908a4 100644 --- a/packages/core/src/__tests__/card.test.ts +++ b/packages/core/src/__tests__/card.test.ts @@ -320,6 +320,7 @@ it("session.issue is gone: no alias, no shim (contract §10.1)", async () => { describe("cs.cards.readiness", () => { it("GETs /v1/cards/readiness with the client's credentials and returns the checklist", async () => { const body: CardReadiness = { + mode: "automated", programs: [ { program: "rain_usd", From 303dd8f4c737145d5751f623a136bfad4916368d Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Thu, 19 Nov 2026 00:56:06 -0300 Subject: [PATCH 12/12] chore(sdk): snapshot source names the final enterprise candidate f6fd2931f The OpenAPI document is byte-identical to 05f75845c (same sha256 3dfc154cf3a5 sealed in the snapshot); only source/fetched_at change in the snapshot and the two generated headers. Co-Authored-By: Claude Opus 5.5 --- packages/core/openapi-snapshot.json | 4 ++-- packages/core/src/generated/openapi.ts | 4 ++-- packages/core/src/generated/operations.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index 530b8a69..ad9e450e 100644 --- a/packages/core/openapi-snapshot.json +++ b/packages/core/openapi-snapshot.json @@ -1,7 +1,7 @@ { "snapshot": { - "source": "candidate:05f75845c051e7e8cba908547a9a2327cd1286e4/openapi-candidate.json", - "fetched_at": "2026-11-19T03:38:42.091Z", + "source": "candidate:f6fd2931f208115d26892f24b9f5562547b32bcb/openapi-candidate.json", + "fetched_at": "2026-11-19T03:55:57.847Z", "sha256": "3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a", "etag": null, "last_modified": null, diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index b834bdba..4d4d63c2 100644 --- a/packages/core/src/generated/openapi.ts +++ b/packages/core/src/generated/openapi.ts @@ -1,6 +1,6 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a, fetched 2026-11-19T03:38:42.091Z -// from candidate:05f75845c051e7e8cba908547a9a2327cd1286e4/openapi-candidate.json, API 0.3.0). +// Source: openapi-snapshot.json (sha256 3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a, fetched 2026-11-19T03:55:57.847Z +// from candidate:f6fd2931f208115d26892f24b9f5562547b32bcb/openapi-candidate.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { "/.well-known/oauth-protected-resource": { diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index 68dbf1de..07d81bdf 100644 --- a/packages/core/src/generated/operations.ts +++ b/packages/core/src/generated/operations.ts @@ -1,6 +1,6 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a, fetched 2026-11-19T03:38:42.091Z -// from candidate:05f75845c051e7e8cba908547a9a2327cd1286e4/openapi-candidate.json, API 0.3.0). +// Source: openapi-snapshot.json (sha256 3dfc154cf3a516dad74db03ccc4ff869ef99af8376944b6f37ab8aebd4d68c5a, fetched 2026-11-19T03:55:57.847Z +// from candidate:f6fd2931f208115d26892f24b9f5562547b32bcb/openapi-candidate.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) import type { ApiOperationRef } from "../api/types.js";