@fastagent-sh/fastagent 0.19.0 → 0.20.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.
Files changed (131) hide show
  1. package/dist/atomic-write.d.ts +11 -7
  2. package/dist/atomic-write.js +16 -11
  3. package/dist/channels/agentcore-limits.d.ts +9 -0
  4. package/dist/channels/agentcore-limits.js +9 -0
  5. package/dist/channels/agentcore-service.d.ts +12 -11
  6. package/dist/channels/agentcore-service.js +14 -18
  7. package/dist/channels/agentcore.d.ts +11 -19
  8. package/dist/channels/agentcore.js +14 -7
  9. package/dist/channels/control.d.ts +50 -12
  10. package/dist/channels/control.js +239 -96
  11. package/dist/channels/discover.d.ts +26 -4
  12. package/dist/channels/discover.js +12 -23
  13. package/dist/channels/feishu/feishu-api.js +5 -8
  14. package/dist/channels/feishu/feishu.js +35 -18
  15. package/dist/channels/kit/attachment-path.d.ts +12 -0
  16. package/dist/channels/kit/attachment-path.js +43 -0
  17. package/dist/channels/kit/context-buffer.d.ts +9 -0
  18. package/dist/channels/kit/context-buffer.js +11 -0
  19. package/dist/channels/kit/signature.d.ts +12 -0
  20. package/dist/channels/kit/signature.js +17 -0
  21. package/dist/channels/kit/stop-command.js +3 -3
  22. package/dist/channels/kit/tasks.d.ts +1 -1
  23. package/dist/channels/kit/tasks.js +10 -4
  24. package/dist/channels/kit/turn-store.d.ts +19 -3
  25. package/dist/channels/kit/turn-store.js +29 -2
  26. package/dist/channels/slack/invoke-turn.d.ts +1 -1
  27. package/dist/channels/slack/invoke-turn.js +5 -1
  28. package/dist/channels/slack/onboard.js +5 -5
  29. package/dist/channels/slack/onboarding-state.d.ts +7 -3
  30. package/dist/channels/slack/onboarding-state.js +13 -20
  31. package/dist/channels/slack/register-webhook.js +1 -1
  32. package/dist/channels/slack/scaffold/slack-send.ts +2 -17
  33. package/dist/channels/slack/slack-api.js +22 -54
  34. package/dist/channels/slack/slack.js +13 -13
  35. package/dist/channels/telegram/parse.d.ts +21 -1
  36. package/dist/channels/telegram/parse.js +65 -11
  37. package/dist/channels/telegram/scaffold/channel.ts +7 -3
  38. package/dist/channels/telegram/telegram-api.js +5 -6
  39. package/dist/channels/telegram/telegram.d.ts +2 -2
  40. package/dist/channels/telegram/telegram.js +57 -69
  41. package/dist/cli/add-slack.js +6 -5
  42. package/dist/cli/commands/add.js +1 -5
  43. package/dist/cli/commands/attach.d.ts +2 -4
  44. package/dist/cli/commands/attach.js +17 -15
  45. package/dist/cli/commands/deploy.d.ts +50 -5
  46. package/dist/cli/commands/deploy.js +183 -134
  47. package/dist/cli/commands/dev.js +4 -31
  48. package/dist/cli/commands/info.js +1 -2
  49. package/dist/cli/commands/init.js +1 -2
  50. package/dist/cli/commands/start.js +31 -41
  51. package/dist/cli/serve.d.ts +12 -21
  52. package/dist/cli/serve.js +20 -25
  53. package/dist/cli/shared.d.ts +40 -10
  54. package/dist/cli/shared.js +51 -4
  55. package/dist/deploy/agentcore/logs.d.ts +2 -2
  56. package/dist/deploy/agentcore/logs.js +2 -2
  57. package/dist/deploy/agentcore/plan.d.ts +12 -10
  58. package/dist/deploy/agentcore/plan.js +39 -31
  59. package/dist/deploy/agentcore/run.d.ts +5 -4
  60. package/dist/deploy/agentcore/run.js +13 -36
  61. package/dist/deploy/channel-ingress.d.ts +73 -0
  62. package/dist/deploy/channel-ingress.js +101 -0
  63. package/dist/deploy/docker/plan.d.ts +3 -7
  64. package/dist/deploy/docker/plan.js +4 -15
  65. package/dist/deploy/docker/run.d.ts +18 -1
  66. package/dist/deploy/docker/run.js +10 -0
  67. package/dist/deploy/fly/plan.d.ts +4 -5
  68. package/dist/deploy/fly/plan.js +7 -22
  69. package/dist/deploy/fly/run.d.ts +9 -23
  70. package/dist/deploy/fly/run.js +32 -68
  71. package/dist/deploy/preflight.d.ts +6 -7
  72. package/dist/deploy/preflight.js +26 -22
  73. package/dist/deploy/railway/plan.d.ts +4 -5
  74. package/dist/deploy/railway/plan.js +11 -26
  75. package/dist/deploy/railway/run.d.ts +9 -9
  76. package/dist/deploy/railway/run.js +40 -40
  77. package/dist/deploy/runner.js +22 -2
  78. package/dist/deploy/secrets.d.ts +18 -9
  79. package/dist/deploy/secrets.js +64 -12
  80. package/dist/dev-supervisor.js +3 -4
  81. package/dist/engines/pi/agent-session-factory.js +20 -39
  82. package/dist/engines/pi/auth.js +43 -43
  83. package/dist/engines/pi/config.d.ts +1 -1
  84. package/dist/engines/pi/create.d.ts +14 -2
  85. package/dist/engines/pi/create.js +2 -2
  86. package/dist/engines/pi/definition.d.ts +1 -1
  87. package/dist/engines/pi/definition.js +3 -4
  88. package/dist/engines/pi/login.js +32 -16
  89. package/dist/engines/pi/open.d.ts +1 -2
  90. package/dist/engines/pi/open.js +1 -1
  91. package/dist/engines/pi/search-tools.js +1 -1
  92. package/dist/engines/pi/service.d.ts +1 -1
  93. package/dist/engines/pi/service.js +8 -0
  94. package/dist/engines/pi/session-builder.js +6 -33
  95. package/dist/engines/pi/session-control.d.ts +19 -6
  96. package/dist/engines/pi/session-control.js +565 -470
  97. package/dist/engines/pi/session-inheritance.d.ts +8 -22
  98. package/dist/engines/pi/session-inheritance.js +95 -76
  99. package/dist/engines/pi/session-markers.d.ts +48 -0
  100. package/dist/engines/pi/session-markers.js +59 -0
  101. package/dist/engines/pi/session-settings.d.ts +4 -4
  102. package/dist/engines/pi/session-settings.js +7 -4
  103. package/dist/engines/pi/session-store.d.ts +83 -13
  104. package/dist/engines/pi/session-store.js +408 -55
  105. package/dist/engines/pi/tool-context.d.ts +21 -8
  106. package/dist/engines/pi/tool-context.js +29 -4
  107. package/dist/engines/pi/tool.js +2 -2
  108. package/dist/env.js +1 -2
  109. package/dist/loader.d.ts +49 -7
  110. package/dist/loader.js +79 -18
  111. package/dist/paths.d.ts +19 -0
  112. package/dist/paths.js +27 -2
  113. package/dist/scaffold/add-channel.js +2 -2
  114. package/dist/scaffold/init.js +7 -2
  115. package/dist/scaffold/templates/tools/fetch-url.ts +0 -2
  116. package/dist/schedule/discover.js +3 -15
  117. package/dist/schedule/wake-alarm.d.ts +13 -7
  118. package/dist/schedule/wake-alarm.js +88 -46
  119. package/dist/schedule/wakeups.d.ts +1 -1
  120. package/dist/schedule/wakeups.js +10 -7
  121. package/dist/service.d.ts +1 -2
  122. package/dist/service.js +27 -5
  123. package/dist/session-remote.d.ts +7 -2
  124. package/dist/session-remote.js +162 -92
  125. package/dist/session.d.ts +226 -92
  126. package/dist/session.js +61 -23
  127. package/dist/telegram.d.ts +1 -1
  128. package/dist/telegram.js +1 -1
  129. package/dist/tunnel.d.ts +18 -3
  130. package/dist/tunnel.js +32 -40
  131. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { INVALID_COMMAND_CODE } from "../session.js";
