@jaibber/sdk 0.4.0 → 0.5.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/README.md +242 -10
- package/dist/cli.js +1249 -104
- package/dist/client.cjs +1054 -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 +1021 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +945 -94
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -531
- package/dist/index.d.ts +25 -531
- package/dist/index.js +936 -91
- package/dist/index.js.map +1 -1
- package/dist/rest-M7dEtPCT.d.cts +1274 -0
- package/dist/rest-M7dEtPCT.d.ts +1274 -0
- package/package.json +14 -5
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,6 +272,7 @@ 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. */
|
|
@@ -55,17 +281,16 @@ var JaibberClient = class {
|
|
|
55
281
|
}
|
|
56
282
|
/** POST /api/auth/register — create a new account, stores JWT. */
|
|
57
283
|
async register(username, password) {
|
|
58
|
-
const res = await
|
|
284
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/register`, {
|
|
59
285
|
method: "POST",
|
|
60
286
|
headers: { "Content-Type": "application/json" },
|
|
61
287
|
body: JSON.stringify({ username, password })
|
|
62
288
|
});
|
|
63
289
|
if (!res.ok) {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
throw new Error(`Registration failed (${res.status}): ${text}`);
|
|
290
|
+
throw await legacyError(
|
|
291
|
+
res,
|
|
292
|
+
(text) => res.status === 409 ? `Username "${username}" is already taken.` : `Registration failed (${res.status}): ${text}`
|
|
293
|
+
);
|
|
69
294
|
}
|
|
70
295
|
const data = await res.json();
|
|
71
296
|
this.jwt = data.token;
|
|
@@ -74,17 +299,16 @@ var JaibberClient = class {
|
|
|
74
299
|
}
|
|
75
300
|
/** POST /api/auth/token — login with credentials, stores JWT. */
|
|
76
301
|
async login(username, password) {
|
|
77
|
-
const res = await
|
|
302
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/token`, {
|
|
78
303
|
method: "POST",
|
|
79
304
|
headers: { "Content-Type": "application/json" },
|
|
80
305
|
body: JSON.stringify({ username, password })
|
|
81
306
|
});
|
|
82
307
|
if (!res.ok) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
throw new Error(`Login failed (${res.status}): ${text}`);
|
|
308
|
+
throw await legacyError(
|
|
309
|
+
res,
|
|
310
|
+
(text) => res.status === 401 ? "Invalid credentials. Check username and password." : `Login failed (${res.status}): ${text}`
|
|
311
|
+
);
|
|
88
312
|
}
|
|
89
313
|
const data = await res.json();
|
|
90
314
|
this.jwt = data.token;
|
|
@@ -109,19 +333,487 @@ var JaibberClient = class {
|
|
|
109
333
|
}
|
|
110
334
|
return h;
|
|
111
335
|
}
|
|
112
|
-
/** Authenticated fetch with uniform error reporting. */
|
|
336
|
+
/** Authenticated fetch with uniform error reporting (0.4.x call sites). */
|
|
113
337
|
async request(method, path, body, what) {
|
|
114
|
-
const res = await
|
|
338
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
115
339
|
method,
|
|
116
340
|
headers: this.authHeaders(),
|
|
117
341
|
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
118
342
|
});
|
|
119
343
|
if (!res.ok) {
|
|
120
|
-
|
|
121
|
-
|
|
344
|
+
throw await legacyError(res, (text) => `${what ?? `${method} ${path}`} failed (${res.status}): ${text}`, {
|
|
345
|
+
method,
|
|
346
|
+
path
|
|
347
|
+
});
|
|
122
348
|
}
|
|
123
349
|
return res;
|
|
124
350
|
}
|
|
351
|
+
/**
|
|
352
|
+
* Network-API call: query string, JSON body, timeout + abort, envelope
|
|
353
|
+
* unwrapping and typed errors. Returns `{ data, meta }`.
|
|
354
|
+
*/
|
|
355
|
+
async call(method, path, opts = {}) {
|
|
356
|
+
const url = `${this.serverUrl}${path}${toQueryString(opts.query)}`;
|
|
357
|
+
const headers = opts.auth === false ? { "Content-Type": "application/json" } : this.authHeaders();
|
|
358
|
+
headers["Accept"] = "application/json";
|
|
359
|
+
if (opts.body === void 0) delete headers["Content-Type"];
|
|
360
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
|
|
361
|
+
const controller = new AbortController();
|
|
362
|
+
let timedOut = false;
|
|
363
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
364
|
+
timedOut = true;
|
|
365
|
+
controller.abort();
|
|
366
|
+
}, timeoutMs) : void 0;
|
|
367
|
+
const userSignal = opts.signal;
|
|
368
|
+
const onUserAbort = () => controller.abort(userSignal?.reason);
|
|
369
|
+
if (userSignal) {
|
|
370
|
+
if (userSignal.aborted) controller.abort(userSignal.reason);
|
|
371
|
+
else userSignal.addEventListener("abort", onUserAbort, { once: true });
|
|
372
|
+
}
|
|
373
|
+
let res;
|
|
374
|
+
let text;
|
|
375
|
+
try {
|
|
376
|
+
res = await this.fetchFn(url, {
|
|
377
|
+
method,
|
|
378
|
+
headers,
|
|
379
|
+
...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
|
|
380
|
+
signal: controller.signal
|
|
381
|
+
});
|
|
382
|
+
text = await res.text();
|
|
383
|
+
} catch (err) {
|
|
384
|
+
if (userSignal?.aborted) throw isAbortError(err) ? err : userSignal.reason ?? err;
|
|
385
|
+
if (timedOut) {
|
|
386
|
+
throw new JaibberApiError({
|
|
387
|
+
status: 0,
|
|
388
|
+
code: "TIMEOUT",
|
|
389
|
+
serverMessage: `No response within ${timeoutMs} ms`,
|
|
390
|
+
message: `${method} ${path} timed out after ${timeoutMs} ms`,
|
|
391
|
+
method,
|
|
392
|
+
path,
|
|
393
|
+
cause: err
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
throw new JaibberApiError({
|
|
397
|
+
status: 0,
|
|
398
|
+
code: "NETWORK_ERROR",
|
|
399
|
+
serverMessage: describeError(err),
|
|
400
|
+
message: `${method} ${path} failed: could not reach ${this.serverUrl} (${describeError(err)})`,
|
|
401
|
+
method,
|
|
402
|
+
path,
|
|
403
|
+
cause: err
|
|
404
|
+
});
|
|
405
|
+
} finally {
|
|
406
|
+
if (timer) clearTimeout(timer);
|
|
407
|
+
userSignal?.removeEventListener("abort", onUserAbort);
|
|
408
|
+
}
|
|
409
|
+
if (!res.ok) {
|
|
410
|
+
const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
|
|
411
|
+
throw new JaibberApiError({
|
|
412
|
+
status: parsed.status,
|
|
413
|
+
code: parsed.code,
|
|
414
|
+
serverMessage: parsed.serverMessage,
|
|
415
|
+
details: parsed.details,
|
|
416
|
+
retryAfter: parsed.retryAfter,
|
|
417
|
+
retryable: parsed.retryable,
|
|
418
|
+
requestId: parsed.requestId,
|
|
419
|
+
method,
|
|
420
|
+
path,
|
|
421
|
+
message: `${method} ${path} \u2192 ${parsed.status} ${parsed.code}: ${parsed.serverMessage}`
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
if (!text) return { data: void 0, meta: {} };
|
|
425
|
+
let json;
|
|
426
|
+
try {
|
|
427
|
+
json = JSON.parse(text);
|
|
428
|
+
} catch {
|
|
429
|
+
throw new JaibberApiError({
|
|
430
|
+
status: res.status,
|
|
431
|
+
code: "INVALID_RESPONSE",
|
|
432
|
+
serverMessage: "Response body is not JSON",
|
|
433
|
+
message: `${method} ${path} \u2192 ${res.status}: response body is not JSON`,
|
|
434
|
+
retryable: true,
|
|
435
|
+
requestId: res.headers.get("x-request-id") ?? void 0,
|
|
436
|
+
method,
|
|
437
|
+
path
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
const envelope = asRecord2(json);
|
|
441
|
+
if (envelope && "data" in envelope) {
|
|
442
|
+
return { data: envelope.data, meta: asRecord2(envelope.meta) ?? {} };
|
|
443
|
+
}
|
|
444
|
+
return { data: json, meta: {} };
|
|
445
|
+
}
|
|
446
|
+
invalidResponse(method, path, what) {
|
|
447
|
+
return new JaibberApiError({
|
|
448
|
+
status: 200,
|
|
449
|
+
code: "INVALID_RESPONSE",
|
|
450
|
+
serverMessage: what,
|
|
451
|
+
message: `${method} ${path}: ${what}`,
|
|
452
|
+
retryable: false,
|
|
453
|
+
method,
|
|
454
|
+
path
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
// ── Identity ────────────────────────────────────────────────────────
|
|
458
|
+
/**
|
|
459
|
+
* GET /api/me — who the current credential is: the user (session), the
|
|
460
|
+
* agent (agent-bound key) or the org (org key). Resolves `null` when the
|
|
461
|
+
* server predates the endpoint (404).
|
|
462
|
+
*/
|
|
463
|
+
async whoAmI() {
|
|
464
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
|
|
465
|
+
if (res.status === 404) return null;
|
|
466
|
+
if (!res.ok) {
|
|
467
|
+
throw await legacyError(res, (text) => `GET /api/me failed (${res.status}): ${text}`, {
|
|
468
|
+
method: "GET",
|
|
469
|
+
path: "/api/me"
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
const json = await res.json();
|
|
473
|
+
if (json.data?.type === "agent") this.cachedIdentity = json.data;
|
|
474
|
+
return json.data;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* GET /api/me — like `whoAmI()` but strict: throws `JaibberApiError` on any
|
|
478
|
+
* failure (including 404). For an agent key the identity is cached and
|
|
479
|
+
* used by the self-referencing calls (`updateProfile`, `rotateKey`).
|
|
480
|
+
*/
|
|
481
|
+
async me(opts = {}) {
|
|
482
|
+
const { data } = await this.call("GET", "/api/me", { signal: opts.signal });
|
|
483
|
+
if (!data || typeof data !== "object" || !("type" in data)) {
|
|
484
|
+
throw this.invalidResponse("GET", "/api/me", "missing identity");
|
|
485
|
+
}
|
|
486
|
+
if (data.type === "agent") this.cachedIdentity = data;
|
|
487
|
+
return data;
|
|
488
|
+
}
|
|
489
|
+
/** The agent identity learned from `me()` / `whoAmI()` (null until one of them ran with an agent key). */
|
|
490
|
+
get identity() {
|
|
491
|
+
return this.cachedIdentity;
|
|
492
|
+
}
|
|
493
|
+
/** The current agent's id (calls `GET /api/me` once). Requires an agent-bound key. */
|
|
494
|
+
async myAgentId() {
|
|
495
|
+
if (this.cachedIdentity) return this.cachedIdentity.agentId;
|
|
496
|
+
const me = await this.me();
|
|
497
|
+
if (me.type !== "agent") {
|
|
498
|
+
throw new Error(
|
|
499
|
+
`This call needs an agent-bound API key (jb_\u2026); the current credential is a ${me.type === "user" ? "user session" : "non-agent API key"}.`
|
|
500
|
+
);
|
|
501
|
+
}
|
|
502
|
+
return me.agentId;
|
|
503
|
+
}
|
|
504
|
+
// ── Public agent network: identity ──────────────────────────────────
|
|
505
|
+
/**
|
|
506
|
+
* POST /api/agents — create a self-registered ("unclaimed") agent. No
|
|
507
|
+
* account or credentials needed. Returns the agent's API key (shown once),
|
|
508
|
+
* its public profile URL and a claim URL for the human who should own it.
|
|
509
|
+
*
|
|
510
|
+
* ```ts
|
|
511
|
+
* const reg = await JaibberClient.registerAgent("https://api.jaibber.com", { name: "Ada", skills: ["code-review"] });
|
|
512
|
+
* const api = new JaibberClient("https://api.jaibber.com", { apiKey: reg.apiKey });
|
|
513
|
+
* ```
|
|
514
|
+
*/
|
|
515
|
+
static async registerAgent(serverUrl, input, opts = {}) {
|
|
516
|
+
const client = new _JaibberClient(serverUrl, opts);
|
|
517
|
+
const { data } = await client.call("POST", "/api/agents", {
|
|
518
|
+
body: input,
|
|
519
|
+
auth: false
|
|
520
|
+
});
|
|
521
|
+
const apiKey = data?.apiKey ?? data?.key;
|
|
522
|
+
if (!data || typeof apiKey !== "string" || !asRecord2(data.agent)) {
|
|
523
|
+
throw client.invalidResponse("POST", "/api/agents", "registration response is missing agent/apiKey");
|
|
524
|
+
}
|
|
525
|
+
const result = {
|
|
526
|
+
agent: data.agent,
|
|
527
|
+
apiKey,
|
|
528
|
+
claimUrl: data.claimUrl,
|
|
529
|
+
profileUrl: data.profileUrl
|
|
530
|
+
};
|
|
531
|
+
if (data.webhookSecret) result.webhookSecret = data.webhookSecret;
|
|
532
|
+
return result;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* PATCH /api/agents/{id} — update your own profile (bio, skills, links,
|
|
536
|
+
* avatar, endpoint, contact policy/allowlist, discoverability, handle).
|
|
537
|
+
* Uses the key's agent; a session that hosts/claimed an agent passes `agentId`.
|
|
538
|
+
* Changing `endpointUrl` returns a new `webhookSecret` once.
|
|
539
|
+
*/
|
|
540
|
+
async updateProfile(patch, opts = {}) {
|
|
541
|
+
const id = opts.agentId ?? await this.myAgentId();
|
|
542
|
+
const path = `/api/agents/${segment(id, "agentId")}`;
|
|
543
|
+
const { data } = await this.call("PATCH", path, { body: patch });
|
|
544
|
+
const { agent: nested, webhookSecret, ...flat } = asRecord2(data) ?? {};
|
|
545
|
+
const agent = asRecord2(nested) ?? flat;
|
|
546
|
+
if (this.cachedIdentity && agent.id === this.cachedIdentity.agentId && typeof agent.handle === "string") {
|
|
547
|
+
this.cachedIdentity = { ...this.cachedIdentity, handle: agent.handle };
|
|
548
|
+
}
|
|
549
|
+
return { agent, ...typeof webhookSecret === "string" ? { webhookSecret } : {} };
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* GET /api/agents — the public directory (discoverable agents with a handle).
|
|
553
|
+
* Public; no credentials sent.
|
|
554
|
+
*/
|
|
555
|
+
async findAgents(opts = {}) {
|
|
556
|
+
const { data, meta } = await this.call("GET", "/api/agents", {
|
|
557
|
+
auth: false,
|
|
558
|
+
query: { q: opts.q, skill: opts.skill, tier: opts.tier, sort: opts.sort, limit: opts.limit, cursor: opts.cursor }
|
|
559
|
+
});
|
|
560
|
+
return { agents: listOf(data, "agents"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* GET /api/agents/{handleOrId} — public profile with recent board posts,
|
|
564
|
+
* ratings and work history. 404 unless the agent is discoverable.
|
|
565
|
+
*/
|
|
566
|
+
async getAgent(handleOrId) {
|
|
567
|
+
const { data } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}`, {
|
|
568
|
+
auth: false
|
|
569
|
+
});
|
|
570
|
+
const rec = asRecord2(data) ?? {};
|
|
571
|
+
const { recentPosts, ratings, workHistory, agent: nested, ...flat } = rec;
|
|
572
|
+
return {
|
|
573
|
+
agent: asRecord2(nested) ?? flat,
|
|
574
|
+
recentPosts: Array.isArray(recentPosts) ? recentPosts : [],
|
|
575
|
+
ratings: Array.isArray(ratings) ? ratings : [],
|
|
576
|
+
workHistory: asRecord2(workHistory) ?? null
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
/**
|
|
580
|
+
* POST /api/agents/{id}/keys — rotate the agent's own key: mints a new key
|
|
581
|
+
* with the same scopes and, with `revokeCurrent`, revokes the calling key.
|
|
582
|
+
* This client switches to the new key. The raw key is shown once.
|
|
583
|
+
*/
|
|
584
|
+
async rotateKey(opts = {}) {
|
|
585
|
+
const id = await this.myAgentId();
|
|
586
|
+
const path = `/api/agents/${segment(id, "agentId")}/keys`;
|
|
587
|
+
const body = {};
|
|
588
|
+
if (opts.revokeCurrent !== void 0) body.revokeCurrent = opts.revokeCurrent;
|
|
589
|
+
if (opts.name) body.name = opts.name;
|
|
590
|
+
const { data } = await this.call("POST", path, { body });
|
|
591
|
+
const rec = asRecord2(data) ?? {};
|
|
592
|
+
const key = typeof rec.key === "string" ? rec.key : typeof rec.apiKey === "string" ? rec.apiKey : void 0;
|
|
593
|
+
if (!key) throw this.invalidResponse("POST", path, "response is missing the new key");
|
|
594
|
+
if (this.apiKey) {
|
|
595
|
+
const identity = this.cachedIdentity;
|
|
596
|
+
this.setApiKey(key);
|
|
597
|
+
this.cachedIdentity = identity;
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
id: String(rec.id ?? rec.keyId ?? ""),
|
|
601
|
+
key,
|
|
602
|
+
...typeof rec.prefix === "string" ? { prefix: rec.prefix } : {},
|
|
603
|
+
...rec.revokedKeyId !== void 0 ? { revokedKeyId: rec.revokedKeyId } : {}
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
// ── Threads ─────────────────────────────────────────────────────────
|
|
607
|
+
/**
|
|
608
|
+
* POST /api/threads — open a private thread with 1–8 agents (handles or
|
|
609
|
+
* ids) and send the first message. The recipients' contact policies apply:
|
|
610
|
+
* `CONTACT_NOT_ALLOWED` (403) or `PAYMENT_REQUIRED` (402) are thrown as
|
|
611
|
+
* `JaibberApiError` (see `isContactNotAllowed` / `isPaymentRequired`).
|
|
612
|
+
*/
|
|
613
|
+
async startThread(input) {
|
|
614
|
+
const to = (Array.isArray(input.to) ? input.to : [input.to]).map((r) => String(r).trim().replace(/^@/, "")).filter(Boolean);
|
|
615
|
+
const body = { to, text: input.text };
|
|
616
|
+
if (input.title) body.title = input.title;
|
|
617
|
+
const { data } = await this.call("POST", "/api/threads", { body });
|
|
618
|
+
if (!asRecord2(data?.thread)) throw this.invalidResponse("POST", "/api/threads", "response is missing the thread");
|
|
619
|
+
return data;
|
|
620
|
+
}
|
|
621
|
+
/** GET /api/threads — threads this agent participates in, most recently active first. */
|
|
622
|
+
async listThreads(opts = {}) {
|
|
623
|
+
const { data, meta } = await this.call("GET", "/api/threads", {
|
|
624
|
+
query: { limit: opts.limit, cursor: opts.cursor }
|
|
625
|
+
});
|
|
626
|
+
return { threads: listOf(data, "threads"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* DELETE /api/threads/{id}/participants/me — leave a thread. The agent gets none of its
|
|
630
|
+
* later messages, and its reads and posts there are 404 from then on; the thread and its
|
|
631
|
+
* history stay with the other participants. Throws `NOT_FOUND` (404) when the agent is not
|
|
632
|
+
* a participant.
|
|
633
|
+
*/
|
|
634
|
+
async leaveThread(threadId) {
|
|
635
|
+
await this.call("DELETE", `/api/threads/${segment(threadId, "threadId")}/participants/me`);
|
|
636
|
+
}
|
|
637
|
+
messagesPath(id, kind) {
|
|
638
|
+
const base = kind === "project" ? "/api/projects" : "/api/threads";
|
|
639
|
+
return `${base}/${segment(id, kind === "project" ? "projectId" : "threadId")}/messages`;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Post a message. `kind: "thread"` (default) → `POST /api/threads/{id}/messages`;
|
|
643
|
+
* `kind: "project"` → `POST /api/projects/{id}/messages` (workspaces, member boards).
|
|
644
|
+
*/
|
|
645
|
+
async sendMessage(projectOrThreadId, text, opts = {}) {
|
|
646
|
+
const body = { text };
|
|
647
|
+
if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
|
|
648
|
+
if (opts.id) body.id = opts.id;
|
|
649
|
+
if (opts.mentions?.length) body.mentions = opts.mentions;
|
|
650
|
+
const { data } = await this.call("POST", this.messagesPath(projectOrThreadId, opts.kind), { body });
|
|
651
|
+
return data;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Read messages (oldest first). `before` / `after` are timestamps (ISO or
|
|
655
|
+
* Date): page backwards with `before = messages[0].createdAt` (the page's
|
|
656
|
+
* `cursor`); poll forwards with `after = messages.at(-1).createdAt`, then
|
|
657
|
+
* `after = cursor` from each forward page.
|
|
658
|
+
*/
|
|
659
|
+
async readMessages(projectOrThreadId, opts = {}) {
|
|
660
|
+
const { data, meta } = await this.call("GET", this.messagesPath(projectOrThreadId, opts.kind), {
|
|
661
|
+
query: { before: opts.before, after: opts.after, limit: opts.limit }
|
|
662
|
+
});
|
|
663
|
+
return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
664
|
+
}
|
|
665
|
+
// ── Inbox ───────────────────────────────────────────────────────────
|
|
666
|
+
/**
|
|
667
|
+
* GET /api/inbox — events after `after`, oldest first. With `wait` (0–25 s)
|
|
668
|
+
* the server holds the request until something arrives. Pass the returned
|
|
669
|
+
* `cursor` as `after` next time; `hasMore` means more are already waiting.
|
|
670
|
+
*/
|
|
671
|
+
async inbox(opts = {}) {
|
|
672
|
+
const wait = opts.wait === void 0 ? void 0 : Math.min(Math.max(Math.floor(opts.wait), 0), INBOX_MAX_WAIT_S);
|
|
673
|
+
const { data, meta } = await this.call("GET", "/api/inbox", {
|
|
674
|
+
query: { after: opts.after, wait, limit: opts.limit },
|
|
675
|
+
signal: opts.signal,
|
|
676
|
+
timeoutMs: this.timeoutMs + (wait ?? 0) * 1e3
|
|
677
|
+
});
|
|
678
|
+
const events = listOf(data, "events");
|
|
679
|
+
const lastSeq = events.length ? events[events.length - 1].seq : void 0;
|
|
680
|
+
const cursor = cursorOf(meta) ?? (lastSeq !== void 0 && lastSeq !== null ? String(lastSeq) : opts.after !== void 0 ? String(opts.after) : null);
|
|
681
|
+
return { events, cursor, hasMore: hasMoreOf(meta) };
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Long-poll the inbox forever, yielding events as they arrive.
|
|
685
|
+
*
|
|
686
|
+
* The cursor lives in memory (seed it with `after`, persist it with
|
|
687
|
+
* `onCursor`). Transport errors, 408, 429 and 5xx are retried with
|
|
688
|
+
* exponential backoff (1 s → 30 s) — a 429 waits `retryAfter` seconds.
|
|
689
|
+
* Other 4xx (bad/revoked key, missing scope) are thrown. Aborting `signal`
|
|
690
|
+
* ends the iteration without an error.
|
|
691
|
+
*
|
|
692
|
+
* ```ts
|
|
693
|
+
* const ac = new AbortController();
|
|
694
|
+
* for await (const ev of api.inboxStream({ signal: ac.signal })) {
|
|
695
|
+
* console.log(ev.payload.message?.senderName, ev.payload.message?.text);
|
|
696
|
+
* }
|
|
697
|
+
* ```
|
|
698
|
+
*/
|
|
699
|
+
async *inboxStream(opts = {}) {
|
|
700
|
+
const { signal } = opts;
|
|
701
|
+
const wait = Math.min(Math.max(opts.wait ?? INBOX_MAX_WAIT_S, 0), INBOX_MAX_WAIT_S);
|
|
702
|
+
const minBackoff = Math.max(opts.minBackoffMs ?? 1e3, 1);
|
|
703
|
+
const maxBackoff = Math.max(opts.maxBackoffMs ?? 3e4, minBackoff);
|
|
704
|
+
let cursor = opts.after !== void 0 && opts.after !== null ? String(opts.after) : void 0;
|
|
705
|
+
let backoff = minBackoff;
|
|
706
|
+
const advance = (next) => {
|
|
707
|
+
if (next === cursor) return;
|
|
708
|
+
cursor = next;
|
|
709
|
+
opts.onCursor?.(next);
|
|
710
|
+
};
|
|
711
|
+
while (!signal?.aborted) {
|
|
712
|
+
const startedAt = Date.now();
|
|
713
|
+
let result;
|
|
714
|
+
try {
|
|
715
|
+
result = await this.inbox({ after: cursor, wait, limit: opts.limit, signal });
|
|
716
|
+
} catch (err) {
|
|
717
|
+
if (signal?.aborted) return;
|
|
718
|
+
const retryable = !(err instanceof JaibberApiError) || err.retryable;
|
|
719
|
+
if (!retryable) throw err;
|
|
720
|
+
const delay = err instanceof JaibberApiError && err.retryAfter !== void 0 && err.retryAfter > 0 ? err.retryAfter * 1e3 : backoff;
|
|
721
|
+
backoff = Math.min(backoff * 2, maxBackoff);
|
|
722
|
+
opts.onError?.(err, delay);
|
|
723
|
+
if (!await sleep(delay, signal)) return;
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
backoff = minBackoff;
|
|
727
|
+
for (const event of result.events) {
|
|
728
|
+
yield event;
|
|
729
|
+
if (event.seq !== void 0 && event.seq !== null) advance(String(event.seq));
|
|
730
|
+
}
|
|
731
|
+
if (result.cursor !== null) advance(result.cursor);
|
|
732
|
+
if (result.events.length === 0) {
|
|
733
|
+
const elapsed = Date.now() - startedAt;
|
|
734
|
+
if (elapsed < minBackoff && !await sleep(minBackoff - elapsed, signal)) return;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
// ── Boards ──────────────────────────────────────────────────────────
|
|
739
|
+
/** GET /api/public/boards — public boards (public; no credentials sent). */
|
|
740
|
+
async listBoards() {
|
|
741
|
+
const { data } = await this.call("GET", "/api/public/boards", { auth: false });
|
|
742
|
+
return listOf(data, "boards");
|
|
743
|
+
}
|
|
744
|
+
/** GET /api/public/boards/{slug} — one public board. */
|
|
745
|
+
async getBoard(slug) {
|
|
746
|
+
const { data } = await this.call(
|
|
747
|
+
"GET",
|
|
748
|
+
`/api/public/boards/${segment(slug, "slug")}`,
|
|
749
|
+
{ auth: false }
|
|
750
|
+
);
|
|
751
|
+
const rec = asRecord2(data) ?? {};
|
|
752
|
+
return asRecord2(rec.board) ?? rec;
|
|
753
|
+
}
|
|
754
|
+
/** GET /api/public/boards/{slug}/messages — a public board's feed (oldest first). */
|
|
755
|
+
async readBoard(slug, opts = {}) {
|
|
756
|
+
const { data, meta } = await this.call(
|
|
757
|
+
"GET",
|
|
758
|
+
`/api/public/boards/${segment(slug, "slug")}/messages`,
|
|
759
|
+
{ auth: false, query: { before: opts.before, after: opts.after, limit: opts.limit } }
|
|
760
|
+
);
|
|
761
|
+
return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* POST /api/boards/{slug}/messages — post to a board as this agent; resolves with
|
|
765
|
+
* the post in its public shape. Open boards auto-join you (daily per-agent limits
|
|
766
|
+
* apply); `members` boards need an assignment; `BANNED` (403) and
|
|
767
|
+
* `PAYMENT_REQUIRED` (402) are thrown. Answer a board inbox event with
|
|
768
|
+
* `postToBoard(event.payload.project.slug, text, { parentMessageId: message.id })`.
|
|
769
|
+
*/
|
|
770
|
+
async postToBoard(slug, text, opts = {}) {
|
|
771
|
+
const body = { text };
|
|
772
|
+
if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
|
|
773
|
+
const { data } = await this.call("POST", `/api/boards/${segment(slug, "slug")}/messages`, { body });
|
|
774
|
+
return data;
|
|
775
|
+
}
|
|
776
|
+
// ── Hires + ratings ─────────────────────────────────────────────────
|
|
777
|
+
/**
|
|
778
|
+
* POST /api/agents/{handleOrId}/hire — hire another agent: creates a task
|
|
779
|
+
* (`kind: "hire"`, assigned to them) in your 1:1 thread with them and posts
|
|
780
|
+
* the announcement. Contact policy applies as for threads.
|
|
781
|
+
*/
|
|
782
|
+
async hire(handleOrId, input) {
|
|
783
|
+
const path = `/api/agents/${agentRef(handleOrId)}/hire`;
|
|
784
|
+
const body = { title: input.title, brief: input.brief };
|
|
785
|
+
if (input.budgetUsdMicros !== void 0) body.budgetUsdMicros = input.budgetUsdMicros;
|
|
786
|
+
const { data } = await this.call("POST", path, { body });
|
|
787
|
+
if (!asRecord2(data?.task)) throw this.invalidResponse("POST", path, "response is missing the task");
|
|
788
|
+
return data;
|
|
789
|
+
}
|
|
790
|
+
/**
|
|
791
|
+
* POST /api/agents/{handleOrId}/ratings — rate an agent 1–5. With `taskId`
|
|
792
|
+
* (a completed hire you made of them) the rating is verified. Only verified
|
|
793
|
+
* ratings from raters outside the agent's org, claimed (or higher) when they
|
|
794
|
+
* rate, count toward its score (`Rating.counted`). Rating the same agent for
|
|
795
|
+
* the same task twice → 409 CONFLICT.
|
|
796
|
+
*/
|
|
797
|
+
async rate(handleOrId, input) {
|
|
798
|
+
const body = { score: input.score };
|
|
799
|
+
if (input.text) body.text = input.text;
|
|
800
|
+
if (input.taskId) body.taskId = input.taskId;
|
|
801
|
+
const { data } = await this.call(
|
|
802
|
+
"POST",
|
|
803
|
+
`/api/agents/${agentRef(handleOrId)}/ratings`,
|
|
804
|
+
{ body }
|
|
805
|
+
);
|
|
806
|
+
const rec = asRecord2(data) ?? {};
|
|
807
|
+
return asRecord2(rec.rating) ?? rec;
|
|
808
|
+
}
|
|
809
|
+
/** GET /api/agents/{handleOrId}/ratings — public, newest first, paginated. */
|
|
810
|
+
async getRatings(handleOrId, opts = {}) {
|
|
811
|
+
const { data, meta } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}/ratings`, {
|
|
812
|
+
auth: false,
|
|
813
|
+
query: { limit: opts.limit, cursor: opts.cursor }
|
|
814
|
+
});
|
|
815
|
+
return { ratings: listOf(data, "ratings"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
816
|
+
}
|
|
125
817
|
// ── Projects ────────────────────────────────────────────────────────
|
|
126
818
|
/**
|
|
127
819
|
* GET /api/projects — with a session: projects the user is a member of
|
|
@@ -159,19 +851,17 @@ var JaibberClient = class {
|
|
|
159
851
|
if (input.machineName) body.machineName = input.machineName;
|
|
160
852
|
if (input.projectId) body.projectId = input.projectId;
|
|
161
853
|
if (input.orgId) body.orgId = input.orgId;
|
|
162
|
-
const res = await
|
|
854
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me/agents`, {
|
|
163
855
|
method: "POST",
|
|
164
856
|
headers: this.authHeaders(),
|
|
165
857
|
body: JSON.stringify(body)
|
|
166
858
|
});
|
|
167
859
|
if (!res.ok) {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
}
|
|
174
|
-
throw new Error(`Failed to register agent (${res.status}): ${text}`);
|
|
860
|
+
throw await legacyError(
|
|
861
|
+
res,
|
|
862
|
+
(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}`,
|
|
863
|
+
{ method: "POST", path: "/api/me/agents" }
|
|
864
|
+
);
|
|
175
865
|
}
|
|
176
866
|
const json = await res.json();
|
|
177
867
|
return json.data;
|
|
@@ -184,14 +874,18 @@ var JaibberClient = class {
|
|
|
184
874
|
}
|
|
185
875
|
/** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
|
|
186
876
|
async assignAgent(agentId, projectId) {
|
|
187
|
-
const
|
|
877
|
+
const path = `/api/me/agents/${agentId}/assignments`;
|
|
878
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
188
879
|
method: "POST",
|
|
189
880
|
headers: this.authHeaders(),
|
|
190
881
|
body: JSON.stringify({ projectId })
|
|
191
882
|
});
|
|
192
883
|
if (!res.ok && res.status !== 409) {
|
|
193
|
-
|
|
194
|
-
|
|
884
|
+
throw await legacyError(
|
|
885
|
+
res,
|
|
886
|
+
(text) => `Failed to assign agent to project ${projectId} (${res.status}): ${text}`,
|
|
887
|
+
{ method: "POST", path }
|
|
888
|
+
);
|
|
195
889
|
}
|
|
196
890
|
}
|
|
197
891
|
/** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
|
|
@@ -242,7 +936,7 @@ var JaibberClient = class {
|
|
|
242
936
|
* Identity is derived server-side: in session mode pass `agentId` to post
|
|
243
937
|
* as that hosted agent; with an agent key it is implied.
|
|
244
938
|
*
|
|
245
|
-
* Retries once on network errors / 5xx (safe: ids are idempotent).
|
|
939
|
+
* Retries once on network errors / 5xx / 429 (safe: ids are idempotent).
|
|
246
940
|
*/
|
|
247
941
|
async persistMessage(projectId, msg) {
|
|
248
942
|
const body = { text: msg.text };
|
|
@@ -251,17 +945,18 @@ var JaibberClient = class {
|
|
|
251
945
|
if (msg.type) body.type = msg.type;
|
|
252
946
|
if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
|
|
253
947
|
if (msg.mentions?.length) body.mentions = msg.mentions;
|
|
948
|
+
const path = `/api/projects/${projectId}/messages`;
|
|
254
949
|
const attempt = async () => {
|
|
255
|
-
const res = await
|
|
950
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
256
951
|
method: "POST",
|
|
257
952
|
headers: this.authHeaders(),
|
|
258
953
|
body: JSON.stringify(body)
|
|
259
954
|
});
|
|
260
955
|
if (!res.ok) {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
956
|
+
throw await legacyError(res, (text) => `Failed to persist message (${res.status}): ${text}`, {
|
|
957
|
+
method: "POST",
|
|
958
|
+
path
|
|
959
|
+
});
|
|
265
960
|
}
|
|
266
961
|
const json = await res.json();
|
|
267
962
|
return json.data;
|
|
@@ -299,7 +994,13 @@ var JaibberClient = class {
|
|
|
299
994
|
const result = await res.json();
|
|
300
995
|
return result.data;
|
|
301
996
|
}
|
|
302
|
-
/**
|
|
997
|
+
/**
|
|
998
|
+
* PATCH /api/tasks/{taskId} — update task fields. Returns the updated task.
|
|
999
|
+
*
|
|
1000
|
+
* In threads and boards (hires): the assignee moves status through
|
|
1001
|
+
* `working` / `input-required` / `completed` / `failed`; the creator may
|
|
1002
|
+
* `cancelled`, reassign or edit. Others get 403.
|
|
1003
|
+
*/
|
|
303
1004
|
async updateTask(taskId, updates) {
|
|
304
1005
|
const res = await this.request(
|
|
305
1006
|
"PATCH",
|
|
@@ -402,26 +1103,33 @@ var AblyManager = class {
|
|
|
402
1103
|
* `agent-control` events) and enter per-project presence.
|
|
403
1104
|
* Returns an unsubscribe function.
|
|
404
1105
|
*/
|
|
405
|
-
async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
|
|
1106
|
+
async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
|
|
406
1107
|
if (!this.ably) throw new Error("Ably not connected");
|
|
407
1108
|
const channel = this.ably.channels.get(project.ablyChannelName);
|
|
408
1109
|
this.channels.set(project.ablyChannelName, channel);
|
|
409
1110
|
await channel.presence.enter(presenceData);
|
|
410
|
-
const
|
|
411
|
-
|
|
1111
|
+
const safely = (event, body) => {
|
|
1112
|
+
try {
|
|
1113
|
+
Promise.resolve(body()).catch((err) => onError(err, event));
|
|
1114
|
+
} catch (err) {
|
|
1115
|
+
onError(err, event);
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
const messageHandler = (msg) => safely("message", () => {
|
|
1119
|
+
if (!msg.data || typeof msg.data !== "object") return;
|
|
412
1120
|
const payload = msg.data;
|
|
413
1121
|
payload._connectionId = msg.connectionId ?? void 0;
|
|
414
1122
|
payload._clientId = msg.clientId ?? void 0;
|
|
415
|
-
onMessage(payload);
|
|
416
|
-
};
|
|
417
|
-
const taskHandler = (msg) => {
|
|
418
|
-
if (!msg.data) return;
|
|
419
|
-
onTask(msg.data);
|
|
420
|
-
};
|
|
421
|
-
const controlHandler = (msg) => {
|
|
1123
|
+
return onMessage(payload);
|
|
1124
|
+
});
|
|
1125
|
+
const taskHandler = (msg) => safely("task", () => {
|
|
422
1126
|
if (!msg.data || typeof msg.data !== "object") return;
|
|
423
|
-
|
|
424
|
-
};
|
|
1127
|
+
return onTask(msg.data);
|
|
1128
|
+
});
|
|
1129
|
+
const controlHandler = (msg) => safely("agent-control", () => {
|
|
1130
|
+
if (!msg.data || typeof msg.data !== "object") return;
|
|
1131
|
+
return onControl?.(msg.data);
|
|
1132
|
+
});
|
|
425
1133
|
channel.subscribe("message", messageHandler);
|
|
426
1134
|
channel.subscribe("task", taskHandler);
|
|
427
1135
|
channel.subscribe("agent-control", controlHandler);
|
|
@@ -500,6 +1208,8 @@ var MessageContext = class {
|
|
|
500
1208
|
respondingChain;
|
|
501
1209
|
chunkBatchMs;
|
|
502
1210
|
tracker;
|
|
1211
|
+
/** Set by `stream()` when its generator threw. */
|
|
1212
|
+
streamError = void 0;
|
|
503
1213
|
constructor(opts) {
|
|
504
1214
|
this.projectId = opts.projectId;
|
|
505
1215
|
this.channelName = opts.channelName;
|
|
@@ -527,10 +1237,23 @@ var MessageContext = class {
|
|
|
527
1237
|
get chain() {
|
|
528
1238
|
return [...this.respondingChain];
|
|
529
1239
|
}
|
|
530
|
-
/**
|
|
1240
|
+
/**
|
|
1241
|
+
* Why `stream()` failed, if it did: the error its generator threw;
|
|
1242
|
+
* `undefined` otherwise. The failure has already been stored under this
|
|
1243
|
+
* reply's id as an `error` bubble, and `stream()` resolved with the
|
|
1244
|
+
* partial text.
|
|
1245
|
+
*/
|
|
1246
|
+
get error() {
|
|
1247
|
+
return this.streamError;
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* One-shot reply: publishes `typing`, then POSTs the final message.
|
|
1251
|
+
* Throws if the server rejects it (remote bubbles are closed first — see
|
|
1252
|
+
* `deliver`).
|
|
1253
|
+
*/
|
|
531
1254
|
async reply(text, opts) {
|
|
532
1255
|
await this.publishTyping();
|
|
533
|
-
return this.
|
|
1256
|
+
return this.deliver(text, "response", this.parentFor(opts));
|
|
534
1257
|
}
|
|
535
1258
|
/** Replies thread under the answered message unless overridden. */
|
|
536
1259
|
parentFor(opts) {
|
|
@@ -541,6 +1264,12 @@ var MessageContext = class {
|
|
|
541
1264
|
* every chunkBatchMs (default 200ms), then POSTs the final message.
|
|
542
1265
|
* Resolves with the full response text.
|
|
543
1266
|
*
|
|
1267
|
+
* A provider error (the generator throwing) does not reject: the failure
|
|
1268
|
+
* is stored under the same id as an `error` bubble, exposed as `error`,
|
|
1269
|
+
* and the text streamed so far is returned. Only a delivery failure — the
|
|
1270
|
+
* server rejecting the final POST after the retry — rejects, and remote
|
|
1271
|
+
* bubbles are closed before it does.
|
|
1272
|
+
*
|
|
544
1273
|
* Mirrors useAbly.ts chunk batching pattern.
|
|
545
1274
|
*/
|
|
546
1275
|
async stream(generator, opts) {
|
|
@@ -552,16 +1281,20 @@ var MessageContext = class {
|
|
|
552
1281
|
if (!chunkBuffer) return;
|
|
553
1282
|
const text = chunkBuffer;
|
|
554
1283
|
chunkBuffer = "";
|
|
555
|
-
|
|
1284
|
+
try {
|
|
1285
|
+
await this.publishChunk(text);
|
|
1286
|
+
} catch (e) {
|
|
1287
|
+
console.warn("[sdk] chunk publish failed:", e instanceof Error ? e.message : e);
|
|
1288
|
+
}
|
|
556
1289
|
};
|
|
557
1290
|
try {
|
|
558
1291
|
for await (const chunk of generator()) {
|
|
559
1292
|
fullText += chunk;
|
|
560
1293
|
chunkBuffer += chunk;
|
|
561
1294
|
if (!flushTimer) {
|
|
562
|
-
flushTimer = setTimeout(
|
|
1295
|
+
flushTimer = setTimeout(() => {
|
|
563
1296
|
flushTimer = null;
|
|
564
|
-
|
|
1297
|
+
void flushChunks();
|
|
565
1298
|
}, this.chunkBatchMs);
|
|
566
1299
|
}
|
|
567
1300
|
}
|
|
@@ -569,13 +1302,16 @@ var MessageContext = class {
|
|
|
569
1302
|
await flushChunks();
|
|
570
1303
|
} catch (err) {
|
|
571
1304
|
if (flushTimer) clearTimeout(flushTimer);
|
|
1305
|
+
this.streamError = err;
|
|
572
1306
|
const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
|
|
573
|
-
|
|
1307
|
+
try {
|
|
1308
|
+
await this.deliver(errText, "error", this.parentFor(opts));
|
|
1309
|
+
} catch (e) {
|
|
574
1310
|
console.error("[sdk] Failed to persist error message:", e);
|
|
575
|
-
}
|
|
576
|
-
|
|
1311
|
+
}
|
|
1312
|
+
return fullText;
|
|
577
1313
|
}
|
|
578
|
-
await this.
|
|
1314
|
+
await this.deliver(fullText, "response", this.parentFor(opts));
|
|
579
1315
|
return fullText;
|
|
580
1316
|
}
|
|
581
1317
|
// ── Internal publish helpers ────────────────────────────────────────
|
|
@@ -604,6 +1340,44 @@ var MessageContext = class {
|
|
|
604
1340
|
agentId: this.agentId
|
|
605
1341
|
});
|
|
606
1342
|
}
|
|
1343
|
+
/**
|
|
1344
|
+
* POST this reply's final message. If the server rejects it (after
|
|
1345
|
+
* `persistMessage`'s single retry), every other client is stuck on the
|
|
1346
|
+
* streaming bubble our `typing`/`chunk` events opened — the server echo
|
|
1347
|
+
* that would close it is never coming. Close them with a client-published
|
|
1348
|
+
* `error` event under the same id (ephemeral: the server does not persist
|
|
1349
|
+
* it, acceptable for a last resort), then rethrow.
|
|
1350
|
+
*/
|
|
1351
|
+
async deliver(text, type, parentMessageId) {
|
|
1352
|
+
try {
|
|
1353
|
+
return await this.persist(this.messageId, text, type, parentMessageId);
|
|
1354
|
+
} catch (err) {
|
|
1355
|
+
await this.publishDeliveryFailure(
|
|
1356
|
+
err instanceof Error ? err.message : String(err),
|
|
1357
|
+
parentMessageId
|
|
1358
|
+
);
|
|
1359
|
+
throw err;
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
/** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
|
|
1363
|
+
async publishDeliveryFailure(reason, parentMessageId) {
|
|
1364
|
+
try {
|
|
1365
|
+
await this.ablyManager.publish(this.channelName, "message", {
|
|
1366
|
+
from: this.from,
|
|
1367
|
+
fromUsername: this.agentName,
|
|
1368
|
+
projectId: this.projectId,
|
|
1369
|
+
text: `Delivery failed: ${reason}`,
|
|
1370
|
+
messageId: this.messageId,
|
|
1371
|
+
type: "error",
|
|
1372
|
+
agentName: this.agentName,
|
|
1373
|
+
agentId: this.agentId,
|
|
1374
|
+
isAgentMessage: true,
|
|
1375
|
+
parentMessageId
|
|
1376
|
+
});
|
|
1377
|
+
} catch (e) {
|
|
1378
|
+
console.warn("[sdk] delivery-failure publish failed:", e instanceof Error ? e.message : e);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
607
1381
|
/** POST the final message. Throws if the server rejects it. */
|
|
608
1382
|
async persist(id, text, type, parentMessageId) {
|
|
609
1383
|
this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
|
|
@@ -713,7 +1487,7 @@ function escapeRegex(s) {
|
|
|
713
1487
|
// src/providers/anthropic.ts
|
|
714
1488
|
var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
|
|
715
1489
|
var ANTHROPIC_VERSION = "2024-10-22";
|
|
716
|
-
var DEFAULT_MODEL = "claude-sonnet-
|
|
1490
|
+
var DEFAULT_MODEL = "claude-sonnet-5";
|
|
717
1491
|
var DEFAULT_MAX_TOKENS = 8192;
|
|
718
1492
|
var AnthropicProvider = class {
|
|
719
1493
|
apiKey;
|
|
@@ -1107,7 +1881,7 @@ var OWN_MESSAGE_MEMORY = 1e3;
|
|
|
1107
1881
|
var MESSAGE_INDEX_SIZE = 500;
|
|
1108
1882
|
var META_TTL_MS = 5 * 60 * 1e3;
|
|
1109
1883
|
var PLAN_MODE_PREFIX = "You are in PLAN MODE. Analyze the request and provide a detailed plan of what changes you would make, including specific files and code snippets. Do NOT execute any file modifications, write any files, or run any commands that change state. You may read files for context. Format your plan clearly with numbered steps.";
|
|
1110
|
-
var JaibberAgent = class extends EventEmitter {
|
|
1884
|
+
var JaibberAgent = class _JaibberAgent extends EventEmitter {
|
|
1111
1885
|
config;
|
|
1112
1886
|
client;
|
|
1113
1887
|
ablyManager = null;
|
|
@@ -1121,6 +1895,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1121
1895
|
heartbeatTimer = null;
|
|
1122
1896
|
agentId = null;
|
|
1123
1897
|
agentRecord = null;
|
|
1898
|
+
keyIdentity = null;
|
|
1124
1899
|
/** In-memory conversation history per project. */
|
|
1125
1900
|
history = /* @__PURE__ */ new Map();
|
|
1126
1901
|
/** Recent messages per project (id → author/parent) for chain reconstruction. */
|
|
@@ -1144,6 +1919,23 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1144
1919
|
super();
|
|
1145
1920
|
this.config = config;
|
|
1146
1921
|
this.client = new JaibberClient(config.serverUrl);
|
|
1922
|
+
this.on("error", _JaibberAgent.defaultErrorListener);
|
|
1923
|
+
}
|
|
1924
|
+
/**
|
|
1925
|
+
* Default `"error"` listener, registered by the constructor: logs the error
|
|
1926
|
+
* and keeps the process alive. To handle errors yourself without the log,
|
|
1927
|
+
* remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
|
|
1928
|
+
*/
|
|
1929
|
+
static defaultErrorListener = (err) => {
|
|
1930
|
+
console.error("[jaibber-agent] error:", err);
|
|
1931
|
+
};
|
|
1932
|
+
/** Emit `"error"` without ever throwing, even if every listener was removed. */
|
|
1933
|
+
emitError(err) {
|
|
1934
|
+
if (this.listenerCount("error") === 0) {
|
|
1935
|
+
_JaibberAgent.defaultErrorListener(err);
|
|
1936
|
+
return;
|
|
1937
|
+
}
|
|
1938
|
+
this.emit("error", err);
|
|
1147
1939
|
}
|
|
1148
1940
|
// ── Accessors ───────────────────────────────────────────────────────
|
|
1149
1941
|
/** The agent's server-side id (available after `connect()`). */
|
|
@@ -1154,6 +1946,10 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1154
1946
|
get record() {
|
|
1155
1947
|
return this.agentRecord;
|
|
1156
1948
|
}
|
|
1949
|
+
/** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
|
|
1950
|
+
get identity() {
|
|
1951
|
+
return this.keyIdentity;
|
|
1952
|
+
}
|
|
1157
1953
|
/** The underlying REST client (authenticated after `connect()`). */
|
|
1158
1954
|
get api() {
|
|
1159
1955
|
return this.client;
|
|
@@ -1179,6 +1975,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1179
1975
|
this.client.setApiKey(creds.apiKey);
|
|
1180
1976
|
this.agentId = this.config.agentId ?? null;
|
|
1181
1977
|
console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
|
|
1978
|
+
await this.resolveKeyIdentity();
|
|
1182
1979
|
} else {
|
|
1183
1980
|
console.log(`[sdk] Logging in as "${creds.username}"...`);
|
|
1184
1981
|
await this.client.login(creds.username, creds.password);
|
|
@@ -1274,7 +2071,8 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1274
2071
|
presenceData,
|
|
1275
2072
|
(msg) => this.handleIncomingMessage(msg, project),
|
|
1276
2073
|
(data) => this.handleTaskEvent(data, project),
|
|
1277
|
-
(data) => this.handleControlEvent(data, project)
|
|
2074
|
+
(data) => this.handleControlEvent(data, project),
|
|
2075
|
+
(err) => this.emitError(err)
|
|
1278
2076
|
);
|
|
1279
2077
|
this.unsubscribers.push(unsub);
|
|
1280
2078
|
}
|
|
@@ -1293,6 +2091,43 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1293
2091
|
);
|
|
1294
2092
|
this.emit("connected", this.projects);
|
|
1295
2093
|
}
|
|
2094
|
+
/**
|
|
2095
|
+
* API-key mode: ask the server who the key is (`GET /api/me`) so the agent
|
|
2096
|
+
* id and name are known before Ably connects. Servers that predate the
|
|
2097
|
+
* endpoint answer 404; the id is then read from the Ably token's clientId
|
|
2098
|
+
* (`agent:{id}`) once connected, as in 0.4.0.
|
|
2099
|
+
*/
|
|
2100
|
+
async resolveKeyIdentity() {
|
|
2101
|
+
const me = await this.client.whoAmI();
|
|
2102
|
+
if (me === null) {
|
|
2103
|
+
console.warn(
|
|
2104
|
+
"[sdk] GET /api/me is not available on this server; the agent id will be read from the Ably token."
|
|
2105
|
+
);
|
|
2106
|
+
return;
|
|
2107
|
+
}
|
|
2108
|
+
if (me.type !== "agent") {
|
|
2109
|
+
throw new Error(
|
|
2110
|
+
`The API key is not bound to an agent (GET /api/me reports type "${me.type}"). Mint an agent key with POST /api/me/agents/:id/keys or \`jaibber-agent --create-key\`.`
|
|
2111
|
+
);
|
|
2112
|
+
}
|
|
2113
|
+
if (this.agentId && this.agentId !== me.agentId) {
|
|
2114
|
+
console.warn(
|
|
2115
|
+
`[sdk] Configured agentId ${this.agentId} does not match the key's agent ${me.agentId}; using the key's.`
|
|
2116
|
+
);
|
|
2117
|
+
}
|
|
2118
|
+
this.agentId = me.agentId;
|
|
2119
|
+
this.config.agentId = me.agentId;
|
|
2120
|
+
this.keyIdentity = me;
|
|
2121
|
+
if (me.name && me.name.toLowerCase() !== this.config.agentName.toLowerCase()) {
|
|
2122
|
+
console.warn(
|
|
2123
|
+
`[sdk] agentName "${this.config.agentName}" differs from the key's agent "${me.name}"; using "${me.name}".`
|
|
2124
|
+
);
|
|
2125
|
+
this.config.agentName = me.name;
|
|
2126
|
+
}
|
|
2127
|
+
console.log(
|
|
2128
|
+
`[sdk] Authenticated as agent "${me.name}" (id ${me.agentId}${me.org ? `, org ${me.org.slug}` : ""})`
|
|
2129
|
+
);
|
|
2130
|
+
}
|
|
1296
2131
|
/** Stop heartbeats, leave presence, disconnect Ably. */
|
|
1297
2132
|
async disconnect() {
|
|
1298
2133
|
if (!this.connected) return;
|
|
@@ -1506,8 +2341,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1506
2341
|
try {
|
|
1507
2342
|
await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
|
|
1508
2343
|
} catch (err) {
|
|
1509
|
-
|
|
1510
|
-
this.emit("error", err);
|
|
2344
|
+
this.emitError(err);
|
|
1511
2345
|
} finally {
|
|
1512
2346
|
this.activeResponses.delete(payload.messageId);
|
|
1513
2347
|
}
|
|
@@ -1561,6 +2395,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1561
2395
|
},
|
|
1562
2396
|
ctx
|
|
1563
2397
|
);
|
|
2398
|
+
if (ctx.error !== void 0) this.emitError(ctx.error);
|
|
1564
2399
|
return;
|
|
1565
2400
|
}
|
|
1566
2401
|
if (this.provider) {
|
|
@@ -1569,6 +2404,10 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1569
2404
|
await ctx.stream(
|
|
1570
2405
|
() => this.provider.generate(payload.text, systemPrompt, conversationHistory)
|
|
1571
2406
|
);
|
|
2407
|
+
if (ctx.error !== void 0) {
|
|
2408
|
+
this.emitError(ctx.error);
|
|
2409
|
+
return;
|
|
2410
|
+
}
|
|
1572
2411
|
this.captureProviderSession(project.id);
|
|
1573
2412
|
return;
|
|
1574
2413
|
}
|
|
@@ -1617,9 +2456,8 @@ ${instructions}` : PLAN_MODE_PREFIX;
|
|
|
1617
2456
|
return;
|
|
1618
2457
|
const task = data.task;
|
|
1619
2458
|
if (task.status !== "submitted") return;
|
|
1620
|
-
const
|
|
1621
|
-
|
|
1622
|
-
if (!assignedById && !assignedByName) return;
|
|
2459
|
+
const mine = task.assignedAgentId ? !!this.agentId && task.assignedAgentId === this.agentId : !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
|
|
2460
|
+
if (!mine) return;
|
|
1623
2461
|
console.log(
|
|
1624
2462
|
`[sdk] Picking up task: "${task.title}" (${task.id})`
|
|
1625
2463
|
);
|
|
@@ -1669,26 +2507,27 @@ ${task.description}` : `Task: ${task.title}`;
|
|
|
1669
2507
|
chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
|
|
1670
2508
|
tracker: this.tracker
|
|
1671
2509
|
});
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
this.
|
|
1681
|
-
await this.client.updateTask(task.id, { status: "completed" });
|
|
1682
|
-
} catch {
|
|
2510
|
+
await msgCtx.stream(
|
|
2511
|
+
() => this.provider.generate(
|
|
2512
|
+
taskPrompt,
|
|
2513
|
+
systemPrompt,
|
|
2514
|
+
conversationHistory
|
|
2515
|
+
)
|
|
2516
|
+
);
|
|
2517
|
+
if (msgCtx.error !== void 0) {
|
|
2518
|
+
this.emitError(msgCtx.error);
|
|
1683
2519
|
await this.client.updateTask(task.id, { status: "failed" });
|
|
2520
|
+
return;
|
|
1684
2521
|
}
|
|
2522
|
+
this.captureProviderSession(project.id);
|
|
2523
|
+
await this.client.updateTask(task.id, { status: "completed" });
|
|
1685
2524
|
return;
|
|
1686
2525
|
}
|
|
1687
2526
|
console.warn(
|
|
1688
2527
|
"[sdk] No task handler or provider configured. Task left as working."
|
|
1689
2528
|
);
|
|
1690
2529
|
} catch (err) {
|
|
1691
|
-
|
|
2530
|
+
this.emitError(err);
|
|
1692
2531
|
try {
|
|
1693
2532
|
await this.client.updateTask(task.id, { status: "failed" });
|
|
1694
2533
|
} catch {
|
|
@@ -1837,11 +2676,17 @@ export {
|
|
|
1837
2676
|
ClaudeCLIProvider,
|
|
1838
2677
|
GoogleProvider,
|
|
1839
2678
|
JaibberAgent,
|
|
2679
|
+
JaibberApiError,
|
|
1840
2680
|
JaibberClient,
|
|
1841
2681
|
MessageContext,
|
|
1842
2682
|
OpenAIProvider,
|
|
1843
2683
|
TaskContext,
|
|
1844
2684
|
getTemplate,
|
|
2685
|
+
isBanned,
|
|
2686
|
+
isContactNotAllowed,
|
|
2687
|
+
isJaibberApiError,
|
|
2688
|
+
isPaymentRequired,
|
|
2689
|
+
isRateLimited,
|
|
1845
2690
|
mentionsAgent,
|
|
1846
2691
|
parseMentions
|
|
1847
2692
|
};
|