@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
@@ -3,16 +3,18 @@
3
3
  // came since its cursor is one firing through the path a pushed event takes (triggers.ts): its accept filter, a run per
4
4
  // message, max_active_runs, its key kept for its day. The cursor is the account it was read on (its user, IMAP host and
5
5
  // port: nothing secret), the mailbox, its UIDVALIDITY and the last UID read, in the trigger's own settings, kept only once
6
- // the poll's firings are recorded, so a restart goes on from it. Its start
7
- // (the engine's start hook) is taken when the trigger is made, when an edit changes its mailbox or account, and when it
8
- // is turned on again: mail from before then starts no run, and that is said; any other edit keeps the cursor. A start
9
- // that can't sign in is taken at the first poll that does, and said; a UIDVALIDITY the server changed the same, and so
10
- // another account saved in its place (PUT /v2/settings/email). A message's key is its Message-ID (else UIDVALIDITY:UID), so
6
+ // the poll's firings are recorded, so a restart goes on from it. A poll with no cursor, or one read on another mailbox
7
+ // or account, starts watching: the mailbox's end now, mail from before it starting no run, and that is said. The engine
8
+ // polls at once when the trigger is made, turned on again (its cursor forgotten) or edited (its cursor kept), so it
9
+ // watches from then; one that couldn't check until a later poll says so then. A UIDVALIDITY the server changed starts
10
+ // over the same, as does another account saved in its place (PUT /v2/settings/email). A message's key is its Message-ID (else UIDVALIDITY:UID), so
11
11
  // one seen twice fires once; its attrs say where it was found (mailbox, UIDVALIDITY, UID), which a run's thread is read
12
12
  // from (email/tools.ts). At most POLL_TAKES messages a poll, oldest first. A
13
13
  // message this server sent (X-AgentRun-Sent, email/tools.ts email_send) is left, and said. An unreachable server is said
14
14
  // on the trigger and tried at the next time; a refused sign-in counts (the engine turns the trigger off at the third).
15
15
  import { DEFAULT_ACCOUNT, NO_ACCOUNT } from "./email/account.js";
16
+ import { fittedPayload } from "./email/answer.js";
17
+ import { messages } from "./email/names.js";
16
18
  import { ACCEPT_SCHEMA, acceptOf, acceptRefusal } from "./trigger-accept.js";
17
19
  import { closedSchema, PAYLOAD_KEPT_BYTES, unknownSourceFields } from "./trigger-adapter.js";
