pindrop 0.0.0-stage → 0.1.1

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/lib/auth.mjs ADDED
@@ -0,0 +1,520 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import {
4
+ chmodSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ renameSync,
9
+ unlinkSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import { createServer } from "node:http";
13
+ import { homedir, platform } from "node:os";
14
+ import { dirname, join } from "node:path";
15
+
16
+ export const DEFAULT_MCP_URL = "https://mcp.pindrop.page";
17
+ const EXPIRY_BUFFER_MS = 60_000;
18
+ const LOGIN_TIMEOUT_MS = 180_000;
19
+ const FETCH_RETRY_DELAY_MS = 400;
20
+
21
+ export async function fetchWithRetry(url, init, fetchImpl = fetch) {
22
+ let lastErr;
23
+ for (let attempt = 0; attempt < 2; attempt += 1) {
24
+ try {
25
+ return await fetchImpl(url, init);
26
+ } catch (err) {
27
+ lastErr = err;
28
+ if (attempt === 0) {
29
+ await new Promise((r) => setTimeout(r, FETCH_RETRY_DELAY_MS));
30
+ }
31
+ }
32
+ }
33
+ const cause = lastErr?.cause?.message || lastErr?.cause?.code || "";
34
+ const msg = lastErr?.message || "Network request failed";
35
+ throw new Error(cause ? `${msg} (${cause})` : msg, { cause: lastErr });
36
+ }
37
+
38
+ export function resolveMcpUrl(override) {
39
+ const raw =
40
+ override ||
41
+ process.env.PINDROP_MCP_URL ||
42
+ process.env.PINDROP_API_URL ||
43
+ DEFAULT_MCP_URL;
44
+ return raw.trim().replace(/\/+$/, "").replace(/\/api\/v1$/, "");
45
+ }
46
+
47
+ export function authFilePath() {
48
+ const dir = process.env.PINDROP_CONFIG_DIR || join(homedir(), ".pindrop");
49
+ return join(dir, "auth.json");
50
+ }
51
+
52
+ function readAuthStore() {
53
+ const file = authFilePath();
54
+ if (!existsSync(file)) return { profiles: {} };
55
+ try {
56
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
57
+ if (parsed && typeof parsed === "object" && parsed.profiles && typeof parsed.profiles === "object") {
58
+ return parsed;
59
+ }
60
+ return { profiles: {} };
61
+ } catch {
62
+ return { profiles: {} };
63
+ }
64
+ }
65
+
66
+ function writeAuthStore(store) {
67
+ const file = authFilePath();
68
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
69
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
70
+ try {
71
+ writeFileSync(tmp, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
72
+ try {
73
+ chmodSync(tmp, 0o600);
74
+ } catch {
75
+ // Ignore on filesystems without POSIX mode bits.
76
+ }
77
+ renameSync(tmp, file);
78
+ } catch (err) {
79
+ try {
80
+ if (existsSync(tmp)) unlinkSync(tmp);
81
+ } catch {
82
+ // Ignore cleanup errors.
83
+ }
84
+ throw err;
85
+ }
86
+ }
87
+
88
+ export function getSavedProfile(mcpUrl) {
89
+ const store = readAuthStore();
90
+ return store.profiles[mcpUrl] ?? null;
91
+ }
92
+
93
+ export function saveProfile(mcpUrl, profile) {
94
+ const store = readAuthStore();
95
+ store.profiles[mcpUrl] = profile;
96
+ writeAuthStore(store);
97
+ }
98
+
99
+ export function clearProfile(mcpUrl) {
100
+ const store = readAuthStore();
101
+ const existed = Boolean(store.profiles[mcpUrl]);
102
+ delete store.profiles[mcpUrl];
103
+ writeAuthStore(store);
104
+ return existed;
105
+ }
106
+
107
+ export function openInBrowser(url) {
108
+ const os = platform();
109
+ let cmd;
110
+ let args;
111
+ if (os === "darwin") {
112
+ cmd = "open";
113
+ args = [url];
114
+ } else if (os === "win32") {
115
+ cmd = "cmd";
116
+ args = ["/c", "start", "", url];
117
+ } else {
118
+ cmd = "xdg-open";
119
+ args = [url];
120
+ }
121
+ try {
122
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
123
+ child.on("error", () => {});
124
+ child.unref();
125
+ return true;
126
+ } catch {
127
+ return false;
128
+ }
129
+ }
130
+
131
+ export async function discoverOAuth(mcpUrl, fetchImpl = fetch) {
132
+ const parsed = new URL(mcpUrl);
133
+ const resourceMetadataUrl = `${parsed.origin}/.well-known/oauth-protected-resource${
134
+ parsed.pathname === "/mcp" ? "/mcp" : ""
135
+ }`;
136
+ const resMetaResp = await fetchWithRetry(
137
+ resourceMetadataUrl,
138
+ { headers: { Accept: "application/json" } },
139
+ fetchImpl,
140
+ );
141
+ if (!resMetaResp.ok) {
142
+ throw new Error(
143
+ `OAuth resource discovery failed (${resMetaResp.status}) at ${resourceMetadataUrl}`,
144
+ );
145
+ }
146
+ const resourceMeta = await resMetaResp.json();
147
+ const issuerHref = resourceMeta.authorization_servers?.[0];
148
+ if (!issuerHref) {
149
+ throw new Error("OAuth discovery did not advertise an authorization server.");
150
+ }
151
+ const issuer = new URL(issuerHref);
152
+ const issuerPath = issuer.pathname.replace(/\/+$/, "");
153
+ const authServerUrl = `${issuer.origin}/.well-known/oauth-authorization-server${issuerPath}`;
154
+ const authServerResp = await fetchWithRetry(
155
+ authServerUrl,
156
+ { headers: { Accept: "application/json" } },
157
+ fetchImpl,
158
+ );
159
+ if (!authServerResp.ok) {
160
+ throw new Error(
161
+ `OAuth server discovery failed (${authServerResp.status}) at ${authServerUrl}`,
162
+ );
163
+ }
164
+ const serverMeta = await authServerResp.json();
165
+ if (!serverMeta.authorization_endpoint || !serverMeta.token_endpoint) {
166
+ throw new Error("OAuth server metadata is missing authorization or token endpoints.");
167
+ }
168
+ return {
169
+ resource: resourceMeta.resource || mcpUrl,
170
+ scopes: Array.isArray(resourceMeta.scopes_supported) && resourceMeta.scopes_supported.length > 0
171
+ ? resourceMeta.scopes_supported.join(" ")
172
+ : "pindrop offline_access",
173
+ authorizationEndpoint: serverMeta.authorization_endpoint,
174
+ tokenEndpoint: serverMeta.token_endpoint,
175
+ registrationEndpoint: serverMeta.registration_endpoint,
176
+ revocationEndpoint: serverMeta.revocation_endpoint,
177
+ };
178
+ }
179
+
180
+ function callbackHtml(title, body, ok) {
181
+ const accent = ok ? "#1f9d55" : "#c8361a";
182
+ return `<!doctype html>
183
+ <html lang="en">
184
+ <head>
185
+ <meta charset="utf-8" />
186
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
187
+ <title>${title}</title>
188
+ <style>
189
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f5f1eb; color: #1d1a17; font: 15px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
190
+ .card { max-width: 420px; padding: 28px 30px; border-radius: 18px; background: #fff; box-shadow: 0 18px 40px -24px rgba(30,20,20,.35), 0 0 0 1px rgba(60,40,30,.08); }
191
+ .dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: ${accent}; margin-right: 8px; vertical-align: middle; }
192
+ h1 { margin: 0 0 8px; font-size: 18px; font-weight: 600; }
193
+ p { margin: 0; color: #5b554d; }
194
+ </style>
195
+ </head>
196
+ <body>
197
+ <div class="card">
198
+ <h1><span class="dot"></span>${title}</h1>
199
+ <p>${body}</p>
200
+ </div>
201
+ </body>
202
+ </html>`;
203
+ }
204
+
205
+ function startCallbackServer(expectedState, timeoutMs = LOGIN_TIMEOUT_MS) {
206
+ return new Promise((resolveStart, rejectStart) => {
207
+ let settled = false;
208
+ let resolveCode;
209
+ let rejectCode;
210
+ const waitForCode = new Promise((res, rej) => {
211
+ resolveCode = res;
212
+ rejectCode = rej;
213
+ });
214
+
215
+ const server = createServer((req, res) => {
216
+ const url = new URL(req.url || "/", "http://127.0.0.1");
217
+ if (url.pathname !== "/callback") {
218
+ res.writeHead(404, { "Content-Type": "text/plain" });
219
+ res.end("Not found");
220
+ return;
221
+ }
222
+ const error = url.searchParams.get("error");
223
+ const errorDesc = url.searchParams.get("error_description");
224
+ const state = url.searchParams.get("state");
225
+ const code = url.searchParams.get("code");
226
+
227
+ if (error) {
228
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
229
+ res.end(
230
+ callbackHtml(
231
+ "PinDrop sign-in cancelled",
232
+ errorDesc || error || "Authorization was denied.",
233
+ false,
234
+ ),
235
+ );
236
+ if (!settled) {
237
+ settled = true;
238
+ clearTimeout(timer);
239
+ server.close();
240
+ rejectCode(new Error(errorDesc || `OAuth error: ${error}`));
241
+ }
242
+ return;
243
+ }
244
+
245
+ if (!code || state !== expectedState) {
246
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
247
+ res.end(
248
+ callbackHtml(
249
+ "Invalid OAuth callback",
250
+ "State mismatch or missing authorization code. Try running pindrop login again.",
251
+ false,
252
+ ),
253
+ );
254
+ return;
255
+ }
256
+
257
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
258
+ res.end(
259
+ callbackHtml(
260
+ "PinDrop CLI connected",
261
+ "You can close this tab and return to your terminal or coding agent.",
262
+ true,
263
+ ),
264
+ );
265
+ if (!settled) {
266
+ settled = true;
267
+ clearTimeout(timer);
268
+ server.close();
269
+ resolveCode(code);
270
+ }
271
+ });
272
+
273
+ const timer = setTimeout(() => {
274
+ if (!settled) {
275
+ settled = true;
276
+ server.close();
277
+ rejectCode(new Error("Timed out waiting for browser sign-in (3 minutes)."));
278
+ }
279
+ }, timeoutMs);
280
+ timer.unref?.();
281
+
282
+ server.on("error", (err) => {
283
+ clearTimeout(timer);
284
+ if (!settled) {
285
+ settled = true;
286
+ rejectStart(err);
287
+ rejectCode(err);
288
+ }
289
+ });
290
+
291
+ server.listen(0, "127.0.0.1", () => {
292
+ const addr = server.address();
293
+ if (!addr || typeof addr === "string") {
294
+ clearTimeout(timer);
295
+ server.close();
296
+ rejectStart(new Error("Could not bind local OAuth callback port."));
297
+ return;
298
+ }
299
+ resolveStart({
300
+ redirectUri: `http://127.0.0.1:${addr.port}/callback`,
301
+ waitForCode,
302
+ close() {
303
+ clearTimeout(timer);
304
+ server.close();
305
+ },
306
+ });
307
+ });
308
+ });
309
+ }
310
+
311
+ export async function loginWithBrowser({
312
+ mcpUrl,
313
+ openBrowser = true,
314
+ timeoutMs = LOGIN_TIMEOUT_MS,
315
+ onAuthorizeUrl,
316
+ fetchImpl = fetch,
317
+ }) {
318
+ const meta = await discoverOAuth(mcpUrl, fetchImpl);
319
+ if (!meta.registrationEndpoint) {
320
+ throw new Error("OAuth server does not support dynamic client registration.");
321
+ }
322
+
323
+ const state = randomBytes(16).toString("hex");
324
+ const verifier = randomBytes(32).toString("base64url");
325
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
326
+
327
+ const callback = await startCallbackServer(state, timeoutMs);
328
+ try {
329
+ const regResp = await fetchWithRetry(
330
+ meta.registrationEndpoint,
331
+ {
332
+ method: "POST",
333
+ headers: { "Content-Type": "application/json" },
334
+ body: JSON.stringify({
335
+ client_name: "PinDrop CLI",
336
+ redirect_uris: [callback.redirectUri],
337
+ token_endpoint_auth_method: "none",
338
+ grant_types: ["authorization_code", "refresh_token"],
339
+ response_types: ["code"],
340
+ }),
341
+ },
342
+ fetchImpl,
343
+ );
344
+ const regData = await regResp.json().catch(() => ({}));
345
+ if (!regResp.ok || !regData.client_id) {
346
+ throw new Error(
347
+ regData.error_description ||
348
+ regData.error ||
349
+ `OAuth client registration failed (${regResp.status}).`,
350
+ );
351
+ }
352
+
353
+ const params = new URLSearchParams({
354
+ client_id: regData.client_id,
355
+ redirect_uri: callback.redirectUri,
356
+ response_type: "code",
357
+ scope: meta.scopes,
358
+ state,
359
+ code_challenge: challenge,
360
+ code_challenge_method: "S256",
361
+ resource: meta.resource,
362
+ });
363
+ const authUrl = `${meta.authorizationEndpoint}?${params.toString()}`;
364
+ onAuthorizeUrl?.(authUrl);
365
+ if (openBrowser) {
366
+ openInBrowser(authUrl);
367
+ }
368
+
369
+ const code = await callback.waitForCode;
370
+ const tokenResp = await fetchWithRetry(
371
+ meta.tokenEndpoint,
372
+ {
373
+ method: "POST",
374
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
375
+ body: new URLSearchParams({
376
+ grant_type: "authorization_code",
377
+ client_id: regData.client_id,
378
+ code,
379
+ code_verifier: verifier,
380
+ redirect_uri: callback.redirectUri,
381
+ resource: meta.resource,
382
+ }),
383
+ },
384
+ fetchImpl,
385
+ );
386
+ const tokenData = await tokenResp.json().catch(() => ({}));
387
+ if (!tokenResp.ok || !tokenData.access_token) {
388
+ throw new Error(
389
+ tokenData.error_description ||
390
+ tokenData.error ||
391
+ `OAuth token exchange failed (${tokenResp.status}).`,
392
+ );
393
+ }
394
+
395
+ const expiresIn = Number(tokenData.expires_in) || 3600;
396
+ const profile = {
397
+ type: "oauth",
398
+ mcpUrl,
399
+ resource: meta.resource,
400
+ tokenEndpoint: meta.tokenEndpoint,
401
+ revocationEndpoint: meta.revocationEndpoint || null,
402
+ clientId: regData.client_id,
403
+ accessToken: tokenData.access_token,
404
+ refreshToken: tokenData.refresh_token || null,
405
+ expiresAt: Date.now() + expiresIn * 1000,
406
+ updatedAt: Date.now(),
407
+ };
408
+ saveProfile(mcpUrl, profile);
409
+ return profile;
410
+ } finally {
411
+ callback.close();
412
+ }
413
+ }
414
+
415
+ export async function refreshSavedToken(mcpUrl, profile, fetchImpl = fetch) {
416
+ if (!profile || profile.type !== "oauth" || !profile.refreshToken || !profile.tokenEndpoint) {
417
+ return null;
418
+ }
419
+ const resp = await fetchImpl(profile.tokenEndpoint, {
420
+ method: "POST",
421
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
422
+ body: new URLSearchParams({
423
+ grant_type: "refresh_token",
424
+ client_id: profile.clientId,
425
+ refresh_token: profile.refreshToken,
426
+ resource: profile.resource || mcpUrl,
427
+ }),
428
+ });
429
+ const data = await resp.json().catch(() => ({}));
430
+ if (!resp.ok || !data.access_token) {
431
+ return null;
432
+ }
433
+ const expiresIn = Number(data.expires_in) || 3600;
434
+ const updated = {
435
+ ...profile,
436
+ accessToken: data.access_token,
437
+ refreshToken: data.refresh_token || profile.refreshToken,
438
+ expiresAt: Date.now() + expiresIn * 1000,
439
+ updatedAt: Date.now(),
440
+ };
441
+ saveProfile(mcpUrl, updated);
442
+ return updated;
443
+ }
444
+
445
+ export function saveApiKeyProfile(mcpUrl, apiKey) {
446
+ const profile = {
447
+ type: "api_key",
448
+ mcpUrl,
449
+ apiKey: apiKey.trim(),
450
+ updatedAt: Date.now(),
451
+ };
452
+ saveProfile(mcpUrl, profile);
453
+ return profile;
454
+ }
455
+
456
+ export async function revokeAndLogout(mcpUrl, fetchImpl = fetch) {
457
+ const profile = getSavedProfile(mcpUrl);
458
+ if (
459
+ profile?.type === "oauth" &&
460
+ profile.revocationEndpoint &&
461
+ profile.clientId &&
462
+ (profile.refreshToken || profile.accessToken)
463
+ ) {
464
+ try {
465
+ await fetchImpl(profile.revocationEndpoint, {
466
+ method: "POST",
467
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
468
+ body: new URLSearchParams({
469
+ client_id: profile.clientId,
470
+ token: profile.refreshToken || profile.accessToken,
471
+ }),
472
+ });
473
+ } catch {
474
+ // Best-effort server revocation; always clear local credentials.
475
+ }
476
+ }
477
+ return clearProfile(mcpUrl);
478
+ }
479
+
480
+ export async function resolveBearerToken({
481
+ mcpUrl,
482
+ autoLogin = false,
483
+ openBrowser = true,
484
+ onAuthorizeUrl,
485
+ fetchImpl = fetch,
486
+ }) {
487
+ const envKey = process.env.PINDROP_API_KEY?.trim();
488
+ if (envKey) {
489
+ return { token: envKey, source: "env", profile: null };
490
+ }
491
+
492
+ const saved = getSavedProfile(mcpUrl);
493
+ if (saved?.type === "api_key" && saved.apiKey) {
494
+ return { token: saved.apiKey, source: "api_key", profile: saved };
495
+ }
496
+
497
+ if (saved?.type === "oauth" && saved.accessToken) {
498
+ const expired =
499
+ typeof saved.expiresAt === "number" && Date.now() + EXPIRY_BUFFER_MS >= saved.expiresAt;
500
+ if (!expired) {
501
+ return { token: saved.accessToken, source: "oauth", profile: saved };
502
+ }
503
+ const refreshed = await refreshSavedToken(mcpUrl, saved, fetchImpl);
504
+ if (refreshed?.accessToken) {
505
+ return { token: refreshed.accessToken, source: "oauth", profile: refreshed };
506
+ }
507
+ }
508
+
509
+ if (autoLogin) {
510
+ const loggedIn = await loginWithBrowser({
511
+ mcpUrl,
512
+ openBrowser,
513
+ onAuthorizeUrl,
514
+ fetchImpl,
515
+ });
516
+ return { token: loggedIn.accessToken, source: "oauth", profile: loggedIn };
517
+ }
518
+
519
+ return null;
520
+ }
package/lib/client.mjs ADDED
@@ -0,0 +1,141 @@
1
+ import {
2
+ fetchWithRetry,
3
+ refreshSavedToken,
4
+ resolveBearerToken,
5
+ } from "./auth.mjs";
6
+
7
+ export class CliError extends Error {
8
+ constructor(message, exitCode = 1) {
9
+ super(message);
10
+ this.exitCode = exitCode;
11
+ }
12
+ }
13
+
14
+ async function postMcp(mcpUrl, token, toolName, args, fetchImpl = fetch) {
15
+ const response = await fetchWithRetry(
16
+ mcpUrl,
17
+ {
18
+ method: "POST",
19
+ headers: {
20
+ "Content-Type": "application/json",
21
+ Accept: "application/json, text/event-stream",
22
+ Authorization: `Bearer ${token}`,
23
+ "User-Agent": "pindrop-cli/0.1.1",
24
+ },
25
+ body: JSON.stringify({
26
+ jsonrpc: "2.0",
27
+ id: 1,
28
+ method: "tools/call",
29
+ params: {
30
+ name: toolName,
31
+ arguments: args ?? {},
32
+ },
33
+ }),
34
+ },
35
+ fetchImpl,
36
+ );
37
+ const text = await response.text();
38
+ let payload = null;
39
+ try {
40
+ payload = JSON.parse(text);
41
+ } catch {
42
+ payload = null;
43
+ }
44
+ return { status: response.status, payload, rawText: text };
45
+ }
46
+
47
+ function classifyToolFailure(message) {
48
+ if (/not found|unknown pin|no project|does not exist/i.test(message)) return 3;
49
+ if (/unauthorized|expired|disconnected|connect your pindrop account/i.test(message)) return 2;
50
+ return 1;
51
+ }
52
+
53
+ export async function callPinDropTool({
54
+ mcpUrl,
55
+ toolName,
56
+ args = {},
57
+ autoLogin = false,
58
+ openBrowser = true,
59
+ onAuthorizeUrl,
60
+ fetchImpl = fetch,
61
+ }) {
62
+ const auth = await resolveBearerToken({
63
+ mcpUrl,
64
+ autoLogin,
65
+ openBrowser,
66
+ onAuthorizeUrl,
67
+ fetchImpl,
68
+ });
69
+ if (!auth) {
70
+ throw new CliError(
71
+ "Not signed in to PinDrop. Run `pindrop login` (or set PINDROP_API_KEY).",
72
+ 2,
73
+ );
74
+ }
75
+
76
+ let res = await postMcp(mcpUrl, auth.token, toolName, args, fetchImpl);
77
+
78
+ if (res.status === 401 && auth.source === "oauth" && auth.profile) {
79
+ const refreshed = await refreshSavedToken(mcpUrl, auth.profile, fetchImpl);
80
+ if (refreshed?.accessToken) {
81
+ res = await postMcp(mcpUrl, refreshed.accessToken, toolName, args, fetchImpl);
82
+ }
83
+ }
84
+
85
+ if (res.status === 401) {
86
+ if (autoLogin && auth.source !== "env") {
87
+ const fresh = await resolveBearerToken({
88
+ mcpUrl,
89
+ autoLogin: true,
90
+ openBrowser,
91
+ onAuthorizeUrl,
92
+ fetchImpl,
93
+ });
94
+ if (fresh?.token && fresh.token !== auth.token) {
95
+ res = await postMcp(mcpUrl, fresh.token, toolName, args, fetchImpl);
96
+ }
97
+ }
98
+ }
99
+
100
+ if (res.status === 401) {
101
+ throw new CliError(
102
+ "PinDrop session expired or disconnected. Run `pindrop login` to reconnect.",
103
+ 2,
104
+ );
105
+ }
106
+
107
+ if (res.status >= 400) {
108
+ const msg =
109
+ res.payload?.error?.message ||
110
+ res.payload?.error ||
111
+ `PinDrop request failed (${res.status}).`;
112
+ throw new CliError(String(msg), res.status === 404 ? 3 : 1);
113
+ }
114
+
115
+ if (res.payload?.error) {
116
+ const msg = res.payload.error.message || "PinDrop tool error.";
117
+ throw new CliError(msg, classifyToolFailure(msg));
118
+ }
119
+
120
+ const result = res.payload?.result;
121
+ if (!result || typeof result !== "object") {
122
+ throw new CliError("Unexpected response from PinDrop server.", 1);
123
+ }
124
+
125
+ const textBlocks = Array.isArray(result.content)
126
+ ? result.content
127
+ .filter((item) => item && item.type === "text" && typeof item.text === "string")
128
+ .map((item) => item.text)
129
+ : [];
130
+
131
+ if (result.isError) {
132
+ const msg = textBlocks.join("\n").trim() || "PinDrop returned an error.";
133
+ throw new CliError(msg, classifyToolFailure(msg));
134
+ }
135
+
136
+ return {
137
+ structured: result.structuredContent ?? null,
138
+ text: textBlocks.join("\n").trim(),
139
+ content: Array.isArray(result.content) ? result.content : [],
140
+ };
141
+ }