@b3os/mcp 0.2.1 → 0.2.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.
Files changed (61) hide show
  1. package/README.md +31 -6
  2. package/dist/handlers/_common.d.ts +27 -0
  3. package/dist/handlers/_common.js +39 -0
  4. package/dist/handlers/_common.js.map +1 -1
  5. package/dist/handlers/actions.d.ts +12 -1
  6. package/dist/handlers/actions.js +51 -2
  7. package/dist/handlers/actions.js.map +1 -1
  8. package/dist/handlers/agents.d.ts +2 -0
  9. package/dist/handlers/agents.js +41 -0
  10. package/dist/handlers/agents.js.map +1 -0
  11. package/dist/handlers/platform.d.ts +32 -0
  12. package/dist/handlers/platform.js +675 -0
  13. package/dist/handlers/platform.js.map +1 -0
  14. package/dist/handlers/render.d.ts +13 -0
  15. package/dist/handlers/render.js +170 -18
  16. package/dist/handlers/render.js.map +1 -1
  17. package/dist/handlers/routines.d.ts +8 -2
  18. package/dist/handlers/routines.js +175 -15
  19. package/dist/handlers/routines.js.map +1 -1
  20. package/dist/handlers/sandboxes.js +232 -15
  21. package/dist/handlers/sandboxes.js.map +1 -1
  22. package/dist/handlers/vision.d.ts +1 -6
  23. package/dist/handlers/vision.js +1 -13
  24. package/dist/handlers/vision.js.map +1 -1
  25. package/dist/server.d.ts +4 -0
  26. package/dist/server.js +4 -1
  27. package/dist/server.js.map +1 -1
  28. package/dist/stdio.d.ts +8 -0
  29. package/dist/stdio.js +18 -1
  30. package/dist/stdio.js.map +1 -1
  31. package/dist/table.gen.js +4868 -701
  32. package/dist/table.gen.js.map +1 -1
  33. package/dist/table.js +4 -0
  34. package/dist/table.js.map +1 -1
  35. package/dist/tools.js +3 -0
  36. package/dist/tools.js.map +1 -1
  37. package/package.json +2 -2
  38. package/src/handlers/_common.ts +53 -0
  39. package/src/handlers/actions.ts +50 -2
  40. package/src/handlers/agents.ts +50 -0
  41. package/src/handlers/platform.ts +728 -0
  42. package/src/handlers/render.ts +173 -16
  43. package/src/handlers/routines.ts +186 -14
  44. package/src/handlers/sandboxes.ts +259 -11
  45. package/src/handlers/vision.ts +1 -11
  46. package/src/server.ts +7 -1
  47. package/src/stdio.ts +21 -1
  48. package/src/table.gen.ts +4952 -707
  49. package/src/table.ts +4 -0
  50. package/src/tools.ts +3 -0
  51. package/table/core.mjs +13 -2
  52. package/table/node-toolsets.json +668 -0
  53. package/table/requests.json +1008 -10
  54. package/table/table.json +4869 -680
  55. package/table/tools/agents.mjs +232 -0
  56. package/table/tools/listeners.mjs +124 -0
  57. package/table/tools/platform.mjs +136 -3
  58. package/table/tools/render.mjs +196 -3
  59. package/table/tools/routines.mjs +55 -0
  60. package/table/tools/sandboxes.mjs +236 -1
  61. package/table/tools.mjs +3 -1
@@ -10,8 +10,10 @@ import {
10
10
  type Obj,
11
11
  pageReport,
12
12
  type Runner,
13
+ requestFor,
13
14
  startOrContinue,
14
15
  type ToolIO,
16
+ type ToolResult,
15
17
  text,
16
18
  toBase64,
17
19
  } from "./_common.ts";
@@ -50,6 +52,95 @@ export function screenshotText(shot: Obj, url: string | undefined): string {
50
52
  return lines.join("\n");
51
53
  }
52
54
 
