@portlesslabs/sdk 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,826 @@
1
+ // src/env.ts
2
+ function readEnv(name) {
3
+ const g = globalThis;
4
+ let value;
5
+ try {
6
+ value = g.process?.env?.[name];
7
+ if (value === void 0 && typeof g.Deno?.env?.get === "function") {
8
+ value = g.Deno.env.get(name);
9
+ }
10
+ } catch {
11
+ return void 0;
12
+ }
13
+ if (typeof value !== "string") return void 0;
14
+ const trimmed = value.trim();
15
+ return trimmed === "" ? void 0 : trimmed;
16
+ }
17
+
18
+ // src/errors.ts
19
+ var PortlessError = class extends Error {
20
+ name = "PortlessError";
21
+ /** HTTP status, when the error came from a gateway response. */
22
+ status;
23
+ /** Machine-readable error code (the gateway's `error.code`, or an SDK code for local errors). */
24
+ code;
25
+ /** Gateway request id, useful when contacting support. */
26
+ requestId;
27
+ constructor(message, options) {
28
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
29
+ this.code = options.code;
30
+ this.status = options.status;
31
+ this.requestId = options.requestId;
32
+ }
33
+ /** A JSON-safe summary (no stack, no cause). */
34
+ toJSON() {
35
+ return {
36
+ name: this.name,
37
+ message: this.message,
38
+ code: this.code,
39
+ ...this.status === void 0 ? {} : { status: this.status },
40
+ ...this.requestId === void 0 ? {} : { requestId: this.requestId }
41
+ };
42
+ }
43
+ };
44
+ var AuthenticationError = class extends PortlessError {
45
+ name = "AuthenticationError";
46
+ };
47
+ var PermissionError = class extends PortlessError {
48
+ name = "PermissionError";
49
+ };
50
+ var NotFoundError = class extends PortlessError {
51
+ name = "NotFoundError";
52
+ };
53
+ var ValidationError = class extends PortlessError {
54
+ name = "ValidationError";
55
+ };
56
+ var UpstreamError = class extends PortlessError {
57
+ name = "UpstreamError";
58
+ };
59
+ var ServerError = class extends PortlessError {
60
+ name = "ServerError";
61
+ };
62
+ var ConnectionError = class extends PortlessError {
63
+ name = "ConnectionError";
64
+ };
65
+ var TimeoutError = class extends PortlessError {
66
+ name = "TimeoutError";
67
+ };
68
+ var ToolExecutionError = class extends PortlessError {
69
+ name = "ToolExecutionError";
70
+ /** The full call, including `result` and `text`. */
71
+ toolCall;
72
+ constructor(message, options) {
73
+ super(message, options);
74
+ this.toolCall = options.toolCall;
75
+ }
76
+ };
77
+ var CLASS_BY_CODE = {
78
+ invalid_json: ValidationError,
79
+ invalid_request: ValidationError,
80
+ method_not_allowed: ValidationError,
81
+ invalid_endpoint: ValidationError,
82
+ endpoint_not_allowed: ValidationError,
83
+ missing_api_key: AuthenticationError,
84
+ invalid_api_key: AuthenticationError,
85
+ tool_disabled: PermissionError,
86
+ tool_not_found: NotFoundError,
87
+ server_not_found: NotFoundError,
88
+ credentials_unavailable: ServerError,
89
+ internal_error: ServerError,
90
+ transport_not_supported: UpstreamError,
91
+ upstream_error: UpstreamError,
92
+ upstream_unreachable: UpstreamError
93
+ };
94
+ function errorClassFor(status, code) {
95
+ if (code !== void 0 && Object.hasOwn(CLASS_BY_CODE, code)) {
96
+ return CLASS_BY_CODE[code];
97
+ }
98
+ if (status === 401) return AuthenticationError;
99
+ if (status === 403) return PermissionError;
100
+ if (status === 404) return NotFoundError;
101
+ if (status === 400 || status === 405 || status === 422) return ValidationError;
102
+ if (status === 501 || status === 502) return UpstreamError;
103
+ if (status >= 500) return ServerError;
104
+ return PortlessError;
105
+ }
106
+ function isRecord(value) {
107
+ return typeof value === "object" && value !== null && !Array.isArray(value);
108
+ }
109
+ function parseErrorBody(body) {
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(body);
113
+ } catch {
114
+ return {};
115
+ }
116
+ if (!isRecord(parsed)) return {};
117
+ const error = parsed.error;
118
+ if (isRecord(error)) {
119
+ return {
120
+ ...typeof error.code === "string" && error.code !== "" ? { code: error.code } : {},
121
+ ...typeof error.message === "string" && error.message !== "" ? { message: error.message } : {}
122
+ };
123
+ }
124
+ if (typeof error === "string" && error !== "") return { message: error };
125
+ if (typeof parsed.message === "string" && parsed.message !== "") {
126
+ return { message: parsed.message };
127
+ }
128
+ return {};
129
+ }
130
+ function describeNonJsonBody(status, statusText, body) {
131
+ const label = statusText ? `HTTP ${status} ${statusText}` : `HTTP ${status}`;
132
+ const trimmed = body.trim();
133
+ if (trimmed === "") return `Portless gateway returned ${label} with an empty body.`;
134
+ if (!trimmed.startsWith("<") && trimmed.length <= 200) {
135
+ return `Portless gateway returned ${label}: ${trimmed}`;
136
+ }
137
+ return `Portless gateway returned ${label} with a non-JSON body (likely from a proxy or load balancer).`;
138
+ }
139
+ function fromResponse(info) {
140
+ const { code, message } = parseErrorBody(info.body);
141
+ const requestId = info.headers.get("x-request-id") ?? info.headers.get("x-vercel-id") ?? void 0;
142
+ const text = message ?? describeNonJsonBody(info.status, info.statusText, info.body);
143
+ const ErrorCtor = errorClassFor(info.status, code);
144
+ return new ErrorCtor(info.redact(text), {
145
+ status: info.status,
146
+ code: code ?? `http_${info.status}`,
147
+ requestId
148
+ });
149
+ }
150
+
151
+ // src/retry.ts
152
+ var RETRY_BASE_MS = 300;
153
+ var RETRY_CAP_MS = 4e3;
154
+ var RETRY_AFTER_MAX_MS = 6e4;
155
+ function isRetryableStatus(status) {
156
+ return status === 502 || status === 503 || status === 504;
157
+ }
158
+ function backoffDelay(attempt, random = Math.random) {
159
+ const ceiling = Math.min(RETRY_CAP_MS, RETRY_BASE_MS * 2 ** Math.max(0, attempt));
160
+ return Math.floor(random() * ceiling);
161
+ }
162
+ function parseRetryAfter(value, now = Date.now()) {
163
+ if (value === null || value === void 0) return void 0;
164
+ const trimmed = value.trim();
165
+ if (trimmed === "") return void 0;
166
+ let ms;
167
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
168
+ ms = Number(trimmed) * 1e3;
169
+ } else {
170
+ const date = Date.parse(trimmed);
171
+ if (Number.isNaN(date)) return void 0;
172
+ ms = date - now;
173
+ }
174
+ return Math.min(RETRY_AFTER_MAX_MS, Math.max(0, Math.round(ms)));
175
+ }
176
+ function abortReason(signal) {
177
+ return signal.reason ?? new DOMException("This operation was aborted", "AbortError");
178
+ }
179
+ function sleep(ms, signal) {
180
+ return new Promise((resolve, reject) => {
181
+ if (signal?.aborted) {
182
+ reject(abortReason(signal));
183
+ return;
184
+ }
185
+ const onAbort = () => {
186
+ clearTimeout(timer);
187
+ reject(abortReason(signal));
188
+ };
189
+ const timer = setTimeout(() => {
190
+ signal?.removeEventListener("abort", onAbort);
191
+ resolve();
192
+ }, ms);
193
+ signal?.addEventListener("abort", onAbort, { once: true });
194
+ });
195
+ }
196
+
197
+ // src/version.ts
198
+ var VERSION = "0.1.0";
199
+
200
+ // src/http.ts
201
+ var CLIENT_ID = `portless-sdk-js/${VERSION}`;
202
+ var REDACTED_KEY = "pl_live_****";
203
+ var MAX_TIMER_MS = 2147483647;
204
+ var retryAfterMs = /* @__PURE__ */ new WeakMap();
205
+ function canSetUserAgent() {
206
+ return typeof globalThis.document === "undefined";
207
+ }
208
+ function assertHeaderValue(value, what) {
209
+ if (/[\u0000-\u001f\u007f]/.test(value)) {
210
+ throw new ValidationError(`${what} must not contain control characters or newlines.`, {
211
+ code: "invalid_option"
212
+ });
213
+ }
214
+ }
215
+ var HttpClient = class {
216
+ #config;
217
+ constructor(config) {
218
+ this.#config = config;
219
+ }
220
+ /** Performs the request, retrying when allowed, and returns the parsed JSON body. */
221
+ async request(req) {
222
+ const retry = req.retry ?? req.method === "GET";
223
+ const maxRetries = retry ? this.#config.maxRetries : 0;
224
+ for (let attempt = 0; ; attempt++) {
225
+ if (req.signal?.aborted) throw abortReason(req.signal);
226
+ try {
227
+ return await this.#attempt(req);
228
+ } catch (error) {
229
+ if (attempt >= maxRetries || !isRetryable(error)) throw error;
230
+ const delay = retryAfterMs.get(error) ?? backoffDelay(attempt);
231
+ await sleep(delay, req.signal);
232
+ }
233
+ }
234
+ }
235
+ /** Removes the API key from any text. */
236
+ redact(text) {
237
+ return text.split(this.#config.apiKey).join(REDACTED_KEY);
238
+ }
239
+ #headers(req) {
240
+ const headers = new Headers(this.#config.headers);
241
+ headers.set("Authorization", `Bearer ${this.#config.apiKey}`);
242
+ headers.set("Accept", "application/json");
243
+ headers.set("X-Portless-Client", CLIENT_ID);
244
+ if (canSetUserAgent()) headers.set("User-Agent", CLIENT_ID);
245
+ const agent = req.agent ?? this.#config.agent;
246
+ if (agent !== void 0) headers.set("X-Portless-Agent", agent);
247
+ if (req.body !== void 0) headers.set("Content-Type", "application/json");
248
+ return headers;
249
+ }
250
+ async #attempt(req) {
251
+ const url = new URL(this.#config.baseUrl + req.path);
252
+ for (const [key, value] of Object.entries(req.query ?? {})) url.searchParams.set(key, value);
253
+ const timeoutMs = Math.min(req.timeoutMs ?? this.#config.timeoutMs, MAX_TIMER_MS);
254
+ const controller = new AbortController();
255
+ let timedOut = false;
256
+ const timer = setTimeout(() => {
257
+ timedOut = true;
258
+ controller.abort();
259
+ }, timeoutMs);
260
+ const userSignal = req.signal;
261
+ const onUserAbort = () => controller.abort(userSignal?.reason);
262
+ userSignal?.addEventListener("abort", onUserAbort, { once: true });
263
+ const fail = (error) => {
264
+ if (userSignal?.aborted) return abortReason(userSignal);
265
+ if (timedOut) {
266
+ return new TimeoutError(
267
+ `Request to ${req.method} ${req.path} timed out after ${timeoutMs}ms.`,
268
+ {
269
+ code: "timeout",
270
+ cause: error
271
+ }
272
+ );
273
+ }
274
+ const detail = error instanceof Error && error.message ? `: ${this.redact(error.message)}` : "";
275
+ return new ConnectionError(`Could not reach the Portless gateway at ${url.origin}${detail}`, {
276
+ code: "connection_error",
277
+ cause: error
278
+ });
279
+ };
280
+ try {
281
+ let response;
282
+ let body;
283
+ try {
284
+ response = await this.#config.fetch(url.toString(), {
285
+ method: req.method,
286
+ headers: this.#headers(req),
287
+ ...req.body === void 0 ? {} : { body: JSON.stringify(req.body) },
288
+ signal: controller.signal
289
+ });
290
+ body = await response.text();
291
+ } catch (error) {
292
+ throw fail(error);
293
+ }
294
+ if (!response.ok) {
295
+ const error = fromResponse({
296
+ status: response.status,
297
+ statusText: response.statusText,
298
+ body,
299
+ headers: response.headers,
300
+ redact: (text) => this.redact(text)
301
+ });
302
+ const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
303
+ if (retryAfter !== void 0) retryAfterMs.set(error, retryAfter);
304
+ throw error;
305
+ }
306
+ try {
307
+ return JSON.parse(body);
308
+ } catch (error) {
309
+ throw new ServerError(
310
+ `Portless gateway returned HTTP ${response.status} with a body that is not valid JSON.`,
311
+ {
312
+ status: response.status,
313
+ code: "invalid_response",
314
+ requestId: response.headers.get("x-request-id") ?? void 0,
315
+ cause: error
316
+ }
317
+ );
318
+ }
319
+ } finally {
320
+ clearTimeout(timer);
321
+ userSignal?.removeEventListener("abort", onUserAbort);
322
+ }
323
+ }
324
+ };
325
+ function isRetryable(error) {
326
+ if (error instanceof ConnectionError) return true;
327
+ return error instanceof PortlessError && isRetryableStatus(error.status);
328
+ }
329
+
330
+ // src/resources/shared.ts
331
+ function checkRequestOptions(options) {
332
+ if (options === void 0) return;
333
+ if (typeof options !== "object" || options === null) {
334
+ throw new ValidationError("Options must be an object.", { code: "invalid_option" });
335
+ }
336
+ if (options.timeoutMs !== void 0) checkTimeout(options.timeoutMs, "timeoutMs");
337
+ }
338
+ function checkTimeout(value, what) {
339
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
340
+ throw new ValidationError(`${what} must be a positive number of milliseconds.`, {
341
+ code: "invalid_option"
342
+ });
343
+ }
344
+ }
345
+ function checkAgent(value, what) {
346
+ if (value === void 0) return;
347
+ if (typeof value !== "string" || value.trim() === "") {
348
+ throw new ValidationError(`${what} must be a non-empty string.`, { code: "invalid_option" });
349
+ }
350
+ assertHeaderValue(value, what);
351
+ }
352
+ function expectArray(payload, key, endpoint) {
353
+ const value = isObject(payload) ? payload[key] : void 0;
354
+ if (!Array.isArray(value)) {
355
+ throw new ServerError(`Unexpected response from ${endpoint}: missing "${key}" array.`, {
356
+ code: "invalid_response",
357
+ status: 200
358
+ });
359
+ }
360
+ return value;
361
+ }
362
+ function expectObject(payload, endpoint) {
363
+ if (!isObject(payload)) {
364
+ throw new ServerError(`Unexpected response from ${endpoint}: expected a JSON object.`, {
365
+ code: "invalid_response",
366
+ status: 200
367
+ });
368
+ }
369
+ return payload;
370
+ }
371
+ function isObject(value) {
372
+ return typeof value === "object" && value !== null && !Array.isArray(value);
373
+ }
374
+
375
+ // src/resources/mcp.ts
376
+ var McpResource = class {
377
+ #apiKey;
378
+ #baseUrl;
379
+ #agent;
380
+ constructor(apiKey, baseUrl, agent) {
381
+ this.#apiKey = apiKey;
382
+ this.#baseUrl = baseUrl;
383
+ this.#agent = agent;
384
+ }
385
+ /** The Streamable HTTP MCP endpoint: `${baseUrl}/api/v1/mcp`. */
386
+ get url() {
387
+ return `${this.#baseUrl}/api/v1/mcp`;
388
+ }
389
+ /**
390
+ * Builds an `mcpServers` config block for MCP clients.
391
+ *
392
+ * **The returned object CONTAINS YOUR SECRET API KEY** in `headers.Authorization`.
393
+ * Write it only to local, git-ignored config files. Never log it, commit it,
394
+ * or send it to a browser.
395
+ */
396
+ config(options = {}) {
397
+ const name = options.name ?? "portless";
398
+ if (typeof name !== "string" || name.trim() === "") {
399
+ throw new ValidationError("name must be a non-empty string.", { code: "invalid_option" });
400
+ }
401
+ const agent = options.agent ?? this.#agent;
402
+ checkAgent(agent, "agent");
403
+ const headers = { Authorization: `Bearer ${this.#apiKey}` };
404
+ if (agent !== void 0) headers["X-Portless-Agent"] = agent;
405
+ return { mcpServers: { [name]: { url: this.url, headers } } };
406
+ }
407
+ };
408
+
409
+ // src/resources/me.ts
410
+ var MeResource = class {
411
+ #http;
412
+ constructor(http) {
413
+ this.#http = http;
414
+ }
415
+ /** Returns the workspace, key and agent the current credentials resolve to. */
416
+ async get(options) {
417
+ checkRequestOptions(options);
418
+ const payload = await this.#http.request({
419
+ method: "GET",
420
+ path: "/api/v1/me",
421
+ signal: options?.signal,
422
+ timeoutMs: options?.timeoutMs
423
+ });
424
+ return expectObject(payload, "GET /api/v1/me");
425
+ }
426
+ };
427
+
428
+ // src/resources/servers.ts
429
+ var ServersResource = class {
430
+ #http;
431
+ constructor(http) {
432
+ this.#http = http;
433
+ }
434
+ /** Lists the workspace's servers. Retried on transient failures. */
435
+ async list(options) {
436
+ checkRequestOptions(options);
437
+ const payload = await this.#http.request({
438
+ method: "GET",
439
+ path: "/api/v1/servers",
440
+ signal: options?.signal,
441
+ timeoutMs: options?.timeoutMs
442
+ });
443
+ return expectArray(payload, "servers", "GET /api/v1/servers");
444
+ }
445
+ /**
446
+ * Re-reads the server's tool list from the upstream and updates Portless.
447
+ * Not retried automatically.
448
+ */
449
+ async sync(serverId, options) {
450
+ if (typeof serverId !== "string" || serverId.trim() === "") {
451
+ throw new ValidationError("serverId must be a non-empty string.", {
452
+ code: "invalid_server_id"
453
+ });
454
+ }
455
+ checkRequestOptions(options);
456
+ const payload = await this.#http.request({
457
+ method: "POST",
458
+ path: `/api/v1/servers/${encodeURIComponent(serverId)}/sync`,
459
+ signal: options?.signal,
460
+ timeoutMs: options?.timeoutMs,
461
+ retry: false
462
+ });
463
+ return expectObject(payload, "POST /api/v1/servers/{id}/sync");
464
+ }
465
+ };
466
+
467
+ // src/tool-call.ts
468
+ var ToolCall = class {
469
+ /** Qualified name of the tool that ran, e.g. `github.get_issue`. */
470
+ tool;
471
+ /** Gateway-measured upstream latency in milliseconds. */
472
+ latencyMs;
473
+ /** The MCP result exactly as the upstream returned it. */
474
+ result;
475
+ constructor(response) {
476
+ this.tool = response.tool;
477
+ this.latencyMs = response.latencyMs;
478
+ this.result = response.result;
479
+ }
480
+ /** `true` when the tool ran but reported failure (`result.isError === true`). */
481
+ get isError() {
482
+ return this.result.isError === true;
483
+ }
484
+ /** All `text` content parts joined with `"\n"`. Non-text parts are skipped. */
485
+ get text() {
486
+ const content = Array.isArray(this.result.content) ? this.result.content : [];
487
+ const parts = [];
488
+ for (const block of content) {
489
+ if (block?.type === "text" && typeof block.text === "string") parts.push(block.text);
490
+ }
491
+ return parts.join("\n");
492
+ }
493
+ /**
494
+ * The tool's JSON output: `structuredContent` when present, otherwise `JSON.parse(text)`.
495
+ * The type parameter is not validated at runtime.
496
+ *
497
+ * @throws {@link PortlessError} with code `invalid_json` when there is no structured content and
498
+ * the text is not valid JSON.
499
+ */
500
+ json() {
501
+ if (this.result.structuredContent !== void 0) return this.result.structuredContent;
502
+ try {
503
+ return JSON.parse(this.text);
504
+ } catch (error) {
505
+ throw new PortlessError(
506
+ `Tool ${this.tool} returned no structuredContent and its text is not valid JSON.`,
507
+ { code: "invalid_json", cause: error }
508
+ );
509
+ }
510
+ }
511
+ /** JSON form: the gateway response plus `isError` and `text`. */
512
+ toJSON() {
513
+ return {
514
+ tool: this.tool,
515
+ latencyMs: this.latencyMs,
516
+ result: this.result,
517
+ isError: this.isError,
518
+ text: this.text
519
+ };
520
+ }
521
+ };
522
+
523
+ // src/tool-name.ts
524
+ var WHITESPACE = /\s/;
525
+ function parseToolName(input) {
526
+ if (typeof input !== "string") {
527
+ throw invalid(`Tool name must be a string, got ${input === null ? "null" : typeof input}.`);
528
+ }
529
+ if (input === "" || WHITESPACE.test(input)) {
530
+ throw invalid(
531
+ `Invalid tool name ${JSON.stringify(input)}: it must not be empty or contain whitespace.`
532
+ );
533
+ }
534
+ const dot = input.indexOf(".");
535
+ const underscores = input.indexOf("__");
536
+ let index;
537
+ let separatorLength;
538
+ if (dot === -1 && underscores === -1) {
539
+ throw invalid(
540
+ `Invalid tool name ${JSON.stringify(input)}: expected "namespace.tool" or "namespace__tool".`
541
+ );
542
+ }
543
+ if (underscores === -1 || dot !== -1 && dot < underscores) {
544
+ index = dot;
545
+ separatorLength = 1;
546
+ } else {
547
+ index = underscores;
548
+ separatorLength = 2;
549
+ }
550
+ const namespace = input.slice(0, index);
551
+ const name = input.slice(index + separatorLength);
552
+ if (namespace === "" || name === "") {
553
+ throw invalid(
554
+ `Invalid tool name ${JSON.stringify(input)}: namespace and tool name must both be non-empty.`
555
+ );
556
+ }
557
+ return { namespace, name, qualified: `${namespace}.${name}` };
558
+ }
559
+ function invalid(message) {
560
+ return new ValidationError(message, { code: "invalid_tool_name" });
561
+ }
562
+
563
+ // src/resources/tools.ts
564
+ var ToolsResource = class {
565
+ #http;
566
+ constructor(http) {
567
+ this.#http = http;
568
+ }
569
+ /**
570
+ * Lists tools. `{ enabled: true }` asks the gateway for enabled tools only;
571
+ * `{ enabled: false }` returns only disabled tools. Retried on transient failures.
572
+ */
573
+ async list(options = {}) {
574
+ checkRequestOptions(options);
575
+ if (options.enabled !== void 0 && typeof options.enabled !== "boolean") {
576
+ throw new ValidationError("enabled must be a boolean.", { code: "invalid_option" });
577
+ }
578
+ const payload = await this.#http.request({
579
+ method: "GET",
580
+ path: "/api/v1/tools",
581
+ ...options.enabled === true ? { query: { enabled: "true" } } : {},
582
+ signal: options.signal,
583
+ timeoutMs: options.timeoutMs
584
+ });
585
+ const tools = expectArray(payload, "tools", "GET /api/v1/tools");
586
+ return options.enabled === false ? tools.filter((tool) => tool.enabled === false) : tools;
587
+ }
588
+ /**
589
+ * Calls a tool through the gateway. A tool that ran but failed resolves normally with
590
+ * `isError: true`; use {@link ToolsResource.run} to throw instead.
591
+ *
592
+ * Not retried unless `options.retry` is `true`, because tool calls may have side effects.
593
+ *
594
+ * @param tool - `"namespace.tool"` or `"namespace__tool"`.
595
+ * @param args - Tool arguments (a JSON object).
596
+ */
597
+ async call(tool, args, options = {}) {
598
+ let parsed;
599
+ try {
600
+ parsed = parseToolName(tool);
601
+ } catch (error) {
602
+ const { message, code } = error;
603
+ throw new ValidationError(this.#http.redact(message), { code });
604
+ }
605
+ if (args !== void 0 && !isObject(args)) {
606
+ throw new ValidationError("Tool arguments must be a plain JSON object.", {
607
+ code: "invalid_arguments"
608
+ });
609
+ }
610
+ if (typeof options !== "object" || options === null) {
611
+ throw new ValidationError("Options must be an object.", { code: "invalid_option" });
612
+ }
613
+ checkAgent(options.agent, "agent");
614
+ if (options.timeoutMs !== void 0) checkTimeout(options.timeoutMs, "timeoutMs");
615
+ const body = {
616
+ tool: parsed.qualified
617
+ };
618
+ if (args !== void 0) body.arguments = args;
619
+ if (options.agent !== void 0) body.agent = options.agent;
620
+ const payload = await this.#http.request({
621
+ method: "POST",
622
+ path: "/api/v1/tools/call",
623
+ body,
624
+ agent: options.agent,
625
+ signal: options.signal,
626
+ timeoutMs: options.timeoutMs,
627
+ retry: options.retry === true
628
+ });
629
+ const response = expectObject(payload, "POST /api/v1/tools/call");
630
+ expectObject(response.result, "POST /api/v1/tools/call (result)");
631
+ return new ToolCall(response);
632
+ }
633
+ /**
634
+ * Like {@link ToolsResource.call}, but throws {@link ToolExecutionError} when the tool
635
+ * returns `isError: true`. The call is available as `error.toolCall`.
636
+ */
637
+ async run(tool, args, options) {
638
+ const call = await this.call(tool, args, options);
639
+ if (call.isError) {
640
+ const detail = call.text.trim();
641
+ const summary = detail.length > 300 ? `${detail.slice(0, 300)}\u2026` : detail;
642
+ throw new ToolExecutionError(
643
+ `Tool ${call.tool} returned an error${summary ? `: ${this.#http.redact(summary)}` : "."}`,
644
+ { code: "tool_error", toolCall: call }
645
+ );
646
+ }
647
+ return call;
648
+ }
649
+ };
650
+
651
+ // src/client.ts
652
+ var DEFAULT_BASE_URL = "https://www.initpbj.dev";
653
+ var DEFAULT_TIMEOUT_MS = 6e4;
654
+ var DEFAULT_MAX_RETRIES = 2;
655
+ var API_KEY_PREFIX = "pl_live_";
656
+ var Portless = class {
657
+ /** Upstream MCP servers. */
658
+ servers;
659
+ /** Tools: list, call, run. */
660
+ tools;
661
+ /** MCP client config helpers. */
662
+ mcp;
663
+ /** Normalised gateway base URL (no trailing slash). */
664
+ baseUrl;
665
+ /** Default agent sent as `X-Portless-Agent`, if configured. */
666
+ agent;
667
+ /** Per-request timeout in milliseconds. */
668
+ timeoutMs;
669
+ /** Retries for idempotent requests. */
670
+ maxRetries;
671
+ #me;
672
+ /**
673
+ * @throws {@link AuthenticationError} (`missing_api_key`) when no key is given or found in
674
+ * `PORTLESS_API_KEY`, or (`invalid_api_key`) when the key does not start with `pl_live_`.
675
+ * @throws {@link ValidationError} for other invalid options.
676
+ */
677
+ constructor(options = {}) {
678
+ if (typeof options !== "object" || options === null) {
679
+ throw new ValidationError("Options must be an object.", { code: "invalid_option" });
680
+ }
681
+ const apiKey = resolveApiKey(options.apiKey);
682
+ this.baseUrl = resolveBaseUrl(options.baseUrl);
683
+ checkAgent(options.agent, "agent");
684
+ this.agent = options.agent;
685
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
686
+ checkTimeout(this.timeoutMs, "timeoutMs");
687
+ this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
688
+ if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0) {
689
+ throw new ValidationError("maxRetries must be a non-negative integer.", {
690
+ code: "invalid_option"
691
+ });
692
+ }
693
+ const fetchImpl = resolveFetch(options.fetch);
694
+ const headers = resolveHeaders(options.headers);
695
+ const http = new HttpClient({
696
+ apiKey,
697
+ baseUrl: this.baseUrl,
698
+ agent: this.agent,
699
+ timeoutMs: this.timeoutMs,
700
+ maxRetries: this.maxRetries,
701
+ fetch: fetchImpl,
702
+ headers
703
+ });
704
+ this.#me = new MeResource(http);
705
+ this.servers = new ServersResource(http);
706
+ this.tools = new ToolsResource(http);
707
+ this.mcp = new McpResource(apiKey, this.baseUrl, this.agent);
708
+ }
709
+ /** `GET /api/v1/me`: the workspace, key and agent these credentials resolve to. */
710
+ me(options) {
711
+ return this.#me.get(options);
712
+ }
713
+ /** Secret-free JSON form. The API key is always shown as `pl_live_****`. */
714
+ toJSON() {
715
+ return {
716
+ baseUrl: this.baseUrl,
717
+ apiKey: REDACTED_KEY,
718
+ ...this.agent === void 0 ? {} : { agent: this.agent },
719
+ timeoutMs: this.timeoutMs,
720
+ maxRetries: this.maxRetries
721
+ };
722
+ }
723
+ /** Secret-free string form. */
724
+ toString() {
725
+ return `Portless(${JSON.stringify(this.toJSON())})`;
726
+ }
727
+ /** Node.js `util.inspect` / `console.log` output, without the key. */
728
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
729
+ return this.toString();
730
+ }
731
+ /** Deno `Deno.inspect` / `console.log` output, without the key. */
732
+ [/* @__PURE__ */ Symbol.for("Deno.customInspect")]() {
733
+ return this.toString();
734
+ }
735
+ };
736
+ function resolveApiKey(explicit) {
737
+ if (explicit !== void 0 && typeof explicit !== "string") {
738
+ throw new AuthenticationError("apiKey must be a string.", { code: "invalid_api_key" });
739
+ }
740
+ const key = (typeof explicit === "string" ? explicit.trim() : "") || readEnv("PORTLESS_API_KEY");
741
+ if (key === void 0 || key === "") {
742
+ throw new AuthenticationError(
743
+ "No Portless API key found. Pass `apiKey` or set the PORTLESS_API_KEY environment variable. Create a key in the Portless dashboard.",
744
+ { code: "missing_api_key" }
745
+ );
746
+ }
747
+ if (!key.startsWith(API_KEY_PREFIX) || key.length === API_KEY_PREFIX.length || /\s/.test(key)) {
748
+ throw new AuthenticationError(
749
+ `Invalid Portless API key: keys start with "${API_KEY_PREFIX}" and contain no whitespace.`,
750
+ { code: "invalid_api_key" }
751
+ );
752
+ }
753
+ assertHeaderValue(key, "apiKey");
754
+ return key;
755
+ }
756
+ function resolveBaseUrl(explicit) {
757
+ if (explicit !== void 0 && typeof explicit !== "string") {
758
+ throw new ValidationError("baseUrl must be a string.", { code: "invalid_base_url" });
759
+ }
760
+ const raw = (typeof explicit === "string" ? explicit.trim() : "") || readEnv("PORTLESS_BASE_URL") || DEFAULT_BASE_URL;
761
+ const normalised = raw.replace(/\/+$/, "");
762
+ let parsed;
763
+ try {
764
+ parsed = new URL(normalised);
765
+ } catch {
766
+ throw new ValidationError(`Invalid baseUrl ${JSON.stringify(normalised)}: not a URL.`, {
767
+ code: "invalid_base_url"
768
+ });
769
+ }
770
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
771
+ throw new ValidationError("baseUrl must use http: or https:.", { code: "invalid_base_url" });
772
+ }
773
+ if (parsed.search || parsed.hash) {
774
+ throw new ValidationError("baseUrl must not contain a query string or fragment.", {
775
+ code: "invalid_base_url"
776
+ });
777
+ }
778
+ return normalised;
779
+ }
780
+ function resolveFetch(explicit) {
781
+ if (explicit !== void 0) {
782
+ if (typeof explicit !== "function") {
783
+ throw new ValidationError("fetch must be a function.", { code: "invalid_option" });
784
+ }
785
+ return explicit;
786
+ }
787
+ const globalFetch = globalThis.fetch;
788
+ if (typeof globalFetch !== "function") {
789
+ throw new ValidationError(
790
+ "No global fetch found. Use Node.js 18+ or pass a `fetch` implementation.",
791
+ { code: "fetch_unavailable" }
792
+ );
793
+ }
794
+ return (input, init) => globalFetch.call(globalThis, input, init);
795
+ }
796
+ function resolveHeaders(explicit) {
797
+ if (explicit === void 0) return {};
798
+ if (typeof explicit !== "object" || explicit === null || Array.isArray(explicit)) {
799
+ throw new ValidationError("headers must be an object of string values.", {
800
+ code: "invalid_option"
801
+ });
802
+ }
803
+ const headers = {};
804
+ for (const [name, value] of Object.entries(explicit)) {
805
+ if (typeof value !== "string") {
806
+ throw new ValidationError(`Header ${JSON.stringify(name)} must be a string.`, {
807
+ code: "invalid_option"
808
+ });
809
+ }
810
+ if (name.toLowerCase() === "authorization") continue;
811
+ assertHeaderValue(value, `Header ${JSON.stringify(name)}`);
812
+ try {
813
+ new Headers([[name, value]]);
814
+ } catch {
815
+ throw new ValidationError(`Invalid header name ${JSON.stringify(name)}.`, {
816
+ code: "invalid_option"
817
+ });
818
+ }
819
+ headers[name] = value;
820
+ }
821
+ return headers;
822
+ }
823
+
824
+ export { API_KEY_PREFIX, AuthenticationError, ConnectionError, DEFAULT_BASE_URL, NotFoundError, PermissionError, Portless, PortlessError, ServerError, TimeoutError, ToolCall, ToolExecutionError, UpstreamError, VERSION, ValidationError, parseToolName };
825
+ //# sourceMappingURL=index.js.map
826
+ //# sourceMappingURL=index.js.map