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