Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions packages/cli/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# @codespar/cli — changelog

## 0.22.8 — 2026-11-17

### Added

- Derived commands `shop create-data-calls`, `shop get-data-calls` and
`shop data-calls-execute` (Shop G3.1). Their exit code is the outcome: 0
confirmed, 10 pending (the person still runs it), 20 refused by the API
(`person_required` included), 30 failure, 40 uncertain (an effect may have
happened). Every other command keeps exit 1 for any failure.
- Derived command `shop offers-image` (`GET /v1/shop/agent/offers/{id}/image/{n}`, `image/jpeg`): an offer's image from a key's research, through the CodeSpar proxy (Shop v0.7).
- Needs @codespar/sdk ^0.16.31 (the data-call client and `nextActionOfError`).

## 0.22.7 — 2026-11-11

### Added
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@codespar/cli",
"version": "0.22.7",
"version": "0.22.8",
"description": "CodeSpar CLI. The agentic OS for money movement in Latin America, from your terminal: authenticate, browse servers, mint mandates, execute tools, manage sessions, stream logs.",
"type": "module",
"bin": {
Expand Down Expand Up @@ -48,7 +48,7 @@
"node": ">=20"
},
"dependencies": {
"@codespar/sdk": "^0.16.26",
"@codespar/sdk": "^0.16.31",
"commander": "^13.0.0"
},
"devDependencies": {
Expand Down
72 changes: 72 additions & 0 deletions packages/cli/src/__tests__/exit-codes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* Exit codes of the outcome commands (Shop G3.1 data calls): 0 confirmed,
* 10 pending, 20 refused, 30 failure, 40 uncertain. Only an opted-in command
* uses them; every other command keeps exit 1 for any failure.
*/
import { afterEach, describe, expect, it } from "vitest";
import { EXIT, exitCodeForDataCall, exitCodeForFailure, outcomeExitCodesOn, pendingOnPerson, resetExitPolicy, useOutcomeExitCodes } from "../exit-codes.js";

afterEach(() => resetExitPolicy());

const base = {
proposal_id: "prp_AbCdEfGhIjKlMnOp",
run_state: "ready",
awaiting: null,
offer: {} as never,
quotation: { state: "valid", total_minor: 50, observed_at: "", valid_until: "" },
authorization: { state: "needed", amount_max_minor: 50 },
commitment: { state: "not_started" },
payment: { state: "none" },
confirmation: { state: "none" },
actions: { execute: true, cancel: true, requote: false },
} as const;
const view = (over: Record<string, unknown>) => ({ ...base, ...over }) as never;

describe("exit codes of a data call's answer", () => {
it("each outcome has its code, read from the four states apart", () => {
expect(exitCodeForDataCall(view({ confirmation: { state: "confirmed", result_ref: "tdr_1" } }))).toBe(EXIT.ok);
expect(exitCodeForDataCall(view({}))).toBe(EXIT.pending);
expect(exitCodeForDataCall(view({ error: { code: "commitment_terms_changed" } }))).toBe(EXIT.refused);
expect(exitCodeForDataCall(view({ commitment: { state: "failed" }, confirmation: { state: "failed" } }))).toBe(EXIT.failed);
expect(exitCodeForDataCall(view({ commitment: { state: "uncertain" }, payment: { state: "debited" } }))).toBe(EXIT.uncertain);
});
});

describe("exit codes of a failure", () => {
it("off by default: nothing opted in", () => {
expect(outcomeExitCodesOn()).toBe(false);
});

it("an API refusal (4xx) is 20; a server error is 30", () => {
useOutcomeExitCodes({ effect: false });
expect(exitCodeForFailure("api", 403)).toBe(EXIT.refused);
expect(exitCodeForFailure("api", 409)).toBe(EXIT.refused);
expect(exitCodeForFailure("api", 503)).toBe(EXIT.failed);
});

it("a timeout or a dropped connection is 30 on a read, 40 on an effect", () => {
useOutcomeExitCodes({ effect: false });
expect(exitCodeForFailure("timeout")).toBe(EXIT.failed);
expect(exitCodeForFailure("network")).toBe(EXIT.failed);
useOutcomeExitCodes({ effect: true });
expect(exitCodeForFailure("timeout")).toBe(EXIT.uncertain);
expect(exitCodeForFailure("network")).toBe(EXIT.uncertain);
});
});

describe("a key asked to run a data call: pending on the person, with their protected action", () => {
const refusal = (url?: string) =>
Object.assign(new Error("person_required"), { code: "person_required", status: 403, body: { error: { code: "person_required", details: url ? { next_action: { kind: "person_authorization", url } } : {} } } });

it("an opted-in command gets the url to print (and exits pending)", () => {
useOutcomeExitCodes({ effect: true });
expect(pendingOnPerson(refusal("https://codespar.dev/dashboard/shop/data-calls/prp_x"))).toBe("https://codespar.dev/dashboard/shop/data-calls/prp_x");
});

it("without the protected action, or outside an opted-in command, it is a plain refusal", () => {
useOutcomeExitCodes({ effect: true });
expect(pendingOnPerson(refusal())).toBeNull();
resetExitPolicy();
expect(pendingOnPerson(refusal("https://codespar.dev/dashboard/shop/data-calls/prp_x"))).toBeNull();
});
});
4 changes: 4 additions & 0 deletions packages/cli/src/__tests__/resource-commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@ const PINNED_COMMANDS = [
"shop get-purchases → GET /v1/shop/agent/purchases/{id}",
"shop create-research → POST /v1/shop/agent/research",
"shop get-research → GET /v1/shop/agent/research/{id}",
"shop create-data-calls → POST /v1/shop/agent/data-calls",
"shop get-data-calls → GET /v1/shop/agent/data-calls/{id}",
"shop data-calls-execute → POST /v1/shop/agent/data-calls/{id}/execute",
"shop offers-image → GET /v1/shop/agent/offers/{id}/image/{n}",
"shop capabilities → GET /v1/shop/agent/capabilities",
"shop instruments → GET /v1/shop/agent/instruments",
"collect list-links → GET /v1/collect/links",
Expand Down
12 changes: 12 additions & 0 deletions packages/cli/src/commands/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -106,17 +110,25 @@ 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),
query: parseQuery(opts.query),
...(body !== undefined ? { body } : {}),
});

