@parcha/agentrun-serve 0.1.0-beta.39 → 0.1.0-beta.41

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 (173) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +129 -16
  3. package/dist/api-only.d.ts +3 -1
  4. package/dist/api-only.js +4 -2
  5. package/dist/api-token.d.ts +30 -0
  6. package/dist/api-token.js +89 -0
  7. package/dist/cli.js +19 -5
  8. package/dist/composio-made.d.ts +54 -0
  9. package/dist/composio-made.js +83 -0
  10. package/dist/composio-preset.d.ts +16 -8
  11. package/dist/composio-preset.js +106 -43
  12. package/dist/composio-triggers.d.ts +7 -2
  13. package/dist/composio-triggers.js +13 -7
  14. package/dist/computer-attach.d.ts +29 -11
  15. package/dist/computer-attach.js +141 -47
  16. package/dist/computer-keys.d.ts +4 -0
  17. package/dist/computer-keys.js +5 -0
  18. package/dist/computers.d.ts +11 -1
  19. package/dist/computers.js +21 -12
  20. package/dist/console/assets/index-C3gNPz58.css +1 -0
  21. package/dist/console/assets/index-COGhx_2Z.js +711 -0
  22. package/dist/console/index.html +2 -2
  23. package/dist/decisions.js +9 -2
  24. package/dist/email/account.d.ts +0 -1
  25. package/dist/email/account.js +3 -3
  26. package/dist/email/answer.d.ts +5 -0
  27. package/dist/email/answer.js +35 -0
  28. package/dist/email/mail.js +19 -26
  29. package/dist/email/names.d.ts +30 -0
  30. package/dist/email/names.js +34 -0
  31. package/dist/email/routes.d.ts +1 -0
  32. package/dist/email/routes.js +1 -1
  33. package/dist/email/tools.d.ts +11 -4
  34. package/dist/email/tools.js +91 -46
  35. package/dist/eval-feed.d.ts +26 -0
  36. package/dist/eval-feed.js +68 -0
  37. package/dist/eval-mailbox.d.ts +5 -2
  38. package/dist/eval-mailbox.js +14 -6
  39. package/dist/exa-keyless.d.ts +1 -1
  40. package/dist/exa-keyless.js +1 -1
  41. package/dist/feed/feed-faux.d.ts +62 -0
  42. package/dist/feed/feed-faux.js +123 -0
  43. package/dist/feed/fetch.d.ts +41 -0
  44. package/dist/feed/fetch.js +128 -0
  45. package/dist/feed/parse.d.ts +41 -0
  46. package/dist/feed/parse.js +300 -0
  47. package/dist/learn/check.d.ts +3 -1
  48. package/dist/learn/check.js +57 -2
  49. package/dist/learn/compile.d.ts +3 -2
  50. package/dist/learn/compile.js +7 -6
  51. package/dist/learn/promote.d.ts +25 -14
  52. package/dist/learn/promote.js +32 -14
  53. package/dist/learned-nodes.d.ts +21 -4
  54. package/dist/learned-nodes.js +21 -8
  55. package/dist/learned-workflow.d.ts +3 -3
  56. package/dist/learned-workflow.js +14 -5
  57. package/dist/learning-cost.d.ts +17 -8
  58. package/dist/learning-cost.js +12 -4
  59. package/dist/local-models.d.ts +7 -1
  60. package/dist/local-models.js +11 -5
  61. package/dist/mcp-oauth.d.ts +15 -1
  62. package/dist/mcp-oauth.js +39 -5
  63. package/dist/mcp-pin-first.d.ts +4 -2
  64. package/dist/mcp-pin-first.js +4 -3
  65. package/dist/mcp-servers-store.d.ts +58 -5
  66. package/dist/mcp-servers-store.js +136 -17
  67. package/dist/mcp.d.ts +2 -2
  68. package/dist/mcp.js +2 -2
  69. package/dist/observation/http.d.ts +4 -1
  70. package/dist/observation/http.js +5 -4
  71. package/dist/openapi.d.ts +1 -1
  72. package/dist/openapi.js +63 -27
  73. package/dist/port-models.d.ts +4 -1
  74. package/dist/port-models.js +1 -0
  75. package/dist/print.d.ts +6 -3
  76. package/dist/print.js +4 -2
  77. package/dist/refusal-words.d.ts +3 -0
  78. package/dist/refusal-words.js +3 -0
  79. package/dist/run-labels.d.ts +23 -0
  80. package/dist/run-labels.js +79 -0
  81. package/dist/run-launch.d.ts +2 -0
  82. package/dist/run-launch.js +2 -0
  83. package/dist/run-secrets.js +12 -4
  84. package/dist/run-view.d.ts +3 -4
  85. package/dist/run-view.js +26 -24
  86. package/dist/runner/adapter-loop.d.ts +6 -2
  87. package/dist/runner/adapter-loop.js +136 -22
  88. package/dist/runner/adapter-run-spec.d.ts +5 -0
  89. package/dist/runner/adapter-run-spec.js +75 -32
  90. package/dist/runner/beside.d.ts +6 -3
  91. package/dist/runner/beside.js +9 -7
  92. package/dist/runner/cli-run-spec.js +33 -26
  93. package/dist/runner/conformance/harness.js +69 -14
  94. package/dist/runner/conformance/subject.d.ts +4 -1
  95. package/dist/runner/journal-kinds.d.ts +22 -0
  96. package/dist/runner/journal-kinds.js +39 -0
  97. package/dist/runner/main.d.ts +1 -1
  98. package/dist/runner/main.js +2 -2
  99. package/dist/runner/mcp-claim.d.ts +3 -0
  100. package/dist/runner/mcp-claim.js +1 -1
  101. package/dist/runner/mcp-run.d.ts +4 -0
  102. package/dist/runner/mcp-run.js +5 -3
  103. package/dist/runner/model-route.d.ts +7 -3
  104. package/dist/runner/model-route.js +24 -9
  105. package/dist/runner/promotion.d.ts +16 -8
  106. package/dist/runner/promotion.js +178 -55
  107. package/dist/runner/workflow-first.d.ts +6 -5
  108. package/dist/runner/workflow-first.js +9 -7
  109. package/dist/runs-over-store.js +5 -2
  110. package/dist/sdk/runs.d.ts +7 -1
  111. package/dist/sdk/runs.js +19 -6
  112. package/dist/secret-cut.js +3 -1
  113. package/dist/secrets.js +3 -1
  114. package/dist/server.d.ts +27 -2
  115. package/dist/server.js +181 -56
  116. package/dist/store/dialect.d.ts +6 -0
  117. package/dist/store/dialect.js +2 -0
  118. package/dist/store/index.d.ts +1 -1
  119. package/dist/store/postgres/connection.d.ts +11 -5
  120. package/dist/store/postgres/connection.js +44 -17
  121. package/dist/store/postgres/dialect.js +6 -0
  122. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  123. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  124. package/dist/store/postgres/store.d.ts +7 -3
  125. package/dist/store/postgres/store.js +1 -0
  126. package/dist/store/schema.d.ts +9 -0
  127. package/dist/store/schema.js +26 -2
  128. package/dist/store/sqlite/connection.js +80 -8
  129. package/dist/store/sqlite/run-launch.d.ts +11 -0
  130. package/dist/store/sqlite/run-launch.js +8 -0
  131. package/dist/store/sqlite/run-patch.d.ts +2 -1
  132. package/dist/store/sqlite/run-patch.js +3 -2
  133. package/dist/store/sqlite/store.js +101 -26
  134. package/dist/store/sqlite/worker.d.ts +2 -0
  135. package/dist/store/sqlite/worker.js +13 -10
  136. package/dist/store/store.d.ts +53 -1
  137. package/dist/store-reads/journal.js +2 -1
  138. package/dist/store-reads/learning.d.ts +30 -13
  139. package/dist/store-reads/learning.js +130 -51
  140. package/dist/store-reads/runs.d.ts +4 -3
  141. package/dist/store-reads/runs.js +3 -2
  142. package/dist/store-view.js +4 -2
  143. package/dist/template-eval.d.ts +4 -0
  144. package/dist/template-eval.js +127 -50
  145. package/dist/templates.d.ts +24 -1
  146. package/dist/templates.js +129 -21
  147. package/dist/timeline/origin.d.ts +1 -1
  148. package/dist/timeline/origin.js +2 -2
  149. package/dist/tool-gate.d.ts +5 -3
  150. package/dist/tool-gate.js +5 -2
  151. package/dist/tools.d.ts +13 -0
  152. package/dist/tools.js +15 -10
  153. package/dist/trigger-adapter.d.ts +12 -36
  154. package/dist/trigger-adapters.js +2 -1
  155. package/dist/trigger-email.js +30 -77
  156. package/dist/trigger-feed.d.ts +12 -0
  157. package/dist/trigger-feed.js +371 -0
  158. package/dist/triggers.d.ts +27 -14
  159. package/dist/triggers.js +121 -80
  160. package/dist/webhooks.js +9 -5
  161. package/dist/workflow/decision-recovery.js +5 -2
  162. package/dist/workflow/decisions.d.ts +7 -0
  163. package/dist/workspace/computer-deps.d.ts +5 -1
  164. package/dist/workspace/computer-deps.js +2 -2
  165. package/dist/workspace/index.d.ts +1 -0
  166. package/dist/workspace/index.js +2 -0
  167. package/dist/workspace/resolve-computer.d.ts +32 -3
  168. package/dist/workspace/resolve-computer.js +47 -9
  169. package/launcher/agentrun-serve +6 -1
  170. package/package.json +10 -9
  171. package/templates/README.md +27 -2
  172. package/dist/console/assets/index-BNhZs-jp.css +0 -1
  173. package/dist/console/assets/index-BQv5aOGB.js +0 -700
