@parcha/agentrun-serve 0.1.0-beta.40 → 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 (126) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +78 -15
  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-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
  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/eval-feed.d.ts +26 -0
  25. package/dist/eval-feed.js +68 -0
  26. package/dist/eval-mailbox.d.ts +4 -1
  27. package/dist/eval-mailbox.js +11 -3
  28. package/dist/exa-keyless.d.ts +1 -1
  29. package/dist/exa-keyless.js +1 -1
  30. package/dist/feed/feed-faux.d.ts +62 -0
  31. package/dist/feed/feed-faux.js +123 -0
  32. package/dist/feed/fetch.d.ts +41 -0
  33. package/dist/feed/fetch.js +128 -0
  34. package/dist/feed/parse.d.ts +41 -0
  35. package/dist/feed/parse.js +300 -0
  36. package/dist/learn/check.d.ts +3 -1
  37. package/dist/learn/check.js +57 -2
  38. package/dist/learn/compile.js +1 -1
  39. package/dist/learned-nodes.d.ts +21 -4
  40. package/dist/learned-nodes.js +21 -8
  41. package/dist/learned-workflow.d.ts +3 -3
  42. package/dist/learned-workflow.js +14 -5
  43. package/dist/mcp-oauth.d.ts +15 -1
  44. package/dist/mcp-oauth.js +39 -5
  45. package/dist/mcp-pin-first.d.ts +4 -2
  46. package/dist/mcp-pin-first.js +4 -3
  47. package/dist/mcp-servers-store.d.ts +58 -5
  48. package/dist/mcp-servers-store.js +136 -17
  49. package/dist/mcp.d.ts +2 -2
  50. package/dist/mcp.js +2 -2
  51. package/dist/observation/http.d.ts +4 -1
  52. package/dist/observation/http.js +5 -4
  53. package/dist/openapi.js +46 -12
  54. package/dist/print.d.ts +6 -3
  55. package/dist/print.js +4 -2
  56. package/dist/run-labels.d.ts +23 -0
  57. package/dist/run-labels.js +79 -0
  58. package/dist/run-secrets.js +12 -4
  59. package/dist/runner/adapter-loop.js +91 -10
  60. package/dist/runner/adapter-run-spec.d.ts +4 -0
  61. package/dist/runner/adapter-run-spec.js +38 -31
  62. package/dist/runner/beside.d.ts +6 -3
  63. package/dist/runner/beside.js +9 -7
  64. package/dist/runner/cli-run-spec.js +32 -26
  65. package/dist/runner/conformance/harness.js +69 -14
  66. package/dist/runner/conformance/subject.d.ts +4 -1
  67. package/dist/runner/main.d.ts +1 -1
  68. package/dist/runner/main.js +2 -2
  69. package/dist/runner/mcp-claim.d.ts +3 -0
  70. package/dist/runner/mcp-claim.js +1 -1
  71. package/dist/runner/mcp-run.d.ts +4 -0
  72. package/dist/runner/mcp-run.js +5 -3
  73. package/dist/runner/model-route.d.ts +4 -2
  74. package/dist/runner/model-route.js +8 -8
  75. package/dist/runner/promotion.d.ts +8 -0
  76. package/dist/runner/promotion.js +43 -1
  77. package/dist/runner/workflow-first.d.ts +6 -5
  78. package/dist/runner/workflow-first.js +9 -7
  79. package/dist/runs-over-store.js +5 -2
  80. package/dist/sdk/runs.d.ts +7 -1
  81. package/dist/sdk/runs.js +19 -6
  82. package/dist/secret-cut.js +3 -1
  83. package/dist/secrets.js +3 -1
  84. package/dist/server.d.ts +27 -2
  85. package/dist/server.js +168 -50
  86. package/dist/store/dialect.d.ts +3 -0
  87. package/dist/store/dialect.js +1 -0
  88. package/dist/store/index.d.ts +1 -1
  89. package/dist/store/postgres/dialect.js +1 -0
  90. package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
  91. package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
  92. package/dist/store/schema.d.ts +9 -0
  93. package/dist/store/schema.js +26 -2
  94. package/dist/store/sqlite/connection.js +11 -3
  95. package/dist/store/sqlite/run-patch.d.ts +2 -1
  96. package/dist/store/sqlite/run-patch.js +3 -2
  97. package/dist/store/sqlite/store.js +64 -10
  98. package/dist/store/store.d.ts +38 -1
  99. package/dist/store-reads/journal.js +2 -1
  100. package/dist/store-reads/learning.js +6 -1
  101. package/dist/store-reads/runs.d.ts +4 -3
  102. package/dist/store-reads/runs.js +3 -2
  103. package/dist/store-view.js +4 -2
  104. package/dist/template-eval.d.ts +4 -0
  105. package/dist/template-eval.js +127 -50
  106. package/dist/templates.d.ts +10 -0
  107. package/dist/templates.js +75 -17
  108. package/dist/timeline/origin.d.ts +1 -1
  109. package/dist/timeline/origin.js +2 -2
  110. package/dist/trigger-adapter.d.ts +9 -4
  111. package/dist/trigger-adapters.js +2 -1
  112. package/dist/trigger-feed.d.ts +12 -0
  113. package/dist/trigger-feed.js +371 -0
  114. package/dist/triggers.d.ts +2 -1
  115. package/dist/triggers.js +23 -5
  116. package/dist/webhooks.js +9 -5
  117. package/dist/workspace/computer-deps.d.ts +5 -1
  118. package/dist/workspace/computer-deps.js +2 -2
  119. package/dist/workspace/index.d.ts +1 -0
  120. package/dist/workspace/index.js +2 -0
  121. package/dist/workspace/resolve-computer.d.ts +32 -3
  122. package/dist/workspace/resolve-computer.js +47 -9
  123. package/launcher/agentrun-serve +6 -1
  124. package/package.json +10 -9
  125. package/templates/README.md +27 -2
  126. package/dist/console/assets/index-Jbxjcmdp.js +0 -705
