@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/model.js
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
// Where a run's model comes from. An agentic revision names one as "provider/model-id", or names none and runs on this
|
|
2
|
+
// host's default (`AGENT_MODEL`). A workflow's model node names a tier, and the host maps it: fast to
|
|
3
|
+
// `AGENT_MODEL_FAST`, strong to `AGENT_MODEL_STRONG`, each falling back to the default. With `--faux` every model is the
|
|
4
|
+
// faux module's (no key, no network); with `AGENT_MODEL_BASE_URL` every model id goes to that one OpenAI Responses
|
|
5
|
+
// gateway; otherwise pi-ai's providers serve it, each with its keys from the server's secrets (PROVIDER_KEYS): the
|
|
6
|
+
// launcher hands the server every one, and a run's process those of its model's provider, never in an environment.
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { DEFAULT_HARNESS, FAUX_HARNESS_ENV } from "./harness.js";
|
|
9
|
+
import { authContextOf } from "./secrets.js";
|
|
10
|
+
/** The child's environment names the faux module by absolute path. */
|
|
11
|
+
export const FAUX_ENV = "AGENTRUN_SERVE_FAUX";
|
|
12
|
+
/** Every test hook's name starts so (AGENTRUN_SERVE_FAUX, AGENTRUN_SERVE_FAUX_HARNESS, AGENTRUN_SERVE_FAUX_WEB, ...). */
|
|
13
|
+
export const FAUX_PREFIX = "AGENTRUN_SERVE_FAUX";
|
|
14
|
+
/** `env` without a test hook's name: serve sets those from startServe's options alone, so a name the server's own
|
|
15
|
+
* environment holds (an operator's export, a leftover) never gives its runs fake answers or loads a module. */
|
|
16
|
+
export const withoutFaux = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith(FAUX_PREFIX)));
|
|
17
|
+
/** Under `--faux` only: a module whose default export is the fetch the Anthropic and OpenAI providers send through (the
|
|
18
|
+
* tests' fake upstream), in place of their APIs. With it they are registered beside the faux model, for a tool's own
|
|
19
|
+
* request to the provider the revision's model names (web_search's, hosted-search.ts); the run's turns stay faux. */
|
|
20
|
+
export const FAUX_UPSTREAM_ENV = "AGENTRUN_SERVE_FAUX_UPSTREAM";
|
|
21
|
+
/** A run's `effort`, passed to its child. */
|
|
22
|
+
export const EFFORT_ENV = "AGENTRUN_SERVE_EFFORT";
|
|
23
|
+
/** The model the server's keys give a run that names none (hostModel at the run's launch, from every key the server
|
|
24
|
+
* holds), passed to its child as its effort is: behind a gateway the run holds the gateway's key alone, never the key
|
|
25
|
+
* that names its default (runs.ts). A model id, never a secret, so its name has no secret's segment (pi-durable-disk's
|
|
26
|
+
* secret-name rule): a harness's log keeps it (adapters.ts harnessLog). */
|
|
27
|
+
export const DEFAULT_MODEL_ENV = "AGENTRUN_SERVE_DEFAULT_MODEL";
|
|
28
|
+
export const MODEL_PROVIDER = "agent-model";
|
|
29
|
+
export const EFFORTS = ["low", "medium", "high"];
|
|
30
|
+
/** The thinking levels a revision or the host may name. Never off. */
|
|
31
|
+
export const THINKING_LEVELS = ["low", "medium", "high", "xhigh", "max"];
|
|
32
|
+
export const TIERS = ["fast", "default", "strong"];
|
|
33
|
+
const TIER_ENV = { fast: "AGENT_MODEL_FAST", default: "AGENT_MODEL", strong: "AGENT_MODEL_STRONG" };
|
|
34
|
+
/** The workflow node kinds that run on a model. */
|
|
35
|
+
export const MODEL_NODES = ["agent", "decide", "extract", "report"];
|
|
36
|
+
/** The model providers whose key a person may save here (tool-keys.ts' `model` rows), in the order a default is taken
|
|
37
|
+
* from, each with the model a run gets on its key when neither its revision nor the host names one: the provider's
|
|
38
|
+
* capable everyday model, not its dearest (Claude Sonnet 5.5 and GPT-6.1 Sol, each $2 in and $10 out per million
|
|
39
|
+
* tokens). `harnesses`: those that run on the key, pi on any model of it and the harness that is the provider's own;
|
|
40
|
+
* OpenRouter's runs all three. `models`: a harness's own default on the key where it is not `model`. On OpenRouter:
|
|
41
|
+
* pi's is GPT-6 Sol on pi-ai's openrouter provider (/chat/completions, the key as a bearer token, as OpenRouter's docs
|
|
42
|
+
* name it; its Anthropic models go to /v1/messages with the key in x-api-key, which the docs do not), claude-agent's
|
|
43
|
+
* Claude Sonnet 5.5 and codex's GPT-6 Sol, each through OpenRouter's own endpoint for the harness (adapters.ts), the ids
|
|
44
|
+
* a live run took through OpenRouter on 2026-10-29. The row order is the order a default is taken in: a direct
|
|
45
|
+
* provider's key wins over OpenRouter's. */
|
|
46
|
+
export const MODEL_KEYS = [
|
|
47
|
+
{ id: "anthropic", label: "Anthropic", field: "ANTHROPIC_API_KEY", model: "anthropic/claude-sonnet-5-5", harnesses: [DEFAULT_HARNESS, "claude-agent"] },
|
|
48
|
+
{ id: "openai", label: "OpenAI", field: "OPENAI_API_KEY", model: "openai/gpt-6.1-sol", harnesses: [DEFAULT_HARNESS, "codex"] },
|
|
49
|
+
{ id: "openrouter", label: "OpenRouter", field: "OPENROUTER_API_KEY", model: "openrouter/openai/gpt-6-sol", harnesses: [DEFAULT_HARNESS, "claude-agent", "codex"], models: { "claude-agent": "anthropic/claude-sonnet-5.5", codex: "openai/gpt-6-sol" } },
|
|
50
|
+
];
|
|
51
|
+
/** `row`'s default for `harness`: its own (`models`), else the row's. */
|
|
52
|
+
const rowModel = (row, harness) => row.models?.[harness] ?? row.model;
|
|
53
|
+
/**
|
|
54
|
+
* Whether `harness` reaches its vendor's models here only through OpenRouter: OPENROUTER_API_KEY is set and none of the
|
|
55
|
+
* harness's own settings is. Those win, as on a host with no OpenRouter key: the endpoint the host names
|
|
56
|
+
* (ANTHROPIC_BASE_URL for claude-agent, which needs ANTHROPIC_API_KEY; serve's gateway AGENT_MODEL_BASE_URL for codex,
|
|
57
|
+
* with AGENT_MODEL_API_KEY or none), then the vendor's own key (ANTHROPIC_API_KEY, OPENAI_API_KEY), then OpenRouter. An
|
|
58
|
+
* endpoint the host names never gets the OpenRouter key.
|
|
59
|
+
*/
|
|
60
|
+
export function openRouterOnly(harness, env) {
|
|
61
|
+
if (!env.OPENROUTER_API_KEY)
|
|
62
|
+
return false;
|
|
63
|
+
return harness === "claude-agent" ? !env.ANTHROPIC_BASE_URL && !env.ANTHROPIC_API_KEY : !env.AGENT_MODEL_BASE_URL && !env.OPENAI_API_KEY;
|
|
64
|
+
}
|
|
65
|
+
/** Whether `harness`'s model requests for `model` (as named, `provider/model-id`; none, the host's for the harness) go
|
|
66
|
+
* through OpenRouter: a model named on it (`openrouter/<vendor>/...`), or the harness's vendor reached only through it
|
|
67
|
+
* (openRouterOnly). The route claudeProvider and codexProvider take (adapters.ts); a gateway (AGENT_MODEL_BASE_URL)
|
|
68
|
+
* comes first for codex. On it a harness's own search does not run: OpenRouter runs no OpenAI hosted web_search for
|
|
69
|
+
* Codex and no Anthropic server search for Claude, and its answers carry no count of searches to price. */
|
|
70
|
+
export function viaOpenRouter(env, harness, model) {
|
|
71
|
+
if (harness === "codex")
|
|
72
|
+
return !env.AGENT_MODEL_BASE_URL && (Boolean(model?.startsWith("openrouter/openai/")) || openRouterOnly("codex", env));
|
|
73
|
+
if (harness === "claude-agent")
|
|
74
|
+
return Boolean(model?.startsWith("openrouter/anthropic/")) || openRouterOnly("claude-agent", env);
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
/** What a person does when no model runs here: add a model provider's key in the console, or set one where AgentRun
|
|
78
|
+
* starts (MODEL_KEYS' fields), OpenRouter's named first, as its one key runs every harness. The order a default is
|
|
79
|
+
* taken in is MODEL_KEYS' own. */
|
|
80
|
+
export const ADD_A_KEY = `add a model key in Settings → Model keys, or set ${[...MODEL_KEYS].sort((a, b) => Number(b.id === "openrouter") - Number(a.id === "openrouter")).map((row) => row.field).join(", ").replace(/, ([^,]+)$/, " or $1")} where AgentRun starts.`;
|
|
81
|
+
/** Whether `id` names `vendor`'s model on OpenRouter (`openrouter/<vendor>/<model-id>`), as pi names it and claude-agent
|
|
82
|
+
* and codex take it (adapters.ts' claudeModel and codexProvider). */
|
|
83
|
+
const onOpenRouter = (id, vendor) => new RegExp(`^openrouter/${vendor}/[^/]+$`).test(id);
|
|
84
|
+
/** Whether `harness` runs the model `id`: pi any; claude-agent an Anthropic model (`anthropic/...`, or Anthropic's on
|
|
85
|
+
* OpenRouter, `openrouter/anthropic/...`), as it talks to an Anthropic Messages endpoint only; codex, behind a gateway
|
|
86
|
+
* (AGENT_MODEL_BASE_URL), any id, which is the gateway's own string and names no provider here (team/model included),
|
|
87
|
+
* as codex takes that gateway for its OpenAI-compatible endpoint; without one, an OpenAI model (`openai/...`, or OpenAI's
|
|
88
|
+
* on OpenRouter). On the faux harness every harness runs the run's model. */
|
|
89
|
+
export function harnessRuns(env, id, harness) {
|
|
90
|
+
if (harness === DEFAULT_HARNESS || env[FAUX_HARNESS_ENV])
|
|
91
|
+
return true;
|
|
92
|
+
const slash = id.indexOf("/");
|
|
93
|
+
const provider = slash > 0 ? id.slice(0, slash) : undefined;
|
|
94
|
+
if (harness === "claude-agent")
|
|
95
|
+
return provider === "anthropic" || onOpenRouter(id, "anthropic");
|
|
96
|
+
if (harness === "codex")
|
|
97
|
+
return Boolean(env.AGENT_MODEL_BASE_URL) || provider === "openai" || onOpenRouter(id, "openai");
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
/** The model a revision that names none runs on with `harness`, for `tier`: the tier's own variable, else AGENT_MODEL,
|
|
101
|
+
* each only when `harness` runs it (harnessRuns; one it can't is skipped, never an error), else that of the first of
|
|
102
|
+
* MODEL_KEYS whose key is here (a placeholder behind a base URL counts) and that `harness` runs on, else, in a run's
|
|
103
|
+
* process that holds none of those keys, the one the server's keys gave it (DEFAULT_MODEL_ENV). Undefined when none is:
|
|
104
|
+
* the harness has no default here. */
|
|
105
|
+
export function hostModel(env, tier = "default", harness = DEFAULT_HARNESS) {
|
|
106
|
+
for (const id of [env[TIER_ENV[tier]], env.AGENT_MODEL])
|
|
107
|
+
if (id && harnessRuns(env, id, harness))
|
|
108
|
+
return id;
|
|
109
|
+
const row = MODEL_KEYS.find((row) => env[row.field] && row.harnesses.includes(harness));
|
|
110
|
+
return row ? rowModel(row, harness) : env[DEFAULT_MODEL_ENV] || undefined;
|
|
111
|
+
}
|
|
112
|
+
/** A faux model id per tier: `faux-1`, or the id a tier's variable names. */
|
|
113
|
+
const fauxModel = (env, tier) => (tier === "default" ? undefined : env[TIER_ENV[tier]]) || "faux-1";
|
|
114
|
+
/** `route_prefix`: the routing prefix this server puts before a gateway's model ids (MODEL_PROVIDER), which a reader takes off
|
|
115
|
+
* to show the gateway's own id; null with any other source. */
|
|
116
|
+
/** The values `models.source` takes here: a faux module, a gateway, or each provider with its own key. */
|
|
117
|
+
export const MODEL_SOURCES = ["faux", "gateway", "providers"];
|
|
118
|
+
/** What capabilities say about models here: where they come from, and the model of each tier (`default` is also what a
|
|
119
|
+
* revision that names none runs on). */
|
|
120
|
+
export function modelSource(env) {
|
|
121
|
+
const each = (name) => Object.fromEntries(TIERS.map((tier) => [tier, name(tier)]));
|
|
122
|
+
if (env[FAUX_ENV])
|
|
123
|
+
return { source: "faux", route_prefix: null, ...each((tier) => `faux/${fauxModel(env, tier)}`) };
|
|
124
|
+
if (env.AGENT_MODEL_BASE_URL)
|
|
125
|
+
return { source: "gateway", route_prefix: MODEL_PROVIDER, ...each((tier) => (hostModel(env, tier) ? `${MODEL_PROVIDER}/${hostModel(env, tier)}` : null)) };
|
|
126
|
+
return { source: "providers", route_prefix: null, ...each((tier) => hostModel(env, tier) ?? null) };
|
|
127
|
+
}
|
|
128
|
+
/** A workflow's nodes as the DSL's inspection lists them, each read from the document at its path: only what the
|
|
129
|
+
* workflow's structure makes a node, never data shaped like one (a node's `state` may hold an example node). */
|
|
130
|
+
export function workflowNodes(workflow, inspection) {
|
|
131
|
+
const at = (path) => path.split("/").slice(1).reduce((value, part) => value[part.replace(/~1/g, "/").replace(/~0/g, "~")], workflow);
|
|
132
|
+
return inspection.nodes.map(({ path }) => at(path));
|
|
133
|
+
}
|
|
134
|
+
/** The tiers a workflow's model nodes name (`nodes` from workflowNodes); a node that names none is `default`. */
|
|
135
|
+
export function nodeTiers(nodes) {
|
|
136
|
+
const tiers = new Set();
|
|
137
|
+
for (const node of nodes) {
|
|
138
|
+
const model = MODEL_NODES.includes(node.node) || (node.node === "artifact" && ["markdown", "report"].includes(String(node.type)));
|
|
139
|
+
if (model)
|
|
140
|
+
tiers.add(TIERS.includes(node.tier) ? node.tier : "default");
|
|
141
|
+
}
|
|
142
|
+
return TIERS.filter((tier) => tiers.has(tier));
|
|
143
|
+
}
|
|
144
|
+
/** A `{dot.path}` the DSL fills in from the state when the node runs. */
|
|
145
|
+
const TEMPLATE = /\{[a-zA-Z0-9_.$]+\}/;
|
|
146
|
+
/** `tiers` with those a workflow's `llm` calls name (`args.tier`, else default) added: an `llm` call completes on the
|
|
147
|
+
* model of its tier, as a model node does. A tier the state fills in when the call runs (`"{requestedTier}"`, or args
|
|
148
|
+
* filled in whole) may be any of the three, so it adds all three. */
|
|
149
|
+
export function llmTiers(nodes, tiers) {
|
|
150
|
+
const all = new Set(tiers);
|
|
151
|
+
for (const node of nodes) {
|
|
152
|
+
if (node.node !== "call" || node.via !== "tool" || node.tool !== "llm")
|
|
153
|
+
continue;
|
|
154
|
+
const tier = typeof node.args === "string" ? node.args : node.args?.tier;
|
|
155
|
+
if (typeof tier === "string" && TEMPLATE.test(tier))
|
|
156
|
+
TIERS.forEach((each) => all.add(each));
|
|
157
|
+
else
|
|
158
|
+
all.add(TIERS.includes(tier) ? tier : "default");
|
|
159
|
+
}
|
|
160
|
+
return TIERS.filter((tier) => all.has(tier));
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* The model a revision runs on here, or why it cannot: `ref` is an agentic revision's "provider/model-id", absent for
|
|
164
|
+
* the host's model of `tier`. Through the gateway the ref goes whole, as a gateway such as OpenRouter names its models
|
|
165
|
+
* `vendor/model` (with `AGENT_MODEL_GATEWAY_IDS=bare`, only the part after the provider), and `namedProvider` is that
|
|
166
|
+
* provider, whose catalog entry prices the model. `host` says a setting of this host (a key, a default model) could
|
|
167
|
+
* make it reachable; a model the revision names that pi-ai does not know is not. `needs`: what would: a provider's key
|
|
168
|
+
* (none names a model, or the model's provider has no key here), or another model. `harness` picks the host's model
|
|
169
|
+
* when `ref` is absent (hostModel).
|
|
170
|
+
*/
|
|
171
|
+
export async function chooseModel(env, ref, tier = "default", harness = DEFAULT_HARNESS) {
|
|
172
|
+
if (env[FAUX_ENV])
|
|
173
|
+
return { model: { provider: "faux", modelId: fauxModel(env, tier) } };
|
|
174
|
+
const named = ref ?? hostModel(env, tier, harness);
|
|
175
|
+
// In a person's words (a first run from npx sees them): what to add and where. Operator detail is the README's.
|
|
176
|
+
const none = tier === "default" ? "No model yet" : `No model yet for this workflow's ${tier} tier`;
|
|
177
|
+
if (env.AGENT_MODEL_BASE_URL) {
|
|
178
|
+
if (!named)
|
|
179
|
+
return { why: `${none}: name the gateway's model in AGENT_MODEL where AgentRun starts, or add a model key in Settings → Model keys.`, host: true, needs: "key" };
|
|
180
|
+
// A revision's model, and a key's default (MODEL_KEYS: "provider/model"), go as the gateway takes its ids (bare: the
|
|
181
|
+
// part after the provider), that provider pricing them; the host's own AGENT_MODEL or tier id goes as configured.
|
|
182
|
+
const id = ref ?? ([env[TIER_ENV[tier]], env.AGENT_MODEL].includes(named) ? undefined : named);
|
|
183
|
+
const slash = id?.indexOf("/") ?? -1;
|
|
184
|
+
const sent = id && env.AGENT_MODEL_GATEWAY_IDS === "bare" ? id.slice(slash + 1) : named;
|
|
185
|
+
return { model: { provider: MODEL_PROVIDER, modelId: sent }, ...(id && slash > 0 ? { namedProvider: id.slice(0, slash) } : {}) };
|
|
186
|
+
}
|
|
187
|
+
if (!named)
|
|
188
|
+
return { why: `${none}: ${ADD_A_KEY}`, host: true, needs: "key" };
|
|
189
|
+
const slash = named.indexOf("/");
|
|
190
|
+
if (slash < 1)
|
|
191
|
+
return { why: `The host's default model ${named} is not a provider/model-id.`, host: true, needs: "model" };
|
|
192
|
+
const [provider, modelId] = [named.slice(0, slash), named.slice(slash + 1)];
|
|
193
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
194
|
+
const models = builtinModels({ authContext: authContextOf(env) });
|
|
195
|
+
const model = models.getModel(provider, modelId);
|
|
196
|
+
if (!model)
|
|
197
|
+
return { why: `pi-ai knows no model ${modelId} of ${provider}. Name one of its models, or route every model through a gateway with AGENT_MODEL_BASE_URL.`, host: ref === undefined, needs: "model" };
|
|
198
|
+
if (!(await models.getAuth(model))) {
|
|
199
|
+
const row = MODEL_KEYS.find((r) => r.id === provider);
|
|
200
|
+
const field = row?.field ?? models.getProvider(provider)?.auth.apiKey?.name ?? "its API key";
|
|
201
|
+
return { why: `No ${row?.label ?? provider} key here for ${named}: ${row ? `add one in Settings → Model keys, or set ${field}` : `set ${field}`} where AgentRun starts.`, host: true, needs: "key" };
|
|
202
|
+
}
|
|
203
|
+
return { model: { provider, modelId } };
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* The keys each of pi-ai's providers reads, by its id: pi-ai's own table (env-api-keys' findEnvKeys), and Amazon
|
|
207
|
+
* Bedrock's AWS keys, which that table leaves out as ambient. Every one is on the launcher's list (secrets.ts'
|
|
208
|
+
* SECRET_NAMES), so the server holds it and no environment does, and a run's process is handed a provider's keys over
|
|
209
|
+
* its pipe only when a model it runs is that provider's (runs.ts' secretsFor), as its model's provider reads them from
|
|
210
|
+
* the run's auth context. The custody test checks this against the pi-ai installed, so one that reads another key fails
|
|
211
|
+
* there.
|
|
212
|
+
*/
|
|
213
|
+
export const PROVIDER_KEYS = {
|
|
214
|
+
"amazon-bedrock": ["AWS_BEARER_TOKEN_BEDROCK", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"],
|
|
215
|
+
"ant-ling": ["ANT_LING_API_KEY"],
|
|
216
|
+
anthropic: ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
|
|
217
|
+
azure: ["AZURE_OPENAI_API_KEY"],
|
|
218
|
+
baseten: ["BASETEN_API_KEY"],
|
|
219
|
+
cerebras: ["CEREBRAS_API_KEY"],
|
|
220
|
+
"cloudflare-ai-gateway": ["CLOUDFLARE_API_KEY"],
|
|
221
|
+
"cloudflare-workers-ai": ["CLOUDFLARE_API_KEY"],
|
|
222
|
+
deepseek: ["DEEPSEEK_API_KEY"],
|
|
223
|
+
fireworks: ["FIREWORKS_API_KEY"],
|
|
224
|
+
"github-copilot": ["COPILOT_GITHUB_TOKEN"],
|
|
225
|
+
google: ["GEMINI_API_KEY"],
|
|
226
|
+
"google-vertex": ["GOOGLE_CLOUD_API_KEY"],
|
|
227
|
+
groq: ["GROQ_API_KEY"],
|
|
228
|
+
huggingface: ["HF_TOKEN"],
|
|
229
|
+
"kimi-coding": ["KIMI_API_KEY"],
|
|
230
|
+
meta: ["META_API_KEY"],
|
|
231
|
+
minimax: ["MINIMAX_API_KEY"],
|
|
232
|
+
"minimax-cn": ["MINIMAX_CN_API_KEY"],
|
|
233
|
+
mistral: ["MISTRAL_API_KEY"],
|
|
234
|
+
moonshotai: ["MOONSHOT_API_KEY"],
|
|
235
|
+
"moonshotai-cn": ["MOONSHOT_API_KEY"],
|
|
236
|
+
nvidia: ["NVIDIA_API_KEY"],
|
|
237
|
+
openai: ["OPENAI_API_KEY"],
|
|
238
|
+
opencode: ["OPENCODE_API_KEY"],
|
|
239
|
+
"opencode-go": ["OPENCODE_API_KEY"],
|
|
240
|
+
openrouter: ["OPENROUTER_API_KEY"],
|
|
241
|
+
"qwen-token-plan": ["QWEN_TOKEN_PLAN_API_KEY"],
|
|
242
|
+
"qwen-token-plan-cn": ["QWEN_TOKEN_PLAN_CN_API_KEY"],
|
|
243
|
+
"qwen-token-plan-individual": ["QWEN_TOKEN_PLAN_API_KEY"],
|
|
244
|
+
radius: ["RADIUS_API_KEY"],
|
|
245
|
+
together: ["TOGETHER_API_KEY"],
|
|
246
|
+
typesafe: ["TYPESAFE_API_KEY"],
|
|
247
|
+
"vercel-ai-gateway": ["AI_GATEWAY_API_KEY"],
|
|
248
|
+
xai: ["XAI_API_KEY"],
|
|
249
|
+
xiaomi: ["XIAOMI_API_KEY"],
|
|
250
|
+
"xiaomi-token-plan-ams": ["XIAOMI_TOKEN_PLAN_AMS_API_KEY"],
|
|
251
|
+
"xiaomi-token-plan-cn": ["XIAOMI_TOKEN_PLAN_CN_API_KEY"],
|
|
252
|
+
"xiaomi-token-plan-sgp": ["XIAOMI_TOKEN_PLAN_SGP_API_KEY"],
|
|
253
|
+
zai: ["ZAI_API_KEY"],
|
|
254
|
+
"zai-coding-cn": ["ZAI_CODING_CN_API_KEY"],
|
|
255
|
+
};
|
|
256
|
+
/** The keys pi-ai reads at a request, from the request's `env` option (else the process's environment), past the auth
|
|
257
|
+
* context: Bedrock's, whose request builds its AWS credentials itself. */
|
|
258
|
+
const REQUEST_KEYS = PROVIDER_KEYS["amazon-bedrock"];
|
|
259
|
+
/** The gateway's key (AGENT_MODEL_BASE_URL's), which its every model is reached on. */
|
|
260
|
+
export const GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
|
|
261
|
+
/** The model keys a pi run takes, by the models chooseModel picks for it: the keys of each one's provider (PROVIDER_KEYS),
|
|
262
|
+
* the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's the host's model
|
|
263
|
+
* of that tier; through a gateway (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as
|
|
264
|
+
* chooseModel is, faux or not, so a run on the faux model is handed what a run on its model would be. */
|
|
265
|
+
export function modelKeys(env, ref, tiers = ["default"]) {
|
|
266
|
+
if (env.AGENT_MODEL_BASE_URL)
|
|
267
|
+
return [GATEWAY_KEY_ENV];
|
|
268
|
+
const named = tiers.map((tier) => (tier === "default" ? ref : undefined) ?? hostModel(env, tier));
|
|
269
|
+
const providers = named.flatMap((name) => (name && name.indexOf("/") > 0 ? [name.slice(0, name.indexOf("/"))] : []));
|
|
270
|
+
return [...new Set(providers.flatMap((provider) => PROVIDER_KEYS[provider] ?? []))];
|
|
271
|
+
}
|
|
272
|
+
/** A run's thinking level: its `effort`, else its revision's `thinking`, else the host's `AGENT_THINKING`, else medium.
|
|
273
|
+
* Never off. */
|
|
274
|
+
export function thinkingOf(env, revision) {
|
|
275
|
+
const level = [env[EFFORT_ENV], revision, env.AGENT_THINKING].find((name) => THINKING_LEVELS.includes(name));
|
|
276
|
+
return (level ?? "medium");
|
|
277
|
+
}
|
|
278
|
+
/** The models for a run, and its model of each tier it uses and of no other: an agentic revision's `ref` (or the
|
|
279
|
+
* default) is its `default`, and a workflow's tiers are the ones its nodes name. The faux module's replies, the gateway
|
|
280
|
+
* in the environment, or pi-ai's providers. `unpriced`: the ids of its models serve has no price for (a gateway model the
|
|
281
|
+
* catalog does not list, with no price set), which a cap cannot be kept on. */
|
|
282
|
+
export async function runModels(env, ref, tiers = ["default"], harness = DEFAULT_HARNESS) {
|
|
283
|
+
const ai = await import("@earendil-works/pi-ai");
|
|
284
|
+
const { createModels, createProvider } = await import("@earendil-works/pi-ai/models");
|
|
285
|
+
const faux = env[FAUX_ENV];
|
|
286
|
+
const byTier = new Map();
|
|
287
|
+
const namedBy = new Map();
|
|
288
|
+
for (const tier of new Set(tiers)) {
|
|
289
|
+
const chosen = await chooseModel(env, tier === "default" ? ref : undefined, tier, harness);
|
|
290
|
+
if ("why" in chosen)
|
|
291
|
+
throw new Error(chosen.why);
|
|
292
|
+
byTier.set(tier, chosen.model);
|
|
293
|
+
if (chosen.namedProvider)
|
|
294
|
+
namedBy.set(tier, chosen.namedProvider);
|
|
295
|
+
}
|
|
296
|
+
const model = byTier.get("default");
|
|
297
|
+
if (!faux && !env.AGENT_MODEL_BASE_URL) {
|
|
298
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
299
|
+
// Each provider's key from `env`, which holds this process's secrets, never from process.env (secrets.ts).
|
|
300
|
+
return { models: withRequestKeys(builtinModels({ authContext: authContextOf(env) }), env), model, byTier, unpriced: new Set() };
|
|
301
|
+
}
|
|
302
|
+
const ids = [...new Set([...byTier.values()].map((m) => m.modelId))];
|
|
303
|
+
const models = createModels({ authContext: authContextOf(env) });
|
|
304
|
+
const unpriced = new Set();
|
|
305
|
+
if (!ids.length)
|
|
306
|
+
return { models, model, byTier, unpriced };
|
|
307
|
+
if (faux) {
|
|
308
|
+
const mod = (await import(pathToFileURL(faux).href));
|
|
309
|
+
const price = typeof mod.cost === "object" ? mod.cost : undefined;
|
|
310
|
+
if (typeof mod.default !== "function")
|
|
311
|
+
throw new Error(`the faux module ${faux} has no default export function`);
|
|
312
|
+
const reply = mod.default;
|
|
313
|
+
const helpers = { message: ai.fauxAssistantMessage, text: ai.fauxText, thinking: ai.fauxThinking, toolCall: ai.fauxToolCall };
|
|
314
|
+
// `contextWindow` sizes the faux model's window, so a test can make a run long enough to compact.
|
|
315
|
+
const core = ai.createFauxCore({ models: ids.map((id) => ({ id, ...(price ? { cost: price } : {}), ...(typeof mod.contextWindow === "number" ? { contextWindow: mod.contextWindow } : {}) })) });
|
|
316
|
+
const step = (async (context, options, _state, model) => reply(context, { ...helpers, ...(options?.signal ? { signal: options.signal } : {}), ...(model?.id ? { model: model.id } : {}) }));
|
|
317
|
+
core.setResponses(Array.from({ length: 10_000 }, () => step));
|
|
318
|
+
// `cost` (USD per million tokens) prices the faux model's usage, which the faux core leaves at $0, so a run's
|
|
319
|
+
// estimate and its cap can be tested; "unknown" leaves its usage with no cost, as a provider that does not price it.
|
|
320
|
+
const priced = (model, context, options) => {
|
|
321
|
+
const inner = core.stream(model, context, options);
|
|
322
|
+
if (!mod.cost)
|
|
323
|
+
return inner;
|
|
324
|
+
const outer = ai.createAssistantMessageEventStream();
|
|
325
|
+
void (async () => {
|
|
326
|
+
let last;
|
|
327
|
+
for await (const event of inner) {
|
|
328
|
+
const message = event.type === "done" ? event.message : event.type === "error" ? event.error : undefined;
|
|
329
|
+
if (message) {
|
|
330
|
+
if (price)
|
|
331
|
+
message.usage.cost = ai.calculateCost(model, message.usage);
|
|
332
|
+
else
|
|
333
|
+
delete message.usage.cost;
|
|
334
|
+
last = message;
|
|
335
|
+
}
|
|
336
|
+
outer.push(event);
|
|
337
|
+
}
|
|
338
|
+
outer.end(last ?? (await inner.result()));
|
|
339
|
+
})();
|
|
340
|
+
return outer;
|
|
341
|
+
};
|
|
342
|
+
models.setProvider(createProvider({
|
|
343
|
+
id: core.provider,
|
|
344
|
+
auth: { apiKey: { name: "Faux", resolve: async () => ({ auth: {} }) } },
|
|
345
|
+
models: core.models,
|
|
346
|
+
api: { stream: priced, streamSimple: priced, fetchDeferred: core.fetchDeferred, cancelDeferred: core.cancelDeferred },
|
|
347
|
+
}));
|
|
348
|
+
if (env[FAUX_UPSTREAM_ENV]) {
|
|
349
|
+
const send = (await import(pathToFileURL(env[FAUX_UPSTREAM_ENV]).href)).default;
|
|
350
|
+
const [{ anthropicProvider }, { openaiProvider }] = await Promise.all([import("@earendil-works/pi-ai/providers/anthropic"), import("@earendil-works/pi-ai/providers/openai")]);
|
|
351
|
+
for (const provider of [anthropicProvider(), openaiProvider()]) {
|
|
352
|
+
const via = (stream) => ((model, context, options) => stream(model, context, { ...options, fetch: send }));
|
|
353
|
+
models.setProvider(Object.assign(Object.create(provider), { stream: via(provider.stream.bind(provider)), streamSimple: via(provider.streamSimple.bind(provider)) }));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return { models, model, byTier, unpriced };
|
|
357
|
+
}
|
|
358
|
+
// One base rule for every harness (adapters.ts' gatewayBase): one trailing /v1 off, then the API under <base>/v1, so
|
|
359
|
+
// <gw>/api and <gw>/api/v1 both reach <gw>/api/v1/responses, as OpenRouter serves it.
|
|
360
|
+
const baseUrl = `${env.AGENT_MODEL_BASE_URL.replace(/\/+$/, "").replace(/\/v1$/, "")}/v1`;
|
|
361
|
+
const { openAIResponsesApi } = await import("@earendil-works/pi-ai/api/openai-responses.lazy");
|
|
362
|
+
// USD per million input, output, cache-read and cache-write tokens, so the run's usage has a price. A tier's own price
|
|
363
|
+
// (`AGENT_MODEL_FAST_PRICE`, `AGENT_MODEL_STRONG_PRICE`) goes with its model, else the default's; a model two tiers
|
|
364
|
+
// share takes the default's. With none set, pi-ai's catalog prices it (listedPrice), a $0 entry included; an id it does
|
|
365
|
+
// not list is unpriced: its answers carry no total (unpricedApi), so the run's cost reads unknown, never $0, and a cap
|
|
366
|
+
// refuses it.
|
|
367
|
+
const prices = new Map();
|
|
368
|
+
for (const tier of ["default", "fast", "strong"]) {
|
|
369
|
+
const id = byTier.get(tier)?.modelId;
|
|
370
|
+
if (id !== undefined && !prices.has(id))
|
|
371
|
+
prices.set(id, { given: (tier !== "default" && env[`${TIER_ENV[tier]}_PRICE`]) || env.AGENT_MODEL_PRICE || undefined, named: namedBy.get(tier) });
|
|
372
|
+
}
|
|
373
|
+
const catalog = [...prices.values()].some((price) => price.given === undefined) ? await catalogPrices() : new Map();
|
|
374
|
+
const listedOf = (id, named) => {
|
|
375
|
+
// A revision's ref names its provider: priced as that provider's entry for the model, whether it went whole or bare.
|
|
376
|
+
if (named !== undefined)
|
|
377
|
+
return listedPrice(catalog.get(id.startsWith(`${named}/`) ? id.slice(named.length + 1) : id) ?? [], named);
|
|
378
|
+
// A host model set whole (`vendor/model`) the catalog does not list as it is: priced as its model, the vendor named.
|
|
379
|
+
const slash = id.indexOf("/");
|
|
380
|
+
if (catalog.has(id) || slash < 1)
|
|
381
|
+
return listedPrice(catalog.get(id) ?? [], undefined);
|
|
382
|
+
return listedPrice(catalog.get(id.slice(slash + 1)) ?? [], id.slice(0, slash));
|
|
383
|
+
};
|
|
384
|
+
const priceOf = (id) => {
|
|
385
|
+
const { given, named } = prices.get(id);
|
|
386
|
+
if (given === undefined) {
|
|
387
|
+
const listed = listedOf(id, named);
|
|
388
|
+
if (listed)
|
|
389
|
+
return listed;
|
|
390
|
+
unpriced.add(id);
|
|
391
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
392
|
+
}
|
|
393
|
+
const [input = 0, output = 0, cacheRead = 0, cacheWrite = input] = given.split(",").map(Number);
|
|
394
|
+
return { input, output, cacheRead, cacheWrite };
|
|
395
|
+
};
|
|
396
|
+
// `models` is priced first, which fills `unpriced`, and `api` is chosen by it.
|
|
397
|
+
models.setProvider(createProvider({
|
|
398
|
+
id: MODEL_PROVIDER,
|
|
399
|
+
baseUrl,
|
|
400
|
+
auth: { apiKey: { name: GATEWAY_KEY_ENV, resolve: async () => ({ auth: { apiKey: env[GATEWAY_KEY_ENV] || "none" }, source: GATEWAY_KEY_ENV }) } },
|
|
401
|
+
models: ids.map((id) => ({
|
|
402
|
+
id, name: id, api: "openai-responses", provider: MODEL_PROVIDER, baseUrl, reasoning: true, input: ["text", "image"],
|
|
403
|
+
cost: priceOf(id), contextWindow: 128_000, maxTokens: 32_000, compat: { supportsDeveloperRole: false },
|
|
404
|
+
})),
|
|
405
|
+
api: unpriced.size ? unpricedApi(openAIResponsesApi(), unpriced, ai) : openAIResponsesApi(),
|
|
406
|
+
}));
|
|
407
|
+
return { models, model, byTier, unpriced };
|
|
408
|
+
}
|
|
409
|
+
/** The requests a Models object sends, each with its options third. */
|
|
410
|
+
const REQUESTS = new Set(["stream", "streamSimple", "complete", "completeSimple"]);
|
|
411
|
+
/** `models` with each request's `env` option carrying the REQUEST_KEYS that `env` holds (a run's process holds only
|
|
412
|
+
* those of its model's provider), so Bedrock's request finds its AWS keys there: in no environment, which would hand
|
|
413
|
+
* them to every program the run starts. A request's own `env` wins. With none held, `models` as it is. */
|
|
414
|
+
function withRequestKeys(models, env) {
|
|
415
|
+
const keys = Object.fromEntries(REQUEST_KEYS.flatMap((name) => (env[name] ? [[name, env[name]]] : [])));
|
|
416
|
+
if (!Object.keys(keys).length)
|
|
417
|
+
return models;
|
|
418
|
+
return new Proxy(models, {
|
|
419
|
+
get: (target, key) => {
|
|
420
|
+
const value = Reflect.get(target, key, target);
|
|
421
|
+
if (typeof value !== "function")
|
|
422
|
+
return value;
|
|
423
|
+
if (!REQUESTS.has(key))
|
|
424
|
+
return value.bind(target);
|
|
425
|
+
return (model, context, options) => value.call(target, model, context, { ...options, env: { ...keys, ...options?.env } });
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
/** `api`, with each answer of a model in `unpriced` written as an unpriced one: its usage's cost has no total, as
|
|
430
|
+
* harness-app writes a harness's, so the timeline, the run's cost and /v2 read it unknown rather than $0. Every pi request
|
|
431
|
+
* passes through it, a compaction's summary (`completeSimple`) included. */
|
|
432
|
+
function unpricedApi(api, unpriced, ai) {
|
|
433
|
+
const strip = (message) => void (message?.usage?.cost && delete message.usage.cost.total);
|
|
434
|
+
const unpricedOf = (stream) => ((model, context, options) => {
|
|
435
|
+
const inner = stream(model, context, options);
|
|
436
|
+
if (!unpriced.has(model.id))
|
|
437
|
+
return inner;
|
|
438
|
+
const outer = ai.createAssistantMessageEventStream();
|
|
439
|
+
void (async () => {
|
|
440
|
+
let last;
|
|
441
|
+
for await (const event of inner) {
|
|
442
|
+
const message = event.type === "done" ? event.message : event.type === "error" ? event.error : undefined;
|
|
443
|
+
if (message) {
|
|
444
|
+
strip(message);
|
|
445
|
+
last = message;
|
|
446
|
+
}
|
|
447
|
+
outer.push(event);
|
|
448
|
+
}
|
|
449
|
+
const result = last ?? (await inner.result());
|
|
450
|
+
strip(result);
|
|
451
|
+
outer.end(result);
|
|
452
|
+
})().catch((error) => {
|
|
453
|
+
const message = { role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }, errorMessage: `the model request failed: ${String(error?.message ?? error).slice(0, 200)}` };
|
|
454
|
+
outer.push({ type: "error", reason: "error", error: message });
|
|
455
|
+
outer.end(message);
|
|
456
|
+
});
|
|
457
|
+
return outer;
|
|
458
|
+
});
|
|
459
|
+
return { ...api, stream: unpricedOf(api.stream.bind(api)), streamSimple: unpricedOf(api.streamSimple.bind(api)) };
|
|
460
|
+
}
|
|
461
|
+
/** pi-ai's catalog list prices by model id: every provider's entry for it, in the catalog's order. */
|
|
462
|
+
export async function catalogPrices() {
|
|
463
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
464
|
+
const out = new Map();
|
|
465
|
+
for (const model of builtinModels().getModels()) {
|
|
466
|
+
const { input = 0, output = 0, cacheRead = 0, cacheWrite = 0, tiers } = model.cost ?? {};
|
|
467
|
+
const listed = out.get(model.id) ?? out.set(model.id, []).get(model.id);
|
|
468
|
+
listed.push({ provider: model.provider, cost: { input, output, cacheRead, cacheWrite, ...(tiers ? { tiers } : {}) } });
|
|
469
|
+
}
|
|
470
|
+
return out;
|
|
471
|
+
}
|
|
472
|
+
/** A gateway model's catalog price: the paid entry of the provider its ref names, when the catalog lists one. Else, as
|
|
473
|
+
* the gateway does not say whose model answers (a named provider is a hint), the highest any provider lists, so the
|
|
474
|
+
* estimate and a cap on it err high: one entry's whole price, the one with the most input plus output (the first of
|
|
475
|
+
* equals), so a $0 entry never wins over a paid one, a named provider's included. An id the catalog lists at $0 is a
|
|
476
|
+
* known $0; one it does not list has no price (undefined). */
|
|
477
|
+
function listedPrice(entries, named) {
|
|
478
|
+
if (!entries.length)
|
|
479
|
+
return undefined;
|
|
480
|
+
const own = named === undefined ? undefined : entries.find((entry) => entry.provider === named);
|
|
481
|
+
if (own && own.cost.input + own.cost.output > 0)
|
|
482
|
+
return own.cost;
|
|
483
|
+
return entries.reduce((top, { cost }) => (cost.input + cost.output > top.input + top.output ? cost : top), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
|
484
|
+
}
|
package/dist/monid.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type ToolRegistration } from "@earendil-works/pi-durable";
|
|
2
|
+
import type { ToolEntry } from "./tools.js";
|
|
3
|
+
import { type Json } from "./validate.js";
|
|
4
|
+
export declare const MONID_KEY_ENV = "MONID_API_KEY";
|
|
5
|
+
/** Under `faux` only (startServe's `fauxMonid`): a module whose default export is the fetch monid's calls go through, in
|
|
6
|
+
* place of monid's API (the tests' fake). */
|
|
7
|
+
export declare const FAUX_MONID_ENV = "AGENTRUN_SERVE_FAUX_MONID";
|
|
8
|
+
export declare const MONID_API = "https://api.monid.ai";
|
|
9
|
+
/** The most characters of one answer the model reads. */
|
|
10
|
+
export declare const CLIP = 60000;
|
|
11
|
+
/** monid's answer, or `error` saying why there is none, with the HTTP `status` when one came. */
|
|
12
|
+
export type MonidAnswer = Json & {
|
|
13
|
+
error?: string;
|
|
14
|
+
};
|
|
15
|
+
export type MonidOptions = {
|
|
16
|
+
key: string;
|
|
17
|
+
fetch?: typeof fetch;
|
|
18
|
+
/** Each request's own limit (30 s), but a run's first, which gets the whole wait: a sync provider answers in it. */
|
|
19
|
+
requestMs?: number;
|
|
20
|
+
/** Between two reads of an async run (2 s). */
|
|
21
|
+
pollMs?: number;
|
|
22
|
+
/** The most a run is waited for, its first request and every read together (150 s: monid's runs take 1 to 120 s). */
|
|
23
|
+
waitMs?: number;
|
|
24
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
25
|
+
};
|
|
26
|
+
/** What a run cost: `cost` on a run read back, else a sync answer's settled `billing.reportedCost`. */
|
|
27
|
+
export declare const costOf: (record: Json) => {
|
|
28
|
+
value: number;
|
|
29
|
+
currency: string;
|
|
30
|
+
} | undefined;
|
|
31
|
+
/** What a run's answer says monid charged, in USD: its cost; else undefined when monid charged nothing (UNCHARGED), and
|
|
32
|
+
* null for every other answer, which may have been charged (one with no cost, FAILED, TIMED_OUT, a run stopped by its
|
|
33
|
+
* caller or the wait, a run whose sending failed): never $0 for a charge no one knows, and counted by the cap at what
|
|
34
|
+
* the run was held at (paidCall). A cost in another currency is unknown too. */
|
|
35
|
+
export declare function chargeOf(answer: MonidAnswer): number | null | undefined;
|
|
36
|
+
/** monid's three calls on `key`, each answering what the model reads, never throwing. */
|
|
37
|
+
export declare function monidClient(options: MonidOptions): {
|
|
38
|
+
discover: (args: {
|
|
39
|
+
query: string;
|
|
40
|
+
limit?: number;
|
|
41
|
+
minScore?: number;
|
|
42
|
+
}, signal?: AbortSignal) => Promise<MonidAnswer>;
|
|
43
|
+
inspect: (args: {
|
|
44
|
+
provider: string;
|
|
45
|
+
endpoint: string;
|
|
46
|
+
}, signal?: AbortSignal) => Promise<MonidAnswer>;
|
|
47
|
+
run(args: {
|
|
48
|
+
provider: string;
|
|
49
|
+
endpoint: string;
|
|
50
|
+
input?: Json;
|
|
51
|
+
}, signal?: AbortSignal): Promise<MonidAnswer>;
|
|
52
|
+
};
|
|
53
|
+
/** `answer` as the model reads it: JSON, cut at CLIP characters, the whole then filed under `work`'s evidence/monid/
|
|
54
|
+
* (by run id, else by `label` and the time) and the cut saying where. A copy that cannot be filed (a full disk) still
|
|
55
|
+
* answers, cut and saying so: the answer may have been paid for. */
|
|
56
|
+
export declare function monidText(answer: MonidAnswer, work: string, label: string): Promise<string>;
|
|
57
|
+
declare const KINDS: readonly ["discover", "inspect", "run"];
|
|
58
|
+
type Kind = (typeof KINDS)[number];
|
|
59
|
+
/** What a run is held at when no inspect in this run's process quoted its price: an allowance, not a price, set high on
|
|
60
|
+
* purpose. A crash between sending a run and recording its charge leaves the cap counting it, so a cap errs toward
|
|
61
|
+
* refusing sooner, never toward passing unseen. */
|
|
62
|
+
export declare const MONID_RUN_ALLOWANCE_USD = 1;
|
|
63
|
+
/** monid's tool `kind` for a run, under its wire name: the key and the faux hook read from `env` (the run's process's,
|
|
64
|
+
* with its secrets) at each call, an answer too long for the model filed under `work()`, read at the call. A run goes
|
|
65
|
+
* through the run's cap (paidCall), is marked before it is sent (TOOL_STARTED, held at its quoted price or the
|
|
66
|
+
* allowance) and settled by its charge (TOOL_COST): a crash between the two leaves the cap counting the held figure
|
|
67
|
+
* and the run's cost unknown, never $0. pi binds it (monidTool); another harness runs it as a host tool
|
|
68
|
+
* (host-tools.ts), whose `api` commits to the run's store as pi's does. */
|
|
69
|
+
export declare function monidRegistration(kind: Kind, env: NodeJS.ProcessEnv, work: () => string): ToolRegistration;
|
|
70
|
+
/** The three, as another harness's host tools. */
|
|
71
|
+
export declare const monidTools: (env: NodeJS.ProcessEnv, work: () => string) => ToolRegistration[];
|
|
72
|
+
/** The table's entry for `monid.<kind>`: it needs MONID_API_KEY, and no workflow node names it yet. */
|
|
73
|
+
export declare const monidTool: (kind: Kind) => ToolEntry;
|
|
74
|
+
export {};
|