diff --git a/package-lock.json b/package-lock.json index 5f1759f..7091db3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3022,10 +3022,10 @@ }, "packages/cli": { "name": "@codespar/cli", - "version": "0.22.7", + "version": "0.22.8", "license": "MIT", "dependencies": { - "@codespar/sdk": "^0.16.26", + "@codespar/sdk": "^0.16.31", "commander": "^13.0.0" }, "bin": { @@ -3041,7 +3041,7 @@ }, "packages/core": { "name": "@codespar/sdk", - "version": "0.16.30", + "version": "0.16.31", "license": "MIT", "dependencies": { "@codespar/types": "^0.10.1 || ^0.11.0", @@ -3180,7 +3180,7 @@ }, "packages/mcp": { "name": "@codespar/mcp", - "version": "0.5.20", + "version": "0.5.21", "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", @@ -3215,7 +3215,7 @@ }, "packages/types": { "name": "@codespar/types", - "version": "0.11.7", + "version": "0.11.8", "license": "MIT", "devDependencies": { "@types/node": "^25.6.0", diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 7ac5e73..c9a7a30 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,5 +1,17 @@ # @codespar/cli — changelog +## 0.22.8 — 2026-11-17 + +### Added + +- Derived commands `shop create-data-calls`, `shop get-data-calls` and + `shop data-calls-execute` (Shop G3.1). Their exit code is the outcome: 0 + confirmed, 10 pending (the person still runs it), 20 refused by the API + (`person_required` included), 30 failure, 40 uncertain (an effect may have + happened). Every other command keeps exit 1 for any failure. +- Derived command `shop offers-image` (`GET /v1/shop/agent/offers/{id}/image/{n}`, `image/jpeg`): an offer's image from a key's research, through the CodeSpar proxy (Shop v0.7). +- Needs @codespar/sdk ^0.16.31 (the data-call client and `nextActionOfError`). + ## 0.22.7 — 2026-11-11 ### Added diff --git a/packages/cli/package.json b/packages/cli/package.json index 388a149..6faf9ec 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/cli", - "version": "0.22.7", + "version": "0.22.8", "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.16.31", "commander": "^13.0.0" }, "devDependencies": { diff --git a/packages/cli/src/__tests__/exit-codes.test.ts b/packages/cli/src/__tests__/exit-codes.test.ts new file mode 100644 index 0000000..46d6208 --- /dev/null +++ b/packages/cli/src/__tests__/exit-codes.test.ts @@ -0,0 +1,72 @@ +/** + * Exit codes of the outcome commands (Shop G3.1 data calls): 0 confirmed, + * 10 pending, 20 refused, 30 failure, 40 uncertain. Only an opted-in command + * uses them; every other command keeps exit 1 for any failure. + */ +import { afterEach, describe, expect, it } from "vitest"; +import { EXIT, exitCodeForDataCall, exitCodeForFailure, outcomeExitCodesOn, pendingOnPerson, resetExitPolicy, useOutcomeExitCodes } from "../exit-codes.js"; + +afterEach(() => resetExitPolicy()); + +const base = { + proposal_id: "prp_AbCdEfGhIjKlMnOp", + run_state: "ready", + awaiting: null, + offer: {} as never, + quotation: { state: "valid", total_minor: 50, observed_at: "", valid_until: "" }, + authorization: { state: "needed", amount_max_minor: 50 }, + commitment: { state: "not_started" }, + payment: { state: "none" }, + confirmation: { state: "none" }, + actions: { execute: true, cancel: true, requote: false }, +} as const; +const view = (over: Record) => ({ ...base, ...over }) as never; + +describe("exit codes of a data call's answer", () => { + it("each outcome has its code, read from the four states apart", () => { + expect(exitCodeForDataCall(view({ confirmation: { state: "confirmed", result_ref: "tdr_1" } }))).toBe(EXIT.ok); + expect(exitCodeForDataCall(view({}))).toBe(EXIT.pending); + expect(exitCodeForDataCall(view({ error: { code: "commitment_terms_changed" } }))).toBe(EXIT.refused); + expect(exitCodeForDataCall(view({ commitment: { state: "failed" }, confirmation: { state: "failed" } }))).toBe(EXIT.failed); + expect(exitCodeForDataCall(view({ commitment: { state: "uncertain" }, payment: { state: "debited" } }))).toBe(EXIT.uncertain); + }); +}); + +describe("exit codes of a failure", () => { + it("off by default: nothing opted in", () => { + expect(outcomeExitCodesOn()).toBe(false); + }); + + it("an API refusal (4xx) is 20; a server error is 30", () => { + useOutcomeExitCodes({ effect: false }); + expect(exitCodeForFailure("api", 403)).toBe(EXIT.refused); + expect(exitCodeForFailure("api", 409)).toBe(EXIT.refused); + expect(exitCodeForFailure("api", 503)).toBe(EXIT.failed); + }); + + it("a timeout or a dropped connection is 30 on a read, 40 on an effect", () => { + useOutcomeExitCodes({ effect: false }); + expect(exitCodeForFailure("timeout")).toBe(EXIT.failed); + expect(exitCodeForFailure("network")).toBe(EXIT.failed); + useOutcomeExitCodes({ effect: true }); + expect(exitCodeForFailure("timeout")).toBe(EXIT.uncertain); + expect(exitCodeForFailure("network")).toBe(EXIT.uncertain); + }); +}); + +describe("a key asked to run a data call: pending on the person, with their protected action", () => { + const refusal = (url?: string) => + Object.assign(new Error("person_required"), { code: "person_required", status: 403, body: { error: { code: "person_required", details: url ? { next_action: { kind: "person_authorization", url } } : {} } } }); + + it("an opted-in command gets the url to print (and exits pending)", () => { + useOutcomeExitCodes({ effect: true }); + expect(pendingOnPerson(refusal("https://codespar.dev/dashboard/shop/data-calls/prp_x"))).toBe("https://codespar.dev/dashboard/shop/data-calls/prp_x"); + }); + + it("without the protected action, or outside an opted-in command, it is a plain refusal", () => { + useOutcomeExitCodes({ effect: true }); + expect(pendingOnPerson(refusal())).toBeNull(); + resetExitPolicy(); + expect(pendingOnPerson(refusal("https://codespar.dev/dashboard/shop/data-calls/prp_x"))).toBeNull(); + }); +}); diff --git a/packages/cli/src/__tests__/resource-commands.test.ts b/packages/cli/src/__tests__/resource-commands.test.ts index 64253cb..8546e7c 100644 --- a/packages/cli/src/__tests__/resource-commands.test.ts +++ b/packages/cli/src/__tests__/resource-commands.test.ts @@ -189,6 +189,10 @@ const PINNED_COMMANDS = [ "shop get-purchases → GET /v1/shop/agent/purchases/{id}", "shop create-research → POST /v1/shop/agent/research", "shop get-research → GET /v1/shop/agent/research/{id}", + "shop create-data-calls → POST /v1/shop/agent/data-calls", + "shop get-data-calls → GET /v1/shop/agent/data-calls/{id}", + "shop data-calls-execute → POST /v1/shop/agent/data-calls/{id}/execute", + "shop offers-image → GET /v1/shop/agent/offers/{id}/image/{n}", "shop capabilities → GET /v1/shop/agent/capabilities", "shop instruments → GET /v1/shop/agent/instruments", "collect list-links → GET /v1/collect/links", diff --git a/packages/cli/src/commands/resource.ts b/packages/cli/src/commands/resource.ts index 22ea89a..3cc1562 100644 --- a/packages/cli/src/commands/resource.ts +++ b/packages/cli/src/commands/resource.ts @@ -3,6 +3,10 @@ import { CliError } from "../config.js"; import { info, json, renderResult } from "../output.js"; import { resolveOptionalInput } from "./meta-input.js"; import type { DerivedCommand } from "../surface.js"; +import { exitCodeForDataCall, useOutcomeExitCodes } from "../exit-codes.js"; + +/** The data-call routes answer an outcome: their commands exit with its code (exit-codes.ts). */ +const DATA_CALLS_PATH = "/v1/shop/agent/data-calls"; export interface ResourceCommandOptions { apiKey: string; @@ -106,6 +110,8 @@ export async function runResourceCommand( ...(timeout !== undefined ? { timeout } : {}), }); + if (command.path.startsWith(DATA_CALLS_PATH)) useOutcomeExitCodes({ effect: command.path.endsWith("/execute") }); + const api = cs.api as unknown as UntypedApi; const result = await api.request(command.method, command.path, { path: bindPathParams(command, opts.args), @@ -113,10 +119,16 @@ export async function runResourceCommand( ...(body !== undefined ? { body } : {}), }); + const dataCall = command.path.startsWith(DATA_CALLS_PATH) ? (result as { data_call?: Parameters[0] } | null)?.data_call : undefined; + if (dataCall) process.exitCode = exitCodeForDataCall(dataCall); + if (opts.json) { json(result ?? null); return; } info(`${command.method.toUpperCase()} ${command.path}`); renderResult(result); + // While a data call waits for the person: the protected action, for them to open (criterion 5). + const next = (result as { next_action?: { url?: unknown } | null } | null)?.next_action; + if (dataCall && next && typeof next.url === "string") info(`A pessoa executa esta consulta em: ${next.url}`); } diff --git a/packages/cli/src/exit-codes.ts b/packages/cli/src/exit-codes.ts new file mode 100644 index 0000000..244ee53 --- /dev/null +++ b/packages/cli/src/exit-codes.ts @@ -0,0 +1,75 @@ +/** + * Exit codes for the commands whose answer is an outcome a script branches + * on (Shop G3.1 data calls first; the store commands of G2.1 reuse them). + * Agreed across the core fronts on 07/11: + * + * 0 ok: the result is confirmed + * 10 pending: the person or a next step is needed (a draft waits to be run) + * 20 refused by the API with a code (person_required, 404, 409, terms changed) + * 30 failure (5xx, or a network error on a READ) + * 40 uncertain: an effect may have happened (sent, outcome not known yet) + * 1 the CLI's own usage or configuration error + * + * Every other command keeps exit 1 for any failure: a command opts in, so + * a script that already branches on 1 never sees its meaning change. + */ +import { dataCallOutcome, nextActionOfError, type DataCall } from "@codespar/sdk"; + +export const EXIT = { ok: 0, pending: 10, refused: 20, failed: 30, uncertain: 40, usage: 1 } as const; + +interface Policy { + /** Whether the running command uses these codes. */ + on: boolean; + /** Whether the command asks for an effect (a timeout there is uncertain, not a failure). */ + effect: boolean; +} + +const policy: Policy = { on: false, effect: false }; + +/** Opt the running command in. `effect`: it may cause something at the provider. */ +export function useOutcomeExitCodes(opts: { effect: boolean }): void { + policy.on = true; + policy.effect = opts.effect; +} + +export function outcomeExitCodesOn(): boolean { + return policy.on; +} + +/** The code of a data call's answer, from its four states. */ +export function exitCodeForDataCall(view: DataCall): number { + switch (dataCallOutcome(view)) { + case "succeeded": + return EXIT.ok; + case "pending": + return EXIT.pending; + case "refused": + return EXIT.refused; + case "failed": + return EXIT.failed; + case "uncertain": + return EXIT.uncertain; + } +} + +/** + * A refusal that hands the person's protected action (criterion 5: a key asked to run a data call): the step is + * pending on the person, not refused. Returns the url to print, or null. + */ +export function pendingOnPerson(err: unknown): string | null { + if (!policy.on || (err as { code?: unknown } | null)?.code !== "person_required") return null; + return nextActionOfError(err)?.url ?? null; +} + +/** The code of a failure of an opted-in command: the API's refusal, a server error, the network or a timeout. */ +export function exitCodeForFailure(kind: "api" | "timeout" | "network", status?: number): number { + if (kind === "api" && status !== undefined && status >= 400 && status < 500) return EXIT.refused; + if ((kind === "timeout" || kind === "network") && policy.effect) return EXIT.uncertain; + return EXIT.failed; +} + +/** For tests: back to the default policy. */ +export function resetExitPolicy(): void { + policy.on = false; + policy.effect = false; +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index a01db25..280be57 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -43,6 +43,7 @@ import { showMetaToolCommand, } from "./commands/meta-tool.js"; import { runResourceCommand } from "./commands/resource.js"; +import { EXIT, exitCodeForFailure, outcomeExitCodesOn, pendingOnPerson } from "./exit-codes.js"; import { payablesBatchCreateCommand, payablesBatchGetCommand, @@ -1011,6 +1012,14 @@ async function main() { // The generated REST client answers with its own error types. Print the // API's message and body verbatim — an exit code plus a stack trace // would hide the one thing the caller needs, which is what the API said. + // A data call a key asked to run: the person's protected action, printed for them; pending, not refused. + const personUrl = err instanceof CodesparApiError ? pendingOnPerson(err) : null; + if (personUrl) { + process.stderr.write(`${c.yellow("…")} A pessoa precisa executar esta consulta: ${personUrl}\n`); + if (hasJsonFlag) json({ pending: { kind: "person_authorization", url: personUrl, code: (err as CodesparApiError).code } }); + else process.stdout.write(`${personUrl}\n`); + process.exit(EXIT.pending); + } if (err instanceof CodesparApiError) { process.stderr.write(`${c.red("✗")} ${err.message}\n`); if (err.body !== undefined && !hasJsonFlag) { @@ -1021,12 +1030,12 @@ async function main() { ...(err.code === undefined ? {} : { code: err.code }), ...(err.body === undefined ? {} : { body: err.body }), }); - process.exit(1); + process.exit(outcomeExitCodesOn() ? exitCodeForFailure(err.status === undefined || err.status === 0 ? "network" : "api", err.status) : 1); } if (err instanceof TimeoutError) { process.stderr.write(`${c.red("✗")} ${err.message}\n`); falhou("timeout", err.message); - process.exit(1); + process.exit(outcomeExitCodesOn() ? exitCodeForFailure("timeout") : 1); } // Unexpected error — show stack so we can debug. process.stderr.write(`${c.red("✗ internal error:")}\n`); diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index f10b4c7..9bff908 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,30 @@ # @codespar/sdk — CHANGELOG +## 0.16.31 — 2026-11-17 + +### Added + +- **Shop G3.1 data calls**: `cs.dataCalls` (and `session.dataCalls`) over + `/v1/shop/agent/data-calls`: `create({ agentId, offerId, idempotencyKey })` + drafts a data call from a `data_service` offer of a research, `get(id)` reads + it with the four states apart (quotation, authorization, commitment, payment, + confirmation), and `execute(id)` surfaces the API's `person_required` (403): + a key never runs a data call, the person does. `dataCallOutcome(view)` reads + one word (`succeeded`, `pending`, `refused`, `failed`, `uncertain`). +- `session.research.create` takes `taskKind` (`data_service` among them) and + `criteria.dataService { params, sku? }`. +- OpenAPI snapshot: the served document of 0.16.30 plus the three data-call + operations and the research body with `task_kind`, from the enterprise + routes of Shop G3.1 (codespar-enterprise #2520). They are served once #2520 + is deployed; until then `spec:check` reports the served document as behind + the snapshot, and this version is not published. +- The rest of the snapshot follows the served document as of 2026-11-17: the + research body's `task_kind` (`product`, `service_plan`, `reservation`), + the `web` source with `sources.origins` and the `reservation` and + `service_plan` criteria (Shop G1, enterprise #2366/#2367); `monthly_minor` + and `monthly_quantity` on the sweeping consents; the Test treasury top-up + described against 20 USDC. + ## 0.16.30 — 2026-11-15 ### Security diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index d1b3ac6..a2b9536 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", + "fetched_at": "2026-11-19T22:56:00.566Z", + "sha256": "1e6a6006fe5e00b10e48e23de7d9c90d61f25fc7fd065bb774f57181382ab426", "etag": null, "last_modified": null, "info": { "title": "CodeSpar AgentGate API", "version": "0.3.0" }, - "paths": 329, - "operations": 390, + "paths": 336, + "operations": 397, "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,6 +18934,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": [ @@ -18748,6 +19325,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": [ @@ -118047,6 +118632,16 @@ "maxLength": 200, "description": "The pedido aberto, as the person said it (e.g. \"fone bluetooth\")." }, + "task_kind": { + "type": "string", + "enum": [ + "product", + "service_plan", + "reservation", + "data_service" + ], + "description": "product (default), service_plan, reservation or data_service (a per-call data service, executed by a data call)." + }, "criteria": { "type": "object", "properties": { @@ -118071,259 +118666,191 @@ "enum": [ "registry", "vtex", - "meli" + "meli", + "web", + "data" ] }, "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": 5, + "description": "Where to look: `registry` (the stores the Shop can buy at), `vtex` and `meli` (comparison only), `web` (the origins named in sources.origins), `data` (the data-service providers, for task_kind data_service). Default: `registry` in Test, `vtex` and `meli` in Live; `data` for a data service." }, "limit": { "type": "integer", "minimum": 1, "maximum": 5, "description": "Offers per source, 1 to 5 (default 5)." - } - }, - "additionalProperties": false - } - }, - "required": [ - "query" - ], - "additionalProperties": false - } - } - } - }, - "responses": { - "201": { - "description": "OK", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "research": { - "type": "object", - "additionalProperties": {}, - "description": "The research as CONTRATO-I2 describes it: offers, recommendation, sources." - } - }, - "required": [ - "research" - ] - } - } - } - }, - "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" + }, + "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." + } }, - "details": { - "type": "object", - "additionalProperties": {} - } + "required": [ + "check_in", + "check_out", + "occupants" + ], + "additionalProperties": false, + "description": "task_kind reservation: check_in, check_out, occupants, location." }, - "required": [ - "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": "The key does not hold `shop:purchases:write`.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { - "type": "string" + "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." + } }, - "message": { - "type": "string" + "required": [ + "licenses", + "period" + ], + "additionalProperties": false, + "description": "task_kind service_plan: licenses and period." + }, + "data_service": { + "type": "object", + "properties": { + "params": { + "type": "object", + "additionalProperties": { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + "description": "The call's params, e.g. { cnpj: \"11222333000181\" }." + }, + "sku": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9-]{0,63}$", + "description": "The provider's SKU, when the person named one." + } }, - "details": { - "type": "object", - "additionalProperties": {} - } + "required": [ + "params" + ], + "additionalProperties": false, + "description": "task_kind data_service: the call's params, and the SKU when the person named one." }, - "required": [ - "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": "No source of the asked groups exists in this environment.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { + "required": { + "type": "array", + "items": { "type": "string", "enum": [ - "research_no_sources" + "free_cancellation", + "breakfast_included", + "invoice", + "refundable", + "location" ] }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } - }, - "required": [ - "code", - "message" - ] + "maxItems": 5, + "description": "Conditions an offer must state to be compared: an offer that does not state one is left out, with the reason." + } }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } + "additionalProperties": false }, - "required": [ - "error", - "request_id" - ] - } - } - } - }, - "503": { - "description": "No source answered, or Shop purchases are off on this deployment.", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "code": { + "sources": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { "type": "string", "enum": [ - "research_no_sources", - "shop_purchases_disabled" + "registry", + "vtex", + "meli", + "web", + "data" ] }, - "message": { - "type": "string" - }, - "details": { - "type": "object", - "additionalProperties": {} - } + "minItems": 1, + "maxItems": 5 }, - "required": [ - "code", - "message" - ] + "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 + } }, - "request_id": { - "type": [ - "string", - "null" - ], - "description": "Echoes the `X-Request-Id` header when the request carried one." - } - }, - "required": [ - "error", - "request_id" - ] - } + "additionalProperties": false + } + }, + "required": [ + "query" + ], + "additionalProperties": false } } } }, - "x-codespar-scope": "shop:purchases:write", - "security": [ - { - "bearerAuth": [ - "shop:purchases:write" - ] - } - ] - } - }, - "/v1/shop/agent/research/{id}": { - "get": { - "summary": "Read a research back", - "description": "Scope `shop:purchases:read`. The research this project's keys ran, with each offer's `stale` computed at the time of the answer.\n\n**What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`.", - "parameters": [ - { - "schema": { - "type": "string", - "description": "The research id (`srr_...`), from `POST /v1/shop/agent/research`." - }, - "required": true, - "description": "The research id (`srr_...`), from `POST /v1/shop/agent/research`.", - "name": "id", - "in": "path" - } - ], "responses": { - "200": { + "201": { "description": "OK", "content": { "application/json": { @@ -118343,8 +118870,8 @@ } } }, - "403": { - "description": "The key does not hold `shop:purchases:read`.", + "400": { + "description": "The body did not match the schema.", "content": { "application/json": { "schema": { @@ -118354,7 +118881,1999 @@ "type": "object", "properties": { "code": { - "type": "string" + "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", + "request_id" + ] + } + } + } + }, + "403": { + "description": "The key does not hold `shop:purchases:write`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "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" + ] + } + } + } + }, + "409": { + "description": "No source of the asked groups exists in this environment.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "research_no_sources" + ] + }, + "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 source answered, or Shop purchases are off on this deployment.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "research_no_sources", + "shop_purchases_disabled" + ] + }, + "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": "shop:purchases:write", + "security": [ + { + "bearerAuth": [ + "shop:purchases:write" + ] + } + ] + } + }, + "/v1/shop/agent/research/{id}": { + "get": { + "summary": "Read a research back", + "description": "Scope `shop:purchases:read`. The research this project's keys ran, with each offer's `stale` computed at the time of the answer.\n\n**What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The research id (`srr_...`), from `POST /v1/shop/agent/research`." + }, + "required": true, + "description": "The research id (`srr_...`), from `POST /v1/shop/agent/research`.", + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "research": { + "type": "object", + "additionalProperties": {}, + "description": "The research as CONTRATO-I2 describes it: offers, recommendation, sources." + } + }, + "required": [ + "research" + ] + } + } + } + }, + "403": { + "description": "The key does not hold `shop:purchases:read`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "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": "Not Found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "not_found" + ] + } + }, + "required": [ + "error" + ] + } + } + } + } + }, + "x-codespar-scope": "shop:purchases:read", + "security": [ + { + "bearerAuth": [ + "shop:purchases:read" + ] + } + ] + } + }, + "/v1/shop/agent/data-calls": { + "post": { + "summary": "Draft a data call from a data_service offer (never run)", + "description": "Scope `shop:purchases:write`. Shop G3.1: `offer_id` names a `data_service` offer of this key's research (`POST /v1/shop/agent/research` with `task_kind: \"data_service\"`). The provider quotes the call again and the call is drafted at those terms under the agent's mandate; nothing is reserved or sent. The answer shows the four states apart: quotation, authorization, commitment (the call), payment (Wallet) and the provider's confirmation. The same `agent_id` and `idempotency_key` answer the same draft (`idempotent_replay: true`). Running it is the person's authorization: a key never runs it. While it waits for the person, `next_action` is the protected action to hand them: `{ kind: \"person_authorization\", url }`, the call's card on the dashboard behind their sign-in (only the call's and the project's ids are in the url). Test projects only.\n\n**What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`.", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "agent_id": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "offer_id": { + "type": "string", + "pattern": "^sof_[A-Za-z0-9_-]{16}$", + "description": "A data_service offer of this key's research (`POST /v1/shop/agent/research`, task_kind data_service)." + }, + "idempotency_key": { + "type": "string", + "pattern": "^[A-Za-z0-9_.:-]{8,128}$" + } + }, + "required": [ + "agent_id", + "offer_id", + "idempotency_key" + ], + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data_call": { + "type": "object", + "properties": { + "proposal_id": { + "type": "string", + "description": "The data call's proposal id (`prp_...`)." + }, + "run_state": { + "type": "string", + "enum": [ + "ready", + "awaiting_user", + "running", + "interrupted", + "completed", + "cancelled" + ] + }, + "awaiting": { + "type": [ + "object", + "null" + ], + "properties": { + "reason": { + "type": "string" + }, + "cause": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "reason", + "cause" + ] + }, + "offer": { + "type": "object", + "properties": { + "offer_id": { + "type": "string" + }, + "offer_kind": { + "type": "string", + "enum": [ + "data_service" + ] + }, + "merchant_name": { + "type": "string" + }, + "title": { + "type": "string" + }, + "attributes": { + "type": "object", + "properties": { + "coverage": { + "type": "string" + }, + "refresh": { + "type": "string" + }, + "license": { + "type": "string" + }, + "unit": { + "type": "string", + "enum": [ + "call" + ] + }, + "params": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "offer_version": { + "type": "integer" + }, + "terms_hash": { + "type": "string" + } + }, + "required": [ + "coverage", + "refresh", + "license", + "unit", + "params", + "offer_version", + "terms_hash" + ] + }, + "cost_lines": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "call" + ] + }, + "label": { + "type": "string" + }, + "unit_minor": { + "type": "integer" + }, + "quantity": { + "type": "number", + "enum": [ + 1 + ] + }, + "amount_minor": { + "type": "integer" + } + }, + "required": [ + "kind", + "label", + "unit_minor", + "quantity", + "amount_minor" + ] + } + }, + "total_minor": { + "type": "integer" + }, + "currency": { + "type": "string", + "enum": [ + "BRL" + ] + }, + "observed_at": { + "type": "string" + }, + "valid_until": { + "type": "string" + }, + "source": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "data_catalog" + ] + } + }, + "required": [ + "kind" + ] + } + }, + "required": [ + "offer_id", + "offer_kind", + "merchant_name", + "title", + "attributes", + "cost_lines", + "total_minor", + "currency", + "observed_at", + "valid_until", + "source" + ] + }, + "quotation": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "valid", + "stale", + "changed" + ] + }, + "total_minor": { + "type": "integer" + }, + "previous_total_minor": { + "type": "integer" + }, + "observed_at": { + "type": "string" + }, + "valid_until": { + "type": "string" + } + }, + "required": [ + "state", + "total_minor", + "observed_at", + "valid_until" + ] + }, + "authorization": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "needed", + "awaiting_approval", + "authorized", + "refused", + "expired" + ] + }, + "amount_max_minor": { + "type": "integer" + }, + "approval_id": { + "type": "string" + }, + "expires_at": { + "type": "string" + } + }, + "required": [ + "state", + "amount_max_minor" + ] + }, + "commitment": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "not_started", + "claimed", + "dispatching", + "settled", + "uncertain", + "failed", + "cancelled" + ], + "description": "The call at the provider. `uncertain`: sent and not known yet; the read reconciles it by lookup, never by a resend." + }, + "attempt_id": { + "type": "string" + }, + "call_id": { + "type": "string" + }, + "at": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "payment": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "none", + "held", + "debited", + "released" + ], + "description": "The Wallet: the ceiling held, then the observed amount debited and the rest released." + }, + "held_minor": { + "type": "integer" + }, + "debited_minor": { + "type": "integer" + }, + "released_minor": { + "type": "integer" + }, + "receipt_id": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "confirmation": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "none", + "pending", + "confirmed", + "failed" + ], + "description": "The provider's result: `confirmed` only with its call id and result ref." + }, + "at": { + "type": "string" + }, + "source": { + "type": "string" + }, + "result_ref": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "commitment_terms_changed, data_call_refused, a mandate's or the Wallet's code: an unknown one is shown as a neutral text with the code." + }, + "detail": { + "type": "string" + } + }, + "required": [ + "code" + ] + }, + "actions": { + "type": "object", + "properties": { + "execute": { + "type": "boolean" + }, + "cancel": { + "type": "boolean" + }, + "requote": { + "type": "boolean" + } + }, + "required": [ + "execute", + "cancel", + "requote" + ] + } + }, + "required": [ + "proposal_id", + "run_state", + "awaiting", + "offer", + "quotation", + "authorization", + "commitment", + "payment", + "confirmation", + "actions" + ] + }, + "next_action": { + "type": [ + "object", + "null" + ], + "properties": { + "kind": { + "type": "string", + "enum": [ + "person_authorization" + ] + }, + "url": { + "type": "string", + "description": "The call's card on the dashboard, behind the person's sign-in; only the call's and the project's ids are in it." + }, + "proposal_id": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "kind", + "url", + "proposal_id", + "description" + ] + }, + "idempotent_replay": { + "type": "boolean" + } + }, + "required": [ + "data_call", + "next_action", + "idempotent_replay" + ] + } + } + } + }, + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data_call": { + "type": "object", + "properties": { + "proposal_id": { + "type": "string", + "description": "The data call's proposal id (`prp_...`)." + }, + "run_state": { + "type": "string", + "enum": [ + "ready", + "awaiting_user", + "running", + "interrupted", + "completed", + "cancelled" + ] + }, + "awaiting": { + "type": [ + "object", + "null" + ], + "properties": { + "reason": { + "type": "string" + }, + "cause": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "reason", + "cause" + ] + }, + "offer": { + "type": "object", + "properties": { + "offer_id": { + "type": "string" + }, + "offer_kind": { + "type": "string", + "enum": [ + "data_service" + ] + }, + "merchant_name": { + "type": "string" + }, + "title": { + "type": "string" + }, + "attributes": { + "type": "object", + "properties": { + "coverage": { + "type": "string" + }, + "refresh": { + "type": "string" + }, + "license": { + "type": "string" + }, + "unit": { + "type": "string", + "enum": [ + "call" + ] + }, + "params": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "offer_version": { + "type": "integer" + }, + "terms_hash": { + "type": "string" + } + }, + "required": [ + "coverage", + "refresh", + "license", + "unit", + "params", + "offer_version", + "terms_hash" + ] + }, + "cost_lines": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "call" + ] + }, + "label": { + "type": "string" + }, + "unit_minor": { + "type": "integer" + }, + "quantity": { + "type": "number", + "enum": [ + 1 + ] + }, + "amount_minor": { + "type": "integer" + } + }, + "required": [ + "kind", + "label", + "unit_minor", + "quantity", + "amount_minor" + ] + } + }, + "total_minor": { + "type": "integer" + }, + "currency": { + "type": "string", + "enum": [ + "BRL" + ] + }, + "observed_at": { + "type": "string" + }, + "valid_until": { + "type": "string" + }, + "source": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "data_catalog" + ] + } + }, + "required": [ + "kind" + ] + } + }, + "required": [ + "offer_id", + "offer_kind", + "merchant_name", + "title", + "attributes", + "cost_lines", + "total_minor", + "currency", + "observed_at", + "valid_until", + "source" + ] + }, + "quotation": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "valid", + "stale", + "changed" + ] + }, + "total_minor": { + "type": "integer" + }, + "previous_total_minor": { + "type": "integer" + }, + "observed_at": { + "type": "string" + }, + "valid_until": { + "type": "string" + } + }, + "required": [ + "state", + "total_minor", + "observed_at", + "valid_until" + ] + }, + "authorization": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "needed", + "awaiting_approval", + "authorized", + "refused", + "expired" + ] + }, + "amount_max_minor": { + "type": "integer" + }, + "approval_id": { + "type": "string" + }, + "expires_at": { + "type": "string" + } + }, + "required": [ + "state", + "amount_max_minor" + ] + }, + "commitment": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "not_started", + "claimed", + "dispatching", + "settled", + "uncertain", + "failed", + "cancelled" + ], + "description": "The call at the provider. `uncertain`: sent and not known yet; the read reconciles it by lookup, never by a resend." + }, + "attempt_id": { + "type": "string" + }, + "call_id": { + "type": "string" + }, + "at": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "payment": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "none", + "held", + "debited", + "released" + ], + "description": "The Wallet: the ceiling held, then the observed amount debited and the rest released." + }, + "held_minor": { + "type": "integer" + }, + "debited_minor": { + "type": "integer" + }, + "released_minor": { + "type": "integer" + }, + "receipt_id": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "confirmation": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "none", + "pending", + "confirmed", + "failed" + ], + "description": "The provider's result: `confirmed` only with its call id and result ref." + }, + "at": { + "type": "string" + }, + "source": { + "type": "string" + }, + "result_ref": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "commitment_terms_changed, data_call_refused, a mandate's or the Wallet's code: an unknown one is shown as a neutral text with the code." + }, + "detail": { + "type": "string" + } + }, + "required": [ + "code" + ] + }, + "actions": { + "type": "object", + "properties": { + "execute": { + "type": "boolean" + }, + "cancel": { + "type": "boolean" + }, + "requote": { + "type": "boolean" + } + }, + "required": [ + "execute", + "cancel", + "requote" + ] + } + }, + "required": [ + "proposal_id", + "run_state", + "awaiting", + "offer", + "quotation", + "authorization", + "commitment", + "payment", + "confirmation", + "actions" + ] + }, + "next_action": { + "type": [ + "object", + "null" + ], + "properties": { + "kind": { + "type": "string", + "enum": [ + "person_authorization" + ] + }, + "url": { + "type": "string", + "description": "The call's card on the dashboard, behind the person's sign-in; only the call's and the project's ids are in it." + }, + "proposal_id": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "kind", + "url", + "proposal_id", + "description" + ] + }, + "idempotent_replay": { + "type": "boolean" + } + }, + "required": [ + "data_call", + "next_action", + "idempotent_replay" + ] + } + } + } + }, + "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." + } + }, + "required": [ + "error", + "request_id" + ] + } + } + } + }, + "403": { + "description": "The key does not hold `shop:purchases:write`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "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": "The offer is not in this key's research.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "offer_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" + ] + } + } + } + }, + "409": { + "description": "No mandate permits the provider, the project is not a Test one, or the idempotency key drafted from another offer.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "proposal_no_mandate", + "data_call_live_unavailable", + "idempotency_key_reused" + ] + }, + "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 offer is not a data service, the provider refuses the call, or the agent is not registered.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "offer_not_data_service", + "data_call_refused", + "agent_not_registered" + ] + }, + "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": "The provider did not answer, or Shop purchases are off on this deployment.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "data_provider_unavailable", + "shop_purchases_disabled" + ] + }, + "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": "shop:purchases:write", + "security": [ + { + "bearerAuth": [ + "shop:purchases:write" + ] + } + ] + } + }, + "/v1/shop/agent/data-calls/{id}": { + "get": { + "summary": "Read a data call back", + "description": "Scope `shop:purchases:read`. The data call with its four states apart, as the Shop's card shows it. A call sent and not known yet is reconciled by the provider's lookup on this read, never resent: read the same id again, across restarts, until `confirmation.state` is `confirmed` (or the call failed). `next_action` while it waits for the person.\n\n**What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The data call id (`prp_...`), from `POST /v1/shop/agent/data-calls`." + }, + "required": true, + "description": "The data call id (`prp_...`), from `POST /v1/shop/agent/data-calls`.", + "name": "id", + "in": "path" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data_call": { + "type": "object", + "properties": { + "proposal_id": { + "type": "string", + "description": "The data call's proposal id (`prp_...`)." + }, + "run_state": { + "type": "string", + "enum": [ + "ready", + "awaiting_user", + "running", + "interrupted", + "completed", + "cancelled" + ] + }, + "awaiting": { + "type": [ + "object", + "null" + ], + "properties": { + "reason": { + "type": "string" + }, + "cause": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "reason", + "cause" + ] + }, + "offer": { + "type": "object", + "properties": { + "offer_id": { + "type": "string" + }, + "offer_kind": { + "type": "string", + "enum": [ + "data_service" + ] + }, + "merchant_name": { + "type": "string" + }, + "title": { + "type": "string" + }, + "attributes": { + "type": "object", + "properties": { + "coverage": { + "type": "string" + }, + "refresh": { + "type": "string" + }, + "license": { + "type": "string" + }, + "unit": { + "type": "string", + "enum": [ + "call" + ] + }, + "params": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "offer_version": { + "type": "integer" + }, + "terms_hash": { + "type": "string" + } + }, + "required": [ + "coverage", + "refresh", + "license", + "unit", + "params", + "offer_version", + "terms_hash" + ] + }, + "cost_lines": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "call" + ] + }, + "label": { + "type": "string" + }, + "unit_minor": { + "type": "integer" + }, + "quantity": { + "type": "number", + "enum": [ + 1 + ] + }, + "amount_minor": { + "type": "integer" + } + }, + "required": [ + "kind", + "label", + "unit_minor", + "quantity", + "amount_minor" + ] + } + }, + "total_minor": { + "type": "integer" + }, + "currency": { + "type": "string", + "enum": [ + "BRL" + ] + }, + "observed_at": { + "type": "string" + }, + "valid_until": { + "type": "string" + }, + "source": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "data_catalog" + ] + } + }, + "required": [ + "kind" + ] + } + }, + "required": [ + "offer_id", + "offer_kind", + "merchant_name", + "title", + "attributes", + "cost_lines", + "total_minor", + "currency", + "observed_at", + "valid_until", + "source" + ] + }, + "quotation": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "valid", + "stale", + "changed" + ] + }, + "total_minor": { + "type": "integer" + }, + "previous_total_minor": { + "type": "integer" + }, + "observed_at": { + "type": "string" + }, + "valid_until": { + "type": "string" + } + }, + "required": [ + "state", + "total_minor", + "observed_at", + "valid_until" + ] + }, + "authorization": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "needed", + "awaiting_approval", + "authorized", + "refused", + "expired" + ] + }, + "amount_max_minor": { + "type": "integer" + }, + "approval_id": { + "type": "string" + }, + "expires_at": { + "type": "string" + } + }, + "required": [ + "state", + "amount_max_minor" + ] + }, + "commitment": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "not_started", + "claimed", + "dispatching", + "settled", + "uncertain", + "failed", + "cancelled" + ], + "description": "The call at the provider. `uncertain`: sent and not known yet; the read reconciles it by lookup, never by a resend." + }, + "attempt_id": { + "type": "string" + }, + "call_id": { + "type": "string" + }, + "at": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "payment": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "none", + "held", + "debited", + "released" + ], + "description": "The Wallet: the ceiling held, then the observed amount debited and the rest released." + }, + "held_minor": { + "type": "integer" + }, + "debited_minor": { + "type": "integer" + }, + "released_minor": { + "type": "integer" + }, + "receipt_id": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "confirmation": { + "type": "object", + "properties": { + "state": { + "type": "string", + "enum": [ + "none", + "pending", + "confirmed", + "failed" + ], + "description": "The provider's result: `confirmed` only with its call id and result ref." + }, + "at": { + "type": "string" + }, + "source": { + "type": "string" + }, + "result_ref": { + "type": "string" + } + }, + "required": [ + "state" + ] + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "description": "commitment_terms_changed, data_call_refused, a mandate's or the Wallet's code: an unknown one is shown as a neutral text with the code." + }, + "detail": { + "type": "string" + } + }, + "required": [ + "code" + ] + }, + "actions": { + "type": "object", + "properties": { + "execute": { + "type": "boolean" + }, + "cancel": { + "type": "boolean" + }, + "requote": { + "type": "boolean" + } + }, + "required": [ + "execute", + "cancel", + "requote" + ] + } + }, + "required": [ + "proposal_id", + "run_state", + "awaiting", + "offer", + "quotation", + "authorization", + "commitment", + "payment", + "confirmation", + "actions" + ] + }, + "next_action": { + "type": [ + "object", + "null" + ], + "properties": { + "kind": { + "type": "string", + "enum": [ + "person_authorization" + ] + }, + "url": { + "type": "string", + "description": "The call's card on the dashboard, behind the person's sign-in; only the call's and the project's ids are in it." + }, + "proposal_id": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "kind", + "url", + "proposal_id", + "description" + ] + } + }, + "required": [ + "data_call", + "next_action" + ] + } + } + } + }, + "403": { + "description": "The key does not hold `shop:purchases:read`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "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": "Not Found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "not_found" + ] + } + }, + "required": [ + "error" + ] + } + } + } + } + }, + "x-codespar-scope": "shop:purchases:read", + "security": [ + { + "bearerAuth": [ + "shop:purchases:read" + ] + } + ] + } + }, + "/v1/shop/agent/data-calls/{id}/execute": { + "post": { + "summary": "Run a data call: always refused for a key", + "description": "Scope `shop:purchases:write`. Running a data call reserves the Wallet and makes the provider's call: that is the person's authorization, and a key never gives it. This route always answers `person_required` (403), with `details.next_action` (the protected action: the call's card on the dashboard, behind the person's sign-in) and `details.data_call`. The person runs it there, or through an MCP client with their full-access login; then read it back by id.\n\n**What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The data call id (`prp_...`)." + }, + "required": true, + "description": "The data call id (`prp_...`).", + "name": "id", + "in": "path" + } + ], + "responses": { + "403": { + "description": "A key never runs a data call; `details.next_action` is the person's way.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "person_required" + ] }, "message": { "type": "string" @@ -118407,6 +120926,161 @@ } } }, + "x-codespar-scope": "shop:purchases:write", + "security": [ + { + "bearerAuth": [ + "shop:purchases:write" + ] + } + ] + } + }, + "/v1/shop/agent/offers/{id}/image/{n}": { + "get": { + "summary": "An offer's image, through CodeSpar", + "description": "Scope `shop:purchases:read`. The image recorded with an offer of this project's keys' research, served from CodeSpar's domain: the store's URL is never exposed and never fetched by the client. The proxy reads only the URL recorded with that offer, checks the network at every hop, reads the type from the content (JPEG, PNG, WebP or AVIF; never SVG), bounds the size and the dimensions and removes the metadata. An offer's `image.url` is this address. Any offer that is not this project's keys', unknown, without that image or whose image is refused answers the same 404 `image_unavailable`.", + "parameters": [ + { + "schema": { + "type": "string", + "description": "The offer id (`sof_...`), from a research of this project's keys." + }, + "required": true, + "description": "The offer id (`sof_...`), from a research of this project's keys.", + "name": "id", + "in": "path" + }, + { + "schema": { + "type": "string", + "pattern": "^[0-9]$", + "description": "The image's index; `image.url` names 0." + }, + "required": true, + "description": "The image's index; `image.url` names 0.", + "name": "n", + "in": "path" + } + ], + "responses": { + "200": { + "description": "The image, `Cache-Control: private, max-age=300`.", + "content": { + "image/jpeg": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/png": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/webp": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/avif": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "403": { + "description": "The key does not hold `shop:purchases:read`.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "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 image to serve.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "image_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": "shop:purchases:read", "security": [ { diff --git a/packages/core/package.json b/packages/core/package.json index c67ae74..bdcf3cb 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/sdk", - "version": "0.16.30", + "version": "0.16.31", "description": "Commerce SDK for AI agents \u2014 sessions, managed auth, Complete Loop orchestration for Latin American APIs", "type": "module", "main": "./dist/index.js", diff --git a/packages/core/src/__tests__/data-calls.test.ts b/packages/core/src/__tests__/data-calls.test.ts new file mode 100644 index 0000000..6f8cca4 --- /dev/null +++ b/packages/core/src/__tests__/data-calls.test.ts @@ -0,0 +1,112 @@ +/** + * Shop G3.1 data calls (`cs.dataCalls`): the wire it sends to + * `/v1/shop/agent/data-calls`, what it returns (the API's wire, four states + * apart), that a key's `execute` surfaces `person_required` as an error and + * never as a run, and the one-word outcome a program branches on. + */ +import { afterEach, describe, expect, it } from "vitest"; +import { CodeSpar } from "../index.js"; +import { CodesparApiError } from "../errors.js"; +import { DataCallNeedsPersonError, dataCallOutcome, type DataCall } from "../data-calls.js"; + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +const VIEW: DataCall = { + proposal_id: "prp_AbCdEfGhIjKlMnOp", + run_state: "ready", + awaiting: null, + offer: { + offer_id: "sof_AbCdEfGhIjKlMnOp", + offer_kind: "data_service", + merchant_name: "Dados de teste CodeSpar", + title: "Consulta de CNPJ (sintética)", + attributes: { coverage: "BR", refresh: "daily", license: "internal_use", unit: "call", params: { cnpj: "11222333000181" }, offer_version: 1, terms_hash: "a".repeat(64) }, + cost_lines: [{ kind: "call", label: "Consulta", unit_minor: 50, quantity: 1, amount_minor: 50 }], + total_minor: 50, + currency: "BRL", + observed_at: "2026-11-08T12:00:00.000Z", + valid_until: "2026-11-08T12:15:00.000Z", + source: { kind: "data_catalog" }, + }, + quotation: { state: "valid", total_minor: 50, observed_at: "2026-11-08T12:00:00.000Z", valid_until: "2026-11-08T12:15:00.000Z" }, + authorization: { state: "needed", amount_max_minor: 50 }, + commitment: { state: "not_started" }, + payment: { state: "none" }, + confirmation: { state: "none" }, + actions: { execute: true, cancel: true, requote: false }, +}; + +function client(answer: (url: string, init: RequestInit) => { status: number; body: unknown }, seen: { url: string; method: string; body: unknown; auth: string | null }[]) { + globalThis.fetch = (async (input: RequestInfo | URL, init: RequestInit = {}) => { + const url = String(input); + const headers = new Headers(init.headers); + seen.push({ url, method: String(init.method ?? "GET"), body: init.body ? JSON.parse(String(init.body)) : null, auth: headers.get("authorization") }); + const a = answer(url, init); + return new Response(JSON.stringify(a.body), { status: a.status, headers: { "content-type": "application/json" } }); + }) as typeof fetch; + return new CodeSpar({ apiKey: "csk_test_example", baseUrl: "https://api.example.com" }); +} + +describe("cs.dataCalls", () => { + it("create sends the snake_case body and returns the wire; get unwraps data_call", async () => { + const seen: { url: string; method: string; body: unknown; auth: string | null }[] = []; + const NEXT = { kind: "person_authorization", url: `https://codespar.dev/dashboard/shop/data-calls/${VIEW.proposal_id}`, proposal_id: VIEW.proposal_id, description: "x" }; + const cs = client( + (url) => (url.endsWith("/data-calls") ? { status: 201, body: { data_call: VIEW, next_action: NEXT, idempotent_replay: false } } : { status: 200, body: { data_call: VIEW, next_action: NEXT } }), + seen, + ); + const created = await cs.dataCalls.create({ agentId: "ag_example", offerId: VIEW.offer.offer_id, idempotencyKey: "idem_example_1" }); + expect(created).toEqual({ data_call: VIEW, next_action: NEXT, idempotent_replay: false }); + expect(seen[0]).toMatchObject({ + url: "https://api.example.com/v1/shop/agent/data-calls", + method: "POST", + body: { agent_id: "ag_example", offer_id: VIEW.offer.offer_id, idempotency_key: "idem_example_1" }, + auth: "Bearer csk_test_example", + }); + const read = await cs.dataCalls.get(VIEW.proposal_id); + expect(read).toEqual({ data_call: VIEW, next_action: NEXT }); + expect(seen[1]).toMatchObject({ url: `https://api.example.com/v1/shop/agent/data-calls/${VIEW.proposal_id}`, method: "GET" }); + }); + + it("a key's execute surfaces person_required with the protected action, never as a run", async () => { + const seen: { url: string; method: string; body: unknown; auth: string | null }[] = []; + const url = `https://codespar.dev/dashboard/shop/data-calls/${VIEW.proposal_id}`; + const cs = client( + () => ({ + status: 403, + body: { error: { code: "person_required", message: "running a data call is the person's authorization", details: { next_action: { kind: "person_authorization", url, proposal_id: VIEW.proposal_id, description: "x" }, data_call: VIEW } } }, + }), + seen, + ); + const err = await cs.dataCalls.execute(VIEW.proposal_id).catch((e: unknown) => e); + expect(err).toBeInstanceOf(DataCallNeedsPersonError); + expect(err).toBeInstanceOf(CodesparApiError); + expect((err as DataCallNeedsPersonError).nextAction?.url).toBe(url); + expect((err as CodesparApiError).status).toBe(403); + expect((err as CodesparApiError).code).toBe("person_required"); + expect(seen[0]).toMatchObject({ url: `https://api.example.com/v1/shop/agent/data-calls/${VIEW.proposal_id}/execute`, method: "POST" }); + }); + + it("a refused draft (the offer is not a data service) is an error with the API's code", async () => { + const cs = client(() => ({ status: 422, body: { error: { code: "offer_not_data_service", message: "this offer is not a data service" } } }), []); + const err = await cs.dataCalls.create({ agentId: "ag_example", offerId: "sof_x", idempotencyKey: "idem_example_2" }).catch((e: unknown) => e); + expect((err as CodesparApiError).code).toBe("offer_not_data_service"); + }); +}); + +describe("dataCallOutcome: one word from the four states", () => { + const at = (over: Partial): DataCall => ({ ...VIEW, ...over }); + it("confirmed is succeeded; uncertain is uncertain, whatever the payment says", () => { + expect(dataCallOutcome(at({ confirmation: { state: "confirmed", result_ref: "tdr_1" }, commitment: { state: "settled" }, payment: { state: "held", held_minor: 50 } }))).toBe("succeeded"); + expect(dataCallOutcome(at({ commitment: { state: "uncertain" }, payment: { state: "debited", debited_minor: 50 } }))).toBe("uncertain"); + }); + it("terms changed or cancelled is refused; a call that failed after the send is failed; a draft is pending", () => { + expect(dataCallOutcome(at({ error: { code: "commitment_terms_changed" } }))).toBe("refused"); + expect(dataCallOutcome(at({ run_state: "cancelled", commitment: { state: "cancelled" } }))).toBe("refused"); + expect(dataCallOutcome(at({ commitment: { state: "failed" }, confirmation: { state: "failed" } }))).toBe("failed"); + expect(dataCallOutcome(VIEW)).toBe("pending"); + }); +}); diff --git a/packages/core/src/data-calls.ts b/packages/core/src/data-calls.ts new file mode 100644 index 0000000..0ac62dc --- /dev/null +++ b/packages/core/src/data-calls.ts @@ -0,0 +1,137 @@ +/** + * `cs.dataCalls`: Shop G3.1 data calls, over the REST routes + * (`/v1/shop/agent/data-calls`). + * + * A data call is a per-call data service offered by a provider and found by + * a research of `taskKind: "data_service"` (`session.research.create`). A key + * DRAFTS one from such an offer; it never runs it. Running reserves the + * Wallet and makes the provider's call: that is the person's authorization, + * so `execute` with a key always answers `person_required` (403). The person + * runs it in the Shop or through an MCP client with their login. + * + * Every answer is the API's wire (snake_case), with the four states apart: + * `quotation`, `authorization`, `commitment` (the call at the provider), + * `payment` (Wallet) and `confirmation`. None is inferred from another: a + * debited payment with an uncertain call is exactly that, never "success". + * `dataCallOutcome` reads them into one word for a program to branch on. + */ + +import { CodesparApiError, networkErrorToApiError, throwFromResponse, TimeoutError } from "./errors.js"; +import { fetchWithTimeout } from "./internal/fetch.js"; +import type { DataCall, DataCallCreated, DataCallCreateInput, DataCallNextAction, DataCallRead } from "@codespar/types"; +import type { CallOptions } from "./types.js"; + +export type { DataCall, DataCallCreated, DataCallCreateInput, DataCallNextAction, DataCallRead }; + +/** + * A key asked to run a data call: the API refused it (`person_required`, 403) and handed the protected action. + * `nextAction.url` is the call's card on the dashboard, behind the person's sign-in. Nothing was run. Hand the url to + * the person, then read the call by id (`get`) until `dataCallOutcome` is no longer `pending`. + */ +export class DataCallNeedsPersonError extends CodesparApiError { + readonly nextAction: DataCallNextAction | null; + constructor(cause: CodesparApiError, nextAction: DataCallNextAction | null) { + super(cause.message, { status: cause.status, code: cause.code, body: cause.body, cause }); + Object.setPrototypeOf(this, DataCallNeedsPersonError.prototype); + this.name = "DataCallNeedsPersonError"; + this.nextAction = nextAction; + } +} + +/** The protected action in a `person_required` refusal's details, or null. */ +export function nextActionOfError(err: unknown): DataCallNextAction | null { + const body = (err as { body?: unknown } | null)?.body as { error?: { details?: { next_action?: unknown } } } | undefined; + const n = body?.error?.details?.next_action as DataCallNextAction | undefined; + return n && n.kind === "person_authorization" && typeof n.url === "string" ? n : null; +} + +interface DataCallsDeps { + baseUrl: string; + apiKey: string; + projectId?: string; + timeout: number; +} + +/** + * One word for a program to branch on, read from the four states: + * `succeeded` the provider's result is confirmed (call id and result ref) + * `uncertain` the call was sent and its outcome is not known yet; reading it again reconciles it, nothing resends + * `refused` nothing was made: the terms changed, the provider refused, the call was cancelled + * `failed` the call ended without a result after it was sent + * `pending` drafted or running: the person still has to run it, or it is in flight + */ +export type DataCallOutcome = "succeeded" | "uncertain" | "refused" | "failed" | "pending"; + +export function dataCallOutcome(d: DataCall): DataCallOutcome { + if (d.confirmation.state === "confirmed") return "succeeded"; + if (d.commitment.state === "uncertain") return "uncertain"; + if (d.error || d.commitment.state === "cancelled" || d.run_state === "cancelled") return "refused"; + if (d.commitment.state === "failed" || d.confirmation.state === "failed") return "failed"; + return "pending"; +} + +export interface DataCalls { + /** `POST /v1/shop/agent/data-calls`: draft a data call from a `data_service` offer. Nothing is reserved or sent. */ + create(input: DataCallCreateInput, opts?: CallOptions): Promise; + /** + * `GET /v1/shop/agent/data-calls/:id`: where it stands, the four states apart, and `next_action` while it waits for + * the person. A call sent and not known yet is reconciled on this read, never resent: read the same id again, + * across restarts, until it is no longer pending. + */ + get(proposalId: string, opts?: CallOptions): Promise; + /** + * `POST /v1/shop/agent/data-calls/:id/execute`: always refused for a key, thrown as `DataCallNeedsPersonError` + * carrying `nextAction` (the person's protected action). Present so the refusal is explicit, never a silent no-op. + */ + execute(proposalId: string, opts?: CallOptions): Promise; +} + +export function createDataCalls(deps: DataCallsDeps): DataCalls { + const auth: Record = { Authorization: `Bearer ${deps.apiKey}` }; + if (deps.projectId) auth["x-codespar-project"] = deps.projectId; + + async function call(what: string, url: string, init: Omit, opts: CallOptions | undefined): Promise { + try { + return await fetchWithTimeout(url, init, { timeout: opts?.timeout ?? deps.timeout, signal: opts?.signal }, async (r) => { + if (!r.ok) await throwFromResponse(r, what); + return (await r.json()) as T; + }); + } catch (cause) { + if (cause instanceof TimeoutError) throw cause; + if (cause instanceof CodesparApiError) throw cause; + if (opts?.signal?.aborted) throw cause; + throw networkErrorToApiError(cause, what); + } + } + + const base = `${deps.baseUrl}/v1/shop/agent/data-calls`; + const one = (id: string) => `${base}/${encodeURIComponent(id)}`; + + return { + async create(input, opts) { + return call( + "dataCalls.create", + base, + { + method: "POST", + headers: { ...auth, "Content-Type": "application/json", Accept: "application/json" }, + body: JSON.stringify({ agent_id: input.agentId, offer_id: input.offerId, idempotency_key: input.idempotencyKey }), + }, + opts, + ); + }, + async get(proposalId, opts) { + return call("dataCalls.get", one(proposalId), { method: "GET", headers: { ...auth, Accept: "application/json" } }, opts); + }, + async execute(proposalId, opts) { + try { + await call("dataCalls.execute", `${one(proposalId)}/execute`, { method: "POST", headers: { ...auth, Accept: "application/json" } }, opts); + } catch (err) { + if (err instanceof CodesparApiError && err.code === "person_required") throw new DataCallNeedsPersonError(err, nextActionOfError(err)); + throw err; + } + // The route never answers 2xx for a key; reaching here means the API changed under this client. + throw new Error("dataCalls.execute: the API answered a key's run without person_required; refusing to treat it as run"); + }, + }; +} diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index 92d166e..d4ff01a 100644 --- a/packages/core/src/generated/openapi.ts +++ b/packages/core/src/generated/openapi.ts @@ -1,5 +1,5 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 868a0272e249a736c8f2510fb7e7def491fdb6ee509d85fc09e5f2fb32af33bd, fetched 2026-11-15T23:15:37.743Z +// Source: openapi-snapshot.json (sha256 1e6a6006fe5e00b10e48e23de7d9c90d61f25fc7fd065bb774f57181382ab426, fetched 2026-11-19T22:56:00.566Z // from https://api.codespar.dev/openapi.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { @@ -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; @@ -48772,6 +49138,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, reservation or data_service (a per-call data service, executed by a data call). + * @enum {string} + */ + task_kind?: "product" | "service_plan" | "reservation" | "data_service"; criteria?: { /** * @description What decides the principal: the lowest total (default) or the fastest delivery. @@ -48780,10 +49151,53 @@ 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), `data` (the data-service providers, for task_kind data_service). Default: `registry` in Test, `vtex` and `meli` in Live; `data` for a data service. */ + sources?: ("registry" | "vtex" | "meli" | "web" | "data")[]; /** @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 task_kind data_service: the call's params, and the SKU when the person named one. */ + data_service?: { + /** @description The call's params, e.g. { cnpj: "11222333000181" }. */ + params: { + [key: string]: string; + }; + /** @description The provider's SKU, when the person named one. */ + sku?: string; + }; + /** @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" | "data")[]; + 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; + }[]; }; }; }; @@ -48970,6 +49384,750 @@ export interface paths { patch?: never; trace?: never; }; + "/v1/shop/agent/data-calls": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Draft a data call from a data_service offer (never run) + * @description Scope `shop:purchases:write`. Shop G3.1: `offer_id` names a `data_service` offer of this key's research (`POST /v1/shop/agent/research` with `task_kind: "data_service"`). The provider quotes the call again and the call is drafted at those terms under the agent's mandate; nothing is reserved or sent. The answer shows the four states apart: quotation, authorization, commitment (the call), payment (Wallet) and the provider's confirmation. The same `agent_id` and `idempotency_key` answer the same draft (`idempotent_replay: true`). Running it is the person's authorization: a key never runs it. While it waits for the person, `next_action` is the protected action to hand them: `{ kind: "person_authorization", url }`, the call's card on the dashboard behind their sign-in (only the call's and the project's ids are in the url). Test projects only. + * + * **What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`. + */ + post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: { + content: { + "application/json": { + agent_id: string; + /** @description A data_service offer of this key's research (`POST /v1/shop/agent/research`, task_kind data_service). */ + offer_id: string; + idempotency_key: string; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data_call: { + /** @description The data call's proposal id (`prp_...`). */ + proposal_id: string; + /** @enum {string} */ + run_state: "ready" | "awaiting_user" | "running" | "interrupted" | "completed" | "cancelled"; + awaiting: { + reason: string; + cause: string | null; + } | null; + offer: { + offer_id: string; + /** @enum {string} */ + offer_kind: "data_service"; + merchant_name: string; + title: string; + attributes: { + coverage: string; + refresh: string; + license: string; + /** @enum {string} */ + unit: "call"; + params: { + [key: string]: string; + }; + offer_version: number; + terms_hash: string; + }; + cost_lines: { + /** @enum {string} */ + kind: "call"; + label: string; + unit_minor: number; + /** @enum {number} */ + quantity: 1; + amount_minor: number; + }[]; + total_minor: number; + /** @enum {string} */ + currency: "BRL"; + observed_at: string; + valid_until: string; + source: { + /** @enum {string} */ + kind: "data_catalog"; + }; + }; + quotation: { + /** @enum {string} */ + state: "valid" | "stale" | "changed"; + total_minor: number; + previous_total_minor?: number; + observed_at: string; + valid_until: string; + }; + authorization: { + /** @enum {string} */ + state: "needed" | "awaiting_approval" | "authorized" | "refused" | "expired"; + amount_max_minor: number; + approval_id?: string; + expires_at?: string; + }; + commitment: { + /** + * @description The call at the provider. `uncertain`: sent and not known yet; the read reconciles it by lookup, never by a resend. + * @enum {string} + */ + state: "not_started" | "claimed" | "dispatching" | "settled" | "uncertain" | "failed" | "cancelled"; + attempt_id?: string; + call_id?: string; + at?: string; + }; + payment: { + /** + * @description The Wallet: the ceiling held, then the observed amount debited and the rest released. + * @enum {string} + */ + state: "none" | "held" | "debited" | "released"; + held_minor?: number; + debited_minor?: number; + released_minor?: number; + receipt_id?: string; + }; + confirmation: { + /** + * @description The provider's result: `confirmed` only with its call id and result ref. + * @enum {string} + */ + state: "none" | "pending" | "confirmed" | "failed"; + at?: string; + source?: string; + result_ref?: string; + }; + error?: { + /** @description commitment_terms_changed, data_call_refused, a mandate's or the Wallet's code: an unknown one is shown as a neutral text with the code. */ + code: string; + detail?: string; + }; + actions: { + execute: boolean; + cancel: boolean; + requote: boolean; + }; + }; + next_action: { + /** @enum {string} */ + kind: "person_authorization"; + /** @description The call's card on the dashboard, behind the person's sign-in; only the call's and the project's ids are in it. */ + url: string; + proposal_id: string; + description: string; + } | null; + idempotent_replay: boolean; + }; + }; + }; + /** @description OK */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data_call: { + /** @description The data call's proposal id (`prp_...`). */ + proposal_id: string; + /** @enum {string} */ + run_state: "ready" | "awaiting_user" | "running" | "interrupted" | "completed" | "cancelled"; + awaiting: { + reason: string; + cause: string | null; + } | null; + offer: { + offer_id: string; + /** @enum {string} */ + offer_kind: "data_service"; + merchant_name: string; + title: string; + attributes: { + coverage: string; + refresh: string; + license: string; + /** @enum {string} */ + unit: "call"; + params: { + [key: string]: string; + }; + offer_version: number; + terms_hash: string; + }; + cost_lines: { + /** @enum {string} */ + kind: "call"; + label: string; + unit_minor: number; + /** @enum {number} */ + quantity: 1; + amount_minor: number; + }[]; + total_minor: number; + /** @enum {string} */ + currency: "BRL"; + observed_at: string; + valid_until: string; + source: { + /** @enum {string} */ + kind: "data_catalog"; + }; + }; + quotation: { + /** @enum {string} */ + state: "valid" | "stale" | "changed"; + total_minor: number; + previous_total_minor?: number; + observed_at: string; + valid_until: string; + }; + authorization: { + /** @enum {string} */ + state: "needed" | "awaiting_approval" | "authorized" | "refused" | "expired"; + amount_max_minor: number; + approval_id?: string; + expires_at?: string; + }; + commitment: { + /** + * @description The call at the provider. `uncertain`: sent and not known yet; the read reconciles it by lookup, never by a resend. + * @enum {string} + */ + state: "not_started" | "claimed" | "dispatching" | "settled" | "uncertain" | "failed" | "cancelled"; + attempt_id?: string; + call_id?: string; + at?: string; + }; + payment: { + /** + * @description The Wallet: the ceiling held, then the observed amount debited and the rest released. + * @enum {string} + */ + state: "none" | "held" | "debited" | "released"; + held_minor?: number; + debited_minor?: number; + released_minor?: number; + receipt_id?: string; + }; + confirmation: { + /** + * @description The provider's result: `confirmed` only with its call id and result ref. + * @enum {string} + */ + state: "none" | "pending" | "confirmed" | "failed"; + at?: string; + source?: string; + result_ref?: string; + }; + error?: { + /** @description commitment_terms_changed, data_call_refused, a mandate's or the Wallet's code: an unknown one is shown as a neutral text with the code. */ + code: string; + detail?: string; + }; + actions: { + execute: boolean; + cancel: boolean; + requote: boolean; + }; + }; + next_action: { + /** @enum {string} */ + kind: "person_authorization"; + /** @description The call's card on the dashboard, behind the person's sign-in; only the call's and the project's ids are in it. */ + url: string; + proposal_id: string; + description: string; + } | null; + idempotent_replay: boolean; + }; + }; + }; + /** @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 The key does not hold `shop:purchases:write`. */ + 403: { + 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 offer is not in this key's research. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "offer_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 No mandate permits the provider, the project is not a Test one, or the idempotency key drafted from another offer. */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "proposal_no_mandate" | "data_call_live_unavailable" | "idempotency_key_reused"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The offer is not a data service, the provider refuses the call, or the agent is not registered. */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "offer_not_data_service" | "data_call_refused" | "agent_not_registered"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The provider did not answer, or Shop purchases are off on this deployment. */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "data_provider_unavailable" | "shop_purchases_disabled"; + 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/shop/agent/data-calls/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read a data call back + * @description Scope `shop:purchases:read`. The data call with its four states apart, as the Shop's card shows it. A call sent and not known yet is reconciled by the provider's lookup on this read, never resent: read the same id again, across restarts, until `confirmation.state` is `confirmed` (or the call failed). `next_action` while it waits for the person. + * + * **What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The data call id (`prp_...`), from `POST /v1/shop/agent/data-calls`. */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data_call: { + /** @description The data call's proposal id (`prp_...`). */ + proposal_id: string; + /** @enum {string} */ + run_state: "ready" | "awaiting_user" | "running" | "interrupted" | "completed" | "cancelled"; + awaiting: { + reason: string; + cause: string | null; + } | null; + offer: { + offer_id: string; + /** @enum {string} */ + offer_kind: "data_service"; + merchant_name: string; + title: string; + attributes: { + coverage: string; + refresh: string; + license: string; + /** @enum {string} */ + unit: "call"; + params: { + [key: string]: string; + }; + offer_version: number; + terms_hash: string; + }; + cost_lines: { + /** @enum {string} */ + kind: "call"; + label: string; + unit_minor: number; + /** @enum {number} */ + quantity: 1; + amount_minor: number; + }[]; + total_minor: number; + /** @enum {string} */ + currency: "BRL"; + observed_at: string; + valid_until: string; + source: { + /** @enum {string} */ + kind: "data_catalog"; + }; + }; + quotation: { + /** @enum {string} */ + state: "valid" | "stale" | "changed"; + total_minor: number; + previous_total_minor?: number; + observed_at: string; + valid_until: string; + }; + authorization: { + /** @enum {string} */ + state: "needed" | "awaiting_approval" | "authorized" | "refused" | "expired"; + amount_max_minor: number; + approval_id?: string; + expires_at?: string; + }; + commitment: { + /** + * @description The call at the provider. `uncertain`: sent and not known yet; the read reconciles it by lookup, never by a resend. + * @enum {string} + */ + state: "not_started" | "claimed" | "dispatching" | "settled" | "uncertain" | "failed" | "cancelled"; + attempt_id?: string; + call_id?: string; + at?: string; + }; + payment: { + /** + * @description The Wallet: the ceiling held, then the observed amount debited and the rest released. + * @enum {string} + */ + state: "none" | "held" | "debited" | "released"; + held_minor?: number; + debited_minor?: number; + released_minor?: number; + receipt_id?: string; + }; + confirmation: { + /** + * @description The provider's result: `confirmed` only with its call id and result ref. + * @enum {string} + */ + state: "none" | "pending" | "confirmed" | "failed"; + at?: string; + source?: string; + result_ref?: string; + }; + error?: { + /** @description commitment_terms_changed, data_call_refused, a mandate's or the Wallet's code: an unknown one is shown as a neutral text with the code. */ + code: string; + detail?: string; + }; + actions: { + execute: boolean; + cancel: boolean; + requote: boolean; + }; + }; + next_action: { + /** @enum {string} */ + kind: "person_authorization"; + /** @description The call's card on the dashboard, behind the person's sign-in; only the call's and the project's ids are in it. */ + url: string; + proposal_id: string; + description: string; + } | null; + }; + }; + }; + /** @description The key does not hold `shop:purchases:read`. */ + 403: { + 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 Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @enum {string} */ + error: "not_found"; + }; + }; + }; + }; + }; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/shop/agent/data-calls/{id}/execute": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Run a data call: always refused for a key + * @description Scope `shop:purchases:write`. Running a data call reserves the Wallet and makes the provider's call: that is the person's authorization, and a key never gives it. This route always answers `person_required` (403), with `details.next_action` (the protected action: the call's card on the dashboard, behind the person's sign-in) and `details.data_call`. The person runs it there, or through an MCP client with their full-access login; then read it back by id. + * + * **What an assistant can and cannot do.** It proposes a purchase and reads where it stands; it never pays, approves, saves a card or logs in at a store. A verified person presses Pagar on the dashboard and completes what the purchase waits for (the protected card or CVV form, the store login); the purchase then runs through the same executor as the Shop's own chat, at most once at the store. No answer carries a card number, a security code, a cookie or a collect secret. Test projects only in this first delivery; behind `SHOP_PURCHASES_ENABLED`. + */ + post: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The data call id (`prp_...`). */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description A key never runs a data call; `details.next_action` is the person's way. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "person_required"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @enum {string} */ + error: "not_found"; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/v1/shop/agent/offers/{id}/image/{n}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * An offer's image, through CodeSpar + * @description Scope `shop:purchases:read`. The image recorded with an offer of this project's keys' research, served from CodeSpar's domain: the store's URL is never exposed and never fetched by the client. The proxy reads only the URL recorded with that offer, checks the network at every hop, reads the type from the content (JPEG, PNG, WebP or AVIF; never SVG), bounds the size and the dimensions and removes the metadata. An offer's `image.url` is this address. Any offer that is not this project's keys', unknown, without that image or whose image is refused answers the same 404 `image_unavailable`. + */ + get: { + parameters: { + query?: never; + header?: never; + path: { + /** @description The offer id (`sof_...`), from a research of this project's keys. */ + id: string; + /** @description The image's index; `image.url` names 0. */ + n: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The image, `Cache-Control: private, max-age=300`. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "image/jpeg": string; + "image/png": string; + "image/webp": string; + "image/avif": string; + }; + }; + /** @description The key does not hold `shop:purchases:read`. */ + 403: { + 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 No image to serve. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "image_unavailable"; + 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/shop/agent/capabilities": { parameters: { query?: never; diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index 202f9f9..c776999 100644 --- a/packages/core/src/generated/operations.ts +++ b/packages/core/src/generated/operations.ts @@ -1,5 +1,5 @@ // GENERATED FILE — do not edit. -// Source: openapi-snapshot.json (sha256 868a0272e249a736c8f2510fb7e7def491fdb6ee509d85fc09e5f2fb32af33bd, fetched 2026-11-15T23:15:37.743Z +// Source: openapi-snapshot.json (sha256 1e6a6006fe5e00b10e48e23de7d9c90d61f25fc7fd065bb774f57181382ab426, fetched 2026-11-19T22:56:00.566Z // from https://api.codespar.dev/openapi.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 }, @@ -341,6 +344,10 @@ export const API_OPERATIONS = [ { method: "get", path: "/v1/shop/agent/purchases/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "post", path: "/v1/shop/agent/research", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/shop/agent/research/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "post", path: "/v1/shop/agent/data-calls", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "get", path: "/v1/shop/agent/data-calls/{id}", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, + { method: "post", path: "/v1/shop/agent/data-calls/{id}/execute", body: null, accept: null, requiredQuery: [], deprecated: false }, + { method: "get", path: "/v1/shop/agent/offers/{id}/image/{n}", body: null, accept: "image/jpeg", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/shop/agent/capabilities", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/shop/agent/instruments", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/projects", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c8305b0..b7503ef 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -70,6 +70,8 @@ export type { } from "./types.js"; export { PIX_KEY_DELETE_CONSEQUENCE, PixKeyDeleteNotConfirmedError } from "./wallet.js"; export type { Wallet, WalletPixKeys } from "./wallet.js"; +export { dataCallOutcome, DataCallNeedsPersonError, nextActionOfError } from "./data-calls.js"; +export type { DataCall, DataCallCreated, DataCallCreateInput, DataCallNextAction, DataCallOutcome, DataCallRead, DataCalls } from "./data-calls.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 { createDataCalls, type DataCalls } from "./data-calls.js"; import { createDocuments, type Account, type Receipts } from "./documents.js"; import { validateTimeout } from "./internal/fetch.js"; @@ -176,6 +179,20 @@ export class CodeSpar { */ readonly wallet: Wallet; + /** + * Shop G3.1 data calls (`/v1/shop/agent/data-calls`): draft one from a + * `data_service` offer of a research, and read it, the four states apart. + * A key never runs it: `execute` answers `person_required`. + * + * @example + * ```ts + * const research = await session.research.create({ query: "consulta de CNPJ", taskKind: "data_service", criteria: { dataService: { params: { cnpj: "11222333000181" } } } }); + * const { data_call } = await cs.dataCalls.create({ agentId: "ag_example", offerId: research.offers[0].id, idempotencyKey: "idem_example_1" }); + * const now = await cs.dataCalls.get(data_call.proposal_id); + * ``` + */ + readonly dataCalls: DataCalls; + /** * 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 +270,12 @@ export class CodeSpar { projectId: this.config.projectId || undefined, timeout: this.config.timeout, }); + this.dataCalls = createDataCalls({ + 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 8ed779a..135bfb7 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -42,6 +42,7 @@ import type { AgentResearch, AgentResearchInput, } from "@codespar/types"; +import { createDataCalls } from "./data-calls.js"; interface SessionDeps { baseUrl: string; @@ -488,11 +489,12 @@ export async function createSession( ...(c.maxTotalMinor !== undefined ? { max_total_minor: c.maxTotalMinor } : {}), ...(c.sources !== undefined ? { sources: c.sources } : {}), ...(c.limit !== undefined ? { limit: c.limit } : {}), + ...(c.dataService !== undefined ? { data_service: { params: c.dataService.params, ...(c.dataService.sku !== undefined ? { sku: c.dataService.sku } : {}) } } : {}), } : undefined; return await safeFetch( `${baseUrl}/v1/shop/agent/research`, - { method: "POST", headers, body: JSON.stringify({ query: input.query, ...(criteria ? { criteria } : {}) }) }, + { method: "POST", headers, body: JSON.stringify({ query: input.query, ...(input.taskKind ? { task_kind: input.taskKind } : {}), ...(criteria ? { criteria } : {}) }) }, "research.create", callOpts(opts), async (r) => { @@ -522,6 +524,9 @@ export async function createSession( * is deprecated: still sent when given, so an API older than Shop v0.3 * keeps answering, and ignored by a newer one. */ + /** Shop G3.1 data calls (`/v1/shop/agent/data-calls`): the same client as `cs.dataCalls`. */ + dataCalls: createDataCalls({ baseUrl, apiKey, ...(projectId ? { projectId } : {}), timeout: deps.timeout }), + instruments: { async list(opts: { owner?: string } & CallOptions = {}): Promise { const { owner, ...rest } = opts; diff --git a/packages/mcp/CHANGELOG.md b/packages/mcp/CHANGELOG.md index 1432055..4515d32 100644 --- a/packages/mcp/CHANGELOG.md +++ b/packages/mcp/CHANGELOG.md @@ -1,5 +1,13 @@ # @codespar/mcp — changelog +## 0.5.21 — 2026-11-08 + +### Added + +- `codespar_shop_data_call_draft` and `codespar_shop_data_call_status`, and + `task_kind: "data_service"` on `codespar_shop_research` (Shop G3.1). There is + no run tool: running a data call is the person's authorization. + ## 0.5.20 — 2026-10-30 ### Added diff --git a/packages/mcp/package.json b/packages/mcp/package.json index b4f9e65..e4fddfc 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/mcp", - "version": "0.5.20", + "version": "0.5.21", "description": "MCP server for CodeSpar — give Claude, Codex, Cursor & ChatGPT a commerce agent (pay, charge, wallet, mandates, Pomelo card) over MCP", "type": "module", "main": "./dist/index.js", diff --git a/packages/mcp/src/__tests__/shop-purchase-tools.test.ts b/packages/mcp/src/__tests__/shop-purchase-tools.test.ts index ac46523..22c30eb 100644 --- a/packages/mcp/src/__tests__/shop-purchase-tools.test.ts +++ b/packages/mcp/src/__tests__/shop-purchase-tools.test.ts @@ -12,6 +12,9 @@ describe("Shop purchase MCP tools", () => { expect(SHOP_PURCHASE_MCP_TOOLS.map((t) => t.name)).toEqual([ "codespar_shop_purchase_propose", "codespar_shop_research", + "codespar_shop_data_call_draft", + "codespar_shop_data_call_request_authorization", + "codespar_shop_data_call_status", "codespar_shop_research_status", "codespar_shop_purchase_status", "codespar_shop_instruments", @@ -85,4 +88,35 @@ describe("Shop purchase MCP tools", () => { await callShopPurchaseTool(session, "codespar_shop_purchase_propose", { agent_id: "ag", offer_id: "sof_AbCdEfGhIjKlMnOp", quantity: 2, idempotency_key: "idem_0002" }); expect(calls[3]).toEqual(["create", { agentId: "ag", offerId: "sof_AbCdEfGhIjKlMnOp", quantity: 2, idempotencyKey: "idem_0002" }]); }); + + it("Shop G3.1: a data-service research, a draft from its offer and a read; no run tool exists", async () => { + const calls: unknown[] = []; + const session = { + research: { + create: async (i: unknown) => (calls.push(["research.create", i]), { id: "srr_x" }), + get: async () => ({}), + }, + dataCalls: { + create: async (i: unknown) => (calls.push(["dataCalls.create", i]), { data_call: {}, idempotent_replay: false }), + get: async (id: string) => (calls.push(["dataCalls.get", id]), {}), + execute: async () => { + throw Object.assign(new Error("person_required"), { + code: "person_required", + body: { error: { details: { next_action: { url: "https://codespar.dev/dashboard/shop/data-calls/prp_AbCdEfGhIjKlMnOp" } } } }, + }); + }, + }, + purchases: { create: async () => ({}), get: async () => ({}) }, + instruments: { list: async () => [] }, + } as never; + await callShopPurchaseTool(session, "codespar_shop_research", { query: "consulta de CNPJ", task_kind: "data_service", data_service_params: { cnpj: "11222333000181" } }); + expect(calls[0]).toEqual(["research.create", { query: "consulta de CNPJ", taskKind: "data_service", criteria: { dataService: { params: { cnpj: "11222333000181" } } } }]); + await callShopPurchaseTool(session, "codespar_shop_data_call_draft", { agent_id: "ag", offer_id: "sof_AbCdEfGhIjKlMnOp", idempotency_key: "idem_0003" }); + expect(calls[1]).toEqual(["dataCalls.create", { agentId: "ag", offerId: "sof_AbCdEfGhIjKlMnOp", idempotencyKey: "idem_0003" }]); + await callShopPurchaseTool(session, "codespar_shop_data_call_status", { proposal_id: "prp_AbCdEfGhIjKlMnOp" }); + expect(calls[2]).toEqual(["dataCalls.get", "prp_AbCdEfGhIjKlMnOp"]); + expect(SHOP_PURCHASE_MCP_TOOLS.some((t) => /execute|run/.test(t.name))).toBe(false); + const asked = await callShopPurchaseTool(session, "codespar_shop_data_call_request_authorization", { proposal_id: "prp_AbCdEfGhIjKlMnOp" }); + expect(asked).toContain("https://codespar.dev/dashboard/shop/data-calls/prp_AbCdEfGhIjKlMnOp"); + }); }); diff --git a/packages/mcp/src/shop-purchase-tools.ts b/packages/mcp/src/shop-purchase-tools.ts index 0d3c0ff..e082338 100644 --- a/packages/mcp/src/shop-purchase-tools.ts +++ b/packages/mcp/src/shop-purchase-tools.ts @@ -12,6 +12,12 @@ * (`shop:purchases:write`, `shop:purchases:read`, `shop:instruments:read`). * Since Shop v0.3 the card list is the authenticated person's own: with a * project key it answers a text saying so (`INSTRUMENTS_NEED_A_PERSON`). + * + * Shop G3.1 adds data calls (`session.dataCalls`, `/v1/shop/agent/data-calls`): + * a research of task_kind data_service, a draft from its offer, and a read of + * it with the four states apart. Running one is the person's authorization: + * there is no run tool here, and the person runs it in the Shop or through an + * MCP client with their login. */ import type { Session } from "@codespar/sdk"; @@ -72,9 +78,63 @@ export const SHOP_PURCHASE_MCP_TOOLS: readonly McpToolDefinition[] = [ max_total_minor: { type: "integer", minimum: 1, description: "The most to pay, shipping included, in centavos." }, sources: { type: "array", items: { type: "string", enum: ["registry", "vtex", "meli"] }, description: "Where to look; default: registry in Test, vtex and meli in Live." }, limit: { type: "integer", minimum: 1, maximum: 5, description: "Offers per source (default 5)." }, + task_kind: { + type: "string", + enum: ["product", "data_service"], + description: "product (default), or data_service: a per-call data service, with data_service_params (and data_service_sku).", + }, + data_service_params: { + type: "object", + additionalProperties: { type: "string" }, + description: "task_kind data_service: the call's params, e.g. { \"cnpj\": \"11222333000181\" }.", + }, + data_service_sku: { type: "string", description: "task_kind data_service: the provider's SKU, when the person named one." }, + }, + }, + }, + { + name: "codespar_shop_data_call_draft", + description: + "Draft a data call from a data_service offer of codespar_shop_research: the provider quotes it again and the draft " + + "shows the four states apart (quotation, authorization, commitment, payment, confirmation). Nothing is reserved or " + + "sent, and no tool here runs it: running is the person's authorization (in the Shop, or an MCP client with their " + + "login). The same idempotency_key answers the same draft. Needs shop:purchases:write.", + inputSchema: { + type: "object", + additionalProperties: false, + required: ["agent_id", "offer_id", "idempotency_key"], + properties: { + agent_id: { type: "string", description: "The registered agent drafting it." }, + offer_id: { type: "string", pattern: "^sof_[A-Za-z0-9_-]{16}$", description: "A data_service offer of codespar_shop_research." }, + idempotency_key: { type: "string", description: "The same key answers the same draft." }, }, }, }, + { + name: "codespar_shop_data_call_request_authorization", + description: + "Ask for a drafted data call to be run. This key never runs it: the answer is the protected action for the person, " + + "a link to the call's card on the CodeSpar dashboard behind their own sign-in. Give the person the link, then follow " + + "the call with codespar_shop_data_call_status (by id, across restarts) until it is confirmed. Needs shop:purchases:write.", + inputSchema: { + type: "object", + additionalProperties: false, + required: ["proposal_id"], + properties: { proposal_id: { type: "string", pattern: "^prp_[A-Za-z0-9_-]{16}$" } }, + }, + }, + { + name: "codespar_shop_data_call_status", + description: + "Where a data call stands, the four states apart: an uncertain call (sent, outcome not known yet) is reconciled by " + + "the server, never resent. Needs shop:purchases:read.", + inputSchema: { + type: "object", + additionalProperties: false, + required: ["proposal_id"], + properties: { proposal_id: { type: "string", pattern: "^prp_[A-Za-z0-9_-]{16}$" } }, + }, + }, { name: "codespar_shop_research_status", description: "Read a research back, with each offer's staleness at the time of the answer. Needs shop:purchases:read.", @@ -151,11 +211,48 @@ export async function callShopPurchaseTool(session: Session, name: string, args: ...(sources ? { sources } : {}), ...(typeof args.limit === "number" ? { limit: args.limit } : {}), }; - return session.research.create({ query: String(args.query ?? ""), ...(Object.keys(criteria).length > 0 ? { criteria } : {}) }); + const dataService = + args.task_kind === "data_service" && args.data_service_params && typeof args.data_service_params === "object" + ? { + dataService: { + params: Object.fromEntries(Object.entries(args.data_service_params as Record).map(([k, v]) => [k, String(v)])), + ...(typeof args.data_service_sku === "string" ? { sku: args.data_service_sku } : {}), + }, + } + : {}; + const all = { ...criteria, ...dataService }; + return session.research.create({ + query: String(args.query ?? ""), + ...(args.task_kind === "data_service" ? { taskKind: "data_service" as const } : {}), + ...(Object.keys(all).length > 0 ? { criteria: all } : {}), + }); } case "codespar_shop_research_status": if (!session.research) throw new Error("this runtime does not offer Shop research"); return session.research.get(String(args.research_id ?? "")); + case "codespar_shop_data_call_draft": + if (!session.dataCalls) throw new Error("this runtime does not offer Shop data calls"); + return session.dataCalls.create({ agentId: String(args.agent_id ?? ""), offerId: String(args.offer_id ?? ""), idempotencyKey: String(args.idempotency_key ?? "") }); + case "codespar_shop_data_call_request_authorization": { + if (!session.dataCalls) throw new Error("this runtime does not offer Shop data calls"); + try { + await session.dataCalls.execute(String(args.proposal_id ?? "")); + } catch (err) { + // Read by code and shape, so an older @codespar/sdk inside the peer range is read the same way. + const body = (err as { code?: unknown; body?: { error?: { details?: { next_action?: { url?: unknown } } } } } | null) ?? null; + const url = body?.body?.error?.details?.next_action?.url; + if (body?.code === "person_required") { + return typeof url === "string" + ? `This call waits for the person: they open ${url}, sign in and run it on its card. Then follow it with codespar_shop_data_call_status.` + : "This call cannot be run now (it already ran, or can no longer run); read it with codespar_shop_data_call_status."; + } + throw err; + } + throw new Error("the API ran a data call for a key; refusing to report it as run"); + } + case "codespar_shop_data_call_status": + if (!session.dataCalls) throw new Error("this runtime does not offer Shop data calls"); + return session.dataCalls.get(String(args.proposal_id ?? "")); case "codespar_shop_purchase_status": return session.purchases.get(String(args.purchase_id ?? "")); case "codespar_shop_instruments": diff --git a/packages/python/CHANGELOG.md b/packages/python/CHANGELOG.md index b887fd5..44ab1aa 100644 --- a/packages/python/CHANGELOG.md +++ b/packages/python/CHANGELOG.md @@ -1,5 +1,14 @@ # codespar (Python SDK) — CHANGELOG +## Unreleased + +### Added + +- `cs.research` (create, get over `/v1/shop/agent/research`) and + `cs.data_calls` (create, get, execute over `/v1/shop/agent/data-calls`), + with `data_call_outcome`, on the async and the sync client (Shop G3.1). + `execute` with a key raises `ApiError` 403 `person_required`. + ## 0.16.2 The statement as PNG pages, in parity with `@codespar/sdk` 0.16.28. diff --git a/packages/python/src/codespar/__init__.py b/packages/python/src/codespar/__init__.py index adce1a1..bd0d8ac 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -29,6 +29,18 @@ from ._async_client import AsyncCodeSpar from ._async_session import AsyncSession from ._sync_client import CodeSpar, Session +from .data_calls import ( + AsyncDataCalls, + AsyncResearch, + DataCall, + DataCallCreated, + DataCallNextAction, + DataCallRead, + DataCalls, + Research, + data_call_outcome, + next_action_of, +) from .documents import ( Account, AsyncAccount, @@ -204,8 +216,10 @@ "AssistantTextEvent", "AsyncAccount", "AsyncCodeSpar", + "AsyncDataCalls", "AsyncPayables", "AsyncReceipts", + "AsyncResearch", "AsyncSession", "AsyncWallet", "AsyncWalletPixKeys", @@ -229,6 +243,11 @@ "ConnectionWizardInstructions", "ConnectionWizardOptions", "ConnectionWizardResult", + "DataCall", + "DataCallCreated", + "DataCallNextAction", + "DataCallRead", + "DataCalls", # Tool discovery (codespar_discover) "DiscoverOptions", "DiscoverPlanStep", @@ -296,6 +315,7 @@ "ReceiptQuote", "Receipts", "RequiredSecret", + "Research", "SearchStrategy", "SendResult", "ServerConnection", @@ -351,11 +371,13 @@ # Version "__version__", "assert_exhaustive_tool_result", + "data_call_outcome", "filename_from_disposition", "is_approval_required", "is_mocks_engine_error", "is_mocks_exhausted", "is_policy_denied", "is_tool_not_mocked", + "next_action_of", "payable_batch_from_error", ] diff --git a/packages/python/src/codespar/_async_client.py b/packages/python/src/codespar/_async_client.py index 2c5cdcc..09a5d95 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 .data_calls import AsyncDataCalls, AsyncResearch from .documents import AsyncAccount, AsyncReceipts from .errors import ApiError, ConfigError from .payables import AsyncPayables @@ -107,6 +108,11 @@ 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) + #: Shop research (``/v1/shop/agent/research``): offers compared, one recommendation. + self.research = AsyncResearch(self._client, self._api_key, self._project_id) + #: Shop G3.1 data calls (``/v1/shop/agent/data-calls``): + #: a key drafts and reads; the person runs. + self.data_calls = AsyncDataCalls(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/_sync_client.py b/packages/python/src/codespar/_sync_client.py index 086e980..f0ed26f 100644 --- a/packages/python/src/codespar/_sync_client.py +++ b/packages/python/src/codespar/_sync_client.py @@ -22,6 +22,7 @@ from ._async_client import AsyncCodeSpar from ._async_session import AsyncSession from ._http import normalize_timeout +from .data_calls import DataCalls, Research from .documents import Account, Receipts from .errors import ConfigError from .payables import Payables @@ -343,6 +344,11 @@ 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) + #: Shop research (``/v1/shop/agent/research``): offers compared, one recommendation. + self.research = Research(self._async.research, self._runner) + #: Shop G3.1 data calls (``/v1/shop/agent/data-calls``): + #: a key drafts and reads; the person runs. + self.data_calls = DataCalls(self._async.data_calls, 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/data_calls.py b/packages/python/src/codespar/data_calls.py new file mode 100644 index 0000000..3e0d3fc --- /dev/null +++ b/packages/python/src/codespar/data_calls.py @@ -0,0 +1,287 @@ +""" +``cs.research`` and ``cs.data_calls`` — Shop research and G3.1 data calls, +over the REST routes (``/v1/shop/agent/research``, ``/v1/shop/agent/data-calls``). + +A data call is a per-call data service found by a research of +``task_kind="data_service"``. A key DRAFTS one from such an offer; it never +runs it. Running reserves the Wallet and makes the provider's call: that is the +person's authorization, so ``execute`` with a key always raises ``ApiError`` +with status 403 and code ``person_required``. The person runs it in the Shop or +through an MCP client with their login. + +Responses are the wire shape as typed dicts, the four states apart: +``quotation``, ``authorization``, ``commitment`` (the call at the provider), +``payment`` (Wallet) and ``confirmation``. ``data_call_outcome`` reads them into +one word. Mirrors ``session.research`` and ``cs.dataCalls`` in the TypeScript SDK. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, TypedDict +from urllib.parse import quote + +import httpx + +from ._http import request_json +from .errors import ApiError + +if TYPE_CHECKING: + from ._sync_client import _LoopRunner + +TaskKind = Literal["product", "service_plan", "reservation", "data_service"] +DataCallOutcome = Literal["succeeded", "uncertain", "refused", "failed", "pending"] + + +class DataCallCommitment(TypedDict, total=False): + state: str + attempt_id: str + call_id: str + at: str + + +class DataCallPayment(TypedDict, total=False): + state: str + held_minor: int + debited_minor: int + released_minor: int + receipt_id: str + + +class DataCallConfirmation(TypedDict, total=False): + state: str + at: str + source: str + result_ref: str + + +class DataCall(TypedDict, total=False): + """A data call as the API answers it (``DataCallView``), the four states apart.""" + + proposal_id: str + run_state: str + awaiting: dict[str, Any] | None + offer: dict[str, Any] + quotation: dict[str, Any] + authorization: dict[str, Any] + commitment: DataCallCommitment + payment: DataCallPayment + confirmation: DataCallConfirmation + error: dict[str, Any] + actions: dict[str, bool] + + +class DataCallNextAction(TypedDict): + """The protected action while a call waits for the person: its card, behind their sign-in.""" + + kind: Literal["person_authorization"] + url: str + proposal_id: str + description: str + + +class DataCallRead(TypedDict): + """``GET /v1/shop/agent/data-calls/:id``: the call and its protected action. + + ``next_action`` is set while the call waits for the person, None otherwise. + """ + + data_call: DataCall + next_action: DataCallNextAction | None + + +class DataCallCreated(DataCallRead): + """``POST /v1/shop/agent/data-calls``.""" + + idempotent_replay: bool + + +def next_action_of(err: BaseException) -> DataCallNextAction | None: + """The protected action in a ``person_required`` refusal (``ApiError``), or None.""" + if ( + not isinstance(err, ApiError) + or err.code != "person_required" + or not isinstance(err.body, dict) + ): + return None + error = err.body.get("error") + details = error.get("details") if isinstance(error, dict) else None + action = details.get("next_action") if isinstance(details, dict) else None + if ( + isinstance(action, dict) + and action.get("kind") == "person_authorization" + and isinstance(action.get("url"), str) + ): + result: DataCallNextAction = action # type: ignore[assignment] + return result + return None + + +def data_call_outcome(d: DataCall) -> DataCallOutcome: + """One word from the four states (the same rule as ``dataCallOutcome`` in TypeScript).""" + commitment = d.get("commitment", {}).get("state") + confirmation = d.get("confirmation", {}).get("state") + if confirmation == "confirmed": + return "succeeded" + if commitment == "uncertain": + return "uncertain" + if d.get("error") or commitment == "cancelled" or d.get("run_state") == "cancelled": + return "refused" + if commitment == "failed" or confirmation == "failed": + return "failed" + return "pending" + + +class _Rest: + 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 _call( + self, method: str, path: str, *, body: Any = None, timeout: float | None + ) -> Any: + data = await request_json( + self._client, + method, + path, + api_key=self._api_key, + project_id=self._project_id, + body=body, + timeout=timeout, + ) + if not isinstance(data, dict): + raise ApiError(f"{method} {path}: malformed response", status=0, body=data) + return data + + +class AsyncResearch(_Rest): + """``cs.research`` on :class:`AsyncCodeSpar`.""" + + async def create( + self, + query: str, + *, + task_kind: TaskKind | None = None, + criteria: dict[str, Any] | None = None, + timeout: float | None = None, + ) -> dict[str, Any]: + """``POST /v1/shop/agent/research``: offers compared, one recommendation; proposes nothing. + + For a data service: ``task_kind="data_service"`` and + ``criteria={"data_service": {"params": {...}, "sku": ...}}`` (the wire's snake_case). + """ + body: dict[str, Any] = {"query": query} + if task_kind is not None: + body["task_kind"] = task_kind + if criteria is not None: + body["criteria"] = criteria + data = await self._call("POST", "/v1/shop/agent/research", body=body, timeout=timeout) + research: dict[str, Any] = data["research"] + return research + + async def get(self, research_id: str, *, timeout: float | None = None) -> dict[str, Any]: + """``GET /v1/shop/agent/research/:id``.""" + data = await self._call( + "GET", f"/v1/shop/agent/research/{quote(research_id, safe='')}", timeout=timeout + ) + research: dict[str, Any] = data["research"] + return research + + +class AsyncDataCalls(_Rest): + """``cs.data_calls`` on :class:`AsyncCodeSpar`.""" + + async def create( + self, *, agent_id: str, offer_id: str, idempotency_key: str, timeout: float | None = None + ) -> DataCallCreated: + """``POST /v1/shop/agent/data-calls``: draft from a ``data_service`` offer. + + Nothing is reserved or sent. + """ + data: DataCallCreated = await self._call( + "POST", + "/v1/shop/agent/data-calls", + body={"agent_id": agent_id, "offer_id": offer_id, "idempotency_key": idempotency_key}, + timeout=timeout, + ) + return data + + async def get(self, proposal_id: str, *, timeout: float | None = None) -> DataCallRead: + """``GET /v1/shop/agent/data-calls/:id``: where it stands, the four states apart. + + An uncertain call is reconciled on this read, never resent: read the same id + again, across restarts, until it is no longer pending. + """ + data: DataCallRead = await self._call( + "GET", f"/v1/shop/agent/data-calls/{quote(proposal_id, safe='')}", timeout=timeout + ) + return data + + async def execute(self, proposal_id: str, *, timeout: float | None = None) -> DataCall: + """``POST /v1/shop/agent/data-calls/:id/execute``: always refused for a key. + + The API answers ``person_required`` (403) with the person's protected action: + ``next_action_of(err)`` reads it from the raised ``ApiError``. + + Raises ``ApiError``; present so the refusal is explicit, never a silent no-op. + """ + await self._call( + "POST", + f"/v1/shop/agent/data-calls/{quote(proposal_id, safe='')}/execute", + timeout=timeout, + ) + raise ApiError( + "data_calls.execute: the API answered a key's run without person_required; " + "refusing to treat it as run", + status=0, + body=None, + ) + + +class Research: + """``cs.research`` on the sync :class:`CodeSpar`.""" + + def __init__(self, inner: AsyncResearch, runner: _LoopRunner) -> None: + self._inner = inner + self._runner = runner + + def create( + self, + query: str, + *, + task_kind: TaskKind | None = None, + criteria: dict[str, Any] | None = None, + timeout: float | None = None, + ) -> dict[str, Any]: + return self._runner.run( + self._inner.create(query, task_kind=task_kind, criteria=criteria, timeout=timeout) + ) + + def get(self, research_id: str, *, timeout: float | None = None) -> dict[str, Any]: + return self._runner.run(self._inner.get(research_id, timeout=timeout)) + + +class DataCalls: + """``cs.data_calls`` on the sync :class:`CodeSpar`.""" + + def __init__(self, inner: AsyncDataCalls, runner: _LoopRunner) -> None: + self._inner = inner + self._runner = runner + + def create( + self, *, agent_id: str, offer_id: str, idempotency_key: str, timeout: float | None = None + ) -> DataCallCreated: + return self._runner.run( + self._inner.create( + agent_id=agent_id, + offer_id=offer_id, + idempotency_key=idempotency_key, + timeout=timeout, + ) + ) + + def get(self, proposal_id: str, *, timeout: float | None = None) -> DataCallRead: + return self._runner.run(self._inner.get(proposal_id, timeout=timeout)) + + def execute(self, proposal_id: str, *, timeout: float | None = None) -> DataCall: + return self._runner.run(self._inner.execute(proposal_id, timeout=timeout)) diff --git a/packages/python/tests/test_data_calls.py b/packages/python/tests/test_data_calls.py new file mode 100644 index 0000000..62d9b92 --- /dev/null +++ b/packages/python/tests/test_data_calls.py @@ -0,0 +1,136 @@ +""" +``cs.research`` and ``cs.data_calls`` parity with the TypeScript facade (Shop G3.1): +the wire each call sends, the API's wire returned as is, a key's ``execute`` +raised as ``person_required`` and never treated as a run, on the async and the +sync client, and the one-word outcome read from the four states. +""" + +from __future__ import annotations + +import json + +import pytest +from pytest_httpx import HTTPXMock + +from codespar import ApiError, AsyncCodeSpar, CodeSpar, data_call_outcome, next_action_of + +BASE = "https://api.codespar.dev" +PID = "prp_AbCdEfGhIjKlMnOp" +OFFER = "sof_AbCdEfGhIjKlMnOp" +URL = f"https://codespar.dev/dashboard/shop/data-calls/{PID}" +NEXT = {"kind": "person_authorization", "url": URL, "proposal_id": PID, "description": "x"} +VIEW = { + "proposal_id": PID, + "run_state": "ready", + "awaiting": None, + "offer": {"offer_id": OFFER, "offer_kind": "data_service", "total_minor": 50}, + "quotation": {"state": "valid", "total_minor": 50}, + "authorization": {"state": "needed", "amount_max_minor": 50}, + "commitment": {"state": "not_started"}, + "payment": {"state": "none"}, + "confirmation": {"state": "none"}, + "actions": {"execute": True, "cancel": True, "requote": False}, +} + + +async def test_research_of_a_data_service_and_a_draft_from_its_offer(httpx_mock: HTTPXMock) -> None: + httpx_mock.add_response( + method="POST", + url=f"{BASE}/v1/shop/agent/research", + json={"research": {"id": "srr_x", "offers": [{"id": OFFER}]}}, + status_code=201, + ) + httpx_mock.add_response( + method="POST", + url=f"{BASE}/v1/shop/agent/data-calls", + json={"data_call": VIEW, "idempotent_replay": False}, + status_code=201, + ) + httpx_mock.add_response( + method="GET", + url=f"{BASE}/v1/shop/agent/data-calls/{PID}", + json={"data_call": VIEW, "next_action": NEXT}, + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + research = await cs.research.create( + "consulta de CNPJ", + task_kind="data_service", + criteria={"data_service": {"params": {"cnpj": "11222333000181"}}}, + ) + created = await cs.data_calls.create( + agent_id="ag_x", offer_id=research["offers"][0]["id"], idempotency_key="idem_x_0001" + ) + read = await cs.data_calls.get(PID) + assert created == {"data_call": VIEW, "idempotent_replay": False} + assert read == {"data_call": VIEW, "next_action": NEXT} + r, d, _ = httpx_mock.get_requests() + assert json.loads(r.content) == { + "query": "consulta de CNPJ", + "task_kind": "data_service", + "criteria": {"data_service": {"params": {"cnpj": "11222333000181"}}}, + } + assert json.loads(d.content) == { + "agent_id": "ag_x", + "offer_id": OFFER, + "idempotency_key": "idem_x_0001", + } + assert d.headers["authorization"] == "Bearer csk_test_x" + + +async def test_a_keys_execute_is_person_required_never_a_run(httpx_mock: HTTPXMock) -> None: + httpx_mock.add_response( + method="POST", + url=f"{BASE}/v1/shop/agent/data-calls/{PID}/execute", + json={ + "error": { + "code": "person_required", + "message": "running a data call is the person's authorization", + "details": {"next_action": NEXT}, + } + }, + status_code=403, + ) + async with AsyncCodeSpar(api_key="csk_test_x") as cs: + with pytest.raises(ApiError) as caught: + await cs.data_calls.execute(PID) + assert caught.value.status == 403 + assert caught.value.code == "person_required" + action = next_action_of(caught.value) + assert action is not None and action["url"] == URL + + +def test_the_sync_client_reads_the_same_wire(httpx_mock: HTTPXMock) -> None: + httpx_mock.add_response( + method="GET", + url=f"{BASE}/v1/shop/agent/data-calls/{PID}", + json={"data_call": VIEW, "next_action": NEXT}, + ) + with CodeSpar(api_key="csk_test_x") as cs: + assert cs.data_calls.get(PID)["data_call"] == VIEW + + +def test_the_outcome_reads_the_four_states_apart() -> None: + assert ( + data_call_outcome( + { + **VIEW, + "confirmation": {"state": "confirmed", "result_ref": "tdr_1"}, + "payment": {"state": "held"}, + } + ) + == "succeeded" + ) + assert ( + data_call_outcome( + {**VIEW, "commitment": {"state": "uncertain"}, "payment": {"state": "debited"}} + ) + == "uncertain" + ) + assert data_call_outcome({**VIEW, "error": {"code": "commitment_terms_changed"}}) == "refused" + assert ( + data_call_outcome( + {**VIEW, "commitment": {"state": "failed"}, "confirmation": {"state": "failed"}} + ) + == "failed" + ) + assert data_call_outcome(VIEW) == "pending" diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index bbeed08..aac95c3 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -1,5 +1,12 @@ # @codespar/types — CHANGELOG +## 0.11.8 — 2026-11-08 + +### Added + +- `DataCall`, `DataCallCreated`, `DataCallCreateInput` and `Session.dataCalls` + (Shop G3.1); `AgentResearchInput.taskKind` and `criteria.dataService`. + ## 0.11.7 — 2026-10-30 ### Added diff --git a/packages/types/package.json b/packages/types/package.json index 683db50..c2c8035 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/types", - "version": "0.11.7", + "version": "0.11.8", "description": "Shared session interface contract for codespar runtimes", "type": "module", "main": "./dist/index.js", diff --git a/packages/types/src/testing/scenario-manifest.ts b/packages/types/src/testing/scenario-manifest.ts index 7646ac2..0217866 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.11.8", /** 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 91cf66e..2544a71 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -236,6 +236,17 @@ export interface Session extends SessionBase { * (`BearerTokenHasNoPersonError` in the SDK). A session bound to a person * (MCP consent by login) arrives with Shop v0.3 increment 5. */ + /** + * Shop G3.1 data calls (`/v1/shop/agent/data-calls`): draft one from a + * `data_service` offer of a research, and read it, the four states apart. + * A key never runs it: `execute` answers `person_required` (403). + * Optional: a runtime without the Shop omits it. + */ + dataCalls?: { + create(input: DataCallCreateInput, opts?: CallOptions): Promise; + get(proposalId: string, opts?: CallOptions): Promise; + execute(proposalId: string, opts?: CallOptions): Promise; + }; instruments?: { list(opts?: { /** @deprecated Ignored by the API since Shop v0.3: it no longer selects another person's cards. */ @@ -267,16 +278,81 @@ export type AgentPurchaseInput = { export interface AgentResearchInput { /** The pedido aberto, 2 to 200 characters. */ query: string; + /** `product` (default), `service_plan`, `reservation`, or `data_service` (a per-call data service, Shop G3.1). */ + taskKind?: "product" | "service_plan" | "reservation" | "data_service"; criteria?: { priority?: "total" | "eta"; /** Shipping included, in centavos. */ maxTotalMinor?: number; - sources?: ("registry" | "vtex" | "meli")[]; + sources?: ("registry" | "vtex" | "meli" | "web" | "data")[]; /** Offers per source, 1 to 5. */ limit?: number; + /** `taskKind: "data_service"`: the call's params, and the provider's SKU when named. */ + dataService?: { params: Record; sku?: string }; }; } +/* ── Shop G3.1 data calls (`/v1/shop/agent/data-calls`) ── */ + +/** A data call as the API answers it (`DataCallView`), the four states apart. */ +export interface DataCall { + proposal_id: string; + run_state: "ready" | "awaiting_user" | "running" | "interrupted" | "completed" | "cancelled"; + awaiting: { reason: string; cause: string | null } | null; + offer: { + offer_id: string; + offer_kind: "data_service"; + merchant_name: string; + title: string; + attributes: { coverage: string; refresh: string; license: string; unit: "call"; params: Record; offer_version: number; terms_hash: string }; + cost_lines: { kind: "call"; label: string; unit_minor: number; quantity: 1; amount_minor: number }[]; + total_minor: number; + currency: "BRL"; + observed_at: string; + valid_until: string; + source: { kind: "data_catalog" }; + }; + quotation: { state: "valid" | "stale" | "changed"; total_minor: number; previous_total_minor?: number; observed_at: string; valid_until: string }; + authorization: { state: "needed" | "awaiting_approval" | "authorized" | "refused" | "expired"; amount_max_minor: number; approval_id?: string; expires_at?: string }; + commitment: { state: "not_started" | "claimed" | "dispatching" | "settled" | "uncertain" | "failed" | "cancelled"; attempt_id?: string; call_id?: string; at?: string }; + payment: { state: "none" | "held" | "debited" | "released"; held_minor?: number; debited_minor?: number; released_minor?: number; receipt_id?: string }; + confirmation: { state: "none" | "pending" | "confirmed" | "failed"; at?: string; source?: string; result_ref?: string }; + /** Why it ended without a call, or was refused: `commitment_terms_changed`, `data_call_refused`, a mandate's or the Wallet's code, ... */ + error?: { code: string; detail?: string }; + actions: { execute: boolean; cancel: boolean; requote: boolean }; +} + +/** + * The protected action while a data call waits for the person (criterion 5): the call's card on the dashboard, + * behind the person's own sign-in. Only the call's id is in the url. Hand it to the person; then read the call by id. + */ +export interface DataCallNextAction { + kind: "person_authorization"; + url: string; + proposal_id: string; + description: string; +} + +/** `GET /v1/shop/agent/data-calls/:id`: the call, and while it waits for the person, the protected action. */ +export interface DataCallRead { + data_call: DataCall; + next_action: DataCallNextAction | null; +} + +/** `POST /v1/shop/agent/data-calls`: the draft, its protected action, and whether the same idempotency key had drafted it already. */ +export interface DataCallCreated extends DataCallRead { + idempotent_replay: boolean; +} + +export interface DataCallCreateInput { + /** The assistant (agent) the draft is made for: its mandate over the provider is the one used. */ + agentId: string; + /** A `data_service` offer of this key's research (`sof_...`). */ + offerId: string; + /** 8 to 128 of `[A-Za-z0-9_.:-]`: the same key answers the same draft. */ + idempotencyKey: string; +} + export interface AgentResearchOffer { id: string; position: number;