@modelriver/cli 1.2.6 → 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,5 +1,10 @@
1
- const chalk = require('chalk');
2
- const ora = require('ora');
1
+ // chalk 6 and ora 10 are ESM-only. Node 22.12+ can require() them; the
2
+ // exports then sit on `.default`.
3
+ const chalkModule = require('chalk');
4
+ const oraModule = require('ora');
5
+
6
+ const chalk = chalkModule.default || chalkModule;
7
+ const ora = oraModule.default || oraModule;
3
8
 
4
9
  class Logger {
5
10
  static success(message) {
@@ -23,9 +28,7 @@ class Logger {
23
28
  }
24
29
 
25
30
  static spinner(message) {
26
- // Handle both CommonJS and ESM exports
27
- const oraInstance = typeof ora === 'function' ? ora : (ora.default || ora);
28
- return oraInstance(message);
31
+ return ora(message);
29
32
  }
30
33
 
31
34
  static section(title) {
@@ -35,5 +38,3 @@ class Logger {
35
38
  }
36
39
 
37
40
  module.exports = Logger;
38
-
39
-
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Show a secret without revealing it: known prefix (mr_live_, mr_test_) plus
3
+ * the last 4 characters, e.g. "mr_live_…a1b2". Short or unknown values are
4
+ * shown as "****".
5
+ * @param {string} value
6
+ * @returns {string}
7
+ */
8
+ function maskSecret(value) {
9
+ if (!value || typeof value !== 'string') return '(not set)';
10
+ const prefix = ['mr_live_', 'mr_test_'].find((p) => value.startsWith(p)) || '';
11
+ const rest = value.slice(prefix.length);
12
+ if (rest.length < 16) return `${prefix}****`;
13
+ return `${prefix}…${rest.slice(-4)}`;
14
+ }
15
+
16
+ /**
17
+ * Show a `modelriver tools` session token (cts_…) without revealing it:
18
+ * "cts_…" plus the last 4 characters.
19
+ * @param {string} value
20
+ * @returns {string}
21
+ */
22
+ function maskSessionToken(value) {
23
+ if (!value || typeof value !== 'string') return '(not set)';
24
+ const rest = value.startsWith('cts_') ? value.slice(4) : value;
25
+ if (rest.length < 16) return 'cts_****';
26
+ return `cts_…${rest.slice(-4)}`;
27
+ }
28
+
29
+ /**
30
+ * A copy of a request payload that is safe to print: the CLI session token
31
+ * in tool_route is masked.
32
+ * @param {object} payload
33
+ * @returns {object}
34
+ */
35
+ function redactRequestPayload(payload) {
36
+ if (!payload || typeof payload !== 'object') return payload;
37
+ const copy = { ...payload };
38
+ if (copy.tool_route && typeof copy.tool_route === 'object' && 'cli_session' in copy.tool_route) {
39
+ copy.tool_route = { ...copy.tool_route, cli_session: maskSessionToken(copy.tool_route.cli_session) };
40
+ }
41
+ return copy;
42
+ }
43
+
44
+ module.exports = { maskSecret, maskSessionToken, redactRequestPayload };
@@ -0,0 +1,238 @@
1
+ // Helpers for hosted-tools calls that wait for the end user's approval:
2
+ // showing them as plain text, the commands that decide them, how long to
3
+ // keep following a paused request, and what the approval API's errors mean.
4
+
5
+ // A request waits for approval at most an hour; a far-off expires_at (a
6
+ // wrong clock) can't keep the CLI waiting longer. After the last approval
7
+ // expires, give the server this long to resume and answer. Same numbers as
8
+ // the JS SDK (RESUMABLE_REQUEST_MAX_AGE_MS, APPROVAL_RESUME_MARGIN_MS).
9
+ const MAX_APPROVAL_WAIT_MS = 60 * 60 * 1000;
10
+ const APPROVAL_RESUME_MARGIN_MS = 5 * 60 * 1000;
11
+
12
+ // C0 controls except tab and new line, DEL, C1 controls, the Unicode line and
13
+ // paragraph separators, and invisible or direction-changing characters that
14
+ // could make approval text read differently from what it says: zero-width
15
+ // characters and marks (U+200B-U+200F, U+2060-U+2064, U+FEFF, U+061C), bidi
16
+ // embeddings, overrides and isolates (U+202A-U+202E, U+2066-U+2069), other
17
+ // characters that show as nothing (soft hyphen U+00AD, U+034F, U+180E, the
18
+ // Hangul fillers U+115F, U+1160, U+3164, U+FFA0) and tag characters
19
+ // (U+E0000-U+E007F), which can hide text.
20
+ // eslint-disable-next-line no-control-regex, no-misleading-character-class
21
+ const CONTROL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u2028-\u202e\u2060-\u2064\u2066-\u2069\u3164\ufeff\uffa0\u{e0000}-\u{e007f}]/gu;
22
+
23
+ /**
24
+ * Show a value as plain text. Text the model or the tool wrote must not be
25
+ * able to drive the terminal, so control characters (ANSI escapes included)
26
+ * are shown as \uXXXX; new lines and tabs are kept. Non-text values are
27
+ * shown as JSON.
28
+ * @param {*} value
29
+ * @returns {string}
30
+ */
31
+ function plainText(value) {
32
+ let text;
33
+ if (typeof value === 'string') {
34
+ text = value;
35
+ } else if (value === undefined) {
36
+ text = '';
37
+ } else {
38
+ try {
39
+ text = JSON.stringify(value);
40
+ } catch (error) {
41
+ text = String(value);
42
+ }
43
+ }
44
+ return text.replace(CONTROL_CHARS, (ch) => {
45
+ const code = ch.codePointAt(0);
46
+ return code > 0xffff ? `\\u{${code.toString(16)}}` : `\\u${code.toString(16).padStart(4, '0')}`;
47
+ });
48
+ }
49
+
50
+ /**
51
+ * The arguments shown to the end user, one per line, values in full.
52
+ * @param {object} args
53
+ * @param {string} [indent]
54
+ * @returns {string[]}
55
+ */
56
+ function formatArguments(args, indent = ' ') {
57
+ if (!args || typeof args !== 'object' || Array.isArray(args) || Object.keys(args).length === 0) {
58
+ return [`${indent}(none shown)`];
59
+ }
60
+ return Object.entries(args).map(([key, value]) => {
61
+ const text = plainText(value).replace(/\n/g, `\n${indent} `);
62
+ return `${indent}${plainText(key)}: ${text}`;
63
+ });
64
+ }
65
+
66
+ /**
67
+ * Quote a value for a POSIX shell, when it needs it.
68
+ * @param {string} value
69
+ * @returns {string}
70
+ */
71
+ function shellQuote(value) {
72
+ const text = String(value);
73
+ if (/^[A-Za-z0-9_.:@%+=/-]+$/.test(text)) return text;
74
+ return `'${text.replace(/'/g, `'\\''`)}'`;
75
+ }
76
+
77
+ /**
78
+ * The commands that approve or decline a call.
79
+ * @param {string} callId
80
+ * @param {string} [endUserId] - the request's end_user.id, when known
81
+ * @returns {{approve: string, reject: string, show: string}}
82
+ */
83
+ function approvalCommands(callId, endUserId) {
84
+ const id = shellQuote(plainText(callId));
85
+ const user = endUserId ? shellQuote(plainText(endUserId)) : '<end user id>';
86
+ return {
87
+ approve: `modelriver tools approve ${id} --end-user ${user}`,
88
+ reject: `modelriver tools reject ${id} --end-user ${user}`,
89
+ show: `modelriver tools show ${id}`,
90
+ };
91
+ }
92
+
93
+ /**
94
+ * Lines describing one call that waits for approval (a
95
+ * `tool_approval_required` event, or an `awaiting_approval` call in
96
+ * `tool_state`).
97
+ * @param {object} call - {id, name, label, prompt, arguments, expires_at}
98
+ * @param {object} [options] - {endUserId}
99
+ * @returns {string[]}
100
+ */
101
+ function describeApprovalRequired(call, { endUserId } = {}) {
102
+ const c = call || {};
103
+ const commands = approvalCommands(c.id || '<call id>', endUserId);
104
+ return [
105
+ `Waiting for approval: ${plainText(c.name || '(unknown tool)')} (call ${plainText(c.id || '?')})`,
106
+ // The tool's progress label, when it has one (e.g. "Cancelling the order…")
107
+ ...(typeof c.label === 'string' && c.label.trim() !== '' ? [` Label: ${plainText(c.label)}`] : []),
108
+ ` Prompt: ${plainText(c.prompt ?? '')}`,
109
+ ' Arguments shown to the end user:',
110
+ ...formatArguments(c.arguments, ' '),
111
+ ` Expires: ${plainText(c.expires_at || 'unknown')}`,
112
+ ' Decide it with:',
113
+ ` ${commands.approve}`,
114
+ ` ${commands.reject}`,
115
+ ];
116
+ }
117
+
118
+ const DECISION_TEXT = {
119
+ approved: 'approved; it runs now',
120
+ rejected: 'declined; it was not run',
121
+ expired: 'not decided in time; it was not run',
122
+ };
123
+
124
+ /**
125
+ * One line for a `tool_approval_resolved` event.
126
+ * @param {object} event - {id, name, decision}
127
+ * @returns {string}
128
+ */
129
+ function describeApprovalResolved(event) {
130
+ const e = event || {};
131
+ const what = DECISION_TEXT[e.decision] || plainText(e.decision || 'decided');
132
+ return `${plainText(e.name || '(unknown tool)')} (call ${plainText(e.id || '?')}): ${what}`;
133
+ }
134
+
135
+ /**
136
+ * Until when to keep following a request. While calls wait for approval
137
+ * that is the latest expires_at (at most an hour from now) plus a margin for
138
+ * the server to resume; it never moves earlier.
139
+ * @param {number} current - the deadline so far (ms since epoch)
140
+ * @param {Array<string>} expiresAts - ISO times of the calls waiting
141
+ * @param {number} [now]
142
+ * @returns {number}
143
+ */
144
+ function followDeadline(current, expiresAts, now = Date.now()) {
145
+ const times = (expiresAts || []).map((t) => Date.parse(t)).filter(Number.isFinite);
146
+ if (times.length === 0) return current;
147
+ const latest = Math.min(Math.max(...times), now + MAX_APPROVAL_WAIT_MS);
148
+ return Math.max(current, latest + APPROVAL_RESUME_MARGIN_MS);
149
+ }
150
+
151
+ /**
152
+ * What an error from the approval API means, for people.
153
+ * @param {object} response - {status, data, headers}
154
+ * @param {object} [context] - {decision: "approve"|"reject"|undefined}
155
+ * @returns {{message: string, hint: (string|null)}}
156
+ */
157
+ function describeToolCallError(response, { decision } = {}) {
158
+ const status = response && response.status;
159
+ const data = (response && response.data) || {};
160
+ const body = typeof data === 'object' ? data : {};
161
+ const code = typeof body.error === 'string' ? body.error : null;
162
+ const serverMessage = typeof body.message === 'string' ? plainText(body.message) : null;
163
+ const details = body.details && typeof body.details === 'object' ? body.details : {};
164
+ const withServer = (text) => (serverMessage ? `${text} (${serverMessage})` : text);
165
+
166
+ if (status === 400 && (code === 'end_user_required' || code === 'end_user_invalid')) {
167
+ return {
168
+ message: withServer(`The end user is missing or not valid: ${code}`),
169
+ hint: 'Pass --end-user with the end_user.id the request was sent with.',
170
+ };
171
+ }
172
+ if (status === 404 && code !== 'tool_call_not_found') {
173
+ // Not the approval API's own 404: this server has no such route.
174
+ return {
175
+ message: 'ModelRiver has no tool-call approval API at this address (HTTP 404).',
176
+ hint: 'Check --api-url. An older server, or one without hosted tools, does not have it.',
177
+ };
178
+ }
179
+ if (status === 404) {
180
+ return {
181
+ message: 'No call waiting for approval has this id (tool_call_not_found).',
182
+ hint: 'Check the call id and that the API key belongs to the request\'s project. ' +
183
+ 'Playground calls are decided in the console, and a call that needed no approval is not found either.',
184
+ };
185
+ }
186
+ if (status === 409 && code === 'end_user_mismatch') {
187
+ return {
188
+ message: 'This call belongs to a different end user (end_user_mismatch).',
189
+ hint: 'Pass --end-user with the end_user.id the request was sent with.',
190
+ };
191
+ }
192
+ if (status === 409 && code === 'tool_call_already_decided') {
193
+ const current = typeof details.status === 'string' ? plainText(details.status) : 'decided';
194
+ return {
195
+ message: `This call was already ${current}; nothing changed (tool_call_already_decided).`,
196
+ hint: current === 'rejected' && decision === 'approve'
197
+ ? 'A stopped request declines its waiting calls too.'
198
+ : null,
199
+ };
200
+ }
201
+ if (status === 410) {
202
+ return {
203
+ message: 'The time to decide on this call has passed, so it was not run (tool_approval_expired).',
204
+ hint: null,
205
+ };
206
+ }
207
+ if (status === 429) {
208
+ const header = response.headers && (response.headers['retry-after'] || response.headers['Retry-After']);
209
+ const retry = body.retry_after ?? header;
210
+ return {
211
+ message: 'Rate limited by ModelRiver.',
212
+ hint: retry !== undefined && retry !== null ? `Try again in ${plainText(retry)} seconds.` : 'Try again shortly.',
213
+ };
214
+ }
215
+ if (status === 401 || status === 403) {
216
+ return {
217
+ message: withServer(`The API key was refused (HTTP ${status}).`),
218
+ hint: 'Check your API key (modelriver login, or --api-key).',
219
+ };
220
+ }
221
+ return {
222
+ message: withServer(`Request failed with HTTP ${status}${code ? `: ${plainText(code)}` : ''}`),
223
+ hint: null,
224
+ };
225
+ }
226
+
227
+ module.exports = {
228
+ MAX_APPROVAL_WAIT_MS,
229
+ APPROVAL_RESUME_MARGIN_MS,
230
+ plainText,
231
+ formatArguments,
232
+ shellQuote,
233
+ approvalCommands,
234
+ describeApprovalRequired,
235
+ describeApprovalResolved,
236
+ followDeadline,
237
+ describeToolCallError,
238
+ };
@@ -122,8 +122,125 @@ function parseForwardUrl(url) {
122
122
  }
123
123
  }
124
124
 
125
+ /**
126
+ * Is this API host one that may be reached over plain http? The same hosts
127
+ * as for ws:// (see checkWebSocketUrl): localhost, 127.0.0.0/8 and ::1.
128
+ * @param {string} hostname - URL hostname (IPv6 may be bracketed)
129
+ * @returns {boolean}
130
+ */
131
+ function isLocalApiHost(hostname) {
132
+ return isLoopbackHost(hostname);
133
+ }
134
+
135
+ /**
136
+ * Check an API base URL. It must be https, except for localhost,
137
+ * 127.0.0.0/8 and ::1, which may use http.
138
+ *
139
+ * The CLI adds the API path itself (/v1, or /api/v1 off modelriver.com), so a
140
+ * URL saved or given with that path (`http://localhost:4000/api`) is cut back
141
+ * to the base; otherwise requests would go to /api/api/v1/… and be refused.
142
+ * @param {string} apiUrl
143
+ * @returns {string} the base URL, without a trailing slash or API path
144
+ * @throws {Error} when the URL is invalid or uses http for another host
145
+ */
146
+ function checkApiUrl(apiUrl) {
147
+ return stripApiPath(checkApiUrlScheme(apiUrl));
148
+ }
149
+
150
+ function stripApiPath(apiUrl) {
151
+ return apiUrl.replace(/\/(?:api\/v1|api|v1)\/?$/, '').replace(/\/$/, '');
152
+ }
153
+
154
+ function checkApiUrlScheme(apiUrl) {
155
+ let url;
156
+ try {
157
+ url = new URL(apiUrl);
158
+ } catch (error) {
159
+ throw new Error(`Invalid API URL "${apiUrl}"`);
160
+ }
161
+
162
+ if (url.protocol === 'https:') {
163
+ return apiUrl.replace(/\/$/, '');
164
+ }
165
+ if (url.protocol === 'http:' && isLocalApiHost(url.hostname)) {
166
+ return apiUrl.replace(/\/$/, '');
167
+ }
168
+ if (url.protocol === 'http:') {
169
+ throw new Error(`API URL must use https (only localhost, 127.0.0.0/8 and ::1 may use http): ${url.origin}`);
170
+ }
171
+ throw new Error(`API URL must use https: ${url.origin}`);
172
+ }
173
+
174
+ /**
175
+ * Is this host loopback: localhost, 127.0.0.0/8 or ::1?
176
+ * @param {string} hostname - URL hostname (IPv6 may be bracketed)
177
+ * @returns {boolean}
178
+ */
179
+ function isLoopbackHost(hostname) {
180
+ const host = String(hostname || '').toLowerCase().replace(/^\[|\]$/g, '');
181
+ return host === 'localhost' || host === '::1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
182
+ }
183
+
184
+ /**
185
+ * Upgrade a WebSocket URL the server gave as ws:// to wss:// where it can
186
+ * only mean TLS: port 443, or a modelriver.com host (behind a proxy the
187
+ * server may not know the client used https). Other URLs are returned as
188
+ * they are.
189
+ * @param {string} url
190
+ * @returns {string}
191
+ */
192
+ function normalizeWebSocketUrl(url) {
193
+ if (!url) return url;
194
+ try {
195
+ const wsUrl = new URL(url);
196
+ if (wsUrl.protocol !== 'ws:') return url;
197
+ const host = wsUrl.hostname.toLowerCase();
198
+ if (wsUrl.port === '443') {
199
+ wsUrl.protocol = 'wss:';
200
+ wsUrl.port = '';
201
+ } else if (host === 'modelriver.com' || host.endsWith('.modelriver.com')) {
202
+ wsUrl.protocol = 'wss:';
203
+ } else {
204
+ return url;
205
+ }
206
+ return wsUrl.toString().replace(/\/$/, '');
207
+ } catch (error) {
208
+ return url;
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Check a WebSocket URL the server gave us. It must be wss, except for
214
+ * localhost, 127.0.0.0/8 and ::1 (a local ModelRiver server), which may use
215
+ * ws. The socket carries the CLI's token and, for `modelriver tools`, every
216
+ * tool call, so it is never sent in the clear to another host.
217
+ * @param {string} websocketUrl
218
+ * @returns {string} the URL
219
+ * @throws {Error} when the URL is invalid, not ws/wss, or ws for another host
220
+ */
221
+ function checkWebSocketUrl(websocketUrl) {
222
+ let url;
223
+ try {
224
+ url = new URL(websocketUrl);
225
+ } catch (error) {
226
+ throw new Error(`The server gave an invalid WebSocket URL: "${websocketUrl}"`);
227
+ }
228
+
229
+ if (url.protocol === 'wss:') return websocketUrl;
230
+ if (url.protocol === 'ws:' && isLoopbackHost(url.hostname)) return websocketUrl;
231
+ if (url.protocol === 'ws:') {
232
+ throw new Error(`Refusing WebSocket URL ${url.origin}: it must use wss (only localhost, 127.0.0.0/8 and ::1 may use ws)`);
233
+ }
234
+ throw new Error(`Refusing WebSocket URL ${url.origin}: it must use wss`);
235
+ }
236
+
125
237
  module.exports = {
126
238
  normalizeWebhookUrl,
239
+ checkApiUrl,
240
+ checkWebSocketUrl,
241
+ normalizeWebSocketUrl,
242
+ isLoopbackHost,
243
+ isLocalApiHost,
127
244
  extractPort,
128
245
  isValidApiKeyFormat,
129
246
  parseForwardUrl
@@ -41,14 +41,14 @@ function getCustomerData(data) {
41
41
  return Object.keys(customerData).length > 0 ? customerData : null;
42
42
  }
43
43
 
44
- function buildCallbackHint(callbackUrl, channelId, apiKey) {
44
+ // `_apiKey` is accepted for older callers but never printed: the hint always
45
+ // refers to $MODELRIVER_API_KEY so no part of the key ends up in terminal logs.
46
+ function buildCallbackHint(callbackUrl, channelId, _apiKey) {
45
47
  if (!callbackUrl && !channelId) {
46
48
  return null;
47
49
  }
48
50
 
49
- const keyHint = apiKey
50
- ? `${apiKey.substring(0, 12)}...`
51
- : '$MODELRIVER_API_KEY';
51
+ const keyHint = '$MODELRIVER_API_KEY';
52
52
 
53
53
  const lines = [
54
54
  '> Event-driven webhook — complete the flow with a callback:',
@@ -121,13 +121,16 @@ function printWebhookDetails(webhookPayload, options = {}) {
121
121
  }
122
122
  } else {
123
123
  if (signature && webhookSecret && data) {
124
- const isValid = WebhookVerifier.verify(
124
+ const result = WebhookVerifier.check(
125
125
  signature,
126
126
  data,
127
127
  webhookSecret,
128
128
  String(timestamp)
129
129
  );
130
- Logger.log(` Signature: ${isValid ? '✓ Valid' : '✗ Invalid'}`);
130
+ let label = '✗ Invalid';
131
+ if (result.valid) label = '✓ Valid';
132
+ else if (result.signatureValid) label = '✗ Timestamp more than 5 minutes off';
133
+ Logger.log(` Signature: ${label}`);
131
134
  }
132
135
 
133
136
  if (data?.data) {
@@ -0,0 +1,3 @@
1
+ // require('@modelriver/cli/tool-signature'): check the signature on hosted tool calls
2
+ // your local tool server receives. See README, "Check the tool signature".
3
+ module.exports = require('./src/lib/tool-signature');