1
+ import { INVALID_COMMAND_CODE, SESSIONS_UNAVAILABLE_CODE, UNSUPPORTED_CAPABILITY_CODE, UPDATE_FIELDS, } from "../session.js";
2
2
  import { timingSafeEqual } from "node:crypto";
3
3
  import { parseRouteKey, withoutBody } from "./serve.js";
4
4
  import { log } from "../log.js";
@@ -7,6 +7,14 @@ import { MAX_BODY_BYTES, createInvokeHandler, sseHeartbeat } from "./http.js";
7
7
  import { text } from "./respond.js";
8
8
  /** The prefix this plane OWNS: everything under it is the plane's to answer. */
9
9
  const CONTROL_PREFIX = "/control";
10
+ /** The one variable segment in this plane's paths: a percent-encoded session id. Written into route
11
+ * keys so the table reads like the URLs it serves. */
12
+ const SESSION_SEGMENT = "{session}";
13
+ /** The token, when the DEPLOYER owns it rather than the box (`mountSessionControl` reads it, `deploy`
14
+ * carries it). Declared here with the prefix because both are the plane's public names: the serving
15
+ * side and the deploy side must spell it identically, and a rename that hits only one of them fails
16
+ * silently — the box mints its own and every caller the runbook told gets a 401. */
17
+ export const CONTROL_TOKEN_ENV = "FASTAGENT_CONTROL_TOKEN";
10
18
  const json = (value, status = 200) => new Response(`${JSON.stringify(value)}\n`, { status, headers: { "content-type": "application/json" } });
11
19
  /**
12
20
  * The plane as one mounted sub-application rather than routes sharing a prefix.
@@ -26,23 +34,58 @@ const json = (value, status = 200) => new Response(`${JSON.stringify(value)}\n`,
26
34
  * the WRITE routes unreachable while reads work.
27
35
  */
