@modelriver/cli 1.2.5 → 2.0.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.
@@ -1,9 +1,10 @@
1
1
  const ApiClient = require('../lib/api-client');
2
2
  const Logger = require('../utils/logger');
3
3
  const Formatter = require('../utils/formatter');
4
+ const { maskSecret } = require('../utils/secrets');
4
5
 
5
6
  async function triggerCommand(options) {
6
- const { workflow, message, payload, webhookUrl, apiKey, apiUrl, printChannel } = options;
7
+ const { workflow, message, payload, webhookUrl, apiKey, apiUrl, printChannel, showSecret } = options;
7
8
 
8
9
  if (!workflow && !payload) {
9
10
  Logger.error('Error: --workflow or --payload is required');
@@ -62,8 +63,12 @@ async function triggerCommand(options) {
62
63
 
63
64
  webhookSpinner.succeed('Webhook created');
64
65
  Logger.success(`\n> Webhook ID: ${webhookResponse.id}`);
65
- Logger.warning(`> Secret: ${webhookResponse.secret}`);
66
- Logger.warning('> Save this secret - it won\'t be shown again!');
66
+ if (showSecret) {
67
+ Logger.warning(`> Secret: ${webhookResponse.secret}`);
68
+ Logger.warning('> Save this secret - it won\'t be shown again!');
69
+ } else {
70
+ Logger.warning(`> Secret: ${maskSecret(webhookResponse.secret)} (hidden; run with --show-secret to print it once)`);
71
+ }
67
72
  Logger.info(`\n> Response will be sent to: ${webhookUrl}`);
68
73
  } catch (error) {
69
74
  webhookSpinner.fail('Failed to create webhook');
@@ -71,19 +71,22 @@ async function verifyWebhook(options) {
71
71
  // Extract data from payload (webhook format)
72
72
  const webhookData = payloadData.data || payloadData;
73
73
 
74
- // Verify signature
75
- const isValid = WebhookVerifier.verify(
74
+ // Verify signature and timestamp (no more than 5 minutes off)
75
+ const result = WebhookVerifier.check(
76
76
  signature,
77
77
  webhookData,
78
78
  secret,
79
79
  timestamp
80
80
  );
81
81
 
82
- if (isValid) {
83
- Logger.success('✓ Signature is valid');
82
+ if (result.valid) {
83
+ Logger.success('Signature is valid');
84
84
  process.exit(0);
85
+ } else if (result.signatureValid) {
86
+ Logger.error('Signature matches, but the timestamp is more than 5 minutes from now, so a receiver must reject it');
87
+ process.exit(1);
85
88
  } else {
86
- Logger.error('✗ Signature is invalid');
89
+ Logger.error('Signature is invalid');
87
90
  process.exit(1);
88
91
  }
89
92
 
@@ -3,46 +3,130 @@ const WebSocketClient = require('../lib/websocket-client');
3
3
  const config = require('../lib/config');
4
4
  const Logger = require('../utils/logger');
5
5
  const Formatter = require('../utils/formatter');
6
+ const { normalizeWebSocketUrl } = require('../utils/url-helpers');
7
+ const { redactRequestPayload } = require('../utils/secrets');
8
+ const {
9
+ plainText,
10
+ describeApprovalRequired,
11
+ describeApprovalResolved,
12
+ followDeadline,
13
+ } = require('../utils/tool-approvals');
6
14
  const {
7
15
  buildCallbackHint,
8
16
  isFinalWebSocketStatus,
9
17
  isIntermediateWebSocketStatus,
10
18
  } = require('../utils/webhook-payload');
11
19
 
20
+ // How long to wait for a response when nothing is waiting for approval.
21
+ const RESPONSE_TIMEOUT_MS = 5 * 60 * 1000;
22
+
12
23
  /**
13
- * Normalize WebSocket URL for production environments
14
- * Converts ws:// to wss:// for port 443 or production domains
24
+ * Add --end-user and --cli-session to a request payload, unless it already
25
+ * says them.
15
26
  */
16
- function normalizeWebSocketUrl(url) {
17
- if (!url) return url;
27
+ function addToolOptions(requestPayload, { endUser, cliSession }) {
28
+ if (endUser && !requestPayload.end_user) {
29
+ requestPayload.end_user = { id: endUser };
30
+ }
31
+ if (cliSession && !requestPayload.tool_route) {
32
+ requestPayload.tool_route = { cli_session: cliSession };
33
+ }
34
+ return requestPayload;
35
+ }
18
36
 
19
- try {
20
- // Handle URLs like 'ws://api.modelriver.com:443/socket'
21
- // Convert to 'wss://api.modelriver.com/socket'
22
- const wsUrl = new URL(url);
23
-
24
- // If port is 443, use wss:// and remove port
25
- if (wsUrl.port === '443') {
26
- wsUrl.protocol = 'wss:';
27
- wsUrl.port = ''; // Remove port for standard https
28
- }
37
+ /**
38
+ * What to print when ModelRiver refuses the request: the status, then the
39
+ * error code, message and details it sent (details as JSON), and for a 429
40
+ * how long to wait. Text from the server is shown as plain text.
41
+ * @param {number} status
42
+ * @param {object|string} data - response body
43
+ * @param {object} [headers] - response headers (lower-case names)
44
+ * @returns {string[]}
45
+ */
46
+ function requestFailureLines(status, data, headers = {}) {
47
+ const lines = [`Request failed with status code ${status}`];
48
+ let body = {};
49
+ if (typeof data === 'string') {
50
+ body = { message: data };
51
+ } else if (data && typeof data === 'object') {
52
+ body = data;
53
+ }
54
+
55
+ if (body.error) lines.push(`Error: ${plainText(body.error)}`);
56
+ if (body.message) lines.push(`Message: ${plainText(body.message)}`);
57
+ const details = body.details;
58
+ const hasDetails = details && (typeof details !== 'object' || Object.keys(details).length > 0);
59
+ if (hasDetails) lines.push(`Details: ${plainText(details)}`);
60
+
61
+ if (status === 429) {
62
+ const retry = body.retry_after ?? (headers && headers['retry-after']);
63
+ if (retry !== undefined && retry !== null) lines.push(`Try again in ${plainText(retry)} seconds.`);
64
+ }
65
+ return lines;
66
+ }
29
67
 
30
- // If it's a production domain (ends with modelriver.com), ensure wss://
31
- if (wsUrl.hostname.endsWith('modelriver.com') && wsUrl.protocol === 'ws:') {
32
- wsUrl.protocol = 'wss:';
68
+ /**
69
+ * Follows a request's hosted-tools approvals: prints each call that waits
70
+ * for approval (and the commands that decide it) and each decision, and
71
+ * keeps the wait going while calls wait. Pure apart from `print` and `now`,
72
+ * so it can be tested without a socket.
73
+ */
74
+ class ApprovalFollower {
75
+ /**
76
+ * @param {object} options - {endUserId, print(lines, kind), onDeadline(ms), now}
77
+ */
78
+ constructor({ endUserId, print, onDeadline, now = Date.now }) {
79
+ this.endUserId = endUserId;
80
+ this.print = print;
81
+ this.onDeadline = onDeadline;
82
+ this.now = now;
83
+ this.deadline = now() + RESPONSE_TIMEOUT_MS;
84
+ this.waiting = new Map(); // call id -> expires_at
85
+ this.shown = new Set(); // call ids already printed
86
+ }
87
+
88
+ required(call) {
89
+ if (!call || typeof call !== 'object') return;
90
+ const id = call.id || '?';
91
+ this.waiting.set(id, call.expires_at);
92
+ if (!this.shown.has(id)) {
93
+ this.shown.add(id);
94
+ this.print(describeApprovalRequired(call, { endUserId: this.endUserId }), 'required');
33
95
  }
96
+ this.extend(followDeadline(this.deadline, [...this.waiting.values()], this.now()));
97
+ }
98
+
99
+ resolved(event) {
100
+ if (!event || typeof event !== 'object') return;
101
+ this.waiting.delete(event.id);
102
+ this.print([describeApprovalResolved(event)], 'resolved');
103
+ // The request carries on from here: allow it the usual time to answer.
104
+ this.extend(this.now() + RESPONSE_TIMEOUT_MS);
105
+ }
106
+
107
+ /** `tool_state` on join: calls already waiting when we joined. */
108
+ state(payload) {
109
+ const calls = payload && Array.isArray(payload.calls) ? payload.calls : [];
110
+ calls.filter((c) => c && c.status === 'awaiting_approval').forEach((c) => this.required(c));
111
+ }
112
+
113
+ isWaiting() {
114
+ return this.waiting.size > 0;
115
+ }
34
116
 
35
- return wsUrl.toString().replace(/\/$/, ''); // Remove trailing slash
36
- } catch (e) {
37
- // If URL parsing fails, return original
38
- return url;
117
+ extend(deadline) {
118
+ if (deadline > this.deadline) {
119
+ this.deadline = deadline;
120
+ if (this.onDeadline) this.onDeadline(deadline);
121
+ }
39
122
  }
40
123
  }
41
124
 
42
125
  async function websocketCommand(options) {
43
- const { workflow, message, payload, channelId, projectId, apiKey, apiUrl, verbose } = options;
126
+ const { workflow, message, payload, channelId, projectId, apiKey, apiUrl, verbose, endUser, cliSession } = options;
44
127
 
45
128
  let wsToken, websocketChannel, websocketUrl, channelIdToUse, projectIdToUse;
129
+ let endUserId = endUser;
46
130
 
47
131
  try {
48
132
  const apiClient = new ApiClient(apiKey, apiUrl);
@@ -54,6 +138,13 @@ async function websocketCommand(options) {
54
138
 
55
139
  try {
56
140
  const reconnectResponse = await apiClient.reconnectAsync(channelId);
141
+ // A 4xx doesn't throw: without a token there is nothing to connect with.
142
+ if (!reconnectResponse || typeof reconnectResponse.ws_token !== 'string' || !reconnectResponse.ws_token) {
143
+ const reason = reconnectResponse && typeof reconnectResponse.message === 'string'
144
+ ? plainText(reconnectResponse.message)
145
+ : 'ModelRiver gave no token for this channel. The request may have finished, or the channel ID is wrong.';
146
+ throw new Error(reason);
147
+ }
57
148
  wsToken = reconnectResponse.ws_token;
58
149
  websocketChannel = reconnectResponse.websocket_channel;
59
150
  websocketUrl = normalizeWebSocketUrl(reconnectResponse.websocket_url || config.getWebSocketUrl());
@@ -83,6 +174,10 @@ async function websocketCommand(options) {
83
174
  if (workflow && !requestPayload.workflow) {
84
175
  requestPayload.workflow = workflow;
85
176
  }
177
+ addToolOptions(requestPayload, { endUser, cliSession });
178
+ if (requestPayload.end_user && typeof requestPayload.end_user.id === 'string') {
179
+ endUserId = requestPayload.end_user.id;
180
+ }
86
181
 
87
182
  if (!requestPayload.workflow) {
88
183
  spinner.fail('Workflow required');
@@ -93,7 +188,8 @@ async function websocketCommand(options) {
93
188
  if (verbose) {
94
189
  Logger.info(`\n> API URL: ${apiClient.apiUrl}`);
95
190
  Logger.info(`> Workflow: ${requestPayload.workflow}`);
96
- Logger.info(`> Payload: ${JSON.stringify(requestPayload, null, 2)}`);
191
+ // The CLI session token works like a password: never print it.
192
+ Logger.info(`> Payload: ${JSON.stringify(redactRequestPayload(requestPayload), null, 2)}`);
97
193
  }
98
194
 
99
195
  const response = await apiClient.createAsyncRequest(requestPayload);
@@ -120,23 +216,16 @@ async function websocketCommand(options) {
120
216
  data = { message: data };
121
217
  }
122
218
 
123
- Logger.error(`Request failed with status code ${status}`);
219
+ const [first, ...rest] = requestFailureLines(status, data, error.response.headers);
220
+ Logger.error(first);
124
221
 
125
222
  // Log full response for debugging
126
223
  if (verbose) {
127
- Logger.info(`\nFull error response: ${JSON.stringify(data, null, 2)}`);
128
- Logger.info(`Response headers: ${JSON.stringify(error.response.headers, null, 2)}`);
224
+ Logger.info(`\nFull error response: ${plainText(JSON.stringify(data, null, 2))}`);
225
+ Logger.info(`Response headers: ${plainText(JSON.stringify(error.response.headers, null, 2))}`);
129
226
  }
130
227
 
131
- if (data?.error) {
132
- Logger.error(`Error: ${data.error}`);
133
- }
134
- if (data?.message) {
135
- Logger.error(`Message: ${data.message}`);
136
- }
137
- if (data?.details) {
138
- Logger.error(`Details: ${data.details}`);
139
- }
228
+ rest.forEach((line) => Logger.error(line));
140
229
 
141
230
  // If response is just "Forbidden" string, provide more context
142
231
  if (typeof error.response.data === 'string' && error.response.data === 'Forbidden') {
@@ -193,30 +282,21 @@ async function websocketCommand(options) {
193
282
  await wsClient.connect();
194
283
  connectSpinner.succeed('WebSocket connected');
195
284
 
196
- // Join channel
197
- const joinSpinner = Logger.spinner('Joining channel...');
198
- joinSpinner.start();
199
-
200
- try {
201
- await wsClient.joinChannel(websocketChannel);
202
- joinSpinner.succeed('Channel joined');
203
- Logger.warning('\n> Waiting for response...\n');
204
- } catch (error) {
205
- joinSpinner.fail('Failed to join channel');
206
- Logger.error(error.message);
207
- wsClient.close();
208
- process.exit(1);
209
- }
210
-
211
- // Set up response listener BEFORE waiting (to catch responses that arrive quickly)
285
+ // Set up the listeners BEFORE joining (to catch events that arrive quickly)
212
286
  let responseReceived = false;
213
287
  let sawIntermediateEvent = false;
214
288
 
215
- // Timeout after 5 minutes
216
- const timeoutId = setTimeout(() => {
289
+ // Wait 5 minutes for the response; while tool calls wait for approval,
290
+ // until the last approval expires (at most an hour) plus 5 minutes.
291
+ let timeoutId = null;
292
+ const onTimeout = () => {
217
293
  if (!responseReceived) {
218
- Logger.error('\n❌ Timeout: No response received after 5 minutes');
219
- if (sawIntermediateEvent) {
294
+ Logger.error(approvals.isWaiting()
295
+ ? '\n❌ Timeout: No response after the approval window ended'
296
+ : `\n❌ Timeout: No response received after ${Math.round((approvals.deadline - startedAt) / 60000)} minutes`);
297
+ if (approvals.isWaiting()) {
298
+ Logger.error(' Calls were still waiting for approval. Check them with: modelriver tools show <call_id>');
299
+ } else if (sawIntermediateEvent) {
220
300
  Logger.error(' Event-driven flow is waiting for a backend callback.');
221
301
  Logger.error(` Complete it with: modelriver callback --channel-id ${channelIdToUse} --data '{"summary":"..."}'`);
222
302
  } else {
@@ -228,7 +308,32 @@ async function websocketCommand(options) {
228
308
  wsClient.close();
229
309
  process.exit(1);
230
310
  }
231
- }, 5 * 60 * 1000);
311
+ };
312
+ const armTimeout = (deadline) => {
313
+ clearTimeout(timeoutId);
314
+ timeoutId = setTimeout(onTimeout, Math.max(0, deadline - Date.now()));
315
+ };
316
+ const startedAt = Date.now();
317
+ const approvals = new ApprovalFollower({
318
+ endUserId,
319
+ print: (lines, kind) => {
320
+ if (kind === 'required') {
321
+ Logger.warning(`\n${lines[0]}`);
322
+ Logger.log(lines.slice(1).join('\n'));
323
+ } else {
324
+ Logger.info(lines.join('\n'));
325
+ }
326
+ },
327
+ onDeadline: (deadline) => {
328
+ armTimeout(deadline);
329
+ if (verbose) Logger.info(`> Waiting for the response until ${new Date(deadline).toISOString()}`);
330
+ },
331
+ });
332
+ armTimeout(approvals.deadline);
333
+
334
+ wsClient.onEvent('tool_approval_required', (event) => approvals.required(event));
335
+ wsClient.onEvent('tool_approval_resolved', (event) => approvals.resolved(event));
336
+ wsClient.onEvent('tool_state', (state) => approvals.state(state));
232
337
 
233
338
  wsClient.onResponse((payload) => {
234
339
  const status = payload?.status;
@@ -266,11 +371,28 @@ async function websocketCommand(options) {
266
371
  responseReceived = true;
267
372
  clearTimeout(timeoutId);
268
373
  Logger.success('\n✅ Response received:\n');
269
- console.log(Formatter.json(payload));
374
+ // The model wrote the answer: control characters must not reach the terminal.
375
+ console.log(plainText(Formatter.json(payload)));
270
376
  wsClient.close();
271
377
  process.exit(0);
272
378
  });
273
379
 
380
+ // Join only now that every listener is in place: the server sends
381
+ // tool_state (calls already waiting for approval) right after the join.
382
+ const joinSpinner = Logger.spinner('Joining channel...');
383
+ joinSpinner.start();
384
+
385
+ try {
386
+ await wsClient.joinChannel(websocketChannel);
387
+ joinSpinner.succeed('Channel joined');
388
+ Logger.warning('\n> Waiting for response...\n');
389
+ } catch (error) {
390
+ joinSpinner.fail('Failed to join channel');
391
+ Logger.error(error.message);
392
+ wsClient.close();
393
+ process.exit(1);
394
+ }
395
+
274
396
  if (verbose) {
275
397
  Logger.info('✅ Response listener registered and ready');
276
398
  Logger.info('⏳ Waiting for server to send "response" event...');
@@ -280,9 +402,14 @@ async function websocketCommand(options) {
280
402
  wsClient.onClose(() => {
281
403
  clearTimeout(timeoutId);
282
404
  if (!responseReceived) {
405
+ // No response: a script waiting on this command must not read it as success.
406
+ process.exitCode = 1;
283
407
  Logger.warning('\n> WebSocket closed before response received');
284
408
  Logger.warning(' The server may have closed the connection without sending a response.');
285
409
  Logger.warning(' Check server logs or try the request again.');
410
+ if (channelIdToUse && projectIdToUse) {
411
+ Logger.warning(` Follow it again with: modelriver websocket --channel-id ${channelIdToUse} --project-id ${projectIdToUse}`);
412
+ }
286
413
  }
287
414
  });
288
415
 
@@ -298,6 +425,6 @@ async function websocketCommand(options) {
298
425
  }
299
426
  }
300
427
 
301
- module.exports = { websocketCommand };
428
+ module.exports = { websocketCommand, ApprovalFollower, addToolOptions, requestFailureLines, RESPONSE_TIMEOUT_MS };
302
429
 
303
430
 
package/src/index.js CHANGED
@@ -1,175 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { Command } = require('commander');
4
- const { loginCommand } = require('./commands/login');
5
- const { listenCommand } = require('./commands/listen');
6
- const { forwardCommand } = require('./commands/forward');
7
- const { websocketCommand } = require('./commands/websocket');
8
- const { triggerCommand } = require('./commands/trigger');
9
- const { callbackCommand } = require('./commands/callback');
10
- const { testWebhookCommand } = require('./commands/test-webhook');
11
- const { listWebhooks, verifyWebhook } = require('./commands/webhook');
12
- const config = require('./lib/config');
3
+ const { createProgram } = require('./cli');
13
4
 
14
- const program = new Command();
15
-
16
- const { version } = require('../package.json');
17
-
18
- program
19
- .name('modelriver')
20
- .description('ModelRiver CLI for testing webhooks and WebSockets from production')
21
- .version(version);
22
-
23
- // Global options
24
- program
25
- .option('-k, --api-key <key>', 'ModelRiver API key (or set MODELRIVER_API_KEY)')
26
- .option('--api-url <url>', 'API base URL (default: https://api.modelriver.com)')
27
- .option('-p, --project-id <id>', 'Project ID (or set MODELRIVER_PROJECT_ID)');
28
-
29
- // Login command - interactive setup
30
- program
31
- .command('login')
32
- .description('Configure your ModelRiver API key and forward URL interactively')
33
- .action((options) => {
34
- loginCommand(options);
35
- });
36
-
37
- // Listen command with alias 'l'
38
- program
39
- .command('listen')
40
- .alias('l')
41
- .description('Forward webhooks from production to local server via WebSocket')
42
- .option('-k, --api-key <key>', 'ModelRiver API key (or set MODELRIVER_API_KEY)')
43
- .option('--api-url <url>', 'API base URL (default: https://api.modelriver.com)')
44
- .option('-p, --port <port>', 'Local server port (default: 3001)')
45
- .option('-f, --forward', 'Forward to external server (do not start internal server)')
46
- .option('--print', 'Print webhook payloads to console')
47
- .option('-v, --verbose', 'Verbose output')
48
- .action((options) => {
49
- listenCommand({
50
- ...options,
51
- apiKey: options.apiKey || program.opts().apiKey,
52
- apiUrl: options.apiUrl || program.opts().apiUrl || config.getApiUrl(),
53
- });
54
- });
55
-
56
- // Forward command with alias 'f' - simplified webhook forwarding
57
- program
58
- .command('forward')
59
- .alias('f')
60
- .description('Forward webhooks using saved configuration (shortcut for listen --forward --print)')
61
- .option('-p, --port <port>', 'Override target port')
62
- .option('-v, --verbose', 'Verbose output')
63
- .action((options) => {
64
- forwardCommand(options);
65
- });
66
-
67
- // WebSocket command with alias 'ws'
68
- program
69
- .command('websocket')
70
- .alias('ws')
71
- .description('Test WebSocket connection to production')
72
- .option('-w, --workflow <name>', 'Workflow name')
73
- .option('-m, --message <text>', 'Test message')
74
- .option('-P, --payload <json>', 'Custom JSON payload')
75
- .option('-c, --channel-id <id>', 'Existing channel ID (requires --project-id)')
76
- .option('-v, --verbose', 'Verbose output')
77
- .action((options) => {
78
- websocketCommand({
79
- ...options,
80
- apiKey: options.apiKey || program.opts().apiKey,
81
- apiUrl: options.apiUrl || program.opts().apiUrl || config.getApiUrl(),
82
- projectId: options.projectId || program.opts().projectId
83
- });
84
- });
85
-
86
- // Callback command - complete event-driven flows
87
- program
88
- .command('callback')
89
- .description('Send an event-driven callback to complete a pending channel')
90
- .option('-c, --channel-id <id>', 'Channel ID from trigger/listen output')
91
- .option('--callback-url <url>', 'Full callback URL from webhook payload')
92
- .option('-d, --data <json>', 'Callback data object JSON')
93
- .option('-P, --payload <json>', 'Full callback payload JSON')
94
- .option('--task-id <id>', 'Optional task ID')
95
- .option('--metadata <json>', 'Optional metadata object JSON')
96
- .action((options) => {
97
- callbackCommand({
98
- ...options,
99
- apiKey: options.apiKey || program.opts().apiKey,
100
- apiUrl: options.apiUrl || program.opts().apiUrl || config.getApiUrl(),
101
- });
102
- });
103
-
104
- // Test Webhook command
105
- program
106
- .command('test-webhook')
107
- .description('Test webhook delivery - creates webhook, makes request, waits for response')
108
- .option('-w, --workflow <name>', 'Workflow name')
109
- .option('-m, --message <text>', 'Test message')
110
- .option('-P, --payload <json>', 'Custom JSON payload')
111
- .option('-u, --webhook-url <url>', 'Webhook URL (if not provided, starts local server on --port)')
112
- .option('-s, --secret <secret>', 'Webhook secret (optional, auto-generated if not provided)')
113
- .option('-p, --port <port>', 'Local server port when using local server (default: 3001)')
114
- .option('-v, --verbose', 'Verbose output')
115
- .action((options) => {
116
- testWebhookCommand({
117
- ...options,
118
- apiKey: options.apiKey || program.opts().apiKey,
119
- apiUrl: options.apiUrl || program.opts().apiUrl || config.getApiUrl(),
120
- });
121
- });
122
-
123
- // Trigger command with alias 't'
124
- program
125
- .command('trigger')
126
- .alias('t')
127
- .description('Send test async request')
128
- .option('-w, --workflow <name>', 'Workflow name')
129
- .option('-m, --message <text>', 'Test message')
130
- .option('-P, --payload <json>', 'Custom JSON payload')
131
- .option('-u, --webhook-url <url>', 'Webhook URL to receive response')
132
- .option('--print-channel', 'Print channel details')
133
- .action((options) => {
134
- triggerCommand({
135
- ...options,
136
- apiKey: options.apiKey || program.opts().apiKey,
137
- apiUrl: options.apiUrl || program.opts().apiUrl || config.getApiUrl()
138
- });
139
- });
140
-
141
- // Webhook commands
142
- const webhookCmd = program
143
- .command('webhook')
144
- .description('Webhook management commands (read-only and verification)');
145
-
146
- webhookCmd
147
- .command('list')
148
- .description('List all webhooks')
149
- .option('-v, --verbose', 'Show detailed information')
150
- .action((options) => {
151
- listWebhooks({
152
- ...options,
153
- apiKey: options.apiKey || program.opts().apiKey,
154
- apiUrl: options.apiUrl || program.opts().apiUrl || config.getApiUrl(),
155
- });
156
- });
157
-
158
- webhookCmd
159
- .command('verify')
160
- .description('Verify webhook signature')
161
- .requiredOption('-p, --payload <file|json>', 'Payload file path or JSON string')
162
- .requiredOption('-s, --signature <sig>', 'X-ModelRiver-Signature header value')
163
- .requiredOption('-t, --timestamp <ts>', 'X-ModelRiver-Timestamp header value')
164
- .requiredOption('--secret <secret>', 'Webhook secret')
165
- .action(verifyWebhook);
166
-
167
- // Parse arguments
5
+ const program = createProgram();
168
6
  program.parse();
169
7
 
170
8
  // Show help if no command provided
171
9
  if (!process.argv.slice(2).length) {
172
10
  program.outputHelp();
173
11
  }
174
-
175
-