@agenzo/merchant-cli 0.2.2 → 0.3.0

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/core/errors.ts","../src/core/config-manager.ts","../src/core/formatter.ts","../src/core/output.ts","../src/core/version.ts","../src/ride/quote.ts","../src/core/api-client.ts","../src/core/prompt-engine.ts","../src/utils/cli-help.ts","../src/ride/book.ts","../src/utils/idempotency.ts","../src/ride/get.ts","../src/ride/cancel.ts","../src/ride/list-orders.ts","../src/services/list.ts","../src/services/registry.ts","../src/services/get.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { CliError } from './core/errors.js';\nimport { getHost, resetHost, setHost } from './core/config-manager.js';\nimport { Formatter } from './core/formatter.js';\nimport { emit, type OutputFormat } from './core/output.js';\nimport { getCurrentVersion } from './core/version.js';\n\n// Ride command builders\nimport { buildQuoteCommand } from './ride/quote.js';\nimport { buildBookCommand } from './ride/book.js';\nimport { buildRideGetCommand } from './ride/get.js';\nimport { buildCancelCommand } from './ride/cancel.js';\nimport { buildListOrdersCommand } from './ride/list-orders.js';\n\n// Services command builders\nimport { buildServicesListCommand } from './services/list.js';\nimport { buildServiceGetCommand } from './services/get.js';\n\nfunction resolveFormat(cmd: Command): OutputFormat {\n return cmd.optsWithGlobals().format === 'table' ? 'table' : 'json';\n}\n\nasync function main(): Promise<void> {\n const program = new Command();\n program\n .name('agenzo-merchant-cli')\n .description('CLI for ordering rides and querying merchant services')\n .version(getCurrentVersion())\n .option('--format <format>', 'Output format: json|table', 'json')\n .option('--yes', 'Skip confirmation prompts (for automation/AI Agents)', false)\n .option('--api-key <key>', 'API key for runtime requests');\n\n // config group — fully implemented locally (no network)\n const config = program.command('config').description('Local API host configuration');\n config\n .command('set-host <url>')\n .description('Set the API host')\n .action((url: string) => {\n setHost(url);\n console.log(Formatter.status('success', `API host set to ${getHost()}`));\n });\n config\n .command('reset-host')\n .description('Reset the API host to the default')\n .action(() => {\n resetHost();\n console.log(Formatter.status('success', `API host reset to ${getHost()}`));\n });\n config\n .command('show')\n .description('Show the current configuration')\n .action((_options, cmd: Command) => {\n emit({ host: getHost() }, resolveFormat(cmd));\n });\n\n // ride-elife group\n const rideElife = program\n .command('ride-elife')\n .description('Ride ordering (eLife): quote, book, get, cancel, list-orders');\n rideElife.addCommand(buildQuoteCommand());\n rideElife.addCommand(buildBookCommand());\n rideElife.addCommand(buildRideGetCommand());\n rideElife.addCommand(buildCancelCommand());\n rideElife.addCommand(buildListOrdersCommand());\n\n // services group\n const services = program.command('services').description('Service registry: list, get');\n services.addCommand(buildServicesListCommand());\n services.addCommand(buildServiceGetCommand());\n\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error: unknown) => {\n if (error instanceof CliError) {\n console.error(Formatter.status('error', error.message));\n if (error.recovery) console.error(Formatter.status('info', error.recovery));\n process.exit(error.exitCode);\n }\n console.error(\n Formatter.status('error', error instanceof Error ? error.message : 'An unexpected error occurred'),\n );\n process.exit(1);\n});\n","/**\n * SCREAMING_SNAKE_CASE error codes shared across the CLI. Server-returned\n * codes are passed through verbatim; this catalog is the well-known set the\n * CLI itself raises, special-cases, or recognizes from the backend so that\n * agents (and the schema `error_recovery` blocks) never reference an orphan\n * code. Codes are grouped by origin.\n */\nexport const ErrorCodes = {\n // -- Ride/elife domain (raised by the backend, recognized here) --\n QUOTE_EXPIRED: 'QUOTE_EXPIRED',\n VEHICLE_UNAVAILABLE: 'VEHICLE_UNAVAILABLE',\n BOOKING_FAILED: 'BOOKING_FAILED',\n CANCELLATION_NOT_ALLOWED: 'CANCELLATION_NOT_ALLOWED',\n\n // -- Billing / settlement-account (monthly_settlement) --\n BILLING_MODE_MISMATCH: 'BILLING_MODE_MISMATCH',\n ACCOUNT_NOT_FOUND: 'ACCOUNT_NOT_FOUND',\n ACCOUNT_SUSPENDED: 'ACCOUNT_SUSPENDED',\n ACCOUNT_INSUFFICIENT_BALANCE: 'ACCOUNT_INSUFFICIENT_BALANCE',\n\n // -- Payment order (pay_per_call; reserved until payment-cli ships) --\n PAYMENT_ORDER_NOT_FOUND: 'PAYMENT_ORDER_NOT_FOUND',\n PAYMENT_ORDER_NOT_PAID: 'PAYMENT_ORDER_NOT_PAID',\n PAYMENT_ORDER_MISMATCH: 'PAYMENT_ORDER_MISMATCH',\n PAYMENT_ORDER_ALREADY_CONSUMED: 'PAYMENT_ORDER_ALREADY_CONSUMED',\n\n // -- Parameter / idempotency --\n PARAM_IDEMPOTENCY_KEY_REQUIRED: 'PARAM_IDEMPOTENCY_KEY_REQUIRED',\n PARAM_IDEMPOTENCY_KEY_CONFLICT: 'PARAM_IDEMPOTENCY_KEY_CONFLICT',\n\n // -- Service discovery --\n SERVICE_NOT_FOUND: 'SERVICE_NOT_FOUND',\n\n // -- CLI-local / transport --\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n CLI_OUTDATED: 'CLI_OUTDATED',\n CONFIG_ERROR: 'CONFIG_ERROR',\n NOT_IMPLEMENTED: 'NOT_IMPLEMENTED',\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/**\n * Single error type for the CLI. `code` identifies the failure class,\n * `recovery` is an optional human-readable next step, and `exitCode` lets\n * specific failures (e.g. CLI_OUTDATED) signal a distinct process exit code.\n */\nexport class CliError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n public readonly recovery?: string,\n public readonly exitCode: number = 1,\n ) {\n super(message);\n this.name = 'CliError';\n }\n}\n","/**\n * Local config persisted at ~/.agenzo-merchant-cli/config.json.\n * Only the API host is stored; everything else is runtime/flag driven.\n */\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { CliError, ErrorCodes } from './errors.js';\n\nexport const DEFAULT_HOST = 'https://agent.everonet.com';\n\nconst CONFIG_DIR = join(homedir(), '.agenzo-merchant-cli');\nconst CONFIG_PATH = join(CONFIG_DIR, 'config.json');\n\ninterface Config {\n host: string;\n}\n\nfunction read(): Config {\n let raw: string;\n try {\n raw = readFileSync(CONFIG_PATH, 'utf-8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return { host: DEFAULT_HOST };\n }\n throw error;\n }\n try {\n const parsed = JSON.parse(raw) as Partial<Config>;\n return { host: parsed.host ?? DEFAULT_HOST };\n } catch {\n throw new CliError(\n ErrorCodes.CONFIG_ERROR,\n `Invalid config file: ${CONFIG_PATH}`,\n 'Delete the file to reset to defaults.',\n );\n }\n}\n\nfunction write(config: Config): void {\n mkdirSync(CONFIG_DIR, { recursive: true });\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf-8');\n}\n\nexport function getHost(): string {\n return read().host;\n}\n\nexport function setHost(host: string): void {\n write({ host: host.replace(/\\/+$/, '') });\n}\n\nexport function resetHost(): void {\n write({ host: DEFAULT_HOST });\n}\n","export type StatusType = 'success' | 'error' | 'info' | 'warning';\n\nconst ICONS: Record<StatusType, string> = {\n success: '✓',\n error: '✗',\n info: 'ℹ',\n warning: '⚠',\n};\n\nconst SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];\n\nexport interface Spinner {\n /** Update the in-progress message. */\n update(message: string): void;\n /** Stop and clear the spinner line (no final status). */\n stop(): void;\n /** Stop and replace the line with a success status. */\n succeed(message?: string): void;\n /** Stop and replace the line with an error status. */\n fail(message?: string): void;\n}\n\n/**\n * TTY-aware progress spinner. Renders to **stderr** so that stdout stays a\n * clean payload stream (agents/scripts piping `| jq` are unaffected).\n *\n * When stderr is not a TTY (piped, redirected, CI, agent-invoked) the animation\n * is suppressed entirely — no control characters leak into logs. The optional\n * final status (`succeed`/`fail`) is still printed in that case so non-TTY\n * callers get a one-line outcome on stderr without the spinning frames.\n */\nexport function createSpinner(message: string): Spinner {\n const isTty = Boolean(process.stderr.isTTY);\n let current = message;\n\n if (!isTty) {\n return {\n update(msg: string) {\n current = msg;\n },\n stop() {},\n succeed(msg?: string) {\n if (msg) process.stderr.write(`${Formatter.status('success', msg)}\\n`);\n },\n fail(msg?: string) {\n process.stderr.write(`${Formatter.status('error', msg ?? current)}\\n`);\n },\n };\n }\n\n let frame = 0;\n const render = (): void => {\n process.stderr.write(`\\r\\x1b[K${SPINNER_FRAMES[frame]} ${current}`);\n frame = (frame + 1) % SPINNER_FRAMES.length;\n };\n render();\n const timer = setInterval(render, 80);\n\n const clear = (): void => {\n clearInterval(timer);\n process.stderr.write('\\r\\x1b[K');\n };\n\n return {\n update(msg: string) {\n current = msg;\n },\n stop() {\n clear();\n },\n succeed(msg?: string) {\n clear();\n if (msg) process.stderr.write(`${Formatter.status('success', msg)}\\n`);\n },\n fail(msg?: string) {\n clear();\n process.stderr.write(`${Formatter.status('error', msg ?? current)}\\n`);\n },\n };\n}\n\nfunction stringify(value: unknown): string {\n if (value === null || value === undefined) return '';\n if (typeof value === 'object') return JSON.stringify(value);\n return String(value);\n}\n\nexport class Formatter {\n /** Status-prefixed line, e.g. \"✓ done\". */\n static status(type: StatusType, message: string): string {\n return `${ICONS[type]} ${message}`;\n }\n\n /** Aligned columnar table for list output. */\n static table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n const line = (cells: string[]): string =>\n cells.map((c, i) => (c ?? '').padEnd(widths[i])).join(' ');\n return [\n line(headers),\n widths.map((w) => '-'.repeat(w)).join(' '),\n ...rows.map(line),\n ].join('\\n');\n }\n\n /** Key-value detail output with left-aligned keys. */\n static keyValue(entries: [string, string][]): string {\n const width = Math.max(0, ...entries.map(([k]) => k.length));\n return entries.map(([k, v]) => `${k.padEnd(width)} ${v}`).join('\\n');\n }\n\n /** Best-effort human-readable rendering of arbitrary data. */\n static auto(data: unknown): string {\n if (Array.isArray(data)) {\n return Formatter.arrayTable(data);\n }\n if (data && typeof data === 'object') {\n const obj = data as Record<string, unknown>;\n const scalarEntries: [string, string][] = [];\n const tableSections: string[] = [];\n for (const [k, v] of Object.entries(obj)) {\n // Render an array-of-objects value as its own labelled sub-table\n // instead of dumping raw JSON on a key-value line.\n if (Array.isArray(v) && v.some((i) => i && typeof i === 'object')) {\n tableSections.push(`${k}:\\n${Formatter.arrayTable(v)}`);\n } else {\n scalarEntries.push([k, stringify(v)]);\n }\n }\n const parts: string[] = [];\n if (scalarEntries.length) parts.push(Formatter.keyValue(scalarEntries));\n parts.push(...tableSections);\n return parts.join('\\n\\n');\n }\n return stringify(data);\n }\n\n /** Render an array of objects as an aligned table; falls back gracefully. */\n private static arrayTable(items: unknown[]): string {\n if (items.length === 0) return '(empty)';\n const rows = items.filter(\n (i): i is Record<string, unknown> => Boolean(i) && typeof i === 'object',\n );\n if (rows.length === 0) {\n return items.map((i) => stringify(i)).join(', ');\n }\n const headers = Object.keys(rows[0]);\n return Formatter.table(\n headers,\n rows.map((r) => headers.map((h) => stringify(r[h]))),\n );\n }\n}\n","import { Formatter } from './formatter.js';\n\nexport type OutputFormat = 'json' | 'table';\n\n/** Schema descriptor a verb reserves for `--help --format json`. */\nexport interface VerbSchema {\n description: string;\n params: Record<string, string>;\n response: Record<string, string>;\n}\n\n/** Emit a result payload in the requested format (json default, table via Formatter). */\nexport function emit(data: unknown, format: OutputFormat = 'json'): void {\n if (format === 'table') {\n console.log(Formatter.auto(data));\n } else {\n console.log(JSON.stringify(data, null, 2));\n }\n}\n\n/**\n * Emit one NDJSON record (a single-line JSON object terminated by a newline)\n * to stdout. Used by streaming/polling commands (`ride-elife get --watch`):\n * each poll result is written as its own line so an agent can consume the\n * stream incrementally with a line reader. Always compact (no pretty-print),\n * regardless of `--format`, because NDJSON requires one object per line.\n */\nexport function emitNdjsonLine(data: unknown): void {\n console.log(JSON.stringify(data));\n}\n\n/** Helper for `--help --format json`: print a verb's param/response schema. */\nexport function emitSchema(schema: VerbSchema, format: OutputFormat = 'json'): void {\n if (format === 'table') {\n console.log(Formatter.keyValue(Object.entries(schema.params)));\n } else {\n console.log(JSON.stringify(schema, null, 2));\n }\n}\n","/**\n * CLI version source-of-truth + server-driven min-version negotiation.\n *\n * The running version is read from `package.json` at runtime (it lives outside\n * `rootDir`, so we read it via fs rather than importing it to keep `tsc` happy).\n * The server advertises the floor via the `X-CLI-Min-Version` response header;\n * if the local version is below it we throw CLI_OUTDATED and exit with code 2.\n */\nimport { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { CliError, ErrorCodes } from './errors.js';\n\nexport const UPGRADE_COMMAND = 'npm install -g agenzo-merchant-cli@latest';\n\nconst FALLBACK_VERSION = '0.1.0';\n\nlet cached: string | null = null;\n\nexport function getCurrentVersion(): string {\n if (cached !== null) return cached;\n const here = dirname(fileURLToPath(import.meta.url));\n // Both the bundled (dist/index.js) and source layouts resolve to package.json.\n const candidates = [\n join(here, '..', 'package.json'),\n join(here, '..', '..', 'package.json'),\n ];\n for (const p of candidates) {\n try {\n const pkg = JSON.parse(readFileSync(p, 'utf-8')) as { version?: string };\n if (typeof pkg.version === 'string') {\n cached = pkg.version;\n return cached;\n }\n } catch {\n // try the next candidate\n }\n }\n cached = FALLBACK_VERSION;\n return cached;\n}\n\n/** Returns negative / zero / positive comparing `a` against `b` (major.minor.patch). */\nexport function compareVersion(a: string, b: string): number {\n const parse = (v: string): number[] =>\n v\n .trim()\n .replace(/^v/, '')\n .split(/[-+]/)[0]\n .split('.')\n .map((n) => parseInt(n, 10) || 0);\n const pa = parse(a);\n const pb = parse(b);\n for (let i = 0; i < 3; i++) {\n const diff = (pa[i] ?? 0) - (pb[i] ?? 0);\n if (diff !== 0) return diff;\n }\n return 0;\n}\n\n/** Throw CLI_OUTDATED (exit code 2) when the local version is below the header floor. */\nexport function enforceMinVersion(header: string | null): void {\n const min = header?.trim();\n if (!min) return;\n const current = getCurrentVersion();\n if (compareVersion(current, min) < 0) {\n throw new CliError(\n ErrorCodes.CLI_OUTDATED,\n `CLI ${current} is below the required minimum ${min}.`,\n `Upgrade: ${UPGRADE_COMMAND}`,\n 2,\n );\n }\n}\n","import { Command } from 'commander';\nimport { ApiClient } from '../core/api-client.js';\nimport { CliError } from '../core/errors.js';\nimport { emit, type OutputFormat } from '../core/output.js';\nimport { createSpinner } from '../core/formatter.js';\nimport { PromptEngine } from '../core/prompt-engine.js';\nimport { attachSchemaHelp } from '../utils/cli-help.js';\nimport type { QuoteResponse } from '../types/api.js';\n\n/** Reserved for `--help --format json`. */\nexport const quoteSchema = {\n description: 'Request fare quotes for a ride between two points.',\n params: {\n 'pickup-lat': 'number — pickup latitude',\n 'pickup-lng': 'number — pickup longitude',\n 'pickup-name': 'string — pickup location name',\n 'dropoff-lat': 'number — dropoff latitude',\n 'dropoff-lng': 'number — dropoff longitude',\n 'dropoff-name': 'string — dropoff location name',\n 'pickup-time': 'number|string — epoch seconds, or \"now\"',\n 'passenger-name': 'string — optional, lead passenger full name',\n 'passenger-phone': 'string — optional, passenger phone in E.164 format',\n 'passenger-count': 'number — optional passenger count',\n 'luggage-count': 'number — optional luggage count',\n 'passenger-email': 'string — optional passenger email',\n 'children-count': 'number — optional children count',\n },\n response: {\n vehicle_classes:\n 'VehicleClass[] — each: vehicle_class, price{amount,currency,quote_id}, passenger_capacity, luggage_capacity (amount is a decimal in the currency standard unit, e.g. 42.50 = $42.50)',\n meet_and_greet: 'object|null — { available: boolean, price: { amount, currency } } when applicable',\n is_airport_transfer: 'boolean',\n airport_direction: 'string|null — pickup/dropoff direction for airport transfers',\n },\n};\n\nfunction need(value: string | undefined, flag: string): string {\n if (value === undefined) throw new CliError('PARAM_REQUIRED', `Missing required --${flag}.`);\n return value;\n}\n\nfunction num(value: string | undefined, flag: string): number {\n const n = Number(need(value, flag));\n if (!Number.isFinite(n)) throw new CliError('PARAM_INVALID', `--${flag} must be a number.`);\n return n;\n}\n\nexport function buildQuoteCommand(): Command {\n const cmd = new Command('quote')\n .description(quoteSchema.description)\n .option('--pickup-lat <lat>', 'Pickup latitude')\n .option('--pickup-lng <lng>', 'Pickup longitude')\n .option('--pickup-name <name>', 'Pickup location name')\n .option('--dropoff-lat <lat>', 'Dropoff latitude')\n .option('--dropoff-lng <lng>', 'Dropoff longitude')\n .option('--dropoff-name <name>', 'Dropoff location name')\n .option('--pickup-time <time>', 'Pickup time: epoch seconds, or \"now\"')\n .option('--passenger-name <name>', 'Lead passenger full name')\n .option('--passenger-phone <phone>', 'Passenger phone (E.164)')\n .option('--passenger-count <n>', 'Passenger count')\n .option('--luggage-count <n>', 'Luggage count')\n .option('--passenger-email <email>', 'Passenger email')\n .option('--children-count <n>', 'Children count')\n .action(async (_opts, command: Command) => {\n const o = command.optsWithGlobals();\n const format: OutputFormat = o.format === 'table' ? 'table' : 'json';\n const apiKey = await PromptEngine.resolveInput(o.apiKey, {\n message: 'API key:',\n type: 'password',\n });\n\n const body: Record<string, unknown> = {\n pickup: {\n lat: num(o.pickupLat, 'pickup-lat'),\n lng: num(o.pickupLng, 'pickup-lng'),\n name: need(o.pickupName, 'pickup-name'),\n },\n dropoff: {\n lat: num(o.dropoffLat, 'dropoff-lat'),\n lng: num(o.dropoffLng, 'dropoff-lng'),\n name: need(o.dropoffName, 'dropoff-name'),\n },\n pickup_time: o.pickupTime === 'now' ? 'now' : num(o.pickupTime, 'pickup-time'),\n };\n if (o.passengerName) body.passenger_name = o.passengerName;\n if (o.passengerPhone) body.passenger_phone = o.passengerPhone;\n if (o.passengerCount !== undefined) body.passenger_count = num(o.passengerCount, 'passenger-count');\n if (o.luggageCount !== undefined) body.luggage_count = num(o.luggageCount, 'luggage-count');\n if (o.childrenCount !== undefined) body.children_count = num(o.childrenCount, 'children-count');\n if (o.passengerEmail !== undefined) body.passenger_email = o.passengerEmail;\n\n const client = new ApiClient({ apiKey });\n const spinner = createSpinner('Fetching quotes...');\n try {\n const data = await client.post<QuoteResponse>('/ride/quote', { body });\n spinner.stop();\n emit(data, format);\n } catch (err) {\n spinner.fail('Quote request failed');\n throw err;\n }\n });\n\n return attachSchemaHelp(cmd, quoteSchema);\n}\n","/**\n * HTTPS client for the ride/services API.\n *\n * - base = configured host; ride endpoints live under the `/api/v3/agent-pay` prefix\n * - auth via `X-Api-Key` header\n * - write operations may carry an `Idempotency-Key` header (never in the body)\n * - unwraps the v3 envelope `{ code, message, data }`: returns `data` on\n * success (code \"0000\"), throws CliError (server code/message) on failure\n * - negotiates the CLI version floor via the `X-CLI-Min-Version` header\n * - maps connection/timeout failures to NETWORK_ERROR / TIMEOUT\n */\nimport { CliError, ErrorCodes } from './errors.js';\nimport { getHost } from './config-manager.js';\nimport { enforceMinVersion, getCurrentVersion } from './version.js';\n\nconst RIDE_PREFIX = '/api/v3/agent-pay';\n\nexport interface ApiClientOptions {\n apiKey: string;\n host?: string;\n timeout?: number;\n}\n\nexport interface RequestOptions {\n body?: Record<string, unknown>;\n idempotencyKey?: string;\n query?: Record<string, string | number | boolean | undefined>;\n}\n\ninterface Envelope<T> {\n code?: string;\n message?: string;\n data?: T;\n}\n\nexport class ApiClient {\n private readonly host: string;\n private readonly apiKey: string;\n private readonly timeout: number;\n\n constructor(options: ApiClientOptions) {\n this.apiKey = options.apiKey;\n this.host = (options.host ?? getHost()).replace(/\\/+$/, '');\n this.timeout = options.timeout ?? 30000;\n }\n\n get<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n\n post<T>(path: string, options: RequestOptions = {}): Promise<T> {\n return this.request<T>('POST', path, options);\n }\n\n private async request<T>(\n method: string,\n path: string,\n options: RequestOptions,\n ): Promise<T> {\n let url = `${this.host}${RIDE_PREFIX}${path}`;\n if (options.query) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined) params.set(key, String(value));\n }\n const qs = params.toString();\n if (qs) url += `?${qs}`;\n }\n\n const headers: Record<string, string> = {\n 'X-Api-Key': this.apiKey,\n 'User-Agent': `agenzo-merchant-cli/${getCurrentVersion()}`,\n };\n if (options.body) headers['Content-Type'] = 'application/json';\n if (options.idempotencyKey) headers['Idempotency-Key'] = options.idempotencyKey;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n\n let response: Response;\n try {\n response = await fetch(url, {\n method,\n headers,\n body: options.body ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new CliError(\n ErrorCodes.TIMEOUT,\n `Request timed out after ${this.timeout}ms: ${url}`,\n 'Retry, or check your network connection.',\n );\n }\n throw new CliError(\n ErrorCodes.NETWORK_ERROR,\n `Network request failed: ${url}`,\n 'Check your network connection and the configured API host.',\n );\n } finally {\n clearTimeout(timer);\n }\n\n // Enforce the server-advertised version floor before reading the body.\n enforceMinVersion(response.headers.get('x-cli-min-version'));\n\n const text = await response.text();\n let envelope: Envelope<T>;\n try {\n envelope = JSON.parse(text) as Envelope<T>;\n } catch {\n throw new CliError(\n ErrorCodes.NETWORK_ERROR,\n `Unexpected non-JSON response (HTTP ${response.status}) from ${url}`,\n );\n }\n\n if (envelope.code !== undefined && envelope.code !== '0000') {\n const code = envelope.code;\n const message = envelope.message ?? `Request failed (HTTP ${response.status})`;\n throw new CliError(code, message);\n }\n\n return envelope.data as T;\n }\n}\n","import { confirm, input, password, select } from '@inquirer/prompts';\n\nexport interface ResolveOptions {\n message: string;\n type?: 'input' | 'password' | 'select';\n choices?: { name: string; value: string }[];\n validate?: (value: string) => boolean | string;\n}\n\n/**\n * Interactive resolution for missing required parameters (api-key,\n * idempotency-key, etc.). When a flag value is supplied it is returned as-is.\n */\nexport class PromptEngine {\n static async resolveInput(\n flagValue: string | undefined,\n options: ResolveOptions,\n ): Promise<string> {\n if (flagValue !== undefined) return flagValue;\n if (options.type === 'password') {\n return password({ message: options.message, mask: '*' });\n }\n if (options.type === 'select' && options.choices) {\n return select({ message: options.message, choices: options.choices });\n }\n return input({ message: options.message, validate: options.validate });\n }\n\n /** Confirmation prompt; auto-approves when `--yes` is set. */\n static async confirm(message: string, yes: boolean): Promise<boolean> {\n if (yes) return true;\n return confirm({ message });\n }\n}\n","/**\n * `--help --format <fmt>` support shared by the read-only verbs.\n *\n * Commander processes `--help` before later argv tokens, so the resolved\n * `--format` option is not yet available when help renders. We therefore read\n * the format directly from `process.argv`: when it is explicitly `json`/`table`\n * we print the verb schema (via emitSchema) instead of the usage text, and let\n * commander render the default help otherwise.\n */\nimport type { Command } from 'commander';\nimport { emitSchema, type OutputFormat, type VerbSchema } from '../core/output.js';\n\nfunction explicitFormat(): OutputFormat | undefined {\n const argv = process.argv;\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n if (a === '--format=json' || (a === '--format' && argv[i + 1] === 'json')) return 'json';\n if (a === '--format=table' || (a === '--format' && argv[i + 1] === 'table')) return 'table';\n }\n return undefined;\n}\n\n/** Print `schema` for `--help --format json|table`; otherwise default usage. */\nexport function attachSchemaHelp(cmd: Command, schema: VerbSchema): Command {\n const baseHelp = cmd.helpInformation.bind(cmd);\n cmd.helpInformation = (ctx) => {\n const format = explicitFormat();\n if (!format) return baseHelp(ctx);\n emitSchema(schema, format);\n return '';\n };\n return cmd;\n}\n","/*\n * Booking funding is decided server-side by the developer's billing_mode:\n * - monthly_settlement: no payment handle; fare is deducted from the\n * developer's settlement account (payment_status=ON_ACCOUNT).\n * - pay_per_call: pass --payment-order-id (a PAID order from payment-cli).\n * Reserved — gated server-side until payment-cli ships (BACK-040).\n * The CLI no longer accepts --payment-method-id (the merchant domain never\n * holds a payment credential).\n */\nimport { Command } from 'commander';\nimport { ApiClient } from '../core/api-client.js';\nimport { emit, emitSchema, type OutputFormat, type VerbSchema } from '../core/output.js';\nimport { Formatter, createSpinner } from '../core/formatter.js';\nimport { PromptEngine } from '../core/prompt-engine.js';\nimport { resolveIdempotencyKey } from '../utils/idempotency.js';\n\n/** Reserved for `--help --format json`. */\nexport const bookSchema: VerbSchema = {\n description: 'Book a ride against a previously returned quote.',\n params: {\n 'quote-id': 'string — required, quote id from `ride-elife quote`',\n 'vehicle-class': 'string — required, chosen vehicle class',\n 'price-amount': 'number — required, fare in decimal currency units (not cents)',\n 'price-currency': 'string — currency code (default USD)',\n 'payment-order-id': 'string — conditional. Required for pay_per_call billing (a PAID order from payment-cli); omit for monthly_settlement (deducted from the settlement account)',\n 'passenger-name': 'string — required, passenger full name',\n 'passenger-phone': 'string — required, passenger phone',\n 'passenger-email': 'string — optional passenger email',\n 'luggage-count': 'number — optional luggage count',\n 'special-requests': 'string — optional free-text requests',\n 'pickup-lat': 'number — required, pickup latitude',\n 'pickup-lng': 'number — required, pickup longitude',\n 'pickup-name': 'string — required, pickup location name',\n 'dropoff-lat': 'number — required, dropoff latitude',\n 'dropoff-lng': 'number — required, dropoff longitude',\n 'dropoff-name': 'string — required, dropoff location name',\n 'pickup-time': 'number|string — required, epoch seconds or \"now\" (must match quote)',\n 'meet-and-greet': 'boolean — optional meet & greet service',\n 'meet-and-greet-price': 'number — optional meet & greet surcharge',\n 'welcome-sign': 'string — optional welcome sign text',\n 'child-seat-count': 'number — optional child seats (0-5)',\n 'infant-seat-count': 'number — optional infant seats (0-5)',\n 'toddler-seat-count': 'number — optional toddler seats (0-5)',\n 'arrival-flight-no': 'string — optional arrival flight number',\n 'arrival-airline': 'string — optional arrival airline',\n 'departure-flight-no': 'string — optional departure flight number',\n 'departure-airline': 'string — optional departure airline',\n 'idempotency-key': 'string — required, sent as the Idempotency-Key header (never in body)',\n },\n response: {\n ride_id: 'string — booked ride id, used by `ride-elife get` / `ride-elife cancel`',\n order_id: 'string — internal ride order id (rio_...)',\n status: 'string — initial ride status (e.g. INIT / Pending)',\n is_scheduled: 'boolean — true = scheduled/airport ride, false = realtime',\n order_type: 'string — realtime / airport (derived from pickup-time)',\n price: '{ amount, currency, quote_id } — confirmed fare',\n payment_status: 'string — ON_ACCOUNT (monthly_settlement) or PAID (pay_per_call)',\n billing_entry_id: 'string — settlement ledger entry id (monthly_settlement only)',\n },\n};\n\nexport function buildBookCommand(): Command {\n return new Command('book')\n .description(bookSchema.description)\n .helpOption(false)\n .option('--help', 'Show help (add --format json for the machine-readable schema)')\n .option('--format <format>', 'Output format: json|table')\n .option('--api-key <key>', 'API key for runtime requests')\n .option('--yes', 'Skip confirmation prompts')\n .option('--quote-id <id>', 'Quote id from `ride-elife quote`')\n .option('--vehicle-class <class>', 'Chosen vehicle class')\n .option('--price-amount <amount>', 'Fare in decimal currency units (not cents)')\n .option('--price-currency <currency>', 'Currency code (default USD)')\n .option('--payment-order-id <id>', 'Paid payment order id (pay_per_call mode only)')\n .option('--passenger-name <name>', 'Passenger full name')\n .option('--passenger-phone <phone>', 'Passenger phone')\n .option('--passenger-email <email>', 'Passenger email')\n .option('--luggage-count <n>', 'Luggage count')\n .option('--special-requests <text>', 'Free-text special requests')\n .option('--pickup-lat <lat>', 'Pickup latitude')\n .option('--pickup-lng <lng>', 'Pickup longitude')\n .option('--pickup-name <name>', 'Pickup location name')\n .option('--dropoff-lat <lat>', 'Dropoff latitude')\n .option('--dropoff-lng <lng>', 'Dropoff longitude')\n .option('--dropoff-name <name>', 'Dropoff location name')\n .option('--pickup-time <time>', 'Pickup time: epoch seconds, or \"now\"')\n .option('--meet-and-greet', 'Enable meet & greet service')\n .option('--meet-and-greet-price <amount>', 'Meet & greet surcharge')\n .option('--welcome-sign <text>', 'Welcome sign text')\n .option('--child-seat-count <n>', 'Number of child seats needed')\n .option('--infant-seat-count <n>', 'Number of infant seats needed')\n .option('--toddler-seat-count <n>', 'Number of toddler seats needed')\n .option('--arrival-flight-no <no>', 'Arrival flight number')\n .option('--arrival-airline <airline>', 'Arrival airline')\n .option('--departure-flight-no <no>', 'Departure flight number')\n .option('--departure-airline <airline>', 'Departure airline')\n .option('--idempotency-key <key>', 'Caller-supplied idempotency key')\n .action(async (_options, command: Command) => {\n const merged = command.optsWithGlobals();\n const format: OutputFormat = merged.format === 'table' ? 'table' : 'json';\n\n if (merged.help) {\n const wantsSchema = process.argv.some((a) => a === '--format' || a.startsWith('--format='));\n if (wantsSchema) emitSchema(bookSchema, format);\n else command.outputHelp();\n return;\n }\n\n const yes = merged.yes === true;\n const apiKey = await PromptEngine.resolveInput(merged.apiKey, {\n message: 'API key:',\n type: 'password',\n });\n const quoteId = await PromptEngine.resolveInput(merged.quoteId, { message: 'Quote id:' });\n const vehicleClass = await PromptEngine.resolveInput(merged.vehicleClass, {\n message: 'Vehicle class:',\n });\n const priceAmount = await PromptEngine.resolveInput(merged.priceAmount, {\n message: 'Price amount (decimal):',\n });\n const passengerName = await PromptEngine.resolveInput(merged.passengerName, {\n message: 'Passenger name:',\n });\n const passengerPhone = await PromptEngine.resolveInput(merged.passengerPhone, {\n message: 'Passenger phone:',\n });\n\n const body: Record<string, unknown> = {\n quote_id: quoteId,\n vehicle_class: vehicleClass,\n price_amount: Number(priceAmount),\n price_currency: merged.priceCurrency ?? 'USD',\n passenger_name: passengerName,\n passenger_phone: passengerPhone,\n };\n // Funding is decided server-side by the developer's billing_mode:\n // - monthly_settlement: no payment handle (deducted from the account)\n // - pay_per_call: --payment-order-id (a PAID order from payment-cli)\n // Both flags are optional here; the backend rejects the wrong one.\n if (merged.paymentOrderId) body.payment_order_id = merged.paymentOrderId;\n if (merged.passengerEmail) body.passenger_email = merged.passengerEmail;\n if (merged.luggageCount !== undefined) body.luggage_count = Number(merged.luggageCount);\n if (merged.specialRequests) body.special_requests = merged.specialRequests;\n if (merged.pickupLat || merged.pickupLng || merged.pickupName) {\n body.pickup = { lat: Number(merged.pickupLat), lng: Number(merged.pickupLng), name: merged.pickupName };\n }\n if (merged.dropoffLat || merged.dropoffLng || merged.dropoffName) {\n body.dropoff = { lat: Number(merged.dropoffLat), lng: Number(merged.dropoffLng), name: merged.dropoffName };\n }\n if (merged.pickupTime) {\n body.pickup_time = merged.pickupTime === 'now' ? 'now' : Number(merged.pickupTime);\n }\n if (merged.meetAndGreet) body.meet_and_greet = true;\n if (merged.meetAndGreetPrice !== undefined) body.meet_and_greet_price = Number(merged.meetAndGreetPrice);\n if (merged.welcomeSign) body.welcome_sign = merged.welcomeSign;\n if (merged.childSeatCount !== undefined) body.child_seat_count = Number(merged.childSeatCount);\n if (merged.infantSeatCount !== undefined) body.infant_seat_count = Number(merged.infantSeatCount);\n if (merged.toddlerSeatCount !== undefined) body.toddler_seat_count = Number(merged.toddlerSeatCount);\n if (merged.arrivalFlightNo || merged.arrivalAirline) {\n body.arrival_flight = { flight_no: merged.arrivalFlightNo, airline: merged.arrivalAirline };\n }\n if (merged.departureFlightNo || merged.departureAirline) {\n body.departure_flight = { flight_no: merged.departureFlightNo, airline: merged.departureAirline };\n }\n\n if (!(await PromptEngine.confirm(`Book ride with quote ${quoteId}?`, yes))) {\n console.log(Formatter.status('info', 'Booking aborted.'));\n return;\n }\n\n const idempotencyKey = await resolveIdempotencyKey(merged.idempotencyKey, { yes });\n const client = new ApiClient({ apiKey });\n const spinner = createSpinner('Booking ride...');\n try {\n const data = await client.post('/ride/book', { body, idempotencyKey });\n spinner.stop();\n emit(data, format);\n } catch (err) {\n spinner.fail('Booking failed');\n throw err;\n }\n });\n}\n","import { input } from '@inquirer/prompts';\nimport { CliError, ErrorCodes } from '../core/errors.js';\n\nconst KEY_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\nconst RULE = 'Use 1-128 characters from [A-Za-z0-9_-].';\n\n/** Validate + normalize a caller-supplied idempotency key. */\nexport function normalizeIdempotencyKey(key: string): string {\n const trimmed = key.trim();\n if (!KEY_PATTERN.test(trimmed)) {\n throw new CliError(\n ErrorCodes.PARAM_IDEMPOTENCY_KEY_REQUIRED,\n `Invalid idempotency key: \"${key}\".`,\n RULE,\n );\n }\n return trimmed;\n}\n\n/**\n * Resolve the idempotency key for a write operation. The CLI never generates\n * one: if absent and `--yes` is set it is a hard error, otherwise we prompt.\n */\nexport async function resolveIdempotencyKey(\n flagValue: string | undefined,\n options: { yes?: boolean },\n): Promise<string> {\n if (flagValue !== undefined) return normalizeIdempotencyKey(flagValue);\n if (options.yes) {\n throw new CliError(\n ErrorCodes.PARAM_IDEMPOTENCY_KEY_REQUIRED,\n 'An idempotency key is required for write operations.',\n 'Pass --idempotency-key <key>; the CLI never auto-generates one.',\n );\n }\n const entered = await input({\n message: 'Idempotency key:',\n validate: (v) => KEY_PATTERN.test(v.trim()) || RULE,\n });\n return normalizeIdempotencyKey(entered);\n}\n","import { Command } from 'commander';\nimport { ApiClient } from '../core/api-client.js';\nimport { emit, emitNdjsonLine, type OutputFormat } from '../core/output.js';\nimport { createSpinner } from '../core/formatter.js';\nimport { PromptEngine } from '../core/prompt-engine.js';\nimport { attachSchemaHelp } from '../utils/cli-help.js';\nimport type { GetOrderResponse } from '../types/api.js';\n\n/**\n * Terminal ride statuses (schema `polling.terminal_statuses`). Once the order\n * reaches one of these, `--watch` stops polling. Case-sensitive — must match\n * the server casing exactly.\n */\nconst TERMINAL_STATUSES: ReadonlySet<string> = new Set([\n 'At destination',\n 'Cancelled',\n 'Rejected',\n 'Customer no show',\n 'Driver no show',\n]);\n\n/** Schema `polling.recommended_interval_seconds`. */\nconst DEFAULT_WATCH_INTERVAL_SECONDS = 5;\n/** Safety cap so `--watch` can never poll forever. */\nconst DEFAULT_WATCH_TIMEOUT_SECONDS = 600;\n\n/** Reserved for `--help --format json`. */\nexport const rideGetSchema = {\n description: 'Retrieve a single ride order status by id (repeatable for polling).',\n params: {\n 'order-id': 'string — ride order id (the ride_id returned by `ride-elife book`)',\n watch:\n 'boolean — poll until a terminal status, emitting one NDJSON line per update (default off)',\n 'watch-interval': `number — seconds between polls when --watch is set (default ${DEFAULT_WATCH_INTERVAL_SECONDS})`,\n 'watch-timeout': `number — max seconds to poll before giving up (default ${DEFAULT_WATCH_TIMEOUT_SECONDS})`,\n },\n response: {\n status:\n 'OrderStatus — case-sensitive; terminal states: At destination | Cancelled | Rejected | Customer no show | Driver no show',\n from_location: 'GeoPoint — pickup',\n to_location: 'GeoPoint — dropoff',\n pickup_time: 'number|string',\n vehicle_class: 'string',\n price: 'Price{amount,currency} — amount is a decimal in the currency standard unit',\n final_amount: 'number — final settled fare (realtime, after final-fare settlement); local-cache path only',\n final_settlement_status: 'string — pending | settled | no_adjustment | settlement_pending | not_applicable (local-cache path)',\n passenger: 'Passenger',\n driver: 'Driver — present after assignment',\n vehicle: 'Vehicle — present after assignment',\n },\n};\n\nfunction num(value: string | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n const n = Number(value);\n return Number.isFinite(n) && n > 0 ? n : fallback;\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\nfunction statusOf(data: GetOrderResponse): string | undefined {\n return (data as { status?: string }).status;\n}\n\nexport function buildRideGetCommand(): Command {\n const cmd = new Command('get')\n .description(rideGetSchema.description)\n .option('--order-id <id>', 'Ride order id (the ride_id returned by `ride-elife book`)')\n .option('--watch', 'Poll until a terminal status, emitting one NDJSON line per update')\n .option('--watch-interval <seconds>', 'Seconds between polls when --watch is set')\n .option('--watch-timeout <seconds>', 'Max seconds to poll before giving up')\n .action(async (_opts, command: Command) => {\n const o = command.optsWithGlobals();\n const format: OutputFormat = o.format === 'table' ? 'table' : 'json';\n const apiKey = await PromptEngine.resolveInput(o.apiKey, {\n message: 'API key:',\n type: 'password',\n });\n const orderId = await PromptEngine.resolveInput(o.orderId, { message: 'Order id:' });\n const client = new ApiClient({ apiKey });\n const path = `/ride/${encodeURIComponent(orderId)}/status`;\n\n if (o.watch) {\n await watchUntilTerminal(client, path, {\n intervalMs: num(o.watchInterval, DEFAULT_WATCH_INTERVAL_SECONDS) * 1000,\n timeoutMs: num(o.watchTimeout, DEFAULT_WATCH_TIMEOUT_SECONDS) * 1000,\n });\n return;\n }\n\n const spinner = createSpinner('Fetching ride status...');\n try {\n const data = await client.get<GetOrderResponse>(path);\n spinner.stop();\n emit(data, format);\n } catch (err) {\n spinner.fail('Failed to fetch ride status');\n throw err;\n }\n });\n\n return attachSchemaHelp(cmd, rideGetSchema);\n}\n\n/**\n * Poll the status endpoint, writing each result as an NDJSON line on stdout\n * until the order reaches a terminal status or the timeout elapses. Progress\n * is the NDJSON stream itself, so no spinner is shown (stdout stays a clean\n * line stream an agent can consume incrementally). A network/backend error\n * propagates to the top-level handler exactly like the single-shot path.\n */\nasync function watchUntilTerminal(\n client: ApiClient,\n path: string,\n opts: { intervalMs: number; timeoutMs: number },\n): Promise<void> {\n const deadline = Date.now() + opts.timeoutMs;\n for (;;) {\n const data = await client.get<GetOrderResponse>(path);\n emitNdjsonLine(data);\n\n const status = statusOf(data);\n if (status !== undefined && TERMINAL_STATUSES.has(status)) return;\n\n if (Date.now() + opts.intervalMs >= deadline) {\n emitNdjsonLine({\n watch_status: 'timeout',\n message: `Polling stopped after ${opts.timeoutMs / 1000}s without reaching a terminal status.`,\n last_status: status ?? null,\n });\n return;\n }\n await sleep(opts.intervalMs);\n }\n}\n","import { Command } from 'commander';\nimport { ApiClient } from '../core/api-client.js';\nimport { emit, emitSchema, type OutputFormat, type VerbSchema } from '../core/output.js';\nimport { Formatter, createSpinner } from '../core/formatter.js';\nimport { PromptEngine } from '../core/prompt-engine.js';\nimport { resolveIdempotencyKey } from '../utils/idempotency.js';\n\n/** Reserved for `--help --format json`. */\nexport const cancelSchema: VerbSchema = {\n description: 'Cancel a ride order; may incur a cancellation fee.',\n params: {\n 'order-id': 'string — required, order id (a.k.a. ride id) to cancel',\n 'idempotency-key': 'string — required, sent as the Idempotency-Key header (never in body)',\n },\n response: {\n ride_id: 'string — cancelled ride id',\n ride_stat: 'string — resulting ride status',\n cancellation: '{ cancellation_fee, reversal_amount, currency }',\n refund_amount: 'number — amount credited back to the settlement balance (paid − cancellation_fee)',\n },\n};\n\nexport function buildCancelCommand(): Command {\n return new Command('cancel')\n .description(cancelSchema.description)\n .helpOption(false)\n .option('--help', 'Show help (add --format json for the machine-readable schema)')\n .option('--format <format>', 'Output format: json|table')\n .option('--api-key <key>', 'API key for runtime requests')\n .option('--yes', 'Skip confirmation prompts')\n .option('--order-id <id>', 'Order id (a.k.a. ride id) to cancel')\n .option('--idempotency-key <key>', 'Caller-supplied idempotency key')\n .action(async (_options, command: Command) => {\n const merged = command.optsWithGlobals();\n const format: OutputFormat = merged.format === 'table' ? 'table' : 'json';\n\n if (merged.help) {\n const wantsSchema = process.argv.some((a) => a === '--format' || a.startsWith('--format='));\n if (wantsSchema) emitSchema(cancelSchema, format);\n else command.outputHelp();\n return;\n }\n\n const yes = merged.yes === true;\n const apiKey = await PromptEngine.resolveInput(merged.apiKey, {\n message: 'API key:',\n type: 'password',\n });\n const orderId = await PromptEngine.resolveInput(merged.orderId, { message: 'Order id:' });\n\n if (!(await PromptEngine.confirm(`Cancel order ${orderId}? This may incur a fee.`, yes))) {\n console.log(Formatter.status('info', 'Cancellation aborted.'));\n return;\n }\n\n const idempotencyKey = await resolveIdempotencyKey(merged.idempotencyKey, { yes });\n const client = new ApiClient({ apiKey });\n const spinner = createSpinner('Cancelling ride...');\n try {\n const data = await client.post(`/ride/${encodeURIComponent(orderId)}/cancel`, { idempotencyKey });\n spinner.stop();\n emit(data, format);\n } catch (err) {\n spinner.fail('Cancellation failed');\n throw err;\n }\n });\n}\n","import { Command } from 'commander';\nimport { ApiClient } from '../core/api-client.js';\nimport { emit, type OutputFormat } from '../core/output.js';\nimport { createSpinner } from '../core/formatter.js';\nimport { PromptEngine } from '../core/prompt-engine.js';\nimport { attachSchemaHelp } from '../utils/cli-help.js';\nimport type { ListOrdersResponse } from '../types/api.js';\n\n/** Reserved for `--help --format json`. */\nexport const listOrdersSchema = {\n description: 'List ride orders with pagination and optional filters.',\n params: {\n page: 'number — page number (default 1)',\n 'page-size': 'number — page size (default 20)',\n status: 'OrderStatus — optional status filter',\n 'order-type': 'string — optional order type filter',\n },\n response: {\n orders:\n 'RideOrderListItem[] — each: order_id, ride_id, status, vehicle_class, is_scheduled, scheduled_at, price_amount, final_amount, price_currency, payment_status, final_settlement_status (pending|settled|no_adjustment|settlement_pending|not_applicable), cancellation_fee, provider, created_at, updated_at',\n total: 'number',\n page: 'number',\n page_size: 'number',\n },\n};\n\nexport function buildListOrdersCommand(): Command {\n const cmd = new Command('list-orders')\n .description(listOrdersSchema.description)\n .option('--page <page>', 'Page number', '1')\n .option('--page-size <size>', 'Page size', '20')\n .option('--status <status>', 'Filter by order status')\n .option('--order-type <type>', 'Filter by order type')\n .action(async (_opts, command: Command) => {\n const o = command.optsWithGlobals();\n const format: OutputFormat = o.format === 'table' ? 'table' : 'json';\n const apiKey = await PromptEngine.resolveInput(o.apiKey, {\n message: 'API key:',\n type: 'password',\n });\n\n const client = new ApiClient({ apiKey });\n const spinner = createSpinner('Fetching orders...');\n try {\n const data = await client.get<ListOrdersResponse>('/ride/orders', {\n query: {\n page: Number(o.page),\n page_size: Number(o.pageSize),\n status: o.status,\n order_type: o.orderType,\n },\n });\n spinner.stop();\n emit(data, format);\n } catch (err) {\n spinner.fail('Failed to fetch orders');\n throw err;\n }\n });\n\n return attachSchemaHelp(cmd, listOrdersSchema);\n}\n","import { Command } from 'commander';\nimport { emit, emitSchema, type OutputFormat, type VerbSchema } from '../core/output.js';\nimport { SERVICE_REGISTRY } from './registry.js';\n\n/** Reserved for `--help --format json`. */\nexport const servicesListSchema: VerbSchema = {\n description: 'List available merchant services from the registry.',\n params: {},\n response: {\n services:\n 'Service[] — each with service_id, name, provider, cli_noun, version, verbs',\n },\n};\n\nfunction resolveFormat(cmd: Command): OutputFormat {\n return cmd.optsWithGlobals().format === 'table' ? 'table' : 'json';\n}\n\nexport function buildServicesListCommand(): Command {\n return new Command('list')\n .description(servicesListSchema.description)\n .helpOption(false)\n .option('-h, --help', 'Show help; with --format json prints the schema')\n .action((opts: { help?: boolean }, cmd: Command) => {\n const format = resolveFormat(cmd);\n if (opts.help) {\n emitSchema(servicesListSchema, format);\n return;\n }\n const services = SERVICE_REGISTRY.map((s) => ({\n service_id: s.service_id,\n name: s.name,\n provider: s.provider,\n cli_noun: s.cli_noun,\n version: s.version,\n verbs: s.verbs.join(', '),\n }));\n emit(services, format);\n });\n}\n","/**\n * Built-in static capability registry.\n *\n * NOTE: this is a CLI-bundled, single-merchant catalog — NOT a live backend\n * discovery feed. It does not reflect which services are enabled for the\n * current API key, nor the developer's billing mode (that is a per-developer\n * property decided by the backend, surfaced via the `book` response /\n * error codes, not advertised here). When the `merchant-discovery` backend\n * lands, `services list/get` should fetch from it instead of this table.\n *\n * Each entry describes a CLI-exposed service: which `cli_noun` group hosts it,\n * the verbs it offers (with one-line descriptions), the recommended call\n * `workflow`, and discovery hints. `services list` renders a summary of these\n * entries and `services get <service-id>` returns one in full.\n */\n\nexport interface ServiceDiscovery {\n /** Command an agent can run to discover the verbs in detail. */\n help_command: string;\n}\n\nexport interface ServiceCapability {\n service_id: string;\n name: string;\n description: string;\n version: string;\n /** Upstream capability provider. */\n provider: string;\n /** Top-level CLI noun (command group) that hosts this service's verbs. */\n cli_noun: string;\n /** Verb names exposed under `cli_noun`. */\n verbs: string[];\n /** One-line description per verb, keyed by verb name. */\n verb_descriptions: Record<string, string>;\n /** Ordered call sequence; `[cancel]` is optional. */\n workflow: string[];\n /** ISO date the capability became available. */\n since: string;\n discovery: ServiceDiscovery;\n}\n\n/** Static registry. This iteration ships a single `ride-elife` capability. */\nexport const SERVICE_REGISTRY: ServiceCapability[] = [\n {\n service_id: 'ride-elife',\n name: 'Ride hailing (eLife)',\n description: 'On-demand ride ordering: quote a fare, book it, poll status, and cancel.',\n version: '1.0.0',\n provider: 'elife',\n cli_noun: 'ride-elife',\n verbs: ['quote', 'book', 'get', 'cancel', 'list-orders'],\n verb_descriptions: {\n quote: 'Request fare quotes for a ride between two points.',\n book: 'Book a ride using a quote_id returned by quote.',\n get: 'Retrieve a ride order by id (poll for status changes).',\n cancel: 'Cancel a ride order by id.',\n 'list-orders': 'List previously placed ride orders.',\n },\n workflow: ['quote', 'book', 'get (poll for status)', 'cancel (optional)'],\n since: '2026-06-01',\n discovery: { help_command: 'agenzo-merchant-cli ride-elife --help' },\n },\n];\n\n/** Look up a capability by its service_id. */\nexport function findService(serviceId: string): ServiceCapability | undefined {\n return SERVICE_REGISTRY.find((s) => s.service_id === serviceId);\n}\n","import { Command } from 'commander';\nimport { CliError, ErrorCodes } from '../core/errors.js';\nimport { emit, emitSchema, type OutputFormat, type VerbSchema } from '../core/output.js';\nimport { findService } from './registry.js';\n\n/** Reserved for `--help --format json`. */\nexport const serviceGetSchema: VerbSchema = {\n description: 'Retrieve a single merchant service by id, with verb and workflow detail.',\n params: {\n 'service-id': 'string — service id to retrieve',\n },\n response: {\n service_id: 'string',\n name: 'string',\n description: 'string',\n version: 'string',\n provider: 'string',\n cli_noun: 'string',\n verbs: 'string[]',\n verb_descriptions: 'Record<verb, description>',\n workflow: 'string[] — ordered steps quote→book→get(poll)→[cancel]',\n since: 'string — ISO date',\n discovery: '{ help_command: string }',\n },\n};\n\nfunction resolveFormat(cmd: Command): OutputFormat {\n return cmd.optsWithGlobals().format === 'table' ? 'table' : 'json';\n}\n\nexport function buildServiceGetCommand(): Command {\n return new Command('get')\n .description(serviceGetSchema.description)\n .argument('[service-id]', 'Service id to retrieve')\n .helpOption(false)\n .option('-h, --help', 'Show help; with --format json prints the schema')\n .action((serviceId: string | undefined, opts: { help?: boolean }, cmd: Command) => {\n const format = resolveFormat(cmd);\n if (opts.help) {\n emitSchema(serviceGetSchema, format);\n return;\n }\n const service = serviceId ? findService(serviceId) : undefined;\n if (!service) {\n throw new CliError(\n ErrorCodes.SERVICE_NOT_FOUND,\n `Service '${serviceId ?? ''}' not found in the registry (SERVICE_NOT_FOUND).`,\n 'Run \"services list\" to see available services.',\n );\n }\n emit(service, format);\n });\n}\n"],"mappings":";;;AAAA,SAAS,WAAAA,gBAAe;;;ACOjB,IAAM,aAAa;AAAA;AAAA,EAExB,eAAe;AAAA,EACf,qBAAqB;AAAA,EACrB,gBAAgB;AAAA,EAChB,0BAA0B;AAAA;AAAA,EAG1B,uBAAuB;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,MAAM,QAAQ,EAAE,GAAGD,eAAc,GAAG,CAAC;AAAA,EAC9C,CAAC;AAGH,QAAM,YAAY,QACf,QAAQ,YAAY,EACpB,YAAY,8DAA8D;AAC7E,YAAU,WAAW,kBAAkB,CAAC;AACxC,YAAU,WAAW,iBAAiB,CAAC;AACvC,YAAU,WAAW,oBAAoB,CAAC;AAC1C,YAAU,WAAW,mBAAmB,CAAC;AACzC,YAAU,WAAW,uBAAuB,CAAC;AAG7C,QAAM,WAAW,QAAQ,QAAQ,UAAU,EAAE,YAAY,6BAA6B;AACtF,WAAS,WAAW,yBAAyB,CAAC;AAC9C,WAAS,WAAW,uBAAuB,CAAC;AAE5C,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAmB;AAC/B,MAAI,iBAAiB,UAAU;AAC7B,YAAQ,MAAM,UAAU,OAAO,SAAS,MAAM,OAAO,CAAC;AACtD,QAAI,MAAM,SAAU,SAAQ,MAAM,UAAU,OAAO,QAAQ,MAAM,QAAQ,CAAC;AAC1E,YAAQ,KAAK,MAAM,QAAQ;AAAA,EAC7B;AACA,UAAQ;AAAA,IACN,UAAU,OAAO,SAAS,iBAAiB,QAAQ,MAAM,UAAU,8BAA8B;AAAA,EACnG;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Command","readFileSync","join","join","readFileSync","Command","input","input","Command","Command","num","Command","Command","Command","Command","Command","Command","Command","Command","resolveFormat","Command","resolveFormat","Command"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/ride-elife/quote.ts","../src/ride-elife/watch.ts","../src/verb-schema.ts","../src/ride-elife/book.ts","../src/idempotency.ts","../src/ride-elife/get.ts","../src/ride-elife/cancel.ts","../src/ride-elife/list-orders.ts","../src/services/list.ts","../src/services/registry.ts","../src/services/get.ts"],"sourcesContent":["import { Command } from 'commander';\nimport {\n ApiClient,\n ConfigManager,\n Formatter,\n CliError,\n UserCancelError,\n toErrorEnvelope,\n resolveFormat,\n type OutputFormat,\n exitCodeFor,\n getCurrentVersion,\n} from '@agenzo/cli-core';\n\n// ride-elife commands (injection-style register, D6)\nimport { registerQuoteCommand } from './ride-elife/quote.js';\nimport { registerBookCommand } from './ride-elife/book.js';\nimport { registerRideGetCommand } from './ride-elife/get.js';\nimport { registerCancelCommand } from './ride-elife/cancel.js';\nimport { registerListOrdersCommand } from './ride-elife/list-orders.js';\n\n// services commands (CLI-bundled registry, D4)\nimport { registerServicesListCommand } from './services/list.js';\nimport { registerServiceGetCommand } from './services/get.js';\n\n// Holds the parsed program so the top-level error handler can read the\n// resolved `--format` global flag. Assigned inside `main()` once the program\n// is constructed; may be undefined if an error is thrown before then.\nlet programRef: Command | undefined;\n\nasync function main() {\n // Instantiate shared infrastructure. merchant-cli authenticates per-command\n // via `--api-key` (X-Api-Key); there is no Bearer session / AuthService /\n // keystore. The no-arg ConfigManager reuses cli-core's default config (the\n // environment admin-cli governs) purely to supply the ApiClient baseUrl and\n // the json envelope's profile/endpoint — merchant-cli exposes no host\n // commands of its own.\n const configManager = new ConfigManager();\n await configManager.ensureDirectories();\n\n const apiBaseUrl = await configManager.getApiBaseUrl();\n const apiClient = new ApiClient({ baseUrl: apiBaseUrl });\n\n // Shared deps object for networked commands — API Key is supplied per-command\n // (or interactively), so commands only need the HTTP client.\n const deps = { apiClient };\n\n // Create program\n const program = new Command();\n programRef = program;\n program\n .name('agenzo-merchant-cli')\n .version(getCurrentVersion())\n .description(\n 'Agenzo merchant fulfillment plane: service discovery (services) and ride ordering (ride-elife)',\n )\n .option('--verbose', 'Show verbose logs')\n .option('--yes', 'Skip confirmation prompts (for automation/AI Agents)')\n // merchant-cli is an agent-first entrypoint, so it defaults to json (D2),\n // unlike the cli-core default (table). resolveFormat only acts as a\n // fallback when the flag is absent.\n .option(\n '--format <format>',\n 'Output format: json | table (default: json; or set AGENZO_FORMAT)',\n 'json',\n )\n .option('--api-key <key>', 'API Key for authentication (X-Api-Key)');\n\n // Mirror the resolved global --format into AGENZO_FORMAT before any action\n // runs, so code paths without direct format access can resolve the active\n // format and stay silent in json mode.\n program.hook('preAction', (thisCommand) => {\n const flag = thisCommand.opts().format as string | undefined;\n process.env.AGENZO_FORMAT = resolveFormat(flag);\n });\n\n // ride-elife command group (eLife ride ordering)\n const rideCmd = program.command('ride-elife').description('Ride ordering (eLife)');\n registerQuoteCommand(rideCmd, deps);\n registerBookCommand(rideCmd, deps);\n registerRideGetCommand(rideCmd, deps);\n registerCancelCommand(rideCmd, deps);\n registerListOrdersCommand(rideCmd, deps);\n\n // services command group (CLI-bundled capability discovery)\n const servicesCmd = program.command('services').description('Merchant service discovery');\n registerServicesListCommand(servicesCmd);\n registerServiceGetCommand(servicesCmd);\n\n // Parse and execute\n await program.parseAsync(process.argv);\n}\n\n/**\n * Resolve the active output format for error reporting. Prefers the parsed\n * global `--format` flag (available on `programRef` once the program is\n * constructed; defaults to `json` for merchant-cli); if an error was thrown\n * before parsing, falls back to `resolveFormat(undefined)` (which consults\n * `AGENZO_FORMAT`, else `table`).\n */\nfunction resolveActiveFormat(): OutputFormat {\n const flag = programRef?.opts().format as string | undefined;\n return resolveFormat(flag);\n}\n\n/**\n * Top-level failure path. Writes the error envelope to stderr in the resolved\n * format and exits with the mapped code (1–5). stdout is left untouched so a\n * partial machine payload is never emitted on failure.\n *\n * - `json`: a single `{ error: { code, code_num, message, request_id? } }` envelope (§8.2).\n * - `table`: `✗ [<code_num>] <message>`.\n */\nfunction reportError(error: unknown): never {\n const envelope = toErrorEnvelope(error);\n const format = resolveActiveFormat();\n\n if (format === 'json') {\n console.error(JSON.stringify(envelope));\n } else {\n console.error(\n Formatter.status('error', `[${envelope.error.code_num}] ${envelope.error.message}`),\n );\n // Unknown (non-CliError) failures keep the --verbose raw-dump affordance.\n if (!(error instanceof CliError) && process.argv.includes('--verbose')) {\n console.error(error);\n }\n }\n\n // exitCodeFor owns the error-class → exit-code matrix, including\n // UpgradeRequiredError → 2 and UserCancelError → 5.\n process.exit(exitCodeFor(error));\n}\n\n// Ctrl+C / SIGINT maps to a user-cancel (exit 5) via the same envelope path.\nprocess.on('SIGINT', () => {\n reportError(new UserCancelError());\n});\n\n// Global error handler. Normal completion exits 0 naturally (the mapper is\n// never consulted on success).\nmain().catch(reportError);\n","import { Command } from 'commander';\nimport {\n ApiClient,\n ConfigManager,\n PromptEngine,\n Formatter,\n resolveFormat,\n notify,\n CliError,\n renderWithContext,\n} from '@agenzo/cli-core';\nimport type { CommandResult } from '@agenzo/cli-core';\nimport type { QuoteResponse, VehicleClass } from '../types/api.js';\nimport { attachSchemaHelp, quoteSchema } from '../verb-schema.js';\n\n// ============================================================\n// Input helpers (ride-domain — body assembly stays in app per req 4.4)\n// ============================================================\n\n/**\n * Require a flag value. Missing required input maps to `PARAM_INVALID`\n * (requirement 2.1 / design §4.4.1.3) — a catalog code (exit 1), never\n * `PARAM_REQUIRED` (not in the cli-core error catalog).\n */\nfunction need(value: string | undefined, flag: string): string {\n if (value === undefined) {\n throw new CliError('PARAM_INVALID', `Missing required --${flag}.`);\n }\n return value;\n}\n\n/**\n * Number-ify a coordinate / numeric flag. Non-finite input maps to\n * `PARAM_INVALID`. Coordinates are sent as numbers, never strings (§4.4.1.3).\n */\nfunction num(value: string | undefined, flag: string): number {\n const n = Number(need(value, flag));\n if (!Number.isFinite(n)) {\n throw new CliError('PARAM_INVALID', `--${flag} must be a number.`);\n }\n return n;\n}\n\n// ============================================================\n// Output helper (table summary)\n// ============================================================\n\n/**\n * Render the quote as a table for `--format table`. Each vehicle class is one\n * row; amounts are decimal currency units (NOT cents) — printed verbatim.\n */\nfunction formatQuote(data: QuoteResponse): string {\n const classes: VehicleClass[] = data.vehicle_classes ?? [];\n if (classes.length === 0) {\n return Formatter.status('info', 'No vehicle classes available for this route');\n }\n\n const headers = ['Vehicle Class', 'Price', 'Currency', 'Quote ID', 'Pax', 'Luggage'];\n const rows = classes.map((vc) => [\n String(vc.vehicle_class ?? '-'),\n String(vc.price?.amount ?? '-'),\n String(vc.price?.currency ?? '-'),\n String(vc.price?.quote_id ?? '-'),\n String(vc.passenger_capacity ?? '-'),\n String(vc.luggage_capacity ?? '-'),\n ]);\n\n const lines: [string, string][] = [\n ['Airport transfer', String(data.is_airport_transfer ?? false)],\n ];\n if (data.airport_direction) {\n lines.push(['Airport direction', String(data.airport_direction)]);\n }\n if (data.meet_and_greet) {\n const mg = data.meet_and_greet;\n const mgPrice = mg.price ? ` (${mg.price.amount} ${mg.price.currency})` : '';\n lines.push(['Meet & greet', `${mg.available ? 'available' : 'unavailable'}${mgPrice}`]);\n }\n\n return `${Formatter.table(headers, rows)}\\n${Formatter.keyValue(lines)}`;\n}\n\n// ============================================================\n// Command registration\n// ============================================================\n\n/**\n * `ride-elife quote` — request fare quotes between two points (§4.4.1.3).\n *\n * Read-only (no idempotency key). Builds the `/ride/quote` body from flags\n * (coordinates number-ified, missing required → `PARAM_INVALID`), POSTs with\n * the `X-Api-Key` auth, and renders `QuoteResponse` via `renderWithContext`\n * (json carries the profile/endpoint envelope). The progress line is emitted\n * through `notify` so it goes to stderr and stays silent in json mode.\n */\nexport function registerQuoteCommand(parent: Command, deps: { apiClient: ApiClient }): void {\n const cmd = parent\n .command('quote')\n .description('Request fare quotes for a ride between two points')\n .option('--api-key <key>', 'API Key for authentication (X-Api-Key)')\n .option('--pickup-lat <lat>', 'Pickup latitude')\n .option('--pickup-lng <lng>', 'Pickup longitude')\n .option('--pickup-name <name>', 'Pickup location name')\n .option('--dropoff-lat <lat>', 'Dropoff latitude')\n .option('--dropoff-lng <lng>', 'Dropoff longitude')\n .option('--dropoff-name <name>', 'Dropoff location name')\n .option('--pickup-time <time>', 'Pickup time: epoch seconds, or \"now\"')\n .option('--passenger-name <name>', 'Lead passenger full name')\n .option('--passenger-phone <phone>', 'Passenger phone (E.164)')\n .option('--passenger-count <n>', 'Passenger count')\n .option('--luggage-count <n>', 'Luggage count')\n .option('--passenger-email <email>', 'Passenger email')\n .option('--children-count <n>', 'Children count');\n\n attachSchemaHelp(cmd, quoteSchema);\n\n cmd.action(async () => {\n const opts = cmd.optsWithGlobals();\n const format = resolveFormat(opts.format as string | undefined);\n\n const apiKey = await PromptEngine.resolveInput(opts.apiKey as string | undefined, {\n message: 'API Key:',\n type: 'password',\n });\n\n // Build request body. Coordinates are number-ified; pickup_time accepts the\n // literal \"now\" or epoch seconds. Missing required fields throw\n // PARAM_INVALID before any request is sent.\n const body: Record<string, unknown> = {\n pickup: {\n lat: num(opts.pickupLat as string | undefined, 'pickup-lat'),\n lng: num(opts.pickupLng as string | undefined, 'pickup-lng'),\n name: need(opts.pickupName as string | undefined, 'pickup-name'),\n },\n dropoff: {\n lat: num(opts.dropoffLat as string | undefined, 'dropoff-lat'),\n lng: num(opts.dropoffLng as string | undefined, 'dropoff-lng'),\n name: need(opts.dropoffName as string | undefined, 'dropoff-name'),\n },\n pickup_time:\n opts.pickupTime === 'now'\n ? 'now'\n : num(opts.pickupTime as string | undefined, 'pickup-time'),\n };\n\n // Optional passenger / luggage / children fields — included only when set.\n if (opts.passengerName) body.passenger_name = opts.passengerName as string;\n if (opts.passengerPhone) body.passenger_phone = opts.passengerPhone as string;\n if (opts.passengerCount !== undefined) {\n body.passenger_count = num(opts.passengerCount as string, 'passenger-count');\n }\n if (opts.luggageCount !== undefined) {\n body.luggage_count = num(opts.luggageCount as string, 'luggage-count');\n }\n if (opts.childrenCount !== undefined) {\n body.children_count = num(opts.childrenCount as string, 'children-count');\n }\n if (opts.passengerEmail !== undefined) {\n body.passenger_email = opts.passengerEmail as string;\n }\n\n // Progress line: stderr in table mode, silent in json mode.\n notify(format, 'loading', 'Fetching quotes...');\n\n const result = await deps.apiClient.post<QuoteResponse>(\n '/ride/quote',\n { type: 'api-key', key: apiKey },\n body,\n );\n\n if (!result.success) {\n throw CliError.fromApi(result, { auth: 'api-key' });\n }\n\n const data = result.data;\n\n const configManager = new ConfigManager();\n const commandResult: CommandResult<QuoteResponse> = {\n data,\n text: () => formatQuote(data),\n };\n\n await renderWithContext(commandResult, { format }, configManager);\n });\n}\n","import type { ApiClient } from '@agenzo/cli-core';\nimport { CliError } from '@agenzo/cli-core';\nimport type { GetOrderResponse } from '../types/api.js';\n\n/**\n * NDJSON status-polling for `ride-elife get --watch` (§4.4.1.3 polling /\n * design Property 2). Merchant-domain logic — stays in the app per\n * requirement 4.4 (NOT pushed down to cli-core).\n *\n * The watch stream is a line stream: each poll result is written as ONE\n * independent, compact JSON line on stdout. It is deliberately NOT routed\n * through `renderWithContext`, so the profile/endpoint envelope is never\n * wrapped around the stream (an agent consumes it with a line reader).\n *\n * The polling engine is split from its I/O so it can be unit/PBT-tested with a\n * fake clock and shortened constants (task 6.5): `fetchStatus`, `writeLine`,\n * `sleep` and `now` are all injected.\n */\n\n/**\n * Terminal ride statuses (schema `polling.terminal_statuses`). Once the order\n * reaches one of these, `--watch` stops polling. CASE-SENSITIVE — must match\n * the server casing exactly.\n */\nexport const TERMINAL_STATUSES: ReadonlySet<string> = new Set([\n 'At destination',\n 'Cancelled',\n 'Rejected',\n 'Customer no show',\n 'Driver no show',\n]);\n\n/** Schema `polling.recommended_interval_seconds`. */\nexport const DEFAULT_WATCH_INTERVAL_SECONDS = 5;\n/** Safety cap so `--watch` can never poll forever. */\nexport const DEFAULT_WATCH_TIMEOUT_SECONDS = 600;\n\n/**\n * Pure terminal-state predicate (exported for direct unit/PBT testing). A\n * missing/undefined status is never terminal, so polling continues until a\n * known terminal status or the timeout.\n */\nexport function isTerminalStatus(status: string | undefined | null): boolean {\n return status !== undefined && status !== null && TERMINAL_STATUSES.has(status);\n}\n\n/** Read the case-sensitive `status` field off a poll result. */\nexport function statusOf(data: GetOrderResponse): string | undefined {\n const status = (data as { status?: unknown }).status;\n return typeof status === 'string' ? status : undefined;\n}\n\n/** The final NDJSON line emitted when polling gives up before a terminal status. */\nexport interface WatchTimeoutLine {\n watch_status: 'timeout';\n message: string;\n last_status: string | null;\n}\n\n/** I/O + clock seams the polling engine depends on (all injectable for tests). */\nexport interface WatchEngineDeps {\n /** Fetch one status snapshot (throws to abort the whole stream). */\n fetchStatus: () => Promise<GetOrderResponse>;\n /** Write one NDJSON record as a single compact line. */\n writeLine: (record: unknown) => void;\n /** Resolve after `ms` (real timer in prod; fake clock in tests). */\n sleep: (ms: number) => Promise<void>;\n /** Current epoch millis (real `Date.now` in prod; fake clock in tests). */\n now: () => number;\n}\n\n/** Interval / timeout budget for one watch run, in milliseconds. */\nexport interface WatchEngineOptions {\n intervalMs: number;\n timeoutMs: number;\n}\n\n/**\n * Poll `fetchStatus`, writing each result as an NDJSON line, until the order\n * reaches a terminal status or the timeout elapses. On timeout the FINAL line\n * is `{ watch_status: 'timeout', ... }` (requirement 3.2 / Property 2).\n *\n * Termination: every iteration either returns (terminal status) or, when the\n * next poll would land at/after the deadline, emits the timeout line and\n * returns. With a monotonically advancing clock (real time, or a fake clock\n * advanced by `sleep`) the deadline is always reached, so the loop is\n * guaranteed to terminate for any status sequence.\n */\nexport async function runWatch(\n deps: WatchEngineDeps,\n opts: WatchEngineOptions,\n): Promise<void> {\n const deadline = deps.now() + opts.timeoutMs;\n for (;;) {\n const data = await deps.fetchStatus();\n deps.writeLine(data);\n\n const status = statusOf(data);\n if (isTerminalStatus(status)) {\n return;\n }\n\n if (deps.now() + opts.intervalMs >= deadline) {\n const timeoutLine: WatchTimeoutLine = {\n watch_status: 'timeout',\n message: `Polling stopped after ${opts.timeoutMs / 1000}s without reaching a terminal status.`,\n last_status: status ?? null,\n };\n deps.writeLine(timeoutLine);\n return;\n }\n\n await deps.sleep(opts.intervalMs);\n }\n}\n\n/**\n * Parse a positive `--watch-*` seconds flag, falling back to a default when\n * absent or non-positive (mirrors the standalone reference behaviour). Returns\n * a value in SECONDS.\n */\nexport function resolveSeconds(value: string | undefined, fallback: number): number {\n if (value === undefined) return fallback;\n const n = Number(value);\n return Number.isFinite(n) && n > 0 ? n : fallback;\n}\n\n/** Real-timer sleep used by the production watch path. */\nexport const realSleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Compact single-line NDJSON writer used by the production watch path. */\nexport const ndjsonWriteLine = (record: unknown): void => {\n process.stdout.write(`${JSON.stringify(record)}\\n`);\n};\n\n/**\n * Production wiring for `ride-elife get --watch`: bind the polling engine to a\n * live `ApiClient` (status endpoint + api-key auth), the compact NDJSON stdout\n * writer, real timers and the system clock. A network/backend failure on any\n * poll surfaces as a `CliError` to the top-level handler, exactly like the\n * single-shot path.\n */\nexport async function watchRideStatus(\n apiClient: ApiClient,\n apiKey: string,\n orderId: string,\n opts: { intervalSeconds: number; timeoutSeconds: number },\n): Promise<void> {\n const path = `/ride/${encodeURIComponent(orderId)}/status`;\n await runWatch(\n {\n fetchStatus: async () => {\n const result = await apiClient.get<GetOrderResponse>(path, {\n type: 'api-key',\n key: apiKey,\n });\n if (!result.success) {\n throw CliError.fromApi(result, { auth: 'api-key' });\n }\n return result.data;\n },\n writeLine: ndjsonWriteLine,\n sleep: realSleep,\n now: () => Date.now(),\n },\n {\n intervalMs: opts.intervalSeconds * 1000,\n timeoutMs: opts.timeoutSeconds * 1000,\n },\n );\n}\n","/**\n * `--help --format json` verb-level schema (§4.4.1.3) — merchant domain only.\n *\n * Every ride-elife verb supports `--help --format json`, which prints a single\n * machine-readable JSON object describing the verb instead of commander's\n * default text help. This is the standard way an Agent discovers a verb's\n * flags, response shape, example invocation and (where relevant) error-recovery\n * and polling guidance locally, without a network round-trip.\n *\n * admin-cli / token-cli have no such mode, so this lives in the app (not in\n * cli-core) per requirement 4.4.\n *\n * Mechanism (commander v14): `attachSchemaHelp` overrides a command's\n * `helpInformation`. Commander resolves `--help` BEFORE later argv tokens are\n * applied to options, so the parsed `--format` value is not yet available when\n * help renders — we therefore read it straight from `process.argv`. Only an\n * explicit `--format json` switches to the JSON schema; bare `--help` and\n * `--help --format table` keep commander's default text help.\n */\nimport type { Command } from 'commander';\nimport { TERMINAL_STATUSES, DEFAULT_WATCH_INTERVAL_SECONDS } from './ride-elife/watch.js';\n\nconst CLI_NAME = 'agenzo-merchant-cli';\nconst NOUN = 'ride-elife';\n\n// ============================================================\n// Schema shape (§4.4.1.3 verb-level schema)\n// ============================================================\n\n/** One flag descriptor: type / required / optional default / description / constraints. */\nexport interface FlagSchema {\n type: string;\n /** `true` / `false`, or the literal `'conditional'` for mode-dependent flags. */\n required: boolean | 'conditional';\n default?: unknown;\n description: string;\n constraints?: string;\n}\n\n/** A complete, copy-pasteable example invocation plus what to read from the output. */\nexport interface ExampleSchema {\n command: string;\n output_summary: string;\n}\n\n/** Polling guidance — only status-query verbs (`get`) carry this block. */\nexport interface PollingSchema {\n recommended_interval_seconds: number;\n terminal_statuses: string[];\n in_progress_statuses: string[];\n field_availability?: Record<string, string>;\n}\n\n/**\n * The verb-level schema object emitted by `--help --format json`\n * (§4.4.1.3): `{ cli, noun, verb, description, flags, response, example,\n * [error_recovery], [polling] }`. `error_recovery` / `polling` are optional and\n * present only where the verb warrants them.\n */\nexport interface VerbSchema {\n cli: string;\n noun: string;\n verb: string;\n description: string;\n flags: Record<string, FlagSchema>;\n /** Key response fields + type descriptions (nested objects allowed). */\n response: Record<string, unknown>;\n example: ExampleSchema;\n error_recovery?: Record<string, string>;\n polling?: PollingSchema;\n}\n\n// ============================================================\n// Emit + attach mechanism\n// ============================================================\n\n/**\n * True only when `--format json` is explicitly present in `argv`. Commander\n * resolves `--help` before applying later option tokens, so the parsed format\n * is not yet available at help-render time; we read argv directly. Bare `--help`\n * and `--help --format table` deliberately return false (keep text help), even\n * though the program defaults `--format` to json — the default is never written\n * into argv.\n */\nexport function wantsJsonSchema(argv: string[] = process.argv): boolean {\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n if (a === '--format=json') return true;\n if (a === '--format' && argv[i + 1] === 'json') return true;\n }\n return false;\n}\n\n/** Print a verb schema as a single pretty-printed JSON object to stdout. */\nexport function emitSchema(schema: VerbSchema): void {\n console.log(JSON.stringify(schema, null, 2));\n}\n\n/**\n * Attach `--help --format json` schema output to a command. When help is\n * requested with an explicit `--format json`, the schema is printed to stdout\n * and an empty string is returned so commander prints nothing further and exits\n * cleanly. Otherwise the original (text) help is rendered unchanged.\n */\nexport function attachSchemaHelp(cmd: Command, schema: VerbSchema): Command {\n const baseHelp = cmd.helpInformation.bind(cmd);\n cmd.helpInformation = (context) => {\n if (!wantsJsonSchema()) return baseHelp(context);\n emitSchema(schema);\n return '';\n };\n return cmd;\n}\n\n// ============================================================\n// Ride-elife verb schemas\n// ============================================================\n//\n// Flags / response are kept aligned with each command's ACTUAL flags and the\n// cli-core response types (QuoteResponse / BookResponse / GetOrderResponse /\n// CancelResponse / ListOrdersResponse). Notably: quote's passenger fields are\n// optional here (the command only sends them when set); get's pickup/dropoff\n// are `from_location` / `to_location` (v3 snake_case, NOT elife from/to);\n// amounts are decimal currency units (NOT cents).\n\n/** `ride-elife quote` schema (§4.4.1.3 quote schema). */\nexport const quoteSchema: VerbSchema = {\n cli: CLI_NAME,\n noun: NOUN,\n verb: 'quote',\n description: 'Request fare quotes for a ride between two points',\n flags: {\n 'pickup-lat': { type: 'float', required: true, description: 'Pickup latitude', constraints: '-90 to 90' },\n 'pickup-lng': { type: 'float', required: true, description: 'Pickup longitude', constraints: '-180 to 180' },\n 'pickup-name': { type: 'string', required: true, description: 'Pickup location name' },\n 'dropoff-lat': { type: 'float', required: true, description: 'Dropoff latitude', constraints: '-90 to 90' },\n 'dropoff-lng': { type: 'float', required: true, description: 'Dropoff longitude', constraints: '-180 to 180' },\n 'dropoff-name': { type: 'string', required: true, description: 'Dropoff location name' },\n 'pickup-time': {\n type: 'int|string',\n required: true,\n description: \"Epoch seconds or the literal 'now'\",\n },\n 'passenger-name': { type: 'string', required: false, description: 'Lead passenger full name' },\n 'passenger-phone': { type: 'string', required: false, description: 'Passenger phone in E.164 format (e.g. +14155551234)' },\n 'passenger-count': { type: 'int', required: false, description: 'Number of passengers' },\n 'luggage-count': { type: 'int', required: false, description: 'Number of luggage items' },\n 'passenger-email': { type: 'string', required: false, description: 'Passenger email address' },\n 'children-count': { type: 'int', required: false, description: 'Number of children' },\n },\n response: {\n vehicle_classes: {\n type: 'array',\n description: 'Available vehicle options with pricing',\n items: {\n vehicle_class: { type: 'string', description: 'Sedan / SUV / MPV-5 / MPV-7 / Van / Luxury / Train' },\n 'price.amount': { type: 'float', description: 'Price in currency units (e.g. 42.50), NOT cents' },\n 'price.currency': { type: 'string', description: 'ISO 4217 (e.g. USD)' },\n 'price.quote_id': { type: 'string', description: 'Use this in `ride-elife book --quote-id`' },\n passenger_capacity: { type: 'int', description: 'Max passengers' },\n luggage_capacity: { type: 'int', description: 'Max luggage items' },\n },\n },\n meet_and_greet: { type: 'object|null', description: 'Meet & greet availability and price' },\n is_airport_transfer: { type: 'bool', description: 'Whether this is an airport transfer' },\n airport_direction: { type: 'string|null', description: 'pickup / dropoff / null' },\n },\n example: {\n command:\n 'agenzo-merchant-cli ride-elife quote --pickup-lat 37.7937 --pickup-lng -122.3956 --pickup-name \"1 Market St\" --dropoff-lat 37.6213 --dropoff-lng -122.3790 --dropoff-name \"SFO Airport\" --pickup-time now',\n output_summary:\n 'Returns vehicle_classes[] with a quote_id per option. Use quote_id and vehicle_class for booking.',\n },\n error_recovery: {\n VEHICLE_UNAVAILABLE: 'No vehicles for this route/time. Try a different pickup-time or location. Do NOT blindly retry.',\n PARAM_INVALID: 'Fix the offending flag (coordinates must be numbers; required pickup/dropoff/pickup-time present), then retry.',\n },\n};\n\n/** `ride-elife book` schema (§4.4.1.3 book schema). Write op (W/Y). */\nexport const bookSchema: VerbSchema = {\n cli: CLI_NAME,\n noun: NOUN,\n verb: 'book',\n description: 'Book a ride using a quote_id returned by a previous quote call',\n flags: {\n 'quote-id': { type: 'string', required: true, description: 'Quote id from quote response (vehicle_classes[].price.quote_id)' },\n 'vehicle-class': { type: 'string', required: true, description: 'Vehicle class: Sedan / SUV / MPV-5 / MPV-7 / Van / Luxury / Train' },\n 'price-amount': { type: 'float', required: true, description: 'Fare in decimal currency units (NOT cents), from the quote' },\n 'price-currency': { type: 'string', required: false, default: 'USD', description: 'ISO 4217 currency code' },\n 'payment-order-id': {\n type: 'string',\n required: 'conditional',\n description: 'Required when billing_mode=pay_per_call (a PAID payment order). Forbidden when billing_mode=monthly_settlement',\n },\n 'passenger-name': { type: 'string', required: true, description: 'Passenger full name' },\n 'passenger-phone': { type: 'string', required: true, description: 'Passenger phone in E.164 format (e.g. +14155551234)' },\n 'passenger-email': { type: 'string', required: true, description: 'Passenger email (required by eLife for booking)' },\n 'luggage-count': { type: 'int', required: false, description: 'Number of luggage items' },\n 'special-requests': { type: 'string', required: false, description: 'Free-text special requests or notes' },\n 'pickup-lat': { type: 'float', required: false, description: 'Pickup latitude (must match the quote)', constraints: '-90 to 90' },\n 'pickup-lng': { type: 'float', required: false, description: 'Pickup longitude (must match the quote)', constraints: '-180 to 180' },\n 'pickup-name': { type: 'string', required: false, description: 'Pickup location name (must match the quote)' },\n 'dropoff-lat': { type: 'float', required: false, description: 'Dropoff latitude (must match the quote)', constraints: '-90 to 90' },\n 'dropoff-lng': { type: 'float', required: false, description: 'Dropoff longitude (must match the quote)', constraints: '-180 to 180' },\n 'dropoff-name': { type: 'string', required: false, description: 'Dropoff location name (must match the quote)' },\n 'pickup-time': { type: 'int|string', required: false, description: \"Epoch seconds or 'now' (must match the quote)\" },\n 'meet-and-greet': { type: 'bool', required: false, default: false, description: 'Enable meet & greet service' },\n 'meet-and-greet-price': { type: 'float', required: false, description: 'Meet & greet surcharge from the quote (meet_and_greet.price.amount)' },\n 'welcome-sign': { type: 'string', required: false, description: 'Welcome sign text (meet & greet)' },\n 'child-seat-count': { type: 'int', required: false, description: 'Number of child seats needed', constraints: '0 to 5' },\n 'infant-seat-count': { type: 'int', required: false, description: 'Number of infant seats needed', constraints: '0 to 5' },\n 'toddler-seat-count': { type: 'int', required: false, description: 'Number of toddler seats needed', constraints: '0 to 5' },\n 'arrival-flight-no': { type: 'string', required: false, description: 'Arrival flight number (airport pickup)' },\n 'arrival-airline': { type: 'string', required: false, description: 'Arrival airline name' },\n 'departure-flight-no': { type: 'string', required: false, description: 'Departure flight number (airport dropoff)' },\n 'departure-airline': { type: 'string', required: false, description: 'Departure airline name' },\n 'idempotency-key': {\n type: 'string',\n required: true,\n description: 'Unique key (1-128 chars [A-Za-z0-9_-]) forwarded verbatim as the Idempotency-Key header; never auto-generated',\n },\n },\n response: {\n ride_id: { type: 'string|int', description: 'Ride identifier — use for `ride-elife get` / `ride-elife cancel`' },\n order_id: { type: 'string|int', description: 'Internal order id for reconciliation' },\n status: { type: 'string', description: 'Ride status (case-sensitive server casing)' },\n is_scheduled: { type: 'bool', description: 'true = scheduled/airport ride; false = realtime' },\n order_type: { type: 'string', description: \"'realtime' or 'airport'\" },\n price: { type: 'object', description: '{ amount, currency, quote_id }' },\n payment_status: { type: 'string', description: 'PAID (pay_per_call) or ON_ACCOUNT (monthly_settlement)' },\n billing_entry_id: { type: 'string|absent', description: 'Only in monthly_settlement mode' },\n payment_order_id: { type: 'string|absent', description: 'Only in pay_per_call mode (echoes the request)' },\n },\n example: {\n command:\n 'agenzo-merchant-cli ride-elife book --quote-id qte_01HZXD --vehicle-class Sedan --price-amount 42.50 --passenger-name \"Alice\" --passenger-phone +14155551234 --idempotency-key book-123',\n output_summary: 'Returns ride_id. Use ride_id in `ride-elife get` to poll status.',\n },\n error_recovery: {\n QUOTE_EXPIRED: \"Re-invoke 'quote' for a fresh quote_id, then retry 'book' with the SAME --idempotency-key.\",\n BILLING_MODE_MISMATCH: 'Check Developer.billing_mode. pay_per_call requires --payment-order-id; monthly_settlement forbids it.',\n PAYMENT_ORDER_NOT_PAID: 'Wait for the payment order status=PAID, then retry with the SAME --idempotency-key.',\n PAYMENT_ORDER_ALREADY_CONSUMED: 'Create a new payment order, then retry with the new payment-order-id and a NEW --idempotency-key.',\n ACCOUNT_INSUFFICIENT_BALANCE: 'Top up the settlement account (offline) or pick a cheaper vehicle_class, then retry.',\n BOOKING_FAILED: 'elife rejected after settlement. The message contains a ref: for manual reconciliation. Do NOT auto-retry.',\n PARAM_IDEMPOTENCY_KEY_REQUIRED: 'Supply --idempotency-key (1-128 chars [A-Za-z0-9_-]); the CLI never generates one under --yes.',\n },\n};\n\n/** `ride-elife get` schema (§4.4.1.3 get schema). Read-only, supports `--watch`. */\nexport const rideGetSchema: VerbSchema = {\n cli: CLI_NAME,\n noun: NOUN,\n verb: 'get',\n description: 'Retrieve a ride order status by id; with --watch, poll until a terminal status',\n flags: {\n 'order-id': { type: 'string', required: true, description: 'The numeric ride_id (e.g. 4112961) — use the `ride_id` field from book/list-orders responses, NOT the rio_... order_id' },\n watch: { type: 'bool', required: false, default: false, description: 'Poll until a terminal status, emitting one NDJSON line per update' },\n 'watch-interval': { type: 'int', required: false, default: DEFAULT_WATCH_INTERVAL_SECONDS, description: 'Seconds between polls when --watch is set' },\n 'watch-timeout': { type: 'int', required: false, default: 600, description: 'Max seconds to poll before giving up' },\n },\n response: {\n ride_id: { type: 'string|int', description: 'Ride identifier' },\n status: { type: 'string', description: 'Pending / Accepted / On my way / Waiting / On board / At destination / Rejected / Cancelled / Customer no show / Driver no show' },\n source: { type: 'string', description: \"'local_cache' when served from the local fallback; 'mock' in sandbox\" },\n is_scheduled: { type: 'bool', description: 'true = scheduled/airport ride' },\n from_location: { type: 'object', description: 'Pickup { lat, lng, name, address } (v3 snake_case, NOT elife from/to)' },\n to_location: { type: 'object', description: 'Dropoff { lat, lng, name, address }' },\n pickup_time: { type: 'int|string', description: 'Pickup time' },\n vehicle_class: { type: 'string|null', description: 'Vehicle class' },\n price: { type: 'object', description: '{ amount, currency, quote_id }' },\n final_amount: { type: 'float|null', description: 'Final settled fare (realtime, after final-fare settlement)' },\n final_settlement_status: { type: 'string', description: 'pending / settled / no_adjustment / settlement_pending / not_applicable' },\n driver: { type: 'object|null', description: '{ name, phone_number } — available after a driver is assigned' },\n vehicle: { type: 'object|null', description: '{ make, model, color, license_plate, image_url } — available after a driver is assigned' },\n created_at: { type: 'string', description: 'Order creation time' },\n },\n example: {\n command: 'agenzo-merchant-cli ride-elife get --order-id EL-20260527-1023456',\n output_summary:\n 'Returns current status and driver/vehicle info. Terminal statuses: At destination, Cancelled, Rejected, Customer no show, Driver no show.',\n },\n polling: {\n recommended_interval_seconds: DEFAULT_WATCH_INTERVAL_SECONDS,\n terminal_statuses: [...TERMINAL_STATUSES],\n in_progress_statuses: ['Pending', 'Accepted', 'On my way', 'Waiting', 'On board'],\n field_availability: {\n driver: \"Populated from status 'Accepted' onwards (after a driver is dispatched). Null in 'Pending'.\",\n vehicle: \"Populated from status 'Accepted' onwards. Null in 'Pending'.\",\n },\n },\n error_recovery: {\n VEHICLE_UNAVAILABLE: 'Order not found. Verify --order-id is the ride_id from book. Do NOT retry.',\n BOOKING_FAILED: 'Transient elife error. Retry once after 5s.',\n },\n};\n\n/** `ride-elife cancel` schema (§4.4.1.3 cancel schema). Write op (W/Y). */\nexport const cancelSchema: VerbSchema = {\n cli: CLI_NAME,\n noun: NOUN,\n verb: 'cancel',\n description: 'Cancel a ride order by id (a cancellation fee may apply depending on ride status)',\n flags: {\n 'order-id': { type: 'string', required: true, description: 'The numeric ride_id (e.g. 4112961) to cancel — use the `ride_id` field from book/list-orders responses, NOT the rio_... order_id' },\n 'idempotency-key': {\n type: 'string',\n required: true,\n description: 'Unique key (1-128 chars [A-Za-z0-9_-]) forwarded verbatim as the Idempotency-Key header; never auto-generated',\n },\n },\n response: {\n ride_id: { type: 'string|int', description: 'Cancelled ride id' },\n ride_stat: { type: 'string', description: \"Status after cancellation (typically 'Cancelled')\" },\n cancellation: {\n type: 'object|null',\n description: 'Cancellation details',\n properties: {\n cancellation_fee: { type: 'float', description: 'Fee charged for cancellation' },\n reversal_amount: { type: 'float', description: 'Amount reversed/refunded' },\n currency: { type: 'string', description: 'ISO 4217 currency code' },\n },\n },\n refund_amount: { type: 'float', description: 'Amount credited back to the settlement balance (paid − cancellation_fee)' },\n },\n example: {\n command: 'agenzo-merchant-cli ride-elife cancel --order-id EL-20260527-1023456 --idempotency-key cancel-456',\n output_summary: 'Returns cancellation fee and refund amount.',\n },\n error_recovery: {\n CANCELLATION_NOT_ALLOWED: 'The ride is in a non-cancellable state. Do NOT retry; query status with `ride-elife get`.',\n PARAM_IDEMPOTENCY_KEY_REQUIRED: 'Supply --idempotency-key (1-128 chars [A-Za-z0-9_-]); the CLI never generates one under --yes.',\n },\n};\n\n/** `ride-elife list-orders` schema (§4.4.1.3 list-orders schema). Read-only. */\nexport const listOrdersSchema: VerbSchema = {\n cli: CLI_NAME,\n noun: NOUN,\n verb: 'list-orders',\n description: 'List previously placed ride orders with optional filters and pagination',\n flags: {\n status: { type: 'string', required: false, description: 'Filter by ride status (case-sensitive server casing)' },\n 'order-type': { type: 'string', required: false, description: 'Filter by order type (e.g. realtime / airport)' },\n page: { type: 'int', required: false, default: 1, description: 'Page number', constraints: '>= 1' },\n 'page-size': { type: 'int', required: false, default: 20, description: 'Items per page', constraints: '>= 1' },\n },\n response: {\n orders: {\n type: 'array',\n description: 'List of ride orders (slim list-item shape)',\n items: {\n order_id: { type: 'string', description: 'Internal order id' },\n ride_id: { type: 'string', description: 'Ride id (same as ride_id from book)' },\n status: { type: 'string', description: 'Current ride status' },\n vehicle_class: { type: 'string', description: 'Vehicle class' },\n is_scheduled: { type: 'bool', description: 'true = scheduled/airport, false = realtime' },\n scheduled_at: { type: 'string', description: 'ISO 8601 datetime; empty for realtime orders' },\n price_amount: { type: 'float|null', description: 'Price in decimal currency units (NOT cents)' },\n final_amount: { type: 'float|null', description: 'Final settled amount' },\n price_currency: { type: 'string', description: 'ISO 4217 currency code' },\n payment_status: { type: 'string', description: 'Payment status' },\n final_settlement_status: { type: 'string', description: 'pending / settled / no_adjustment / settlement_pending / not_applicable' },\n cancellation_fee: { type: 'float|null', description: 'Cancellation fee for cancelled orders; null otherwise' },\n provider: { type: 'string', description: 'Service provider (elife)' },\n created_at: { type: 'string|null', description: 'Order creation time (ISO 8601)' },\n updated_at: { type: 'string|null', description: 'Last update time (ISO 8601)' },\n },\n },\n total: { type: 'int', description: 'Total matching orders' },\n page: { type: 'int', description: 'Current page' },\n page_size: { type: 'int', description: 'Items per page' },\n },\n example: {\n command: 'agenzo-merchant-cli ride-elife list-orders --status Pending --page 1 --page-size 10',\n output_summary: 'Returns a paginated list of ride orders with status and amount info.',\n },\n error_recovery: {\n INTERNAL_ERROR: 'Transient backend error. Retry once after a short delay.',\n PARAM_INVALID: 'Ensure --page / --page-size are positive integers, then retry.',\n },\n};\n","import { Command } from 'commander';\nimport { confirm } from '@inquirer/prompts';\nimport {\n ApiClient,\n ConfigManager,\n PromptEngine,\n Formatter,\n resolveFormat,\n notify,\n CliError,\n renderWithContext,\n} from '@agenzo/cli-core';\nimport type { CommandResult } from '@agenzo/cli-core';\nimport type { BookResponse } from '../types/api.js';\nimport { attachSchemaHelp, bookSchema } from '../verb-schema.js';\nimport { resolveIdempotencyKey } from '../idempotency.js';\n\n// ============================================================\n// Input helpers (ride-domain — body assembly stays in app per req 4.4)\n// ============================================================\n\n/**\n * Require a flag value. Missing required input maps to `PARAM_INVALID`\n * (requirement 2.2 / design §4.4.1.3) — a catalog code (exit 1), mirroring the\n * sibling `quote` command's convention.\n */\nfunction need(value: string | undefined, flag: string): string {\n if (value === undefined) {\n throw new CliError('PARAM_INVALID', `Missing required --${flag}.`);\n }\n return value;\n}\n\n/** Number-ify a numeric flag. Non-finite input maps to `PARAM_INVALID`. */\nfunction num(value: string | undefined, flag: string): number {\n const n = Number(need(value, flag));\n if (!Number.isFinite(n)) {\n throw new CliError('PARAM_INVALID', `--${flag} must be a number.`);\n }\n return n;\n}\n\n/**\n * Number-ify a seat count and enforce the 0–5 range (design §4.4.1.3 book\n * schema). Out-of-range values map to `PARAM_INVALID`.\n */\nfunction seatCount(value: string, flag: string): number {\n const n = num(value, flag);\n if (!Number.isInteger(n) || n < 0 || n > 5) {\n throw new CliError('PARAM_INVALID', `--${flag} must be an integer between 0 and 5.`);\n }\n return n;\n}\n\n// ============================================================\n// Output helper (table summary)\n// ============================================================\n\n/**\n * Render a booked ride as a key/value block for `--format table`. Amounts are\n * decimal currency units (NOT cents) — printed verbatim.\n */\nfunction formatBook(data: BookResponse): string {\n const lines: [string, string][] = [\n ['Ride ID', String(data.ride_id ?? '-')],\n ['Order ID', String(data.order_id ?? '-')],\n ['Status', String(data.status ?? '-')],\n ['Scheduled', String(data.is_scheduled ?? false)],\n ['Order type', String(data.order_type ?? '-')],\n ];\n if (data.price) {\n lines.push(['Price', `${data.price.amount} ${data.price.currency}`]);\n if (data.price.quote_id) lines.push(['Quote ID', String(data.price.quote_id)]);\n }\n lines.push(['Payment status', String(data.payment_status ?? '-')]);\n // Mode-dependent: monthly_settlement returns billing_entry_id, pay_per_call\n // echoes back payment_order_id.\n if (data.billing_entry_id) lines.push(['Billing entry', String(data.billing_entry_id)]);\n if (data.payment_order_id) lines.push(['Payment order', String(data.payment_order_id)]);\n\n return Formatter.keyValue(lines);\n}\n\n// ============================================================\n// Command registration\n// ============================================================\n\n/**\n * `ride-elife book` — book a ride against a previously returned quote\n * (§4.4.1.3 book schema + §4.4.2.1). Write op (W/Y).\n *\n * Funding is decided server-side by the developer's `billing_mode`:\n * - monthly_settlement: no payment handle; fare is deducted from the\n * settlement account (payment_status=ON_ACCOUNT).\n * - pay_per_call: pass `--payment-order-id` (a PAID order from payment-cli).\n * The CLI MUST NOT accept `--payment-method-id` or card info — the merchant\n * domain never holds a payment credential, so the request body carries at most\n * an optional `payment_order_id` (design Property 5).\n *\n * `POST /ride/book` with `X-Api-Key` auth + the `Idempotency-Key` header (key\n * forwarded verbatim, never in the body). `--yes` skips the confirm; a missing\n * `--idempotency-key` under `--yes` throws `PARAM_IDEMPOTENCY_KEY_REQUIRED`\n * before any request is sent. Renders `BookResponse` via `renderWithContext`\n * (json carries the profile/endpoint envelope); the progress line goes to\n * stderr via `notify` and stays silent in json mode.\n */\nexport function registerBookCommand(parent: Command, deps: { apiClient: ApiClient }): void {\n const cmd = parent\n .command('book')\n .description('Book a ride using a quote_id returned by quote')\n .option('--api-key <key>', 'API Key for authentication (X-Api-Key)')\n .option('--quote-id <id>', 'Quote id from `ride-elife quote`')\n .option('--vehicle-class <class>', 'Chosen vehicle class')\n .option('--price-amount <amount>', 'Fare in decimal currency units (not cents)')\n .option('--price-currency <currency>', 'Currency code (default USD)')\n .option('--payment-order-id <id>', 'Paid payment order id (pay_per_call mode only)')\n .option('--passenger-name <name>', 'Passenger full name')\n .option('--passenger-phone <phone>', 'Passenger phone')\n .option('--passenger-email <email>', 'Passenger email')\n .option('--luggage-count <n>', 'Luggage count')\n .option('--special-requests <text>', 'Free-text special requests')\n .option('--pickup-lat <lat>', 'Pickup latitude')\n .option('--pickup-lng <lng>', 'Pickup longitude')\n .option('--pickup-name <name>', 'Pickup location name')\n .option('--dropoff-lat <lat>', 'Dropoff latitude')\n .option('--dropoff-lng <lng>', 'Dropoff longitude')\n .option('--dropoff-name <name>', 'Dropoff location name')\n .option('--pickup-time <time>', 'Pickup time: epoch seconds, or \"now\"')\n .option('--meet-and-greet', 'Enable meet & greet service')\n .option('--meet-and-greet-price <amount>', 'Meet & greet surcharge')\n .option('--welcome-sign <text>', 'Welcome sign text')\n .option('--child-seat-count <n>', 'Number of child seats needed (0-5)')\n .option('--infant-seat-count <n>', 'Number of infant seats needed (0-5)')\n .option('--toddler-seat-count <n>', 'Number of toddler seats needed (0-5)')\n .option('--arrival-flight-no <no>', 'Arrival flight number')\n .option('--arrival-airline <airline>', 'Arrival airline')\n .option('--departure-flight-no <no>', 'Departure flight number')\n .option('--departure-airline <airline>', 'Departure airline')\n .option(\n '--idempotency-key <key>',\n 'Idempotency key forwarded verbatim as the Idempotency-Key header',\n );\n\n attachSchemaHelp(cmd, bookSchema);\n\n cmd.action(async () => {\n const opts = cmd.optsWithGlobals();\n const format = resolveFormat(opts.format as string | undefined);\n const isYes = Boolean(opts.yes);\n\n const apiKey = await PromptEngine.resolveInput(opts.apiKey as string | undefined, {\n message: 'API Key:',\n type: 'password',\n });\n\n // Build request body. Required fields throw PARAM_INVALID before any\n // request is sent (mirrors the sibling `quote` command). The body carries\n // NO payment_method_id / card info — at most an optional payment_order_id\n // (design Property 5); funding is decided server-side by billing_mode.\n const quoteId = need(opts.quoteId as string | undefined, 'quote-id');\n const body: Record<string, unknown> = {\n quote_id: quoteId,\n vehicle_class: need(opts.vehicleClass as string | undefined, 'vehicle-class'),\n price_amount: num(opts.priceAmount as string | undefined, 'price-amount'),\n price_currency: (opts.priceCurrency as string | undefined) ?? 'USD',\n passenger_name: need(opts.passengerName as string | undefined, 'passenger-name'),\n passenger_phone: need(opts.passengerPhone as string | undefined, 'passenger-phone'),\n };\n\n // pay_per_call: optional paid payment order id (the only payment handle the\n // merchant CLI ever forwards). monthly_settlement omits it entirely.\n if (opts.paymentOrderId) body.payment_order_id = opts.paymentOrderId as string;\n if (opts.passengerEmail) body.passenger_email = opts.passengerEmail as string;\n if (opts.luggageCount !== undefined) {\n body.luggage_count = num(opts.luggageCount as string, 'luggage-count');\n }\n if (opts.specialRequests) body.special_requests = opts.specialRequests as string;\n\n // Pickup / dropoff / pickup_time are included only when supplied (they must\n // match the originating quote). Coordinates are number-ified.\n if (opts.pickupLat || opts.pickupLng || opts.pickupName) {\n body.pickup = {\n lat: num(opts.pickupLat as string | undefined, 'pickup-lat'),\n lng: num(opts.pickupLng as string | undefined, 'pickup-lng'),\n name: need(opts.pickupName as string | undefined, 'pickup-name'),\n };\n }\n if (opts.dropoffLat || opts.dropoffLng || opts.dropoffName) {\n body.dropoff = {\n lat: num(opts.dropoffLat as string | undefined, 'dropoff-lat'),\n lng: num(opts.dropoffLng as string | undefined, 'dropoff-lng'),\n name: need(opts.dropoffName as string | undefined, 'dropoff-name'),\n };\n }\n if (opts.pickupTime) {\n body.pickup_time =\n opts.pickupTime === 'now' ? 'now' : num(opts.pickupTime as string, 'pickup-time');\n }\n\n if (opts.meetAndGreet) body.meet_and_greet = true;\n if (opts.meetAndGreetPrice !== undefined) {\n body.meet_and_greet_price = num(opts.meetAndGreetPrice as string, 'meet-and-greet-price');\n }\n if (opts.welcomeSign) body.welcome_sign = opts.welcomeSign as string;\n if (opts.childSeatCount !== undefined) {\n body.child_seat_count = seatCount(opts.childSeatCount as string, 'child-seat-count');\n }\n if (opts.infantSeatCount !== undefined) {\n body.infant_seat_count = seatCount(opts.infantSeatCount as string, 'infant-seat-count');\n }\n if (opts.toddlerSeatCount !== undefined) {\n body.toddler_seat_count = seatCount(opts.toddlerSeatCount as string, 'toddler-seat-count');\n }\n if (opts.arrivalFlightNo || opts.arrivalAirline) {\n body.arrival_flight = {\n flight_no: opts.arrivalFlightNo as string | undefined,\n airline: opts.arrivalAirline as string | undefined,\n };\n }\n if (opts.departureFlightNo || opts.departureAirline) {\n body.departure_flight = {\n flight_no: opts.departureFlightNo as string | undefined,\n airline: opts.departureAirline as string | undefined,\n };\n }\n\n // Confirm before the write unless --yes. The warning/prompt go to stderr;\n // declining maps to CLIENT_ABORTED (exit 5) via the top-level envelope.\n if (!isYes) {\n const confirmed = await confirm({\n message: `Book ride with quote ${quoteId}?`,\n default: true,\n });\n if (!confirmed) {\n throw new CliError('CLIENT_ABORTED', 'Booking cancelled by user.');\n }\n }\n\n // Idempotency key (requirement 5.3): resolved before the request. Under\n // --yes a missing key is a hard error and no request is sent. The key is\n // sent as a header, never in the body.\n const idempotencyKey = await resolveIdempotencyKey(opts.idempotencyKey as string | undefined, {\n yes: isYes,\n commandPath: 'ride-elife book',\n });\n\n // Progress line: stderr in table mode, silent in json mode.\n notify(format, 'loading', 'Booking ride...');\n\n const result = await deps.apiClient.post<BookResponse>(\n '/ride/book',\n { type: 'api-key', key: apiKey },\n body,\n { 'Idempotency-Key': idempotencyKey },\n );\n\n if (!result.success) {\n throw CliError.fromApi(result, { auth: 'api-key' });\n }\n\n const data = result.data;\n\n const configManager = new ConfigManager();\n const commandResult: CommandResult<BookResponse> = {\n data,\n text: () => formatBook(data),\n };\n\n await renderWithContext(commandResult, { format }, configManager);\n });\n}\n","/**\n * Idempotency key resolution for write commands (`ride-elife book` / `cancel`)\n * — requirement 5.3 / §6.1, design Property 3.\n *\n * The error type is reused from `@agenzo/cli-core` (`IdempotencyKeyRequiredError`\n * → `PARAM_IDEMPOTENCY_KEY_REQUIRED`) so the merchant CLI does not re-define it.\n * The resolve/normalize logic stays in the app because it is merchant-domain\n * policy (per requirement 4.4): the §6.1 key format `[A-Za-z0-9_-]{1,128}`, the\n * `--yes`-missing hard error vs. interactive prompt branch, and the rule that\n * the key is forwarded verbatim as the `Idempotency-Key` HTTP header and is\n * never placed in the request body.\n *\n * The CLI NEVER auto-generates a key: under `--yes` a missing key is a hard\n * error thrown before any request is sent; otherwise the caller is prompted.\n */\nimport {\n CliError,\n IdempotencyKeyRequiredError,\n PromptEngine,\n} from '@agenzo/cli-core';\n\n/**\n * §6.1 idempotency key format: 1–128 characters drawn from `[A-Za-z0-9_-]`.\n */\nexport const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** Human-readable rule reused in validation messages and prompt feedback. */\nexport const IDEMPOTENCY_KEY_RULE = 'Use 1-128 characters from [A-Za-z0-9_-].';\n\n/**\n * Validate + normalize a caller-supplied idempotency key. A malformed key maps\n * to `PARAM_INVALID` (catalog code, exit 1) — never silently corrected and\n * never auto-generated.\n */\nexport function normalizeIdempotencyKey(key: string): string {\n const trimmed = key.trim();\n if (!IDEMPOTENCY_KEY_PATTERN.test(trimmed)) {\n throw new CliError(\n 'PARAM_INVALID',\n `Invalid idempotency key: \"${key}\". ${IDEMPOTENCY_KEY_RULE}`,\n );\n }\n return trimmed;\n}\n\n/**\n * Resolve the idempotency key for a write operation (requirement 5.3). The CLI\n * never generates one:\n * - supplied via `--idempotency-key` → validated + normalized;\n * - absent under `--yes` → hard error (`PARAM_IDEMPOTENCY_KEY_REQUIRED`,\n * reused from cli-core) thrown before any request is sent;\n * - absent otherwise → collected interactively, then validated.\n *\n * The returned key is forwarded verbatim as the `Idempotency-Key` header by the\n * caller — it never enters the request body.\n */\nexport async function resolveIdempotencyKey(\n flagValue: string | undefined,\n opts: { yes: boolean; commandPath: string },\n): Promise<string> {\n if (flagValue !== undefined) {\n return normalizeIdempotencyKey(flagValue);\n }\n if (opts.yes) {\n throw new IdempotencyKeyRequiredError(opts.commandPath);\n }\n const entered = await PromptEngine.resolveInput(undefined, {\n message: 'Idempotency key (unique per write, for safe retry):',\n validate: (v) => IDEMPOTENCY_KEY_PATTERN.test(v.trim()) || IDEMPOTENCY_KEY_RULE,\n });\n return normalizeIdempotencyKey(entered);\n}\n","import { Command } from 'commander';\nimport {\n ApiClient,\n ConfigManager,\n PromptEngine,\n Formatter,\n resolveFormat,\n notify,\n CliError,\n renderWithContext,\n} from '@agenzo/cli-core';\nimport type { CommandResult } from '@agenzo/cli-core';\nimport type { GetOrderResponse } from '../types/api.js';\nimport {\n DEFAULT_WATCH_INTERVAL_SECONDS,\n DEFAULT_WATCH_TIMEOUT_SECONDS,\n resolveSeconds,\n watchRideStatus,\n} from './watch.js';\nimport { attachSchemaHelp, rideGetSchema } from '../verb-schema.js';\n\n// ============================================================\n// Input helpers (ride-domain — stays in app per req 4.4)\n// ============================================================\n\n/**\n * Require a flag value. Missing required input maps to `PARAM_INVALID`\n * (requirement 3.1 / §4.4.1.3) — a catalog code (exit 1), mirroring the\n * sibling quote/book commands' convention.\n */\nfunction need(value: string | undefined, flag: string): string {\n if (value === undefined) {\n throw new CliError('PARAM_INVALID', `Missing required --${flag}.`);\n }\n return value;\n}\n\n// ============================================================\n// Output helper (table summary, non-watch path only)\n// ============================================================\n\n/**\n * Render a single ride order as a key/value block for `--format table`.\n * Pickup/dropoff are `from_location`/`to_location` (v3 snake_case, NOT the\n * elife `from`/`to` aliases). Amounts are decimal currency units (NOT cents).\n */\nfunction formatGetOrder(data: GetOrderResponse): string {\n const lines: [string, string][] = [\n ['Ride ID', String(data.ride_id ?? '-')],\n ['Status', String(data.status ?? '-')],\n ];\n if (data.source) lines.push(['Source', String(data.source)]);\n if (data.is_scheduled !== undefined) lines.push(['Scheduled', String(data.is_scheduled)]);\n if (data.from_location) {\n lines.push(['From', String(data.from_location.name ?? '-')]);\n }\n if (data.to_location) {\n lines.push(['To', String(data.to_location.name ?? '-')]);\n }\n if (data.pickup_time !== undefined) lines.push(['Pickup time', String(data.pickup_time)]);\n if (data.vehicle_class) lines.push(['Vehicle class', String(data.vehicle_class)]);\n if (data.price) {\n lines.push(['Price', `${data.price.amount} ${data.price.currency}`]);\n }\n if (data.final_amount !== undefined && data.final_amount !== null) {\n lines.push(['Final amount', String(data.final_amount)]);\n }\n if (data.final_settlement_status) {\n lines.push(['Settlement', String(data.final_settlement_status)]);\n }\n if (data.driver) {\n const driver = data.driver;\n const phone = driver.phone_number ? ` (${driver.phone_number})` : '';\n lines.push(['Driver', `${driver.name ?? '-'}${phone}`]);\n }\n if (data.vehicle) {\n const v = data.vehicle;\n const desc = [v.color, v.make, v.model].filter(Boolean).join(' ') || '-';\n const plate = v.license_plate ? ` [${v.license_plate}]` : '';\n lines.push(['Vehicle', `${desc}${plate}`]);\n }\n if (data.created_at) lines.push(['Created at', String(data.created_at)]);\n\n return Formatter.keyValue(lines);\n}\n\n// ============================================================\n// Command registration\n// ============================================================\n\n/**\n * `ride-elife get` — fetch a ride order status by id (§4.4.1.3 get schema).\n * Read-only (no idempotency key).\n *\n * Two modes:\n * - Non-`--watch`: a single `GET /ride/<id>/status` → `CommandResult` +\n * `renderWithContext` (json carries the profile/endpoint envelope).\n * - `--watch`: hands off to `watch.ts`, which polls until a terminal status\n * or timeout, writing each result as ONE NDJSON line on stdout. The watch\n * stream is NOT wrapped in the profile/endpoint envelope (it is a line\n * stream); on timeout the final line is `{ watch_status:'timeout', ... }`\n * (design Property 2).\n *\n * Named `registerRideGetCommand` to avoid clashing with the `services get`\n * registration.\n */\nexport function registerRideGetCommand(parent: Command, deps: { apiClient: ApiClient }): void {\n const cmd = parent\n .command('get')\n .description('Retrieve a ride order status by id (repeatable for polling)')\n .option('--api-key <key>', 'API Key for authentication (X-Api-Key)')\n .option('--order-id <id>', 'Ride order id (the ride_id returned by `ride-elife book`)')\n .option('--watch', 'Poll until a terminal status, emitting one NDJSON line per update')\n .option(\n '--watch-interval <seconds>',\n `Seconds between polls when --watch is set (default ${DEFAULT_WATCH_INTERVAL_SECONDS})`,\n )\n .option(\n '--watch-timeout <seconds>',\n `Max seconds to poll before giving up (default ${DEFAULT_WATCH_TIMEOUT_SECONDS})`,\n );\n\n attachSchemaHelp(cmd, rideGetSchema);\n\n cmd.action(async () => {\n const opts = cmd.optsWithGlobals();\n const format = resolveFormat(opts.format as string | undefined);\n\n const apiKey = await PromptEngine.resolveInput(opts.apiKey as string | undefined, {\n message: 'API Key:',\n type: 'password',\n });\n const orderId = need(opts.orderId as string | undefined, 'order-id');\n\n // --watch: NDJSON line stream (no profile/endpoint envelope). The stream\n // itself is the progress, so no spinner/notify is emitted.\n if (opts.watch) {\n await watchRideStatus(deps.apiClient, apiKey, orderId, {\n intervalSeconds: resolveSeconds(\n opts.watchInterval as string | undefined,\n DEFAULT_WATCH_INTERVAL_SECONDS,\n ),\n timeoutSeconds: resolveSeconds(\n opts.watchTimeout as string | undefined,\n DEFAULT_WATCH_TIMEOUT_SECONDS,\n ),\n });\n return;\n }\n\n // Single-shot: progress line on stderr (silent in json mode).\n notify(format, 'loading', 'Fetching ride status...');\n\n const result = await deps.apiClient.get<GetOrderResponse>(\n `/ride/${encodeURIComponent(orderId)}/status`,\n { type: 'api-key', key: apiKey },\n );\n\n if (!result.success) {\n throw CliError.fromApi(result, { auth: 'api-key' });\n }\n\n const data = result.data;\n\n const configManager = new ConfigManager();\n const commandResult: CommandResult<GetOrderResponse> = {\n data,\n text: () => formatGetOrder(data),\n };\n\n await renderWithContext(commandResult, { format }, configManager);\n });\n}\n","import { Command } from 'commander';\nimport { confirm } from '@inquirer/prompts';\nimport {\n ApiClient,\n ConfigManager,\n PromptEngine,\n Formatter,\n resolveFormat,\n notify,\n CliError,\n renderWithContext,\n} from '@agenzo/cli-core';\nimport type { CommandResult } from '@agenzo/cli-core';\nimport type { CancelResponse } from '../types/api.js';\nimport { attachSchemaHelp, cancelSchema } from '../verb-schema.js';\nimport { resolveIdempotencyKey } from '../idempotency.js';\n\n// ============================================================\n// Input helpers (ride-domain — stays in app per req 4.4)\n// ============================================================\n\n/**\n * Require a flag value. Missing required input maps to `PARAM_INVALID`\n * (requirement 3.3 / §4.4.1.3 cancel schema) — a catalog code (exit 1),\n * mirroring the sibling quote/book/get commands' convention.\n */\nfunction need(value: string | undefined, flag: string): string {\n if (value === undefined) {\n throw new CliError('PARAM_INVALID', `Missing required --${flag}.`);\n }\n return value;\n}\n\n// ============================================================\n// Output helper (table summary)\n// ============================================================\n\n/**\n * Render a cancelled ride as a key/value block for `--format table`. Amounts\n * are decimal currency units (NOT cents) — printed verbatim. `cancellation`\n * may be null when the backend reports no fee/reversal breakdown.\n */\nfunction formatCancel(data: CancelResponse): string {\n const lines: [string, string][] = [\n ['Ride ID', String(data.ride_id ?? '-')],\n ['Status', String(data.ride_stat ?? '-')],\n ];\n if (data.cancellation) {\n const c = data.cancellation;\n lines.push(['Cancellation fee', `${c.cancellation_fee} ${c.currency}`]);\n lines.push(['Reversal amount', `${c.reversal_amount} ${c.currency}`]);\n }\n if (data.refund_amount !== undefined && data.refund_amount !== null) {\n lines.push(['Refund amount', String(data.refund_amount)]);\n }\n\n return Formatter.keyValue(lines);\n}\n\n// ============================================================\n// Command registration\n// ============================================================\n\n/**\n * `ride-elife cancel` — cancel a ride order by id (§4.4.1.3 cancel schema).\n * Write op (W/Y).\n *\n * `POST /ride/<order-id>/cancel` with NO request body, `X-Api-Key` auth, and\n * the `Idempotency-Key` header (key forwarded verbatim, never in the body).\n * Cancelling may incur a fee, so the non-`--yes` path MUST confirm before the\n * write; `--yes` skips the confirmation. A missing `--idempotency-key` under\n * `--yes` throws `PARAM_IDEMPOTENCY_KEY_REQUIRED` before any request is sent;\n * non-`--yes` prompts for it. Declining the confirmation maps to\n * `CLIENT_ABORTED` (exit 5) via the top-level envelope. Renders\n * `CancelResponse` via `renderWithContext` (json carries the profile/endpoint\n * envelope); the progress line goes to stderr via `notify` and stays silent in\n * json mode.\n */\nexport function registerCancelCommand(parent: Command, deps: { apiClient: ApiClient }): void {\n const cmd = parent\n .command('cancel')\n .description('Cancel a ride order by id (may incur a cancellation fee)')\n .option('--api-key <key>', 'API Key for authentication (X-Api-Key)')\n .option('--order-id <id>', 'Ride order id to cancel (the ride_id returned by book)')\n .option(\n '--idempotency-key <key>',\n 'Idempotency key forwarded verbatim as the Idempotency-Key header',\n );\n\n attachSchemaHelp(cmd, cancelSchema);\n\n cmd.action(async () => {\n const opts = cmd.optsWithGlobals();\n const format = resolveFormat(opts.format as string | undefined);\n const isYes = Boolean(opts.yes);\n\n const apiKey = await PromptEngine.resolveInput(opts.apiKey as string | undefined, {\n message: 'API Key:',\n type: 'password',\n });\n\n // Required input throws PARAM_INVALID before any request is sent (mirrors\n // the sibling get/book commands).\n const orderId = need(opts.orderId as string | undefined, 'order-id');\n\n // Confirm before the write unless --yes. Cancelling may incur a fee, so the\n // prompt warns explicitly (requirement 3.3). The warning/prompt go to\n // stderr; declining maps to CLIENT_ABORTED (exit 5) via the top-level\n // envelope.\n if (!isYes) {\n const confirmed = await confirm({\n message: `Cancel ride ${orderId}? This may incur a fee.`,\n default: false,\n });\n if (!confirmed) {\n throw new CliError('CLIENT_ABORTED', 'Cancellation aborted by user.');\n }\n }\n\n // Idempotency key (requirement 5.3): resolved before the request. Under\n // --yes a missing key is a hard error and no request is sent. The key is\n // sent as a header, never in the body.\n const idempotencyKey = await resolveIdempotencyKey(opts.idempotencyKey as string | undefined, {\n yes: isYes,\n commandPath: 'ride-elife cancel',\n });\n\n // Progress line: stderr in table mode, silent in json mode.\n notify(format, 'loading', 'Cancelling ride...');\n\n // POST /ride/<id>/cancel carries NO body — only the Idempotency-Key header.\n const result = await deps.apiClient.post<CancelResponse>(\n `/ride/${encodeURIComponent(orderId)}/cancel`,\n { type: 'api-key', key: apiKey },\n undefined,\n { 'Idempotency-Key': idempotencyKey },\n );\n\n if (!result.success) {\n throw CliError.fromApi(result, { auth: 'api-key' });\n }\n\n const data = result.data;\n\n const configManager = new ConfigManager();\n const commandResult: CommandResult<CancelResponse> = {\n data,\n text: () => formatCancel(data),\n };\n\n await renderWithContext(commandResult, { format }, configManager);\n });\n}\n","import { Command } from 'commander';\nimport {\n ApiClient,\n ConfigManager,\n PromptEngine,\n Formatter,\n resolveFormat,\n notify,\n CliError,\n renderWithContext,\n} from '@agenzo/cli-core';\nimport type { CommandResult } from '@agenzo/cli-core';\nimport type { ListOrdersResponse, RideOrderListItem } from '../types/api.js';\nimport { attachSchemaHelp, listOrdersSchema } from '../verb-schema.js';\n\n// ============================================================\n// Input helpers (ride-domain — stays in app per req 4.4)\n// ============================================================\n\nconst DEFAULT_PAGE = '1';\nconst DEFAULT_PAGE_SIZE = '20';\n\n/**\n * Number-ify a pagination flag. Non-finite / non-integer / non-positive input\n * maps to `PARAM_INVALID` (catalog code, exit 1) — mirroring the sibling\n * quote/get/cancel commands' convention. Returns the canonical string form to\n * be passed through as a query parameter.\n */\nfunction positiveInt(value: string, flag: string): string {\n const n = Number(value);\n if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1) {\n throw new CliError('PARAM_INVALID', `--${flag} must be a positive integer.`);\n }\n return String(n);\n}\n\n// ============================================================\n// Output helper (table summary)\n// ============================================================\n\n/**\n * Render the order list as a table for `--format table`. Each order is one\n * row; amounts are decimal currency units (NOT cents) — printed verbatim.\n */\nfunction formatOrders(data: ListOrdersResponse): string {\n const orders: RideOrderListItem[] = data.orders ?? [];\n if (orders.length === 0) {\n return Formatter.status('info', 'No ride orders found');\n }\n\n const headers = ['Order ID', 'Ride ID', 'Status', 'Vehicle Class', 'Price', 'Currency', 'Payment'];\n const rows = orders.map((o) => [\n String(o.order_id ?? '-'),\n String(o.ride_id ?? '-'),\n String(o.status ?? '-'),\n String(o.vehicle_class ?? '-'),\n String(o.price_amount ?? '-'),\n String(o.price_currency ?? '-'),\n String(o.payment_status ?? '-'),\n ]);\n\n const summary: [string, string][] = [\n ['Total', String(data.total ?? '-')],\n ['Page', String(data.page ?? '-')],\n ['Page size', String(data.page_size ?? '-')],\n ];\n\n return `${Formatter.table(headers, rows)}\\n${Formatter.keyValue(summary)}`;\n}\n\n// ============================================================\n// Command registration\n// ============================================================\n\n/**\n * `ride-elife list-orders` — list previously placed ride orders (§4.4.1.3\n * list-orders schema). Read-only (no idempotency key).\n *\n * Passes `--page`(default 1) / `--page-size`(default 20) / `--status` /\n * `--order-type` through as query parameters to `GET /ride/orders` with the\n * `X-Api-Key` auth, and renders `ListOrdersResponse` via `renderWithContext`\n * (json carries the profile/endpoint envelope). `page`/`page-size` are\n * validated as positive integers (invalid → `PARAM_INVALID`); `status` /\n * `order-type` are forwarded verbatim only when set. The progress line is\n * emitted through `notify` so it goes to stderr and stays silent in json mode.\n */\nexport function registerListOrdersCommand(parent: Command, deps: { apiClient: ApiClient }): void {\n const cmd = parent\n .command('list-orders')\n .description('List previously placed ride orders')\n .option('--api-key <key>', 'API Key for authentication (X-Api-Key)')\n .option('--page <page>', 'Page number', DEFAULT_PAGE)\n .option('--page-size <size>', 'Page size', DEFAULT_PAGE_SIZE)\n .option('--status <status>', 'Filter by order status')\n .option('--order-type <type>', 'Filter by order type');\n\n attachSchemaHelp(cmd, listOrdersSchema);\n\n cmd.action(async () => {\n const opts = cmd.optsWithGlobals();\n const format = resolveFormat(opts.format as string | undefined);\n\n const apiKey = await PromptEngine.resolveInput(opts.apiKey as string | undefined, {\n message: 'API Key:',\n type: 'password',\n });\n\n // Build query params. page/page-size are validated as positive integers\n // (invalid → PARAM_INVALID before any request); status/order-type are\n // forwarded verbatim only when set. Sent as a query string, never a body.\n const params: Record<string, string> = {\n page: positiveInt((opts.page as string | undefined) ?? DEFAULT_PAGE, 'page'),\n page_size: positiveInt((opts.pageSize as string | undefined) ?? DEFAULT_PAGE_SIZE, 'page-size'),\n };\n if (opts.status !== undefined) params.status = opts.status as string;\n if (opts.orderType !== undefined) params.order_type = opts.orderType as string;\n\n // Progress line: stderr in table mode, silent in json mode.\n notify(format, 'loading', 'Fetching orders...');\n\n const result = await deps.apiClient.get<ListOrdersResponse>(\n '/ride/orders',\n { type: 'api-key', key: apiKey },\n params,\n );\n\n if (!result.success) {\n throw CliError.fromApi(result, { auth: 'api-key' });\n }\n\n const data = result.data;\n\n const configManager = new ConfigManager();\n const commandResult: CommandResult<ListOrdersResponse> = {\n data,\n text: () => formatOrders(data),\n };\n\n await renderWithContext(commandResult, { format }, configManager);\n });\n}\n","import { Command } from 'commander';\nimport { ConfigManager, Formatter, resolveFormat, renderWithContext } from '@agenzo/cli-core';\nimport type { CommandResult } from '@agenzo/cli-core';\nimport { SERVICE_REGISTRY, type ServiceCapability } from './registry.js';\n\n/**\n * Summary view of a registry entry for `services list` (§4.4.1.1): the\n * discovery-relevant subset — service_id/name/category/provider/cli_noun/\n * version/verbs/since/discovery — without the heavier verb_descriptions /\n * workflow detail (those are returned in full by `services get`).\n */\ninterface ServiceListItem {\n service_id: string;\n name: string;\n category: string;\n provider: string;\n cli_noun: string;\n version: string;\n verbs: string[];\n since: string;\n discovery: ServiceCapability['discovery'];\n}\n\nfunction toListItem(s: ServiceCapability): ServiceListItem {\n return {\n service_id: s.service_id,\n name: s.name,\n category: s.category,\n provider: s.provider,\n cli_noun: s.cli_noun,\n version: s.version,\n verbs: s.verbs,\n since: s.since,\n discovery: s.discovery,\n };\n}\n\n/**\n * `services list` — list available merchant capabilities (§4.4.1.1).\n *\n * Read-only, no `--idempotency-key`. Data source is the CLI-bundled registry\n * (D4), not a live backend feed. Output is wrapped by `renderWithContext` so\n * json carries the profile/endpoint envelope; the table form renders a\n * one-line-per-service summary on stdout.\n */\nexport function registerServicesListCommand(parent: Command): void {\n const cmd = parent\n .command('list')\n .description('List available merchant services from the registry');\n\n cmd.action(async () => {\n const opts = cmd.optsWithGlobals();\n const format = resolveFormat(opts.format as string | undefined);\n\n const services = SERVICE_REGISTRY.map(toListItem);\n\n const configManager = new ConfigManager();\n const commandResult: CommandResult<{ services: ServiceListItem[] }> = {\n data: { services },\n text: () => {\n if (services.length === 0) {\n return Formatter.status('info', 'No services found');\n }\n const headers = ['Service ID', 'Name', 'Category', 'Provider', 'Version', 'Verbs'];\n const rows = services.map((s) => [\n s.service_id,\n s.name,\n s.category,\n s.provider,\n s.version,\n s.verbs.join(', '),\n ]);\n return Formatter.table(headers, rows);\n },\n };\n\n await renderWithContext(commandResult, { format }, configManager);\n });\n}\n","/**\n * Built-in static capability registry (D4, merchant-domain only).\n *\n * NOTE: this is a CLI-bundled, single-merchant catalog — NOT a live backend\n * discovery feed. It does not reflect which services are enabled for the\n * current API key, nor the developer's billing mode (that is a per-developer\n * property decided by the backend, surfaced via the `book` response /\n * error codes, not advertised here). The §4.4.1 backend `/services` discovery\n * endpoint (BACK-063) + top-level `billing` block + `page` cursor are pending\n * impl; until they land, `services list/get` read this table.\n *\n * Each entry describes a CLI-exposed service: which `cli_noun` group hosts it,\n * the verbs it offers (with one-line descriptions), the recommended call\n * `workflow`, and discovery hints. `services list` renders a summary of these\n * entries and `services get <service-id>` returns one in full.\n *\n * `ServiceCapability` / the registry are merchant-domain specific (only\n * merchant-cli uses them) and stay in the app — they are NOT lifted to\n * `@agenzo/cli-core`.\n */\n\n/** Discovery hints for a capability (§4.4.1 schema; `schema_url` reserved for backend feed). */\nexport interface ServiceDiscovery {\n /** Command an agent can run to discover the verbs in detail. */\n help_command: string;\n /** Reserved for the backend discovery feed's per-verb JSON schema URL (pending impl). */\n schema_url?: string;\n}\n\nexport interface ServiceCapability {\n service_id: string;\n name: string;\n description: string;\n /** Service category (e.g. `ride`); part of the §4.4.1 schema form. */\n category: string;\n version: string;\n /** Upstream capability provider. */\n provider: string;\n /** Top-level CLI noun (command group) that hosts this service's verbs (`<category>-<provider>`). */\n cli_noun: string;\n /** Verb names exposed under `cli_noun`. */\n verbs: string[];\n /** One-line description per verb, keyed by verb name. */\n verb_descriptions: Record<string, string>;\n /** Ordered call sequence; `[cancel]` is optional. */\n workflow: string[];\n /** ISO date the capability became available. */\n since: string;\n discovery: ServiceDiscovery;\n}\n\n/** Static registry. This iteration ships a single `ride-elife` capability. */\nexport const SERVICE_REGISTRY: ServiceCapability[] = [\n {\n service_id: 'ride-elife',\n name: 'Ride hailing (eLife)',\n description: 'On-demand ride ordering: quote a fare, book it, poll status, and cancel.',\n category: 'ride',\n version: '1.0.0',\n provider: 'elife',\n cli_noun: 'ride-elife',\n verbs: ['quote', 'book', 'get', 'cancel', 'list-orders'],\n verb_descriptions: {\n quote: 'Request fare quotes for a ride between two points.',\n book: 'Book a ride using a quote_id returned by quote.',\n get: 'Retrieve a ride order by id (poll for status changes with --watch).',\n cancel: 'Cancel a ride order by id (may incur a fee).',\n 'list-orders': 'List previously placed ride orders.',\n },\n workflow: ['quote', 'book', 'get (poll for status)', 'cancel (optional)'],\n since: '2026-06-01',\n discovery: { help_command: 'agenzo-merchant-cli ride-elife --help' },\n },\n];\n\n/** Look up a capability by its service_id. Returns undefined when not found. */\nexport function findService(serviceId: string): ServiceCapability | undefined {\n return SERVICE_REGISTRY.find((s) => s.service_id === serviceId);\n}\n","import { Command } from 'commander';\nimport {\n ConfigManager,\n Formatter,\n CliError,\n resolveFormat,\n renderWithContext,\n} from '@agenzo/cli-core';\nimport type { CommandResult } from '@agenzo/cli-core';\nimport { findService, type ServiceCapability } from './registry.js';\n\n/**\n * Render the full capability as a key/value block for table output.\n */\nfunction formatServiceGet(s: ServiceCapability): string {\n const lines: [string, string][] = [\n ['Service ID', s.service_id],\n ['Name', s.name],\n ['Description', s.description],\n ['Category', s.category],\n ['Version', s.version],\n ['Provider', s.provider],\n ['CLI Noun', s.cli_noun],\n ['Verbs', s.verbs.join(', ')],\n ['Workflow', s.workflow.join(' → ')],\n ['Since', s.since],\n ['Help', s.discovery.help_command],\n ];\n const verbDetail = s.verbs\n .map((v) => ` ${v}: ${s.verb_descriptions[v] ?? ''}`)\n .join('\\n');\n return `${Formatter.keyValue(lines)}\\nVerb descriptions:\\n${verbDetail}`;\n}\n\n/**\n * `services get <service-id>` — return a single capability's full metadata\n * (§4.4.1.2), including verb_descriptions / workflow / discovery.\n *\n * Read-only, reads the CLI-bundled registry (D4). A hit is rendered via\n * `renderWithContext` (json carries the profile/endpoint envelope); a miss\n * throws cli-core's `CliError` with code `SERVICE_NOT_FOUND` (exit 1).\n */\nexport function registerServiceGetCommand(parent: Command): void {\n const cmd = parent\n .command('get <service-id>')\n .description('Retrieve a single merchant service by id');\n\n cmd.action(async (serviceId: string) => {\n const opts = cmd.optsWithGlobals();\n const format = resolveFormat(opts.format as string | undefined);\n\n const service = findService(serviceId);\n if (!service) {\n throw new CliError(\n 'SERVICE_NOT_FOUND',\n `Service '${serviceId}' was not found in the registry. Run \"services list\" to see available services.`,\n );\n }\n\n const configManager = new ConfigManager();\n const commandResult: CommandResult<ServiceCapability> = {\n data: service,\n text: () => formatServiceGet(service),\n };\n\n await renderWithContext(commandResult, { format }, configManager);\n });\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB;AAAA,EACE,aAAAA;AAAA,EACA,iBAAAC;AAAA,EACA,aAAAC;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,iBAAAC;AAAA,EAEA;AAAA,EACA;AAAA,OACK;;;ACXP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,OACK;;;ACTP,SAAS,gBAAgB;AAuBlB,IAAM,oBAAyC,oBAAI,IAAI;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,IAAM,iCAAiC;AAEvC,IAAM,gCAAgC;AAOtC,SAAS,iBAAiB,QAA4C;AAC3E,SAAO,WAAW,UAAa,WAAW,QAAQ,kBAAkB,IAAI,MAA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AAC1C,QAAM,WAAW,gBAAgB,KAAK;AACtC,QAAM,SAAS,oBAAoB;AAEnC,MAAI,WAAW,QAAQ;AACrB,YAAQ,MAAM,KAAK,UAAU,QAAQ,CAAC;AAAA,EACxC,OAAO;AACL,YAAQ;AAAA,MACNC,WAAU,OAAO,SAAS,IAAI,SAAS,MAAM,QAAQ,KAAK,SAAS,MAAM,OAAO,EAAE;AAAA,IACpF;AAEA,QAAI,EAAE,iBAAiBC,cAAa,QAAQ,KAAK,SAAS,WAAW,GAAG;AACtE,cAAQ,MAAM,KAAK;AAAA,IACrB;AAAA,EACF;AAIA,UAAQ,KAAK,YAAY,KAAK,CAAC;AACjC;AAGA,QAAQ,GAAG,UAAU,MAAM;AACzB,cAAY,IAAI,gBAAgB,CAAC;AACnC,CAAC;AAID,KAAK,EAAE,MAAM,WAAW;","names":["ApiClient","ConfigManager","Formatter","CliError","resolveFormat","CliError","CliError","ConfigManager","PromptEngine","Formatter","resolveFormat","notify","CliError","renderWithContext","CliError","PromptEngine","need","CliError","num","Formatter","resolveFormat","PromptEngine","notify","ConfigManager","renderWithContext","ConfigManager","PromptEngine","Formatter","resolveFormat","notify","CliError","renderWithContext","need","CliError","Formatter","resolveFormat","PromptEngine","notify","ConfigManager","renderWithContext","confirm","ConfigManager","PromptEngine","Formatter","resolveFormat","notify","CliError","renderWithContext","need","CliError","Formatter","resolveFormat","PromptEngine","confirm","notify","ConfigManager","renderWithContext","ConfigManager","PromptEngine","Formatter","resolveFormat","notify","CliError","renderWithContext","CliError","Formatter","resolveFormat","PromptEngine","notify","ConfigManager","renderWithContext","ConfigManager","Formatter","resolveFormat","renderWithContext","resolveFormat","ConfigManager","Formatter","renderWithContext","ConfigManager","Formatter","CliError","resolveFormat","renderWithContext","Formatter","resolveFormat","CliError","ConfigManager","renderWithContext","ConfigManager","ApiClient","resolveFormat","Formatter","CliError"]}
package/package.json CHANGED
@@ -1,56 +1,21 @@
1
1
  {
2
2
  "name": "@agenzo/merchant-cli",
3
- "version": "0.2.2",
4
- "description": "CLI tool for AI Agents to order rides and query merchant services",
3
+ "version": "0.3.0",
4
+ "description": "Merchant fulfillment CLI for the Agenzo platform",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "bin": {
8
8
  "agenzo-merchant-cli": "dist/index.js"
9
9
  },
10
10
  "files": [
11
- "dist",
12
- "README.md",
13
- "SKILL.md"
11
+ "dist"
14
12
  ],
15
13
  "scripts": {
16
14
  "build": "tsup",
17
- "dev": "tsup --watch",
18
- "lint": "eslint src",
19
- "test:drift": "node scripts/schema-drift-check.mjs",
20
- "prepublishOnly": "npm run build"
15
+ "dev": "tsup --watch"
21
16
  },
22
- "repository": {
23
- "type": "git",
24
- "url": "git+https://github.com/CardInfoLink/agenzo-token-cli.git",
25
- "directory": "merchant-cli"
26
- },
27
- "homepage": "https://github.com/CardInfoLink/agenzo-token-cli/tree/main/merchant-cli#readme",
28
- "bugs": {
29
- "url": "https://github.com/CardInfoLink/agenzo-token-cli/issues"
30
- },
31
- "author": "CardInfoLink",
32
- "keywords": [
33
- "cli",
34
- "ai-agent",
35
- "ride-hailing",
36
- "merchant",
37
- "fintech",
38
- "developer-tools"
39
- ],
40
- "engines": {
41
- "node": ">=18.0.0"
42
- },
43
- "license": "MIT",
44
17
  "dependencies": {
45
- "@inquirer/prompts": "^8.4.2",
18
+ "@agenzo/cli-core": "*",
46
19
  "commander": "^14.0.3"
47
- },
48
- "devDependencies": {
49
- "@eslint/js": "^9.0.0",
50
- "@types/node": "^25.6.0",
51
- "eslint": "^9.0.0",
52
- "tsup": "^8.5.1",
53
- "typescript": "^6.0.3",
54
- "typescript-eslint": "^8.0.0"
55
20
  }
56
21
  }