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