@teable/agent-gateway 0.0.0-stage → 1.0.0

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