@orth/cli 0.3.1 → 0.5.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.
Files changed (82) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +113 -109
  3. package/dist/analytics.d.ts +36 -8
  4. package/dist/analytics.js +247 -47
  5. package/dist/api.d.ts +34 -2
  6. package/dist/api.js +68 -13
  7. package/dist/command-actions.d.ts +10 -0
  8. package/dist/command-actions.js +42 -0
  9. package/dist/commands/account.d.ts +9 -1
  10. package/dist/commands/account.js +26 -10
  11. package/dist/commands/api.d.ts +3 -0
  12. package/dist/commands/api.js +114 -117
  13. package/dist/commands/auth.d.ts +3 -1
  14. package/dist/commands/auth.js +53 -9
  15. package/dist/commands/onboard/flow.d.ts +22 -0
  16. package/dist/commands/onboard/flow.js +155 -0
  17. package/dist/commands/onboard/guide.d.ts +8 -0
  18. package/dist/commands/onboard/guide.js +73 -0
  19. package/dist/commands/onboard/listing.d.ts +18 -0
  20. package/dist/commands/onboard/listing.js +166 -0
  21. package/dist/commands/onboard/progress.d.ts +44 -0
  22. package/dist/commands/onboard/progress.js +108 -0
  23. package/dist/commands/onboard/register.d.ts +2 -0
  24. package/dist/commands/onboard/register.js +261 -0
  25. package/dist/commands/onboard/requests.d.ts +24 -0
  26. package/dist/commands/onboard/requests.js +96 -0
  27. package/dist/commands/onboard/review.d.ts +31 -0
  28. package/dist/commands/onboard/review.js +228 -0
  29. package/dist/commands/onboard/setup.d.ts +68 -0
  30. package/dist/commands/onboard/setup.js +215 -0
  31. package/dist/commands/onboard/shared.d.ts +41 -0
  32. package/dist/commands/onboard/shared.js +97 -0
  33. package/dist/commands/onboard/tools.d.ts +19 -0
  34. package/dist/commands/onboard/tools.js +104 -0
  35. package/dist/commands/org.d.ts +21 -0
  36. package/dist/commands/org.js +126 -0
  37. package/dist/commands/payouts.d.ts +44 -0
  38. package/dist/commands/payouts.js +125 -0
  39. package/dist/commands/run.d.ts +2 -1
  40. package/dist/commands/run.js +23 -29
  41. package/dist/commands/search.d.ts +8 -1
  42. package/dist/commands/search.js +28 -4
  43. package/dist/commands/skills/browse.d.ts +15 -0
  44. package/dist/commands/skills/browse.js +194 -0
  45. package/dist/commands/skills/create.d.ts +5 -0
  46. package/dist/commands/skills/create.js +62 -0
  47. package/dist/commands/skills/init.d.ts +4 -0
  48. package/dist/commands/skills/init.js +123 -0
  49. package/dist/commands/skills/install.d.ts +6 -0
  50. package/dist/commands/skills/install.js +191 -0
  51. package/dist/commands/skills/local-files.d.ts +15 -0
  52. package/dist/commands/skills/local-files.js +110 -0
  53. package/dist/commands/skills/register.d.ts +2 -0
  54. package/dist/commands/skills/register.js +130 -0
  55. package/dist/commands/skills/shared.d.ts +43 -0
  56. package/dist/commands/skills/shared.js +69 -0
  57. package/dist/commands/skills/upload.d.ts +9 -0
  58. package/dist/commands/skills/upload.js +223 -0
  59. package/dist/commands/skills/verification.d.ts +5 -0
  60. package/dist/commands/skills/verification.js +74 -0
  61. package/dist/commands/telemetry.d.ts +3 -0
  62. package/dist/commands/telemetry.js +38 -0
  63. package/dist/config.d.ts +55 -1
  64. package/dist/config.js +102 -3
  65. package/dist/http.d.ts +15 -0
  66. package/dist/http.js +41 -0
  67. package/dist/index.js +133 -162
  68. package/dist/last-search.d.ts +19 -0
  69. package/dist/last-search.js +60 -0
  70. package/dist/organizations.d.ts +14 -0
  71. package/dist/organizations.js +77 -0
  72. package/dist/urls.d.ts +3 -0
  73. package/dist/urls.js +34 -0
  74. package/dist/utils.d.ts +20 -0
  75. package/dist/utils.js +112 -0
  76. package/dist/version.d.ts +5 -0
  77. package/dist/version.js +21 -0
  78. package/dist/x402.d.ts +7 -0
  79. package/dist/x402.js +27 -0
  80. package/package.json +23 -22
  81. package/dist/commands/skills.d.ts +0 -66
  82. package/dist/commands/skills.js +0 -821
