@teable/agent-gateway 1.0.0 → 1.0.2
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 +4 -0
- package/dist/agent.d.ts +13 -1
- package/dist/agents.d.ts +5 -0
- package/dist/chunks/XGVR5ONA.js +112 -0
- package/dist/cli.js +392 -62
- package/dist/gateway.d.ts +2 -0
- package/dist/protocol.d.ts +411 -60
- package/dist/protocol.js +17 -3
- package/dist/shims.d.ts +38 -0
- package/package.json +1 -1
- package/dist/chunks/5YARUI7L.js +0 -40
package/dist/cli.js
CHANGED
|
@@ -3,14 +3,20 @@ import {
|
|
|
3
3
|
ACP,
|
|
4
4
|
AGENT_NAMES,
|
|
5
5
|
AGENT_PROTOCOL,
|
|
6
|
+
ASK,
|
|
6
7
|
GATEWAY_CLOSE,
|
|
8
|
+
GATEWAY_TOO_FAST,
|
|
9
|
+
MAX_FRAME,
|
|
10
|
+
NOTICE,
|
|
7
11
|
PING,
|
|
8
12
|
PONG,
|
|
9
13
|
SESSION_ID,
|
|
14
|
+
TASK_OUTPUT,
|
|
10
15
|
isAcpNotification,
|
|
11
16
|
isAcpRequest,
|
|
12
|
-
isAcpResponse
|
|
13
|
-
|
|
17
|
+
isAcpResponse,
|
|
18
|
+
shrink
|
|
19
|
+
} from "./chunks/XGVR5ONA.js";
|
|
14
20
|
|
|
15
21
|
// src/cli.ts
|
|
16
22
|
import { readFileSync } from "node:fs";
|
|
@@ -26,13 +32,22 @@ import { join as join3 } from "node:path";
|
|
|
26
32
|
import { spawn } from "node:child_process";
|
|
27
33
|
import { createInterface } from "node:readline";
|
|
28
34
|
var METHOD_NOT_FOUND = -32601;
|
|
35
|
+
var INVALID_PARAMS = -32602;
|
|
29
36
|
var STDERR_LINES = 20;
|
|
30
37
|
var AgentProcess = class {
|
|
31
38
|
#child;
|
|
32
39
|
#start;
|
|
33
40
|
#pending = /* @__PURE__ */ new Map();
|
|
34
|
-
/** The hub's `session/prompt` requests the agent has not answered. */
|
|
41
|
+
/** The hub's `session/prompt` requests the agent has not answered, steers among them. */
|
|
35
42
|
#prompts = /* @__PURE__ */ new Set();
|
|
43
|
+
/** The messages sent to steer a running turn that the agent has not taken in, oldest first. */
|
|
44
|
+
#steers = [];
|
|
45
|
+
/** The steers it took in, whose answers nobody waits for. */
|
|
46
|
+
#absorbed = /* @__PURE__ */ new Set();
|
|
47
|
+
/** Its background tasks that run, as its notices say. */
|
|
48
|
+
#tasks = /* @__PURE__ */ new Set();
|
|
49
|
+
/** The agent's requests that ask the person, relayed by a shim, until the hub answers them. */
|
|
50
|
+
#asked = /* @__PURE__ */ new Map();
|
|
36
51
|
#stderr = [];
|
|
37
52
|
#nextId = 1;
|
|
38
53
|
#loading = false;
|
|
@@ -69,6 +84,10 @@ var AgentProcess = class {
|
|
|
69
84
|
get prompts() {
|
|
70
85
|
return [...this.#prompts];
|
|
71
86
|
}
|
|
87
|
+
/** How many of its background tasks run. */
|
|
88
|
+
get tasks() {
|
|
89
|
+
return this.#tasks.size;
|
|
90
|
+
}
|
|
72
91
|
/** A request of the gateway's own; rejects with the agent's error, or when it takes too long. */
|
|
73
92
|
request(method, params, timeoutMs) {
|
|
74
93
|
const id = `gateway:${this.#nextId++}`;
|
|
@@ -99,11 +118,38 @@ var AgentProcess = class {
|
|
|
99
118
|
this.#loading = false;
|
|
100
119
|
}
|
|
101
120
|
}
|
|
102
|
-
/**
|
|
121
|
+
/**
|
|
122
|
+
* Send a message into the running turn, as the agent takes one: a second
|
|
123
|
+
* `session/prompt`, under the hub's id.
|
|
124
|
+
*/
|
|
125
|
+
steer(request, params) {
|
|
126
|
+
this.#prompts.add(request);
|
|
127
|
+
this.#steers.push(request);
|
|
128
|
+
this.#write({ jsonrpc: "2.0", id: request, method: ACP.prompt, params });
|
|
129
|
+
}
|
|
130
|
+
/** Relay the hub's message to the agent: unchanged, but an answer to what a shim asked, in the agent's words. */
|
|
103
131
|
send(message) {
|
|
104
132
|
if (isAcpRequest(message) && message.method === ACP.prompt) this.#prompts.add(message.id);
|
|
133
|
+
const asked = isAcpResponse(message) ? this.#asked.get(message.id) : void 0;
|
|
134
|
+
if (asked && isAcpResponse(message)) {
|
|
135
|
+
this.#asked.delete(message.id);
|
|
136
|
+
if (message.error === void 0) {
|
|
137
|
+
this.#write(this.#answer(message.id, asked, message.result));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
105
141
|
this.#write(message);
|
|
106
142
|
}
|
|
143
|
+
/** The hub's answer to what a shim asked, in the agent's words. */
|
|
144
|
+
#answer(id, asked, answer) {
|
|
145
|
+
try {
|
|
146
|
+
return { jsonrpc: "2.0", id, result: asked.shim.result(answer, asked.params) };
|
|
147
|
+
} catch (error) {
|
|
148
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
149
|
+
this.#start.log(`the hub's answer to ${asked.shim.method} could not be given: ${why}`);
|
|
150
|
+
return { jsonrpc: "2.0", id, error: { code: INVALID_PARAMS, message: why } };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
107
153
|
/** Stop reading what the agent says (its writes then wait), and read on. */
|
|
108
154
|
pause() {
|
|
109
155
|
this.#child.stdout?.pause();
|
|
@@ -145,17 +191,69 @@ var AgentProcess = class {
|
|
|
145
191
|
return;
|
|
146
192
|
}
|
|
147
193
|
this.#prompts.delete(message.id);
|
|
194
|
+
this.#steers = this.#steers.filter((id) => id !== message.id);
|
|
195
|
+
if (this.#absorbed.delete(message.id)) return;
|
|
148
196
|
} else if (message.method.startsWith("_")) {
|
|
149
|
-
if (isAcpRequest(message))
|
|
150
|
-
|
|
151
|
-
this.#write({ jsonrpc: "2.0", id: message.id, error });
|
|
152
|
-
}
|
|
197
|
+
if (isAcpRequest(message)) this.#vendorRequest(message);
|
|
198
|
+
else this.#vendorNotice(message);
|
|
153
199
|
return;
|
|
154
200
|
} else if (this.#loading && isAcpNotification(message) && message.method === ACP.update) {
|
|
155
201
|
return;
|
|
156
202
|
}
|
|
157
203
|
this.#start.onMessage(message);
|
|
158
204
|
}
|
|
205
|
+
/** A vendor request: what the agent asks the person goes to the hub as the protocol's; the rest is unknown. */
|
|
206
|
+
#vendorRequest(message) {
|
|
207
|
+
const shim = this.#start.asks?.[message.method];
|
|
208
|
+
if (!shim) {
|
|
209
|
+
const error = { code: METHOD_NOT_FOUND, message: `${message.method} is not supported` };
|
|
210
|
+
this.#write({ jsonrpc: "2.0", id: message.id, error });
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
let params;
|
|
214
|
+
try {
|
|
215
|
+
params = shim.request(message.params);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
218
|
+
this.#start.log(`the agent's ${message.method} could not be read: ${why}`);
|
|
219
|
+
this.#write({
|
|
220
|
+
jsonrpc: "2.0",
|
|
221
|
+
id: message.id,
|
|
222
|
+
error: { code: INVALID_PARAMS, message: `${message.method}: ${why}` }
|
|
223
|
+
});
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
this.#asked.set(message.id, { shim, params: message.params });
|
|
227
|
+
this.#start.onMessage({ jsonrpc: "2.0", id: message.id, method: shim.method, params });
|
|
228
|
+
}
|
|
229
|
+
/** A vendor notification: what the protocol has words for goes to the hub as its; the rest is dropped. */
|
|
230
|
+
#vendorNotice(message) {
|
|
231
|
+
const shim = this.#start.notices?.[message.method];
|
|
232
|
+
if (!shim) return;
|
|
233
|
+
let notices;
|
|
234
|
+
try {
|
|
235
|
+
notices = shim.notices(message.params, {
|
|
236
|
+
steered: () => {
|
|
237
|
+
const request = this.#steers.shift();
|
|
238
|
+
if (request === void 0) return null;
|
|
239
|
+
this.#absorbed.add(request);
|
|
240
|
+
return request;
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
} catch (error) {
|
|
244
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
245
|
+
this.#start.log(`the agent's ${message.method} could not be read: ${why}`);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
for (const notice of notices) {
|
|
249
|
+
if (notice.method === NOTICE.task) {
|
|
250
|
+
const { task, status } = notice.params;
|
|
251
|
+
if (status === "running") this.#tasks.add(task);
|
|
252
|
+
else this.#tasks.delete(task);
|
|
253
|
+
}
|
|
254
|
+
this.#start.onMessage(notice);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
159
257
|
#exit(message) {
|
|
160
258
|
if (this.#exited) return;
|
|
161
259
|
this.#exited = true;
|
|
@@ -168,10 +266,158 @@ var AgentProcess = class {
|
|
|
168
266
|
// src/agents.ts
|
|
169
267
|
import { chmodSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
170
268
|
import { dirname, join } from "node:path";
|
|
171
|
-
|
|
269
|
+
|
|
270
|
+
// src/shims.ts
|
|
271
|
+
function fields(value, what) {
|
|
272
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
273
|
+
throw new Error(`${what} is not an object`);
|
|
274
|
+
}
|
|
275
|
+
return value;
|
|
276
|
+
}
|
|
277
|
+
function text(value, what) {
|
|
278
|
+
if (typeof value !== "string") throw new Error(`${what} is not a string`);
|
|
279
|
+
return value;
|
|
280
|
+
}
|
|
281
|
+
var textOrNull = (value) => typeof value === "string" ? value : null;
|
|
282
|
+
function list(value, what) {
|
|
283
|
+
if (!Array.isArray(value)) throw new Error(`${what} is not a list`);
|
|
284
|
+
return value;
|
|
285
|
+
}
|
|
286
|
+
var grokQuestions = {
|
|
287
|
+
method: ASK.question,
|
|
288
|
+
request(params) {
|
|
289
|
+
const asked = fields(params, "ask_user_question's params");
|
|
290
|
+
const questions = list(asked.questions, "questions").map((value, index) => {
|
|
291
|
+
const question = fields(value, `question ${index}`);
|
|
292
|
+
return {
|
|
293
|
+
question: text(question.question, `question ${index}'s text`),
|
|
294
|
+
options: list(question.options, `question ${index}'s options`).map((option, at) => {
|
|
295
|
+
const choice = fields(option, `question ${index}'s option ${at}`);
|
|
296
|
+
return {
|
|
297
|
+
label: text(choice.label, `question ${index}'s option ${at}'s label`),
|
|
298
|
+
description: textOrNull(choice.description),
|
|
299
|
+
preview: textOrNull(choice.preview)
|
|
300
|
+
};
|
|
301
|
+
}),
|
|
302
|
+
multiSelect: question.multiSelect === true,
|
|
303
|
+
freeText: true
|
|
304
|
+
};
|
|
305
|
+
});
|
|
306
|
+
return {
|
|
307
|
+
sessionId: text(asked.sessionId, "sessionId"),
|
|
308
|
+
toolCallId: textOrNull(asked.toolCallId),
|
|
309
|
+
questions
|
|
310
|
+
};
|
|
311
|
+
},
|
|
312
|
+
result(answer, params) {
|
|
313
|
+
const given = fields(answer, "the answer");
|
|
314
|
+
if (given.outcome !== "answered") return { outcome: "cancelled" };
|
|
315
|
+
const questions = list(fields(params, "the params").questions, "questions");
|
|
316
|
+
const answers = list(given.answers, "answers");
|
|
317
|
+
return {
|
|
318
|
+
outcome: "accepted",
|
|
319
|
+
answers: Object.fromEntries(
|
|
320
|
+
questions.map((value, index) => {
|
|
321
|
+
const { picked, text: own } = fields(answers[index] ?? {}, `answer ${index}`);
|
|
322
|
+
const words = [...Array.isArray(picked) ? picked : [], ...own ? [own] : []];
|
|
323
|
+
return [
|
|
324
|
+
text(fields(value, `question ${index}`).question, "a question"),
|
|
325
|
+
words.join(", ")
|
|
326
|
+
];
|
|
327
|
+
})
|
|
328
|
+
),
|
|
329
|
+
annotations: {}
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
var grokPlan = {
|
|
334
|
+
method: ASK.plan,
|
|
335
|
+
request(params) {
|
|
336
|
+
const asked = fields(params, "exit_plan_mode's params");
|
|
337
|
+
return {
|
|
338
|
+
sessionId: text(asked.sessionId, "sessionId"),
|
|
339
|
+
toolCallId: textOrNull(asked.toolCallId),
|
|
340
|
+
plan: typeof asked.planContent === "string" ? asked.planContent : ""
|
|
341
|
+
};
|
|
342
|
+
},
|
|
343
|
+
result(answer) {
|
|
344
|
+
const given = fields(answer, "the answer");
|
|
345
|
+
if (given.outcome === "approved") return { outcome: "approved" };
|
|
346
|
+
if (given.outcome !== "rejected") return { outcome: "cancelled" };
|
|
347
|
+
const feedback = textOrNull(given.feedback);
|
|
348
|
+
return { outcome: "requested_changes", ...feedback ? { feedback } : {} };
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
var GROK_ASKS = {
|
|
352
|
+
"_x.ai/ask_user_question": grokQuestions,
|
|
353
|
+
"_x.ai/exit_plan_mode": grokPlan
|
|
354
|
+
};
|
|
355
|
+
var grokInterjection = {
|
|
356
|
+
notices(params, context) {
|
|
357
|
+
const asked = fields(params, "interjection's params");
|
|
358
|
+
const request = context.steered();
|
|
359
|
+
if (request === null) return [];
|
|
360
|
+
return [
|
|
361
|
+
{
|
|
362
|
+
jsonrpc: "2.0",
|
|
363
|
+
method: NOTICE.steered,
|
|
364
|
+
params: { sessionId: text(asked.sessionId, "sessionId"), request }
|
|
365
|
+
}
|
|
366
|
+
];
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
var taskNotice = (params) => ({
|
|
370
|
+
jsonrpc: "2.0",
|
|
371
|
+
method: NOTICE.task,
|
|
372
|
+
params
|
|
373
|
+
});
|
|
374
|
+
var tail = (output) => output.length > TASK_OUTPUT ? `\u2026${output.slice(-TASK_OUTPUT)}` : output;
|
|
375
|
+
var grokTaskStarted = {
|
|
376
|
+
notices(params) {
|
|
377
|
+
const started = fields(params, "task_backgrounded's params");
|
|
378
|
+
const update = fields(started.update, "its update");
|
|
379
|
+
return [
|
|
380
|
+
taskNotice({
|
|
381
|
+
sessionId: text(started.sessionId, "sessionId"),
|
|
382
|
+
task: text(update.task_id, "task_id"),
|
|
383
|
+
title: textOrNull(update.description) || text(update.command, "command"),
|
|
384
|
+
status: "running",
|
|
385
|
+
toolCallId: textOrNull(update.tool_call_id),
|
|
386
|
+
output: null,
|
|
387
|
+
exitCode: null
|
|
388
|
+
})
|
|
389
|
+
];
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
var grokTaskEnded = {
|
|
393
|
+
notices(params) {
|
|
394
|
+
const ended = fields(params, "task_completed's params");
|
|
395
|
+
const task = fields(fields(ended.update, "its update").task_snapshot, "its task");
|
|
396
|
+
const exitCode = typeof task.exit_code === "number" ? task.exit_code : null;
|
|
397
|
+
return [
|
|
398
|
+
taskNotice({
|
|
399
|
+
sessionId: text(ended.sessionId, "sessionId"),
|
|
400
|
+
task: text(task.task_id, "task_id"),
|
|
401
|
+
title: textOrNull(task.description) || text(task.command, "command"),
|
|
402
|
+
status: exitCode === 0 && task.signal == null ? "finished" : "failed",
|
|
403
|
+
toolCallId: null,
|
|
404
|
+
output: typeof task.output === "string" ? tail(task.output) : null,
|
|
405
|
+
exitCode
|
|
406
|
+
})
|
|
407
|
+
];
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
var GROK_NOTICES = {
|
|
411
|
+
"_x.ai/session/interjection": grokInterjection,
|
|
412
|
+
"_x.ai/task_backgrounded": grokTaskStarted,
|
|
413
|
+
"_x.ai/task_completed": grokTaskEnded
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
// src/agents.ts
|
|
417
|
+
function writeAtomically(path, text2, mode = 384) {
|
|
172
418
|
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
173
419
|
const temporary = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}`;
|
|
174
|
-
writeFileSync(temporary,
|
|
420
|
+
writeFileSync(temporary, text2, { mode });
|
|
175
421
|
renameSync(temporary, path);
|
|
176
422
|
}
|
|
177
423
|
function writeTokenHelper(stateDir) {
|
|
@@ -230,6 +476,16 @@ voice_mode = false
|
|
|
230
476
|
trace_upload = false
|
|
231
477
|
mixpanel_enabled = false
|
|
232
478
|
|
|
479
|
+
# A question waits for the person's answer, as a permission request does
|
|
480
|
+
# (by default it gives up after 30 minutes and the agent guesses).
|
|
481
|
+
[toolset.ask_user_question]
|
|
482
|
+
timeout_enabled = false
|
|
483
|
+
|
|
484
|
+
# A message sent while a turn runs goes into that turn at its next gap, not
|
|
485
|
+
# after it (the default queues it): the hub sends one so only to steer.
|
|
486
|
+
[ui]
|
|
487
|
+
follow_up_behavior = "steer"
|
|
488
|
+
|
|
233
489
|
[endpoints]
|
|
234
490
|
cli_chat_proxy_base_url = "http://127.0.0.1:9/v1"
|
|
235
491
|
xai_api_base_url = "http://127.0.0.1:9/v1"
|
|
@@ -279,16 +535,22 @@ var AGENTS = {
|
|
|
279
535
|
capabilities: {
|
|
280
536
|
agent: "grok",
|
|
281
537
|
title: "Grok Build",
|
|
282
|
-
//
|
|
283
|
-
steering: "
|
|
284
|
-
// Started with --always-approve: it acts without asking
|
|
538
|
+
// A second session/prompt goes into the running turn (follow_up_behavior), which a shim reports.
|
|
539
|
+
steering: "native",
|
|
540
|
+
// Started with --always-approve: it acts without asking,
|
|
285
541
|
approvals: false,
|
|
542
|
+
// but it may still ask the person questions, and to approve a plan.
|
|
543
|
+
questions: true,
|
|
544
|
+
planApproval: true,
|
|
286
545
|
plans: true,
|
|
287
|
-
|
|
546
|
+
// Reported by its shims (shims.ts).
|
|
547
|
+
backgroundTasks: true,
|
|
288
548
|
resume: true
|
|
289
549
|
},
|
|
290
550
|
command: "grok",
|
|
291
551
|
args: ["agent", "--always-approve", "stdio"],
|
|
552
|
+
asks: GROK_ASKS,
|
|
553
|
+
notices: GROK_NOTICES,
|
|
292
554
|
prepare({ stateDir, key, tokenFile }) {
|
|
293
555
|
const home2 = join(stateDir, "grok");
|
|
294
556
|
writeAtomically(join(home2, "config.toml"), grokConfig(key, writeTokenHelper(stateDir)));
|
|
@@ -369,6 +631,7 @@ function checkout(home2, appId, env, log2) {
|
|
|
369
631
|
var TIMING = {
|
|
370
632
|
reconnectMinMs: 1e3,
|
|
371
633
|
reconnectMaxMs: 3e4,
|
|
634
|
+
tooFastMs: 1e4,
|
|
372
635
|
pingEveryMs: 3e4,
|
|
373
636
|
pongWithinMs: 1e4,
|
|
374
637
|
touchEveryMs: 6e4,
|
|
@@ -377,7 +640,7 @@ var TIMING = {
|
|
|
377
640
|
idleMs: 30 * 6e4,
|
|
378
641
|
startMs: 12e4
|
|
379
642
|
};
|
|
380
|
-
var
|
|
643
|
+
var UNACKED_LIMIT = 1e4;
|
|
381
644
|
function messageOf(error) {
|
|
382
645
|
return error instanceof Error ? error.message : String(error);
|
|
383
646
|
}
|
|
@@ -392,7 +655,14 @@ var Gateway = class {
|
|
|
392
655
|
#options;
|
|
393
656
|
#timing;
|
|
394
657
|
#sessions = /* @__PURE__ */ new Map();
|
|
395
|
-
|
|
658
|
+
/** The number of the last frame sent; the next gets the one after. */
|
|
659
|
+
#sent = 0;
|
|
660
|
+
/** The frames the hub has not said it has, in order, as sent: sent again on every connection. */
|
|
661
|
+
#unacked = [];
|
|
662
|
+
/** The number of the last of the hub's frames taken. */
|
|
663
|
+
#received = 0;
|
|
664
|
+
/** Agents' output waits while the hub lacks too much. */
|
|
665
|
+
#paused = false;
|
|
396
666
|
#socket = null;
|
|
397
667
|
/** Which connection is current: events of earlier ones are ignored. */
|
|
398
668
|
#generation = 0;
|
|
@@ -445,18 +715,18 @@ var Gateway = class {
|
|
|
445
715
|
opened = true;
|
|
446
716
|
this.#socket = socket;
|
|
447
717
|
log2(`connected to ${hubUrl2}`);
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
});
|
|
718
|
+
socket.send(
|
|
719
|
+
JSON.stringify({
|
|
720
|
+
type: "hello",
|
|
721
|
+
protocol: AGENT_PROTOCOL,
|
|
722
|
+
instance: this.instance,
|
|
723
|
+
version: this.#options.version,
|
|
724
|
+
agents: AGENT_NAMES.map((name) => AGENTS[name].capabilities),
|
|
725
|
+
received: this.#received,
|
|
726
|
+
sent: this.#sent
|
|
727
|
+
})
|
|
728
|
+
);
|
|
729
|
+
for (const { data } of this.#unacked) socket.send(data);
|
|
460
730
|
this.#attempts = 0;
|
|
461
731
|
this.#keepAlive(socket, current);
|
|
462
732
|
});
|
|
@@ -481,7 +751,8 @@ var Gateway = class {
|
|
|
481
751
|
});
|
|
482
752
|
return;
|
|
483
753
|
}
|
|
484
|
-
|
|
754
|
+
const wait = event.code === GATEWAY_TOO_FAST ? this.#timing.tooFastMs : 0;
|
|
755
|
+
this.#lost(socket, `the hub's socket closed (${event.code} ${event.reason})`, opened, wait);
|
|
485
756
|
});
|
|
486
757
|
socket.addEventListener("error", () => {
|
|
487
758
|
if (current()) this.#lost(socket, "the hub's socket failed", opened);
|
|
@@ -520,7 +791,7 @@ var Gateway = class {
|
|
|
520
791
|
* unless it never opened because the hub refuses the token, which no
|
|
521
792
|
* retry mends.
|
|
522
793
|
*/
|
|
523
|
-
#lost(socket, why, opened) {
|
|
794
|
+
#lost(socket, why, opened, waitMs = 0) {
|
|
524
795
|
this.#generation++;
|
|
525
796
|
this.#socket = null;
|
|
526
797
|
if (this.#ping) clearInterval(this.#ping);
|
|
@@ -533,7 +804,7 @@ var Gateway = class {
|
|
|
533
804
|
}
|
|
534
805
|
if (opened) {
|
|
535
806
|
this.#options.log(`${why}; dialing again`);
|
|
536
|
-
this.#retry();
|
|
807
|
+
this.#retry(waitMs);
|
|
537
808
|
return;
|
|
538
809
|
}
|
|
539
810
|
void this.#refusal().then((refusal) => {
|
|
@@ -546,11 +817,14 @@ var Gateway = class {
|
|
|
546
817
|
this.#retry();
|
|
547
818
|
});
|
|
548
819
|
}
|
|
549
|
-
/** Dial again, waiting longer after each failure, with some jitter. */
|
|
550
|
-
#retry() {
|
|
820
|
+
/** Dial again, waiting longer after each failure (`atLeastMs` at least), with some jitter. */
|
|
821
|
+
#retry(atLeastMs = 0) {
|
|
551
822
|
if (this.#stopped || this.#reconnect) return;
|
|
552
823
|
const { reconnectMinMs, reconnectMaxMs } = this.#timing;
|
|
553
|
-
const wait = Math.
|
|
824
|
+
const wait = Math.max(
|
|
825
|
+
atLeastMs,
|
|
826
|
+
Math.min(reconnectMaxMs, reconnectMinMs * 2 ** this.#attempts++)
|
|
827
|
+
);
|
|
554
828
|
this.#reconnect = setTimeout(
|
|
555
829
|
() => {
|
|
556
830
|
this.#reconnect = null;
|
|
@@ -571,17 +845,46 @@ var Gateway = class {
|
|
|
571
845
|
}, this.#timing.pongWithinMs);
|
|
572
846
|
}, this.#timing.pingEveryMs);
|
|
573
847
|
}
|
|
848
|
+
/**
|
|
849
|
+
* Number a frame and send it, now if the hub is there; it is kept until
|
|
850
|
+
* the hub has it. What an agent says is cut to fit MAX_FRAME, which the
|
|
851
|
+
* hub takes no more of (and a socket would not carry much more).
|
|
852
|
+
*/
|
|
574
853
|
#send(frame) {
|
|
575
|
-
if (this.#socket?.readyState === WebSocket.OPEN) {
|
|
576
|
-
this.#socket.send(JSON.stringify(frame));
|
|
577
|
-
return;
|
|
578
|
-
}
|
|
579
854
|
if (this.#stopped) return;
|
|
580
|
-
this.#
|
|
581
|
-
|
|
855
|
+
const n = ++this.#sent;
|
|
856
|
+
let data = JSON.stringify({ ...frame, n });
|
|
857
|
+
if (data.length > MAX_FRAME && "acp" in frame) {
|
|
858
|
+
const room = MAX_FRAME - JSON.stringify({ ...frame, acp: null, n, shrunk: data.length }).length;
|
|
859
|
+
const { message, shrunk } = shrink(frame.acp, room);
|
|
860
|
+
this.#options.log(
|
|
861
|
+
`${frame.session}: cut ${shrunk} characters from what the agent said, to fit a frame`
|
|
862
|
+
);
|
|
863
|
+
data = JSON.stringify({ ...frame, acp: message, n, shrunk });
|
|
864
|
+
} else if (data.length > MAX_FRAME && !("acp" in frame)) {
|
|
865
|
+
const small = frame.type === "opened" ? {
|
|
866
|
+
...frame,
|
|
867
|
+
initialize: { protocolVersion: frame.initialize.protocolVersion },
|
|
868
|
+
setup: {}
|
|
869
|
+
} : { ...frame, message: frame.message.slice(0, 2e3) };
|
|
870
|
+
data = JSON.stringify({ ...small, n });
|
|
871
|
+
}
|
|
872
|
+
this.#unacked.push({ n, data });
|
|
873
|
+
if (this.#socket?.readyState === WebSocket.OPEN) this.#socket.send(data);
|
|
874
|
+
if (!this.#paused && this.#unacked.length >= UNACKED_LIMIT) {
|
|
875
|
+
this.#paused = true;
|
|
582
876
|
for (const session of this.#sessions.values()) session.process?.pause();
|
|
583
877
|
}
|
|
584
878
|
}
|
|
879
|
+
/** The hub has every frame up to `n`: they are not kept any more. */
|
|
880
|
+
#taken(n) {
|
|
881
|
+
const kept = this.#unacked.findIndex((frame) => frame.n > n);
|
|
882
|
+
this.#unacked = kept < 0 ? [] : this.#unacked.slice(kept);
|
|
883
|
+
if (this.#paused && this.#unacked.length < UNACKED_LIMIT / 2) {
|
|
884
|
+
this.#paused = false;
|
|
885
|
+
for (const session of this.#sessions.values()) session.process?.resume();
|
|
886
|
+
}
|
|
887
|
+
}
|
|
585
888
|
#receive(data) {
|
|
586
889
|
let frame;
|
|
587
890
|
try {
|
|
@@ -590,17 +893,22 @@ var Gateway = class {
|
|
|
590
893
|
this.#options.log(`the hub sent something that is not JSON: ${data.slice(0, 200)}`);
|
|
591
894
|
return;
|
|
592
895
|
}
|
|
593
|
-
if ("
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
896
|
+
if ("type" in frame && frame.type === "received") {
|
|
897
|
+
this.#taken(frame.n);
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
if (typeof frame.n !== "number") {
|
|
901
|
+
this.#options.log(`the hub sent a frame without a number: ${data.slice(0, 200)}`);
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
if (frame.n > this.#received) {
|
|
905
|
+
this.#received = frame.n;
|
|
906
|
+
if ("acp" in frame) this.#relay(frame.session, frame.acp);
|
|
907
|
+
else if (frame.type === "open") void this.#open(frame);
|
|
908
|
+
else if (frame.type === "close") this.#close(frame.session);
|
|
909
|
+
else if (frame.type === "steer") this.#steer(frame);
|
|
910
|
+
}
|
|
911
|
+
this.#socket?.send(JSON.stringify({ type: "received", n: this.#received }));
|
|
604
912
|
}
|
|
605
913
|
// -------------------------------------------------------------------------
|
|
606
914
|
// Sessions
|
|
@@ -656,7 +964,9 @@ var Gateway = class {
|
|
|
656
964
|
onMessage: (message) => this.#fromAgent(session, message),
|
|
657
965
|
// Before it says it runs, an agent that exits has failed to start.
|
|
658
966
|
onExit: (message) => this.#end(session, message, session.opened ? "closed" : "failed"),
|
|
659
|
-
log: (line) => log2(`${id}: ${line}`)
|
|
967
|
+
log: (line) => log2(`${id}: ${line}`),
|
|
968
|
+
asks: definition.asks,
|
|
969
|
+
notices: definition.notices
|
|
660
970
|
});
|
|
661
971
|
session.process = child;
|
|
662
972
|
const initialize = await child.request(
|
|
@@ -753,19 +1063,39 @@ var Gateway = class {
|
|
|
753
1063
|
this.#idle(session);
|
|
754
1064
|
this.#touch();
|
|
755
1065
|
}
|
|
1066
|
+
/**
|
|
1067
|
+
* A message for the session's running turn: the agent takes it in, or
|
|
1068
|
+
* runs it next; one whose agent does not run is answered with an error.
|
|
1069
|
+
*/
|
|
1070
|
+
#steer(frame) {
|
|
1071
|
+
const session = this.#sessions.get(frame.session);
|
|
1072
|
+
const child = session?.process;
|
|
1073
|
+
if (!session || !child?.running || session.opened === null || !session.acpSessionId) {
|
|
1074
|
+
const error = { code: -32e3, message: "The session's agent is not running" };
|
|
1075
|
+
this.#send({ session: frame.session, acp: { jsonrpc: "2.0", id: frame.request, error } });
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
child.steer(frame.request, { sessionId: session.acpSessionId, prompt: frame.prompt });
|
|
1079
|
+
this.#idle(session);
|
|
1080
|
+
this.#touch();
|
|
1081
|
+
}
|
|
756
1082
|
/** The agent's message for the hub. */
|
|
757
1083
|
#fromAgent(session, message) {
|
|
758
1084
|
this.#send({ session: session.session, acp: message });
|
|
759
|
-
if (isAcpResponse(message)) {
|
|
1085
|
+
if (isAcpResponse(message) || "method" in message && message.method === NOTICE.task) {
|
|
760
1086
|
this.#idle(session);
|
|
761
1087
|
this.#touch();
|
|
762
1088
|
}
|
|
763
1089
|
}
|
|
764
|
-
/**
|
|
1090
|
+
/** Whether the session's agent works: on a turn, or on a background task. */
|
|
1091
|
+
#working(session) {
|
|
1092
|
+
return (session.process?.prompts.length ?? 0) > 0 || (session.process?.tasks ?? 0) > 0;
|
|
1093
|
+
}
|
|
1094
|
+
/** An agent with no turn running, and no background task, stops after a while. */
|
|
765
1095
|
#idle(session) {
|
|
766
1096
|
if (session.idle) clearTimeout(session.idle);
|
|
767
1097
|
session.idle = null;
|
|
768
|
-
if (session.closed || (session
|
|
1098
|
+
if (session.closed || this.#working(session)) return;
|
|
769
1099
|
const { idleMs } = this.#timing;
|
|
770
1100
|
session.idle = setTimeout(
|
|
771
1101
|
() => this.#end(session, `no turn for ${Math.round(idleMs / 6e4)} min; the next resumes it`),
|
|
@@ -798,9 +1128,9 @@ var Gateway = class {
|
|
|
798
1128
|
};
|
|
799
1129
|
schedule(key.expiresAt - refreshBeforeMs - Date.now());
|
|
800
1130
|
}
|
|
801
|
-
/** Touch the sandbox while any turn
|
|
1131
|
+
/** Touch the sandbox while any agent works (a turn, a background task): at once, then every touchEveryMs. */
|
|
802
1132
|
#touch() {
|
|
803
|
-
const running = [...this.#sessions.values()].some((
|
|
1133
|
+
const running = [...this.#sessions.values()].some((session) => this.#working(session));
|
|
804
1134
|
if (!running) {
|
|
805
1135
|
if (this.#touching) clearInterval(this.#touching);
|
|
806
1136
|
this.#touching = null;
|
|
@@ -870,15 +1200,15 @@ var Platform = class {
|
|
|
870
1200
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
871
1201
|
signal: AbortSignal.timeout(3e4)
|
|
872
1202
|
});
|
|
873
|
-
const
|
|
1203
|
+
const text2 = await response.text();
|
|
874
1204
|
if (!response.ok) {
|
|
875
|
-
throw new Error(`Teable answered ${response.status} to ${path}: ${
|
|
1205
|
+
throw new Error(`Teable answered ${response.status} to ${path}: ${text2.slice(0, 300)}`);
|
|
876
1206
|
}
|
|
877
|
-
if (
|
|
1207
|
+
if (text2.trim() === "") return void 0;
|
|
878
1208
|
try {
|
|
879
|
-
return JSON.parse(
|
|
1209
|
+
return JSON.parse(text2);
|
|
880
1210
|
} catch {
|
|
881
|
-
throw new Error(`Teable's answer to ${path} is not JSON: ${
|
|
1211
|
+
throw new Error(`Teable's answer to ${path} is not JSON: ${text2.slice(0, 300)}`);
|
|
882
1212
|
}
|
|
883
1213
|
}
|
|
884
1214
|
};
|
package/dist/gateway.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { Platform } from "./platform.js";
|
|
|
3
3
|
interface Timing {
|
|
4
4
|
reconnectMinMs: number;
|
|
5
5
|
reconnectMaxMs: number;
|
|
6
|
+
/** How long to wait at least before dialing again when the hub said the gateway sent too fast. */
|
|
7
|
+
tooFastMs: number;
|
|
6
8
|
/** How often the gateway checks the socket is alive, and how long it waits for the answer. */
|
|
7
9
|
pingEveryMs: number;
|
|
8
10
|
pongWithinMs: number;
|