@@ -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
+ };
@@ -476,7 +476,8 @@ export declare class Triggers {
476
476
  * history line; one it leaves, skipped and said; one its accept does not take, an ignored row kept for its day; any
477
477
  * other due, and driven), its cursor kept once they are, then its last check, and at the REFUSALS_TO_STOPth refused
478
478
  * sign-in in a row the trigger turned off. A poll that throws is a failed check. */
479
- /** False when an edit of its source while it polled dropped what it found (the edit's poll comes after it); else true. */
479
+ /** False when an edit of its source while it polled dropped what it found, or landed while its cursor was written and
480
+ * left its stop and its check unwritten (the edit's poll comes after it); else true. */
480
481
  private polled;
481
482
  /** A firing taken from due to its end: skipped when its trigger's last run is active, else its run started (or its
482
483
  * message sent). A failed try keeps it due under the backoff table, or ends it failed. Each step reads the trigger and
package/dist/triggers.js CHANGED
@@ -716,7 +716,8 @@ export class Triggers {
716
716
  * history line; one it leaves, skipped and said; one its accept does not take, an ignored row kept for its day; any
717
717
  * other due, and driven), its cursor kept once they are, then its last check, and at the REFUSALS_TO_STOPth refused
718
718
  * sign-in in a row the trigger turned off. A poll that throws is a failed check. */
