@teable/agent-gateway 1.0.1 → 1.0.3

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 CHANGED
@@ -33,7 +33,8 @@ grok-build (`grok agent --always-approve stdio`), configured to reach nothing
33
33
  but Teable's AI proxy, with a model token per session that the gateway renews.
34
34
  It acts without asking, but when it asks the person a question, or to approve
35
35
  its plan, the gateway puts that to them in Teable's builder and gives the
36
- answer back.
36
+ answer back. A message the person sends while it works goes into what it is
37
+ doing, and its background tasks show in the builder as they run and end.
37
38
 
38
39
  `@teable/agent-gateway/protocol` holds the types of what travels between the
39
40
  gateway, the hub and the builder.
package/dist/agent.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type AcpMessage, type JsonRpcId } from "./protocol.js";
2
- import type { AskShim } from "./shims.js";
2
+ import type { AskShim, NoticeShim } from "./shims.js";
3
3
  interface AgentStart {
4
4
  command: string;
5
5
  args: string[];
@@ -12,6 +12,8 @@ interface AgentStart {
12
12
  log(line: string): void;
13
13
  /** The vendor requests with which the agent asks the person, by method (shims.ts). */
14
14
  asks?: Readonly<Record<string, AskShim>>;
15
+ /** The vendor notifications that say what the protocol has words for, by method (shims.ts). */
16
+ notices?: Readonly<Record<string, NoticeShim>>;
15
17
  }
16
18
  export declare class AgentProcess {
17
19
  #private;
@@ -19,10 +21,17 @@ export declare class AgentProcess {
19
21
  get running(): boolean;
20
22
  /** The hub's prompts the agent is working on. */
21
23
  get prompts(): JsonRpcId[];
24
+ /** How many of its background tasks run. */
25
+ get tasks(): number;
22
26
  /** A request of the gateway's own; rejects with the agent's error, or when it takes too long. */
23
27
  request(method: string, params: unknown, timeoutMs: number): Promise<unknown>;
24
28
  /** A request whose replayed updates the hub must not see again: `session/load`. */
25
29
  load(params: unknown, timeoutMs: number): Promise<unknown>;
30
+ /**
31
+ * Send a message into the running turn, as the agent takes one: a second
32
+ * `session/prompt`, under the hub's id.
33
+ */
34
+ steer(request: string, params: unknown): void;
26
35
  /** Relay the hub's message to the agent: unchanged, but an answer to what a shim asked, in the agent's words. */
27
36
  send(message: AcpMessage): void;
28
37
  /** Stop reading what the agent says (its writes then wait), and read on. */
package/dist/agents.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ModelKey } from "./platform.js";
2
2
  import type { AgentCapabilities, AgentName } from "./protocol.js";
3
- import { type AskShim } from "./shims.js";
3
+ import { type AskShim, type NoticeShim } from "./shims.js";
4
4
  /** What a session's agent is prepared with. */
5
5
  interface AgentContext {
6
6
  /** The gateway's own directory: agents keep their state under it. */
@@ -17,6 +17,8 @@ interface AgentDefinition {
17
17
  prepare(context: AgentContext): Record<string, string>;
18
18
  /** Its vendor requests that ask the person, by method, and the shims that relay them (shims.ts). */
19
19
  asks?: Readonly<Record<string, AskShim>>;
20
+ /** Its vendor notifications that say what the protocol has words for, by method (shims.ts). */
21
+ notices?: Readonly<Record<string, NoticeShim>>;
20
22
  }
21
23
  /** Write a file whole or not at all: an agent starting meanwhile reads the old one or the new one. */
22
24
  export declare function writeAtomically(path: string, text: string, mode?: number): void;
@@ -0,0 +1,112 @@
1
+ // src/protocol.ts
2
+ var GATEWAY_PATH = "/api/v4/agent/gateway";
3
+ var AGENT_PROTOCOL = 2;
4
+ var PING = "ping";
5
+ var PONG = "pong";
6
+ var GATEWAY_CLOSE = { replaced: 4e3, expired: 4001, unsupported: 4002 };
7
+ var GATEWAY_TOO_FAST = 4429;
8
+ var MAX_FRAME = 256 * 1024;
9
+ function shrink(message, max) {
10
+ const whole = JSON.stringify(message).length;
11
+ if (whole <= max) return { message, shrunk: 0 };
12
+ const lengths = [];
13
+ const collect = (value) => {
14
+ if (typeof value === "string") lengths.push(value.length);
15
+ else if (Array.isArray(value)) value.forEach(collect);
16
+ else if (typeof value === "object" && value !== null) Object.values(value).forEach(collect);
17
+ };
18
+ collect(message);
19
+ lengths.sort((a, b) => b - a);
20
+ const cut = (value, cap2) => {
21
+ if (typeof value === "string") return value.length > cap2 ? `${value.slice(0, cap2)}\u2026` : value;
22
+ if (Array.isArray(value)) return value.map((each) => cut(each, cap2));
23
+ if (typeof value === "object" && value !== null) {
24
+ return Object.fromEntries(Object.entries(value).map(([key, each]) => [key, cut(each, cap2)]));
25
+ }
26
+ return value;
27
+ };
28
+ let excess = whole - max;
29
+ let cap = lengths[0] ?? 0;
30
+ for (let index = 0; index < lengths.length && excess > 0; index++) {
31
+ const next = lengths[index + 1] ?? 0;
32
+ const saved = (cap - next) * (index + 1);
33
+ if (saved >= excess) {
34
+ cap -= Math.ceil(excess / (index + 1));
35
+ excess = 0;
36
+ } else {
37
+ excess -= saved;
38
+ cap = next;
39
+ }
40
+ }
41
+ for (cap = Math.max(cap - 16, 0); ; cap = Math.floor(cap / 2)) {
42
+ const shrunk = cut(message, cap);
43
+ const length = JSON.stringify(shrunk).length;
44
+ if (length <= max) return { message: shrunk, shrunk: whole - length };
45
+ if (cap === 0) break;
46
+ }
47
+ const { jsonrpc, id, method } = message;
48
+ const named = method === void 0 ? { jsonrpc, id, result: null } : { jsonrpc, ...id === void 0 ? {} : { id }, method, params: null };
49
+ return { message: named, shrunk: whole - JSON.stringify(named).length };
50
+ }
51
+ var TAB_CLOSE = {
52
+ expired: 4e3,
53
+ badInput: 4400,
54
+ unauthenticated: 4401,
55
+ forbidden: 4403,
56
+ notFound: 4404,
57
+ rateLimited: 4429
58
+ };
59
+ var SESSION_ID = /^ses[0-9A-Za-z]{16}$/;
60
+ var ACP = {
61
+ initialize: "initialize",
62
+ newSession: "session/new",
63
+ loadSession: "session/load",
64
+ prompt: "session/prompt",
65
+ cancel: "session/cancel",
66
+ update: "session/update",
67
+ requestPermission: "session/request_permission"
68
+ };
69
+ var ASK = {
70
+ /** Questions for the person (AgentQuestionRequest), answered with an AgentQuestionOutcome. */
71
+ question: "_teable/question",
72
+ /** A plan for the person to approve before the agent acts on it (AgentPlanRequest), answered with an AgentPlanOutcome. */
73
+ plan: "_teable/plan"
74
+ };
75
+ var NOTICE = {
76
+ /** The agent took a message sent while its turn ran (a `steer`) into that turn (SteeredNotice). */
77
+ steered: "_teable/steered",
78
+ /** A background task of the agent's started, or ended (TaskNotice). */
79
+ task: "_teable/task"
80
+ };
81
+ var TASK_OUTPUT = 8e3;
82
+ function isAcpRequest(message) {
83
+ return "method" in message && "id" in message;
84
+ }
85
+ function isAcpNotification(message) {
86
+ return "method" in message && !("id" in message);
87
+ }
88
+ function isAcpResponse(message) {
89
+ return !("method" in message) && "id" in message;
90
+ }
91
+ var AGENT_NAMES = ["grok"];
92
+
93
+ export {
94
+ GATEWAY_PATH,
95
+ AGENT_PROTOCOL,
96
+ PING,
97
+ PONG,
98
+ GATEWAY_CLOSE,
99
+ GATEWAY_TOO_FAST,
100
+ MAX_FRAME,
101
+ shrink,
102
+ TAB_CLOSE,
103
+ SESSION_ID,
104
+ ACP,
105
+ ASK,
106
+ NOTICE,
107
+ TASK_OUTPUT,
108
+ isAcpRequest,
109
+ isAcpNotification,
110
+ isAcpResponse,
111
+ AGENT_NAMES
112
+ };
package/dist/cli.js CHANGED
@@ -5,13 +5,18 @@ import {
5
5
  AGENT_PROTOCOL,
6
6
  ASK,
7
7
  GATEWAY_CLOSE,
8
+ GATEWAY_TOO_FAST,
9
+ MAX_FRAME,
10
+ NOTICE,
8
11
  PING,
9
12
  PONG,
10
13
  SESSION_ID,
14
+ TASK_OUTPUT,
11
15
  isAcpNotification,
12
16
  isAcpRequest,
13
- isAcpResponse
14
- } from "./chunks/CYVXAHGU.js";
17
+ isAcpResponse,
18
+ shrink
19
+ } from "./chunks/XGVR5ONA.js";
15
20
 
16
21
  // src/cli.ts
17
22
  import { readFileSync } from "node:fs";
@@ -33,8 +38,14 @@ var AgentProcess = class {
33
38
  #child;
34
39
  #start;
35
40
  #pending = /* @__PURE__ */ new Map();
36
- /** 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. */
37
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();
38
49
  /** The agent's requests that ask the person, relayed by a shim, until the hub answers them. */
39
50
  #asked = /* @__PURE__ */ new Map();
40
51
  #stderr = [];
@@ -73,6 +84,10 @@ var AgentProcess = class {
73
84
  get prompts() {
74
85
  return [...this.#prompts];
75
86
  }
87
+ /** How many of its background tasks run. */
88
+ get tasks() {
89
+ return this.#tasks.size;
90
+ }
76
91
  /** A request of the gateway's own; rejects with the agent's error, or when it takes too long. */
77
92
  request(method, params, timeoutMs) {
78
93
  const id = `gateway:${this.#nextId++}`;
@@ -103,6 +118,15 @@ var AgentProcess = class {
103
118
  this.#loading = false;
104
119
  }
105
120
  }
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
+ }
106
130
  /** Relay the hub's message to the agent: unchanged, but an answer to what a shim asked, in the agent's words. */
107
131
  send(message) {
108
132
  if (isAcpRequest(message) && message.method === ACP.prompt) this.#prompts.add(message.id);
@@ -167,8 +191,11 @@ var AgentProcess = class {
167
191
  return;
168
192
  }
169
193
  this.#prompts.delete(message.id);
194
+ this.#steers = this.#steers.filter((id) => id !== message.id);
195
+ if (this.#absorbed.delete(message.id)) return;
170
196
  } else if (message.method.startsWith("_")) {
171
197
  if (isAcpRequest(message)) this.#vendorRequest(message);
198
+ else this.#vendorNotice(message);
172
199
  return;
173
200
  } else if (this.#loading && isAcpNotification(message) && message.method === ACP.update) {
174
201
  return;
@@ -199,6 +226,34 @@ var AgentProcess = class {
199
226
  this.#asked.set(message.id, { shim, params: message.params });
200
227
  this.#start.onMessage({ jsonrpc: "2.0", id: message.id, method: shim.method, params });
201
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
+ }
202
257
  #exit(message) {
203
258
  if (this.#exited) return;
204
259
  this.#exited = true;
@@ -297,6 +352,66 @@ var GROK_ASKS = {
297
352
  "_x.ai/ask_user_question": grokQuestions,
298
353
  "_x.ai/exit_plan_mode": grokPlan
299
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
+ };
300
415
 
301
416
  // src/agents.ts
302
417
  function writeAtomically(path, text2, mode = 384) {
@@ -333,8 +448,9 @@ model = ${toml(key.model)}
333
448
  base_url = ${toml(key.openaiBaseUrl)}
334
449
  name = "Teable AI"
335
450
  auth_provider = "teable"
336
- api_backend = "responses"
337
- reasoning_summary = "concise"
451
+ # Chat Completions: the AI proxy's Responses stream carries the upstream gateway's
452
+ # response.metadata events, which grok-build 1.0.100 refuses to parse.
453
+ api_backend = "chat_completions"
338
454
  reasoning_efforts = [{ value = "low" }, { value = "medium" }, { value = "high" }]
339
455
 
340
456
  # Asked before every request: the gateway replaces the token before it expires.
@@ -366,6 +482,11 @@ mixpanel_enabled = false
366
482
  [toolset.ask_user_question]
367
483
  timeout_enabled = false
368
484
 
485
+ # A message sent while a turn runs goes into that turn at its next gap, not
486
+ # after it (the default queues it): the hub sends one so only to steer.
487
+ [ui]
488
+ follow_up_behavior = "steer"
489
+
369
490
  [endpoints]
370
491
  cli_chat_proxy_base_url = "http://127.0.0.1:9/v1"
371
492
  xai_api_base_url = "http://127.0.0.1:9/v1"
@@ -415,20 +536,22 @@ var AGENTS = {
415
536
  capabilities: {
416
537
  agent: "grok",
417
538
  title: "Grok Build",
418
- // Its own steering is a vendor extension; until a shim speaks it, the hub interrupts.
419
- steering: "interrupt",
539
+ // A second session/prompt goes into the running turn (follow_up_behavior), which a shim reports.
540
+ steering: "native",
420
541
  // Started with --always-approve: it acts without asking,
421
542
  approvals: false,
422
543
  // but it may still ask the person questions, and to approve a plan.
423
544
  questions: true,
424
545
  planApproval: true,
425
546
  plans: true,
426
- backgroundTasks: false,
547
+ // Reported by its shims (shims.ts).
548
+ backgroundTasks: true,
427
549
  resume: true
428
550
  },
429
551
  command: "grok",
430
552
  args: ["agent", "--always-approve", "stdio"],
431
553
  asks: GROK_ASKS,
554
+ notices: GROK_NOTICES,
432
555
  prepare({ stateDir, key, tokenFile }) {
433
556
  const home2 = join(stateDir, "grok");
434
557
  writeAtomically(join(home2, "config.toml"), grokConfig(key, writeTokenHelper(stateDir)));
@@ -509,6 +632,7 @@ function checkout(home2, appId, env, log2) {
509
632
  var TIMING = {
510
633
  reconnectMinMs: 1e3,
511
634
  reconnectMaxMs: 3e4,
635
+ tooFastMs: 1e4,
512
636
  pingEveryMs: 3e4,
513
637
  pongWithinMs: 1e4,
514
638
  touchEveryMs: 6e4,
@@ -517,7 +641,7 @@ var TIMING = {
517
641
  idleMs: 30 * 6e4,
518
642
  startMs: 12e4
519
643
  };
520
- var OUTBOX_LIMIT = 1e4;
644
+ var UNACKED_LIMIT = 1e4;
521
645
  function messageOf(error) {
522
646
  return error instanceof Error ? error.message : String(error);
523
647
  }
@@ -532,7 +656,14 @@ var Gateway = class {
532
656
  #options;
533
657
  #timing;
534
658
  #sessions = /* @__PURE__ */ new Map();
535
- #outbox = [];
659
+ /** The number of the last frame sent; the next gets the one after. */
660
+ #sent = 0;
661
+ /** The frames the hub has not said it has, in order, as sent: sent again on every connection. */
662
+ #unacked = [];
663
+ /** The number of the last of the hub's frames taken. */
664
+ #received = 0;
665
+ /** Agents' output waits while the hub lacks too much. */
666
+ #paused = false;
536
667
  #socket = null;
537
668
  /** Which connection is current: events of earlier ones are ignored. */
538
669
  #generation = 0;
@@ -585,18 +716,18 @@ var Gateway = class {
585
716
  opened = true;
586
717
  this.#socket = socket;
587
718
  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
- });
719
+ socket.send(
720
+ JSON.stringify({
721
+ type: "hello",
722
+ protocol: AGENT_PROTOCOL,
723
+ instance: this.instance,
724
+ version: this.#options.version,
725
+ agents: AGENT_NAMES.map((name) => AGENTS[name].capabilities),
726
+ received: this.#received,
727
+ sent: this.#sent
728
+ })
729
+ );
730
+ for (const { data } of this.#unacked) socket.send(data);
600
731
  this.#attempts = 0;
601
732
  this.#keepAlive(socket, current);
602
733
  });
@@ -621,7 +752,8 @@ var Gateway = class {
621
752
  });
622
753
  return;
623
754
  }
624
- this.#lost(socket, `the hub's socket closed (${event.code} ${event.reason})`, opened);
755
+ const wait = event.code === GATEWAY_TOO_FAST ? this.#timing.tooFastMs : 0;
756
+ this.#lost(socket, `the hub's socket closed (${event.code} ${event.reason})`, opened, wait);
625
757
  });
626
758
  socket.addEventListener("error", () => {
627
759
  if (current()) this.#lost(socket, "the hub's socket failed", opened);
@@ -660,7 +792,7 @@ var Gateway = class {
660
792
  * unless it never opened because the hub refuses the token, which no
661
793
  * retry mends.
662
794
  */
663
- #lost(socket, why, opened) {
795
+ #lost(socket, why, opened, waitMs = 0) {
664
796
  this.#generation++;
665
797
  this.#socket = null;
666
798
  if (this.#ping) clearInterval(this.#ping);
@@ -673,7 +805,7 @@ var Gateway = class {
673
805
  }
674
806
  if (opened) {
675
807
  this.#options.log(`${why}; dialing again`);
676
- this.#retry();
808
+ this.#retry(waitMs);
677
809
  return;
678
810
  }
679
811
  void this.#refusal().then((refusal) => {
@@ -686,11 +818,14 @@ var Gateway = class {
686
818
  this.#retry();
687
819
  });
688
820
  }
689
- /** Dial again, waiting longer after each failure, with some jitter. */
690
- #retry() {
821
+ /** Dial again, waiting longer after each failure (`atLeastMs` at least), with some jitter. */
822
+ #retry(atLeastMs = 0) {
691
823
  if (this.#stopped || this.#reconnect) return;
692
824
  const { reconnectMinMs, reconnectMaxMs } = this.#timing;
693
- const wait = Math.min(reconnectMaxMs, reconnectMinMs * 2 ** this.#attempts++);
825
+ const wait = Math.max(
826
+ atLeastMs,
827
+ Math.min(reconnectMaxMs, reconnectMinMs * 2 ** this.#attempts++)
828
+ );
694
829
  this.#reconnect = setTimeout(
695
830
  () => {
696
831
  this.#reconnect = null;
@@ -711,17 +846,46 @@ var Gateway = class {
711
846
  }, this.#timing.pongWithinMs);
712
847
  }, this.#timing.pingEveryMs);
713
848
  }
849
+ /**
850
+ * Number a frame and send it, now if the hub is there; it is kept until
851
+ * the hub has it. What an agent says is cut to fit MAX_FRAME, which the
852
+ * hub takes no more of (and a socket would not carry much more).
853
+ */
714
854
  #send(frame) {
715
- if (this.#socket?.readyState === WebSocket.OPEN) {
716
- this.#socket.send(JSON.stringify(frame));
717
- return;
718
- }
719
855
  if (this.#stopped) return;
720
- this.#outbox.push(frame);
721
- if (this.#outbox.length === OUTBOX_LIMIT) {
856
+ const n = ++this.#sent;
857
+ let data = JSON.stringify({ ...frame, n });
858
+ if (data.length > MAX_FRAME && "acp" in frame) {
859
+ const room = MAX_FRAME - JSON.stringify({ ...frame, acp: null, n, shrunk: data.length }).length;
860
+ const { message, shrunk } = shrink(frame.acp, room);
861
+ this.#options.log(
862
+ `${frame.session}: cut ${shrunk} characters from what the agent said, to fit a frame`
863
+ );
864
+ data = JSON.stringify({ ...frame, acp: message, n, shrunk });
865
+ } else if (data.length > MAX_FRAME && !("acp" in frame)) {
866
+ const small = frame.type === "opened" ? {
867
+ ...frame,
868
+ initialize: { protocolVersion: frame.initialize.protocolVersion },
869
+ setup: {}
870
+ } : { ...frame, message: frame.message.slice(0, 2e3) };
871
+ data = JSON.stringify({ ...small, n });
872
+ }
873
+ this.#unacked.push({ n, data });
874
+ if (this.#socket?.readyState === WebSocket.OPEN) this.#socket.send(data);
875
+ if (!this.#paused && this.#unacked.length >= UNACKED_LIMIT) {
876
+ this.#paused = true;
722
877
  for (const session of this.#sessions.values()) session.process?.pause();
723
878
  }
724
879
  }
880
+ /** The hub has every frame up to `n`: they are not kept any more. */
881
+ #taken(n) {
882
+ const kept = this.#unacked.findIndex((frame) => frame.n > n);
883
+ this.#unacked = kept < 0 ? [] : this.#unacked.slice(kept);
884
+ if (this.#paused && this.#unacked.length < UNACKED_LIMIT / 2) {
885
+ this.#paused = false;
886
+ for (const session of this.#sessions.values()) session.process?.resume();
887
+ }
888
+ }
725
889
  #receive(data) {
726
890
  let frame;
727
891
  try {
@@ -730,17 +894,22 @@ var Gateway = class {
730
894
  this.#options.log(`the hub sent something that is not JSON: ${data.slice(0, 200)}`);
731
895
  return;
732
896
  }
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
- }));
897
+ if ("type" in frame && frame.type === "received") {
898
+ this.#taken(frame.n);
899
+ return;
900
+ }
901
+ if (typeof frame.n !== "number") {
902
+ this.#options.log(`the hub sent a frame without a number: ${data.slice(0, 200)}`);
903
+ return;
904
+ }
905
+ if (frame.n > this.#received) {
906
+ this.#received = frame.n;
907
+ if ("acp" in frame) this.#relay(frame.session, frame.acp);
908
+ else if (frame.type === "open") void this.#open(frame);
909
+ else if (frame.type === "close") this.#close(frame.session);
910
+ else if (frame.type === "steer") this.#steer(frame);
911
+ }
912
+ this.#socket?.send(JSON.stringify({ type: "received", n: this.#received }));
744
913
  }
745
914
  // -------------------------------------------------------------------------
746
915
  // Sessions
@@ -797,7 +966,8 @@ var Gateway = class {
797
966
  // Before it says it runs, an agent that exits has failed to start.
798
967
  onExit: (message) => this.#end(session, message, session.opened ? "closed" : "failed"),
799
968
  log: (line) => log2(`${id}: ${line}`),
800
- asks: definition.asks
969
+ asks: definition.asks,
970
+ notices: definition.notices
801
971
  });
802
972
  session.process = child;
803
973
  const initialize = await child.request(
@@ -894,19 +1064,39 @@ var Gateway = class {
894
1064
  this.#idle(session);
895
1065
  this.#touch();
896
1066
  }
1067
+ /**
1068
+ * A message for the session's running turn: the agent takes it in, or
1069
+ * runs it next; one whose agent does not run is answered with an error.
1070
+ */
1071
+ #steer(frame) {
1072
+ const session = this.#sessions.get(frame.session);
1073
+ const child = session?.process;
1074
+ if (!session || !child?.running || session.opened === null || !session.acpSessionId) {
1075
+ const error = { code: -32e3, message: "The session's agent is not running" };
1076
+ this.#send({ session: frame.session, acp: { jsonrpc: "2.0", id: frame.request, error } });
1077
+ return;
1078
+ }
1079
+ child.steer(frame.request, { sessionId: session.acpSessionId, prompt: frame.prompt });
1080
+ this.#idle(session);
1081
+ this.#touch();
1082
+ }
897
1083
  /** The agent's message for the hub. */
898
1084
  #fromAgent(session, message) {
899
1085
  this.#send({ session: session.session, acp: message });
900
- if (isAcpResponse(message)) {
1086
+ if (isAcpResponse(message) || "method" in message && message.method === NOTICE.task) {
901
1087
  this.#idle(session);
902
1088
  this.#touch();
903
1089
  }
904
1090
  }
905
- /** An agent with no turn running stops after a while. */
1091
+ /** Whether the session's agent works: on a turn, or on a background task. */
1092
+ #working(session) {
1093
+ return (session.process?.prompts.length ?? 0) > 0 || (session.process?.tasks ?? 0) > 0;
1094
+ }
1095
+ /** An agent with no turn running, and no background task, stops after a while. */
906
1096
  #idle(session) {
907
1097
  if (session.idle) clearTimeout(session.idle);
908
1098
  session.idle = null;
909
- if (session.closed || (session.process?.prompts.length ?? 0) > 0) return;
1099
+ if (session.closed || this.#working(session)) return;
910
1100
  const { idleMs } = this.#timing;
911
1101
  session.idle = setTimeout(
912
1102
  () => this.#end(session, `no turn for ${Math.round(idleMs / 6e4)} min; the next resumes it`),
@@ -939,9 +1129,9 @@ var Gateway = class {
939
1129
  };
940
1130
  schedule(key.expiresAt - refreshBeforeMs - Date.now());
941
1131
  }
942
- /** Touch the sandbox while any turn runs: at once, then every touchEveryMs. */
1132
+ /** Touch the sandbox while any agent works (a turn, a background task): at once, then every touchEveryMs. */
943
1133
  #touch() {
944
- const running = [...this.#sessions.values()].some((s) => (s.process?.prompts.length ?? 0) > 0);
1134
+ const running = [...this.#sessions.values()].some((session) => this.#working(session));
945
1135
  if (!running) {
946
1136
  if (this.#touching) clearInterval(this.#touching);
947
1137
  this.#touching = null;
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;
@@ -4,19 +4,31 @@
4
4
  * and the builder's agent panel, over two WebSockets.
5
5
  *
6
6
  * gateway ⇄ hub GET GATEWAY_PATH, with `Authorization: Bearer <gateway
7
- * token>`. ACP's JSON-RPC messages, unchanged, in
8
- * `{ session, acp }` frames, with what agents ask the
9
- * person beyond ACP in one agent-neutral form (ASK); and
10
- * control frames, which have a `type`: the hub asks the
11
- * gateway to open and close sessions, the gateway says
12
- * what it runs.
13
- * tab ⇄ hub GET `${APPS_PATH}/:appId/agent?since=<seq>` (APPS_PATH
14
- * from @teable/app/protocol), with the identity cookie.
15
- * The hub sends a snapshot, then each stored event after
16
- * `since` as `{ type: "event", seq, session, at, event }`,
17
- * then live ones; the tab sends commands `{ id, session,
18
- * op }`, each acknowledged once by its `id`. Everything the
19
- * hub sends a tab has a `type`.
7
+ * token>`. The gateway's hello first, then ACP's JSON-RPC
8
+ * messages, unchanged, in `{ session, acp }` frames, with
9
+ * what agents ask the person beyond ACP in one
10
+ * agent-neutral form (ASK); and control frames, which have
11
+ * a `type`: the hub asks the gateway to open and close
12
+ * sessions, the gateway says what became of them. Each
13
+ * side numbers these frames (`n`) and keeps each until the
14
+ * other says it has it (`received`), and sends again what
15
+ * the other lacks when the gateway dials again: while the
16
+ * gateway's process lives, nothing is lost and nothing is
17
+ * taken twice.
18
+ * tab ⇄ hub GET `${APPS_PATH}/:appId/agent?session=<id>&since=<seq>`
19
+ * (APPS_PATH from @teable/app/protocol), with the identity
20
+ * cookie. The hub sends a snapshot of the app's sessions;
21
+ * then, as `{ type: "event", seq, session, at, event }`,
22
+ * the app's events after `since` when they are few, else
23
+ * the latest events of the session the tab shows; then
24
+ * `replayed`, then live events of every session of the
25
+ * app. Older events come when the tab asks (`history`).
26
+ * The tab sends commands `{ id, session, op }`, each
27
+ * acknowledged once by its `id`. Everything the hub sends
28
+ * a tab has a `type`. A tab the runtime refuses, or whose
29
+ * identity runs out, gets its socket closed with a
30
+ * TAB_CLOSE code, which says whether to dial again:
31
+ * browsers are not told why an upgrade failed.
20
32
  *
21
33
  * Every message is one JSON text frame, except the keep-alive: either side
22
34
  * of a hub socket may send PING, which the hub answers with PONG.
@@ -28,9 +40,12 @@
28
40
  export declare const GATEWAY_PATH = "/api/v4/agent/gateway";
29
41
  /**
30
42
  * This protocol's version, which the gateway says in its hello. The hub
31
- * closes the socket of a gateway that speaks another (GATEWAY_CLOSE.unsupported).
43
+ * closes the socket of a gateway that speaks another (GATEWAY_CLOSE.unsupported),
44
+ * which then exits: a gateway already running in a sandbox may be older
45
+ * than the hub. 2: the hello comes first, and frames are numbered and
46
+ * acknowledged.
32
47
  */
33
- export declare const AGENT_PROTOCOL = 1;
48
+ export declare const AGENT_PROTOCOL = 2;
34
49
  /** The keep-alive: sent as a text frame, answered by the hub without waking it. */
35
50
  export declare const PING = "ping";
36
51
  export declare const PONG = "pong";
@@ -46,6 +61,44 @@ export declare const GATEWAY_CLOSE: {
46
61
  readonly expired: 4001;
47
62
  readonly unsupported: 4002;
48
63
  };
64
+ /**
65
+ * The hub closed the gateway's socket because it sent frames faster than
66
+ * the hub takes them. Not for good: the gateway dials again after its
67
+ * usual wait and sends again what the hub did not take.
68
+ */
69
+ export declare const GATEWAY_TOO_FAST = 4429;
70
+ /**
71
+ * The most characters of JSON a gateway's frame may hold. The gateway
72
+ * shrinks what an agent says to fit (`shrink`); the hub shrinks a bigger
73
+ * one itself. Either says how much was cut (`shrunk`).
74
+ */
75
+ export declare const MAX_FRAME: number;
76
+ /**
77
+ * A message as it fits `max` characters of JSON, and how many were cut:
78
+ * its longest strings are cut short (to a length all of them fit under,
79
+ * with "…" where they end); a message that still does not fit keeps only
80
+ * what names it (`jsonrpc`, `id`, `method`), its params or result null.
81
+ */
82
+ export declare function shrink(message: AcpMessage, max: number): {
83
+ message: AcpMessage;
84
+ shrunk: number;
85
+ };
86
+ /**
87
+ * Why the runtime closed a tab's socket. A tab it refuses gets a socket
88
+ * closed at once: signed out, no access, no such app (dial again only once
89
+ * that changes: the person signs in, is given access), a malformed request,
90
+ * or too many requests (dial again later). `expired`: the identity the tab
91
+ * connected with ran out; it dials again at once, with the fresh one the
92
+ * builder keeps, and has the rights that one gives.
93
+ */
94
+ export declare const TAB_CLOSE: {
95
+ readonly expired: 4000;
96
+ readonly badInput: 4400;
97
+ readonly unauthenticated: 4401;
98
+ readonly forbidden: 4403;
99
+ readonly notFound: 4404;
100
+ readonly rateLimited: 4429;
101
+ };
49
102
  /** Session ids, made by the hub: `ses` and 16 letters or digits. */
50
103
  export declare const SESSION_ID: RegExp;
51
104
  /** A JSON-RPC request id. */
@@ -320,6 +373,42 @@ export type AgentPlanOutcome = {
320
373
  };
321
374
  /** An answer to anything the agent asks the person: a permission, questions, a plan. */
322
375
  export type AgentAnswer = AcpPermissionOutcome | AgentQuestionOutcome | AgentPlanOutcome;
376
+ /**
377
+ * What the gateway's shims tell the hub an agent did, when the agent says
378
+ * it in words of its own beyond ACP: notifications in the session's ACP
379
+ * stream, where they happened.
380
+ */
381
+ export declare const NOTICE: {
382
+ /** The agent took a message sent while its turn ran (a `steer`) into that turn (SteeredNotice). */
383
+ readonly steered: "_teable/steered";
384
+ /** A background task of the agent's started, or ended (TaskNotice). */
385
+ readonly task: "_teable/task";
386
+ };
387
+ export interface SteeredNotice {
388
+ sessionId: string;
389
+ /** The id the hub gave the message, as for a `session/prompt`. */
390
+ request: JsonRpcId;
391
+ }
392
+ /**
393
+ * A background task an agent runs beyond its turn (a server, a long build),
394
+ * as it reports it: running, then finished (exit code 0) or failed (another
395
+ * exit code, or killed). While it runs, what it prints comes on the tool
396
+ * call that started it, when the agent says which (`toolCallId`).
397
+ */
398
+ export interface TaskNotice {
399
+ sessionId: string;
400
+ /** The agent's id for it. */
401
+ task: string;
402
+ /** What it runs, for people. */
403
+ title: string;
404
+ status: "running" | "finished" | "failed";
405
+ toolCallId: string | null;
406
+ /** What it printed, its end when long (TASK_OUTPUT); null while it runs. */
407
+ output: string | null;
408
+ exitCode: number | null;
409
+ }
410
+ /** The most of a finished task's output a TaskNotice holds: its last characters. */
411
+ export declare const TASK_OUTPUT = 8000;
323
412
  export declare function isAcpRequest(message: AcpMessage): message is AcpRequest;
324
413
  export declare function isAcpNotification(message: AcpMessage): message is AcpNotification;
325
414
  export declare function isAcpResponse(message: AcpMessage): message is AcpResponse;
@@ -336,10 +425,12 @@ export interface AgentCapabilities {
336
425
  /** Its name, for people. */
337
426
  title: string;
338
427
  /**
339
- * What happens to a message sent with `steer` while a turn runs: "steer"
340
- * puts it into the running turn; "interrupt" stops the turn and sends it next.
428
+ * What happens to a message sent with `steer` while a turn runs:
429
+ * "native", the agent takes it into the running turn (the gateway's shim
430
+ * sends it as the agent takes one); "interrupt", the hub stops the turn
431
+ * and the message runs next.
341
432
  */
342
- steering: "steer" | "interrupt";
433
+ steering: "native" | "interrupt";
343
434
  /** Whether it asks before acting (`session/request_permission`). */
344
435
  approvals: boolean;
345
436
  /** Whether it asks the person questions (ASK.question). */
@@ -348,7 +439,7 @@ export interface AgentCapabilities {
348
439
  planApproval: boolean;
349
440
  /** Whether it reports its plan (`plan` updates). */
350
441
  plans: boolean;
351
- /** Whether it runs background tasks that outlive a turn. */
442
+ /** Whether it runs background tasks that outlive a turn, and reports them (NOTICE.task). */
352
443
  backgroundTasks: boolean;
353
444
  /** Whether a session survives a restart of the agent or the sandbox (`session/load`). */
354
445
  resume: boolean;
@@ -363,6 +454,26 @@ export interface AgentCapabilities {
363
454
  export interface AcpFrame {
364
455
  session: string;
365
456
  acp: AcpMessage;
457
+ /** How many characters the gateway cut from the message to fit MAX_FRAME (`shrink`). */
458
+ shrunk?: number;
459
+ }
460
+ /**
461
+ * A frame the sender keeps until the other side says it has it, numbered
462
+ * in the order sent: by the gateway from 1 in each of its processes, by the
463
+ * hub on from where it got to, whichever gateway it talks to. A side takes
464
+ * a frame whose number it has seen already only to say again that it has it.
465
+ */
466
+ export type Numbered<T> = T & {
467
+ n: number;
468
+ };
469
+ /**
470
+ * Either side has every numbered frame up to `n` from the other, and keeps
471
+ * none of them any more. Not numbered: it is sent again with the next frame
472
+ * taken, or the next hello.
473
+ */
474
+ export interface Received {
475
+ type: "received";
476
+ n: number;
366
477
  }
367
478
  /** What the hub asks of the gateway. */
368
479
  export type HubControl =
@@ -384,38 +495,50 @@ export type HubControl =
384
495
  | {
385
496
  type: "close";
386
497
  session: string;
387
- };
388
- /** The hub sends nothing before the gateway's hello. */
389
- export type HubToGateway = AcpFrame | HubControl;
390
- /** A session the gateway runs an agent for. */
391
- export interface GatewaySession {
392
- session: string;
393
- /** The agent's own session id; null while the agent starts. */
394
- acpSessionId: string | null;
395
- /** The ids of the `session/prompt` requests its agent has not answered yet. */
396
- prompts: JsonRpcId[];
397
498
  }
398
- /** What the gateway tells the hub. */
399
- export type GatewayControl =
400
499
  /**
401
- * Sent on every connection, after what the gateway kept while it was
402
- * disconnected: the protocol it speaks, which gateway process this is
403
- * (`instance`) and its package version, its agents, and the sessions it
404
- * runs now. A session it does not list has no agent.
500
+ * Send a message into the session's running turn, to an agent that takes
501
+ * one natively (`steering: "native"`): the gateway's shim sends it as the
502
+ * agent does, under `request`. The agent takes it into the turn (and the
503
+ * shim says so: NOTICE.steered), or runs it as a turn of its own once the
504
+ * running one ends, answering `request` as a `session/prompt`.
405
505
  */
406
- {
506
+ | {
507
+ type: "steer";
508
+ session: string;
509
+ request: string;
510
+ prompt: AcpContentBlock[];
511
+ };
512
+ /**
513
+ * The hub sends nothing before the gateway's hello; then what the gateway
514
+ * has not taken yet of what it sent before, again, and on.
515
+ */
516
+ export type HubToGateway = Numbered<AcpFrame | HubControl> | Received;
517
+ /**
518
+ * The first frame on every connection: the protocol the gateway speaks
519
+ * (anything else first is an older gateway's, which the hub closes as
520
+ * unsupported), which gateway process this is (`instance`) and its package
521
+ * version, its agents, the last of the hub's frames it took (`received`)
522
+ * and the last it numbered itself (`sent`). Its own frames that the hub may
523
+ * lack follow, again. A process the hub has not met runs no agents: the
524
+ * turns of the one before end, and what the hub kept for it is void.
525
+ */
526
+ export interface GatewayHello {
407
527
  type: "hello";
408
528
  protocol: number;
409
529
  instance: string;
410
530
  version: string;
411
531
  agents: AgentCapabilities[];
412
- sessions: GatewaySession[];
532
+ received: number;
533
+ sent: number;
413
534
  }
535
+ /** What the gateway tells the hub of its sessions. */
536
+ export type GatewayControl =
414
537
  /**
415
538
  * The session's agent runs: it resumed the agent's session (`resumed`), or
416
539
  * started a new one, which knows nothing of the conversation before.
417
540
  */
418
- | {
541
+ {
419
542
  type: "opened";
420
543
  session: string;
421
544
  acpSessionId: string;
@@ -435,7 +558,7 @@ export type GatewayControl =
435
558
  session: string;
436
559
  message: string;
437
560
  };
438
- export type GatewayToHub = AcpFrame | GatewayControl;
561
+ export type GatewayToHub = GatewayHello | Numbered<AcpFrame | GatewayControl> | Received;
439
562
  /**
440
563
  * A command from a tab. `id` names it: any string the tab makes up, unique
441
564
  * among the person's commands, so that sending it again (after a reconnect)
@@ -461,18 +584,48 @@ export type TabOp =
461
584
  }
462
585
  /**
463
586
  * Send a message. While a turn runs it waits in the queue; with `steer`
464
- * it goes to the running turn instead, as the agent's `steering` says.
587
+ * it goes to the running turn now: an agent that steers natively takes it
588
+ * in (`steered`) unless the turn ends first, when it runs next; for any
589
+ * other, the turn stops and the message runs next.
465
590
  */
466
591
  | {
467
592
  type: "prompt";
468
593
  prompt: AcpContentBlock[];
469
594
  steer?: boolean;
470
595
  }
471
- /** Stop a turn: the running one, or a queued one by its number. */
596
+ /** Stop the running turn; `turn` names it, so that a stop meant for one that ended stops no other. */
472
597
  | {
473
598
  type: "cancel";
474
599
  turn?: number;
475
600
  }
601
+ /** Change a message that waits in the queue. */
602
+ | {
603
+ type: "edit";
604
+ turn: number;
605
+ prompt: AcpContentBlock[];
606
+ }
607
+ /** Take back a message that waits in the queue: it never runs. */
608
+ | {
609
+ type: "remove";
610
+ turn: number;
611
+ }
612
+ /** Run a message that waits in the queue next. */
613
+ | {
614
+ type: "front";
615
+ turn: number;
616
+ }
617
+ /**
618
+ * Close the session: what waits is taken back, a running turn is stopped
619
+ * and its agent too; it takes no more messages, and stays readable.
620
+ */
621
+ | {
622
+ type: "close";
623
+ }
624
+ /** Archive the session, closing it, or bring it back to the list (closed still). */
625
+ | {
626
+ type: "archive";
627
+ archived: boolean;
628
+ }
476
629
  /**
477
630
  * Answer what the agent asks the person (a permission, questions, a plan),
478
631
  * named by the `seq` of the event that asked, with the outcome its kind
@@ -484,10 +637,18 @@ export type TabOp =
484
637
  request: number;
485
638
  outcome: AgentAnswer;
486
639
  };
487
- /** Why a command was refused: malformed, not allowed, nothing to act on, or too late. */
488
- export type AgentErrorCode = "BAD_INPUT" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT";
640
+ /**
641
+ * Why a command was refused: malformed (a tab's own mistake), not this
642
+ * person's to do here, nothing to act on, what the agent asked was answered
643
+ * already or can no longer be, the turn has ended, the message went to the
644
+ * agent already (it no longer waits), the session is closed, the message is
645
+ * larger than MAX_FRAME, or the person's hub holds as much as it may. Tabs
646
+ * tell the person in their own words, by the code.
647
+ */
648
+ export type AgentErrorCode = "BAD_INPUT" | "FORBIDDEN" | "NOT_FOUND" | "ANSWERED" | "EXPIRED" | "ENDED" | "STARTED" | "CLOSED" | "TOO_LARGE" | "FULL";
489
649
  export interface AgentError {
490
650
  code: AgentErrorCode;
651
+ /** For people reading logs, in English. */
491
652
  message: string;
492
653
  }
493
654
  /** The answer to a command, sent once per command id to the tab that sent it. */
@@ -527,6 +688,10 @@ export interface SessionInfo {
527
688
  queued: number[];
528
689
  /** What the agent asks the person and waits for an answer to, by the `seq` of the event that asked. */
529
690
  requests: number[];
691
+ /** It takes no more messages. */
692
+ closed: boolean;
693
+ /** It is left out of the list a person picks from. */
694
+ archived: boolean;
530
695
  lastSeq: number;
531
696
  }
532
697
  /** Something that happened in a session: stored, numbered and sent to every tab of its app. */
@@ -559,6 +724,26 @@ export type SessionEvent = {
559
724
  type: "acp";
560
725
  turn: number | null;
561
726
  acp: AcpMessage;
727
+ /** How many characters were cut from it to keep it under MAX_FRAME. */
728
+ shrunk?: number;
729
+ }
730
+ /**
731
+ * A background task of the agent's (TaskNotice, less its session):
732
+ * started, or ended, as the agent reports it. Each report of the same
733
+ * `task` stands for the one before.
734
+ */
735
+ | ({
736
+ type: "task";
737
+ } & Omit<TaskNotice, "sessionId">)
738
+ /**
739
+ * The hub would not take more of what the agent sends: the session holds
740
+ * as much as one may (`session`: it is closed), or the person's hub does
741
+ * (`hub`: the turn stops, and no new message is taken); or the gateway
742
+ * sent too fast (`rate`), and was made to send again more slowly.
743
+ */
744
+ | {
745
+ type: "limited";
746
+ limit: "session" | "hub" | "rate";
562
747
  }
563
748
  /**
564
749
  * What the agent asked (the `seq` of its event) was answered, by `by`. The
@@ -580,6 +765,45 @@ export type SessionEvent = {
580
765
  type: "expired";
581
766
  request: number;
582
767
  }
768
+ /** A message that waits was changed. */
769
+ | {
770
+ type: "edited";
771
+ turn: number;
772
+ by: string;
773
+ prompt: AcpContentBlock[];
774
+ }
775
+ /** A message that waited was taken back: it never runs. */
776
+ | {
777
+ type: "removed";
778
+ turn: number;
779
+ by: string;
780
+ }
781
+ /** A message that waits runs next. */
782
+ | {
783
+ type: "moved";
784
+ turn: number;
785
+ by: string;
786
+ }
787
+ /**
788
+ * The message of `turn`, sent to steer, went into the running turn
789
+ * `into`: it is part of that turn from here, and `turn` never runs.
790
+ */
791
+ | {
792
+ type: "steered";
793
+ turn: number;
794
+ into: number;
795
+ }
796
+ /** The session was closed: it takes no more messages. */
797
+ | {
798
+ type: "closed";
799
+ by: string;
800
+ }
801
+ /** The session was archived, or brought back to the list. */
802
+ | {
803
+ type: "archived";
804
+ archived: boolean;
805
+ by: string;
806
+ }
583
807
  /** Someone asked to stop the turn; it ends with `turn_ended`. */
584
808
  | {
585
809
  type: "cancel_requested";
@@ -613,15 +837,38 @@ export interface TabEvent {
613
837
  /** When the hub stored it, in milliseconds since the epoch. */
614
838
  at: number;
615
839
  event: SessionEvent;
840
+ /**
841
+ * It stands for the session's events from this `seq` to its own, which
842
+ * the hub folded into it when their turn ended: a run of the agent's
843
+ * message or thought chunks, joined, or of one tool call's updates,
844
+ * merged. A tab that has some of them puts this in their place.
845
+ */
846
+ folds?: number;
616
847
  }
848
+ /**
849
+ * What a tab asks of the hub besides commands: a session's events before
850
+ * `before` (the first it has; null for the latest), the newest page of them.
851
+ */
852
+ export interface HistoryRequest {
853
+ type: "history";
854
+ session: string;
855
+ before: number | null;
856
+ }
857
+ export type TabToHub = TabCommand | HistoryRequest;
617
858
  export type HubToTab = TabEvent | Ack
618
859
  /**
619
860
  * First on every connection: this app's sessions as they are, whether a
620
861
  * gateway is connected, whether this person may start sessions, prompt
621
- * and answer what the agent asks here (`canPrompt`), and the latest `seq`
622
- * (of any app's). Events after the tab's `since` follow, up to that `seq`,
623
- * then live ones. Reconnect with `since` the larger of that `seq` and the
624
- * last event's.
862
+ * and answer what the agent asks here (`canPrompt`), the latest `seq` (of
863
+ * any app's), and what the replay that follows holds, up to that `seq`:
864
+ * - `since`: every event of the app after the tab's `since`, which joins
865
+ * on to what it has;
866
+ * - `latest`: the latest events of `session` (the one the tab shows, else
867
+ * the app's newest; null when it has none), as `history` would give
868
+ * them, when the tab has nothing (`since` 0) or would get too many.
869
+ * The tab drops the events it had; older ones, and other sessions'
870
+ * events before the snapshot, come when it asks.
871
+ * Then `replayed`, then live events.
625
872
  */
626
873
  | {
627
874
  type: "snapshot";
@@ -629,6 +876,27 @@ export type HubToTab = TabEvent | Ack
629
876
  canPrompt: boolean;
630
877
  gateway: GatewayStatus;
631
878
  sessions: SessionInfo[];
879
+ replay: "since" | "latest";
880
+ session: string | null;
881
+ }
882
+ /**
883
+ * The replay after the snapshot is whole. Dial again with `since` the
884
+ * larger of the snapshot's `seq` and the last event's; before this, with
885
+ * the last event's (or 0, after a `latest` replay).
886
+ */
887
+ | {
888
+ type: "replayed";
889
+ }
890
+ /**
891
+ * The answer to a HistoryRequest: the session's newest events before
892
+ * `before`, at most a page, oldest first; none when there are none. A
893
+ * session's first event is `created`.
894
+ */
895
+ | {
896
+ type: "history";
897
+ session: string;
898
+ before: number | null;
899
+ events: TabEvent[];
632
900
  }
633
901
  /** The gateway connected or went away. */
634
902
  | {
package/dist/protocol.js CHANGED
@@ -5,13 +5,19 @@ import {
5
5
  ASK,
6
6
  GATEWAY_CLOSE,
7
7
  GATEWAY_PATH,
8
+ GATEWAY_TOO_FAST,
9
+ MAX_FRAME,
10
+ NOTICE,
8
11
  PING,
9
12
  PONG,
10
13
  SESSION_ID,
14
+ TAB_CLOSE,
15
+ TASK_OUTPUT,
11
16
  isAcpNotification,
12
17
  isAcpRequest,
13
- isAcpResponse
14
- } from "./chunks/CYVXAHGU.js";
18
+ isAcpResponse,
19
+ shrink
20
+ } from "./chunks/XGVR5ONA.js";
15
21
  export {
16
22
  ACP,
17
23
  AGENT_NAMES,
@@ -19,10 +25,16 @@ export {
19
25
  ASK,
20
26
  GATEWAY_CLOSE,
21
27
  GATEWAY_PATH,
28
+ GATEWAY_TOO_FAST,
29
+ MAX_FRAME,
30
+ NOTICE,
22
31
  PING,
23
32
  PONG,
24
33
  SESSION_ID,
34
+ TAB_CLOSE,
35
+ TASK_OUTPUT,
25
36
  isAcpNotification,
26
37
  isAcpRequest,
27
- isAcpResponse
38
+ isAcpResponse,
39
+ shrink
28
40
  };
package/dist/shims.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * that the protocol has one word for. Each agent's record (agents.ts) names
4
4
  * its shims; this is the only code that knows an agent's vendor extensions.
5
5
  */
6
- import { type AgentPlanRequest, type AgentQuestionRequest, ASK } from "./protocol.js";
6
+ import { type AcpNotification, type AgentPlanRequest, type AgentQuestionRequest, ASK, type JsonRpcId } from "./protocol.js";
7
7
  /**
8
8
  * A vendor request with which an agent asks the person: relayed to the hub
9
9
  * as the protocol's request (ASK), under the agent's own id, and the answer,
@@ -16,5 +16,23 @@ export interface AskShim {
16
16
  /** The agent's result, from the answer and the params it asked with. */
17
17
  result(answer: unknown, params: unknown): unknown;
18
18
  }
19
+ /** What a notice shim may learn of, and do to, the agent process it reads for. */
20
+ interface NoticeContext {
21
+ /**
22
+ * The agent took the oldest message sent to steer its running turn into
23
+ * it: its id, which is no longer answered; null when none was sent.
24
+ */
25
+ steered(): JsonRpcId | null;
26
+ }
27
+ /**
28
+ * A vendor notification with which an agent says something the protocol
29
+ * has words for: the protocol's notifications for it (none, to drop it).
30
+ */
31
+ export interface NoticeShim {
32
+ notices(params: unknown, context: NoticeContext): AcpNotification[];
33
+ }
19
34
  /** grok-build's requests that ask the person, by method. */
20
35
  export declare const GROK_ASKS: Readonly<Record<string, AskShim>>;
36
+ /** grok-build's notifications the protocol has words for, by method. */
37
+ export declare const GROK_NOTICES: Readonly<Record<string, NoticeShim>>;
38
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teable/agent-gateway",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "The agent gateway in a person's Teable sandbox: starts an ACP agent for each session and relays it to the person's hub",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,47 +0,0 @@
1
- // src/protocol.ts
2
- var GATEWAY_PATH = "/api/v4/agent/gateway";
3
- var AGENT_PROTOCOL = 1;
4
- var PING = "ping";
5
- var PONG = "pong";
6
- var GATEWAY_CLOSE = { replaced: 4e3, expired: 4001, unsupported: 4002 };
7
- var SESSION_ID = /^ses[0-9A-Za-z]{16}$/;
8
- var ACP = {
9
- initialize: "initialize",
10
- newSession: "session/new",
11
- loadSession: "session/load",
12
- prompt: "session/prompt",
13
- cancel: "session/cancel",
14
- update: "session/update",
15
- requestPermission: "session/request_permission"
16
- };
17
- var ASK = {
18
- /** Questions for the person (AgentQuestionRequest), answered with an AgentQuestionOutcome. */
19
- question: "_teable/question",
20
- /** A plan for the person to approve before the agent acts on it (AgentPlanRequest), answered with an AgentPlanOutcome. */
21
- plan: "_teable/plan"
22
- };
23
- function isAcpRequest(message) {
24
- return "method" in message && "id" in message;
25
- }
26
- function isAcpNotification(message) {
27
- return "method" in message && !("id" in message);
28
- }
29
- function isAcpResponse(message) {
30
- return !("method" in message) && "id" in message;
31
- }
32
- var AGENT_NAMES = ["grok"];
33
-
34
- export {
35
- GATEWAY_PATH,
36
- AGENT_PROTOCOL,
37
- PING,
38
- PONG,
39
- GATEWAY_CLOSE,
40
- SESSION_ID,
41
- ACP,
42
- ASK,
43
- isAcpRequest,
44
- isAcpNotification,
45
- isAcpResponse,
46
- AGENT_NAMES
47
- };