package/dist/analytics.js CHANGED
@@ -1,71 +1,271 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.telemetryDisabledReason = telemetryDisabledReason;
3
7
  exports.getSearchFailureResponse = getSearchFailureResponse;
8
+ exports.summarizeSearchResponse = summarizeSearchResponse;
4
9
  exports.trackEvent = trackEvent;
10
+ exports.queueEvent = queueEvent;
11
+ exports.beginCommand = beginCommand;
12
+ exports.sendLoginStarted = sendLoginStarted;
13
+ exports.finishCommand = finishCommand;
14
+ exports.flushOnExit = flushOnExit;
15
+ const chalk_1 = __importDefault(require("chalk"));
16
+ const child_process_1 = require("child_process");
5
17
  const config_js_1 = require("./config.js");
6
- const CLI_VERSION = process.env.npm_package_version || "0.2.0";
7
- const PRODUCTION_BASE_URL = "https://api.orthogonal.com/v1";
8
- function getAnalyticsBaseUrl() {
9
- return process.env.ORTH_API_URL || PRODUCTION_BASE_URL;
18
+ const version_js_1 = require("./version.js");
19
+ const http_js_1 = require("./http.js");
20
+ const urls_js_1 = require("./urls.js");
21
+ /** Longest a finished command waits for its events to be accepted. */
22
+ const SEND_TIMEOUT_MS = 300;
23
+ /** Args whose values are catalog identifiers; every other arg is sent as presence only. */
24
+ const VALUE_ARGS = new Set(["slug", "api", "tool", "limit", "method"]);
25
+ /** The command being run; sent once, when it ends. */
26
+ let current;
27
+ /** Events raised mid-command (login.succeeded), sent with the command's own. */
28
+ let queued = [];
29
+ let startedAt = Date.now();
30
+ let exitHooked = false;
31
+ /** DO_NOT_TRACK convention (consoledonottrack.com): any value but empty, 0 or false. */
32
+ function isTruthy(value) {
33
+ if (!value)
34
+ return false;
35
+ return !["", "0", "false", "no"].includes(value.trim().toLowerCase());
36
+ }
37
+ /** Why telemetry is off, or undefined when it is on. */
38
+ function telemetryDisabledReason() {
39
+ if (isTruthy(process.env.DO_NOT_TRACK))
40
+ return "DO_NOT_TRACK";
41
+ if (isTruthy(process.env.ORTH_TELEMETRY_DISABLED))
42
+ return "ORTH_TELEMETRY_DISABLED";
43
+ if (!(0, config_js_1.getTelemetryEnabled)())
44
+ return "config";
45
+ return undefined;
46
+ }
47
+ function readSearchEventId(body) {
48
+ return body && typeof body === "object" && "searchEventId" in body &&
49
+ typeof body.searchEventId === "string"
50
+ ? body.searchEventId : undefined;
10
51
  }
11
52
  /** Preserve the server correlation ID when search errors become CLI telemetry. */
12
53
  function getSearchFailureResponse(error) {
13
54
  const responseBody = error && typeof error === "object" && "responseBody" in error
14
55
  ? error.responseBody : undefined;
15
- const searchEventId = responseBody && typeof responseBody === "object" &&
16
- "searchEventId" in responseBody && typeof responseBody.searchEventId === "string"
17
- ? responseBody.searchEventId : undefined;
18
- return {
19
- success: false,
20
- error: error instanceof Error ? error.message : "Unknown error",
21
- ...(searchEventId ? { searchEventId } : {}),
22
- };
56
+ const searchEventId = readSearchEventId(responseBody);
57
+ return { success: false, ...(searchEventId ? { searchEventId } : {}) };
58
+ }
59
+ /** Reduce a search response to success and correlation ID; never the body. */
60
+ function summarizeSearchResponse(response) {
61
+ const failed = response && typeof response === "object" && "success" in response &&
62
+ response.success === false;
63
+ const searchEventId = readSearchEventId(response);
64
+ return { success: !failed, ...(searchEventId ? { searchEventId } : {}) };
65
+ }
66
+ /**
67
+ * Keep values only for catalog identifiers (and the tool name of
68
+ * onboard.tools); free text, paths and secrets become presence only.
69
+ */
70
+ function sanitizeArgs(command, args) {
71
+ const sanitized = {};
72
+ for (const [key, value] of Object.entries(args)) {
73
+ if (value === undefined)
74
+ continue;
75
+ const keepValue = VALUE_ARGS.has(key) || (key === "name" && command === "onboard.tools");
76
+ sanitized[key] = keepValue ? value : true;
77
+ }
78
+ return Object.keys(sanitized).length > 0 ? sanitized : undefined;
23
79
  }
24
80
  /**
25
- * Fire-and-forget analytics event for CLI usage tracking.
26
- * Never blocks, never throws, never shows errors to the user.
81
+ * Remember the running command for its end-of-command event. Sends nothing;
82
+ * the asyncAction wrapper in command-actions.ts calls finishCommand when it
83
+ * ends.
27
84
  */
28
85
  function trackEvent(command, args, response) {
29
- // Don't track if no API key (not authenticated)
30
- const apiKey = (0, config_js_1.getApiKey)();
86
+ try {
87
+ current = {
88
+ command,
89
+ args,
90
+ response: response === undefined ? undefined : summarizeSearchResponse(response),
91
+ apiKey: (0, config_js_1.getApiKey)(),
92
+ };
93
+ }
94
+ catch {
95
+ // Telemetry never affects CLI operation.
96
+ }
97
+ }
98
+ /** Queue an event raised mid-command; it goes out with the command's own. */
99
+ function queueEvent(command, args) {
100
+ queued.push({ command, args, timestamp: new Date().toISOString() });
101
+ }
102
+ /** Start timing a command; a direct process.exit still reports it. */
103
+ function beginCommand() {
104
+ startedAt = Date.now();
105
+ if (!exitHooked) {
106
+ exitHooked = true;
107
+ process.on("exit", flushOnExit);
108
+ }
109
+ }
110
+ /** Take every unsent event as payloads, or none when telemetry is off. */
111
+ function takeEvents(exitCode) {
112
+ const events = [...queued];
113
+ const fallbackKey = current?.apiKey;
114
+ if (current) {
115
+ events.push({ ...current, exitCode, durationMs: Date.now() - startedAt });
116
+ }
117
+ current = undefined;
118
+ queued = [];
119
+ if (events.length === 0 || telemetryDisabledReason())
120
+ return undefined;
121
+ // Read at send time: login has just stored the key; logout has just removed it.
122
+ const apiKey = (0, config_js_1.getApiKey)() || fallbackKey;
31
123
  if (!apiKey)
32
- return;
33
- const payload = {
34
- command,
35
- args: args ? sanitizeArgs(args) : undefined,
36
- response,
37
- cliVersion: CLI_VERSION,
124
+ return undefined;
125
+ const timestamp = new Date().toISOString();
126
+ const install = safeInstallId();
127
+ const payloads = events.map((event) => ({
128
+ command: event.command,
129
+ installId: install,
130
+ args: event.args ? sanitizeArgs(event.command, event.args) : undefined,
131
+ response: event.response,
132
+ exitCode: event.exitCode,
133
+ durationMs: event.durationMs,
134
+ cliVersion: version_js_1.CLI_VERSION,
38
135
  os: process.platform,
39
136
  nodeVersion: process.version,
40
137
  apiKeyPrefix: apiKey.substring(0, 12),
41
- timestamp: new Date().toISOString(),
42
- };
43
- // Fire and forget - don't await, don't catch visible errors
44
- fetch(`${getAnalyticsBaseUrl()}/cli/events`, {
45
- method: "POST",
46
- headers: {
47
- Authorization: `Bearer ${apiKey}`,
48
- "Content-Type": "application/json",
49
- "x-orthogonal-source": "cli",
50
- },
51
- body: JSON.stringify(payload),
52
- }).catch(() => {
53
- // Silently ignore - analytics should never affect CLI operation
54
- });
138
+ timestamp: event.timestamp ?? timestamp,
139
+ }));
140
+ if (isTruthy(process.env.ORTH_TELEMETRY_DEBUG)) {
141
+ for (const payload of payloads)
142
+ console.error(`[telemetry] ${JSON.stringify(payload)}`);
143
+ return undefined;
144
+ }
145
+ showNoticeOnce();
146
+ return { apiKey, payloads };
147
+ }
148
+ /** This install's id, or undefined when the config cannot be read or written. */
149
+ function safeInstallId() {
150
+ try {
151
+ return (0, config_js_1.getInstallId)();
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
55
156
  }
56
157
  /**
57
- * Remove any potentially sensitive values from args
158
+ * `orth login` has started, before any key exists: one key-less event with
159
+ * only the install id and CLI version, sent at once (the login waits for the
160
+ * browser meanwhile). Never throws, never prints errors.
58
161
  */
59
- function sanitizeArgs(args) {
60
- const sanitized = {};
61
- const sensitiveKeys = ["key", "apiKey", "token", "secret", "password"];
62
- for (const [key, value] of Object.entries(args)) {
63
- if (sensitiveKeys.some((s) => key.toLowerCase().includes(s))) {
64
- sanitized[key] = "[REDACTED]";
65
- }
66
- else {
67
- sanitized[key] = value;
162
+ function sendLoginStarted() {
163
+ try {
164
+ if (telemetryDisabledReason())
165
+ return;
166
+ const installId = safeInstallId();
167
+ if (!installId)
168
+ return;
169
+ const payload = { command: "login.started", installId, cliVersion: version_js_1.CLI_VERSION };
170
+ if (isTruthy(process.env.ORTH_TELEMETRY_DEBUG)) {
171
+ console.error(`[telemetry] ${JSON.stringify(payload)}`);
172
+ return;
68
173
  }
174
+ showNoticeOnce();
175
+ void (0, http_js_1.orthFetch)(`${(0, urls_js_1.apiBaseUrl)()}/cli/events`, {
176
+ method: "POST",
177
+ headers: { "Content-Type": "application/json", "x-orthogonal-source": "cli" },
178
+ body: JSON.stringify(payload),
179
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
180
+ }).then((response) => response.arrayBuffer(), () => undefined).catch(() => undefined);
181
+ }
182
+ catch {
183
+ // Telemetry never affects CLI operation.
184
+ }
185
+ }
186
+ /** First event ever sent: say what is collected and how to opt out. */
187
+ function showNoticeOnce() {
188
+ if ((0, config_js_1.getTelemetryNoticeShown)())
189
+ return;
190
+ console.error(chalk_1.default.gray("orth sends usage telemetry to Orthogonal: command name, exit code, duration, CLI version\n" +
191
+ "and OS, linked to your API key and a random install id. It never sends search queries,\n" +
192
+ "file paths or responses.\n" +
193
+ "Opt out with 'orth telemetry disable', ORTH_TELEMETRY_DISABLED=1 or DO_NOT_TRACK=1."));
194
+ (0, config_js_1.setTelemetryNoticeShown)();
195
+ }
196
+ function eventHeaders(apiKey) {
197
+ return {
198
+ Authorization: `Bearer ${apiKey}`,
199
+ "Content-Type": "application/json",
200
+ "x-orthogonal-source": "cli",
201
+ };
202
+ }
203
+ /**
204
+ * Send the command's event with its exit code and duration, waiting at most
205
+ * SEND_TIMEOUT_MS. Never throws, never prints errors.
206
+ */
207
+ async function finishCommand(exitCode) {
208
+ try {
209
+ const batch = takeEvents(exitCode);
210
+ if (!batch)
211
+ return;
212
+ const url = `${(0, urls_js_1.apiBaseUrl)()}/cli/events`;
213
+ await Promise.all(batch.payloads.map(async (payload) => {
214
+ try {
215
+ const response = await (0, http_js_1.orthFetch)(url, {
216
+ method: "POST",
217
+ headers: eventHeaders(batch.apiKey),
218
+ body: JSON.stringify(payload),
219
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
220
+ });
221
+ await response.arrayBuffer();
222
+ }
223
+ catch {
224
+ // Silently ignore - analytics should never affect CLI operation
225
+ }
226
+ }));
227
+ }
228
+ catch {
229
+ // Telemetry never affects CLI operation.
230
+ }
231
+ }
232
+ /** Posts each event in ORTH_TELEMETRY_EVENTS from a detached child process. */
233
+ const EXIT_SENDER = `
234
+ const headers = JSON.parse(process.env.ORTH_TELEMETRY_HEADERS);
235
+ for (const event of JSON.parse(process.env.ORTH_TELEMETRY_EVENTS)) {
236
+ fetch(process.env.ORTH_TELEMETRY_URL, {
237
+ method: "POST", headers, body: JSON.stringify(event),
238
+ signal: AbortSignal.timeout(${SEND_TIMEOUT_MS}),
239
+ }).catch(() => {});
240
+ }`;
241
+ /**
242
+ * process.exit mid-command: hand unsent events to a detached child so this
243
+ * process exits at once.
244
+ */
245
+ function flushOnExit(code) {
246
+ try {
247
+ const batch = takeEvents(code);
248
+ if (!batch)
249
+ return;
250
+ const url = `${(0, urls_js_1.apiBaseUrl)()}/cli/events`;
251
+ (0, child_process_1.spawn)(process.execPath, ["-e", EXIT_SENDER], {
252
+ detached: true,
253
+ stdio: "ignore",
254
+ windowsHide: true,
255
+ env: {
256
+ ORTH_TELEMETRY_URL: url,
257
+ // The child's env is only this: the bypass rides in its headers.
258
+ ORTH_TELEMETRY_HEADERS: JSON.stringify({
259
+ ...eventHeaders(batch.apiKey),
260
+ ...(0, urls_js_1.protectionBypass)(url),
261
+ }),
262
+ ORTH_TELEMETRY_EVENTS: JSON.stringify(batch.payloads),
263
+ // Windows sockets need SystemRoot.
264
+ ...(process.env.SYSTEMROOT ? { SYSTEMROOT: process.env.SYSTEMROOT } : {}),
265
+ },
266
+ }).unref();
267
+ }
268
+ catch {
269
+ // Telemetry never affects CLI operation.
69
270
  }
70
- return sanitized;
71
271
  }
package/dist/api.d.ts CHANGED
@@ -3,9 +3,13 @@ export declare function apiRequest<T = unknown>(endpoint: string, options?: {
3
3
  body?: unknown;
4
4
  }): Promise<T>;
5
5
  export interface SearchResponse {
6
+ /** This search's id: /v1/run takes it back to link the call to it. */
7
+ searchId?: string;
6
8
  results: Array<{
7
9
  name: string;
8
10
  slug: string;
11
+ /** "integration" for an OAuth app (Gmail, Slack, …) run on the person's own connected account. */
12
+ kind?: string;
9
13
  endpoints: Array<{
10
14
  path: string;
11
15
  method: string;
@@ -14,12 +18,31 @@ export interface SearchResponse {
14
18
  hasDynamicPricing?: boolean;
15
19
  pricing_formula?: string;
16
20
  apiSlug?: string;
21
+ /** 30-day delivered quality, while the server shows it. */
22
+ quality?: Pick<EndpointQuality, "tier" | "scope" | "successRate30d">;
17
23
  }>;
18
24
  }>;
19
25
  count: number;
20
26
  apisCount: number;
21
27
  }
28
+ /**
29
+ * An endpoint's last 30 days as /v1/details reports them: the success rate
30
+ * (0 to 1) and median ms are null below 100 calls; `scope` "api" means the
31
+ * figures are the whole API's, the endpoint having too few calls of its own.
32
+ */
33
+ export interface EndpointQuality {
34
+ tier: string;
35
+ scope?: "endpoint" | "api";
36
+ successRate30d: number | null;
37
+ medianMs: number | null;
38
+ calls30d: number;
39
+ }
22
40
  export interface DetailsResponse {
41
+ /** How to call the endpoint; x402 is the server's pay-per-call URL. */
42
+ usage?: {
43
+ runApi?: string;
44
+ x402?: string;
45
+ };
23
46
  api?: string | {
24
47
  name: string;
25
48
  slug: string;
@@ -50,6 +73,12 @@ export interface DetailsResponse {
50
73
  method: string;
51
74
  description?: string;
52
75
  price?: number | string;
76
+ hasDynamicPricing?: boolean;
77
+ /** A self-service listing's per-call maximum and what it refuses. */
78
+ pricingNote?: string;
79
+ maxPrice?: number;
80
+ /** 30-day delivered quality, while the server shows it. */
81
+ quality?: EndpointQuality;
53
82
  queryParams?: Array<{
54
83
  name: string;
55
84
  type: string;
@@ -94,7 +123,6 @@ export interface ListApisResponse {
94
123
  name: string;
95
124
  slug: string;
96
125
  description?: string;
97
- baseUrl: string;
98
126
  verified: boolean;
99
127
  endpoints: Array<{
100
128
  path: string;
@@ -115,7 +143,6 @@ export interface ApiBySlugResponse {
115
143
  name: string;
116
144
  slug: string;
117
145
  description?: string;
118
- baseUrl: string;
119
146
  verified: boolean;
120
147
  };
121
148
  endpoints: Array<{
@@ -124,6 +151,8 @@ export interface ApiBySlugResponse {
124
151
  method: string;
125
152
  description?: string;
126
153
  price?: number;
154
+ /** The price as the site words it ("from $0.04 per call", "Free"). */
155
+ priceText?: string;
127
156
  isPayable?: boolean;
128
157
  hasDynamicPricing?: boolean;
129
158
  pricing_formula?: string;
@@ -151,10 +180,13 @@ export declare function run(api: string, path: string, options?: {
151
180
  query?: Record<string, string>;
152
181
  body?: unknown;
153
182
  dryRun?: boolean;
183
+ /** The search that led to this call (optional; servers ignore a bad one). */
184
+ searchId?: string;
154
185
  }): Promise<RunResponse>;
155
186
  export declare function integrate(api: string, path: string, format?: string): Promise<IntegrateResponse>;
156
187
  export interface MeResponse {
157
188
  type: "user" | "organization";
189
+ userId?: string;
158
190
  name?: string | null;
159
191
  email?: string | null;
160
192
  organizationId?: string;
package/dist/api.js CHANGED
@@ -8,19 +8,55 @@ exports.getDetails = getDetails;
8
8
  exports.run = run;
9
9
  exports.integrate = integrate;
10
10
  exports.getMe = getMe;
11
+ const node_http_1 = require("node:http");
11
12
  const config_js_1 = require("./config.js");
12
- const BASE_URL = process.env.ORTH_API_URL || "https://api.orthogonal.com/v1";
13
+ const http_js_1 = require("./http.js");
14
+ const urls_js_1 = require("./urls.js");
15
+ const utils_js_1 = require("./utils.js");
16
+ // fetch's (undici's) cause codes for a server that took too long to answer or
17
+ // dropped the connection without one.
18
+ const NO_ANSWER_CODES = new Set([
19
+ "UND_ERR_HEADERS_TIMEOUT",
20
+ "UND_ERR_CONNECT_TIMEOUT",
21
+ "UND_ERR_SOCKET",
22
+ "ECONNRESET",
23
+ "ETIMEDOUT",
24
+ ]);
25
+ /**
26
+ * Why a request got no response: nothing listening (refused), a server that
27
+ * did not answer in time, or else most likely the network.
28
+ */
29
+ function unreachableMessage(error, elapsedMs) {
30
+ const host = new URL((0, urls_js_1.apiBaseUrl)()).host;
31
+ const cause = error instanceof Error ? error.cause : undefined;
32
+ const code = cause instanceof Error && "code" in cause ? cause.code : undefined;
33
+ if (code === "ECONNREFUSED") {
34
+ return `${host} refused the connection. Check that the server is running.`;
35
+ }
36
+ if (typeof code === "string" && NO_ANSWER_CODES.has(code)) {
37
+ return `${host} did not answer in ${(elapsedMs / 1000).toFixed(1)} s. Try again in a moment.`;
38
+ }
39
+ return `Can't reach ${host}. Check your internet connection and try again.`;
40
+ }
13
41
  async function apiRequest(endpoint, options = {}) {
14
42
  const apiKey = (0, config_js_1.requireApiKey)();
15
- const res = await fetch(`${BASE_URL}${endpoint}`, {
16
- method: options.method || "GET",
17
- headers: {
18
- Authorization: `Bearer ${apiKey}`,
19
- "Content-Type": "application/json",
20
- "x-orthogonal-source": "cli",
21
- },
22
- body: options.body ? JSON.stringify(options.body) : undefined,
23
- });
43
+ const url = `${(0, urls_js_1.apiBaseUrl)()}${endpoint}`;
44
+ const started = Date.now();
45
+ let res;
46
+ try {
47
+ res = await (0, http_js_1.orthFetch)(url, {
48
+ method: options.method || "GET",
49
+ headers: {
50
+ Authorization: `Bearer ${apiKey}`,
51
+ "Content-Type": "application/json",
52
+ "x-orthogonal-source": "cli",
53
+ },
54
+ body: options.body ? JSON.stringify(options.body) : undefined,
55
+ });
56
+ }
57
+ catch (error) {
58
+ throw new Error(unreachableMessage(error, Date.now() - started));
59
+ }
24
60
  // Parse defensively: error responses (e.g. a bare 404) may return an empty
25
61
  // or non-JSON body, which would otherwise throw here and lose the status.
26
62
  const rawBody = await res.text();
@@ -33,12 +69,30 @@ async function apiRequest(endpoint, options = {}) {
33
69
  catch {
34
70
  data = {};
35
71
  }
72
+ // Vercel's own answer (dev.mono's sign-in) never reached Orthogonal: no key helps.
73
+ const protectedBy = (0, http_js_1.vercelProtectionMessage)(url, res, data);
74
+ if (protectedBy) {
75
+ throw Object.assign(new Error(protectedBy), { status: res.status });
76
+ }
36
77
  if (!res.ok || data.success === false) {
37
78
  // Include more details in error message
38
79
  let errorMsg = data.error || `API request failed with status ${res.status}`;
39
- // Add any additional error details from the response
40
- if (data.message) {
41
- errorMsg += `: ${data.message}`;
80
+ const message = data.message;
81
+ // Mono's routes answer { error: <the status's name>, message }: the
82
+ // message alone says what happened ("Bad Request: …" says nothing more).
83
+ if (typeof message === "string" && message && Object.values(node_http_1.STATUS_CODES).includes(data.error)) {
84
+ errorMsg = message;
85
+ }
86
+ else if (message) {
87
+ errorMsg += `: ${message}`;
88
+ }
89
+ else if (!data.error && res.status >= 500) {
90
+ errorMsg = `Orthogonal had a problem (status ${res.status}). Try again in a moment.`;
91
+ }
92
+ if (res.status === 401) {
93
+ errorMsg = process.env.ORTHOGONAL_API_KEY
94
+ ? `Authentication needed: the key comes from ORTHOGONAL_API_KEY in this shell, and it was refused. Run \`unset ORTHOGONAL_API_KEY\` and sign in with: ${(0, utils_js_1.cliName)()} login, or set it to a valid key.`
95
+ : `Authentication needed: you're not signed in, or your key was revoked. Sign in with: ${(0, utils_js_1.cliName)()} login`;
42
96
  }
43
97
  if (data.data?.error) {
44
98
  errorMsg += ` - ${data.data.error}`;
@@ -112,6 +166,7 @@ async function run(api, path, options = {}) {
112
166
  query: options.query,
113
167
  body: options.body,
114
168
  dryRun: options.dryRun,
169
+ searchId: options.searchId,
115
170
  },
116
171
  });
117
172
  }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Wraps an async action callback so that rejected promises are caught,
3
+ * logged, and set the process exit code to 1. Without this,
4
+ * Commander.js silently swallows unhandled rejections from async actions.
5
+ * Times the action and sends its telemetry event when it ends.
6
+ */
7
+ export declare function asyncAction(fn: (...args: any[]) => Promise<void>): (...args: any[]) => void;
8
+ export declare function runTrackedSearch<T>(command: string, query: string, operation: () => Promise<T>): Promise<void>;
9
+ /** The --org option of the commands that act for a selling organization. */
10
+ export declare const orgOption: readonly ["--org <name>", "Organization (a name, part of one, or an id); default: the one `org use` chose"];
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.orgOption = void 0;
4
+ exports.asyncAction = asyncAction;
5
+ exports.runTrackedSearch = runTrackedSearch;
6
+ const analytics_js_1 = require("./analytics.js");
7
+ const utils_js_1 = require("./utils.js");
8
+ /**
9
+ * Wraps an async action callback so that rejected promises are caught,
10
+ * logged, and set the process exit code to 1. Without this,
11
+ * Commander.js silently swallows unhandled rejections from async actions.
12
+ * Times the action and sends its telemetry event when it ends.
13
+ */
14
+ function asyncAction(fn) {
15
+ return (...args) => {
16
+ (0, analytics_js_1.beginCommand)();
17
+ fn(...args)
18
+ .catch((err) => {
19
+ (0, utils_js_1.printError)(err);
20
+ // Avoid a hard exit so the command's telemetry event can flush.
21
+ process.exitCode = 1;
22
+ })
23
+ .then(() => (0, analytics_js_1.finishCommand)(Number(process.exitCode ?? 0)));
24
+ };
25
+ }
26
+ async function runTrackedSearch(command, query, operation) {
27
+ // Remembered up front so a process.exit mid-search still reports it.
28
+ (0, analytics_js_1.trackEvent)(command, { query });
29
+ try {
30
+ const response = await operation();
31
+ (0, analytics_js_1.trackEvent)(command, { query }, response);
32
+ }
33
+ catch (error) {
34
+ (0, analytics_js_1.trackEvent)(command, { query }, (0, analytics_js_1.getSearchFailureResponse)(error));
35
+ throw error;
36
+ }
37
+ }
38
+ /** The --org option of the commands that act for a selling organization. */
39
+ exports.orgOption = [
40
+ "--org <name>",
41
+ "Organization (a name, part of one, or an id); default: the one `org use` chose",
42
+ ];
@@ -1,5 +1,13 @@
1
- export declare function balanceCommand(): Promise<void>;
1
+ /**
2
+ * orth balance - The credits of whoever the key bills: your account for a
3
+ * personal key, the organization's shared credits for an organization key
4
+ */
5
+ export declare function balanceCommand(options?: {
6
+ json?: boolean;
7
+ }): Promise<void>;
2
8
  export declare function usageCommand(options: {
3
9
  limit: string;
4
10
  days?: string;
11
+ offset?: string;
12
+ json?: boolean;
5
13
  }): Promise<void>;
@@ -8,18 +8,29 @@ exports.usageCommand = usageCommand;
8
8
  const chalk_1 = __importDefault(require("chalk"));
9
9
  const ora_1 = __importDefault(require("ora"));
10
10
  const api_js_1 = require("../api.js");
11
- async function balanceCommand() {
12
- const spinner = (0, ora_1.default)("Fetching balance...").start();
11
+ const urls_js_1 = require("../urls.js");
12
+ const utils_js_1 = require("../utils.js");
13
+ /**
14
+ * orth balance - The credits of whoever the key bills: your account for a
15
+ * personal key, the organization's shared credits for an organization key
16
+ */
17
+ async function balanceCommand(options = {}) {
18
+ const spinner = options.json ? null : (0, ora_1.default)("Fetching balance...").start();
13
19
  try {
14
20
  const data = await (0, api_js_1.apiRequest)("/credits/balance");
15
- spinner.stop();
21
+ spinner?.stop();
22
+ if (options.json) {
23
+ console.log(JSON.stringify(data, null, 2));
24
+ return;
25
+ }
16
26
  console.log(`\n ${chalk_1.default.green.bold(data.balance)}\n`);
27
+ console.log(chalk_1.default.gray(" Add credits: ") + chalk_1.default.cyan(`${(0, urls_js_1.webBaseUrl)()}/account/add-funds`) + "\n");
17
28
  }
18
29
  catch (error) {
19
- spinner.stop();
30
+ spinner?.stop();
20
31
  const message = error instanceof Error ? error.message : String(error);
21
32
  if (message.includes("401") || message.includes("Authentication")) {
22
- console.error(chalk_1.default.red("\n Authentication failed. Check your API key with: orth login\n"));
33
+ console.error(chalk_1.default.red(`\n Authentication failed. Check your API key with: ${(0, utils_js_1.cliName)()} login\n`));
23
34
  }
24
35
  else {
25
36
  console.error(chalk_1.default.red(`\n Failed to fetch balance: ${message}\n`));
@@ -28,12 +39,17 @@ async function balanceCommand() {
28
39
  }
29
40
  }
30
41
  async function usageCommand(options) {
31
- const spinner = (0, ora_1.default)("Fetching usage...").start();
42
+ const spinner = options.json ? null : (0, ora_1.default)("Fetching usage...").start();
32
43
  try {
33
44
  const limit = parseInt(options.limit) || 20;
34
45
  const days = parseInt(options.days || "30") || 30;
35
- const data = await (0, api_js_1.apiRequest)(`/credits/usage?limit=${limit}&days=${days}`);
36
- spinner.stop();
46
+ const offset = Math.max(parseInt(options.offset || "0") || 0, 0);
47
+ const data = await (0, api_js_1.apiRequest)(`/credits/usage?limit=${limit}&days=${days}${offset ? `&offset=${offset}` : ""}`);
48
+ spinner?.stop();
49
+ if (options.json) {
50
+ console.log(JSON.stringify(data, null, 2));
51
+ return;
52
+ }
37
53
  if (!data?.usage || data.usage.length === 0) {
38
54
  console.log(chalk_1.default.gray("\n No API usage in the last " + days + " days.\n"));
39
55
  return;
@@ -74,10 +90,10 @@ async function usageCommand(options) {
74
90
  console.log();
75
91
  }
76
92
  catch (error) {
77
- spinner.stop();
93
+ spinner?.stop();
78
94
  const message = error instanceof Error ? error.message : String(error);
79
95
  if (message.includes("401") || message.includes("Authentication")) {
80
- console.error(chalk_1.default.red("\n Authentication failed. Check your API key with: orth login\n"));
96
+ console.error(chalk_1.default.red(`\n Authentication failed. Check your API key with: ${(0, utils_js_1.cliName)()} login\n`));
81
97
  }
82
98
  else {
83
99
  console.error(chalk_1.default.red(`\n Failed to fetch usage: ${message}\n`));