719
- /** False when an edit of its source while it polled dropped what it found (the edit's poll comes after it); else true. */
719
+ /** False when an edit of its source while it polled dropped what it found, or landed while its cursor was written and
720
+ * left its stop and its check unwritten (the edit's poll comes after it); else true. */
720
721
  async polled(trigger, adapter, nominalAt, now) {
721
722
  const settings = this.deps.settings(adapter.id);
722
723
  // Turned on again while it polled (off and on): its cursor was forgotten, and nothing this poll found is its own.
@@ -743,7 +744,9 @@ export class Triggers {
743
744
  if (result.note)
744
745
  await this.record(current, { key: firingKey(by, trigger.id, `note\n${second(nominalAt)}`), by, nominalAt: at, status: "skipped", reason: result.note });
745
746
  const events = result.events ?? [];
746
- let cursor = events.length ? undefined : result.cursor;
747
+ // The last event recorded: the cursor is its once they are (each event's is read only here, once: a source may make
748
+ // it when asked, as the feed's does).
749
+ let last;
747
750
  let full = false;
748
751
  for (const event of events) {
749
752
  const key = firingKey(by, trigger.id, event.key);
@@ -767,20 +770,35 @@ export class Triggers {
767
770
  full = true;
768
771
  break;
769
772
  }
770
- cursor = event.cursor;
773
+ last = event;
771
774
  }
772
- if (!full && events.length)
773
- cursor = result.cursor ?? cursor;
775
+ const cursor = !events.length ? result.cursor : full ? last?.cursor : (result.cursor ?? last?.cursor);
774
776
  if (restarted())
775
777
  return true;
776
778
  for (const [field, value] of Object.entries(cursor ?? {}))
777
779
  await settings?.set(trigger.id, field, value);
780
+ // Edited, turned off or on again while its cursor was written: its stop, a refusal's turn-off and its check were read
781
+ // on the source as it was. None is applied; an edit's poll, after this one, says what holds now.
782
+ const still = await this.find(trigger.id);
783
+ if (!still || !still.enabled || restarted())
784
+ return true;
785
+ if (JSON.stringify(still.source) !== JSON.stringify(trigger.source))
786
+ return false;
778
787
  const refusals = result.refused ? (checkOf(settings?.get(trigger.id, LAST_CHECK))?.refused ?? 0) + 1 : 0;
779
788
  if (result.refused && refusals >= REFUSALS_TO_STOP) {
780
789
  await this.store.triggers.update(trigger.id, { enabled: false, nextAt: null, disabled: { at: iso(this.clock.now()), reason: "sign_in_refused", detail: result.refused.detail } });
781
790
  this.deps.say({ condition: "trigger_sign_in_refused", trigger: trigger.id, refused: refusals });
782
791
  await this.arm();
783
792
  }
793
+ // Its source can't be read again as it is (every feed gone): off now, in its words, until an owner edits it and
794
+ // turns it on again. Before its last check is written, as a refused sign-in's is: a check that says so is never read
795
+ // beside a trigger still on.
796
+ if (result.stop && !result.refused) {
797
+ await this.store.triggers.update(trigger.id, { enabled: false, nextAt: null, disabled: { at: iso(this.clock.now()), reason: "source_unreadable", detail: result.stop.detail } });
798
+ this.deps.say({ condition: "trigger_source_unreadable", trigger: trigger.id, error: result.stop.detail });
799
+ await this.offThere([current]);
800
+ await this.arm();
801
+ }
784
802
  const message = full ? `${result.check.message} ${DUE_KEPT} firings are still waiting for their runs: the rest wait for the next check.` : result.check.message;
785
803
  await settings?.set(trigger.id, LAST_CHECK, JSON.stringify({ at: iso(now), ok: result.check.ok, message, refused: refusals }));
786
804
  if (!result.check.ok)
package/dist/webhooks.js CHANGED
@@ -73,12 +73,15 @@ const WAIT = "wait:";
73
73
  * read of the run) needs its mark, and that is one of its last few. */
74
74
  const WAITS_KEPT = 20;
75
75
  const iso = (ms) => new Date(ms).toISOString();
76
- /** `work`'s result, or `signal`'s reason the moment it aborts: a lookup that never answers is given up on, not waited out. */
76
+ /** `work`'s result, or `signal`'s reason the moment it aborts: a lookup that never answers is given up on, not waited out.
77
+ * `work` is always followed to its end, so one that fails after the abort (a name that answers NXDOMAIN once the server
78
+ * is stopping) is no unhandled rejection. */
77
79
  const abortable = (work, signal) => new Promise((resolve, reject) => {
78
- if (signal.aborted)
79
- return reject(signal.reason);
80
80
  const onAbort = () => reject(signal.reason);
81
- signal.addEventListener("abort", onAbort, { once: true });
81
+ if (signal.aborted)
82
+ onAbort();
83
+ else
84
+ signal.addEventListener("abort", onAbort, { once: true });
82
85
  work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
83
86
  });
84
87
  export { signatureOf } from "./standard-webhooks.js";
@@ -627,6 +630,8 @@ export class Webhooks {
627
630
  }
628
631
  attempt.latency_ms = Math.round(performance.now() - started);
629
632
  }
