@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,300 @@
1
+ // A feed's body read into its items (trigger-feed.ts): RSS 2.0 (and 1.0), Atom, JSON Feed, or a JSON list (an API's
2
+ // array of objects, GitHub's pulls, read at an items pointer and keyed at an id pointer). XML is read with
3
+ // fast-xml-parser, checked well-formed first, and one that declares entities is refused: none is ever expanded, and only
4
+ // XML's five named references and numeric ones decode. Every text is untrusted and bounded; HTML is read as text (its
5
+ // tags dropped, its entities decoded, a block a line).
6
+ import { createHash } from "node:crypto";
7
+ import { XMLParser, XMLValidator } from "fast-xml-parser";
8
+ /** The most characters of an item's summary its payload holds. */
9
+ export const SUMMARY_CHARS = 4000;
10
+ /** The most characters of a title. */
11
+ const TITLE_CHARS = 1000;
12
+ /** The most characters of any other text field (an id, a link, an author, a category). */
13
+ const FIELD_CHARS = 2000;
14
+ /** The most categories an item's payload lists. */
15
+ const CATEGORIES = 50;
16
+ /** A body that is no feed this reads: its words. */
17
+ export class FeedUnreadable extends Error {
18
+ name = "FeedUnreadable";
19
+ }
20
+ const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
21
+ const hash = (text) => createHash("sha256").update(text).digest("hex").slice(0, 16);
22
+ const NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", mdash: "—", ndash: "–", hellip: "…", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“", copy: "©", reg: "®", trade: "™", middot: "·", bull: "•" };
23
+ /** `text`'s HTML character references decoded (the named ones above, and every numeric one). */
24
+ const entities = (text) => text.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (whole, ref) => {
25
+ if (ref[0] === "#") {
26
+ const code = ref[1] === "x" || ref[1] === "X" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);
27
+ return code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff) ? String.fromCodePoint(code) : "";
28
+ }
29
+ return NAMED[ref.toLowerCase()] ?? whole;
30
+ });
31
+ const BLOCK = /<\s*\/?\s*(?:p|div|br|li|ul|ol|dl|dt|dd|h[1-6]|tr|table|thead|tbody|blockquote|pre|section|article|header|footer|hr|figure|figcaption)\b[^>]*>/gi;
32
+ /** HTML as text: scripts and styles dropped, each block its own line, other tags dropped, references decoded, the spaces
33
+ * in each line collapsed and empty lines dropped. */
34
+ export function htmlToText(html) {
35
+ const text = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi, "").replace(BLOCK, "\n").replace(/<[^>]*>/g, "");
36
+ return lines(entities(text));
37
+ }
38
+ /** Plain text: the spaces in each line collapsed, empty lines dropped. */
39
+ const lines = (text) => text.split(/\r?\n/).map((line) => line.replace(/[ \t \f\v\r]+/g, " ").trim()).filter(Boolean).join("\n");
40
+ /** An instant from an RFC 3339 or RFC 822 date, or null. */
41
+ function instant(value) {
42
+ const text = textOf(value);
43
+ if (!text)
44
+ return null;
45
+ const at = Date.parse(text);
46
+ return Number.isFinite(at) ? at : null;
47
+ }
48
+ /** A parsed XML node's text: a string as it is; an element with attributes, its text node; a list, its first. */
49
+ function textOf(node) {
50
+ if (Array.isArray(node))
51
+ return textOf(node[0]);
52
+ if (typeof node === "string")
53
+ return node;
54
+ if (typeof node === "number" || typeof node === "boolean")
55
+ return String(node);
56
+ if (node && typeof node === "object") {
57
+ // Its text and its CDATA, kept apart by the parser: each as it reads (both, in the rare node with both).
58
+ const parts = [node["#text"], ...list(node["#cdata"])].filter((one) => typeof one === "string" || typeof one === "number");
59
+ return parts.length ? parts.map(String).join(" ") : undefined;
60
+ }
61
+ return undefined;
62
+ }
63
+ /** A node's text, trimmed and bounded, or null when it holds none. */
64
+ const field = (node, max = FIELD_CHARS) => {
65
+ const text = textOf(node)?.trim();
66
+ return text ? clip(text, max) : null;
67
+ };
68
+ /** An Atom text construct (a title, a summary, a content) as text: type html read as HTML, text as text; type xhtml (its
69
+ * XHTML inline, which the parser keeps by name, out of order) as the HTML its `ordered` reading writes. */
70
+ const atomText = (node, ordered) => {
71
+ const type = node && typeof node === "object" && !Array.isArray(node) ? node["@_type"] : undefined;
72
+ if (type === "xhtml" && ordered !== undefined)
73
+ return htmlToText(ordered) || null;
74
+ const text = textOf(node);
75
+ if (!text?.trim())
76
+ return null;
77
+ return type === "html" || type === "xhtml" ? htmlToText(text) || null : lines(text) || null;
78
+ };
79
+ const list = (node) => (node === undefined || node === null ? [] : Array.isArray(node) ? node : [node]);
80
+ const attr = (node, name) => (node && typeof node === "object" && !Array.isArray(node) ? textOf(node[`@_${name}`]) : undefined);
81
+ /** The key an item is known by: its id, else its link, else a hash of its title and date (`hash:` and 16 hex). */
82
+ const keyOf = (id, link, title, date, rest) => id ?? link ?? `hash:${hash(`${title ?? rest ?? ""}\n${date === null ? "" : new Date(date).toISOString()}`)}`;
83
+ function item(fields) {
84
+ return { key: keyOf(fields.id, fields.link, fields.title, fields.published ?? fields.updated, fields.summary), ...fields };
85
+ }
86
+ /** XML's own references decoded in one pass, so each decodes once ("&amp;lt;" is "&lt;"): the five XML names and every
87
+ * numeric character reference. Any other name stays as it is written; a document that declares one is refused first. */
88
+ const xmlRefs = (text) => text.indexOf("&") === -1 ? text : text.replace(/&(?:(amp|lt|gt|quot|apos)|#(\d{1,7})|#x([0-9a-f]{1,6}));/gi, (whole, name, dec, hex) => {
89
+ if (name)
90
+ return XML_NAMED[name] ?? whole;
91
+ const code = dec !== undefined ? parseInt(dec, 10) : parseInt(hex, 16);
92
+ return code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff) ? String.fromCodePoint(code) : "";
93
+ });
94
+ const XML_NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
95
+ // The parser expands nothing (processEntities off: no DOCTYPE entity, and no count of references to cap a long feed);
96
+ // text and attribute values are decoded here instead, and a CDATA section is kept apart (#cdata), as it is written.
97
+ const XML = new XMLParser({
98
+ ignoreAttributes: false,
99
+ attributeNamePrefix: "@_",
100
+ textNodeName: "#text",
101
+ cdataPropName: "#cdata",
102
+ parseTagValue: false,
103
+ parseAttributeValue: false,
104
+ trimValues: true,
105
+ processEntities: false,
106
+ htmlEntities: false,
107
+ removeNSPrefix: true,
108
+ tagValueProcessor: (_name, value) => xmlRefs(value),
109
+ attributeValueProcessor: (_name, value) => xmlRefs(value),
110
+ isArray: (name) => ["item", "entry", "category", "link", "author", "creator"].includes(name),
111
+ });
112
+ // The same reading with each element's children in the order they are written (an xhtml text construct's), the spaces
113
+ // between them kept.
114
+ const ORDERED = new XMLParser({
115
+ ignoreAttributes: false,
116
+ attributeNamePrefix: "@_",
117
+ textNodeName: "#text",
118
+ cdataPropName: "#cdata",
119
+ parseTagValue: false,
120
+ parseAttributeValue: false,
121
+ trimValues: false,
122
+ processEntities: false,
123
+ htmlEntities: false,
124
+ removeNSPrefix: true,
125
+ preserveOrder: true,
126
+ tagValueProcessor: (_name, value) => xmlRefs(value),
127
+ attributeValueProcessor: (_name, value) => xmlRefs(value),
128
+ });
129
+ const nameOf = (node) => Object.keys(node).find((key) => key !== ":@");
130
+ const children = (node, name) => (node && Array.isArray(node[name]) ? node[name] : []);
131
+ const escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
132
+ /** Ordered nodes written back as HTML: each element's tag around its children, text escaped, CDATA as text. */
133
+ const markup = (nodes) => nodes
134
+ .map((node) => {
135
+ const name = nameOf(node);
136
+ if (name === undefined)
137
+ return "";
138
+ if (name === "#text")
139
+ return escapeHtml(String(node[name]));
140
+ if (name === "#cdata")
141
+ return children(node, name).map((one) => escapeHtml(String(one["#text"] ?? ""))).join("");
142
+ return `<${name}>${markup(children(node, name))}</${name}>`;
143
+ })
144
+ .join("");
145
+ /** Each xhtml text construct of an Atom document as HTML, written in order: the feed's title, and each entry's (in the
146
+ * order the entries are) title, summary and content; undefined for one that is not xhtml or not there. */
147
+ function atomXhtml(text) {
148
+ const doc = ORDERED.parse(text);
149
+ const feed = doc.find((node) => nameOf(node) === "feed");
150
+ const of = (parent, field) => {
151
+ const node = children(parent, parent ? nameOf(parent) : "").find((one) => nameOf(one) === field);
152
+ return node && node[":@"]?.["@_type"] === "xhtml" ? markup(children(node, field)) : undefined;
153
+ };
154
+ return {
155
+ title: of(feed, "title"),
156
+ entries: children(feed, "feed").filter((node) => nameOf(node) === "entry").map((entry) => ({ title: of(entry, "title"), summary: of(entry, "summary"), content: of(entry, "content") })),
157
+ };
158
+ }
159
+ /** `body` read as a feed. A JSON document is a JSON Feed (its `version` says so) unless `pointers` name a list, else a
160
+ * JSON list; anything else is read as XML: RSS or Atom. Throws FeedUnreadable in words. */
161
+ export function parseFeed(body, pointers = {}) {
162
+ const text = body.replace(/^/, "").trim();
163
+ if (!text)
164
+ throw new FeedUnreadable("its answer is empty");
165
+ if (text[0] === "{" || text[0] === "[") {
166
+ let doc;
167
+ try {
168
+ doc = JSON.parse(text);
169
+ }
170
+ catch {
171
+ throw new FeedUnreadable("its answer is not JSON, RSS or Atom");
172
+ }
173
+ const jsonFeed = doc !== null && typeof doc === "object" && !Array.isArray(doc) && typeof doc.version === "string" && String(doc.version).startsWith("https://jsonfeed.org/version/");
174
+ return jsonFeed && pointers.items === undefined && pointers.id === undefined ? jsonFeedOf(doc) : jsonListOf(doc, pointers);
175
+ }
176
+ // No entity is ever expanded: a document that declares one is refused before it is parsed.
177
+ if (/<!ENTITY/i.test(text))
178
+ throw new FeedUnreadable("it declares XML entities, which a feed is read without");
179
+ const valid = XMLValidator.validate(text);
180
+ if (valid !== true)
181
+ throw new FeedUnreadable(`it is not well-formed XML (line ${valid.err.line}: ${clip(valid.err.msg.replace(/\s+/g, " "), 200)})`);
182
+ let doc;
183
+ try {
184
+ doc = XML.parse(text);
185
+ }
186
+ catch (error) {
187
+ throw new FeedUnreadable(`it is not well-formed XML (${clip(String(error?.message ?? error), 200)})`);
188
+ }
189
+ const rss = doc.rss;
190
+ if (rss && typeof rss === "object") {
191
+ const channel = list(rss.channel)[0];
192
+ const read = channel && typeof channel === "object" ? channel : {};
193
+ return rssOf(read, list(read.item));
194
+ }
195
+ const rdf = doc.RDF;
196
+ if (rdf && typeof rdf === "object")
197
+ return rssOf(list(rdf.channel)[0] ?? {}, list(rdf.item));
198
+ const atom = doc.feed;
199
+ if (atom && typeof atom === "object")
200
+ return atomOf(atom, /\btype\s*=\s*["']xhtml["']/.test(text) ? atomXhtml(text) : undefined);
201
+ throw new FeedUnreadable("it is not RSS, Atom, JSON Feed or a JSON list");
202
+ }
203
+ function rssOf(channel, items) {
204
+ return {
205
+ list: false,
206
+ title: field(channel.title, TITLE_CHARS),
207
+ items: items.filter((one) => !!one && typeof one === "object").map((one) => {
208
+ const guid = field(one.guid);
209
+ const permalink = attr(one.guid, "isPermaLink") !== "false";
210
+ // An RSS item's link is text; an atom:link inside it (its prefix dropped) has an href.
211
+ const link = list(one.link).map((l) => (typeof l === "string" ? l.trim() : attr(l, "href"))).find((l) => !!l) ?? (guid && permalink && /^https?:\/\//i.test(guid) ? guid : null);
212
+ const description = textOf(one.description) ?? textOf(one.encoded);
213
+ return item({
214
+ // A title is text, as written: never read as HTML, so nothing in it is dropped.
215
+ id: guid, link: link ? clip(link, FIELD_CHARS) : null, title: (() => {
216
+ const title = lines(textOf(one.title) ?? "");
217
+ return title ? clip(title, TITLE_CHARS) : null;
218
+ })(),
219
+ published: instant(one.pubDate) ?? instant(one.date), updated: instant(one.updated),
220
+ author: field(one.author) ?? field(one.creator),
221
+ summary: description ? clip(htmlToText(description), SUMMARY_CHARS) || null : null,
222
+ categories: list(one.category).map((c) => field(c)).filter((c) => !!c).slice(0, CATEGORIES),
223
+ });
224
+ }),
225
+ };
226
+ }
227
+ /** An Atom feed; `xhtml`, its xhtml text constructs written in order (atomXhtml), when it has any. */
228
+ function atomOf(feed, xhtml) {
229
+ return {
230
+ list: false,
231
+ title: (() => {
232
+ const title = atomText(feed.title, xhtml?.title);
233
+ return title ? clip(title, TITLE_CHARS) : null;
234
+ })(),
235
+ items: list(feed.entry).map((one, i) => [one, xhtml?.entries[i]]).filter((pair) => !!pair[0] && typeof pair[0] === "object").map(([one, ordered]) => {
236
+ const links = list(one.link);
237
+ const alternate = links.find((l) => (attr(l, "rel") ?? "alternate") === "alternate" && attr(l, "href")) ?? links.find((l) => attr(l, "href"));
238
+ const summary = atomText(one.summary, ordered?.summary) ?? atomText(one.content, ordered?.content);
239
+ const title = atomText(one.title, ordered?.title);
240
+ return item({
241
+ id: field(one.id), link: alternate ? clip(attr(alternate, "href").trim(), FIELD_CHARS) : null, title: title ? clip(title, TITLE_CHARS) : null,
242
+ published: instant(one.published) ?? instant(one.issued), updated: instant(one.updated) ?? instant(one.modified),
243
+ author: field(list(one.author)[0]?.name),
244
+ summary: summary ? clip(summary, SUMMARY_CHARS) : null,
245
+ categories: list(one.category).map((c) => attr(c, "term") ?? field(c)).filter((c) => !!c).map((c) => clip(c, FIELD_CHARS)).slice(0, CATEGORIES),
246
+ });
247
+ }),
248
+ };
249
+ }
250
+ const str = (value, max = FIELD_CHARS) => (typeof value === "string" && value.trim() ? clip(value.trim(), max) : typeof value === "number" && Number.isFinite(value) ? String(value) : null);
251
+ function jsonFeedOf(doc) {
252
+ const items = Array.isArray(doc.items) ? doc.items : [];
253
+ return {
254
+ list: false,
255
+ title: str(doc.title, TITLE_CHARS),
256
+ items: items.filter((one) => !!one && typeof one === "object" && !Array.isArray(one)).map((one) => {
257
+ const authors = Array.isArray(one.authors) ? one.authors : one.author ? [one.author] : [];
258
+ const author = authors.map((a) => (a && typeof a === "object" ? str(a.name) : null)).find(Boolean) ?? null;
259
+ const summary = typeof one.summary === "string" && one.summary.trim() ? lines(one.summary) : typeof one.content_text === "string" && one.content_text.trim() ? lines(one.content_text) : typeof one.content_html === "string" ? htmlToText(one.content_html) : "";
260
+ return item({
261
+ id: str(one.id), link: str(one.url) ?? str(one.external_url), title: str(one.title, TITLE_CHARS),
262
+ published: instant(one.date_published), updated: instant(one.date_modified), author,
263
+ summary: summary ? clip(summary, SUMMARY_CHARS) : null,
264
+ categories: (Array.isArray(one.tags) ? one.tags : []).map((tag) => str(tag)).filter((tag) => !!tag).slice(0, CATEGORIES),
265
+ });
266
+ }),
267
+ };
268
+ }
269
+ /** The value at JSON Pointer `pointer` in `doc`, or undefined. */
270
+ export function pointed(doc, pointer) {
271
+ if (pointer === "")
272
+ return doc;
273
+ let at = doc;
274
+ for (const raw of pointer.split("/").slice(1)) {
275
+ const part = raw.replace(/~1/g, "/").replace(/~0/g, "~");
276
+ if (Array.isArray(at) && /^(0|[1-9]\d*)$/.test(part))
277
+ at = at[Number(part)];
278
+ else if (at && typeof at === "object" && !Array.isArray(at) && Object.hasOwn(at, part))
279
+ at = at[part];
280
+ else
281
+ return undefined;
282
+ }
283
+ return at;
284
+ }
285
+ function jsonListOf(doc, { items: itemsAt = "", id: idAt = "/id" }) {
286
+ const items = pointed(doc, itemsAt);
287
+ if (!Array.isArray(items))
288
+ throw new FeedUnreadable(itemsAt ? `nothing at ${itemsAt} in its JSON is a list` : "its JSON is no list, and the trigger names no items pointer to one");
289
+ return {
290
+ list: true,
291
+ title: null,
292
+ items: items.filter((one) => one !== null && typeof one === "object").map((one) => {
293
+ const object = one;
294
+ const id = str(pointed(object, idAt));
295
+ const link = str(object.html_url) ?? str(object.url) ?? str(object.link);
296
+ const title = str(object.title, TITLE_CHARS) ?? str(object.name, TITLE_CHARS);
297
+ return { key: id ?? link ?? `hash:${hash(title ?? JSON.stringify(one))}`, id, link, title, published: null, updated: null, author: null, summary: null, categories: [], raw: one };
298
+ }),
299
+ };
300
+ }
@@ -112,7 +112,9 @@ export declare function answerTierProblems(doc: unknown): string[];
112
112
  /** Why a draft's quote check is not code: its answer carries quotes (a `quote` or `quotes` property in its output schema)
113
113
  * and it fetches pages (a call step), yet some place in the answer holding quotes has no escalate on quote_missing
114
114
  * reading it after the answer is written (quoteRule), or that escalate reads as a page a key holding no page as fetched
115
- * (a model's summary of a page is no page). A judge or an `ask` is never the quote check:
115
+ * (a model's summary of a page is no page), or, those checks in place, the step writing the answer hands back on its
116
+ * first miss instead of re-picking once (a loop of REPICK_PASSES until its check passes), or its quotes have more than
117
+ * one check (a loop's `until` waits on one: the others would hand back with no re-pick). A judge or an `ask` is never the quote check:
116
118
  * H5's judge flagged 149 of 170 answers while 416 of 429 quotes were in the pages, and could not tell the 8 answers
117
119
  * quoting text no page held from the rest; code can. One line each, in words the compile retry acts on. */
118
120
  export declare function quoteCheckProblems(doc: unknown): string[];
@@ -377,13 +377,47 @@ const writesKey = (node, key) => isNode(node) && (writeKeyOf(node) === key || (n
377
377
  /** Why a draft's quote check is not code: its answer carries quotes (a `quote` or `quotes` property in its output schema)
378
378
  * and it fetches pages (a call step), yet some place in the answer holding quotes has no escalate on quote_missing
379
379
  * reading it after the answer is written (quoteRule), or that escalate reads as a page a key holding no page as fetched
380
- * (a model's summary of a page is no page). A judge or an `ask` is never the quote check:
380
+ * (a model's summary of a page is no page), or, those checks in place, the step writing the answer hands back on its
381
+ * first miss instead of re-picking once (a loop of REPICK_PASSES until its check passes), or its quotes have more than
382
+ * one check (a loop's `until` waits on one: the others would hand back with no re-pick). A judge or an `ask` is never the quote check:
381
383
  * H5's judge flagged 149 of 170 answers while 416 of 429 quotes were in the pages, and could not tell the 8 answers
382
384
  * quoting text no page held from the rest; code can. One line each, in words the compile retry acts on. */
383
385
  export function quoteCheckProblems(doc) {
384
386
  return isObject(doc) ? quoteRule(doc, {}).problems : [];
385
387
  }
386
388
  const siteKey = (site) => site.keys.join("\u0000");
389
+ /** The passes of a checked answer's re-pick loop: the draft, then one re-pick. */
390
+ const REPICK_PASSES = 2;
391
+ const quoteMissingText = ({ path, field, pages }) => `{"predicate": "quote_missing", "path": ${JSON.stringify(path)}${field ? `, "field": ${JSON.stringify(field)}` : ""}, "pages": ${JSON.stringify(pages)}}`;
392
+ /** Whether `step` is the re-pick of an answer `check` reads: a loop of REPICK_PASSES until that check's quote_missing (its
393
+ * path, field and pages) no longer holds. */
394
+ const repicks = (step, check) => {
395
+ if (!isNode(step) || step.node !== "loop" || step.maxIters !== REPICK_PASSES || !isObject(step.until) || step.until.predicate !== "not" || !isObject(step.until.of))
396
+ return false;
397
+ const of = step.until.of;
398
+ return of.predicate === "quote_missing" && of.path === check.path && (of.field ?? "") === check.field && JSON.stringify(of.pages) === JSON.stringify(check.pages);
399
+ };
400
+ /** The labels of the steps inside `node` (a loop's body) that write state key `key` from a `state` map. The DSL sends
401
+ * such a step only the keys its map names (each pass a fresh model session), so on a re-pick it never sees the failed
402
+ * draft, and a map naming the answer fails the first pass, which has none yet: only a step with no map reads the whole
403
+ * state. A map's or a composed workflow's own steps write their item's or child's state, not this one. */
404
+ const answersFromStateMap = (node, key, depth = 0) => {
405
+ if (!isNode(node) || depth > 32)
406
+ return [];
407
+ const own = writeKeyOf(node) === key && node.state !== undefined ? [String(node.label ?? node.node).slice(0, 64)] : [];
408
+ const inner = node.node === "map" || node.node === "workflow" ? [] : childNodes(node).flatMap((child) => answersFromStateMap(child, key, depth + 1));
409
+ return [...own, ...inner];
410
+ };
411
+ /** The labels of the quote_missing escalates inside `node` (a loop's body), a composed workflow's included: each hands
412
+ * back on the first pass's miss, so a re-pick loop around one never re-picks. */
413
+ const quoteEscalatesIn = (node, depth = 0) => {
414
+ if (!isNode(node) || depth > 32)
415
+ return [];
416
+ if (node.node === "escalate")
417
+ return isObject(node.when) && node.when.predicate === "quote_missing" ? [String(node.label ?? "(no label)").slice(0, 64)] : [];
418
+ const inner = node.node === "workflow" && isObject(node.workflow) ? [node.workflow.root] : childNodes(node);
419
+ return inner.flatMap((child) => quoteEscalatesIn(child, depth + 1));
420
+ };
387
421
  /** quoteCheckProblems for one workflow (the draft's, or a composed workflow node's child, its schemas its own else
388
422
  * `schemasAround`): whether the rule applies (its answer carries quotes and it fetches pages), and why it fails. Only a
389
423
  * run's path through its top-level chain is sure to pass a step: a check is an escalate on quote_missing that is a step
@@ -439,7 +473,7 @@ function quoteRule(workflow, schemasAround, depth = 0) {
439
473
  const field = read.field ?? "";
440
474
  if (checks.some((check) => check.path === path && check.field === field))
441
475
  continue;
442
- const predicate = `{"predicate": "quote_missing", "path": ${JSON.stringify(path)}${field ? `, "field": ${JSON.stringify(field)}` : ""}, "pages": ${JSON.stringify(pages)}}`;
476
+ const predicate = quoteMissingText({ path, field, pages });
443
477
  problems.push(`the answer carries quotes (${where(site)}) and the workflow fetches pages: check them in code, with an escalate ${predicate} as a step of its top-level chain after the step that writes the answer (pages: the state keys its call steps write), never a judge`);
444
478
  }
445
479
  for (const { label, pages: read } of checks)
@@ -448,6 +482,27 @@ function quoteRule(workflow, schemasAround, depth = 0) {
448
482
  if (!pages.includes(head))
449
483
  problems.push(`the quote_missing escalate ${JSON.stringify(label)} reads ${JSON.stringify(String(page).slice(0, 64))} as a page, which no call step fetched: its pages are the state keys its call steps write (${pages.join(", ")})`);
450
484
  }
485
+ // Once the checks hold, the answer re-picks once before one hands back (H5d, preregistered: the answer step once more
486
+ // over the run's pages kept 26 of 31 misses, right 76.9% against the draft's 50.0%, at 11.6% of the agent's cost
487
+ // where handing every miss back cost 21.7%): the step writing it is a loop of REPICK_PASSES until its check passes.
488
+ // A loop's `until` is one predicate and none joins two, so the loop waits on every check only when they are all one
489
+ // check (the same path, field and pages): a loop watching one of several lets the others hand back with no re-pick.
490
+ const [first] = checks;
491
+ const distinct = new Set(checks.map(quoteMissingText)).size;
492
+ if (!problems.length && distinct > 1) {
493
+ problems.push(`the answer's quotes are checked by ${distinct} different quote_missing escalates, and a re-pick loop's "until" reads one check (no predicate joins two), so the loop would let the others hand back with no re-pick: give the answer's quotes one place one check reads (a quote, a list of quotes or a list of records each holding its quote at one field), one quote_missing escalate on it after the step that writes the answer, and that step the body of a loop {"node": "loop", "label": "repick", "maxIters": ${REPICK_PASSES}, "until": {"predicate": "not", "of": <that same quote_missing>}, "body": <the step>}`);
494
+ }
495
+ else if (!problems.length && first && isNode(writer) && writer.node === "loop" && quoteEscalatesIn(writer.body).length) {
496
+ // A check inside the loop's body hands back on the first draft's miss: the loop never re-picks.
497
+ problems.push(`the re-pick loop ${JSON.stringify(String(writer.label ?? "(no label)").slice(0, 64))} holds the quote_missing escalate ${JSON.stringify(quoteEscalatesIn(writer.body)[0])} in its body, which hands back on the first draft's miss, so the loop never re-picks: the check after the loop, never inside it, as a step of the top-level chain`);
498
+ }
499
+ else if (!problems.length && first && isNode(writer) && writer.node === "loop" && repicks(writer, first) && answersFromStateMap(writer.body, answerPath.split(".")[0]).length) {
500
+ // The re-pick must see the failed draft: its step reads the whole state (no `state` map).
501
+ problems.push(`the step ${JSON.stringify(answersFromStateMap(writer.body, answerPath.split(".")[0])[0])} in the re-pick loop ${JSON.stringify(String(writer.label ?? "(no label)").slice(0, 64))} writes the answer from a "state" map, which passes it only the keys it names, so its second pass never sees the failed draft (and naming the answer there fails the first pass, before any draft exists): give it no "state" map, so it reads the whole run state, the failed draft included`);
502
+ }
503
+ else if (!problems.length && first && !checks.every((check) => repicks(writer, check))) {
504
+ problems.push(`the step ${JSON.stringify(String(isNode(writer) ? writer.label ?? writer.node : "(no label)").slice(0, 64))} writes the answer and the escalate ${JSON.stringify(first.label)} hands it back on its first quote miss: give it one re-pick first, the step in a loop {"node": "loop", "label": "repick", "maxIters": ${REPICK_PASSES}, "until": {"predicate": "not", "of": ${quoteMissingText(first)}}, "body": <the step>} in its place, its instructions saying that a draft already in state failed the quote check, so a draft quoting text no page holds is written once more and only a second miss hands back: the check after the loop, never inside it`);
505
+ }
451
506
  }
452
507
  // A composed workflow writing the answer that applies the rule and fails it: its own check is the one to fix.
453
508
  if (problems.length && child.problems.length)
@@ -76,7 +76,7 @@ const guardOf = (signal) => ({ signal, threshold: GUARD_THRESHOLD });
76
76
  const guardText = (signal) => `\`"guard": {"signal": "${signal}", "threshold": ${GUARD_THRESHOLD}}\``;
77
77
  /** The quote check a compiled workflow's answer gets when it quotes fetched pages (check.ts quoteCheckProblems refuses a
78
78
  * draft without it): code, never a judge. */
79
- const QUOTE_CHECK_RULE = "An answer that quotes pages a call step fetched is checked in code: an escalate on `{\"predicate\": \"quote_missing\", \"path\": \"<the answer's quotes, e.g. answer.evidence>\", \"field\": \"quote\", \"pages\": [<the keys the call steps write>]}`, a step of the top-level chain after the step that writes the answer, hands back an answer quoting text no fetched page holds. Its pages are what the calls fetched, never a model's summary of them. Never ask a judge, an `ask` or a guard whether quotes are verbatim.";
79
+ const QUOTE_CHECK_RULE = "An answer that quotes pages a call step fetched is checked in code: an escalate on `{\"predicate\": \"quote_missing\", \"path\": \"<the answer's quotes, e.g. answer.evidence>\", \"field\": \"quote\", \"pages\": [<the keys the call steps write>]}`, a step of the top-level chain after the step that writes the answer, hands back an answer quoting text no fetched page holds. Its pages are what the calls fetched, never a model's summary of them. Never ask a judge, an `ask` or a guard whether quotes are verbatim. Give the answer one re-pick before it hands back: make the step that writes the answer the body of a `loop` with `\"maxIters\": 2` and `\"until\": {\"predicate\": \"not\", \"of\": <that same quote_missing>}`, its instructions saying that a draft already in state failed the quote check (recopy each quote exactly from the page it names, or quote another line); the step in the loop has no `state` map, so it reads the whole run state and its second pass sees the failed draft (a `state` map passes only the keys it names, and naming the answer there fails the first pass, before any draft exists); and keep the escalate a step of the top-level chain: the check after the loop, never inside it (a check in its body hands back on the first miss, so the loop never re-picks); only a second miss hands back. The loop's `until` reads one check: keep the answer's quotes in one place one `quote_missing` reads (a quote, a list of quotes or a list of records each holding its quote at one field), never a quote that may be a string or records, nor quotes in two places.";
80
80
  /** This host's addendum to the DSL's author contract: the node kinds it runs, and its rules, each one the checks hold a
81
81
  * draft to (learn/skills.ts draftProblems; propose.ts). `jev`: the run can call Jev (one of its decision providers,
82
82
  * not denied), so every step is asked for a guard Jev reads. */
@@ -1,7 +1,8 @@
1
1
  import type { Skipped } from "./learn/replay-calls.js";
2
- /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, guards? }`, its call's id, the
3
- * workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX) and every guard check it made
4
- * (GuardRow, never capped: a map over more items than the trace holds keeps each); on a replay run's call that a write
2
+ /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, guards?, loops? }`, its call's
3
+ * id, the workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX), every guard check it made
4
+ * (GuardRow) and every loop exit (LoopRow), these two never capped (a map over more items than the trace holds keeps
5
+ * each); on a replay run's call that a write
5
6
  * stopped (learn/replay-calls.ts: one the graded run's recording does not have), `replay_skipped: { tool, step }` too; and
6
7
  * `ended`, how the workflow ended (LearnedEnded), on a call that ended (a replay run's call always keeps its entry). */
7
8
  export declare const LEARNED_NODES = "agentrun.learned_nodes";
@@ -42,9 +43,19 @@ export type GuardRow = {
42
43
  readonly escalated: boolean;
43
44
  readonly workflow?: string;
44
45
  };
46
+ /** One loop's exit (the DSL's `loop.exited`): its label, how many passes its body ran and whether its `until` held (false:
47
+ * it reached maxIters). A compiled answer's quote re-pick (learn/check.ts) is a loop of 2 until its quote check passes:
48
+ * `iterations` 2 is a re-pick, `met` whether it found its quotes. Rows, uncapped, are a run's metrics' `loops`, each
49
+ * naming the workflow whose call ran it (`workflow`), as `guards` are. */
50
+ export type LoopRow = {
51
+ readonly node: string;
52
+ readonly iterations: number;
53
+ readonly met: boolean;
54
+ readonly workflow?: string;
55
+ };
45
56
  /** The LEARNED_NODES entry that counts for each learned_workflow call in `entries`, by the call's id, as its index in
46
57
  * `entries`. A call run again (after a park or a crash: it nests calls) keeps an entry each time; the one that counts is
47
- * its last that ran a node or made a check, as it holds every node and check its rerun made again. A rerun refused before
58
+ * its last that ran a node, made a check or exited a loop, as it holds every node and check its rerun made again. A rerun refused before
48
59
  * any node ran (a replay run keeps that entry: `nodes: []`, ended `failed`) leaves the attempt before it standing; a call
49
60
  * none of whose entries ran a node counts its last. What the run's guard rows (guardsOf) and its timeline rows'
50
61
  * `learned_nodes` (store-reads/journal.ts) both read, so the two never pick apart. */
@@ -59,6 +70,12 @@ export declare function guardsOf(entries: readonly {
59
70
  readonly kind: string;
60
71
  readonly data?: unknown;
61
72
  }[]): GuardRow[];
73
+ /** A run's loop rows, from its root entries: every loop exit of every learned_workflow call (LEARNED_NODES `loops`), read
74
+ * as guardsOf reads `guards`. What its metrics keep as `loops`. */
75
+ export declare function loopsOf(entries: readonly {
76
+ readonly kind: string;
77
+ readonly data?: unknown;
78
+ }[]): LoopRow[];
62
79
  /** How the newest learned_workflow call of `workflow` in `entries` (its root's) ended (LEARNED_NODES `ended`), or undefined
63
80
  * when no entry says. */
64
81
  export declare function endedIn(entries: readonly {
@@ -1,6 +1,7 @@
1
- /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, guards? }`, its call's id, the
2
- * workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX) and every guard check it made
3
- * (GuardRow, never capped: a map over more items than the trace holds keeps each); on a replay run's call that a write
1
+ /** The journal entry a learned_workflow call keeps beside itself: `{ call, workflow, nodes, guards?, loops? }`, its call's
2
+ * id, the workflow's name, each of its nodes that ran (LearnedNode, at most LEARNED_NODES_MAX), every guard check it made
3
+ * (GuardRow) and every loop exit (LoopRow), these two never capped (a map over more items than the trace holds keeps
4
+ * each); on a replay run's call that a write
4
5
  * stopped (learn/replay-calls.ts: one the graded run's recording does not have), `replay_skipped: { tool, step }` too; and
5
6
  * `ended`, how the workflow ended (LearnedEnded), on a call that ended (a replay run's call always keeps its entry). */
6
7
  export const LEARNED_NODES = "agentrun.learned_nodes";
@@ -8,7 +9,7 @@ export const LEARNED_NODES = "agentrun.learned_nodes";
8
9
  export const LEARNED_NODES_MAX = 64;
9
10
  /** The LEARNED_NODES entry that counts for each learned_workflow call in `entries`, by the call's id, as its index in
10
11
  * `entries`. A call run again (after a park or a crash: it nests calls) keeps an entry each time; the one that counts is
11
- * its last that ran a node or made a check, as it holds every node and check its rerun made again. A rerun refused before
12
+ * its last that ran a node, made a check or exited a loop, as it holds every node and check its rerun made again. A rerun refused before
12
13
  * any node ran (a replay run keeps that entry: `nodes: []`, ended `failed`) leaves the attempt before it standing; a call
13
14
  * none of whose entries ran a node counts its last. What the run's guard rows (guardsOf) and its timeline rows'
14
15
  * `learned_nodes` (store-reads/journal.ts) both read, so the two never pick apart. */
@@ -21,7 +22,8 @@ export function learnedCallEntries(entries) {
21
22
  const data = entry.data;
22
23
  if (typeof data?.call !== "string")
23
24
  return;
24
- const made = (Array.isArray(data.nodes) && data.nodes.length > 0) || (Array.isArray(data.guards) && data.guards.length > 0);
25
+ // A loop's exit is a run's row as a check is (a loop over an empty map exits with no node ended).
26
+ const made = [data.nodes, data.guards, data.loops].some((rows) => Array.isArray(rows) && rows.length > 0);
25
27
  if (made)
26
28
  ran.add(data.call);
27
29
  if (made || !ran.has(data.call))
@@ -33,6 +35,16 @@ export function learnedCallEntries(entries) {
33
35
  * never the capped trace's), in order, each with its call's workflow, from the entry that counts for each call
34
36
  * (learnedCallEntries). What its metrics keep as `guards`. */
35
37
  export function guardsOf(entries) {
38
+ return rowsOf(entries, "guards");
39
+ }
40
+ /** A run's loop rows, from its root entries: every loop exit of every learned_workflow call (LEARNED_NODES `loops`), read
41
+ * as guardsOf reads `guards`. What its metrics keep as `loops`. */
42
+ export function loopsOf(entries) {
43
+ return rowsOf(entries, "loops");
44
+ }
45
+ /** The rows at `key` of each LEARNED_NODES entry that counts for its call (learnedCallEntries), in order, each with its
46
+ * call's workflow. */
47
+ function rowsOf(entries, key) {
36
48
  const rows = [];
37
49
  const last = learnedCallEntries(entries);
38
50
  for (const [index, entry] of entries.entries()) {
@@ -41,10 +53,11 @@ export function guardsOf(entries) {
41
53
  const data = entry.data;
42
54
  if (typeof data?.call === "string" && last.get(data.call) !== index)
43
55
  continue;
44
- if (!Array.isArray(data?.guards))
56
+ const kept = data?.[key];
57
+ if (!Array.isArray(kept))
45
58
  continue;
46
- const workflow = typeof data.workflow === "string" ? data.workflow : undefined;
47
- for (const row of data.guards)
59
+ const workflow = typeof data?.workflow === "string" ? data.workflow : undefined;
60
+ for (const row of kept)
48
61
  if (row && typeof row === "object")
49
62
  rows.push(workflow ? { ...row, workflow } : row);
50
63
  }
@@ -1,5 +1,5 @@
1
1
  import { type ToolRegistration } from "@earendil-works/pi-durable";
2
- import { type GuardRow, type LearnedEnded, type LearnedNode } from "./learned-nodes.js";
2
+ import { type GuardRow, type LearnedEnded, type LearnedNode, type LoopRow } from "./learned-nodes.js";
3
3
  import { type LearnedWorkflow } from "./learning.js";
4
4
  import type { ModelRef } from "./model.js";
5
5
  import { type Ledger } from "./paid-calls.js";
@@ -155,8 +155,8 @@ export declare function learnedWorkflowTool(run: LearnedWorkflowRun): ToolRegist
155
155
  * `nested`: the session's tools as calls nested in this one, which its MCP nodes run as; and the values its first run
156
156
  * fixed (`memo`), so a rerun of the call (after a park, a crash) goes on from what its model, decision and call nodes
157
157
  * answered then, its MCP calls with the arguments they were asked and approved with, each recorded one answered from its
158
- * record, never sent twice. */
159
- export declare function runLearned(run: LearnedWorkflowRun, flow: LearnedWorkflow, input: unknown, signal?: AbortSignal, ledger?: Ledger, nodes?: LearnedNode[], guards?: GuardRow[], nested?: NestedCalls): Promise<{
158
+ * record, never sent twice. `loops`: where each loop's exit is added (LoopRow), as `guards` are. */
159
+ export declare function runLearned(run: LearnedWorkflowRun, flow: LearnedWorkflow, input: unknown, signal?: AbortSignal, ledger?: Ledger, nodes?: LearnedNode[], guards?: GuardRow[], nested?: NestedCalls, loops?: LoopRow[]): Promise<{
160
160
  text: string;
161
161
  isError: boolean;
162
162
  nodes: LearnedNode[];
@@ -273,18 +273,21 @@ export function learnedWorkflowTool(run) {
273
273
  // written outside the stopped call's context, and still ends as a stop.
274
274
  const trace = [];
275
275
  const guards = [];
276
+ // Every loop's exit (`loops`, uncapped too: a quote re-pick is a loop's second pass, which the run's metrics count).
277
+ const loops = [];
276
278
  // A replay's write the recording did not have (learn/replay-calls.ts) rides on the same entry, ran a node or not; so
277
279
  // does how the workflow ended (`ended`, LearnedEnded), the one thing a replay's outcome reads (workflow-first.ts
278
280
  // pathMetrics): a replay run keeps its entry whatever ran, so a refusal before any node is read as one.
279
281
  const keep = (signal, ended) => {
280
282
  const skipped = run.replay?.skipped;
281
- if (!trace.length && !guards.length && !skipped && !(run.replay && ended))
283
+ // A loop's exit counts too: a loop over an empty map ends no node, yet its row is the run's (metrics `loops`).
284
+ if (!trace.length && !guards.length && !loops.length && !skipped && !(run.replay && ended))
282
285
  return undefined;
283
- return api.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: LEARNED_NODES, data: { call: ledger.call, workflow: flow.name, nodes: trace, ...(guards.length ? { guards } : {}), ...(skipped ? { replay_skipped: skipped } : {}), ...(ended ? { ended } : {}) } })), signal).catch(() => undefined);
286
+ return api.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: LEARNED_NODES, data: { call: ledger.call, workflow: flow.name, nodes: trace, ...(guards.length ? { guards } : {}), ...(loops.length ? { loops } : {}), ...(skipped ? { replay_skipped: skipped } : {}), ...(ended ? { ended } : {}) } })), signal).catch(() => undefined);
284
287
  };
285
288
  let said;
286
289
  try {
287
- said = await runLearned(run, flow, input, context?.abortSignal, ledger, trace, guards, run.nestedOf?.(api.callId));
290
+ said = await runLearned(run, flow, input, context?.abortSignal, ledger, trace, guards, run.nestedOf?.(api.callId), loops);
288
291
  }
289
292
  catch (error) {
290
293
  await keep(BACKGROUND_CONTEXT);
@@ -303,8 +306,8 @@ export function learnedWorkflowTool(run) {
303
306
  * `nested`: the session's tools as calls nested in this one, which its MCP nodes run as; and the values its first run
304
307
  * fixed (`memo`), so a rerun of the call (after a park, a crash) goes on from what its model, decision and call nodes
305
308
  * answered then, its MCP calls with the arguments they were asked and approved with, each recorded one answered from its
306
- * record, never sent twice. */
307
- export async function runLearned(run, flow, input, signal, ledger, nodes = [], guards = [], nested) {
309
+ * record, never sent twice. `loops`: where each loop's exit is added (LoopRow), as `guards` are. */
310
+ export async function runLearned(run, flow, input, signal, ledger, nodes = [], guards = [], nested, loops = []) {
308
311
  const refuse = (why) => ({ text: `The learned workflow ${flow.name} was not run: ${why}`, isError: true, nodes, ended: "failed" });
309
312
  if (!input || typeof input !== "object" || Array.isArray(input))
310
313
  return refuse("its input must be a JSON object");
@@ -461,6 +464,12 @@ export async function runLearned(run, flow, input, signal, ledger, nodes = [], g
461
464
  const soft = replay ? dsl.softEscalates(doc) : undefined;
462
465
  // Each node as it ends, by the DSL's own event: what the call's timeline row shows of it.
463
466
  const onEvent = (event) => {
467
+ if (event.type === "loop.exited") {
468
+ const detail = (event.detail ?? {});
469
+ if (typeof detail.iterations === "number")
470
+ loops.push({ node: String(event.label), iterations: detail.iterations, met: detail.reason === "condition_met" });
471
+ return;
472
+ }
464
473
  if (event.type === "escalate.evaluated") {
465
474
  const detail = (event.detail ?? {});
466
475
  if (detail.soft === true)
@@ -101,6 +101,17 @@ export type Reach = {
101
101
  allowed?: readonly string[];
102
102
  loopback?: boolean;
103
103
  };
104
+ /** Where a feed trigger's read of `url` (feed/fetch.ts readFeed, each redirect again) may go, before anything is sent:
105
+ * `checked`'s rule, an MCP server's, with plain http allowed on a public address alone (a feed is public text, and many
106
+ * are served over http; a private host the owner allows, `reach.allowed`, is read over https). A URL on loopback as
107
+ * written where `reach.loopback` allows it (a local install, as for an MCP server) on any port but this server's own:
108
+ * `address` undefined, dialled as written. A URL that isn't http(s) is refused. */
109
+ export declare function feedAt(url: URL, signal: AbortSignal, network: OAuthNetwork, reach?: Reach): Promise<{
110
+ refused: string;
111
+ unresolved?: true;
112
+ } | {
113
+ address: string | undefined;
114
+ }>;
104
115
  /** Where a request to the MCP server at `url` may go, before anything is sent to it: the preview, the save, the tools'
105
116
  * refresh and the sign-in on this server, and each request of a run's calls on the runner. The rule is `checked`'s, the
106
117
  * one an authorization server's endpoint is held to: a public https address; a private-network one only for a host the
@@ -142,9 +153,12 @@ export declare class McpSignIns {
142
153
  /** Whether this server is a local install (McpServersOverStore.attach): only then may a loopback MCP server's
143
154
  * authorization server be on loopback too. */
144
155
  loopback: boolean;
156
+ /** A runner's registry (mcp-pin-first.ts registryListing), which listens nowhere: the own addresses of the
157
+ * local-install server beside it (Serve.own), held to as this server's own are. Set by McpServersOverStore.attach. */
158
+ beside: readonly string[];
145
159
  /** This server's own local addresses, whose ports a loopback authorization server may never name: where it listens,
146
160
  * and its public address too when that is on loopback (a local https proxy on another port, in front of the
147
- * listener, reaches this server). */
161
+ * listener, reaches this server); on a runner, the server's beside it. */
148
162
  get own(): string[];
149
163
  /** CIMD only from a public https address: an authorization server must be able to fetch the document. */
150
164
  private get metadataUrl();