55
+ /**
56
+ * The text of an inspection answer: its summary lines (the same events as `report` and `trace`), then the sheet's
57
+ * size and token cost, its link, and what the site answered when it was not a 2xx or the answer has warnings (the
58
+ * lines pageReport shares with vision_scrape). The whole answer is the structured content.
59
+ */
60
+ export function inspectionText(ins: Obj): string {
61
+ const lines = (Array.isArray(ins.summary) ? ins.summary : []).filter((l): l is string => typeof l === "string");
62
+ const sheet = isObj(ins.sheet) ? ins.sheet : undefined;
63
+ const art = sheet && isObj(sheet.artifact) ? sheet.artifact : undefined;
64
+ if (sheet) lines.push(`sheet ${sheet.width}x${sheet.height}, ${sheet.tokens} tokens`);
65
+ if (typeof art?.url === "string") lines.push(art.url);
66
+ const source = isObj(ins.source) ? ins.source : {};
67
+ const report = pageReport({ status_code: source.status_code, warnings: ins.warnings });
68
+ if (report) lines.push(report);
69
+ return lines.join("\n");
70
+ }
71
+
72
+ /** A beat as one line: `title: say [steps]`. */
73
+ function beatLine(b: unknown): string {
74
+ if (!isObj(b)) return "";
75
+ const steps = (Array.isArray(b.do) ? b.do : []).filter(isObj).map((s) => {
76
+ const t = isObj(s.target) ? s.target : {};
77
+ const what = t.role ? `${t.role} ${JSON.stringify(t.name ?? "")}` : JSON.stringify(t.text ?? t.selector ?? "");
78
+ return s.kind === "type" ? `type ${JSON.stringify(s.text ?? "")} into ${what}` : `${s.kind} ${what}`;
79
+ });
80
+ const head = [b.title, b.say].filter((x) => typeof x === "string" && x).join(": ");
81
+ return `${head} [${steps.join("; ")}]`;
82
+ }
83
+
84
+ /** What a goal-planned video's text adds: the state, then each planned beat; the advice when planning failed. */
85
+ const GOAL_ADVICE = "Give beats, or a goal that names something on that page.";
86
+
87
+ /**
88
+ * A video's text: its status, its artifacts, the alias it was made with and the one that keeps it, its share, the
89
+ * goal's state and planned beats, and its error. `goal_unplanned` reads `goal_unplanned (<reason>): <detail> <advice>`.
90
+ */
91
+ export function videoText(v: Obj): string {
92
+ const result = isObj(v.result) ? v.result : {};
93
+ const arts = (Array.isArray(result.artifacts) ? result.artifacts : []) as Obj[];
94
+ const lines = [`video ${v.id}: ${v.status}`, ...arts.map((a) => `${a.kind} ${a.url ?? ""}`)];
95
+ if (typeof v.alias === "string") lines.push(`alias ${v.alias}`);
96
+ if (typeof v.kept_by_alias === "string") lines.push(`kept while ${v.kept_by_alias} points at it`);
97
+ // A share B3 took down says so (security review ruling 6); its page answers 451.
98
+ if (isObj(v.share) && typeof v.share.url === "string")
99
+ lines.push(`share ${v.share.url}${v.share.blocked === true ? " (taken down by B3: abuse@b3os.org)" : ""}`);
100
+ if (isObj(v.goal)) {
101
+ const g = v.goal;
102
+ const beats = Array.isArray(g.beats) ? g.beats : [];
103
+ lines.push(`goal ${g.state}${beats.length ? `: ${beats.length} beats` : ""}${g.model ? ` (${g.model})` : ""}`);
104
+ for (const b of beats) lines.push(` ${beatLine(b)}`);
105
+ }
106
+ const err = isObj(v.error) ? v.error : undefined;
107
+ if (err?.code === "goal_unplanned") lines.push(`goal_unplanned (${err.reason}): ${err.detail} ${GOAL_ADVICE}`);
108
+ else if (err) lines.push(`${err.code}: ${err.detail}`);
109
+ return lines.join("\n");
110
+ }
111
+
112
+ /** A video answer with its poster as an image once it succeeded (unless include_poster is false). */
113
+ async function videoResult(v: Obj, args: Obj, io: ToolIO, signal: AbortSignal | undefined): Promise<ToolResult> {
114
+ const out = { ...text(videoText(v), v), isError: v.status === "failed" };
115
+ const result = isObj(v.result) ? v.result : {};
116
+ const arts = (Array.isArray(result.artifacts) ? result.artifacts : []) as Obj[];
117
+ // The poster frame as an image, so a model sees what the video shows without downloading the MP4.
118
+ const poster = arts.find((a) => a.kind === "poster");
119
+ if (v.status === "succeeded" && poster && args.include_poster !== false) {
120
+ const image = await imageOf(
121
+ typeof poster.url === "string" ? poster.url : undefined,
122
+ poster.content_type,
123
+ io,
124
+ signal,
125
+ );
126
+ if (image) out.content = [...out.content, image];
127
+ }
128
+ return out;
129
+ }
130
+
131
+ /** A share's text: its URLs and how long it lasts. */
132
+ export function shareText(s: Obj): string {
133
+ const media = isObj(s.media) ? s.media : {};
134
+ const lines = [`share ${s.url}`, `embed_html ${s.embed_html}`, `oembed_url ${s.oembed_url}`];
135
+ for (const k of ["mp4", "gif", "poster"]) if (typeof media[k] === "string") lines.push(`${k} ${media[k]}`);
136
+ lines.push(
137
+ s.alias
138
+ ? `plays alias ${s.alias} (now ${s.video_id ?? "no video"}); kept while the alias points at its video`
139
+ : `expires_at ${s.expires_at}`,
140
+ );
141
+ return lines.join("\n");
142
+ }
143
+
53
144
  export const RUNNERS: Record<string, Runner> = {
54
145
  async render_screenshot(tool, args, io, ctx) {
55
146
  if (!args.url && !args.html) throw invalid("give url or html", "/url");
@@ -65,26 +156,92 @@ export const RUNNERS: Record<string, Runner> = {
65
156
  return { content, structuredContent: shot };
66
157
  },
67
158
 
68
- async render_video(tool, args, io, ctx) {
69
- if (!args.job_id && (!args.source || !args.beats)) throw invalid("give source and beats, or job_id", "/source");
70
- const v = await startOrContinue(tool, args, io, ctx);
71
- const result = isObj(v.result) ? v.result : {};
72
- const arts = (Array.isArray(result.artifacts) ? result.artifacts : []) as Obj[];
73
- const lines = [`video ${v.id}: ${v.status}`, ...arts.map((a) => `${a.kind} ${a.url ?? ""}`)];
74
- const err = isObj(v.error) ? v.error : undefined;
75
- if (err) lines.push(`${err.code}: ${err.detail}`);
76
- const out = { ...text(lines.join("\n"), v), isError: v.status === "failed" };
77
- // The poster frame as an image, so a model sees what the video shows without downloading the MP4.
78
- const poster = arts.find((a) => a.kind === "poster");
79
- if (v.status === "succeeded" && poster && args.include_poster !== false) {
159
+ // render_screenshot_file (the render toolset): the same capture, saved to a file on the user's machine by the
160
+ // local server, answered with the path, size and URL and never the image (about 100 KB of base64 the model would
161
+ // carry). render_screenshot stays as it is: loop-v2 pins its definition (test/pinned.test.ts).
162
+ async render_screenshot_file(tool, args, io, ctx) {
163
+ if (!args.url && !args.html) throw invalid("give url or html", "/url");
164
+ if (typeof args.path !== "string" || !args.path) throw invalid("give path: the file to save the image to", "/path");
165
+ const shot = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
166
+ const arts = (Array.isArray(shot.artifacts) ? shot.artifacts : []) as Obj[];
167
+ const url = typeof arts[0]?.url === "string" ? (arts[0].url as string) : undefined;
168
+ // A server that cannot write files (the hosted /mcp) still took the screenshot: it says so, with the URL.
169
+ if (!ctx.saveFile)
170
+ return text(
171
+ `${screenshotText(shot, url)}\nnot saved: only the local server (npx @b3os/mcp, b3os mcp serve) writes files; download the URL`,
172
+ { ...shot, saved_to: null },
173
+ );
174
+ const got = url && io.fetchBytes ? await io.fetchBytes(url, ctx.signal).catch(() => undefined) : undefined;
175
+ if (!got) throw invalid("the image could not be downloaded to save it; render_screenshot returns its URL", "/path");
176
+ const saved = await ctx.saveFile(args.path, got.bytes).catch((e: unknown) => {
177
+ throw invalid((e as Error).message, "/path");
178
+ });
179
+ return text(`${screenshotText(shot, url)}\nsaved_to ${saved.saved_to} (${saved.bytes} bytes)`, {
180
+ ...shot,
181
+ ...saved,
182
+ });
183
+ },
184
+
185
+ async render_inspect(tool, args, io, ctx) {
186
+ if (!args.url === !args.video_id) throw invalid("give url or video_id, not both", "/url");
187
+ const ins = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
188
+ const content: ContentBlock[] = [{ type: "text", text: inspectionText(ins) }];
189
+ const art = isObj(ins.sheet) && isObj(ins.sheet.artifact) ? ins.sheet.artifact : undefined;
190
+ if (args.include_image !== false) {
80
191
  const image = await imageOf(
81
- typeof poster.url === "string" ? poster.url : undefined,
82
- poster.content_type,
192
+ typeof art?.url === "string" ? art.url : undefined,
193
+ art?.content_type,
83
194
  io,
84
195
  ctx.signal,
85
196
  );
86
- if (image) out.content = [...out.content, image];
197
+ if (image) content.push(image);
87
198
  }
88
- return out;
199
+ return { content, structuredContent: ins };
200
+ },
201
+
202
+ async render_video(tool, args, io, ctx) {
203
+ if (!args.job_id) {
204
+ if (!args.source || (!args.beats && !args.goal))
205
+ throw invalid("give source with beats or goal, or job_id", "/source");
206
+ if (args.beats && args.goal) throw invalid("give beats or goal, not both", "/goal");
207
+ }
208
+ const v = (await startOrContinue(tool, args, io, ctx)) as Obj;
209
+ return videoResult(v, args, io, ctx.signal);
210
+ },
211
+
212
+ async render_get(tool, args, io, ctx) {
213
+ if (typeof args.video_id !== "string" || !args.video_id) throw invalid("give video_id", "/video_id");
214
+ const v = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
215
+ return videoResult(v, args, io, ctx.signal);
216
+ },
217
+
218
+ async render_restyle(tool, args, io, ctx) {
219
+ if (!args.job_id && !args.video_id) throw invalid("give video_id, or job_id", "/video_id");
220
+ const v = (await startOrContinue(tool, args, io, ctx)) as Obj;
221
+ return videoResult(v, args, io, ctx.signal);
222
+ },
223
+
224
+ async render_presets(tool, args, io, ctx) {
225
+ const r = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
226
+ const data = (Array.isArray(r.data) ? r.data : []).filter(isObj);
227
+ return text(data.map((p) => `${p.id} (${p.kind}): ${p.name}`).join("\n"), r);
228
+ },
229
+
230
+ async render_share(tool, args, io, ctx) {
231
+ const video = typeof args.video_id === "string" && args.video_id ? args.video_id : undefined;
232
+ const alias = typeof args.alias === "string" && args.alias ? args.alias : undefined;
233
+ if (!video === !alias) throw invalid("give exactly one of video_id and alias", video ? "/alias" : "/video_id");
234
+ const stop = args.stop === true;
235
+ const title = typeof args.title === "string" && args.title ? { title: args.title } : undefined;
236
+ const req = stop
237
+ ? video
238
+ ? requestFor("renderUnshareVideo", [video])
239
+ : requestFor("renderUnshareAlias", [alias])
240
+ : video
241
+ ? buildRequest(tool, args)
242
+ : requestFor("renderShareAlias", [alias], title ? { body: title } : {});
243
+ const r = (await io.request(req, ctx.signal)) as Obj;
244
+ if (stop) return text(`stopped; the link answers 404 within 60 s (${video ?? alias})`, r);
245
+ return text(shareText(r), r);
89
246
  },
90
247
  };
@@ -4,24 +4,49 @@
4
4
 
5
5
  import type { JsonSchemaObject } from "../table-types.ts";
6
6
  import {
7
+ abortError,
7
8
  buildRequest,
8
9
  clip,
10
+ intArg,
9
11
  invalid,
10
12
  isObj,
13
+ isTerminal,
11
14
  json,
15
+ listOf,
16
+ ms,
17
+ nextCursor,
12
18
  type Obj,
13
19
  type Runner,
14
20
  requestFor,
21
+ short,
15
22
  startOrContinue,
23
+ ToolCallError,
16
24
  text,
25
+ when,
17
26
  } from "./_common.ts";
18
27
 
19
- const ms = (v: unknown) =>
20
- typeof v === "number" ? (v >= 1000 ? `${(v / 1000).toFixed(2)} s` : `${+v.toPrecision(3)} ms`) : "";
28
+ /** Steps listed in a run's text at most; the rest are counted. */
29
+ export const RUN_STEPS_SHOWN = 60;
30
+ /** A run's output in its text at most, in characters; the structured content has all of it. */
31
+ export const RUN_OUTPUT_CHARS = 4000;
21
32
 
22
33
  /**
23
- * A run as an agent reads it: the status line, where and why it failed, one line per step, then the output. The
24
- * full run is the structured content.
34
+ * `failed at step fetch: upstream_error: ...`, from the run's error and the failed step's own problem, with the step
35
+ * it names (the error's `step`, else the first failed step).
36
+ */
37
+ function failure(run: Obj, steps: readonly Obj[]): { line: string; at: unknown } | undefined {
38
+ const err = isObj(run.error) ? run.error : undefined;
39
+ if (!err) return undefined;
40
+ const at = typeof err.step === "string" ? err.step : steps.find((s) => s.status === "failed")?.id;
41
+ const stepErr = steps.find((s) => s.id === at)?.error;
42
+ const code = isObj(stepErr) && typeof stepErr.code === "string" ? stepErr.code : err.code;
43
+ const detail = isObj(stepErr) && typeof stepErr.detail === "string" ? stepErr.detail : err.detail;
44
+ return { line: at ? `failed at step ${at}: ${code}: ${detail}` : `${err.code}: ${err.detail}`, at };
45
+ }
46
+
47
+ /**
48
+ * A run as an agent reads it: the status line, where and why it failed, one line per step (a failed step's error
49
+ * under it), then the output, cut at RUN_OUTPUT_CHARS. The full run is the structured content.
25
50
  */
26
51
  export function runText(run: Obj): string {
27
52
  const steps = Array.isArray(run.steps) ? run.steps.filter(isObj) : [];
@@ -32,30 +57,77 @@ export function runText(run: Obj): string {
32
57
  const timing = isObj(run.timing) ? run.timing : {};
33
58
  if (timing.total_ms !== undefined) head.push(ms(timing.total_ms));
34
59
  const lines = [head.join(", ")];
35
- const err = isObj(run.error) ? run.error : undefined;
36
- if (err) {
37
- const at = typeof err.step === "string" ? err.step : steps.find((s) => s.status === "failed")?.id;
38
- const stepErr = steps.find((s) => s.id === at)?.error;
39
- const code = isObj(stepErr) && typeof stepErr.code === "string" ? stepErr.code : err.code;
40
- const detail = isObj(stepErr) && typeof stepErr.detail === "string" ? stepErr.detail : err.detail;
41
- lines.push(at ? `failed at step ${at}: ${code}: ${detail}` : `${err.code}: ${err.detail}`);
42
- }
60
+ const failed = failure(run, steps);
61
+ if (failed) lines.push(failed.line);
43
62
  // An ephemeral run read after it ended kept its summary only: say so instead of listing no steps.
44
63
  if (run.steps_kept === false) lines.push("steps: not kept (an ephemeral run keeps only its summary once it ends)");
45
64
  else if (steps.length) {
46
65
  lines.push("steps:");
47
- for (const s of steps) {
66
+ for (const s of steps.slice(0, RUN_STEPS_SHOWN)) {
48
67
  const e = isObj(s.error) && typeof s.error.code === "string" ? ` ${s.error.code}` : "";
49
68
  const tries = typeof s.attempt === "number" && s.attempt > 1 ? ` (attempt ${s.attempt})` : "";
50
69
  const copied = s.replayed ? " (copied)" : "";
51
70
  const waits = s.status === "waiting" && isObj(s.waiting_for) ? ` ${waitingFor(s.waiting_for)}` : "";
52
71
  lines.push(` ${s.id} ${s.uses ?? ""} ${s.status}${waits}${e}${tries}${copied} ${ms(s.duration_ms)}`.trimEnd());
72
+ // A failed step's detail, unless the failure line above already gave it.
73
+ if (isObj(s.error) && typeof s.error.detail === "string" && s.id !== failed?.at)
74
+ lines.push(` ${short(s.error.detail, 200)}`);
53
75
  }
76
+ if (steps.length > RUN_STEPS_SHOWN)
77
+ lines.push(` (${steps.length - RUN_STEPS_SHOWN} more steps; the structured content lists them)`);
78
+ }
79
+ if (run.result !== undefined) {
80
+ const out = json(run.result);
81
+ lines.push(
82
+ out.length <= RUN_OUTPUT_CHARS
83
+ ? `output: ${out}`
84
+ : `output: ${out.slice(0, RUN_OUTPUT_CHARS)} [cut at ${RUN_OUTPUT_CHARS} of ${out.length} characters; the structured content has all of it]`,
85
+ );
54
86
  }
55
- if (run.result !== undefined) lines.push(`output: ${json(run.result)}`);
87
+ if (run.status === "failed") lines.push(`routine_run_events ${run.id} reads its event log (retries, run.log lines)`);
56
88
  return lines.join("\n");
57
89
  }
58
90
 
91
+ /** A run in a line (and its failure on the next): what the console's run list shows first. */
92
+ function runLines(r: Obj): string[] {
93
+ const trigger = isObj(r.trigger) ? r.trigger : {};
94
+ const timing = isObj(r.timing) ? r.timing : {};
95
+ const facts = [
96
+ r.version_number !== undefined ? `v${r.version_number}` : "",
97
+ trigger.type ? String(trigger.type) : "",
98
+ timing.total_ms !== undefined ? ms(timing.total_ms) : "",
99
+ ].filter(Boolean);
100
+ const summary = typeof r.summary === "string" && r.summary ? `: ${r.summary}` : "";
101
+ const out = [`${r.id} ${r.status} ${when(r.created_at)} ${facts.join(" ")}${summary}`.trimEnd()];
102
+ const steps = Array.isArray(r.steps) ? r.steps.filter(isObj) : [];
103
+ const failed = failure(r, steps);
104
+ if (failed) out.push(` ${short(failed.line, 240)}`);
105
+ return out;
106
+ }
107
+
108
+ /** One event of a run's stream in a line: number, time, type, then the step, its time and its error. */
109
+ function eventLine(e: Obj): string {
110
+ const t = typeof e.ts === "string" ? e.ts.slice(11) : "";
111
+ const head = `#${e.seq ?? "?"} ${t} ${e.type}`;
112
+ if (e.type === "run.log") return `${head} [${e.level ?? "info"}] ${e.step_id ?? ""}: ${short(e.message, 300)}`;
113
+ const s = isObj(e.step) ? e.step : undefined;
114
+ if (s) {
115
+ const item = typeof s.item_index === "number" ? `[${s.item_index}]` : "";
116
+ const tries = typeof s.attempt === "number" && s.attempt > 1 ? ` (attempt ${s.attempt})` : "";
117
+ const took = typeof s.duration_ms === "number" ? ` ${ms(s.duration_ms)}` : "";
118
+ const waits = isObj(s.waiting_for) ? ` ${waitingFor(s.waiting_for)}` : "";
119
+ const err = isObj(s.error) ? `: ${s.error.code}: ${short(s.error.detail, 200)}` : "";
120
+ return `${head} ${s.id}${item}${s.uses ? ` ${s.uses}` : ""}${tries}${took}${waits}${err}`;
121
+ }
122
+ const job = isObj(e.job) ? e.job : undefined;
123
+ const err = job && isObj(job.error) ? job.error : undefined;
124
+ if (err) return `${head}: ${err.step ? `step ${err.step}: ` : ""}${err.code}: ${short(err.detail, 200)}`;
125
+ return job && typeof job.summary === "string" ? `${head}: ${job.summary}` : head;
126
+ }
127
+
128
+ /** How long reading a finished run's stream may take before the tool gives up (it ends after the terminal event). */
129
+ export const EVENTS_READ_MS = 30_000;
130
+
59
131
  /**
60
132
  * What a waiting step waits for, in a few words: an event (and its match), a person's answer (the prompt's title;
61
133
  * the routine sent them a link), or a signal, with the deadline.
@@ -78,6 +150,84 @@ export const RUNNERS: Record<string, Runner> = {
78
150
  return { ...text(clip(runText(run)), run), isError: run.status === "failed" };
79
151
  },
80
152
 
153
+ async routine_list_runs(tool, args, io, ctx) {
154
+ const page = await io.request(buildRequest(tool, args), ctx.signal);
155
+ const rows = listOf(page);
156
+ const next = nextCursor(page);
157
+ const of = `${args.routine}${args.status ? ` (${args.status})` : ""}`;
158
+ const lines = [
159
+ rows.length ? `${rows.length} run${rows.length === 1 ? "" : "s"} of ${of}, newest first:` : `no runs of ${of}`,
160
+ ];
161
+ for (const r of rows) lines.push(...runLines(r));
162
+ if (next) lines.push(`more: call again with cursor ${next}`);
163
+ if (rows.length) lines.push("routine_get_run <run id> reads a run's steps; routine_run_events its event log");
164
+ return text(clip(lines.join("\n")), {
165
+ runs: rows.map((r) => ({
166
+ id: r.id,
167
+ status: r.status,
168
+ created_at: r.created_at,
169
+ version_number: r.version_number,
170
+ trigger: isObj(r.trigger) ? r.trigger.type : undefined,
171
+ total_ms: isObj(r.timing) ? r.timing.total_ms : undefined,
172
+ summary: r.summary,
173
+ error: isObj(r.error) ? { code: r.error.code, detail: r.error.detail, step: r.error.step } : undefined,
174
+ })),
175
+ next_cursor: next ?? null,
176
+ });
177
+ },
178
+
179
+ async routine_run_events(tool, args, io, ctx) {
180
+ const runId = args.run_id;
181
+ const run = await io.request(requestFor("routinesGetRun", [runId]), ctx.signal);
182
+ if (!isObj(run)) return text(clip(json(run)));
183
+ // The stream of a run in progress stays open until the run ends, which a tool call cannot wait for: answer with
184
+ // its steps so far instead.
185
+ if (!isTerminal(run.status))
186
+ return text(
187
+ clip(
188
+ `run ${run.id} is ${run.status}: its events are read once it ends (routine_run with job_id waits for it). ` +
189
+ `Its state now:\n${runText(run)}`,
190
+ ),
191
+ run,
192
+ );
193
+ const timeout = AbortSignal.timeout(EVENTS_READ_MS);
194
+ const signal = ctx.signal ? AbortSignal.any([ctx.signal, timeout]) : timeout;
195
+ let got: unknown;
196
+ try {
197
+ got = await io.request({ ...buildRequest(tool, args), accept: "events" }, signal);
198
+ } catch (e) {
199
+ if (ctx.signal?.aborted) throw abortError();
200
+ if (timeout.aborted)
201
+ throw new ToolCallError({
202
+ code: "timeout",
203
+ detail: `the event stream of ${run.id} did not end within ${EVENTS_READ_MS / 1000} s; routine_get_run reads its steps`,
204
+ });
205
+ throw e;
206
+ }
207
+ const events = (Array.isArray(got) ? got : []).filter(isObj);
208
+ const max = intArg(args, "max_events", 40, 1, 500);
209
+ const shown = events.slice(-max);
210
+ const lines = [
211
+ `run ${run.id}: ${run.status}, ${events.length} event${events.length === 1 ? "" : "s"}${events.length > shown.length ? ` (the last ${shown.length} shown)` : ""}${typeof run.created_at === "string" ? `, created ${run.created_at}` : ""}`,
212
+ ];
213
+ if (events.length > shown.length)
214
+ lines.push(
215
+ `(${events.length - shown.length} earlier events not shown: call again with a larger max_events, at most 500)`,
216
+ );
217
+ if (run.steps_kept === false)
218
+ lines.push("(an ephemeral run keeps only its terminal event once it ends; the event stream had its steps live)");
219
+ for (const e of shown) lines.push(eventLine(e));
220
+ return {
221
+ ...text(clip(lines.join("\n")), {
222
+ run_id: run.id,
223
+ status: run.status,
224
+ events: events.length,
225
+ shown: shown.map((e) => ({ seq: e.seq, ts: e.ts, type: e.type })),
226
+ }),
227
+ isError: run.status === "failed",
228
+ };
229
+ },
230
+
81
231
  async routine_validate(tool, args, io, ctx) {
82
232
  let def: unknown = args.definition;
83
233
  if (typeof def === "string") {
@@ -96,6 +246,28 @@ export const RUNNERS: Record<string, Runner> = {
96
246
  return text(clip(lines.join("\n")), v);
97
247
  },
98
248
 
249
+ async routine_publish(tool, args, io, ctx) {
250
+ let def: unknown = args.definition;
251
+ if (typeof def === "string") {
252
+ try {
253
+ def = JSON.parse(def);
254
+ } catch {
255
+ throw invalid("definition must be a JSON object (the routine's YAML as JSON)", "/definition");
256
+ }
257
+ }
258
+ if (!isObj(def)) throw invalid("give definition: the routine as a JSON object", "/definition");
259
+ const name = typeof args.routine === "string" && args.routine ? args.routine : def.name;
260
+ if (typeof name !== "string" || !name)
261
+ throw invalid("give the routine's name in definition.name", "/definition/name");
262
+ const r = await io.request(requestFor(tool.operationId, [name], { body: def }), ctx.signal);
263
+ if (!isObj(r)) return text(clip(json(r)));
264
+ const v = isObj(r.version) ? r.version : {};
265
+ return text(
266
+ `published ${r.name ?? name} (${r.id ?? "?"}) version ${v.number ?? "?"}: run it with routine_run, routine ${r.name ?? name}`,
267
+ r,
268
+ );
269
+ },
270
+
99
271
  async routine_run(tool, args, io, ctx) {
100
272
  if (!args.job_id && !args.routine) throw invalid("give routine (start a run) or job_id (continue one)", "/routine");
101
273
  const run = await startOrContinue(tool, args, io, ctx);