28
36
  function planeApp(routes) {
29
- // Normalised keys (see serve.ts): the method is upper-cased when parsed.
30
- const byKey = new Map(Object.entries(routes).map(([key, handler]) => {
37
+ /** A route key's path split into segments, with `{session}` marked. Paths are matched SEGMENT BY
38
+ * SEGMENT rather than by regex because a session id is an opaque Caller string: percent-encoded
39
+ * it can contain anything, and `URL.pathname` leaves `%2F` encoded — so splitting on `/` cannot
40
+ * be fooled by an id that contains one. */
41
+ const compiled = Object.entries(routes).map(([key, handler]) => {
31
42
  const { method, path } = parseRouteKey(key);
32
- return [method ? `${method} ${path}` : path, handler];
33
- }));
34
- const methodsByPath = new Map();
35
- for (const key of Object.keys(routes)) {
36
- const { method, path } = parseRouteKey(key);
37
- const methods = methodsByPath.get(path) ?? new Set();
38
- if (method)
39
- methods.add(method);
40
- methodsByPath.set(path, methods);
41
- }
43
+ return { method, path, segments: path.split("/"), handler };
44
+ });
45
+ const match = (path) => {
46
+ const segments = path.split("/");
47
+ const hits = [];
48
+ for (const route of compiled) {
49
+ if (route.segments.length !== segments.length)
50
+ continue;
51
+ let session;
52
+ let ok = true;
53
+ for (const [i, expected] of route.segments.entries()) {
54
+ const actual = segments[i];
55
+ if (expected === SESSION_SEGMENT) {
56
+ // The one place a path segment becomes a Caller id again. An empty segment is not an id —
57
+ // it would address a session no other call can name.
58
+ if (actual === "") {
59
+ ok = false;
60
+ break;
61
+ }
62
+ try {
63
+ session = decodeURIComponent(actual);
64
+ }
65
+ catch {
66
+ // `%zz` and friends: not an id any client could have produced, so this path matches
67
+ // nothing and falls through to the plane's own 404. Decoding runs BEFORE the try that
68
+ // guards the handlers, so letting it throw would leave the boundary entirely — no CORS
69
+ // headers, no log line, and a rejected promise for an embedder mounting this handler
70
+ // directly. The query-parameter form this replaced decoded leniently and could not.
71
+ ok = false;
72
+ break;
73
+ }
74
+ }
75
+ else if (expected !== actual) {
76
+ ok = false;
77
+ break;
78
+ }
79
+ }
80
+ if (ok)
81
+ hits.push({ route, session });
82
+ }
83
+ return hits;
84
+ };
42
85
  // Per PATH, stating what it actually serves — omitting a method it does serve has the browser
43
86
  // refuse a call that would have worked. `HEAD` is that case: every GET route answers it.
44
- const allowMethods = (path, requested) => {
45
- const methods = new Set(methodsByPath.get(path) ?? []);
87
+ const allowMethods = (hits, requested) => {
88
+ const methods = new Set(hits.flatMap((h) => (h.route.method ? [h.route.method] : [])));
46
89
  if (methods.has("GET"))
47
90
  methods.add("HEAD");
48
91
  // The requested method is always allowed, even where this path does not serve it: preflight is a
@@ -55,22 +98,18 @@ function planeApp(routes) {
55
98
  };
56
99
  return async (req) => {
57
100
  const path = new URL(req.url).pathname;
58
- const known = methodsByPath.has(path);
101
+ const hits = match(path);
59
102
  const answer = async () => {
60
103
  // A preflight carries no token — that is its purpose — so it is answered before auth, and for
61
104
  // ANY path under the prefix: gating it would stop the request the 404 below is waiting for.
62
105
  if (req.method === "OPTIONS")
63
106
  return new Response(null, { status: 204 });
64
- const handler = byKey.get(`${req.method} ${path}`) ?? byKey.get(path);
65
- if (handler)
66
- return await handler(req);
67
- if (known && req.method === "HEAD") {
68
- const get = byKey.get(`GET ${path}`);
69
- if (get)
70
- return await get(req);
71
- }
107
+ const hit = hits.find((h) => h.route.method === req.method) ??
108
+ (req.method === "HEAD" ? hits.find((h) => h.route.method === "GET") : undefined);
109
+ if (hit)
110
+ return await hit.route.handler(req, hit.session ?? "");
72
111
  // 404 vs 405 as in the host router: a client reads 404 as "this serve predates the route".
73
- if (known)
112
+ if (hits.length > 0)
74
113
  return text("method not allowed\n", 405);
75
114
  return text("not found\n", 404);
76
115
  };
@@ -89,34 +128,31 @@ function planeApp(routes) {
89
128
  // THE single exit. Every reply above — route, preflight, 404, 405, 500 — leaves through here.
90
129
  res.headers.set("access-control-allow-origin", "*");
91
130
  res.headers.set("access-control-allow-headers", "authorization, content-type");
92
- res.headers.set("access-control-allow-methods", allowMethods(path, req.headers.get("access-control-request-method")));
131
+ res.headers.set("access-control-allow-methods", allowMethods(hits, req.headers.get("access-control-request-method")));
93
132
  return res;
94
133
  };
95
134
  }
96
135
  // ONE constant for every Prompt-bearing wire surface (imported from the invoke channel — the two
97
- // caps cannot drift apart): commands carry Prompts, which may ride base64 images.
98
- const DISPATCH_BODY_LIMIT = MAX_BODY_BYTES;
136
+ // caps cannot drift apart): actions carry Prompts, which may ride base64 images.
137
+ const ACTION_BODY_LIMIT = MAX_BODY_BYTES;
99
138
  /**
100
139
  * Parse-don't-validate at the wire: a remote client can send any JSON, and the hub's inner layers
101
- * trust command shapes (a malformed `steer` would surface as an ENGINE failure misclassified as
102
- * `run_command_failed`). Returns the typed command, or undefined for anything malformed — which
140
+ * trust action shapes (a malformed `steer` would surface as an ENGINE failure misclassified as
141
+ * `run_command_failed`). Returns the typed action, or undefined for anything malformed — which
103
142
  * answers protocol-level `invalid_command`, same responsibility as the hub's unknown-type default.
104
143
  */
105
- function parseWireCommand(raw) {
106
- // COMPILE-TIME drift guard, variant level: this switch hand-mirrors the SessionCommand union,
107
- // and a new variant added in session.ts would otherwise compile clean while the wire answers it
144
+ function parseWireAction(raw) {
145
+ // COMPILE-TIME drift guard, variant level: this switch hand-mirrors the SessionAction union, and a
146
+ // new variant added in session.ts would otherwise compile clean while the wire answers it
108
147
  // `invalid_command` — silently breaking local/remote isomorphism. A new variant must break THIS
109
148
  // line first, forcing the decision of how the wire carries it.
110
- const _commandDriftGuard = {
149
+ const _actionDriftGuard = {
111
150
  steer: true,
112
151
  follow_up: true,
113
152
  abort: true,
114
153
  compact: true,
115
- set_model: true,
116
- set_thinking: true,
117
- navigate: true,
118
154
  };
119
- void _commandDriftGuard;
155
+ void _actionDriftGuard;
120
156
  if (typeof raw !== "object" || raw === null)
121
157
  return undefined;
122
158
  const c = raw;
@@ -134,8 +170,8 @@ function parseWireCommand(raw) {
134
170
  // failure this parser exists to prevent (ImageRef shape from src/session.ts's Prompt).
135
171
  return images === undefined || (Array.isArray(images) && images.every(imageOk));
136
172
  };
137
- // REBUILD, never pass raw through: "typed command out" must be construction, not assertion — a
138
- // passed-through object would carry arbitrary extra keys into the engine.
173
+ // REBUILD, never pass raw through: "typed out" must be construction, not assertion — a passed-
174
+ // through object would carry arbitrary extra keys into the engine.
139
175
  const rebuildPrompt = (p) => {
140
176
  const images = p.images;
141
177
  return {
@@ -162,33 +198,69 @@ function parseWireCommand(raw) {
162
198
  return c.instructions === undefined || typeof c.instructions === "string"
163
199
  ? { type: "compact", instructions: c.instructions }
164
200
  : undefined;
165
- case "set_model":
166
- return typeof c.model === "string" ? { type: "set_model", model: c.model } : undefined;
167
- case "set_thinking":
168
- return typeof c.level === "string" ? { type: "set_thinking", level: c.level } : undefined;
169
- case "navigate":
170
- return typeof c.targetId === "string" ? { type: "navigate", targetId: c.targetId } : undefined;
171
201
  default:
172
202
  return undefined;
173
203
  }
174
204
  }
175
205
  /**
176
- * Create the control plane as a mountable prefix owner: `GET
177
- * /control/capabilities|commands|state|entries|events` + `POST /control/dispatch`, all
178
- * bearer-authenticated. `events` streams SSE (`data: <WireEvent>` lines).
179
- * The plane OWNS {@link CONTROL_PREFIX}: it is mounted as one sub-application, answers its own
180
- * 404/405/preflight, and puts CORS headers on every reply see {@link planeApp}.
206
+ * Parse a PATCH body into a session update or into the REASON it is not one, because the two
207
+ * reasons are different answers to the client. An unknown KEY means this serve does not have that
208
+ * field (a newer client talking to an older serve, or a typo), and the client's move is to drop it:
209
+ * `unsupported_capability`, the same code the in-process path answers, so the two planes stay
210
+ * isomorphic. A wrong VALUE TYPE is a malformed payload: `invalid_command`. Neither is dropped
211
+ * silently, which would answer `ok: true` for a patch that set nothing.
212
+ */
213
+ function parseWireUpdate(raw) {
214
+ if (typeof raw !== "object" || raw === null) {
215
+ return { code: INVALID_COMMAND_CODE, message: "expected an object of session properties" };
216
+ }
217
+ const c = raw;
218
+ const unknown = Object.keys(c).filter((key) => !UPDATE_FIELDS.includes(key));
219
+ if (unknown.length > 0) {
220
+ return {
221
+ code: UNSUPPORTED_CAPABILITY_CODE,
222
+ message: `update field(s) ${unknown.join(", ")} — capabilities().updatable lists what this serve sets`,
223
+ };
224
+ }
225
+ const patch = {};
226
+ // The field list is the CONTRACT's (`UPDATE_FIELDS`), not a copy: a field added to SessionUpdate
227
+ // travels here without anyone remembering to, and one removed cannot linger.
228
+ for (const field of UPDATE_FIELDS) {
229
+ const value = c[field];
230
+ if (value === undefined)
231
+ continue;
232
+ if (typeof value !== "string") {
233
+ return { code: INVALID_COMMAND_CODE, message: `${field} must be a string` };
234
+ }
235
+ patch[field] = value;
236
+ }
237
+ return { patch };
238
+ }
239
+ /**
240
+ * Create the control plane as a mountable prefix owner — a RESTful surface over
241
+ * {@link CONTROL_PREFIX}: sessions are a collection, a session is a resource, its history and event
242
+ * stream are sub-resources, and the things that HAPPEN to a run are posted to `…/actions`.
243
+ * The plane OWNS the prefix: it answers its own 404/405/preflight and puts CORS headers on every
244
+ * reply — see {@link planeApp}.
181
245
  */
182
246
  export function createControlPlane(control, options) {
183
247
  return mountControlPlane(controlPlaneRoutes(control, options));
184
248
  }
185
249
  /** Mount a plane route table as a {@link PrefixMount} — the plane owns a PREFIX, while a route
186
- * table is a set of literal paths. */
250
+ * table is a set of paths, at most one segment of which is a session id. */
187
251
  export function mountControlPlane(routes) {
188
252
  return { prefix: CONTROL_PREFIX, handler: planeApp(routes) };
189
253
  }
190
- /** The plane's route table. Exported so the conformance sweeps derive their route list from what is
191
- * actually mounted, rather than from a hand-kept copy that cannot notice a new route. */
254
+ /**
255
+ * The plane's route table. Exported so the conformance sweeps derive their route list from what is
256
+ * actually mounted, rather than from a hand-kept copy that cannot notice a new route.
257
+ *
258
+ * The shape mirrors the contract: a collection, a resource, its sub-resources, and one action
259
+ * endpoint. What a session IS gets `GET`; what a session HAS gets `PATCH` (properties, last-wins);
260
+ * what happens TO a run gets `POST …/actions` (not a property — an event in time). `PUT` on a
261
+ * session id is the fork, and it is a PUT because a fork is idempotent by construction: the id is
262
+ * the caller's, the body says where the history came from, and repeating it changes nothing.
263
+ */
192
264
  export function controlPlaneRoutes(control, options) {
193
265
  const { token } = options;
194
266
  if (!token)
@@ -202,66 +274,137 @@ export function controlPlaneRoutes(control, options) {
202
274
  return header.length === expected.length && timingSafeEqual(header, expected);
203
275
  };
204
276
  const invokeHandler = options.agent ? createInvokeHandler(options.agent) : undefined;
205
- /** Wrap a handler with auth + the session query param most routes need. */
206
- const guard = (handler) => (req) => {
277
+ /** Authenticate, then hand the handler the pieces every route wants: the request, the URL (for
278
+ * query parameters), and the session the PATH named — `""` on the routes that have no id in
279
+ * them, which those handlers never read. */
280
+ const guard = (handler) => (req, session) => {
207
281
  if (!authed(req))
208
282
  return text("unauthorized\n", 401);
209
- return handler(req, new URL(req.url));
283
+ return handler(req, new URL(req.url), session);
284
+ };
285
+ /** Read a JSON body under the shared cap. Answers the Response to send on failure, so a route can
286
+ * `if ("error" in read) return read.error`. */
287
+ const readJson = async (req) => {
288
+ const body = await readBodyCapped(req, ACTION_BODY_LIMIT);
289
+ // The 413 names the ceiling: the docs promise images on this plane, and an unexplained
290
+ // rejection would send a client author hunting everywhere but the cap. Derived from the
291
+ // constant — a hardcoded "1 MiB" would lie the day the cap changes.
292
+ if ("tooLarge" in body) {
293
+ return {
294
+ error: text(`body too large (limit ${MAX_BODY_BYTES >> 20} MiB — images count base64-inflated)\n`, 413),
295
+ };
296
+ }
297
+ // An empty body is an empty object: `POST …/actions` always carries one, but `PATCH` with
298
+ // nothing to set is a legal no-op and a client should not have to send `{}` to say so.
299
+ if (body.text.trim() === "")
300
+ return { value: {} };
301
+ try {
302
+ return { value: JSON.parse(body.text) };
303
+ }
304
+ catch {
305
+ return { error: text("invalid JSON\n", 400) };
306
+ }
210
307
  };
211
- // Extraction only — each route still answers its own 400 (the name must not imply enforcement).
212
- const sessionParam = (url) => url.searchParams.get("session") ?? undefined;
213
308
  return {
309
+ // The DATA plane, at the prefix rather than under a session: its body already carries the scope
310
+ // (SPEC `invoke(scope, prompt)`), so a session in the path would be a second place to say it —
311
+ // and two places to say one thing is a place for them to disagree.
214
312
  ...(invokeHandler ? { "POST /control/invoke": guard((req) => invokeHandler(req)) } : {}),
215
313
  "GET /control/capabilities": guard(() => json(control.capabilities())),
216
314
  "GET /control/commands": guard(async () => json(await control.commands())),
217
- "GET /control/state": guard(async (_req, url) => {
218
- const session = sessionParam(url);
219
- if (!session)
220
- return text("missing ?session\n", 400);
221
- return json(await control.state(session));
222
- }),
223
- "GET /control/entries": guard(async (_req, url) => {
224
- const session = sessionParam(url);
225
- if (!session)
226
- return text("missing ?session\n", 400);
227
- const since = url.searchParams.get("since") ?? undefined;
228
- return json(await control.entries(session, since !== undefined ? { since } : undefined));
229
- }),
230
- "POST /control/dispatch": guard(async (req) => {
231
- const body = await readBodyCapped(req, DISPATCH_BODY_LIMIT);
232
- // The 413 names the ceiling: the docs promise images on this plane, and an unexplained
233
- // rejection would send a client author hunting everywhere but the cap.
234
- if ("tooLarge" in body) {
235
- // Derived from the constant — a hardcoded "1 MiB" would lie the day the cap changes.
236
- return text(`body too large (limit ${MAX_BODY_BYTES >> 20} MiB — images count base64-inflated)\n`, 413);
237
- }
238
- let parsed;
315
+ // The DEPLOYMENT's conversation list — and the one read that may fail: `[]` is what an empty
316
+ // deployment answers, so a store that cannot be enumerated gets a coded non-2xx instead. 503 +
317
+ // the code, because the alternative (#309's lesson) is a client that can only classify a bare
318
+ // 500 as "the endpoint is unreachable" and burns its reconnect budget on a condition
319
+ // reconnecting cannot fix.
320
+ "GET /control/sessions": guard(async () => {
239
321
  try {
240
- parsed = JSON.parse(body.text);
322
+ return json(await control.sessions.list());
241
323
  }
242
- catch {
243
- return text("invalid JSON\n", 400);
324
+ catch (error) {
325
+ // ONLY a store fault becomes the retryable code. A TypeError from our own row building is a
326
+ // bug, and answering `retryable: true` for it has a client poll forever on something no
327
+ // retry can fix — so it goes back to the plane's totality boundary, which logs it and
328
+ // answers 500. An IO error carries an ERRNO `code` (EACCES, ENOTDIR); that is the shape of a
329
+ // condition the operator can act on.
330
+ //
331
+ // The errno SHAPE, not merely "has a string code": Node's own argument-validation errors are
332
+ // TypeErrors carrying `ERR_INVALID_ARG_TYPE`/`ERR_OUT_OF_RANGE`, so a bug in row building
333
+ // would otherwise be handed to a client as retryable — the exact case this excludes. Read
334
+ // through `?.` because a thrown null must reach the boundary as itself, not as a TypeError
335
+ // from this line that replaces it in the log.
336
+ const code = error?.code;
337
+ if (typeof code !== "string" || !/^E[A-Z]+$/.test(code))
338
+ throw error;
339
+ // Logged as well as answered: the catch would otherwise be the one place a store fault is
340
+ // invisible on the server, since it preempts the boundary that does the logging.
341
+ log.error(`[control] GET /control/sessions failed: ${String(error)}`);
342
+ return json({ code: SESSIONS_UNAVAILABLE_CODE, message: String(error), retryable: true }, 503);
244
343
  }
245
- if (typeof parsed.session !== "string") {
246
- return text("expected { session: string, command: SessionCommand }\n", 400);
344
+ }),
345
+ // PUT, because a fork is idempotent: this id, holding the history that was at `from`@`at`.
346
+ // Repeating it answers ok and writes nothing; naming an id that holds a different history is a
347
+ // conflict, not an overwrite.
348
+ [`PUT /control/sessions/${SESSION_SEGMENT}`]: guard(async (req, _url, session) => {
349
+ const read = await readJson(req);
350
+ if ("error" in read)
351
+ return read.error;
352
+ // `JSON.parse("null")` is null, and a body is whatever the client sent: reaching into it
353
+ // unguarded turns a malformed request into a 500 the client cannot act on.
354
+ const body = read.value;
355
+ if (typeof body?.from !== "string" || typeof body.at !== "string") {
356
+ return text("expected { from: string, at: string }\n", 400);
357
+ }
358
+ return json(await control.sessions.fork({ from: body.from, at: body.at, into: session }));
359
+ }),
360
+ [`GET /control/sessions/${SESSION_SEGMENT}`]: guard(async (_req, _url, session) => json(await control.sessions.get(session).state())),
361
+ // PATCH, because these are session PROPERTIES: last-wins, durable, applied by the next turn.
362
+ [`PATCH /control/sessions/${SESSION_SEGMENT}`]: guard(async (req, _url, session) => {
363
+ const read = await readJson(req);
364
+ if ("error" in read)
365
+ return read.error;
366
+ const parsed = parseWireUpdate(read.value);
367
+ // A protocol-level answer carrying the SAME code the hub would have used — the wire must not
368
+ // be where a client loses the difference between "drop that field" and "fix that value".
369
+ if (!("patch" in parsed)) {
370
+ return json({ ok: false, error: { ...parsed, retryable: false } });
247
371
  }
248
- const command = parseWireCommand(parsed.command);
249
- if (!command) {
250
- // Malformed shape = a protocol-level answer, mirrored from the hub's unknown-type default.
372
+ return json(await control.sessions.get(session).update(parsed.patch));
373
+ }),
374
+ [`DELETE /control/sessions/${SESSION_SEGMENT}`]: guard(async (_req, _url, session) => json(await control.sessions.get(session).delete())),
375
+ [`GET /control/sessions/${SESSION_SEGMENT}/entries`]: guard(async (_req, url, session) => {
376
+ const since = url.searchParams.get("since") ?? undefined;
377
+ return json(await control.sessions.get(session).entries(since !== undefined ? { since } : undefined));
378
+ }),
379
+ // The run actions. Not PATCH: none of them SETS anything — they join, queue, stop, or summarize,
380
+ // and the outcome arrives on the event stream rather than in the resource's next read.
381
+ [`POST /control/sessions/${SESSION_SEGMENT}/actions`]: guard(async (req, _url, session) => {
382
+ const read = await readJson(req);
383
+ if ("error" in read)
384
+ return read.error;
385
+ const action = parseWireAction(read.value);
386
+ if (!action) {
251
387
  return json({
252
388
  ok: false,
253
- error: { code: INVALID_COMMAND_CODE, message: "malformed command", retryable: false },
389
+ error: { code: INVALID_COMMAND_CODE, message: "malformed action", retryable: false },
254
390
  });
255
391
  }
392
+ const s = control.sessions.get(session);
256
393
  // The result rides HTTP 200 either way: `ok: false` is a protocol-level answer (rejected
257
394
  // before acceptance), not a transport failure.
258
- return json(await control.dispatch(parsed.session, command));
395
+ switch (action.type) {
396
+ case "steer":
397
+ return json(await s.steer(action.prompt));
398
+ case "follow_up":
399
+ return json(await s.followUp(action.prompt));
400
+ case "abort":
401
+ return json(await s.abort());
402
+ case "compact":
403
+ return json(await s.compact(action.instructions !== undefined ? { instructions: action.instructions } : {}));
404
+ }
259
405
  }),
260
- "GET /control/events": guard((_req, url) => {
261
- const session = sessionParam(url);
262
- if (!session)
263
- return text("missing ?session\n", 400);
264
- const iterator = control.events(session)[Symbol.asyncIterator]();
406
+ [`GET /control/sessions/${SESSION_SEGMENT}/events`]: guard((_req, _url, session) => {
407
+ const iterator = control.sessions.get(session).events()[Symbol.asyncIterator]();
265
408
  // EAGER registration: issue the first pull NOW, before the Response (and thus the client's
266
409
  // fetch resolution) exists — hub subscription is registered synchronously inside next(), so
267
410
  // "the client saw response headers" implies "events from that moment on will be delivered".
@@ -10,15 +10,37 @@ export interface LoadedLongConnectionChannel {
10
10
  name: string;
11
11
  connect(signal: AbortSignal): LongConnection;
12
12
  }
13
+ /**
14
+ * HOW A CHANNEL IS REACHED — the authored structural fact, and the ONE shape it travels in.
15
+ *
16
+ * A webhook channel is reached at a URL someone must set; a long-connection channel dials out, so
17
+ * there is no URL and setting one breaks it (Telegram answers `getUpdates` with 409 once a webhook
18
+ * exists). Everything downstream — which secrets to carry, what the runbook says, what `--run` and
19
+ * `--tunnel` register — is a question about THIS.
20
+ *
21
+ * It is one list because it used to be three (`channels` + `routeChannels` + `longConnectionChannels`,
22
+ * two of them including custom channels and one not), and every consumer re-derived the answer from
23
+ * whichever pair it happened to hold. Two deploys shipped a webhook for a long-connection channel
24
+ * that way. A list of pairs cannot be recombined wrongly, and a consumer that needs a subset asks for
25
+ * it here rather than trusting its caller to have filtered.
26
+ */
27
+ export type ChannelIngress = "webhook" | "long-connection";
28
+ /** One channel a directory declares, with the ingress its module shape says it has. `name` is the
29
+ * basename, which is a {@link ChannelKind} for the first-party ones and anything for a custom one. */
30
+ export interface DeclaredChannel {
31
+ name: string;
32
+ ingress: ChannelIngress;
33
+ }
34
+ /** Declared channels from basenames that share one ingress: the serving surface's mounted route list
35
+ * (a long-connection channel mounts no HTTP route, so every route IS a webhook channel), and fixtures. */
36
+ export declare function declaredChannels(names: readonly string[], ingress?: ChannelIngress): DeclaredChannel[];
13
37
  /**
14
38
  * Import channel files without mounting route factories or opening connections. Deployment needs only
15
- * the authored structural fact: function exports are route channels; `{ connect() }` exports are
39
+ * the authored structural fact: function exports are webhook channels; `{ connect() }` exports are
16
40
  * long-connection channels. There is no second ingress/lifecycle declaration to keep in sync.
17
41
  */
18
42
  export declare function inspectChannels(dir: string): Promise<{
19
- channels: string[];
20
- routeChannels: string[];
21
- longConnectionChannels: string[];
43
+ channels: DeclaredChannel[];
22
44
  failures: ModuleLoadFailure[];
23
45
  }>;
24
46
  /**
@@ -5,10 +5,9 @@
5
5
  * Engine-neutral, and living here rather than under `engines/` because of it: reading `channels/*.ts`
6
6
  * is the Channel contract plus a directory, with no engine in sight.
7
7
  */
8
- import { readdir } from "node:fs/promises";
9
8
  import { isAbsolute, join } from "node:path";
10
9
  import { assertRouteKey, routeKeysConflict } from "./serve.js";
11
- import { isModuleFile, loadModuleDir } from "../loader.js";
10
+ import { loadModuleDir, moduleInventory } from "../loader.js";
12
11
  import { assertInsideAgentDir } from "../paths.js";
13
12
  function longConnectionModule(value) {
14
13
  return value !== null && typeof value === "object" && typeof value.connect === "function";
@@ -18,28 +17,29 @@ function validateLongConnectionModule(value, label) {
18
17
  throw new Error(`${label}: long-connection channel name must be a non-empty string`);
19
18
  }
20
19
  }
20
+ /** Declared channels from basenames that share one ingress: the serving surface's mounted route list
21
+ * (a long-connection channel mounts no HTTP route, so every route IS a webhook channel), and fixtures. */
22
+ export function declaredChannels(names, ingress = "webhook") {
23
+ return names.map((name) => ({ name, ingress }));
24
+ }
21
25
  /**
22
26
  * Import channel files without mounting route factories or opening connections. Deployment needs only
23
- * the authored structural fact: function exports are route channels; `{ connect() }` exports are
27
+ * the authored structural fact: function exports are webhook channels; `{ connect() }` exports are
24
28
  * long-connection channels. There is no second ingress/lifecycle declaration to keep in sync.
25
29
  */
26
30
  export async function inspectChannels(dir) {
27
31
  await assertInsideAgentDir(dir, "channels");
28
32
  const { modules, failures } = await loadModuleDir(join(dir, "channels"));
29
33
  const channels = [];
30
- const routeChannels = [];
31
- const longConnectionChannels = [];
32
34
  for (const { name, label, file, mod } of modules) {
33
35
  try {
34
36
  if (typeof mod.default === "function") {
35
- channels.push(name);
36
- routeChannels.push(name);
37
+ channels.push({ name, ingress: "webhook" });
37
38
  continue;
38
39
  }
39
40
  if (longConnectionModule(mod.default)) {
40
41
  validateLongConnectionModule(mod.default, label);
41
- channels.push(name);
42
- longConnectionChannels.push(name);
42
+ channels.push({ name, ingress: "long-connection" });
43
43
  continue;
44
44
  }
45
45
  throw new Error(`${label} must default-export (ctx) => Routes or { name, connect(ctx, signal) }`);
@@ -48,7 +48,7 @@ export async function inspectChannels(dir) {
48
48
  failures.push({ label, file, message: error.message });
49
49
  }
50
50
  }
51
- return { channels, routeChannels, longConnectionChannels, failures };
51
+ return { channels, failures };
52
52
  }
53
53
  /**
54
54
  * Channel file basenames under `<dir>/channels/` — the authoring view (`fastagent info`), which lists
@@ -56,19 +56,8 @@ export async function inspectChannels(dir) {
56
56
  */
57
57
  export async function discoverChannelFiles(dir) {
58
58
  await assertInsideAgentDir(dir, "channels");
59
- let names;
60
- try {
61
- names = await readdir(join(dir, "channels"));
62
- }
63
- catch (error) {
64
- if (error.code === "ENOENT")
65
- return [];
66
- throw error;
67
- }
68
- return names
69
- .filter(isModuleFile)
70
- .map((name) => name.replace(/\.(ts|js|mjs)$/, ""))
71
- .sort();
59
+ const entries = await moduleInventory(join(dir, "channels"));
60
+ return entries.map((entry) => entry.name);
72
61
  }
73
62
  function validateRoutes(value, label) {
74
63
  if (value === null || typeof value !== "object" || value instanceof Map) {
@@ -20,7 +20,7 @@
20
20
  * here are shape-compatible with the SDK's `client.im.*` style, so the policy layer survives that swap.
21
21
  */
22
22
  import { mkdir, writeFile } from "node:fs/promises";
23
- import { join } from "node:path";
23
+ import { attachmentPath } from "../kit/attachment-path.js";
24
24
  import { utf8Prefix } from "../kit/text.js";
25
25
  /** Per-attempt timeout for a JSON API call — small JSON round-trips, so 30s is generous. */
26
26
  const API_TIMEOUT_MS = 30_000;
@@ -283,13 +283,10 @@ export function createFeishuApi(opts) {
283
283
  },
284
284
  async fetchFile(messageId, fileKey, name, chatId, filesDir) {
285
285
  const { bytes } = await api.downloadResource(messageId, fileKey, "file");
286
- // The name is external input destined for a filesystem path — keep only its basename-safe core.
287
- const safe = name.replace(/[/\\]/g, "_").replace(/^\.+/, "_") || "file";
288
- const dir = join(filesDir, chatId);
289
- await mkdir(dir, { recursive: true });
290
- const dest = join(dir, safe);
291
- await writeFile(dest, bytes);
292
- return { path: dest, name: safe, size: bytes.byteLength };
286
+ const dest = attachmentPath(filesDir, chatId, name);
287
+ await mkdir(dest.dir, { recursive: true });
288
+ await writeFile(dest.path, bytes);
289
+ return { path: dest.path, name: dest.name, size: bytes.byteLength };
293
290
  },
294
291
  async getAppConfig(appId) {
295
292
  // v6 app detail — the one read surface that returns the event-security material (under data.app).