@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.29
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.
- package/CHANGELOG.md +560 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +1723 -2
- package/dist/adapters.d.ts +205 -0
- package/dist/adapters.js +459 -0
- package/dist/agents.d.ts +124 -0
- package/dist/agents.js +302 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +324 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +283 -0
- package/dist/box-relay.d.ts +42 -0
- package/dist/box-relay.js +222 -0
- package/dist/boxes.d.ts +54 -0
- package/dist/boxes.js +182 -0
- package/dist/cap.d.ts +224 -0
- package/dist/cap.js +721 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +31 -0
- package/dist/coding-tools.js +81 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
- package/dist/console/assets/index-BN7oVcO4.js +445 -0
- package/dist/console/assets/index-By-jkqki.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +11 -0
- package/dist/decision-rows.js +116 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +72 -0
- package/dist/errors.js +66 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +60 -0
- package/dist/files.js +153 -0
- package/dist/grade.d.ts +96 -0
- package/dist/grade.js +348 -0
- package/dist/graph-view.d.ts +100 -0
- package/dist/graph-view.js +212 -0
- package/dist/harness-app.d.ts +38 -0
- package/dist/harness-app.js +626 -0
- package/dist/harness.d.ts +53 -0
- package/dist/harness.js +74 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +20 -0
- package/dist/host-tools.js +140 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +81 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +129 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1221 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +36 -0
- package/dist/key-check.js +108 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +187 -0
- package/dist/learn/check.d.ts +99 -0
- package/dist/learn/check.js +259 -0
- package/dist/learn/grade.d.ts +79 -0
- package/dist/learn/grade.js +433 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +146 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +167 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +111 -0
- package/dist/learn/skills.d.ts +84 -0
- package/dist/learn/skills.js +198 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +304 -0
- package/dist/learning-run.js +797 -0
- package/dist/learning-words.d.ts +73 -0
- package/dist/learning-words.js +171 -0
- package/dist/learning.d.ts +377 -0
- package/dist/learning.js +801 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +115 -0
- package/dist/mcp-servers.js +445 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +184 -0
- package/dist/model.js +484 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4805 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1417 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +46 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +68 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +46 -0
- package/dist/place.js +105 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +38 -0
- package/dist/propose.js +82 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +14 -0
- package/dist/request-start.js +226 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +134 -0
- package/dist/run-box.js +440 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +80 -0
- package/dist/runnable.js +162 -0
- package/dist/runs.d.ts +840 -0
- package/dist/runs.js +2279 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +50 -0
- package/dist/secrets.js +140 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +626 -0
- package/dist/server.js +1756 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/skills.d.ts +31 -0
- package/dist/skills.js +68 -0
- package/dist/stats.d.ts +101 -0
- package/dist/stats.js +82 -0
- package/dist/tool-keys.d.ts +151 -0
- package/dist/tool-keys.js +273 -0
- package/dist/tool-plane.d.ts +143 -0
- package/dist/tool-plane.js +242 -0
- package/dist/tools.d.ts +147 -0
- package/dist/tools.js +253 -0
- package/dist/turn-end.d.ts +23 -0
- package/dist/turn-end.js +14 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +55 -0
- package/dist/validate.js +175 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +182 -0
- package/dist/webhooks.js +487 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +94 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/validate.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// Structural checks of request bodies against the contract's schemas, as field issues (`422 input_invalid`).
|
|
2
|
+
import { invalid } from "./errors.js";
|
|
3
|
+
import { HARNESSES } from "./harness.js";
|
|
4
|
+
import { THINKING_LEVELS } from "./model.js";
|
|
5
|
+
import { placeIssues } from "./place.js";
|
|
6
|
+
import { settingsIssues } from "./tool-plane.js";
|
|
7
|
+
export const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
8
|
+
const SKILL_PATH = /^(?!.*(?:^|\/)\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^/\\\u0000][^\\\u0000]*$/;
|
|
9
|
+
export const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10
|
+
/** JSON with every object's keys sorted, so two equal values read the same. */
|
|
11
|
+
export const stable = (value) => Array.isArray(value) ? `[${value.map(stable).join(",")}]` : isObject(value) ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stable(value[k])}`).join(",")}}` : JSON.stringify(value);
|
|
12
|
+
export const DEFINITION_FIELDS = ["id", "version", "name", "description", "instructions", "workflow", "model", "thinking", "harness", "place", "learning", "skills", "tools", "tool_settings"];
|
|
13
|
+
/** Why a field a definition may have elsewhere has no place in an agent store's revision. */
|
|
14
|
+
export const NOT_KEPT = {
|
|
15
|
+
input_schema: "The agent store keeps no input_schema: an agentic run takes {content}, and a workflow checks its input against its own schema.",
|
|
16
|
+
output_schema: "The agent store keeps no output_schema: a workflow run's output is its workflow's.",
|
|
17
|
+
max_cost_usd: "The agent store keeps no max_cost_usd on a definition: give one with each run.",
|
|
18
|
+
};
|
|
19
|
+
/** `provider/model-id`. */
|
|
20
|
+
export const MODEL_REF = /^[^/\s]+\/\S+$/;
|
|
21
|
+
const SKILL_FILE = "/SKILL.md";
|
|
22
|
+
const issue = (field, reason, message, fix) => ({ field, reason, message, ...(fix ? { fix } : {}) });
|
|
23
|
+
/** A body's fields that `allowed` does not name, each as the 422's not_allowed issue. */
|
|
24
|
+
export const unknownFields = (body, allowed) => Object.keys(body).filter((key) => !allowed.includes(key)).map((key) => ({ field: key, reason: "not_allowed", message: `The body keeps no field ${key}.` }));
|
|
25
|
+
function names(value, field, out) {
|
|
26
|
+
if (!Array.isArray(value))
|
|
27
|
+
return void out.push(issue(field, "wrong_type", `${field} is not a list of names`));
|
|
28
|
+
if (!value.every((name) => typeof name === "string" && name !== ""))
|
|
29
|
+
out.push(issue(field, "wrong_type", `${field} holds an item that is not a non-empty string`));
|
|
30
|
+
else if (new Set(value).size !== value.length)
|
|
31
|
+
out.push(issue(field, "duplicate", `${field} names one item twice`));
|
|
32
|
+
}
|
|
33
|
+
/** The skills a revision's files hold: each `<name>/SKILL.md`, by name, sorted. */
|
|
34
|
+
export const skillNames = (files) => [...files].filter((path) => path.endsWith(SKILL_FILE)).map((path) => path.slice(0, -SKILL_FILE.length)).sort();
|
|
35
|
+
/**
|
|
36
|
+
* A definition as `POST /agents` and `PUT .../definition` take it: what one revision of an agent keeps. `instructions`
|
|
37
|
+
* makes an agentic revision, `workflow` (an agentrun-dsl workflow) a workflow revision. `creating` asks for a name.
|
|
38
|
+
*/
|
|
39
|
+
export function definitionIssues(definition, { at = "definition", creating = true } = {}) {
|
|
40
|
+
if (!isObject(definition))
|
|
41
|
+
return [issue(at, definition === undefined ? "missing" : "wrong_type", `${at} is not an object`)];
|
|
42
|
+
const out = [];
|
|
43
|
+
for (const key of Object.keys(definition)) {
|
|
44
|
+
if (!DEFINITION_FIELDS.includes(key))
|
|
45
|
+
out.push(issue(`${at}.${key}`, "not_allowed", NOT_KEPT[key] ?? `The definition keeps no field ${key}.`, `Remove ${at}.${key}.`));
|
|
46
|
+
}
|
|
47
|
+
const d = definition;
|
|
48
|
+
if (creating && d.name === undefined)
|
|
49
|
+
out.push(issue(`${at}.name`, "missing", `${at}.name is required`));
|
|
50
|
+
if (d.instructions === undefined && d.workflow === undefined)
|
|
51
|
+
out.push(issue(`${at}.instructions`, "missing", `${at} needs instructions (an agentic revision) or a workflow (a workflow revision)`));
|
|
52
|
+
if (d.instructions !== undefined && d.workflow !== undefined)
|
|
53
|
+
out.push(issue(`${at}.workflow`, "not_allowed", `${at} has instructions or a workflow, not both`, `Remove ${at}.workflow or ${at}.instructions.`));
|
|
54
|
+
if (d.id !== undefined && (typeof d.id !== "string" || !ID.test(d.id)))
|
|
55
|
+
out.push(issue(`${at}.id`, "bad_format", `${at}.id must match ${ID.source}`));
|
|
56
|
+
if (d.version !== undefined && (!Number.isSafeInteger(d.version) || d.version < 1))
|
|
57
|
+
out.push(issue(`${at}.version`, "wrong_type", `${at}.version is not a positive integer`));
|
|
58
|
+
if (d.name !== undefined && (typeof d.name !== "string" || d.name.trim() === ""))
|
|
59
|
+
out.push(issue(`${at}.name`, typeof d.name === "string" ? "too_short" : "wrong_type", `${at}.name is not a non-empty string`));
|
|
60
|
+
if (d.description !== undefined && typeof d.description !== "string")
|
|
61
|
+
out.push(issue(`${at}.description`, "wrong_type", `${at}.description is not a string`));
|
|
62
|
+
if (d.instructions !== undefined && typeof d.instructions !== "string")
|
|
63
|
+
out.push(issue(`${at}.instructions`, "wrong_type", `${at}.instructions is not a string`));
|
|
64
|
+
if (d.workflow !== undefined && !isObject(d.workflow))
|
|
65
|
+
out.push(issue(`${at}.workflow`, "wrong_type", `${at}.workflow is not an object`));
|
|
66
|
+
if (d.model !== undefined) {
|
|
67
|
+
if (d.workflow !== undefined)
|
|
68
|
+
out.push(issue(`${at}.model`, "not_allowed", "A workflow revision keeps no model: its model nodes run on this host's default.", `Remove ${at}.model.`));
|
|
69
|
+
else if (typeof d.model !== "string" || !MODEL_REF.test(d.model))
|
|
70
|
+
out.push(issue(`${at}.model`, "bad_format", `${at}.model is "provider/model-id"`));
|
|
71
|
+
}
|
|
72
|
+
if (d.harness !== undefined && !HARNESSES.includes(d.harness))
|
|
73
|
+
out.push(issue(`${at}.harness`, "not_an_option", `${at}.harness is one of ${HARNESSES.join(", ")}`));
|
|
74
|
+
if (d.place !== undefined)
|
|
75
|
+
out.push(...placeIssues(d.place, `${at}.place`));
|
|
76
|
+
if (d.thinking !== undefined) {
|
|
77
|
+
if (d.workflow !== undefined)
|
|
78
|
+
out.push(issue(`${at}.thinking`, "not_allowed", "A workflow revision keeps no thinking level: each model node carries its own.", `Remove ${at}.thinking.`));
|
|
79
|
+
else if (!THINKING_LEVELS.includes(d.thinking))
|
|
80
|
+
out.push(issue(`${at}.thinking`, "not_an_option", `${at}.thinking is one of ${THINKING_LEVELS.join(", ")}: thinking is never off`));
|
|
81
|
+
}
|
|
82
|
+
if (d.learning !== undefined) {
|
|
83
|
+
if (d.workflow !== undefined)
|
|
84
|
+
out.push(issue(`${at}.learning`, "not_allowed", "A workflow revision does not learn: only an agentic run reflects on its work.", `Remove ${at}.learning.`));
|
|
85
|
+
else if (typeof d.learning !== "boolean")
|
|
86
|
+
out.push(issue(`${at}.learning`, "wrong_type", `${at}.learning is true or false`));
|
|
87
|
+
}
|
|
88
|
+
if (d.skills !== undefined)
|
|
89
|
+
names(d.skills, `${at}.skills`, out);
|
|
90
|
+
if (d.tools !== undefined)
|
|
91
|
+
names(d.tools, `${at}.tools`, out);
|
|
92
|
+
// The agent's own tool settings, over the server's (tool-plane.ts); an edit that leaves them out keeps none.
|
|
93
|
+
if (d.tool_settings !== undefined)
|
|
94
|
+
out.push(...settingsIssues(d.tool_settings, `${at}.tool_settings`));
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
/** The skill files a body names: an object of relative paths inside `.agents/skills/` to text. */
|
|
98
|
+
function skillFileIssues(skills, out) {
|
|
99
|
+
if (!isObject(skills))
|
|
100
|
+
return void out.push(issue("skills", "wrong_type", "skills is not an object of paths to text"));
|
|
101
|
+
for (const [path, text] of Object.entries(skills)) {
|
|
102
|
+
if (path.length > 512 || !SKILL_PATH.test(path))
|
|
103
|
+
out.push(issue(`skills.${path}`, "bad_format", `the skill path ${JSON.stringify(path)} is not a relative path inside .agents/skills/`));
|
|
104
|
+
else if (typeof text !== "string")
|
|
105
|
+
out.push(issue(`skills.${path}`, "wrong_type", `the skill ${path} is not text`));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** A definition's skill names against the files its revision holds: each named skill has its SKILL.md, and each
|
|
109
|
+
* SKILL.md is named. */
|
|
110
|
+
export function skillIssues(named, files) {
|
|
111
|
+
if (!Array.isArray(named))
|
|
112
|
+
return [];
|
|
113
|
+
const held = skillNames(files);
|
|
114
|
+
return [
|
|
115
|
+
...named.filter((name) => !held.includes(name)).map((name) => issue(`skills.${name}${SKILL_FILE}`, "missing", `the definition names the skill ${name}, and skills holds no ${name}${SKILL_FILE}`)),
|
|
116
|
+
...held.filter((name) => !named.includes(name)).map((name) => issue(`skills.${name}${SKILL_FILE}`, "not_allowed", `skills holds ${name}${SKILL_FILE}, a skill the definition does not name`, `Name ${name} in definition.skills, or leave it out.`)),
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* `{definition, skills?, note?}`, as `POST /agents` and `PUT .../definition` take it. `skills` are the revision's skill
|
|
121
|
+
* files (absent on an edit: the current revision's); `note` says what the revision changes. Throws `422 input_invalid`
|
|
122
|
+
* naming every field that is wrong.
|
|
123
|
+
*/
|
|
124
|
+
export function checkDefinitionBody(body, { creating = true } = {}) {
|
|
125
|
+
const out = [];
|
|
126
|
+
for (const key of Object.keys(body))
|
|
127
|
+
if (!["definition", "skills", "note"].includes(key))
|
|
128
|
+
out.push(issue(key, "not_allowed", `The body keeps no field ${key}.`, `Remove ${key}.`));
|
|
129
|
+
out.push(...definitionIssues(body.definition, { creating }));
|
|
130
|
+
if (body.skills !== undefined || creating)
|
|
131
|
+
skillFileIssues(body.skills ?? {}, out);
|
|
132
|
+
if (body.note !== undefined && !(typeof body.note === "string" && body.note.length <= 2_000))
|
|
133
|
+
out.push(issue("note", "wrong_type", "note is text of at most 2000 characters"));
|
|
134
|
+
if (out.length)
|
|
135
|
+
throw invalid(out);
|
|
136
|
+
return { definition: body.definition, ...(body.skills !== undefined || creating ? { skills: (body.skills ?? {}) } : {}), ...(typeof body.note === "string" ? { note: body.note } : {}) };
|
|
137
|
+
}
|
|
138
|
+
const TYPE_CHECK = {
|
|
139
|
+
string: (v) => typeof v === "string",
|
|
140
|
+
number: (v) => typeof v === "number" && Number.isFinite(v),
|
|
141
|
+
integer: (v) => Number.isSafeInteger(v),
|
|
142
|
+
boolean: (v) => typeof v === "boolean",
|
|
143
|
+
object: isObject,
|
|
144
|
+
array: Array.isArray,
|
|
145
|
+
null: (v) => v === null,
|
|
146
|
+
};
|
|
147
|
+
/** The default input schema: `{content: string}`. */
|
|
148
|
+
export const DEFAULT_INPUT_SCHEMA = { type: "object", required: ["content"], properties: { content: { type: "string" } } };
|
|
149
|
+
/**
|
|
150
|
+
* An object against a JSON Schema at its top level (a run's input against `input_schema`, a submitted output against
|
|
151
|
+
* `output_schema`): each required property present, each property of a declared type of that type. Deeper keywords
|
|
152
|
+
* are not checked here.
|
|
153
|
+
*/
|
|
154
|
+
export function inputIssues(input, schema, at = "input") {
|
|
155
|
+
const out = [];
|
|
156
|
+
const required = Array.isArray(schema.required) ? schema.required.filter((k) => typeof k === "string") : [];
|
|
157
|
+
const properties = isObject(schema.properties) ? schema.properties : {};
|
|
158
|
+
for (const key of required)
|
|
159
|
+
if (input[key] === undefined)
|
|
160
|
+
out.push(issue(`${at}.${key}`, "missing", `${at}.${key} is required`));
|
|
161
|
+
for (const [key, value] of Object.entries(input)) {
|
|
162
|
+
const property = properties[key];
|
|
163
|
+
if (!isObject(property)) {
|
|
164
|
+
if (schema.additionalProperties === false)
|
|
165
|
+
out.push(issue(`${at}.${key}`, "not_allowed", `${at} keeps no field ${key}`, `Remove ${at}.${key}.`));
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
const types = (Array.isArray(property.type) ? property.type : [property.type]).filter((t) => typeof t === "string" && t in TYPE_CHECK);
|
|
169
|
+
if (types.length && !types.some((t) => TYPE_CHECK[t](value)))
|
|
170
|
+
out.push(issue(`${at}.${key}`, "wrong_type", `${at}.${key} is not ${types.join(" or ")}`));
|
|
171
|
+
if (Array.isArray(property.enum) && !property.enum.some((option) => JSON.stringify(option) === JSON.stringify(value)))
|
|
172
|
+
out.push(issue(`${at}.${key}`, "not_an_option", `${at}.${key} is not one of the options`));
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { JsonValue } from "@earendil-works/chord";
|
|
2
|
+
import type { TSchema } from "@earendil-works/pi-ai";
|
|
3
|
+
import { type ToolRegistration } from "@earendil-works/pi-durable";
|
|
4
|
+
import type { PublicFetchOptions } from "@parcha/pi-browser";
|
|
5
|
+
import { type Page, type Part, type Read, type Unread } from "./fetch-page.js";
|
|
6
|
+
export declare const WEB_FETCH_TOOL = "web_fetch";
|
|
7
|
+
export declare const PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
|
|
8
|
+
/** How many pages a run keeps what it read of (Pages): each at most PAGE_READ_MAX_CHARS characters of text. */
|
|
9
|
+
export declare const PAGES_HELD = 8;
|
|
10
|
+
/** `parallel`, on a page fetched directly where Parallel was asked for one: why Parallel gave none. */
|
|
11
|
+
export type WebPage = Page & {
|
|
12
|
+
via: "parallel" | "direct" | "stopped";
|
|
13
|
+
parallel?: string;
|
|
14
|
+
};
|
|
15
|
+
/** A page web_fetch read, and how (WebPage's `via` and `parallel`). */
|
|
16
|
+
export type WebRead = Read & Pick<WebPage, "via" | "parallel">;
|
|
17
|
+
/** A page web_fetch could not read, and how it tried. */
|
|
18
|
+
type WebUnread = Unread & Pick<WebPage, "via" | "parallel">;
|
|
19
|
+
/** The pages a run reads, by the URL asked for, each from its read's start (so calls at once share it), the last used
|
|
20
|
+
* last: at most PAGES_HELD of them. */
|
|
21
|
+
export type Pages = Map<string, Promise<WebRead | WebUnread>>;
|
|
22
|
+
type GuardOptions = Omit<PublicFetchOptions, "maxBytes">;
|
|
23
|
+
/** Parallel for one run, on one key: `read`, its extract of a page (one billed request), the page it read or, for any
|
|
24
|
+
* failure, why it read none; `post`, one request to another of its endpoints (web_search's, web-search.ts). Neither
|
|
25
|
+
* retries, and each stops at 60 s. `live` is false once a 401 or 403 to either said the key is not served. */
|
|
26
|
+
export type Extract = {
|
|
27
|
+
live(): boolean;
|
|
28
|
+
read(url: string, signal?: AbortSignal): Promise<Read | string>;
|
|
29
|
+
post(url: string, body: unknown, signal?: AbortSignal): Promise<Response>;
|
|
30
|
+
};
|
|
31
|
+
/** Parallel's extract on `apiKey`: one URL a request, each a billed extract, its full content to the most of a page
|
|
32
|
+
* web_fetch reads as the page's text (markdown), its links read from it, status 200 (Parallel answers a page it could
|
|
33
|
+
* not read in `errors`, with no content). */
|
|
34
|
+
export declare function parallelExtract(apiKey: string, send?: typeof fetch): Extract;
|
|
35
|
+
/** The part (`offset`, `maxChars`) of the page at `url` as a WebPage: from `pages`, the run's, where it holds the URL
|
|
36
|
+
* (read, or being read), with no request of its own; else read once (readOnce), kept there from the read's start. A read
|
|
37
|
+
* that fails leaves `pages`, so a later call reads again. The read is the run's, not a caller's: no caller's signal
|
|
38
|
+
* reaches it (it keeps Parallel's and the fetch's own time limits), so one caller's stop never fails another's; each
|
|
39
|
+
* caller stops waiting at its own signal (untilStopped). */
|
|
40
|
+
export declare function webFetch(url: unknown, { parallel, pages, checkMs, offset, maxChars, signal, ...options }?: GuardOptions & Part & {
|
|
41
|
+
parallel?: Extract | null;
|
|
42
|
+
pages?: Pages;
|
|
43
|
+
checkMs?: number;
|
|
44
|
+
}): Promise<WebPage>;
|
|
45
|
+
/** The pages this run read (Pages): its process is the run's, so the agent's tool and a call node's web_fetch share them. */
|
|
46
|
+
export declare const runPages: Pages;
|
|
47
|
+
/** The run's Parallel extract, made once in its process so a refused key holds for the rest of the run: on the Parallel
|
|
48
|
+
* key the server handed it (handedKeys, the read the decision providers share), null without one. */
|
|
49
|
+
export declare function parallelOf(env: NodeJS.ProcessEnv): Extract | null;
|
|
50
|
+
/** The part `options` names of the page at `url` by the provider the run's plane resolves web_fetch to: Parallel's
|
|
51
|
+
* extract (with the direct fetch behind it) where it resolves to parallel, the guarded direct fetch otherwise, and a
|
|
52
|
+
* failed Page saying why where it is unavailable or the part is one a call may not ask for (partProblem), before
|
|
53
|
+
* anything is fetched. From `pages` (the run's, runPages) where they hold the URL. */
|
|
54
|
+
export declare function fetchFor(env: NodeJS.ProcessEnv, url: unknown, options?: GuardOptions & Part & {
|
|
55
|
+
pages?: Pages;
|
|
56
|
+
}): Promise<WebPage | Page>;
|
|
57
|
+
/** A page as the tool `name` answers the model: its JSON, then a line saying why Parallel gave none where it was picked,
|
|
58
|
+
* and one saying where this part is in the page when it is not all of it. */
|
|
59
|
+
export declare function webFetchText(page: WebPage | Page, name?: string): string;
|
|
60
|
+
/** The agent's tool: the WebPage as JSON text (webFetchText), named `name` (fetch_page, its legacy name, runs it too). A
|
|
61
|
+
* run whose web_fetch resolves to Parallel reads its key as the tool is made, when the run opens. */
|
|
62
|
+
/** Typed here, so its declaration names the schema type by a package serve declares (pi-ai), whatever else the build loads. */
|
|
63
|
+
export declare function webFetchTool(env: NodeJS.ProcessEnv, name?: string): ToolRegistration<TSchema, JsonValue>;
|
|
64
|
+
export {};
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { defineTool } from "@earendil-works/pi-durable";
|
|
2
|
+
import { FAUX_PARALLEL_ENV, fauxFetch, handedKeys, PARALLEL_KEY_ENV } from "./decisions.js";
|
|
3
|
+
import { clip, fetchOptions, HTML_READ_CHARS, linksWithin, MAX_CHARS_MIN, PAGE_CHARS, PAGE_READ_MAX_CHARS, partOfRead, partProblem, readDirect, TEXT_CAP, TIMEOUT_MS, TITLE_CAP, textOf, URL_MAX, URL_PARAMETERS } from "./fetch-page.js";
|
|
4
|
+
import { FAUX_ENV } from "./model.js";
|
|
5
|
+
import { PaidRefused, paidRequest, parallelFeeOf } from "./paid-calls.js";
|
|
6
|
+
import { forModel } from "./result.js";
|
|
7
|
+
import { isUnavailable, planeOf } from "./tool-plane.js";
|
|
8
|
+
export const WEB_FETCH_TOOL = "web_fetch";
|
|
9
|
+
export const PARALLEL_EXTRACT_URL = "https://api.parallel.ai/v1/extract";
|
|
10
|
+
const PARALLEL_TIMEOUT_MS = 60_000;
|
|
11
|
+
const PORTS = new Set(["", "80", "443"]);
|
|
12
|
+
/** How many pages a run keeps what it read of (Pages): each at most PAGE_READ_MAX_CHARS characters of text. */
|
|
13
|
+
export const PAGES_HELD = 8;
|
|
14
|
+
/** The absolute http(s) URLs a markdown text links to (`[text](url)`), each once and without its fragment, in order, as
|
|
15
|
+
* they are read (linksWithin keeps those within the caps and counts the rest). A URL ends at whitespace or at the ")"
|
|
16
|
+
* that closes the link, so parentheses it holds in pairs (a wiki title's) stay. */
|
|
17
|
+
function* linksOf(markdown) {
|
|
18
|
+
const seen = new Set();
|
|
19
|
+
// The next "](" is looked for from where this one's URL ended, so no character is scanned twice: one pass, however
|
|
20
|
+
// many unclosed "](" a hostile page holds.
|
|
21
|
+
for (let at = markdown.indexOf("]("), end = 0; at !== -1; at = markdown.indexOf("](", Math.max(at + 2, end))) {
|
|
22
|
+
end = at + 2;
|
|
23
|
+
for (let depth = 0; end < markdown.length && !/\s/.test(markdown[end]); end++) {
|
|
24
|
+
if (markdown[end] === "(")
|
|
25
|
+
depth++;
|
|
26
|
+
else if (markdown[end] === ")" && depth-- === 0)
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
const href = markdown.slice(at + 2, end);
|
|
30
|
+
const link = /^https?:\/\//i.test(href) ? URL.parse(href) : null;
|
|
31
|
+
if (!link)
|
|
32
|
+
continue;
|
|
33
|
+
link.hash = "";
|
|
34
|
+
if (seen.has(link.href))
|
|
35
|
+
continue;
|
|
36
|
+
seen.add(link.href);
|
|
37
|
+
yield link.href;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Parallel's extract on `apiKey`: one URL a request, each a billed extract, its full content to the most of a page
|
|
41
|
+
* web_fetch reads as the page's text (markdown), its links read from it, status 200 (Parallel answers a page it could
|
|
42
|
+
* not read in `errors`, with no content). */
|
|
43
|
+
export function parallelExtract(apiKey, send = fetch) {
|
|
44
|
+
let refused = false;
|
|
45
|
+
// Each request is a paid one (paid-calls.ts): held by the run's cap and booked as the call's cost at its endpoint's
|
|
46
|
+
// price. One the cap refuses is not sent: it throws its refusal (PaidRefused).
|
|
47
|
+
const post = async (url, body, signal) => {
|
|
48
|
+
const sent = async () => {
|
|
49
|
+
const response = await send(url, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
headers: { "x-api-key": apiKey, "content-type": "application/json" },
|
|
52
|
+
body: JSON.stringify(body),
|
|
53
|
+
signal: AbortSignal.any([AbortSignal.timeout(PARALLEL_TIMEOUT_MS), ...(signal ? [signal] : [])]),
|
|
54
|
+
});
|
|
55
|
+
if (response.status === 401 || response.status === 403)
|
|
56
|
+
refused = true;
|
|
57
|
+
return response;
|
|
58
|
+
};
|
|
59
|
+
const fee = parallelFeeOf(url, body);
|
|
60
|
+
if (!fee)
|
|
61
|
+
throw new PaidRefused(`Parallel's ${URL.parse(url)?.pathname ?? url} was not sent: it has no price here`);
|
|
62
|
+
return paidRequest(fee, sent);
|
|
63
|
+
};
|
|
64
|
+
return {
|
|
65
|
+
live: () => !refused,
|
|
66
|
+
post,
|
|
67
|
+
async read(url, signal) {
|
|
68
|
+
try {
|
|
69
|
+
// The most of a page a read reaches and one character more, so a page Parallel cut there shows as going on.
|
|
70
|
+
const asked = PAGE_READ_MAX_CHARS + 1;
|
|
71
|
+
const response = await post(PARALLEL_EXTRACT_URL, { urls: [url], advanced_settings: { full_content: { max_chars_per_result: asked } } }, signal);
|
|
72
|
+
if (!response.ok) {
|
|
73
|
+
await response.body?.cancel().catch(() => undefined);
|
|
74
|
+
return response.status === 401 || response.status === 403 ? `refused the key (${response.status})` : `answered ${response.status}`;
|
|
75
|
+
}
|
|
76
|
+
const { results, errors } = (await response.json());
|
|
77
|
+
const row = results?.find((r) => typeof r?.url === "string" && typeof r.full_content === "string" && r.full_content.trim() !== "");
|
|
78
|
+
if (!row)
|
|
79
|
+
return errors?.length ? "listed the URL in errors" : "answered no content";
|
|
80
|
+
const text = row.full_content;
|
|
81
|
+
return { ok: true, url: clip(row.url, URL_MAX), status: 200, title: clip(typeof row.title === "string" ? row.title : "", TITLE_CAP), ...textOf(text, text.length < asked), ...linksWithin(linksOf(text)) };
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (error instanceof PaidRefused)
|
|
85
|
+
return error.message;
|
|
86
|
+
const name = error?.name;
|
|
87
|
+
return name === "TimeoutError" ? "timed out" : name === "AbortError" ? "was stopped" : `failed: ${String(error?.message ?? error).slice(0, 200)}`;
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/** Whether the public-host guard passes `url` within `ms` and the caller's signal: fetch_page's port check, then
|
|
93
|
+
* publicFetch's own checks of the first hop (scheme, name, every address it resolves to), stopped before it dials. A
|
|
94
|
+
* check that runs out of time (a resolver that does not answer) does not pass; publicFetch ends a lookup at the abort. */
|
|
95
|
+
async function passes(url, options, ms) {
|
|
96
|
+
const target = URL.parse(url);
|
|
97
|
+
if (!target || !PORTS.has(target.port) || url.length > URL_MAX)
|
|
98
|
+
return false;
|
|
99
|
+
const { publicFetch } = await import("@parcha/pi-browser");
|
|
100
|
+
const checked = new Error("checked, not dialled");
|
|
101
|
+
const signal = AbortSignal.any([AbortSignal.timeout(ms), ...(options.signal ? [options.signal] : [])]);
|
|
102
|
+
return publicFetch(url, { ...options, signal, fetchImpl: async () => { throw checked; } }).then(() => false, (error) => error === checked);
|
|
103
|
+
}
|
|
104
|
+
/** The page at `url` read once: through `parallel` when it is given and live and the guard passes the URL within
|
|
105
|
+
* `checkMs` (default fetch_page's 30 s), else (or when it answers no page) through fetch_page's guarded fetch. A page
|
|
106
|
+
* fetched directly where `parallel` was given says why Parallel gave none (`parallel`): a picked provider that fails is
|
|
107
|
+
* never a silent fallback. */
|
|
108
|
+
async function readOnce(url, parallel, checkMs, options) {
|
|
109
|
+
let why;
|
|
110
|
+
if (parallel && !parallel.live())
|
|
111
|
+
why = "not tried: refused earlier in this run";
|
|
112
|
+
else if (parallel && !(typeof url === "string" && (await passes(url, options, checkMs))))
|
|
113
|
+
why = "not tried: the URL did not pass the public-host guard";
|
|
114
|
+
else if (parallel) {
|
|
115
|
+
const read = await parallel.read(url, options.signal);
|
|
116
|
+
if (typeof read !== "string")
|
|
117
|
+
return { ...read, via: "parallel" };
|
|
118
|
+
why = read;
|
|
119
|
+
}
|
|
120
|
+
return { ...(await readDirect(url, options)), via: "direct", ...(why ? { parallel: why } : {}) };
|
|
121
|
+
}
|
|
122
|
+
/** The reads that have ended: only these leave `pages` past its bound (trim). */
|
|
123
|
+
const settled = new WeakSet();
|
|
124
|
+
/** `pages` down to PAGES_HELD reads that have ENDED, dropping the least recently used of those first. Only ended reads
|
|
125
|
+
* count toward the bound, and only they are dropped: a read under way stays until it ends (a caller may be about to
|
|
126
|
+
* share it, and dropping it would read and bill the page again), and it never makes room by pushing out a page that has
|
|
127
|
+
* ended. So the run holds at most PAGES_HELD ended reads plus the ones still under way, and trims again as each ends. */
|
|
128
|
+
function trim(pages) {
|
|
129
|
+
let ended = 0;
|
|
130
|
+
for (const read of pages.values())
|
|
131
|
+
if (settled.has(read))
|
|
132
|
+
ended++;
|
|
133
|
+
for (const [held, read] of pages) {
|
|
134
|
+
if (ended <= PAGES_HELD)
|
|
135
|
+
return;
|
|
136
|
+
if (settled.has(read))
|
|
137
|
+
(pages.delete(held), ended--);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** `reading`, or, as soon as `signal` stops this call, a failed page saying so (as a stopped read reads): the read
|
|
141
|
+
* itself goes on for the run's other callers of the URL, within its own time limits. */
|
|
142
|
+
function untilStopped(url, reading, signal) {
|
|
143
|
+
if (!signal)
|
|
144
|
+
return reading;
|
|
145
|
+
// No page came for this call, by any path: never "direct", which says the host was fetched.
|
|
146
|
+
const stopped = () => ({ ok: false, url: typeof url === "string" ? clip(url, URL_MAX) : "", status: 0, title: "", text: "", links: [], error: "the call was stopped before the page arrived", via: "stopped" });
|
|
147
|
+
if (signal.aborted)
|
|
148
|
+
return Promise.resolve(stopped());
|
|
149
|
+
return new Promise((resolve, reject) => {
|
|
150
|
+
const onStop = () => resolve(stopped());
|
|
151
|
+
signal.addEventListener("abort", onStop, { once: true });
|
|
152
|
+
reading.then((read) => (signal.removeEventListener("abort", onStop), resolve(read)), (error) => (signal.removeEventListener("abort", onStop), reject(error)));
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/** The part (`offset`, `maxChars`) of the page at `url` as a WebPage: from `pages`, the run's, where it holds the URL
|
|
156
|
+
* (read, or being read), with no request of its own; else read once (readOnce), kept there from the read's start. A read
|
|
157
|
+
* that fails leaves `pages`, so a later call reads again. The read is the run's, not a caller's: no caller's signal
|
|
158
|
+
* reaches it (it keeps Parallel's and the fetch's own time limits), so one caller's stop never fails another's; each
|
|
159
|
+
* caller stops waiting at its own signal (untilStopped). */
|
|
160
|
+
export async function webFetch(url, { parallel, pages, checkMs = TIMEOUT_MS, offset, maxChars, signal, ...options } = {}) {
|
|
161
|
+
const named = typeof url === "string" ? url : undefined;
|
|
162
|
+
let reading = named === undefined ? undefined : pages?.get(named);
|
|
163
|
+
if (!reading) {
|
|
164
|
+
const started = readOnce(url, parallel, checkMs, options);
|
|
165
|
+
if (pages && named !== undefined) {
|
|
166
|
+
// Ahead of any caller's await, so no call sees a failed read kept.
|
|
167
|
+
const drop = () => void (pages.get(named) === started && pages.delete(named));
|
|
168
|
+
void started.then((read) => { settled.add(started); if (!read.ok)
|
|
169
|
+
drop(); trim(pages); }, () => { settled.add(started); drop(); });
|
|
170
|
+
}
|
|
171
|
+
reading = started;
|
|
172
|
+
}
|
|
173
|
+
if (pages && named !== undefined) {
|
|
174
|
+
// The last used last: the oldest goes past PAGES_HELD.
|
|
175
|
+
pages.delete(named);
|
|
176
|
+
pages.set(named, reading);
|
|
177
|
+
trim(pages);
|
|
178
|
+
}
|
|
179
|
+
const read = await untilStopped(url, reading, signal);
|
|
180
|
+
if (!read.ok)
|
|
181
|
+
return read;
|
|
182
|
+
const { via, parallel: why, ...page } = read;
|
|
183
|
+
return { ...partOfRead(page, { offset, maxChars }), via, ...(why ? { parallel: why } : {}) };
|
|
184
|
+
}
|
|
185
|
+
let parallel;
|
|
186
|
+
/** The pages this run read (Pages): its process is the run's, so the agent's tool and a call node's web_fetch share them. */
|
|
187
|
+
export const runPages = new Map();
|
|
188
|
+
/** The run's Parallel extract, made once in its process so a refused key holds for the rest of the run: on the Parallel
|
|
189
|
+
* key the server handed it (handedKeys, the read the decision providers share), null without one. */
|
|
190
|
+
export function parallelOf(env) {
|
|
191
|
+
if (parallel !== undefined)
|
|
192
|
+
return parallel;
|
|
193
|
+
const key = handedKeys(env)[PARALLEL_KEY_ENV];
|
|
194
|
+
return (parallel = key === undefined ? null : parallelExtract(key, async (...args) => ((await fauxFetch(env, FAUX_PARALLEL_ENV)) ?? fetch)(...args)));
|
|
195
|
+
}
|
|
196
|
+
/** The part `options` names of the page at `url` by the provider the run's plane resolves web_fetch to: Parallel's
|
|
197
|
+
* extract (with the direct fetch behind it) where it resolves to parallel, the guarded direct fetch otherwise, and a
|
|
198
|
+
* failed Page saying why where it is unavailable or the part is one a call may not ask for (partProblem), before
|
|
199
|
+
* anything is fetched. From `pages` (the run's, runPages) where they hold the URL. */
|
|
200
|
+
export async function fetchFor(env, url, options = {}) {
|
|
201
|
+
const problem = partProblem(options);
|
|
202
|
+
if (problem)
|
|
203
|
+
return { ok: false, url: typeof url === "string" ? clip(url, URL_MAX) : "", status: 0, title: "", text: "", links: [], error: problem };
|
|
204
|
+
const resolved = planeOf(env).web_fetch;
|
|
205
|
+
if (isUnavailable(resolved))
|
|
206
|
+
return { ok: false, url: typeof url === "string" ? clip(url, URL_MAX) : "", status: 0, title: "", text: "", links: [], error: `web_fetch does not run here: ${resolved.slice("unavailable: ".length)}` };
|
|
207
|
+
const extract = resolved === "parallel" ? parallelOf(env) : null;
|
|
208
|
+
const page = await webFetch(url, { ...options, parallel: extract });
|
|
209
|
+
return resolved === "parallel" && !extract ? { ...page, parallel: "not tried: this run holds no Parallel key" } : page;
|
|
210
|
+
}
|
|
211
|
+
/** What the part no part follows says of a page whose HTML readPage cut before it was read (html_chars). */
|
|
212
|
+
const CUT_LINE = `The page was cut at ${HTML_READ_CHARS.toLocaleString("en-US")} characters of HTML before reading; the rest wasn't read.`;
|
|
213
|
+
/** Where a part of a page is in it, for the model: which characters of how many, and the call that reads on; the end of
|
|
214
|
+
* the page, or where it was cut before it was read; or that the offset is past it. Nothing for a page read whole, or
|
|
215
|
+
* one that was not read. */
|
|
216
|
+
function partLine(page, name) {
|
|
217
|
+
if (!page.ok || page.chars === undefined)
|
|
218
|
+
return undefined;
|
|
219
|
+
const start = page.offset ?? 0;
|
|
220
|
+
const end = start + page.chars;
|
|
221
|
+
if (page.truncated)
|
|
222
|
+
return `Characters ${start}-${end} of ${page.original_chars ?? "a longer page"}: call ${name} again with offset=${page.next_offset ?? end} for the rest.`;
|
|
223
|
+
// No part follows, and the page was cut before it was read: its text ends at the cut, not at the page's end.
|
|
224
|
+
if (page.html_chars !== undefined)
|
|
225
|
+
return CUT_LINE;
|
|
226
|
+
if (page.beyond_read)
|
|
227
|
+
return `Characters ${start}-${end}${page.original_chars === undefined ? "" : ` of ${page.original_chars}`}: the page goes on, but web_fetch reads only a page's first ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")} characters.`;
|
|
228
|
+
if (page.original_chars === undefined)
|
|
229
|
+
return undefined;
|
|
230
|
+
if (page.chars === 0)
|
|
231
|
+
return `Nothing at offset=${start}: the page has ${page.original_chars} characters.`;
|
|
232
|
+
return `Characters ${start}-${end} of ${page.original_chars}: the end of the page.`;
|
|
233
|
+
}
|
|
234
|
+
/** A page as the tool `name` answers the model: its JSON, then a line saying why Parallel gave none where it was picked,
|
|
235
|
+
* and one saying where this part is in the page when it is not all of it. */
|
|
236
|
+
export function webFetchText(page, name = WEB_FETCH_TOOL) {
|
|
237
|
+
const lines = [JSON.stringify(page)];
|
|
238
|
+
if ("parallel" in page && page.parallel)
|
|
239
|
+
lines.push(`Parallel was picked for web_fetch and gave no page (${page.parallel}); this one was fetched directly.`);
|
|
240
|
+
const where = partLine(page, name);
|
|
241
|
+
if (where)
|
|
242
|
+
lines.push(where);
|
|
243
|
+
return lines.join("\n");
|
|
244
|
+
}
|
|
245
|
+
/** The agent's tool: the WebPage as JSON text (webFetchText), named `name` (fetch_page, its legacy name, runs it too). A
|
|
246
|
+
* run whose web_fetch resolves to Parallel reads its key as the tool is made, when the run opens. */
|
|
247
|
+
/** Typed here, so its declaration names the schema type by a package serve declares (pi-ai), whatever else the build loads. */
|
|
248
|
+
export function webFetchTool(env, name = WEB_FETCH_TOOL) {
|
|
249
|
+
if (planeOf(env).web_fetch === "parallel")
|
|
250
|
+
parallelOf(env);
|
|
251
|
+
return defineTool({
|
|
252
|
+
name,
|
|
253
|
+
description: `Read one web page from a public host, a part at a time. Answers JSON: ok, the final url, the HTTP status, the page's title, text (a part of its readable text as markdown: about max_chars characters from offset, ${PAGE_CHARS.toLocaleString("en-US")} by default, at least ${MAX_CHARS_MIN} and at most ${TEXT_CAP.toLocaleString("en-US")}) and chars (that part's length), the absolute links the page holds (with the part at offset 0; links_omitted counts those its caps left out), and via: parallel when Parallel's extract read it, direct when it was fetched from the host (with parallel saying why, where Parallel was picked and gave no page), stopped when the call was stopped before its page arrived. A part that is not the whole page says so: truncated is true while more follows, next_offset is where the rest begins, original_chars is the page's whole length where it is known, and a line after the JSON says which characters these are; call again with offset to read on. A page whose HTML is longer than ${HTML_READ_CHARS.toLocaleString("en-US")} characters (scripts and styles aside) is cut before it is read: html_chars gives its whole length on every part, its text is only the start of the page, and the last part's line says it was cut. converted is "text" when the text is the page's plain text, its conversion to markdown having run out of time. A page is read to its first ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")} characters (beyond_read on the last part says it goes on). A page is fetched once a run, at its first call: its later parts come from that read, with no request (through Parallel, one billed extract a page). A private or local address, a port other than 80 or 443, or a scheme other than http(s) is refused and never read (ok false, with refused saying why); so is a page fetched directly that is not text.`,
|
|
254
|
+
parameters: URL_PARAMETERS,
|
|
255
|
+
replay: "safe",
|
|
256
|
+
execute: async (args, _api, context) => {
|
|
257
|
+
const { url, offset, max_chars } = args;
|
|
258
|
+
const page = await fetchFor(env, url, { ...(await fetchOptions(env, FAUX_ENV)), offset, maxChars: max_chars, pages: runPages, ...(context?.abortSignal ? { signal: context.abortSignal } : {}) });
|
|
259
|
+
return forModel(webFetchText(page, name), { details: page });
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { TSchema } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { JsonValue } from "@earendil-works/chord";
|
|
3
|
+
import { type ToolRegistration } from "@earendil-works/pi-durable";
|
|
4
|
+
import { type Extract } from "./web-fetch.js";
|
|
5
|
+
export declare const WEB_SEARCH_TOOL = "web_search";
|
|
6
|
+
/** The tools that reach the web, each through the provider its run's plane resolves it to. */
|
|
7
|
+
export declare const WEB_TOOLS: readonly string[];
|
|
8
|
+
export declare const PARALLEL_SEARCH_URL = "https://api.parallel.ai/v1/search";
|
|
9
|
+
export declare const QUERY_MAX = 200;
|
|
10
|
+
export declare const RESULTS_MAX = 25;
|
|
11
|
+
/** The most of a result's text its snippet keeps; Parallel is asked for as much of each result's excerpts. */
|
|
12
|
+
export declare const SNIPPET_MAX = 3000;
|
|
13
|
+
/** The most of the provider's own short answer (`text`) a search keeps (hosted-search.ts). */
|
|
14
|
+
export declare const ANSWER_MAX = 4000;
|
|
15
|
+
/** The most characters a search's answer takes, its citing line included: about RESULTS_MAX results with whole snippets,
|
|
16
|
+
* under the host's result bound (HOST_RESULT_MAX_CHARS), which the host-bounds test holds it to. */
|
|
17
|
+
export declare const SEARCH_MAX_CHARS = 100000;
|
|
18
|
+
export type Hit = {
|
|
19
|
+
url: string;
|
|
20
|
+
title: string;
|
|
21
|
+
snippet: string;
|
|
22
|
+
published?: string;
|
|
23
|
+
};
|
|
24
|
+
export type Search = {
|
|
25
|
+
provider: "native" | "exa-keyless" | "parallel";
|
|
26
|
+
query: string;
|
|
27
|
+
results: Hit[];
|
|
28
|
+
text?: string;
|
|
29
|
+
omitted?: number;
|
|
30
|
+
} | {
|
|
31
|
+
error: string;
|
|
32
|
+
};
|
|
33
|
+
/** The line that ends a search's answer to the model, as Claude Code's WebSearch ends its own. */
|
|
34
|
+
export declare const CITE = "Cite the URL of each result you rely on.";
|
|
35
|
+
/** `answer` within SEARCH_MAX_CHARS, as searchText writes it: whole when it fits, else without its least relevant results
|
|
36
|
+
* (the last), as many as it takes, `omitted` counting them. */
|
|
37
|
+
export declare function fitSearch(answer: Search): Search;
|
|
38
|
+
/** A search as the model reads it: its JSON (fitSearch), then the line asking it to cite the URLs it relies on; an
|
|
39
|
+
* error's JSON alone. */
|
|
40
|
+
export declare function searchText(answer: Search): string;
|
|
41
|
+
/** A result's text as its snippet: links reduced to their text, whitespace collapsed, cut at SNIPPET_MAX on a word. */
|
|
42
|
+
export declare function snippetOf(raw: string): string;
|
|
43
|
+
/** `{query, n?}` as every provider takes it: the query trimmed and cut at QUERY_MAX, n 1 to RESULTS_MAX. */
|
|
44
|
+
export declare const searchArgs: (args: Record<string, unknown>) => {
|
|
45
|
+
query: string;
|
|
46
|
+
n: number;
|
|
47
|
+
};
|
|
48
|
+
/** `{query, n?}` searched through `parallel` (null: the run holds no key), as a Search. */
|
|
49
|
+
export declare function webSearch(args: Record<string, unknown>, parallel: Extract | null, signal?: AbortSignal): Promise<Search>;
|
|
50
|
+
/** `{query, n?}` searched by the provider the run's plane resolves web_search to, as a Search. */
|
|
51
|
+
export declare function searchFor(env: NodeJS.ProcessEnv, args: Record<string, unknown>, signal?: AbortSignal): Promise<Search>;
|
|
52
|
+
/** The agent's tool: the Search as JSON text. A run whose web_search resolves to Parallel reads its key as the tool is
|
|
53
|
+
* made, when the run opens. */
|
|
54
|
+
export declare function webSearchTool(env: NodeJS.ProcessEnv): ToolRegistration<TSchema, JsonValue>;
|