633
+ // In its words, written or not: a try the server's stop cut short still says why it ended.
634
+ attempt.error = failure ?? null;
630
635
  if (this.closed)
631
636
  return attempt;
632
637
  // What the try found is settled against the webhook as it stands once every change asked for before it (a PUT, a
@@ -644,7 +649,6 @@ export class Webhooks {
644
649
  async settleTry(id, how, now, tryId, claimed, config, failure, attempt) {
645
650
  if (this.closed)
646
651
  return attempt;
647
- attempt.error = failure ?? null;
648
652
  // The schedule counts the message's own tries, from the count its claim took it at; a redelivery counts none.
649
653
  const attempts = claimed ? claimed.attempts + 1 : undefined;
650
654
  // A 410 turns off the webhook as this try found it: one set again or removed while the try waited is not its to turn
@@ -1,4 +1,4 @@
1
- import { type AttachHub, type ComputerSpec, type DockerVolume } from "@parcha/agentrun-computer";
1
+ import { type AttachHub, type ComputerSpec, type DockerVolume, type HostedDial } from "@parcha/agentrun-computer";
2
2
  import type { DockerPaths } from "../box-paths.js";
3
3
  import { type HostRead } from "../docker-host-addresses.js";
4
4
  import { type ProviderFactories } from "../computer-keys.js";
@@ -56,6 +56,10 @@ export interface ComputerDepsOptions {
56
56
  /** The server's AttachHub, where this runner shares the server's process (runner/beside.ts): a paired computer's
57
57
  * socket is there. Absent: a runner of its own process, which refuses a paired computer in words. */
58
58
  readonly hub?: AttachHub;
59
+ /** The server's dial (Serve.dial), where this runner shares the server's process: every remote provider's create
60
+ * takes it, and one whose host dials the server (facts.connect "dial") mints its machine's token there. Absent: a
61
+ * runner of its own process, where such a provider's create refuses in words. */
62
+ readonly dial?: HostedDial;
59
63
  /** The server's seal key: absent, no saved key is opened (a key from the environment still is). */
60
64
  readonly sealKey: Buffer | undefined;
61
65
  /** The kind registry: the computer package's unless given (a test's fixture). */
@@ -293,11 +293,11 @@ export function computerDepsFrom(options) {
293
293
  * Chrome's, where it finds Chrome), and no other variable of the server's. */
294
294
  const hostEnvOf = (names) => Object.fromEntries(names.flatMap((name) => (env[name] === undefined ? [] : [[name, String(env[name])]])));
295
295
  /** The options a provider takes beside its keys, by what its descriptor declares, never by its id: for a local one,
296
- * its image source and its host options; the host environment it reads. */
296
+ * its image source and its host options; for a remote one, the server's dial; the host environment it reads. */
297
297
  const declaredOptions = async (id, boxAllow) => {
298
298
  const entry = kinds.PROVIDERS.find((one) => one.id === id);
299
299
  return {
300
- ...(entry?.local ? { image: preparedImage, ...(await localHostOptions(boxAllow)) } : {}),
300
+ ...(entry?.local ? { image: preparedImage, ...(await localHostOptions(boxAllow)) } : options.dial ? { dial: options.dial } : {}),
301
301
  ...(entry?.hostEnv ? { env: hostEnvOf(entry.hostEnv) } : {}),
302
302
  };
303
303
  };
@@ -15,6 +15,7 @@ export { type LearningPlace, type LearningWorkspace, learningWorkspace, type Lea
15
15
  export { ARCHIL_MAX_EXEC_S, handsOf, MAX_EXEC_S, processesOf, shellEnv } from "./hands.js";
16
16
  export { type AgentComputer, type RunComputer, type RunHold, runTools, type RunTools, type ScriptComputer, withKindTools } from "./run-tools.js";
17
17
  export { NO_PROGRAMS_WORDS, portOf } from "./computer-ports.js";
18
+ export { registryHere } from "./resolve-computer.js";
18
19
  export { COMPUTER_MCP_NAME, computerMcp, type ComputerMcpAnswer, mcpAnswerOf } from "./computer-mcp.js";
19
20
  export { type ClaimSide, computerReadiness, type ComputerSetting, type KindRegistry, type LaunchedComputer, type Port, resolveComputer, type ResolvedComputer, runShellOf, type ShellPlace, shellPlaceOf, type StartedComputer, } from "./resolve-computer.js";
20
21
  export { computerProviderFactories, computerProviderMakers, type ProviderLoad } from "./computer-providers.js";
@@ -16,6 +16,8 @@ export { learningWorkspace } from "./learning-workspace.js";
16
16
  export { ARCHIL_MAX_EXEC_S, handsOf, MAX_EXEC_S, processesOf, shellEnv } from "./hands.js";
17
17
  export { runTools, withKindTools } from "./run-tools.js";
18
18
  export { NO_PROGRAMS_WORDS, portOf } from "./computer-ports.js";
19
+ // Each provider as this server has it (the mounts its keys turn on), on a line of its own.
20
+ export { registryHere } from "./resolve-computer.js";
19
21
  export { COMPUTER_MCP_NAME, computerMcp, mcpAnswerOf } from "./computer-mcp.js";
20
22
  export { computerReadiness, resolveComputer, runShellOf, shellPlaceOf, } from "./resolve-computer.js";
21
23
  export { computerProviderFactories, computerProviderMakers } from "./computer-providers.js";
@@ -121,6 +121,33 @@ export type Port = "files" | "exec" | "processes" | "screen" | "input" | "phone"
121
121
  /** A provider's keys as the claim reads them: each key its registry entry declares, by `keyOf` (the server's reader:
122
122
  * key-meta.ts keyReader, the environment's value, else the saved one); a key with no value is left out. */
123
123
  export declare const providerKeys: (registry: Pick<KindRegistry, "PROVIDERS">, keyOf: (name: string) => Promise<string | undefined>) => ClaimSide["keysOf"];
124
+ /** What a provider is on this server beside its descriptor: the mounts the operator's keys turn on, and whether the
125
+ * operator names its image here. */
126
+ type HereFields = {
127
+ readonly mounts: readonly string[];
128
+ readonly unmounted?: Readonly<Partial<Record<string, string>>>;
129
+ readonly mountsWith?: Readonly<Partial<Record<string, string>>>;
130
+ readonly imageEnv?: string;
131
+ readonly prepareImage?: boolean;
132
+ /** Its descriptor's imageEnv has a value here: the operator names the image every computer of it starts from. */
133
+ readonly imageNamed?: true;
134
+ };
135
+ /** `entry` as this server has it, by `set` (whether a key, or a setting of this server, has a value here): with the
136
+ * mounts the operator's keys turn on (its descriptor's mountsWith, by the computer package's mountsOf: Daytona's Archil
137
+ * mount where DAYTONA_ARCHIL_EGRESS names a self-hosted target's Archil egress relay), and imageNamed where its
138
+ * descriptor's imageEnv names its image here (Daytona's AGENTRUN_DAYTONA_SNAPSHOT). Any other entry as it is. Every
139
+ * reader of an entry's mounts (Settings → Computers, the claim, a run's start, its shell) reads this, so the
140
+ * provider made with those keys and the server agree on what it mounts. */
141
+ export declare function entryHere<Entry extends HereFields>(entry: Entry, set: (name: string) => boolean): Entry;
142
+ /** `registry` with each provider as this server has it (entryHere), reading only the names an entry's mountsWith or
143
+ * imageEnv names, by `valueOf` (key-meta.ts keyReader: the environment's value, else the saved key). A value of
144
+ * whitespace alone is none. */
145
+ export declare function registryHere<Registry extends {
146
+ readonly PROVIDERS: readonly ProviderEntry[];
147
+ }>(registry: Registry, valueOf: (name: string) => Promise<string | undefined>): Promise<Registry>;
148
+ /** Whether a computer of `entry` that mounts the owner's Archil disk has Archil's image in the owner's vendor account:
149
+ * its provider prepares it (prepareImage), or the operator names it here (imageNamed, entryHere). */
150
+ export declare const archilImageHere: (entry: HereFields) => boolean;
124
151
  /** Whether a provider's computers run only on the vendor's own network: the network forms it declares (its
125
152
  * descriptor's, its capabilities().network) are "open" alone, as a cloud phone's and a hosted browser's are. */
126
153
  export declare const vendorNetworkOnly: (network: readonly string[] | undefined) => boolean;
@@ -133,8 +160,10 @@ export declare const aLabel: (label: string, start?: boolean) => string;
133
160
  /** Why a sandbox or a desktop that would mount the owner's Archil disk can't start in Mode 2: the mount needs Archil's
134
161
  * image in the owner's own vendor account, and this server can't put it there yet. A provider that prepares its image
135
162
  * (prepareImage: Agent37 registers the box image in the owner's workspace, Modal pulls it, E2B starts its public
136
- * template) is never refused so; today every provider that mounts the disk does. Settings (computers.ts modeRefusal) and a run's start (computerReadiness) say it. */
137
- export declare const mode2ArchilWhy: (label: string, kind: "sandbox" | "desktop") => string;
163
+ * template) is never refused so, nor one whose image the operator names here (archilImageHere: Daytona's
164
+ * AGENTRUN_DAYTONA_SNAPSHOT). For such a one, `imageEnv` says where to name it. Settings (computers.ts modeRefusal)
165
+ * and a run's start (computerReadiness) say it. */
166
+ export declare const mode2ArchilWhy: (label: string, kind: "sandbox" | "desktop", imageEnv?: string) => string;
138
167
  /** Why a computer that needs a network is refused where this server's AGENTRUN_BOX_ALLOW is none, in words that name the
139
168
  * fix: the operator said no network at all, and the computer can't run without one. */
140
169
  export declare const noNetworkRefusal: (label: string, kind: string) => string;
@@ -153,7 +182,7 @@ export declare const noNetworkRefusal: (label: string, kind: string) => string;
153
182
  *
154
183
  * `hostWhy`: why this machine cannot run a provider's computers, in words that say how to fix it (computers.ts
155
184
  * hostCommandRefusals, read at the server's start: the phone's adb not on PATH), or undefined. Absent: not asked. */
156
- export declare function computerReadiness(setting: ComputerSetting, mode: 1 | 2, registry: KindRegistry, keyOf: (name: string) => Promise<string | undefined>, answers?: (provider: string) => DockerDaemon | Promise<DockerDaemon>, boxAllow?: readonly string[] | "none", hostWhy?: (provider: string) => string | undefined): Promise<{
185
+ export declare function computerReadiness(setting: ComputerSetting, mode: 1 | 2, given: KindRegistry, keyOf: (name: string) => Promise<string | undefined>, answers?: (provider: string) => DockerDaemon | Promise<DockerDaemon>, boxAllow?: readonly string[] | "none", hostWhy?: (provider: string) => string | undefined): Promise<{
157
186
  readonly ok: true;
158
187
  } | {
159
188
  readonly refused: string;