const dataCall = command.path.startsWith(DATA_CALLS_PATH) ? (result as { data_call?: Parameters<typeof exitCodeForDataCall>[0] } | null)?.data_call : undefined;
if (dataCall) process.exitCode = exitCodeForDataCall(dataCall);

if (opts.json) {
json(result ?? null);
return;
}
info(`${command.method.toUpperCase()} ${command.path}`);
renderResult(result);
// While a data call waits for the person: the protected action, for them to open (criterion 5).
const next = (result as { next_action?: { url?: unknown } | null } | null)?.next_action;
if (dataCall && next && typeof next.url === "string") info(`A pessoa executa esta consulta em: ${next.url}`);
}
75 changes: 75 additions & 0 deletions packages/cli/src/exit-codes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Exit codes for the commands whose answer is an outcome a script branches
* on (Shop G3.1 data calls first; the store commands of G2.1 reuse them).
* Agreed across the core fronts on 07/11:
*
* 0 ok: the result is confirmed
* 10 pending: the person or a next step is needed (a draft waits to be run)
* 20 refused by the API with a code (person_required, 404, 409, terms changed)
* 30 failure (5xx, or a network error on a READ)
* 40 uncertain: an effect may have happened (sent, outcome not known yet)
* 1 the CLI's own usage or configuration error
*
* Every other command keeps exit 1 for any failure: a command opts in, so
* a script that already branches on 1 never sees its meaning change.
*/
import { dataCallOutcome, nextActionOfError, type DataCall } from "@codespar/sdk";

export const EXIT = { ok: 0, pending: 10, refused: 20, failed: 30, uncertain: 40, usage: 1 } as const;

interface Policy {
/** Whether the running command uses these codes. */
on: boolean;
/** Whether the command asks for an effect (a timeout there is uncertain, not a failure). */
effect: boolean;
}

const policy: Policy = { on: false, effect: false };

/** Opt the running command in. `effect`: it may cause something at the provider. */
export function useOutcomeExitCodes(opts: { effect: boolean }): void {
policy.on = true;
policy.effect = opts.effect;
}

export function outcomeExitCodesOn(): boolean {
return policy.on;
}

/** The code of a data call's answer, from its four states. */
export function exitCodeForDataCall(view: DataCall): number {
switch (dataCallOutcome(view)) {
case "succeeded":
return EXIT.ok;
case "pending":
return EXIT.pending;
case "refused":
return EXIT.refused;
case "failed":
return EXIT.failed;
case "uncertain":
return EXIT.uncertain;
}
}

