Skip to content
Open
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@
"author": "",
"license": "MIT",
"dependencies": {
"@contextvm/sdk": "^0.11.14",
"@contextvm/sdk": "^0.13.0",
"@modelcontextprotocol/sdk": "^1.27.1",
"json-schema-to-typescript": "15.0.4",
"nostr-tools": "^2.23.3",
Expand Down
81 changes: 31 additions & 50 deletions pnpm-lock.yaml

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

35 changes: 34 additions & 1 deletion src/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import { generatePrivateKey, normalizePrivateKey, normalizePublicKey } from './u
import { BOLD, CYAN, DIM, RESET, TEXT } from './constants/ui.ts';
import { renderDefaultResult } from './call/render-result.ts';
import { renderSchemaProperties, renderToolSchema } from './call/render-schema.ts';
import { withClientPayments, PMI_BITCOIN_LIGHTNING_BOLT11 } from '@contextvm/sdk/payments';
import type { PaymentInteractionMode } from '@contextvm/sdk/payments';
import { CliPaymentHandler } from './payments/cli-payment-handler.ts';

const HEX_PUBKEY_PATTERN = /^[0-9a-f]{64}$/i;

Expand All @@ -37,6 +40,7 @@ export interface CallOptions {
prettyRaw?: boolean;
extract?: string;
help?: boolean;
paymentMode?: PaymentInteractionMode;
}

export interface ParseCallResult {
Expand All @@ -56,6 +60,7 @@ export interface ParseCallResult {
showServerDetails: boolean;
config: string | undefined;
unknownFlags: string[];
paymentMode: PaymentInteractionMode;
}

interface ResolvedServerTarget {
Expand Down Expand Up @@ -118,6 +123,7 @@ export function parseCallArgs(args: string[]): ParseCallResult {
showServerDetails: false,
config: undefined,
unknownFlags: [],
paymentMode: 'transparent',
};

for (let i = 0; i < args.length; i++) {
Expand Down Expand Up @@ -167,6 +173,13 @@ export function parseCallArgs(args: string[]): ParseCallResult {
result.isStateless = false;
} else if (arg === '--details') {
result.showServerDetails = true;
} else if (arg === '--payment-mode') {
const value = consumeValue('--payment-mode');
if (value === 'transparent' || value === 'explicit_gating') {
result.paymentMode = value;
} else {
result.unknownFlags.push(`--payment-mode${value ? ` (${value})` : ''}`);
}
} else if (arg.startsWith('--')) {
result.unknownFlags.push(arg);
} else if (!result.server) {
Expand Down Expand Up @@ -511,8 +524,18 @@ async function createRemoteClient(target: ResolvedServerTarget, options: CallOpt
logLevel: options.debug ? 'debug' : 'silent',
});

const cliHandler = new CliPaymentHandler({
pmi: PMI_BITCOIN_LIGHTNING_BOLT11,
verbose: options.verbose,
});

const paidTransport = withClientPayments(transport, {
handlers: [cliHandler],
paymentInteraction: options.paymentMode ?? 'transparent',
});

const client = new Client({ name: 'cvmi', version: '0.1.0' });
await client.connect(transport);
await client.connect(paidTransport);

return {
client,
Expand Down Expand Up @@ -718,6 +741,11 @@ function isMissingToolInvocationError(error: unknown): boolean {
return /tool.+not found|unknown tool|method not found|-32601/i.test(error.message);
}

function isPaymentRequiredError(error: unknown): boolean {
// CEP-8 Payment Required JSON-RPC error code
return error instanceof Error && 'code' in error && (error as any).code === -32042;
}

export async function call(
serverArg: string | undefined,
capabilityArg: string | undefined,
Expand Down Expand Up @@ -793,6 +821,10 @@ export async function call(
);
} catch (error) {
if (!isMissingToolInvocationError(error)) {
if (options.paymentMode === 'explicit_gating' && isPaymentRequiredError(error)) {
console.log(JSON.stringify((error as any).data, null, 2));
process.exit(2);
}
throw error;
}

Expand Down Expand Up @@ -845,6 +877,7 @@ ${BOLD}Options:${RESET}
--private-key <key> Your Nostr private key (hex/nsec format, overrides env, auto-generated if not provided)
--relays <urls> Comma-separated relay URLs
--encryption-mode Encryption mode: optional, required, disabled
--payment-mode Payment interaction mode: transparent (default), explicit_gating
--stateless Enable stateless transport mode (default)
--stateful Disable stateless transport mode
--details Show resolved server identity and relay details during inspection
Expand Down
43 changes: 43 additions & 0 deletions src/payments/cli-payment-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { PaymentHandler, PaymentHandlerRequest } from '@contextvm/sdk/payments';
import { BOLD, CYAN, DIM, RESET, TEXT } from '../constants/ui.ts';

/**
* CLI payment handler for transparent mode.
*
* - Lets the SDK advertise the PMI via `pmi` tags (CEP-8 discovery)
* - Captures `payment_required` and renders the invoice in the terminal
* - Does NOT attempt to pay (human pays out-of-band)
*/
export class CliPaymentHandler implements PaymentHandler {
public readonly pmi: string;
private readonly verbose: boolean;

constructor(options: { pmi: string; verbose?: boolean }) {
this.pmi = options.pmi;
this.verbose = options.verbose ?? false;
}

canHandle(_req: PaymentHandlerRequest): boolean {
return true;
}

async handle(req: PaymentHandlerRequest): Promise<void> {
console.error();
console.error(`${BOLD}⚡ Payment Required${RESET}`);
console.error(`${DIM}${'─'.repeat(50)}${RESET}`);
console.error(` ${CYAN}Amount:${RESET} ${req.amount}`);
if (req.description) {
console.error(` ${CYAN}Description:${RESET} ${req.description}`);
}
console.error(` ${CYAN}PMI:${RESET} ${req.pmi}`);
if (req.ttl) {
console.error(` ${CYAN}Expires in:${RESET} ${req.ttl}s`);
}
console.error(`${DIM}${'─'.repeat(50)}${RESET}`);
console.error(` ${CYAN}Invoice:${RESET}`);
console.error(` ${TEXT}${req.pay_req}${RESET}`);
console.error(`${DIM}${'─'.repeat(50)}${RESET}`);
console.error();
console.error(`${DIM}Pay the invoice above. The CLI is waiting for confirmation...${RESET}`);
}
}
Loading