@parcha/agentrun-serve 0.1.0-beta.40 → 0.1.0-beta.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +77 -0
- package/README.md +78 -15
- package/dist/api-only.d.ts +3 -1
- package/dist/api-only.js +4 -2
- package/dist/api-token.d.ts +30 -0
- package/dist/api-token.js +89 -0
- package/dist/cli.js +19 -5
- package/dist/composio-made.d.ts +54 -0
- package/dist/composio-made.js +83 -0
- package/dist/composio-preset.d.ts +16 -8
- package/dist/composio-preset.js +106 -43
- package/dist/composio-triggers.d.ts +7 -2
- package/dist/composio-triggers.js +13 -7
- package/dist/computer-attach.d.ts +29 -11
- package/dist/computer-attach.js +141 -47
- package/dist/computer-keys.d.ts +4 -0
- package/dist/computer-keys.js +5 -0
- package/dist/computers.d.ts +11 -1
- package/dist/computers.js +21 -12
- package/dist/console/assets/{index-B8Zn1Iqn.css → index-C3gNPz58.css} +1 -1
- package/dist/console/assets/index-COGhx_2Z.js +711 -0
- package/dist/console/index.html +2 -2
- package/dist/decisions.js +9 -2
- package/dist/eval-feed.d.ts +26 -0
- package/dist/eval-feed.js +68 -0
- package/dist/eval-mailbox.d.ts +4 -1
- package/dist/eval-mailbox.js +11 -3
- package/dist/exa-keyless.d.ts +1 -1
- package/dist/exa-keyless.js +1 -1
- package/dist/feed/feed-faux.d.ts +62 -0
- package/dist/feed/feed-faux.js +123 -0
- package/dist/feed/fetch.d.ts +41 -0
- package/dist/feed/fetch.js +128 -0
- package/dist/feed/parse.d.ts +41 -0
- package/dist/feed/parse.js +300 -0
- package/dist/learn/check.d.ts +3 -1
- package/dist/learn/check.js +57 -2
- package/dist/learn/compile.js +1 -1
- package/dist/learned-nodes.d.ts +21 -4
- package/dist/learned-nodes.js +21 -8
- package/dist/learned-workflow.d.ts +3 -3
- package/dist/learned-workflow.js +14 -5
- package/dist/mcp-oauth.d.ts +15 -1
- package/dist/mcp-oauth.js +39 -5
- package/dist/mcp-pin-first.d.ts +4 -2
- package/dist/mcp-pin-first.js +4 -3
- package/dist/mcp-servers-store.d.ts +58 -5
- package/dist/mcp-servers-store.js +136 -17
- package/dist/mcp.d.ts +2 -2
- package/dist/mcp.js +2 -2
- package/dist/observation/http.d.ts +4 -1
- package/dist/observation/http.js +5 -4
- package/dist/openapi.js +46 -12
- package/dist/print.d.ts +6 -3
- package/dist/print.js +4 -2
- package/dist/run-labels.d.ts +23 -0
- package/dist/run-labels.js +79 -0
- package/dist/run-secrets.js +12 -4
- package/dist/runner/adapter-loop.js +91 -10
- package/dist/runner/adapter-run-spec.d.ts +4 -0
- package/dist/runner/adapter-run-spec.js +38 -31
- package/dist/runner/beside.d.ts +6 -3
- package/dist/runner/beside.js +9 -7
- package/dist/runner/cli-run-spec.js +32 -26
- package/dist/runner/conformance/harness.js +69 -14
- package/dist/runner/conformance/subject.d.ts +4 -1
- package/dist/runner/main.d.ts +1 -1
- package/dist/runner/main.js +2 -2
- package/dist/runner/mcp-claim.d.ts +3 -0
- package/dist/runner/mcp-claim.js +1 -1
- package/dist/runner/mcp-run.d.ts +4 -0
- package/dist/runner/mcp-run.js +5 -3
- package/dist/runner/model-route.d.ts +4 -2
- package/dist/runner/model-route.js +8 -8
- package/dist/runner/promotion.d.ts +8 -0
- package/dist/runner/promotion.js +43 -1
- package/dist/runner/workflow-first.d.ts +6 -5
- package/dist/runner/workflow-first.js +9 -7
- package/dist/runs-over-store.js +5 -2
- package/dist/sdk/runs.d.ts +7 -1
- package/dist/sdk/runs.js +19 -6
- package/dist/secret-cut.js +3 -1
- package/dist/secrets.js +3 -1
- package/dist/server.d.ts +27 -2
- package/dist/server.js +168 -50
- package/dist/store/dialect.d.ts +3 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/postgres/dialect.js +1 -0
- package/dist/store/postgres/migrations/0015_run_labels.sql +5 -0
- package/dist/store/postgres/migrations/0016_minted_tokens.sql +21 -0
- package/dist/store/schema.d.ts +9 -0
- package/dist/store/schema.js +26 -2
- package/dist/store/sqlite/connection.js +11 -3
- package/dist/store/sqlite/run-patch.d.ts +2 -1
- package/dist/store/sqlite/run-patch.js +3 -2
- package/dist/store/sqlite/store.js +64 -10
- package/dist/store/store.d.ts +38 -1
- package/dist/store-reads/journal.js +2 -1
- package/dist/store-reads/learning.js +6 -1
- package/dist/store-reads/runs.d.ts +4 -3
- package/dist/store-reads/runs.js +3 -2
- package/dist/store-view.js +4 -2
- package/dist/template-eval.d.ts +4 -0
- package/dist/template-eval.js +127 -50
- package/dist/templates.d.ts +10 -0
- package/dist/templates.js +75 -17
- package/dist/timeline/origin.d.ts +1 -1
- package/dist/timeline/origin.js +2 -2
- package/dist/trigger-adapter.d.ts +9 -4
- package/dist/trigger-adapters.js +2 -1
- package/dist/trigger-feed.d.ts +12 -0
- package/dist/trigger-feed.js +371 -0
- package/dist/triggers.d.ts +2 -1
- package/dist/triggers.js +23 -5
- package/dist/webhooks.js +9 -5
- package/dist/workspace/computer-deps.d.ts +5 -1
- package/dist/workspace/computer-deps.js +2 -2
- package/dist/workspace/index.d.ts +1 -0
- package/dist/workspace/index.js +2 -0
- package/dist/workspace/resolve-computer.d.ts +32 -3
- package/dist/workspace/resolve-computer.js +47 -9
- package/launcher/agentrun-serve +6 -1
- package/package.json +10 -9
- package/templates/README.md +27 -2
- package/dist/console/assets/index-Jbxjcmdp.js +0 -705
package/dist/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { maintainObservations, Observations } from './observation/observer.js';
|
|
2
2
|
import { isObservationRoute, observationHttp } from './observation/http.js';
|
|
3
|
-
import { SdkRuns, sdkOf } from "./sdk/runs.js";
|
|
3
|
+
import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
|
|
4
4
|
import { gradeRouteFor } from "./runner/harness-loops.js";
|
|
5
5
|
import { routeOf as sdkModelRoute } from "./runner/model-route.js";
|
|
6
6
|
import { answerSkill } from './skill-route.js';
|
|
@@ -12,7 +12,7 @@ import { isNativeRuntime } from "./native/runtimes.js";
|
|
|
12
12
|
import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
|
|
13
13
|
// The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
|
|
14
14
|
// token.
|
|
15
|
-
import { createHash, randomBytes
|
|
15
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
16
16
|
import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
|
|
17
17
|
import { createServer } from "node:http";
|
|
18
18
|
import proxyaddr from "proxy-addr";
|
|
@@ -53,7 +53,8 @@ import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPl
|
|
|
53
53
|
import { boxAllowOf, boxAllowSetIn } from "./box-settings.js";
|
|
54
54
|
import { dockerLimitsOf } from "./workspace/computer-deps.js";
|
|
55
55
|
import { Owner, passwordProblem, SESSION_MS } from "./owner.js";
|
|
56
|
-
import {
|
|
56
|
+
import { acceptedTokens, bearerCheck, tokenProblem } from "./api-token.js";
|
|
57
|
+
import { answerPage, byConsoleSession, byOwnerSession, ConsoleSessions, heldSessions, isJson, overHttps, ownerCookie, ownOrigin, sendHostRefused, signedIn } from "./page.js";
|
|
57
58
|
import { hostFix, hostName, loopbackNames } from "./host-check.js";
|
|
58
59
|
import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
|
|
59
60
|
import { browserHandBack, handBackTarget } from "./browser-commands.js";
|
|
@@ -72,6 +73,7 @@ import { runCutValues } from "./run-cut.js";
|
|
|
72
73
|
import { readLaunchBody } from "./run-launch.js";
|
|
73
74
|
import { listRunFiles as listRunFilesOverStore, readRunFile as readRunFileOverStore, runGraphView, runTimelines } from "./run-reads-over-store.js";
|
|
74
75
|
import { triggerTargets } from "./trigger-targets.js";
|
|
76
|
+
import { labelFilter, labelsIssues } from "./run-labels.js";
|
|
75
77
|
import { listRuns as listRunsOverStore, readRun as readRunOverStore, runOfOrigin as runOfOriginOverStore } from "./store-reads/runs.js";
|
|
76
78
|
import { runEntries } from "./store-reads/journal.js";
|
|
77
79
|
import { metersOverStore } from "./store-reads/cap.js";
|
|
@@ -138,7 +140,7 @@ import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
|
|
|
138
140
|
import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
|
|
139
141
|
import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
|
|
140
142
|
import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
|
|
141
|
-
import { applyBodyOf, choiceUnrunnable, COMPOSIO_TRIGGER_FIX, composioTriggerSkipped, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, notSetUpYet, serversFor, TemplateRegistry } from "./templates.js";
|
|
143
|
+
import { applyBodyOf, choiceUnrunnable, COMPOSIO_TRIGGER_FIX, composioTriggerSkipped, COMPUTER_FIX, compiled, feedLeftEmpty, feedTriggerEmpty, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, notSetUpYet, serversFor, TemplateRegistry } from "./templates.js";
|
|
142
144
|
import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
|
|
143
145
|
import { templateInstallLink, templateLink } from "./console-links.js";
|
|
144
146
|
import { GITHUB_HOSTS } from "./template-source.js";
|
|
@@ -164,7 +166,7 @@ import { computerOfPlace } from "./computer-setting.js";
|
|
|
164
166
|
import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
|
|
165
167
|
import { fauxComputers } from "./faux-computers.js";
|
|
166
168
|
import { writesHeld } from "./workspace.js";
|
|
167
|
-
import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
|
|
169
|
+
import { agentComputerOf, agentComputerView, agentHomeFolder, claimKinds, computerProviderFactories, computerProviderMakers, computerReadiness, dockerHostAddressesOf, isWorkspaceError, localWorkspace, reconcileAgentComputer, registryHere, runShellOf, serverRunWorkspace, storeLedger } from "./workspace/index.js";
|
|
168
170
|
import { keyReader } from "./key-meta.js";
|
|
169
171
|
export const CONTRACT = "agentrun.v2/0";
|
|
170
172
|
/** A process's flags for a worker of it: without --input-type and the code string given with -e, --eval, -p or --print. */
|
|
@@ -221,7 +223,6 @@ async function tokenIn(file) {
|
|
|
221
223
|
await writeDurable(file, `${token}\n`, 0o600, undefined, true);
|
|
222
224
|
return { token, made: true };
|
|
223
225
|
}
|
|
224
|
-
const digest = (text) => createHash("sha256").update(text).digest();
|
|
225
226
|
const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
|
|
226
227
|
const SESSION_S = SESSION_MS / 1000;
|
|
227
228
|
export const ROUTES = [
|
|
@@ -309,6 +310,8 @@ export const ROUTES = [
|
|
|
309
310
|
{ method: "POST", pattern: /^\/computers\/pairings$/, name: "createPairing" },
|
|
310
311
|
{ method: "POST", pattern: /^\/computers\/pair$/, name: "pairComputer" },
|
|
311
312
|
{ method: "GET", pattern: /^\/computers\/attach$/, name: "attachComputer" },
|
|
313
|
+
// A hosted machine's computerd build, fetched at its boot with the token its create minted (computer-attach.ts daemon).
|
|
314
|
+
{ method: "GET", pattern: /^\/computers\/daemon$/, name: "getComputerDaemon" },
|
|
312
315
|
{ method: "DELETE", pattern: /^\/computers\/([^/]+)$/, name: "deleteComputer" },
|
|
313
316
|
{ method: "GET", pattern: /^\/workspace\/archil$/, name: "getWorkspaceArchil" },
|
|
314
317
|
{ method: "PUT", pattern: /^\/workspace\/archil$/, name: "putWorkspaceArchil" },
|
|
@@ -672,8 +675,17 @@ export async function startServe(options) {
|
|
|
672
675
|
await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
|
|
673
676
|
// Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
|
|
674
677
|
const data = await realpath(resolve(options.data));
|
|
675
|
-
|
|
676
|
-
|
|
678
|
+
const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
|
|
679
|
+
if (tokenRefused)
|
|
680
|
+
throw new Error(tokenRefused);
|
|
681
|
+
for (const entry of options.tokens ?? []) {
|
|
682
|
+
const refused = tokenProblem(entry.token, `the API token ${entry.id}`);
|
|
683
|
+
if (refused)
|
|
684
|
+
throw new Error(refused);
|
|
685
|
+
}
|
|
686
|
+
// Ids each once, secrets each once (api-token.ts), checked before any lock is taken.
|
|
687
|
+
if (options.token !== undefined || (options.tokens?.length ?? 0) > 0)
|
|
688
|
+
acceptedTokens(options.token, options.tokens);
|
|
677
689
|
if (options.drainTimeout !== undefined && durationMs(options.drainTimeout) === undefined)
|
|
678
690
|
throw new Error(`the drain timeout ${options.drainTimeout} is not a duration such as 8s`);
|
|
679
691
|
enabledBoxes(process.env);
|
|
@@ -796,7 +808,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
796
808
|
// which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
|
|
797
809
|
// store is refused above (its owner lock).
|
|
798
810
|
const attachHub = new AttachHub();
|
|
799
|
-
const attach = createAttachRoutes({ store, hub: attachHub, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
|
|
811
|
+
const attach = createAttachRoutes({ store, hub: attachHub, machinesOnly: options.apiOnly === true, log: (event, fields) => (log ? log(logLine(event, fields)) : void process.stderr.write(`agentrun-serve: ${logLine(event, fields)}\n`)) });
|
|
800
812
|
// The data root's own lock, once the store is held (so a deploy on Postgres waits at the store's owner lock first): the
|
|
801
813
|
// store's lock holds one store, but the data root also holds what the server writes beside it (its token, its seal key,
|
|
802
814
|
// uploads, harness installs, learning folders), which two servers on two stores (two Postgres schemas, or SQLite and
|
|
@@ -806,13 +818,17 @@ async function startHolding(options, data, checked, stops) {
|
|
|
806
818
|
const dataLock = await whileReplaced(() => takeServerLock(data), (error) => error instanceof ServerLockHeldError, Math.max(replacedUntil, Date.now() + START_WAIT_MARGIN_MS), waitingForReplaced);
|
|
807
819
|
stops.push(async () => dataLock.release());
|
|
808
820
|
// The token, once both locks are held: a start the locks refuse reads, makes and removes nothing in the data root.
|
|
809
|
-
|
|
810
|
-
const
|
|
811
|
-
const
|
|
812
|
-
|
|
821
|
+
// Given a token list (AGENTRUN_TOKENS), DIR/.token is no token of this server's, as with AGENTRUN_TOKEN.
|
|
822
|
+
const given = options.token !== undefined || (options.tokens?.length ?? 0) > 0;
|
|
823
|
+
const tokenFile = given ? null : join(data, TOKEN_FILE);
|
|
824
|
+
const stored = given ? undefined : await tokenIn(tokenFile);
|
|
825
|
+
// Every token this server takes, by id (api-token.ts): AGENTRUN_TOKEN's (or DIR/.token's) as `default`, then the list's.
|
|
826
|
+
const tokens = acceptedTokens(options.token ?? stored?.token, options.tokens);
|
|
827
|
+
const token = tokens[0].token;
|
|
828
|
+
// Given a token (AGENTRUN_TOKEN or AGENTRUN_TOKENS), a .token an earlier start made holds one this server refuses: it goes, so nothing
|
|
813
829
|
// (a person told the token is there, a CLI that reads it) takes a dead token from it. A later start without one makes a
|
|
814
830
|
// new file and token.
|
|
815
|
-
if (
|
|
831
|
+
if (given)
|
|
816
832
|
await rm(join(data, TOKEN_FILE), { force: true });
|
|
817
833
|
// No start without a seal key (seal-key.ts), checked against the store before anything reads it: the one handed over,
|
|
818
834
|
// else the one in the data directory beside the store, made at the first start with only its path printed. A store whose
|
|
@@ -967,6 +983,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
967
983
|
const adapters = options.triggerAdapters ?? TRIGGER_ADAPTERS;
|
|
968
984
|
const openapi = openapiDocument((operationId) => ROUTES.find((r) => r.name === operationId)?.capability, adapters);
|
|
969
985
|
const sealKey = seal.key;
|
|
986
|
+
// SDK runs' credentials are signed with a key from the seal key, never an API token: a rotation leaves them working.
|
|
987
|
+
const sdkSecret = sdkRunSecret(sealKey);
|
|
970
988
|
// Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
|
|
971
989
|
// the proxy's proof under the seal key (live-reach.ts); any other host is never dialled.
|
|
972
990
|
const reach = liveReachOf(env, sealKey);
|
|
@@ -1009,7 +1027,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1009
1027
|
// probe Docker: a provider whose program is missing is not ready, and its words say what to install.
|
|
1010
1028
|
const hostWhy = hostCommandRefusals(COMPUTER_PROVIDERS, process.env.PATH);
|
|
1011
1029
|
const computersOf = () => (computerRoutes ??= createComputerRoutes({
|
|
1012
|
-
|
|
1030
|
+
// A provider's key set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name
|
|
1031
|
+
// from what the server was started with, as computerReady below reads it.
|
|
1032
|
+
store, sealKey, tools: kindTools, mode: folderModeOf(store, process.env), env: withSecrets(process.env, "own"),
|
|
1013
1033
|
paired: { rows: () => store.pairedComputers.list(), viewOf: (row, serves) => pairedView(row, attachHub, serves) },
|
|
1014
1034
|
...(options.faux
|
|
1015
1035
|
// --faux's providers stand in for every vendor's, a local one's daemon included.
|
|
@@ -1033,6 +1053,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1033
1053
|
const modeNow = async () => ((await folderModeOf(store, process.env)()) === "disk" ? 2 : 1);
|
|
1034
1054
|
/** The registry a run's claim resolves against (claimKinds), as its runner composes it. */
|
|
1035
1055
|
const claimRegistry = () => claimKinds(options.faux ? { faux: fauxOf() } : {});
|
|
1056
|
+
/** A key as the runner reads it: the secrets this process was started with (withSecrets "own"), else the saved one. */
|
|
1057
|
+
const runnerKeys = () => keyReader(store, sealKey, own(withSecrets(process.env, "own")));
|
|
1036
1058
|
// A paired computer is one more provider of the registry (workspace/attached-computers.ts), ready while its driver is
|
|
1037
1059
|
// attached to this process's hub.
|
|
1038
1060
|
const computerReady = async (setting) => {
|
|
@@ -1041,12 +1063,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1041
1063
|
const offline = row ? pairedRefusal(row, attachHub) : undefined;
|
|
1042
1064
|
if (offline)
|
|
1043
1065
|
return { refused: offline };
|
|
1044
|
-
return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired),
|
|
1066
|
+
return computerReadiness(setting, await modeNow(), withPaired(claimRegistry(), paired), runnerKeys(), dockerAnswers, boxAllow, (provider) => (Object.hasOwn(hostWhy, provider) ? hostWhy[provider] : undefined));
|
|
1045
1067
|
};
|
|
1046
1068
|
/** Where a run of an agent with computer `setting` has its shell here now (resolve-computer.ts runShellOf, in the
|
|
1047
1069
|
* folder mode of now, over the registry the claim reads): what runnable.ts lets a sandbox-only tool on the runner by,
|
|
1048
1070
|
* and capabilities show bash by. In Mode 2 a run with no computer has bash on Archil's serverless exec. */
|
|
1049
|
-
const shellOf = async (setting) => runShellOf(setting, await modeNow(), setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()));
|
|
1071
|
+
const shellOf = async (setting) => runShellOf(setting, await modeNow(), await registryHere(setting.provider === undefined ? claimRegistry() : withPaired(claimRegistry(), await store.pairedComputers.list()), runnerKeys()));
|
|
1050
1072
|
/** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
|
|
1051
1073
|
* has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
|
|
1052
1074
|
* with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
|
|
@@ -1079,7 +1101,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1079
1101
|
return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
|
|
1080
1102
|
};
|
|
1081
1103
|
};
|
|
1082
|
-
|
|
1104
|
+
// ARCHIL_API_KEY set where the server starts is one of its secrets, held off process.env (secrets.ts): read by name.
|
|
1105
|
+
const archil = createArchilRoutes({ store, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl ? { control: options.archilControl } : {}) });
|
|
1083
1106
|
/** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
|
|
1084
1107
|
* settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
|
|
1085
1108
|
* list reads it, so a tool of bash's family the run would not have shows unavailable (tool-plane.ts shellUnavailable). */
|
|
@@ -1113,7 +1136,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1113
1136
|
close: () => store.close(),
|
|
1114
1137
|
};
|
|
1115
1138
|
({ secrets: secretStores, settings: triggerSettings } = await openServerSecretsOverStore(store, data, env, adapters, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`))));
|
|
1116
|
-
secretStores.add("server", () =>
|
|
1139
|
+
secretStores.add("server", () => tokens.map((entry) => entry.token));
|
|
1117
1140
|
// The email account's password (email/account.ts), and each one saved since this server started: cut from everything
|
|
1118
1141
|
// it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
|
|
1119
1142
|
const emailPasswords = new Set();
|
|
@@ -1130,6 +1153,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1130
1153
|
const signIns = signInsOverStore(store, sealKey, vendorsOver(() => env, checkFetch));
|
|
1131
1154
|
const webhooks = new Webhooks(store, sealKey, (fields) => (log ? log(logLine("webhook", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("webhook", fields)}\n`)), {
|
|
1132
1155
|
...(options.webhookRetryMs ? { retryMs: options.webhookRetryMs } : {}),
|
|
1156
|
+
...(options.webhookLookup ? { lookup: options.webhookLookup } : {}),
|
|
1133
1157
|
privateTargets: options.webhookPrivateTargets ?? process.env.AGENTRUN_WEBHOOK_PRIVATE_TARGETS === "1",
|
|
1134
1158
|
});
|
|
1135
1159
|
// The outbound webhook's secret, as it stands (set by a PUT, gone with a DELETE), and each it held before.
|
|
@@ -1337,7 +1361,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1337
1361
|
// (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
|
|
1338
1362
|
// timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
|
|
1339
1363
|
const runReadsDeps = {
|
|
1340
|
-
runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: process.env }),
|
|
1364
|
+
runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own") }),
|
|
1341
1365
|
env,
|
|
1342
1366
|
runFacts: (_store, runId) => factsOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1343
1367
|
withheld: (_store, runId) => withheldOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
@@ -1373,7 +1397,16 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1373
1397
|
},
|
|
1374
1398
|
};
|
|
1375
1399
|
const targets = triggerTargets(store, triggerDeps);
|
|
1376
|
-
|
|
1400
|
+
// Every presented token is checked here, against every token the server takes, in constant time (api-token.ts). The id
|
|
1401
|
+
// of the one that opened a request is kept with it for its log line (tokenUsed), never the secret.
|
|
1402
|
+
const bearerOf = bearerCheck(tokens);
|
|
1403
|
+
const tokenUsed = new WeakMap();
|
|
1404
|
+
const bearer = (header, req) => {
|
|
1405
|
+
const id = bearerOf(header);
|
|
1406
|
+
if (id !== undefined && req)
|
|
1407
|
+
tokenUsed.set(req, id);
|
|
1408
|
+
return id !== undefined;
|
|
1409
|
+
};
|
|
1377
1410
|
const keptFile = join(data, IDEMPOTENCY_FILE);
|
|
1378
1411
|
const kept = JSON.parse(await readFile(keptFile, "utf8").catch(() => "null"));
|
|
1379
1412
|
const idempotency = new Map((kept?.entries ?? []).filter(([, v]) => v?.answer && Date.now() - v.at <= IDEMPOTENCY_TTL_S * 1000));
|
|
@@ -1494,7 +1527,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1494
1527
|
adapters,
|
|
1495
1528
|
unavailable: async (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : kind === "email" && !(await openAccount(store, sealKey)) ? noAccount() : undefined),
|
|
1496
1529
|
// The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
|
|
1497
|
-
|
|
1530
|
+
// A feed trigger's reach: where its reads may go, as an MCP server's requests may (mcp-oauth.ts feedAt), and a test's
|
|
1531
|
+
// or an eval's route to its fake feeds (feedsAt).
|
|
1532
|
+
credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : kind === "feed" ? { ...(await mcpServers.outboundReach()), ...(options.feedsAt ? { route: options.feedsAt } : {}) } : undefined),
|
|
1498
1533
|
say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
|
|
1499
1534
|
// The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
|
|
1500
1535
|
// (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
|
|
@@ -1514,6 +1549,21 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1514
1549
|
signal: stopping.signal,
|
|
1515
1550
|
say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
|
|
1516
1551
|
});
|
|
1552
|
+
/** What a save refused while Composio triggers use the server says to do once they are gone (composio-triggers.ts inUse). */
|
|
1553
|
+
const SAVE_AFTER_TRIGGERS = "then save the server again";
|
|
1554
|
+
/** What a save over a preset server left at Composio (ComposioDropped), removed there with the key it was made with, in
|
|
1555
|
+
* words; when that key doesn't open here, all of it said to remove by hand. */
|
|
1556
|
+
const composioLeft = async (name, dropped) => "unusable" in dropped && (dropped.mcp || dropped.cleanup.remove.length) ? composioNote(name, dropped.cleanup, dropped.mcp ?? false, true)
|
|
1557
|
+
: await composioForget(options.composioControl ?? {}, "key" in dropped ? dropped.key : "", dropped.mcp, name, stopping.signal, dropped.cleanup);
|
|
1558
|
+
// The Composio preset's saves, the saves of the servers it made, and the MCP servers' deletes, one at a time, Composio's
|
|
1559
|
+
// calls included: a delete never removes there an auth config or account that a save still at Composio reuses (it would
|
|
1560
|
+
// find no record of it yet), and a save never reuses one a delete is removing. A failure of one never stops the next.
|
|
1561
|
+
let composioLast = Promise.resolve();
|
|
1562
|
+
const inComposioTurn = (work) => {
|
|
1563
|
+
const turn = composioLast.then(work, work);
|
|
1564
|
+
composioLast = turn.catch(() => undefined);
|
|
1565
|
+
return turn;
|
|
1566
|
+
};
|
|
1517
1567
|
// A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
|
|
1518
1568
|
stops.push(() => githubConnect.close());
|
|
1519
1569
|
stops.push(async () => triggers.close());
|
|
@@ -2145,7 +2195,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2145
2195
|
// Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
|
|
2146
2196
|
// from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>). "Passed"
|
|
2147
2197
|
// by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
|
|
2148
|
-
|
|
2198
|
+
// A feed trigger whose urls are one array parameter given empty reads no feed: skipped, never the apply (feedLeftEmpty).
|
|
2199
|
+
const emptyFeeds = new Set(made.triggers.flatMap((trigger, i) => (feedLeftEmpty(trigger) ? [i] : [])));
|
|
2200
|
+
const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !emptyFeeds.has(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
|
|
2149
2201
|
if (refusedTriggers.length)
|
|
2150
2202
|
throw invalid(refusedTriggers);
|
|
2151
2203
|
// POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
|
|
@@ -2164,6 +2216,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2164
2216
|
const unconnected = new Map();
|
|
2165
2217
|
try {
|
|
2166
2218
|
for (const [i, trigger] of made.triggers.entries()) {
|
|
2219
|
+
if (emptyFeeds.has(i))
|
|
2220
|
+
continue;
|
|
2167
2221
|
try {
|
|
2168
2222
|
const { id: madeId, secret } = await triggers.create({ ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } });
|
|
2169
2223
|
ids.push(madeId);
|
|
@@ -2214,12 +2268,14 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2214
2268
|
const refused = unconnected.get(i);
|
|
2215
2269
|
return refused && isObject(trigger.source) && trigger.source.kind === "composio" ? [{ field: `triggers.${i}`, reason: NOT_SET_UP, message: composioTriggerSkipped(pkg.name, trigger, refused.message), fix: COMPOSIO_TRIGGER_FIX }] : [];
|
|
2216
2270
|
});
|
|
2271
|
+
// Each feed trigger it skipped for want of a feed: which, and the parameter to set.
|
|
2272
|
+
const feedsSkipped = [...emptyFeeds].map((i) => ({ field: `triggers.${i}`, reason: NOT_SET_UP, message: feedTriggerEmpty(pkg.name, made.triggers[i], isObject(pkg.triggers[i]?.source) ? pkg.triggers[i].source.urls : undefined) }));
|
|
2217
2273
|
// Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
|
|
2218
2274
|
// (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
|
|
2219
2275
|
const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
|
|
2220
2276
|
// Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
|
|
2221
2277
|
const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
|
|
2222
|
-
const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...appShort] };
|
|
2278
|
+
const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...appShort] };
|
|
2223
2279
|
return { applied, minted };
|
|
2224
2280
|
}
|
|
2225
2281
|
/** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
|
|
@@ -2420,7 +2476,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2420
2476
|
}
|
|
2421
2477
|
/** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
|
|
2422
2478
|
function runBodyIssues(body) {
|
|
2423
|
-
const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
|
|
2479
|
+
const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes", "labels"]);
|
|
2424
2480
|
issues.push(...holdIssues(body));
|
|
2425
2481
|
if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
|
|
2426
2482
|
issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
|
|
@@ -2446,6 +2502,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2446
2502
|
issues.push({ field: "workflow_first", reason: "wrong_type", message: "workflow_first is true or false" });
|
|
2447
2503
|
if (body.learning !== undefined && body.learning !== RUN_LEARNING_USE)
|
|
2448
2504
|
issues.push({ field: "learning", reason: "not_an_option", message: `learning is "${RUN_LEARNING_USE}" (the run starts from what its agent learned and keeps nothing), or absent (its agent's own)` });
|
|
2505
|
+
issues.push(...labelsIssues(body.labels));
|
|
2449
2506
|
return issues;
|
|
2450
2507
|
}
|
|
2451
2508
|
/** A page of runs from the store, newest first: `agent`, `revision` and `status` narrow it. */
|
|
@@ -2466,8 +2523,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2466
2523
|
if (value !== undefined && !ID.test(value))
|
|
2467
2524
|
throw new ApiError("bad_request", `${key} is an id`);
|
|
2468
2525
|
const archived = archivedParam(url);
|
|
2526
|
+
// `label=<key>:<value>`, once: only the runs holding it (run-labels.ts), filtered in the store.
|
|
2527
|
+
const labels = labelFilter(url.searchParams.getAll("label"));
|
|
2469
2528
|
const vd = viewDepsFor(origin);
|
|
2470
|
-
let rows = (await listRunsOverStore(store, filter, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
|
|
2529
|
+
let rows = (await listRunsOverStore(store, { ...filter, ...(labels ? { labels } : {}) }, ctx)).filter((row) => Boolean(row.archivedAt) === archived);
|
|
2471
2530
|
if (status !== null) {
|
|
2472
2531
|
// The v2 status is the run view's (store-view over the journal), per row.
|
|
2473
2532
|
const statuses = await Promise.all(rows.map((row) => viewOverStore(store, row.id, vd).then((v) => v?.status)));
|
|
@@ -2711,7 +2770,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2711
2770
|
switch (path) {
|
|
2712
2771
|
case "/setup": {
|
|
2713
2772
|
const byToken = req.headers.authorization !== undefined;
|
|
2714
|
-
if (byToken && !
|
|
2773
|
+
if (byToken && !bearer(req.headers.authorization, req))
|
|
2715
2774
|
throw new ApiError("unauthenticated", "the Bearer here is the server's token, or none", {}, { "www-authenticate": "Bearer" });
|
|
2716
2775
|
if (!byToken)
|
|
2717
2776
|
fromPage(req);
|
|
@@ -2725,7 +2784,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2725
2784
|
const along = body.import === true ? { keep: () => writeDurable(importAsked, ""), drop: () => rm(importAsked, { force: true }) } : undefined;
|
|
2726
2785
|
// The server's API token stands in for the code in the code field too (on Render it is in the Environment tab, the
|
|
2727
2786
|
// code only in the log), compared as the header is, in constant time; a wrong one counts as a wrong code.
|
|
2728
|
-
const tokenAsCode = typeof body.code === "string" && body.code !== "" &&
|
|
2787
|
+
const tokenAsCode = typeof body.code === "string" && body.code !== "" && bearer(`Bearer ${body.code}`, req);
|
|
2729
2788
|
const made = await me.setFirst(password, body.code, byToken || tokenAsCode, along);
|
|
2730
2789
|
if (made === "exists")
|
|
2731
2790
|
throw new ApiError("forbidden", "this server has its owner, or is being set up: sign in");
|
|
@@ -2918,6 +2977,20 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2918
2977
|
// limited by source address before anything in the body is checked.
|
|
2919
2978
|
if (found.name === "pairComputer")
|
|
2920
2979
|
return send(res, 201, await attach.pair(await bodyOf(req), clientOf(req)), { "cache-control": "no-store" });
|
|
2980
|
+
// A hosted machine fetching this server's computerd build: the token its create minted is its credential, never the
|
|
2981
|
+
// owner's (computer-attach.ts daemon).
|
|
2982
|
+
if (found.name === "getComputerDaemon") {
|
|
2983
|
+
const file = await attach.daemon(req.headers.authorization, url.searchParams.get("arch")).catch((error) => {
|
|
2984
|
+
if (error instanceof ApiError && error.status === 401)
|
|
2985
|
+
authFailed(`/v2${path}`, "machine_token");
|
|
2986
|
+
throw error;
|
|
2987
|
+
});
|
|
2988
|
+
const bytes = await readFile(file).catch(() => {
|
|
2989
|
+
throw new ApiError("unavailable", `this server has no computerd build at ${file}: run npm run build:daemon -w @parcha/agentrun-computer where it runs`);
|
|
2990
|
+
});
|
|
2991
|
+
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": String(bytes.length), "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
2992
|
+
return void res.end(req.method === "HEAD" ? undefined : bytes);
|
|
2993
|
+
}
|
|
2921
2994
|
// An MCP server's OAuth sign-in: the browser coming back from its authorization server carries no token (the state
|
|
2922
2995
|
// it brings is the check, mcp-oauth.ts), and the client metadata document is for that server to fetch.
|
|
2923
2996
|
if (found.name === "mcpOAuthCallback") {
|
|
@@ -3050,7 +3123,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3050
3123
|
if (found.name === "importRemoteTarget")
|
|
3051
3124
|
return send(res, 200, await broker.importTarget(connectorId, body));
|
|
3052
3125
|
if (found.name === "importRemoteHistory")
|
|
3053
|
-
return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [token, String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
|
|
3126
|
+
return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [...tokens.map((entry) => entry.token), String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
|
|
3054
3127
|
if (found.name === "pollRemoteConnector")
|
|
3055
3128
|
return send(res, 200, await broker.poll(connectorId, body));
|
|
3056
3129
|
const commandId = decodeURIComponent(parts[2]);
|
|
@@ -3058,7 +3131,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3058
3131
|
}
|
|
3059
3132
|
if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
|
|
3060
3133
|
const runId = decodeURIComponent(found.pattern.exec(path)[1]);
|
|
3061
|
-
const sdk = new SdkRuns(store, data,
|
|
3134
|
+
const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
|
|
3062
3135
|
await sdk.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
|
|
3063
3136
|
if (found.name === "sdkRunEvents")
|
|
3064
3137
|
return send(res, 200, await sdk.events(runId, await bodyOf(req)));
|
|
@@ -3066,7 +3139,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3066
3139
|
return send(res, 200, await sdk.complete(runId, await bodyOf(req)));
|
|
3067
3140
|
return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
|
|
3068
3141
|
}
|
|
3069
|
-
if (!
|
|
3142
|
+
if (!bearer(req.headers.authorization, req)) {
|
|
3070
3143
|
authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
|
|
3071
3144
|
throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
|
|
3072
3145
|
}
|
|
@@ -3090,7 +3163,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3090
3163
|
}
|
|
3091
3164
|
catch { }
|
|
3092
3165
|
}
|
|
3093
|
-
const sdk = new SdkRuns(store, data,
|
|
3166
|
+
const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
|
|
3094
3167
|
const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, { ...startDeps, ...(gradeModel ? { gradeModel } : {}) }, origin, async (model) => {
|
|
3095
3168
|
try {
|
|
3096
3169
|
const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
|
|
@@ -3750,9 +3823,30 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3750
3823
|
case "previewMcpServer":
|
|
3751
3824
|
return send(res, 200, await mcpServers.preview(await bodyOf(req), stopping.signal));
|
|
3752
3825
|
case "saveMcpServer": {
|
|
3753
|
-
const
|
|
3826
|
+
const body = await bodyOf(req);
|
|
3827
|
+
// A server that isn't a Composio preset's is saved at once, as ever: no save waits on another's listing.
|
|
3828
|
+
if (!(await mcpServers.composioPreset(id))) {
|
|
3829
|
+
const saved = await mcpServers.save(id, body, stopping.signal, secretSeen);
|
|
3830
|
+
await refreshMcpMeta();
|
|
3831
|
+
return send(res, 200, saved);
|
|
3832
|
+
}
|
|
3833
|
+
// A preset server's: listed as any save is, at once; then its write and cleanup in the Composio turn and its
|
|
3834
|
+
// project's. A save that moves it off Composio is refused while Composio triggers use it, in the delete's words;
|
|
3835
|
+
// else it removes there what its save made (the MCP server, then what no other saved server uses), as a delete
|
|
3836
|
+
// does, with the key it was saved with, and says so.
|
|
3837
|
+
const over = {};
|
|
3838
|
+
const guard = {
|
|
3839
|
+
turn: (work) => inComposioTurn(async () => {
|
|
3840
|
+
const done = await composioTriggers.inTurnOf(id, work);
|
|
3841
|
+
if (over.dropped)
|
|
3842
|
+
over.note = await composioLeft(id, over.dropped);
|
|
3843
|
+
return done;
|
|
3844
|
+
}),
|
|
3845
|
+
inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS),
|
|
3846
|
+
};
|
|
3847
|
+
const saved = await mcpServers.save(id, body, stopping.signal, secretSeen, undefined, undefined, (left) => (over.dropped = left), guard);
|
|
3754
3848
|
await refreshMcpMeta();
|
|
3755
|
-
return send(res, 200, saved);
|
|
3849
|
+
return send(res, 200, over.note ? { ...saved, composio: over.note } : saved);
|
|
3756
3850
|
}
|
|
3757
3851
|
// Composio makes the managed MCP server; what is kept is the ordinary MCP save, so the key is a sealed header.
|
|
3758
3852
|
case "listComposioTools":
|
|
@@ -3761,8 +3855,18 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3761
3855
|
// The name is checked before Composio is called: a refused name leaves nothing made there.
|
|
3762
3856
|
mcpNameOf(id);
|
|
3763
3857
|
const body = await bodyOf(req);
|
|
3764
|
-
|
|
3765
|
-
|
|
3858
|
+
// In the Composio turn. A save over a preset server removes there, once it is saved, the MCP server the save before
|
|
3859
|
+
// made and what that save made that this one no longer stands on (an account of another user, an auth config of
|
|
3860
|
+
// another toolkit), with the key it was made with, and says so as a delete does; what another saved server uses is
|
|
3861
|
+
// that one's now, and said too. A save as another user or auth config is refused while Composio triggers use the
|
|
3862
|
+
// server, in the delete's words, checked in its project's turn before the row is written.
|
|
3863
|
+
const answer = await inComposioTurn(async () => {
|
|
3864
|
+
const over = {};
|
|
3865
|
+
const guard = { turn: (work) => composioTriggers.inTurnOf(id, work), inUse: () => composioTriggers.inUse(id, SAVE_AFTER_TRIGGERS) };
|
|
3866
|
+
const saved = await composioSave(body, options.composioControl ?? {}, (mcp, made, stands) => mcpServers.save(id, mcp, stopping.signal, undefined, made, stands, (left) => (over.dropped = left), guard), id, stopping.signal, async () => (await mcpServers.get(id)).url);
|
|
3867
|
+
await refreshMcpMeta();
|
|
3868
|
+
return over.dropped ? { ...saved, composio: await composioLeft(id, over.dropped) } : saved;
|
|
3869
|
+
});
|
|
3766
3870
|
return send(res, 200, answer, { "cache-control": "no-store" });
|
|
3767
3871
|
}
|
|
3768
3872
|
case "listComposioEvents":
|
|
@@ -3819,14 +3923,18 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3819
3923
|
return send(res, 200, await privateHostsRoute(mcpServers, { method: "PUT", body: () => bodyOf(req) }), { "cache-control": "no-store" });
|
|
3820
3924
|
case "deleteMcpServer": {
|
|
3821
3925
|
// Our row goes first, by the checked removal (a 412 sends Composio nothing), and answers what it removed: a Composio
|
|
3822
|
-
// preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key
|
|
3823
|
-
//
|
|
3824
|
-
//
|
|
3825
|
-
//
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
const forgotten =
|
|
3829
|
-
|
|
3926
|
+
// preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key, then
|
|
3927
|
+
// what its save made for it there that no other saved server uses (its connect link's account, its auth config).
|
|
3928
|
+
// Composio refusing or not answering, or a key that does not open, never keeps our row. A preset's answer says in
|
|
3929
|
+
// words what went there, what stays and why, and what to remove by hand. One that Composio triggers still use is kept: refused, naming them, checked and deleted in
|
|
3930
|
+
// its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting). All of
|
|
3931
|
+
// it in the Composio turn, so a Composio save still at work finishes first and its record is counted.
|
|
3932
|
+
const forgotten = await inComposioTurn(async () => {
|
|
3933
|
+
const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
|
|
3934
|
+
await refreshMcpMeta();
|
|
3935
|
+
return !made ? undefined : "unusable" in made ? composioNote(id, made.cleanup) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal, made.cleanup);
|
|
3936
|
+
});
|
|
3937
|
+
if (forgotten)
|
|
3830
3938
|
return send(res, 200, { deleted: true, composio: forgotten }, { "cache-control": "no-store" });
|
|
3831
3939
|
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
3832
3940
|
}
|
|
@@ -4115,7 +4223,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4115
4223
|
throw new ApiError("not_found", `no route ${path}`);
|
|
4116
4224
|
}
|
|
4117
4225
|
// The MCP endpoint's tools are the routes above, called in process with the caller's token (mcp.ts).
|
|
4118
|
-
const mcp = mcpEndpoint({ route, authorized: (header) =>
|
|
4226
|
+
const mcp = mcpEndpoint({ route, authorized: (header, req) => bearer(header, req), authFailed, version: VERSION });
|
|
4119
4227
|
function send(res, status, body, headers = {}) {
|
|
4120
4228
|
const text = JSON.stringify(body);
|
|
4121
4229
|
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
|
|
@@ -4158,7 +4266,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4158
4266
|
const started = performance.now();
|
|
4159
4267
|
const method = req.method ?? "GET";
|
|
4160
4268
|
const path = (req.url ?? "/").split("?")[0];
|
|
4161
|
-
|
|
4269
|
+
// Who the request was answered for: the owner's or the console's session, or the id of the API token it carried
|
|
4270
|
+
// (api-token.ts), never a secret. A request opened by neither has no such field.
|
|
4271
|
+
res.once("finish", () => {
|
|
4272
|
+
const by = byOwnerSession(req) ? { session: "owner" } : byConsoleSession(req) ? { session: "console" } : tokenUsed.has(req) ? { token: tokenUsed.get(req) } : {};
|
|
4273
|
+
log(logLine("request", { method, path, status: res.statusCode, ms: Math.round(performance.now() - started), ...by }));
|
|
4274
|
+
});
|
|
4162
4275
|
}
|
|
4163
4276
|
const fail = (error) => {
|
|
4164
4277
|
if (res.headersSent)
|
|
@@ -4205,7 +4318,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4205
4318
|
if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
|
|
4206
4319
|
return;
|
|
4207
4320
|
if (isObservationRoute(raw))
|
|
4208
|
-
return void observationHttp(req, res, url, new Observations(store),
|
|
4321
|
+
return void observationHttp(req, res, url, new Observations(store), (header) => bearer(header, req)).catch(fail);
|
|
4209
4322
|
if (!raw.startsWith("/v2/"))
|
|
4210
4323
|
return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
|
|
4211
4324
|
// A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
|
|
@@ -4230,10 +4343,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4230
4343
|
// away. Its name alone, on any port, as the HTTP routes check it.
|
|
4231
4344
|
if (names && !names.has(hostName(req.headers.host) ?? ""))
|
|
4232
4345
|
return deny("403 Forbidden");
|
|
4233
|
-
// API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings)
|
|
4234
|
-
|
|
4346
|
+
// API-only: a run's live view is the console's, and refused with it; so are paired computers (Settings), whose tokens
|
|
4347
|
+
// the attach socket takes as unknown there (machinesOnly). A run's hosted machine that dials still reaches it.
|
|
4348
|
+
if (options.apiOnly && raw !== ATTACH_PATH)
|
|
4235
4349
|
return deny("404 Not Found");
|
|
4236
|
-
// A paired computer's driver dialing
|
|
4350
|
+
// A paired computer's driver or a hosted machine dialing the attach socket (computer-attach.ts): its token, not the
|
|
4351
|
+
// owner's, lets it in.
|
|
4237
4352
|
if (raw === ATTACH_PATH) {
|
|
4238
4353
|
return attach.upgrade(req, socket, head, (status, words = "", headers = {}) => {
|
|
4239
4354
|
if (status.startsWith("401"))
|
|
@@ -4627,13 +4742,16 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4627
4742
|
baseUrl: `${url}/v2`,
|
|
4628
4743
|
port: address.port,
|
|
4629
4744
|
token,
|
|
4745
|
+
tokenIds: tokens.map((entry) => entry.id),
|
|
4630
4746
|
tokenFile,
|
|
4631
4747
|
tokenMade: stored?.made ?? false,
|
|
4632
4748
|
...(setupUrl ? { setupUrl, setupOpen: openSetup } : {}),
|
|
4633
4749
|
...(consoleSessions ? { launchCode: consoleSessions.code } : {}),
|
|
4634
4750
|
boxesLine: boxesLine(boxOffers, enabledBoxes(env), boxAllow, boxesByDefault(env)),
|
|
4635
4751
|
attachHub,
|
|
4752
|
+
dial: { ...(options.publicUrl ? { url: options.publicUrl.replace(/\/+$/, "") } : {}), tokens: attach.machineTokens, hub: attachHub },
|
|
4636
4753
|
localInstall,
|
|
4754
|
+
own: mcpServers.own,
|
|
4637
4755
|
// Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
|
|
4638
4756
|
// never writes this data root's record again (the next server's, by then).
|
|
4639
4757
|
close: () => (stopped ??= stop()),
|
package/dist/store/dialect.d.ts
CHANGED
|
@@ -10,6 +10,9 @@ export interface Dialect {
|
|
|
10
10
|
jsonNotFalse(column: string, path: readonly string[]): string;
|
|
11
11
|
/** True when the JSON array in TEXT column `column` holds the string parameter that follows (one `?`). */
|
|
12
12
|
jsonArrayHas(column: string): string;
|
|
13
|
+
/** True when the JSON object of strings in TEXT column `column` holds the key and the value of the two string parameters
|
|
14
|
+
* that follow (two `?`): bound, never spliced, so any key reads safely. False when the column is NULL. */
|
|
15
|
+
jsonObjectHas(column: string): string;
|
|
13
16
|
/** The length of the JSON array in TEXT column `column`. */
|
|
14
17
|
jsonArrayLength(column: string): string;
|
|
15
18
|
/** The JSON object in TEXT column `column` without its top-level `key`. */
|
package/dist/store/dialect.js
CHANGED
|
@@ -15,6 +15,7 @@ export const SQLITE = {
|
|
|
15
15
|
jsonText: (column, path) => `json_extract(${column}, ${jsonPath(path)})`,
|
|
16
16
|
jsonNotFalse: (column, path) => `json_extract(${column}, ${jsonPath(path)}) IS NOT 0`,
|
|
17
17
|
jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) WHERE value = ?)`,
|
|
18
|
+
jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each(${column}) AS entry WHERE entry.key = ? AND entry.value = ?)`,
|
|
18
19
|
jsonArrayLength: (column) => `json_array_length(${column})`,
|
|
19
20
|
jsonWithout: (column, key) => `json_remove(${column}, ${jsonPath([key])})`,
|
|
20
21
|
firingOrder: "rowid",
|
package/dist/store/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { AgentArchived, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull } from "./store.js";
|
|
2
|
-
export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, Learning, LearningProposal, LiveViewerRow, LiveViewers, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
|
|
2
|
+
export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpRemoved, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerStamp, McpServerWrite, MintedTokenRow, MintedTokens, NewFiring, NewPairedComputer, NewRevision, NewTrigger, PairedComputerRow, PairedComputers, ReleasedState, RevisionRow, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, Channels, ChannelAttemptRow, ChannelPostRow, ChannelToldRow, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunLabels, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, Learning, LearningProposal, LiveViewerRow, LiveViewers, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
|
|
3
3
|
export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunMcpAuth, type RunMcpAuth, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunMcpAuth, unsealColumn } from "./seal.js";
|
|
4
4
|
export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type MonidPinBody, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
|
|
5
5
|
export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
|
|
@@ -12,6 +12,7 @@ export function postgresDialect(schema, { testClock = false } = {}) {
|
|
|
12
12
|
// SQLite's json_extract(...) IS NOT 0: true unless the value is false or the number 0 (absent and null are true).
|
|
13
13
|
jsonNotFalse: (column, keys) => `COALESCE((${column}::json #> ${path(keys)})::text NOT IN ('false', '0'), TRUE)`,
|
|
14
14
|
jsonArrayHas: (column) => `EXISTS (SELECT 1 FROM json_array_elements_text(${column}::json) AS element(value) WHERE element.value = ?)`,
|
|
15
|
+
jsonObjectHas: (column) => `EXISTS (SELECT 1 FROM json_each_text(${column}::json) AS entry(key, value) WHERE entry.key = ? AND entry.value = ?)`,
|
|
15
16
|
jsonArrayLength: (column) => `json_array_length(${column}::json)`,
|
|
16
17
|
// Through jsonb, the one place: a body that loses a key is never read for its key order. Every Postgres JSON function
|
|
17
18
|
// decodes the whole document's strings, so a body holding a string jsonb refuses (an escaped NUL, a lone surrogate)
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
-- Version 15: a run's labels (runs.labels, as store/schema.ts keeps them on SQLite): the caller's labels, a JSON object of
|
|
2
|
+
-- strings set once at the run's start; null when it was given none, so a run started before reads as given none. Applied
|
|
3
|
+
-- once, after 0014, inside the transaction migrate.ts opens. Never edit this file once applied: a change is a new file.
|
|
4
|
+
ALTER TABLE runs ADD COLUMN IF NOT EXISTS labels TEXT COLLATE "C" CHECK (labels IS NULL OR labels::json IS NOT NULL);
|
|
5
|
+
UPDATE store_meta SET schema_version = 15 WHERE singleton = 1;
|