From 39d36143e881c7da6de89e672ad6dc13c335d9ac Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Sat, 7 Nov 2026 19:18:36 -0300 Subject: [PATCH 1/9] feat(shop): G3.1 data calls in the SDKs, the CLI and the MCP package MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The core side of Shop G3.1 (CONTRATO-G3 §7A item 2), over the enterprise routes /v1/shop/agent/data-calls (key: draft, read; run is always person_required) and the research's task_kind data_service. - TS: cs.dataCalls / session.dataCalls (create, get, execute) and dataCallOutcome; session.research.create takes taskKind and criteria.dataService. Types in @codespar/types. - Python: cs.research and cs.data_calls (async and sync) with data_call_outcome; the same names and states. - CLI: derived shop create-data-calls / get-data-calls / data-calls-execute; these commands exit with the outcome (0 confirmed, 10 pending, 20 refused, 30 failure, 40 uncertain); every other command keeps exit 1. - MCP package: codespar_shop_data_call_draft / _status and the data_service research; no run tool. - OpenAPI snapshot: the three data-call operations and the research body, from the enterprise routes (served once deployed). Co-Authored-By: Claude Opus 5.5 --- packages/cli/CHANGELOG.md | 10 + packages/cli/src/__tests__/exit-codes.test.ts | 55 + .../src/__tests__/resource-commands.test.ts | 3 + packages/cli/src/commands/resource.ts | 9 + packages/cli/src/exit-codes.ts | 66 + packages/cli/src/index.ts | 5 +- packages/core/CHANGELOG.md | 17 + packages/core/openapi-snapshot.json | 1848 ++++++++++++++++- .../core/src/__tests__/data-calls.test.ts | 99 + packages/core/src/data-calls.ts | 107 + packages/core/src/generated/openapi.ts | 676 +++++- packages/core/src/generated/operations.ts | 5 +- packages/core/src/index.ts | 23 + packages/core/src/session.ts | 7 +- packages/mcp/CHANGELOG.md | 8 + .../src/__tests__/shop-purchase-tools.test.ts | 28 + packages/mcp/src/shop-purchase-tools.ts | 69 +- packages/python/CHANGELOG.md | 9 + packages/python/src/codespar/__init__.py | 16 + packages/python/src/codespar/_async_client.py | 6 + packages/python/src/codespar/_sync_client.py | 6 + packages/python/src/codespar/data_calls.py | 244 +++ packages/python/tests/test_data_calls.py | 127 ++ packages/types/CHANGELOG.md | 7 + packages/types/src/types.ts | 61 +- 25 files changed, 3495 insertions(+), 16 deletions(-) create mode 100644 packages/cli/src/__tests__/exit-codes.test.ts create mode 100644 packages/cli/src/exit-codes.ts create mode 100644 packages/core/src/__tests__/data-calls.test.ts create mode 100644 packages/core/src/data-calls.ts create mode 100644 packages/python/src/codespar/data_calls.py create mode 100644 packages/python/tests/test_data_calls.py diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 2c95af2c..53873e4a 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,5 +1,15 @@ # @codespar/cli — changelog +## Unreleased + +### 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. + ## 0.22.6 — 2026-11-01 ### Fixed 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 00000000..58866e7c --- /dev/null +++ b/packages/cli/src/__tests__/exit-codes.test.ts @@ -0,0 +1,55 @@ +/** + * 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, 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); + }); +}); diff --git a/packages/cli/src/__tests__/resource-commands.test.ts b/packages/cli/src/__tests__/resource-commands.test.ts index b0cf5c17..1c566ab6 100644 --- a/packages/cli/src/__tests__/resource-commands.test.ts +++ b/packages/cli/src/__tests__/resource-commands.test.ts @@ -168,6 +168,9 @@ 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 instruments → GET /v1/shop/agent/instruments", "collect list-links → GET /v1/collect/links", "collect create-links → POST /v1/collect/links", diff --git a/packages/cli/src/commands/resource.ts b/packages/cli/src/commands/resource.ts index 22ea89ae..881f5861 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,6 +119,9 @@ 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; diff --git a/packages/cli/src/exit-codes.ts b/packages/cli/src/exit-codes.ts new file mode 100644 index 00000000..26150305 --- /dev/null +++ b/packages/cli/src/exit-codes.ts @@ -0,0 +1,66 @@ +/** + * 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, 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; + } +} + +/** 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 a01db25b..26372bbf 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 { exitCodeForFailure, outcomeExitCodesOn } from "./exit-codes.js"; import { payablesBatchCreateCommand, payablesBatchGetCommand, @@ -1021,12 +1022,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 4914bb54..3e514bc3 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,22 @@ # @codespar/sdk — CHANGELOG +## Unreleased + +### 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 three data-call operations and the research body with + `task_kind`, from the enterprise routes of Shop G3.1 (served once they are + deployed; `spec:check` compares the served document then). + ## 0.16.28 — 2026-10-30 ### Added diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index 6a4b761f..8a942839 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-10-31T00:54:41.356Z", - "sha256": "4ae3274e16aa0655cacab1b3a1f0c1fbe8ad710fe2c0184c9b0aa816fdd0095c", + "fetched_at": "2026-11-07T22:14:34.465Z", + "sha256": "e663353c1254c82455e896a78160504feee3e39654456d7e0a869aa02a67fb58", "etag": null, "last_modified": null, "info": { "title": "CodeSpar AgentGate API", "version": "0.3.0" }, - "paths": 317, - "operations": 373, + "paths": 320, + "operations": 376, "generator": "openapi-typescript@7.13.0" }, "document": { @@ -110547,6 +110547,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": { @@ -110571,18 +110581,176 @@ "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)." + }, + "reservation": { + "type": "object", + "properties": { + "check_in": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$", + "description": "Check-in day, YYYY-MM-DD (São Paulo)." + }, + "check_out": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$", + "description": "Check-out day, YYYY-MM-DD, after check_in." + }, + "occupants": { + "type": "object", + "properties": { + "adults": { + "type": "integer", + "minimum": 1, + "maximum": 10 + }, + "children": { + "type": "integer", + "minimum": 0, + "maximum": 10 + } + }, + "required": [ + "adults" + ], + "additionalProperties": false + }, + "location": { + "type": "string", + "minLength": 2, + "maxLength": 120, + "description": "Where, as the person said it." + } + }, + "required": [ + "check_in", + "check_out", + "occupants" + ], + "additionalProperties": false, + "description": "task_kind reservation: check_in, check_out, occupants, location." + }, + "service_plan": { + "type": "object", + "properties": { + "licenses": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "description": "How many seats or licenses." + }, + "period": { + "type": "string", + "enum": [ + "monthly", + "annual" + ], + "description": "The billing period to compare on." + } + }, + "required": [ + "licenses", + "period" + ], + "additionalProperties": false, + "description": "task_kind service_plan: licenses and period." + }, + "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." + } + }, + "required": [ + "params" + ], + "additionalProperties": false, + "description": "task_kind data_service: the call's params, and the SKU when the person named one." + }, + "required": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "free_cancellation", + "breakfast_included", + "invoice", + "refundable", + "location" + ] + }, + "maxItems": 5, + "description": "Conditions an offer must state to be compared: an offer that does not state one is left out, with the reason." + } + }, + "additionalProperties": false + }, + "sources": { + "type": "object", + "properties": { + "groups": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "registry", + "vtex", + "meli", + "web", + "data" + ] + }, + "minItems": 1, + "maxItems": 5 + }, + "origins": { + "type": "array", + "items": { + "type": "object", + "properties": { + "origin": { + "type": "string", + "maxLength": 300, + "description": "https://host of a site to consult, as the person or you named it." + }, + "start_path": { + "type": "string", + "maxLength": 200, + "description": "The path to start at; default /." + } + }, + "required": [ + "origin" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 5 } }, "additionalProperties": false @@ -110917,6 +111085,1672 @@ ] } }, + "/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 (`POST .../execute` answers `person_required`). 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", + "enum": [ + "commitment_terms_changed", + "offer_stale", + "data_call_refused", + "data_provider_unavailable" + ] + }, + "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" + ] + }, + "idempotent_replay": { + "type": "boolean" + } + }, + "required": [ + "data_call", + "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", + "enum": [ + "commitment_terms_changed", + "offer_stale", + "data_call_refused", + "data_provider_unavailable" + ] + }, + "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" + ] + }, + "idempotent_replay": { + "type": "boolean" + } + }, + "required": [ + "data_call", + "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, or the project is not a Test one.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "proposal_no_mandate", + "data_call_live_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" + ] + } + } + } + }, + "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.\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", + "enum": [ + "commitment_terms_changed", + "offer_stale", + "data_call_refused", + "data_provider_unavailable" + ] + }, + "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" + ] + } + }, + "required": [ + "data_call" + ] + } + } + } + }, + "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); the person runs the call in the Shop (Executar consulta) or through an MCP client with their login.\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.", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "person_required" + ] + }, + "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/instruments": { "get": { "summary": "The calling person's cards, masked", 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 00000000..4826e651 --- /dev/null +++ b/packages/core/src/__tests__/data-calls.test.ts @@ -0,0 +1,99 @@ +/** + * 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 { 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 cs = client((url) => (url.endsWith("/data-calls") ? { status: 201, body: { data_call: VIEW, idempotent_replay: false } } : { status: 200, body: { data_call: VIEW } }), 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, 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(VIEW); + 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 as an error, never as a run", async () => { + const seen: { url: string; method: string; body: unknown; auth: string | null }[] = []; + const cs = client(() => ({ status: 403, body: { error: { code: "person_required", message: "running a data call is the person's authorization" } } }), seen); + const err = await cs.dataCalls.execute(VIEW.proposal_id).catch((e: unknown) => e); + expect(err).toBeInstanceOf(CodesparApiError); + 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 00000000..7719fe1f --- /dev/null +++ b/packages/core/src/data-calls.ts @@ -0,0 +1,107 @@ +/** + * `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 } from "@codespar/types"; +import type { CallOptions } from "./types.js"; + +export type { DataCall, DataCallCreated, DataCallCreateInput }; + +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. */ + get(proposalId: string, opts?: CallOptions): Promise; + /** + * `POST /v1/shop/agent/data-calls/:id/execute`: always refused for a key (`person_required`, 403), thrown as + * `CodesparApiError`. 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) { + const r = await call<{ data_call: DataCall }>("dataCalls.get", one(proposalId), { method: "GET", headers: { ...auth, Accept: "application/json" } }, opts); + return r.data_call; + }, + async execute(proposalId, opts) { + await call("dataCalls.execute", `${one(proposalId)}/execute`, { method: "POST", headers: { ...auth, Accept: "application/json" } }, opts); + // 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 23f13d00..9abe6d2e 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 4ae3274e16aa0655cacab1b3a1f0c1fbe8ad710fe2c0184c9b0aa816fdd0095c, fetched 2026-10-31T00:54:41.356Z +// Source: openapi-snapshot.json (sha256 e663353c1254c82455e896a78160504feee3e39654456d7e0a869aa02a67fb58, fetched 2026-11-07T22:14:34.465Z // from https://api.codespar.dev/openapi.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { @@ -45777,6 +45777,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. @@ -45785,10 +45790,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; + }[]; }; }; }; @@ -45975,6 +46023,628 @@ 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 (`POST .../execute` answers `person_required`). 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?: { + /** @enum {string} */ + code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; + detail?: string; + }; + actions: { + execute: boolean; + cancel: boolean; + requote: boolean; + }; + }; + 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?: { + /** @enum {string} */ + code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; + detail?: string; + }; + actions: { + execute: boolean; + cancel: boolean; + requote: boolean; + }; + }; + 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, or the project is not a Test one. */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + error: { + /** @enum {string} */ + code: "proposal_no_mandate" | "data_call_live_unavailable"; + message: string; + details?: { + [key: string]: unknown; + }; + }; + /** @description Echoes the `X-Request-Id` header when the request carried one. */ + request_id: string | null; + }; + }; + }; + /** @description The 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. + * + * **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?: { + /** @enum {string} */ + code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; + detail?: string; + }; + actions: { + execute: boolean; + cancel: boolean; + requote: boolean; + }; + }; + }; + }; + }; + /** @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); the person runs the call in the Shop (Executar consulta) or through an MCP client with their login. + * + * **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. */ + 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; + }; + }; + }; + }; + }; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/v1/shop/agent/instruments": { parameters: { query?: never; diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index ec863a66..793292d9 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 4ae3274e16aa0655cacab1b3a1f0c1fbe8ad710fe2c0184c9b0aa816fdd0095c, fetched 2026-10-31T00:54:41.356Z +// Source: openapi-snapshot.json (sha256 e663353c1254c82455e896a78160504feee3e39654456d7e0a869aa02a67fb58, fetched 2026-11-07T22:14:34.465Z // 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"; @@ -325,6 +325,9 @@ 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/instruments", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "get", path: "/v1/projects", body: null, accept: "application/json", requiredQuery: [], deprecated: false }, { method: "post", path: "/v1/projects", body: "application/json", accept: "application/json", requiredQuery: [], deprecated: false }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c8305b0b..581a86e0 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 } from "./data-calls.js"; +export type { DataCall, DataCallCreated, DataCallCreateInput, DataCallOutcome, 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 8ed779af..135bfb7f 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 1432055f..0d7d8fe0 100644 --- a/packages/mcp/CHANGELOG.md +++ b/packages/mcp/CHANGELOG.md @@ -1,5 +1,13 @@ # @codespar/mcp — changelog +## Unreleased + +### 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/src/__tests__/shop-purchase-tools.test.ts b/packages/mcp/src/__tests__/shop-purchase-tools.test.ts index ac465233..7075c700 100644 --- a/packages/mcp/src/__tests__/shop-purchase-tools.test.ts +++ b/packages/mcp/src/__tests__/shop-purchase-tools.test.ts @@ -12,6 +12,8 @@ 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_status", "codespar_shop_research_status", "codespar_shop_purchase_status", "codespar_shop_instruments", @@ -85,4 +87,30 @@ 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 new Error("never called"); + }, + }, + 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); + }); }); diff --git a/packages/mcp/src/shop-purchase-tools.ts b/packages/mcp/src/shop-purchase-tools.ts index 0d3c0ff7..749f8e94 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,50 @@ 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_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 +198,31 @@ 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_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 b887fd56..44ab1aae 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 adce1a10..0162b8d9 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -29,6 +29,15 @@ from ._async_client import AsyncCodeSpar from ._async_session import AsyncSession from ._sync_client import CodeSpar, Session +from .data_calls import ( + AsyncDataCalls, + AsyncResearch, + DataCall, + DataCallCreated, + DataCalls, + Research, + data_call_outcome, +) from .documents import ( Account, AsyncAccount, @@ -204,8 +213,10 @@ "AssistantTextEvent", "AsyncAccount", "AsyncCodeSpar", + "AsyncDataCalls", "AsyncPayables", "AsyncReceipts", + "AsyncResearch", "AsyncSession", "AsyncWallet", "AsyncWalletPixKeys", @@ -229,6 +240,9 @@ "ConnectionWizardInstructions", "ConnectionWizardOptions", "ConnectionWizardResult", + "DataCall", + "DataCallCreated", + "DataCalls", # Tool discovery (codespar_discover) "DiscoverOptions", "DiscoverPlanStep", @@ -296,6 +310,7 @@ "ReceiptQuote", "Receipts", "RequiredSecret", + "Research", "SearchStrategy", "SendResult", "ServerConnection", @@ -351,6 +366,7 @@ # Version "__version__", "assert_exhaustive_tool_result", + "data_call_outcome", "filename_from_disposition", "is_approval_required", "is_mocks_engine_error", diff --git a/packages/python/src/codespar/_async_client.py b/packages/python/src/codespar/_async_client.py index 2c5cdcc0..09a5d95c 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 086e9805..f0ed26f0 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 00000000..459135bb --- /dev/null +++ b/packages/python/src/codespar/data_calls.py @@ -0,0 +1,244 @@ +""" +``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 DataCallCreated(TypedDict): + """``POST /v1/shop/agent/data-calls``.""" + + data_call: DataCall + idempotent_replay: bool + + +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) -> DataCall: + """``GET /v1/shop/agent/data-calls/:id``: where it stands, the four states apart.""" + data = await self._call( + "GET", f"/v1/shop/agent/data-calls/{quote(proposal_id, safe='')}", timeout=timeout + ) + call: DataCall = data["data_call"] + return call + + 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). + + 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) -> DataCall: + 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 00000000..e4f17dd4 --- /dev/null +++ b/packages/python/tests/test_data_calls.py @@ -0,0 +1,127 @@ +""" +``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 + +BASE = "https://api.codespar.dev" +PID = "prp_AbCdEfGhIjKlMnOp" +OFFER = "sof_AbCdEfGhIjKlMnOp" +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} + ) + 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 == VIEW + 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", + } + }, + 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" + + +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} + ) + with CodeSpar(api_key="csk_test_x") as cs: + assert cs.data_calls.get(PID) == 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 bbeed086..5e6ccac9 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -1,5 +1,12 @@ # @codespar/types — CHANGELOG +## Unreleased + +### 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/src/types.ts b/packages/types/src/types.ts index 91cf66e2..27d0e73f 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,64 @@ 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 }; + error?: { code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; detail?: string }; + actions: { execute: boolean; cancel: boolean; requote: boolean }; +} + +/** `POST /v1/shop/agent/data-calls`: the draft, and whether the same idempotency key had drafted it already. */ +export interface DataCallCreated { + data_call: DataCall; + 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; From 8a25f4ac012d5167efdb79a8cb99e8dc2beebf57 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Sat, 7 Nov 2026 20:10:53 -0300 Subject: [PATCH 2/9] fix(shop): a data call's error code is any failure code, as the API answers it The API's view follows lane B's state map: error.code names the provider's, the mandate's or the Wallet's code. The snapshot picks up the draft route's 409 idempotency_key_reused. Co-Authored-By: Claude Opus 5.5 --- packages/core/openapi-snapshot.json | 30 ++++++----------------- packages/core/src/generated/openapi.ts | 18 +++++++------- packages/core/src/generated/operations.ts | 2 +- packages/types/src/types.ts | 3 ++- 4 files changed, 20 insertions(+), 33 deletions(-) diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index 8a942839..3e5eaf88 100644 --- a/packages/core/openapi-snapshot.json +++ b/packages/core/openapi-snapshot.json @@ -1,8 +1,8 @@ { "snapshot": { "source": "https://api.codespar.dev/openapi.json", - "fetched_at": "2026-11-07T22:14:34.465Z", - "sha256": "e663353c1254c82455e896a78160504feee3e39654456d7e0a869aa02a67fb58", + "fetched_at": "2026-11-07T22:49:28.730Z", + "sha256": "84e5aabf9ee26b8d2fafcff96e9cbb1eb81e0bde785a866c35758c9a61bb5a4f", "etag": null, "last_modified": null, "info": { @@ -111457,12 +111457,7 @@ "properties": { "code": { "type": "string", - "enum": [ - "commitment_terms_changed", - "offer_stale", - "data_call_refused", - "data_provider_unavailable" - ] + "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" @@ -111853,12 +111848,7 @@ "properties": { "code": { "type": "string", - "enum": [ - "commitment_terms_changed", - "offer_stale", - "data_call_refused", - "data_provider_unavailable" - ] + "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" @@ -112046,7 +112036,7 @@ } }, "409": { - "description": "No mandate permits the provider, or the project is not a Test one.", + "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": { @@ -112059,7 +112049,8 @@ "type": "string", "enum": [ "proposal_no_mandate", - "data_call_live_unavailable" + "data_call_live_unavailable", + "idempotency_key_reused" ] }, "message": { @@ -112548,12 +112539,7 @@ "properties": { "code": { "type": "string", - "enum": [ - "commitment_terms_changed", - "offer_stale", - "data_call_refused", - "data_provider_unavailable" - ] + "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" diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index 9abe6d2e..b4fb4cac 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 e663353c1254c82455e896a78160504feee3e39654456d7e0a869aa02a67fb58, fetched 2026-11-07T22:14:34.465Z +// Source: openapi-snapshot.json (sha256 84e5aabf9ee26b8d2fafcff96e9cbb1eb81e0bde785a866c35758c9a61bb5a4f, fetched 2026-11-07T22:49:28.730Z // from https://api.codespar.dev/openapi.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { @@ -46156,8 +46156,8 @@ export interface paths { result_ref?: string; }; error?: { - /** @enum {string} */ - code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; + /** @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: { @@ -46270,8 +46270,8 @@ export interface paths { result_ref?: string; }; error?: { - /** @enum {string} */ - code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; + /** @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: { @@ -46343,7 +46343,7 @@ export interface paths { }; }; }; - /** @description No mandate permits the provider, or the project is not a Test one. */ + /** @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; @@ -46352,7 +46352,7 @@ export interface paths { "application/json": { error: { /** @enum {string} */ - code: "proposal_no_mandate" | "data_call_live_unavailable"; + code: "proposal_no_mandate" | "data_call_live_unavailable" | "idempotency_key_reused"; message: string; details?: { [key: string]: unknown; @@ -46536,8 +46536,8 @@ export interface paths { result_ref?: string; }; error?: { - /** @enum {string} */ - code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; + /** @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: { diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index 793292d9..0b38f07b 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 e663353c1254c82455e896a78160504feee3e39654456d7e0a869aa02a67fb58, fetched 2026-11-07T22:14:34.465Z +// Source: openapi-snapshot.json (sha256 84e5aabf9ee26b8d2fafcff96e9cbb1eb81e0bde785a866c35758c9a61bb5a4f, fetched 2026-11-07T22:49:28.730Z // 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"; diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index 27d0e73f..ccefe499 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -317,7 +317,8 @@ export interface DataCall { 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 }; - error?: { code: "commitment_terms_changed" | "offer_stale" | "data_call_refused" | "data_provider_unavailable"; detail?: 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 }; } From 9a5a4e09458306ecddd7dcd544a6e7db2f45c7fe Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Sun, 8 Nov 2026 00:25:02 -0300 Subject: [PATCH 3/9] feat(shop): criterion 5, the external client offers the person's protected action and resumes by id A key still never runs a data call; the API's person_required now carries next_action (the call's card on the dashboard, behind the person's sign-in, only the id in the url). - TS: execute throws DataCallNeedsPersonError with nextAction; nextActionOfError; get answers { data_call, next_action } (create too). - Python: next_action_of(ApiError); get answers the same read. - CLI: a data-call command refused with the protected action exits 10 (pending) and prints the url; create/get print it while pending. - MCP package: codespar_shop_data_call_request_authorization answers the link for the person; still no tool runs a call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Baaitxfwpx5yJ8xhz6nNhT --- packages/cli/src/__tests__/exit-codes.test.ts | 19 +++++- packages/cli/src/commands/resource.ts | 3 + packages/cli/src/exit-codes.ts | 11 +++- packages/cli/src/index.ts | 10 ++- .../core/src/__tests__/data-calls.test.ts | 25 ++++++-- packages/core/src/data-calls.ts | 48 ++++++++++++--- packages/core/src/index.ts | 4 +- .../src/__tests__/shop-purchase-tools.test.ts | 8 ++- packages/mcp/src/shop-purchase-tools.ts | 30 +++++++++ packages/python/src/codespar/__init__.py | 6 ++ packages/python/src/codespar/data_calls.py | 61 ++++++++++++++++--- packages/python/tests/test_data_calls.py | 19 ++++-- packages/types/src/types.ts | 22 ++++++- 13 files changed, 228 insertions(+), 38 deletions(-) diff --git a/packages/cli/src/__tests__/exit-codes.test.ts b/packages/cli/src/__tests__/exit-codes.test.ts index 58866e7c..46d6208c 100644 --- a/packages/cli/src/__tests__/exit-codes.test.ts +++ b/packages/cli/src/__tests__/exit-codes.test.ts @@ -4,7 +4,7 @@ * uses them; every other command keeps exit 1 for any failure. */ import { afterEach, describe, expect, it } from "vitest"; -import { EXIT, exitCodeForDataCall, exitCodeForFailure, outcomeExitCodesOn, resetExitPolicy, useOutcomeExitCodes } from "../exit-codes.js"; +import { EXIT, exitCodeForDataCall, exitCodeForFailure, outcomeExitCodesOn, pendingOnPerson, resetExitPolicy, useOutcomeExitCodes } from "../exit-codes.js"; afterEach(() => resetExitPolicy()); @@ -53,3 +53,20 @@ describe("exit codes of a failure", () => { 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/commands/resource.ts b/packages/cli/src/commands/resource.ts index 881f5861..3cc1562b 100644 --- a/packages/cli/src/commands/resource.ts +++ b/packages/cli/src/commands/resource.ts @@ -128,4 +128,7 @@ export async function runResourceCommand( } 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 index 26150305..244ee534 100644 --- a/packages/cli/src/exit-codes.ts +++ b/packages/cli/src/exit-codes.ts @@ -13,7 +13,7 @@ * 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, type DataCall } from "@codespar/sdk"; +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; @@ -52,6 +52,15 @@ export function exitCodeForDataCall(view: DataCall): number { } } +/** + * 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; diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 26372bbf..280be57a 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -43,7 +43,7 @@ import { showMetaToolCommand, } from "./commands/meta-tool.js"; import { runResourceCommand } from "./commands/resource.js"; -import { exitCodeForFailure, outcomeExitCodesOn } from "./exit-codes.js"; +import { EXIT, exitCodeForFailure, outcomeExitCodesOn, pendingOnPerson } from "./exit-codes.js"; import { payablesBatchCreateCommand, payablesBatchGetCommand, @@ -1012,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) { diff --git a/packages/core/src/__tests__/data-calls.test.ts b/packages/core/src/__tests__/data-calls.test.ts index 4826e651..6f8cca45 100644 --- a/packages/core/src/__tests__/data-calls.test.ts +++ b/packages/core/src/__tests__/data-calls.test.ts @@ -7,7 +7,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { CodeSpar } from "../index.js"; import { CodesparApiError } from "../errors.js"; -import { dataCallOutcome, type DataCall } from "../data-calls.js"; +import { DataCallNeedsPersonError, dataCallOutcome, type DataCall } from "../data-calls.js"; const originalFetch = globalThis.fetch; afterEach(() => { @@ -53,9 +53,13 @@ function client(answer: (url: string, init: RequestInit) => { status: number; bo 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 cs = client((url) => (url.endsWith("/data-calls") ? { status: 201, body: { data_call: VIEW, idempotent_replay: false } } : { status: 200, body: { data_call: VIEW } }), seen); + 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, idempotent_replay: false }); + 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", @@ -63,15 +67,24 @@ describe("cs.dataCalls", () => { auth: "Bearer csk_test_example", }); const read = await cs.dataCalls.get(VIEW.proposal_id); - expect(read).toEqual(VIEW); + 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 as an error, never as a run", async () => { + 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 cs = client(() => ({ status: 403, body: { error: { code: "person_required", message: "running a data call is the person's authorization" } } }), seen); + 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" }); diff --git a/packages/core/src/data-calls.ts b/packages/core/src/data-calls.ts index 7719fe1f..0ac62dc9 100644 --- a/packages/core/src/data-calls.ts +++ b/packages/core/src/data-calls.ts @@ -18,10 +18,32 @@ import { CodesparApiError, networkErrorToApiError, throwFromResponse, TimeoutError } from "./errors.js"; import { fetchWithTimeout } from "./internal/fetch.js"; -import type { DataCall, DataCallCreated, DataCallCreateInput } from "@codespar/types"; +import type { DataCall, DataCallCreated, DataCallCreateInput, DataCallNextAction, DataCallRead } from "@codespar/types"; import type { CallOptions } from "./types.js"; -export type { DataCall, DataCallCreated, DataCallCreateInput }; +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; @@ -51,11 +73,15 @@ export function dataCallOutcome(d: DataCall): DataCallOutcome { 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. */ - get(proposalId: string, opts?: CallOptions): Promise; /** - * `POST /v1/shop/agent/data-calls/:id/execute`: always refused for a key (`person_required`, 403), thrown as - * `CodesparApiError`. Present so the refusal is explicit, never a silent no-op. + * `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; } @@ -95,11 +121,15 @@ export function createDataCalls(deps: DataCallsDeps): DataCalls { ); }, async get(proposalId, opts) { - const r = await call<{ data_call: DataCall }>("dataCalls.get", one(proposalId), { method: "GET", headers: { ...auth, Accept: "application/json" } }, opts); - return r.data_call; + return call("dataCalls.get", one(proposalId), { method: "GET", headers: { ...auth, Accept: "application/json" } }, opts); }, async execute(proposalId, opts) { - await call("dataCalls.execute", `${one(proposalId)}/execute`, { method: "POST", headers: { ...auth, Accept: "application/json" } }, 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/index.ts b/packages/core/src/index.ts index 581a86e0..b7503ef9 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -70,8 +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 } from "./data-calls.js"; -export type { DataCall, DataCallCreated, DataCallCreateInput, DataCallOutcome, DataCalls } from "./data-calls.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"; diff --git a/packages/mcp/src/__tests__/shop-purchase-tools.test.ts b/packages/mcp/src/__tests__/shop-purchase-tools.test.ts index 7075c700..22c30ebe 100644 --- a/packages/mcp/src/__tests__/shop-purchase-tools.test.ts +++ b/packages/mcp/src/__tests__/shop-purchase-tools.test.ts @@ -13,6 +13,7 @@ describe("Shop purchase MCP tools", () => { "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", @@ -99,7 +100,10 @@ describe("Shop purchase MCP tools", () => { 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 new Error("never called"); + 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 () => ({}) }, @@ -112,5 +116,7 @@ describe("Shop purchase MCP tools", () => { 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 749f8e94..e0823389 100644 --- a/packages/mcp/src/shop-purchase-tools.ts +++ b/packages/mcp/src/shop-purchase-tools.ts @@ -110,6 +110,19 @@ export const SHOP_PURCHASE_MCP_TOOLS: readonly McpToolDefinition[] = [ }, }, }, + { + 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: @@ -220,6 +233,23 @@ export async function callShopPurchaseTool(session: Session, name: string, args: 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 ?? "")); diff --git a/packages/python/src/codespar/__init__.py b/packages/python/src/codespar/__init__.py index 0162b8d9..bd0d8ac0 100644 --- a/packages/python/src/codespar/__init__.py +++ b/packages/python/src/codespar/__init__.py @@ -34,9 +34,12 @@ AsyncResearch, DataCall, DataCallCreated, + DataCallNextAction, + DataCallRead, DataCalls, Research, data_call_outcome, + next_action_of, ) from .documents import ( Account, @@ -242,6 +245,8 @@ "ConnectionWizardResult", "DataCall", "DataCallCreated", + "DataCallNextAction", + "DataCallRead", "DataCalls", # Tool discovery (codespar_discover) "DiscoverOptions", @@ -373,5 +378,6 @@ "is_mocks_exhausted", "is_policy_denied", "is_tool_not_mocked", + "next_action_of", "payable_batch_from_error", ] diff --git a/packages/python/src/codespar/data_calls.py b/packages/python/src/codespar/data_calls.py index 459135bb..3e0d3fcb 100644 --- a/packages/python/src/codespar/data_calls.py +++ b/packages/python/src/codespar/data_calls.py @@ -70,13 +70,52 @@ class DataCall(TypedDict, total=False): actions: dict[str, bool] -class DataCallCreated(TypedDict): - """``POST /v1/shop/agent/data-calls``.""" +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") @@ -167,18 +206,22 @@ async def create( ) return data - async def get(self, proposal_id: str, *, timeout: float | None = None) -> DataCall: - """``GET /v1/shop/agent/data-calls/:id``: where it stands, the four states apart.""" - data = await self._call( + 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 ) - call: DataCall = data["data_call"] - return call + 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). + 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. """ @@ -237,7 +280,7 @@ def create( ) ) - def get(self, proposal_id: str, *, timeout: float | None = None) -> DataCall: + 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: diff --git a/packages/python/tests/test_data_calls.py b/packages/python/tests/test_data_calls.py index e4f17dd4..62d9b920 100644 --- a/packages/python/tests/test_data_calls.py +++ b/packages/python/tests/test_data_calls.py @@ -12,11 +12,13 @@ import pytest from pytest_httpx import HTTPXMock -from codespar import ApiError, AsyncCodeSpar, CodeSpar, data_call_outcome +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", @@ -45,7 +47,9 @@ async def test_research_of_a_data_service_and_a_draft_from_its_offer(httpx_mock: status_code=201, ) httpx_mock.add_response( - method="GET", url=f"{BASE}/v1/shop/agent/data-calls/{PID}", json={"data_call": VIEW} + 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( @@ -58,7 +62,7 @@ async def test_research_of_a_data_service_and_a_draft_from_its_offer(httpx_mock: ) read = await cs.data_calls.get(PID) assert created == {"data_call": VIEW, "idempotent_replay": False} - assert read == VIEW + assert read == {"data_call": VIEW, "next_action": NEXT} r, d, _ = httpx_mock.get_requests() assert json.loads(r.content) == { "query": "consulta de CNPJ", @@ -81,6 +85,7 @@ async def test_a_keys_execute_is_person_required_never_a_run(httpx_mock: HTTPXMo "error": { "code": "person_required", "message": "running a data call is the person's authorization", + "details": {"next_action": NEXT}, } }, status_code=403, @@ -90,14 +95,18 @@ async def test_a_keys_execute_is_person_required_never_a_run(httpx_mock: HTTPXMo 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} + 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) == VIEW + assert cs.data_calls.get(PID)["data_call"] == VIEW def test_the_outcome_reads_the_four_states_apart() -> None: diff --git a/packages/types/src/types.ts b/packages/types/src/types.ts index ccefe499..2544a717 100644 --- a/packages/types/src/types.ts +++ b/packages/types/src/types.ts @@ -244,7 +244,7 @@ export interface Session extends SessionBase { */ dataCalls?: { create(input: DataCallCreateInput, opts?: CallOptions): Promise; - get(proposalId: string, opts?: CallOptions): Promise; + get(proposalId: string, opts?: CallOptions): Promise; execute(proposalId: string, opts?: CallOptions): Promise; }; instruments?: { @@ -322,9 +322,25 @@ export interface DataCall { actions: { execute: boolean; cancel: boolean; requote: boolean }; } -/** `POST /v1/shop/agent/data-calls`: the draft, and whether the same idempotency key had drafted it already. */ -export interface DataCallCreated { +/** + * 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; } From 521ac5067d075adf251d03c9ab40b8d5ecc1aa8a Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Sun, 8 Nov 2026 00:49:18 -0300 Subject: [PATCH 4/9] chore(sdk): the snapshot carries next_action on the data-call key routes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Baaitxfwpx5yJ8xhz6nNhT --- packages/core/openapi-snapshot.json | 128 ++++++++++++++++++++-- packages/core/src/generated/openapi.ts | 46 +++++++- packages/core/src/generated/operations.ts | 2 +- 3 files changed, 163 insertions(+), 13 deletions(-) diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index 3e5eaf88..ec89d6a1 100644 --- a/packages/core/openapi-snapshot.json +++ b/packages/core/openapi-snapshot.json @@ -1,8 +1,8 @@ { "snapshot": { "source": "https://api.codespar.dev/openapi.json", - "fetched_at": "2026-11-07T22:49:28.730Z", - "sha256": "84e5aabf9ee26b8d2fafcff96e9cbb1eb81e0bde785a866c35758c9a61bb5a4f", + "fetched_at": "2026-11-08T03:49:09.330Z", + "sha256": "5495b828036f355738c4b07d426b7e2b15208b9005d6c0324f621d79956348e3", "etag": null, "last_modified": null, "info": { @@ -111088,7 +111088,7 @@ "/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 (`POST .../execute` answers `person_required`). 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`.", + "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 id is 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": { @@ -111500,12 +111500,43 @@ "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 id is 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" ] } @@ -111891,12 +111922,43 @@ "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 id is 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" ] } @@ -112189,7 +112251,7 @@ "/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.\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`.", + "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": { @@ -112581,10 +112643,41 @@ "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 id is in it." + }, + "proposal_id": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "kind", + "url", + "proposal_id", + "description" + ] } }, "required": [ - "data_call" + "data_call", + "next_action" ] } } @@ -112667,7 +112760,7 @@ "/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); the person runs the call in the Shop (Executar consulta) or through an MCP client with their login.\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`.", + "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": { @@ -112682,7 +112775,7 @@ ], "responses": { "403": { - "description": "A key never runs a data call.", + "description": "A key never runs a data call; `details.next_action` is the person's way.", "content": { "application/json": { "schema": { @@ -112725,6 +112818,27 @@ } } } + }, + "404": { + "description": "Not Found", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string", + "enum": [ + "not_found" + ] + } + }, + "required": [ + "error" + ] + } + } + } } }, "x-codespar-scope": "shop:purchases:write", diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index b4fb4cac..9471ef05 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 84e5aabf9ee26b8d2fafcff96e9cbb1eb81e0bde785a866c35758c9a61bb5a4f, fetched 2026-11-07T22:49:28.730Z +// Source: openapi-snapshot.json (sha256 5495b828036f355738c4b07d426b7e2b15208b9005d6c0324f621d79956348e3, fetched 2026-11-08T03:49:09.330Z // from https://api.codespar.dev/openapi.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { @@ -46034,7 +46034,7 @@ export interface paths { 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 (`POST .../execute` answers `person_required`). Test projects only. + * @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 id is 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`. */ @@ -46166,6 +46166,14 @@ export interface paths { 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 id is in it. */ + url: string; + proposal_id: string; + description: string; + } | null; idempotent_replay: boolean; }; }; @@ -46280,6 +46288,14 @@ export interface paths { 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 id is in it. */ + url: string; + proposal_id: string; + description: string; + } | null; idempotent_replay: boolean; }; }; @@ -46420,7 +46436,7 @@ export interface paths { }; /** * 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. + * @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`. */ @@ -46546,6 +46562,14 @@ export interface paths { 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 id is in it. */ + url: string; + proposal_id: string; + description: string; + } | null; }; }; }; @@ -46601,7 +46625,7 @@ export interface paths { 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); the person runs the call in the Shop (Executar consulta) or through an MCP client with their login. + * @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`. */ @@ -46617,7 +46641,7 @@ export interface paths { }; requestBody?: never; responses: { - /** @description A key never runs a data call. */ + /** @description A key never runs a data call; `details.next_action` is the person's way. */ 403: { headers: { [name: string]: unknown; @@ -46637,6 +46661,18 @@ export interface paths { }; }; }; + /** @description Not Found */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @enum {string} */ + error: "not_found"; + }; + }; + }; }; }; delete?: never; diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index 0b38f07b..c1ef1e92 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 84e5aabf9ee26b8d2fafcff96e9cbb1eb81e0bde785a866c35758c9a61bb5a4f, fetched 2026-11-07T22:49:28.730Z +// Source: openapi-snapshot.json (sha256 5495b828036f355738c4b07d426b7e2b15208b9005d6c0324f621d79956348e3, fetched 2026-11-08T03:49:09.330Z // 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"; From 20f4c5b9e20296983927c455687163deabf1a64c Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Sun, 8 Nov 2026 03:08:27 -0300 Subject: [PATCH 5/9] chore(sdk): the snapshot's next_action description names the project id Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Baaitxfwpx5yJ8xhz6nNhT --- packages/core/openapi-snapshot.json | 12 ++++++------ packages/core/src/generated/openapi.ts | 10 +++++----- packages/core/src/generated/operations.ts | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index ec89d6a1..7f644b3b 100644 --- a/packages/core/openapi-snapshot.json +++ b/packages/core/openapi-snapshot.json @@ -1,8 +1,8 @@ { "snapshot": { "source": "https://api.codespar.dev/openapi.json", - "fetched_at": "2026-11-08T03:49:09.330Z", - "sha256": "5495b828036f355738c4b07d426b7e2b15208b9005d6c0324f621d79956348e3", + "fetched_at": "2026-11-08T06:08:25.993Z", + "sha256": "336015728bcef0492980f7a93de26a69c7d5c45cd0205a3eadbe316149d31e9b", "etag": null, "last_modified": null, "info": { @@ -111088,7 +111088,7 @@ "/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 id is 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`.", + "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": { @@ -111514,7 +111514,7 @@ }, "url": { "type": "string", - "description": "The call's card on the dashboard, behind the person's sign-in; only the call's id is in it." + "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" @@ -111936,7 +111936,7 @@ }, "url": { "type": "string", - "description": "The call's card on the dashboard, behind the person's sign-in; only the call's id is in it." + "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" @@ -112658,7 +112658,7 @@ }, "url": { "type": "string", - "description": "The call's card on the dashboard, behind the person's sign-in; only the call's id is in it." + "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" diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index 9471ef05..0e72883f 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 5495b828036f355738c4b07d426b7e2b15208b9005d6c0324f621d79956348e3, fetched 2026-11-08T03:49:09.330Z +// Source: openapi-snapshot.json (sha256 336015728bcef0492980f7a93de26a69c7d5c45cd0205a3eadbe316149d31e9b, fetched 2026-11-08T06:08:25.993Z // from https://api.codespar.dev/openapi.json, API 0.3.0). // Regenerate: npm run spec:generate (in packages/core) export interface paths { @@ -46034,7 +46034,7 @@ export interface paths { 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 id is in the url). Test projects only. + * @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`. */ @@ -46169,7 +46169,7 @@ export interface paths { 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 id is in it. */ + /** @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; @@ -46291,7 +46291,7 @@ export interface paths { 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 id is in it. */ + /** @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; @@ -46565,7 +46565,7 @@ export interface paths { 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 id is in it. */ + /** @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; diff --git a/packages/core/src/generated/operations.ts b/packages/core/src/generated/operations.ts index c1ef1e92..94f10d37 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 5495b828036f355738c4b07d426b7e2b15208b9005d6c0324f621d79956348e3, fetched 2026-11-08T03:49:09.330Z +// Source: openapi-snapshot.json (sha256 336015728bcef0492980f7a93de26a69c7d5c45cd0205a3eadbe316149d31e9b, fetched 2026-11-08T06:08:25.993Z // 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"; From a277246d46360b7822a80d0d1652799935a8bdde Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Sun, 8 Nov 2026 10:16:42 -0300 Subject: [PATCH 6/9] chore(release-prep): bump sdk 0.16.29, cli 0.22.7, mcp 0.5.21, types 0.11.8 for the data-call changes npm versions are immutable, so changed packages carry a new version. No release here: publishing is a tag push, done separately. The CLI's floor on the SDK rises to the version that exports dataCallOutcome and nextActionOfError. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Baaitxfwpx5yJ8xhz6nNhT --- package-lock.json | 10 +++++----- packages/cli/CHANGELOG.md | 2 +- packages/cli/package.json | 4 ++-- packages/core/CHANGELOG.md | 2 +- packages/core/package.json | 2 +- packages/mcp/CHANGELOG.md | 2 +- packages/mcp/package.json | 2 +- packages/types/CHANGELOG.md | 2 +- packages/types/package.json | 2 +- 9 files changed, 14 insertions(+), 14 deletions(-) diff --git a/package-lock.json b/package-lock.json index 60525867..a934e561 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3020,10 +3020,10 @@ }, "packages/cli": { "name": "@codespar/cli", - "version": "0.22.6", + "version": "0.22.7", "license": "MIT", "dependencies": { - "@codespar/sdk": "^0.16.26", + "@codespar/sdk": "^0.16.29", "commander": "^13.0.0" }, "bin": { @@ -3039,7 +3039,7 @@ }, "packages/core": { "name": "@codespar/sdk", - "version": "0.16.28", + "version": "0.16.29", "license": "MIT", "dependencies": { "@codespar/types": "^0.10.1 || ^0.11.0", @@ -3178,7 +3178,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", @@ -3213,7 +3213,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 53873e4a..b8b459ec 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,6 +1,6 @@ # @codespar/cli — changelog -## Unreleased +## 0.22.7 — 2026-11-08 ### Added diff --git a/packages/cli/package.json b/packages/cli/package.json index db78c146..24a1a35d 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/cli", - "version": "0.22.6", + "version": "0.22.7", "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.29", "commander": "^13.0.0" }, "devDependencies": { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 3e514bc3..62308e9d 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,6 +1,6 @@ # @codespar/sdk — CHANGELOG -## Unreleased +## 0.16.29 — 2026-11-08 ### Added diff --git a/packages/core/package.json b/packages/core/package.json index dc2deda2..3ee596ff 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@codespar/sdk", - "version": "0.16.28", + "version": "0.16.29", "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/mcp/CHANGELOG.md b/packages/mcp/CHANGELOG.md index 0d7d8fe0..4515d32d 100644 --- a/packages/mcp/CHANGELOG.md +++ b/packages/mcp/CHANGELOG.md @@ -1,6 +1,6 @@ # @codespar/mcp — changelog -## Unreleased +## 0.5.21 — 2026-11-08 ### Added diff --git a/packages/mcp/package.json b/packages/mcp/package.json index b4f9e654..e4fddfc3 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/types/CHANGELOG.md b/packages/types/CHANGELOG.md index 5e6ccac9..aac95c3b 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -1,6 +1,6 @@ # @codespar/types — CHANGELOG -## Unreleased +## 0.11.8 — 2026-11-08 ### Added diff --git a/packages/types/package.json b/packages/types/package.json index 683db501..c2c80352 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", From e39ad9013b6859119bec0a0f57b846a916019e01 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Sun, 8 Nov 2026 10:27:08 -0300 Subject: [PATCH 7/9] chore(types): the demo scenario manifest's version follows the package (0.11.8) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Baaitxfwpx5yJ8xhz6nNhT --- packages/types/src/testing/scenario-manifest.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/types/src/testing/scenario-manifest.ts b/packages/types/src/testing/scenario-manifest.ts index 7646ac21..0217866b 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", From eeac8c820c5eb1da736c0ca6d40590251fdd59ee Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Thu, 19 Nov 2026 19:56:16 -0300 Subject: [PATCH 8/9] chore(sdk): refresh the OpenAPI snapshot from the published API (Shop v0.7 served) `npm run sdk:spec:refresh` against https://api.codespar.dev/openapi.json after enterprise #2535 (740313cae) was served: 397 operations (was 393). It adds the offer image route of #2535 and the OAuth consent routes already in production from other PRs, and picks up description-only changes in triggers and webhook-endpoints. Generated files only; no hand-written code changes. Co-Authored-By: Claude Opus 5.5 --- packages/core/openapi-snapshot.json | 720 +++++++++++++++++++++- packages/core/src/generated/openapi.ts | 448 +++++++++++++- packages/core/src/generated/operations.ts | 6 +- 3 files changed, 1155 insertions(+), 19 deletions(-) diff --git a/packages/core/openapi-snapshot.json b/packages/core/openapi-snapshot.json index 2307f3b1..a2b95368 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-18T02:07:57.966Z", - "sha256": "3e716356adacd0e48ee0f7ad9e5f5e786d5412a7e5b2d9fa0a60333ab149216d", + "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": 332, - "operations": 393, + "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", @@ -120393,6 +120936,161 @@ ] } }, + "/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": [ + { + "bearerAuth": [ + "shop:purchases:read" + ] + } + ] + } + }, "/v1/shop/agent/capabilities": { "get": { "summary": "What the Shop can do in this project and mode", diff --git a/packages/core/src/generated/openapi.ts b/packages/core/src/generated/openapi.ts index 16c29cad..d4ff01aa 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 3e716356adacd0e48ee0f7ad9e5f5e786d5412a7e5b2d9fa0a60333ab149216d, fetched 2026-11-18T02:07:57.966Z +// 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; /** @@ -49694,6 +50042,92 @@ export interface paths { 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 be64eff0..c7769999 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 3e716356adacd0e48ee0f7ad9e5f5e786d5412a7e5b2d9fa0a60333ab149216d, fetched 2026-11-18T02:07:57.966Z +// 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 }, @@ -344,6 +347,7 @@ export const API_OPERATIONS = [ { 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 }, From 42416fd9c15d2f4ad1f5feb6062aa62e859d34b1 Mon Sep 17 00:00:00 2001 From: Fabiano Cruz Date: Thu, 19 Nov 2026 20:03:53 -0300 Subject: [PATCH 9/9] test(cli): pin `shop offers-image`, derived from the refreshed snapshot The refreshed snapshot adds GET /v1/shop/agent/offers/{id}/image/{n} (enterprise #2535, key scope shop:purchases:read). The CLI derives it as `shop offers-image`, after `shop data-calls-execute`. The OAuth routes the refresh also brought are outside /v1 and derive no command. Pinned in the resource commands test and named in the 0.22.8 changelog. Co-Authored-By: Claude Opus 5.5 --- packages/cli/CHANGELOG.md | 1 + packages/cli/src/__tests__/resource-commands.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 758d0b5b..c9a7a30f 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -9,6 +9,7 @@ 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 diff --git a/packages/cli/src/__tests__/resource-commands.test.ts b/packages/cli/src/__tests__/resource-commands.test.ts index d52b3bee..8546e7cf 100644 --- a/packages/cli/src/__tests__/resource-commands.test.ts +++ b/packages/cli/src/__tests__/resource-commands.test.ts @@ -192,6 +192,7 @@ const PINNED_COMMANDS = [ "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",