@teable/agent-gateway 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +38 -2
- package/dist/agent.d.ts +33 -0
- package/dist/agents.d.ts +24 -0
- package/dist/checkout.d.ts +13 -0
- package/dist/chunks/CYVXAHGU.js +47 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1094 -0
- package/dist/gateway.d.ts +53 -0
- package/dist/platform.d.ts +35 -0
- package/dist/protocol.d.ts +637 -0
- package/dist/protocol.js +28 -0
- package/dist/shims.d.ts +20 -0
- package/package.json +30 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1094 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
ACP,
|
|
4
|
+
AGENT_NAMES,
|
|
5
|
+
AGENT_PROTOCOL,
|
|
6
|
+
ASK,
|
|
7
|
+
GATEWAY_CLOSE,
|
|
8
|
+
PING,
|
|
9
|
+
PONG,
|
|
10
|
+
SESSION_ID,
|
|
11
|
+
isAcpNotification,
|
|
12
|
+
isAcpRequest,
|
|
13
|
+
isAcpResponse
|
|
14
|
+
} from "./chunks/CYVXAHGU.js";
|
|
15
|
+
|
|
16
|
+
// src/cli.ts
|
|
17
|
+
import { readFileSync } from "node:fs";
|
|
18
|
+
import { homedir } from "node:os";
|
|
19
|
+
import { join as join4 } from "node:path";
|
|
20
|
+
|
|
21
|
+
// src/gateway.ts
|
|
22
|
+
import { randomUUID } from "node:crypto";
|
|
23
|
+
import { rmSync } from "node:fs";
|
|
24
|
+
import { join as join3 } from "node:path";
|
|
25
|
+
|
|
26
|
+
// src/agent.ts
|
|
27
|
+
import { spawn } from "node:child_process";
|
|
28
|
+
import { createInterface } from "node:readline";
|
|
29
|
+
var METHOD_NOT_FOUND = -32601;
|
|
30
|
+
var INVALID_PARAMS = -32602;
|
|
31
|
+
var STDERR_LINES = 20;
|
|
32
|
+
var AgentProcess = class {
|
|
33
|
+
#child;
|
|
34
|
+
#start;
|
|
35
|
+
#pending = /* @__PURE__ */ new Map();
|
|
36
|
+
/** The hub's `session/prompt` requests the agent has not answered. */
|
|
37
|
+
#prompts = /* @__PURE__ */ new Set();
|
|
38
|
+
/** The agent's requests that ask the person, relayed by a shim, until the hub answers them. */
|
|
39
|
+
#asked = /* @__PURE__ */ new Map();
|
|
40
|
+
#stderr = [];
|
|
41
|
+
#nextId = 1;
|
|
42
|
+
#loading = false;
|
|
43
|
+
#exited = false;
|
|
44
|
+
constructor(start) {
|
|
45
|
+
this.#start = start;
|
|
46
|
+
this.#child = spawn(start.command, start.args, {
|
|
47
|
+
cwd: start.cwd,
|
|
48
|
+
env: start.env,
|
|
49
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
50
|
+
});
|
|
51
|
+
const child = this.#child;
|
|
52
|
+
createInterface({ input: child.stdout }).on(
|
|
53
|
+
"line",
|
|
54
|
+
(line) => this.#receive(line)
|
|
55
|
+
);
|
|
56
|
+
createInterface({ input: child.stderr }).on("line", (line) => {
|
|
57
|
+
this.#stderr.push(line);
|
|
58
|
+
if (this.#stderr.length > STDERR_LINES) this.#stderr.shift();
|
|
59
|
+
});
|
|
60
|
+
child.stdin?.on("error", () => {
|
|
61
|
+
});
|
|
62
|
+
child.on("error", (error) => this.#exit(`could not start ${start.command}: ${error.message}`));
|
|
63
|
+
child.on("exit", (code, signal) => {
|
|
64
|
+
const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
|
|
65
|
+
const said = this.#stderr.length > 0 ? `; it said: ${this.#stderr.join("\n")}` : "";
|
|
66
|
+
this.#exit(`the agent ${how}${said}`);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
get running() {
|
|
70
|
+
return !this.#exited;
|
|
71
|
+
}
|
|
72
|
+
/** The hub's prompts the agent is working on. */
|
|
73
|
+
get prompts() {
|
|
74
|
+
return [...this.#prompts];
|
|
75
|
+
}
|
|
76
|
+
/** A request of the gateway's own; rejects with the agent's error, or when it takes too long. */
|
|
77
|
+
request(method, params, timeoutMs) {
|
|
78
|
+
const id = `gateway:${this.#nextId++}`;
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
const timer = setTimeout(() => {
|
|
81
|
+
this.#pending.delete(id);
|
|
82
|
+
reject(new Error(`the agent did not answer ${method} within ${timeoutMs / 1e3} s`));
|
|
83
|
+
}, timeoutMs);
|
|
84
|
+
this.#pending.set(id, {
|
|
85
|
+
resolve: (result) => {
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
resolve(result);
|
|
88
|
+
},
|
|
89
|
+
reject: (error) => {
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
reject(error);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
this.#write({ jsonrpc: "2.0", id, method, params });
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** A request whose replayed updates the hub must not see again: `session/load`. */
|
|
98
|
+
async load(params, timeoutMs) {
|
|
99
|
+
this.#loading = true;
|
|
100
|
+
try {
|
|
101
|
+
return await this.request(ACP.loadSession, params, timeoutMs);
|
|
102
|
+
} finally {
|
|
103
|
+
this.#loading = false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Relay the hub's message to the agent: unchanged, but an answer to what a shim asked, in the agent's words. */
|
|
107
|
+
send(message) {
|
|
108
|
+
if (isAcpRequest(message) && message.method === ACP.prompt) this.#prompts.add(message.id);
|
|
109
|
+
const asked = isAcpResponse(message) ? this.#asked.get(message.id) : void 0;
|
|
110
|
+
if (asked && isAcpResponse(message)) {
|
|
111
|
+
this.#asked.delete(message.id);
|
|
112
|
+
if (message.error === void 0) {
|
|
113
|
+
this.#write(this.#answer(message.id, asked, message.result));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
this.#write(message);
|
|
118
|
+
}
|
|
119
|
+
/** The hub's answer to what a shim asked, in the agent's words. */
|
|
120
|
+
#answer(id, asked, answer) {
|
|
121
|
+
try {
|
|
122
|
+
return { jsonrpc: "2.0", id, result: asked.shim.result(answer, asked.params) };
|
|
123
|
+
} catch (error) {
|
|
124
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
125
|
+
this.#start.log(`the hub's answer to ${asked.shim.method} could not be given: ${why}`);
|
|
126
|
+
return { jsonrpc: "2.0", id, error: { code: INVALID_PARAMS, message: why } };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/** Stop reading what the agent says (its writes then wait), and read on. */
|
|
130
|
+
pause() {
|
|
131
|
+
this.#child.stdout?.pause();
|
|
132
|
+
}
|
|
133
|
+
resume() {
|
|
134
|
+
this.#child.stdout?.resume();
|
|
135
|
+
}
|
|
136
|
+
kill() {
|
|
137
|
+
if (this.#exited) return;
|
|
138
|
+
this.#child.kill("SIGTERM");
|
|
139
|
+
setTimeout(() => {
|
|
140
|
+
if (!this.#exited) this.#child.kill("SIGKILL");
|
|
141
|
+
}, 5e3).unref();
|
|
142
|
+
}
|
|
143
|
+
#write(message) {
|
|
144
|
+
if (this.#exited) return;
|
|
145
|
+
this.#child.stdin?.write(`${JSON.stringify(message)}
|
|
146
|
+
`);
|
|
147
|
+
}
|
|
148
|
+
#receive(line) {
|
|
149
|
+
if (line.trim() === "") return;
|
|
150
|
+
let message;
|
|
151
|
+
try {
|
|
152
|
+
message = JSON.parse(line);
|
|
153
|
+
} catch {
|
|
154
|
+
this.#start.log(`the agent wrote a line that is not JSON: ${line.slice(0, 200)}`);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (typeof message !== "object" || message === null || message.jsonrpc !== "2.0") {
|
|
158
|
+
this.#start.log(`the agent wrote something that is not JSON-RPC: ${line.slice(0, 200)}`);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (isAcpResponse(message)) {
|
|
162
|
+
const pending = this.#pending.get(message.id);
|
|
163
|
+
if (pending) {
|
|
164
|
+
this.#pending.delete(message.id);
|
|
165
|
+
if (message.error) pending.reject(new Error(message.error.message));
|
|
166
|
+
else pending.resolve(message.result);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
this.#prompts.delete(message.id);
|
|
170
|
+
} else if (message.method.startsWith("_")) {
|
|
171
|
+
if (isAcpRequest(message)) this.#vendorRequest(message);
|
|
172
|
+
return;
|
|
173
|
+
} else if (this.#loading && isAcpNotification(message) && message.method === ACP.update) {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
this.#start.onMessage(message);
|
|
177
|
+
}
|
|
178
|
+
/** A vendor request: what the agent asks the person goes to the hub as the protocol's; the rest is unknown. */
|
|
179
|
+
#vendorRequest(message) {
|
|
180
|
+
const shim = this.#start.asks?.[message.method];
|
|
181
|
+
if (!shim) {
|
|
182
|
+
const error = { code: METHOD_NOT_FOUND, message: `${message.method} is not supported` };
|
|
183
|
+
this.#write({ jsonrpc: "2.0", id: message.id, error });
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
let params;
|
|
187
|
+
try {
|
|
188
|
+
params = shim.request(message.params);
|
|
189
|
+
} catch (error) {
|
|
190
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
191
|
+
this.#start.log(`the agent's ${message.method} could not be read: ${why}`);
|
|
192
|
+
this.#write({
|
|
193
|
+
jsonrpc: "2.0",
|
|
194
|
+
id: message.id,
|
|
195
|
+
error: { code: INVALID_PARAMS, message: `${message.method}: ${why}` }
|
|
196
|
+
});
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
this.#asked.set(message.id, { shim, params: message.params });
|
|
200
|
+
this.#start.onMessage({ jsonrpc: "2.0", id: message.id, method: shim.method, params });
|
|
201
|
+
}
|
|
202
|
+
#exit(message) {
|
|
203
|
+
if (this.#exited) return;
|
|
204
|
+
this.#exited = true;
|
|
205
|
+
for (const { reject } of this.#pending.values()) reject(new Error(message));
|
|
206
|
+
this.#pending.clear();
|
|
207
|
+
this.#start.onExit(message);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
// src/agents.ts
|
|
212
|
+
import { chmodSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
213
|
+
import { dirname, join } from "node:path";
|
|
214
|
+
|
|
215
|
+
// src/shims.ts
|
|
216
|
+
function fields(value, what) {
|
|
217
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
218
|
+
throw new Error(`${what} is not an object`);
|
|
219
|
+
}
|
|
220
|
+
return value;
|
|
221
|
+
}
|
|
222
|
+
function text(value, what) {
|
|
223
|
+
if (typeof value !== "string") throw new Error(`${what} is not a string`);
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
var textOrNull = (value) => typeof value === "string" ? value : null;
|
|
227
|
+
function list(value, what) {
|
|
228
|
+
if (!Array.isArray(value)) throw new Error(`${what} is not a list`);
|
|
229
|
+
return value;
|
|
230
|
+
}
|
|
231
|
+
var grokQuestions = {
|
|
232
|
+
method: ASK.question,
|
|
233
|
+
request(params) {
|
|
234
|
+
const asked = fields(params, "ask_user_question's params");
|
|
235
|
+
const questions = list(asked.questions, "questions").map((value, index) => {
|
|
236
|
+
const question = fields(value, `question ${index}`);
|
|
237
|
+
return {
|
|
238
|
+
question: text(question.question, `question ${index}'s text`),
|
|
239
|
+
options: list(question.options, `question ${index}'s options`).map((option, at) => {
|
|
240
|
+
const choice = fields(option, `question ${index}'s option ${at}`);
|
|
241
|
+
return {
|
|
242
|
+
label: text(choice.label, `question ${index}'s option ${at}'s label`),
|
|
243
|
+
description: textOrNull(choice.description),
|
|
244
|
+
preview: textOrNull(choice.preview)
|
|
245
|
+
};
|
|
246
|
+
}),
|
|
247
|
+
multiSelect: question.multiSelect === true,
|
|
248
|
+
freeText: true
|
|
249
|
+
};
|
|
250
|
+
});
|
|
251
|
+
return {
|
|
252
|
+
sessionId: text(asked.sessionId, "sessionId"),
|
|
253
|
+
toolCallId: textOrNull(asked.toolCallId),
|
|
254
|
+
questions
|
|
255
|
+
};
|
|
256
|
+
},
|
|
257
|
+
result(answer, params) {
|
|
258
|
+
const given = fields(answer, "the answer");
|
|
259
|
+
if (given.outcome !== "answered") return { outcome: "cancelled" };
|
|
260
|
+
const questions = list(fields(params, "the params").questions, "questions");
|
|
261
|
+
const answers = list(given.answers, "answers");
|
|
262
|
+
return {
|
|
263
|
+
outcome: "accepted",
|
|
264
|
+
answers: Object.fromEntries(
|
|
265
|
+
questions.map((value, index) => {
|
|
266
|
+
const { picked, text: own } = fields(answers[index] ?? {}, `answer ${index}`);
|
|
267
|
+
const words = [...Array.isArray(picked) ? picked : [], ...own ? [own] : []];
|
|
268
|
+
return [
|
|
269
|
+
text(fields(value, `question ${index}`).question, "a question"),
|
|
270
|
+
words.join(", ")
|
|
271
|
+
];
|
|
272
|
+
})
|
|
273
|
+
),
|
|
274
|
+
annotations: {}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
var grokPlan = {
|
|
279
|
+
method: ASK.plan,
|
|
280
|
+
request(params) {
|
|
281
|
+
const asked = fields(params, "exit_plan_mode's params");
|
|
282
|
+
return {
|
|
283
|
+
sessionId: text(asked.sessionId, "sessionId"),
|
|
284
|
+
toolCallId: textOrNull(asked.toolCallId),
|
|
285
|
+
plan: typeof asked.planContent === "string" ? asked.planContent : ""
|
|
286
|
+
};
|
|
287
|
+
},
|
|
288
|
+
result(answer) {
|
|
289
|
+
const given = fields(answer, "the answer");
|
|
290
|
+
if (given.outcome === "approved") return { outcome: "approved" };
|
|
291
|
+
if (given.outcome !== "rejected") return { outcome: "cancelled" };
|
|
292
|
+
const feedback = textOrNull(given.feedback);
|
|
293
|
+
return { outcome: "requested_changes", ...feedback ? { feedback } : {} };
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
var GROK_ASKS = {
|
|
297
|
+
"_x.ai/ask_user_question": grokQuestions,
|
|
298
|
+
"_x.ai/exit_plan_mode": grokPlan
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
// src/agents.ts
|
|
302
|
+
function writeAtomically(path, text2, mode = 384) {
|
|
303
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
304
|
+
const temporary = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}`;
|
|
305
|
+
writeFileSync(temporary, text2, { mode });
|
|
306
|
+
renameSync(temporary, path);
|
|
307
|
+
}
|
|
308
|
+
function writeTokenHelper(stateDir) {
|
|
309
|
+
const helper = join(stateDir, "bin", "model-token");
|
|
310
|
+
writeAtomically(helper, '#!/bin/sh\nexec cat "$TEABLE_MODEL_TOKEN_FILE"\n', 493);
|
|
311
|
+
chmodSync(helper, 493);
|
|
312
|
+
return helper;
|
|
313
|
+
}
|
|
314
|
+
var toml = (value) => JSON.stringify(value);
|
|
315
|
+
function grokConfig(key, helper) {
|
|
316
|
+
return `# Written by @teable/agent-gateway whenever it starts a session's agent.
|
|
317
|
+
disable_web_search = true
|
|
318
|
+
|
|
319
|
+
[cli]
|
|
320
|
+
auto_update = false
|
|
321
|
+
show_tips = false
|
|
322
|
+
|
|
323
|
+
[models]
|
|
324
|
+
default = "teable"
|
|
325
|
+
session_summary = "teable"
|
|
326
|
+
image_description = "teable"
|
|
327
|
+
disabled_models = ["grok-4.6", "grok-4.5"]
|
|
328
|
+
max_retries = 4
|
|
329
|
+
default_reasoning_effort = "medium"
|
|
330
|
+
|
|
331
|
+
[model.teable]
|
|
332
|
+
model = ${toml(key.model)}
|
|
333
|
+
base_url = ${toml(key.openaiBaseUrl)}
|
|
334
|
+
name = "Teable AI"
|
|
335
|
+
auth_provider = "teable"
|
|
336
|
+
api_backend = "responses"
|
|
337
|
+
reasoning_summary = "concise"
|
|
338
|
+
reasoning_efforts = [{ value = "low" }, { value = "medium" }, { value = "high" }]
|
|
339
|
+
|
|
340
|
+
# Asked before every request: the gateway replaces the token before it expires.
|
|
341
|
+
[auth_provider.teable]
|
|
342
|
+
command = ${toml(helper)}
|
|
343
|
+
token_ttl_secs = 1
|
|
344
|
+
|
|
345
|
+
[features]
|
|
346
|
+
telemetry = false
|
|
347
|
+
remote_fetch = false
|
|
348
|
+
managed_config = false
|
|
349
|
+
campaigns = false
|
|
350
|
+
feedback = false
|
|
351
|
+
backend_tools = false
|
|
352
|
+
image_gen = false
|
|
353
|
+
video_gen = false
|
|
354
|
+
web_fetch = false
|
|
355
|
+
turn_summary = false
|
|
356
|
+
session_recap = false
|
|
357
|
+
codebase_indexing = false
|
|
358
|
+
voice_mode = false
|
|
359
|
+
|
|
360
|
+
[telemetry]
|
|
361
|
+
trace_upload = false
|
|
362
|
+
mixpanel_enabled = false
|
|
363
|
+
|
|
364
|
+
# A question waits for the person's answer, as a permission request does
|
|
365
|
+
# (by default it gives up after 30 minutes and the agent guesses).
|
|
366
|
+
[toolset.ask_user_question]
|
|
367
|
+
timeout_enabled = false
|
|
368
|
+
|
|
369
|
+
[endpoints]
|
|
370
|
+
cli_chat_proxy_base_url = "http://127.0.0.1:9/v1"
|
|
371
|
+
xai_api_base_url = "http://127.0.0.1:9/v1"
|
|
372
|
+
feedback_base_url = "http://127.0.0.1:9/v1"
|
|
373
|
+
trace_upload_url = "http://127.0.0.1:9/v1"
|
|
374
|
+
managed_config_url = "http://127.0.0.1:9/v1"
|
|
375
|
+
|
|
376
|
+
[managed_mcps]
|
|
377
|
+
enabled = false
|
|
378
|
+
|
|
379
|
+
[memory]
|
|
380
|
+
enabled = false
|
|
381
|
+
|
|
382
|
+
[relay]
|
|
383
|
+
enabled = false
|
|
384
|
+
|
|
385
|
+
[harness]
|
|
386
|
+
disable_workspace_teleport = true
|
|
387
|
+
|
|
388
|
+
[sandbox]
|
|
389
|
+
profile = "off"
|
|
390
|
+
|
|
391
|
+
[compat.claude]
|
|
392
|
+
skills = false
|
|
393
|
+
rules = false
|
|
394
|
+
agents = false
|
|
395
|
+
mcps = false
|
|
396
|
+
hooks = false
|
|
397
|
+
sessions = false
|
|
398
|
+
|
|
399
|
+
[compat.cursor]
|
|
400
|
+
skills = false
|
|
401
|
+
rules = false
|
|
402
|
+
agents = false
|
|
403
|
+
mcps = false
|
|
404
|
+
hooks = false
|
|
405
|
+
sessions = false
|
|
406
|
+
|
|
407
|
+
[compat.codex]
|
|
408
|
+
hooks = false
|
|
409
|
+
skills = false
|
|
410
|
+
sessions = false
|
|
411
|
+
`;
|
|
412
|
+
}
|
|
413
|
+
var AGENTS = {
|
|
414
|
+
grok: {
|
|
415
|
+
capabilities: {
|
|
416
|
+
agent: "grok",
|
|
417
|
+
title: "Grok Build",
|
|
418
|
+
// Its own steering is a vendor extension; until a shim speaks it, the hub interrupts.
|
|
419
|
+
steering: "interrupt",
|
|
420
|
+
// Started with --always-approve: it acts without asking,
|
|
421
|
+
approvals: false,
|
|
422
|
+
// but it may still ask the person questions, and to approve a plan.
|
|
423
|
+
questions: true,
|
|
424
|
+
planApproval: true,
|
|
425
|
+
plans: true,
|
|
426
|
+
backgroundTasks: false,
|
|
427
|
+
resume: true
|
|
428
|
+
},
|
|
429
|
+
command: "grok",
|
|
430
|
+
args: ["agent", "--always-approve", "stdio"],
|
|
431
|
+
asks: GROK_ASKS,
|
|
432
|
+
prepare({ stateDir, key, tokenFile }) {
|
|
433
|
+
const home2 = join(stateDir, "grok");
|
|
434
|
+
writeAtomically(join(home2, "config.toml"), grokConfig(key, writeTokenHelper(stateDir)));
|
|
435
|
+
return {
|
|
436
|
+
// Its config and its sessions, which session/load reads after a restart.
|
|
437
|
+
GROK_HOME: home2,
|
|
438
|
+
GROK_DISABLE_AUTOUPDATER: "1",
|
|
439
|
+
TEABLE_MODEL_TOKEN_FILE: tokenFile
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
// src/checkout.ts
|
|
446
|
+
import { execFile } from "node:child_process";
|
|
447
|
+
import { existsSync, mkdirSync as mkdirSync2 } from "node:fs";
|
|
448
|
+
import { join as join2 } from "node:path";
|
|
449
|
+
var APP_DIRECTORY = /^[A-Za-z0-9_-]+$/;
|
|
450
|
+
var CLONE_TIMEOUT_MS = 5 * 6e4;
|
|
451
|
+
function cliMissing(appId) {
|
|
452
|
+
return [
|
|
453
|
+
`[Teable] You work in a person's Teable sandbox, on the Teable app ${appId}, in this directory.`,
|
|
454
|
+
"The teable-next CLI is not installed here, so the directory was created empty instead of",
|
|
455
|
+
"checked out. Run the CLI with `npx -y @teable/next-cli` (or install it with",
|
|
456
|
+
`\`npm install -g @teable/next-cli\`): \`clone ${appId} .\` checks the app out here, and`,
|
|
457
|
+
"`--help` lists the rest, publishing included."
|
|
458
|
+
].join(" ");
|
|
459
|
+
}
|
|
460
|
+
function cloneFailed(appId, output) {
|
|
461
|
+
return [
|
|
462
|
+
`[Teable] You work in a person's Teable sandbox, on the Teable app ${appId}, in this directory.`,
|
|
463
|
+
`Checking it out with \`teable-next clone ${appId}\` failed, so the directory may be empty.`,
|
|
464
|
+
`Try \`teable-next clone ${appId} .\` again, or tell the person what went wrong. It said:`,
|
|
465
|
+
output.trim().slice(-2e3) || "(nothing)"
|
|
466
|
+
].join(" ");
|
|
467
|
+
}
|
|
468
|
+
function clone(appId, dir, env) {
|
|
469
|
+
return new Promise((resolve) => {
|
|
470
|
+
execFile(
|
|
471
|
+
"teable-next",
|
|
472
|
+
["clone", appId, dir],
|
|
473
|
+
{ env, timeout: CLONE_TIMEOUT_MS, maxBuffer: 16 << 20 },
|
|
474
|
+
(error, stdout, stderr) => {
|
|
475
|
+
if (error === null) resolve(null);
|
|
476
|
+
else if (error.code === "ENOENT") resolve("missing");
|
|
477
|
+
else resolve(`${stdout}${stderr}`.trim() || error.message);
|
|
478
|
+
}
|
|
479
|
+
);
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
var cloning = /* @__PURE__ */ new Map();
|
|
483
|
+
function checkout(home2, appId, env, log2) {
|
|
484
|
+
if (!APP_DIRECTORY.test(appId)) {
|
|
485
|
+
return Promise.reject(new Error(`"${appId}" is not an app id`));
|
|
486
|
+
}
|
|
487
|
+
const cwd = join2(home2, "apps", appId);
|
|
488
|
+
if (existsSync(cwd)) return Promise.resolve({ cwd, rules: null });
|
|
489
|
+
const running = cloning.get(cwd);
|
|
490
|
+
if (running) return running;
|
|
491
|
+
const made = (async () => {
|
|
492
|
+
mkdirSync2(join2(home2, "apps"), { recursive: true });
|
|
493
|
+
log2(`cloning ${appId} into ${cwd}`);
|
|
494
|
+
const failed = await clone(appId, cwd, env);
|
|
495
|
+
if (failed === null && existsSync(cwd)) return { cwd, rules: null };
|
|
496
|
+
mkdirSync2(cwd, { recursive: true });
|
|
497
|
+
if (failed === "missing") {
|
|
498
|
+
log2(`teable-next is not installed: ${cwd} starts empty`);
|
|
499
|
+
return { cwd, rules: cliMissing(appId) };
|
|
500
|
+
}
|
|
501
|
+
log2(`teable-next clone ${appId} failed: ${failed}`);
|
|
502
|
+
return { cwd, rules: cloneFailed(appId, failed ?? "it made no directory") };
|
|
503
|
+
})();
|
|
504
|
+
cloning.set(cwd, made);
|
|
505
|
+
return made.finally(() => cloning.delete(cwd));
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// src/gateway.ts
|
|
509
|
+
var TIMING = {
|
|
510
|
+
reconnectMinMs: 1e3,
|
|
511
|
+
reconnectMaxMs: 3e4,
|
|
512
|
+
pingEveryMs: 3e4,
|
|
513
|
+
pongWithinMs: 1e4,
|
|
514
|
+
touchEveryMs: 6e4,
|
|
515
|
+
refreshBeforeMs: 5 * 6e4,
|
|
516
|
+
refreshRetryMs: 3e4,
|
|
517
|
+
idleMs: 30 * 6e4,
|
|
518
|
+
startMs: 12e4
|
|
519
|
+
};
|
|
520
|
+
var OUTBOX_LIMIT = 1e4;
|
|
521
|
+
function messageOf(error) {
|
|
522
|
+
return error instanceof Error ? error.message : String(error);
|
|
523
|
+
}
|
|
524
|
+
function withRules(message, rules) {
|
|
525
|
+
if (!isAcpRequest(message)) return message;
|
|
526
|
+
const params = message.params;
|
|
527
|
+
const prompt = [{ type: "text", text: rules }, ...params.prompt ?? []];
|
|
528
|
+
return { ...message, params: { ...params, prompt } };
|
|
529
|
+
}
|
|
530
|
+
var Gateway = class {
|
|
531
|
+
instance = randomUUID();
|
|
532
|
+
#options;
|
|
533
|
+
#timing;
|
|
534
|
+
#sessions = /* @__PURE__ */ new Map();
|
|
535
|
+
#outbox = [];
|
|
536
|
+
#socket = null;
|
|
537
|
+
/** Which connection is current: events of earlier ones are ignored. */
|
|
538
|
+
#generation = 0;
|
|
539
|
+
#attempts = 0;
|
|
540
|
+
#reconnect = null;
|
|
541
|
+
#ping = null;
|
|
542
|
+
#pong = null;
|
|
543
|
+
#touching = null;
|
|
544
|
+
#lastTouch = 0;
|
|
545
|
+
#stopped = false;
|
|
546
|
+
constructor(options) {
|
|
547
|
+
this.#options = options;
|
|
548
|
+
this.#timing = { ...TIMING, ...options.timing };
|
|
549
|
+
}
|
|
550
|
+
start() {
|
|
551
|
+
rmSync(join3(this.#options.stateDir, "sessions"), { recursive: true, force: true });
|
|
552
|
+
this.#connect();
|
|
553
|
+
}
|
|
554
|
+
/** Stop: the socket, every agent, every timer. */
|
|
555
|
+
stop() {
|
|
556
|
+
if (this.#stopped) return;
|
|
557
|
+
this.#stopped = true;
|
|
558
|
+
for (const timer of [this.#reconnect, this.#pong, this.#ping, this.#touching]) {
|
|
559
|
+
if (timer) clearTimeout(timer);
|
|
560
|
+
}
|
|
561
|
+
this.#generation++;
|
|
562
|
+
this.#socket?.close(1e3, "The gateway stopped");
|
|
563
|
+
this.#socket = null;
|
|
564
|
+
for (const session of this.#sessions.values()) this.#end(session, "the gateway stopped");
|
|
565
|
+
}
|
|
566
|
+
// -------------------------------------------------------------------------
|
|
567
|
+
// The hub's socket
|
|
568
|
+
// -------------------------------------------------------------------------
|
|
569
|
+
#connect() {
|
|
570
|
+
if (this.#stopped) return;
|
|
571
|
+
const generation = ++this.#generation;
|
|
572
|
+
const { hubUrl: hubUrl2, token: token2, log: log2 } = this.#options;
|
|
573
|
+
let socket;
|
|
574
|
+
try {
|
|
575
|
+
socket = new WebSocket(hubUrl2, { headers: { Authorization: `Bearer ${token2}` } });
|
|
576
|
+
} catch (error) {
|
|
577
|
+
log2(`cannot dial ${hubUrl2}: ${messageOf(error)}`);
|
|
578
|
+
this.#retry();
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
const current = () => generation === this.#generation;
|
|
582
|
+
let opened = false;
|
|
583
|
+
socket.addEventListener("open", () => {
|
|
584
|
+
if (!current()) return;
|
|
585
|
+
opened = true;
|
|
586
|
+
this.#socket = socket;
|
|
587
|
+
log2(`connected to ${hubUrl2}`);
|
|
588
|
+
const waiting = this.#outbox;
|
|
589
|
+
this.#outbox = [];
|
|
590
|
+
for (const frame of waiting) socket.send(JSON.stringify(frame));
|
|
591
|
+
for (const session of this.#sessions.values()) session.process?.resume();
|
|
592
|
+
this.#send({
|
|
593
|
+
type: "hello",
|
|
594
|
+
protocol: AGENT_PROTOCOL,
|
|
595
|
+
instance: this.instance,
|
|
596
|
+
version: this.#options.version,
|
|
597
|
+
agents: AGENT_NAMES.map((name) => AGENTS[name].capabilities),
|
|
598
|
+
sessions: this.#live()
|
|
599
|
+
});
|
|
600
|
+
this.#attempts = 0;
|
|
601
|
+
this.#keepAlive(socket, current);
|
|
602
|
+
});
|
|
603
|
+
socket.addEventListener("message", (event) => {
|
|
604
|
+
if (!current()) return;
|
|
605
|
+
const data = typeof event.data === "string" ? event.data : "";
|
|
606
|
+
if (data === PONG) {
|
|
607
|
+
if (this.#pong) clearTimeout(this.#pong);
|
|
608
|
+
this.#pong = null;
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
this.#receive(data);
|
|
612
|
+
});
|
|
613
|
+
socket.addEventListener("close", (event) => {
|
|
614
|
+
if (!current()) return;
|
|
615
|
+
const final = Object.entries(GATEWAY_CLOSE).find(([, code]) => code === event.code);
|
|
616
|
+
if (final) {
|
|
617
|
+
const [why] = final;
|
|
618
|
+
this.#finish({
|
|
619
|
+
reason: `the hub closed the socket for good (${why}): ${event.reason}`,
|
|
620
|
+
refused: why !== "replaced"
|
|
621
|
+
});
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
this.#lost(socket, `the hub's socket closed (${event.code} ${event.reason})`, opened);
|
|
625
|
+
});
|
|
626
|
+
socket.addEventListener("error", () => {
|
|
627
|
+
if (current()) this.#lost(socket, "the hub's socket failed", opened);
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
/** Stop for good, and say why. */
|
|
631
|
+
#finish(stop2) {
|
|
632
|
+
this.#options.log(stop2.reason);
|
|
633
|
+
this.stop();
|
|
634
|
+
this.#options.onStop?.(stop2);
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Whether the hub refuses the gateway token, as it answers the socket's
|
|
638
|
+
* URL over plain HTTP: browsers' WebSocket API, which Node's and Bun's
|
|
639
|
+
* follow, does not say why an upgrade failed. The hub authenticates
|
|
640
|
+
* before it asks for an upgrade: 401 or 403 is the token, anything else
|
|
641
|
+
* (the 426 a good token gets, a failure on the way) is not.
|
|
642
|
+
*/
|
|
643
|
+
async #refusal() {
|
|
644
|
+
const { hubUrl: hubUrl2, token: token2 } = this.#options;
|
|
645
|
+
try {
|
|
646
|
+
const response = await fetch(hubUrl2.replace(/^ws/, "http"), {
|
|
647
|
+
headers: { Authorization: `Bearer ${token2}` },
|
|
648
|
+
signal: AbortSignal.timeout(1e4)
|
|
649
|
+
});
|
|
650
|
+
const said = (await response.text()).slice(0, 300);
|
|
651
|
+
if (response.status === 401 || response.status === 403) {
|
|
652
|
+
return `the hub refused the gateway token (${response.status}: ${said})`;
|
|
653
|
+
}
|
|
654
|
+
} catch {
|
|
655
|
+
}
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* The connection is gone, or as good as gone: forget it, and dial again;
|
|
660
|
+
* unless it never opened because the hub refuses the token, which no
|
|
661
|
+
* retry mends.
|
|
662
|
+
*/
|
|
663
|
+
#lost(socket, why, opened) {
|
|
664
|
+
this.#generation++;
|
|
665
|
+
this.#socket = null;
|
|
666
|
+
if (this.#ping) clearInterval(this.#ping);
|
|
667
|
+
if (this.#pong) clearTimeout(this.#pong);
|
|
668
|
+
this.#ping = null;
|
|
669
|
+
this.#pong = null;
|
|
670
|
+
try {
|
|
671
|
+
socket.close();
|
|
672
|
+
} catch {
|
|
673
|
+
}
|
|
674
|
+
if (opened) {
|
|
675
|
+
this.#options.log(`${why}; dialing again`);
|
|
676
|
+
this.#retry();
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
void this.#refusal().then((refusal) => {
|
|
680
|
+
if (this.#stopped) return;
|
|
681
|
+
if (refusal !== null) {
|
|
682
|
+
this.#finish({ reason: refusal, refused: true });
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
this.#options.log(`${why}; dialing again`);
|
|
686
|
+
this.#retry();
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
/** Dial again, waiting longer after each failure, with some jitter. */
|
|
690
|
+
#retry() {
|
|
691
|
+
if (this.#stopped || this.#reconnect) return;
|
|
692
|
+
const { reconnectMinMs, reconnectMaxMs } = this.#timing;
|
|
693
|
+
const wait = Math.min(reconnectMaxMs, reconnectMinMs * 2 ** this.#attempts++);
|
|
694
|
+
this.#reconnect = setTimeout(
|
|
695
|
+
() => {
|
|
696
|
+
this.#reconnect = null;
|
|
697
|
+
this.#connect();
|
|
698
|
+
},
|
|
699
|
+
wait * (0.8 + Math.random() * 0.4)
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
/** PING now and then; a socket that does not answer is dead, though it may not know it. */
|
|
703
|
+
#keepAlive(socket, current) {
|
|
704
|
+
if (this.#ping) clearInterval(this.#ping);
|
|
705
|
+
this.#ping = setInterval(() => {
|
|
706
|
+
if (!current() || this.#pong) return;
|
|
707
|
+
socket.send(PING);
|
|
708
|
+
this.#pong = setTimeout(() => {
|
|
709
|
+
this.#pong = null;
|
|
710
|
+
if (current()) this.#lost(socket, "the hub did not answer a ping", true);
|
|
711
|
+
}, this.#timing.pongWithinMs);
|
|
712
|
+
}, this.#timing.pingEveryMs);
|
|
713
|
+
}
|
|
714
|
+
#send(frame) {
|
|
715
|
+
if (this.#socket?.readyState === WebSocket.OPEN) {
|
|
716
|
+
this.#socket.send(JSON.stringify(frame));
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
if (this.#stopped) return;
|
|
720
|
+
this.#outbox.push(frame);
|
|
721
|
+
if (this.#outbox.length === OUTBOX_LIMIT) {
|
|
722
|
+
for (const session of this.#sessions.values()) session.process?.pause();
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
#receive(data) {
|
|
726
|
+
let frame;
|
|
727
|
+
try {
|
|
728
|
+
frame = JSON.parse(data);
|
|
729
|
+
} catch {
|
|
730
|
+
this.#options.log(`the hub sent something that is not JSON: ${data.slice(0, 200)}`);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if ("acp" in frame) this.#relay(frame.session, frame.acp);
|
|
734
|
+
else if (frame.type === "open") void this.#open(frame);
|
|
735
|
+
else if (frame.type === "close") this.#close(frame.session);
|
|
736
|
+
}
|
|
737
|
+
/** The sessions with an agent, as the hello reports them. */
|
|
738
|
+
#live() {
|
|
739
|
+
return [...this.#sessions.values()].map((session) => ({
|
|
740
|
+
session: session.session,
|
|
741
|
+
acpSessionId: session.acpSessionId,
|
|
742
|
+
prompts: session.process?.prompts ?? []
|
|
743
|
+
}));
|
|
744
|
+
}
|
|
745
|
+
// -------------------------------------------------------------------------
|
|
746
|
+
// Sessions
|
|
747
|
+
// -------------------------------------------------------------------------
|
|
748
|
+
async #open(request) {
|
|
749
|
+
const { session: id, agent, appId, acpSessionId } = request;
|
|
750
|
+
const { log: log2, stateDir } = this.#options;
|
|
751
|
+
const existing = this.#sessions.get(id);
|
|
752
|
+
if (existing) {
|
|
753
|
+
if (existing.opened && existing.acpSessionId) {
|
|
754
|
+
this.#send({
|
|
755
|
+
type: "opened",
|
|
756
|
+
session: id,
|
|
757
|
+
acpSessionId: existing.acpSessionId,
|
|
758
|
+
...existing.opened
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
if (!SESSION_ID.test(id) || !AGENT_NAMES.includes(agent)) {
|
|
764
|
+
this.#send({ type: "failed", session: id, message: `cannot open ${id} with ${agent}` });
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
const session = {
|
|
768
|
+
session: id,
|
|
769
|
+
agent,
|
|
770
|
+
appId,
|
|
771
|
+
process: null,
|
|
772
|
+
acpSessionId: null,
|
|
773
|
+
rules: null,
|
|
774
|
+
opened: null,
|
|
775
|
+
tokenFile: join3(stateDir, "sessions", id, "model-token"),
|
|
776
|
+
refresh: null,
|
|
777
|
+
idle: null,
|
|
778
|
+
closed: false
|
|
779
|
+
};
|
|
780
|
+
this.#sessions.set(id, session);
|
|
781
|
+
log2(`${id}: starting ${agent} for ${appId}${acpSessionId ? `, resuming ${acpSessionId}` : ""}`);
|
|
782
|
+
try {
|
|
783
|
+
const { cwd, rules } = await checkout(this.#options.home, appId, this.#agentEnv(), log2);
|
|
784
|
+
const key = await this.#options.platform.modelKey(appId);
|
|
785
|
+
this.#keep(session, key);
|
|
786
|
+
const definition = AGENTS[agent];
|
|
787
|
+
if (session.closed) throw new Error("closed while it started");
|
|
788
|
+
const child = new AgentProcess({
|
|
789
|
+
command: definition.command,
|
|
790
|
+
args: definition.args,
|
|
791
|
+
cwd,
|
|
792
|
+
env: {
|
|
793
|
+
...this.#agentEnv(),
|
|
794
|
+
...definition.prepare({ stateDir, key, tokenFile: session.tokenFile })
|
|
795
|
+
},
|
|
796
|
+
onMessage: (message) => this.#fromAgent(session, message),
|
|
797
|
+
// Before it says it runs, an agent that exits has failed to start.
|
|
798
|
+
onExit: (message) => this.#end(session, message, session.opened ? "closed" : "failed"),
|
|
799
|
+
log: (line) => log2(`${id}: ${line}`),
|
|
800
|
+
asks: definition.asks
|
|
801
|
+
});
|
|
802
|
+
session.process = child;
|
|
803
|
+
const initialize = await child.request(
|
|
804
|
+
ACP.initialize,
|
|
805
|
+
{
|
|
806
|
+
protocolVersion: 1,
|
|
807
|
+
clientCapabilities: {
|
|
808
|
+
fs: { readTextFile: false, writeTextFile: false },
|
|
809
|
+
terminal: false
|
|
810
|
+
},
|
|
811
|
+
clientInfo: { name: "teable-agent-gateway", version: this.#options.version }
|
|
812
|
+
},
|
|
813
|
+
this.#timing.startMs
|
|
814
|
+
);
|
|
815
|
+
let setup = null;
|
|
816
|
+
if (acpSessionId !== null && initialize.agentCapabilities?.loadSession) {
|
|
817
|
+
try {
|
|
818
|
+
setup = await child.load(
|
|
819
|
+
{ sessionId: acpSessionId, cwd, mcpServers: [] },
|
|
820
|
+
this.#timing.startMs
|
|
821
|
+
);
|
|
822
|
+
session.acpSessionId = acpSessionId;
|
|
823
|
+
} catch (error) {
|
|
824
|
+
if (!child.running) throw error;
|
|
825
|
+
log2(`${id}: the agent could not resume ${acpSessionId}: ${messageOf(error)}`);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
const resumed = setup !== null;
|
|
829
|
+
if (!resumed) {
|
|
830
|
+
const { sessionId, ...rest } = await child.request(
|
|
831
|
+
ACP.newSession,
|
|
832
|
+
{ cwd, mcpServers: [] },
|
|
833
|
+
this.#timing.startMs
|
|
834
|
+
);
|
|
835
|
+
if (typeof sessionId !== "string")
|
|
836
|
+
throw new Error("the agent's session/new named no session");
|
|
837
|
+
session.acpSessionId = sessionId;
|
|
838
|
+
session.rules = rules;
|
|
839
|
+
setup = rest;
|
|
840
|
+
}
|
|
841
|
+
session.opened = { initialize, setup: setup ?? {}, resumed };
|
|
842
|
+
if (session.closed || !child.running) throw new Error("the agent stopped as it started");
|
|
843
|
+
this.#send({
|
|
844
|
+
type: "opened",
|
|
845
|
+
session: id,
|
|
846
|
+
acpSessionId: session.acpSessionId ?? "",
|
|
847
|
+
...session.opened
|
|
848
|
+
});
|
|
849
|
+
this.#idle(session);
|
|
850
|
+
log2(`${id}: ${agent} ${resumed ? "resumed" : "started"} ${session.acpSessionId}`);
|
|
851
|
+
} catch (error) {
|
|
852
|
+
const message = `could not start ${agent}: ${messageOf(error)}`;
|
|
853
|
+
log2(`${id}: ${message}`);
|
|
854
|
+
this.#end(session, message, "failed");
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
#close(id) {
|
|
858
|
+
const session = this.#sessions.get(id);
|
|
859
|
+
if (session) this.#end(session, "closed by the hub");
|
|
860
|
+
else this.#send({ type: "closed", session: id, message: "no agent runs for it" });
|
|
861
|
+
}
|
|
862
|
+
/** The session ends: its agent, its token, its timers; the hub hears why. */
|
|
863
|
+
#end(session, message, as = "closed") {
|
|
864
|
+
if (session.closed) return;
|
|
865
|
+
session.closed = true;
|
|
866
|
+
this.#sessions.delete(session.session);
|
|
867
|
+
if (session.refresh) clearTimeout(session.refresh);
|
|
868
|
+
if (session.idle) clearTimeout(session.idle);
|
|
869
|
+
session.process?.kill();
|
|
870
|
+
rmSync(join3(this.#options.stateDir, "sessions", session.session), {
|
|
871
|
+
recursive: true,
|
|
872
|
+
force: true
|
|
873
|
+
});
|
|
874
|
+
this.#send({ type: as, session: session.session, message });
|
|
875
|
+
this.#touch();
|
|
876
|
+
}
|
|
877
|
+
/** The hub's message for the session's agent. */
|
|
878
|
+
#relay(id, message) {
|
|
879
|
+
const session = this.#sessions.get(id);
|
|
880
|
+
const child = session?.process;
|
|
881
|
+
if (!session || !child?.running || session.opened === null) {
|
|
882
|
+
if (isAcpRequest(message)) {
|
|
883
|
+
const error = { code: -32e3, message: "The session's agent is not running" };
|
|
884
|
+
this.#send({ session: id, acp: { jsonrpc: "2.0", id: message.id, error } });
|
|
885
|
+
}
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
let outgoing = message;
|
|
889
|
+
if (isAcpRequest(message) && message.method === ACP.prompt && session.rules !== null) {
|
|
890
|
+
outgoing = withRules(message, session.rules);
|
|
891
|
+
session.rules = null;
|
|
892
|
+
}
|
|
893
|
+
child.send(outgoing);
|
|
894
|
+
this.#idle(session);
|
|
895
|
+
this.#touch();
|
|
896
|
+
}
|
|
897
|
+
/** The agent's message for the hub. */
|
|
898
|
+
#fromAgent(session, message) {
|
|
899
|
+
this.#send({ session: session.session, acp: message });
|
|
900
|
+
if (isAcpResponse(message)) {
|
|
901
|
+
this.#idle(session);
|
|
902
|
+
this.#touch();
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
/** An agent with no turn running stops after a while. */
|
|
906
|
+
#idle(session) {
|
|
907
|
+
if (session.idle) clearTimeout(session.idle);
|
|
908
|
+
session.idle = null;
|
|
909
|
+
if (session.closed || (session.process?.prompts.length ?? 0) > 0) return;
|
|
910
|
+
const { idleMs } = this.#timing;
|
|
911
|
+
session.idle = setTimeout(
|
|
912
|
+
() => this.#end(session, `no turn for ${Math.round(idleMs / 6e4)} min; the next resumes it`),
|
|
913
|
+
idleMs
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
// -------------------------------------------------------------------------
|
|
917
|
+
// The old platform: model tokens, and keeping the sandbox up
|
|
918
|
+
// -------------------------------------------------------------------------
|
|
919
|
+
/** Write the session's model token, and replace it before it expires. */
|
|
920
|
+
#keep(session, key) {
|
|
921
|
+
if (session.closed) return;
|
|
922
|
+
writeAtomically(session.tokenFile, key.token);
|
|
923
|
+
const { refreshBeforeMs, refreshRetryMs } = this.#timing;
|
|
924
|
+
const schedule = (ms) => {
|
|
925
|
+
if (session.refresh) clearTimeout(session.refresh);
|
|
926
|
+
session.refresh = setTimeout(() => void refresh(), Math.max(ms, 0));
|
|
927
|
+
};
|
|
928
|
+
const refresh = async () => {
|
|
929
|
+
session.refresh = null;
|
|
930
|
+
if (session.closed) return;
|
|
931
|
+
try {
|
|
932
|
+
this.#keep(session, await this.#options.platform.modelKey(session.appId));
|
|
933
|
+
} catch (error) {
|
|
934
|
+
this.#options.log(
|
|
935
|
+
`${session.session}: could not renew the model token: ${messageOf(error)}`
|
|
936
|
+
);
|
|
937
|
+
if (!session.closed) schedule(refreshRetryMs);
|
|
938
|
+
}
|
|
939
|
+
};
|
|
940
|
+
schedule(key.expiresAt - refreshBeforeMs - Date.now());
|
|
941
|
+
}
|
|
942
|
+
/** Touch the sandbox while any turn runs: at once, then every touchEveryMs. */
|
|
943
|
+
#touch() {
|
|
944
|
+
const running = [...this.#sessions.values()].some((s) => (s.process?.prompts.length ?? 0) > 0);
|
|
945
|
+
if (!running) {
|
|
946
|
+
if (this.#touching) clearInterval(this.#touching);
|
|
947
|
+
this.#touching = null;
|
|
948
|
+
return;
|
|
949
|
+
}
|
|
950
|
+
if (this.#touching) return;
|
|
951
|
+
const touch = () => {
|
|
952
|
+
this.#lastTouch = Date.now();
|
|
953
|
+
this.#options.platform.touch().catch((error) => {
|
|
954
|
+
this.#options.log(`could not keep the sandbox up: ${messageOf(error)}`);
|
|
955
|
+
});
|
|
956
|
+
};
|
|
957
|
+
if (Date.now() - this.#lastTouch >= this.#timing.touchEveryMs) touch();
|
|
958
|
+
this.#touching = setInterval(touch, this.#timing.touchEveryMs);
|
|
959
|
+
}
|
|
960
|
+
/** The environment of agents and the CLI: the gateway's own, without its token or the hub's address. */
|
|
961
|
+
#agentEnv() {
|
|
962
|
+
const {
|
|
963
|
+
TEABLE_NEXT_GATEWAY_TOKEN: _token,
|
|
964
|
+
TEABLE_NEXT_AGENT_URL: _hub,
|
|
965
|
+
...env
|
|
966
|
+
} = this.#options.env;
|
|
967
|
+
return env;
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
|
|
971
|
+
// src/platform.ts
|
|
972
|
+
function expiryOf(value) {
|
|
973
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
|
|
974
|
+
return value < 1e12 ? value * 1e3 : value;
|
|
975
|
+
}
|
|
976
|
+
if (typeof value === "string") {
|
|
977
|
+
const parsed = Date.parse(value);
|
|
978
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
979
|
+
}
|
|
980
|
+
return void 0;
|
|
981
|
+
}
|
|
982
|
+
var Platform = class {
|
|
983
|
+
#endpoint;
|
|
984
|
+
#token;
|
|
985
|
+
constructor(endpoint, token2) {
|
|
986
|
+
this.#endpoint = endpoint.replace(/\/+$/, "");
|
|
987
|
+
this.#token = token2;
|
|
988
|
+
}
|
|
989
|
+
/** A model token for the project `baseId` (an app's id). */
|
|
990
|
+
async modelKey(baseId) {
|
|
991
|
+
const body = await this.#post("/api/teable-next/agent/model-key", { baseId });
|
|
992
|
+
const { token: token2, expiresAt: expiresAt2, model, openaiBaseUrl, anthropicBaseUrl } = body ?? {};
|
|
993
|
+
const expiry = expiryOf(expiresAt2);
|
|
994
|
+
if (typeof token2 !== "string" || token2 === "" || expiry === void 0 || typeof model !== "string" || typeof openaiBaseUrl !== "string" || typeof anthropicBaseUrl !== "string") {
|
|
995
|
+
throw new Error(
|
|
996
|
+
"Teable's model-key answer lacks token, expiresAt, model, openaiBaseUrl or anthropicBaseUrl"
|
|
997
|
+
);
|
|
998
|
+
}
|
|
999
|
+
return { token: token2, expiresAt: expiry, model, openaiBaseUrl, anthropicBaseUrl };
|
|
1000
|
+
}
|
|
1001
|
+
async touch() {
|
|
1002
|
+
await this.#post("/api/teable-next/agent/sandbox/touch", void 0);
|
|
1003
|
+
}
|
|
1004
|
+
async #post(path, body) {
|
|
1005
|
+
const response = await fetch(`${this.#endpoint}${path}`, {
|
|
1006
|
+
method: "POST",
|
|
1007
|
+
headers: {
|
|
1008
|
+
Authorization: `Bearer ${this.#token}`,
|
|
1009
|
+
...body !== void 0 && { "Content-Type": "application/json" }
|
|
1010
|
+
},
|
|
1011
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
1012
|
+
signal: AbortSignal.timeout(3e4)
|
|
1013
|
+
});
|
|
1014
|
+
const text2 = await response.text();
|
|
1015
|
+
if (!response.ok) {
|
|
1016
|
+
throw new Error(`Teable answered ${response.status} to ${path}: ${text2.slice(0, 300)}`);
|
|
1017
|
+
}
|
|
1018
|
+
if (text2.trim() === "") return void 0;
|
|
1019
|
+
try {
|
|
1020
|
+
return JSON.parse(text2);
|
|
1021
|
+
} catch {
|
|
1022
|
+
throw new Error(`Teable's answer to ${path} is not JSON: ${text2.slice(0, 300)}`);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
// src/cli.ts
|
|
1028
|
+
var USAGE = `teable-agent-gateway: run a person's agents for Teable, from their sandbox.
|
|
1029
|
+
|
|
1030
|
+
Environment: TEABLE_NEXT_AGENT_URL, TEABLE_NEXT_GATEWAY_TOKEN, TEABLE_ENDPOINT,
|
|
1031
|
+
TEABLE_TOKEN, and optionally TEABLE_NEXT_ENDPOINT.`;
|
|
1032
|
+
function log(line) {
|
|
1033
|
+
console.error(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}`);
|
|
1034
|
+
}
|
|
1035
|
+
function fail(message) {
|
|
1036
|
+
console.error(`teable-agent-gateway: ${message}
|
|
1037
|
+
|
|
1038
|
+
${USAGE}`);
|
|
1039
|
+
process.exit(1);
|
|
1040
|
+
}
|
|
1041
|
+
function required(name) {
|
|
1042
|
+
return process.env[name]?.trim() || fail(`${name} is not set`);
|
|
1043
|
+
}
|
|
1044
|
+
function expiryOf2(token2) {
|
|
1045
|
+
try {
|
|
1046
|
+
const payload = JSON.parse(Buffer.from(token2.split(".")[1] ?? "", "base64url").toString());
|
|
1047
|
+
return typeof payload.exp === "number" ? payload.exp * 1e3 : void 0;
|
|
1048
|
+
} catch {
|
|
1049
|
+
return void 0;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
var version = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
1053
|
+
var [argument] = process.argv.slice(2);
|
|
1054
|
+
if (argument === "--help" || argument === "-h") {
|
|
1055
|
+
console.log(USAGE);
|
|
1056
|
+
process.exit(0);
|
|
1057
|
+
}
|
|
1058
|
+
if (argument === "--version") {
|
|
1059
|
+
console.log(version);
|
|
1060
|
+
process.exit(0);
|
|
1061
|
+
}
|
|
1062
|
+
if (argument !== void 0) fail(`unknown argument ${argument}`);
|
|
1063
|
+
var hubUrl = required("TEABLE_NEXT_AGENT_URL");
|
|
1064
|
+
if (!/^wss?:\/\//.test(hubUrl)) fail(`TEABLE_NEXT_AGENT_URL must be a ws:// or wss:// URL`);
|
|
1065
|
+
var token = required("TEABLE_NEXT_GATEWAY_TOKEN");
|
|
1066
|
+
var expiresAt = expiryOf2(token);
|
|
1067
|
+
if (expiresAt === void 0) fail("TEABLE_NEXT_GATEWAY_TOKEN is not a JWT with an expiry");
|
|
1068
|
+
if (expiresAt <= Date.now()) fail("TEABLE_NEXT_GATEWAY_TOKEN has expired");
|
|
1069
|
+
var home = homedir();
|
|
1070
|
+
var gateway = new Gateway({
|
|
1071
|
+
hubUrl,
|
|
1072
|
+
token,
|
|
1073
|
+
platform: new Platform(required("TEABLE_ENDPOINT"), required("TEABLE_TOKEN")),
|
|
1074
|
+
home,
|
|
1075
|
+
stateDir: join4(home, ".teable-agent-gateway"),
|
|
1076
|
+
env: process.env,
|
|
1077
|
+
version,
|
|
1078
|
+
log,
|
|
1079
|
+
// Agents get a moment to exit on SIGTERM.
|
|
1080
|
+
onStop: ({ refused }) => setTimeout(() => process.exit(refused ? 1 : 0), 1e3)
|
|
1081
|
+
});
|
|
1082
|
+
var stop = (why, code) => {
|
|
1083
|
+
log(`stopping: ${why}`);
|
|
1084
|
+
gateway.stop();
|
|
1085
|
+
setTimeout(() => process.exit(code), 1e3);
|
|
1086
|
+
};
|
|
1087
|
+
process.on("SIGTERM", () => stop("SIGTERM", 0));
|
|
1088
|
+
process.on("SIGINT", () => stop("SIGINT", 0));
|
|
1089
|
+
setTimeout(
|
|
1090
|
+
() => stop("the gateway token expired", 1),
|
|
1091
|
+
Math.min(expiresAt - Date.now(), 2 ** 31 - 1)
|
|
1092
|
+
);
|
|
1093
|
+
log(`teable-agent-gateway ${version} (${gateway.instance}) dialing ${hubUrl}`);
|
|
1094
|
+
gateway.start();
|