@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.
- package/README.md +198 -3
- package/package.json +29 -12
- package/src/cli.js +232 -0
- package/src/commands/listen.js +17 -8
- package/src/commands/login.js +59 -16
- package/src/commands/test-webhook.js +10 -3
- package/src/commands/tool-calls.js +138 -0
- package/src/commands/tools.js +762 -0
- package/src/commands/trigger.js +8 -3
- package/src/commands/webhook.js +8 -5
- package/src/commands/websocket.js +185 -58
- package/src/index.js +2 -166
- package/src/lib/api-client.js +116 -11
- package/src/lib/cli-websocket-client.js +381 -137
- package/src/lib/config.js +141 -13
- package/src/lib/tool-forwarder.js +325 -0
- package/src/lib/tool-session-store.js +361 -0
- package/src/lib/tool-signature.js +141 -0
- package/src/lib/webhook-verifier.js +43 -16
- package/src/lib/websocket-client.js +29 -3
- package/src/utils/logger.js +8 -7
- package/src/utils/secrets.js +44 -0
- package/src/utils/tool-approvals.js +238 -0
- package/src/utils/url-helpers.js +117 -0
- package/src/utils/webhook-payload.js +9 -6
- package/tool-signature.js +3 -0
package/src/commands/trigger.js
CHANGED
|
@@ -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
|
-
|
|
66
|
-
|
|
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');
|
package/src/commands/webhook.js
CHANGED
|
@@ -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
|
|
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 (
|
|
83
|
-
Logger.success('
|
|
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('
|
|
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
|
-
*
|
|
14
|
-
*
|
|
24
|
+
* Add --end-user and --cli-session to a request payload, unless it already
|
|
25
|
+
* says them.
|
|
15
26
|
*/
|
|
16
|
-
function
|
|
17
|
-
if (!
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
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
|
-
//
|
|
216
|
-
|
|
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(
|
|
219
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
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 {
|
|
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 =
|
|
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
|
-
|