@@ -0,0 +1,68 @@
1
+ // A template eval case's fake feed (template-eval.ts `feed:`): its fixture, checked when the case is read, and each run's
2
+ // fake feeds on loopback (feed/feed-faux.ts), so no run of an eval reads a real feed. The first URL the package's feed
3
+ // trigger names is read from a fake serving the fixture's items; each other URL it names from an empty fake of the same
4
+ // format. The eval's own server reads them in place of those URLs (ServeOptions.feedsAt): the trigger, its payload and its
5
+ // words keep the package's URLs. The trigger's first poll, at the apply, takes its start on the fixture's items; the
6
+ // fixture's `item` is then added (or, when one there has its id, put in its place: an incident updated) and the trigger's
7
+ // next poll fires on it.
8
+ import { FEED_FORMATS, startFeedFaux } from "./feed/feed-faux.js";
9
+ import { isObject } from "./validate.js";
10
+ const FIXTURE_FIELDS = ["description", "format", "title", "items", "item", "trigger"];
11
+ /** `value` read as a feed fixture, each problem through `bad` in words naming `at`; undefined when one does not read. Its
12
+ * `trigger` is filled in by the caller, from the package. */
13
+ export function feedFixtureOf(value, at, bad) {
14
+ if (!isObject(value))
15
+ return bad(`${at}: a feed fixture is {description?, format, title?, items, item, trigger?}`), undefined;
16
+ let ok = true;
17
+ const no = (message) => ((ok = false), bad(`${at}: ${message}`));
18
+ for (const key of Object.keys(value).filter((key) => !FIXTURE_FIELDS.includes(key)))
19
+ no(`no field ${key}: its fields are ${FIXTURE_FIELDS.join(", ")}`);
20
+ if (value.description !== undefined && typeof value.description !== "string")
21
+ no("description is text");
22
+ if (!FEED_FORMATS.includes(value.format))
23
+ no(`format is ${FEED_FORMATS.slice(0, -1).join(", ")} or ${FEED_FORMATS.at(-1)}`);
24
+ if (value.title !== undefined && typeof value.title !== "string")
25
+ no("title is the feed's own title, text");
26
+ if (!Array.isArray(value.items) || !value.items.every(isObject))
27
+ no("items is the feed's items before the run, newest first, each an object");
28
+ if (!isObject(value.item))
29
+ no("item is the new or updated item the run is started on: an object (one with an id of the items' replaces it)");
30
+ if (value.trigger !== undefined && (typeof value.trigger !== "string" || !value.trigger))
31
+ no("trigger is the name of the package's feed trigger that starts the run");
32
+ if (!ok)
33
+ return undefined;
34
+ return {
35
+ ...(typeof value.description === "string" ? { description: value.description } : {}), format: value.format, ...(typeof value.title === "string" ? { title: value.title } : {}),
36
+ items: value.items, item: value.item, ...(typeof value.trigger === "string" ? { trigger: value.trigger } : {}),
37
+ };
38
+ }
39
+ /** The fake feeds of one run of a case on `fixture`, for a trigger that reads `urls` (its first the fixture's) and, for a
40
+ * JSON list, its items at `under`. */
41
+ export async function caseFeeds(fixture, urls, under) {
42
+ const fakes = new Map();
43
+ try {
44
+ for (const [i, url] of urls.entries()) {
45
+ fakes.set(url, await startFeedFaux({ format: fixture.format, ...(fixture.title !== undefined ? { title: fixture.title } : {}), items: i === 0 ? fixture.items : [], ...(fixture.format === "json-list" && under ? { under } : {}) }));
46
+ }
47
+ }
48
+ catch (error) {
49
+ for (const fake of fakes.values())
50
+ await fake.close();
51
+ throw error;
52
+ }
53
+ const first = fakes.get(urls[0]);
54
+ return {
55
+ route: (url) => fakes.get(url)?.url,
56
+ deliver() {
57
+ const id = fixture.item.id;
58
+ if (id !== undefined && first.items().some((one) => one.id === id))
59
+ first.update(fixture.item);
60
+ else
61
+ first.add(fixture.item);
62
+ },
63
+ async close() {
64
+ for (const fake of fakes.values())
65
+ await fake.close();
66
+ },
67
+ };
68
+ }
@@ -36,7 +36,7 @@ export declare function mailboxFixtureOf(value: unknown, at: string, bad: (messa
36
36
  /** `m` put in `mailbox` of `faux` as it would have arrived: on gmail, a folder is a label, carried out of the inbox. */
37
37
  export declare function seed(faux: EmailFaux, layout: Layout, mailbox: string, m: MailFixtureMessage): void;
38
38
  /** A fake account on `layout`, its clock `now` when the case sets one, seeded with the fixture's mailboxes (not its new
39
- * message, which comes after the package's trigger takes its start). */
39
+ * message, which comes after the package's trigger's first poll). */
40
40
  export declare function seededFaux(fixture: MailboxFixture, layout: Layout, now?: Date): Promise<EmailFaux>;
41
41
  /** Where each message of the account is: its mailbox and, on gmail, its labels. */
42
42
  type Place = {
@@ -94,7 +94,10 @@ export declare function mailboxVerdict(record: MailboxRecord, id: string, inside
94
94
  * fired. A run starts as its trigger's would: the eval moves the clock to the trigger's next time, and the trigger's own
95
95
  * poll or schedule fires through the engine's path, never a paste of its payload into an ordinary run. `set` puts it at
96
96
  * `at`, back or forward, and holds it there until the next `to`, before a case's run makes its trigger: a case with a
97
- * clock of its own (`now`) fires every run on its own date, never on the schedule's next time after the run before. */
97
+ * clock of its own (`now`) fires every run on its own date, never on the schedule's next time after the run before.
98
+ * A timer `to` leaves fires when the clock, running on from `at`, reaches its time: the engine reads its wait on one
99
+ * now() and the timer is armed on the next, so one armed across a millisecond's tick is a millisecond past the time the
100
+ * eval moves to, and its first real wait, armed before the move, is a whole interval on. */
98
101
  export type EvalClock = TriggerClock & {
99
102
  to(at: number): void;
100
103
  set(at: number): void;
@@ -8,7 +8,7 @@
8
8
  // the package's schedule's. `trigger` names which of the package's triggers when it has more than one of that kind.
9
9
  // On the gmail layout a folder is a label: its messages are seeded out of the inbox, carrying it. The fake has no clock of
10
10
  // its own: a message's date stays as written, and what the fake stamps (an appended draft's arrival) reads the case's now.
11
- import { ADDRESS } from "./email/account.js";
11
+ import { EMAIL_ADDRESS } from "./email/names.js";
12
12
  import { startEmailFaux } from "./email/email-faux.js";
13
13
  import { messageOf } from "./email/mail.js";
14
14
  import { instantOf } from "./trigger-adapter.js";
@@ -22,7 +22,7 @@ const MESSAGE_ID = /^<[^<>\s]+>$/;
22
22
  const TEXT_SHOWN = 4_000;
23
23
  const isText = (value, max = 100_000) => typeof value === "string" && value.length <= max;
24
24
  const isList = (value, each) => Array.isArray(value) && value.every(each);
25
- const isAddress = (value) => typeof value === "string" && ADDRESS.test(value);
25
+ const isAddress = (value) => typeof value === "string" && EMAIL_ADDRESS.test(value);
26
26
  /** A message of the fixture checked, at `at`. */
27
27
  function messageOk(value, at, bad) {
28
28
  if (!isObject(value))
@@ -116,7 +116,7 @@ export function seed(faux, layout, mailbox, m) {
116
116
  faux.seed(message);
117
117
  }
118
118
  /** A fake account on `layout`, its clock `now` when the case sets one, seeded with the fixture's mailboxes (not its new
119
- * message, which comes after the package's trigger takes its start). */
119
+ * message, which comes after the package's trigger's first poll). */
120
120
  export async function seededFaux(fixture, layout, now) {
121
121
  const faux = await startEmailFaux({ layout: layout === "gmail" ? "gmail" : "standard", ...(now ? { now: () => now } : {}) });
122
122
  try {
@@ -201,6 +201,13 @@ export function evalClock() {
201
201
  let held;
202
202
  const holds = new Set();
203
203
  const now = () => held ?? Date.now() + skew;
204
+ // Its real timer, for the wait from the clock's time to its own (a wait past setTimeout's range fires early, and the
205
+ // engine, finding nothing due, arms again).
206
+ const wait = (hold) => {
207
+ clearTimeout(hold.timer);
208
+ hold.timer = setTimeout(() => holds.delete(hold) && hold.fire(), Math.max(0, Math.min(hold.at - now(), 2 ** 31 - 1)));
209
+ hold.timer.unref();
210
+ };
204
211
  // Every timer due by the clock's time, fired.
205
212
  const due = () => {
206
213
  for (const hold of [...holds]) {
@@ -215,9 +222,7 @@ export function evalClock() {
215
222
  now,
216
223
  arm(fire, ms) {
217
224
  const hold = { at: now() + ms, fire, timer: undefined };
218
- // A timer past setTimeout's range fires early, and the engine, finding nothing due, arms again.
219
- hold.timer = setTimeout(() => holds.delete(hold) && fire(), Math.max(0, Math.min(ms, 2 ** 31 - 1)));
220
- hold.timer.unref();
225
+ wait(hold);
221
226
  holds.add(hold);
222
227
  return { clear: () => (clearTimeout(hold.timer), holds.delete(hold), undefined) };
223
228
  },
@@ -227,6 +232,9 @@ export function evalClock() {
227
232
  held = undefined;
228
233
  skew = from - Date.now();
229
234
  due();
235
+ // The rest wait from the clock's new time, not from where it was when they were armed.
236
+ for (const hold of holds)
237
+ wait(hold);
230
238
  },
231
239
  set(at) {
232
240
  held = at;
@@ -7,7 +7,7 @@ export declare const EXA_SEARCH_TOOL = "web_search_exa";
7
7
  export declare const FAUX_EXA_ENV = "AGENTRUN_SERVE_FAUX_EXA";
8
8
  /** What a search answers when Exa's free limit holds after the one retry. Exa's own words name a fix (an API key in
9
9
  * its MCP URL) that means nothing to a person here, so they are never passed on. */
10
- export declare const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute, or add a Parallel key in Settings \u2192 Tool keys to search with a key.";
10
+ export declare const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute; add the free Parallel Search server in Settings \u2192 MCP servers and grant the agent its web_search; or add a Parallel key in Settings \u2192 Tool keys to search with a key.";
11
11
  /** A search Exa refused for its free limit (`retryAfterS`, the wait it named, when it named one) or for the connection
12
12
  * (403): a reason another provider may get past, which the caller reads before the model reads `error` alone. */
13
13
  export type ExaLimited = {
@@ -33,7 +33,7 @@ const ACCEPT = "application/json, text/event-stream";
33
33
  const MAX_BYTES = 1 << 20;
34
34
  /** What a search answers when Exa's free limit holds after the one retry. Exa's own words name a fix (an API key in
35
35
  * its MCP URL) that means nothing to a person here, so they are never passed on. */
36
- export const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute, or add a Parallel key in Settings → Tool keys to search with a key.";
36
+ export const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute; add the free Parallel Search server in Settings → MCP servers and grant the agent its web_search; or add a Parallel key in Settings → Tool keys to search with a key.";
37
37
  /** The most of Exa's own words a failure quotes: the first sentence of its first line, cut on a word. */
38
38
  const SAID_MAX = 120;
39
39
  /** A failure Exa answered, in our words: the first sentence of its text, short and quoted. Its later lines (a fix for its
@@ -0,0 +1,62 @@
1
+ /** The formats a feed trigger reads. */
2
+ export declare const FEED_FORMATS: readonly ["rss", "atom", "json-feed", "json-list"];
3
+ export type FeedFormat = (typeof FEED_FORMATS)[number];
4
+ /** An item of an RSS, Atom or JSON Feed feed, each field left out when it is undefined (a feed with no ids, say):
5
+ * `summary` its summary (RSS description, Atom summary, JSON Feed summary), `content` its HTML content (Atom content
6
+ * type="html", as Statuspage's entries carry, JSON Feed content_html). A JSON list's items are its raw objects. */
7
+ export type FauxEntry = {
8
+ id?: string;
9
+ link?: string;
10
+ title?: string;
11
+ published?: string;
12
+ updated?: string;
13
+ author?: string;
14
+ summary?: string;
15
+ content?: string;
16
+ categories?: string[];
17
+ };
18
+ export type FauxItem = FauxEntry | Record<string, unknown>;
19
+ export type FeedFixtureOptions = {
20
+ format: FeedFormat;
21
+ /** The feed's own title (RSS, Atom and JSON Feed). */
22
+ title?: string;
23
+ /** Its items, newest first. */
24
+ items?: FauxItem[];
25
+ /** The loopback name it is reached at: the v4 loopback address (the default) or its name, another host to a URL's eye. */
26
+ host?: "127.0.0.1" | "localhost";
27
+ /** For a JSON list: the pointer its array is served under (`/data/items` serves {"data": {"items": [...]}}); none, the
28
+ * document is the array. */
29
+ under?: string;
30
+ };
31
+ /** One request the feed was sent. */
32
+ export type FauxRequest = {
33
+ path: string;
34
+ method: string;
35
+ status: number;
36
+ authorization?: string;
37
+ if_none_match?: string;
38
+ if_modified_since?: string;
39
+ };
40
+ export type FeedFaux = {
41
+ /** The feed's address. */
42
+ url: string;
43
+ /** The items it serves now, newest first. */
44
+ items(): FauxItem[];
45
+ /** One more item at the top, as a new post or pull request comes; the feed changes. */
46
+ add(item: FauxItem): void;
47
+ /** Its items replaced. */
48
+ set(items: FauxItem[]): void;
49
+ /** The item whose id is `item.id` replaced by `item`, in its place (an incident updated). */
50
+ update(item: FauxItem): void;
51
+ /** Every request answered with `status` (a 410, a 404, a 500) until it is called with none. */
52
+ fail(status?: number): void;
53
+ /** Every request answered with a 302 to `url` until it is called with none. */
54
+ moveTo(url?: string): void;
55
+ /** Every request answered 200 with `body` as it is (a feed that won't parse) until it is called with none. */
56
+ raw(body?: string): void;
57
+ /** The requests it was sent, in order. */
58
+ requests(): FauxRequest[];
59
+ close(): Promise<void>;
60
+ };
61
+ /** A feed on loopback, closed with `close`. */
62
+ export declare function startFeedFaux(options: FeedFixtureOptions): Promise<FeedFaux>;
@@ -0,0 +1,123 @@
1
+ // A feed for tests and template evals, on this machine's loopback: hand-written runtime code, as email/email-faux.ts is,
2
+ // so a template eval (eval-feed.ts) can start a feed trigger with no network. It serves one feed in one of the formats
3
+ // a feed trigger reads (RSS 2.0, Atom as Statuspage's incident history serves it, JSON Feed, or a JSON list, GitHub's
4
+ // pulls API's shape), newest first, as feeds are: `add` puts an item at the top, `update` replaces one by its id (a
5
+ // Statuspage incident keeps its id and gets a new <updated> with each status post). It answers a conditional request whose ETag still holds with 304, and records
6
+ // each request (its path, its conditionals, and whether it carried an Authorization header and what), so a test can
7
+ // read what the server sent. `fail` answers every request with a status until it is cleared (a 410, a 404, a 500);
8
+ // `moveTo` answers with a redirect to another address. Nothing here reaches the network.
9
+ import { createHash } from "node:crypto";
10
+ import { createServer } from "node:http";
11
+ /** The formats a feed trigger reads. */
12
+ export const FEED_FORMATS = ["rss", "atom", "json-feed", "json-list"];
13
+ const xml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
14
+ const rfc822 = (iso) => new Date(iso).toUTCString();
15
+ const entry = (item) => item;
16
+ /** The feed's body in `format`. */
17
+ function bodyOf(format, title, items, under, url) {
18
+ if (format === "json-list") {
19
+ let doc = items;
20
+ for (const part of (under ?? "").split("/").slice(1).reverse())
21
+ doc = { [part.replace(/~1/g, "/").replace(/~0/g, "~")]: doc };
22
+ return { body: JSON.stringify(doc), type: "application/json; charset=utf-8" };
23
+ }
24
+ if (format === "json-feed") {
25
+ const list = items.map(entry).map((i) => ({
26
+ ...(i.id !== undefined ? { id: i.id } : {}), ...(i.link !== undefined ? { url: i.link } : {}), ...(i.title !== undefined ? { title: i.title } : {}),
27
+ ...(i.published !== undefined ? { date_published: i.published } : {}), ...(i.updated !== undefined ? { date_modified: i.updated } : {}),
28
+ ...(i.author !== undefined ? { authors: [{ name: i.author }] } : {}), ...(i.summary !== undefined ? { summary: i.summary } : {}), ...(i.content !== undefined ? { content_html: i.content } : {}), ...(i.categories ? { tags: i.categories } : {}),
29
+ }));
30
+ return { body: JSON.stringify({ version: "https://jsonfeed.org/version/1.1", title, home_page_url: url, feed_url: url, items: list }), type: "application/feed+json; charset=utf-8" };
31
+ }
32
+ if (format === "atom") {
33
+ const entries = items.map(entry).map((i) => [
34
+ "<entry>",
35
+ i.id !== undefined ? `<id>${xml(i.id)}</id>` : "",
36
+ i.link !== undefined ? `<link rel="alternate" type="text/html" href="${xml(i.link)}"/>` : "",
37
+ i.title !== undefined ? `<title type="text">${xml(i.title)}</title>` : "",
38
+ i.published !== undefined ? `<published>${xml(i.published)}</published>` : "",
39
+ i.updated !== undefined ? `<updated>${xml(i.updated)}</updated>` : "",
40
+ i.author !== undefined ? `<author><name>${xml(i.author)}</name></author>` : "",
41
+ i.summary !== undefined ? `<summary type="html">${xml(i.summary)}</summary>` : "",
42
+ i.content !== undefined ? `<content type="html">${xml(i.content)}</content>` : "",
43
+ ...(i.categories ?? []).map((c) => `<category term="${xml(c)}"/>`),
44
+ "</entry>",
45
+ ].join(""));
46
+ // As Statuspage's /history.atom: a tag: id, an alternate and a self link, then the entries.
47
+ const home = new URL(url).origin;
48
+ return { body: `<?xml version="1.0" encoding="UTF-8"?>\n<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom"><id>tag:${xml(new URL(url).hostname)},2005:/history</id><link rel="alternate" type="text/html" href="${xml(home)}"/><link rel="self" type="application/atom+xml" href="${xml(url)}"/><title>${xml(title)}</title><updated>2026-01-01T00:00:00Z</updated>${entries.join("")}</feed>`, type: "application/atom+xml; charset=utf-8" };
49
+ }
50
+ const rssItems = items.map(entry).map((i) => [
51
+ "<item>",
52
+ i.id !== undefined ? `<guid isPermaLink="false">${xml(i.id)}</guid>` : "",
53
+ i.link !== undefined ? `<link>${xml(i.link)}</link>` : "",
54
+ i.title !== undefined ? `<title>${xml(i.title)}</title>` : "",
55
+ i.published !== undefined ? `<pubDate>${rfc822(i.published)}</pubDate>` : "",
56
+ i.author !== undefined ? `<dc:creator>${xml(i.author)}</dc:creator>` : "",
57
+ i.summary !== undefined || i.content !== undefined ? `<description><![CDATA[${i.summary ?? i.content}]]></description>` : "",
58
+ ...(i.categories ?? []).map((c) => `<category>${xml(c)}</category>`),
59
+ "</item>",
60
+ ].join(""));
61
+ return { body: `<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>${xml(title)}</title><link>${xml(url)}</link><description>${xml(title)}</description>${rssItems.join("")}</channel></rss>`, type: "application/rss+xml; charset=utf-8" };
62
+ }
63
+ /** Where a fake feed listens, and its URL's host by default. */
64
+ const LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule a fake feed listens on loopback alone
65
+ /** A feed on loopback, closed with `close`. */
66
+ export async function startFeedFaux(options) {
67
+ const host = options.host ?? LOOPBACK;
68
+ let items = [...(options.items ?? [])];
69
+ let failing;
70
+ let moved;
71
+ let rawBody;
72
+ let changed = new Date(Date.UTC(2026, 0, 1)).toUTCString();
73
+ const requests = [];
74
+ const title = options.title ?? "Faux feed";
75
+ let url = "";
76
+ const header = (req, name) => (typeof req.headers[name] === "string" ? req.headers[name] : undefined);
77
+ const answer = (req, res) => {
78
+ const seen = { path: req.url ?? "/", method: req.method ?? "GET", status: 200 };
79
+ const authorization = header(req, "authorization");
80
+ const ifNoneMatch = header(req, "if-none-match");
81
+ const ifModifiedSince = header(req, "if-modified-since");
82
+ if (authorization !== undefined)
83
+ seen.authorization = authorization;
84
+ if (ifNoneMatch !== undefined)
85
+ seen.if_none_match = ifNoneMatch;
86
+ if (ifModifiedSince !== undefined)
87
+ seen.if_modified_since = ifModifiedSince;
88
+ requests.push(seen);
89
+ if (moved !== undefined)
90
+ return void ((seen.status = 302), res.writeHead(302, { location: moved }).end());
91
+ if (failing !== undefined)
92
+ return void ((seen.status = failing), res.writeHead(failing, { "content-type": "text/plain" }).end(`HTTP ${failing}`));
93
+ if (rawBody !== undefined)
94
+ return void res.writeHead(200, { "content-type": "application/xml" }).end(rawBody);
95
+ const { body, type } = bodyOf(options.format, title, items, options.under, url);
96
+ const etag = `"${createHash("sha256").update(body).digest("hex").slice(0, 16)}"`;
97
+ if (ifNoneMatch === etag)
98
+ return void ((seen.status = 304), res.writeHead(304, { etag, "last-modified": changed }).end());
99
+ res.writeHead(200, { "content-type": type, etag, "last-modified": changed, "cache-control": "no-cache" }).end(body);
100
+ };
101
+ const http = createServer((req, res) => {
102
+ req.resume();
103
+ req.on("end", () => answer(req, res));
104
+ });
105
+ await new Promise((resolve) => http.listen(0, LOOPBACK, resolve));
106
+ url = `http://${host}:${http.address().port}/feed`;
107
+ const touch = () => void (changed = new Date().toUTCString());
108
+ return {
109
+ url,
110
+ items: () => [...items],
111
+ add: (item) => void ((items = [item, ...items]), touch()),
112
+ set: (next) => void ((items = [...next]), touch()),
113
+ update: (item) => void ((items = items.map((one) => (one.id === item.id ? item : one))), touch()),
114
+ fail: (status) => void (failing = status),
115
+ moveTo: (to) => void (moved = to),
116
+ raw: (body) => void ((rawBody = body), touch()),
117
+ requests: () => requests.map((one) => ({ ...one })),
118
+ close: () => new Promise((resolve) => {
119
+ http.close(() => resolve());
120
+ http.closeAllConnections();
121
+ }),
122
+ };
123
+ }
@@ -0,0 +1,41 @@
1
+ import { type OAuthNetwork, type Reach } from "../mcp-oauth.js";
2
+ /** The largest body a feed may answer: past it the read stops and the check says so. */
3
+ export declare const FEED_MAX_BYTES: number;
4
+ /** How long one read may take, its redirects and its body with it. */
5
+ export declare const FEED_TIMEOUT_MS = 20000;
6
+ /** The redirects one read follows. */
7
+ export declare const FEED_MAX_REDIRECTS = 5;
8
+ /** Where a feed is read from: the network (the server's own, a test's), where it may go (`reach`), and `route`, a test's
9
+ * or an eval's seam (ServeOptions.feedsAt): the URL actually read in place of a trigger's, its answer the trigger's;
10
+ * null when the seam serves no feed at that URL (an eval's, for a feed its case doesn't fake), read as unreachable and
11
+ * never sent; undefined to read the URL as it is. */
12
+ export type FeedReach = {
13
+ network: OAuthNetwork;
14
+ reach: Reach;
15
+ route?: (url: string) => string | null | undefined;
16
+ signal?: AbortSignal;
17
+ };
18
+ /** The last read's validators, sent back so a feed that hasn't changed answers 304. */
19
+ export type Validators = {
20
+ etag?: string;
21
+ modified?: string;
22
+ };
23
+ /** A read: 200 with its body and validators, 304, or another status (with no body). */
24
+ export type FeedRead = {
25
+ status: 200;
26
+ body: string;
27
+ etag?: string;
28
+ modified?: string;
29
+ } | {
30
+ status: number;
31
+ };
32
+ /** A read refused before it was sent (an address the check refused, too many redirects, too large a body): its words. */
33
+ export declare class FeedRefused extends Error {
34
+ name: string;
35
+ }
36
+ /** A read that got no answer: no connection, a name that does not resolve, a read cut short, out of time. */
37
+ export declare class FeedUnreachable extends Error {
38
+ name: string;
39
+ }
40
+ /** `url` read, conditional on `last`. Throws FeedRefused or FeedUnreachable, in words that name the feed's host. */
41
+ export declare function readFeed(url: string, last: Validators, { network, reach, route, signal: stop }: FeedReach): Promise<FeedRead>;
@@ -0,0 +1,128 @@
1
+ // A feed trigger's read of one feed (trigger-feed.ts): one GET, held to the address check an MCP server's requests are
2
+ // (mcp-oauth.ts feedAt: no private or link-local address, no address of this machine, every address a name resolves to
3
+ // checked and the one dialled one checked), with plain http allowed on a public address alone. Redirects are followed by
4
+ // hand, each checked again, at most FEED_MAX_REDIRECTS. The read is conditional on the last ETag and Last-Modified, a
5
+ // 304 handed back with no body; the body is read to FEED_MAX_BYTES at most, the whole read held to FEED_TIMEOUT_MS.
6
+ import { feedAt } from "../mcp-oauth.js";
7
+ /** The largest body a feed may answer: past it the read stops and the check says so. */
8
+ export const FEED_MAX_BYTES = 5 * 1024 * 1024;
9
+ /** How long one read may take, its redirects and its body with it. */
10
+ export const FEED_TIMEOUT_MS = 20_000;
11
+ /** The redirects one read follows. */
12
+ export const FEED_MAX_REDIRECTS = 5;
13
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
14
+ /** A read refused before it was sent (an address the check refused, too many redirects, too large a body): its words. */
15
+ export class FeedRefused extends Error {
16
+ name = "FeedRefused";
17
+ }
18
+ /** A read that got no answer: no connection, a name that does not resolve, a read cut short, out of time. */
19
+ export class FeedUnreachable extends Error {
20
+ name = "FeedUnreachable";
21
+ }
22
+ /** `url` read, conditional on `last`. Throws FeedRefused or FeedUnreachable, in words that name the feed's host. */
23
+ export async function readFeed(url, last, { network, reach, route, signal: stop }) {
24
+ const signal = AbortSignal.any([AbortSignal.timeout(FEED_TIMEOUT_MS), ...(stop ? [stop] : [])]);
25
+ let at;
26
+ const routed = route?.(url);
27
+ try {
28
+ at = new URL(routed ?? url);
29
+ }
30
+ catch {
31
+ throw new FeedRefused(`${url.slice(0, 200)} is not a URL; refused`);
32
+ }
33
+ if (routed === null)
34
+ throw new FeedUnreachable(`the eval serves no feed at ${at.host}`);
35
+ const headers = { accept: "application/atom+xml, application/rss+xml, application/feed+json, application/json;q=0.9, application/xml;q=0.8, text/xml;q=0.8, */*;q=0.5", "user-agent": "agentrun-feed/1" };
36
+ if (last.etag)
37
+ headers["if-none-match"] = last.etag;
38
+ if (last.modified)
39
+ headers["if-modified-since"] = last.modified;
40
+ for (let hops = 0;; hops++) {
41
+ let checked;
42
+ try {
43
+ checked = await feedAt(at, signal, network, reach);
44
+ }
45
+ catch {
46
+ throw new FeedUnreachable(`couldn't reach ${at.host}: ${signal.aborted && !stop?.aborted ? `no answer within ${FEED_TIMEOUT_MS / 1000} s` : "stopped"}`);
47
+ }
48
+ if ("refused" in checked)
49
+ throw checked.unresolved ? new FeedUnreachable(checked.refused.replace(/; refused$/, "")) : new FeedRefused(checked.refused);
50
+ let res;
51
+ try {
52
+ const init = { method: "GET", headers, redirect: "manual", signal };
53
+ res = checked.address === undefined ? await fetch(at.href, init) : await (network.dial ?? network.fetch).call(network, at.href, init, checked.address);
54
+ }
55
+ catch (error) {
56
+ throw new FeedUnreachable(`couldn't reach ${at.host}${signal.aborted ? `: no answer within ${FEED_TIMEOUT_MS / 1000} s` : causeOf(error)}`);
57
+ }
58
+ if (REDIRECTS.has(res.status)) {
59
+ await res.body?.cancel().catch(() => undefined);
60
+ const location = res.headers.get("location");
61
+ if (!location)
62
+ return { status: res.status };
63
+ if (hops >= FEED_MAX_REDIRECTS)
64
+ throw new FeedRefused(`${at.host} sent the read through more than ${FEED_MAX_REDIRECTS} redirects; refused`);
65
+ try {
66
+ at = new URL(location, at);
67
+ }
68
+ catch {
69
+ throw new FeedRefused(`${at.host} redirected to ${location.slice(0, 200)}, which is not a URL; refused`);
70
+ }
71
+ continue;
72
+ }
73
+ if (res.status === 304) {
74
+ await res.body?.cancel().catch(() => undefined);
75
+ return { status: 304 };
76
+ }
77
+ if (res.status !== 200) {
78
+ await res.body?.cancel().catch(() => undefined);
79
+ return { status: res.status };
80
+ }
81
+ const bytes = await bounded(res, at, signal);
82
+ const etag = res.headers.get("etag") ?? undefined;
83
+ const modified = res.headers.get("last-modified") ?? undefined;
84
+ return { status: 200, body: decoded(bytes, res.headers.get("content-type")), ...(etag ? { etag } : {}), ...(modified ? { modified } : {}) };
85
+ }
86
+ }
87
+ /** The connection error's code, when it names one (", ECONNREFUSED"). */
88
+ function causeOf(error) {
89
+ for (let at = error, depth = 0; at && typeof at === "object" && depth < 5; at = at.cause, depth++) {
90
+ const code = at.code;
91
+ if (typeof code === "string" && /^[A-Z_]+$/.test(code))
92
+ return ` (${code})`;
93
+ }
94
+ return "";
95
+ }
96
+ /** `res`'s body, read to FEED_MAX_BYTES at most: one byte more stops the read, refused. */
97
+ async function bounded(res, at, signal) {
98
+ const chunks = [];
99
+ let size = 0;
100
+ const reader = res.body?.getReader();
101
+ try {
102
+ for (; reader;) {
103
+ const { done, value } = await reader.read();
104
+ if (done)
105
+ break;
106
+ if ((size += value.length) > FEED_MAX_BYTES)
107
+ throw new FeedRefused(`the feed at ${at.host} answered more than ${FEED_MAX_BYTES / 1024 / 1024} MB; refused`);
108
+ chunks.push(value);
109
+ }
110
+ }
111
+ catch (error) {
112
+ await reader?.cancel().catch(() => undefined);
113
+ if (error instanceof FeedRefused)
114
+ throw error;
115
+ throw new FeedUnreachable(`couldn't reach ${at.host}: ${signal.aborted ? `no answer within ${FEED_TIMEOUT_MS / 1000} s` : "the answer was cut short"}`);
116
+ }
117
+ return Buffer.concat(chunks);
118
+ }
119
+ /** `bytes` as text in the charset the answer names, UTF-8 when it names none this runtime decodes. */
120
+ function decoded(bytes, type) {
121
+ const charset = /charset\s*=\s*"?([\w.:-]+)/i.exec(type ?? "")?.[1];
122
+ try {
123
+ return new TextDecoder(charset ?? "utf-8").decode(bytes);
124
+ }
125
+ catch {
126
+ return new TextDecoder("utf-8").decode(bytes);
127
+ }
128
+ }
@@ -0,0 +1,41 @@
1
+ /** The most characters of an item's summary its payload holds. */
2
+ export declare const SUMMARY_CHARS = 4000;
3
+ /** One item as a feed trigger reads it. `key`: what it is known by (its id, else its link, else a hash of its title and
4
+ * date); `updated`, the instant its feed says it last changed (none for a JSON list's item); `raw`, a JSON list's item as
5
+ * it was served. */
6
+ export type FeedItem = {
7
+ key: string;
8
+ id: string | null;
9
+ link: string | null;
10
+ title: string | null;
11
+ published: number | null;
12
+ updated: number | null;
13
+ author: string | null;
14
+ summary: string | null;
15
+ categories: string[];
16
+ raw?: unknown;
17
+ };
18
+ /** A feed read: what it is (`list`, a JSON list), its own title (none for a list), and its items in the order it serves
19
+ * them. */
20
+ export type ParsedFeed = {
21
+ list: boolean;
22
+ title: string | null;
23
+ items: FeedItem[];
24
+ };
25
+ /** Where a JSON list's items are, and each one's id: JSON Pointers, the whole document and `/id` by default. */
26
+ export type ListPointers = {
27
+ items?: string;
28
+ id?: string;
29
+ };
30
+ /** A body that is no feed this reads: its words. */
31
+ export declare class FeedUnreadable extends Error {
32
+ name: string;
33
+ }
34
+ /** HTML as text: scripts and styles dropped, each block its own line, other tags dropped, references decoded, the spaces
35
+ * in each line collapsed and empty lines dropped. */
36
+ export declare function htmlToText(html: string): string;
37
+ /** `body` read as a feed. A JSON document is a JSON Feed (its `version` says so) unless `pointers` name a list, else a
38
+ * JSON list; anything else is read as XML: RSS or Atom. Throws FeedUnreadable in words. */
39
+ export declare function parseFeed(body: string, pointers?: ListPointers): ParsedFeed;
40
+ /** The value at JSON Pointer `pointer` in `doc`, or undefined. */
41
+ export declare function pointed(doc: unknown, pointer: string): unknown;