@jaibber/sdk 0.3.8 → 0.4.1
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 +216 -22
- package/dist/cli.js +1112 -377
- package/dist/index.cjs +965 -308
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +556 -142
- package/dist/index.d.ts +556 -142
- package/dist/index.js +961 -307
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,17 +1,58 @@
|
|
|
1
1
|
// src/agent.ts
|
|
2
2
|
import { EventEmitter } from "events";
|
|
3
|
-
import { v4 as uuidv42 } from "uuid";
|
|
4
3
|
|
|
5
4
|
// src/client.ts
|
|
5
|
+
var API_KEY_PREFIX = "jb_";
|
|
6
|
+
async function readError(res) {
|
|
7
|
+
const text = await res.text().catch(() => "");
|
|
8
|
+
try {
|
|
9
|
+
const json = JSON.parse(text);
|
|
10
|
+
const err = json?.error;
|
|
11
|
+
if (typeof err === "string") return err;
|
|
12
|
+
if (err && typeof err === "object") {
|
|
13
|
+
const e = err;
|
|
14
|
+
if (typeof e.message === "string") {
|
|
15
|
+
return e.code ? `${e.code}: ${e.message}` : e.message;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
} catch {
|
|
19
|
+
}
|
|
20
|
+
return text || res.statusText || "Unknown error";
|
|
21
|
+
}
|
|
22
|
+
function mapProject(p, fallbackRole = "member") {
|
|
23
|
+
return {
|
|
24
|
+
id: p.id,
|
|
25
|
+
name: p.name,
|
|
26
|
+
description: p.description ?? null,
|
|
27
|
+
orgId: p.orgId ?? null,
|
|
28
|
+
ablyChannelName: p.ablyChannelName,
|
|
29
|
+
role: p.role ?? fallbackRole
|
|
30
|
+
};
|
|
31
|
+
}
|
|
6
32
|
var JaibberClient = class {
|
|
7
33
|
serverUrl;
|
|
8
34
|
jwt = null;
|
|
35
|
+
apiKey = null;
|
|
9
36
|
userId = null;
|
|
10
37
|
username = null;
|
|
11
|
-
constructor(serverUrl) {
|
|
38
|
+
constructor(serverUrl, opts) {
|
|
12
39
|
this.serverUrl = serverUrl.replace(/\/+$/, "");
|
|
40
|
+
if (opts?.apiKey) this.setApiKey(opts.apiKey);
|
|
41
|
+
if (opts?.token) this.jwt = opts.token;
|
|
13
42
|
}
|
|
14
43
|
// ── Auth ────────────────────────────────────────────────────────────
|
|
44
|
+
/** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
|
|
45
|
+
setApiKey(apiKey) {
|
|
46
|
+
const key = apiKey.trim();
|
|
47
|
+
if (!key.startsWith(API_KEY_PREFIX)) {
|
|
48
|
+
throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
|
|
49
|
+
}
|
|
50
|
+
this.apiKey = key;
|
|
51
|
+
}
|
|
52
|
+
/** Use an existing session JWT for all requests. */
|
|
53
|
+
setToken(token) {
|
|
54
|
+
this.jwt = token;
|
|
55
|
+
}
|
|
15
56
|
/** POST /api/auth/register — create a new account, stores JWT. */
|
|
16
57
|
async register(username, password) {
|
|
17
58
|
const res = await fetch(`${this.serverUrl}/api/auth/register`, {
|
|
@@ -20,7 +61,7 @@ var JaibberClient = class {
|
|
|
20
61
|
body: JSON.stringify({ username, password })
|
|
21
62
|
});
|
|
22
63
|
if (!res.ok) {
|
|
23
|
-
const text = await res
|
|
64
|
+
const text = await readError(res);
|
|
24
65
|
if (res.status === 409) {
|
|
25
66
|
throw new Error(`Username "${username}" is already taken.`);
|
|
26
67
|
}
|
|
@@ -39,7 +80,7 @@ var JaibberClient = class {
|
|
|
39
80
|
body: JSON.stringify({ username, password })
|
|
40
81
|
});
|
|
41
82
|
if (!res.ok) {
|
|
42
|
-
const text = await res
|
|
83
|
+
const text = await readError(res);
|
|
43
84
|
if (res.status === 401) {
|
|
44
85
|
throw new Error("Invalid credentials. Check username and password.");
|
|
45
86
|
}
|
|
@@ -51,169 +92,300 @@ var JaibberClient = class {
|
|
|
51
92
|
this.username = data.username;
|
|
52
93
|
}
|
|
53
94
|
get isAuthenticated() {
|
|
54
|
-
return this.jwt !== null;
|
|
95
|
+
return this.jwt !== null || this.apiKey !== null;
|
|
96
|
+
}
|
|
97
|
+
/** Which credential requests will carry. */
|
|
98
|
+
get authMode() {
|
|
99
|
+
if (this.apiKey) return "apiKey";
|
|
100
|
+
if (this.jwt) return "session";
|
|
101
|
+
return "none";
|
|
55
102
|
}
|
|
56
103
|
authHeaders() {
|
|
57
104
|
const h = { "Content-Type": "application/json" };
|
|
58
|
-
if (this.
|
|
105
|
+
if (this.apiKey) {
|
|
106
|
+
h["X-API-Key"] = this.apiKey;
|
|
107
|
+
} else if (this.jwt) {
|
|
59
108
|
h["Authorization"] = `Bearer ${this.jwt}`;
|
|
60
109
|
}
|
|
61
110
|
return h;
|
|
62
111
|
}
|
|
112
|
+
/** Authenticated fetch with uniform error reporting. */
|
|
113
|
+
async request(method, path, body, what) {
|
|
114
|
+
const res = await fetch(`${this.serverUrl}${path}`, {
|
|
115
|
+
method,
|
|
116
|
+
headers: this.authHeaders(),
|
|
117
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {}
|
|
118
|
+
});
|
|
119
|
+
if (!res.ok) {
|
|
120
|
+
const text = await readError(res);
|
|
121
|
+
throw new Error(`${what ?? `${method} ${path}`} failed (${res.status}): ${text}`);
|
|
122
|
+
}
|
|
123
|
+
return res;
|
|
124
|
+
}
|
|
125
|
+
// ── Identity ────────────────────────────────────────────────────────
|
|
126
|
+
/**
|
|
127
|
+
* GET /api/me — who the current credential is: the user (session), the
|
|
128
|
+
* agent (agent-bound key) or the org (org key). Resolves `null` when the
|
|
129
|
+
* server predates the endpoint (404).
|
|
130
|
+
*/
|
|
131
|
+
async whoAmI() {
|
|
132
|
+
const res = await fetch(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
|
|
133
|
+
if (res.status === 404) return null;
|
|
134
|
+
if (!res.ok) {
|
|
135
|
+
const text = await readError(res);
|
|
136
|
+
throw new Error(`GET /api/me failed (${res.status}): ${text}`);
|
|
137
|
+
}
|
|
138
|
+
const json = await res.json();
|
|
139
|
+
return json.data;
|
|
140
|
+
}
|
|
63
141
|
// ── Projects ────────────────────────────────────────────────────────
|
|
64
|
-
/**
|
|
142
|
+
/**
|
|
143
|
+
* GET /api/projects — with a session: projects the user is a member of
|
|
144
|
+
* (plus org-admin-visible ones with role "org-admin"); with an agent key:
|
|
145
|
+
* the agent's assigned projects.
|
|
146
|
+
*/
|
|
65
147
|
async listProjects() {
|
|
66
|
-
const res = await
|
|
67
|
-
|
|
148
|
+
const res = await this.request("GET", "/api/projects", void 0, "Failed to list projects");
|
|
149
|
+
const json = await res.json();
|
|
150
|
+
const rows = json.projects ?? json.data ?? [];
|
|
151
|
+
return rows.map((p) => mapProject(p, this.apiKey ? "agent" : "member"));
|
|
152
|
+
}
|
|
153
|
+
/** POST /api/projects — create a new project (session only), returns it. */
|
|
154
|
+
async createProject(name, description, orgId) {
|
|
155
|
+
const res = await this.request(
|
|
156
|
+
"POST",
|
|
157
|
+
"/api/projects",
|
|
158
|
+
{ name, description, ...orgId ? { orgId } : {} },
|
|
159
|
+
"Failed to create project"
|
|
160
|
+
);
|
|
161
|
+
const json = await res.json();
|
|
162
|
+
const p = json.project ?? json.data;
|
|
163
|
+
if (!p) throw new Error("Failed to create project: malformed response");
|
|
164
|
+
return mapProject(p, "admin");
|
|
165
|
+
}
|
|
166
|
+
// ── Agents (/api/me/agents) ─────────────────────────────────────────
|
|
167
|
+
/**
|
|
168
|
+
* POST /api/me/agents — idempotent upsert of an agent hosted by the
|
|
169
|
+
* logged-in user, keyed by (org, lower(name)). Session only.
|
|
170
|
+
*/
|
|
171
|
+
async ensureAgent(input) {
|
|
172
|
+
const body = { name: input.name, kind: input.kind };
|
|
173
|
+
if (input.instructions !== void 0) body.instructions = input.instructions;
|
|
174
|
+
if (input.provider) body.provider = input.provider;
|
|
175
|
+
if (input.machineName) body.machineName = input.machineName;
|
|
176
|
+
if (input.projectId) body.projectId = input.projectId;
|
|
177
|
+
if (input.orgId) body.orgId = input.orgId;
|
|
178
|
+
const res = await fetch(`${this.serverUrl}/api/me/agents`, {
|
|
179
|
+
method: "POST",
|
|
180
|
+
headers: this.authHeaders(),
|
|
181
|
+
body: JSON.stringify(body)
|
|
68
182
|
});
|
|
69
183
|
if (!res.ok) {
|
|
70
|
-
const text = await res
|
|
71
|
-
|
|
184
|
+
const text = await readError(res);
|
|
185
|
+
if (res.status === 404) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
"This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
throw new Error(`Failed to register agent (${res.status}): ${text}`);
|
|
72
191
|
}
|
|
73
|
-
const
|
|
74
|
-
return data
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
}
|
|
82
|
-
/** POST /api/
|
|
83
|
-
async
|
|
84
|
-
const res = await fetch(`${this.serverUrl}/api/
|
|
192
|
+
const json = await res.json();
|
|
193
|
+
return json.data;
|
|
194
|
+
}
|
|
195
|
+
/** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
|
|
196
|
+
async listMyAgents() {
|
|
197
|
+
const res = await this.request("GET", "/api/me/agents", void 0, "Failed to list agents");
|
|
198
|
+
const json = await res.json();
|
|
199
|
+
return json.data;
|
|
200
|
+
}
|
|
201
|
+
/** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
|
|
202
|
+
async assignAgent(agentId, projectId) {
|
|
203
|
+
const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
|
|
85
204
|
method: "POST",
|
|
86
205
|
headers: this.authHeaders(),
|
|
87
|
-
body: JSON.stringify({
|
|
206
|
+
body: JSON.stringify({ projectId })
|
|
88
207
|
});
|
|
89
|
-
if (!res.ok) {
|
|
90
|
-
const text = await res
|
|
91
|
-
throw new Error(`Failed to
|
|
208
|
+
if (!res.ok && res.status !== 409) {
|
|
209
|
+
const text = await readError(res);
|
|
210
|
+
throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
|
|
92
211
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
212
|
+
}
|
|
213
|
+
/** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
|
|
214
|
+
async unassignAgent(agentId, projectId) {
|
|
215
|
+
const res = await this.request(
|
|
216
|
+
"DELETE",
|
|
217
|
+
`/api/me/agents/${agentId}/assignments?projectId=${encodeURIComponent(projectId)}`,
|
|
218
|
+
void 0,
|
|
219
|
+
"Failed to unassign agent"
|
|
220
|
+
);
|
|
221
|
+
const json = await res.json().catch(() => ({}));
|
|
222
|
+
return json.data?.removed ?? true;
|
|
223
|
+
}
|
|
224
|
+
/** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
|
|
225
|
+
async createAgentKey(agentId, name) {
|
|
226
|
+
const res = await this.request(
|
|
227
|
+
"POST",
|
|
228
|
+
`/api/me/agents/${agentId}/keys`,
|
|
229
|
+
name ? { name } : {},
|
|
230
|
+
"Failed to create agent API key"
|
|
231
|
+
);
|
|
232
|
+
const json = await res.json();
|
|
233
|
+
return json.data;
|
|
234
|
+
}
|
|
235
|
+
/** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
|
|
236
|
+
async heartbeat(agentId) {
|
|
237
|
+
const res = await this.request(
|
|
238
|
+
"POST",
|
|
239
|
+
`/api/agents/${agentId}/heartbeat`,
|
|
240
|
+
void 0,
|
|
241
|
+
"Heartbeat"
|
|
242
|
+
);
|
|
243
|
+
const json = await res.json();
|
|
244
|
+
return json.data;
|
|
101
245
|
}
|
|
102
246
|
// ── Ably token ──────────────────────────────────────────────────────
|
|
103
247
|
/** POST /api/ably/token — get scoped Ably TokenRequest. */
|
|
104
248
|
async getAblyToken() {
|
|
105
|
-
const res = await
|
|
106
|
-
method: "POST",
|
|
107
|
-
headers: this.authHeaders()
|
|
108
|
-
});
|
|
109
|
-
if (!res.ok) {
|
|
110
|
-
const text = await res.text();
|
|
111
|
-
throw new Error(`Failed to get Ably token (${res.status}): ${text}`);
|
|
112
|
-
}
|
|
249
|
+
const res = await this.request("POST", "/api/ably/token", void 0, "Failed to get Ably token");
|
|
113
250
|
return res.json();
|
|
114
251
|
}
|
|
115
252
|
// ── Messages ────────────────────────────────────────────────────────
|
|
116
253
|
/**
|
|
117
|
-
* POST /api/projects/{id}/messages — persist a message
|
|
118
|
-
*
|
|
254
|
+
* POST /api/projects/{id}/messages — persist a message. This is the only
|
|
255
|
+
* write path for final messages: the server publishes the echo to Ably
|
|
256
|
+
* itself. Idempotent on `id` (201 on create, 200 if it already existed).
|
|
257
|
+
*
|
|
258
|
+
* Identity is derived server-side: in session mode pass `agentId` to post
|
|
259
|
+
* as that hosted agent; with an agent key it is implied.
|
|
260
|
+
*
|
|
261
|
+
* Retries once on network errors / 5xx (safe: ids are idempotent).
|
|
119
262
|
*/
|
|
120
263
|
async persistMessage(projectId, msg) {
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
264
|
+
const body = { text: msg.text };
|
|
265
|
+
if (msg.id) body.id = msg.id;
|
|
266
|
+
if (msg.agentId) body.agentId = msg.agentId;
|
|
267
|
+
if (msg.type) body.type = msg.type;
|
|
268
|
+
if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
|
|
269
|
+
if (msg.mentions?.length) body.mentions = msg.mentions;
|
|
270
|
+
const attempt = async () => {
|
|
271
|
+
const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
|
|
124
272
|
method: "POST",
|
|
125
273
|
headers: this.authHeaders(),
|
|
126
|
-
body: JSON.stringify(
|
|
274
|
+
body: JSON.stringify(body)
|
|
275
|
+
});
|
|
276
|
+
if (!res.ok) {
|
|
277
|
+
const text = await readError(res);
|
|
278
|
+
const err = new Error(`Failed to persist message (${res.status}): ${text}`);
|
|
279
|
+
err.status = res.status;
|
|
280
|
+
throw err;
|
|
127
281
|
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
282
|
+
const json = await res.json();
|
|
283
|
+
return json.data;
|
|
284
|
+
};
|
|
285
|
+
try {
|
|
286
|
+
return await attempt();
|
|
287
|
+
} catch (err) {
|
|
288
|
+
const status = err.status;
|
|
289
|
+
const retryable = status === void 0 || status >= 500 || status === 429;
|
|
290
|
+
if (!retryable) throw err;
|
|
291
|
+
await new Promise((r) => setTimeout(r, 1e3));
|
|
292
|
+
return attempt();
|
|
134
293
|
}
|
|
135
294
|
}
|
|
136
|
-
/** GET /api/projects/{id}/messages — fetch recent messages. */
|
|
295
|
+
/** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
|
|
137
296
|
async fetchMessages(projectId, limit = 20) {
|
|
138
|
-
const res = await
|
|
139
|
-
|
|
140
|
-
{
|
|
297
|
+
const res = await this.request(
|
|
298
|
+
"GET",
|
|
299
|
+
`/api/projects/${projectId}/messages?limit=${limit}`,
|
|
300
|
+
void 0,
|
|
301
|
+
"Failed to fetch messages"
|
|
141
302
|
);
|
|
142
|
-
if (!res.ok) {
|
|
143
|
-
const text = await res.text();
|
|
144
|
-
throw new Error(`Failed to fetch messages (${res.status}): ${text}`);
|
|
145
|
-
}
|
|
146
303
|
const data = await res.json();
|
|
147
304
|
return data.data;
|
|
148
305
|
}
|
|
149
306
|
// ── Tasks ───────────────────────────────────────────────────────────
|
|
150
307
|
/** POST /api/projects/{id}/tasks — create a task. */
|
|
151
308
|
async createTask(projectId, data) {
|
|
152
|
-
const res = await
|
|
153
|
-
|
|
154
|
-
{
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
body: JSON.stringify(data)
|
|
158
|
-
}
|
|
309
|
+
const res = await this.request(
|
|
310
|
+
"POST",
|
|
311
|
+
`/api/projects/${projectId}/tasks`,
|
|
312
|
+
data,
|
|
313
|
+
"Failed to create task"
|
|
159
314
|
);
|
|
160
|
-
if (!res.ok) {
|
|
161
|
-
const text = await res.text();
|
|
162
|
-
throw new Error(`Failed to create task (${res.status}): ${text}`);
|
|
163
|
-
}
|
|
164
315
|
const result = await res.json();
|
|
165
316
|
return result.data;
|
|
166
317
|
}
|
|
167
|
-
/** PATCH /api/tasks/{taskId} — update task fields. */
|
|
318
|
+
/** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
|
|
168
319
|
async updateTask(taskId, updates) {
|
|
169
|
-
const res = await
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
}
|
|
320
|
+
const res = await this.request(
|
|
321
|
+
"PATCH",
|
|
322
|
+
`/api/tasks/${taskId}`,
|
|
323
|
+
updates,
|
|
324
|
+
"Failed to update task"
|
|
325
|
+
);
|
|
326
|
+
const result = await res.json();
|
|
327
|
+
return result.data;
|
|
178
328
|
}
|
|
179
329
|
};
|
|
180
330
|
|
|
181
331
|
// src/ably-manager.ts
|
|
182
332
|
import Ably from "ably";
|
|
333
|
+
var CONNECT_TIMEOUT_MS = 3e4;
|
|
183
334
|
var AblyManager = class {
|
|
184
|
-
constructor(client,
|
|
335
|
+
constructor(client, opts) {
|
|
185
336
|
this.client = client;
|
|
186
|
-
this.
|
|
187
|
-
this.username = username;
|
|
337
|
+
this.opts = opts;
|
|
188
338
|
}
|
|
189
339
|
ably = null;
|
|
190
340
|
channels = /* @__PURE__ */ new Map();
|
|
191
341
|
presenceChannel = null;
|
|
192
342
|
/** Create Ably Realtime client with token auth callback. */
|
|
193
|
-
async connect() {
|
|
343
|
+
async connect(timeoutMs = CONNECT_TIMEOUT_MS) {
|
|
194
344
|
return new Promise((resolve, reject) => {
|
|
345
|
+
let lastAuthError = null;
|
|
346
|
+
let settled = false;
|
|
347
|
+
const finish = (fn) => {
|
|
348
|
+
if (settled) return;
|
|
349
|
+
settled = true;
|
|
350
|
+
clearTimeout(timer);
|
|
351
|
+
fn();
|
|
352
|
+
};
|
|
353
|
+
const timer = setTimeout(() => {
|
|
354
|
+
finish(() => {
|
|
355
|
+
this.ably?.close();
|
|
356
|
+
this.ably = null;
|
|
357
|
+
reject(
|
|
358
|
+
new Error(
|
|
359
|
+
`Ably connection timed out after ${Math.round(timeoutMs / 1e3)}s` + (lastAuthError ? ` (last auth error: ${lastAuthError.message})` : "")
|
|
360
|
+
)
|
|
361
|
+
);
|
|
362
|
+
});
|
|
363
|
+
}, timeoutMs);
|
|
195
364
|
this.ably = new Ably.Realtime({
|
|
196
365
|
authCallback: async (_tokenParams, callback) => {
|
|
197
366
|
try {
|
|
198
367
|
const tokenRequest = await this.client.getAblyToken();
|
|
199
368
|
callback(null, tokenRequest);
|
|
200
369
|
} catch (err) {
|
|
201
|
-
|
|
370
|
+
lastAuthError = err instanceof Error ? err : new Error(String(err));
|
|
371
|
+
callback(lastAuthError.message, null);
|
|
202
372
|
}
|
|
203
373
|
},
|
|
204
|
-
clientId: this.
|
|
374
|
+
...this.opts.clientId ? { clientId: this.opts.clientId } : {},
|
|
205
375
|
disconnectedRetryTimeout: 5e3,
|
|
206
376
|
// 5s initial retry on disconnect
|
|
207
377
|
suspendedRetryTimeout: 3e4
|
|
208
378
|
// 30s retry when suspended
|
|
209
379
|
});
|
|
210
380
|
this.ably.connection.once("connected", () => {
|
|
211
|
-
resolve
|
|
381
|
+
finish(resolve);
|
|
212
382
|
});
|
|
213
383
|
this.ably.connection.once("failed", (stateChange) => {
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
384
|
+
finish(
|
|
385
|
+
() => reject(
|
|
386
|
+
new Error(
|
|
387
|
+
`Ably connection failed: ${stateChange?.reason?.message ?? lastAuthError?.message ?? "unknown"}`
|
|
388
|
+
)
|
|
217
389
|
)
|
|
218
390
|
);
|
|
219
391
|
});
|
|
@@ -231,42 +403,62 @@ var AblyManager = class {
|
|
|
231
403
|
});
|
|
232
404
|
}
|
|
233
405
|
/** Enter global presence channel (jaibber:presence). */
|
|
234
|
-
async enterGlobalPresence(
|
|
406
|
+
async enterGlobalPresence(data) {
|
|
235
407
|
if (!this.ably) throw new Error("Ably not connected");
|
|
236
408
|
this.presenceChannel = this.ably.channels.get("jaibber:presence");
|
|
237
409
|
await this.presenceChannel.presence.enter({
|
|
238
|
-
userId:
|
|
239
|
-
|
|
240
|
-
|
|
410
|
+
...data.userId ? { userId: data.userId } : {},
|
|
411
|
+
...data.agentId ? { agentId: data.agentId } : {},
|
|
412
|
+
username: data.username,
|
|
413
|
+
projectIds: data.projectIds
|
|
241
414
|
});
|
|
242
415
|
}
|
|
243
416
|
/**
|
|
244
|
-
* Subscribe to a project channel and
|
|
417
|
+
* Subscribe to a project channel (`message`, `task` and server-published
|
|
418
|
+
* `agent-control` events) and enter per-project presence.
|
|
245
419
|
* Returns an unsubscribe function.
|
|
246
420
|
*/
|
|
247
|
-
async subscribeToProject(project, presenceData, onMessage, onTask) {
|
|
421
|
+
async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
|
|
248
422
|
if (!this.ably) throw new Error("Ably not connected");
|
|
249
423
|
const channel = this.ably.channels.get(project.ablyChannelName);
|
|
250
424
|
this.channels.set(project.ablyChannelName, channel);
|
|
251
425
|
await channel.presence.enter(presenceData);
|
|
252
|
-
const
|
|
253
|
-
|
|
426
|
+
const safely = (event, body) => {
|
|
427
|
+
try {
|
|
428
|
+
Promise.resolve(body()).catch((err) => onError(err, event));
|
|
429
|
+
} catch (err) {
|
|
430
|
+
onError(err, event);
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
const messageHandler = (msg) => safely("message", () => {
|
|
434
|
+
if (!msg.data || typeof msg.data !== "object") return;
|
|
254
435
|
const payload = msg.data;
|
|
255
436
|
payload._connectionId = msg.connectionId ?? void 0;
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
437
|
+
payload._clientId = msg.clientId ?? void 0;
|
|
438
|
+
return onMessage(payload);
|
|
439
|
+
});
|
|
440
|
+
const taskHandler = (msg) => safely("task", () => {
|
|
441
|
+
if (!msg.data || typeof msg.data !== "object") return;
|
|
442
|
+
return onTask(msg.data);
|
|
443
|
+
});
|
|
444
|
+
const controlHandler = (msg) => safely("agent-control", () => {
|
|
445
|
+
if (!msg.data || typeof msg.data !== "object") return;
|
|
446
|
+
return onControl?.(msg.data);
|
|
447
|
+
});
|
|
262
448
|
channel.subscribe("message", messageHandler);
|
|
263
449
|
channel.subscribe("task", taskHandler);
|
|
450
|
+
channel.subscribe("agent-control", controlHandler);
|
|
264
451
|
return () => {
|
|
265
452
|
channel.unsubscribe("message", messageHandler);
|
|
266
453
|
channel.unsubscribe("task", taskHandler);
|
|
454
|
+
channel.unsubscribe("agent-control", controlHandler);
|
|
267
455
|
};
|
|
268
456
|
}
|
|
269
|
-
/**
|
|
457
|
+
/**
|
|
458
|
+
* Publish a client-side event on a project channel. Only `typing` and
|
|
459
|
+
* `chunk` are client-published; final messages go through the REST API
|
|
460
|
+
* and are echoed by the server.
|
|
461
|
+
*/
|
|
270
462
|
async publish(channelName, eventName, data) {
|
|
271
463
|
const channel = this.channels.get(channelName);
|
|
272
464
|
if (!channel) {
|
|
@@ -278,6 +470,10 @@ var AblyManager = class {
|
|
|
278
470
|
get connectionId() {
|
|
279
471
|
return this.ably?.connection.id;
|
|
280
472
|
}
|
|
473
|
+
/** The clientId this connection authenticated as (from the token in API-key mode). */
|
|
474
|
+
get clientId() {
|
|
475
|
+
return this.ably?.auth.clientId ?? void 0;
|
|
476
|
+
}
|
|
281
477
|
/** Leave presence on all channels and close the connection. */
|
|
282
478
|
async disconnect() {
|
|
283
479
|
for (const channel of this.channels.values()) {
|
|
@@ -308,44 +504,90 @@ var MessageContext = class {
|
|
|
308
504
|
conversationHistory;
|
|
309
505
|
/** The project ID this message was received on. */
|
|
310
506
|
projectId;
|
|
311
|
-
|
|
507
|
+
/** The agent's server-side id (sent as `agentId` on every save). */
|
|
508
|
+
agentId;
|
|
509
|
+
/** The agent's display name. */
|
|
510
|
+
agentName;
|
|
511
|
+
/** Id of the message being responded to (if any). */
|
|
512
|
+
incomingMessageId;
|
|
513
|
+
/**
|
|
514
|
+
* The id the final reply will be stored under. Also the `responseId` sent
|
|
515
|
+
* with `typing` so clients can pre-create the bubble.
|
|
516
|
+
*/
|
|
517
|
+
messageId;
|
|
312
518
|
ablyManager;
|
|
313
519
|
channelName;
|
|
314
|
-
|
|
315
|
-
agentName;
|
|
520
|
+
from;
|
|
316
521
|
client;
|
|
317
522
|
responseDepth;
|
|
318
523
|
respondingChain;
|
|
319
524
|
chunkBatchMs;
|
|
525
|
+
tracker;
|
|
526
|
+
/** Set by `stream()` when its generator threw. */
|
|
527
|
+
streamError = void 0;
|
|
320
528
|
constructor(opts) {
|
|
321
529
|
this.projectId = opts.projectId;
|
|
322
530
|
this.channelName = opts.channelName;
|
|
323
531
|
this.conversationHistory = opts.conversationHistory;
|
|
324
532
|
this.ablyManager = opts.ablyManager;
|
|
325
|
-
this.
|
|
533
|
+
this.from = opts.from;
|
|
534
|
+
this.agentId = opts.agentId;
|
|
326
535
|
this.agentName = opts.agentName;
|
|
327
536
|
this.client = opts.client;
|
|
537
|
+
this.incomingMessageId = opts.incomingMessageId;
|
|
328
538
|
this.responseDepth = opts.incomingDepth + 1;
|
|
329
539
|
this.respondingChain = [
|
|
330
540
|
...opts.incomingChain,
|
|
331
541
|
opts.agentName.toLowerCase()
|
|
332
542
|
];
|
|
333
543
|
this.chunkBatchMs = opts.chunkBatchMs;
|
|
334
|
-
this.
|
|
544
|
+
this.tracker = opts.tracker;
|
|
545
|
+
this.messageId = uuidv4();
|
|
546
|
+
}
|
|
547
|
+
/** Agent-to-agent hop count this reply will carry (informational). */
|
|
548
|
+
get depth() {
|
|
549
|
+
return this.responseDepth;
|
|
550
|
+
}
|
|
551
|
+
/** Agents that have already responded in this chain, including this one. */
|
|
552
|
+
get chain() {
|
|
553
|
+
return [...this.respondingChain];
|
|
335
554
|
}
|
|
336
|
-
/**
|
|
337
|
-
|
|
555
|
+
/**
|
|
556
|
+
* Why `stream()` failed, if it did: the error its generator threw;
|
|
557
|
+
* `undefined` otherwise. The failure has already been stored under this
|
|
558
|
+
* reply's id as an `error` bubble, and `stream()` resolved with the
|
|
559
|
+
* partial text.
|
|
560
|
+
*/
|
|
561
|
+
get error() {
|
|
562
|
+
return this.streamError;
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* One-shot reply: publishes `typing`, then POSTs the final message.
|
|
566
|
+
* Throws if the server rejects it (remote bubbles are closed first — see
|
|
567
|
+
* `deliver`).
|
|
568
|
+
*/
|
|
569
|
+
async reply(text, opts) {
|
|
338
570
|
await this.publishTyping();
|
|
339
|
-
|
|
340
|
-
|
|
571
|
+
return this.deliver(text, "response", this.parentFor(opts));
|
|
572
|
+
}
|
|
573
|
+
/** Replies thread under the answered message unless overridden. */
|
|
574
|
+
parentFor(opts) {
|
|
575
|
+
return opts?.parentMessageId ?? this.incomingMessageId;
|
|
341
576
|
}
|
|
342
577
|
/**
|
|
343
578
|
* Streaming reply: consumes an async generator, batches chunks to Ably
|
|
344
|
-
* every chunkBatchMs (default 200ms), then
|
|
579
|
+
* every chunkBatchMs (default 200ms), then POSTs the final message.
|
|
580
|
+
* Resolves with the full response text.
|
|
581
|
+
*
|
|
582
|
+
* A provider error (the generator throwing) does not reject: the failure
|
|
583
|
+
* is stored under the same id as an `error` bubble, exposed as `error`,
|
|
584
|
+
* and the text streamed so far is returned. Only a delivery failure — the
|
|
585
|
+
* server rejecting the final POST after the retry — rejects, and remote
|
|
586
|
+
* bubbles are closed before it does.
|
|
345
587
|
*
|
|
346
|
-
* Mirrors useAbly.ts
|
|
588
|
+
* Mirrors useAbly.ts chunk batching pattern.
|
|
347
589
|
*/
|
|
348
|
-
async stream(generator) {
|
|
590
|
+
async stream(generator, opts) {
|
|
349
591
|
await this.publishTyping();
|
|
350
592
|
let fullText = "";
|
|
351
593
|
let chunkBuffer = "";
|
|
@@ -354,177 +596,201 @@ var MessageContext = class {
|
|
|
354
596
|
if (!chunkBuffer) return;
|
|
355
597
|
const text = chunkBuffer;
|
|
356
598
|
chunkBuffer = "";
|
|
357
|
-
|
|
599
|
+
try {
|
|
600
|
+
await this.publishChunk(text);
|
|
601
|
+
} catch (e) {
|
|
602
|
+
console.warn("[sdk] chunk publish failed:", e instanceof Error ? e.message : e);
|
|
603
|
+
}
|
|
358
604
|
};
|
|
359
605
|
try {
|
|
360
606
|
for await (const chunk of generator()) {
|
|
361
607
|
fullText += chunk;
|
|
362
608
|
chunkBuffer += chunk;
|
|
363
609
|
if (!flushTimer) {
|
|
364
|
-
flushTimer = setTimeout(
|
|
610
|
+
flushTimer = setTimeout(() => {
|
|
365
611
|
flushTimer = null;
|
|
366
|
-
|
|
612
|
+
void flushChunks();
|
|
367
613
|
}, this.chunkBatchMs);
|
|
368
614
|
}
|
|
369
615
|
}
|
|
370
616
|
if (flushTimer) clearTimeout(flushTimer);
|
|
371
617
|
await flushChunks();
|
|
372
|
-
await this.publishResponse(fullText);
|
|
373
|
-
this.persistAsync(fullText, "response");
|
|
374
618
|
} catch (err) {
|
|
375
619
|
if (flushTimer) clearTimeout(flushTimer);
|
|
620
|
+
this.streamError = err;
|
|
376
621
|
const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
|
|
377
|
-
|
|
378
|
-
|
|
622
|
+
try {
|
|
623
|
+
await this.deliver(errText, "error", this.parentFor(opts));
|
|
624
|
+
} catch (e) {
|
|
625
|
+
console.error("[sdk] Failed to persist error message:", e);
|
|
626
|
+
}
|
|
627
|
+
return fullText;
|
|
379
628
|
}
|
|
629
|
+
await this.deliver(fullText, "response", this.parentFor(opts));
|
|
630
|
+
return fullText;
|
|
380
631
|
}
|
|
381
632
|
// ── Internal publish helpers ────────────────────────────────────────
|
|
382
633
|
async publishTyping() {
|
|
383
634
|
await this.ablyManager.publish(this.channelName, "message", {
|
|
384
|
-
from: this.
|
|
635
|
+
from: this.from,
|
|
385
636
|
fromUsername: this.agentName,
|
|
386
637
|
projectId: this.projectId,
|
|
387
638
|
text: "",
|
|
388
639
|
messageId: uuidv4(),
|
|
389
|
-
responseId: this.
|
|
640
|
+
responseId: this.messageId,
|
|
390
641
|
type: "typing",
|
|
391
|
-
agentName: this.agentName
|
|
642
|
+
agentName: this.agentName,
|
|
643
|
+
agentId: this.agentId
|
|
392
644
|
});
|
|
393
645
|
}
|
|
394
646
|
async publishChunk(text) {
|
|
395
647
|
await this.ablyManager.publish(this.channelName, "message", {
|
|
396
|
-
from: this.
|
|
648
|
+
from: this.from,
|
|
397
649
|
fromUsername: this.agentName,
|
|
398
650
|
projectId: this.projectId,
|
|
399
651
|
text,
|
|
400
|
-
messageId: this.
|
|
652
|
+
messageId: this.messageId,
|
|
401
653
|
type: "chunk",
|
|
402
|
-
agentName: this.agentName
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
async publishResponse(text) {
|
|
406
|
-
await this.ablyManager.publish(this.channelName, "message", {
|
|
407
|
-
from: this.userId,
|
|
408
|
-
fromUsername: this.agentName,
|
|
409
|
-
projectId: this.projectId,
|
|
410
|
-
text,
|
|
411
|
-
messageId: this.responseId,
|
|
412
|
-
type: "response",
|
|
413
654
|
agentName: this.agentName,
|
|
414
|
-
|
|
415
|
-
responseDepth: this.responseDepth,
|
|
416
|
-
respondingChain: this.respondingChain
|
|
655
|
+
agentId: this.agentId
|
|
417
656
|
});
|
|
418
657
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
658
|
+
/**
|
|
659
|
+
* POST this reply's final message. If the server rejects it (after
|
|
660
|
+
* `persistMessage`'s single retry), every other client is stuck on the
|
|
661
|
+
* streaming bubble our `typing`/`chunk` events opened — the server echo
|
|
662
|
+
* that would close it is never coming. Close them with a client-published
|
|
663
|
+
* `error` event under the same id (ephemeral: the server does not persist
|
|
664
|
+
* it, acceptable for a last resort), then rethrow.
|
|
665
|
+
*/
|
|
666
|
+
async deliver(text, type, parentMessageId) {
|
|
667
|
+
try {
|
|
668
|
+
return await this.persist(this.messageId, text, type, parentMessageId);
|
|
669
|
+
} catch (err) {
|
|
670
|
+
await this.publishDeliveryFailure(
|
|
671
|
+
err instanceof Error ? err.message : String(err),
|
|
672
|
+
parentMessageId
|
|
673
|
+
);
|
|
674
|
+
throw err;
|
|
675
|
+
}
|
|
429
676
|
}
|
|
430
|
-
/**
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
677
|
+
/** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
|
|
678
|
+
async publishDeliveryFailure(reason, parentMessageId) {
|
|
679
|
+
try {
|
|
680
|
+
await this.ablyManager.publish(this.channelName, "message", {
|
|
681
|
+
from: this.from,
|
|
682
|
+
fromUsername: this.agentName,
|
|
683
|
+
projectId: this.projectId,
|
|
684
|
+
text: `Delivery failed: ${reason}`,
|
|
685
|
+
messageId: this.messageId,
|
|
686
|
+
type: "error",
|
|
687
|
+
agentName: this.agentName,
|
|
688
|
+
agentId: this.agentId,
|
|
689
|
+
isAgentMessage: true,
|
|
690
|
+
parentMessageId
|
|
691
|
+
});
|
|
692
|
+
} catch (e) {
|
|
693
|
+
console.warn("[sdk] delivery-failure publish failed:", e instanceof Error ? e.message : e);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
/** POST the final message. Throws if the server rejects it. */
|
|
697
|
+
async persist(id, text, type, parentMessageId) {
|
|
698
|
+
this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
|
|
699
|
+
try {
|
|
700
|
+
const saved = await this.client.persistMessage(this.projectId, {
|
|
701
|
+
id,
|
|
702
|
+
agentId: this.agentId,
|
|
703
|
+
type,
|
|
704
|
+
text,
|
|
705
|
+
parentMessageId
|
|
706
|
+
});
|
|
707
|
+
this.tracker?.posted(id);
|
|
708
|
+
return saved;
|
|
709
|
+
} catch (err) {
|
|
710
|
+
this.tracker?.failed(id);
|
|
711
|
+
throw err;
|
|
712
|
+
}
|
|
441
713
|
}
|
|
442
714
|
};
|
|
443
715
|
var TaskContext = class {
|
|
444
716
|
task;
|
|
445
717
|
projectId;
|
|
446
718
|
conversationHistory;
|
|
447
|
-
|
|
448
|
-
channelName;
|
|
449
|
-
userId;
|
|
719
|
+
agentId;
|
|
450
720
|
agentName;
|
|
451
721
|
client;
|
|
722
|
+
tracker;
|
|
452
723
|
constructor(opts) {
|
|
453
724
|
this.task = opts.task;
|
|
454
725
|
this.projectId = opts.projectId;
|
|
455
|
-
this.channelName = opts.channelName;
|
|
456
726
|
this.conversationHistory = opts.conversationHistory;
|
|
457
|
-
this.
|
|
458
|
-
this.userId = opts.userId;
|
|
727
|
+
this.agentId = opts.agentId;
|
|
459
728
|
this.agentName = opts.agentName;
|
|
460
729
|
this.client = opts.client;
|
|
730
|
+
this.tracker = opts.tracker;
|
|
461
731
|
}
|
|
462
|
-
/** Mark task as completed, optionally
|
|
732
|
+
/** Mark task as completed, optionally posting a response message. */
|
|
463
733
|
async complete(resultText) {
|
|
464
734
|
await this.client.updateTask(this.task.id, { status: "completed" });
|
|
465
735
|
if (resultText) {
|
|
466
736
|
await this.sendMessage(resultText);
|
|
467
737
|
}
|
|
468
738
|
}
|
|
469
|
-
/** Mark task as failed, optionally
|
|
739
|
+
/** Mark task as failed, optionally posting an error message. */
|
|
470
740
|
async fail(errorText) {
|
|
471
741
|
await this.client.updateTask(this.task.id, { status: "failed" });
|
|
472
742
|
if (errorText) {
|
|
473
|
-
|
|
474
|
-
await this.ablyManager.publish(this.channelName, "message", {
|
|
475
|
-
from: this.userId,
|
|
476
|
-
fromUsername: this.agentName,
|
|
477
|
-
projectId: this.projectId,
|
|
478
|
-
text: errorText,
|
|
479
|
-
messageId: msgId,
|
|
480
|
-
type: "error",
|
|
481
|
-
agentName: this.agentName
|
|
482
|
-
});
|
|
483
|
-
this.client.persistMessage(this.projectId, {
|
|
484
|
-
id: msgId,
|
|
485
|
-
senderType: "agent",
|
|
486
|
-
senderName: this.agentName,
|
|
487
|
-
type: "error",
|
|
488
|
-
text: errorText
|
|
489
|
-
}).catch((err) => console.error("[sdk] Failed to persist:", err));
|
|
743
|
+
await this.sendMessage(errorText, { type: "error" });
|
|
490
744
|
}
|
|
491
745
|
}
|
|
492
746
|
/**
|
|
493
747
|
* Create a follow-up task assigned to another agent.
|
|
494
|
-
* Automatically sets parentTaskId to the current task's ID
|
|
748
|
+
* Automatically sets parentTaskId to the current task's ID and attributes
|
|
749
|
+
* creation to this agent.
|
|
495
750
|
*/
|
|
496
751
|
async createFollowUpTask(data) {
|
|
497
752
|
return this.client.createTask(this.projectId, {
|
|
498
753
|
...data,
|
|
499
754
|
parentTaskId: this.task.id,
|
|
500
755
|
createdByType: "agent",
|
|
501
|
-
createdByName: this.agentName
|
|
756
|
+
createdByName: this.agentName,
|
|
757
|
+
createdByAgentId: this.agentId
|
|
502
758
|
});
|
|
503
759
|
}
|
|
504
|
-
/**
|
|
505
|
-
|
|
760
|
+
/**
|
|
761
|
+
* Post a chat message (for progress updates). Returns the stored message.
|
|
762
|
+
* `type` defaults to "response"; use "message" for notices that must never
|
|
763
|
+
* trigger other agents (agent-to-agent chaining only flows through responses).
|
|
764
|
+
*/
|
|
765
|
+
async sendMessage(text, opts) {
|
|
506
766
|
const msgId = uuidv4();
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
}).catch((err) => console.error("[sdk] Failed to persist:", err));
|
|
767
|
+
const type = opts?.type ?? "response";
|
|
768
|
+
this.tracker?.begin(msgId, this.projectId, text, type, opts?.parentMessageId);
|
|
769
|
+
try {
|
|
770
|
+
const saved = await this.client.persistMessage(this.projectId, {
|
|
771
|
+
id: msgId,
|
|
772
|
+
agentId: this.agentId,
|
|
773
|
+
type,
|
|
774
|
+
text,
|
|
775
|
+
parentMessageId: opts?.parentMessageId
|
|
776
|
+
});
|
|
777
|
+
this.tracker?.posted(msgId);
|
|
778
|
+
return saved;
|
|
779
|
+
} catch (err) {
|
|
780
|
+
this.tracker?.failed(msgId);
|
|
781
|
+
throw err;
|
|
782
|
+
}
|
|
524
783
|
}
|
|
525
784
|
};
|
|
526
785
|
|
|
527
786
|
// src/mentions.ts
|
|
787
|
+
function parseMentions(text) {
|
|
788
|
+
const mentions = [];
|
|
789
|
+
for (const match of text.matchAll(/@(\w+(?:\s+\w+)*)/g)) {
|
|
790
|
+
mentions.push(match[1].toLowerCase());
|
|
791
|
+
}
|
|
792
|
+
return mentions;
|
|
793
|
+
}
|
|
528
794
|
function mentionsAgent(text, agentName) {
|
|
529
795
|
const pattern = new RegExp(`@${escapeRegex(agentName)}(?!\\w)`, "i");
|
|
530
796
|
return pattern.test(text);
|
|
@@ -536,7 +802,7 @@ function escapeRegex(s) {
|
|
|
536
802
|
// src/providers/anthropic.ts
|
|
537
803
|
var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
|
|
538
804
|
var ANTHROPIC_VERSION = "2024-10-22";
|
|
539
|
-
var DEFAULT_MODEL = "claude-sonnet-
|
|
805
|
+
var DEFAULT_MODEL = "claude-sonnet-5";
|
|
540
806
|
var DEFAULT_MAX_TOKENS = 8192;
|
|
541
807
|
var AnthropicProvider = class {
|
|
542
808
|
apiKey;
|
|
@@ -925,82 +1191,262 @@ ${systemPrompt}
|
|
|
925
1191
|
var DEFAULT_MAX_DEPTH = 3;
|
|
926
1192
|
var DEFAULT_CHUNK_BATCH_MS = 200;
|
|
927
1193
|
var DEFAULT_CONTEXT_WINDOW = 20;
|
|
928
|
-
var
|
|
1194
|
+
var DEFAULT_HEARTBEAT_MS = 12e4;
|
|
1195
|
+
var OWN_MESSAGE_MEMORY = 1e3;
|
|
1196
|
+
var MESSAGE_INDEX_SIZE = 500;
|
|
1197
|
+
var META_TTL_MS = 5 * 60 * 1e3;
|
|
1198
|
+
var PLAN_MODE_PREFIX = "You are in PLAN MODE. Analyze the request and provide a detailed plan of what changes you would make, including specific files and code snippets. Do NOT execute any file modifications, write any files, or run any commands that change state. You may read files for context. Format your plan clearly with numbered steps.";
|
|
1199
|
+
var JaibberAgent = class _JaibberAgent extends EventEmitter {
|
|
929
1200
|
config;
|
|
930
1201
|
client;
|
|
931
1202
|
ablyManager = null;
|
|
932
1203
|
messageHandler = null;
|
|
933
1204
|
taskHandler = null;
|
|
934
1205
|
provider = null;
|
|
1206
|
+
providerKind = null;
|
|
935
1207
|
connected = false;
|
|
936
1208
|
projects = [];
|
|
937
1209
|
unsubscribers = [];
|
|
1210
|
+
heartbeatTimer = null;
|
|
1211
|
+
agentId = null;
|
|
1212
|
+
agentRecord = null;
|
|
1213
|
+
keyIdentity = null;
|
|
938
1214
|
/** In-memory conversation history per project. */
|
|
939
1215
|
history = /* @__PURE__ */ new Map();
|
|
1216
|
+
/** Recent messages per project (id → author/parent) for chain reconstruction. */
|
|
1217
|
+
messageIndex = /* @__PURE__ */ new Map();
|
|
940
1218
|
/** Track in-flight responses to prevent double-handling. */
|
|
941
1219
|
activeResponses = /* @__PURE__ */ new Set();
|
|
942
1220
|
/** Session IDs per project for Claude --resume. */
|
|
943
1221
|
sessionIds = /* @__PURE__ */ new Map();
|
|
1222
|
+
/** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
|
|
1223
|
+
ownMessages = /* @__PURE__ */ new Map();
|
|
1224
|
+
/** `meta` hints waiting for their server echo. */
|
|
1225
|
+
pendingMeta = /* @__PURE__ */ new Map();
|
|
1226
|
+
/**
|
|
1227
|
+
* Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
|
|
1228
|
+
* project since the last human message. Threaded chains are bounded by the
|
|
1229
|
+
* `parentMessageId` walk; this catches agents that post without threading,
|
|
1230
|
+
* which would otherwise look like a fresh depth-1 chain every time.
|
|
1231
|
+
*/
|
|
1232
|
+
unthreadedHops = /* @__PURE__ */ new Map();
|
|
944
1233
|
constructor(config) {
|
|
945
1234
|
super();
|
|
946
1235
|
this.config = config;
|
|
947
1236
|
this.client = new JaibberClient(config.serverUrl);
|
|
1237
|
+
this.on("error", _JaibberAgent.defaultErrorListener);
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Default `"error"` listener, registered by the constructor: logs the error
|
|
1241
|
+
* and keeps the process alive. To handle errors yourself without the log,
|
|
1242
|
+
* remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
|
|
1243
|
+
*/
|
|
1244
|
+
static defaultErrorListener = (err) => {
|
|
1245
|
+
console.error("[jaibber-agent] error:", err);
|
|
1246
|
+
};
|
|
1247
|
+
/** Emit `"error"` without ever throwing, even if every listener was removed. */
|
|
1248
|
+
emitError(err) {
|
|
1249
|
+
if (this.listenerCount("error") === 0) {
|
|
1250
|
+
_JaibberAgent.defaultErrorListener(err);
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
this.emit("error", err);
|
|
1254
|
+
}
|
|
1255
|
+
// ── Accessors ───────────────────────────────────────────────────────
|
|
1256
|
+
/** The agent's server-side id (available after `connect()`). */
|
|
1257
|
+
get id() {
|
|
1258
|
+
return this.agentId;
|
|
1259
|
+
}
|
|
1260
|
+
/** The agent record returned by the server (session mode only). */
|
|
1261
|
+
get record() {
|
|
1262
|
+
return this.agentRecord;
|
|
1263
|
+
}
|
|
1264
|
+
/** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
|
|
1265
|
+
get identity() {
|
|
1266
|
+
return this.keyIdentity;
|
|
1267
|
+
}
|
|
1268
|
+
/** The underlying REST client (authenticated after `connect()`). */
|
|
1269
|
+
get api() {
|
|
1270
|
+
return this.client;
|
|
1271
|
+
}
|
|
1272
|
+
/** Projects this agent has joined. */
|
|
1273
|
+
get joinedProjects() {
|
|
1274
|
+
return [...this.projects];
|
|
1275
|
+
}
|
|
1276
|
+
/** Sender id used on client-published typing/chunk events. */
|
|
1277
|
+
get senderId() {
|
|
1278
|
+
return this.client.userId ?? `agent:${this.agentId ?? "unknown"}`;
|
|
1279
|
+
}
|
|
1280
|
+
get maxDepth() {
|
|
1281
|
+
return this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
|
|
948
1282
|
}
|
|
949
1283
|
// ── Lifecycle ───────────────────────────────────────────────────────
|
|
950
|
-
/** Authenticate, connect Ably, subscribe to project channels. */
|
|
1284
|
+
/** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
|
|
951
1285
|
async connect() {
|
|
952
1286
|
if (this.connected) throw new Error("Already connected");
|
|
953
|
-
const
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1287
|
+
const creds = this.config.credentials;
|
|
1288
|
+
const apiKeyMode = "apiKey" in creds;
|
|
1289
|
+
if (apiKeyMode) {
|
|
1290
|
+
this.client.setApiKey(creds.apiKey);
|
|
1291
|
+
this.agentId = this.config.agentId ?? null;
|
|
1292
|
+
console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
|
|
1293
|
+
await this.resolveKeyIdentity();
|
|
1294
|
+
} else {
|
|
1295
|
+
console.log(`[sdk] Logging in as "${creds.username}"...`);
|
|
1296
|
+
await this.client.login(creds.username, creds.password);
|
|
1297
|
+
const record = await this.client.ensureAgent({
|
|
1298
|
+
name: this.config.agentName,
|
|
1299
|
+
instructions: this.config.agentInstructions,
|
|
1300
|
+
provider: this.resolveProviderKind(),
|
|
1301
|
+
kind: "sdk",
|
|
1302
|
+
machineName: this.config.machineName,
|
|
1303
|
+
orgId: this.config.orgId
|
|
1304
|
+
});
|
|
1305
|
+
this.agentId = record.id;
|
|
1306
|
+
this.agentRecord = record;
|
|
1307
|
+
this.config.agentId = record.id;
|
|
1308
|
+
console.log(`[sdk] Agent "${record.name}" registered (id ${record.id})`);
|
|
1309
|
+
}
|
|
958
1310
|
const allProjects = await this.client.listProjects();
|
|
959
|
-
|
|
1311
|
+
if (this.config.projectIds) {
|
|
1312
|
+
const wanted = new Set(this.config.projectIds);
|
|
1313
|
+
this.projects = allProjects.filter((p) => wanted.has(p.id));
|
|
1314
|
+
const missing = this.config.projectIds.filter(
|
|
1315
|
+
(id) => !this.projects.some((p) => p.id === id)
|
|
1316
|
+
);
|
|
1317
|
+
if (missing.length > 0) {
|
|
1318
|
+
console.warn(`[sdk] Project(s) not accessible, skipping: ${missing.join(", ")}`);
|
|
1319
|
+
}
|
|
1320
|
+
} else {
|
|
1321
|
+
this.projects = allProjects.filter((p) => p.role !== "org-admin");
|
|
1322
|
+
}
|
|
960
1323
|
if (this.projects.length === 0) {
|
|
961
1324
|
throw new Error(
|
|
962
|
-
"No projects found. Ensure the
|
|
1325
|
+
apiKeyMode ? "No projects found. Assign this agent to at least one project first (POST /api/me/agents/:id/assignments, or run with --projects when minting the key)." : "No projects found. Ensure the account is a member of at least one project."
|
|
963
1326
|
);
|
|
964
1327
|
}
|
|
965
1328
|
console.log(
|
|
966
1329
|
`[sdk] Found ${this.projects.length} project(s): ${this.projects.map((p) => p.name).join(", ")}`
|
|
967
1330
|
);
|
|
968
|
-
|
|
1331
|
+
if (!apiKeyMode) {
|
|
1332
|
+
for (const project of this.projects) {
|
|
1333
|
+
try {
|
|
1334
|
+
await this.client.assignAgent(this.agentId, project.id);
|
|
1335
|
+
} catch (err) {
|
|
1336
|
+
console.warn(
|
|
1337
|
+
`[sdk] Could not assign agent to "${project.name}": ${err instanceof Error ? err.message : err}`
|
|
1338
|
+
);
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
this.ablyManager = new AblyManager(this.client, {
|
|
1343
|
+
clientId: apiKeyMode ? void 0 : this.client.userId,
|
|
1344
|
+
username: this.config.agentName
|
|
1345
|
+
});
|
|
969
1346
|
await this.ablyManager.connect();
|
|
970
|
-
|
|
971
|
-
this.
|
|
972
|
-
|
|
973
|
-
|
|
1347
|
+
try {
|
|
1348
|
+
if (!this.agentId) {
|
|
1349
|
+
const cid = this.ablyManager.clientId;
|
|
1350
|
+
if (cid && cid.startsWith("agent:")) {
|
|
1351
|
+
this.agentId = cid.slice("agent:".length);
|
|
1352
|
+
this.config.agentId = this.agentId;
|
|
1353
|
+
} else {
|
|
1354
|
+
throw new Error(
|
|
1355
|
+
`Could not resolve the agent id from the API key (Ably clientId was ${JSON.stringify(cid ?? null)}). The key must be bound to an agent \u2014 mint one with POST /api/me/agents/:id/keys or \`jaibber-agent --create-key\`.`
|
|
1356
|
+
);
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
this.startHeartbeat();
|
|
1360
|
+
await this.ablyManager.enterGlobalPresence({
|
|
1361
|
+
userId: this.client.userId ?? void 0,
|
|
1362
|
+
agentId: this.agentId,
|
|
1363
|
+
username: this.config.agentName,
|
|
1364
|
+
projectIds: this.projects.map((p) => p.id)
|
|
1365
|
+
});
|
|
974
1366
|
const presenceData = {
|
|
975
|
-
userId,
|
|
1367
|
+
userId: this.client.userId ?? void 0,
|
|
976
1368
|
username: this.config.agentName,
|
|
977
1369
|
isAgent: true,
|
|
978
1370
|
agentName: this.config.agentName,
|
|
1371
|
+
agentId: this.agentId,
|
|
979
1372
|
agentInstructions: this.config.agentInstructions,
|
|
980
1373
|
agents: [
|
|
981
1374
|
{
|
|
1375
|
+
agentId: this.agentId,
|
|
982
1376
|
agentName: this.config.agentName,
|
|
983
1377
|
agentInstructions: this.config.agentInstructions
|
|
984
1378
|
}
|
|
985
1379
|
],
|
|
986
1380
|
machineName: this.config.machineName
|
|
987
1381
|
};
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
1382
|
+
for (const project of this.projects) {
|
|
1383
|
+
await this.loadHistory(project.id);
|
|
1384
|
+
const unsub = await this.ablyManager.subscribeToProject(
|
|
1385
|
+
project,
|
|
1386
|
+
presenceData,
|
|
1387
|
+
(msg) => this.handleIncomingMessage(msg, project),
|
|
1388
|
+
(data) => this.handleTaskEvent(data, project),
|
|
1389
|
+
(data) => this.handleControlEvent(data, project),
|
|
1390
|
+
(err) => this.emitError(err)
|
|
1391
|
+
);
|
|
1392
|
+
this.unsubscribers.push(unsub);
|
|
1393
|
+
}
|
|
1394
|
+
} catch (err) {
|
|
1395
|
+
this.stopHeartbeat();
|
|
1396
|
+
for (const unsub of this.unsubscribers) unsub();
|
|
1397
|
+
this.unsubscribers = [];
|
|
1398
|
+
await this.ablyManager.disconnect().catch(() => {
|
|
1399
|
+
});
|
|
1400
|
+
this.ablyManager = null;
|
|
1401
|
+
throw err;
|
|
996
1402
|
}
|
|
997
1403
|
this.connected = true;
|
|
998
|
-
console.log(
|
|
1404
|
+
console.log(
|
|
1405
|
+
`[sdk] Agent "${this.config.agentName}" (${this.agentId}) connected and listening`
|
|
1406
|
+
);
|
|
999
1407
|
this.emit("connected", this.projects);
|
|
1000
1408
|
}
|
|
1001
|
-
/**
|
|
1409
|
+
/**
|
|
1410
|
+
* API-key mode: ask the server who the key is (`GET /api/me`) so the agent
|
|
1411
|
+
* id and name are known before Ably connects. Servers that predate the
|
|
1412
|
+
* endpoint answer 404; the id is then read from the Ably token's clientId
|
|
1413
|
+
* (`agent:{id}`) once connected, as in 0.4.0.
|
|
1414
|
+
*/
|
|
1415
|
+
async resolveKeyIdentity() {
|
|
1416
|
+
const me = await this.client.whoAmI();
|
|
1417
|
+
if (me === null) {
|
|
1418
|
+
console.warn(
|
|
1419
|
+
"[sdk] GET /api/me is not available on this server; the agent id will be read from the Ably token."
|
|
1420
|
+
);
|
|
1421
|
+
return;
|
|
1422
|
+
}
|
|
1423
|
+
if (me.type !== "agent") {
|
|
1424
|
+
throw new Error(
|
|
1425
|
+
`The API key is not bound to an agent (GET /api/me reports type "${me.type}"). Mint an agent key with POST /api/me/agents/:id/keys or \`jaibber-agent --create-key\`.`
|
|
1426
|
+
);
|
|
1427
|
+
}
|
|
1428
|
+
if (this.agentId && this.agentId !== me.agentId) {
|
|
1429
|
+
console.warn(
|
|
1430
|
+
`[sdk] Configured agentId ${this.agentId} does not match the key's agent ${me.agentId}; using the key's.`
|
|
1431
|
+
);
|
|
1432
|
+
}
|
|
1433
|
+
this.agentId = me.agentId;
|
|
1434
|
+
this.config.agentId = me.agentId;
|
|
1435
|
+
this.keyIdentity = me;
|
|
1436
|
+
if (me.name && me.name.toLowerCase() !== this.config.agentName.toLowerCase()) {
|
|
1437
|
+
console.warn(
|
|
1438
|
+
`[sdk] agentName "${this.config.agentName}" differs from the key's agent "${me.name}"; using "${me.name}".`
|
|
1439
|
+
);
|
|
1440
|
+
this.config.agentName = me.name;
|
|
1441
|
+
}
|
|
1442
|
+
console.log(
|
|
1443
|
+
`[sdk] Authenticated as agent "${me.name}" (id ${me.agentId}${me.org ? `, org ${me.org.slug}` : ""})`
|
|
1444
|
+
);
|
|
1445
|
+
}
|
|
1446
|
+
/** Stop heartbeats, leave presence, disconnect Ably. */
|
|
1002
1447
|
async disconnect() {
|
|
1003
1448
|
if (!this.connected) return;
|
|
1449
|
+
this.stopHeartbeat();
|
|
1004
1450
|
for (const unsub of this.unsubscribers) {
|
|
1005
1451
|
unsub();
|
|
1006
1452
|
}
|
|
@@ -1025,51 +1471,192 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1025
1471
|
switch (name) {
|
|
1026
1472
|
case "anthropic":
|
|
1027
1473
|
this.provider = new AnthropicProvider(options);
|
|
1474
|
+
this.providerKind = "claude";
|
|
1028
1475
|
break;
|
|
1029
1476
|
case "openai":
|
|
1030
1477
|
this.provider = new OpenAIProvider(options);
|
|
1478
|
+
this.providerKind = "openai";
|
|
1031
1479
|
break;
|
|
1032
1480
|
case "google":
|
|
1033
1481
|
this.provider = new GoogleProvider(options);
|
|
1482
|
+
this.providerKind = "google";
|
|
1034
1483
|
break;
|
|
1035
1484
|
case "claude-cli":
|
|
1036
1485
|
this.provider = new ClaudeCLIProvider(options);
|
|
1486
|
+
this.providerKind = "claude";
|
|
1037
1487
|
break;
|
|
1038
1488
|
}
|
|
1039
1489
|
}
|
|
1490
|
+
/** Provider label stored on the agent record. */
|
|
1491
|
+
resolveProviderKind() {
|
|
1492
|
+
return this.config.provider ?? this.providerKind ?? "custom";
|
|
1493
|
+
}
|
|
1494
|
+
// ── Heartbeat ───────────────────────────────────────────────────────
|
|
1495
|
+
startHeartbeat() {
|
|
1496
|
+
this.stopHeartbeat();
|
|
1497
|
+
const beat = async () => {
|
|
1498
|
+
if (!this.agentId) return;
|
|
1499
|
+
try {
|
|
1500
|
+
await this.client.heartbeat(this.agentId);
|
|
1501
|
+
} catch (err) {
|
|
1502
|
+
console.warn(`[sdk] Heartbeat failed: ${err instanceof Error ? err.message : err}`);
|
|
1503
|
+
}
|
|
1504
|
+
};
|
|
1505
|
+
void beat();
|
|
1506
|
+
this.heartbeatTimer = setInterval(beat, this.config.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
|
|
1507
|
+
this.heartbeatTimer.unref?.();
|
|
1508
|
+
}
|
|
1509
|
+
stopHeartbeat() {
|
|
1510
|
+
if (this.heartbeatTimer) {
|
|
1511
|
+
clearInterval(this.heartbeatTimer);
|
|
1512
|
+
this.heartbeatTimer = null;
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
// ── Message index / chain reconstruction ────────────────────────────
|
|
1516
|
+
indexMessage(projectId, id, entry) {
|
|
1517
|
+
const idx = this.messageIndex.get(projectId) ?? /* @__PURE__ */ new Map();
|
|
1518
|
+
idx.delete(id);
|
|
1519
|
+
idx.set(id, entry);
|
|
1520
|
+
while (idx.size > MESSAGE_INDEX_SIZE) {
|
|
1521
|
+
const oldest = idx.keys().next().value;
|
|
1522
|
+
if (oldest === void 0) break;
|
|
1523
|
+
idx.delete(oldest);
|
|
1524
|
+
}
|
|
1525
|
+
this.messageIndex.set(projectId, idx);
|
|
1526
|
+
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Loop prevention for agent-to-agent chains. The server echo carries no
|
|
1529
|
+
* chain metadata, so the chain is reconstructed from `parentMessageId`
|
|
1530
|
+
* links: every agent response is posted as a reply to the message it
|
|
1531
|
+
* answered. Returns the number of consecutive agent hops ending at
|
|
1532
|
+
* `payload` (the depth) and the lowercased names of the agents in that run.
|
|
1533
|
+
* Mirrors useAbly.ts agentChainFor().
|
|
1534
|
+
*/
|
|
1535
|
+
agentChainFor(projectId, payload) {
|
|
1536
|
+
const idx = this.messageIndex.get(projectId);
|
|
1537
|
+
const chain = [(payload.agentName ?? payload.fromUsername).toLowerCase()];
|
|
1538
|
+
let parentId = payload.parentMessageId;
|
|
1539
|
+
let guard = 0;
|
|
1540
|
+
while (parentId && guard++ < 50) {
|
|
1541
|
+
const parent = idx?.get(parentId);
|
|
1542
|
+
if (!parent?.agentId) break;
|
|
1543
|
+
chain.push(parent.senderName.toLowerCase());
|
|
1544
|
+
parentId = parent.parentMessageId;
|
|
1545
|
+
}
|
|
1546
|
+
return { depth: chain.length, chain };
|
|
1547
|
+
}
|
|
1548
|
+
// ── `meta` hints ────────────────────────────────────────────────────
|
|
1549
|
+
rememberMeta(messageId, meta) {
|
|
1550
|
+
const cutoff = Date.now() - META_TTL_MS;
|
|
1551
|
+
for (const [id, m] of this.pendingMeta) {
|
|
1552
|
+
if (m.receivedAt < cutoff) this.pendingMeta.delete(id);
|
|
1553
|
+
}
|
|
1554
|
+
this.pendingMeta.set(messageId, meta);
|
|
1555
|
+
}
|
|
1556
|
+
takeMeta(messageId, senderId) {
|
|
1557
|
+
const meta = this.pendingMeta.get(messageId);
|
|
1558
|
+
if (!meta) return void 0;
|
|
1559
|
+
this.pendingMeta.delete(messageId);
|
|
1560
|
+
return meta.clientId === senderId ? meta : void 0;
|
|
1561
|
+
}
|
|
1562
|
+
// ── Own-message tracking (echo dedupe + own replies in history) ─────
|
|
1563
|
+
tracker = {
|
|
1564
|
+
begin: (id, projectId, text, type, parentMessageId) => {
|
|
1565
|
+
this.ownMessages.set(id, { projectId, text, type, recorded: false });
|
|
1566
|
+
while (this.ownMessages.size > OWN_MESSAGE_MEMORY) {
|
|
1567
|
+
const oldest = this.ownMessages.keys().next().value;
|
|
1568
|
+
if (oldest === void 0) break;
|
|
1569
|
+
this.ownMessages.delete(oldest);
|
|
1570
|
+
}
|
|
1571
|
+
this.indexMessage(projectId, id, {
|
|
1572
|
+
agentId: this.agentId ?? void 0,
|
|
1573
|
+
senderName: this.config.agentName,
|
|
1574
|
+
parentMessageId
|
|
1575
|
+
});
|
|
1576
|
+
},
|
|
1577
|
+
posted: (id) => this.recordOwnMessage(id),
|
|
1578
|
+
failed: (id) => {
|
|
1579
|
+
this.ownMessages.delete(id);
|
|
1580
|
+
}
|
|
1581
|
+
};
|
|
1582
|
+
/**
|
|
1583
|
+
* Add one of our own messages to history exactly once — whichever arrives
|
|
1584
|
+
* first: the server's Ably echo or the POST response.
|
|
1585
|
+
*/
|
|
1586
|
+
recordOwnMessage(id) {
|
|
1587
|
+
const own = this.ownMessages.get(id);
|
|
1588
|
+
if (!own || own.recorded) return;
|
|
1589
|
+
own.recorded = true;
|
|
1590
|
+
if (own.type === "error") return;
|
|
1591
|
+
this.addToHistory(own.projectId, {
|
|
1592
|
+
sender: "agent",
|
|
1593
|
+
senderName: this.config.agentName,
|
|
1594
|
+
text: own.text,
|
|
1595
|
+
agentId: this.agentId ?? void 0
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1040
1598
|
// ── Message handling ────────────────────────────────────────────────
|
|
1041
1599
|
async handleIncomingMessage(payload, project) {
|
|
1042
1600
|
if (payload._connectionId && payload._connectionId === this.ablyManager?.connectionId) return;
|
|
1043
|
-
if (payload.type === "
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1601
|
+
if (payload.type === "meta") {
|
|
1602
|
+
if (!payload._clientId) return;
|
|
1603
|
+
this.rememberMeta(payload.messageId, {
|
|
1604
|
+
clientId: payload._clientId,
|
|
1605
|
+
executionMode: payload.executionMode,
|
|
1606
|
+
attachments: payload.attachments,
|
|
1607
|
+
receivedAt: Date.now()
|
|
1608
|
+
});
|
|
1050
1609
|
return;
|
|
1051
1610
|
}
|
|
1052
|
-
if (payload.isTaskNotification) return;
|
|
1053
1611
|
if (payload.type !== "message" && payload.type !== "response") return;
|
|
1612
|
+
if (this.ownMessages.has(payload.messageId)) {
|
|
1613
|
+
this.recordOwnMessage(payload.messageId);
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1054
1616
|
if (payload.text && payload.text.length > 1e5) {
|
|
1055
1617
|
console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
|
|
1056
1618
|
return;
|
|
1057
1619
|
}
|
|
1620
|
+
const isAgent = payload.isAgentMessage === true || !!payload.agentId;
|
|
1621
|
+
const isSelf = !!this.agentId && payload.agentId === this.agentId;
|
|
1622
|
+
this.indexMessage(project.id, payload.messageId, {
|
|
1623
|
+
agentId: payload.agentId,
|
|
1624
|
+
senderName: payload.agentName ?? payload.fromUsername,
|
|
1625
|
+
parentMessageId: payload.parentMessageId
|
|
1626
|
+
});
|
|
1627
|
+
if (!isAgent) this.unthreadedHops.set(project.id, 0);
|
|
1058
1628
|
this.addToHistory(project.id, {
|
|
1059
|
-
sender:
|
|
1629
|
+
sender: isAgent ? "agent" : "user",
|
|
1060
1630
|
senderName: payload.fromUsername,
|
|
1061
|
-
text: payload.text
|
|
1631
|
+
text: payload.text,
|
|
1632
|
+
agentId: payload.agentId
|
|
1062
1633
|
});
|
|
1063
|
-
|
|
1064
|
-
|
|
1634
|
+
if (isSelf) return;
|
|
1635
|
+
if (payload.isTaskNotification) return;
|
|
1636
|
+
let depth = 0;
|
|
1637
|
+
let chain = [];
|
|
1638
|
+
let executionMode = payload.executionMode;
|
|
1639
|
+
let attachments = payload.attachments;
|
|
1640
|
+
if (isAgent) {
|
|
1641
|
+
if (payload.type !== "response") return;
|
|
1642
|
+
({ depth, chain } = this.agentChainFor(project.id, payload));
|
|
1643
|
+
if (!payload.parentMessageId) {
|
|
1644
|
+
const n = (this.unthreadedHops.get(project.id) ?? 0) + 1;
|
|
1645
|
+
this.unthreadedHops.set(project.id, n);
|
|
1646
|
+
if (n > this.maxDepth) return;
|
|
1647
|
+
}
|
|
1648
|
+
} else {
|
|
1649
|
+
const meta = this.takeMeta(payload.messageId, payload.from);
|
|
1650
|
+
executionMode = executionMode ?? meta?.executionMode;
|
|
1651
|
+
attachments = attachments ?? meta?.attachments;
|
|
1652
|
+
}
|
|
1065
1653
|
if (!this.shouldRespond(payload.text, depth, chain)) return;
|
|
1066
1654
|
if (this.activeResponses.has(payload.messageId)) return;
|
|
1067
1655
|
this.activeResponses.add(payload.messageId);
|
|
1068
1656
|
try {
|
|
1069
|
-
await this.respondToMessage(payload, project, depth, chain);
|
|
1657
|
+
await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
|
|
1070
1658
|
} catch (err) {
|
|
1071
|
-
|
|
1072
|
-
this.emit("error", err);
|
|
1659
|
+
this.emitError(err);
|
|
1073
1660
|
} finally {
|
|
1074
1661
|
this.activeResponses.delete(payload.messageId);
|
|
1075
1662
|
}
|
|
@@ -1079,26 +1666,27 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1079
1666
|
* Mirrors useAbly.ts shouldAgentRespond() logic.
|
|
1080
1667
|
*/
|
|
1081
1668
|
shouldRespond(text, depth, chain) {
|
|
1082
|
-
|
|
1083
|
-
if (depth >= maxDepth) return false;
|
|
1669
|
+
if (depth >= this.maxDepth) return false;
|
|
1084
1670
|
if (chain.includes(this.config.agentName.toLowerCase())) return false;
|
|
1085
1671
|
if (!mentionsAgent(text, this.config.agentName)) return false;
|
|
1086
1672
|
return true;
|
|
1087
1673
|
}
|
|
1088
|
-
async respondToMessage(payload, project, incomingDepth, incomingChain) {
|
|
1089
|
-
const userId = this.client.userId;
|
|
1674
|
+
async respondToMessage(payload, project, incomingDepth, incomingChain, executionMode, attachments) {
|
|
1090
1675
|
const conversationHistory = this.getFormattedHistory(project.id);
|
|
1091
1676
|
const ctx = new MessageContext({
|
|
1092
1677
|
projectId: project.id,
|
|
1093
1678
|
channelName: project.ablyChannelName,
|
|
1094
1679
|
conversationHistory,
|
|
1095
1680
|
ablyManager: this.ablyManager,
|
|
1096
|
-
|
|
1681
|
+
from: this.senderId,
|
|
1682
|
+
agentId: this.agentId,
|
|
1097
1683
|
agentName: this.config.agentName,
|
|
1098
1684
|
client: this.client,
|
|
1685
|
+
incomingMessageId: payload.messageId,
|
|
1099
1686
|
incomingDepth,
|
|
1100
1687
|
incomingChain,
|
|
1101
|
-
chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
|
|
1688
|
+
chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
|
|
1689
|
+
tracker: this.tracker
|
|
1102
1690
|
});
|
|
1103
1691
|
if (this.messageHandler) {
|
|
1104
1692
|
await this.messageHandler(
|
|
@@ -1111,20 +1699,30 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1111
1699
|
type: payload.type,
|
|
1112
1700
|
responseDepth: incomingDepth,
|
|
1113
1701
|
respondingChain: incomingChain,
|
|
1114
|
-
executionMode
|
|
1702
|
+
executionMode,
|
|
1115
1703
|
isAgentMessage: payload.isAgentMessage,
|
|
1116
|
-
|
|
1704
|
+
agentId: payload.agentId,
|
|
1705
|
+
agentName: payload.agentName,
|
|
1706
|
+
mentions: payload.mentions,
|
|
1707
|
+
parentMessageId: payload.parentMessageId,
|
|
1708
|
+
attachments,
|
|
1709
|
+
createdAt: payload.createdAt
|
|
1117
1710
|
},
|
|
1118
1711
|
ctx
|
|
1119
1712
|
);
|
|
1713
|
+
if (ctx.error !== void 0) this.emitError(ctx.error);
|
|
1120
1714
|
return;
|
|
1121
1715
|
}
|
|
1122
1716
|
if (this.provider) {
|
|
1123
1717
|
this.updateProviderSession(project.id);
|
|
1124
|
-
const systemPrompt = this.
|
|
1718
|
+
const systemPrompt = this.systemPromptFor(executionMode);
|
|
1125
1719
|
await ctx.stream(
|
|
1126
1720
|
() => this.provider.generate(payload.text, systemPrompt, conversationHistory)
|
|
1127
1721
|
);
|
|
1722
|
+
if (ctx.error !== void 0) {
|
|
1723
|
+
this.emitError(ctx.error);
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1128
1726
|
this.captureProviderSession(project.id);
|
|
1129
1727
|
return;
|
|
1130
1728
|
}
|
|
@@ -1132,36 +1730,54 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1132
1730
|
"[sdk] No message handler or provider configured. Ignoring message."
|
|
1133
1731
|
);
|
|
1134
1732
|
}
|
|
1733
|
+
/** Agent instructions, prefixed with the plan-mode directive when requested. */
|
|
1734
|
+
systemPromptFor(executionMode) {
|
|
1735
|
+
const instructions = this.config.agentInstructions ?? "";
|
|
1736
|
+
if (executionMode !== "plan") return instructions;
|
|
1737
|
+
return instructions ? `${PLAN_MODE_PREFIX}
|
|
1738
|
+
|
|
1739
|
+
${instructions}` : PLAN_MODE_PREFIX;
|
|
1740
|
+
}
|
|
1741
|
+
// ── Agent control (server-published lifecycle commands) ─────────────
|
|
1742
|
+
/** Is a server control event addressed to this agent? */
|
|
1743
|
+
isControlForMe(data) {
|
|
1744
|
+
if (this.agentId) return data.agentId === this.agentId;
|
|
1745
|
+
return !!data.agentName && data.agentName.toLowerCase() === this.config.agentName.toLowerCase();
|
|
1746
|
+
}
|
|
1747
|
+
/**
|
|
1748
|
+
* `agent-control` events are published by the server on project channels,
|
|
1749
|
+
* e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
|
|
1750
|
+
* via the API. Events for other agents are ignored.
|
|
1751
|
+
*/
|
|
1752
|
+
async handleControlEvent(data, project) {
|
|
1753
|
+
if (!data || data.action !== "deregister") return;
|
|
1754
|
+
if (!this.isControlForMe(data)) return;
|
|
1755
|
+
console.log(
|
|
1756
|
+
`[sdk] Agent "${this.config.agentName}" was deregistered by the server (via project "${project.name}"). Shutting down...`
|
|
1757
|
+
);
|
|
1758
|
+
try {
|
|
1759
|
+
await this.disconnect();
|
|
1760
|
+
} catch (err) {
|
|
1761
|
+
console.error("[sdk] Error during deregister shutdown:", err);
|
|
1762
|
+
}
|
|
1763
|
+
this.emit("deregistered", data);
|
|
1764
|
+
if (this.config.exitOnDeregister !== false) {
|
|
1765
|
+
process.exit(0);
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1135
1768
|
// ── Task handling ───────────────────────────────────────────────────
|
|
1136
1769
|
async handleTaskEvent(data, project) {
|
|
1137
1770
|
if (data.type !== "task-created" && data.type !== "task-updated")
|
|
1138
1771
|
return;
|
|
1139
1772
|
const task = data.task;
|
|
1140
1773
|
if (task.status !== "submitted") return;
|
|
1141
|
-
|
|
1142
|
-
|
|
1774
|
+
const mine = task.assignedAgentId ? !!this.agentId && task.assignedAgentId === this.agentId : !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
|
|
1775
|
+
if (!mine) return;
|
|
1143
1776
|
console.log(
|
|
1144
1777
|
`[sdk] Picking up task: "${task.title}" (${task.id})`
|
|
1145
1778
|
);
|
|
1146
1779
|
try {
|
|
1147
1780
|
await this.client.updateTask(task.id, { status: "working" });
|
|
1148
|
-
const userId = this.client.userId;
|
|
1149
|
-
const announceMsgId = uuidv42();
|
|
1150
|
-
await this.ablyManager.publish(
|
|
1151
|
-
project.ablyChannelName,
|
|
1152
|
-
"message",
|
|
1153
|
-
{
|
|
1154
|
-
from: userId,
|
|
1155
|
-
fromUsername: this.config.agentName,
|
|
1156
|
-
projectId: project.id,
|
|
1157
|
-
text: `Picking up task: **${task.title}**`,
|
|
1158
|
-
messageId: announceMsgId,
|
|
1159
|
-
type: "message",
|
|
1160
|
-
agentName: this.config.agentName,
|
|
1161
|
-
isAgentMessage: true,
|
|
1162
|
-
isTaskNotification: true
|
|
1163
|
-
}
|
|
1164
|
-
);
|
|
1165
1781
|
const conversationHistory = this.getFormattedHistory(project.id);
|
|
1166
1782
|
const ctx = new TaskContext({
|
|
1167
1783
|
task,
|
|
@@ -1169,10 +1785,19 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1169
1785
|
channelName: project.ablyChannelName,
|
|
1170
1786
|
conversationHistory,
|
|
1171
1787
|
ablyManager: this.ablyManager,
|
|
1172
|
-
|
|
1788
|
+
from: this.senderId,
|
|
1789
|
+
agentId: this.agentId,
|
|
1173
1790
|
agentName: this.config.agentName,
|
|
1174
|
-
client: this.client
|
|
1791
|
+
client: this.client,
|
|
1792
|
+
tracker: this.tracker
|
|
1175
1793
|
});
|
|
1794
|
+
try {
|
|
1795
|
+
await ctx.sendMessage(`Picking up task: **${task.title}**`, { type: "message" });
|
|
1796
|
+
} catch (err) {
|
|
1797
|
+
console.warn(
|
|
1798
|
+
`[sdk] Could not announce task pickup: ${err instanceof Error ? err.message : err}`
|
|
1799
|
+
);
|
|
1800
|
+
}
|
|
1176
1801
|
if (this.taskHandler) {
|
|
1177
1802
|
await this.taskHandler(task, ctx);
|
|
1178
1803
|
return;
|
|
@@ -1188,33 +1813,36 @@ ${task.description}` : `Task: ${task.title}`;
|
|
|
1188
1813
|
channelName: project.ablyChannelName,
|
|
1189
1814
|
conversationHistory,
|
|
1190
1815
|
ablyManager: this.ablyManager,
|
|
1191
|
-
|
|
1816
|
+
from: this.senderId,
|
|
1817
|
+
agentId: this.agentId,
|
|
1192
1818
|
agentName: this.config.agentName,
|
|
1193
1819
|
client: this.client,
|
|
1194
1820
|
incomingDepth: 0,
|
|
1195
1821
|
incomingChain: [],
|
|
1196
|
-
chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
|
|
1822
|
+
chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
|
|
1823
|
+
tracker: this.tracker
|
|
1197
1824
|
});
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
this.
|
|
1207
|
-
await this.client.updateTask(task.id, { status: "completed" });
|
|
1208
|
-
} catch {
|
|
1825
|
+
await msgCtx.stream(
|
|
1826
|
+
() => this.provider.generate(
|
|
1827
|
+
taskPrompt,
|
|
1828
|
+
systemPrompt,
|
|
1829
|
+
conversationHistory
|
|
1830
|
+
)
|
|
1831
|
+
);
|
|
1832
|
+
if (msgCtx.error !== void 0) {
|
|
1833
|
+
this.emitError(msgCtx.error);
|
|
1209
1834
|
await this.client.updateTask(task.id, { status: "failed" });
|
|
1835
|
+
return;
|
|
1210
1836
|
}
|
|
1837
|
+
this.captureProviderSession(project.id);
|
|
1838
|
+
await this.client.updateTask(task.id, { status: "completed" });
|
|
1211
1839
|
return;
|
|
1212
1840
|
}
|
|
1213
1841
|
console.warn(
|
|
1214
1842
|
"[sdk] No task handler or provider configured. Task left as working."
|
|
1215
1843
|
);
|
|
1216
1844
|
} catch (err) {
|
|
1217
|
-
|
|
1845
|
+
this.emitError(err);
|
|
1218
1846
|
try {
|
|
1219
1847
|
await this.client.updateTask(task.id, { status: "failed" });
|
|
1220
1848
|
} catch {
|
|
@@ -1243,6 +1871,11 @@ ${task.description}` : `Task: ${task.title}`;
|
|
|
1243
1871
|
}
|
|
1244
1872
|
}
|
|
1245
1873
|
// ── Conversation history ────────────────────────────────────────────
|
|
1874
|
+
/** Is this stored message one of this agent's own prior replies? */
|
|
1875
|
+
isOwnServerMessage(m) {
|
|
1876
|
+
if (this.agentId && m.senderAgentId === this.agentId) return true;
|
|
1877
|
+
return m.senderType === "agent" && m.senderName.toLowerCase() === this.config.agentName.toLowerCase();
|
|
1878
|
+
}
|
|
1246
1879
|
async loadHistory(projectId) {
|
|
1247
1880
|
const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
|
|
1248
1881
|
try {
|
|
@@ -1250,12 +1883,30 @@ ${task.description}` : `Task: ${task.title}`;
|
|
|
1250
1883
|
projectId,
|
|
1251
1884
|
contextSize
|
|
1252
1885
|
);
|
|
1253
|
-
const
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
}
|
|
1258
|
-
|
|
1886
|
+
const first = messages[0];
|
|
1887
|
+
const last = messages[messages.length - 1];
|
|
1888
|
+
if (first && last && first !== last && first.createdAt > last.createdAt) {
|
|
1889
|
+
messages.reverse();
|
|
1890
|
+
}
|
|
1891
|
+
const entries = [];
|
|
1892
|
+
for (const m of messages) {
|
|
1893
|
+
const own = this.isOwnServerMessage(m);
|
|
1894
|
+
const agentId = m.senderAgentId ?? (own ? this.agentId ?? void 0 : void 0);
|
|
1895
|
+
this.indexMessage(projectId, m.id, {
|
|
1896
|
+
agentId,
|
|
1897
|
+
senderName: own ? this.config.agentName : m.senderName,
|
|
1898
|
+
parentMessageId: m.parentMessageId ?? void 0
|
|
1899
|
+
});
|
|
1900
|
+
if (m.type === "system" || !m.text) continue;
|
|
1901
|
+
const sender = own || m.senderType === "agent" ? "agent" : "user";
|
|
1902
|
+
entries.push({
|
|
1903
|
+
sender,
|
|
1904
|
+
senderName: own ? this.config.agentName : m.senderName,
|
|
1905
|
+
text: m.text,
|
|
1906
|
+
agentId
|
|
1907
|
+
});
|
|
1908
|
+
}
|
|
1909
|
+
this.history.set(projectId, entries.slice(-contextSize));
|
|
1259
1910
|
} catch (err) {
|
|
1260
1911
|
console.error(
|
|
1261
1912
|
`[sdk] Failed to load history for project ${projectId}:`,
|
|
@@ -1275,7 +1926,7 @@ ${task.description}` : `Task: ${task.title}`;
|
|
|
1275
1926
|
}
|
|
1276
1927
|
/**
|
|
1277
1928
|
* Format conversation history for LLM context.
|
|
1278
|
-
* Matches useAbly.ts
|
|
1929
|
+
* Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
|
|
1279
1930
|
*/
|
|
1280
1931
|
getFormattedHistory(projectId) {
|
|
1281
1932
|
const entries = this.history.get(projectId) ?? [];
|
|
@@ -1340,9 +1991,12 @@ export {
|
|
|
1340
1991
|
ClaudeCLIProvider,
|
|
1341
1992
|
GoogleProvider,
|
|
1342
1993
|
JaibberAgent,
|
|
1994
|
+
JaibberClient,
|
|
1343
1995
|
MessageContext,
|
|
1344
1996
|
OpenAIProvider,
|
|
1345
1997
|
TaskContext,
|
|
1346
|
-
getTemplate
|
|
1998
|
+
getTemplate,
|
|
1999
|
+
mentionsAgent,
|
|
2000
|
+
parseMentions
|
|
1347
2001
|
};
|
|
1348
2002
|
//# sourceMappingURL=index.js.map
|