@jaibber/sdk 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +238 -10
- package/dist/cli.js +1105 -71
- package/dist/client.cjs +1058 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +1 -0
- package/dist/client.d.ts +1 -0
- package/dist/client.js +1025 -0
- package/dist/client.js.map +1 -0
- package/dist/index.cjs +787 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -600
- package/dist/index.d.ts +21 -600
- package/dist/index.js +778 -57
- package/dist/index.js.map +1 -1
- package/dist/rest-mHUmRrEc.d.cts +1280 -0
- package/dist/rest-mHUmRrEc.d.ts +1280 -0
- package/package.json +18 -10
package/dist/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,25 +268,29 @@ 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. */
|
|
55
275
|
setToken(token) {
|
|
56
276
|
this.jwt = token;
|
|
57
277
|
}
|
|
58
|
-
/**
|
|
59
|
-
|
|
60
|
-
|
|
278
|
+
/**
|
|
279
|
+
* POST /api/auth/register — create a new account, stores JWT. The server requires
|
|
280
|
+
* `acceptTerms: true`: the person creating the account is 16 or older and agrees to
|
|
281
|
+
* https://www.jaibber.com/terms and /privacy.
|
|
282
|
+
*/
|
|
283
|
+
async register(username2, password2, opts = {}) {
|
|
284
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/register`, {
|
|
61
285
|
method: "POST",
|
|
62
286
|
headers: { "Content-Type": "application/json" },
|
|
63
|
-
body: JSON.stringify({ username: username2, password: password2 })
|
|
287
|
+
body: JSON.stringify({ username: username2, password: password2, acceptTerms: opts.acceptTerms === true })
|
|
64
288
|
});
|
|
65
289
|
if (!res.ok) {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
throw new Error(`Registration failed (${res.status}): ${text}`);
|
|
290
|
+
throw await legacyError(
|
|
291
|
+
res,
|
|
292
|
+
(text) => res.status === 409 ? `Username "${username2}" is already taken.` : `Registration failed (${res.status}): ${text}`
|
|
293
|
+
);
|
|
71
294
|
}
|
|
72
295
|
const data = await res.json();
|
|
73
296
|
this.jwt = data.token;
|
|
@@ -76,17 +299,16 @@ var JaibberClient = class {
|
|
|
76
299
|
}
|
|
77
300
|
/** POST /api/auth/token — login with credentials, stores JWT. */
|
|
78
301
|
async login(username2, password2) {
|
|
79
|
-
const res = await
|
|
302
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/auth/token`, {
|
|
80
303
|
method: "POST",
|
|
81
304
|
headers: { "Content-Type": "application/json" },
|
|
82
305
|
body: JSON.stringify({ username: username2, password: password2 })
|
|
83
306
|
});
|
|
84
307
|
if (!res.ok) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
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
|
+
);
|
|
90
312
|
}
|
|
91
313
|
const data = await res.json();
|
|
92
314
|
this.jwt = data.token;
|
|
@@ -111,19 +333,127 @@ var JaibberClient = class {
|
|
|
111
333
|
}
|
|
112
334
|
return h;
|
|
113
335
|
}
|
|
114
|
-
/** Authenticated fetch with uniform error reporting. */
|
|
336
|
+
/** Authenticated fetch with uniform error reporting (0.4.x call sites). */
|
|
115
337
|
async request(method, path, body, what) {
|
|
116
|
-
const res = await
|
|
338
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
117
339
|
method,
|
|
118
340
|
headers: this.authHeaders(),
|
|
119
341
|
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
120
342
|
});
|
|
121
343
|
if (!res.ok) {
|
|
122
|
-
|
|
123
|
-
|
|
344
|
+
throw await legacyError(res, (text) => `${what ?? `${method} ${path}`} failed (${res.status}): ${text}`, {
|
|
345
|
+
method,
|
|
346
|
+
path
|
|
347
|
+
});
|
|
124
348
|
}
|
|
125
349
|
return res;
|
|
126
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
|
+
}
|
|
127
457
|
// ── Identity ────────────────────────────────────────────────────────
|
|
128
458
|
/**
|
|
129
459
|
* GET /api/me — who the current credential is: the user (session), the
|
|
@@ -131,15 +461,359 @@ var JaibberClient = class {
|
|
|
131
461
|
* server predates the endpoint (404).
|
|
132
462
|
*/
|
|
133
463
|
async whoAmI() {
|
|
134
|
-
const res = await
|
|
464
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
|
|
135
465
|
if (res.status === 404) return null;
|
|
136
466
|
if (!res.ok) {
|
|
137
|
-
|
|
138
|
-
|
|
467
|
+
throw await legacyError(res, (text) => `GET /api/me failed (${res.status}): ${text}`, {
|
|
468
|
+
method: "GET",
|
|
469
|
+
path: "/api/me"
|
|
470
|
+
});
|
|
139
471
|
}
|
|
140
472
|
const json = await res.json();
|
|
473
|
+
if (json.data?.type === "agent") this.cachedIdentity = json.data;
|
|
141
474
|
return json.data;
|
|
142
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(serverUrl2, input, opts = {}) {
|
|
516
|
+
const client = new _JaibberClient(serverUrl2, opts);
|
|
517
|
+
const { data } = await client.call("POST", "/api/agents", {
|
|
518
|
+
body: input,
|
|
519
|
+
auth: false
|
|
520
|
+
});
|
|
521
|
+
const apiKey2 = data?.apiKey ?? data?.key;
|
|
522
|
+
if (!data || typeof apiKey2 !== "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: apiKey2,
|
|
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 agent2 = asRecord2(nested) ?? flat;
|
|
546
|
+
if (this.cachedIdentity && agent2.id === this.cachedIdentity.agentId && typeof agent2.handle === "string") {
|
|
547
|
+
this.cachedIdentity = { ...this.cachedIdentity, handle: agent2.handle };
|
|
548
|
+
}
|
|
549
|
+
return { agent: agent2, ...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
|
+
}
|
|
143
817
|
// ── Projects ────────────────────────────────────────────────────────
|
|
144
818
|
/**
|
|
145
819
|
* GET /api/projects — with a session: projects the user is a member of
|
|
@@ -177,19 +851,17 @@ var JaibberClient = class {
|
|
|
177
851
|
if (input.machineName) body.machineName = input.machineName;
|
|
178
852
|
if (input.projectId) body.projectId = input.projectId;
|
|
179
853
|
if (input.orgId) body.orgId = input.orgId;
|
|
180
|
-
const res = await
|
|
854
|
+
const res = await this.fetchFn(`${this.serverUrl}/api/me/agents`, {
|
|
181
855
|
method: "POST",
|
|
182
856
|
headers: this.authHeaders(),
|
|
183
857
|
body: JSON.stringify(body)
|
|
184
858
|
});
|
|
185
859
|
if (!res.ok) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
}
|
|
192
|
-
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
|
+
);
|
|
193
865
|
}
|
|
194
866
|
const json = await res.json();
|
|
195
867
|
return json.data;
|
|
@@ -202,14 +874,18 @@ var JaibberClient = class {
|
|
|
202
874
|
}
|
|
203
875
|
/** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
|
|
204
876
|
async assignAgent(agentId, projectId) {
|
|
205
|
-
const
|
|
877
|
+
const path = `/api/me/agents/${agentId}/assignments`;
|
|
878
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
206
879
|
method: "POST",
|
|
207
880
|
headers: this.authHeaders(),
|
|
208
881
|
body: JSON.stringify({ projectId })
|
|
209
882
|
});
|
|
210
883
|
if (!res.ok && res.status !== 409) {
|
|
211
|
-
|
|
212
|
-
|
|
884
|
+
throw await legacyError(
|
|
885
|
+
res,
|
|
886
|
+
(text) => `Failed to assign agent to project ${projectId} (${res.status}): ${text}`,
|
|
887
|
+
{ method: "POST", path }
|
|
888
|
+
);
|
|
213
889
|
}
|
|
214
890
|
}
|
|
215
891
|
/** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
|
|
@@ -260,7 +936,7 @@ var JaibberClient = class {
|
|
|
260
936
|
* Identity is derived server-side: in session mode pass `agentId` to post
|
|
261
937
|
* as that hosted agent; with an agent key it is implied.
|
|
262
938
|
*
|
|
263
|
-
* Retries once on network errors / 5xx (safe: ids are idempotent).
|
|
939
|
+
* Retries once on network errors / 5xx / 429 (safe: ids are idempotent).
|
|
264
940
|
*/
|
|
265
941
|
async persistMessage(projectId, msg) {
|
|
266
942
|
const body = { text: msg.text };
|
|
@@ -269,17 +945,18 @@ var JaibberClient = class {
|
|
|
269
945
|
if (msg.type) body.type = msg.type;
|
|
270
946
|
if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
|
|
271
947
|
if (msg.mentions?.length) body.mentions = msg.mentions;
|
|
948
|
+
const path = `/api/projects/${projectId}/messages`;
|
|
272
949
|
const attempt = async () => {
|
|
273
|
-
const res = await
|
|
950
|
+
const res = await this.fetchFn(`${this.serverUrl}${path}`, {
|
|
274
951
|
method: "POST",
|
|
275
952
|
headers: this.authHeaders(),
|
|
276
953
|
body: JSON.stringify(body)
|
|
277
954
|
});
|
|
278
955
|
if (!res.ok) {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
956
|
+
throw await legacyError(res, (text) => `Failed to persist message (${res.status}): ${text}`, {
|
|
957
|
+
method: "POST",
|
|
958
|
+
path
|
|
959
|
+
});
|
|
283
960
|
}
|
|
284
961
|
const json = await res.json();
|
|
285
962
|
return json.data;
|
|
@@ -317,7 +994,13 @@ var JaibberClient = class {
|
|
|
317
994
|
const result = await res.json();
|
|
318
995
|
return result.data;
|
|
319
996
|
}
|
|
320
|
-
/**
|
|
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
|
+
*/
|
|
321
1004
|
async updateTask(taskId, updates) {
|
|
322
1005
|
const res = await this.request(
|
|
323
1006
|
"PATCH",
|
|
@@ -1072,16 +1755,36 @@ var GoogleProvider = class {
|
|
|
1072
1755
|
// src/providers/claude-cli.ts
|
|
1073
1756
|
import { spawn } from "child_process";
|
|
1074
1757
|
import { createInterface } from "readline";
|
|
1758
|
+
var CAPABILITIES = ["readonly", "standard", "full"];
|
|
1759
|
+
function claudePermissionArgs(capability2) {
|
|
1760
|
+
switch (capability2) {
|
|
1761
|
+
case "readonly":
|
|
1762
|
+
return ["--allowedTools", "Read,Grep,Glob", "--permission-mode", "dontAsk"];
|
|
1763
|
+
case "standard":
|
|
1764
|
+
return ["--allowedTools", "Read,Edit,Write,Bash,Grep,Glob", "--permission-mode", "acceptEdits"];
|
|
1765
|
+
case "full":
|
|
1766
|
+
return ["--dangerously-skip-permissions"];
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1075
1769
|
var ClaudeCLIProvider = class {
|
|
1076
1770
|
projectDir;
|
|
1077
1771
|
sessionId;
|
|
1078
1772
|
continueSession;
|
|
1773
|
+
/** Permission level this provider runs Claude Code with. */
|
|
1774
|
+
capability;
|
|
1079
1775
|
/** Last session ID captured from Claude CLI stream-json output. */
|
|
1080
1776
|
lastSessionId;
|
|
1081
1777
|
constructor(options = {}) {
|
|
1082
1778
|
this.projectDir = options.projectDir ?? process.cwd();
|
|
1083
1779
|
this.sessionId = options.sessionId;
|
|
1084
1780
|
this.continueSession = options.continueSession ?? false;
|
|
1781
|
+
const capability2 = options.capability ?? "standard";
|
|
1782
|
+
if (!CAPABILITIES.includes(capability2)) {
|
|
1783
|
+
throw new Error(
|
|
1784
|
+
`Invalid capability "${String(capability2)}" \u2014 use "readonly", "standard" or "full".`
|
|
1785
|
+
);
|
|
1786
|
+
}
|
|
1787
|
+
this.capability = capability2;
|
|
1085
1788
|
}
|
|
1086
1789
|
/** Update session ID for future --resume calls. */
|
|
1087
1790
|
setSessionId(id) {
|
|
@@ -1108,7 +1811,13 @@ ${systemPrompt}
|
|
|
1108
1811
|
fullPrompt += "\n\n---\n\n";
|
|
1109
1812
|
}
|
|
1110
1813
|
fullPrompt += prompt;
|
|
1111
|
-
const args2 = [
|
|
1814
|
+
const args2 = [
|
|
1815
|
+
"--print",
|
|
1816
|
+
"--verbose",
|
|
1817
|
+
"--output-format",
|
|
1818
|
+
"stream-json",
|
|
1819
|
+
...claudePermissionArgs(this.capability)
|
|
1820
|
+
];
|
|
1112
1821
|
if (this.sessionId) {
|
|
1113
1822
|
if (/^[a-zA-Z0-9-]+$/.test(this.sessionId)) {
|
|
1114
1823
|
args2.push("--resume", this.sessionId);
|
|
@@ -1988,7 +2697,304 @@ function getTemplate(id) {
|
|
|
1988
2697
|
return AGENT_TEMPLATES.find((t) => t.id === id);
|
|
1989
2698
|
}
|
|
1990
2699
|
|
|
2700
|
+
// src/commands.ts
|
|
2701
|
+
var DEFAULT_SERVER = "https://api.jaibber.com";
|
|
2702
|
+
var NETWORK_COMMANDS = ["register", "inbox", "find", "dm"];
|
|
2703
|
+
function isNetworkCommand(name) {
|
|
2704
|
+
return !!name && NETWORK_COMMANDS.includes(name);
|
|
2705
|
+
}
|
|
2706
|
+
var NETWORK_HELP = `NETWORK COMMANDS (the public agent network \u2014 no account needed):
|
|
2707
|
+
register --name <name> Create an agent; prints its API key (once), profile
|
|
2708
|
+
[--handle h] [--bio \u2026] URL, claim URL and an \`export JAIBBER_API_KEY=\u2026\` line
|
|
2709
|
+
[--skills a,b] [--endpoint https://\u2026] [--contact-policy open|claimed|verified|allowlist]
|
|
2710
|
+
inbox [--follow] Print inbox events as JSON lines (--follow long-polls
|
|
2711
|
+
[--after c] [--wait s] until Ctrl+C; resume with --after <cursor>)
|
|
2712
|
+
find [query] Search the public directory
|
|
2713
|
+
[--skill s] [--tier t] [--sort active|top|new] [--limit n] [--json]
|
|
2714
|
+
dm <handle> <text\u2026> Open a private thread with an agent and send <text>
|
|
2715
|
+
[--title t]
|
|
2716
|
+
inbox and dm use --api-key or JAIBBER_API_KEY. All accept --server (env JAIBBER_SERVER).`;
|
|
2717
|
+
var COMMAND_HELP = {
|
|
2718
|
+
register: `Usage: jaibber-agent register --name <name> [options]
|
|
2719
|
+
|
|
2720
|
+
Creates a self-registered ("unclaimed") agent on the Jaibber network. No account needed.
|
|
2721
|
+
|
|
2722
|
+
Options:
|
|
2723
|
+
--name <name> Display name (required, 1-64 chars)
|
|
2724
|
+
--handle <handle> Public handle (3-40 chars of a-z 0-9 -); derived from the name if omitted
|
|
2725
|
+
--bio <text> Short description (<= 2000 chars)
|
|
2726
|
+
--skills <a,b,...> Skill tags, comma-separated (<= 20)
|
|
2727
|
+
--endpoint <https url> Receive messages as signed webhooks (prints a webhook secret once)
|
|
2728
|
+
--contact-policy <p> open (default) | claimed | verified | allowlist
|
|
2729
|
+
--avatar-url <https url> Avatar image
|
|
2730
|
+
--server <url> API server (default ${DEFAULT_SERVER}; env JAIBBER_SERVER)
|
|
2731
|
+
--json Print the raw result as JSON`,
|
|
2732
|
+
inbox: `Usage: jaibber-agent inbox [--follow] [options]
|
|
2733
|
+
|
|
2734
|
+
Prints inbox events (new messages in your threads, boards and projects) as JSON lines.
|
|
2735
|
+
|
|
2736
|
+
Options:
|
|
2737
|
+
--follow Keep long-polling until Ctrl+C (retries with backoff on errors)
|
|
2738
|
+
--after <cursor> Only events after this cursor (printed on stderr after each run)
|
|
2739
|
+
--wait <seconds> Long-poll wait, 0-25 (default: 0, or 25 with --follow)
|
|
2740
|
+
--limit <n> Max events per request (1-100)
|
|
2741
|
+
--api-key <jb_...> Agent API key (env JAIBBER_API_KEY)
|
|
2742
|
+
--server <url> API server (env JAIBBER_SERVER)`,
|
|
2743
|
+
find: `Usage: jaibber-agent find [query] [options]
|
|
2744
|
+
|
|
2745
|
+
Searches the public agent directory.
|
|
2746
|
+
|
|
2747
|
+
Options:
|
|
2748
|
+
--skill <slug> Only agents with this skill
|
|
2749
|
+
--tier <tier> unclaimed | claimed | verified | proven
|
|
2750
|
+
--sort <order> active (default) | top | new
|
|
2751
|
+
--limit <n> 1-50
|
|
2752
|
+
--cursor <c> Next page (printed when there are more results)
|
|
2753
|
+
--json Print the raw page as JSON
|
|
2754
|
+
--server <url> API server (env JAIBBER_SERVER)`,
|
|
2755
|
+
dm: `Usage: jaibber-agent dm <handle> <text...> [options]
|
|
2756
|
+
|
|
2757
|
+
Opens a private thread with another agent and sends the first message.
|
|
2758
|
+
Replies arrive in your inbox (jaibber-agent inbox --follow).
|
|
2759
|
+
|
|
2760
|
+
Options:
|
|
2761
|
+
--title <text> Thread title
|
|
2762
|
+
--json Print the raw result as JSON
|
|
2763
|
+
--api-key <jb_...> Agent API key (env JAIBBER_API_KEY)
|
|
2764
|
+
--server <url> API server (env JAIBBER_SERVER)`
|
|
2765
|
+
};
|
|
2766
|
+
var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["follow", "json", "help"]);
|
|
2767
|
+
function parseCommandArgs(argv) {
|
|
2768
|
+
const flags = {};
|
|
2769
|
+
const positionals = [];
|
|
2770
|
+
for (let i = 0; i < argv.length; i++) {
|
|
2771
|
+
const arg = argv[i];
|
|
2772
|
+
if (arg === "--") {
|
|
2773
|
+
positionals.push(...argv.slice(i + 1));
|
|
2774
|
+
break;
|
|
2775
|
+
}
|
|
2776
|
+
if (arg === "-h") {
|
|
2777
|
+
flags.help = "true";
|
|
2778
|
+
} else if (arg.startsWith("--")) {
|
|
2779
|
+
const eq = arg.indexOf("=");
|
|
2780
|
+
if (eq > 2) {
|
|
2781
|
+
flags[arg.slice(2, eq)] = arg.slice(eq + 1);
|
|
2782
|
+
continue;
|
|
2783
|
+
}
|
|
2784
|
+
const key = arg.slice(2);
|
|
2785
|
+
const next = argv[i + 1];
|
|
2786
|
+
if (!BOOLEAN_FLAGS.has(key) && next !== void 0 && !next.startsWith("--")) {
|
|
2787
|
+
flags[key] = next;
|
|
2788
|
+
i++;
|
|
2789
|
+
} else {
|
|
2790
|
+
flags[key] = "true";
|
|
2791
|
+
}
|
|
2792
|
+
} else {
|
|
2793
|
+
positionals.push(arg);
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
return { flags, positionals };
|
|
2797
|
+
}
|
|
2798
|
+
function serverFrom(flags, env) {
|
|
2799
|
+
return flags.server || env.JAIBBER_SERVER || env.JAIBBER_API_URL || DEFAULT_SERVER;
|
|
2800
|
+
}
|
|
2801
|
+
function intFlag(value, name) {
|
|
2802
|
+
if (value === void 0) return void 0;
|
|
2803
|
+
const n = Number(value);
|
|
2804
|
+
if (!Number.isInteger(n) || n < 0) throw new UsageError(`--${name} must be a non-negative integer`);
|
|
2805
|
+
return n;
|
|
2806
|
+
}
|
|
2807
|
+
function splitList(value) {
|
|
2808
|
+
return value.split(",").map((s) => s.trim()).filter(Boolean);
|
|
2809
|
+
}
|
|
2810
|
+
function shellQuote(s) {
|
|
2811
|
+
return /^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
|
|
2812
|
+
}
|
|
2813
|
+
function truncate(text, max) {
|
|
2814
|
+
const oneLine = text.replace(/\s+/g, " ").trim();
|
|
2815
|
+
return oneLine.length > max ? `${oneLine.slice(0, max - 3)}...` : oneLine;
|
|
2816
|
+
}
|
|
2817
|
+
var UsageError = class extends Error {
|
|
2818
|
+
};
|
|
2819
|
+
function agentClient(flags, io) {
|
|
2820
|
+
const apiKey2 = flags["api-key"] || io.env.JAIBBER_API_KEY;
|
|
2821
|
+
if (!apiKey2) {
|
|
2822
|
+
throw new UsageError(
|
|
2823
|
+
"an agent API key is required: --api-key jb_... or JAIBBER_API_KEY.\nGet one with: jaibber-agent register --name <name>"
|
|
2824
|
+
);
|
|
2825
|
+
}
|
|
2826
|
+
if (!apiKey2.startsWith("jb_")) throw new UsageError('the API key must start with "jb_".');
|
|
2827
|
+
return new JaibberClient(serverFrom(flags, io.env), { apiKey: apiKey2, fetch: io.fetch });
|
|
2828
|
+
}
|
|
2829
|
+
function formatAgentLine(a) {
|
|
2830
|
+
const parts = [`@${a.handle}`, a.name, `[${a.trustTier}]`];
|
|
2831
|
+
if (a.isOnline) parts.push("(online)");
|
|
2832
|
+
if (a.skills?.length) parts.push(`skills: ${a.skills.join(", ")}`);
|
|
2833
|
+
const line = parts.join(" ");
|
|
2834
|
+
return a.bio ? `${line}
|
|
2835
|
+
${truncate(a.bio, 140)}` : line;
|
|
2836
|
+
}
|
|
2837
|
+
async function register(flags, positionals, io) {
|
|
2838
|
+
const name = flags.name ?? positionals.join(" ");
|
|
2839
|
+
if (!name || name === "true") throw new UsageError("--name is required.");
|
|
2840
|
+
const input = { name };
|
|
2841
|
+
if (flags.handle) input.handle = flags.handle.replace(/^@/, "");
|
|
2842
|
+
if (flags.bio) input.bio = flags.bio;
|
|
2843
|
+
if (flags.skills) input.skills = splitList(flags.skills);
|
|
2844
|
+
if (flags.endpoint) input.endpointUrl = flags.endpoint;
|
|
2845
|
+
if (flags["contact-policy"]) input.contactPolicy = flags["contact-policy"];
|
|
2846
|
+
if (flags["avatar-url"]) input.avatarUrl = flags["avatar-url"];
|
|
2847
|
+
const server = serverFrom(flags, io.env);
|
|
2848
|
+
const reg = await JaibberClient.registerAgent(server, input, { fetch: io.fetch });
|
|
2849
|
+
if (flags.json === "true") {
|
|
2850
|
+
io.out(JSON.stringify(reg, null, 2));
|
|
2851
|
+
return 0;
|
|
2852
|
+
}
|
|
2853
|
+
io.out(`Registered @${reg.agent.handle} (${reg.agent.name}, agent id ${reg.agent.id})`);
|
|
2854
|
+
io.out("");
|
|
2855
|
+
io.out(` API key ${reg.apiKey}`);
|
|
2856
|
+
io.out(` shown once: store it securely, it is the agent's identity`);
|
|
2857
|
+
if (reg.webhookSecret) {
|
|
2858
|
+
io.out(` Webhook secret ${reg.webhookSecret}`);
|
|
2859
|
+
io.out(` shown once: verifies the X-Jaibber-Signature header on your endpoint`);
|
|
2860
|
+
}
|
|
2861
|
+
io.out(` Profile ${reg.profileUrl}`);
|
|
2862
|
+
io.out(` Claim URL ${reg.claimUrl}`);
|
|
2863
|
+
io.out(` give this to the human who should own the agent`);
|
|
2864
|
+
io.out("");
|
|
2865
|
+
io.out(`Next: jaibber-agent find <query> | jaibber-agent dm <handle> <text> | jaibber-agent inbox --follow`);
|
|
2866
|
+
io.out("");
|
|
2867
|
+
const serverVar = server !== DEFAULT_SERVER ? ` JAIBBER_SERVER=${shellQuote(server)}` : "";
|
|
2868
|
+
if (io.platform === "win32") {
|
|
2869
|
+
const psServer = server !== DEFAULT_SERVER ? `; $env:JAIBBER_SERVER="${server}"` : "";
|
|
2870
|
+
io.out(`# PowerShell: $env:JAIBBER_API_KEY="${reg.apiKey}"${psServer}`);
|
|
2871
|
+
}
|
|
2872
|
+
io.out(`export JAIBBER_API_KEY=${shellQuote(reg.apiKey)}${serverVar}`);
|
|
2873
|
+
return 0;
|
|
2874
|
+
}
|
|
2875
|
+
async function inbox(flags, _positionals, io) {
|
|
2876
|
+
const client = agentClient(flags, io);
|
|
2877
|
+
const after = flags.after && flags.after !== "true" ? flags.after : void 0;
|
|
2878
|
+
const limit = intFlag(flags.limit, "limit");
|
|
2879
|
+
if (flags.follow === "true") {
|
|
2880
|
+
let cursor2 = after;
|
|
2881
|
+
const stream = client.inboxStream({
|
|
2882
|
+
after,
|
|
2883
|
+
wait: intFlag(flags.wait, "wait") ?? 25,
|
|
2884
|
+
limit,
|
|
2885
|
+
signal: io.signal,
|
|
2886
|
+
onCursor: (c) => {
|
|
2887
|
+
cursor2 = c;
|
|
2888
|
+
},
|
|
2889
|
+
onError: (err, ms) => {
|
|
2890
|
+
const text = err instanceof Error ? err.message : String(err);
|
|
2891
|
+
io.err(`[inbox] ${text} (retrying in ${Math.ceil(ms / 1e3)}s)`);
|
|
2892
|
+
}
|
|
2893
|
+
});
|
|
2894
|
+
for await (const event of stream) io.out(JSON.stringify(event));
|
|
2895
|
+
if (cursor2) io.err(`[inbox] stopped at cursor ${cursor2}; resume with: jaibber-agent inbox --follow --after ${cursor2}`);
|
|
2896
|
+
return 0;
|
|
2897
|
+
}
|
|
2898
|
+
const { events, cursor } = await client.inbox({ after, wait: intFlag(flags.wait, "wait") ?? 0, limit, signal: io.signal });
|
|
2899
|
+
for (const event of events) io.out(JSON.stringify(event));
|
|
2900
|
+
io.err(
|
|
2901
|
+
`[inbox] ${events.length} event(s); cursor ${cursor ?? "(none)"}` + (cursor ? `; next: jaibber-agent inbox --after ${cursor}` : "")
|
|
2902
|
+
);
|
|
2903
|
+
return 0;
|
|
2904
|
+
}
|
|
2905
|
+
async function find(flags, positionals, io) {
|
|
2906
|
+
const q = positionals.join(" ").trim() || void 0;
|
|
2907
|
+
const client = new JaibberClient(serverFrom(flags, io.env), { fetch: io.fetch });
|
|
2908
|
+
const page = await client.findAgents({
|
|
2909
|
+
q,
|
|
2910
|
+
skill: flags.skill,
|
|
2911
|
+
tier: flags.tier,
|
|
2912
|
+
sort: flags.sort,
|
|
2913
|
+
limit: intFlag(flags.limit, "limit"),
|
|
2914
|
+
cursor: flags.cursor
|
|
2915
|
+
});
|
|
2916
|
+
if (flags.json === "true") {
|
|
2917
|
+
io.out(JSON.stringify(page, null, 2));
|
|
2918
|
+
return 0;
|
|
2919
|
+
}
|
|
2920
|
+
if (page.agents.length === 0) {
|
|
2921
|
+
io.out("No agents found.");
|
|
2922
|
+
return 0;
|
|
2923
|
+
}
|
|
2924
|
+
for (const agent2 of page.agents) io.out(formatAgentLine(agent2));
|
|
2925
|
+
if (page.hasMore && page.cursor) {
|
|
2926
|
+
io.out("");
|
|
2927
|
+
io.out(`More: jaibber-agent find ${q ? `${shellQuote(q)} ` : ""}--cursor ${shellQuote(page.cursor)}`);
|
|
2928
|
+
}
|
|
2929
|
+
return 0;
|
|
2930
|
+
}
|
|
2931
|
+
async function dm(flags, positionals, io) {
|
|
2932
|
+
const [to, ...words] = positionals;
|
|
2933
|
+
const text = words.join(" ").trim();
|
|
2934
|
+
if (!to || !text) throw new UsageError("usage: jaibber-agent dm <handle> <text...>");
|
|
2935
|
+
const client = agentClient(flags, io);
|
|
2936
|
+
const result = await client.startThread({ to: [to], text, title: flags.title });
|
|
2937
|
+
if (flags.json === "true") {
|
|
2938
|
+
io.out(JSON.stringify(result, null, 2));
|
|
2939
|
+
return 0;
|
|
2940
|
+
}
|
|
2941
|
+
io.out(`Thread ${result.thread.id} opened with @${to.replace(/^@/, "")}; message ${result.message?.id ?? "?"} sent.`);
|
|
2942
|
+
io.out(`Replies arrive in your inbox: jaibber-agent inbox --follow`);
|
|
2943
|
+
return 0;
|
|
2944
|
+
}
|
|
2945
|
+
var HANDLERS = { register, inbox, find, dm };
|
|
2946
|
+
function reportError(err, io) {
|
|
2947
|
+
if (isPaymentRequired(err)) {
|
|
2948
|
+
io.err(`Error: ${err.serverMessage}`);
|
|
2949
|
+
io.err("(402 PAYMENT_REQUIRED: this needs payment; paid contact arrives with Jaibber payments and is not available yet.)");
|
|
2950
|
+
} else if (isContactNotAllowed(err)) {
|
|
2951
|
+
io.err(`Error: ${err.serverMessage}`);
|
|
2952
|
+
io.err(
|
|
2953
|
+
"(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.)"
|
|
2954
|
+
);
|
|
2955
|
+
} else if (err instanceof JaibberApiError) {
|
|
2956
|
+
io.err(`Error: ${err.message}${err.retryAfter !== void 0 ? ` (retry after ${err.retryAfter}s)` : ""}`);
|
|
2957
|
+
} else {
|
|
2958
|
+
io.err(`Error: ${err instanceof Error ? err.message : String(err)}`);
|
|
2959
|
+
}
|
|
2960
|
+
}
|
|
2961
|
+
async function runNetworkCommand(name, argv, io) {
|
|
2962
|
+
const { flags, positionals } = parseCommandArgs(argv);
|
|
2963
|
+
if (flags.help === "true") {
|
|
2964
|
+
io.out(COMMAND_HELP[name]);
|
|
2965
|
+
return 0;
|
|
2966
|
+
}
|
|
2967
|
+
try {
|
|
2968
|
+
return await HANDLERS[name](flags, positionals, io);
|
|
2969
|
+
} catch (err) {
|
|
2970
|
+
if (err instanceof UsageError) {
|
|
2971
|
+
io.err(`Error: ${err.message}`);
|
|
2972
|
+
io.err(`Run: jaibber-agent ${name} --help`);
|
|
2973
|
+
return 2;
|
|
2974
|
+
}
|
|
2975
|
+
reportError(err, io);
|
|
2976
|
+
return 1;
|
|
2977
|
+
}
|
|
2978
|
+
}
|
|
2979
|
+
|
|
1991
2980
|
// src/cli.ts
|
|
2981
|
+
var subcommand = process.argv[2];
|
|
2982
|
+
if (isNetworkCommand(subcommand)) {
|
|
2983
|
+
const abort = new AbortController();
|
|
2984
|
+
process.once("SIGINT", () => abort.abort());
|
|
2985
|
+
process.once("SIGTERM", () => abort.abort());
|
|
2986
|
+
const code = await runNetworkCommand(subcommand, process.argv.slice(3), {
|
|
2987
|
+
out: (line) => console.log(line),
|
|
2988
|
+
err: (line) => console.error(line),
|
|
2989
|
+
env: process.env,
|
|
2990
|
+
signal: abort.signal,
|
|
2991
|
+
platform: process.platform
|
|
2992
|
+
});
|
|
2993
|
+
await Promise.all(
|
|
2994
|
+
[process.stdout, process.stderr].map((s) => new Promise((resolve) => s.write("", () => resolve())))
|
|
2995
|
+
);
|
|
2996
|
+
process.exit(code);
|
|
2997
|
+
}
|
|
1992
2998
|
function parseArgs(argv) {
|
|
1993
2999
|
const args2 = {};
|
|
1994
3000
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -2007,7 +3013,7 @@ function parseArgs(argv) {
|
|
|
2007
3013
|
return args2;
|
|
2008
3014
|
}
|
|
2009
3015
|
var args = parseArgs(process.argv.slice(2));
|
|
2010
|
-
var
|
|
3016
|
+
var DEFAULT_SERVER2 = "https://api.jaibber.com";
|
|
2011
3017
|
var DEFAULTS = {
|
|
2012
3018
|
anthropic: "claude-sonnet-5",
|
|
2013
3019
|
openai: "gpt-4o",
|
|
@@ -2015,10 +3021,14 @@ var DEFAULTS = {
|
|
|
2015
3021
|
};
|
|
2016
3022
|
if (args["help"] || args["h"] || process.argv.length <= 2) {
|
|
2017
3023
|
console.log(`
|
|
2018
|
-
Jaibber Agent CLI \u2014 run a headless AI agent
|
|
3024
|
+
Jaibber Agent CLI \u2014 run a headless AI agent, or use the public agent network
|
|
2019
3025
|
|
|
2020
3026
|
USAGE:
|
|
2021
|
-
npx @jaibber/sdk [options]
|
|
3027
|
+
npx @jaibber/sdk [options] Run an agent (options below)
|
|
3028
|
+
npx @jaibber/sdk <command> [options] register | inbox | find | dm
|
|
3029
|
+
jaibber-agent <command> --help Help for one command
|
|
3030
|
+
|
|
3031
|
+
${NETWORK_HELP}
|
|
2022
3032
|
|
|
2023
3033
|
AUTH (one of):
|
|
2024
3034
|
--api-key <jb_...> Agent API key \u2014 the key IS the agent's identity
|
|
@@ -2036,6 +3046,10 @@ PROVIDER (at least one required \u2014 first match wins):
|
|
|
2036
3046
|
--openai-key <key> OpenAI API key (GPT)
|
|
2037
3047
|
--google-key <key> Google AI API key (Gemini)
|
|
2038
3048
|
--claude-cli Use local Claude CLI (no API key needed)
|
|
3049
|
+
--capability <level> Claude CLI permissions: readonly | standard | full
|
|
3050
|
+
(default: standard \u2014 edits files, Read/Edit/Write/
|
|
3051
|
+
Bash/Grep/Glob only; full skips every permission
|
|
3052
|
+
check: opt-in, only on a machine you can lose)
|
|
2039
3053
|
|
|
2040
3054
|
MODEL OVERRIDES (optional \u2014 defaults track each provider's recommended model):
|
|
2041
3055
|
--anthropic-model <id> Anthropic model (default: ${DEFAULTS.anthropic};
|
|
@@ -2045,6 +3059,8 @@ MODEL OVERRIDES (optional \u2014 defaults track each provider's recommended mode
|
|
|
2045
3059
|
|
|
2046
3060
|
ACCOUNT & SETUP (require --username/--password):
|
|
2047
3061
|
--create-account Create a new Jaibber account, then continue
|
|
3062
|
+
--accept-terms Required with --create-account: you are 16 or older and
|
|
3063
|
+
agree to https://www.jaibber.com/terms and /privacy
|
|
2048
3064
|
--create-project <name> Create a new project and join it (prints project ID)
|
|
2049
3065
|
--create-key Register the agent, assign it to --projects (or all
|
|
2050
3066
|
your projects), mint an agent API key, print it, exit
|
|
@@ -2057,7 +3073,7 @@ OPTIONAL:
|
|
|
2057
3073
|
written to service files)
|
|
2058
3074
|
--template <name> Use a preset agent template (sets agent-name + instructions)
|
|
2059
3075
|
--list-templates Show available agent templates and exit
|
|
2060
|
-
--server <url> Server URL (default: ${
|
|
3076
|
+
--server <url> Server URL (default: ${DEFAULT_SERVER2}; env JAIBBER_SERVER)
|
|
2061
3077
|
--instructions <text> System prompt for the agent
|
|
2062
3078
|
--machine-name <name> Machine identifier shown in presence
|
|
2063
3079
|
--projects <id,id,...> Comma-separated project IDs to join (default: all)
|
|
@@ -2067,7 +3083,7 @@ OPTIONAL:
|
|
|
2067
3083
|
EXAMPLES:
|
|
2068
3084
|
# First run: create an account, register the agent, chat via Anthropic
|
|
2069
3085
|
npx @jaibber/sdk \\
|
|
2070
|
-
--create-account --username coding-bot --password s3cret \\
|
|
3086
|
+
--create-account --accept-terms --username coding-bot --password s3cret \\
|
|
2071
3087
|
--agent-name "CodingAgent" \\
|
|
2072
3088
|
--anthropic-key sk-ant-api03-...
|
|
2073
3089
|
|
|
@@ -2130,7 +3146,7 @@ var username = args["username"];
|
|
|
2130
3146
|
var password = args["password"] || process.env.JAIBBER_PASSWORD;
|
|
2131
3147
|
var apiKey = args["api-key"] || process.env.JAIBBER_API_KEY;
|
|
2132
3148
|
var agentName = args["agent-name"] || template?.agentName;
|
|
2133
|
-
var serverUrl = args["server"] || process.env.JAIBBER_SERVER ||
|
|
3149
|
+
var serverUrl = args["server"] || process.env.JAIBBER_SERVER || DEFAULT_SERVER2;
|
|
2134
3150
|
var orgId = args["org"];
|
|
2135
3151
|
var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
|
|
2136
3152
|
var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
|
|
@@ -2139,6 +3155,12 @@ var anthropicModel = args["anthropic-model"] || process.env.ANTHROPIC_MODEL;
|
|
|
2139
3155
|
var openaiModel = args["openai-model"] || process.env.OPENAI_MODEL;
|
|
2140
3156
|
var googleModel = args["google-model"] || process.env.GEMINI_MODEL;
|
|
2141
3157
|
var useClaudeCli = args["claude-cli"] === "true";
|
|
3158
|
+
var capabilityArg = args["capability"];
|
|
3159
|
+
if (capabilityArg !== void 0 && !["readonly", "standard", "full"].includes(capabilityArg)) {
|
|
3160
|
+
console.error('Error: --capability must be "readonly", "standard" or "full".');
|
|
3161
|
+
process.exit(1);
|
|
3162
|
+
}
|
|
3163
|
+
var capability = capabilityArg;
|
|
2142
3164
|
var projectDir = args["project-dir"];
|
|
2143
3165
|
var instructions = args["instructions"] || template?.instructions;
|
|
2144
3166
|
var machineName = args["machine-name"];
|
|
@@ -2165,6 +3187,12 @@ if (!agentName) {
|
|
|
2165
3187
|
console.error("Error: --agent-name is required (or pick a --template)");
|
|
2166
3188
|
process.exit(1);
|
|
2167
3189
|
}
|
|
3190
|
+
if (createAccount && args["accept-terms"] !== "true") {
|
|
3191
|
+
console.error(
|
|
3192
|
+
"Error: --create-account needs --accept-terms: you are 16 or older and agree to https://www.jaibber.com/terms and https://www.jaibber.com/privacy."
|
|
3193
|
+
);
|
|
3194
|
+
process.exit(1);
|
|
3195
|
+
}
|
|
2168
3196
|
if ((createAccount || createProjectName || createKey) && !hasSession) {
|
|
2169
3197
|
console.error(
|
|
2170
3198
|
"Error: --create-account, --create-project and --create-key act on your user account and require --username and --password."
|
|
@@ -2176,7 +3204,7 @@ if (createAccount) {
|
|
|
2176
3204
|
console.log(`[cli] Creating account "${username}"...`);
|
|
2177
3205
|
const client = new JaibberClient(serverUrl);
|
|
2178
3206
|
try {
|
|
2179
|
-
await client.register(username, password);
|
|
3207
|
+
await client.register(username, password, { acceptTerms: true });
|
|
2180
3208
|
console.log(`[cli] Account created successfully.`);
|
|
2181
3209
|
} catch (err) {
|
|
2182
3210
|
console.error(
|
|
@@ -2237,7 +3265,7 @@ if (createKey) {
|
|
|
2237
3265
|
}
|
|
2238
3266
|
process.exit(0);
|
|
2239
3267
|
}
|
|
2240
|
-
function
|
|
3268
|
+
function shellQuote2(s) {
|
|
2241
3269
|
if (/^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s)) return s;
|
|
2242
3270
|
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
2243
3271
|
}
|
|
@@ -2262,15 +3290,16 @@ then re-run with --api-key jb_... --install-service`
|
|
|
2262
3290
|
const flags = [];
|
|
2263
3291
|
flags.push(`--agent-name`, agentName);
|
|
2264
3292
|
if (resolvedProjectIds?.length) flags.push(`--projects`, resolvedProjectIds.join(","));
|
|
2265
|
-
if (serverUrl !==
|
|
3293
|
+
if (serverUrl !== DEFAULT_SERVER2) flags.push(`--server`, serverUrl);
|
|
2266
3294
|
if (instructions) flags.push(`--instructions`, instructions);
|
|
2267
3295
|
if (machineName) flags.push(`--machine-name`, machineName);
|
|
2268
3296
|
if (projectDir) flags.push(`--project-dir`, projectDir);
|
|
2269
3297
|
if (useClaudeCli) flags.push(`--claude-cli`);
|
|
3298
|
+
if (capability) flags.push(`--capability`, capability);
|
|
2270
3299
|
if (anthropicModel) flags.push(`--anthropic-model`, anthropicModel);
|
|
2271
3300
|
if (openaiModel) flags.push(`--openai-model`, openaiModel);
|
|
2272
3301
|
if (googleModel) flags.push(`--google-model`, googleModel);
|
|
2273
|
-
const execStart = [binaryPath, scriptPath, ...flags].map(
|
|
3302
|
+
const execStart = [binaryPath, scriptPath, ...flags].map(shellQuote2).join(" ");
|
|
2274
3303
|
const envLines = Object.entries(env).map(([k, v]) => `Environment="${k}=${v.replace(/(["\\])/g, "\\$1")}"`).join("\n");
|
|
2275
3304
|
const serviceContent = `[Unit]
|
|
2276
3305
|
Description=Jaibber Agent (${agentName})
|
|
@@ -2303,8 +3332,8 @@ WantedBy=default.target
|
|
|
2303
3332
|
console.log(`[cli] journalctl --user -u ${serviceSlug} -f`);
|
|
2304
3333
|
} catch {
|
|
2305
3334
|
const logFile = `${homedir()}/${serviceSlug}.log`;
|
|
2306
|
-
const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${
|
|
2307
|
-
const cronLine = `@reboot ${envPrefix} ${execStart} >> ${
|
|
3335
|
+
const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${shellQuote2(v)}`).join(" ");
|
|
3336
|
+
const cronLine = `@reboot ${envPrefix} ${execStart} >> ${shellQuote2(logFile)} 2>&1`;
|
|
2308
3337
|
const cronMarker = `jaibber:${serviceSlug}`;
|
|
2309
3338
|
try {
|
|
2310
3339
|
let existing = "";
|
|
@@ -2365,8 +3394,13 @@ if (anthropicKey) {
|
|
|
2365
3394
|
agent.useProvider("google", { apiKey: googleKey, model });
|
|
2366
3395
|
console.log(`[cli] Using Google provider (${model})`);
|
|
2367
3396
|
} else if (useClaudeCli) {
|
|
2368
|
-
agent.useProvider("claude-cli", { projectDir });
|
|
2369
|
-
console.log(`[cli] Using Claude CLI provider (local auth)`);
|
|
3397
|
+
agent.useProvider("claude-cli", { projectDir, capability });
|
|
3398
|
+
console.log(`[cli] Using Claude CLI provider (local auth, capability: ${capability ?? "standard"})`);
|
|
3399
|
+
if (capability === "full") {
|
|
3400
|
+
console.warn(
|
|
3401
|
+
"[cli] WARNING: --capability full skips every Claude Code permission check. Anyone who can message this agent can run any command as this OS user."
|
|
3402
|
+
);
|
|
3403
|
+
}
|
|
2370
3404
|
} else {
|
|
2371
3405
|
console.log(
|
|
2372
3406
|
"[cli] No provider configured. Pass --anthropic-key, --openai-key, --google-key, or --claude-cli."
|