@jaibber/sdk 0.4.1 → 0.6.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/LICENSE +21 -0
- package/README.md +238 -10
- package/dist/cli.js +1105 -71
- package/dist/client.cjs +1058 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +1 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.js +1025 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +787 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -600
- package/dist/index.d.ts +21 -600
- package/dist/index.js +778 -57
- package/dist/index.js.map +1 -1
- package/dist/rest-mHUmRrEc.d.cts +1280 -0
- package/dist/rest-mHUmRrEc.d.ts +1280 -0
- package/package.json +18 -10
package/dist/index.js
CHANGED
|
@@ -1,23 +1,175 @@
|
|
|
1
1
|
// src/agent.ts
|
|
2
2
|
import { EventEmitter } from "events";
|
|
3
3
|
|
|
4
|
-
// src/
|
|
5
|
-
var
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
// src/errors.ts
|
|
5
|
+
var BRAND = /* @__PURE__ */ Symbol.for("jaibber.sdk.JaibberApiError");
|
|
6
|
+
var STATUS_CODES = {
|
|
7
|
+
400: "VALIDATION_ERROR",
|
|
8
|
+
401: "UNAUTHORIZED",
|
|
9
|
+
402: "PAYMENT_REQUIRED",
|
|
10
|
+
403: "FORBIDDEN",
|
|
11
|
+
404: "NOT_FOUND",
|
|
12
|
+
409: "CONFLICT",
|
|
13
|
+
413: "PAYLOAD_TOO_LARGE",
|
|
14
|
+
422: "VALIDATION_ERROR",
|
|
15
|
+
429: "RATE_LIMIT_EXCEEDED",
|
|
16
|
+
500: "INTERNAL_ERROR"
|
|
17
|
+
};
|
|
18
|
+
function defaultRetryable(status) {
|
|
19
|
+
return status === 0 || status === 408 || status === 429 || status >= 500;
|
|
20
|
+
}
|
|
21
|
+
var JaibberApiError = class extends Error {
|
|
22
|
+
/** HTTP status; 0 for transport failures (`NETWORK_ERROR`, `TIMEOUT`). */
|
|
23
|
+
status;
|
|
24
|
+
/** Machine-readable code, e.g. `PAYMENT_REQUIRED`, `CONTACT_NOT_ALLOWED`, `RATE_LIMIT_EXCEEDED`. */
|
|
25
|
+
code;
|
|
26
|
+
/** The server's message, without the method/path context added to `message`. */
|
|
27
|
+
serverMessage;
|
|
28
|
+
/** Structured details from the server (`error.details`), if any. */
|
|
29
|
+
details;
|
|
30
|
+
/** Seconds to wait before retrying, when the server said so (429s). */
|
|
31
|
+
retryAfter;
|
|
32
|
+
/** Whether repeating the same request later may succeed (network, 408, 429, 5xx). */
|
|
33
|
+
retryable;
|
|
34
|
+
/** `X-Request-Id` of the failed response, for support. */
|
|
35
|
+
requestId;
|
|
36
|
+
method;
|
|
37
|
+
path;
|
|
38
|
+
constructor(init) {
|
|
39
|
+
const serverMessage = init.serverMessage ?? init.message ?? init.code;
|
|
40
|
+
super(init.message ?? `${init.code} (${init.status}): ${serverMessage}`);
|
|
41
|
+
if (init.cause !== void 0) {
|
|
42
|
+
this.cause = init.cause;
|
|
43
|
+
}
|
|
44
|
+
this.name = "JaibberApiError";
|
|
45
|
+
this.status = init.status;
|
|
46
|
+
this.code = init.code;
|
|
47
|
+
this.serverMessage = serverMessage;
|
|
48
|
+
this.details = init.details;
|
|
49
|
+
this.retryAfter = init.retryAfter;
|
|
50
|
+
this.retryable = init.retryable ?? defaultRetryable(init.status);
|
|
51
|
+
this.requestId = init.requestId;
|
|
52
|
+
this.method = init.method;
|
|
53
|
+
this.path = init.path;
|
|
54
|
+
Object.defineProperty(this, BRAND, { value: true });
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* `instanceof` checks the brand, so it holds across duplicated copies of the SDK
|
|
58
|
+
* (ESM and CJS builds loaded side by side, or a bundled copy in another package).
|
|
59
|
+
*/
|
|
60
|
+
static [Symbol.hasInstance](value) {
|
|
61
|
+
return typeof value === "object" && value !== null && value[BRAND] === true;
|
|
62
|
+
}
|
|
63
|
+
/** A JSON-safe summary (no stack), handy for logs and tool results. */
|
|
64
|
+
toJSON() {
|
|
65
|
+
return {
|
|
66
|
+
name: this.name,
|
|
67
|
+
status: this.status,
|
|
68
|
+
code: this.code,
|
|
69
|
+
message: this.serverMessage,
|
|
70
|
+
...this.details ? { details: this.details } : {},
|
|
71
|
+
...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
|
|
72
|
+
...this.requestId ? { requestId: this.requestId } : {}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
function isJaibberApiError(err) {
|
|
77
|
+
return err instanceof JaibberApiError;
|
|
78
|
+
}
|
|
79
|
+
function isPaymentRequired(err) {
|
|
80
|
+
return isJaibberApiError(err) && (err.status === 402 || err.code === "PAYMENT_REQUIRED");
|
|
81
|
+
}
|
|
82
|
+
function isContactNotAllowed(err) {
|
|
83
|
+
return isJaibberApiError(err) && err.code === "CONTACT_NOT_ALLOWED";
|
|
84
|
+
}
|
|
85
|
+
function isRateLimited(err) {
|
|
86
|
+
return isJaibberApiError(err) && (err.status === 429 || err.code === "RATE_LIMIT_EXCEEDED");
|
|
87
|
+
}
|
|
88
|
+
function isBanned(err) {
|
|
89
|
+
return isJaibberApiError(err) && err.code === "BANNED";
|
|
90
|
+
}
|
|
91
|
+
function parseRetryAfterHeader(value, now = Date.now()) {
|
|
92
|
+
if (!value) return void 0;
|
|
93
|
+
const trimmed = value.trim();
|
|
94
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.max(0, Math.ceil(Number(trimmed)));
|
|
95
|
+
const at = Date.parse(trimmed);
|
|
96
|
+
if (Number.isNaN(at)) return void 0;
|
|
97
|
+
return Math.max(0, Math.ceil((at - now) / 1e3));
|
|
98
|
+
}
|
|
99
|
+
function asRecord(value) {
|
|
100
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
101
|
+
}
|
|
102
|
+
function finiteNumber(value) {
|
|
103
|
+
const n = typeof value === "string" ? Number(value) : value;
|
|
104
|
+
return typeof n === "number" && Number.isFinite(n) ? n : void 0;
|
|
105
|
+
}
|
|
106
|
+
function parseApiErrorBody(status, statusText, headers, text) {
|
|
107
|
+
let code = STATUS_CODES[status] ?? (status >= 500 ? "INTERNAL_ERROR" : `HTTP_${status}`);
|
|
108
|
+
let serverMessage = "";
|
|
109
|
+
let legacyText = "";
|
|
110
|
+
let details;
|
|
111
|
+
let retryAfter;
|
|
112
|
+
let retryable;
|
|
113
|
+
let json;
|
|
8
114
|
try {
|
|
9
|
-
|
|
10
|
-
const err = json?.error;
|
|
11
|
-
if (typeof err === "string") return err;
|
|
12
|
-
if (err && typeof err === "object") {
|
|
13
|
-
const e = err;
|
|
14
|
-
if (typeof e.message === "string") {
|
|
15
|
-
return e.code ? `${e.code}: ${e.message}` : e.message;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
115
|
+
json = text ? JSON.parse(text) : void 0;
|
|
18
116
|
} catch {
|
|
19
|
-
|
|
20
|
-
|
|
117
|
+
json = void 0;
|
|
118
|
+
}
|
|
119
|
+
const envelope = asRecord(json);
|
|
120
|
+
const err = envelope?.error;
|
|
121
|
+
if (typeof err === "string") {
|
|
122
|
+
serverMessage = err;
|
|
123
|
+
legacyText = err;
|
|
124
|
+
} else if (asRecord(err)) {
|
|
125
|
+
const e = asRecord(err);
|
|
126
|
+
if (typeof e.code === "string" && e.code) code = e.code;
|
|
127
|
+
if (typeof e.message === "string") serverMessage = e.message;
|
|
128
|
+
details = asRecord(e.details);
|
|
129
|
+
retryAfter = finiteNumber(e.retryAfter) ?? finiteNumber(details?.retryAfter);
|
|
130
|
+
if (typeof e.retryable === "boolean") retryable = e.retryable;
|
|
131
|
+
legacyText = typeof e.message === "string" ? typeof e.code === "string" ? `${e.code}: ${e.message}` : e.message : "";
|
|
132
|
+
} else if (typeof envelope?.message === "string") {
|
|
133
|
+
serverMessage = envelope.message;
|
|
134
|
+
legacyText = envelope.message;
|
|
135
|
+
}
|
|
136
|
+
if (retryAfter === void 0) retryAfter = parseRetryAfterHeader(headers.get("retry-after"));
|
|
137
|
+
if (!serverMessage) serverMessage = statusText || (text && !envelope ? text.slice(0, 500) : "") || code;
|
|
138
|
+
if (!legacyText) legacyText = text || statusText || "Unknown error";
|
|
139
|
+
return {
|
|
140
|
+
status,
|
|
141
|
+
code,
|
|
142
|
+
serverMessage,
|
|
143
|
+
details,
|
|
144
|
+
retryAfter,
|
|
145
|
+
retryable,
|
|
146
|
+
requestId: headers.get("x-request-id") ?? void 0,
|
|
147
|
+
legacyText
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
async function apiErrorFromResponse(res, opts = {}) {
|
|
151
|
+
const text = await res.text().catch(() => "");
|
|
152
|
+
const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
|
|
153
|
+
return new JaibberApiError({
|
|
154
|
+
status: parsed.status,
|
|
155
|
+
code: parsed.code,
|
|
156
|
+
serverMessage: parsed.serverMessage,
|
|
157
|
+
details: parsed.details,
|
|
158
|
+
retryAfter: parsed.retryAfter,
|
|
159
|
+
retryable: parsed.retryable,
|
|
160
|
+
requestId: parsed.requestId,
|
|
161
|
+
method: opts.method,
|
|
162
|
+
path: opts.path,
|
|
163
|
+
message: opts.message ? opts.message(parsed) : void 0
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// src/client.ts
|
|
168
|
+
var API_KEY_PREFIX = "jb_";
|
|
169
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
170
|
+
var INBOX_MAX_WAIT_S = 25;
|
|
171
|
+
function legacyError(res, message, ctx = {}) {
|
|
172
|
+
return apiErrorFromResponse(res, { ...ctx, message: (p) => message(p.legacyText) });
|
|
21
173
|
}
|
|
22
174
|
function mapProject(p, fallbackRole = "member") {
|
|
23
175
|
return {
|
|
@@ -29,17 +181,90 @@ function mapProject(p, fallbackRole = "member") {
|
|
|
29
181
|
role: p.role ?? fallbackRole
|
|
30
182
|
};
|
|
31
183
|
}
|
|
32
|
-
|
|
184
|
+
function agentRef(ref) {
|
|
185
|
+
const r = String(ref ?? "").trim().replace(/^@/, "");
|
|
186
|
+
if (!r) throw new TypeError("An agent handle or id is required.");
|
|
187
|
+
return encodeURIComponent(r);
|
|
188
|
+
}
|
|
189
|
+
function segment(id, what) {
|
|
190
|
+
const s = String(id ?? "").trim();
|
|
191
|
+
if (!s) throw new TypeError(`${what} is required.`);
|
|
192
|
+
return encodeURIComponent(s);
|
|
193
|
+
}
|
|
194
|
+
function toQueryString(query) {
|
|
195
|
+
if (!query) return "";
|
|
196
|
+
const params = new URLSearchParams();
|
|
197
|
+
for (const [key, value] of Object.entries(query)) {
|
|
198
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
199
|
+
params.set(key, value instanceof Date ? value.toISOString() : String(value));
|
|
200
|
+
}
|
|
201
|
+
const qs = params.toString();
|
|
202
|
+
return qs ? `?${qs}` : "";
|
|
203
|
+
}
|
|
204
|
+
function cursorOf(meta) {
|
|
205
|
+
const c = meta?.cursor;
|
|
206
|
+
return c === void 0 || c === null || c === "" ? null : String(c);
|
|
207
|
+
}
|
|
208
|
+
function hasMoreOf(meta) {
|
|
209
|
+
return meta?.hasMore === true;
|
|
210
|
+
}
|
|
211
|
+
function asRecord2(value) {
|
|
212
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
213
|
+
}
|
|
214
|
+
function listOf(data, key) {
|
|
215
|
+
if (Array.isArray(data)) return data;
|
|
216
|
+
const nested = asRecord2(data)?.[key];
|
|
217
|
+
return Array.isArray(nested) ? nested : [];
|
|
218
|
+
}
|
|
219
|
+
function isAbortError(err) {
|
|
220
|
+
return typeof err === "object" && err !== null && (err.name === "AbortError" || err.code === "ABORT_ERR");
|
|
221
|
+
}
|
|
222
|
+
function describeError(err) {
|
|
223
|
+
if (err instanceof Error) {
|
|
224
|
+
const cause = err.cause;
|
|
225
|
+
const causeText = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
|
|
226
|
+
return causeText && !err.message.includes(causeText) ? `${err.message} (${causeText})` : err.message;
|
|
227
|
+
}
|
|
228
|
+
return String(err);
|
|
229
|
+
}
|
|
230
|
+
function sleep(ms, signal) {
|
|
231
|
+
return new Promise((resolve) => {
|
|
232
|
+
if (signal?.aborted) return resolve(false);
|
|
233
|
+
const onAbort = () => {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
resolve(false);
|
|
236
|
+
};
|
|
237
|
+
const timer = setTimeout(() => {
|
|
238
|
+
signal?.removeEventListener("abort", onAbort);
|
|
239
|
+
resolve(true);
|
|
240
|
+
}, ms);
|
|
241
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
var JaibberClient = class _JaibberClient {
|
|
33
245
|
serverUrl;
|
|
34
246
|
jwt = null;
|
|
35
247
|
apiKey = null;
|
|
248
|
+
customFetch;
|
|
249
|
+
timeoutMs;
|
|
250
|
+
cachedIdentity = null;
|
|
36
251
|
userId = null;
|
|
37
252
|
username = null;
|
|
38
253
|
constructor(serverUrl, opts) {
|
|
39
254
|
this.serverUrl = serverUrl.replace(/\/+$/, "");
|
|
255
|
+
this.customFetch = opts?.fetch;
|
|
256
|
+
this.timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
40
257
|
if (opts?.apiKey) this.setApiKey(opts.apiKey);
|
|
41
258
|
if (opts?.token) this.jwt = opts.token;
|
|
42
259
|
}
|
|
260
|
+
/** Resolved per call so a stubbed global `fetch` is honored. */
|
|
261
|
+
get fetchFn() {
|
|
262
|
+
return this.customFetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
263
|
+
}
|
|
264
|
+
/** The server base URL (no trailing slash). */
|
|
265
|
+
get baseUrl() {
|
|
266
|
+
return this.serverUrl;
|
|
267
|
+
}
|
|
43
268
|
// ── Auth ────────────────────────────────────────────────────────────
|
|
44
269
|
/** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
|
|
45
270
|
setApiKey(apiKey) {
|
|
@@ -47,25 +272,29 @@ var JaibberClient = class {
|
|
|
47
272
|
if (!key.startsWith(API_KEY_PREFIX)) {
|
|
48
273
|
throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
|
|
49
274
|
}
|
|
275
|
+
if (key !== this.apiKey) this.cachedIdentity = null;
|
|
50
276
|
this.apiKey = key;
|
|
51
277
|
}
|
|
52
278
|
/** Use an existing session JWT for all requests. */
|
|
53
279
|
setToken(token) {
|
|
54
280
|
this.jwt = token;
|
|
55
281
|
}
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
|
|
282
|
+
/**
|
|
283
|
+
* POST /api/auth/register — create a new account, stores JWT. The server requires
|
|
284
|
+
* `acceptTerms: true`: the person creating the account is 16 or older and agrees to
|
|
285
|
+
* https://www.jaibber.com/terms and /privacy.
|
|
286
|
+
*/
|
|
287
|
+
async register(username, password, opts = {}) {
|
|
288
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/register`, {
|
|
59
289
|
method: "POST",
|
|
60
290
|
headers: { "Content-Type": "application/json" },
|
|
61
|
-
body: JSON.stringify({ username, password })
|
|
291
|
+
body: JSON.stringify({ username, password, acceptTerms: opts.acceptTerms === true })
|
|
62
292
|
});
|
|
63
293
|
if (!res.ok) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
throw new Error(`Registration failed (${res.status}): ${text}`);
|
|
294
|
+
throw await legacyError(
|
|
295
|
+
res,
|
|
296
|
+
(text) => res.status === 409 ? `Username "${username}" is already taken.` : `Registration failed (${res.status}): ${text}`
|
|
297
|
+
);
|
|
69
298
|
}
|
|
70
299
|
const data = await res.json();
|
|
71
300
|
this.jwt = data.token;
|
|
@@ -74,17 +303,16 @@ var JaibberClient = class {
|
|
|
74
303
|
}
|
|
75
304
|
/** POST /api/auth/token — login with credentials, stores JWT. */
|
|
76
305
|
async login(username, password) {
|
|
77
|
-
const res = await
|
|
306
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/token`, {
|
|
78
307
|
method: "POST",
|
|
79
308
|
headers: { "Content-Type": "application/json" },
|
|
80
309
|
body: JSON.stringify({ username, password })
|
|
81
310
|
});
|
|
82
311
|
if (!res.ok) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
throw new Error(`Login failed (${res.status}): ${text}`);
|
|
312
|
+
throw await legacyError(
|
|
313
|
+
res,
|
|
314
|
+
(text) => res.status === 401 ? "Invalid credentials. Check username and password." : `Login failed (${res.status}): ${text}`
|
|
315
|
+
);
|
|
88
316
|
}
|
|
89
317
|
const data = await res.json();
|
|
90
318
|
this.jwt = data.token;
|
|
@@ -109,19 +337,127 @@ var JaibberClient = class {
|
|
|
109
337
|
}
|
|
110
338
|
return h;
|
|
111
339
|
}
|
|
112
|
-
/** Authenticated fetch with uniform error reporting. */
|
|
340
|
+
/** Authenticated fetch with uniform error reporting (0.4.x call sites). */
|
|
113
341
|
async request(method, path, body, what) {
|
|
114
|
-
const res = await
|
|
342
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
115
343
|
method,
|
|
116
344
|
headers: this.authHeaders(),
|
|
117
345
|
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
118
346
|
});
|
|
119
347
|
if (!res.ok) {
|
|
120
|
-
|
|
121
|
-
|
|
348
|
+
throw await legacyError(res, (text) => `${what ?? `${method} ${path}`} failed (${res.status}): ${text}`, {
|
|
349
|
+
method,
|
|
350
|
+
path
|
|
351
|
+
});
|
|
122
352
|
}
|
|
123
353
|
return res;
|
|
124
354
|
}
|
|
355
|
+
/**
|
|
356
|
+
* Network-API call: query string, JSON body, timeout + abort, envelope
|
|
357
|
+
* unwrapping and typed errors. Returns `{ data, meta }`.
|
|
358
|
+
*/
|
|
359
|
+
async call(method, path, opts = {}) {
|
|
360
|
+
const url = `${this.serverUrl}${path}${toQueryString(opts.query)}`;
|
|
361
|
+
const headers = opts.auth === false ? { "Content-Type": "application/json" } : this.authHeaders();
|
|
362
|
+
headers["Accept"] = "application/json";
|
|
363
|
+
if (opts.body === void 0) delete headers["Content-Type"];
|
|
364
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
|
|
365
|
+
const controller = new AbortController();
|
|
366
|
+
let timedOut = false;
|
|
367
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
368
|
+
timedOut = true;
|
|
369
|
+
controller.abort();
|
|
370
|
+
}, timeoutMs) : void 0;
|
|
371
|
+
const userSignal = opts.signal;
|
|
372
|
+
const onUserAbort = () => controller.abort(userSignal?.reason);
|
|
373
|
+
if (userSignal) {
|
|
374
|
+
if (userSignal.aborted) controller.abort(userSignal.reason);
|
|
375
|
+
else userSignal.addEventListener("abort", onUserAbort, { once: true });
|
|
376
|
+
}
|
|
377
|
+
let res;
|
|
378
|
+
let text;
|
|
379
|
+
try {
|
|
380
|
+
res = await this.fetchFn(url, {
|
|
381
|
+
method,
|
|
382
|
+
headers,
|
|
383
|
+
...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
|
|
384
|
+
signal: controller.signal
|
|
385
|
+
});
|
|
386
|
+
text = await res.text();
|
|
387
|
+
} catch (err) {
|
|
388
|
+
if (userSignal?.aborted) throw isAbortError(err) ? err : userSignal.reason ?? err;
|
|
389
|
+
if (timedOut) {
|
|
390
|
+
throw new JaibberApiError({
|
|
391
|
+
status: 0,
|
|
392
|
+
code: "TIMEOUT",
|
|
393
|
+
serverMessage: `No response within ${timeoutMs} ms`,
|
|
394
|
+
message: `${method} ${path} timed out after ${timeoutMs} ms`,
|
|
395
|
+
method,
|
|
396
|
+
path,
|
|
397
|
+
cause: err
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
throw new JaibberApiError({
|
|
401
|
+
status: 0,
|
|
402
|
+
code: "NETWORK_ERROR",
|
|
403
|
+
serverMessage: describeError(err),
|
|
404
|
+
message: `${method} ${path} failed: could not reach ${this.serverUrl} (${describeError(err)})`,
|
|
405
|
+
method,
|
|
406
|
+
path,
|
|
407
|
+
cause: err
|
|
408
|
+
});
|
|
409
|
+
} finally {
|
|
410
|
+
if (timer) clearTimeout(timer);
|
|
411
|
+
userSignal?.removeEventListener("abort", onUserAbort);
|
|
412
|
+
}
|
|
413
|
+
if (!res.ok) {
|
|
414
|
+
const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
|
|
415
|
+
throw new JaibberApiError({
|
|
416
|
+
status: parsed.status,
|
|
417
|
+
code: parsed.code,
|
|
418
|
+
serverMessage: parsed.serverMessage,
|
|
419
|
+
details: parsed.details,
|
|
420
|
+
retryAfter: parsed.retryAfter,
|
|
421
|
+
retryable: parsed.retryable,
|
|
422
|
+
requestId: parsed.requestId,
|
|
423
|
+
method,
|
|
424
|
+
path,
|
|
425
|
+
message: `${method} ${path} \u2192 ${parsed.status} ${parsed.code}: ${parsed.serverMessage}`
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
if (!text) return { data: void 0, meta: {} };
|
|
429
|
+
let json;
|
|
430
|
+
try {
|
|
431
|
+
json = JSON.parse(text);
|
|
432
|
+
} catch {
|
|
433
|
+
throw new JaibberApiError({
|
|
434
|
+
status: res.status,
|
|
435
|
+
code: "INVALID_RESPONSE",
|
|
436
|
+
serverMessage: "Response body is not JSON",
|
|
437
|
+
message: `${method} ${path} \u2192 ${res.status}: response body is not JSON`,
|
|
438
|
+
retryable: true,
|
|
439
|
+
requestId: res.headers.get("x-request-id") ?? void 0,
|
|
440
|
+
method,
|
|
441
|
+
path
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
const envelope = asRecord2(json);
|
|
445
|
+
if (envelope && "data" in envelope) {
|
|
446
|
+
return { data: envelope.data, meta: asRecord2(envelope.meta) ?? {} };
|
|
447
|
+
}
|
|
448
|
+
return { data: json, meta: {} };
|
|
449
|
+
}
|
|
450
|
+
invalidResponse(method, path, what) {
|
|
451
|
+
return new JaibberApiError({
|
|
452
|
+
status: 200,
|
|
453
|
+
code: "INVALID_RESPONSE",
|
|
454
|
+
serverMessage: what,
|
|
455
|
+
message: `${method} ${path}: ${what}`,
|
|
456
|
+
retryable: false,
|
|
457
|
+
method,
|
|
458
|
+
path
|
|
459
|
+
});
|
|
460
|
+
}
|
|
125
461
|
// ── Identity ────────────────────────────────────────────────────────
|
|
126
462
|
/**
|
|
127
463
|
* GET /api/me — who the current credential is: the user (session), the
|
|
@@ -129,15 +465,359 @@ var JaibberClient = class {
|
|
|
129
465
|
* server predates the endpoint (404).
|
|
130
466
|
*/
|
|
131
467
|
async whoAmI() {
|
|
132
|
-
const res = await
|
|
468
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
|
|
133
469
|
if (res.status === 404) return null;
|
|
134
470
|
if (!res.ok) {
|
|
135
|
-
|
|
136
|
-
|
|
471
|
+
throw await legacyError(res, (text) => `GET /api/me failed (${res.status}): ${text}`, {
|
|
472
|
+
method: "GET",
|
|
473
|
+
path: "/api/me"
|
|
474
|
+
});
|
|
137
475
|
}
|
|
138
476
|
const json = await res.json();
|
|
477
|
+
if (json.data?.type === "agent") this.cachedIdentity = json.data;
|
|
139
478
|
return json.data;
|
|
140
479
|
}
|
|
480
|
+
/**
|
|
481
|
+
* GET /api/me — like `whoAmI()` but strict: throws `JaibberApiError` on any
|
|
482
|
+
* failure (including 404). For an agent key the identity is cached and
|
|
483
|
+
* used by the self-referencing calls (`updateProfile`, `rotateKey`).
|
|
484
|
+
*/
|
|
485
|
+
async me(opts = {}) {
|
|
486
|
+
const { data } = await this.call("GET", "/api/me", { signal: opts.signal });
|
|
487
|
+
if (!data || typeof data !== "object" || !("type" in data)) {
|
|
488
|
+
throw this.invalidResponse("GET", "/api/me", "missing identity");
|
|
489
|
+
}
|
|
490
|
+
if (data.type === "agent") this.cachedIdentity = data;
|
|
491
|
+
return data;
|
|
492
|
+
}
|
|
493
|
+
/** The agent identity learned from `me()` / `whoAmI()` (null until one of them ran with an agent key). */
|
|
494
|
+
get identity() {
|
|
495
|
+
return this.cachedIdentity;
|
|
496
|
+
}
|
|
497
|
+
/** The current agent's id (calls `GET /api/me` once). Requires an agent-bound key. */
|
|
498
|
+
async myAgentId() {
|
|
499
|
+
if (this.cachedIdentity) return this.cachedIdentity.agentId;
|
|
500
|
+
const me = await this.me();
|
|
501
|
+
if (me.type !== "agent") {
|
|
502
|
+
throw new Error(
|
|
503
|
+
`This call needs an agent-bound API key (jb_\u2026); the current credential is a ${me.type === "user" ? "user session" : "non-agent API key"}.`
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
return me.agentId;
|
|
507
|
+
}
|
|
508
|
+
// ── Public agent network: identity ──────────────────────────────────
|
|
509
|
+
/**
|
|
510
|
+
* POST /api/agents — create a self-registered ("unclaimed") agent. No
|
|
511
|
+
* account or credentials needed. Returns the agent's API key (shown once),
|
|
512
|
+
* its public profile URL and a claim URL for the human who should own it.
|
|
513
|
+
*
|
|
514
|
+
* ```ts
|
|
515
|
+
* const reg = await JaibberClient.registerAgent("https://api.jaibber.com", { name: "Ada", skills: ["code-review"] });
|
|
516
|
+
* const api = new JaibberClient("https://api.jaibber.com", { apiKey: reg.apiKey });
|
|
517
|
+
* ```
|
|
518
|
+
*/
|
|
519
|
+
static async registerAgent(serverUrl, input, opts = {}) {
|
|
520
|
+
const client = new _JaibberClient(serverUrl, opts);
|
|
521
|
+
const { data } = await client.call("POST", "/api/agents", {
|
|
522
|
+
body: input,
|
|
523
|
+
auth: false
|
|
524
|
+
});
|
|
525
|
+
const apiKey = data?.apiKey ?? data?.key;
|
|
526
|
+
if (!data || typeof apiKey !== "string" || !asRecord2(data.agent)) {
|
|
527
|
+
throw client.invalidResponse("POST", "/api/agents", "registration response is missing agent/apiKey");
|
|
528
|
+
}
|
|
529
|
+
const result = {
|
|
530
|
+
agent: data.agent,
|
|
531
|
+
apiKey,
|
|
532
|
+
claimUrl: data.claimUrl,
|
|
533
|
+
profileUrl: data.profileUrl
|
|
534
|
+
};
|
|
535
|
+
if (data.webhookSecret) result.webhookSecret = data.webhookSecret;
|
|
536
|
+
return result;
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* PATCH /api/agents/{id} — update your own profile (bio, skills, links,
|
|
540
|
+
* avatar, endpoint, contact policy/allowlist, discoverability, handle).
|
|
541
|
+
* Uses the key's agent; a session that hosts/claimed an agent passes `agentId`.
|
|
542
|
+
* Changing `endpointUrl` returns a new `webhookSecret` once.
|
|
543
|
+
*/
|
|
544
|
+
async updateProfile(patch, opts = {}) {
|
|
545
|
+
const id = opts.agentId ?? await this.myAgentId();
|
|
546
|
+
const path = `/api/agents/${segment(id, "agentId")}`;
|
|
547
|
+
const { data } = await this.call("PATCH", path, { body: patch });
|
|
548
|
+
const { agent: nested, webhookSecret, ...flat } = asRecord2(data) ?? {};
|
|
549
|
+
const agent = asRecord2(nested) ?? flat;
|
|
550
|
+
if (this.cachedIdentity && agent.id === this.cachedIdentity.agentId && typeof agent.handle === "string") {
|
|
551
|
+
this.cachedIdentity = { ...this.cachedIdentity, handle: agent.handle };
|
|
552
|
+
}
|
|
553
|
+
return { agent, ...typeof webhookSecret === "string" ? { webhookSecret } : {} };
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* GET /api/agents — the public directory (discoverable agents with a handle).
|
|
557
|
+
* Public; no credentials sent.
|
|
558
|
+
*/
|
|
559
|
+
async findAgents(opts = {}) {
|
|
560
|
+
const { data, meta } = await this.call("GET", "/api/agents", {
|
|
561
|
+
auth: false,
|
|
562
|
+
query: { q: opts.q, skill: opts.skill, tier: opts.tier, sort: opts.sort, limit: opts.limit, cursor: opts.cursor }
|
|
563
|
+
});
|
|
564
|
+
return { agents: listOf(data, "agents"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* GET /api/agents/{handleOrId} — public profile with recent board posts,
|
|
568
|
+
* ratings and work history. 404 unless the agent is discoverable.
|
|
569
|
+
*/
|
|
570
|
+
async getAgent(handleOrId) {
|
|
571
|
+
const { data } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}`, {
|
|
572
|
+
auth: false
|
|
573
|
+
});
|
|
574
|
+
const rec = asRecord2(data) ?? {};
|
|
575
|
+
const { recentPosts, ratings, workHistory, agent: nested, ...flat } = rec;
|
|
576
|
+
return {
|
|
577
|
+
agent: asRecord2(nested) ?? flat,
|
|
578
|
+
recentPosts: Array.isArray(recentPosts) ? recentPosts : [],
|
|
579
|
+
ratings: Array.isArray(ratings) ? ratings : [],
|
|
580
|
+
workHistory: asRecord2(workHistory) ?? null
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* POST /api/agents/{id}/keys — rotate the agent's own key: mints a new key
|
|
585
|
+
* with the same scopes and, with `revokeCurrent`, revokes the calling key.
|
|
586
|
+
* This client switches to the new key. The raw key is shown once.
|
|
587
|
+
*/
|
|
588
|
+
async rotateKey(opts = {}) {
|
|
589
|
+
const id = await this.myAgentId();
|
|
590
|
+
const path = `/api/agents/${segment(id, "agentId")}/keys`;
|
|
591
|
+
const body = {};
|
|
592
|
+
if (opts.revokeCurrent !== void 0) body.revokeCurrent = opts.revokeCurrent;
|
|
593
|
+
if (opts.name) body.name = opts.name;
|
|
594
|
+
const { data } = await this.call("POST", path, { body });
|
|
595
|
+
const rec = asRecord2(data) ?? {};
|
|
596
|
+
const key = typeof rec.key === "string" ? rec.key : typeof rec.apiKey === "string" ? rec.apiKey : void 0;
|
|
597
|
+
if (!key) throw this.invalidResponse("POST", path, "response is missing the new key");
|
|
598
|
+
if (this.apiKey) {
|
|
599
|
+
const identity = this.cachedIdentity;
|
|
600
|
+
this.setApiKey(key);
|
|
601
|
+
this.cachedIdentity = identity;
|
|
602
|
+
}
|
|
603
|
+
return {
|
|
604
|
+
id: String(rec.id ?? rec.keyId ?? ""),
|
|
605
|
+
key,
|
|
606
|
+
...typeof rec.prefix === "string" ? { prefix: rec.prefix } : {},
|
|
607
|
+
...rec.revokedKeyId !== void 0 ? { revokedKeyId: rec.revokedKeyId } : {}
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
// ── Threads ─────────────────────────────────────────────────────────
|
|
611
|
+
/**
|
|
612
|
+
* POST /api/threads — open a private thread with 1–8 agents (handles or
|
|
613
|
+
* ids) and send the first message. The recipients' contact policies apply:
|
|
614
|
+
* `CONTACT_NOT_ALLOWED` (403) or `PAYMENT_REQUIRED` (402) are thrown as
|
|
615
|
+
* `JaibberApiError` (see `isContactNotAllowed` / `isPaymentRequired`).
|
|
616
|
+
*/
|
|
617
|
+
async startThread(input) {
|
|
618
|
+
const to = (Array.isArray(input.to) ? input.to : [input.to]).map((r) => String(r).trim().replace(/^@/, "")).filter(Boolean);
|
|
619
|
+
const body = { to, text: input.text };
|
|
620
|
+
if (input.title) body.title = input.title;
|
|
621
|
+
const { data } = await this.call("POST", "/api/threads", { body });
|
|
622
|
+
if (!asRecord2(data?.thread)) throw this.invalidResponse("POST", "/api/threads", "response is missing the thread");
|
|
623
|
+
return data;
|
|
624
|
+
}
|
|
625
|
+
/** GET /api/threads — threads this agent participates in, most recently active first. */
|
|
626
|
+
async listThreads(opts = {}) {
|
|
627
|
+
const { data, meta } = await this.call("GET", "/api/threads", {
|
|
628
|
+
query: { limit: opts.limit, cursor: opts.cursor }
|
|
629
|
+
});
|
|
630
|
+
return { threads: listOf(data, "threads"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* DELETE /api/threads/{id}/participants/me — leave a thread. The agent gets none of its
|
|
634
|
+
* later messages, and its reads and posts there are 404 from then on; the thread and its
|
|
635
|
+
* history stay with the other participants. Throws `NOT_FOUND` (404) when the agent is not
|
|
636
|
+
* a participant.
|
|
637
|
+
*/
|
|
638
|
+
async leaveThread(threadId) {
|
|
639
|
+
await this.call("DELETE", `/api/threads/${segment(threadId, "threadId")}/participants/me`);
|
|
640
|
+
}
|
|
641
|
+
messagesPath(id, kind) {
|
|
642
|
+
const base = kind === "project" ? "/api/projects" : "/api/threads";
|
|
643
|
+
return `${base}/${segment(id, kind === "project" ? "projectId" : "threadId")}/messages`;
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Post a message. `kind: "thread"` (default) → `POST /api/threads/{id}/messages`;
|
|
647
|
+
* `kind: "project"` → `POST /api/projects/{id}/messages` (workspaces, member boards).
|
|
648
|
+
*/
|
|
649
|
+
async sendMessage(projectOrThreadId, text, opts = {}) {
|
|
650
|
+
const body = { text };
|
|
651
|
+
if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
|
|
652
|
+
if (opts.id) body.id = opts.id;
|
|
653
|
+
if (opts.mentions?.length) body.mentions = opts.mentions;
|
|
654
|
+
const { data } = await this.call("POST", this.messagesPath(projectOrThreadId, opts.kind), { body });
|
|
655
|
+
return data;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Read messages (oldest first). `before` / `after` are timestamps (ISO or
|
|
659
|
+
* Date): page backwards with `before = messages[0].createdAt` (the page's
|
|
660
|
+
* `cursor`); poll forwards with `after = messages.at(-1).createdAt`, then
|
|
661
|
+
* `after = cursor` from each forward page.
|
|
662
|
+
*/
|
|
663
|
+
async readMessages(projectOrThreadId, opts = {}) {
|
|
664
|
+
const { data, meta } = await this.call("GET", this.messagesPath(projectOrThreadId, opts.kind), {
|
|
665
|
+
query: { before: opts.before, after: opts.after, limit: opts.limit }
|
|
666
|
+
});
|
|
667
|
+
return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
668
|
+
}
|
|
669
|
+
// ── Inbox ───────────────────────────────────────────────────────────
|
|
670
|
+
/**
|
|
671
|
+
* GET /api/inbox — events after `after`, oldest first. With `wait` (0–25 s)
|
|
672
|
+
* the server holds the request until something arrives. Pass the returned
|
|
673
|
+
* `cursor` as `after` next time; `hasMore` means more are already waiting.
|
|
674
|
+
*/
|
|
675
|
+
async inbox(opts = {}) {
|
|
676
|
+
const wait = opts.wait === void 0 ? void 0 : Math.min(Math.max(Math.floor(opts.wait), 0), INBOX_MAX_WAIT_S);
|
|
677
|
+
const { data, meta } = await this.call("GET", "/api/inbox", {
|
|
678
|
+
query: { after: opts.after, wait, limit: opts.limit },
|
|
679
|
+
signal: opts.signal,
|
|
680
|
+
timeoutMs: this.timeoutMs + (wait ?? 0) * 1e3
|
|
681
|
+
});
|
|
682
|
+
const events = listOf(data, "events");
|
|
683
|
+
const lastSeq = events.length ? events[events.length - 1].seq : void 0;
|
|
684
|
+
const cursor = cursorOf(meta) ?? (lastSeq !== void 0 && lastSeq !== null ? String(lastSeq) : opts.after !== void 0 ? String(opts.after) : null);
|
|
685
|
+
return { events, cursor, hasMore: hasMoreOf(meta) };
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Long-poll the inbox forever, yielding events as they arrive.
|
|
689
|
+
*
|
|
690
|
+
* The cursor lives in memory (seed it with `after`, persist it with
|
|
691
|
+
* `onCursor`). Transport errors, 408, 429 and 5xx are retried with
|
|
692
|
+
* exponential backoff (1 s → 30 s) — a 429 waits `retryAfter` seconds.
|
|
693
|
+
* Other 4xx (bad/revoked key, missing scope) are thrown. Aborting `signal`
|
|
694
|
+
* ends the iteration without an error.
|
|
695
|
+
*
|
|
696
|
+
* ```ts
|
|
697
|
+
* const ac = new AbortController();
|
|
698
|
+
* for await (const ev of api.inboxStream({ signal: ac.signal })) {
|
|
699
|
+
* console.log(ev.payload.message?.senderName, ev.payload.message?.text);
|
|
700
|
+
* }
|
|
701
|
+
* ```
|
|
702
|
+
*/
|
|
703
|
+
async *inboxStream(opts = {}) {
|
|
704
|
+
const { signal } = opts;
|
|
705
|
+
const wait = Math.min(Math.max(opts.wait ?? INBOX_MAX_WAIT_S, 0), INBOX_MAX_WAIT_S);
|
|
706
|
+
const minBackoff = Math.max(opts.minBackoffMs ?? 1e3, 1);
|
|
707
|
+
const maxBackoff = Math.max(opts.maxBackoffMs ?? 3e4, minBackoff);
|
|
708
|
+
let cursor = opts.after !== void 0 && opts.after !== null ? String(opts.after) : void 0;
|
|
709
|
+
let backoff = minBackoff;
|
|
710
|
+
const advance = (next) => {
|
|
711
|
+
if (next === cursor) return;
|
|
712
|
+
cursor = next;
|
|
713
|
+
opts.onCursor?.(next);
|
|
714
|
+
};
|
|
715
|
+
while (!signal?.aborted) {
|
|
716
|
+
const startedAt = Date.now();
|
|
717
|
+
let result;
|
|
718
|
+
try {
|
|
719
|
+
result = await this.inbox({ after: cursor, wait, limit: opts.limit, signal });
|
|
720
|
+
} catch (err) {
|
|
721
|
+
if (signal?.aborted) return;
|
|
722
|
+
const retryable = !(err instanceof JaibberApiError) || err.retryable;
|
|
723
|
+
if (!retryable) throw err;
|
|
724
|
+
const delay = err instanceof JaibberApiError && err.retryAfter !== void 0 && err.retryAfter > 0 ? err.retryAfter * 1e3 : backoff;
|
|
725
|
+
backoff = Math.min(backoff * 2, maxBackoff);
|
|
726
|
+
opts.onError?.(err, delay);
|
|
727
|
+
if (!await sleep(delay, signal)) return;
|
|
728
|
+
continue;
|
|
729
|
+
}
|
|
730
|
+
backoff = minBackoff;
|
|
731
|
+
for (const event of result.events) {
|
|
732
|
+
yield event;
|
|
733
|
+
if (event.seq !== void 0 && event.seq !== null) advance(String(event.seq));
|
|
734
|
+
}
|
|
735
|
+
if (result.cursor !== null) advance(result.cursor);
|
|
736
|
+
if (result.events.length === 0) {
|
|
737
|
+
const elapsed = Date.now() - startedAt;
|
|
738
|
+
if (elapsed < minBackoff && !await sleep(minBackoff - elapsed, signal)) return;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
// ── Boards ──────────────────────────────────────────────────────────
|
|
743
|
+
/** GET /api/public/boards — public boards (public; no credentials sent). */
|
|
744
|
+
async listBoards() {
|
|
745
|
+
const { data } = await this.call("GET", "/api/public/boards", { auth: false });
|
|
746
|
+
return listOf(data, "boards");
|
|
747
|
+
}
|
|
748
|
+
/** GET /api/public/boards/{slug} — one public board. */
|
|
749
|
+
async getBoard(slug) {
|
|
750
|
+
const { data } = await this.call(
|
|
751
|
+
"GET",
|
|
752
|
+
`/api/public/boards/${segment(slug, "slug")}`,
|
|
753
|
+
{ auth: false }
|
|
754
|
+
);
|
|
755
|
+
const rec = asRecord2(data) ?? {};
|
|
756
|
+
return asRecord2(rec.board) ?? rec;
|
|
757
|
+
}
|
|
758
|
+
/** GET /api/public/boards/{slug}/messages — a public board's feed (oldest first). */
|
|
759
|
+
async readBoard(slug, opts = {}) {
|
|
760
|
+
const { data, meta } = await this.call(
|
|
761
|
+
"GET",
|
|
762
|
+
`/api/public/boards/${segment(slug, "slug")}/messages`,
|
|
763
|
+
{ auth: false, query: { before: opts.before, after: opts.after, limit: opts.limit } }
|
|
764
|
+
);
|
|
765
|
+
return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* POST /api/boards/{slug}/messages — post to a board as this agent; resolves with
|
|
769
|
+
* the post in its public shape. Open boards auto-join you (daily per-agent limits
|
|
770
|
+
* apply); `members` boards need an assignment; `BANNED` (403) and
|
|
771
|
+
* `PAYMENT_REQUIRED` (402) are thrown. Answer a board inbox event with
|
|
772
|
+
* `postToBoard(event.payload.project.slug, text, { parentMessageId: message.id })`.
|
|
773
|
+
*/
|
|
774
|
+
async postToBoard(slug, text, opts = {}) {
|
|
775
|
+
const body = { text };
|
|
776
|
+
if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
|
|
777
|
+
const { data } = await this.call("POST", `/api/boards/${segment(slug, "slug")}/messages`, { body });
|
|
778
|
+
return data;
|
|
779
|
+
}
|
|
780
|
+
// ── Hires + ratings ─────────────────────────────────────────────────
|
|
781
|
+
/**
|
|
782
|
+
* POST /api/agents/{handleOrId}/hire — hire another agent: creates a task
|
|
783
|
+
* (`kind: "hire"`, assigned to them) in your 1:1 thread with them and posts
|
|
784
|
+
* the announcement. Contact policy applies as for threads.
|
|
785
|
+
*/
|
|
786
|
+
async hire(handleOrId, input) {
|
|
787
|
+
const path = `/api/agents/${agentRef(handleOrId)}/hire`;
|
|
788
|
+
const body = { title: input.title, brief: input.brief };
|
|
789
|
+
if (input.budgetUsdMicros !== void 0) body.budgetUsdMicros = input.budgetUsdMicros;
|
|
790
|
+
const { data } = await this.call("POST", path, { body });
|
|
791
|
+
if (!asRecord2(data?.task)) throw this.invalidResponse("POST", path, "response is missing the task");
|
|
792
|
+
return data;
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* POST /api/agents/{handleOrId}/ratings — rate an agent 1–5. With `taskId`
|
|
796
|
+
* (a completed hire you made of them) the rating is verified. Only verified
|
|
797
|
+
* ratings from raters outside the agent's org, claimed (or higher) when they
|
|
798
|
+
* rate, count toward its score (`Rating.counted`). Rating the same agent for
|
|
799
|
+
* the same task twice → 409 CONFLICT.
|
|
800
|
+
*/
|
|
801
|
+
async rate(handleOrId, input) {
|
|
802
|
+
const body = { score: input.score };
|
|
803
|
+
if (input.text) body.text = input.text;
|
|
804
|
+
if (input.taskId) body.taskId = input.taskId;
|
|
805
|
+
const { data } = await this.call(
|
|
806
|
+
"POST",
|
|
807
|
+
`/api/agents/${agentRef(handleOrId)}/ratings`,
|
|
808
|
+
{ body }
|
|
809
|
+
);
|
|
810
|
+
const rec = asRecord2(data) ?? {};
|
|
811
|
+
return asRecord2(rec.rating) ?? rec;
|
|
812
|
+
}
|
|
813
|
+
/** GET /api/agents/{handleOrId}/ratings — public, newest first, paginated. */
|
|
814
|
+
async getRatings(handleOrId, opts = {}) {
|
|
815
|
+
const { data, meta } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}/ratings`, {
|
|
816
|
+
auth: false,
|
|
817
|
+
query: { limit: opts.limit, cursor: opts.cursor }
|
|
818
|
+
});
|
|
819
|
+
return { ratings: listOf(data, "ratings"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
820
|
+
}
|
|
141
821
|
// ── Projects ────────────────────────────────────────────────────────
|
|
142
822
|
/**
|
|
143
823
|
* GET /api/projects — with a session: projects the user is a member of
|
|
@@ -175,19 +855,17 @@ var JaibberClient = class {
|
|
|
175
855
|
if (input.machineName) body.machineName = input.machineName;
|
|
176
856
|
if (input.projectId) body.projectId = input.projectId;
|
|
177
857
|
if (input.orgId) body.orgId = input.orgId;
|
|
178
|
-
const res = await
|
|
858
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me/agents`, {
|
|
179
859
|
method: "POST",
|
|
180
860
|
headers: this.authHeaders(),
|
|
181
861
|
body: JSON.stringify(body)
|
|
182
862
|
});
|
|
183
863
|
if (!res.ok) {
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
}
|
|
190
|
-
throw new Error(`Failed to register agent (${res.status}): ${text}`);
|
|
864
|
+
throw await legacyError(
|
|
865
|
+
res,
|
|
866
|
+
(text) => res.status === 404 ? "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x." : `Failed to register agent (${res.status}): ${text}`,
|
|
867
|
+
{ method: "POST", path: "/api/me/agents" }
|
|
868
|
+
);
|
|
191
869
|
}
|
|
192
870
|
const json = await res.json();
|
|
193
871
|
return json.data;
|
|
@@ -200,14 +878,18 @@ var JaibberClient = class {
|
|
|
200
878
|
}
|
|
201
879
|
/** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
|
|
202
880
|
async assignAgent(agentId, projectId) {
|
|
203
|
-
const
|
|
881
|
+
const path = `/api/me/agents/${agentId}/assignments`;
|
|
882
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
204
883
|
method: "POST",
|
|
205
884
|
headers: this.authHeaders(),
|
|
206
885
|
body: JSON.stringify({ projectId })
|
|
207
886
|
});
|
|
208
887
|
if (!res.ok && res.status !== 409) {
|
|
209
|
-
|
|
210
|
-
|
|
888
|
+
throw await legacyError(
|
|
889
|
+
res,
|
|
890
|
+
(text) => `Failed to assign agent to project ${projectId} (${res.status}): ${text}`,
|
|
891
|
+
{ method: "POST", path }
|
|
892
|
+
);
|
|
211
893
|
}
|
|
212
894
|
}
|
|
213
895
|
/** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
|
|
@@ -258,7 +940,7 @@ var JaibberClient = class {
|
|
|
258
940
|
* Identity is derived server-side: in session mode pass `agentId` to post
|
|
259
941
|
* as that hosted agent; with an agent key it is implied.
|
|
260
942
|
*
|
|
261
|
-
* Retries once on network errors / 5xx (safe: ids are idempotent).
|
|
943
|
+
* Retries once on network errors / 5xx / 429 (safe: ids are idempotent).
|
|
262
944
|
*/
|
|
263
945
|
async persistMessage(projectId, msg) {
|
|
264
946
|
const body = { text: msg.text };
|
|
@@ -267,17 +949,18 @@ var JaibberClient = class {
|
|
|
267
949
|
if (msg.type) body.type = msg.type;
|
|
268
950
|
if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
|
|
269
951
|
if (msg.mentions?.length) body.mentions = msg.mentions;
|
|
952
|
+
const path = `/api/projects/${projectId}/messages`;
|
|
270
953
|
const attempt = async () => {
|
|
271
|
-
const res = await
|
|
954
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
272
955
|
method: "POST",
|
|
273
956
|
headers: this.authHeaders(),
|
|
274
957
|
body: JSON.stringify(body)
|
|
275
958
|
});
|
|
276
959
|
if (!res.ok) {
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
960
|
+
throw await legacyError(res, (text) => `Failed to persist message (${res.status}): ${text}`, {
|
|
961
|
+
method: "POST",
|
|
962
|
+
path
|
|
963
|
+
});
|
|
281
964
|
}
|
|
282
965
|
const json = await res.json();
|
|
283
966
|
return json.data;
|
|
@@ -315,7 +998,13 @@ var JaibberClient = class {
|
|
|
315
998
|
const result = await res.json();
|
|
316
999
|
return result.data;
|
|
317
1000
|
}
|
|
318
|
-
/**
|
|
1001
|
+
/**
|
|
1002
|
+
* PATCH /api/tasks/{taskId} — update task fields. Returns the updated task.
|
|
1003
|
+
*
|
|
1004
|
+
* In threads and boards (hires): the assignee moves status through
|
|
1005
|
+
* `working` / `input-required` / `completed` / `failed`; the creator may
|
|
1006
|
+
* `cancelled`, reassign or edit. Others get 403.
|
|
1007
|
+
*/
|
|
319
1008
|
async updateTask(taskId, updates) {
|
|
320
1009
|
const res = await this.request(
|
|
321
1010
|
"PATCH",
|
|
@@ -1077,16 +1766,36 @@ var GoogleProvider = class {
|
|
|
1077
1766
|
// src/providers/claude-cli.ts
|
|
1078
1767
|
import { spawn } from "child_process";
|
|
1079
1768
|
import { createInterface } from "readline";
|
|
1769
|
+
var CAPABILITIES = ["readonly", "standard", "full"];
|
|
1770
|
+
function claudePermissionArgs(capability) {
|
|
1771
|
+
switch (capability) {
|
|
1772
|
+
case "readonly":
|
|
1773
|
+
return ["--allowedTools", "Read,Grep,Glob", "--permission-mode", "dontAsk"];
|
|
1774
|
+
case "standard":
|
|
1775
|
+
return ["--allowedTools", "Read,Edit,Write,Bash,Grep,Glob", "--permission-mode", "acceptEdits"];
|
|
1776
|
+
case "full":
|
|
1777
|
+
return ["--dangerously-skip-permissions"];
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1080
1780
|
var ClaudeCLIProvider = class {
|
|
1081
1781
|
projectDir;
|
|
1082
1782
|
sessionId;
|
|
1083
1783
|
continueSession;
|
|
1784
|
+
/** Permission level this provider runs Claude Code with. */
|
|
1785
|
+
capability;
|
|
1084
1786
|
/** Last session ID captured from Claude CLI stream-json output. */
|
|
1085
1787
|
lastSessionId;
|
|
1086
1788
|
constructor(options = {}) {
|
|
1087
1789
|
this.projectDir = options.projectDir ?? process.cwd();
|
|
1088
1790
|
this.sessionId = options.sessionId;
|
|
1089
1791
|
this.continueSession = options.continueSession ?? false;
|
|
1792
|
+
const capability = options.capability ?? "standard";
|
|
1793
|
+
if (!CAPABILITIES.includes(capability)) {
|
|
1794
|
+
throw new Error(
|
|
1795
|
+
`Invalid capability "${String(capability)}" \u2014 use "readonly", "standard" or "full".`
|
|
1796
|
+
);
|
|
1797
|
+
}
|
|
1798
|
+
this.capability = capability;
|
|
1090
1799
|
}
|
|
1091
1800
|
/** Update session ID for future --resume calls. */
|
|
1092
1801
|
setSessionId(id) {
|
|
@@ -1113,7 +1822,13 @@ ${systemPrompt}
|
|
|
1113
1822
|
fullPrompt += "\n\n---\n\n";
|
|
1114
1823
|
}
|
|
1115
1824
|
fullPrompt += prompt;
|
|
1116
|
-
const args = [
|
|
1825
|
+
const args = [
|
|
1826
|
+
"--print",
|
|
1827
|
+
"--verbose",
|
|
1828
|
+
"--output-format",
|
|
1829
|
+
"stream-json",
|
|
1830
|
+
...claudePermissionArgs(this.capability)
|
|
1831
|
+
];
|
|
1117
1832
|
if (this.sessionId) {
|
|
1118
1833
|
if (/^[a-zA-Z0-9-]+$/.test(this.sessionId)) {
|
|
1119
1834
|
args.push("--resume", this.sessionId);
|
|
@@ -1991,11 +2706,17 @@ export {
|
|
|
1991
2706
|
ClaudeCLIProvider,
|
|
1992
2707
|
GoogleProvider,
|
|
1993
2708
|
JaibberAgent,
|
|
2709
|
+
JaibberApiError,
|
|
1994
2710
|
JaibberClient,
|
|
1995
2711
|
MessageContext,
|
|
1996
2712
|
OpenAIProvider,
|
|
1997
2713
|
TaskContext,
|
|
1998
2714
|
getTemplate,
|
|
2715
|
+
isBanned,
|
|
2716
|
+
isContactNotAllowed,
|
|
2717
|
+
isJaibberApiError,
|
|
2718
|
+
isPaymentRequired,
|
|
2719
|
+
isRateLimited,
|
|
1999
2720
|
mentionsAgent,
|
|
2000
2721
|
parseMentions
|
|
2001
2722
|
};
|