/**
* A refusal that hands the person's protected action (criterion 5: a key asked to run a data call): the step is
* pending on the person, not refused. Returns the url to print, or null.
*/
export function pendingOnPerson(err: unknown): string | null {
if (!policy.on || (err as { code?: unknown } | null)?.code !== "person_required") return null;
return nextActionOfError(err)?.url ?? null;
}

/** The code of a failure of an opted-in command: the API's refusal, a server error, the network or a timeout. */
export function exitCodeForFailure(kind: "api" | "timeout" | "network", status?: number): number {
if (kind === "api" && status !== undefined && status >= 400 && status < 500) return EXIT.refused;
if ((kind === "timeout" || kind === "network") && policy.effect) return EXIT.uncertain;
return EXIT.failed;
}

/** For tests: back to the default policy. */
export function resetExitPolicy(): void {
policy.on = false;
policy.effect = false;
}
13 changes: 11 additions & 2 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
showMetaToolCommand,
} from "./commands/meta-tool.js";
import { runResourceCommand } from "./commands/resource.js";
import { EXIT, exitCodeForFailure, outcomeExitCodesOn, pendingOnPerson } from "./exit-codes.js";
import {
payablesBatchCreateCommand,
payablesBatchGetCommand,
Expand Down Expand Up @@ -1011,6 +1012,14 @@ async function main() {
// The generated REST client answers with its own error types. Print the
// API's message and body verbatim — an exit code plus a stack trace
// would hide the one thing the caller needs, which is what the API said.
// A data call a key asked to run: the person's protected action, printed for them; pending, not refused.
const personUrl = err instanceof CodesparApiError ? pendingOnPerson(err) : null;
if (personUrl) {
process.stderr.write(`${c.yellow("…")} A pessoa precisa executar esta consulta: ${personUrl}\n`);
if (hasJsonFlag) json({ pending: { kind: "person_authorization", url: personUrl, code: (err as CodesparApiError).code } });
else process.stdout.write(`${personUrl}\n`);
process.exit(EXIT.pending);
}
if (err instanceof CodesparApiError) {
process.stderr.write(`${c.red("✗")} ${err.message}\n`);
if (err.body !== undefined && !hasJsonFlag) {
Expand All @@ -1021,12 +1030,12 @@ async function main() {
...(err.code === undefined ? {} : { code: err.code }),
...(err.body === undefined ? {} : { body: err.body }),
});
process.exit(1);
process.exit(outcomeExitCodesOn() ? exitCodeForFailure(err.status === undefined || err.status === 0 ? "network" : "api", err.status) : 1);
}
if (err instanceof TimeoutError) {
process.stderr.write(`${c.red("✗")} ${err.message}\n`);
falhou("timeout", err.message);
process.exit(1);
process.exit(outcomeExitCodesOn() ? exitCodeForFailure("timeout") : 1);
}
// Unexpected error — show stack so we can debug.
process.stderr.write(`${c.red("✗ internal error:")}\n`);
Expand Down
25 changes: 25 additions & 0 deletions packages/core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
# @codespar/sdk — CHANGELOG

## 0.16.31 — 2026-11-17

### Added

- **Shop G3.1 data calls**: `cs.dataCalls` (and `session.dataCalls`) over
`/v1/shop/agent/data-calls`: `create({ agentId, offerId, idempotencyKey })`
drafts a data call from a `data_service` offer of a research, `get(id)` reads
it with the four states apart (quotation, authorization, commitment, payment,
confirmation), and `execute(id)` surfaces the API's `person_required` (403):
a key never runs a data call, the person does. `dataCallOutcome(view)` reads
one word (`succeeded`, `pending`, `refused`, `failed`, `uncertain`).
- `session.research.create` takes `taskKind` (`data_service` among them) and
`criteria.dataService { params, sku? }`.
- OpenAPI snapshot: the served document of 0.16.30 plus the three data-call
operations and the research body with `task_kind`, from the enterprise
routes of Shop G3.1 (codespar-enterprise #2520). They are served once #2520
is deployed; until then `spec:check` reports the served document as behind
the snapshot, and this version is not published.
- The rest of the snapshot follows the served document as of 2026-11-17: the
research body's `task_kind` (`product`, `service_plan`, `reservation`),
the `web` source with `sources.origins` and the `reservation` and
`service_plan` criteria (Shop G1, enterprise #2366/#2367); `monthly_minor`
and `monthly_quantity` on the sweeping consents; the Test treasury top-up
described against 20 USDC.

## 0.16.30 — 2026-11-15

### Security
Expand Down
Loading
Loading