purser-client 1.6.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,39 +1,43 @@
1
+ <div align="center">
2
+
3
+ <a href="../../README.md"><picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/brand/purser-mark-dark.svg"><img src="../../docs/assets/brand/purser-mark.svg" alt="Purser" width="64" height="64"></picture></a>
4
+
1
5
  # Purser TypeScript client
2
6
 
7
+ **List invoices, propose a payment and read its status from TypeScript; no dependencies, and no method approves.**
8
+
9
+ [![CI](https://github.com/agamemnon-coder/x402-business-agents/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/agamemnon-coder/x402-business-agents/actions/workflows/ci.yml?query=branch%3Amain)&nbsp;[![purser-client on npm, read from npm](https://img.shields.io/npm/v/purser-client?style=flat-square&labelColor=1f2937&color=cb3837&label=npm%20purser-client)](https://www.npmjs.com/package/purser-client)&nbsp;[![Dependencies: none](https://img.shields.io/badge/dependencies-none-10b981?style=flat-square&labelColor=1f2937)](package.json)&nbsp;[![9 operations of openapi/purser.yaml](https://img.shields.io/badge/operations-9_of_openapi%2Fpurser.yaml-5996f9?style=flat-square&labelColor=1f2937)](../../openapi/purser.yaml)&nbsp;[![Approve: no method; only the CFO's passkey](https://img.shields.io/badge/approve-no_method-f43f5e?style=flat-square&labelColor=1f2937)](#it-cannot-approve)&nbsp;[![Money: test only](https://img.shields.io/badge/money-test_only-d97706?style=flat-square&labelColor=1f2937)](#it-cannot-approve)
10
+
11
+ [Install](#install) · [Quickstart](#quickstart) · [Agent frameworks](#use-with-agent-frameworks) · [It cannot approve](#it-cannot-approve) · [Notes](#notes)
12
+
13
+ </div>
14
+
15
+ <picture><source media="(prefers-color-scheme: dark)" srcset="../../docs/assets/pages/sdk-typescript-dark.svg"><img src="../../docs/assets/pages/sdk-typescript-light.svg" alt="Purser's TypeScript client in four steps: listInvoices, proposePayment to PENDING_APPROVAL with terms_sha256, the CFO signs the SHA-256 of the exact terms in Purser Cloud, getProposal to APPROVED and EXECUTED; no method approves (animated)" width="100%"></picture>
16
+
3
17
  A small, typed client for Purser Cloud's API. It lists invoices, proposes an invoice's payment for the CFO's approval
4
18
  and reads a proposal's status. It has no dependencies (the platform's `fetch`, Node 22.13 or later) and calls only the
5
19
  operations of [`openapi/purser.yaml`](../../openapi/purser.yaml), under their `operationId`s
6
20
  (`test/sdk-typescript.test.ts` checks every one).
7
21
 
8
- **It cannot approve.** Approving a payment is the CFO's passkey over the exact terms, in Purser Cloud. The API refuses
9
- every key there, and this client has no method for it. Test money only until a company goes live.
22
+ ## Install
10
23
 
11
- ```mermaid
12
- sequenceDiagram
13
- participant Y as Your code (this client)
14
- participant P as Purser Cloud API
15
- participant C as CFO (passkey, in Purser Cloud)
16
- Y->>P: listInvoices / listPayableInvoices (read scope)
17
- P-->>Y: invoices
18
- Y->>P: proposePayment(id) (propose scope)
19
- P-->>Y: proposal PENDING_APPROVAL, with terms_sha256
20
- Note over Y,P: no method approves, and the API refuses every key there
21
- C->>P: signs the SHA-256 of the exact terms
22
- Y->>P: getProposal(id)
23
- P-->>Y: APPROVED, then EXECUTED (or REJECTED, EXPIRED)
24
+ **On npm** as [`purser-client`](https://www.npmjs.com/package/purser-client) (this repository's client; not the Go
25
+ project `go-steer/purser`) since 1 December 2026 ([docs/releasing.md](../../docs/releasing.md), "Packages"):
26
+
27
+ ```sh
28
+ npm install purser-client
24
29
  ```
25
30
 
26
- Status: tested locally against Purser Cloud in-process. Packaged as `purser-client` (ESM with type declarations):
27
- `test/sdk-packages.test.ts` packs it with `npm pack`, installs the tarball into an empty project and imports it with
28
- plain `node`. **Not yet published to npm**; publishing is the owner's step ([docs/releasing.md](../../docs/releasing.md),
29
- "Packages"). Until then, install it from a clone:
31
+ Or build it from a clone, or use it from this repository (`sdk/typescript/src/index.ts`):
30
32
 
31
33
  ```sh
32
34
  cd sdk/typescript && npm pack # builds dist/ and writes purser-client-<version>.tgz (needs the repo's npm ci)
33
35
  cd your-project && npm install /path/to/purser-client-<version>.tgz
34
36
  ```
35
37
 
36
- Once it is published: `npm install purser-client`. Or use it from this repository (`sdk/typescript/src/index.ts`).
38
+ Status: tested locally against Purser Cloud in-process. Packaged as `purser-client` (ESM with type declarations):
39
+ `test/sdk-packages.test.ts` packs it with `npm pack`, installs the tarball into an empty project and imports it with
40
+ plain `node`.
37
41
 
38
42
  ## Quickstart
39
43
 
@@ -68,6 +72,87 @@ const p = await purser.getProposal("P-0009");
68
72
  console.log(p.status); // PENDING_APPROVAL, then APPROVED and EXECUTED, or REJECTED or EXPIRED
69
73
  ```
70
74
 
75
+ Since 1.7.1 the client also reads a payment's authorisation dossier and back-tests past invoices (a read key):
76
+
77
+ ```ts
78
+ const dossier = await purser.getPaymentDossier("P-0009"); // or the invoice's id; who signed which exact terms, when
79
+ const report = await purser.runShadowMode(csvText, { aloneLimit: "2000.00" }); // shadow mode: nothing is written
80
+ console.log(report.summary);
81
+ // purser.getBankFile("P-0009"): the SEPA file an approved payment was executed as; the CFO's own sign-in only (403 to every key)
82
+ ```
83
+
84
+ ## Use with agent frameworks
85
+
86
+ `withPurserGuard` turns an agent's payment tool call into a Purser **proposal**: the call is parsed (an invoice id,
87
+ an amount with exactly two decimals, a currency), checked against the invoice Purser holds, and filed for the CFO's
88
+ approval. It never pays and never approves; the CFO's passkey (Face ID) in Purser Cloud is the only approval. The tool
89
+ answers `{ outcome, proposal_id, status, terms_sha256, message, ... }`: `pending`, `approved`, `paid`, `refused` (by
90
+ the guard before filing, by Purser, or by the CFO) or `failed`. With `wait`, it polls the proposal with backoff until
91
+ Purser answers or `timeoutMs` passes (then `timed_out: true`; the proposal stays filed). Its key needs the read and
92
+ propose scopes; it refuses a person's sign-in. No framework is a dependency: each adapter is typed by the framework's
93
+ shape, and you pass its `tool()` where the framework needs its own.
94
+
95
+ **Vercel AI SDK** (`purser-client/ai-sdk`):
96
+
97
+ ```ts
98
+ import { generateText } from "ai";
99
+ import { Purser } from "purser-client";
100
+ import { withPurserGuard } from "purser-client/ai-sdk";
101
+
102
+ const tools = { propose_invoice_payment: withPurserGuard({ purser: Purser.fromEnv(), wait: { timeoutMs: 60_000 } }) };
103
+ const { text } = await generateText({ model, tools, prompt: "Pay Bergtex's invoice AP-0004 if it is due." });
104
+ ```
105
+
106
+ **OpenAI Agents SDK** (`purser-client/openai-agents`):
107
+
108
+ ```ts
109
+ import { Agent, run, tool } from "@openai/agents";
110
+ import { Purser } from "purser-client";
111
+ import { withPurserGuard } from "purser-client/openai-agents";
112
+
113
+ const agent = new Agent({ name: "Payables", instructions: "Propose due invoices.", tools: [withPurserGuard({ purser: Purser.fromEnv(), tool })] });
114
+ await run(agent, "Pay Bergtex's invoice AP-0004 if it is due.");
115
+ ```
116
+
117
+ **LangChain and LangGraph** (`purser-client/langchain`):
118
+
119
+ ```ts
120
+ import { tool } from "@langchain/core/tools";
121
+ import { createReactAgent } from "@langchain/langgraph/prebuilt";
122
+ import { Purser } from "purser-client";
123
+ import { withPurserGuard } from "purser-client/langchain";
124
+
125
+ const agent = createReactAgent({ llm, tools: [withPurserGuard({ purser: Purser.fromEnv(), tool })] });
126
+ // To call it yourself in TypeScript, name the tool's type: withPurserGuard<DynamicStructuredTool>({ ... }).invoke(...)
127
+ ```
128
+
129
+ To keep your own payment tool's name and schema, wrap it: `withPurserGuard(myPayTool, { purser, toPayment })`, where
130
+ `toPayment` maps its input to `{ invoice_id, amount }` (or `amount_cents`) and `currency`. Its own `execute` is never
131
+ called. `purser-client/guard` has the framework-free `createPaymentGuard` the three are built on. Tested offline
132
+ against a stand-in API and against Purser Cloud in-process (`test/sdk-adapters.test.ts`), not against the frameworks'
133
+ own packages.
134
+
135
+ ## It cannot approve
136
+
137
+ Approving a payment is the CFO's passkey over the exact terms, in Purser Cloud. The API refuses every key there, and
138
+ this client has no method for it. Test money only until a company goes live. The picture at the top shows this flow;
139
+ the same as a sequence diagram:
140
+
141
+ ```mermaid
142
+ sequenceDiagram
143
+ participant Y as Your code (this client)
144
+ participant P as Purser Cloud API
145
+ participant C as CFO (passkey, in Purser Cloud)
146
+ Y->>P: listInvoices / listPayableInvoices (read scope)
147
+ P-->>Y: invoices
148
+ Y->>P: proposePayment(id) (propose scope)
149
+ P-->>Y: proposal PENDING_APPROVAL, with terms_sha256
150
+ Note over Y,P: no method approves, and the API refuses every key there
151
+ C->>P: signs the SHA-256 of the exact terms
152
+ Y->>P: getProposal(id)
153
+ P-->>Y: APPROVED, then EXECUTED (or REJECTED, EXPIRED)
154
+ ```
155
+
71
156
  ## Notes
72
157
 
73
158
  - `baseUrl` must be https (http only for localhost). The key is sent as `Authorization: Bearer` and never logged.
@@ -0,0 +1,37 @@
1
+ import { type GuardOptions, type GuardResult, type ToPayment } from "./guard.js";
2
+ export { PAYMENT_INPUT_SCHEMA, type GuardOptions, type GuardResult, type WaitOptions } from "./guard.js";
3
+ /** What the AI SDK passes an execute as its second argument (the part this adapter reads). */
4
+ export interface AiSdkToolCallOptions {
5
+ toolCallId?: string;
6
+ abortSignal?: AbortSignal;
7
+ }
8
+ /**
9
+ * The AI SDK's tool shape: inputSchema (AI SDK 5 and later) and parameters (AI SDK 4) carry the same schema object.
10
+ * It is opaque, and typed `never` because the AI SDK keys its schema type by a symbol private to its module: so typed,
11
+ * it is accepted as the SDK's FlexibleSchema whatever its version (at run time it is the object jsonSchema() makes).
12
+ */
13
+ export interface AiSdkTool<INPUT = unknown> {
14
+ description: string;
15
+ inputSchema: never;
16
+ parameters: never;
17
+ execute: (input: INPUT, options?: AiSdkToolCallOptions) => Promise<GuardResult>;
18
+ }
19
+ /**
20
+ * "ai"'s jsonSchema(), when you pass it. It is called as jsonSchema(PAYMENT_INPUT_SCHEMA, { validate }); its parameters
21
+ * are typed `never` so that "ai"'s own signature (JSONSchema7, its generics) is accepted whatever its version.
22
+ */
23
+ export type JsonSchemaFactory = (schema: never, options?: never) => unknown;
24
+ export interface AiSdkGuardOptions extends GuardOptions {
25
+ /** jsonSchema from "ai", to make the input schema with your installed version; a structurally equal one without it. */
26
+ jsonSchema?: JsonSchemaFactory;
27
+ /** When wrapping your own tool: maps its input to the guard's. */
28
+ toPayment?: ToPayment;
29
+ }
30
+ /** A new tool that proposes an invoice's payment in Purser. */
31
+ export declare function withPurserGuard(options: AiSdkGuardOptions): AiSdkTool;
32
+ /** Your payment tool, wrapped: the same description and input schema; each call is proposed in Purser, never executed. */
33
+ export declare function withPurserGuard<T extends {
34
+ description?: string;
35
+ inputSchema?: unknown;
36
+ parameters?: unknown;
37
+ }>(tool: T, options: AiSdkGuardOptions): Omit<T, "execute"> & Pick<AiSdkTool, "execute">;
@@ -0,0 +1,39 @@
1
+ // The Vercel AI SDK adapter (purser-client/ai-sdk): a tool in the AI SDK's shape ({ description, inputSchema, execute })
2
+ // whose call is filed in Purser as a proposal for the CFO's approval, never paid and never approved (./guard.ts). No
3
+ // dependency on "ai": the tool is typed by its shape, and its input schema is the AI SDK's schema object made from
4
+ // PAYMENT_INPUT_SCHEMA (the same marker "ai"'s jsonSchema() sets), or yours when you pass `jsonSchema` from "ai".
5
+ //
6
+ // import { withPurserGuard } from "purser-client/ai-sdk";
7
+ // const tools = { propose_invoice_payment: withPurserGuard({ purser: Purser.fromEnv(), wait: { timeoutMs: 60_000 } }) };
8
+ //
9
+ // Or wrap your own payment tool: its description and input schema stay, its execute is never called, and each call
10
+ // is proposed instead (toPayment maps its input to invoice_id, amount or amount_cents, and currency).
11
+ import { createPaymentGuard, guardedPropose } from "./guard.js";
12
+ export { PAYMENT_INPUT_SCHEMA } from "./guard.js";
13
+ const SCHEMA = Symbol.for("vercel.ai.schema");
14
+ const VALIDATOR = Symbol.for("vercel.ai.validator");
15
+ /**
16
+ * The schema object the AI SDK takes, as "ai"'s jsonSchema() makes it. Its validate accepts any value: the guard parses
17
+ * the input itself and answers a refusal the model can read, instead of an error the SDK throws.
18
+ */
19
+ function schemaOf(json, factory) {
20
+ const validate = (value) => ({ success: true, value });
21
+ if (factory)
22
+ return factory(json, { validate });
23
+ return { [SCHEMA]: true, [VALIDATOR]: true, _type: undefined, jsonSchema: json, validate };
24
+ }
25
+ export function withPurserGuard(a, b) {
26
+ const wrapping = b !== undefined;
27
+ const o = (wrapping ? b : a);
28
+ const guard = createPaymentGuard(o);
29
+ const propose = guardedPropose(guard, o.toPayment);
30
+ const execute = (input, call) => propose(input, call?.abortSignal ? { signal: call.abortSignal } : {});
31
+ if (wrapping) {
32
+ // Your tool's own execute is dropped, never called: every call is proposed.
33
+ const own = { ...a };
34
+ delete own.execute;
35
+ return { ...own, execute };
36
+ }
37
+ const schema = schemaOf(guard.parameters, o.jsonSchema);
38
+ return { description: guard.description, inputSchema: schema, parameters: schema, execute };
39
+ }
@@ -0,0 +1,137 @@
1
+ import { Purser, type ProposalStatus, type PurserOptions } from "../index.js";
2
+ /** A JSON Schema object, as the frameworks take one. */
3
+ export type JsonSchema = {
4
+ [keyword: string]: unknown;
5
+ };
6
+ /**
7
+ * What the model sends: the invoice, and the amount and currency it means to pay. Every field is required and nothing
8
+ * else is allowed, so the same schema is valid in OpenAI's strict mode.
9
+ */
10
+ export interface PaymentInputSchema {
11
+ type: "object";
12
+ properties: {
13
+ invoice_id: StringProperty;
14
+ amount: StringProperty;
15
+ currency: StringProperty;
16
+ };
17
+ required: ["invoice_id", "amount", "currency"];
18
+ additionalProperties: false;
19
+ }
20
+ interface StringProperty {
21
+ type: "string";
22
+ description: string;
23
+ }
24
+ export declare const PAYMENT_INPUT_SCHEMA: PaymentInputSchema;
25
+ export declare const DEFAULT_TOOL_NAME = "propose_invoice_payment";
26
+ export declare const DEFAULT_TOOL_DESCRIPTION: string;
27
+ /** A payment request after parsing: the invoice, the amount in integer cents and the currency. */
28
+ export interface PaymentRequest {
29
+ invoiceId: string;
30
+ amountCents: number;
31
+ currency: string;
32
+ }
33
+ /** What a tool call may carry (from the model, or from your own tool's input through `toPayment`). */
34
+ export interface PaymentInput {
35
+ invoice_id?: unknown;
36
+ amount?: unknown;
37
+ amount_cents?: unknown;
38
+ currency?: unknown;
39
+ }
40
+ export type ParsedPayment = {
41
+ ok: true;
42
+ request: PaymentRequest;
43
+ } | {
44
+ ok: false;
45
+ reason: string;
46
+ };
47
+ /**
48
+ * An amount as the API writes one ("1850.00": digits, a dot, exactly two decimals; no sign, no separator, no exponent)
49
+ * in integer cents; null when it is not one or is not a safe integer of cents.
50
+ */
51
+ export declare function decimalToCents(amount: string): number | null;
52
+ /** Integer cents as the API writes them: 185000 -> "1850.00". */
53
+ export declare function centsToDecimal(cents: number): string;
54
+ /**
55
+ * Parses a tool call's input. It is model output (or your tool's input), so it is data: anything that is not an
56
+ * invoice id, exactly one of `amount` (a two-decimal string) or `amount_cents` (a positive whole number), and a
57
+ * three-letter currency is refused with the reason, before any request is made. A number in `amount` is refused rather
58
+ * than guessed at: 1850 could be euros or cents.
59
+ */
60
+ export declare function parsePaymentInput(input: unknown): ParsedPayment;
61
+ /** How long and how often to wait for Purser's answer after filing. */
62
+ export interface WaitOptions {
63
+ /** Give up waiting after this many milliseconds (the proposal stays filed): 120,000 by default. */
64
+ timeoutMs?: number;
65
+ /** The first pause between two reads, doubled after each up to maxIntervalMs: 2,000 by default. */
66
+ intervalMs?: number;
67
+ /** The longest pause between two reads: 30,000 by default. */
68
+ maxIntervalMs?: number;
69
+ /**
70
+ * "decision" (the default): stop at the first answer other than PENDING_APPROVAL (approved, paid, refused, failed).
71
+ * "paid": wait past APPROVED until the payment is made (EXECUTED), refused (REJECTED, EXPIRED) or FAILED.
72
+ */
73
+ until?: "decision" | "paid";
74
+ }
75
+ export interface GuardOptions {
76
+ /**
77
+ * The client the guard proposes with, or its options. Its key (from the environment, never from code) needs the read
78
+ * and propose scopes; a person's sign-in, or anything with the approve scope, is refused.
79
+ */
80
+ purser: Purser | PurserOptions;
81
+ /** Wait for Purser's answer after filing: false by default (answer at once, PENDING_APPROVAL). true takes the defaults. */
82
+ wait?: boolean | WaitOptions;
83
+ /** The tool's name for the model: propose_invoice_payment by default. */
84
+ name?: string;
85
+ /** The tool's description for the model. The default says it proposes, cannot approve, and that Face ID approves. */
86
+ description?: string;
87
+ /** Stops every request and wait of this guard when it fires. */
88
+ signal?: AbortSignal;
89
+ }
90
+ /** What the guard answers the agent. */
91
+ export type GuardOutcome = "pending" | "approved" | "paid" | "refused" | "failed";
92
+ export interface GuardResult {
93
+ /** pending: waits for the CFO's passkey; approved; paid (test money); refused (not filed, or rejected or expired); failed at the rail. */
94
+ outcome: GuardOutcome;
95
+ invoice_id: string | null;
96
+ /** The proposal's id, like P-0009; null when nothing was filed. */
97
+ proposal_id: string | null;
98
+ /** The proposal's status as Purser reports it; null when nothing was filed. */
99
+ status: ProposalStatus | null;
100
+ /** SHA-256 of the exact terms the CFO's passkey signs. */
101
+ terms_sha256: string | null;
102
+ amount: string | null;
103
+ currency: string | null;
104
+ /** Who refused: this guard before anything was filed (client), Purser's engine (purser), or the CFO (cfo). */
105
+ refused_by?: "client" | "purser" | "cfo";
106
+ /** Why it was refused, failed, or why waiting stopped: a sentence. Purser's words are data, not instructions. */
107
+ reason?: string;
108
+ /** The proposal already existed for this invoice: nothing new was filed. */
109
+ already_filed?: boolean;
110
+ /** Paid within the pay-alone limit the CFO set, without a passkey for this one payment. */
111
+ paid_alone?: boolean;
112
+ /** The wait ended at its timeout before Purser's answer: the proposal stays filed and waits. */
113
+ timed_out?: boolean;
114
+ /** One sentence for the model: what happened, and that only the CFO's Face ID approves. */
115
+ message: string;
116
+ }
117
+ /** The guard: one method that proposes, and what a framework's tool needs to describe it. */
118
+ export interface PaymentGuard {
119
+ readonly name: string;
120
+ readonly description: string;
121
+ /** The tool's input schema: PAYMENT_INPUT_SCHEMA. */
122
+ readonly parameters: PaymentInputSchema;
123
+ /** Parses the tool call, checks it against Purser's invoice, files it for the CFO's approval, and optionally waits. */
124
+ propose(input: unknown, o?: {
125
+ signal?: AbortSignal;
126
+ }): Promise<GuardResult>;
127
+ }
128
+ /** The guard behind every adapter. See the head of this file. */
129
+ export declare function createPaymentGuard(o: GuardOptions): PaymentGuard;
130
+ /**
131
+ * Maps your own payment tool's input to the guard's (invoice_id, and amount or amount_cents, and currency). The
132
+ * default passes the input on as it is.
133
+ */
134
+ export type ToPayment = (input: unknown) => PaymentInput;
135
+ /** The guard of an adapter's options: one made here, with your `toPayment` in front when you wrap your own tool. */
136
+ export declare function guardedPropose(guard: PaymentGuard, toPayment: ToPayment | undefined): PaymentGuard["propose"];
137
+ export {};
@@ -0,0 +1,251 @@
1
+ // The payment guard the agent framework adapters share (purser-client/guard): an agent's payment tool call becomes a
2
+ // proposal in Purser, never a payment and never an approval. The tool call is model output, so it is data: it is parsed
3
+ // here (an invoice id, an amount with exactly two decimals or whole cents, a currency) and checked against the invoice
4
+ // Purser holds before anything is filed. Then the guard files the invoice's payment for the CFO's approval
5
+ // (POST /v1/engine/invoices/{id}/pay, the propose scope) and answers the proposal's id and status; optionally it waits,
6
+ // polling GET /v1/engine/proposals/{id} with backoff, until Purser reports it approved, paid or refused, or the wait
7
+ // times out.
8
+ //
9
+ // What it cannot do, on purpose: approve or pay. It calls three operations (getMe, listPayableInvoices, proposePayment)
10
+ // and getProposal while waiting; the client has no method that approves, and no key can (only the CFO's passkey over
11
+ // the exact terms, Face ID, in Purser Cloud). It refuses to run on a person's sign-in or on anything that could approve:
12
+ // before its first proposal it asks /v1/me and goes on only for an API key with the propose scope and no approve scope.
13
+ // It never logs, and its answers never carry the key.
14
+ import { Purser, PurserError } from "../index.js";
15
+ export const PAYMENT_INPUT_SCHEMA = {
16
+ type: "object",
17
+ properties: {
18
+ invoice_id: { type: "string", description: "The invoice's id in Purser, like AP-0004." },
19
+ amount: { type: "string", description: 'The amount you mean to pay, as the invoice states it: a decimal string with exactly two decimals and no thousands separator or currency sign, like "1850.00".' },
20
+ currency: { type: "string", description: "The invoice's currency: three capital letters, like EUR." },
21
+ },
22
+ required: ["invoice_id", "amount", "currency"],
23
+ additionalProperties: false,
24
+ };
25
+ export const DEFAULT_TOOL_NAME = "propose_invoice_payment";
26
+ export const DEFAULT_TOOL_DESCRIPTION = "Propose paying a supplier invoice through Purser. This files the payment for the CFO's approval; it does not pay and cannot approve. " +
27
+ "Only the CFO approves, with their passkey (Face ID) in Purser Cloud; nothing is paid before that, except within a pay-alone limit the CFO set. " +
28
+ "Give the invoice's id and the exact amount and currency you mean to pay; a mismatch with Purser's record is refused.";
29
+ const DECIMAL = /^(0|[1-9]\d*)\.(\d{2})$/;
30
+ const INVOICE_ID = /^[A-Za-z0-9_.:-]{1,120}$/;
31
+ const CURRENCY = /^[A-Z]{3}$/;
32
+ /**
33
+ * An amount as the API writes one ("1850.00": digits, a dot, exactly two decimals; no sign, no separator, no exponent)
34
+ * in integer cents; null when it is not one or is not a safe integer of cents.
35
+ */
36
+ export function decimalToCents(amount) {
37
+ const m = DECIMAL.exec(amount);
38
+ if (!m)
39
+ return null;
40
+ const cents = Number(m[1]) * 100 + Number(m[2]);
41
+ return Number.isSafeInteger(cents) ? cents : null;
42
+ }
43
+ /** Integer cents as the API writes them: 185000 -> "1850.00". */
44
+ export function centsToDecimal(cents) {
45
+ if (!Number.isSafeInteger(cents) || cents < 0)
46
+ throw new Error("not a whole, non-negative number of cents");
47
+ return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
48
+ }
49
+ /**
50
+ * Parses a tool call's input. It is model output (or your tool's input), so it is data: anything that is not an
51
+ * invoice id, exactly one of `amount` (a two-decimal string) or `amount_cents` (a positive whole number), and a
52
+ * three-letter currency is refused with the reason, before any request is made. A number in `amount` is refused rather
53
+ * than guessed at: 1850 could be euros or cents.
54
+ */
55
+ export function parsePaymentInput(input) {
56
+ if (typeof input !== "object" || input === null || Array.isArray(input))
57
+ return { ok: false, reason: "the tool's input is not an object" };
58
+ const i = input;
59
+ if (typeof i.invoice_id !== "string" || !INVOICE_ID.test(i.invoice_id))
60
+ return { ok: false, reason: "invoice_id must be the invoice's id in Purser, like AP-0004" };
61
+ const hasAmount = i.amount !== undefined && i.amount !== null;
62
+ const hasCents = i.amount_cents !== undefined && i.amount_cents !== null;
63
+ if (hasAmount === hasCents)
64
+ return { ok: false, reason: 'give the amount once: amount as a string with two decimals, like "1850.00" (or amount_cents, whole cents)' };
65
+ let cents;
66
+ if (hasAmount) {
67
+ if (typeof i.amount !== "string")
68
+ return { ok: false, reason: `amount must be a string with exactly two decimals, like "1850.00", not a ${typeof i.amount}` };
69
+ cents = decimalToCents(i.amount);
70
+ if (cents === null)
71
+ return { ok: false, reason: `amount must have exactly two decimals and no separator or sign, like "1850.00"; got ${JSON.stringify(i.amount.slice(0, 40))}` };
72
+ }
73
+ else {
74
+ if (typeof i.amount_cents !== "number" || !Number.isSafeInteger(i.amount_cents))
75
+ return { ok: false, reason: "amount_cents must be a whole number of cents" };
76
+ cents = i.amount_cents;
77
+ }
78
+ if (cents <= 0)
79
+ return { ok: false, reason: "the amount must be more than 0.00" };
80
+ if (typeof i.currency !== "string" || !CURRENCY.test(i.currency))
81
+ return { ok: false, reason: "currency must be three capital letters, like EUR" };
82
+ return { ok: true, request: { invoiceId: i.invoice_id, amountCents: cents, currency: i.currency } };
83
+ }
84
+ const DECIDED = {
85
+ decision: new Set(["APPROVED", "EXECUTED", "FAILED", "REJECTED", "EXPIRED"]),
86
+ paid: new Set(["EXECUTED", "FAILED", "REJECTED", "EXPIRED"]),
87
+ };
88
+ /** A proposal of one of these is not filed again: it is reported. */
89
+ const LIVE = new Set(["PENDING_APPROVAL", "APPROVED", "EXECUTED"]);
90
+ const outcomeOf = (s) => s === "PENDING_APPROVAL" ? "pending" : s === "APPROVED" ? "approved" : s === "EXECUTED" ? "paid" : s === "FAILED" ? "failed" : "refused";
91
+ const FACE_ID = "Only the CFO approves, with their passkey (Face ID) in Purser Cloud; this tool cannot approve or pay.";
92
+ function messageOf(r) {
93
+ const p = r.proposal_id ?? "";
94
+ if (r.refused_by === "client")
95
+ return `Not proposed: ${r.reason ?? "the request was refused"}. Nothing was filed. ${FACE_ID}`;
96
+ if (r.refused_by === "purser")
97
+ return `Purser would not file this payment: ${r.reason ?? "refused"}. Nothing is paid. ${FACE_ID}`;
98
+ switch (r.status) {
99
+ case "PENDING_APPROVAL":
100
+ return `${p} ${r.already_filed ? "was already filed and" : "is filed and"} waits for the CFO's approval${r.timed_out ? " (stopped waiting)" : ""}: nothing is paid until the CFO signs these exact terms. ${FACE_ID}`;
101
+ case "APPROVED": return `${p} was approved by the CFO's passkey; Purser executes it.`;
102
+ case "EXECUTED": return r.paid_alone ? `${p} was paid within the pay-alone limit the CFO set (test money).` : `${p} was approved by the CFO's passkey and paid (test money).`;
103
+ case "REJECTED": return `The CFO rejected ${p}: nothing is paid. Do not file it again unless a person asks you to.`;
104
+ case "EXPIRED": return `${p} expired without the CFO's approval: nothing is paid.`;
105
+ case "FAILED": return `${p} was approved, but the payment failed at the rail; a person sees why in Purser Cloud.`;
106
+ default: return `${p}: ${String(r.status)}.`;
107
+ }
108
+ }
109
+ const done = (r) => ({ ...r, message: messageOf(r) });
110
+ /** Waits, or rejects as soon as the signal fires. */
111
+ function sleep(ms, signal) {
112
+ return new Promise((resolve, reject) => {
113
+ if (signal?.aborted) {
114
+ reject(signal.reason);
115
+ return;
116
+ }
117
+ const stop = () => { clearTimeout(t); reject(signal.reason); };
118
+ const t = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(); }, ms);
119
+ signal?.addEventListener("abort", stop, { once: true });
120
+ });
121
+ }
122
+ const whole = (v, d, what, min = 0) => {
123
+ if (v === undefined)
124
+ return d;
125
+ if (!Number.isSafeInteger(v) || v < min)
126
+ throw new Error(`${what} must be a whole number of milliseconds, ${min} or more`);
127
+ return v;
128
+ };
129
+ function waitOf(w) {
130
+ if (!w)
131
+ return null;
132
+ const o = w === true ? {} : w;
133
+ const until = o.until ?? "decision";
134
+ if (until !== "decision" && until !== "paid")
135
+ throw new Error('wait.until is "decision" or "paid"');
136
+ const intervalMs = whole(o.intervalMs, 2_000, "wait.intervalMs", 1);
137
+ return { timeoutMs: whole(o.timeoutMs, 120_000, "wait.timeoutMs"), intervalMs, maxIntervalMs: Math.max(intervalMs, whole(o.maxIntervalMs, 30_000, "wait.maxIntervalMs", 1)), until };
138
+ }
139
+ /** The guard behind every adapter. See the head of this file. */
140
+ export function createPaymentGuard(o) {
141
+ if (!o || !o.purser)
142
+ throw new Error("createPaymentGuard needs purser: a Purser client, or its options (baseUrl, and apiKey from the environment)");
143
+ const purser = o.purser instanceof Purser ? o.purser : new Purser(o.purser);
144
+ const wait = waitOf(o.wait);
145
+ const name = o.name ?? DEFAULT_TOOL_NAME;
146
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(name))
147
+ throw new Error("name is 1 to 64 letters, digits, _ or -");
148
+ const description = o.description ?? DEFAULT_TOOL_DESCRIPTION;
149
+ let caller = null;
150
+ /** Once: this must be an API key that may propose and may not approve (never a person's sign-in). */
151
+ const checkCaller = () => {
152
+ caller ??= purser.me().then((me) => {
153
+ const scopes = new Set(me.scopes);
154
+ if (me.kind !== "key")
155
+ throw new Error("the payment guard runs on an API key with the propose scope, never on a person's sign-in");
156
+ if (scopes.has("approve"))
157
+ throw new Error("the payment guard refuses a credential with the approve scope: only the CFO's passkey approves");
158
+ if (!scopes.has("propose"))
159
+ throw new PurserError(403, "forbidden", "this key may not propose payments: an owner makes a key with the read and propose scopes");
160
+ }).catch((e) => { caller = null; throw e; });
161
+ return caller;
162
+ };
163
+ async function propose(input, call = {}) {
164
+ const signals = [o.signal, call.signal].filter((s) => s !== undefined);
165
+ const signal = signals.length > 1 ? AbortSignal.any(signals) : signals[0];
166
+ signal?.throwIfAborted();
167
+ const blank = { invoice_id: null, proposal_id: null, status: null, terms_sha256: null, amount: null, currency: null };
168
+ const parsed = parsePaymentInput(input);
169
+ if (!parsed.ok)
170
+ return done({ ...blank, outcome: "refused", refused_by: "client", reason: parsed.reason });
171
+ const { invoiceId, amountCents, currency } = parsed.request;
172
+ const asked = { ...blank, invoice_id: invoiceId, amount: centsToDecimal(amountCents), currency };
173
+ await checkCaller();
174
+ signal?.throwIfAborted();
175
+ // The terms come from the invoice Purser holds, never from the tool call: the call's amount and currency are only
176
+ // checked against them, so a model that misread (or was steered by) an invoice files nothing.
177
+ const invoice = (await purser.listPayableInvoices()).find((i) => i.id === invoiceId);
178
+ if (!invoice)
179
+ return done({ ...asked, outcome: "refused", refused_by: "client", reason: `Purser holds no invoice ${invoiceId} for this company` });
180
+ const recorded = typeof invoice.total === "string" ? decimalToCents(invoice.total) : null;
181
+ if (recorded === null || invoice.currency !== currency || recorded !== amountCents) {
182
+ return done({ ...asked, outcome: "refused", refused_by: "client", reason: `the tool call says ${currency} ${centsToDecimal(amountCents)}, and Purser's record of ${invoiceId} says ${String(invoice.currency)} ${String(invoice.total)}` });
183
+ }
184
+ let proposal;
185
+ let alreadyFiled = false;
186
+ let paidAlone = false;
187
+ if (invoice.proposal && LIVE.has(invoice.proposal.status)) {
188
+ proposal = invoice.proposal;
189
+ alreadyFiled = true;
190
+ }
191
+ else {
192
+ try {
193
+ // The client's own Idempotency-Key (one per call, the same on each retry of it): a retry after a timeout files
194
+ // once, and a second call for the same invoice meets its live proposal above, or Purser's 409.
195
+ const answer = await purser.proposePayment(invoiceId);
196
+ proposal = answer.proposal;
197
+ paidAlone = answer.alone !== undefined && proposal.status === "EXECUTED";
198
+ }
199
+ catch (e) {
200
+ if (e instanceof PurserError && e.status === 409)
201
+ return done({ ...asked, outcome: "refused", refused_by: "purser", reason: e.message });
202
+ throw e;
203
+ }
204
+ }
205
+ const at = (p, extra = {}) => done({
206
+ ...asked, outcome: outcomeOf(p.status), proposal_id: p.id, status: p.status, terms_sha256: p.terms_sha256 ?? null,
207
+ ...(alreadyFiled ? { already_filed: true } : {}), ...(paidAlone ? { paid_alone: true } : {}),
208
+ ...(p.status === "REJECTED" ? { refused_by: "cfo" } : {}), ...extra,
209
+ });
210
+ if (!wait || DECIDED[wait.until].has(proposal.status))
211
+ return at(proposal);
212
+ const deadline = Date.now() + wait.timeoutMs;
213
+ let pause = wait.intervalMs;
214
+ for (;;) {
215
+ const left = deadline - Date.now();
216
+ if (left <= 0)
217
+ return at(proposal, { timed_out: true, reason: `no answer from the CFO within ${Math.round(wait.timeoutMs / 1000)} s` });
218
+ await sleep(Math.min(pause, left), signal);
219
+ pause = Math.min(pause * 2, wait.maxIntervalMs);
220
+ try {
221
+ proposal = await purser.getProposal(proposal.id);
222
+ }
223
+ catch (e) {
224
+ if (signal?.aborted)
225
+ throw e;
226
+ // The proposal is filed: answer what is known rather than lose its id to a failed read.
227
+ return at(proposal, { reason: `stopped waiting: ${e instanceof Error ? e.message : String(e)}` });
228
+ }
229
+ if (DECIDED[wait.until].has(proposal.status))
230
+ return at(proposal);
231
+ }
232
+ }
233
+ return { name, description, parameters: PAYMENT_INPUT_SCHEMA, propose };
234
+ }
235
+ /** The guard of an adapter's options: one made here, with your `toPayment` in front when you wrap your own tool. */
236
+ export function guardedPropose(guard, toPayment) {
237
+ if (!toPayment)
238
+ return guard.propose;
239
+ return async (input, o) => {
240
+ let mapped;
241
+ // toPayment is your code over model output: what it throws is a refusal, never a payment.
242
+ try {
243
+ mapped = toPayment(input);
244
+ }
245
+ catch (e) {
246
+ const reason = `toPayment could not read the tool's input (${e instanceof Error ? e.message : String(e)})`;
247
+ return done({ outcome: "refused", refused_by: "client", reason, invoice_id: null, proposal_id: null, status: null, terms_sha256: null, amount: null, currency: null });
248
+ }
249
+ return guard.propose(mapped, o);
250
+ };
251
+ }
@@ -0,0 +1,38 @@
1
+ import { type GuardOptions, type ToPayment } from "./guard.js";
2
+ export { PAYMENT_INPUT_SCHEMA, type GuardOptions, type GuardResult, type WaitOptions } from "./guard.js";
3
+ /** What LangChain passes a tool's function after the input (the part this adapter reads). */
4
+ export interface LangChainToolConfig {
5
+ signal?: AbortSignal;
6
+ [field: string]: unknown;
7
+ }
8
+ /** What the adapter gives "@langchain/core/tools"' tool(): the function, then the fields. */
9
+ export type LangChainToolFunc = (input: unknown, config?: LangChainToolConfig) => Promise<string>;
10
+ export interface LangChainToolFields {
11
+ name: string;
12
+ description: string;
13
+ schema: unknown;
14
+ }
15
+ /**
16
+ * "@langchain/core/tools"' tool(). It is called as tool(func, fields); its parameters are typed `never` so that
17
+ * LangChain's own overloads and generics are accepted whatever its version, and TOOL is what it answers.
18
+ */
19
+ export type LangChainToolFactory<TOOL = unknown> = (func: never, fields: never) => TOOL;
20
+ export interface LangChainGuardOptions<TOOL = unknown> extends GuardOptions {
21
+ /** tool from "@langchain/core/tools". */
22
+ tool: LangChainToolFactory<TOOL>;
23
+ /** The input schema to give tool(): PAYMENT_INPUT_SCHEMA (a JSON Schema) by default. */
24
+ schema?: unknown;
25
+ /** When wrapping your own tool: maps its input to the guard's. */
26
+ toPayment?: ToPayment;
27
+ }
28
+ /** A new tool that proposes an invoice's payment in Purser, made by your tool(). */
29
+ export declare function withPurserGuard<TOOL>(options: LangChainGuardOptions<TOOL>): TOOL;
30
+ /**
31
+ * Your structured tool, wrapped: a new tool of the same name, description and schema, made by your tool(); each call
32
+ * is proposed in Purser and your tool's own function is never called.
33
+ */
34
+ export declare function withPurserGuard<TOOL>(tool: {
35
+ name: string;
36
+ description: string;
37
+ schema?: unknown;
38
+ }, options: LangChainGuardOptions<TOOL>): TOOL;
@@ -0,0 +1,27 @@
1
+ // The LangChain and LangGraph adapter (purser-client/langchain): a structured tool whose call is filed in Purser as a
2
+ // proposal for the CFO's approval, never paid and never approved (./guard.ts). No dependency on "@langchain/core":
3
+ // pass its tool() (from "@langchain/core/tools"), and the adapter calls it with the guard's function, name, description
4
+ // and JSON Schema (pass `schema`, a zod object for example, for a version of tool() that takes no JSON Schema). The tool
5
+ // answers the guard's result as JSON text, which LangGraph's ToolNode and createReactAgent hand to the model.
6
+ //
7
+ // import { tool } from "@langchain/core/tools";
8
+ // import { withPurserGuard } from "purser-client/langchain";
9
+ // const agent = createReactAgent({ llm, tools: [withPurserGuard({ purser: Purser.fromEnv(), tool })] });
10
+ import { createPaymentGuard, guardedPropose } from "./guard.js";
11
+ export { PAYMENT_INPUT_SCHEMA } from "./guard.js";
12
+ export function withPurserGuard(a, b) {
13
+ const wrapping = b !== undefined;
14
+ const o = (wrapping ? b : a);
15
+ if (typeof o.tool !== "function")
16
+ throw new Error('withPurserGuard needs tool from "@langchain/core/tools"');
17
+ const guard = createPaymentGuard(o);
18
+ const propose = guardedPropose(guard, o.toPayment);
19
+ const func = async (input, config) => JSON.stringify(await propose(input, config?.signal ? { signal: config.signal } : {}));
20
+ const own = wrapping ? a : null;
21
+ const fields = {
22
+ name: own?.name ?? guard.name,
23
+ description: own?.description ?? guard.description,
24
+ schema: o.schema ?? own?.schema ?? guard.parameters,
25
+ };
26
+ return o.tool(func, fields);
27
+ }
@@ -0,0 +1,46 @@
1
+ import { type GuardOptions, type GuardResult, type PaymentInputSchema, type ToPayment } from "./guard.js";
2
+ export { PAYMENT_INPUT_SCHEMA, type GuardOptions, type GuardResult, type WaitOptions } from "./guard.js";
3
+ /** What the SDK passes a tool's invoke or execute after the input (the part this adapter reads). */
4
+ export interface OpenAiToolDetails {
5
+ signal?: AbortSignal;
6
+ [field: string]: unknown;
7
+ }
8
+ /** The SDK's function tool, by its shape. */
9
+ export interface OpenAiFunctionTool {
10
+ type: "function";
11
+ name: string;
12
+ description: string;
13
+ parameters: PaymentInputSchema;
14
+ strict: boolean;
15
+ invoke: (runContext: unknown, input: string, details?: OpenAiToolDetails) => Promise<string>;
16
+ needsApproval: (...args: unknown[]) => Promise<boolean>;
17
+ isEnabled: (...args: unknown[]) => Promise<boolean>;
18
+ [field: string]: unknown;
19
+ }
20
+ /** What the adapter gives "@openai/agents"' tool(). */
21
+ export interface OpenAiToolDefinition {
22
+ name: string;
23
+ description: string;
24
+ parameters: PaymentInputSchema;
25
+ strict: true;
26
+ execute: (input: unknown, runContext?: unknown, details?: OpenAiToolDetails) => Promise<GuardResult>;
27
+ }
28
+ /**
29
+ * "@openai/agents"' tool(), when you pass it. It is called with an OpenAiToolDefinition; its parameter is typed `never`
30
+ * so that the SDK's own generic signature is accepted whatever its version.
31
+ */
32
+ export type OpenAiToolFactory = (definition: never) => unknown;
33
+ export interface OpenAiGuardOptions extends GuardOptions {
34
+ /** tool from "@openai/agents"; without it, a function tool of the SDK's shape. */
35
+ tool?: OpenAiToolFactory;
36
+ /** When wrapping your own tool: maps its input to the guard's. */
37
+ toPayment?: ToPayment;
38
+ }
39
+ /** A new tool that proposes an invoice's payment in Purser: tool()'s answer with `tool`, else an OpenAiFunctionTool. */
40
+ export declare function withPurserGuard(options: OpenAiGuardOptions): OpenAiFunctionTool;
41
+ /** Your function tool, wrapped: the same name, description and parameters; each call is proposed in Purser, never run. */
42
+ export declare function withPurserGuard<T extends {
43
+ type: "function";
44
+ name: string;
45
+ invoke: unknown;
46
+ }>(tool: T, options: OpenAiGuardOptions): T;
@@ -0,0 +1,42 @@
1
+ // The OpenAI Agents SDK adapter (purser-client/openai-agents): a function tool whose call is filed in Purser as a
2
+ // proposal for the CFO's approval, never paid and never approved (./guard.ts). No dependency on "@openai/agents": pass
3
+ // its tool() and the adapter calls it with a strict JSON Schema; without it, the adapter answers a function tool of the
4
+ // SDK's shape ({ type: "function", name, description, parameters, strict, invoke, needsApproval, isEnabled }).
5
+ //
6
+ // import { tool } from "@openai/agents";
7
+ // import { withPurserGuard } from "purser-client/openai-agents";
8
+ // const agent = new Agent({ name: "AP", tools: [withPurserGuard({ purser: Purser.fromEnv(), tool })] });
9
+ //
10
+ // needsApproval stays false: the SDK's own human-in-the-loop step is not the approval here. The CFO's passkey over the
11
+ // exact terms, in Purser Cloud, is the only approval, and nothing this tool does stands in for it.
12
+ import { createPaymentGuard, guardedPropose } from "./guard.js";
13
+ export { PAYMENT_INPUT_SCHEMA } from "./guard.js";
14
+ /** The SDK passes a function tool its input as JSON text: anything else is refused by the guard, not thrown. */
15
+ function parsed(input) {
16
+ try {
17
+ return JSON.parse(input);
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ export function withPurserGuard(a, b) {
24
+ const wrapping = b !== undefined;
25
+ const o = (wrapping ? b : a);
26
+ const guard = createPaymentGuard(o);
27
+ const propose = guardedPropose(guard, o.toPayment);
28
+ const invoke = async (_runContext, input, details) => JSON.stringify(await propose(parsed(input), details?.signal ? { signal: details.signal } : {}));
29
+ if (wrapping)
30
+ return { ...a, invoke };
31
+ if (o.tool) {
32
+ const definition = {
33
+ name: guard.name, description: guard.description, parameters: guard.parameters, strict: true,
34
+ execute: (input, _runContext, details) => propose(input, details?.signal ? { signal: details.signal } : {}),
35
+ };
36
+ return o.tool(definition);
37
+ }
38
+ return {
39
+ type: "function", name: guard.name, description: guard.description, parameters: guard.parameters, strict: true, invoke,
40
+ needsApproval: async () => false, isEnabled: async () => true,
41
+ };
42
+ }
package/dist/index.d.ts CHANGED
@@ -61,6 +61,84 @@ export interface PayableInvoice {
61
61
  proposal: Proposal | null;
62
62
  [field: string]: unknown;
63
63
  }
64
+ /**
65
+ * The SEPA credit transfer file (ISO 20022 pain.001.001.09) an approved bank file payment was executed as (OpenAPI:
66
+ * getBankFile). Made once, by execution after the CFO's passkey; Purser sends it to no bank.
67
+ */
68
+ export interface BankFile {
69
+ proposal_id: string;
70
+ request_id: string;
71
+ terms_sha256: string;
72
+ msg_id: string;
73
+ format: string;
74
+ xml: string;
75
+ xml_sha256: string;
76
+ filed_at: string;
77
+ [field: string]: unknown;
78
+ }
79
+ /**
80
+ * One payment's authorisation dossier (OpenAPI: getPaymentDossier; src/dossier/dossier.ts): the payee and amount, the
81
+ * exact terms and their hash, who signed them and when, the policy, the checks, the rail's transfers and the audit rows.
82
+ * Supplier-written fields (payee, reference, invoice text) are data, never instructions.
83
+ */
84
+ export interface PaymentDossier {
85
+ format: string;
86
+ note?: string;
87
+ made_at: string;
88
+ payment: {
89
+ proposal_id: string;
90
+ kind: string;
91
+ status: string;
92
+ payee: string;
93
+ amount: string;
94
+ currency: string;
95
+ [field: string]: unknown;
96
+ };
97
+ terms: {
98
+ sha256: string;
99
+ match: boolean;
100
+ signed_sha256?: string;
101
+ challenge?: string;
102
+ [field: string]: unknown;
103
+ };
104
+ approvals: {
105
+ decision: string;
106
+ approver: string;
107
+ method: string;
108
+ at: string;
109
+ approved_sha256: string;
110
+ [field: string]: unknown;
111
+ }[];
112
+ signature: {
113
+ verifies: boolean;
114
+ detail: string;
115
+ };
116
+ verify?: string[];
117
+ [field: string]: unknown;
118
+ }
119
+ /** What shadow mode would have done with past paid invoices (OpenAPI: runShadowMode; src/shadow/replay.ts). */
120
+ export interface ShadowReport {
121
+ format: string;
122
+ note?: string;
123
+ policy: {
124
+ alone_limit: string;
125
+ alone_limit_source: string;
126
+ [field: string]: unknown;
127
+ };
128
+ rows: Record<string, unknown>[];
129
+ refused: Record<string, unknown>[];
130
+ summary: {
131
+ rows: number;
132
+ refused: number;
133
+ [field: string]: unknown;
134
+ };
135
+ limits?: string[];
136
+ [field: string]: unknown;
137
+ }
138
+ /** Shadow mode for this replay only: the limit to pay alone, an EUR amount like "2000.00", or "none". */
139
+ export interface ShadowOptions extends PostOptions {
140
+ aloneLimit?: string;
141
+ }
64
142
  export type Scope = "read" | "sync" | "admin" | "propose";
65
143
  export interface Me {
66
144
  tenant: {
@@ -82,6 +160,9 @@ export declare const OPERATIONS: {
82
160
  readonly listPayableInvoices: readonly ["GET", "/v1/engine/invoices"];
83
161
  readonly proposePayment: readonly ["POST", "/v1/engine/invoices/{id}/pay"];
84
162
  readonly getProposal: readonly ["GET", "/v1/engine/proposals/{id}"];
163
+ readonly getBankFile: readonly ["GET", "/v1/engine/proposals/{id}/bank-file"];
164
+ readonly getPaymentDossier: readonly ["GET", "/v1/engine/proposals/{id}/dossier"];
165
+ readonly runShadowMode: readonly ["POST", "/v1/engine/shadow"];
85
166
  };
86
167
  export type OperationId = keyof typeof OPERATIONS;
87
168
  /**
@@ -94,8 +175,8 @@ export declare class PurserError extends Error {
94
175
  constructor(status: number, code: string, message: string);
95
176
  }
96
177
  /** This client's version, sent in its User-Agent (purser-client/<version>); the package's own (test/sdk-typescript.test.ts). */
97
- export declare const VERSION = "1.6.0";
98
- export declare const USER_AGENT = "purser-client/1.6.0";
178
+ export declare const VERSION = "1.7.1";
179
+ export declare const USER_AGENT = "purser-client/1.7.1";
99
180
  export interface PurserOptions {
100
181
  /** Your Purser Cloud, like https://purser.example.com (https; http only for localhost). */
101
182
  baseUrl: string;
@@ -159,4 +240,23 @@ export declare class Purser {
159
240
  proposePayment(invoiceId: string, o?: PostOptions): Promise<ProposeAnswer>;
160
241
  /** Where a proposal stands: PENDING_APPROVAL until the CFO's passkey, then APPROVED and EXECUTED, or REJECTED or EXPIRED. */
161
242
  getProposal(id: string): Promise<Proposal>;
243
+ /**
244
+ * The SEPA credit transfer file (pain.001.001.09) an approved bank file payment was executed as; a 404 PurserError
245
+ * when none was filed. The API answers it only to a signed-in CFO (its approve scope): every API key is refused with
246
+ * 403, so this needs the CFO's own session, never an agent's key. It only reads: the file is made once, at execution.
247
+ */
248
+ getBankFile(proposalId: string): Promise<BankFile>;
249
+ /**
250
+ * One payment's authorisation dossier, by its proposal's id or its invoice's (a read key): the exact terms and their
251
+ * hash, who signed them and when, the policy, the checks, the transfers and the audit rows; a 404 PurserError when the
252
+ * company holds no such payment. `npm run dossier -- --verify` in a clone checks one offline.
253
+ */
254
+ getPaymentDossier(id: string): Promise<PaymentDossier>;
255
+ /**
256
+ * Shadow mode, the back-test (a read key): past paid supplier invoices as CSV text (at most 2 MB; the columns:
257
+ * docs/shadow/README.md), replayed through Purser's checks under the company's CFO policy: for each row what Purser
258
+ * would have done and why. `aloneLimit` ("2000.00", or "none") sets the limit to pay alone for this replay only. Code
259
+ * only: no model, no rail, nothing written. A file the API cannot read is a 400 PurserError naming the line.
260
+ */
261
+ runShadowMode(csv: string, o?: ShadowOptions): Promise<ShadowReport>;
162
262
  }
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Purser's TypeScript client (sdk/typescript/README.md): read the books, propose an invoice's payment, read a proposal's
2
- // status. No dependency: the platform's fetch. Its operations are those of openapi/purser.yaml (test/sdk-typescript.test.ts
2
+ // status, a payment's dossier and its bank file, and back-test past invoices (shadow mode). No dependency: the platform's
3
+ // fetch. The adapters for agent frameworks (src/adapters/, subpaths of the package) are built on this client. Its operations are those of openapi/purser.yaml (test/sdk-typescript.test.ts
3
4
  // checks every one against the document).
4
5
  //
5
6
  // What it cannot do, on purpose: approve. Approving a payment is a signed-in person's passkey over the exact terms, in
@@ -13,6 +14,9 @@ export const OPERATIONS = {
13
14
  listPayableInvoices: ["GET", "/v1/engine/invoices"],
14
15
  proposePayment: ["POST", "/v1/engine/invoices/{id}/pay"],
15
16
  getProposal: ["GET", "/v1/engine/proposals/{id}"],
17
+ getBankFile: ["GET", "/v1/engine/proposals/{id}/bank-file"],
18
+ getPaymentDossier: ["GET", "/v1/engine/proposals/{id}/dossier"],
19
+ runShadowMode: ["POST", "/v1/engine/shadow"],
16
20
  };
17
21
  /**
18
22
  * An answer that was not 2xx (the API's sentence for a person and its stable code for a program), or a 2xx answer the
@@ -29,7 +33,7 @@ export class PurserError extends Error {
29
33
  }
30
34
  }
31
35
  /** This client's version, sent in its User-Agent (purser-client/<version>); the package's own (test/sdk-typescript.test.ts). */
32
- export const VERSION = "1.6.0";
36
+ export const VERSION = "1.7.1";
33
37
  export const USER_AGENT = `purser-client/${VERSION}`;
34
38
  /** Whether an answer's status is worth asking again (a read only): too many requests, or the server's fault. */
35
39
  export const RETRYABLE = (status) => status === 429 || (status >= 500 && status <= 599);
@@ -82,7 +86,7 @@ export class Purser {
82
86
  static fromEnv(env = platformEnv()) {
83
87
  return new Purser({ baseUrl: env.PURSER_BASE_URL || env.PURSER_URL || "", apiKey: env.PURSER_API_KEY ?? "" });
84
88
  }
85
- async #call(op, id, query, post = {}) {
89
+ async #call(op, id, query, post = {}, body) {
86
90
  const [method, path] = OPERATIONS[op];
87
91
  if (path.includes("{id}") && !(id && ID.test(id)))
88
92
  throw new Error(`${op} needs an id like AP-0004 or P-0009`);
@@ -92,33 +96,34 @@ export class Purser {
92
96
  const key = method === "POST" ? (post.idempotencyKey ?? (this.#idempotencyKeys ? crypto.randomUUID() : undefined)) : undefined;
93
97
  if (key !== undefined && !/^[\x21-\x7e]{1,255}$/.test(key))
94
98
  throw new Error("idempotencyKey is 1 to 255 printable characters without spaces");
95
- const res = await this.#send(url, method, key);
99
+ const res = await this.#send(url, method, key, body);
96
100
  const text = await res.text();
97
- let body = null;
101
+ let answer = null;
98
102
  try {
99
- body = text ? JSON.parse(text) : null;
103
+ answer = text ? JSON.parse(text) : null;
100
104
  }
101
105
  catch { /* not JSON: said below */ }
102
106
  if (!res.ok) {
103
- const e = (body ?? {});
107
+ const e = (answer ?? {});
104
108
  throw new PurserError(res.status, e.code ?? "error", e.error ?? `HTTP ${res.status}`);
105
109
  }
106
- if (body === null)
110
+ if (answer === null)
107
111
  throw new PurserError(res.status, "not_json", "the answer was not JSON");
108
- return body;
112
+ return answer;
109
113
  }
110
114
  /**
111
115
  * One request, with the timeout and the client's signal; tried again after a 429 or a 5xx, as `retries` says, when it
112
116
  * is a read or carries an Idempotency-Key (every try the same key).
113
117
  */
114
- async #send(url, method, idempotencyKey) {
118
+ async #send(url, method, idempotencyKey, body) {
115
119
  const tries = method === "GET" || idempotencyKey !== undefined ? this.#retries + 1 : 1;
116
120
  for (let attempt = 1;; attempt++) {
117
121
  this.#signal?.throwIfAborted();
118
122
  const signals = [this.#signal, this.#timeoutMs ? AbortSignal.timeout(this.#timeoutMs) : undefined].filter((x) => x !== undefined);
119
123
  const res = await this.#fetch(url, {
120
124
  method,
121
- headers: { authorization: `Bearer ${this.#key}`, accept: "application/json", "user-agent": USER_AGENT, ...(idempotencyKey !== undefined ? { "idempotency-key": idempotencyKey } : {}) },
125
+ headers: { authorization: `Bearer ${this.#key}`, accept: "application/json", "user-agent": USER_AGENT, ...(idempotencyKey !== undefined ? { "idempotency-key": idempotencyKey } : {}), ...(body ? { "content-type": body.type } : {}) },
126
+ ...(body ? { body: body.text } : {}),
122
127
  ...(signals.length ? { signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals) } : {}),
123
128
  });
124
129
  if (attempt >= tries || !RETRYABLE(res.status))
@@ -171,6 +176,36 @@ export class Purser {
171
176
  async getProposal(id) {
172
177
  return (await this.#call("getProposal", id)).proposal;
173
178
  }
179
+ /**
180
+ * The SEPA credit transfer file (pain.001.001.09) an approved bank file payment was executed as; a 404 PurserError
181
+ * when none was filed. The API answers it only to a signed-in CFO (its approve scope): every API key is refused with
182
+ * 403, so this needs the CFO's own session, never an agent's key. It only reads: the file is made once, at execution.
183
+ */
184
+ async getBankFile(proposalId) {
185
+ return (await this.#call("getBankFile", proposalId)).bank_file;
186
+ }
187
+ /**
188
+ * One payment's authorisation dossier, by its proposal's id or its invoice's (a read key): the exact terms and their
189
+ * hash, who signed them and when, the policy, the checks, the transfers and the audit rows; a 404 PurserError when the
190
+ * company holds no such payment. `npm run dossier -- --verify` in a clone checks one offline.
191
+ */
192
+ async getPaymentDossier(id) {
193
+ return (await this.#call("getPaymentDossier", id)).dossier;
194
+ }
195
+ /**
196
+ * Shadow mode, the back-test (a read key): past paid supplier invoices as CSV text (at most 2 MB; the columns:
197
+ * docs/shadow/README.md), replayed through Purser's checks under the company's CFO policy: for each row what Purser
198
+ * would have done and why. `aloneLimit` ("2000.00", or "none") sets the limit to pay alone for this replay only. Code
199
+ * only: no model, no rail, nothing written. A file the API cannot read is a 400 PurserError naming the line.
200
+ */
201
+ async runShadowMode(csv, o = {}) {
202
+ if (typeof csv !== "string" || !csv.trim())
203
+ throw new Error("runShadowMode needs the CSV's text");
204
+ const { aloneLimit, ...post } = o;
205
+ if (aloneLimit !== undefined && aloneLimit !== "none" && !/^\d{1,9}\.\d{2}$/.test(aloneLimit))
206
+ throw new Error('aloneLimit is an amount in EUR like "2000.00", or "none"');
207
+ return (await this.#call("runShadowMode", undefined, { alone_limit: aloneLimit }, post, { type: "text/csv", text: csv })).report;
208
+ }
174
209
  }
175
210
  /** Waits, or rejects as soon as the signal fires. */
176
211
  function sleep(ms, signal) {
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "purser-client",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
4
4
  "description": "Purser's TypeScript client: read the books, propose an invoice's payment, read a proposal's status. It cannot approve: only the CFO's passkey does.",
5
- "keywords": ["purser", "accounts-payable", "payments", "x402"],
5
+ "keywords": ["purser", "accounts-payable", "payments", "x402", "ai-agents", "ai-sdk", "openai-agents", "langchain"],
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/agamemnon-coder/x402-business-agents/tree/main/sdk/typescript#readme",
8
8
  "bugs": "https://github.com/agamemnon-coder/x402-business-agents/issues",
@@ -20,6 +20,22 @@
20
20
  "types": "./dist/index.d.ts",
21
21
  "default": "./dist/index.js"
22
22
  },
23
+ "./guard": {
24
+ "types": "./dist/adapters/guard.d.ts",
25
+ "default": "./dist/adapters/guard.js"
26
+ },
27
+ "./ai-sdk": {
28
+ "types": "./dist/adapters/ai-sdk.d.ts",
29
+ "default": "./dist/adapters/ai-sdk.js"
30
+ },
31
+ "./openai-agents": {
32
+ "types": "./dist/adapters/openai-agents.d.ts",
33
+ "default": "./dist/adapters/openai-agents.js"
34
+ },
35
+ "./langchain": {
36
+ "types": "./dist/adapters/langchain.d.ts",
37
+ "default": "./dist/adapters/langchain.js"
38
+ },
23
39
  "./package.json": "./package.json"
24
40
  },
25
41
  "files": ["dist", "README.md", "LICENSE"],