@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
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Decision providers: the models a workflow's judge, pick, sift, route and ask nodes ask, through the DSL's `runJudge`.
|
|
2
|
+
// This server runs three, each when its environment names the provider's key: Jev (TypeSafe's System One), on
|
|
3
|
+
// TYPESAFE_API_KEY (the route to use), or for Jev through OpenRouter OPENROUTER_API_KEY, else an OpenRouter model
|
|
4
|
+
// gateway's AGENT_MODEL_API_KEY; Parallel Decisions, on PARALLEL_API_KEY; and OpenRouter's Decisions models, on the
|
|
5
|
+
// same OpenRouter key Jev's OpenRouter route reads. A node names its provider (`provider: "parallel"`); one that names
|
|
6
|
+
// none is answered by Jev.
|
|
7
|
+
//
|
|
8
|
+
// The server chooses the keys a run needs (decisionKeysFor) and hands them over once, by name, on an inherited pipe
|
|
9
|
+
// (`DECISION_KEY_FD_ENV` names it), at each launch of the run: its workflow's decision providers' keys, and Parallel's
|
|
10
|
+
// where one of its web tools resolves to Parallel (tool-plane.ts); a run that needs none gets no pipe. The run's process
|
|
11
|
+
// reads them once (handedKeys) into its providers and the web tools' Parallel client (web-fetch.ts), and nowhere else;
|
|
12
|
+
// no provider reads a key from the environment. The TypeSafe and Parallel keys never enter a run's environment, which
|
|
13
|
+
// the run's tools and its model's provider read (`ToolHost.env`, a call node's effect): the server drops the variables
|
|
14
|
+
// from the run's process. On the OpenRouter route the Jev key is also the model gateway's key, which the run's process
|
|
15
|
+
// holds for its model nodes.
|
|
16
|
+
import { closeSync, readFileSync } from "node:fs";
|
|
17
|
+
import { pathToFileURL } from "node:url";
|
|
18
|
+
import { FAUX_ENV } from "./model.js";
|
|
19
|
+
export const JEV_KEY_ENV = "TYPESAFE_API_KEY";
|
|
20
|
+
export const JEV_OPENROUTER_KEY_ENV = "OPENROUTER_API_KEY";
|
|
21
|
+
export const PARALLEL_KEY_ENV = "PARALLEL_API_KEY";
|
|
22
|
+
/** The provider a decision node that names none is answered by. */
|
|
23
|
+
export const DEFAULT_DECISION_PROVIDER = "jev";
|
|
24
|
+
/** The adapter a workflow's typed questions run through. */
|
|
25
|
+
export const DECISION_ADAPTER = "runJudge";
|
|
26
|
+
/** Set on a run's process the server hands decision keys: the descriptor's number, never a key. The keys come as one
|
|
27
|
+
* JSON object of variable name to value, on the first descriptor after the process's stdio and its secrets pipe:
|
|
28
|
+
* macOS aborts the parent of a spawn with a pipe at 16 or above. */
|
|
29
|
+
export const DECISION_KEY_FD_ENV = "AGENTRUN_SERVE_DECISION_KEY_FD";
|
|
30
|
+
/** Under --faux only: a module whose default export is the fetch Jev's runner sends through, in place of TypeSafe's
|
|
31
|
+
* API (the tests' fake). */
|
|
32
|
+
export const FAUX_JEV_ENV = "AGENTRUN_SERVE_FAUX_JEV";
|
|
33
|
+
/** Under --faux only: a module whose default export is the fetch the Parallel provider sends through, in place of
|
|
34
|
+
* Parallel's API (the tests' fake). */
|
|
35
|
+
export const FAUX_PARALLEL_ENV = "AGENTRUN_SERVE_FAUX_PARALLEL";
|
|
36
|
+
/** Under `faux` only (startServe's `fauxOpenrouter`): a module whose default export is the fetch the OpenRouter decisions
|
|
37
|
+
* provider sends through, in place of OpenRouter's System One API (`@parcha/agentrun-decisions/testing/faux-system-one`
|
|
38
|
+
* is one). */
|
|
39
|
+
export const FAUX_OPENROUTER_ENV = "AGENTRUN_SERVE_FAUX_OPENROUTER";
|
|
40
|
+
const isSet = (value) => typeof value === "string" && value.trim() !== "";
|
|
41
|
+
/** The model gateway's key (model.ts), Jev's on the OpenRouter route when that gateway is OpenRouter. */
|
|
42
|
+
export const JEV_GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
|
|
43
|
+
/** The variable Jev's OpenRouter key is in: OPENROUTER_API_KEY, else the model gateway's key when AGENT_MODEL_BASE_URL's
|
|
44
|
+
* host is exactly openrouter.ai. Jev sends it to openrouter.ai, so another host's key never goes there. */
|
|
45
|
+
function openRouterKeyEnv(env) {
|
|
46
|
+
if (isSet(env[JEV_OPENROUTER_KEY_ENV]))
|
|
47
|
+
return JEV_OPENROUTER_KEY_ENV;
|
|
48
|
+
const onOpenRouter = URL.parse(env.AGENT_MODEL_BASE_URL ?? "")?.hostname === "openrouter.ai";
|
|
49
|
+
return onOpenRouter && isSet(env[JEV_GATEWAY_KEY_ENV]) ? JEV_GATEWAY_KEY_ENV : undefined;
|
|
50
|
+
}
|
|
51
|
+
/** The key Jev runs on here and its route: TypeSafe's API when its key is set, else OpenRouter's System One when an
|
|
52
|
+
* OpenRouter key is (openRouterKeyEnv). */
|
|
53
|
+
export function jevKey(env) {
|
|
54
|
+
if (isSet(env[JEV_KEY_ENV]))
|
|
55
|
+
return { route: "typesafe", key: env[JEV_KEY_ENV] };
|
|
56
|
+
const name = openRouterKeyEnv(env);
|
|
57
|
+
return name ? { route: "openrouter", key: env[name] } : undefined;
|
|
58
|
+
}
|
|
59
|
+
/** How this server reaches Jev, when it does. */
|
|
60
|
+
export const jevRoute = (env) => jevKey(env)?.route;
|
|
61
|
+
/** The keys the server hands a workflow run's process, by name: Jev's, as TYPESAFE_API_KEY or, on the OpenRouter route,
|
|
62
|
+
* as OPENROUTER_API_KEY whichever variable holds it; an OpenRouter key (openRouterKeyEnv) as OPENROUTER_API_KEY for
|
|
63
|
+
* OpenRouter's Decisions models, on either Jev route; and Parallel's. */
|
|
64
|
+
export function decisionKeysOf(env) {
|
|
65
|
+
const jev = jevKey(env);
|
|
66
|
+
const openrouter = openRouterKeyEnv(env);
|
|
67
|
+
return {
|
|
68
|
+
...(jev ? { [jev.route === "typesafe" ? JEV_KEY_ENV : JEV_OPENROUTER_KEY_ENV]: jev.key } : {}),
|
|
69
|
+
...(openrouter ? { [JEV_OPENROUTER_KEY_ENV]: env[openrouter] } : {}),
|
|
70
|
+
...(isSet(env[PARALLEL_KEY_ENV]) ? { [PARALLEL_KEY_ENV]: env[PARALLEL_KEY_ENV] } : {}),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** The decision keys the server hands a run's process for `needs`, of those it holds (decisionKeysOf): Jev's by its route
|
|
74
|
+
* (TypeSafe's, or OpenRouter's), OpenRouter's for an OpenRouter decision node, Parallel's for a Parallel one or for a
|
|
75
|
+
* web tool that resolves to Parallel. None else: a run with no decision node and no web tool on Parallel gets no
|
|
76
|
+
* descriptor at all. */
|
|
77
|
+
export function decisionKeysFor(env, needs) {
|
|
78
|
+
const names = new Set();
|
|
79
|
+
for (const id of needs.providers) {
|
|
80
|
+
const route = id === DEFAULT_DECISION_PROVIDER ? jevRoute(env) : undefined;
|
|
81
|
+
if (route)
|
|
82
|
+
names.add(route === "typesafe" ? JEV_KEY_ENV : JEV_OPENROUTER_KEY_ENV);
|
|
83
|
+
if (id === "openrouter")
|
|
84
|
+
names.add(JEV_OPENROUTER_KEY_ENV);
|
|
85
|
+
if (id === "parallel")
|
|
86
|
+
names.add(PARALLEL_KEY_ENV);
|
|
87
|
+
}
|
|
88
|
+
if (needs.parallelWeb)
|
|
89
|
+
names.add(PARALLEL_KEY_ENV);
|
|
90
|
+
return Object.fromEntries(Object.entries(decisionKeysOf(env)).filter(([name]) => names.has(name)));
|
|
91
|
+
}
|
|
92
|
+
/** Why Jev does not run here, naming the variable to set. */
|
|
93
|
+
export const jevMissing = `This server's environment does not set ${JEV_KEY_ENV} (or, for Jev through OpenRouter, ${JEV_OPENROUTER_KEY_ENV}, or ${JEV_GATEWAY_KEY_ENV} with AGENT_MODEL_BASE_URL on openrouter.ai), which a workflow's judge, pick, sift, route and ask nodes need.`;
|
|
94
|
+
/** Why Parallel does not run here, naming the variable to set. */
|
|
95
|
+
export const parallelMissing = `This server's environment does not set ${PARALLEL_KEY_ENV}, which a decision node naming the provider "parallel" needs.`;
|
|
96
|
+
/** Why the OpenRouter route is worth a note, naming the variable Jev runs on: its key is also the model gateway's, which
|
|
97
|
+
* a run's process holds. */
|
|
98
|
+
export const jevGatewayNote = (env) => `Jev runs on ${openRouterKeyEnv(env)}, the model gateway key on this server, which a run's processes hold in their environment for its model nodes. Set ${JEV_KEY_ENV} to keep the decision key out of them.`;
|
|
99
|
+
/** Why OpenRouter's decision models do not run here, naming the variable to set. */
|
|
100
|
+
export const openrouterMissing = `This server's environment does not set ${JEV_OPENROUTER_KEY_ENV} (or ${JEV_GATEWAY_KEY_ENV} with AGENT_MODEL_BASE_URL on openrouter.ai), which a decision node naming the provider "openrouter" needs.`;
|
|
101
|
+
/** What to know of OpenRouter's decision models here: the key they run on, which a run's process holds as the model
|
|
102
|
+
* gateway's, and that images go only to a model the catalog lists with image input, untested live. */
|
|
103
|
+
export const openrouterNote = (env) => `Any OpenRouter Decisions model, named by the node's model (required), on ${openRouterKeyEnv(env)}, the model gateway key on this server, which a run's processes hold in their environment. Images are experimental: sent only to a model OpenRouter's catalog lists with image input.`;
|
|
104
|
+
/** What this server offers of each decision provider. */
|
|
105
|
+
export function decisionsOf(env) {
|
|
106
|
+
const route = jevRoute(env);
|
|
107
|
+
const jev = route === "typesafe" ? { id: "jev", available: true } : route === "openrouter" ? { id: "jev", available: true, note: jevGatewayNote(env) } : { id: "jev", available: false, reason: jevMissing };
|
|
108
|
+
const parallel = isSet(env[PARALLEL_KEY_ENV]) ? { id: "parallel", available: true } : { id: "parallel", available: false, reason: parallelMissing };
|
|
109
|
+
const openrouter = openRouterKeyEnv(env) ? { id: "openrouter", available: true, note: openrouterNote(env) } : { id: "openrouter", available: false, reason: openrouterMissing };
|
|
110
|
+
return [jev, parallel, openrouter];
|
|
111
|
+
}
|
|
112
|
+
/** Why provider `id` does not run here and the variables that would make it run; undefined when it runs, and no `needs`
|
|
113
|
+
* for a provider this server does not have at all. */
|
|
114
|
+
export function providerMissing(env, id) {
|
|
115
|
+
if (id === DEFAULT_DECISION_PROVIDER)
|
|
116
|
+
return jevRoute(env) ? undefined : { message: jevMissing, needs: [JEV_KEY_ENV] };
|
|
117
|
+
if (id === "parallel")
|
|
118
|
+
return isSet(env[PARALLEL_KEY_ENV]) ? undefined : { message: parallelMissing, needs: [PARALLEL_KEY_ENV] };
|
|
119
|
+
if (id === "openrouter")
|
|
120
|
+
return openRouterKeyEnv(env) ? undefined : { message: openrouterMissing, needs: [JEV_OPENROUTER_KEY_ENV] };
|
|
121
|
+
return { message: `This server's decision providers are jev, parallel and openrouter; this workflow also names the provider ${id}.` };
|
|
122
|
+
}
|
|
123
|
+
/** The providers a workflow's typed questions are answered by (`nodes` from workflowNodes): each decision node's and
|
|
124
|
+
* `ask` predicate's own, else the default, as is a generative node's `verify`. */
|
|
125
|
+
export function providersNamed(nodes) {
|
|
126
|
+
const ids = new Set();
|
|
127
|
+
const add = (at) => ids.add(typeof at.provider === "string" ? (at.provider) : DEFAULT_DECISION_PROVIDER);
|
|
128
|
+
for (const node of nodes) {
|
|
129
|
+
if (["judge", "pick", "sift"].includes(node.node) || (node.node === "route" && node.valuePath === undefined))
|
|
130
|
+
add(node);
|
|
131
|
+
for (const predicate of [node.node === "loop" ? node.until : undefined, node.node === "escalate" ? node.when : undefined]) {
|
|
132
|
+
if (predicate?.predicate === "ask")
|
|
133
|
+
add(predicate);
|
|
134
|
+
}
|
|
135
|
+
if (node.verify)
|
|
136
|
+
ids.add(DEFAULT_DECISION_PROVIDER);
|
|
137
|
+
}
|
|
138
|
+
return [...ids];
|
|
139
|
+
}
|
|
140
|
+
let keysHanded;
|
|
141
|
+
/** The keys the server handed the run's process, by name: read at the first call and the descriptor closed, and the
|
|
142
|
+
* same object at every later one (the decision providers' and the web tools'), so the descriptor is read and closed once
|
|
143
|
+
* whoever asks first. Empty when none were handed, or when the first read failed. */
|
|
144
|
+
export function handedKeys(env) {
|
|
145
|
+
if (keysHanded)
|
|
146
|
+
return keysHanded;
|
|
147
|
+
keysHanded = {};
|
|
148
|
+
const fd = Number(env[DECISION_KEY_FD_ENV]);
|
|
149
|
+
if (!Number.isSafeInteger(fd) || fd < 3)
|
|
150
|
+
return keysHanded;
|
|
151
|
+
try {
|
|
152
|
+
const keys = JSON.parse(readFileSync(fd, "utf8"));
|
|
153
|
+
return (keysHanded = Object.fromEntries([JEV_KEY_ENV, JEV_OPENROUTER_KEY_ENV, PARALLEL_KEY_ENV].flatMap((name) => (typeof keys?.[name] === "string" ? [[name, keys[name]]] : []))));
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
closeSync(fd);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** Under --faux only: the fetch the module `env[name]` names, in place of a provider's API (the tests' fake). */
|
|
160
|
+
export const fauxFetch = async (env, name) => env[FAUX_ENV] && env[name] ? (await import(pathToFileURL(env[name]).href)).default : undefined;
|
|
161
|
+
/** In a run's process: the decision providers its workflow's typed questions are answered by, on the keys the server
|
|
162
|
+
* handed it (Jev's, Parallel's), and the one a node that names none gets; undefined when it handed none. Called once per
|
|
163
|
+
* process, on the keys handedKeys read once for it and the web tools alike. The run's judge (`judgeFromProviders`) and its
|
|
164
|
+
* checks before any node runs take this one registry, so a node's provider and timeoutMs hold, and a node naming a
|
|
165
|
+
* provider it lacks is refused before the run instead of being asked of another. Each provider sends a request once: one that fails after it
|
|
166
|
+
* was sent may have been answered and billed, so the decision escalates as interrupted instead of being asked again. */
|
|
167
|
+
export async function decisionProvidersOf(env) {
|
|
168
|
+
const handed = handedKeys(env);
|
|
169
|
+
const providers = {};
|
|
170
|
+
const jev = handed[JEV_KEY_ENV] !== undefined ? { apiKey: handed[JEV_KEY_ENV] } : handed[JEV_OPENROUTER_KEY_ENV] !== undefined ? { provider: "openrouter", apiKey: handed[JEV_OPENROUTER_KEY_ENV] } : undefined;
|
|
171
|
+
if (jev) {
|
|
172
|
+
const [{ jevProvider }, faux] = await Promise.all([import("@parcha/agentrun-jev"), fauxFetch(env, FAUX_JEV_ENV)]);
|
|
173
|
+
providers.jev = jevProvider({ ...jev, ...(faux ? { fetch: faux } : {}) });
|
|
174
|
+
}
|
|
175
|
+
if (handed[PARALLEL_KEY_ENV] !== undefined) {
|
|
176
|
+
const [{ parallelProvider }, faux] = await Promise.all([import("@parcha/agentrun-decisions"), fauxFetch(env, FAUX_PARALLEL_ENV)]);
|
|
177
|
+
providers.parallel = parallelProvider({ apiKey: handed[PARALLEL_KEY_ENV], ...(faux ? { fetch: faux } : {}) });
|
|
178
|
+
}
|
|
179
|
+
if (handed[JEV_OPENROUTER_KEY_ENV] !== undefined) {
|
|
180
|
+
const [{ openrouterProvider }, faux] = await Promise.all([import("@parcha/agentrun-decisions"), fauxFetch(env, FAUX_OPENROUTER_ENV)]);
|
|
181
|
+
providers.openrouter = openrouterProvider({ apiKey: handed[JEV_OPENROUTER_KEY_ENV], ...(faux ? { fetch: faux } : {}), app: { title: "AgentRun Server" } });
|
|
182
|
+
}
|
|
183
|
+
return Object.keys(providers).length ? { providers, default: DEFAULT_DECISION_PROVIDER } : undefined;
|
|
184
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Effort } from "./model.js";
|
|
2
|
+
/** The note each effort adds after the agent's instructions. */
|
|
3
|
+
export declare const EFFORT_GUIDANCE: Readonly<Record<Effort, string>>;
|
|
4
|
+
/** `effort`'s note, or undefined for none (or a value that is not an effort). */
|
|
5
|
+
export declare function effortGuidance(effort: string | undefined): string | undefined;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// A run's effort is its model's thinking level (model.ts thinkingOf) and a short note on how to work, added right after
|
|
2
|
+
// the agent's instructions on every harness (app.ts): one table, one note for each effort. A run with no effort gets no
|
|
3
|
+
// note, and thinks at its agent revision's own thinking level, else the host's default.
|
|
4
|
+
import { EFFORTS } from "./model.js";
|
|
5
|
+
/** The note each effort adds after the agent's instructions. */
|
|
6
|
+
export const EFFORT_GUIDANCE = {
|
|
7
|
+
low: "Answer directly and keep it short. If you need a fact you don't have, or one that may have changed since your training, search once and use what you find. Cite the sources you use. Don't make a plan, don't write extra files, and don't explore past the question. Stop as soon as the question is answered.",
|
|
8
|
+
medium: "Start with a short plan of two to four steps. When you need facts, run your searches in parallel, prefer recent primary sources, and check each key claim against a second, independent source. Cite what you use. Do the work the plan calls for and no more. Write the answer, then check it once against the question: does it answer every part, and is each claim supported? Fix what's missing, then finish.",
|
|
9
|
+
high: "Be thorough. Before you start, break the task into its parts and plan how to cover each one. Work through the parts in order. Where a part needs facts, search widely: run searches in parallel, read the primary sources, and check every important claim against at least two independent sources. When the parts are done, look for gaps, contradictions and claims you haven't checked, and fill them. Then write the full result, with citations. Before you finish, review it once against the original request, point by point, and fix anything missing or wrong.",
|
|
10
|
+
};
|
|
11
|
+
/** `effort`'s note, or undefined for none (or a value that is not an effort). */
|
|
12
|
+
export function effortGuidance(effort) {
|
|
13
|
+
return EFFORTS.includes(effort) ? EFFORT_GUIDANCE[effort] : undefined;
|
|
14
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Extension } from "@earendil-works/pi-durable";
|
|
2
|
+
/** The environment line on `now`'s day, in UTC. */
|
|
3
|
+
export declare function environmentLine(now?: Date): string;
|
|
4
|
+
/** pi's section of the line, untagged: installed before any other extension, it is the system prompt's first text. */
|
|
5
|
+
export declare const EnvironmentLine: Extension;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The line every harness's system prompt starts with: today's date, in UTC, and where the run works. A model knows only
|
|
2
|
+
// the date its training ended, so a question about "the latest" release is answered from then unless the run says what
|
|
3
|
+
// day it is. One line for every harness, made as each turn starts, so a run resumed on a later day reads that day: pi's
|
|
4
|
+
// section is rendered again before each model request, and another harness's session is opened with it in each process.
|
|
5
|
+
import { defineExtension, section } from "@earendil-works/pi-durable";
|
|
6
|
+
/** The environment line on `now`'s day, in UTC. */
|
|
7
|
+
export function environmentLine(now = new Date()) {
|
|
8
|
+
return `Today is ${now.toISOString().slice(0, 10)} (UTC). You are running on AgentRun; your workspace is your working directory, and file paths are relative to it.`;
|
|
9
|
+
}
|
|
10
|
+
/** pi's section of the line, untagged: installed before any other extension, it is the system prompt's first text. */
|
|
11
|
+
export const EnvironmentLine = defineExtension({ name: "agentrun-environment", sections: [section("environment", () => environmentLine(), { tag: false })] });
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Each code of the closed list, with its one HTTP status. */
|
|
2
|
+
export declare const ERROR_STATUS: {
|
|
3
|
+
readonly bad_request: 400;
|
|
4
|
+
readonly invalid_file_path: 400;
|
|
5
|
+
readonly unauthenticated: 401;
|
|
6
|
+
readonly insufficient_credits: 402;
|
|
7
|
+
readonly spend_cap_reached: 402;
|
|
8
|
+
readonly forbidden: 403;
|
|
9
|
+
readonly system_file_forbidden: 403;
|
|
10
|
+
readonly not_found: 404;
|
|
11
|
+
readonly method_not_allowed: 405;
|
|
12
|
+
readonly agent_exists: 409;
|
|
13
|
+
readonly agent_not_runnable: 409;
|
|
14
|
+
readonly home_busy: 409;
|
|
15
|
+
readonly idempotency_mismatch: 409;
|
|
16
|
+
readonly idempotency_in_progress: 409;
|
|
17
|
+
readonly not_continuable: 409;
|
|
18
|
+
readonly quote_invalid: 409;
|
|
19
|
+
readonly precondition_failed: 412;
|
|
20
|
+
readonly payload_too_large: 413;
|
|
21
|
+
readonly unsupported_media_type: 415;
|
|
22
|
+
readonly range_not_satisfiable: 416;
|
|
23
|
+
readonly input_invalid: 422;
|
|
24
|
+
readonly home_check_failed: 422;
|
|
25
|
+
readonly rate_limited: 429;
|
|
26
|
+
readonly internal: 500;
|
|
27
|
+
readonly unsupported_here: 501;
|
|
28
|
+
readonly unavailable: 503;
|
|
29
|
+
readonly key_set_by_server: 409;
|
|
30
|
+
readonly no_sealing_key: 409;
|
|
31
|
+
readonly webhook_off: 409;
|
|
32
|
+
readonly precondition_required: 428;
|
|
33
|
+
readonly auth_required: 422;
|
|
34
|
+
readonly not_mcp: 422;
|
|
35
|
+
readonly upstream_failed: 424;
|
|
36
|
+
readonly store_unreadable: 409;
|
|
37
|
+
};
|
|
38
|
+
export type ErrorCode = keyof typeof ERROR_STATUS;
|
|
39
|
+
export type InputIssue = {
|
|
40
|
+
field: string;
|
|
41
|
+
reason: string;
|
|
42
|
+
message: string;
|
|
43
|
+
expected?: string;
|
|
44
|
+
fix?: string;
|
|
45
|
+
code?: string;
|
|
46
|
+
};
|
|
47
|
+
/** What a refusal carries beside its code and message. */
|
|
48
|
+
export type ErrorExtra = {
|
|
49
|
+
capability?: string;
|
|
50
|
+
fields?: InputIssue[];
|
|
51
|
+
next_action?: Record<string, unknown>;
|
|
52
|
+
details?: Record<string, unknown>;
|
|
53
|
+
retry_after_ms?: number;
|
|
54
|
+
/** A learning note the structural checks refuse: each problem, printable. */
|
|
55
|
+
problems?: readonly unknown[];
|
|
56
|
+
};
|
|
57
|
+
export declare class ApiError extends Error {
|
|
58
|
+
readonly code: ErrorCode;
|
|
59
|
+
readonly status: number;
|
|
60
|
+
readonly extra: ErrorExtra;
|
|
61
|
+
readonly headers: Record<string, string>;
|
|
62
|
+
constructor(code: ErrorCode, message: string, extra?: ErrorExtra, headers?: Record<string, string>);
|
|
63
|
+
body(requestId: string): {
|
|
64
|
+
error: Record<string, unknown>;
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/** A feature this server does not offer: 501 naming its dotted path under `features`. */
|
|
68
|
+
export declare const unsupported: (capability: string, message: string) => ApiError;
|
|
69
|
+
/** `text` as one sentence: it ends in one full stop, whatever it ended in (a box's reason ends in none). */
|
|
70
|
+
export declare const sentence: (text: string) => string;
|
|
71
|
+
/** `422 input_invalid` with each field that is missing or wrong. */
|
|
72
|
+
export declare const invalid: (fields: InputIssue[], message?: string) => ApiError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// The /v2 error envelope: `{error: {code, message, retryable, ...}}`, with a code from the contract's closed list and
|
|
2
|
+
// that code's one HTTP status.
|
|
3
|
+
/** Each code of the closed list, with its one HTTP status. */
|
|
4
|
+
export const ERROR_STATUS = {
|
|
5
|
+
bad_request: 400,
|
|
6
|
+
invalid_file_path: 400,
|
|
7
|
+
unauthenticated: 401,
|
|
8
|
+
insufficient_credits: 402,
|
|
9
|
+
spend_cap_reached: 402,
|
|
10
|
+
forbidden: 403,
|
|
11
|
+
system_file_forbidden: 403,
|
|
12
|
+
not_found: 404,
|
|
13
|
+
method_not_allowed: 405,
|
|
14
|
+
agent_exists: 409,
|
|
15
|
+
agent_not_runnable: 409,
|
|
16
|
+
home_busy: 409,
|
|
17
|
+
idempotency_mismatch: 409,
|
|
18
|
+
idempotency_in_progress: 409,
|
|
19
|
+
not_continuable: 409,
|
|
20
|
+
quote_invalid: 409,
|
|
21
|
+
precondition_failed: 412,
|
|
22
|
+
payload_too_large: 413,
|
|
23
|
+
unsupported_media_type: 415,
|
|
24
|
+
range_not_satisfiable: 416,
|
|
25
|
+
input_invalid: 422,
|
|
26
|
+
home_check_failed: 422,
|
|
27
|
+
rate_limited: 429,
|
|
28
|
+
internal: 500,
|
|
29
|
+
unsupported_here: 501,
|
|
30
|
+
unavailable: 503,
|
|
31
|
+
// This server's own, beside the contract's list (openapi.ts marks them): a tool key its launcher sets, a key saved with
|
|
32
|
+
// no seal key to keep it under, a send to a webhook a 410 turned off, a write to a learning note that names no
|
|
33
|
+
// version it read, a remote MCP server that asks for a credential, does not speak MCP, or fails, and a saved-servers
|
|
34
|
+
// file that does not read, which is never written over (mcp-servers.ts).
|
|
35
|
+
key_set_by_server: 409,
|
|
36
|
+
no_sealing_key: 409,
|
|
37
|
+
webhook_off: 409,
|
|
38
|
+
precondition_required: 428,
|
|
39
|
+
auth_required: 422,
|
|
40
|
+
not_mcp: 422,
|
|
41
|
+
upstream_failed: 424,
|
|
42
|
+
store_unreadable: 409,
|
|
43
|
+
};
|
|
44
|
+
const RETRYABLE = new Set(["home_busy", "idempotency_in_progress", "rate_limited", "internal", "unavailable"]);
|
|
45
|
+
export class ApiError extends Error {
|
|
46
|
+
code;
|
|
47
|
+
status;
|
|
48
|
+
extra;
|
|
49
|
+
headers;
|
|
50
|
+
constructor(code, message, extra = {}, headers = {}) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.code = code;
|
|
53
|
+
this.status = ERROR_STATUS[code];
|
|
54
|
+
this.extra = extra;
|
|
55
|
+
this.headers = headers;
|
|
56
|
+
}
|
|
57
|
+
body(requestId) {
|
|
58
|
+
return { error: { code: this.code, message: this.message, retryable: RETRYABLE.has(this.code), request_id: requestId, ...this.extra } };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/** A feature this server does not offer: 501 naming its dotted path under `features`. */
|
|
62
|
+
export const unsupported = (capability, message) => new ApiError("unsupported_here", message, { capability });
|
|
63
|
+
/** `text` as one sentence: it ends in one full stop, whatever it ended in (a box's reason ends in none). */
|
|
64
|
+
export const sentence = (text) => `${text.trimEnd().replace(/[.?!;:,]+$/, "")}.`;
|
|
65
|
+
/** `422 input_invalid` with each field that is missing or wrong. */
|
|
66
|
+
export const invalid = (fields, message = fields[0]?.message ?? "the request is not valid") => new ApiError("input_invalid", message, { fields });
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { LookupFunction } from "node:net";
|
|
2
|
+
import { type Search } from "./web-search.js";
|
|
3
|
+
export declare const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
|
|
4
|
+
export declare const EXA_SEARCH_TOOL = "web_search_exa";
|
|
5
|
+
/** Under `--faux` only: a module whose default export is the fetch Exa's MCP exchange goes through (the tests' fake
|
|
6
|
+
* MCP server), in place of Exa's endpoint. */
|
|
7
|
+
export declare const FAUX_EXA_ENV = "AGENTRUN_SERVE_FAUX_EXA";
|
|
8
|
+
/** What a search answers when Exa's free limit holds after the one retry. Exa's own words name a fix (an API key in
|
|
9
|
+
* its MCP URL) that means nothing to a person here, so they are never passed on. */
|
|
10
|
+
export declare const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute, or add a Parallel key in Settings \u2192 Tool keys to search with a key.";
|
|
11
|
+
/** A search Exa refused for its free limit (`retryAfterS`, the wait it named, when it named one) or for the connection
|
|
12
|
+
* (403): a reason another provider may get past, which the caller reads before the model reads `error` alone. */
|
|
13
|
+
export type ExaLimited = {
|
|
14
|
+
error: string;
|
|
15
|
+
limit: "rate_limited";
|
|
16
|
+
retryAfterS?: number;
|
|
17
|
+
} | {
|
|
18
|
+
error: string;
|
|
19
|
+
limit: "connection_refused";
|
|
20
|
+
};
|
|
21
|
+
/** A fetch that reaches hosts over IPv4 alone: each name looked up for family 4 (through `lookup`, default the system
|
|
22
|
+
* resolver) and the connection dialled at the address found, never an IPv6 one. undici loads at the first request, so
|
|
23
|
+
* a run that never searches never loads it; `close` ends the connections. */
|
|
24
|
+
export declare function ipv4Fetch(lookup?: LookupFunction): {
|
|
25
|
+
send: typeof fetch;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
};
|
|
28
|
+
/** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
|
|
29
|
+
* ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
|
|
30
|
+
* `pause` (default a wait the search's signal ends; a test's records it). */
|
|
31
|
+
export declare function exaSearch(query: string, n: number, { send, signal, pause }?: {
|
|
32
|
+
send?: typeof fetch;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
pause?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
35
|
+
}): Promise<Search | ExaLimited>;
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// web_search's keyless fallback: Exa's public MCP endpoint (https://mcp.exa.ai/mcp, docs.exa.ai/reference/exa-mcp),
|
|
2
|
+
// which answers its `web_search_exa` tool with no key at a free rate limit. One search is one MCP exchange over its
|
|
3
|
+
// streamable HTTP transport: `initialize` (its session id, when it names one), `notifications/initialized`, then
|
|
4
|
+
// `tools/call` of web_search_exa with `{query, numResults}`, at most 8. Exa answers one text block, a result per section split by
|
|
5
|
+
// `---` lines, each `Title:`, `URL:`, `Published:`, `Author:`, then `Highlights:` (or `Text:`) and its lines; a `Note:`
|
|
6
|
+
// line may lead it. That text is read into the same Search every web_search answers, and no more than 1 MiB of an
|
|
7
|
+
// answer is read. Past its free limit Exa answers a 429 with Retry-After, or (when its search API refuses the keyless
|
|
8
|
+
// call) a 200 whose tool result is marked isError and `ai.exa/rateLimited`, its text telling the user to put an API key
|
|
9
|
+
// in their MCP URL. Either is tried once more, a new exchange after a jittered 1 to 3 s or the Retry-After Exa names when
|
|
10
|
+
// it is 5 s or less (past that, as with its daily limit, the limit does not lift within a search, and it is not tried
|
|
11
|
+
// again); still limited, the search answers RATE_LIMITED, in our words, never Exa's. Any other failure Exa answers is
|
|
12
|
+
// ours too, quoting only the first sentence of Exa's (exaSaid). A 403 is a connection keyless use
|
|
13
|
+
// refuses (Exa takes it over IPv4, straight to the endpoint), never tried again. Both say which limit they met
|
|
14
|
+
// (ExaLimited), for the caller's fallback. A search ends at 60 s, its retry and wait included. No key is sent, ever.
|
|
15
|
+
// Exa is dialled over IPv4 alone (ipv4Fetch): its name looked up for family 4 and the connection made to that address,
|
|
16
|
+
// so a host whose default route is IPv6 reaches it the one way keyless use is taken.
|
|
17
|
+
import { lookup as dnsLookup } from "node:dns";
|
|
18
|
+
import { clip, TITLE_CAP } from "./fetch-page.js";
|
|
19
|
+
import { snippetOf } from "./web-search.js";
|
|
20
|
+
export const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
|
|
21
|
+
export const EXA_SEARCH_TOOL = "web_search_exa";
|
|
22
|
+
/** Under `--faux` only: a module whose default export is the fetch Exa's MCP exchange goes through (the tests' fake
|
|
23
|
+
* MCP server), in place of Exa's endpoint. */
|
|
24
|
+
export const FAUX_EXA_ENV = "AGENTRUN_SERVE_FAUX_EXA";
|
|
25
|
+
/** The MCP revision this client speaks; the server answers the one it takes. */
|
|
26
|
+
const PROTOCOL = "2025-06-18";
|
|
27
|
+
const TIMEOUT_MS = 60_000;
|
|
28
|
+
/** The most results Exa's free endpoint is asked for (its default is 10). Its own cap on purpose, not web search's
|
|
29
|
+
* RESULTS_MAX: the hosted providers take more, and Exa's keyless limit is per request. */
|
|
30
|
+
const RESULTS_MAX = 8;
|
|
31
|
+
const ACCEPT = "application/json, text/event-stream";
|
|
32
|
+
/** The most of an answer read: a search's text is a few kilobytes; past this the rest is never read. */
|
|
33
|
+
const MAX_BYTES = 1 << 20;
|
|
34
|
+
/** What a search answers when Exa's free limit holds after the one retry. Exa's own words name a fix (an API key in
|
|
35
|
+
* its MCP URL) that means nothing to a person here, so they are never passed on. */
|
|
36
|
+
export const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute, or add a Parallel key in Settings → Tool keys to search with a key.";
|
|
37
|
+
/** The most of Exa's own words a failure quotes: the first sentence of its first line, cut on a word. */
|
|
38
|
+
const SAID_MAX = 120;
|
|
39
|
+
/** A failure Exa answered, in our words: the first sentence of its text, short and quoted. Its later lines (a fix for its
|
|
40
|
+
* MCP URL, a timestamp) are never passed on, so a deployment that does not mark its free limit says no setup text. */
|
|
41
|
+
function exaSaid(text) {
|
|
42
|
+
const line = text.split("\n").map((part) => part.trim()).find(Boolean) ?? "";
|
|
43
|
+
const sentence = /^.*?[.!?](?=\s|$)/.exec(line)?.[0] ?? line;
|
|
44
|
+
const short = sentence.length <= SAID_MAX ? sentence : `${sentence.slice(0, SAID_MAX - 1).replace(/\s+\S*$/, "")}…`;
|
|
45
|
+
return short ? `Free web search failed. Exa said: "${short}"` : "Free web search failed: Exa gave no answer";
|
|
46
|
+
}
|
|
47
|
+
/** The `_meta` key Exa's MCP server marks a tool result reporting its free limit with (isError as well). */
|
|
48
|
+
const RATE_LIMITED_META = "ai.exa/rateLimited";
|
|
49
|
+
/** The longest Retry-After waited out before the one retry. */
|
|
50
|
+
const RETRY_AFTER_MAX_S = 5;
|
|
51
|
+
/** The seconds a Retry-After names, as seconds or a date; undefined when it names none. */
|
|
52
|
+
function retryAfterOf(response) {
|
|
53
|
+
const said = response.headers.get("retry-after")?.trim();
|
|
54
|
+
if (!said)
|
|
55
|
+
return undefined;
|
|
56
|
+
if (/^\d+$/.test(said))
|
|
57
|
+
return Number(said);
|
|
58
|
+
const at = Date.parse(said);
|
|
59
|
+
return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - Date.now()) / 1000));
|
|
60
|
+
}
|
|
61
|
+
/** The wait before the one retry: the Retry-After Exa named, else 1 to 3 s, each with jitter so runs limited together
|
|
62
|
+
* do not all ask again at once. */
|
|
63
|
+
const waitOf = (retryAfterS) => (retryAfterS === undefined ? 1_000 + Math.random() * 2_000 : retryAfterS * 1_000 + Math.random() * 500);
|
|
64
|
+
/** `ms` of waiting that `signal` ends, rejecting with its reason. */
|
|
65
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
66
|
+
if (signal.aborted)
|
|
67
|
+
return reject(signal.reason);
|
|
68
|
+
const stop = () => {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
reject(signal.reason);
|
|
71
|
+
};
|
|
72
|
+
const timer = setTimeout(() => {
|
|
73
|
+
signal.removeEventListener("abort", stop);
|
|
74
|
+
resolve();
|
|
75
|
+
}, ms);
|
|
76
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
77
|
+
});
|
|
78
|
+
/** A fetch that reaches hosts over IPv4 alone: each name looked up for family 4 (through `lookup`, default the system
|
|
79
|
+
* resolver) and the connection dialled at the address found, never an IPv6 one. undici loads at the first request, so
|
|
80
|
+
* a run that never searches never loads it; `close` ends the connections. */
|
|
81
|
+
export function ipv4Fetch(lookup = dnsLookup) {
|
|
82
|
+
const ipv4 = (host, options, callback) => lookup(host, { ...options, family: 4 }, callback);
|
|
83
|
+
let opened;
|
|
84
|
+
const open = () => (opened ??= import("undici").then(({ Agent, fetch }) => ({ dispatcher: new Agent({ connect: { family: 4, lookup: ipv4 } }), dial: fetch })));
|
|
85
|
+
const send = async (url, init) => {
|
|
86
|
+
const { dispatcher, dial } = await open();
|
|
87
|
+
return dial(url, { ...init, dispatcher });
|
|
88
|
+
};
|
|
89
|
+
return { send: send, close: async () => void (opened && (await (await opened).dispatcher.close())) };
|
|
90
|
+
}
|
|
91
|
+
/** At most MAX_BYTES of a body, as text; the rest is not read. */
|
|
92
|
+
async function boundedText(response) {
|
|
93
|
+
const reader = response.body?.getReader();
|
|
94
|
+
const chunks = [];
|
|
95
|
+
for (let size = 0; reader && size < MAX_BYTES;) {
|
|
96
|
+
const { done, value } = await reader.read();
|
|
97
|
+
if (done)
|
|
98
|
+
break;
|
|
99
|
+
chunks.push(value);
|
|
100
|
+
size += value.byteLength;
|
|
101
|
+
}
|
|
102
|
+
await reader?.cancel().catch(() => undefined);
|
|
103
|
+
return Buffer.concat(chunks).subarray(0, MAX_BYTES).toString("utf8");
|
|
104
|
+
}
|
|
105
|
+
/** A JSON-RPC answer's body: JSON, or the `data:` lines of an event stream, the one answering `id`. */
|
|
106
|
+
async function answerOf(response, id) {
|
|
107
|
+
const text = await boundedText(response);
|
|
108
|
+
const messages = /event-stream/i.test(response.headers.get("content-type") ?? "")
|
|
109
|
+
? text.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim())
|
|
110
|
+
: [text];
|
|
111
|
+
for (const message of messages) {
|
|
112
|
+
try {
|
|
113
|
+
const parsed = JSON.parse(message);
|
|
114
|
+
if (parsed.id === id)
|
|
115
|
+
return parsed;
|
|
116
|
+
}
|
|
117
|
+
catch { }
|
|
118
|
+
}
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
/** Exa's text for one result as a Hit, or undefined when it names no URL. */
|
|
122
|
+
function hitOf(section) {
|
|
123
|
+
const lines = section.split("\n");
|
|
124
|
+
const field = (name) => lines.find((line) => line.startsWith(`${name}:`))?.slice(name.length + 1).trim();
|
|
125
|
+
const url = field("URL");
|
|
126
|
+
if (!url || !URL.canParse(url))
|
|
127
|
+
return undefined;
|
|
128
|
+
const known = (value) => (value && value !== "N/A" ? value : undefined);
|
|
129
|
+
const body = lines.findIndex((line) => /^(Highlights|Text):/.test(line));
|
|
130
|
+
const snippet = body < 0 ? "" : [lines[body].replace(/^(Highlights|Text):\s*/, ""), ...lines.slice(body + 1)].join(" ").trim();
|
|
131
|
+
const published = known(field("Published"));
|
|
132
|
+
return { url, title: clip(known(field("Title")) ?? "", TITLE_CAP), snippet: snippetOf(snippet), ...(published ? { published } : {}) };
|
|
133
|
+
}
|
|
134
|
+
/** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
|
|
135
|
+
* ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
|
|
136
|
+
* `pause` (default a wait the search's signal ends; a test's records it). */
|
|
137
|
+
export async function exaSearch(query, n, { send, signal, pause = sleep } = {}) {
|
|
138
|
+
const deadline = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]);
|
|
139
|
+
const own = send ? undefined : ipv4Fetch();
|
|
140
|
+
const dial = send ?? own.send;
|
|
141
|
+
try {
|
|
142
|
+
const first = await exchange(query, n, dial, deadline);
|
|
143
|
+
if (!("limit" in first) || first.limit !== "rate_limited" || (first.retryAfterS ?? 0) > RETRY_AFTER_MAX_S)
|
|
144
|
+
return first;
|
|
145
|
+
await pause(waitOf(first.retryAfterS), deadline);
|
|
146
|
+
return await exchange(query, n, dial, deadline);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
const name = error?.name;
|
|
150
|
+
return { error: name === "TimeoutError" ? "Exa's search did not answer within 60 s" : name === "AbortError" ? "the search was stopped" : `Exa's search failed: ${String(error?.message ?? error).slice(0, 300)}` };
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
await own?.close().catch(() => undefined);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** One MCP exchange searching `query` through `dial`, each request ended by `deadline`; a failure to reach Exa throws. */
|
|
157
|
+
async function exchange(query, n, dial, deadline) {
|
|
158
|
+
let session;
|
|
159
|
+
const post = (body) => dial(EXA_MCP_URL, {
|
|
160
|
+
method: "POST",
|
|
161
|
+
headers: { "content-type": "application/json", accept: ACCEPT, "mcp-protocol-version": PROTOCOL, ...(session ? { "mcp-session-id": session } : {}) },
|
|
162
|
+
body: JSON.stringify({ jsonrpc: "2.0", ...body }),
|
|
163
|
+
signal: deadline,
|
|
164
|
+
});
|
|
165
|
+
const refused = async (response, step) => {
|
|
166
|
+
if (response.ok)
|
|
167
|
+
return undefined;
|
|
168
|
+
await response.body?.cancel().catch(() => undefined);
|
|
169
|
+
if (response.status === 429) {
|
|
170
|
+
const retryAfterS = retryAfterOf(response);
|
|
171
|
+
return { error: RATE_LIMITED, limit: "rate_limited", ...(retryAfterS === undefined ? {} : { retryAfterS }) };
|
|
172
|
+
}
|
|
173
|
+
if (response.status === 403)
|
|
174
|
+
return { error: "Exa refused keyless use from this connection (403): it takes keyless searches only over IPv4, straight to its endpoint, not over IPv6 or through a proxy", limit: "connection_refused" };
|
|
175
|
+
return { error: `Exa's MCP endpoint answered ${response.status} to ${step}` };
|
|
176
|
+
};
|
|
177
|
+
const opened = await post({ id: 1, method: "initialize", params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "agentrun-serve", version: "1" } } });
|
|
178
|
+
const failed = await refused(opened, "initialize");
|
|
179
|
+
if (failed)
|
|
180
|
+
return failed;
|
|
181
|
+
session = opened.headers.get("mcp-session-id") ?? undefined;
|
|
182
|
+
if (!(await answerOf(opened, 1))?.result)
|
|
183
|
+
return { error: "Exa's MCP endpoint did not answer initialize" };
|
|
184
|
+
const ready = await post({ method: "notifications/initialized" });
|
|
185
|
+
await ready.body?.cancel().catch(() => undefined);
|
|
186
|
+
const called = await post({ id: 2, method: "tools/call", params: { name: EXA_SEARCH_TOOL, arguments: { query, numResults: Math.min(n, RESULTS_MAX) } } });
|
|
187
|
+
const late = await refused(called, "the search");
|
|
188
|
+
if (late)
|
|
189
|
+
return late;
|
|
190
|
+
const answer = await answerOf(called, 2);
|
|
191
|
+
if (answer?.error)
|
|
192
|
+
return { error: exaSaid(typeof answer.error.message === "string" ? answer.error.message : "") };
|
|
193
|
+
const meta = answer?.result?._meta;
|
|
194
|
+
if (answer?.result?.isError === true && typeof meta === "object" && meta !== null && meta[RATE_LIMITED_META] === true)
|
|
195
|
+
return { error: RATE_LIMITED, limit: "rate_limited" };
|
|
196
|
+
const content = Array.isArray(answer?.result?.content) ? answer.result.content : undefined;
|
|
197
|
+
const said = content?.flatMap((part) => (part.type === "text" && typeof part.text === "string" ? [part.text] : [])).join("\n") ?? "";
|
|
198
|
+
if (!content || answer?.result?.isError === true)
|
|
199
|
+
return { error: exaSaid(said) };
|
|
200
|
+
const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
|
|
201
|
+
return { provider: "exa-keyless", query, results: hits.slice(0, n) };
|
|
202
|
+
}
|