@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,5 +1,20 @@
1
1
  const axios = require('axios');
2
2
  const config = require('./config');
3
+ const { checkApiUrl } = require('../utils/url-helpers');
4
+
5
+ // A hosted-tools call id, as ModelRiver makes them (Signing.call_id/4).
6
+ const TOOL_CALL_ID = /^tc_[0-9a-f]{24}$/;
7
+
8
+ /**
9
+ * Throw unless this is a tool call id, so nothing else ends up in the URL.
10
+ * @param {string} callId
11
+ */
12
+ function checkToolCallId(callId) {
13
+ if (typeof callId !== 'string' || !TOOL_CALL_ID.test(callId)) {
14
+ const shown = typeof callId === 'string' ? JSON.stringify(callId.slice(0, 80)) : String(callId);
15
+ throw new Error(`${shown} is not a tool call id (expected "tc_" followed by 24 hex characters)`);
16
+ }
17
+ }
3
18
 
4
19
  function createAuthHeaders(apiKey) {
5
20
  return {
@@ -11,8 +26,6 @@ function createAuthHeaders(apiKey) {
11
26
  class ApiClient {
12
27
  constructor(apiKey = null, apiUrl = null) {
13
28
  this.apiKey = apiKey || config.getApiKey();
14
- this.apiUrl = (apiUrl || config.getApiUrl()).replace(/\/$/, '');
15
-
16
29
  if (!this.apiKey) {
17
30
  throw new Error('API key is required. Set MODELRIVER_API_KEY env var or use --api-key flag.');
18
31
  }
@@ -22,6 +35,9 @@ class ApiClient {
22
35
  throw new Error('Invalid API key format. API keys must start with "mr_live_" or "mr_test_".');
23
36
  }
24
37
 
38
+ // Throws unless the URL is https (http is allowed only for localhost).
39
+ this.apiUrl = checkApiUrl(apiUrl || config.getApiUrl());
40
+
25
41
  // Determine API path: /v1 in production (api.modelriver.com), /api/v1 in dev/test
26
42
  try {
27
43
  const apiUrlObj = new URL(this.apiUrl);
@@ -33,12 +49,6 @@ class ApiClient {
33
49
  this.apiPath = '/api/v1';
34
50
  }
35
51
 
36
- // Debug: Log API key info if DEBUG is set
37
- if (process.env.DEBUG) {
38
- console.log('[DEBUG] API Key (first 30 chars):', this.apiKey ? this.apiKey.substring(0, 30) + '...' : 'NOT SET');
39
- console.log('[DEBUG] Authorization header will be:', this.apiKey ? `Bearer ${this.apiKey.substring(0, 30)}...` : 'NOT SET');
40
- }
41
-
42
52
  this.client = axios.create({
43
53
  baseURL: this.apiUrl,
44
54
  headers: {
@@ -139,11 +149,8 @@ class ApiClient {
139
149
  try {
140
150
  const url = `${this.apiPath}/cli/connect`;
141
151
 
142
- // Debug: Log the request details
143
152
  if (process.env.DEBUG || this.verbose) {
144
153
  console.log('[DEBUG] Making request to:', `${this.apiUrl}${url}`);
145
- console.log('[DEBUG] API Key (first 30 chars):', this.apiKey ? this.apiKey.substring(0, 30) + '...' : 'NOT SET');
146
- console.log('[DEBUG] Authorization header:', this.apiKey ? `Bearer ${this.apiKey.substring(0, 30)}...` : 'NOT SET');
147
154
  }
148
155
 
149
156
  const response = await this.client.post(url, {});
@@ -174,6 +181,90 @@ class ApiClient {
174
181
  }
175
182
  }
176
183
 
184
+ /**
185
+ * Open a CLI tool session. Tool calls for this session are sent to the CLI
186
+ * over the WebSocket channel the response names.
187
+ * @returns {Promise<object>} - {session_id (the cts_ token), channel, expires_at, project_id}
188
+ */
189
+ async createToolSession() {
190
+ const url = `${this.apiPath}/cli/tool-sessions`;
191
+ let response;
192
+ try {
193
+ response = await this.client.post(url, {});
194
+ } catch (error) {
195
+ if (error.response) {
196
+ response = error.response;
197
+ } else if (error.request) {
198
+ throw new Error('Failed to open tool session: No response from server. Is the backend running?');
199
+ } else {
200
+ throw new Error(`Failed to open tool session: ${error.message}`);
201
+ }
202
+ }
203
+
204
+ if (response.status >= 400) {
205
+ const errorMsg = response.data?.message || response.data?.error?.message || response.data?.error || `HTTP ${response.status}`;
206
+ const error = new Error(`Failed to open tool session: ${typeof errorMsg === 'string' ? errorMsg : JSON.stringify(errorMsg)}`);
207
+ error.response = response;
208
+ throw error;
209
+ }
210
+
211
+ const data = response.data || {};
212
+ if (typeof data.session_id !== 'string' || !data.session_id) {
213
+ throw new Error('Failed to open tool session: the server did not return a session_id');
214
+ }
215
+ if (typeof data.channel !== 'string' || !data.channel.startsWith('cli_tools:')) {
216
+ throw new Error('Failed to open tool session: the server did not return a cli_tools channel');
217
+ }
218
+ return data;
219
+ }
220
+
221
+ /**
222
+ * Read a hosted-tools call waiting for approval: its prompt and the
223
+ * arguments the developer chose to show.
224
+ * GET /v1/ai/tool-calls/:call_id
225
+ * @param {string} callId - tc_…
226
+ * @returns {Promise<object>} - Axios response {status, data, headers}; 4xx don't throw
227
+ */
228
+ async getToolCall(callId) {
229
+ checkToolCallId(callId);
230
+ return this.client.get(`${this.apiPath}/ai/tool-calls/${encodeURIComponent(callId)}`, {
231
+ maxRedirects: 0,
232
+ });
233
+ }
234
+
235
+ /**
236
+ * Approve or decline a hosted-tools call for its end user.
237
+ * POST /v1/ai/tool-calls/:call_id/approve | reject
238
+ * @param {string} callId - tc_…
239
+ * @param {"approve"|"reject"} decision
240
+ * @param {string} endUserId - must be the request's end_user.id
241
+ * @returns {Promise<object>} - Axios response {status, data, headers}; 4xx don't throw
242
+ */
243
+ async decideToolCall(callId, decision, endUserId) {
244
+ if (decision !== 'approve' && decision !== 'reject') {
245
+ throw new Error(`Unknown decision "${decision}"`);
246
+ }
247
+ checkToolCallId(callId);
248
+ return this.client.post(
249
+ `${this.apiPath}/ai/tool-calls/${encodeURIComponent(callId)}/${decision}`,
250
+ { end_user: { id: endUserId } },
251
+ { maxRedirects: 0 }
252
+ );
253
+ }
254
+
255
+ /**
256
+ * Is this URL on the configured API host (same scheme, host and port)?
257
+ * @param {string} url
258
+ * @returns {boolean}
259
+ */
260
+ isApiOrigin(url) {
261
+ try {
262
+ return new URL(url).origin === new URL(this.apiUrl).origin;
263
+ } catch (error) {
264
+ return false;
265
+ }
266
+ }
267
+
177
268
  /**
178
269
  * Send an event-driven callback to complete a pending channel.
179
270
  * @param {string} callbackUrl - Full callback URL from webhook payload
@@ -181,8 +272,20 @@ class ApiClient {
181
272
  * @returns {Promise<object>} - Axios-like response { status, data }
182
273
  */
183
274
  async sendCallback(callbackUrl, body) {
275
+ // The API key goes only to the configured API host, never to a URL taken
276
+ // from a webhook payload that points somewhere else.
277
+ if (!this.isApiOrigin(callbackUrl)) {
278
+ let origin = callbackUrl;
279
+ try { origin = new URL(callbackUrl).origin; } catch (error) { /* keep as given */ }
280
+ throw new Error(
281
+ `Refusing to send your API key to ${origin}: callback URLs must be on the configured API host (${new URL(this.apiUrl).origin}). ` +
282
+ 'Use --channel-id, or set --api-url to match.'
283
+ );
284
+ }
285
+
184
286
  const response = await axios.post(callbackUrl, body, {
185
287
  headers: createAuthHeaders(this.apiKey),
288
+ maxRedirects: 0,
186
289
  validateStatus: (status) => status < 500,
187
290
  });
188
291
 
@@ -191,5 +294,7 @@ class ApiClient {
191
294
  }
192
295
 
193
296
  module.exports = ApiClient;
297
+ module.exports.TOOL_CALL_ID = TOOL_CALL_ID;
298
+ module.exports.checkToolCallId = checkToolCallId;
194
299
 
195
300