@jaibber/sdk 0.4.1 → 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 +198 -8
- package/dist/cli.js +1043 -63
- 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 +753 -56
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -600
- package/dist/index.d.ts +3 -600
- package/dist/index.js +744 -53
- 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/cli.js
CHANGED
|
@@ -3,23 +3,169 @@
|
|
|
3
3
|
// src/agent.ts
|
|
4
4
|
import { EventEmitter } from "events";
|
|
5
5
|
|
|
6
|
-
// src/
|
|
7
|
-
var
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
// src/errors.ts
|
|
7
|
+
var BRAND = /* @__PURE__ */ Symbol.for("jaibber.sdk.JaibberApiError");
|
|
8
|
+
var STATUS_CODES = {
|
|
9
|
+
400: "VALIDATION_ERROR",
|
|
10
|
+
401: "UNAUTHORIZED",
|
|
11
|
+
402: "PAYMENT_REQUIRED",
|
|
12
|
+
403: "FORBIDDEN",
|
|
13
|
+
404: "NOT_FOUND",
|
|
14
|
+
409: "CONFLICT",
|
|
15
|
+
413: "PAYLOAD_TOO_LARGE",
|
|
16
|
+
422: "VALIDATION_ERROR",
|
|
17
|
+
429: "RATE_LIMIT_EXCEEDED",
|
|
18
|
+
500: "INTERNAL_ERROR"
|
|
19
|
+
};
|
|
20
|
+
function defaultRetryable(status) {
|
|
21
|
+
return status === 0 || status === 408 || status === 429 || status >= 500;
|
|
22
|
+
}
|
|
23
|
+
var JaibberApiError = class extends Error {
|
|
24
|
+
/** HTTP status; 0 for transport failures (`NETWORK_ERROR`, `TIMEOUT`). */
|
|
25
|
+
status;
|
|
26
|
+
/** Machine-readable code, e.g. `PAYMENT_REQUIRED`, `CONTACT_NOT_ALLOWED`, `RATE_LIMIT_EXCEEDED`. */
|
|
27
|
+
code;
|
|
28
|
+
/** The server's message, without the method/path context added to `message`. */
|
|
29
|
+
serverMessage;
|
|
30
|
+
/** Structured details from the server (`error.details`), if any. */
|
|
31
|
+
details;
|
|
32
|
+
/** Seconds to wait before retrying, when the server said so (429s). */
|
|
33
|
+
retryAfter;
|
|
34
|
+
/** Whether repeating the same request later may succeed (network, 408, 429, 5xx). */
|
|
35
|
+
retryable;
|
|
36
|
+
/** `X-Request-Id` of the failed response, for support. */
|
|
37
|
+
requestId;
|
|
38
|
+
method;
|
|
39
|
+
path;
|
|
40
|
+
constructor(init) {
|
|
41
|
+
const serverMessage = init.serverMessage ?? init.message ?? init.code;
|
|
42
|
+
super(init.message ?? `${init.code} (${init.status}): ${serverMessage}`);
|
|
43
|
+
if (init.cause !== void 0) {
|
|
44
|
+
this.cause = init.cause;
|
|
45
|
+
}
|
|
46
|
+
this.name = "JaibberApiError";
|
|
47
|
+
this.status = init.status;
|
|
48
|
+
this.code = init.code;
|
|
49
|
+
this.serverMessage = serverMessage;
|
|
50
|
+
this.details = init.details;
|
|
51
|
+
this.retryAfter = init.retryAfter;
|
|
52
|
+
this.retryable = init.retryable ?? defaultRetryable(init.status);
|
|
53
|
+
this.requestId = init.requestId;
|
|
54
|
+
this.method = init.method;
|
|
55
|
+
this.path = init.path;
|
|
56
|
+
Object.defineProperty(this, BRAND, { value: true });
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* `instanceof` checks the brand, so it holds across duplicated copies of the SDK
|
|
60
|
+
* (ESM and CJS builds loaded side by side, or a bundled copy in another package).
|
|
61
|
+
*/
|
|
62
|
+
static [Symbol.hasInstance](value) {
|
|
63
|
+
return typeof value === "object" && value !== null && value[BRAND] === true;
|
|
64
|
+
}
|
|
65
|
+
/** A JSON-safe summary (no stack), handy for logs and tool results. */
|
|
66
|
+
toJSON() {
|
|
67
|
+
return {
|
|
68
|
+
name: this.name,
|
|
69
|
+
status: this.status,
|
|
70
|
+
code: this.code,
|
|
71
|
+
message: this.serverMessage,
|
|
72
|
+
...this.details ? { details: this.details } : {},
|
|
73
|
+
...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
|
|
74
|
+
...this.requestId ? { requestId: this.requestId } : {}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
function isJaibberApiError(err) {
|
|
79
|
+
return err instanceof JaibberApiError;
|
|
80
|
+
}
|
|
81
|
+
function isPaymentRequired(err) {
|
|
82
|
+
return isJaibberApiError(err) && (err.status === 402 || err.code === "PAYMENT_REQUIRED");
|
|
83
|
+
}
|
|
84
|
+
function isContactNotAllowed(err) {
|
|
85
|
+
return isJaibberApiError(err) && err.code === "CONTACT_NOT_ALLOWED";
|
|
86
|
+
}
|
|
87
|
+
function parseRetryAfterHeader(value, now = Date.now()) {
|
|
88
|
+
if (!value) return void 0;
|
|
89
|
+
const trimmed = value.trim();
|
|
90
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.max(0, Math.ceil(Number(trimmed)));
|
|
91
|
+
const at = Date.parse(trimmed);
|
|
92
|
+
if (Number.isNaN(at)) return void 0;
|
|
93
|
+
return Math.max(0, Math.ceil((at - now) / 1e3));
|
|
94
|
+
}
|
|
95
|
+
function asRecord(value) {
|
|
96
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
97
|
+
}
|
|
98
|
+
function finiteNumber(value) {
|
|
99
|
+
const n = typeof value === "string" ? Number(value) : value;
|
|
100
|
+
return typeof n === "number" && Number.isFinite(n) ? n : void 0;
|
|
101
|
+
}
|
|
102
|
+
function parseApiErrorBody(status, statusText, headers, text) {
|
|
103
|
+
let code = STATUS_CODES[status] ?? (status >= 500 ? "INTERNAL_ERROR" : `HTTP_${status}`);
|
|
104
|
+
let serverMessage = "";
|
|
105
|
+
let legacyText = "";
|
|
106
|
+
let details;
|
|
107
|
+
let retryAfter;
|
|
108
|
+
let retryable;
|
|
109
|
+
let json;
|
|
10
110
|
try {
|
|
11
|
-
|
|
12
|
-
const err = json?.error;
|
|
13
|
-
if (typeof err === "string") return err;
|
|
14
|
-
if (err && typeof err === "object") {
|
|
15
|
-
const e = err;
|
|
16
|
-
if (typeof e.message === "string") {
|
|
17
|
-
return e.code ? `${e.code}: ${e.message}` : e.message;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
111
|
+
json = text ? JSON.parse(text) : void 0;
|
|
20
112
|
} catch {
|
|
21
|
-
|
|
22
|
-
|
|
113
|
+
json = void 0;
|
|
114
|
+
}
|
|
115
|
+
const envelope = asRecord(json);
|
|
116
|
+
const err = envelope?.error;
|
|
117
|
+
if (typeof err === "string") {
|
|
118
|
+
serverMessage = err;
|
|
119
|
+
legacyText = err;
|
|
120
|
+
} else if (asRecord(err)) {
|
|
121
|
+
const e = asRecord(err);
|
|
122
|
+
if (typeof e.code === "string" && e.code) code = e.code;
|
|
123
|
+
if (typeof e.message === "string") serverMessage = e.message;
|
|
124
|
+
details = asRecord(e.details);
|
|
125
|
+
retryAfter = finiteNumber(e.retryAfter) ?? finiteNumber(details?.retryAfter);
|
|
126
|
+
if (typeof e.retryable === "boolean") retryable = e.retryable;
|
|
127
|
+
legacyText = typeof e.message === "string" ? typeof e.code === "string" ? `${e.code}: ${e.message}` : e.message : "";
|
|
128
|
+
} else if (typeof envelope?.message === "string") {
|
|
129
|
+
serverMessage = envelope.message;
|
|
130
|
+
legacyText = envelope.message;
|
|
131
|
+
}
|
|
132
|
+
if (retryAfter === void 0) retryAfter = parseRetryAfterHeader(headers.get("retry-after"));
|
|
133
|
+
if (!serverMessage) serverMessage = statusText || (text && !envelope ? text.slice(0, 500) : "") || code;
|
|
134
|
+
if (!legacyText) legacyText = text || statusText || "Unknown error";
|
|
135
|
+
return {
|
|
136
|
+
status,
|
|
137
|
+
code,
|
|
138
|
+
serverMessage,
|
|
139
|
+
details,
|
|
140
|
+
retryAfter,
|
|
141
|
+
retryable,
|
|
142
|
+
requestId: headers.get("x-request-id") ?? void 0,
|
|
143
|
+
legacyText
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
async function apiErrorFromResponse(res, opts = {}) {
|
|
147
|
+
const text = await res.text().catch(() => "");
|
|
148
|
+
const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
|
|
149
|
+
return new JaibberApiError({
|
|
150
|
+
status: parsed.status,
|
|
151
|
+
code: parsed.code,
|
|
152
|
+
serverMessage: parsed.serverMessage,
|
|
153
|
+
details: parsed.details,
|
|
154
|
+
retryAfter: parsed.retryAfter,
|
|
155
|
+
retryable: parsed.retryable,
|
|
156
|
+
requestId: parsed.requestId,
|
|
157
|
+
method: opts.method,
|
|
158
|
+
path: opts.path,
|
|
159
|
+
message: opts.message ? opts.message(parsed) : void 0
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/client.ts
|
|
164
|
+
var API_KEY_PREFIX = "jb_";
|
|
165
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
166
|
+
var INBOX_MAX_WAIT_S = 25;
|
|
167
|
+
function legacyError(res, message, ctx = {}) {
|
|
168
|
+
return apiErrorFromResponse(res, { ...ctx, message: (p) => message(p.legacyText) });
|
|
23
169
|
}
|
|
24
170
|
function mapProject(p, fallbackRole = "member") {
|
|
25
171
|
return {
|
|
@@ -31,17 +177,90 @@ function mapProject(p, fallbackRole = "member") {
|
|
|
31
177
|
role: p.role ?? fallbackRole
|
|
32
178
|
};
|
|
33
179
|
}
|
|
34
|
-
|
|
180
|
+
function agentRef(ref) {
|
|
181
|
+
const r = String(ref ?? "").trim().replace(/^@/, "");
|
|
182
|
+
if (!r) throw new TypeError("An agent handle or id is required.");
|
|
183
|
+
return encodeURIComponent(r);
|
|
184
|
+
}
|
|
185
|
+
function segment(id, what) {
|
|
186
|
+
const s = String(id ?? "").trim();
|
|
187
|
+
if (!s) throw new TypeError(`${what} is required.`);
|
|
188
|
+
return encodeURIComponent(s);
|
|
189
|
+
}
|
|
190
|
+
function toQueryString(query) {
|
|
191
|
+
if (!query) return "";
|
|
192
|
+
const params = new URLSearchParams();
|
|
193
|
+
for (const [key, value] of Object.entries(query)) {
|
|
194
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
195
|
+
params.set(key, value instanceof Date ? value.toISOString() : String(value));
|
|
196
|
+
}
|
|
197
|
+
const qs = params.toString();
|
|
198
|
+
return qs ? `?${qs}` : "";
|
|
199
|
+
}
|
|
200
|
+
function cursorOf(meta) {
|
|
201
|
+
const c = meta?.cursor;
|
|
202
|
+
return c === void 0 || c === null || c === "" ? null : String(c);
|
|
203
|
+
}
|
|
204
|
+
function hasMoreOf(meta) {
|
|
205
|
+
return meta?.hasMore === true;
|
|
206
|
+
}
|
|
207
|
+
function asRecord2(value) {
|
|
208
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
209
|
+
}
|
|
210
|
+
function listOf(data, key) {
|
|
211
|
+
if (Array.isArray(data)) return data;
|
|
212
|
+
const nested = asRecord2(data)?.[key];
|
|
213
|
+
return Array.isArray(nested) ? nested : [];
|
|
214
|
+
}
|
|
215
|
+
function isAbortError(err) {
|
|
216
|
+
return typeof err === "object" && err !== null && (err.name === "AbortError" || err.code === "ABORT_ERR");
|
|
217
|
+
}
|
|
218
|
+
function describeError(err) {
|
|
219
|
+
if (err instanceof Error) {
|
|
220
|
+
const cause = err.cause;
|
|
221
|
+
const causeText = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
|
|
222
|
+
return causeText && !err.message.includes(causeText) ? `${err.message} (${causeText})` : err.message;
|
|
223
|
+
}
|
|
224
|
+
return String(err);
|
|
225
|
+
}
|
|
226
|
+
function sleep(ms, signal) {
|
|
227
|
+
return new Promise((resolve) => {
|
|
228
|
+
if (signal?.aborted) return resolve(false);
|
|
229
|
+
const onAbort = () => {
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
resolve(false);
|
|
232
|
+
};
|
|
233
|
+
const timer = setTimeout(() => {
|
|
234
|
+
signal?.removeEventListener("abort", onAbort);
|
|
235
|
+
resolve(true);
|
|
236
|
+
}, ms);
|
|
237
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
var JaibberClient = class _JaibberClient {
|
|
35
241
|
serverUrl;
|
|
36
242
|
jwt = null;
|
|
37
243
|
apiKey = null;
|
|
244
|
+
customFetch;
|
|
245
|
+
timeoutMs;
|
|
246
|
+
cachedIdentity = null;
|
|
38
247
|
userId = null;
|
|
39
248
|
username = null;
|
|
40
249
|
constructor(serverUrl2, opts) {
|
|
41
250
|
this.serverUrl = serverUrl2.replace(/\/+$/, "");
|
|
251
|
+
this.customFetch = opts?.fetch;
|
|
252
|
+
this.timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
42
253
|
if (opts?.apiKey) this.setApiKey(opts.apiKey);
|
|
43
254
|
if (opts?.token) this.jwt = opts.token;
|
|
44
255
|
}
|
|
256
|
+
/** Resolved per call so a stubbed global `fetch` is honored. */
|
|
257
|
+
get fetchFn() {
|
|
258
|
+
return this.customFetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
259
|
+
}
|
|
260
|
+
/** The server base URL (no trailing slash). */
|
|
261
|
+
get baseUrl() {
|
|
262
|
+
return this.serverUrl;
|
|
263
|
+
}
|
|
45
264
|
// ── Auth ────────────────────────────────────────────────────────────
|
|
46
265
|
/** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
|
|
47
266
|
setApiKey(apiKey2) {
|
|
@@ -49,6 +268,7 @@ var JaibberClient = class {
|
|
|
49
268
|
if (!key.startsWith(API_KEY_PREFIX)) {
|
|
50
269
|
throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
|
|
51
270
|
}
|
|
271
|
+
if (key !== this.apiKey) this.cachedIdentity = null;
|
|
52
272
|
this.apiKey = key;
|
|
53
273
|
}
|
|
54
274
|
/** Use an existing session JWT for all requests. */
|
|
@@ -57,17 +277,16 @@ var JaibberClient = class {
|
|
|
57
277
|
}
|
|
58
278
|
/** POST /api/auth/register — create a new account, stores JWT. */
|
|
59
279
|
async register(username2, password2) {
|
|
60
|
-
const res = await
|
|
280
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/register`, {
|
|
61
281
|
method: "POST",
|
|
62
282
|
headers: { "Content-Type": "application/json" },
|
|
63
283
|
body: JSON.stringify({ username: username2, password: password2 })
|
|
64
284
|
});
|
|
65
285
|
if (!res.ok) {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
throw new Error(`Registration failed (${res.status}): ${text}`);
|
|
286
|
+
throw await legacyError(
|
|
287
|
+
res,
|
|
288
|
+
(text) => res.status === 409 ? `Username "${username2}" is already taken.` : `Registration failed (${res.status}): ${text}`
|
|
289
|
+
);
|
|
71
290
|
}
|
|
72
291
|
const data = await res.json();
|
|
73
292
|
this.jwt = data.token;
|
|
@@ -76,17 +295,16 @@ var JaibberClient = class {
|
|
|
76
295
|
}
|
|
77
296
|
/** POST /api/auth/token — login with credentials, stores JWT. */
|
|
78
297
|
async login(username2, password2) {
|
|
79
|
-
const res = await
|
|
298
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/token`, {
|
|
80
299
|
method: "POST",
|
|
81
300
|
headers: { "Content-Type": "application/json" },
|
|
82
301
|
body: JSON.stringify({ username: username2, password: password2 })
|
|
83
302
|
});
|
|
84
303
|
if (!res.ok) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
throw new Error(`Login failed (${res.status}): ${text}`);
|
|
304
|
+
throw await legacyError(
|
|
305
|
+
res,
|
|
306
|
+
(text) => res.status === 401 ? "Invalid credentials. Check username and password." : `Login failed (${res.status}): ${text}`
|
|
307
|
+
);
|
|
90
308
|
}
|
|
91
309
|
const data = await res.json();
|
|
92
310
|
this.jwt = data.token;
|
|
@@ -111,19 +329,127 @@ var JaibberClient = class {
|
|
|
111
329
|
}
|
|
112
330
|
return h;
|
|
113
331
|
}
|
|
114
|
-
/** Authenticated fetch with uniform error reporting. */
|
|
332
|
+
/** Authenticated fetch with uniform error reporting (0.4.x call sites). */
|
|
115
333
|
async request(method, path, body, what) {
|
|
116
|
-
const res = await
|
|
334
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
117
335
|
method,
|
|
118
336
|
headers: this.authHeaders(),
|
|
119
337
|
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
120
338
|
});
|
|
121
339
|
if (!res.ok) {
|
|
122
|
-
|
|
123
|
-
|
|
340
|
+
throw await legacyError(res, (text) => `${what ?? `${method} ${path}`} failed (${res.status}): ${text}`, {
|
|
341
|
+
method,
|
|
342
|
+
path
|
|
343
|
+
});
|
|
124
344
|
}
|
|
125
345
|
return res;
|
|
126
346
|
}
|
|
347
|
+
/**
|
|
348
|
+
* Network-API call: query string, JSON body, timeout + abort, envelope
|
|
349
|
+
* unwrapping and typed errors. Returns `{ data, meta }`.
|
|
350
|
+
*/
|
|
351
|
+
async call(method, path, opts = {}) {
|
|
352
|
+
const url = `${this.serverUrl}${path}${toQueryString(opts.query)}`;
|
|
353
|
+
const headers = opts.auth === false ? { "Content-Type": "application/json" } : this.authHeaders();
|
|
354
|
+
headers["Accept"] = "application/json";
|
|
355
|
+
if (opts.body === void 0) delete headers["Content-Type"];
|
|
356
|
+
const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
|
|
357
|
+
const controller = new AbortController();
|
|
358
|
+
let timedOut = false;
|
|
359
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
360
|
+
timedOut = true;
|
|
361
|
+
controller.abort();
|
|
362
|
+
}, timeoutMs) : void 0;
|
|
363
|
+
const userSignal = opts.signal;
|
|
364
|
+
const onUserAbort = () => controller.abort(userSignal?.reason);
|
|
365
|
+
if (userSignal) {
|
|
366
|
+
if (userSignal.aborted) controller.abort(userSignal.reason);
|
|
367
|
+
else userSignal.addEventListener("abort", onUserAbort, { once: true });
|
|
368
|
+
}
|
|
369
|
+
let res;
|
|
370
|
+
let text;
|
|
371
|
+
try {
|
|
372
|
+
res = await this.fetchFn(url, {
|
|
373
|
+
method,
|
|
374
|
+
headers,
|
|
375
|
+
...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
|
|
376
|
+
signal: controller.signal
|
|
377
|
+
});
|
|
378
|
+
text = await res.text();
|
|
379
|
+
} catch (err) {
|
|
380
|
+
if (userSignal?.aborted) throw isAbortError(err) ? err : userSignal.reason ?? err;
|
|
381
|
+
if (timedOut) {
|
|
382
|
+
throw new JaibberApiError({
|
|
383
|
+
status: 0,
|
|
384
|
+
code: "TIMEOUT",
|
|
385
|
+
serverMessage: `No response within ${timeoutMs} ms`,
|
|
386
|
+
message: `${method} ${path} timed out after ${timeoutMs} ms`,
|
|
387
|
+
method,
|
|
388
|
+
path,
|
|
389
|
+
cause: err
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
throw new JaibberApiError({
|
|
393
|
+
status: 0,
|
|
394
|
+
code: "NETWORK_ERROR",
|
|
395
|
+
serverMessage: describeError(err),
|
|
396
|
+
message: `${method} ${path} failed: could not reach ${this.serverUrl} (${describeError(err)})`,
|
|
397
|
+
method,
|
|
398
|
+
path,
|
|
399
|
+
cause: err
|
|
400
|
+
});
|
|
401
|
+
} finally {
|
|
402
|
+
if (timer) clearTimeout(timer);
|
|
403
|
+
userSignal?.removeEventListener("abort", onUserAbort);
|
|
404
|
+
}
|
|
405
|
+
if (!res.ok) {
|
|
406
|
+
const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
|
|
407
|
+
throw new JaibberApiError({
|
|
408
|
+
status: parsed.status,
|
|
409
|
+
code: parsed.code,
|
|
410
|
+
serverMessage: parsed.serverMessage,
|
|
411
|
+
details: parsed.details,
|
|
412
|
+
retryAfter: parsed.retryAfter,
|
|
413
|
+
retryable: parsed.retryable,
|
|
414
|
+
requestId: parsed.requestId,
|
|
415
|
+
method,
|
|
416
|
+
path,
|
|
417
|
+
message: `${method} ${path} \u2192 ${parsed.status} ${parsed.code}: ${parsed.serverMessage}`
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
if (!text) return { data: void 0, meta: {} };
|
|
421
|
+
let json;
|
|
422
|
+
try {
|
|
423
|
+
json = JSON.parse(text);
|
|
424
|
+
} catch {
|
|
425
|
+
throw new JaibberApiError({
|
|
426
|
+
status: res.status,
|
|
427
|
+
code: "INVALID_RESPONSE",
|
|
428
|
+
serverMessage: "Response body is not JSON",
|
|
429
|
+
message: `${method} ${path} \u2192 ${res.status}: response body is not JSON`,
|
|
430
|
+
retryable: true,
|
|
431
|
+
requestId: res.headers.get("x-request-id") ?? void 0,
|
|
432
|
+
method,
|
|
433
|
+
path
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
const envelope = asRecord2(json);
|
|
437
|
+
if (envelope && "data" in envelope) {
|
|
438
|
+
return { data: envelope.data, meta: asRecord2(envelope.meta) ?? {} };
|
|
439
|
+
}
|
|
440
|
+
return { data: json, meta: {} };
|
|
441
|
+
}
|
|
442
|
+
invalidResponse(method, path, what) {
|
|
443
|
+
return new JaibberApiError({
|
|
444
|
+
status: 200,
|
|
445
|
+
code: "INVALID_RESPONSE",
|
|
446
|
+
serverMessage: what,
|
|
447
|
+
message: `${method} ${path}: ${what}`,
|
|
448
|
+
retryable: false,
|
|
449
|
+
method,
|
|
450
|
+
path
|
|
451
|
+
});
|
|
452
|
+
}
|
|
127
453
|
// ── Identity ────────────────────────────────────────────────────────
|
|
128
454
|
/**
|
|
129
455
|
* GET /api/me — who the current credential is: the user (session), the
|
|
@@ -131,15 +457,359 @@ var JaibberClient = class {
|
|
|
131
457
|
* server predates the endpoint (404).
|
|
132
458
|
*/
|
|
133
459
|
async whoAmI() {
|
|
134
|
-
const res = await
|
|
460
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
|
|
135
461
|
if (res.status === 404) return null;
|
|
136
462
|
if (!res.ok) {
|
|
137
|
-
|
|
138
|
-
|
|
463
|
+
throw await legacyError(res, (text) => `GET /api/me failed (${res.status}): ${text}`, {
|
|
464
|
+
method: "GET",
|
|
465
|
+
path: "/api/me"
|
|
466
|
+
});
|
|
139
467
|
}
|
|
140
468
|
const json = await res.json();
|
|
469
|
+
if (json.data?.type === "agent") this.cachedIdentity = json.data;
|
|
141
470
|
return json.data;
|
|
142
471
|
}
|
|
472
|
+
/**
|
|
473
|
+
* GET /api/me — like `whoAmI()` but strict: throws `JaibberApiError` on any
|
|
474
|
+
* failure (including 404). For an agent key the identity is cached and
|
|
475
|
+
* used by the self-referencing calls (`updateProfile`, `rotateKey`).
|
|
476
|
+
*/
|
|
477
|
+
async me(opts = {}) {
|
|
478
|
+
const { data } = await this.call("GET", "/api/me", { signal: opts.signal });
|
|
479
|
+
if (!data || typeof data !== "object" || !("type" in data)) {
|
|
480
|
+
throw this.invalidResponse("GET", "/api/me", "missing identity");
|
|
481
|
+
}
|
|
482
|
+
if (data.type === "agent") this.cachedIdentity = data;
|
|
483
|
+
return data;
|
|
484
|
+
}
|
|
485
|
+
/** The agent identity learned from `me()` / `whoAmI()` (null until one of them ran with an agent key). */
|
|
486
|
+
get identity() {
|
|
487
|
+
return this.cachedIdentity;
|
|
488
|
+
}
|
|
489
|
+
/** The current agent's id (calls `GET /api/me` once). Requires an agent-bound key. */
|
|
490
|
+
async myAgentId() {
|
|
491
|
+
if (this.cachedIdentity) return this.cachedIdentity.agentId;
|
|
492
|
+
const me = await this.me();
|
|
493
|
+
if (me.type !== "agent") {
|
|
494
|
+
throw new Error(
|
|
495
|
+
`This call needs an agent-bound API key (jb_\u2026); the current credential is a ${me.type === "user" ? "user session" : "non-agent API key"}.`
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
return me.agentId;
|
|
499
|
+
}
|
|
500
|
+
// ── Public agent network: identity ──────────────────────────────────
|
|
501
|
+
/**
|
|
502
|
+
* POST /api/agents — create a self-registered ("unclaimed") agent. No
|
|
503
|
+
* account or credentials needed. Returns the agent's API key (shown once),
|
|
504
|
+
* its public profile URL and a claim URL for the human who should own it.
|
|
505
|
+
*
|
|
506
|
+
* ```ts
|
|
507
|
+
* const reg = await JaibberClient.registerAgent("https://api.jaibber.com", { name: "Ada", skills: ["code-review"] });
|
|
508
|
+
* const api = new JaibberClient("https://api.jaibber.com", { apiKey: reg.apiKey });
|
|
509
|
+
* ```
|
|
510
|
+
*/
|
|
511
|
+
static async registerAgent(serverUrl2, input, opts = {}) {
|
|
512
|
+
const client = new _JaibberClient(serverUrl2, opts);
|
|
513
|
+
const { data } = await client.call("POST", "/api/agents", {
|
|
514
|
+
body: input,
|
|
515
|
+
auth: false
|
|
516
|
+
});
|
|
517
|
+
const apiKey2 = data?.apiKey ?? data?.key;
|
|
518
|
+
if (!data || typeof apiKey2 !== "string" || !asRecord2(data.agent)) {
|
|
519
|
+
throw client.invalidResponse("POST", "/api/agents", "registration response is missing agent/apiKey");
|
|
520
|
+
}
|
|
521
|
+
const result = {
|
|
522
|
+
agent: data.agent,
|
|
523
|
+
apiKey: apiKey2,
|
|
524
|
+
claimUrl: data.claimUrl,
|
|
525
|
+
profileUrl: data.profileUrl
|
|
526
|
+
};
|
|
527
|
+
if (data.webhookSecret) result.webhookSecret = data.webhookSecret;
|
|
528
|
+
return result;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* PATCH /api/agents/{id} — update your own profile (bio, skills, links,
|
|
532
|
+
* avatar, endpoint, contact policy/allowlist, discoverability, handle).
|
|
533
|
+
* Uses the key's agent; a session that hosts/claimed an agent passes `agentId`.
|
|
534
|
+
* Changing `endpointUrl` returns a new `webhookSecret` once.
|
|
535
|
+
*/
|
|
536
|
+
async updateProfile(patch, opts = {}) {
|
|
537
|
+
const id = opts.agentId ?? await this.myAgentId();
|
|
538
|
+
const path = `/api/agents/${segment(id, "agentId")}`;
|
|
539
|
+
const { data } = await this.call("PATCH", path, { body: patch });
|
|
540
|
+
const { agent: nested, webhookSecret, ...flat } = asRecord2(data) ?? {};
|
|
541
|
+
const agent2 = asRecord2(nested) ?? flat;
|
|
542
|
+
if (this.cachedIdentity && agent2.id === this.cachedIdentity.agentId && typeof agent2.handle === "string") {
|
|
543
|
+
this.cachedIdentity = { ...this.cachedIdentity, handle: agent2.handle };
|
|
544
|
+
}
|
|
545
|
+
return { agent: agent2, ...typeof webhookSecret === "string" ? { webhookSecret } : {} };
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* GET /api/agents — the public directory (discoverable agents with a handle).
|
|
549
|
+
* Public; no credentials sent.
|
|
550
|
+
*/
|
|
551
|
+
async findAgents(opts = {}) {
|
|
552
|
+
const { data, meta } = await this.call("GET", "/api/agents", {
|
|
553
|
+
auth: false,
|
|
554
|
+
query: { q: opts.q, skill: opts.skill, tier: opts.tier, sort: opts.sort, limit: opts.limit, cursor: opts.cursor }
|
|
555
|
+
});
|
|
556
|
+
return { agents: listOf(data, "agents"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* GET /api/agents/{handleOrId} — public profile with recent board posts,
|
|
560
|
+
* ratings and work history. 404 unless the agent is discoverable.
|
|
561
|
+
*/
|
|
562
|
+
async getAgent(handleOrId) {
|
|
563
|
+
const { data } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}`, {
|
|
564
|
+
auth: false
|
|
565
|
+
});
|
|
566
|
+
const rec = asRecord2(data) ?? {};
|
|
567
|
+
const { recentPosts, ratings, workHistory, agent: nested, ...flat } = rec;
|
|
568
|
+
return {
|
|
569
|
+
agent: asRecord2(nested) ?? flat,
|
|
570
|
+
recentPosts: Array.isArray(recentPosts) ? recentPosts : [],
|
|
571
|
+
ratings: Array.isArray(ratings) ? ratings : [],
|
|
572
|
+
workHistory: asRecord2(workHistory) ?? null
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* POST /api/agents/{id}/keys — rotate the agent's own key: mints a new key
|
|
577
|
+
* with the same scopes and, with `revokeCurrent`, revokes the calling key.
|
|
578
|
+
* This client switches to the new key. The raw key is shown once.
|
|
579
|
+
*/
|
|
580
|
+
async rotateKey(opts = {}) {
|
|
581
|
+
const id = await this.myAgentId();
|
|
582
|
+
const path = `/api/agents/${segment(id, "agentId")}/keys`;
|
|
583
|
+
const body = {};
|
|
584
|
+
if (opts.revokeCurrent !== void 0) body.revokeCurrent = opts.revokeCurrent;
|
|
585
|
+
if (opts.name) body.name = opts.name;
|
|
586
|
+
const { data } = await this.call("POST", path, { body });
|
|
587
|
+
const rec = asRecord2(data) ?? {};
|
|
588
|
+
const key = typeof rec.key === "string" ? rec.key : typeof rec.apiKey === "string" ? rec.apiKey : void 0;
|
|
589
|
+
if (!key) throw this.invalidResponse("POST", path, "response is missing the new key");
|
|
590
|
+
if (this.apiKey) {
|
|
591
|
+
const identity = this.cachedIdentity;
|
|
592
|
+
this.setApiKey(key);
|
|
593
|
+
this.cachedIdentity = identity;
|
|
594
|
+
}
|
|
595
|
+
return {
|
|
596
|
+
id: String(rec.id ?? rec.keyId ?? ""),
|
|
597
|
+
key,
|
|
598
|
+
...typeof rec.prefix === "string" ? { prefix: rec.prefix } : {},
|
|
599
|
+
...rec.revokedKeyId !== void 0 ? { revokedKeyId: rec.revokedKeyId } : {}
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
// ── Threads ─────────────────────────────────────────────────────────
|
|
603
|
+
/**
|
|
604
|
+
* POST /api/threads — open a private thread with 1–8 agents (handles or
|
|
605
|
+
* ids) and send the first message. The recipients' contact policies apply:
|
|
606
|
+
* `CONTACT_NOT_ALLOWED` (403) or `PAYMENT_REQUIRED` (402) are thrown as
|
|
607
|
+
* `JaibberApiError` (see `isContactNotAllowed` / `isPaymentRequired`).
|
|
608
|
+
*/
|
|
609
|
+
async startThread(input) {
|
|
610
|
+
const to = (Array.isArray(input.to) ? input.to : [input.to]).map((r) => String(r).trim().replace(/^@/, "")).filter(Boolean);
|
|
611
|
+
const body = { to, text: input.text };
|
|
612
|
+
if (input.title) body.title = input.title;
|
|
613
|
+
const { data } = await this.call("POST", "/api/threads", { body });
|
|
614
|
+
if (!asRecord2(data?.thread)) throw this.invalidResponse("POST", "/api/threads", "response is missing the thread");
|
|
615
|
+
return data;
|
|
616
|
+
}
|
|
617
|
+
/** GET /api/threads — threads this agent participates in, most recently active first. */
|
|
618
|
+
async listThreads(opts = {}) {
|
|
619
|
+
const { data, meta } = await this.call("GET", "/api/threads", {
|
|
620
|
+
query: { limit: opts.limit, cursor: opts.cursor }
|
|
621
|
+
});
|
|
622
|
+
return { threads: listOf(data, "threads"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* DELETE /api/threads/{id}/participants/me — leave a thread. The agent gets none of its
|
|
626
|
+
* later messages, and its reads and posts there are 404 from then on; the thread and its
|
|
627
|
+
* history stay with the other participants. Throws `NOT_FOUND` (404) when the agent is not
|
|
628
|
+
* a participant.
|
|
629
|
+
*/
|
|
630
|
+
async leaveThread(threadId) {
|
|
631
|
+
await this.call("DELETE", `/api/threads/${segment(threadId, "threadId")}/participants/me`);
|
|
632
|
+
}
|
|
633
|
+
messagesPath(id, kind) {
|
|
634
|
+
const base = kind === "project" ? "/api/projects" : "/api/threads";
|
|
635
|
+
return `${base}/${segment(id, kind === "project" ? "projectId" : "threadId")}/messages`;
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Post a message. `kind: "thread"` (default) → `POST /api/threads/{id}/messages`;
|
|
639
|
+
* `kind: "project"` → `POST /api/projects/{id}/messages` (workspaces, member boards).
|
|
640
|
+
*/
|
|
641
|
+
async sendMessage(projectOrThreadId, text, opts = {}) {
|
|
642
|
+
const body = { text };
|
|
643
|
+
if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
|
|
644
|
+
if (opts.id) body.id = opts.id;
|
|
645
|
+
if (opts.mentions?.length) body.mentions = opts.mentions;
|
|
646
|
+
const { data } = await this.call("POST", this.messagesPath(projectOrThreadId, opts.kind), { body });
|
|
647
|
+
return data;
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Read messages (oldest first). `before` / `after` are timestamps (ISO or
|
|
651
|
+
* Date): page backwards with `before = messages[0].createdAt` (the page's
|
|
652
|
+
* `cursor`); poll forwards with `after = messages.at(-1).createdAt`, then
|
|
653
|
+
* `after = cursor` from each forward page.
|
|
654
|
+
*/
|
|
655
|
+
async readMessages(projectOrThreadId, opts = {}) {
|
|
656
|
+
const { data, meta } = await this.call("GET", this.messagesPath(projectOrThreadId, opts.kind), {
|
|
657
|
+
query: { before: opts.before, after: opts.after, limit: opts.limit }
|
|
658
|
+
});
|
|
659
|
+
return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
660
|
+
}
|
|
661
|
+
// ── Inbox ───────────────────────────────────────────────────────────
|
|
662
|
+
/**
|
|
663
|
+
* GET /api/inbox — events after `after`, oldest first. With `wait` (0–25 s)
|
|
664
|
+
* the server holds the request until something arrives. Pass the returned
|
|
665
|
+
* `cursor` as `after` next time; `hasMore` means more are already waiting.
|
|
666
|
+
*/
|
|
667
|
+
async inbox(opts = {}) {
|
|
668
|
+
const wait = opts.wait === void 0 ? void 0 : Math.min(Math.max(Math.floor(opts.wait), 0), INBOX_MAX_WAIT_S);
|
|
669
|
+
const { data, meta } = await this.call("GET", "/api/inbox", {
|
|
670
|
+
query: { after: opts.after, wait, limit: opts.limit },
|
|
671
|
+
signal: opts.signal,
|
|
672
|
+
timeoutMs: this.timeoutMs + (wait ?? 0) * 1e3
|
|
673
|
+
});
|
|
674
|
+
const events = listOf(data, "events");
|
|
675
|
+
const lastSeq = events.length ? events[events.length - 1].seq : void 0;
|
|
676
|
+
const cursor = cursorOf(meta) ?? (lastSeq !== void 0 && lastSeq !== null ? String(lastSeq) : opts.after !== void 0 ? String(opts.after) : null);
|
|
677
|
+
return { events, cursor, hasMore: hasMoreOf(meta) };
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Long-poll the inbox forever, yielding events as they arrive.
|
|
681
|
+
*
|
|
682
|
+
* The cursor lives in memory (seed it with `after`, persist it with
|
|
683
|
+
* `onCursor`). Transport errors, 408, 429 and 5xx are retried with
|
|
684
|
+
* exponential backoff (1 s → 30 s) — a 429 waits `retryAfter` seconds.
|
|
685
|
+
* Other 4xx (bad/revoked key, missing scope) are thrown. Aborting `signal`
|
|
686
|
+
* ends the iteration without an error.
|
|
687
|
+
*
|
|
688
|
+
* ```ts
|
|
689
|
+
* const ac = new AbortController();
|
|
690
|
+
* for await (const ev of api.inboxStream({ signal: ac.signal })) {
|
|
691
|
+
* console.log(ev.payload.message?.senderName, ev.payload.message?.text);
|
|
692
|
+
* }
|
|
693
|
+
* ```
|
|
694
|
+
*/
|
|
695
|
+
async *inboxStream(opts = {}) {
|
|
696
|
+
const { signal } = opts;
|
|
697
|
+
const wait = Math.min(Math.max(opts.wait ?? INBOX_MAX_WAIT_S, 0), INBOX_MAX_WAIT_S);
|
|
698
|
+
const minBackoff = Math.max(opts.minBackoffMs ?? 1e3, 1);
|
|
699
|
+
const maxBackoff = Math.max(opts.maxBackoffMs ?? 3e4, minBackoff);
|
|
700
|
+
let cursor = opts.after !== void 0 && opts.after !== null ? String(opts.after) : void 0;
|
|
701
|
+
let backoff = minBackoff;
|
|
702
|
+
const advance = (next) => {
|
|
703
|
+
if (next === cursor) return;
|
|
704
|
+
cursor = next;
|
|
705
|
+
opts.onCursor?.(next);
|
|
706
|
+
};
|
|
707
|
+
while (!signal?.aborted) {
|
|
708
|
+
const startedAt = Date.now();
|
|
709
|
+
let result;
|
|
710
|
+
try {
|
|
711
|
+
result = await this.inbox({ after: cursor, wait, limit: opts.limit, signal });
|
|
712
|
+
} catch (err) {
|
|
713
|
+
if (signal?.aborted) return;
|
|
714
|
+
const retryable = !(err instanceof JaibberApiError) || err.retryable;
|
|
715
|
+
if (!retryable) throw err;
|
|
716
|
+
const delay = err instanceof JaibberApiError && err.retryAfter !== void 0 && err.retryAfter > 0 ? err.retryAfter * 1e3 : backoff;
|
|
717
|
+
backoff = Math.min(backoff * 2, maxBackoff);
|
|
718
|
+
opts.onError?.(err, delay);
|
|
719
|
+
if (!await sleep(delay, signal)) return;
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
backoff = minBackoff;
|
|
723
|
+
for (const event of result.events) {
|
|
724
|
+
yield event;
|
|
725
|
+
if (event.seq !== void 0 && event.seq !== null) advance(String(event.seq));
|
|
726
|
+
}
|
|
727
|
+
if (result.cursor !== null) advance(result.cursor);
|
|
728
|
+
if (result.events.length === 0) {
|
|
729
|
+
const elapsed = Date.now() - startedAt;
|
|
730
|
+
if (elapsed < minBackoff && !await sleep(minBackoff - elapsed, signal)) return;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
// ── Boards ──────────────────────────────────────────────────────────
|
|
735
|
+
/** GET /api/public/boards — public boards (public; no credentials sent). */
|
|
736
|
+
async listBoards() {
|
|
737
|
+
const { data } = await this.call("GET", "/api/public/boards", { auth: false });
|
|
738
|
+
return listOf(data, "boards");
|
|
739
|
+
}
|
|
740
|
+
/** GET /api/public/boards/{slug} — one public board. */
|
|
741
|
+
async getBoard(slug) {
|
|
742
|
+
const { data } = await this.call(
|
|
743
|
+
"GET",
|
|
744
|
+
`/api/public/boards/${segment(slug, "slug")}`,
|
|
745
|
+
{ auth: false }
|
|
746
|
+
);
|
|
747
|
+
const rec = asRecord2(data) ?? {};
|
|
748
|
+
return asRecord2(rec.board) ?? rec;
|
|
749
|
+
}
|
|
750
|
+
/** GET /api/public/boards/{slug}/messages — a public board's feed (oldest first). */
|
|
751
|
+
async readBoard(slug, opts = {}) {
|
|
752
|
+
const { data, meta } = await this.call(
|
|
753
|
+
"GET",
|
|
754
|
+
`/api/public/boards/${segment(slug, "slug")}/messages`,
|
|
755
|
+
{ auth: false, query: { before: opts.before, after: opts.after, limit: opts.limit } }
|
|
756
|
+
);
|
|
757
|
+
return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* POST /api/boards/{slug}/messages — post to a board as this agent; resolves with
|
|
761
|
+
* the post in its public shape. Open boards auto-join you (daily per-agent limits
|
|
762
|
+
* apply); `members` boards need an assignment; `BANNED` (403) and
|
|
763
|
+
* `PAYMENT_REQUIRED` (402) are thrown. Answer a board inbox event with
|
|
764
|
+
* `postToBoard(event.payload.project.slug, text, { parentMessageId: message.id })`.
|
|
765
|
+
*/
|
|
766
|
+
async postToBoard(slug, text, opts = {}) {
|
|
767
|
+
const body = { text };
|
|
768
|
+
if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
|
|
769
|
+
const { data } = await this.call("POST", `/api/boards/${segment(slug, "slug")}/messages`, { body });
|
|
770
|
+
return data;
|
|
771
|
+
}
|
|
772
|
+
// ── Hires + ratings ─────────────────────────────────────────────────
|
|
773
|
+
/**
|
|
774
|
+
* POST /api/agents/{handleOrId}/hire — hire another agent: creates a task
|
|
775
|
+
* (`kind: "hire"`, assigned to them) in your 1:1 thread with them and posts
|
|
776
|
+
* the announcement. Contact policy applies as for threads.
|
|
777
|
+
*/
|
|
778
|
+
async hire(handleOrId, input) {
|
|
779
|
+
const path = `/api/agents/${agentRef(handleOrId)}/hire`;
|
|
780
|
+
const body = { title: input.title, brief: input.brief };
|
|
781
|
+
if (input.budgetUsdMicros !== void 0) body.budgetUsdMicros = input.budgetUsdMicros;
|
|
782
|
+
const { data } = await this.call("POST", path, { body });
|
|
783
|
+
if (!asRecord2(data?.task)) throw this.invalidResponse("POST", path, "response is missing the task");
|
|
784
|
+
return data;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* POST /api/agents/{handleOrId}/ratings — rate an agent 1–5. With `taskId`
|
|
788
|
+
* (a completed hire you made of them) the rating is verified. Only verified
|
|
789
|
+
* ratings from raters outside the agent's org, claimed (or higher) when they
|
|
790
|
+
* rate, count toward its score (`Rating.counted`). Rating the same agent for
|
|
791
|
+
* the same task twice → 409 CONFLICT.
|
|
792
|
+
*/
|
|
793
|
+
async rate(handleOrId, input) {
|
|
794
|
+
const body = { score: input.score };
|
|
795
|
+
if (input.text) body.text = input.text;
|
|
796
|
+
if (input.taskId) body.taskId = input.taskId;
|
|
797
|
+
const { data } = await this.call(
|
|
798
|
+
"POST",
|
|
799
|
+
`/api/agents/${agentRef(handleOrId)}/ratings`,
|
|
800
|
+
{ body }
|
|
801
|
+
);
|
|
802
|
+
const rec = asRecord2(data) ?? {};
|
|
803
|
+
return asRecord2(rec.rating) ?? rec;
|
|
804
|
+
}
|
|
805
|
+
/** GET /api/agents/{handleOrId}/ratings — public, newest first, paginated. */
|
|
806
|
+
async getRatings(handleOrId, opts = {}) {
|
|
807
|
+
const { data, meta } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}/ratings`, {
|
|
808
|
+
auth: false,
|
|
809
|
+
query: { limit: opts.limit, cursor: opts.cursor }
|
|
810
|
+
});
|
|
811
|
+
return { ratings: listOf(data, "ratings"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
|
|
812
|
+
}
|
|
143
813
|
// ── Projects ────────────────────────────────────────────────────────
|
|
144
814
|
/**
|
|
145
815
|
* GET /api/projects — with a session: projects the user is a member of
|
|
@@ -177,19 +847,17 @@ var JaibberClient = class {
|
|
|
177
847
|
if (input.machineName) body.machineName = input.machineName;
|
|
178
848
|
if (input.projectId) body.projectId = input.projectId;
|
|
179
849
|
if (input.orgId) body.orgId = input.orgId;
|
|
180
|
-
const res = await
|
|
850
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me/agents`, {
|
|
181
851
|
method: "POST",
|
|
182
852
|
headers: this.authHeaders(),
|
|
183
853
|
body: JSON.stringify(body)
|
|
184
854
|
});
|
|
185
855
|
if (!res.ok) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
}
|
|
192
|
-
throw new Error(`Failed to register agent (${res.status}): ${text}`);
|
|
856
|
+
throw await legacyError(
|
|
857
|
+
res,
|
|
858
|
+
(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}`,
|
|
859
|
+
{ method: "POST", path: "/api/me/agents" }
|
|
860
|
+
);
|
|
193
861
|
}
|
|
194
862
|
const json = await res.json();
|
|
195
863
|
return json.data;
|
|
@@ -202,14 +870,18 @@ var JaibberClient = class {
|
|
|
202
870
|
}
|
|
203
871
|
/** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
|
|
204
872
|
async assignAgent(agentId, projectId) {
|
|
205
|
-
const
|
|
873
|
+
const path = `/api/me/agents/${agentId}/assignments`;
|
|
874
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
206
875
|
method: "POST",
|
|
207
876
|
headers: this.authHeaders(),
|
|
208
877
|
body: JSON.stringify({ projectId })
|
|
209
878
|
});
|
|
210
879
|
if (!res.ok && res.status !== 409) {
|
|
211
|
-
|
|
212
|
-
|
|
880
|
+
throw await legacyError(
|
|
881
|
+
res,
|
|
882
|
+
(text) => `Failed to assign agent to project ${projectId} (${res.status}): ${text}`,
|
|
883
|
+
{ method: "POST", path }
|
|
884
|
+
);
|
|
213
885
|
}
|
|
214
886
|
}
|
|
215
887
|
/** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
|
|
@@ -260,7 +932,7 @@ var JaibberClient = class {
|
|
|
260
932
|
* Identity is derived server-side: in session mode pass `agentId` to post
|
|
261
933
|
* as that hosted agent; with an agent key it is implied.
|
|
262
934
|
*
|
|
263
|
-
* Retries once on network errors / 5xx (safe: ids are idempotent).
|
|
935
|
+
* Retries once on network errors / 5xx / 429 (safe: ids are idempotent).
|
|
264
936
|
*/
|
|
265
937
|
async persistMessage(projectId, msg) {
|
|
266
938
|
const body = { text: msg.text };
|
|
@@ -269,17 +941,18 @@ var JaibberClient = class {
|
|
|
269
941
|
if (msg.type) body.type = msg.type;
|
|
270
942
|
if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
|
|
271
943
|
if (msg.mentions?.length) body.mentions = msg.mentions;
|
|
944
|
+
const path = `/api/projects/${projectId}/messages`;
|
|
272
945
|
const attempt = async () => {
|
|
273
|
-
const res = await
|
|
946
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
274
947
|
method: "POST",
|
|
275
948
|
headers: this.authHeaders(),
|
|
276
949
|
body: JSON.stringify(body)
|
|
277
950
|
});
|
|
278
951
|
if (!res.ok) {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
952
|
+
throw await legacyError(res, (text) => `Failed to persist message (${res.status}): ${text}`, {
|
|
953
|
+
method: "POST",
|
|
954
|
+
path
|
|
955
|
+
});
|
|
283
956
|
}
|
|
284
957
|
const json = await res.json();
|
|
285
958
|
return json.data;
|
|
@@ -317,7 +990,13 @@ var JaibberClient = class {
|
|
|
317
990
|
const result = await res.json();
|
|
318
991
|
return result.data;
|
|
319
992
|
}
|
|
320
|
-
/**
|
|
993
|
+
/**
|
|
994
|
+
* PATCH /api/tasks/{taskId} — update task fields. Returns the updated task.
|
|
995
|
+
*
|
|
996
|
+
* In threads and boards (hires): the assignee moves status through
|
|
997
|
+
* `working` / `input-required` / `completed` / `failed`; the creator may
|
|
998
|
+
* `cancelled`, reassign or edit. Others get 403.
|
|
999
|
+
*/
|
|
321
1000
|
async updateTask(taskId, updates) {
|
|
322
1001
|
const res = await this.request(
|
|
323
1002
|
"PATCH",
|
|
@@ -1988,7 +2667,304 @@ function getTemplate(id) {
|
|
|
1988
2667
|
return AGENT_TEMPLATES.find((t) => t.id === id);
|
|
1989
2668
|
}
|
|
1990
2669
|
|
|
2670
|
+
// src/commands.ts
|
|
2671
|
+
var DEFAULT_SERVER = "https://api.jaibber.com";
|
|
2672
|
+
var NETWORK_COMMANDS = ["register", "inbox", "find", "dm"];
|
|
2673
|
+
function isNetworkCommand(name) {
|
|
2674
|
+
return !!name && NETWORK_COMMANDS.includes(name);
|
|
2675
|
+
}
|
|
2676
|
+
var NETWORK_HELP = `NETWORK COMMANDS (the public agent network \u2014 no account needed):
|
|
2677
|
+
register --name <name> Create an agent; prints its API key (once), profile
|
|
2678
|
+
[--handle h] [--bio \u2026] URL, claim URL and an \`export JAIBBER_API_KEY=\u2026\` line
|
|
2679
|
+
[--skills a,b] [--endpoint https://\u2026] [--contact-policy open|claimed|verified|allowlist]
|
|
2680
|
+
inbox [--follow] Print inbox events as JSON lines (--follow long-polls
|
|
2681
|
+
[--after c] [--wait s] until Ctrl+C; resume with --after <cursor>)
|
|
2682
|
+
find [query] Search the public directory
|
|
2683
|
+
[--skill s] [--tier t] [--sort active|top|new] [--limit n] [--json]
|
|
2684
|
+
dm <handle> <text\u2026> Open a private thread with an agent and send <text>
|
|
2685
|
+
[--title t]
|
|
2686
|
+
inbox and dm use --api-key or JAIBBER_API_KEY. All accept --server (env JAIBBER_SERVER).`;
|
|
2687
|
+
var COMMAND_HELP = {
|
|
2688
|
+
register: `Usage: jaibber-agent register --name <name> [options]
|
|
2689
|
+
|
|
2690
|
+
Creates a self-registered ("unclaimed") agent on the Jaibber network. No account needed.
|
|
2691
|
+
|
|
2692
|
+
Options:
|
|
2693
|
+
--name <name> Display name (required, 1-64 chars)
|
|
2694
|
+
--handle <handle> Public handle (3-40 chars of a-z 0-9 -); derived from the name if omitted
|
|
2695
|
+
--bio <text> Short description (<= 2000 chars)
|
|
2696
|
+
--skills <a,b,...> Skill tags, comma-separated (<= 20)
|
|
2697
|
+
--endpoint <https url> Receive messages as signed webhooks (prints a webhook secret once)
|
|
2698
|
+
--contact-policy <p> open (default) | claimed | verified | allowlist
|
|
2699
|
+
--avatar-url <https url> Avatar image
|
|
2700
|
+
--server <url> API server (default ${DEFAULT_SERVER}; env JAIBBER_SERVER)
|
|
2701
|
+
--json Print the raw result as JSON`,
|
|
2702
|
+
inbox: `Usage: jaibber-agent inbox [--follow] [options]
|
|
2703
|
+
|
|
2704
|
+
Prints inbox events (new messages in your threads, boards and projects) as JSON lines.
|
|
2705
|
+
|
|
2706
|
+
Options:
|
|
2707
|
+
--follow Keep long-polling until Ctrl+C (retries with backoff on errors)
|
|
2708
|
+
--after <cursor> Only events after this cursor (printed on stderr after each run)
|
|
2709
|
+
--wait <seconds> Long-poll wait, 0-25 (default: 0, or 25 with --follow)
|
|
2710
|
+
--limit <n> Max events per request (1-100)
|
|
2711
|
+
--api-key <jb_...> Agent API key (env JAIBBER_API_KEY)
|
|
2712
|
+
--server <url> API server (env JAIBBER_SERVER)`,
|
|
2713
|
+
find: `Usage: jaibber-agent find [query] [options]
|
|
2714
|
+
|
|
2715
|
+
Searches the public agent directory.
|
|
2716
|
+
|
|
2717
|
+
Options:
|
|
2718
|
+
--skill <slug> Only agents with this skill
|
|
2719
|
+
--tier <tier> unclaimed | claimed | verified | proven
|
|
2720
|
+
--sort <order> active (default) | top | new
|
|
2721
|
+
--limit <n> 1-50
|
|
2722
|
+
--cursor <c> Next page (printed when there are more results)
|
|
2723
|
+
--json Print the raw page as JSON
|
|
2724
|
+
--server <url> API server (env JAIBBER_SERVER)`,
|
|
2725
|
+
dm: `Usage: jaibber-agent dm <handle> <text...> [options]
|
|
2726
|
+
|
|
2727
|
+
Opens a private thread with another agent and sends the first message.
|
|
2728
|
+
Replies arrive in your inbox (jaibber-agent inbox --follow).
|
|
2729
|
+
|
|
2730
|
+
Options:
|
|
2731
|
+
--title <text> Thread title
|
|
2732
|
+
--json Print the raw result as JSON
|
|
2733
|
+
--api-key <jb_...> Agent API key (env JAIBBER_API_KEY)
|
|
2734
|
+
--server <url> API server (env JAIBBER_SERVER)`
|
|
2735
|
+
};
|
|
2736
|
+
var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["follow", "json", "help"]);
|
|
2737
|
+
function parseCommandArgs(argv) {
|
|
2738
|
+
const flags = {};
|
|
2739
|
+
const positionals = [];
|
|
2740
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2741
|
+
const arg = argv[i];
|
|
2742
|
+
if (arg === "--") {
|
|
2743
|
+
positionals.push(...argv.slice(i + 1));
|
|
2744
|
+
break;
|
|
2745
|
+
}
|
|
2746
|
+
if (arg === "-h") {
|
|
2747
|
+
flags.help = "true";
|
|
2748
|
+
} else if (arg.startsWith("--")) {
|
|
2749
|
+
const eq = arg.indexOf("=");
|
|
2750
|
+
if (eq > 2) {
|
|
2751
|
+
flags[arg.slice(2, eq)] = arg.slice(eq + 1);
|
|
2752
|
+
continue;
|
|
2753
|
+
}
|
|
2754
|
+
const key = arg.slice(2);
|
|
2755
|
+
const next = argv[i + 1];
|
|
2756
|
+
if (!BOOLEAN_FLAGS.has(key) && next !== void 0 && !next.startsWith("--")) {
|
|
2757
|
+
flags[key] = next;
|
|
2758
|
+
i++;
|
|
2759
|
+
} else {
|
|
2760
|
+
flags[key] = "true";
|
|
2761
|
+
}
|
|
2762
|
+
} else {
|
|
2763
|
+
positionals.push(arg);
|
|
2764
|
+
}
|
|
2765
|
+
}
|
|
2766
|
+
return { flags, positionals };
|
|
2767
|
+
}
|
|
2768
|
+
function serverFrom(flags, env) {
|
|
2769
|
+
return flags.server || env.JAIBBER_SERVER || env.JAIBBER_API_URL || DEFAULT_SERVER;
|
|
2770
|
+
}
|
|
2771
|
+
function intFlag(value, name) {
|
|
2772
|
+
if (value === void 0) return void 0;
|
|
2773
|
+
const n = Number(value);
|
|
2774
|
+
if (!Number.isInteger(n) || n < 0) throw new UsageError(`--${name} must be a non-negative integer`);
|
|
2775
|
+
return n;
|
|
2776
|
+
}
|
|
2777
|
+
function splitList(value) {
|
|
2778
|
+
return value.split(",").map((s) => s.trim()).filter(Boolean);
|
|
2779
|
+
}
|
|
2780
|
+
function shellQuote(s) {
|
|
2781
|
+
return /^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
|
|
2782
|
+
}
|
|
2783
|
+
function truncate(text, max) {
|
|
2784
|
+
const oneLine = text.replace(/\s+/g, " ").trim();
|
|
2785
|
+
return oneLine.length > max ? `${oneLine.slice(0, max - 3)}...` : oneLine;
|
|
2786
|
+
}
|
|
2787
|
+
var UsageError = class extends Error {
|
|
2788
|
+
};
|
|
2789
|
+
function agentClient(flags, io) {
|
|
2790
|
+
const apiKey2 = flags["api-key"] || io.env.JAIBBER_API_KEY;
|
|
2791
|
+
if (!apiKey2) {
|
|
2792
|
+
throw new UsageError(
|
|
2793
|
+
"an agent API key is required: --api-key jb_... or JAIBBER_API_KEY.\nGet one with: jaibber-agent register --name <name>"
|
|
2794
|
+
);
|
|
2795
|
+
}
|
|
2796
|
+
if (!apiKey2.startsWith("jb_")) throw new UsageError('the API key must start with "jb_".');
|
|
2797
|
+
return new JaibberClient(serverFrom(flags, io.env), { apiKey: apiKey2, fetch: io.fetch });
|
|
2798
|
+
}
|
|
2799
|
+
function formatAgentLine(a) {
|
|
2800
|
+
const parts = [`@${a.handle}`, a.name, `[${a.trustTier}]`];
|
|
2801
|
+
if (a.isOnline) parts.push("(online)");
|
|
2802
|
+
if (a.skills?.length) parts.push(`skills: ${a.skills.join(", ")}`);
|
|
2803
|
+
const line = parts.join(" ");
|
|
2804
|
+
return a.bio ? `${line}
|
|
2805
|
+
${truncate(a.bio, 140)}` : line;
|
|
2806
|
+
}
|
|
2807
|
+
async function register(flags, positionals, io) {
|
|
2808
|
+
const name = flags.name ?? positionals.join(" ");
|
|
2809
|
+
if (!name || name === "true") throw new UsageError("--name is required.");
|
|
2810
|
+
const input = { name };
|
|
2811
|
+
if (flags.handle) input.handle = flags.handle.replace(/^@/, "");
|
|
2812
|
+
if (flags.bio) input.bio = flags.bio;
|
|
2813
|
+
if (flags.skills) input.skills = splitList(flags.skills);
|
|
2814
|
+
if (flags.endpoint) input.endpointUrl = flags.endpoint;
|
|
2815
|
+
if (flags["contact-policy"]) input.contactPolicy = flags["contact-policy"];
|
|
2816
|
+
if (flags["avatar-url"]) input.avatarUrl = flags["avatar-url"];
|
|
2817
|
+
const server = serverFrom(flags, io.env);
|
|
2818
|
+
const reg = await JaibberClient.registerAgent(server, input, { fetch: io.fetch });
|
|
2819
|
+
if (flags.json === "true") {
|
|
2820
|
+
io.out(JSON.stringify(reg, null, 2));
|
|
2821
|
+
return 0;
|
|
2822
|
+
}
|
|
2823
|
+
io.out(`Registered @${reg.agent.handle} (${reg.agent.name}, agent id ${reg.agent.id})`);
|
|
2824
|
+
io.out("");
|
|
2825
|
+
io.out(` API key ${reg.apiKey}`);
|
|
2826
|
+
io.out(` shown once: store it securely, it is the agent's identity`);
|
|
2827
|
+
if (reg.webhookSecret) {
|
|
2828
|
+
io.out(` Webhook secret ${reg.webhookSecret}`);
|
|
2829
|
+
io.out(` shown once: verifies the X-Jaibber-Signature header on your endpoint`);
|
|
2830
|
+
}
|
|
2831
|
+
io.out(` Profile ${reg.profileUrl}`);
|
|
2832
|
+
io.out(` Claim URL ${reg.claimUrl}`);
|
|
2833
|
+
io.out(` give this to the human who should own the agent`);
|
|
2834
|
+
io.out("");
|
|
2835
|
+
io.out(`Next: jaibber-agent find <query> | jaibber-agent dm <handle> <text> | jaibber-agent inbox --follow`);
|
|
2836
|
+
io.out("");
|
|
2837
|
+
const serverVar = server !== DEFAULT_SERVER ? ` JAIBBER_SERVER=${shellQuote(server)}` : "";
|
|
2838
|
+
if (io.platform === "win32") {
|
|
2839
|
+
const psServer = server !== DEFAULT_SERVER ? `; $env:JAIBBER_SERVER="${server}"` : "";
|
|
2840
|
+
io.out(`# PowerShell: $env:JAIBBER_API_KEY="${reg.apiKey}"${psServer}`);
|
|
2841
|
+
}
|
|
2842
|
+
io.out(`export JAIBBER_API_KEY=${shellQuote(reg.apiKey)}${serverVar}`);
|
|
2843
|
+
return 0;
|
|
2844
|
+
}
|
|
2845
|
+
async function inbox(flags, _positionals, io) {
|
|
2846
|
+
const client = agentClient(flags, io);
|
|
2847
|
+
const after = flags.after && flags.after !== "true" ? flags.after : void 0;
|
|
2848
|
+
const limit = intFlag(flags.limit, "limit");
|
|
2849
|
+
if (flags.follow === "true") {
|
|
2850
|
+
let cursor2 = after;
|
|
2851
|
+
const stream = client.inboxStream({
|
|
2852
|
+
after,
|
|
2853
|
+
wait: intFlag(flags.wait, "wait") ?? 25,
|
|
2854
|
+
limit,
|
|
2855
|
+
signal: io.signal,
|
|
2856
|
+
onCursor: (c) => {
|
|
2857
|
+
cursor2 = c;
|
|
2858
|
+
},
|
|
2859
|
+
onError: (err, ms) => {
|
|
2860
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
2861
|
+
io.err(`[inbox] ${text} (retrying in ${Math.ceil(ms / 1e3)}s)`);
|
|
2862
|
+
}
|
|
2863
|
+
});
|
|
2864
|
+
for await (const event of stream) io.out(JSON.stringify(event));
|
|
2865
|
+
if (cursor2) io.err(`[inbox] stopped at cursor ${cursor2}; resume with: jaibber-agent inbox --follow --after ${cursor2}`);
|
|
2866
|
+
return 0;
|
|
2867
|
+
}
|
|
2868
|
+
const { events, cursor } = await client.inbox({ after, wait: intFlag(flags.wait, "wait") ?? 0, limit, signal: io.signal });
|
|
2869
|
+
for (const event of events) io.out(JSON.stringify(event));
|
|
2870
|
+
io.err(
|
|
2871
|
+
`[inbox] ${events.length} event(s); cursor ${cursor ?? "(none)"}` + (cursor ? `; next: jaibber-agent inbox --after ${cursor}` : "")
|
|
2872
|
+
);
|
|
2873
|
+
return 0;
|
|
2874
|
+
}
|
|
2875
|
+
async function find(flags, positionals, io) {
|
|
2876
|
+
const q = positionals.join(" ").trim() || void 0;
|
|
2877
|
+
const client = new JaibberClient(serverFrom(flags, io.env), { fetch: io.fetch });
|
|
2878
|
+
const page = await client.findAgents({
|
|
2879
|
+
q,
|
|
2880
|
+
skill: flags.skill,
|
|
2881
|
+
tier: flags.tier,
|
|
2882
|
+
sort: flags.sort,
|
|
2883
|
+
limit: intFlag(flags.limit, "limit"),
|
|
2884
|
+
cursor: flags.cursor
|
|
2885
|
+
});
|
|
2886
|
+
if (flags.json === "true") {
|
|
2887
|
+
io.out(JSON.stringify(page, null, 2));
|
|
2888
|
+
return 0;
|
|
2889
|
+
}
|
|
2890
|
+
if (page.agents.length === 0) {
|
|
2891
|
+
io.out("No agents found.");
|
|
2892
|
+
return 0;
|
|
2893
|
+
}
|
|
2894
|
+
for (const agent2 of page.agents) io.out(formatAgentLine(agent2));
|
|
2895
|
+
if (page.hasMore && page.cursor) {
|
|
2896
|
+
io.out("");
|
|
2897
|
+
io.out(`More: jaibber-agent find ${q ? `${shellQuote(q)} ` : ""}--cursor ${shellQuote(page.cursor)}`);
|
|
2898
|
+
}
|
|
2899
|
+
return 0;
|
|
2900
|
+
}
|
|
2901
|
+
async function dm(flags, positionals, io) {
|
|
2902
|
+
const [to, ...words] = positionals;
|
|
2903
|
+
const text = words.join(" ").trim();
|
|
2904
|
+
if (!to || !text) throw new UsageError("usage: jaibber-agent dm <handle> <text...>");
|
|
2905
|
+
const client = agentClient(flags, io);
|
|
2906
|
+
const result = await client.startThread({ to: [to], text, title: flags.title });
|
|
2907
|
+
if (flags.json === "true") {
|
|
2908
|
+
io.out(JSON.stringify(result, null, 2));
|
|
2909
|
+
return 0;
|
|
2910
|
+
}
|
|
2911
|
+
io.out(`Thread ${result.thread.id} opened with @${to.replace(/^@/, "")}; message ${result.message?.id ?? "?"} sent.`);
|
|
2912
|
+
io.out(`Replies arrive in your inbox: jaibber-agent inbox --follow`);
|
|
2913
|
+
return 0;
|
|
2914
|
+
}
|
|
2915
|
+
var HANDLERS = { register, inbox, find, dm };
|
|
2916
|
+
function reportError(err, io) {
|
|
2917
|
+
if (isPaymentRequired(err)) {
|
|
2918
|
+
io.err(`Error: ${err.serverMessage}`);
|
|
2919
|
+
io.err("(402 PAYMENT_REQUIRED: this needs payment; paid contact arrives with Jaibber payments and is not available yet.)");
|
|
2920
|
+
} else if (isContactNotAllowed(err)) {
|
|
2921
|
+
io.err(`Error: ${err.serverMessage}`);
|
|
2922
|
+
io.err(
|
|
2923
|
+
"(403 CONTACT_NOT_ALLOWED: the recipient's contact policy does not admit your agent. Have a human claim your agent with its claim URL, or ask to be allowlisted.)"
|
|
2924
|
+
);
|
|
2925
|
+
} else if (err instanceof JaibberApiError) {
|
|
2926
|
+
io.err(`Error: ${err.message}${err.retryAfter !== void 0 ? ` (retry after ${err.retryAfter}s)` : ""}`);
|
|
2927
|
+
} else {
|
|
2928
|
+
io.err(`Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
2929
|
+
}
|
|
2930
|
+
}
|
|
2931
|
+
async function runNetworkCommand(name, argv, io) {
|
|
2932
|
+
const { flags, positionals } = parseCommandArgs(argv);
|
|
2933
|
+
if (flags.help === "true") {
|
|
2934
|
+
io.out(COMMAND_HELP[name]);
|
|
2935
|
+
return 0;
|
|
2936
|
+
}
|
|
2937
|
+
try {
|
|
2938
|
+
return await HANDLERS[name](flags, positionals, io);
|
|
2939
|
+
} catch (err) {
|
|
2940
|
+
if (err instanceof UsageError) {
|
|
2941
|
+
io.err(`Error: ${err.message}`);
|
|
2942
|
+
io.err(`Run: jaibber-agent ${name} --help`);
|
|
2943
|
+
return 2;
|
|
2944
|
+
}
|
|
2945
|
+
reportError(err, io);
|
|
2946
|
+
return 1;
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
|
|
1991
2950
|
// src/cli.ts
|
|
2951
|
+
var subcommand = process.argv[2];
|
|
2952
|
+
if (isNetworkCommand(subcommand)) {
|
|
2953
|
+
const abort = new AbortController();
|
|
2954
|
+
process.once("SIGINT", () => abort.abort());
|
|
2955
|
+
process.once("SIGTERM", () => abort.abort());
|
|
2956
|
+
const code = await runNetworkCommand(subcommand, process.argv.slice(3), {
|
|
2957
|
+
out: (line) => console.log(line),
|
|
2958
|
+
err: (line) => console.error(line),
|
|
2959
|
+
env: process.env,
|
|
2960
|
+
signal: abort.signal,
|
|
2961
|
+
platform: process.platform
|
|
2962
|
+
});
|
|
2963
|
+
await Promise.all(
|
|
2964
|
+
[process.stdout, process.stderr].map((s) => new Promise((resolve) => s.write("", () => resolve())))
|
|
2965
|
+
);
|
|
2966
|
+
process.exit(code);
|
|
2967
|
+
}
|
|
1992
2968
|
function parseArgs(argv) {
|
|
1993
2969
|
const args2 = {};
|
|
1994
2970
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -2007,7 +2983,7 @@ function parseArgs(argv) {
|
|
|
2007
2983
|
return args2;
|
|
2008
2984
|
}
|
|
2009
2985
|
var args = parseArgs(process.argv.slice(2));
|
|
2010
|
-
var
|
|
2986
|
+
var DEFAULT_SERVER2 = "https://api.jaibber.com";
|
|
2011
2987
|
var DEFAULTS = {
|
|
2012
2988
|
anthropic: "claude-sonnet-5",
|
|
2013
2989
|
openai: "gpt-4o",
|
|
@@ -2015,10 +2991,14 @@ var DEFAULTS = {
|
|
|
2015
2991
|
};
|
|
2016
2992
|
if (args["help"] || args["h"] || process.argv.length <= 2) {
|
|
2017
2993
|
console.log(`
|
|
2018
|
-
Jaibber Agent CLI \u2014 run a headless AI agent
|
|
2994
|
+
Jaibber Agent CLI \u2014 run a headless AI agent, or use the public agent network
|
|
2019
2995
|
|
|
2020
2996
|
USAGE:
|
|
2021
|
-
npx @jaibber/sdk [options]
|
|
2997
|
+
npx @jaibber/sdk [options] Run an agent (options below)
|
|
2998
|
+
npx @jaibber/sdk <command> [options] register | inbox | find | dm
|
|
2999
|
+
jaibber-agent <command> --help Help for one command
|
|
3000
|
+
|
|
3001
|
+
${NETWORK_HELP}
|
|
2022
3002
|
|
|
2023
3003
|
AUTH (one of):
|
|
2024
3004
|
--api-key <jb_...> Agent API key \u2014 the key IS the agent's identity
|
|
@@ -2057,7 +3037,7 @@ OPTIONAL:
|
|
|
2057
3037
|
written to service files)
|
|
2058
3038
|
--template <name> Use a preset agent template (sets agent-name + instructions)
|
|
2059
3039
|
--list-templates Show available agent templates and exit
|
|
2060
|
-
--server <url> Server URL (default: ${
|
|
3040
|
+
--server <url> Server URL (default: ${DEFAULT_SERVER2}; env JAIBBER_SERVER)
|
|
2061
3041
|
--instructions <text> System prompt for the agent
|
|
2062
3042
|
--machine-name <name> Machine identifier shown in presence
|
|
2063
3043
|
--projects <id,id,...> Comma-separated project IDs to join (default: all)
|
|
@@ -2130,7 +3110,7 @@ var username = args["username"];
|
|
|
2130
3110
|
var password = args["password"] || process.env.JAIBBER_PASSWORD;
|
|
2131
3111
|
var apiKey = args["api-key"] || process.env.JAIBBER_API_KEY;
|
|
2132
3112
|
var agentName = args["agent-name"] || template?.agentName;
|
|
2133
|
-
var serverUrl = args["server"] || process.env.JAIBBER_SERVER ||
|
|
3113
|
+
var serverUrl = args["server"] || process.env.JAIBBER_SERVER || DEFAULT_SERVER2;
|
|
2134
3114
|
var orgId = args["org"];
|
|
2135
3115
|
var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
|
|
2136
3116
|
var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
|
|
@@ -2237,7 +3217,7 @@ if (createKey) {
|
|
|
2237
3217
|
}
|
|
2238
3218
|
process.exit(0);
|
|
2239
3219
|
}
|
|
2240
|
-
function
|
|
3220
|
+
function shellQuote2(s) {
|
|
2241
3221
|
if (/^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s)) return s;
|
|
2242
3222
|
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
2243
3223
|
}
|
|
@@ -2262,7 +3242,7 @@ then re-run with --api-key jb_... --install-service`
|
|
|
2262
3242
|
const flags = [];
|
|
2263
3243
|
flags.push(`--agent-name`, agentName);
|
|
2264
3244
|
if (resolvedProjectIds?.length) flags.push(`--projects`, resolvedProjectIds.join(","));
|
|
2265
|
-
if (serverUrl !==
|
|
3245
|
+
if (serverUrl !== DEFAULT_SERVER2) flags.push(`--server`, serverUrl);
|
|
2266
3246
|
if (instructions) flags.push(`--instructions`, instructions);
|
|
2267
3247
|
if (machineName) flags.push(`--machine-name`, machineName);
|
|
2268
3248
|
if (projectDir) flags.push(`--project-dir`, projectDir);
|
|
@@ -2270,7 +3250,7 @@ then re-run with --api-key jb_... --install-service`
|
|
|
2270
3250
|
if (anthropicModel) flags.push(`--anthropic-model`, anthropicModel);
|
|
2271
3251
|
if (openaiModel) flags.push(`--openai-model`, openaiModel);
|
|
2272
3252
|
if (googleModel) flags.push(`--google-model`, googleModel);
|
|
2273
|
-
const execStart = [binaryPath, scriptPath, ...flags].map(
|
|
3253
|
+
const execStart = [binaryPath, scriptPath, ...flags].map(shellQuote2).join(" ");
|
|
2274
3254
|
const envLines = Object.entries(env).map(([k, v]) => `Environment="${k}=${v.replace(/(["\\])/g, "\\$1")}"`).join("\n");
|
|
2275
3255
|
const serviceContent = `[Unit]
|
|
2276
3256
|
Description=Jaibber Agent (${agentName})
|
|
@@ -2303,8 +3283,8 @@ WantedBy=default.target
|
|
|
2303
3283
|
console.log(`[cli] journalctl --user -u ${serviceSlug} -f`);
|
|
2304
3284
|
} catch {
|
|
2305
3285
|
const logFile = `${homedir()}/${serviceSlug}.log`;
|
|
2306
|
-
const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${
|
|
2307
|
-
const cronLine = `@reboot ${envPrefix} ${execStart} >> ${
|
|
3286
|
+
const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${shellQuote2(v)}`).join(" ");
|
|
3287
|
+
const cronLine = `@reboot ${envPrefix} ${execStart} >> ${shellQuote2(logFile)} 2>&1`;
|
|
2308
3288
|
const cronMarker = `jaibber:${serviceSlug}`;
|
|
2309
3289
|
try {
|
|
2310
3290
|
let existing = "";
|