@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.30
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 +188 -0
- package/README.md +564 -97
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +11 -5
- package/dist/agents.js +16 -10
- package/dist/app.js +80 -20
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +1 -1
- package/dist/box-image.js +9 -7
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +21 -3
- package/dist/boxes.js +14 -7
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +129 -21
- package/dist/cap.js +338 -67
- package/dist/coding-tools.d.ts +7 -3
- package/dist/coding-tools.js +16 -10
- package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-rows.d.ts +11 -3
- package/dist/decision-rows.js +18 -11
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +6 -1
- package/dist/files.js +7 -2
- package/dist/grade.d.ts +7 -10
- package/dist/grade.js +31 -51
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +7 -5
- package/dist/graph-view.js +10 -3
- package/dist/harness-app.d.ts +4 -2
- package/dist/harness-app.js +101 -19
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +4 -1
- package/dist/harness.js +5 -2
- package/dist/host-tools.d.ts +12 -2
- package/dist/host-tools.js +26 -12
- package/dist/host.js +6 -2
- package/dist/hosted-search.js +5 -1
- package/dist/import.d.ts +2 -2
- package/dist/import.js +4 -3
- package/dist/key-check.d.ts +3 -2
- package/dist/key-check.js +7 -3
- package/dist/key-refusal.js +8 -4
- package/dist/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +3 -2
- package/dist/learn/grade.js +25 -13
- package/dist/learn/index.d.ts +2 -2
- package/dist/learn/index.js +2 -2
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +51 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +17 -4
- package/dist/learn/skills.js +79 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-run.d.ts +7 -5
- package/dist/learning-run.js +45 -23
- package/dist/learning-words.d.ts +6 -3
- package/dist/learning-words.js +8 -5
- package/dist/learning.d.ts +44 -3
- package/dist/learning.js +148 -3
- package/dist/mcp-servers.d.ts +7 -4
- package/dist/mcp-servers.js +5 -0
- package/dist/mcp.js +5 -5
- package/dist/model.d.ts +13 -11
- package/dist/model.js +11 -10
- package/dist/openapi/agentrun-v2.openapi.json +1 -0
- package/dist/openapi.js +358 -48
- package/dist/paid-calls.d.ts +5 -1
- package/dist/paid-calls.js +1 -1
- package/dist/pause.d.ts +2 -0
- package/dist/place.d.ts +27 -4
- package/dist/place.js +42 -10
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +38 -8
- package/dist/request-start.d.ts +12 -4
- package/dist/request-start.js +139 -15
- package/dist/run-box.d.ts +56 -4
- package/dist/run-box.js +173 -23
- package/dist/runnable.d.ts +5 -2
- package/dist/runnable.js +12 -4
- package/dist/runs.d.ts +258 -36
- package/dist/runs.js +830 -89
- package/dist/secrets.d.ts +12 -0
- package/dist/secrets.js +18 -0
- package/dist/server.d.ts +131 -35
- package/dist/server.js +467 -105
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +16 -4
- package/dist/skills.js +35 -7
- package/dist/stats.d.ts +7 -2
- package/dist/stats.js +28 -7
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +46 -10
- package/dist/tool-keys.js +44 -2
- package/dist/tool-plane.d.ts +112 -27
- package/dist/tool-plane.js +205 -47
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +143 -24
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +3 -2
- package/dist/turn-end.js +3 -2
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +11 -2
- package/dist/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +19 -13
- package/dist/console/assets/index-BN7oVcO4.js +0 -445
- package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/tools.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
1
3
|
import { pathToFileURL } from "node:url";
|
|
2
4
|
import { defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
5
|
+
import { BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES } from "./background.js";
|
|
3
6
|
import { writeInWork } from "./workspace.js";
|
|
4
7
|
import { FETCH_PAGE_TOOL, fetchOptions, HTML_READ_CHARS, TEXT_CAP } from "./fetch-page.js";
|
|
5
8
|
import { DEFAULT_HARNESS, HARNESSES } from "./harness.js";
|
|
@@ -9,14 +12,19 @@ import { DOCUMENTS_ENV, PDF_PAGES_TOOL, pdfPages } from "./pdf-pages.js";
|
|
|
9
12
|
import { monidTool } from "./monid.js";
|
|
10
13
|
import { FAUX_ENV, workflowNodes } from "./model.js";
|
|
11
14
|
import { bookedIn, booking } from "./paid-calls.js";
|
|
15
|
+
import { browserPrice, browserSpend } from "./browser-cost.js";
|
|
12
16
|
import { forModel } from "./result.js";
|
|
13
17
|
import { fetchFor, runPages, WEB_FETCH_TOOL, webFetchTool } from "./web-fetch.js";
|
|
14
18
|
import { searchFor, WEB_SEARCH_TOOL, webSearchTool } from "./web-search.js";
|
|
15
|
-
import { capabilityOf, explainsView, isUnavailable, NO_PARALLEL_KEY, PICKABLE, PROVIDERS, whyUnavailable, withDefaults } from "./tool-plane.js";
|
|
19
|
+
import { browserNeeds, capabilityOf, explainsView, isUnavailable, NO_PARALLEL_KEY, permissionsOf, PICKABLE, planeOf, PROVIDERS, whyUnavailable, withDefaults } from "./tool-plane.js";
|
|
20
|
+
import { defaultPermission, permissionOf } from "./tool-gate.js";
|
|
16
21
|
import { PARALLEL_KEY_ENV } from "./decisions.js";
|
|
22
|
+
import { handedSignIn } from "./secrets.js";
|
|
23
|
+
import { SIGN_IN_KEY, SIGN_IN_SAVED } from "./sign-ins.js";
|
|
17
24
|
export const ASK_TOOL = "ask_person";
|
|
18
|
-
/** Under `--faux` only: a module whose default export gives the browser's `{ provider, driver }
|
|
19
|
-
*
|
|
25
|
+
/** Under `--faux` only: a module whose default export gives the browser's `{ provider, driver }` for the run's
|
|
26
|
+
* environment, the vendor its plane names (`browserbase`, `kernel`) and the saved sign-in it was handed for that
|
|
27
|
+
* vendor (`{ provider, ref, save }`, or undefined), in place of that vendor's (the tests' fake backend). */
|
|
20
28
|
export const FAUX_BROWSER_ENV = "AGENTRUN_SERVE_FAUX_BROWSER";
|
|
21
29
|
/** What the result of `ask_person` says; the person's page shows the question as a waiting row. */
|
|
22
30
|
export const asked = (question) => `Asked the person: ${question.slice(0, 500)}. Waiting for their answer.`;
|
|
@@ -101,32 +109,113 @@ export const evidenceIn = (work) => {
|
|
|
101
109
|
},
|
|
102
110
|
};
|
|
103
111
|
};
|
|
104
|
-
/**
|
|
105
|
-
*
|
|
112
|
+
/** The Browserbase contexts a run's browser may open: its agent's saved sign-in's alone, by its profile name, never one
|
|
113
|
+
* made here (nothing a run makes is kept for its agent). */
|
|
114
|
+
export const keptContexts = (ref) => ({
|
|
115
|
+
clear: false,
|
|
116
|
+
resolve: async (key) => {
|
|
117
|
+
if (ref && key.endsWith(`|profile:${SIGN_IN_KEY}`))
|
|
118
|
+
return ref;
|
|
119
|
+
throw new Error("this run's browser has no saved sign-in to open");
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
/** Kernel's provider, opening the agent's saved profile (`ref`, its name at Kernel) where a session asks for the
|
|
123
|
+
* profile `default`: the policy, the session's record and the model see only that name. */
|
|
124
|
+
export const keptProfile = (provider, ref) => ({
|
|
125
|
+
...provider,
|
|
126
|
+
create: (spec, signal) => provider.create(spec.profile?.name === SIGN_IN_KEY ? { ...spec, profile: { ...spec.profile, name: ref } } : spec, signal),
|
|
127
|
+
});
|
|
128
|
+
/** `provider`, its sessions' profile as this launch was handed it, whatever the policy a conversation was made with (a
|
|
129
|
+
* follow-up's was made under an earlier launch, which may have had no sign-in, or another lease): with a sign-in, every
|
|
130
|
+
* session opens on the profile `default`, saving only as `kept.save` says; without one, none asks for a profile. */
|
|
131
|
+
export const asHanded = (provider, kept) => ({
|
|
132
|
+
...provider,
|
|
133
|
+
create: (spec, signal) => provider.create(kept ? { ...spec, profile: { name: SIGN_IN_KEY, save: kept.save } } : spec.profile ? { ...spec, profile: undefined } : spec, signal),
|
|
134
|
+
});
|
|
135
|
+
/** Whether a session's change is one that saved to the run's sign-in, in a run that saves (every session of it runs on
|
|
136
|
+
* the profile, asHanded, whatever its record names): let go by the run (its tool, its idle time, a relaunch, its close,
|
|
137
|
+
* its end), never one the vendor had already lost or never made. */
|
|
138
|
+
export const savedOnRelease = (row, change) => change === "released" && row.session.resourceId !== null && row.session.releaseReason !== null && !["lost", "create_failed"].includes(row.session.releaseReason);
|
|
139
|
+
/** A hosted browser driven through Stagehand, on pi-browser's durable adapter: Browserbase or Kernel (headless), the one
|
|
140
|
+
* the run's plane names (tool-plane.ts: picked, else Browserbase where the server holds its keys, else Kernel), kept
|
|
141
|
+
* for the run's life; a plane that names none (a run kept from before the pick) is Browserbase. Its sessions' custody
|
|
142
|
+
* lives in the run's own store. No recording and no live view; a session the run still holds is released when the run
|
|
143
|
+
* is let go. Where the plane says unavailable (its vendor's key gone since), each call is refused, saying why.
|
|
144
|
+
* Its session time is the run's spend, held under its cap before it runs (browser-cost.ts). A run handed its agent's
|
|
145
|
+
* saved sign-in for that vendor (sign-ins.ts, over its pipe) opens every session on it, as the profile `default`,
|
|
146
|
+
* saving only where it holds the agent's save lease; one that saved says so in its run directory. */
|
|
106
147
|
const browserTool = {
|
|
107
|
-
summary: "Drive a Browserbase
|
|
108
|
-
needs:
|
|
148
|
+
summary: "Drive a hosted browser, Browserbase's or Kernel's (picked in tool settings, else whichever's key the server holds): open pages, read and screenshot them, and act on them.",
|
|
149
|
+
// Which vendor's keys it needs is the plane's to say (tool-plane.ts BROWSER_KEYS): neither alone is required.
|
|
150
|
+
needs: [],
|
|
109
151
|
nodes: true,
|
|
110
152
|
// Its downloads and uploads go through work/ by path (pi-browser), which a box's command could turn through a link.
|
|
111
153
|
runnerOnly: true,
|
|
112
154
|
bind: async (host) => {
|
|
113
|
-
const [{ BACKGROUND_CONTEXT: context }, { createBrowserExtension }, { DEFAULT_BROWSER_POLICY }] = await Promise.all([
|
|
155
|
+
const [{ BACKGROUND_CONTEXT: context }, { createBrowserExtension }, { DEFAULT_BROWSER_POLICY, BrowserFailureError, browserFailure, workspaceFiles }] = await Promise.all([
|
|
114
156
|
import("@earendil-works/chord/context"),
|
|
115
157
|
import("@parcha/pi-browser/durable"),
|
|
116
158
|
import("@parcha/pi-browser"),
|
|
117
159
|
]);
|
|
160
|
+
const vendor = planeOf(host.env).browser ?? "browserbase";
|
|
161
|
+
const refused = isUnavailable(vendor) ? new BrowserFailureError(browserFailure("browser_unavailable", `The browser does not run here: ${whyUnavailable(vendor)}.`)) : undefined;
|
|
162
|
+
const handed = handedSignIn();
|
|
163
|
+
const kept = !refused && handed?.provider === vendor ? handed : undefined;
|
|
118
164
|
const faux = host.env[FAUX_ENV] ? host.env[FAUX_BROWSER_ENV] : undefined;
|
|
119
165
|
const parts = faux
|
|
120
|
-
? (await import(pathToFileURL(faux).href)).default(host.env)
|
|
121
|
-
: {
|
|
122
|
-
|
|
123
|
-
|
|
166
|
+
? (await import(pathToFileURL(faux).href)).default(host.env, vendor, kept)
|
|
167
|
+
: {
|
|
168
|
+
provider: refused
|
|
169
|
+
? undefined
|
|
170
|
+
: vendor === "kernel"
|
|
171
|
+
? ((kernel) => (kept ? keptProfile(kernel, kept.ref) : kernel))((await import("@parcha/pi-browser/providers/kernel")).kernelProvider({ env: host.env, headless: true }))
|
|
172
|
+
: (await import("@parcha/pi-browser/providers/browserbase")).browserbaseProvider({ env: host.env, profiles: keptContexts(kept?.ref) }),
|
|
173
|
+
driver: (await import("@parcha/pi-browser/driver/stagehand")).stagehandDriver(),
|
|
174
|
+
};
|
|
175
|
+
// The save flag every session carries is this launch's (asHanded), never the one stored with its conversation.
|
|
176
|
+
const handedProvider = parts.provider ? asHanded(parts.provider, kept) : undefined;
|
|
177
|
+
const provider = () => {
|
|
178
|
+
if (refused)
|
|
179
|
+
throw refused;
|
|
180
|
+
return handedProvider;
|
|
181
|
+
};
|
|
182
|
+
// Its session time is the run's spend, at its provider's price, and held under the run's cap (browser-cost.ts).
|
|
183
|
+
const providerName = parts.provider?.name ?? vendor;
|
|
184
|
+
const price = browserPrice(providerName, host.env);
|
|
185
|
+
const spend = browserSpend(providerName, price, DEFAULT_BROWSER_POLICY.idleReleaseS, (conversation, at) => browser.release(conversation, "close", at));
|
|
186
|
+
// browser_downloads is listed only with a workspace to copy into, and only a provider that keeps a session's downloads
|
|
187
|
+
// (Browserbase's; Kernel's keeps none) has any: without one, uploads still read the run's work/, through `files`.
|
|
188
|
+
const downloads = typeof parts.provider?.downloads === "object";
|
|
189
|
+
const files = downloads ? { workspace: () => host.where.work } : { files: workspaceFiles(host.where.work) };
|
|
190
|
+
// A session that saved to the sign-in, let go: its time, for the sign-in's verified_at when the run's lease ends.
|
|
191
|
+
const saved = kept?.save
|
|
192
|
+
? { onSession: (row, change) => void (savedOnRelease(row, change) && writeFileSync(join(host.where.root, SIGN_IN_SAVED), new Date().toISOString(), { mode: 0o600 })) }
|
|
193
|
+
: {};
|
|
194
|
+
// The pointer is cut from everything the browser hands the model (its results, their details, its failures): a
|
|
195
|
+
// vendor's refusal can quote it, as pi-browser's one-saver rule names Kernel's profile.
|
|
196
|
+
const browser = createBrowserExtension({ provider, driver: parts.driver, evidence: evidenceIn(host.where.work), ...files, ...saved, redact: { values: () => (kept ? [kept.ref] : []) }, prices: { sessionUsdPerHour: price.usdPerHour, sessionMinimumS: price.minimumS }, onCharge: spend.onCharge });
|
|
197
|
+
const tools = browser.tools.map(spend.capped);
|
|
198
|
+
const extension = { ...browser.extension, tools };
|
|
124
199
|
host.install(extension);
|
|
125
200
|
host.onConversation(async (tx, conversationId) => {
|
|
126
|
-
|
|
201
|
+
// The profile is the host's choice, never the model's: the agent's one sign-in, when the run was handed it.
|
|
202
|
+
const policy = kept ? { ...DEFAULT_BROWSER_POLICY, profile: { name: SIGN_IN_KEY, save: kept.save } } : DEFAULT_BROWSER_POLICY;
|
|
203
|
+
Object.assign(await tx.doc(browser.docs.Config, conversationId), { label: "run", run: host.where.ref.id, policy });
|
|
204
|
+
});
|
|
205
|
+
host.beforeResume(async (harness) => {
|
|
206
|
+
// Its charges move what the process counts once each is committed, reconcile's own among them.
|
|
207
|
+
spend.watch(harness, browser.docs.Inventory.definition.kind);
|
|
208
|
+
// With its vendor's key gone there is no session to reconcile or release from here: each would only fail.
|
|
209
|
+
if (refused)
|
|
210
|
+
return;
|
|
211
|
+
// Every session custody still tracks across a restart is held from here; one kept is released an idle window on
|
|
212
|
+
// unless a call uses it.
|
|
213
|
+
await browser.reconcile(harness, () => true, context);
|
|
214
|
+
await spend.reopened(harness, browser.docs, context);
|
|
127
215
|
});
|
|
128
|
-
host.beforeResume(async (harness) => void (await browser.reconcile(harness, () => true, context)));
|
|
129
216
|
host.beforeRelease(async (harness) => {
|
|
217
|
+
if (refused)
|
|
218
|
+
return;
|
|
130
219
|
const held = await harness.snapshot(browser.docs.Inventory, context);
|
|
131
220
|
for (const id of new Set(Object.values(held?.rows ?? {}).filter((row) => row.state !== "released").map((row) => row.conversationId))) {
|
|
132
221
|
const conversation = await harness.conversation(id, context);
|
|
@@ -135,7 +224,7 @@ const browserTool = {
|
|
|
135
224
|
}
|
|
136
225
|
await browser.drain(harness, context);
|
|
137
226
|
});
|
|
138
|
-
return { tools
|
|
227
|
+
return { tools, extensions: [extension] };
|
|
139
228
|
},
|
|
140
229
|
};
|
|
141
230
|
export const TOOLS = Object.freeze({
|
|
@@ -143,6 +232,12 @@ export const TOOLS = Object.freeze({
|
|
|
143
232
|
write: fileTool("write", "Write a file in the run's work/."),
|
|
144
233
|
edit: fileTool("edit", "Edit a file in the run's work/."),
|
|
145
234
|
bash: fileTool("bash", "Run a bash command in the run's box, from its work/, never on this server itself: only an agent whose place is a sandbox names it. Its output's tail; 300 s unless the call names a timeout.", true),
|
|
235
|
+
// The background tools (background.ts): each call a short command in the run's box, on bash's environment.
|
|
236
|
+
bash_background: fileTool("bash_background", `Start a command in the background in the run's box, from its work/, and get its id at once: its stdout and stderr go to work/background/<id>/output.log (the first ${BACKGROUND_LOG_BYTES / (1024 * 1024)} MiB), its stdin is a pipe, and the run's end ends it; at most ${BACKGROUND_MAX} run at once. Only an agent whose place is a sandbox names it.`, true),
|
|
237
|
+
bash_output: fileTool("bash_output", `Read a background process's output from a byte offset, at most ${BACKGROUND_PAGE_BYTES / 1024} KiB a call, with whether it still runs, its exit code and the next offset. Sandbox only.`, true),
|
|
238
|
+
bash_input: fileTool("bash_input", "Write text to a running background process's stdin, and close it if asked. Sandbox only.", true),
|
|
239
|
+
bash_signal: fileTool("bash_signal", "Send TERM, INT or KILL to a background process's process group. Sandbox only.", true),
|
|
240
|
+
bash_list: fileTool("bash_list", "List the run's background processes: id, state or exit code, output size and command. Sandbox only.", true),
|
|
146
241
|
[ASK_TOOL]: {
|
|
147
242
|
summary: "Ask the person who started the run; the turn ends until a message answers.",
|
|
148
243
|
needs: [],
|
|
@@ -176,10 +271,27 @@ export const CALL_TOOLS = Object.keys(TOOLS).filter((name) => TOOLS[name].effect
|
|
|
176
271
|
/** Whether `name` is one of `allowed`, or a legacy name for one (fetch_page, web_fetch's): a revision that names it
|
|
177
272
|
* still saves and runs, though the table lists it no more. */
|
|
178
273
|
export const allows = (allowed, name) => allowed.includes(capabilityOf(name));
|
|
179
|
-
/** The tools a run's learned workflow
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
|
|
274
|
+
/** The tools a run's learned workflow may name (learn/check.ts at learn time, learned-workflow.ts at a call): those of the
|
|
275
|
+
* agent's `granted` tools a workflow's call node runs here (CALL_TOOLS), each as granted and by its capability's name,
|
|
276
|
+
* and with the run's `plane`, none it resolves unavailable (its agent's own tool of the name does not run either). A
|
|
277
|
+
* learned model node runs without tools (learn/skills.ts MODEL_NODE_TOOLS), and a harness's own tool (Bash,
|
|
278
|
+
* exec_command, apply_patch) is never one, so the DSL refuses a draft that names it. */
|
|
279
|
+
export const learnedWorkflowTools = (granted, plane) => [...new Set(granted.filter((name) => allows(CALL_TOOLS, name) && !isUnavailable(plane?.[capabilityOf(name)])).flatMap((name) => [name, capabilityOf(name)]))];
|
|
280
|
+
/** The tools a learned draft may name (learnedWorkflowTools) that the gate allows: `permission` is what the gate holds a
|
|
281
|
+
* tool to now (tool-gate.ts permissionOf, or the run's gate's policy), by its capability's settings key, as the gate
|
|
282
|
+
* holds a legacy name. One set to ask or deny is left out of `tools`, so the end-of-run prompt never offers it, and named
|
|
283
|
+
* in `gated` with its setting, which the checker and a learned workflow's check before it runs refuse a draft for. */
|
|
284
|
+
export const learnedDraftTools = (granted, permission, plane) => {
|
|
285
|
+
const gated = {};
|
|
286
|
+
const tools = learnedWorkflowTools(granted, plane).filter((name) => {
|
|
287
|
+
const setting = permission(capabilityOf(name));
|
|
288
|
+
if (setting === "allow")
|
|
289
|
+
return true;
|
|
290
|
+
gated[name] = setting;
|
|
291
|
+
return false;
|
|
292
|
+
});
|
|
293
|
+
return { tools, gated };
|
|
294
|
+
};
|
|
183
295
|
/** The tools a workflow names (`nodes` from workflowNodes): on its model nodes (`tools`), and on its `call` nodes
|
|
184
296
|
* `via: "tool"` (`tool`). */
|
|
185
297
|
export function workflowTools(nodes) {
|
|
@@ -235,8 +347,11 @@ export function toolRefusal(names, env, where = "agent") {
|
|
|
235
347
|
* sets none), the default, and what it resolves to on each harness under the server's `settings`: available where any
|
|
236
348
|
* is not unavailable, and missing PARALLEL_API_KEY where Parallel is picked without it. An unavailable tool says why
|
|
237
349
|
* (`reason`). `noBox`: why no box can run a sandbox-only tool here (place.ts noBoxReason), which leaves it
|
|
238
|
-
* unavailable with that reason; undefined, a box can.
|
|
239
|
-
|
|
350
|
+
* unavailable with that reason; undefined, a box can. `refused`: the variables of the keys this server was started with
|
|
351
|
+
* that their provider refused at the start (ToolKeys.refused), each with why: a tool that needs one is unavailable,
|
|
352
|
+
* saying that. Each tool also gives its permission under the server's settings (tool-gate.ts), the owner's default
|
|
353
|
+
* and the permissions it may be set to. */
|
|
354
|
+
export const toolsView = (env, settings = {}, noBox, refused = {}) => {
|
|
240
355
|
const views = explainsView(env, settings);
|
|
241
356
|
const picked = withDefaults(settings);
|
|
242
357
|
return Object.entries(TOOLS).map(([name, entry]) => {
|
|
@@ -244,10 +359,14 @@ export const toolsView = (env, settings = {}, noBox) => {
|
|
|
244
359
|
const plane = view?.resolves;
|
|
245
360
|
const missing = plane && Object.values(plane).includes(NO_PARALLEL_KEY) ? [PARALLEL_KEY_ENV] : missingEnv(entry, env);
|
|
246
361
|
const boxless = entry.sandboxOnly ? noBox : undefined;
|
|
247
|
-
|
|
362
|
+
// The browser needs the keys of the vendor it resolves to: one refused at the start leaves it unavailable, never on the
|
|
363
|
+
// other vendor, as a refused Parallel key never moves web_search elsewhere.
|
|
364
|
+
const needs = name === "browser" ? [...new Set(Object.values(plane ?? {}).flatMap(browserNeeds))] : entry.needs;
|
|
365
|
+
const refusal = needs.map((name) => (Object.hasOwn(refused, name) ? refused[name] : undefined)).find((why) => why !== undefined);
|
|
366
|
+
const available = (plane ? Object.values(plane).some((resolution) => !isUnavailable(resolution)) : missing.length === 0) && boxless === undefined && refusal === undefined;
|
|
248
367
|
// Unavailable says why: a sandbox-only tool no box here can run, why none can (`noBox`); on a tool a user picks a
|
|
249
368
|
// provider for, the resolutions' own words (`web_search is turned off in settings`); else the variables it needs.
|
|
250
|
-
const reason = available ? undefined : boxless ?? (plane ? [...new Set(Object.values(plane).filter(isUnavailable).map(whyUnavailable))].join("; ") : `Needs ${missing.join(", ")}`);
|
|
251
|
-
return { name, summary: entry.summary, nodes: entry.nodes, calls: entry.effect !== undefined, ...(entry.callOnly ? { call_only: true } : {}), ...(entry.sandboxOnly ? { sandbox_only: true } : {}), available, ...(reason ? { reason } : {}), ...(missing.length ? { missing } : {}), harnesses: name in REPLAY ? [...HARNESSES] : [DEFAULT_HARNESS], ...(plane ? { providers: [...PROVIDERS[name]], provider: picked[name].provider, default_provider: PROVIDERS[name][0], resolves: plane, why: view.why } : {}) };
|
|
369
|
+
const reason = available ? undefined : refusal ?? boxless ?? (plane ? [...new Set(Object.values(plane).filter(isUnavailable).map(whyUnavailable))].join("; ") : `Needs ${missing.join(", ")}`);
|
|
370
|
+
return { name, summary: entry.summary, nodes: entry.nodes, calls: entry.effect !== undefined, ...(entry.callOnly ? { call_only: true } : {}), ...(entry.sandboxOnly ? { sandbox_only: true } : {}), available, ...(reason ? { reason } : {}), ...(missing.length ? { missing } : {}), harnesses: name in REPLAY ? [...HARNESSES] : [DEFAULT_HARNESS], permission: permissionOf(name, settings), default_permission: defaultPermission(name), permissions: [...permissionsOf(name)], ...(plane ? { providers: [...PROVIDERS[name]], provider: picked[name].provider, default_provider: PROVIDERS[name][0], resolves: plane, why: view.why } : {}) };
|
|
252
371
|
});
|
|
253
372
|
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export declare const TRIGGER_SECRETS_FILE = "trigger-secrets.json";
|
|
2
|
+
/** The trigger secrets data directory `data` keeps, opened with the seal key of `env` (those that open): what an import
|
|
3
|
+
* cuts out of everything it writes. */
|
|
4
|
+
export declare function triggerSecretsIn(data: string, env: NodeJS.ProcessEnv): string[];
|
|
5
|
+
export declare class TriggerSecrets {
|
|
6
|
+
private readonly file;
|
|
7
|
+
private readonly key;
|
|
8
|
+
/** Opened, by trigger id: read once at start, then kept with every write. */
|
|
9
|
+
private secrets;
|
|
10
|
+
private sealed;
|
|
11
|
+
/** Why the file does not read: no secret is made or rotated, none signs, and the file is never written over. */
|
|
12
|
+
private readonly unreadable?;
|
|
13
|
+
constructor(data: string, env: NodeJS.ProcessEnv, say?: (fields: Record<string, string>) => void);
|
|
14
|
+
get sealing(): "sealed" | "unavailable";
|
|
15
|
+
/** A new secret for `triggerId`, written sealed before it is answered: its only showing. */
|
|
16
|
+
mint(triggerId: string): string;
|
|
17
|
+
value(triggerId: string): string | undefined;
|
|
18
|
+
/** A deleted trigger's secret goes; with the file unreadable it stays in it, unread, as the file is never written over. */
|
|
19
|
+
remove(triggerId: string): void;
|
|
20
|
+
/** Every secret held, for the redaction of what is shown. */
|
|
21
|
+
values(): string[];
|
|
22
|
+
private write;
|
|
23
|
+
}
|
|
24
|
+
/** How far a request's `webhook-timestamp` may be from this server's clock, either way. */
|
|
25
|
+
export declare const HOOK_TOLERANCE_S = 300;
|
|
26
|
+
/** Why a request's webhook headers are refused before its body is read, or undefined when they may be checked:
|
|
27
|
+
* present, a webhook-id of printable ASCII, a bounded signature list, a timestamp within HOOK_TOLERANCE_S. */
|
|
28
|
+
export declare function hookHeadersRefusal(headers: Record<string, string | string[] | undefined>, nowMs: number): string | undefined;
|
|
29
|
+
/** Why a request to /v2/hooks/{id} is not signed by `secret` under the Standard Webhooks spec, or undefined when it is:
|
|
30
|
+
* `webhook-signature` lists `v1,<base64 HMAC-SHA256 of "{webhook-id}.{webhook-timestamp}.{body}">` signatures, space
|
|
31
|
+
* separated, under the secret's bytes, and any one that matches passes; the timestamp is within HOOK_TOLERANCE_S. */
|
|
32
|
+
export declare function hookRefusal(secret: string, headers: Record<string, string | string[] | undefined>, body: Buffer, nowMs: number): string | undefined;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Each webhook trigger's signing secret (triggers.ts): `whsec_` and 32 random bytes in base64, as the Standard Webhooks
|
|
2
|
+
// spec gives one, made at the trigger's create or a rotation, shown that once, and kept in DIR/trigger-secrets.json only
|
|
3
|
+
// sealed under the seal key (tool-keys.ts), each bound to its trigger by its AAD. With no seal key none is kept, never in
|
|
4
|
+
// the clear, so no webhook trigger is made.
|
|
5
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { seal, unseal } from "@parcha/pi-durable-agent";
|
|
9
|
+
import { ApiError } from "./errors.js";
|
|
10
|
+
import { writeDurableSync } from "./files.js";
|
|
11
|
+
import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
|
|
12
|
+
import { isObject } from "./validate.js";
|
|
13
|
+
export const TRIGGER_SECRETS_FILE = "trigger-secrets.json";
|
|
14
|
+
const aad = (triggerId) => `trigger-secret|${triggerId}`;
|
|
15
|
+
/** The sealed secrets `file` keeps, by trigger id: none when there is no file, and why not when it does not read. */
|
|
16
|
+
function sealedIn(file) {
|
|
17
|
+
let text;
|
|
18
|
+
try {
|
|
19
|
+
text = readFileSync(file, "utf8");
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
return error.code === "ENOENT" ? { sealed: {} } : { unreadable: error.message };
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const doc = JSON.parse(text);
|
|
26
|
+
if (!isObject(doc) || doc.v !== 1 || !isObject(doc.secrets) || !Object.values(doc.secrets).every((v) => typeof v === "string"))
|
|
27
|
+
return { unreadable: "not a trigger secrets file of version 1" };
|
|
28
|
+
return { sealed: doc.secrets };
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
return { unreadable: error.message };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const opened = (key, sealed) => Object.fromEntries(Object.entries(sealed).flatMap(([id, value]) => {
|
|
35
|
+
try {
|
|
36
|
+
return [[id, unseal(key, Buffer.from(value, "base64"), aad(id)).toString("utf8")]];
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
}));
|
|
42
|
+
/** The trigger secrets data directory `data` keeps, opened with the seal key of `env` (those that open): what an import
|
|
43
|
+
* cuts out of everything it writes. */
|
|
44
|
+
export function triggerSecretsIn(data, env) {
|
|
45
|
+
const key = sealKeyOf(env[SEAL_KEY_ENV]);
|
|
46
|
+
const read = sealedIn(join(data, TRIGGER_SECRETS_FILE));
|
|
47
|
+
return key && "sealed" in read ? Object.values(opened(key, read.sealed)) : [];
|
|
48
|
+
}
|
|
49
|
+
export class TriggerSecrets {
|
|
50
|
+
file;
|
|
51
|
+
key;
|
|
52
|
+
/** Opened, by trigger id: read once at start, then kept with every write. */
|
|
53
|
+
secrets;
|
|
54
|
+
sealed = {};
|
|
55
|
+
/** Why the file does not read: no secret is made or rotated, none signs, and the file is never written over. */
|
|
56
|
+
unreadable;
|
|
57
|
+
constructor(data, env, say = () => { }) {
|
|
58
|
+
this.file = join(data, TRIGGER_SECRETS_FILE);
|
|
59
|
+
this.key = sealKeyOf(env[SEAL_KEY_ENV]);
|
|
60
|
+
const read = sealedIn(this.file);
|
|
61
|
+
if ("sealed" in read)
|
|
62
|
+
this.sealed = read.sealed;
|
|
63
|
+
else {
|
|
64
|
+
this.unreadable = read.unreadable;
|
|
65
|
+
say({ condition: "trigger_secrets_unreadable", file: this.file, error: read.unreadable });
|
|
66
|
+
}
|
|
67
|
+
this.secrets = this.key ? opened(this.key, this.sealed) : {};
|
|
68
|
+
}
|
|
69
|
+
get sealing() {
|
|
70
|
+
return this.key ? "sealed" : "unavailable";
|
|
71
|
+
}
|
|
72
|
+
/** A new secret for `triggerId`, written sealed before it is answered: its only showing. */
|
|
73
|
+
mint(triggerId) {
|
|
74
|
+
if (this.unreadable)
|
|
75
|
+
throw new ApiError("store_unreadable", `${TRIGGER_SECRETS_FILE} in the data directory does not read (${this.unreadable}); it is never written over, so no webhook trigger's secret is made or rotated. Fix it or move it away, then restart.`);
|
|
76
|
+
if (!this.key)
|
|
77
|
+
throw new ApiError("no_sealing_key", `This server was handed no seal key (${SEAL_KEY_ENV}), so it keeps no webhook trigger's secret: it never keeps one in the clear.`);
|
|
78
|
+
const secret = `whsec_${randomBytes(32).toString("base64")}`;
|
|
79
|
+
this.write({ ...this.sealed, [triggerId]: seal(this.key, Buffer.from(secret, "utf8"), aad(triggerId)).toString("base64") });
|
|
80
|
+
this.secrets[triggerId] = secret;
|
|
81
|
+
return secret;
|
|
82
|
+
}
|
|
83
|
+
value(triggerId) {
|
|
84
|
+
return this.secrets[triggerId];
|
|
85
|
+
}
|
|
86
|
+
/** A deleted trigger's secret goes; with the file unreadable it stays in it, unread, as the file is never written over. */
|
|
87
|
+
remove(triggerId) {
|
|
88
|
+
if (this.unreadable || !(triggerId in this.sealed))
|
|
89
|
+
return;
|
|
90
|
+
const { [triggerId]: _, ...rest } = this.sealed;
|
|
91
|
+
this.write(rest);
|
|
92
|
+
delete this.secrets[triggerId];
|
|
93
|
+
}
|
|
94
|
+
/** Every secret held, for the redaction of what is shown. */
|
|
95
|
+
values() {
|
|
96
|
+
return Object.values(this.secrets);
|
|
97
|
+
}
|
|
98
|
+
write(sealed) {
|
|
99
|
+
writeDurableSync(this.file, `${JSON.stringify({ v: 1, secrets: sealed }, null, 2)}\n`);
|
|
100
|
+
this.sealed = sealed;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** How far a request's `webhook-timestamp` may be from this server's clock, either way. */
|
|
104
|
+
export const HOOK_TOLERANCE_S = 300;
|
|
105
|
+
/** A webhook-id: printable ASCII with no space, as the spec's `msg_...` ids are; it goes into a firing's key and history. */
|
|
106
|
+
const HOOK_ID = /^[\x21-\x7e]{1,255}$/;
|
|
107
|
+
/** The longest `webhook-signature` list read: room for many keys during a rotation, never an unbounded loop. */
|
|
108
|
+
const MAX_SIGNATURES_CHARS = 2048;
|
|
109
|
+
/** The fewest bytes a signing key may have (the spec's secrets are 24 to 64; this server makes 32): a shorter one,
|
|
110
|
+
* an empty one above all, signs nothing. */
|
|
111
|
+
const MIN_KEY_BYTES = 24;
|
|
112
|
+
/** Why a request's webhook headers are refused before its body is read, or undefined when they may be checked:
|
|
113
|
+
* present, a webhook-id of printable ASCII, a bounded signature list, a timestamp within HOOK_TOLERANCE_S. */
|
|
114
|
+
export function hookHeadersRefusal(headers, nowMs) {
|
|
115
|
+
const [id, timestamp, signatures] = ["webhook-id", "webhook-timestamp", "webhook-signature"].map((name) => headers[name]);
|
|
116
|
+
if (typeof id !== "string" || typeof timestamp !== "string" || typeof signatures !== "string")
|
|
117
|
+
return "missing_headers";
|
|
118
|
+
if (!HOOK_ID.test(id) || signatures.length > MAX_SIGNATURES_CHARS)
|
|
119
|
+
return "malformed_headers";
|
|
120
|
+
if (!/^\d{1,12}$/.test(timestamp) || Math.abs(nowMs / 1000 - Number(timestamp)) > HOOK_TOLERANCE_S)
|
|
121
|
+
return "stale_timestamp";
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
/** Why a request to /v2/hooks/{id} is not signed by `secret` under the Standard Webhooks spec, or undefined when it is:
|
|
125
|
+
* `webhook-signature` lists `v1,<base64 HMAC-SHA256 of "{webhook-id}.{webhook-timestamp}.{body}">` signatures, space
|
|
126
|
+
* separated, under the secret's bytes, and any one that matches passes; the timestamp is within HOOK_TOLERANCE_S. */
|
|
127
|
+
export function hookRefusal(secret, headers, body, nowMs) {
|
|
128
|
+
const early = hookHeadersRefusal(headers, nowMs);
|
|
129
|
+
if (early)
|
|
130
|
+
return early;
|
|
131
|
+
const [id, timestamp, signatures] = ["webhook-id", "webhook-timestamp", "webhook-signature"].map((name) => headers[name]);
|
|
132
|
+
const key = Buffer.from(secret.slice("whsec_".length), "base64");
|
|
133
|
+
const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
|
|
134
|
+
// Compared all the same, so a short key costs what a good one does; it fails after.
|
|
135
|
+
const matched = signatures.split(" ").some((part) => {
|
|
136
|
+
const [version, signature] = part.split(",");
|
|
137
|
+
const given = Buffer.from(signature ?? "", "base64");
|
|
138
|
+
return version === "v1" && given.length === expected.length && timingSafeEqual(given, expected);
|
|
139
|
+
});
|
|
140
|
+
if (key.length < MIN_KEY_BYTES)
|
|
141
|
+
return "short_key";
|
|
142
|
+
return matched ? undefined : "bad_signature";
|
|
143
|
+
}
|