18
20
  import { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
@@ -20,8 +22,9 @@ import { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
20
22
  export const POLL_TAKES = 20;
21
23
  /** The one event an email trigger's accept names. */
22
24
  const EVENT = "message";
23
- /** The trigger's own settings: its cursor and its last check, no secret (public). */
25
+ /** The trigger's own settings: its cursor and its last check (the engine's), no secret (public). */
24
26
  const CURSOR = "cursor";
27
+ const LAST_CHECK = "last_check";
25
28
  /** Which account a cursor was read on: its user, IMAP host and port, nothing secret (the cursor is a public setting). */
26
29
  const accountKey = (account) => `${account.user.trim().toLowerCase()}@${account.imap.host.toLowerCase()}:${account.imap.port}`;
27
30
  /** The source's own fields, checked: each issue through `bad`. Undefined when one does not read. */
@@ -61,45 +64,10 @@ function cursorOf(text) {
61
64
  }
62
65
  }
63
66
  const kept = (cursor) => ({ [CURSOR]: JSON.stringify(cursor) });
64
- /** Whether `payload`'s JSON is within the engine's bound, measured as the engine does: bytes of UTF-8, escapes counted. */
65
- const fits = (payload) => Buffer.byteLength(JSON.stringify(payload), "utf8") <= PAYLOAD_KEPT_BYTES;
66
- /** The first `n` characters (code points) of `text`, ending in `…` when cut. */
67
- const clipped = (text, n) => (typeof text === "string" && [...text].length > n ? `${[...text].slice(0, n).join("")}…` : text);
68
- /** A message's payload whole, its JSON within PAYLOAD_KEPT_BYTES, so the engine never cuts it mid-string. When it is over,
69
- * the text is cut, the longest prefix that fits found by halving (a character's start, escapes counted), said in it and
70
- * marked `text_truncated: true`; when its other fields alone are over, the subject, the names and the lists are cut too,
71
- * shorter until it fits. */
72
- function fittedPayload(whole) {
73
- if (fits(whole))
74
- return whole;
75
- const text = typeof whole.text === "string" ? whole.text : "";
76
- // No more characters than the bound has bytes can fit: the halving reads at most that many.
77
- const chars = [...text.slice(0, 2 * PAYLOAD_KEPT_BYTES)].slice(0, PAYLOAD_KEPT_BYTES);
78
- const said = `\n[cut: the message's text was ${Buffer.byteLength(text, "utf8")} bytes]`;
79
- let rest = whole;
80
- const withText = (n) => ({ ...rest, text: `${chars.slice(0, n).join("")}${said}`, text_truncated: true });
81
- for (let room = 1000; !fits(withText(0)); room = Math.floor(room / 2)) {
82
- const list = (value) => (Array.isArray(value) ? value.slice(0, Math.max(1, Math.floor(room / 20))).map((one) => (typeof one === "string" ? clipped(one, Math.min(320, room)) : one)) : value);
83
- const attachments = Array.isArray(whole.attachments) ? whole.attachments.slice(0, Math.max(0, Math.floor(room / 20))).map((a) => ({ ...a, name: clipped(a?.name, Math.min(200, room)) })) : whole.attachments;
84
- rest = { ...whole, from: clipped(whole.from, Math.min(998, room)), message_id: clipped(whole.message_id, Math.min(998, room)), in_reply_to: clipped(whole.in_reply_to, Math.min(998, room)), subject: clipped(whole.subject, room), from_name: clipped(whole.from_name, Math.min(320, room)), to: list(whole.to), cc: list(whole.cc), attachments };
85
- if (room === 0)
86
- break;
87
- }
88
- let lo = 0;
89
- let hi = chars.length;
90
- while (lo < hi) {
91
- const mid = Math.ceil((lo + hi) / 2);
92
- if (fits(withText(mid)))
93
- lo = mid;
94
- else
95
- hi = mid - 1;
96
- }
97
- return withText(lo);
98
- }
99
67
  /** A message as the event its trigger fires: its payload (JSON, untrusted, whole within the engine's bound), its attrs
100
68
  * (who, what, and where it was found: the run's thread is read from there), keyed by its Message-ID. */
101
69
  function eventOf(m, cursor, payloadOf) {
102
- const payload = fittedPayload(payloadOf(m));
70
+ const payload = fittedPayload(payloadOf(m), PAYLOAD_KEPT_BYTES);
103
71
  return {
104
72
  key: m.message_id ?? `${cursor.uidvalidity}:${m.uid}`,
105
73
  text: JSON.stringify(payload),
@@ -110,8 +78,6 @@ function eventOf(m, cursor, payloadOf) {
110
78
  ...(m.sent_here !== undefined ? { left: "Left: this server sent that message (it carries X-AgentRun-Sent), so it starts no run." } : {}),
111
79
  };
112
80
  }
113
- /** `n` messages, in words. */
114
- const messages = (n) => `${n} message${n === 1 ? "" : "s"}`;
115
81
  /** The cursor at the end of `source`'s mailbox on `account` as it is now, and how many messages it holds: where watching
116
82
  * starts. */
117
83
  async function endOf(session, source, account) {
@@ -121,33 +87,30 @@ async function endOf(session, source, account) {
121
87
  const uid = box.uidNext > 0 ? box.uidNext - 1 : Math.max(0, ...(await session.uids({ all: true })));
122
88
  return { cursor: { account: accountKey(account), mailbox: path, uidvalidity: box.uidValidity, uid }, exists: box.exists };
123
89
  }
124
- /** The history line of a start taken for `why`, with `exists` messages left. */
125
- const watching = (source, exists, why) => why === "enabled"
126
- ? `Watching ${source.mailbox} from now, on again: the ${messages(exists)} already there, any that came while it was off among them, won't start runs.`
90
+ /** The history line of a start, with `exists` messages left: said once, by the poll that starts watching, which says so
91
+ * when the checks before it failed (`failedBefore`). */
92
+ const watching = (source, exists, failedBefore) => failedBefore
93
+ ? `Couldn't check ${source.mailbox} until now; watching from now: the ${messages(exists)} there won't start runs.`
127
94
  : `Watching ${source.mailbox} from now: the ${messages(exists)} already there won't start runs.`;
128
- /** The history line of a start that could not read the mailbox. */
129
- const unchecked = (source, why) => `Couldn't check ${String(source.mailbox ?? "INBOX")} when it was ${why === "created" ? "created" : why === "edited" ? "changed" : "turned on again"}; watching from the first check that signs in.`;
130
- /** `source`'s start, on `account`: the cursor at its mailbox's end now. */
131
- async function start(source, account, why) {
132
- const { MailError, withImap } = await import("./email/mail.js");
133
- return withImap(account, async (session) => {
134
- const end = await endOf(session, source, account);
135
- return { check: { ok: true, message: `Watching ${source.mailbox}.` }, note: watching(source, end.exists, why), cursor: kept(end.cursor) };
136
- }).catch((error) => {
137
- const failure = error instanceof MailError ? error : new MailError("failed", String(error?.message ?? error));
138
- return { check: { ok: false, message: failure.message }, note: unchecked(source, why) };
139
- });
140
- }
141
- /** One poll of `source`'s mailbox from `cursor`, on `account`. The mail libraries load at the first poll, never with the
142
- * registry (every process that reads the sources). */
143
- async function poll(source, account, cursor) {
95
+ /** Whether the trigger's last check (the engine's last_check setting) failed. */
96
+ const lastFailed = (text) => {
97
+ try {
98
+ return text !== undefined && JSON.parse(text).ok === false;
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ };
104
+ /** One poll of `source`'s mailbox from `cursor`, on `account`; `failedBefore`, its last check failed. The mail libraries
105
+ * load at the first poll, never with the registry (every process that reads the sources). */
106
+ async function poll(source, account, cursor, failedBefore) {
144
107
  const { MailError, payloadOf, READ_BYTES, withImap } = await import("./email/mail.js");
145
108
  return withImap(account, async (session) => {
146
109
  const end = await endOf(session, source, account);
147
110
  const path = end.cursor.mailbox;
148
- // No start yet (one that could not sign in, or a cursor kept before starts were taken): this check takes it.
111
+ // No cursor (made, turned on again, or no check signed in yet), or one on another mailbox (an edit): it starts here.
149
112
  if (!cursor || cursor.mailbox !== path)
150
- return { check: { ok: true, message: `Watching ${source.mailbox}.` }, note: watching(source, end.exists, "created"), cursor: kept(end.cursor) };
113
+ return { check: { ok: true, message: `Watching ${source.mailbox}.` }, note: watching(source, end.exists, failedBefore), cursor: kept(end.cursor) };
151
114
  // Another account saved in its place (or a cursor that names none): its UIDs are another mailbox's, so it starts over.
152
115
  if (cursor.account !== end.cursor.account) {
153
116
  return { check: { ok: true, message: `Watching ${source.mailbox} again: the email account changed.` }, note: `The email account changed: watching ${source.mailbox} from now; the ${messages(end.exists)} there won't start runs.`, cursor: kept(end.cursor) };
@@ -177,7 +140,7 @@ export const email = {
177
140
  owner: false,
178
141
  // Each message is its sender's: one run's answer (to alice) is never handed to the next (bob's).
179
142
  previousResult: false,
180
- settings: { scope: "trigger", fields: { [CURSOR]: { public: true }, last_check: { public: true } } },
143
+ settings: { scope: "trigger", fields: { [CURSOR]: { public: true }, [LAST_CHECK]: { public: true } } },
181
144
  describe: `{kind: "email", account?: "${DEFAULT_ACCOUNT}", mailbox?: "INBOX", every_s?: ${MIN_EVERY_S}, accept?: [{event: "${EVENT}", where?}]}`,
182
145
  fires: "each new message in the server's email account's mailbox (`email`), read every every_s seconds, that its `accept` takes",
183
146
  firedBy: "`email`: a message found in the email account's mailbox, its key from the trigger and the message's Message-ID (else its UIDVALIDITY and UID).",
@@ -212,17 +175,7 @@ export const email = {
212
175
  const account = (await ctx.credentials());
213
176
  if (!account)
214
177
  return { check: { ok: false, message: NO_ACCOUNT } };
215
- return poll(source, account, cursorOf(ctx.setting(CURSOR)));
216
- },
217
- start: {
218
- on: ["account", "mailbox"],
219
- async take(source, ctx) {
220
- const account = (await ctx.credentials());
221
- if (!account)
222
- return { check: { ok: false, message: NO_ACCOUNT }, note: unchecked(source, ctx.why) };
223
- return start(source, account, ctx.why);
224
- },
225
- unchecked,
178
+ return poll(source, account, cursorOf(ctx.setting(CURSOR)), lastFailed(ctx.setting(LAST_CHECK)));
226
179
  },
227
180
  title: (attrs) => `${attrs.from ?? ""} — ${attrs.subject ?? ""}`,
228
181
  };
@@ -0,0 +1,12 @@
1
+ import { type TriggerAdapter } from "./trigger-adapter.js";
2
+ /** The most items one poll takes, across its feeds: the rest wait for the next. */
3
+ export declare const POLL_TAKES = 20;
4
+ /** The most feeds one trigger reads. */
5
+ export declare const MAX_FEEDS = 20;
6
+ /** How often a feed is read by default, in seconds. */
7
+ export declare const DEFAULT_EVERY_S = 900;
8
+ /** The keys a feed's seen set keeps at least (twice its feed's length when that is more). */
9
+ export declare const SEEN_KEPT = 1000;
10
+ /** Why `url` is no feed URL a trigger reads, or undefined: an http(s) URL, with no user or password in it. */
11
+ export declare function urlProblem(url: unknown): string | undefined;
12
+ export declare const feed: TriggerAdapter;
@@ -0,0 +1,371 @@
1
+ import { ACCEPT_SCHEMA, acceptOf, acceptRefusal } from "./trigger-accept.js";
2
+ import { closedSchema, PAYLOAD_KEPT_BYTES, unknownSourceFields } from "./trigger-adapter.js";
3
+ import { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
4
+ import { createHash } from "node:crypto";
5
+ /** The most items one poll takes, across its feeds: the rest wait for the next. */
6
+ export const POLL_TAKES = 20;
7
+ /** The most feeds one trigger reads. */
8
+ export const MAX_FEEDS = 20;
9
+ /** How often a feed is read by default, in seconds. */
10
+ export const DEFAULT_EVERY_S = 900;
11
+ /** The keys a feed's seen set keeps at least (twice its feed's length when that is more). */
12
+ export const SEEN_KEPT = 1000;
13
+ /** The 404s in a row that stop a feed. */
14
+ const MISSING_TO_STOP = 3;
15
+ /** The feeds read at once. */
16
+ const READ_AT_ONCE = 4;
17
+ /** The one event a feed trigger's accept names. */
18
+ const EVENT = "item";
19
+ /** The trigger's own settings: its cursor and its last check (the engine's), no secret (public). */
20
+ const CURSOR = "cursor";
21
+ const LAST_CHECK = "last_check";
22
+ const URL_CHARS = 2000;
23
+ const POINTER = /^(\/([^~]|~[01])*)?$/;
24
+ const POINTER_CHARS = 300;
25
+ /** The source's own fields, checked: each issue through `bad`. Undefined when one does not read. */
26
+ function fieldsOf(value, bad) {
27
+ let failed = false;
28
+ const fail = (field, reason, message) => ((failed = true), bad(field, reason, message));
29
+ const urls = value.urls;
30
+ const rule = `urls is a list of 1 to ${MAX_FEEDS} feed URLs, each http or https, none twice`;
31
+ if (!Array.isArray(urls))
32
+ fail("urls", urls === undefined ? "missing" : "wrong_type", rule);
33
+ else if (urls.length < 1 || urls.length > MAX_FEEDS)
34
+ fail("urls", "invalid", rule);
35
+ else {
36
+ const seen = new Set();
37
+ urls.forEach((url, i) => {
38
+ const why = urlProblem(url);
39
+ if (why)
40
+ fail(`urls[${i}]`, "invalid", why);
41
+ else if (seen.has(url))
42
+ fail(`urls[${i}]`, "duplicate", `urls[${i}] is ${url} again: each feed is read once`);
43
+ else
44
+ seen.add(url);
45
+ });
46
+ }
47
+ const every = value.every_s ?? DEFAULT_EVERY_S;
48
+ if (!Number.isSafeInteger(every) || every < MIN_EVERY_S || every > MAX_EVERY_S)
49
+ fail("every_s", "invalid", `every_s is a whole number of seconds, ${MIN_EVERY_S} to ${MAX_EVERY_S}`);
50
+ for (const name of ["items", "id"]) {
51
+ const pointer = value[name];
52
+ if (pointer === undefined)
53
+ continue;
54
+ const whole = name === "items";
55
+ if (typeof pointer !== "string" || pointer.length > POINTER_CHARS || !POINTER.test(pointer) || (!whole && !pointer)) {
56
+ fail(name, "invalid", whole ? `items is a JSON Pointer to a JSON list's array of items ("" for the whole document, /data/items): for a feed that is a JSON list` : `id is a JSON Pointer into a JSON list's item to its id (/id, /number): for a feed that is a JSON list`);
57
+ }
58
+ }
59
+ const accept = value.accept === undefined ? undefined : acceptOf(value.accept, fail);
60
+ accept?.forEach((rule, i) => {
61
+ if (rule.event !== EVENT)
62
+ fail(`accept[${i}].event`, "not_an_option", `A feed trigger's one event is "${EVENT}"`);
63
+ if (rule.actions !== undefined)
64
+ fail(`accept[${i}].actions`, "not_allowed", "A feed item has no action: take it by its fields with where");
65
+ });
66
+ if (failed)
67
+ return undefined;
68
+ return { kind: "feed", urls: urls, every_s: every, ...(value.items !== undefined ? { items: value.items } : {}), ...(value.id !== undefined ? { id: value.id } : {}), ...(accept ? { accept } : {}) };
69
+ }
70
+ /** Why `url` is no feed URL a trigger reads, or undefined: an http(s) URL, with no user or password in it. */
71
+ export function urlProblem(url) {
72
+ const words = "a feed URL is http or https, with no user or password in it";
73
+ if (typeof url !== "string" || !url || url.length > URL_CHARS)
74
+ return `${words}, at most ${URL_CHARS} characters`;
75
+ const at = URL.parse(url);
76
+ if (!at || (at.protocol !== "http:" && at.protocol !== "https:") || !at.hostname)
77
+ return `${words}: ${url.slice(0, 200)} is not`;
78
+ if (at.username || at.password)
79
+ return `${words}: ${at.host}'s holds one`;
80
+ return undefined;
81
+ }
82
+ /** The cursor kept, when it reads; else none (every feed starts). */
83
+ function cursorOf(text) {
84
+ if (!text)
85
+ return { feeds: {} };
86
+ try {
87
+ const value = JSON.parse(text);
88
+ return value && typeof value.feeds === "object" && value.feeds !== null && !Array.isArray(value.feeds) ? value : { feeds: {} };
89
+ }
90
+ catch {
91
+ return { feeds: {} };
92
+ }
93
+ }
94
+ const hashed = (key) => createHash("sha256").update(key).digest("hex").slice(0, 16);
95
+ const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
96
+ const itemsWord = (n) => `${n} item${n === 1 ? "" : "s"}`;
97
+ /** `url` read on `reach` from its state's validators: its items, a 304, or what went wrong, in words. */
98
+ async function readOne(url, state, source, reach) {
99
+ const [{ readFeed, FeedRefused, FeedUnreachable }, { parseFeed, FeedUnreadable }] = await Promise.all([import("./feed/fetch.js"), import("./feed/parse.js")]);
100
+ // A feed with no seen set yet is read whole: its start is every item there now.
101
+ const last = state?.seen ? { ...(state.etag ? { etag: state.etag } : {}), ...(state.modified ? { modified: state.modified } : {}) } : {};
102
+ try {
103
+ const read = await readFeed(url, last, reach);
104
+ if (read.status === 304)
105
+ return { url, ok: true, changed: false };
106
+ if (!("body" in read))
107
+ return { url, ok: false, status: read.status, problem: `Couldn't read ${url}: HTTP ${read.status}.` };
108
+ try {
109
+ const feed = parseFeed(read.body, { ...(source.items !== undefined ? { items: source.items } : {}), ...(source.id !== undefined ? { id: source.id } : {}) });
110
+ return { url, ok: true, changed: true, feed, validators: { ...(read.etag ? { etag: read.etag } : {}), ...(read.modified ? { modified: read.modified } : {}) } };
111
+ }
112
+ catch (error) {
113
+ if (!(error instanceof FeedUnreadable))
114
+ throw error;
115
+ return { url, ok: false, status: 200, problem: `Couldn't read ${url}: ${error.message}.` };
116
+ }
117
+ }
118
+ catch (error) {
119
+ if (error instanceof FeedUnreachable)
120
+ return { url, ok: false, problem: `Couldn't reach ${url}: ${error.message}.` };
121
+ if (error instanceof FeedRefused)
122
+ return { url, ok: false, problem: `Couldn't read ${url}: ${error.message}.` };
123
+ return { url, ok: false, problem: `Couldn't read ${url}: ${String(error?.message ?? error).slice(0, 300)}.` };
124
+ }
125
+ }
126
+ /** `work` over `items`, at most `n` at once, in their order. */
127
+ async function pooled(items, n, work) {
128
+ const out = new Array(items.length);
129
+ let next = 0;
130
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
131
+ for (let i = next++; i < items.length; i = next++)
132
+ out[i] = await work(items[i]);
133
+ }));
134
+ return out;
135
+ }
136
+ /** One feed's items, oldest first: as it serves them reversed (a feed lists newest first), then by date when every one
137
+ * has one. Each key once (its first, the newest). */
138
+ function oldestFirst(items) {
139
+ const once = new Map();
140
+ for (const item of items)
141
+ if (!once.has(item.key))
142
+ once.set(item.key, item);
143
+ const reversed = [...once.values()].reverse();
144
+ const dated = (item) => item.updated ?? item.published;
145
+ return reversed.every((item) => dated(item) !== null) ? reversed.sort((a, b) => dated(a) - dated(b)) : reversed;
146
+ }
147
+ /** The payload an item fires with, within PAYLOAD_KEPT_BYTES: a JSON list's {id, link, title, item, update}, its raw item
148
+ * cut shallower until it fits; any other's {id, link, title, published, updated, author, summary, categories, feed,
149
+ * update}, its summary cut until it fits. */
150
+ function payloadOf(c, list, title) {
151
+ const { item, update } = c;
152
+ if (list) {
153
+ const whole = { id: item.id, link: item.link, title: item.title, item: item.raw, update };
154
+ if (fits(whole))
155
+ return whole;
156
+ for (const [depth, chars] of [[3, 2000], [3, 300], [2, 2000], [2, 300], [1, 300], [1, 100]]) {
157
+ const cut = { ...whole, item: shallow(item.raw, depth, chars), item_truncated: true };
158
+ if (fits(cut))
159
+ return cut;
160
+ }
161
+ return { id: item.id, link: item.link, title: item.title?.slice(0, 300) ?? null, item: null, item_truncated: true, update };
162
+ }
163
+ const whole = { id: item.id, link: item.link, title: item.title, published: iso(item.published), updated: iso(item.updated), author: item.author, summary: item.summary, categories: item.categories, feed: { title, url: c.url }, update };
164
+ if (fits(whole))
165
+ return whole;
166
+ for (const chars of [1000, 300]) {
167
+ const cut = { ...whole, id: clipped(item.id, chars), link: clipped(item.link, chars), title: clipped(item.title, chars), author: clipped(item.author, chars), summary: clipped(item.summary, chars), categories: item.categories.slice(0, 10).map((one) => clipped(one, 100)), feed: { title: clipped(title, 200), url: c.url } };
168
+ if (fits(cut))
169
+ return cut;
170
+ }
171
+ return { id: clipped(item.id, 200), link: clipped(item.link, 200), title: clipped(item.title, 200), published: iso(item.published), updated: iso(item.updated), author: null, summary: null, categories: [], feed: { title: null, url: c.url }, update };
172
+ }
173
+ const fits = (value) => Buffer.byteLength(JSON.stringify(value), "utf8") <= PAYLOAD_KEPT_BYTES;
174
+ const clipped = (text, n) => (text !== null && text.length > n ? `${text.slice(0, n - 1)}…` : text);
175
+ /** `value` with its objects and lists `depth` deep (deeper ones dropped), a list's first 20, its strings `chars` long. */
176
+ function shallow(value, depth, chars) {
177
+ if (typeof value === "string")
178
+ return clipped(value, chars);
179
+ if (value === null || typeof value !== "object")
180
+ return value;
181
+ if (depth <= 0)
182
+ return undefined;
183
+ if (Array.isArray(value))
184
+ return value.slice(0, 20).map((one) => shallow(one, depth - 1, chars)).filter((one) => one !== undefined);
185
+ return Object.fromEntries(Object.entries(value).map(([key, one]) => [key, shallow(one, depth - 1, chars)]).filter(([, one]) => one !== undefined));
186
+ }
187
+ /** One poll of `source`'s feeds from `cursor`. */
188
+ async function poll(source, reach, cursor) {
189
+ // Each feed the source reads now, with the state it had (none for one an edit added); a removed one's goes.
190
+ const states = Object.fromEntries(source.urls.flatMap((url) => (cursor.feeds[url] ? [[url, { ...cursor.feeds[url] }]] : [])));
191
+ const live = source.urls.filter((url) => !states[url]?.stopped);
192
+ const reads = await pooled(live, READ_AT_ONCE, (url) => readOne(url, states[url], source, reach));
193
+ const problems = [];
194
+ const started = [];
195
+ const candidates = [];
196
+ /** Each feed read and parsed: its items oldest first, for its seen set. */
197
+ const present = new Map();
198
+ const lists = new Map();
199
+ for (const read of reads) {
200
+ const state = (states[read.url] ??= {});
201
+ if (!read.ok) {
202
+ state.missing = read.status === 404 ? (state.missing ?? 0) + 1 : 0;
203
+ if (read.status === 410)
204
+ state.stopped = "is gone (HTTP 410)";
205
+ else if (read.status === 404 && state.missing >= MISSING_TO_STOP)
206
+ state.stopped = `answered HTTP 404 ${MISSING_TO_STOP} checks running`;
207
+ if (!state.stopped)
208
+ problems.push(read.problem);
209
+ continue;
210
+ }
211
+ state.missing = 0;
212
+ if (!read.changed)
213
+ continue;
214
+ const { feed, validators } = read;
215
+ if (feed.title)
216
+ state.title = feed.title;
217
+ delete state.etag;
218
+ delete state.modified;
219
+ Object.assign(state, validators);
220
+ const items = oldestFirst(feed.items);
221
+ lists.set(read.url, feed.list);
222
+ if (!state.seen) {
223
+ // Its start: every item there now is seen, and starts nothing.
224
+ state.seen = items.map((item) => [hashed(item.key), item.updated ?? 0]);
225
+ started.push({ url: read.url, count: items.length });
226
+ continue;
227
+ }
228
+ present.set(read.url, items);
229
+ const seen = new Map(state.seen);
230
+ const fresh = [];
231
+ for (const item of items) {
232
+ const was = seen.get(hashed(item.key));
233
+ if (was === undefined)
234
+ fresh.push({ url: read.url, item, update: false, at: item.updated ?? item.published, n: 0 });
235
+ else if (item.updated !== null && item.updated > was)
236
+ fresh.push({ url: read.url, item, update: true, at: item.updated, n: 0 });
237
+ }
238
+ candidates.push(fresh);
239
+ }
240
+ // The oldest POLL_TAKES across the feeds: each feed's in its order, the oldest head first (one with no date at once).
241
+ const taken = [];
242
+ const heads = candidates.map(() => 0);
243
+ while (taken.length < POLL_TAKES) {
244
+ let pick = -1;
245
+ for (let i = 0; i < candidates.length; i++) {
246
+ const head = candidates[i][heads[i]];
247
+ if (!head)
248
+ continue;
249
+ const best = pick < 0 ? undefined : candidates[pick][heads[pick]];
250
+ if (!best || (head.at ?? -Infinity) < (best.at ?? -Infinity))
251
+ pick = i;
252
+ }
253
+ if (pick < 0)
254
+ break;
255
+ taken.push({ ...candidates[pick][heads[pick]], n: taken.length });
256
+ heads[pick]++;
257
+ }
258
+ const waiting = candidates.flat().length - taken.length;
259
+ // The feeds with an item not taken this poll: read whole at the next.
260
+ const left = new Set(candidates.flatMap((list, i) => list.slice(heads[i]).map((c) => c.url)));
261
+ const marks = new Map(taken.map((c) => [`${c.url}\n${c.item.key}`, c]));
262
+ /** The cursor once the first `upTo` items taken are recorded: each feed's seen set with them marked, the items it
263
+ * serves now moved to its end, trimmed; a feed with an item not marked yet keeps no validators, so its next read is
264
+ * whole. An item new to its feed and not marked is not in its set; one updated and not marked keeps its last time. */
265
+ const cursorAfter = (upTo) => {
266
+ const feeds = {};
267
+ for (const url of source.urls) {
268
+ const state = states[url];
269
+ if (!state)
270
+ continue;
271
+ const items = present.get(url);
272
+ if (!items || !state.seen) {
273
+ feeds[url] = state;
274
+ continue;
275
+ }
276
+ const seen = new Map(state.seen);
277
+ for (const item of items) {
278
+ const key = hashed(item.key);
279
+ const was = seen.get(key);
280
+ const mark = marks.get(`${url}\n${item.key}`);
281
+ seen.delete(key);
282
+ if (mark && mark.n < upTo)
283
+ seen.set(key, item.updated ?? 0);
284
+ else if (was !== undefined)
285
+ seen.set(key, was);
286
+ }
287
+ const whole = !left.has(url) && !taken.slice(upTo).some((c) => c.url === url);
288
+ const { etag, modified, ...rest } = state;
289
+ feeds[url] = { ...rest, ...(whole && etag ? { etag } : {}), ...(whole && modified ? { modified } : {}), seen: [...seen.entries()].slice(-Math.max(SEEN_KEPT, 2 * items.length)) };
290
+ }
291
+ return { [CURSOR]: JSON.stringify({ feeds }) };
292
+ };
293
+ const name = (url) => states[url]?.title ?? url;
294
+ const named = (urls) => (urls.length === 1 ? name(urls[0]) : `${urls.length} feeds`);
295
+ const events = taken.map((c) => {
296
+ const body = payloadOf(c, lists.get(c.url) ?? false, states[c.url]?.title ?? null);
297
+ const key = `${c.url}\n${c.item.key}${c.item.updated !== null ? `\n${iso(c.item.updated)}` : ""}`;
298
+ // Its cursor made only when the engine asks for it (the last event it records, when the poll is cut short): never one
299
+ // whole cursor per item taken.
300
+ return { key, text: JSON.stringify(body), attrs: { title: (c.item.title ?? c.item.link ?? c.item.key).slice(0, 200), feed: c.url }, event: EVENT, body, get cursor() { return cursorAfter(c.n + 1); } };
301
+ });
302
+ const stopped = source.urls.filter((url) => states[url]?.stopped);
303
+ const said = stopped.map((url) => `${url} ${states[url].stopped}: it is no longer read; edit the trigger's urls to drop or fix it.`);
304
+ const parts = [];
305
+ if (started.length)
306
+ parts.push(`Watching ${named(started.map((s) => s.url))}.`);
307
+ const okUrls = reads.filter((r) => r.ok && !started.some((s) => s.url === r.url)).map((r) => r.url);
308
+ if (okUrls.length)
309
+ parts.push(`Read ${named(okUrls)}: ${taken.length} new${waiting > 0 ? `, ${waiting} more at the next check` : ""}.`);
310
+ const note = started.length ? (() => {
311
+ const count = started.reduce((sum, s) => sum + s.count, 0);
312
+ const which = named(started.map((s) => s.url));
313
+ return count ? `Watching ${which} from now: the ${itemsWord(count)} already there won't start runs.` : `Watching ${which} from now: ${started.length === 1 ? "it holds" : "they hold"} no items yet.`;
314
+ })() : undefined;
315
+ const result = {
316
+ check: { ok: !problems.length && !stopped.length, message: [...parts, ...problems, ...said].join(" ") || "Read nothing." },
317
+ ...(note ? { note } : {}),
318
+ ...(events.length ? { events } : {}),
319
+ cursor: cursorAfter(taken.length),
320
+ };
321
+ if (stopped.length === source.urls.length) {
322
+ result.stop = { detail: `Every feed it reads has stopped: ${stopped.map((url) => `${url} ${states[url].stopped}`).join("; ")}. Edit its urls, then turn it on again.` };
323
+ }
324
+ return result;
325
+ }
326
+ export const feed = {
327
+ id: "feed",
328
+ label: "feed trigger",
329
+ delivery: "clock",
330
+ owner: false,
331
+ // Each item is its own: one run's answer is never handed to the next.
332
+ previousResult: false,
333
+ settings: { scope: "trigger", fields: { [CURSOR]: { public: true }, [LAST_CHECK]: { public: true } } },
334
+ describe: `{kind: "feed", urls: ["https://..."], every_s?: ${DEFAULT_EVERY_S}, items?: "/data/items", id?: "/id", accept?: [{event: "${EVENT}", where?}]}`,
335
+ fires: "each new or updated item in its feeds (`feed`: RSS, Atom, JSON Feed or a JSON list), read every every_s seconds, that its `accept` takes",
336
+ firedBy: "`feed`: an item new to one of its feeds, or one seen before with a later updated time, its key from the trigger, the feed's URL, the item's key and its updated time.",
337
+ schemas: [
338
+ closedSchema({ kind: { const: "feed" }, urls: { type: "array", minItems: 1, maxItems: MAX_FEEDS, uniqueItems: true, items: { type: "string", minLength: 1, maxLength: URL_CHARS, pattern: "^[Hh][Tt][Tt][Pp][Ss]?://" }, description: `The feeds it reads, 1 to ${MAX_FEEDS}, each an http or https URL: RSS, Atom, JSON Feed, or a JSON list (an API's array of objects). Plain http is read on a public address alone.` } }, {
339
+ every_s: { type: "integer", minimum: MIN_EVERY_S, maximum: MAX_EVERY_S, default: DEFAULT_EVERY_S, description: "How often it reads its feeds, in seconds, on a grid from the epoch." },
340
+ items: { type: "string", maxLength: POINTER_CHARS, pattern: "^(/([^~]|~[01])*)?$", description: "For a JSON list: a JSON Pointer to its array of items. Absent: the whole document." },
341
+ id: { type: "string", minLength: 1, maxLength: POINTER_CHARS, pattern: "^/([^~]|~[01])*$", description: "For a JSON list: a JSON Pointer into each item to its id. Absent: /id." },
342
+ accept: { ...ACCEPT_SCHEMA, description: `The items that start a run: each rule's event is "${EVENT}", its where reads the payload (/title, /link, /feed/url; a JSON list's /item/...). None: every item.` },
343
+ }),
344
+ ],
345
+ sent: [
346
+ closedSchema({ kind: { const: "feed" }, urls: { type: "array", minItems: 1, maxItems: MAX_FEEDS, items: { type: "string" } }, every_s: { type: "integer", minimum: MIN_EVERY_S, maximum: MAX_EVERY_S } }, { items: { type: "string" }, id: { type: "string" }, accept: ACCEPT_SCHEMA }),
347
+ ],
348
+ parse(value, _now, bad, issues) {
349
+ issues.push(...unknownSourceFields(value, ["kind", "urls", "every_s", "items", "id", "accept"]));
350
+ return fieldsOf(value, bad);
351
+ },
352
+ wellFormed: (source) => fieldsOf(source, () => { }) !== undefined,
353
+ clock(source) {
354
+ const step = source.every_s * 1000;
355
+ return { next: (after) => (Math.floor(after / step) + 1) * step, latest: (first, now) => first + Math.floor((now - first) / step) * step, step };
356
+ },
357
+ problem: (source) => (typeof source.every_s === "number" && (source.every_s < MIN_EVERY_S || source.every_s > MAX_EVERY_S) ? `every_s ${source.every_s} is not ${MIN_EVERY_S} to ${MAX_EVERY_S} seconds` : undefined),
358
+ // Each item is its own work: a run per item, max_active_runs bounding how many at once.
359
+ concurrent: () => true,
360
+ takes: (source, event) => {
361
+ const rules = source.accept;
362
+ return rules ? acceptRefusal(rules, event.event, event.body) : undefined;
363
+ },
364
+ async poll(source, ctx) {
365
+ const reach = (await ctx.credentials());
366
+ if (!reach)
367
+ return { check: { ok: false, message: "This server reads no feeds." } };
368
+ return poll(source, reach, cursorOf(ctx.setting(CURSOR)));
369
+ },
370
+ title: (attrs) => attrs.title,
371
+ };