@parcha/agentrun-serve 0.1.0-beta.52 → 0.1.0-beta.54
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 +149 -1
- package/README.md +295 -37
- package/dist/agent-delete.d.ts +5 -6
- package/dist/agent-delete.js +30 -67
- package/dist/agent-package.d.ts +71 -0
- package/dist/agent-package.js +345 -0
- package/dist/agent-rows.d.ts +1 -1
- package/dist/agents-store.d.ts +26 -20
- package/dist/agents-store.js +42 -34
- package/dist/api-only.d.ts +25 -6
- package/dist/api-only.js +34 -13
- package/dist/claude-login.d.ts +1 -0
- package/dist/claude-login.js +1 -1
- package/dist/cli-learning/cli.d.ts +3 -0
- package/dist/cli-learning/cli.js +17 -3
- package/dist/cli-learning/connections.js +3 -2
- package/dist/cli-learning/schema.js +2 -1
- package/dist/cli.js +76 -8
- package/dist/composio-preset.d.ts +3 -1
- package/dist/composio-preset.js +5 -3
- package/dist/composio-triggers.d.ts +4 -0
- package/dist/composio-triggers.js +4 -1
- package/dist/computer-needs.d.ts +32 -0
- package/dist/computer-needs.js +80 -0
- package/dist/computer-setting.d.ts +5 -2
- package/dist/computer-setting.js +8 -1
- package/dist/computers.d.ts +0 -2
- package/dist/computers.js +1 -1
- package/dist/console/assets/index-B_85An2t.js +745 -0
- package/dist/console/assets/index-n1YsbnYh.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/console-links.d.ts +1 -0
- package/dist/console-links.js +2 -0
- package/dist/env-switch.d.ts +14 -0
- package/dist/env-switch.js +23 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +10 -0
- package/dist/eval-previous.js +4 -3
- package/dist/fal-price.js +10 -13
- package/dist/github-connection.d.ts +50 -1
- package/dist/github-connection.js +96 -3
- package/dist/github-faux.d.ts +11 -2
- package/dist/github-faux.js +138 -7
- package/dist/github-pull-request.d.ts +37 -0
- package/dist/github-pull-request.js +110 -0
- package/dist/handed-secret.d.ts +4 -0
- package/dist/handed-secret.js +10 -0
- package/dist/harness-archive.d.ts +15 -5
- package/dist/harness-archive.js +71 -34
- package/dist/harness-check.d.ts +2 -1
- package/dist/harness-check.js +36 -95
- package/dist/harness-egress.d.ts +23 -0
- package/dist/harness-egress.js +69 -0
- package/dist/harness-recipe-entry.d.ts +71 -0
- package/dist/harness-recipe-entry.js +184 -0
- package/dist/harness-recipe.d.ts +73 -6
- package/dist/harness-recipe.js +185 -31
- package/dist/harness-sign-in.d.ts +29 -0
- package/dist/harness-sign-in.js +122 -0
- package/dist/harness-table.d.ts +21 -0
- package/dist/harness-table.js +58 -3
- package/dist/harness-zip.d.ts +6 -0
- package/dist/harness-zip.js +203 -0
- package/dist/ids.d.ts +11 -0
- package/dist/ids.js +36 -0
- package/dist/learn/commit.d.ts +14 -1
- package/dist/learn/commit.js +156 -1
- package/dist/learn/compile.js +22 -8
- package/dist/learn/folder.d.ts +5 -0
- package/dist/learn/folder.js +10 -1
- package/dist/learn/learning.sh +15 -3
- package/dist/learn/promote.d.ts +2 -2
- package/dist/learn/secrets.js +30 -7
- package/dist/learning-routes.d.ts +23 -11
- package/dist/learning-routes.js +110 -20
- package/dist/learning.d.ts +9 -6
- package/dist/learning.js +9 -4
- package/dist/live-reach.d.ts +34 -7
- package/dist/live-reach.js +76 -11
- package/dist/mcp-gateway.js +15 -2
- package/dist/mcp-probe.d.ts +3 -0
- package/dist/mcp-probe.js +8 -3
- package/dist/mcp-resources.d.ts +44 -0
- package/dist/mcp-resources.js +100 -0
- package/dist/mcp-servers-store.d.ts +16 -12
- package/dist/model.d.ts +4 -4
- package/dist/model.js +6 -6
- package/dist/native/cli.js +9 -2
- package/dist/native/connection.d.ts +2 -2
- package/dist/native/connection.js +5 -2
- package/dist/native/discovery.d.ts +2 -0
- package/dist/native/discovery.js +10 -6
- package/dist/native/remote-worker-bridge.js +36 -4
- package/dist/native/remote.d.ts +18 -1
- package/dist/native/remote.js +126 -37
- package/dist/native/schema.d.ts +6 -0
- package/dist/native/schema.js +31 -6
- package/dist/native/source-account.d.ts +13 -0
- package/dist/native/source-account.js +114 -0
- package/dist/native/source-capture-hooks.d.ts +5 -0
- package/dist/native/source-capture-hooks.js +102 -0
- package/dist/native/source-mcp-selection.d.ts +13 -0
- package/dist/native/source-mcp-selection.js +72 -0
- package/dist/native/source-runtime-tools.d.ts +19 -0
- package/dist/native/source-runtime-tools.js +103 -0
- package/dist/native/source-snapshot-types.d.ts +138 -0
- package/dist/native/source-snapshot-types.js +12 -0
- package/dist/native/source-snapshot.d.ts +8 -0
- package/dist/native/source-snapshot.js +1201 -0
- package/dist/observation/learning.js +3 -2
- package/dist/openapi.js +275 -40
- package/dist/print.js +1 -1
- package/dist/purged-workflow.d.ts +12 -0
- package/dist/purged-workflow.js +43 -0
- package/dist/run-keys.d.ts +46 -0
- package/dist/run-keys.js +109 -0
- package/dist/run-launch.d.ts +16 -1
- package/dist/run-launch.js +30 -1
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-model-key.d.ts +2 -2
- package/dist/run-model-key.js +5 -5
- package/dist/run-secrets.d.ts +2 -0
- package/dist/run-secrets.js +7 -4
- package/dist/run-view.d.ts +17 -0
- package/dist/run-view.js +25 -1
- package/dist/runner/adapter-loop.d.ts +11 -3
- package/dist/runner/adapter-loop.js +138 -22
- package/dist/runner/adapter-run-spec.js +26 -13
- package/dist/runner/audit.d.ts +2 -0
- package/dist/runner/audit.js +9 -1
- package/dist/runner/beside.js +2 -1
- package/dist/runner/claim-secrets.d.ts +29 -3
- package/dist/runner/claim-secrets.js +38 -4
- package/dist/runner/cli-run-spec.js +24 -13
- package/dist/runner/harness-loops.d.ts +6 -0
- package/dist/runner/harness-loops.js +11 -1
- package/dist/runner/held.d.ts +4 -0
- package/dist/runner/journal-kinds.d.ts +2 -0
- package/dist/runner/learned-first.d.ts +2 -0
- package/dist/runner/learned-first.js +1 -1
- package/dist/runner/learning-end.d.ts +7 -2
- package/dist/runner/learning-end.js +22 -10
- package/dist/runner/learning-seed.d.ts +9 -3
- package/dist/runner/learning-seed.js +2 -2
- package/dist/runner/main.d.ts +1 -0
- package/dist/runner/main.js +20 -13
- package/dist/runner/mcp-claim.js +6 -1
- package/dist/runner/mcp-run.d.ts +10 -7
- package/dist/runner/mcp-run.js +3 -5
- package/dist/runner/metrics.d.ts +4 -2
- package/dist/runner/metrics.js +15 -3
- package/dist/runner/monid-run.js +9 -11
- package/dist/runner/pr-checkout.d.ts +21 -4
- package/dist/runner/pr-checkout.js +103 -4
- package/dist/runner/project-checkpoint.d.ts +35 -0
- package/dist/runner/project-checkpoint.js +116 -0
- package/dist/runner/project-drain.d.ts +8 -0
- package/dist/runner/project-drain.js +25 -0
- package/dist/runner/project-host.d.ts +10 -0
- package/dist/runner/project-host.js +52 -0
- package/dist/runner/promotion.d.ts +14 -6
- package/dist/runner/promotion.js +98 -41
- package/dist/runner/redact.d.ts +13 -0
- package/dist/runner/redact.js +67 -1
- package/dist/runner/run-channel.d.ts +9 -0
- package/dist/runner/run-channel.js +15 -2
- package/dist/runner/run-child-host.d.ts +8 -4
- package/dist/runner/run-child-host.js +178 -45
- package/dist/runner/run-errors.js +2 -2
- package/dist/runner/runner-check.d.ts +3 -0
- package/dist/runner/runner-check.js +28 -2
- package/dist/runner/runner.js +26 -9
- package/dist/runner/store-secrets.js +7 -3
- package/dist/runner/workflow-first.d.ts +4 -0
- package/dist/runner/workflow-first.js +13 -0
- package/dist/runner/workflow-loop.d.ts +2 -1
- package/dist/runner/workflow-loop.js +2 -1
- package/dist/runner/workflow-spec.js +1 -1
- package/dist/runs-over-store.d.ts +34 -6
- package/dist/runs-over-store.js +133 -25
- package/dist/sdk/runs.d.ts +11 -1
- package/dist/sdk/runs.js +117 -26
- package/dist/sdk/schema.js +12 -2
- package/dist/sdk/workflows.d.ts +1 -1
- package/dist/server.d.ts +79 -32
- package/dist/server.js +673 -113
- package/dist/skills/agentrun-serve/SKILL.md +2 -1
- package/dist/source-sync/adoption.d.ts +15 -0
- package/dist/source-sync/adoption.js +36 -0
- package/dist/source-sync/auxiliary.d.ts +23 -0
- package/dist/source-sync/auxiliary.js +64 -0
- package/dist/source-sync/capture-git.d.ts +5 -0
- package/dist/source-sync/capture-git.js +272 -0
- package/dist/source-sync/capture-project.d.ts +53 -0
- package/dist/source-sync/capture-project.js +206 -0
- package/dist/source-sync/capture-refusal.d.ts +7 -0
- package/dist/source-sync/capture-refusal.js +16 -0
- package/dist/source-sync/capture.d.ts +11 -0
- package/dist/source-sync/capture.js +22 -0
- package/dist/source-sync/checkpoint-gate.d.ts +21 -0
- package/dist/source-sync/checkpoint-gate.js +52 -0
- package/dist/source-sync/checkpoints.d.ts +66 -0
- package/dist/source-sync/checkpoints.js +168 -0
- package/dist/source-sync/claim.d.ts +11 -0
- package/dist/source-sync/claim.js +48 -0
- package/dist/source-sync/destination.d.ts +47 -0
- package/dist/source-sync/destination.js +239 -0
- package/dist/source-sync/io.d.ts +15 -0
- package/dist/source-sync/io.js +52 -0
- package/dist/source-sync/local.d.ts +43 -0
- package/dist/source-sync/local.js +229 -0
- package/dist/source-sync/prepare.d.ts +59 -0
- package/dist/source-sync/prepare.js +93 -0
- package/dist/source-sync/projects.d.ts +61 -0
- package/dist/source-sync/projects.js +130 -0
- package/dist/source-sync/registry.d.ts +95 -0
- package/dist/source-sync/registry.js +226 -0
- package/dist/source-sync/service.d.ts +33 -0
- package/dist/source-sync/service.js +118 -0
- package/dist/source-sync/skill-edits.d.ts +12 -0
- package/dist/source-sync/skill-edits.js +122 -0
- package/dist/source-sync/snapshots.d.ts +48 -0
- package/dist/source-sync/snapshots.js +448 -0
- package/dist/source-sync/types.d.ts +9 -0
- package/dist/source-sync/types.js +14 -0
- package/dist/source-sync/workspace.d.ts +66 -0
- package/dist/source-sync/workspace.js +273 -0
- package/dist/store/agent-body.d.ts +6 -2
- package/dist/store/agent-body.js +18 -7
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/schema.d.ts +2 -1
- package/dist/store/schema.js +2 -1
- package/dist/store/seal.d.ts +5 -1
- package/dist/store/seal.js +12 -3
- package/dist/store/sqlite/project-checkpoints.d.ts +11 -0
- package/dist/store/sqlite/project-checkpoints.js +70 -0
- package/dist/store/sqlite/run-launch.d.ts +4 -12
- package/dist/store/sqlite/run-launch.js +5 -19
- package/dist/store/sqlite/store.js +224 -170
- package/dist/store/store.d.ts +116 -39
- package/dist/store/store.js +14 -1
- package/dist/store-reads/learning.d.ts +2 -2
- package/dist/store-view.d.ts +3 -1
- package/dist/store-view.js +17 -5
- package/dist/suggestions.d.ts +282 -0
- package/dist/suggestions.js +919 -0
- package/dist/telemetry.d.ts +8 -1
- package/dist/telemetry.js +12 -4
- package/dist/template-import.d.ts +27 -2
- package/dist/template-import.js +148 -13
- package/dist/templates.d.ts +103 -77
- package/dist/templates.js +71 -17
- package/dist/timeline/index.d.ts +1 -1
- package/dist/timeline/index.js +1 -1
- package/dist/timeline/timeline.d.ts +5 -0
- package/dist/timeline/timeline.js +8 -0
- package/dist/tool-plane.d.ts +12 -12
- package/dist/tools.d.ts +8 -8
- package/dist/trigger-launch-hook.d.ts +49 -0
- package/dist/trigger-launch-hook.js +91 -0
- package/dist/trigger-targets.d.ts +14 -1
- package/dist/trigger-targets.js +20 -0
- package/dist/triggers.d.ts +54 -5
- package/dist/triggers.js +143 -8
- package/dist/uploads-archil.js +1 -1
- package/dist/uploads.js +1 -1
- package/dist/validate.d.ts +1 -1
- package/dist/validate.js +3 -4
- package/dist/workspace/computer-for-claim.d.ts +2 -0
- package/dist/workspace/computer-for-claim.js +43 -0
- package/dist/workspace/paths.d.ts +6 -0
- package/dist/workspace/paths.js +6 -0
- package/dist/workspace/resolve-computer.d.ts +1 -0
- package/dist/workspace/run-tools.d.ts +2 -0
- package/dist/workspace/run-tools.js +8 -0
- package/dist/workspace/synced-folder.d.ts +1 -1
- package/dist/workspace/synced-folder.js +11 -14
- package/launcher/agentrun-serve +1 -1
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +2 -1
- package/templates/README.md +8 -4
- package/templates/agent-scout/agent.md +46 -0
- package/templates/agent-scout/skills/scout/SKILL.md +88 -0
- package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
- package/dist/console/assets/index-B-D0EM3j.js +0 -733
- package/dist/console/assets/index-DlQepP2J.css +0 -1
package/dist/server.js
CHANGED
|
@@ -1,9 +1,20 @@
|
|
|
1
|
+
import { prepareProjectSkillEdit } from "./source-sync/skill-edits.js";
|
|
2
|
+
import { sourceSyncOf } from "./source-sync/types.js";
|
|
3
|
+
import { sourceService, SOURCE_BODY_BYTES } from "./source-sync/service.js";
|
|
4
|
+
import { destinationPreparation, bindSourceTool } from "./source-sync/destination.js";
|
|
5
|
+
import { prepareSource, SourcePreparationError } from "./source-sync/prepare.js";
|
|
6
|
+
import { SnapshotError, validateSourceSnapshot } from "./source-sync/snapshots.js";
|
|
7
|
+
import { cliAdoptionResolver } from "./source-sync/adoption.js";
|
|
8
|
+
import { projectPlacement } from "./source-sync/projects.js";
|
|
9
|
+
import { auxiliaryAdmitter } from "./source-sync/auxiliary.js";
|
|
10
|
+
import { openRunPlacement, sourceSnapshotReader } from "./source-sync/workspace.js";
|
|
11
|
+
import { SOURCE_FAILURES, configurationDigest } from "./source-sync/registry.js";
|
|
1
12
|
import { CliLearningConnections } from "./cli-learning/connections.js";
|
|
2
13
|
import { ObservationLearning } from "./observation/learning.js";
|
|
3
14
|
import { cliLearningOf } from "./store/agent-body.js";
|
|
4
15
|
import { maintainObservations, Observations } from './observation/observer.js';
|
|
5
16
|
import { isObservationRoute, observationHttp } from './observation/http.js';
|
|
6
|
-
import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
|
|
17
|
+
import { SDK_MAX_OPEN_MS, SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
|
|
7
18
|
import { learningModelOf } from "./learning-model.js";
|
|
8
19
|
import { answerSkill } from './skill-route.js';
|
|
9
20
|
import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
|
|
@@ -18,7 +29,9 @@ import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
|
18
29
|
import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
|
|
19
30
|
import { createServer } from "node:http";
|
|
20
31
|
import proxyaddr from "proxy-addr";
|
|
21
|
-
import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
|
|
32
|
+
import { API_ONLY_HOOKED_KINDS, apiOnlyRefusal, apiOnlyTriggerSkipped, servedApiOnly } from "./api-only.js";
|
|
33
|
+
import { RUN_KEYS_ENV } from "./env-switch.js";
|
|
34
|
+
import { declaredKeys, keysOwed, keysOwedRefusal, packageKeysOf, runKeysOf, runKeysTriggerSkipped, undeclaredKeys, withCarried } from "./run-keys.js";
|
|
22
35
|
import { capacityOverStore, capacityWindowOf } from "./capacity.js";
|
|
23
36
|
import { carriedFields } from "./answer-json.js";
|
|
24
37
|
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
@@ -29,7 +42,9 @@ import { existsSync } from "node:fs";
|
|
|
29
42
|
import { rm } from "node:fs/promises";
|
|
30
43
|
import { homedir, hostname } from "node:os";
|
|
31
44
|
import { pinFirst as pinFirstOf } from "./mcp-pin-first.js";
|
|
32
|
-
import {
|
|
45
|
+
import { agentPackage } from "./agent-package.js";
|
|
46
|
+
import { uuidv7 } from "./ids.js";
|
|
47
|
+
import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, definitionOf, etagOf, externalKey, getAgent, listAgents, makeRevision, ownedElsewhere, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
|
|
33
48
|
import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
|
|
34
49
|
import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
|
|
35
50
|
import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
|
|
@@ -43,7 +58,7 @@ import { DATA_ENV, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
|
|
|
43
58
|
import { homePath, hostOwnedOf } from "./home-path.js";
|
|
44
59
|
import { chooseModel, EFFORTS, FAUX_ENV, FAUX_UPSTREAM_ENV, MODEL_NODES, modelSource, THINKING_LEVELS, unpricedModels, withoutFaux } from "./model.js";
|
|
45
60
|
import { DEFAULT_HARNESS, HARNESSES, harnessOfBody, harnessOffers } from "./harness.js";
|
|
46
|
-
import { HARNESS_MODULES_ENV, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, tableIds } from "./harness-table.js";
|
|
61
|
+
import { HARNESS_MODULES_ENV, HARNESS_MODULES_SETTING, HARNESS_RECIPES_ENV, HARNESS_RECIPES_SETTING, HARNESS_TABLE_ENV, harnessIds, harnessModulesEnv, harnessOf, harnessRecipesEnv, recipeHarness, tableIds } from "./harness-table.js";
|
|
47
62
|
import { claudeCliIn, HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./harness-install.js";
|
|
48
63
|
import { DEFAULT_PORT, healthOf, hostMemory, maxRunsOf, runsThatFit } from "./host.js";
|
|
49
64
|
import { DEFAULT_HOST, elsewhereOf, listenOn, minFreeMibOf, takeOver, urlOf } from "./listen-first.js";
|
|
@@ -51,7 +66,8 @@ import { IMPORT_ASKED, MAX_CANDIDATES } from "./import.js";
|
|
|
51
66
|
import { answerStoreCall } from "./import-proxy.js";
|
|
52
67
|
import { LEARNING_LABEL, learningFolderOf, secretsShown, learningOf, learnsOf, RUN_LEARNING_USE, seedOf, withAgentRepo } from "./learning.js";
|
|
53
68
|
import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
|
|
54
|
-
import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
|
|
69
|
+
import { agentLearning, changeWorkflow, correctionsView, correctionsWrite, forgetRunLearning, learningLog, pendingCount, readLearnedFile, sendText, statusesOf, textBody, workflowAtDigest, workflowRevisions } from "./learning-routes.js";
|
|
70
|
+
import { purgedRun } from "./purged-workflow.js";
|
|
55
71
|
import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
|
|
56
72
|
import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
|
|
57
73
|
import { boxAvailability, boxesLine, defaultPlaceOf, NEW_AGENT_TOOLS, newAgentPlace, noBoxReason, placesOf, resolvePlace } from "./place.js";
|
|
@@ -73,6 +89,10 @@ import { keepPresence, refusedEnd, runnersRefused } from "./runner/presence.js";
|
|
|
73
89
|
import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
|
|
74
90
|
import { builtOfNow, factsOverStore, listedItem, lookingBackEnd, momentOverStore, summaryOverStore, timelineOverStore, toolsUsdOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
|
|
75
91
|
import { healEndedCosts } from "./cost-heal.js";
|
|
92
|
+
import { reconcileProjectCheckpoints } from "./source-sync/checkpoints.js";
|
|
93
|
+
import { acknowledgeProjects } from "./source-sync/checkpoint-gate.js";
|
|
94
|
+
import { LocalSources } from "./source-sync/local.js";
|
|
95
|
+
import { beginSourceIO } from "./source-sync/io.js";
|
|
76
96
|
import { createLister } from "./run-listing.js";
|
|
77
97
|
import { HELD_WAITS } from "./runner/journal-kinds.js";
|
|
78
98
|
import { servedTimelineRows } from "./run-timeline-served.js";
|
|
@@ -119,7 +139,7 @@ import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
|
|
|
119
139
|
import { isSecretWriteOperation, secretPageFor, secretsWritableFields, secretWriteRefusal, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
|
|
120
140
|
import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
|
|
121
141
|
import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-gateway.js";
|
|
122
|
-
import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
|
|
142
|
+
import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, loopback, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
|
|
123
143
|
import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
|
|
124
144
|
import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
|
|
125
145
|
import { recordDataRoot } from "./runner/disk-free.js";
|
|
@@ -139,7 +159,7 @@ import { signInsOverStore } from "./sign-ins-store.js";
|
|
|
139
159
|
import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
|
|
140
160
|
import { composioMadeKey, composioPerRun } from "./composio-made.js";
|
|
141
161
|
import { COMPOSIO_PER_RUN, composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
|
|
142
|
-
import { ComposioTriggers } from "./composio-triggers.js";
|
|
162
|
+
import { ComposioTriggers, composioNoPublicUrl } from "./composio-triggers.js";
|
|
143
163
|
import { loopbackWords, mcpServersOverStore } from "./mcp-servers-store.js";
|
|
144
164
|
import { MCP_ALLOW_LOOPBACK_ENV, startSwitches, WEBHOOK_PRIVATE_TARGETS_ENV } from "./start-switches.js";
|
|
145
165
|
import { getMcpServer, listMcpServers } from "./mcp-store.js";
|
|
@@ -154,6 +174,7 @@ import { templateApplied, templateTriggerSecret, templateWebhookSecrets, trigger
|
|
|
154
174
|
import { openServerSecretsOverStore } from "./server-secrets-store.js";
|
|
155
175
|
import { HOOK_TOLERANCE_S } from "./standard-webhooks.js";
|
|
156
176
|
import { GitHubConnect, GitHubConnection, INSTALLED_PATH, startedHere as gitHubStartedHere, stateCookie } from "./github-connection.js";
|
|
177
|
+
import { SCOUT_TEMPLATE, Suggestions } from "./suggestions.js";
|
|
157
178
|
import { FAUX_GITHUB, FAUX_GITHUB_FILE, startFauxGitHub } from "./github-faux.js";
|
|
158
179
|
import { GITHUB_API } from "./github.js";
|
|
159
180
|
import { bindingOf, REPO_NAME } from "./run-repo.js";
|
|
@@ -167,9 +188,9 @@ import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
|
|
|
167
188
|
import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
|
|
168
189
|
import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
|
|
169
190
|
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";
|
|
170
|
-
import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
|
|
171
|
-
import { templateInstallLink, templateLink } from "./console-links.js";
|
|
172
|
-
import { GITHUB_HOSTS } from "./template-source.js";
|
|
191
|
+
import { applyImported, deleteTemplate, dropRemovedUploads, importTemplate, loadImported, UPLOAD_PREFIX } from "./template-import.js";
|
|
192
|
+
import { templateInstallLink, templateLink, templatesLink } from "./console-links.js";
|
|
193
|
+
import { GITHUB_HOSTS, IMPORT_LIMITS } from "./template-source.js";
|
|
173
194
|
import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, inputSchemaOf, isObject, stable, unknownFields } from "./validate.js";
|
|
174
195
|
import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, loadToolSettings, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
|
|
175
196
|
import { wakeAnsweredBySetting } from "./settings-wake.js";
|
|
@@ -194,12 +215,12 @@ import { noAccount, openAccount } from "./email/account.js";
|
|
|
194
215
|
import { emailRoute } from "./email/routes.js";
|
|
195
216
|
import { addressForms, openCalendar } from "./calendar/address.js";
|
|
196
217
|
import { calendarRoute } from "./calendar/routes.js";
|
|
197
|
-
import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, runDiskKept, runDiskKey } from "./archil-settings.js";
|
|
218
|
+
import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode, loadArchilSettings, runDiskKept, runDiskKey } from "./archil-settings.js";
|
|
198
219
|
import { computerOfPlace } from "./computer-setting.js";
|
|
199
220
|
import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
|
|
200
221
|
import { fauxComputers } from "./faux-computers.js";
|
|
201
222
|
import { writesHeld } from "./workspace.js";
|
|
202
|
-
import { deleteExternalAgent, oneAtATime, purgeAgent,
|
|
223
|
+
import { deleteExternalAgent, oneAtATime, purgeAgent, purgeRun, purgingKey } from "./agent-delete.js";
|
|
203
224
|
import { resetLearning } from "./learning-reset.js";
|
|
204
225
|
import { agentComputerHoldKey } from "./workspace/agent-computer.js";
|
|
205
226
|
import { sdkRunKey } from "./sdk/runs.js";
|
|
@@ -216,6 +237,9 @@ const IDEMPOTENCY_FILE = ".idempotency.json";
|
|
|
216
237
|
* computer kind; `browser`, the browser's own), then its page, files or WebSocket. Both are served by the same code. */
|
|
217
238
|
const LIVE_PATH = /^\/v2\/runs\/([^/]+)\/(computer|browser)\/live(\/.*)$/;
|
|
218
239
|
const MAX_BODY = 1 << 20;
|
|
240
|
+
/** POST /v2/templates/import's body: an upload's files at the import's own limit, base64 (4/3) with room for the JSON
|
|
241
|
+
* around them. */
|
|
242
|
+
const TEMPLATE_UPLOAD_BODY = Math.ceil((IMPORT_LIMITS.packageBytes * 4) / 3) + MAX_BODY;
|
|
219
243
|
/** The starts that may begin setup's import without ending it (a worker that failed, a process that ended) before the
|
|
220
244
|
* owner's yes is dropped: an import that fails the same way each time is not taken up at every start for good. */
|
|
221
245
|
const IMPORT_STARTS = 3;
|
|
@@ -249,7 +273,7 @@ const FAUX_SWITCHES = [["fauxBrowser", FAUX_BROWSER_ENV], ["fauxWeb", FAUX_WEB_E
|
|
|
249
273
|
* startInProcessRunner). */
|
|
250
274
|
export function fauxEnvOf(options) {
|
|
251
275
|
// The owner's harness modules too (not a test switch): a run's process reads the same table as the server.
|
|
252
|
-
const env = { ...harnessModulesEnv(options.harnessModules ?? [], options.data), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
|
|
276
|
+
const env = { ...harnessModulesEnv(options.harnessModules ?? [], options.data), ...harnessRecipesEnv(options.harnessRecipes ?? [], options.data, { signIn: options.harnessSignIn === true }), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}) };
|
|
253
277
|
if (!options.faux)
|
|
254
278
|
return env;
|
|
255
279
|
env[FAUX_ENV] = resolve(options.faux);
|
|
@@ -278,19 +302,6 @@ async function tokenIn(file) {
|
|
|
278
302
|
}
|
|
279
303
|
const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
|
|
280
304
|
const SESSION_S = SESSION_MS / 1000;
|
|
281
|
-
const isoOrNull = (ms) => (ms === null ? null : new Date(ms).toISOString());
|
|
282
|
-
/** 410 purged for a route of a purged run (Runs.purge): its tombstone, what is kept of it. `tools_usd`: its paid tools'
|
|
283
|
-
* meter as /usage read it at its purge (null: unknown, or none read). */
|
|
284
|
-
function purgedRun(row) {
|
|
285
|
-
const meters = row.metrics?.purged?.meters;
|
|
286
|
-
return new ApiError("purged", `The run ${row.id} was purged: what it was given and did is gone, and its cost stays in every total.`, {
|
|
287
|
-
details: {
|
|
288
|
-
run_id: row.id, agent_id: row.agentId, state: row.state, started_at: isoOrNull(row.startedAt), ended_at: isoOrNull(row.endedAt),
|
|
289
|
-
cost_usd: row.costUsd ?? row.costAtMostUsd, cost_upper_bound: row.costUsd === null && row.costAtMostUsd !== null, tools_usd: typeof meters?.tools === "number" ? meters.tools : null,
|
|
290
|
-
purged_at: isoOrNull(row.purgedAt),
|
|
291
|
-
},
|
|
292
|
-
});
|
|
293
|
-
}
|
|
294
305
|
export const ROUTES = [
|
|
295
306
|
{ method: "GET", pattern: /^\/observations$/, name: "getObservations" },
|
|
296
307
|
{ method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
|
|
@@ -299,6 +310,15 @@ export const ROUTES = [
|
|
|
299
310
|
{ method: "DELETE", pattern: /^\/connectors\/([^/]+)$/, name: "revokeRemoteConnector" },
|
|
300
311
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/import$/, name: "importRemoteTarget" },
|
|
301
312
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/history$/, name: "importRemoteHistory" },
|
|
313
|
+
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/sync\/grant$/, name: "grantSourceSync" },
|
|
314
|
+
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/sync$/, name: "publishSourceSync" },
|
|
315
|
+
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/sync\/status$/, name: "sourceSyncFailure" },
|
|
316
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/source$/, name: "getSourceSync" },
|
|
317
|
+
{ method: "PATCH", pattern: /^\/agents\/([^/]+)\/source$/, name: "setSourceSync" },
|
|
318
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/source\/move$/, name: "moveSourceAgent" },
|
|
319
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/source\/tools$/, name: "bindSourceTool" },
|
|
320
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/source\/resolve$/, name: "resolveSourceSync" },
|
|
321
|
+
{ method: "POST", pattern: /^\/agents\/([^/]+)\/source\/project-review$/, name: "reviewSourceProject" },
|
|
302
322
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
|
|
303
323
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
|
|
304
324
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
|
|
@@ -329,6 +349,7 @@ export const ROUTES = [
|
|
|
329
349
|
{ method: "DELETE", pattern: /^\/agents\/([^/]+)$/, name: "deleteAgent" },
|
|
330
350
|
{ method: "PUT", pattern: /^\/agents\/([^/]+)\/definition$/, name: "updateDefinition" },
|
|
331
351
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/revisions$/, name: "listRevisions" },
|
|
352
|
+
{ method: "GET", pattern: /^\/agents\/([^/]+)\/package$/, name: "getAgentPackage" },
|
|
332
353
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/current$/, name: "setCurrent" },
|
|
333
354
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/archive$/, name: "archiveAgent" },
|
|
334
355
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/unarchive$/, name: "unarchiveAgent" },
|
|
@@ -438,6 +459,7 @@ export const ROUTES = [
|
|
|
438
459
|
{ method: "DELETE", pattern: /^\/settings\/model-gateway$/, name: "deleteModelGateway" },
|
|
439
460
|
{ method: "POST", pattern: /^\/settings\/model-gateway\/test$/, name: "testModelGateway" },
|
|
440
461
|
{ method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
|
|
462
|
+
{ method: "GET", pattern: /^\/settings\/mcp-server-names$/, name: "listMcpServerNames" },
|
|
441
463
|
{ method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
|
|
442
464
|
{ method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
|
|
443
465
|
{ method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
|
|
@@ -483,6 +505,7 @@ export const ROUTES = [
|
|
|
483
505
|
{ method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
|
|
484
506
|
{ method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
|
|
485
507
|
{ method: "POST", pattern: /^\/templates\/import$/, name: "importTemplate" },
|
|
508
|
+
{ method: "GET", pattern: /^\/templates\/([^/]+)$/, name: "getTemplate" },
|
|
486
509
|
{ method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
|
|
487
510
|
{ method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
|
|
488
511
|
// Answered before the bearer check: the request's signature is its credential.
|
|
@@ -493,6 +516,14 @@ export const ROUTES = [
|
|
|
493
516
|
{ method: "POST", pattern: /^\/integrations\/github\/connect$/, name: "connectGitHub" },
|
|
494
517
|
{ method: "GET", pattern: /^\/integrations\/github\/callback$/, name: "gitHubCallback" },
|
|
495
518
|
{ method: "GET", pattern: /^\/integrations\/github\/installed$/, name: "gitHubInstalled" },
|
|
519
|
+
{ method: "GET", pattern: /^\/integrations\/github\/repositories$/, name: "listGitHubRepositories" },
|
|
520
|
+
// Suggested agents (suggestions.ts): what the agent-scout template finds in a repository, and what a person decides.
|
|
521
|
+
{ method: "GET", pattern: /^\/suggestions$/, name: "listSuggestions" },
|
|
522
|
+
{ method: "POST", pattern: /^\/suggestions\/scans$/, name: "scanForSuggestions" },
|
|
523
|
+
{ method: "GET", pattern: /^\/suggestions\/([^/]+)$/, name: "getSuggestion" },
|
|
524
|
+
{ method: "POST", pattern: /^\/suggestions\/([^/]+)\/discard$/, name: "discardSuggestion" },
|
|
525
|
+
{ method: "POST", pattern: /^\/suggestions\/([^/]+)\/restore$/, name: "restoreSuggestion" },
|
|
526
|
+
{ method: "POST", pattern: /^\/suggestions\/([^/]+)\/create$/, name: "createSuggestedAgent" },
|
|
496
527
|
// Answered before routing (mcp.ts), with the token only: listed here for the document.
|
|
497
528
|
{ method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
|
|
498
529
|
{ method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
|
|
@@ -736,6 +767,8 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced, le
|
|
|
736
767
|
* URL kept sealed, never shown. */
|
|
737
768
|
slack: { routes: true, events: [...SLACK_EVENTS], at_rest: "sealed" },
|
|
738
769
|
/** /triggers: what starts an agent's capped runs with no caller (triggers.ts). */
|
|
770
|
+
/** A backend SDK run's start (sdk/runs.ts): the fields it takes, and the most seconds it stays open. */
|
|
771
|
+
sdk_runs: { started_at: true, title: true, labels: true, max_open_s: SDK_MAX_OPEN_MS / 1000 },
|
|
739
772
|
triggers: { routes: true, sources: [...SOURCE_KINDS], targets: [...TARGET_KINDS], min_every_s: MIN_EVERY_S, history_kept: HISTORY_KEPT, catchup_window_s: CATCHUP_WINDOW_S, failures_to_pause: FAILURES_TO_PAUSE, webhook: { signing: "standard-webhooks/v1", signatures: [...SCHEME_NAMES], tolerance_s: HOOK_TOLERANCE_S, max_body_bytes: webhook.push.maxBodyBytes, payload_kept_bytes: PAYLOAD_KEPT_BYTES, at_rest: "sealed" } },
|
|
740
773
|
},
|
|
741
774
|
regions: [{ id: "local", jurisdiction: null, state: "live" }],
|
|
@@ -788,6 +821,29 @@ function integerParam(value, name, max) {
|
|
|
788
821
|
throw new ApiError("bad_request", `${name} is an integer from 0 to ${max}`);
|
|
789
822
|
return Number(value);
|
|
790
823
|
}
|
|
824
|
+
/** A start with --harness-sign-in on a server that is not one owner's own, on their own machine. */
|
|
825
|
+
export const HARNESS_SIGN_IN_NOT_LOCAL = "HARNESS_SIGN_IN_NOT_LOCAL";
|
|
826
|
+
/** Why `options` on `data` may not run a recipe on its owner's own sign-in (--harness-sign-in), in words; undefined when
|
|
827
|
+
* it may. One owner's own server on their own machine: it listens on loopback alone, with no public address; its store
|
|
828
|
+
* is the SQLite one in its data directory (no AGENTRUN_STORE_URL, which servers elsewhere share); its runs run beside
|
|
829
|
+
* it as its own user (`ownUser`: runIsolationOf's `process`), never under --no-runner or a user of their own; and one
|
|
830
|
+
* person starts them, as Claude Code's login on this machine asks (claude-login.ts whyNotOneOwner): an owner, and one
|
|
831
|
+
* API token. A check, a schedule and a shared server run on a key (HARNESS.md#sign-in). */
|
|
832
|
+
export function harnessSignInRefusal(options, data, ownUser) {
|
|
833
|
+
const host = options.host ?? DEFAULT_HOST;
|
|
834
|
+
// Every token the server takes (acceptedTokens): AGENTRUN_TOKEN's as `default` beside the list's, or else DIR/.token's alone.
|
|
835
|
+
const tokens = (options.token === undefined ? 0 : 1) + (options.tokens?.length ?? 0);
|
|
836
|
+
const why = [
|
|
837
|
+
...(loopback(host) ? [] : [`listens on ${host}, past loopback`]),
|
|
838
|
+
...(options.publicUrl ? [`has a public address (${options.publicUrl})`] : []),
|
|
839
|
+
...(options.apiOnly ? ["has no owner (the API-only profile), so anyone with its token starts runs"] : []),
|
|
840
|
+
...(tokens > 1 ? [`takes ${tokens} API tokens (AGENTRUN_TOKEN and AGENTRUN_TOKENS together), so more than one person starts runs`] : []),
|
|
841
|
+
...(storeTarget(data).kind === "sqlite" ? [] : ["keeps its store in Postgres (AGENTRUN_STORE_URL), which servers elsewhere share"]),
|
|
842
|
+
...(options.runnerApart ? ["runs no runner beside it (--no-runner)"] : []),
|
|
843
|
+
...(ownUser ? [] : ["runs each run as a user of its own (unset AGENTRUN_RUN_USER=slot, or set AGENTRUN_RUN_USER=same)"]),
|
|
844
|
+
];
|
|
845
|
+
return why.length ? `${HARNESS_SIGN_IN_NOT_LOCAL}: --harness-sign-in runs a recipe on its owner's own sign-in on one owner's own machine alone, and this server ${why.join("; ")}. Start it without --harness-sign-in: its plan-billed recipes run on keys.` : undefined;
|
|
846
|
+
}
|
|
791
847
|
// A data directory an earlier version wrote (old agent homes, an old runs/ layout, or an earlier store version) is refused
|
|
792
848
|
// by the store itself when it opens (StoreFromEarlierVersion), in words, to start fresh: no pre-open scan, no migration.
|
|
793
849
|
export async function startServe(options) {
|
|
@@ -800,9 +856,17 @@ export async function startServe(options) {
|
|
|
800
856
|
// So is the harness modules list, from `harnessModules` alone (an operator names them with --harness-module or
|
|
801
857
|
// AGENTRUN_SERVE_HARNESS_MODULES, which the CLI reads into the option).
|
|
802
858
|
delete process.env[HARNESS_MODULES_ENV];
|
|
859
|
+
// And the recipes, from `harnessRecipes` alone (--harness-recipe or AGENTRUN_SERVE_HARNESS_RECIPES).
|
|
860
|
+
delete process.env[HARNESS_RECIPES_ENV];
|
|
803
861
|
await mkdir(resolve(options.data), { recursive: true, mode: 0o700 });
|
|
804
862
|
// Canonical once, here: a computer's mount source below it must then be its own canonical path, through no link.
|
|
805
863
|
const data = await realpath(resolve(options.data));
|
|
864
|
+
if (options.harnessSignIn) {
|
|
865
|
+
const { runsAsOwnUser } = await import("./runner/run-child-host.js");
|
|
866
|
+
const refused = harnessSignInRefusal(options, data, runsAsOwnUser(process.env));
|
|
867
|
+
if (refused)
|
|
868
|
+
throw new Error(refused);
|
|
869
|
+
}
|
|
806
870
|
const tokenRefused = options.token === undefined ? undefined : tokenProblem(options.token);
|
|
807
871
|
if (tokenRefused)
|
|
808
872
|
throw new Error(tokenRefused);
|
|
@@ -895,7 +959,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
895
959
|
// shown nowhere.
|
|
896
960
|
let secretStores;
|
|
897
961
|
let triggerSettings = new Map();
|
|
898
|
-
const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data) };
|
|
962
|
+
const base = { ...withoutFaux(process.env), [DATA_ENV]: data, ...(options.allowCodeNodes ? { [CODE_NODES_ENV]: "1" } : {}), ...(options.faux ? { [FAUX_ENV]: resolve(options.faux) } : {}), ...(options.harnessTable ? { [HARNESS_TABLE_ENV]: resolve(options.harnessTable) } : {}), ...harnessModulesEnv(options.harnessModules ?? [], data), ...harnessRecipesEnv(options.harnessRecipes ?? [], data, { signIn: options.harnessSignIn === true }) };
|
|
899
963
|
// The table, loaded once here: a harness module that is missing, names a built-in harness or gives half an entry refuses
|
|
900
964
|
// the start, in words, before anything else opens.
|
|
901
965
|
// The harness ids a definition may name here: the table's, the built-in ones and those the modules add, and one the
|
|
@@ -971,7 +1035,14 @@ async function startHolding(options, data, checked, stops) {
|
|
|
971
1035
|
// runner/runner-check.ts): this data root's id, and the names (never the values) of the run-facing environment this
|
|
972
1036
|
// server holds, each said in the store at every start, replacing the last start's.
|
|
973
1037
|
await recordDataRoot(store, data);
|
|
974
|
-
|
|
1038
|
+
// Harness modules and recipes this start was given as options (--harness-module, --harness-recipe) are said under the
|
|
1039
|
+
// setting a runner apart reads them from, as an exported setting is: a runner without them would claim their runs and
|
|
1040
|
+
// have no harness to run them on.
|
|
1041
|
+
const startedWith = {
|
|
1042
|
+
[HARNESS_MODULES_SETTING]: options.harnessModules?.length ? options.harnessModules.join(",") : undefined,
|
|
1043
|
+
[HARNESS_RECIPES_SETTING]: options.harnessRecipes?.length ? options.harnessRecipes.join(",") : undefined,
|
|
1044
|
+
};
|
|
1045
|
+
await recordRunEnv(store, runFacingNames((name) => startedWith[name] ?? secret(name) ?? base[name], Object.keys(base)));
|
|
975
1046
|
// Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
|
|
976
1047
|
// the proxy's proof under the seal key (live-reach.ts); any other host is never dialled. A hosted machine a runner in a
|
|
977
1048
|
// process of its own made is relayed to that runner's attach listener the same way (dial-relay.ts).
|
|
@@ -1028,7 +1099,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1028
1099
|
// with whether each can be granted: a known meta tool can't (mcp-meta.ts).
|
|
1029
1100
|
const mcpTools = (server) => {
|
|
1030
1101
|
const saved = mcpMeta.get(server);
|
|
1031
|
-
return saved && marked(saved.url, { tools: saved.tools.map(
|
|
1102
|
+
return saved && marked(saved.url, { tools: saved.tools.map(boundTool) }).tools;
|
|
1032
1103
|
};
|
|
1033
1104
|
// The server's tool settings, in the store: capabilities say what they resolve to, again after a PUT. load() reads them
|
|
1034
1105
|
// once here.
|
|
@@ -1279,9 +1350,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1279
1350
|
/** The shell this server can give a template's agent now (templates.ts pickComputer's `shell`), by the rules a run
|
|
1280
1351
|
* has it by (shellOf): Archil's serverless exec on the runner in Mode 2 (bash alone); else the box a new agent is saved
|
|
1281
1352
|
* with (Docker), where it answers now (computerReady asks the daemon, not the start's offers: a Docker stopped since
|
|
1282
|
-
* is no shell), whose shell runs the shell tools; else none, and why.
|
|
1283
|
-
|
|
1284
|
-
|
|
1353
|
+
* is no shell), whose shell runs the shell tools; else none, and why. A package that needs programs (`sandbox`) asks
|
|
1354
|
+
* for a sandbox alone, whose box a run checks for them: Archil's exec is none, so in Mode 2 it is told why no sandbox
|
|
1355
|
+
* answers (the Docker box can't mount Archil's workspaces), never given the exec. */
|
|
1356
|
+
const shellHere = async (wants = {}) => {
|
|
1357
|
+
const exec = (await shellOf({ kind: "none" })) === "local";
|
|
1358
|
+
if (exec && !wants.sandbox)
|
|
1285
1359
|
return { computer: { kind: "none" }, tools: [...shellTools("local")], words: "Archil's serverless exec" };
|
|
1286
1360
|
const fresh = newAgentPlace(boxOffers);
|
|
1287
1361
|
let why = "why" in fresh ? fresh.why : "it is not set up";
|
|
@@ -1293,14 +1367,18 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1293
1367
|
else if ((await shellOf(computer)) === "computer")
|
|
1294
1368
|
return { computer, tools: [...shellTools("computer")], words: `the ${fresh.place.box} sandbox` };
|
|
1295
1369
|
}
|
|
1370
|
+
if (exec)
|
|
1371
|
+
return { none: `no sandbox answers here: Archil's serverless exec is no sandbox, and the docker box is unavailable here (${why})` };
|
|
1296
1372
|
return { none: `this server has no shell to give an agent now: Archil is off (Settings → Workspace), and the docker box is unavailable here (${why})` };
|
|
1297
1373
|
};
|
|
1298
1374
|
/** Each package's computer list read against this server now, as a listing shows it (`computer_here`): what an apply
|
|
1299
1375
|
* here would pick (pickComputer), the shell asked for once for them all. */
|
|
1300
1376
|
const computerHere = async (packages) => {
|
|
1301
|
-
const here = packages.some((one) => one.computer) ? await shellHere() : undefined;
|
|
1377
|
+
const here = packages.some((one) => one.computer && !one.needs) ? await shellHere() : undefined;
|
|
1378
|
+
const sandbox = packages.some((one) => one.computer && one.needs) ? await shellHere({ sandbox: true }) : undefined;
|
|
1302
1379
|
return (pkg) => {
|
|
1303
|
-
const
|
|
1380
|
+
const shell = pkg.needs ? sandbox : here;
|
|
1381
|
+
const pick = shell && pickComputer(pkg, shell);
|
|
1304
1382
|
if (!pick)
|
|
1305
1383
|
return null;
|
|
1306
1384
|
if ("refused" in pick)
|
|
@@ -1525,7 +1603,65 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1525
1603
|
refusedTimer.unref();
|
|
1526
1604
|
// The runner beside this server, when its run isolation was refused (cli.ts): its word, kept in this store until the stop.
|
|
1527
1605
|
let refusedBeside;
|
|
1606
|
+
const sourceWorkspaces = { data, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl ? { control: options.archilControl } : {}) };
|
|
1607
|
+
const localSources = new LocalSources(store, { secrets: () => [...serverSecrets(), sdkSecret, ...tokens.map(entry => entry.token)] });
|
|
1608
|
+
const sources = sourceService(store, sourceWorkspaces, async (entry, snapshot) => {
|
|
1609
|
+
const prepared = await prepareSource(snapshot, destinationPreparation(store, entry.agent.id, {
|
|
1610
|
+
env: () => env, boxes: () => boxOffers, check: revision => saveable(revision),
|
|
1611
|
+
// Readiness needs a successful probe, not capabilities' display fallback after a failed helper check.
|
|
1612
|
+
// A different runner repeats this prerequisite at claim, before its ownership helper changes any bytes/modes.
|
|
1613
|
+
projectExecution: async () => ({ isolation: runIsolationName(await runIsolationOf(base, 1, () => { })),
|
|
1614
|
+
storage: await loadArchilSettings(store, sourceWorkspaces.env) ? "archil" : "local" }),
|
|
1615
|
+
}));
|
|
1616
|
+
const prior = entry.revision?.body;
|
|
1617
|
+
// Main's corrections/workflow setting remains the owner's choice across the ownership cutover.
|
|
1618
|
+
return prior?.learning === undefined ? prepared : { ...prepared, revision: { ...prepared.revision,
|
|
1619
|
+
body: { ...prepared.revision.body, learning: prior.learning } } };
|
|
1620
|
+
}, async (entry, snapshot, prepared) => {
|
|
1621
|
+
const record = await sources.sync.get(entry.agent.id);
|
|
1622
|
+
if (!record)
|
|
1623
|
+
throw new ApiError("precondition_failed", "The source sync connection changed during preparation.");
|
|
1624
|
+
const revision = { ...prepared.revision, body: { ...prepared.revision.body, sourceSync: {
|
|
1625
|
+
id: record.id, snapshot: snapshot.digest, project: snapshot.digest, configuration: configurationDigest(prepared.revision.body),
|
|
1626
|
+
} } };
|
|
1627
|
+
// This private, unadmitted probe verifies the actual destination's modes, Git and assets before ownership moves.
|
|
1628
|
+
const placed = await sourceProjects.place({ agentId: entry.agent.id, runId: uuidv7(), revision,
|
|
1629
|
+
launch: { input: "", title: "Source preparation", place: resolvePlace(prepared.revision.body.place, { mode: "runner" }) } });
|
|
1630
|
+
await placed?.undo();
|
|
1631
|
+
}, agentId => localSources.authorize(agentId));
|
|
1632
|
+
const sourceProjects = projectPlacement({ snapshots: agentId => sourceSnapshotReader(store, agentId, sourceWorkspaces),
|
|
1633
|
+
hold: ({ agentId }) => beginSourceIO(store, agentId, "placement"),
|
|
1634
|
+
destination: target => openRunPlacement(store, target, sourceWorkspaces),
|
|
1635
|
+
placeUploads: async ({ runId, launch, workspace }) => {
|
|
1636
|
+
const { files, bytesOf } = await uploads.heldFiles(runId, launch.files ?? []);
|
|
1637
|
+
await uploads.copyInto(workspace, files, bytesOf);
|
|
1638
|
+
await uploads.release(runId);
|
|
1639
|
+
} });
|
|
1640
|
+
const localSourcePublisher = localSources.publisher(sources.sync, { agentWrite: (id, call) => agentWrite(id, call) });
|
|
1641
|
+
let localSourceSweep = Promise.resolve(), localSourceBusy = false;
|
|
1642
|
+
const sweepLocalSources = () => {
|
|
1643
|
+
if (localSourceBusy || stopping.signal.aborted)
|
|
1644
|
+
return localSourceSweep;
|
|
1645
|
+
localSourceBusy = true;
|
|
1646
|
+
localSourceSweep = localSourcePublisher.tick(stopping.signal).then(() => undefined).catch(() => {
|
|
1647
|
+
if (!stopping.signal.aborted)
|
|
1648
|
+
process.stderr.write("agentrun-serve: source setup sync could not finish; the last complete snapshot is retained. Check the source status and connection.\n");
|
|
1649
|
+
}).finally(() => { localSourceBusy = false; });
|
|
1650
|
+
return localSourceSweep;
|
|
1651
|
+
};
|
|
1652
|
+
const localSourceTimer = setInterval(() => void sweepLocalSources(), 30_000);
|
|
1653
|
+
localSourceTimer.unref();
|
|
1528
1654
|
const startDeps = {
|
|
1655
|
+
project: { ...sourceProjects, place: async (given) => {
|
|
1656
|
+
try {
|
|
1657
|
+
return await sourceProjects.place(given);
|
|
1658
|
+
}
|
|
1659
|
+
catch (error) {
|
|
1660
|
+
if (error instanceof SnapshotError)
|
|
1661
|
+
throw new ApiError("agent_not_runnable", error.message);
|
|
1662
|
+
throw error;
|
|
1663
|
+
}
|
|
1664
|
+
} },
|
|
1529
1665
|
// A start while every runner here refused to claim is refused in their words (runner/presence.ts).
|
|
1530
1666
|
runnersRefused: refusedNow,
|
|
1531
1667
|
runBodyIssues,
|
|
@@ -1596,6 +1732,12 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1596
1732
|
return [...serverSecrets(), ...pointers];
|
|
1597
1733
|
};
|
|
1598
1734
|
const learningShown = async (agentId) => secretsShown(await learningValues(agentId));
|
|
1735
|
+
// Which runs a learning folder's log names are purged, by each one's row (its purge time): the history reads serve none
|
|
1736
|
+
// of their merges.
|
|
1737
|
+
const purgedOf = async (runIds) => {
|
|
1738
|
+
const rows = await Promise.all(runIds.map((runId) => store.runs.get(runId)));
|
|
1739
|
+
return new Set(runIds.filter((_, i) => rows[i] !== undefined && rows[i].purgedAt !== null));
|
|
1740
|
+
};
|
|
1599
1741
|
// The agent's audit ledger on its learning folder's main (learn/audit.ts), oldest first.
|
|
1600
1742
|
const auditsOfAgent = async (agentId) => {
|
|
1601
1743
|
const { workspace, end } = learningFolderOf(data, agentId);
|
|
@@ -1652,6 +1794,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1652
1794
|
getAgent: async (agentId) => (await getAgent(store, agentId)) ?? undefined,
|
|
1653
1795
|
needAgent,
|
|
1654
1796
|
momentOf: (runId) => momentOverStore(store, runId, viewDepsFor(ownOriginOf())),
|
|
1797
|
+
// A trigger never messages a run on a plan-billed recipe: its turn would run on its owner's own sign-in.
|
|
1798
|
+
planRecipe: (harness) => recipeHarness(base, harness) === "plan",
|
|
1655
1799
|
// Read when a firing's message is sent (declared below, with the delete turn).
|
|
1656
1800
|
runWrite: (agentId, runId, work) => runWrite(agentId, runId, work),
|
|
1657
1801
|
runStatus: async (runId) => (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())))?.status ?? null,
|
|
@@ -1664,6 +1808,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1664
1808
|
const carried = typeof view.revision === "string" ? carriedFields((await store.agents.revision(view.revision))?.body?.outputSchema) : undefined;
|
|
1665
1809
|
return { output: view.result?.output ?? null, endedAt: view.ended_at ?? null, ...(carried ? { carried } : {}) };
|
|
1666
1810
|
},
|
|
1811
|
+
// Read as the server's environment stands now (a saved key changes it).
|
|
1812
|
+
...(options.runKeys ? { keysOwed: (revision) => keysOwed(revision, env, []) } : {}),
|
|
1813
|
+
hooked: options.launchHook !== undefined,
|
|
1667
1814
|
};
|
|
1668
1815
|
const targets = triggerTargets(store, triggerDeps);
|
|
1669
1816
|
// Every presented token is checked here, against every token the server takes, in constant time (api-token.ts). The id
|
|
@@ -1773,14 +1920,15 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1773
1920
|
const was = options.faux && options.fauxGitHub ? github.view() : undefined;
|
|
1774
1921
|
if (was && was.slug !== FAUX_GITHUB.slug)
|
|
1775
1922
|
throw new Error(`--faux-github connects a fake GitHub App, and this data directory has the GitHub App ${was.slug} connected: use a scratch data directory.`);
|
|
1776
|
-
|
|
1923
|
+
// Its repository as a bare git repository beside the data, so a run's checkout of it (agent-scout's) stays on this machine.
|
|
1924
|
+
const fauxGitHub = options.faux && options.fauxGitHub ? await startFauxGitHub({ webDir: join(data, "faux-github-web") }) : undefined;
|
|
1777
1925
|
if (fauxGitHub) {
|
|
1778
1926
|
stops.push(() => fauxGitHub.close());
|
|
1779
1927
|
if (was)
|
|
1780
1928
|
await github.remove();
|
|
1781
1929
|
await github.save(fauxGitHub.app);
|
|
1782
1930
|
await github.setInstallations([{ id: FAUX_GITHUB.installation, account: FAUX_GITHUB.account }]);
|
|
1783
|
-
await writeFile(join(data, FAUX_GITHUB_FILE), `${JSON.stringify({ webhook_secret: fauxGitHub.app.webhookSecret, installation: FAUX_GITHUB.installation, account: FAUX_GITHUB.account, repositories: FAUX_GITHUB.repositories })}\n`, { mode: 0o600 });
|
|
1931
|
+
await writeFile(join(data, FAUX_GITHUB_FILE), `${JSON.stringify({ webhook_secret: fauxGitHub.app.webhookSecret, installation: FAUX_GITHUB.installation, account: FAUX_GITHUB.account, repositories: FAUX_GITHUB.repositories, api_url: fauxGitHub.url })}\n`, { mode: 0o600 });
|
|
1784
1932
|
}
|
|
1785
1933
|
const githubConnect = new GitHubConnect(github, { ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}), api: fauxGitHub?.url ?? options.githubApi ?? GITHUB_API, say: (fields) => log?.(logLine("github", fields)) });
|
|
1786
1934
|
/** The connection a GitHub template or the console reads: the App's id, slug and installations, never a secret. */
|
|
@@ -1790,7 +1938,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1790
1938
|
// A template import reads GitHub's own hosts alone (a test's faux GitHub in their place), with an installation token of
|
|
1791
1939
|
// the App when GitHub is connected (tokenForListing: metadata read, the least there is), else anonymously, and says why.
|
|
1792
1940
|
const importDeps = {
|
|
1793
|
-
registry, store,
|
|
1941
|
+
registry, store, apiOnly: options.apiOnly === true,
|
|
1794
1942
|
reach: async (signal) => {
|
|
1795
1943
|
const api = options.templateImportApi ?? GITHUB_API;
|
|
1796
1944
|
const hosts = options.templateImportApi ? [new URL(options.templateImportApi).host] : GITHUB_HOSTS;
|
|
@@ -1798,11 +1946,50 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1798
1946
|
return "token" in minted ? { api, hosts, token: minted.token } : { api, hosts, anonymous: "unusable" in minted ? minted.unusable : minted.failed };
|
|
1799
1947
|
},
|
|
1800
1948
|
};
|
|
1949
|
+
// Suggested agents (suggestions.ts): scans run the bundled agent-scout, applied once and reused (one apply at a time
|
|
1950
|
+
// on this server); a create pushes through the App's token for the one repository, then applies the package it pushed
|
|
1951
|
+
// as an imported template, so the agent here is made from the very files the pull request adds.
|
|
1952
|
+
let scouting;
|
|
1953
|
+
const suggestions = new Suggestions({
|
|
1954
|
+
settings: store.settings,
|
|
1955
|
+
github: { view: () => github.view(), settingsUrl: () => github.settingsUrl(), get api() { return githubConnect.api; }, repoInstallation: (repo, signal) => githubConnect.repoInstallation(repo, signal), tokenWith: (installation, repo, permissions, signal) => githubConnect.tokenWith(installation, repo, permissions, signal), revokeToken: (token) => githubConnect.revokeToken(token) },
|
|
1956
|
+
scoutAgent: () => (scouting ??= (async () => {
|
|
1957
|
+
const mine = (await agents.list()).find((one) => one.template?.id === SCOUT_TEMPLATE && !one.agent.archivedAt);
|
|
1958
|
+
if (mine)
|
|
1959
|
+
return mine.agent.id;
|
|
1960
|
+
const pkg = registry.get(SCOUT_TEMPLATE);
|
|
1961
|
+
if (!pkg)
|
|
1962
|
+
throw new ApiError("unavailable", `This server does not ship the ${SCOUT_TEMPLATE} template, which scans a repository.`);
|
|
1963
|
+
return (await applyTemplate(pkg, { parameters: {} })).applied.agent_id;
|
|
1964
|
+
})().finally(() => { scouting = undefined; })),
|
|
1965
|
+
startScan: async (agentId, content) => (await startRunOf(await needRunnableAgent(agentId), { input: { content } })).id,
|
|
1966
|
+
readRun: async (runId) => {
|
|
1967
|
+
const view = await viewOverStore(store, runId, viewDepsFor(ownOriginOf()));
|
|
1968
|
+
if (!view)
|
|
1969
|
+
return undefined;
|
|
1970
|
+
const result = isObject(view.result) ? view.result : undefined;
|
|
1971
|
+
const error = isObject(view.error) && typeof view.error.message === "string" ? view.error.message : typeof result?.output_error === "string" ? `Its answer did not meet the scout's schema: ${result.output_error}` : undefined;
|
|
1972
|
+
return { status: String(view.status), ...(result && result.output != null ? { output: result.output } : {}), ...(error ? { error } : {}), ...(typeof view.ended_at === "string" ? { endedAt: Date.parse(view.ended_at) } : {}) };
|
|
1973
|
+
},
|
|
1974
|
+
// Kept, then applied (template-import.ts applyImported): a thrown error means no agent was made. The package has no
|
|
1975
|
+
// trigger, so the apply makes the agent as its last write.
|
|
1976
|
+
cancelScan: async (runId) => { await cancel(store, await needRun(runId)); },
|
|
1977
|
+
agentFrom: async (id, sha) => (await agents.list()).find((one) => one.template?.id === id && one.template.sha === sha && !one.agent.archivedAt)?.agent.id,
|
|
1978
|
+
makeAgent: async (id, origin, files) => {
|
|
1979
|
+
const made = await applyImported({ registry, store, apply: (pkg) => applyTemplate(pkg, { parameters: {} }) }, id, origin, files);
|
|
1980
|
+
return { agentId: made.applied.agent_id, warnings: made.applied.warnings };
|
|
1981
|
+
},
|
|
1982
|
+
...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
|
|
1983
|
+
...(options.onUsage ? { used: options.onUsage } : {}),
|
|
1984
|
+
});
|
|
1801
1985
|
// A github_app MCP server's tools are listed with an installation token of the App, narrowed to one repository it covers
|
|
1802
1986
|
// with metadata read (tokenForListing); a run's own is minted in the runner (runner/github-app.ts). Every token minted
|
|
1803
1987
|
// is a server secret while it may be in use.
|
|
1804
1988
|
mcpServers.appToken = (signal) => githubConnect.tokenForListing(signal);
|
|
1805
1989
|
secretStores.add("github-tokens", () => githubConnect.liveTokens());
|
|
1990
|
+
/** Why a trigger of `kind` can't be on here now (its connection), or undefined: what a create of an enabled one is
|
|
1991
|
+
* refused with, and what an apply's plan says of the triggers it would make. */
|
|
1992
|
+
const triggerUnavailable = 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);
|
|
1806
1993
|
const triggers = new Triggers({
|
|
1807
1994
|
// The server's own store (the one it opened) holds the triggers a person writes and reads; a test may inject another
|
|
1808
1995
|
// (startServe's `store`).
|
|
@@ -1810,7 +1997,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1810
1997
|
clock: options.triggerClock,
|
|
1811
1998
|
...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
|
|
1812
1999
|
adapters,
|
|
1813
|
-
unavailable:
|
|
2000
|
+
unavailable: triggerUnavailable,
|
|
1814
2001
|
// The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
|
|
1815
2002
|
// 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
|
|
1816
2003
|
// or an eval's route to its fake feeds (feedsAt).
|
|
@@ -1828,6 +2015,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1828
2015
|
},
|
|
1829
2016
|
// A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
|
|
1830
2017
|
upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
|
|
2018
|
+
...(options.launchHook ? { launchHook: options.launchHook } : {}),
|
|
1831
2019
|
});
|
|
1832
2020
|
const composioTriggers = new ComposioTriggers({
|
|
1833
2021
|
control: options.composioControl ?? {},
|
|
@@ -2218,7 +2406,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2218
2406
|
async function needRunnableAgent(id) {
|
|
2219
2407
|
const entry = await needAgent(id);
|
|
2220
2408
|
// Another system's agent is archived only by its delete (its archive route is refused).
|
|
2221
|
-
if (entry.agent.archivedAt && entry.agent
|
|
2409
|
+
if (entry.agent.archivedAt && ownedElsewhere(entry.agent))
|
|
2222
2410
|
throw agentDeleting(id);
|
|
2223
2411
|
if (entry.agent.archivedAt)
|
|
2224
2412
|
throw new ApiError("agent_not_runnable", `The agent ${id} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
|
|
@@ -2287,7 +2475,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2287
2475
|
// A purged agent's row stays as its tombstone: a write that waited on its purge is 410, never a folder made again.
|
|
2288
2476
|
if (entry.agent.purgedAt !== null)
|
|
2289
2477
|
throw purgedAgent(entry.agent);
|
|
2290
|
-
if (entry.agent.archivedAt && entry.agent
|
|
2478
|
+
if (entry.agent.archivedAt && ownedElsewhere(entry.agent))
|
|
2291
2479
|
throw agentDeleting(id);
|
|
2292
2480
|
// A purge stopped part way (its mark still there): nothing of the agent is written, nor is it unarchived, until a
|
|
2293
2481
|
// DELETE finishes it.
|
|
@@ -2434,12 +2622,26 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2434
2622
|
// The agent's folder (its runs' folders, its home, its learning folder) and its scratch folder.
|
|
2435
2623
|
await rm(agentFolder(data, agentId), { recursive: true, force: true });
|
|
2436
2624
|
await rm(join(data, "scratch", agentDirName(agentId)), { recursive: true, force: true });
|
|
2625
|
+
// Private source metadata is owned by this exact agent. Prefix siblings with dotted IDs are left alone.
|
|
2626
|
+
for (const key of [`source-sync.agent.${agentId}`, `source-sync.local.${agentId}`])
|
|
2627
|
+
await store.settings.remove(key);
|
|
2628
|
+
for (const prefix of [`source-sync.tool.${agentId}.`, `source-sync.checkpoint.${agentId}.`]) {
|
|
2629
|
+
for (const row of await store.settings.all({ prefix }))
|
|
2630
|
+
if (/^[a-f0-9]{64}$/.test(row.key.slice(prefix.length)))
|
|
2631
|
+
await store.settings.remove(row.key);
|
|
2632
|
+
}
|
|
2437
2633
|
await forgetKept("agent", agentId);
|
|
2438
2634
|
},
|
|
2439
2635
|
// The replay runs of its input, its audit's shadow run and a learning run it names (the store's), and its audit's shadow
|
|
2440
2636
|
// run by its id (one whose launch is gone too).
|
|
2441
2637
|
madeFrom: async (runId) => [...new Set([...(await store.runs.madeFrom(runId)), shadowRunId(runId)])],
|
|
2442
|
-
|
|
2638
|
+
// Its copies in the agent's promotion records, then its text off the agent's learning folder's current files (its
|
|
2639
|
+
// merges' diff files and feedback lines), in the agent's queue: a folder that can't be written now is 503, the run
|
|
2640
|
+
// purged or kept as the purge had got, and the next DELETE does it again.
|
|
2641
|
+
forgetCopies: async (agentId, runId) => {
|
|
2642
|
+
await forgetRunCopies(store.settings, agentId, runId);
|
|
2643
|
+
await notYetWith(() => forgetRunLearning(data, agentId, runId), ["unavailable"], "The agent's learning folder keeps the run's text until the DELETE is sent again.");
|
|
2644
|
+
},
|
|
2443
2645
|
// /usage's meters and a live read's spend, from its journal, as they read now (store-reads/cap.ts), and how its
|
|
2444
2646
|
// learning ended as /stats counts it (its state and reason alone).
|
|
2445
2647
|
kept: async (runId) => {
|
|
@@ -2575,8 +2777,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2575
2777
|
/** What keeps `revision` from running here at `place` (its own, else this host's default), checked before anything
|
|
2576
2778
|
* starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
|
|
2577
2779
|
* does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
|
|
2578
|
-
* what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice).
|
|
2579
|
-
|
|
2780
|
+
* what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice).
|
|
2781
|
+
* `carried`: the names of the tool keys the run carries (run-keys.ts), each read as one this host holds. */
|
|
2782
|
+
async function runnable(revision, place, { capped = false, price = decisionPrice, carried = [] } = {}) {
|
|
2580
2783
|
if (cliLearningOf(revision.body))
|
|
2581
2784
|
throw new ApiError("agent_not_runnable", "Continue in the original CLI session; this connection records learning without launching its tools.");
|
|
2582
2785
|
if (sdkOf(revision.body))
|
|
@@ -2634,8 +2837,13 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2634
2837
|
});
|
|
2635
2838
|
};
|
|
2636
2839
|
const monid = revision.monidPin ?? undefined;
|
|
2840
|
+
// Under the run-keys setting, a template's tool key this host does not hold is each run's to carry: one that does not
|
|
2841
|
+
// is refused for it alone, before the checks that read the keys it would bring.
|
|
2842
|
+
const owed = options.runKeys ? keysOwed(revision, env, carried) : [];
|
|
2843
|
+
if (owed.length)
|
|
2844
|
+
throw keysOwedRefusal(owed);
|
|
2637
2845
|
// Claude Code's login on this machine is a runner place's alone: a sandbox run is checked for a key, as it runs.
|
|
2638
|
-
const blockers = await blockersOf(envAtPlace(env, shape.place), shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice: price });
|
|
2846
|
+
const blockers = await blockersOf(withCarried(envAtPlace(env, shape.place), carried), shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice: price });
|
|
2639
2847
|
if (!blockers.length)
|
|
2640
2848
|
return;
|
|
2641
2849
|
const message = blockers.map((b) => b.message).join(" ");
|
|
@@ -2839,7 +3047,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2839
3047
|
// Its last read and its commit in the agent's delete turn (agentWrite), the check outside it: an edit or a template
|
|
2840
3048
|
// update whose commit comes once the agent is purged is 410, and one after a purge stopped part way is 409, nothing
|
|
2841
3049
|
// written (the store refuses a purged agent's revision too, AgentPurged).
|
|
2842
|
-
const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, ...options, inTurn: (work) => agentWrite(entry.agent.id, work) });
|
|
3050
|
+
const edited = await agents.commit(entry, checkDefinitionBody(body, { creating: false, harnesses }), { check, prepare: prepareProjectSkillEdit(store, entry.agent.id, sourceWorkspaces), ...options, inTurn: (work) => agentWrite(entry.agent.id, work) });
|
|
2843
3051
|
reconcileComputer(entry.agent.id);
|
|
2844
3052
|
return { entry: edited, warnings };
|
|
2845
3053
|
}
|
|
@@ -2863,6 +3071,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2863
3071
|
* reads it, cut of the host's secrets as the learning reads cut them, and a replay run's launch made as a run's start
|
|
2864
3072
|
* makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
|
|
2865
3073
|
const replayAskOf = (entry) => ({
|
|
3074
|
+
admitAuxiliary: auxiliaryAdmitter(store, { data, project: startDeps.project }),
|
|
2866
3075
|
store, agentId: entry.agent.id, context: ctx, log: (line) => void log?.(line),
|
|
2867
3076
|
folder: () => learningFolderOf(data, entry.agent.id), shown: () => learningShown(entry.agent.id),
|
|
2868
3077
|
launchOf: async (input) => {
|
|
@@ -2924,19 +3133,96 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2924
3133
|
return false;
|
|
2925
3134
|
throw error;
|
|
2926
3135
|
};
|
|
2927
|
-
/**
|
|
2928
|
-
|
|
2929
|
-
|
|
3136
|
+
/** POST /templates/{id}/apply {dry_run: true}: the apply's plan, from the same reads and checks as the apply
|
|
3137
|
+
* (prepareApply), with nothing written: whether it makes an agent or revises the one agent_id names (and its current
|
|
3138
|
+
* revision), the keys and MCP servers this server lacks (where the apply would refuse with 409, the plan lists them),
|
|
3139
|
+
* what becomes of each trigger (made, changed in place, removed, or skipped for a connection this server lacks), and
|
|
3140
|
+
* the computer it picks. Any other refusal is the apply's own. */
|
|
3141
|
+
async function planTemplate(template, body) {
|
|
3142
|
+
const p = await prepareApply(template, body, { plan: true });
|
|
3143
|
+
// A monid grant is pinned to monid's listing when the agent is saved (saveable: monidPinOf), read with the monid key:
|
|
3144
|
+
// with none here the apply is refused, so the plan lists the key. A grant the agent's current pin carries reads
|
|
3145
|
+
// nothing (pinMonid with no key answers before any request).
|
|
3146
|
+
const definition = isObject(p.made.agent) && isObject(p.made.agent.definition) ? p.made.agent.definition : {};
|
|
3147
|
+
const tools = Array.isArray(definition.tools) ? definition.tools.filter((tool) => typeof tool === "string") : [];
|
|
3148
|
+
const was = p.onto?.revision?.kind === "agentic" ? p.onto.revision : undefined;
|
|
3149
|
+
const unread = !env[MONID_KEY_ENV]?.trim() && (await pinMonid(tools, { key: undefined, ...(was ? { previous: { grants: was.body.tools ?? [], pin: was.monidPin ?? null } } : {}) }));
|
|
3150
|
+
const missing = unread && "refused" in unread && !p.missing.includes(MONID_KEY_ENV) ? [...p.missing, MONID_KEY_ENV] : p.missing;
|
|
3151
|
+
const planned = [];
|
|
3152
|
+
for (const [i, trigger] of p.made.triggers.entries()) {
|
|
3153
|
+
const name = String(trigger.name).trim();
|
|
3154
|
+
const kind = isObject(trigger.source) ? String(trigger.source.kind) : "";
|
|
3155
|
+
// On an API-only server, skipped in the apply's own words (prepareApply).
|
|
3156
|
+
const hostSkip = p.hostless.get(i);
|
|
3157
|
+
if (hostSkip) {
|
|
3158
|
+
planned.push({ name, kind, action: "skip", reason: hostSkip.message });
|
|
3159
|
+
continue;
|
|
3160
|
+
}
|
|
3161
|
+
if (p.emptyFeeds.has(i)) {
|
|
3162
|
+
planned.push({ name, kind, action: "skip", reason: feedTriggerEmpty(p.pkg.name, trigger, isObject(p.pkg.triggers[i]?.source) ? p.pkg.triggers[i].source.urls : undefined) });
|
|
3163
|
+
continue;
|
|
3164
|
+
}
|
|
3165
|
+
const was = p.hadByName.get(name);
|
|
3166
|
+
if (was && isObject(was.source) && was.source.kind === kind && !p.remade.has(i)) {
|
|
3167
|
+
planned.push({ name, kind, action: "update" });
|
|
3168
|
+
continue;
|
|
3169
|
+
}
|
|
3170
|
+
// Made (again), on unless the owner had turned the old one off: a connection this server lacks skips it, as the
|
|
3171
|
+
// apply's create does (notSetUpYet), or refuses the apply. A Composio trigger is skipped for want of a public URL
|
|
3172
|
+
// (any trigger, on or off), read here; its account and subscription are Composio's to answer, which a plan never asks.
|
|
3173
|
+
const refusal = kind === "composio" && !options.publicUrl ? composioNoPublicUrl() : trigger.enabled !== false && !(was && !was.enabled) ? await triggerUnavailable(kind) : undefined;
|
|
3174
|
+
if (refusal && notSetUpYet(kind, refusal.code))
|
|
3175
|
+
planned.push({ name, kind, action: "skip", reason: refusal.message });
|
|
3176
|
+
else if (refusal)
|
|
3177
|
+
throw refusal;
|
|
3178
|
+
else
|
|
3179
|
+
planned.push({ name, kind, action: "create", ...(was ? { reason: `The agent's ${name} trigger is removed and made again: its kind or its Composio server, event or config changed.` } : {}) });
|
|
3180
|
+
}
|
|
3181
|
+
for (const row of p.removing)
|
|
3182
|
+
planned.push({ name: row.name, kind: isObject(row.source) ? String(row.source.kind) : "", action: "remove" });
|
|
3183
|
+
const computer = p.pick && !("refused" in p.pick) ? p.pick.computer : undefined;
|
|
3184
|
+
return {
|
|
3185
|
+
plan: {
|
|
3186
|
+
action: p.onto ? "revise" : "create",
|
|
3187
|
+
agent_id: p.onto?.agent.id ?? null,
|
|
3188
|
+
current_revision_id: p.onto?.revision?.id ?? null,
|
|
3189
|
+
missing_secrets: missing,
|
|
3190
|
+
unmatched_mcp: p.unsaved.map((need) => ({ source: need.source, toolkit: need.toolkit, required: need.required })),
|
|
3191
|
+
triggers: planned,
|
|
3192
|
+
computer: computer ? { kind: computer.kind, provider: computer.provider ?? null } : null,
|
|
3193
|
+
},
|
|
3194
|
+
};
|
|
3195
|
+
}
|
|
3196
|
+
/** What an apply reads and checks before its first write, the same for its plan (`plan`) and itself: the body
|
|
3197
|
+
* (applyBodyOf), the agent agent_id names, the keys and MCP servers, the computer, the model, the agent and triggers it
|
|
3198
|
+
* makes and how they meet the agent's, every refusal but the keys' and MCP servers' (which the plan lists). */
|
|
3199
|
+
async function prepareApply(template, body, { plan }) {
|
|
3200
|
+
const { parameters, grants: asked, servers: picks, model: override, choice, approvals, agentId, revision: expected, sha } = applyBodyOf(template, body);
|
|
3201
|
+
// The package the caller read (its sha): another stored under this id since (an upload of the same name) is not what
|
|
3202
|
+
// they planned or confirmed.
|
|
3203
|
+
if (sha !== undefined && (template.origin?.sha ?? null) !== sha)
|
|
3204
|
+
throw new ApiError("precondition_failed", `The ${template.name} template stored here is not the package of sha ${sha} (another was stored under ${template.id} since): nothing was changed. Read it again (GET /templates), then apply.`);
|
|
2930
3205
|
// With agent_id, the apply writes a new revision of that agent (one this template made) in place of making another:
|
|
2931
|
-
// everything below checks the package as a fresh apply does, through the same code.
|
|
3206
|
+
// everything below checks the package as a fresh apply does, through the same code. With `revision`, only onto the
|
|
3207
|
+
// revision the caller read: the write below is held to the revision read here (ifCurrent), so one written in between
|
|
3208
|
+
// is 412 as well.
|
|
2932
3209
|
const onto = agentId === undefined ? undefined : await templateAgentOf(agentId, template);
|
|
3210
|
+
if (onto && expected !== undefined && (onto.revision?.id ?? null) !== expected)
|
|
3211
|
+
throw new ApiError("precondition_failed", `The agent ${onto.agent.id}'s current revision is ${onto.revision?.id ?? "none"}, not ${expected} (an edit, or another apply, wrote one since it was read): nothing was changed. Read it again, then apply.`);
|
|
2933
3212
|
// An update's triggers are reconciled by name with the ones the agent has (below), read with the agent: each write to
|
|
2934
3213
|
// one is made only while it is still this agent's (TriggerOwn.onAgent), so one a PATCH moves away meanwhile is left.
|
|
2935
3214
|
const had = onto ? await store.triggers.list(onto.agent.id) : [];
|
|
2936
|
-
if (onto && options.templateApplyRead)
|
|
3215
|
+
if (onto && !plan && options.templateApplyRead)
|
|
2937
3216
|
await options.templateApplyRead(onto.agent.id);
|
|
2938
|
-
// A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
|
|
2939
|
-
|
|
3217
|
+
// A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made. Under
|
|
3218
|
+
// the run-keys setting, a tool key is each run's to carry (run-keys.ts): its agent is made, the warning says so, and a
|
|
3219
|
+
// run that does not carry it is refused. A model key is still the server's, and so is monid's: the agent's monid tools
|
|
3220
|
+
// are checked with it when the agent is saved (monidPinOf), before any run.
|
|
3221
|
+
const declared = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].sort();
|
|
3222
|
+
const absent = declared.filter((name) => !secret(name, storedKeys));
|
|
3223
|
+
const brought = options.runKeys ? absent.filter((name) => TOOL_FIELDS.includes(name) && name !== MONID_KEY_ENV) : [];
|
|
3224
|
+
const missing = absent.filter((name) => !brought.includes(name));
|
|
3225
|
+
const keyWarnings = brought.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server: it takes it from each run (${RUN_KEYS_ENV}=1), so a run that does not carry it in keys is refused.`, fix: `Send keys.${name} with each run, or add it in Settings → API Keys.` }));
|
|
2940
3226
|
// Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
|
|
2941
3227
|
// one: several and no pick is a 422); the package's
|
|
2942
3228
|
// tool names, mcp:<toolkit>/<tool>, read as that server's from here on (templates.ts onServers).
|
|
@@ -2949,29 +3235,32 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2949
3235
|
// of a saved server that happens to be named as its toolkit.
|
|
2950
3236
|
const grants = asked.filter((tool) => Object.hasOwn(servers, mcpToolOf(tool)?.server ?? "")).map((tool) => onServerName(tool, servers));
|
|
2951
3237
|
const needed = unsaved.filter((need) => need.required);
|
|
2952
|
-
if (missing.length || needed.length) {
|
|
3238
|
+
if (!plan && (missing.length || needed.length)) {
|
|
2953
3239
|
const fix = "Add it in Settings → API Keys, or set it where AgentRun starts, then apply the template again.";
|
|
2954
|
-
throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `a ${need.source} MCP server of the toolkit ${need.toolkit}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}.`, fix: mcpSetUp(need) }))] });
|
|
3240
|
+
throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `a ${need.source} MCP server of the toolkit ${need.toolkit}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: options.runKeys && name === MONID_KEY_ENV ? `${name} is not set on this server, and a run can't bring it (${RUN_KEYS_ENV}=1): the agent's monid tools are checked with this server's key when it is saved.` : `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}.`, fix: mcpSetUp(need) }))] });
|
|
2955
3241
|
}
|
|
2956
3242
|
// The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
|
|
2957
3243
|
// agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
|
|
2958
3244
|
// whose entries is met (a shell alone, where there is none) refuses the apply: nothing is made.
|
|
2959
|
-
const pick = pickComputer(pkg, await shellHere());
|
|
3245
|
+
const pick = pickComputer(pkg, await shellHere({ sandbox: Boolean(pkg.needs) }));
|
|
2960
3246
|
if (pick && "refused" in pick)
|
|
2961
|
-
throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: COMPUTER_FIX }] });
|
|
3247
|
+
throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: pick.fix ?? COMPUTER_FIX }] });
|
|
2962
3248
|
const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
|
|
2963
3249
|
// An MCP server the package can do without is skipped, and said: its tools are not granted.
|
|
2964
3250
|
const skipped = unsaved.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}, so the agent was made without its tools (${need.tools.join(", ")}).`, fix: mcpSetUp(need) }));
|
|
2965
3251
|
// A model choice the owner picked is its model on its harness, or a refusal naming the model: never the tier's model
|
|
2966
|
-
// in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway.
|
|
2967
|
-
|
|
3252
|
+
// in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway. A plan whose keys are
|
|
3253
|
+
// missing lists them and goes on: a model refused for want of one of them is the same lack, and once they are added
|
|
3254
|
+
// the next plan reads the model again.
|
|
3255
|
+
const lacking = plan && missing.length > 0;
|
|
3256
|
+
const unrunnable = choice && !lacking && (await choiceUnrunnable(env, choice, offers.find((offer) => offer.id === choice.harness)));
|
|
2968
3257
|
if (choice && unrunnable) {
|
|
2969
3258
|
const message = `The ${pkg.name} template's choice ${choice.label} runs ${choice.model} on ${choice.harness}, which this server can't run: ${unrunnable.replace(/\.$/, "")}. Nothing was created.`;
|
|
2970
3259
|
throw new ApiError("agent_not_runnable", message, { fields: [{ field: "overrides.choice", reason: NOT_SET_UP, message, fix: "Apply with the default or another choice, or, where the model only wants a key, add it in Settings → Model keys." }] });
|
|
2971
3260
|
}
|
|
2972
3261
|
const harness = choice ? choice.harness : pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
|
|
2973
3262
|
const picked = choice ? { model: choice.model } : override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
|
|
2974
|
-
if ("refused" in picked && picked.refused) {
|
|
3263
|
+
if ("refused" in picked && picked.refused && !lacking) {
|
|
2975
3264
|
const message = `The ${pkg.name} template prefers ${pkg.model?.prefer}, which this server can't run on ${harness ?? DEFAULT_HARNESS}: ${picked.refused.why}. Nothing was created.`;
|
|
2976
3265
|
throw new ApiError("agent_not_runnable", message, { fields: [{ field: "model", reason: NOT_SET_UP, message, fix: picked.refused.fix }] });
|
|
2977
3266
|
}
|
|
@@ -2995,15 +3284,26 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2995
3284
|
// by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
|
|
2996
3285
|
// A feed trigger whose urls are one array parameter given empty reads no feed: skipped, never the apply (feedLeftEmpty).
|
|
2997
3286
|
const emptyFeeds = new Set(made.triggers.flatMap((trigger, i) => (feedLeftEmpty(trigger) ? [i] : [])));
|
|
2998
|
-
|
|
3287
|
+
// A trigger is made only when its firings have somewhere to go: on an API-only server, a schedule or a feed with the
|
|
3288
|
+
// launch hook set (api-only.ts); under the run-keys setting, for an agent whose runs owe keys, only with the launch
|
|
3289
|
+
// hook, the one way a firing's run carries them (run-keys.ts). Each other is said, and stays listed, so a trigger the
|
|
3290
|
+
// agent has by its name is left as it is, never removed.
|
|
3291
|
+
const hooked = options.launchHook !== undefined;
|
|
3292
|
+
const hostless = new Map(made.triggers.flatMap((trigger, i) => {
|
|
3293
|
+
const skip = (options.apiOnly ? apiOnlyTriggerSkipped(pkg.name, trigger, hooked) : undefined) ?? runKeysTriggerSkipped(pkg.name, trigger, brought, hooked);
|
|
3294
|
+
return skip ? [[i, skip]] : [];
|
|
3295
|
+
}));
|
|
3296
|
+
const unmade = (i) => emptyFeeds.has(i) || hostless.has(i);
|
|
3297
|
+
const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema).filter((issue) => !unmade(Number(/^triggers\.(\d+)\./.exec(issue.field)?.[1])));
|
|
2999
3298
|
if (refusedTriggers.length)
|
|
3000
3299
|
throw invalid(refusedTriggers);
|
|
3001
3300
|
// POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
|
|
3002
3301
|
for (const one of [made.agent, ...made.triggers])
|
|
3003
3302
|
if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
|
|
3004
3303
|
throw new ApiError("payload_too_large", `the ${pkg.name} template, its parameters filled in, makes a body over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
|
|
3005
|
-
// The package's triggers by name, as this apply makes them (a feed it left empty is not made, so not listed either
|
|
3006
|
-
|
|
3304
|
+
// The package's triggers by name, as this apply makes them (a feed it left empty is not made, so not listed either,
|
|
3305
|
+
// except one an API-only server does not make, which leaves each the agent has: hostless above).
|
|
3306
|
+
const listed = new Set(made.triggers.flatMap((trigger, i) => (emptyFeeds.has(i) && !hostless.has(i) ? [] : [String(trigger.name).trim()])));
|
|
3007
3307
|
// The triggers to remove: each of the agent's that an apply of this package marked as its own (TriggerRow.templateId)
|
|
3008
3308
|
// and whose name the package no longer lists. A trigger the owner made, one a PATCH moved here from another agent (or
|
|
3009
3309
|
// away and back), and one made before the mark was kept carry none, and are left. One whose removal fails keeps its
|
|
@@ -3018,7 +3318,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3018
3318
|
const resent = new Map();
|
|
3019
3319
|
const remade = new Set();
|
|
3020
3320
|
for (const [i, trigger] of made.triggers.entries()) {
|
|
3021
|
-
const was =
|
|
3321
|
+
const was = unmade(i) ? undefined : hadByName.get(String(trigger.name).trim());
|
|
3022
3322
|
if (!was || !isObject(trigger.source) || trigger.source.kind !== "composio" || !isObject(was.source) || was.source.kind !== "composio")
|
|
3023
3323
|
continue;
|
|
3024
3324
|
try {
|
|
@@ -3037,7 +3337,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3037
3337
|
// have to make again without being its own, or another package's, refuses the apply with nothing written (409 under
|
|
3038
3338
|
// triggers.<i>): the owner renames or deletes it, then applies again.
|
|
3039
3339
|
const notOurs = made.triggers.flatMap((trigger, i) => {
|
|
3040
|
-
const was =
|
|
3340
|
+
const was = unmade(i) ? undefined : hadByName.get(String(trigger.name).trim());
|
|
3041
3341
|
if (!was || was.templateId === pkg.id)
|
|
3042
3342
|
return [];
|
|
3043
3343
|
const kind = isObject(trigger.source) ? String(trigger.source.kind) : "";
|
|
@@ -3052,10 +3352,18 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3052
3352
|
if (notOurs.length)
|
|
3053
3353
|
throw new ApiError("name_taken", notOurs.length === 1 ? notOurs[0].message : `${notOurs.length} of the agent's triggers have the names of the ${pkg.name} template's and are not its own. Nothing was changed: rename or delete each, then apply the template again.`, { fields: notOurs });
|
|
3054
3354
|
// The agent keeps where it came from (the package on the revision the apply writes): the package's id, version and,
|
|
3055
|
-
// imported, its SHA;
|
|
3056
|
-
//
|
|
3355
|
+
// imported, its SHA; a keyed digest of the parameters it was given (never the parameters: one may be a credential); and
|
|
3356
|
+
// the names of the keys it declared (never a value), which an export names after the server's copy of the package
|
|
3357
|
+
// changes, and whose tool keys a run may carry (under the run-keys setting, a run that does not is refused). Which
|
|
3358
|
+
// triggers are the package's is on each trigger (its mark), not here.
|
|
3057
3359
|
const digest = parametersDigest(sealKey, stable(parameters));
|
|
3058
|
-
const origin = { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null, parameters_digest: digest };
|
|
3360
|
+
const origin = { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null, parameters_digest: digest, secrets: declared };
|
|
3361
|
+
return { pkg, onto, missing, unsaved, saved, mapped, grants, pick, made, emptyFeeds, hostless, unmade, hadByName, remade, resent, removing, digest, origin, warned: [...keyWarnings, ...skipped, ...kept, ...modelWarnings, ...computerWarnings] };
|
|
3362
|
+
}
|
|
3363
|
+
/** applyTemplate's work, in its turn on the agent where it has agent_id: prepareApply's reads and checks, then its
|
|
3364
|
+
* writes. */
|
|
3365
|
+
async function applyWith(template, body) {
|
|
3366
|
+
const { pkg, onto, saved, mapped, grants, made, emptyFeeds, hostless, unmade, hadByName, remade, resent, removing, digest, origin, warned } = await prepareApply(template, body, { plan: false });
|
|
3059
3367
|
// A fresh apply of what already made a live agent here (the same package and parameters) still makes one, and says
|
|
3060
3368
|
// which is there: an apply with its agent_id updates that one instead. Read before this apply's agent is made.
|
|
3061
3369
|
const twins = onto ? [] : (await agents.list())
|
|
@@ -3095,7 +3403,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3095
3403
|
const leftThere = [];
|
|
3096
3404
|
try {
|
|
3097
3405
|
for (const [i, trigger] of made.triggers.entries()) {
|
|
3098
|
-
if (
|
|
3406
|
+
if (unmade(i))
|
|
3099
3407
|
continue;
|
|
3100
3408
|
const aimed = { ...trigger, target: { ...trigger.target, agent_id: entry.agent.id } };
|
|
3101
3409
|
let was = hadByName.get(String(trigger.name).trim());
|
|
@@ -3180,9 +3488,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3180
3488
|
const ticked = saved.map((need) => ({ ...need, tools: need.tools.filter((tool) => grants.includes(mcpToolName(need.server, tool))) }));
|
|
3181
3489
|
const appShort = await appPermissionWarnings({ name: pkg.name, mcp: ticked }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
|
|
3182
3490
|
// A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
|
|
3183
|
-
const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
|
|
3491
|
+
const hooks = made.triggers.flatMap((trigger, i) => (!hostless.has(i) && isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
|
|
3184
3492
|
// Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
|
|
3185
|
-
const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
|
|
3493
|
+
const githubTriggers = made.triggers.flatMap((trigger, i) => (!hostless.has(i) && isObject(trigger.source) && trigger.source.kind === "github"
|
|
3186
3494
|
? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: githubTriggerUnconnected(pkg.name, trigger.source) } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
|
|
3187
3495
|
: []));
|
|
3188
3496
|
// Each composio trigger it skipped: which, the refusal's words, and where to make it once that's fixed.
|
|
@@ -3191,7 +3499,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3191
3499
|
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 }] : [];
|
|
3192
3500
|
});
|
|
3193
3501
|
// Each feed trigger it skipped for want of a feed: which, and the parameter to set.
|
|
3194
|
-
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) }));
|
|
3502
|
+
const feedsSkipped = [...emptyFeeds].filter((i) => !hostless.has(i)).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) }));
|
|
3503
|
+
// Each trigger an API-only server does not make: not_set_up_here when the launch hook would make it, else not_an_option.
|
|
3504
|
+
const hostSkipped = [...hostless].map(([i, { reason, message }]) => ({ field: `triggers.${i}`, reason, message }));
|
|
3195
3505
|
// Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
|
|
3196
3506
|
// (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
|
|
3197
3507
|
const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
|
|
@@ -3200,7 +3510,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3200
3510
|
// What the apply did to the agent: made it, wrote a new revision, or wrote none (an update whose package and
|
|
3201
3511
|
// parameters the current revision already holds: commitAgent keeps that revision).
|
|
3202
3512
|
const agentChange = !onto ? "made" : entry.revision?.id === onto.revision?.id ? "unchanged" : "updated";
|
|
3203
|
-
const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, agent_change: agentChange, servers: used, triggers: answered, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...
|
|
3513
|
+
const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_id: entry.revision?.id ?? null, revision_version: entry.version, agent_change: agentChange, servers: used, triggers: answered, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...warned, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...hostSkipped, ...leftThere, ...appShort, ...twins] };
|
|
3204
3514
|
return { applied, minted, updated: onto !== undefined };
|
|
3205
3515
|
}
|
|
3206
3516
|
/** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
|
|
@@ -3259,11 +3569,13 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3259
3569
|
* bound to its server's origin then and the model key to the gateway's (AGENT_MODEL_BASE_URL). `handed` is called only
|
|
3260
3570
|
* for new work, inside the request's idempotent work: there each mcp_auth entry must name a saved per_run server, and
|
|
3261
3571
|
* the model key must be text, else 422, nothing written. A retry its key already answered replays that answer even
|
|
3262
|
-
* when the server has since changed or gone, since it does no new work.
|
|
3572
|
+
* when the server has since changed or gone, since it does no new work. `keys`, the run's own tool keys (run-keys.ts),
|
|
3573
|
+
* go the same way: each a tool key name to its value as text, else 422 by name, never with the value; whether the
|
|
3574
|
+
* run's revision reads each is its start's check (prepareLaunch), by name alone. */
|
|
3263
3575
|
function handedLaunchSecrets(body) {
|
|
3264
|
-
if (body.mcp_auth === undefined && body.model_key === undefined)
|
|
3576
|
+
if (body.mcp_auth === undefined && body.model_key === undefined && body.keys === undefined)
|
|
3265
3577
|
return { body, handed: async () => ({}) };
|
|
3266
|
-
const { mcp_auth, model_key, ...rest } = body;
|
|
3578
|
+
const { mcp_auth, model_key, keys: given, ...rest } = body;
|
|
3267
3579
|
const handed = async () => {
|
|
3268
3580
|
const issues = [];
|
|
3269
3581
|
const mcp = mcp_auth === undefined ? undefined : mcpAuthOf(mcp_auth, issues);
|
|
@@ -3289,12 +3601,16 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3289
3601
|
issues.push({ field, reason: "not_an_option", message: perRunComposio ? `The MCP server ${server} takes a Composio account from each run, not headers: send {"composio_user_id": "<user>", "connected_account_id": "ca_..."} (the account optional).` : `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` });
|
|
3290
3602
|
}
|
|
3291
3603
|
const model = model_key === undefined ? undefined : modelKeyOf(model_key, issues);
|
|
3604
|
+
const keys = given === undefined ? undefined : runKeysOf(given, issues);
|
|
3292
3605
|
if (issues.length)
|
|
3293
3606
|
throw invalid(issues);
|
|
3294
|
-
|
|
3607
|
+
// Empty keys are kept: on a message they replace the run's keys with none (on a start, none is what it has).
|
|
3608
|
+
return { ...(mcp_auth !== undefined ? { mcp: auth } : {}), ...(model !== undefined ? { model } : {}), ...(keys !== undefined ? { keys } : {}) };
|
|
3295
3609
|
};
|
|
3296
3610
|
return { body: rest, handed };
|
|
3297
3611
|
}
|
|
3612
|
+
/** The start option naming the tool keys `handed` carries, by name (runs-over-store StartOptions.keys). */
|
|
3613
|
+
const carriedOf = (handed) => (handed.keys ? { keys: Object.keys(handed.keys) } : {});
|
|
3298
3614
|
/** The 422 for a model key where the run's model never takes it (run-model-key.ts modelKeyMisfit), at `model_key`. */
|
|
3299
3615
|
const misfit = (why) => invalid([{ field: "model_key", reason: "not_an_option", message: why }]);
|
|
3300
3616
|
/** A start's launch seal of `handed` (handedLaunchSecrets), made once the start prepared the run's launch: a model key
|
|
@@ -3302,7 +3618,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3302
3618
|
* is refused where the server holds no key for the run's route (serverKeyMissing). Undefined when nothing is handed:
|
|
3303
3619
|
* the start's own check (runs-over-store keyedOrRefused) refuses that one where it has no key to spend. */
|
|
3304
3620
|
function startSeal(handed) {
|
|
3305
|
-
if (handed.mcp === undefined && handed.model === undefined)
|
|
3621
|
+
if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined)
|
|
3306
3622
|
return undefined;
|
|
3307
3623
|
return (runId, launch, kind) => {
|
|
3308
3624
|
const target = { kind, model: launch.model, native: Boolean(launch.native) };
|
|
@@ -3314,7 +3630,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3314
3630
|
else if (serverKeyMissing(env, target))
|
|
3315
3631
|
throw modelKeyRequired(false);
|
|
3316
3632
|
const origin = runModelOrigin(env);
|
|
3317
|
-
return sealRunLaunch(sealKey, runId, { ...(handed.mcp ? { mcp: handed.mcp } : {}), ...(handed.model !== undefined && origin ? { model: { key: handed.model, origin } } : {}) });
|
|
3633
|
+
return sealRunLaunch(sealKey, runId, { ...(handed.mcp ? { mcp: handed.mcp } : {}), ...(handed.model !== undefined && origin ? { model: { key: handed.model, origin } } : {}), ...(handed.keys ? { keys: handed.keys } : {}) });
|
|
3318
3634
|
};
|
|
3319
3635
|
}
|
|
3320
3636
|
/** A message's launch secrets for run `run` (its kind and launch as stored): what it hands replaces that part of the
|
|
@@ -3322,7 +3638,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3322
3638
|
* part it does not hand is kept as the run holds it (none after its turn's end erased it). A model key is refused
|
|
3323
3639
|
* where the run's model never takes it. One is required where the server holds no key for the run's route and the
|
|
3324
3640
|
* run holds none when the message is written (its last turn ended): 422 model_key_required from inside that write,
|
|
3325
|
-
* which then writes nothing, so a turn never starts with no key to spend.
|
|
3641
|
+
* which then writes nothing, so a turn never starts with no key to spend. Its `keys` replace the run's whole, each one
|
|
3642
|
+
* its revision reads (else 422 by name); under the run-keys setting, a message that would leave the run without a tool
|
|
3643
|
+
* key its template declared and this host does not hold (its last turn's end erased them) is refused, 409, nothing
|
|
3644
|
+
* written. */
|
|
3326
3645
|
async function messageSeal(run, handed) {
|
|
3327
3646
|
const launch = readLaunchBody((await store.runs.launch(run.id)).body);
|
|
3328
3647
|
const target = { kind: run.kind, model: launch?.model, native: Boolean(launch?.native) };
|
|
@@ -3331,22 +3650,51 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3331
3650
|
if (why)
|
|
3332
3651
|
throw misfit(why);
|
|
3333
3652
|
}
|
|
3653
|
+
const row = handed.keys || options.runKeys ? await store.runs.get(run.id) : undefined;
|
|
3654
|
+
const revision = row ? await store.agents.revision(row.revisionId) : undefined;
|
|
3655
|
+
if (handed.keys) {
|
|
3656
|
+
const undeclared = undeclaredKeys(Object.keys(handed.keys), revision ? await declaredKeys(revision) : []);
|
|
3657
|
+
if (undeclared.length)
|
|
3658
|
+
throw invalid(undeclared);
|
|
3659
|
+
}
|
|
3660
|
+
const owed = options.runKeys && revision ? packageKeysOf(revision).filter((name) => !env[name]) : [];
|
|
3334
3661
|
const needsKey = handed.model === undefined && serverKeyMissing(env, target);
|
|
3335
|
-
if (handed.mcp === undefined && handed.model === undefined && !needsKey)
|
|
3662
|
+
if (handed.mcp === undefined && handed.model === undefined && handed.keys === undefined && !needsKey && !owed.length)
|
|
3336
3663
|
return undefined;
|
|
3337
3664
|
const origin = runModelOrigin(env);
|
|
3338
3665
|
return (current) => {
|
|
3339
3666
|
const held = current === null ? {} : (openRunLaunch(sealKey, run.id, current) ?? {});
|
|
3340
3667
|
const mcp = handed.mcp ?? held.mcp;
|
|
3341
3668
|
const model = handed.model !== undefined && origin ? { key: handed.model, origin } : held.model;
|
|
3669
|
+
const keys = handed.keys ?? held.keys;
|
|
3342
3670
|
if (!model && needsKey)
|
|
3343
3671
|
throw modelKeyRequired(true);
|
|
3344
|
-
|
|
3672
|
+
const unpaid = revision ? keysOwed(revision, env, Object.keys(keys ?? {})) : [];
|
|
3673
|
+
if (owed.length && unpaid.length)
|
|
3674
|
+
throw new ApiError("agent_not_runnable", unpaid.map((one) => one.message).join(" "), { fields: unpaid });
|
|
3675
|
+
return sealRunLaunch(sealKey, run.id, { ...(mcp ? { mcp } : {}), ...(model ? { model } : {}), ...(keys ? { keys } : {}) });
|
|
3345
3676
|
};
|
|
3346
3677
|
}
|
|
3347
3678
|
async function createRun(req, agentId) {
|
|
3348
3679
|
const entry = await needRunnableAgent(agentId);
|
|
3349
3680
|
const { body, handed } = handedLaunchSecrets(await bodyOf(req));
|
|
3681
|
+
// The host's run for a firing the launch hook handed it: the firing's own run, under the firing's key (a second start
|
|
3682
|
+
// answers that run), with the trigger, input origin and title a start here would give it, and capped as a trigger's
|
|
3683
|
+
// run is. The firing is its key, so it takes no Idempotency-Key, whose check across a restart is the run's origin.
|
|
3684
|
+
if (body.trigger_firing !== undefined) {
|
|
3685
|
+
if (req.headers["idempotency-key"] !== undefined)
|
|
3686
|
+
throw invalid([{ field: "trigger_firing", reason: "not_allowed", message: "A run for a trigger firing is keyed by the firing, and a second start answers its run: send it without Idempotency-Key." }]);
|
|
3687
|
+
const { trigger_firing: given, ...rest } = body;
|
|
3688
|
+
const firing = await triggers.handedStart(given, agentId);
|
|
3689
|
+
if ("run_id" in firing)
|
|
3690
|
+
return { status: 202, body: await viewOverStore(store, firing.run_id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${firing.run_id}`, "idempotent-replayed": "true" } };
|
|
3691
|
+
const secrets = await handed();
|
|
3692
|
+
const seal = startSeal(secrets);
|
|
3693
|
+
const run = await startRunOf(entry, rest, { origin: { key: firing.key }, trigger: firing.trigger, from: firing.from, title: firing.title, capped: !nativeOf(entry.revision?.body), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
|
|
3694
|
+
// A host that answered its hook first started this run after: the firing is started with it now.
|
|
3695
|
+
await triggers.handedRan(firing.trigger.id, firing.key, run.id);
|
|
3696
|
+
return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
|
|
3697
|
+
}
|
|
3350
3698
|
return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
|
|
3351
3699
|
// A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
|
|
3352
3700
|
const first = origin && (await agents.request(() => agents.store.runOfOrigin(origin.key)));
|
|
@@ -3356,8 +3704,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3356
3704
|
const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
|
|
3357
3705
|
return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
|
|
3358
3706
|
}
|
|
3359
|
-
const
|
|
3360
|
-
const
|
|
3707
|
+
const secrets = await handed();
|
|
3708
|
+
const seal = startSeal(secrets);
|
|
3709
|
+
const run = await startRunOf(entry, body, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
|
|
3361
3710
|
// Its view from the store: the run and its launch were inserted in one transaction, so the view reads it whole.
|
|
3362
3711
|
return { status: 202, body: await viewOverStore(store, run.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${run.id}` } };
|
|
3363
3712
|
});
|
|
@@ -3413,8 +3762,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3413
3762
|
const headers = { location: `/v2/runs/${first.runId}`, "idempotent-replayed": "true" };
|
|
3414
3763
|
return { status: 202, body: await viewOverStore(store, first.runId, viewDepsFor(linkOrigin(req))), headers };
|
|
3415
3764
|
}
|
|
3416
|
-
const
|
|
3417
|
-
const
|
|
3765
|
+
const secrets = await handed();
|
|
3766
|
+
const seal = startSeal(secrets);
|
|
3767
|
+
const started = await startInline(store, startDeps, inline, run, { ...(origin ? { origin } : {}), ...(seal ? { sealed: seal } : {}), ...carriedOf(secrets) });
|
|
3418
3768
|
return { status: 202, body: await viewOverStore(store, started.id, viewDepsFor(linkOrigin(req))), headers: { location: `/v2/runs/${started.id}` } };
|
|
3419
3769
|
});
|
|
3420
3770
|
}
|
|
@@ -4187,19 +4537,72 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4187
4537
|
await broker.authenticate(connectorId, String(req.headers.authorization).slice(7));
|
|
4188
4538
|
return send(res, 200, await broker.revoke(connectorId));
|
|
4189
4539
|
}
|
|
4190
|
-
if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand"].includes(found.name)) {
|
|
4540
|
+
if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand", "grantSourceSync", "publishSourceSync", "sourceSyncFailure"].includes(found.name)) {
|
|
4191
4541
|
const parts = found.pattern.exec(path);
|
|
4192
4542
|
const connectorId = decodeURIComponent(parts[1]);
|
|
4193
4543
|
const broker = new RemoteConnectors(store);
|
|
4194
4544
|
await broker.authenticate(connectorId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
|
|
4195
4545
|
// History pages and command completions have separate bounded contracts; other JSON keeps MAX_BODY.
|
|
4196
4546
|
const limit = found.name === "importRemoteHistory" ? REMOTE_HISTORY_BODY_BYTES
|
|
4197
|
-
: found.name === "completeRemoteCommand" ? REMOTE_COMPLETION_BODY_BYTES : MAX_BODY;
|
|
4547
|
+
: found.name === "completeRemoteCommand" ? REMOTE_COMPLETION_BODY_BYTES : found.name === "publishSourceSync" ? SOURCE_BODY_BYTES : MAX_BODY;
|
|
4198
4548
|
const body = await bodyOf(req, limit);
|
|
4199
4549
|
if (found.name === "importRemoteTarget")
|
|
4200
|
-
return send(res, 200, await broker.importTarget(connectorId, body));
|
|
4550
|
+
return send(res, 200, await broker.importTarget(connectorId, body, cliAdoptionResolver(store, new CliLearningConnections(store, sdkSecret))));
|
|
4201
4551
|
if (found.name === "importRemoteHistory")
|
|
4202
4552
|
return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [...tokens.map((entry) => entry.token), String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
|
|
4553
|
+
if (["grantSourceSync", "publishSourceSync", "sourceSyncFailure"].includes(found.name)) {
|
|
4554
|
+
const targetId = decodeURIComponent(parts[2]), target = await broker.syncAuthority(connectorId, targetId);
|
|
4555
|
+
const scoped = sources.forConnector(broker, connectorId, targetId);
|
|
4556
|
+
if (found.name === "grantSourceSync") {
|
|
4557
|
+
if (Object.keys(body).length)
|
|
4558
|
+
throw new ApiError("input_invalid", "A sync grant takes an empty object; export authority comes from connector enrollment.");
|
|
4559
|
+
const granted = await agentWrite(target.agentId, async () => {
|
|
4560
|
+
const record = await scoped.grant(target.agentId);
|
|
4561
|
+
// Account/environment prerequisites can recover while source bytes stay unchanged.
|
|
4562
|
+
try {
|
|
4563
|
+
await scoped.reconcile(target.agentId);
|
|
4564
|
+
}
|
|
4565
|
+
catch (error) {
|
|
4566
|
+
if (!(error instanceof SourcePreparationError) && !(error instanceof ApiError && error.status < 500))
|
|
4567
|
+
throw error;
|
|
4568
|
+
}
|
|
4569
|
+
return record;
|
|
4570
|
+
});
|
|
4571
|
+
return send(res, 200, granted);
|
|
4572
|
+
}
|
|
4573
|
+
const allowed = found.name === "publishSourceSync" ? ["generation", "sequence", "snapshot"] : ["generation", "sequence", "code"];
|
|
4574
|
+
if (Object.keys(body).some(key => !allowed.includes(key)) || typeof body.generation !== "string" || !Number.isSafeInteger(body.sequence) || Number(body.sequence) < 0)
|
|
4575
|
+
throw new ApiError("input_invalid", "Supply the current sync generation and a non-negative sequence.");
|
|
4576
|
+
if (found.name === "sourceSyncFailure") {
|
|
4577
|
+
if (typeof body.code !== "string" || !Object.hasOwn(SOURCE_FAILURES, body.code))
|
|
4578
|
+
throw new ApiError("input_invalid", "Choose a supported source failure code.");
|
|
4579
|
+
return send(res, 200, await agentWrite(target.agentId, () => scoped.failed(target.agentId, { generation: body.generation, sequence: Number(body.sequence), code: body.code })));
|
|
4580
|
+
}
|
|
4581
|
+
if (!isObject(body.snapshot))
|
|
4582
|
+
throw new ApiError("input_invalid", "Supply a complete source snapshot envelope.");
|
|
4583
|
+
try {
|
|
4584
|
+
// Even an idempotent replay must carry a valid bounded envelope; a matching digest is not validation.
|
|
4585
|
+
validateSourceSnapshot(body.snapshot);
|
|
4586
|
+
const saved = await agentWrite(target.agentId, async () => {
|
|
4587
|
+
const published = await scoped.publish(target.agentId, { generation: body.generation, sequence: Number(body.sequence), snapshot: body.snapshot });
|
|
4588
|
+
// Publication is durable even when a new setup cannot yet be applied; the owner sees its readiness reason.
|
|
4589
|
+
try {
|
|
4590
|
+
await scoped.reconcile(target.agentId);
|
|
4591
|
+
}
|
|
4592
|
+
catch (error) {
|
|
4593
|
+
if (!(error instanceof SourcePreparationError) && !(error instanceof ApiError && error.status < 500))
|
|
4594
|
+
throw error;
|
|
4595
|
+
}
|
|
4596
|
+
return published;
|
|
4597
|
+
});
|
|
4598
|
+
return send(res, 200, saved);
|
|
4599
|
+
}
|
|
4600
|
+
catch (error) {
|
|
4601
|
+
if (error instanceof SnapshotError)
|
|
4602
|
+
throw new ApiError("input_invalid", error.message);
|
|
4603
|
+
throw error;
|
|
4604
|
+
}
|
|
4605
|
+
}
|
|
4203
4606
|
if (found.name === "pollRemoteConnector")
|
|
4204
4607
|
return send(res, 200, await broker.poll(connectorId, body));
|
|
4205
4608
|
const commandId = decodeURIComponent(parts[2]);
|
|
@@ -4285,7 +4688,14 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4285
4688
|
case "enrollCliLearning": {
|
|
4286
4689
|
if (!isLoopback(req.socket.remoteAddress ?? ""))
|
|
4287
4690
|
throw new ApiError("forbidden", "CLI learning enrollment must come from the local source machine.");
|
|
4288
|
-
|
|
4691
|
+
const { source_sync, ...body } = await bodyOf(req);
|
|
4692
|
+
const connection = await new CliLearningConnections(store, sdkSecret).enroll(body);
|
|
4693
|
+
if (source_sync !== undefined) {
|
|
4694
|
+
await localSources.grant(connection.agent_id, source_sync);
|
|
4695
|
+
await sources.sync.grant(connection.agent_id);
|
|
4696
|
+
void sweepLocalSources();
|
|
4697
|
+
}
|
|
4698
|
+
return send(res, 201, connection);
|
|
4289
4699
|
}
|
|
4290
4700
|
case "listCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).list());
|
|
4291
4701
|
case "revokeCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).revoke(id));
|
|
@@ -4319,6 +4729,64 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4319
4729
|
throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
|
|
4320
4730
|
return send(res, 200, await new Observations(store, Date.now, new ObservationLearning(store, new CliLearningConnections(store, sdkSecret), learning !== "off")).snapshot(days, url.searchParams.get("session_id") ?? undefined));
|
|
4321
4731
|
}
|
|
4732
|
+
case "getSourceSync": return send(res, 200, await sources.status(id));
|
|
4733
|
+
case "reviewSourceProject": {
|
|
4734
|
+
const body = await bodyOf(req), entry = await needAgent(id);
|
|
4735
|
+
if (!sourceSyncOf(entry.revision?.body))
|
|
4736
|
+
throw new ApiError("input_invalid", "This agent has no moved project to review.");
|
|
4737
|
+
if (Object.keys(body).length !== 1 || !Object.hasOwn(body, "receipts"))
|
|
4738
|
+
throw new ApiError("input_invalid", "Choose the unresolved run receipts you reviewed.");
|
|
4739
|
+
await reconcileProjectCheckpoints(store, id);
|
|
4740
|
+
await acknowledgeProjects(store, id, body.receipts);
|
|
4741
|
+
return send(res, 200, await sources.status(id));
|
|
4742
|
+
}
|
|
4743
|
+
case "setSourceSync": {
|
|
4744
|
+
const body = await bodyOf(req);
|
|
4745
|
+
if (Object.keys(body).length !== 1 || typeof body.enabled !== "boolean")
|
|
4746
|
+
throw new ApiError("input_invalid", "Set enabled to true or false.");
|
|
4747
|
+
await sources.sync.setEnabled(id, body.enabled);
|
|
4748
|
+
return send(res, 200, await sources.status(id));
|
|
4749
|
+
}
|
|
4750
|
+
case "moveSourceAgent": {
|
|
4751
|
+
const body = await bodyOf(req);
|
|
4752
|
+
if (Object.keys(body).length)
|
|
4753
|
+
throw new ApiError("input_invalid", "Move takes an empty object and uses the latest complete synchronized setup.");
|
|
4754
|
+
try {
|
|
4755
|
+
const entry = await agentWrite(id, () => sources.sync.move(id));
|
|
4756
|
+
return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), source: await sources.status(id) });
|
|
4757
|
+
}
|
|
4758
|
+
catch (error) {
|
|
4759
|
+
if (error instanceof SourcePreparationError || error instanceof SnapshotError)
|
|
4760
|
+
throw new ApiError("agent_not_runnable", error.message);
|
|
4761
|
+
throw error;
|
|
4762
|
+
}
|
|
4763
|
+
}
|
|
4764
|
+
case "resolveSourceSync": {
|
|
4765
|
+
const body = await bodyOf(req);
|
|
4766
|
+
if (Object.keys(body).some(key => !["revision", "snapshot"].includes(key)) || typeof body.revision !== "string" || typeof body.snapshot !== "string")
|
|
4767
|
+
throw new ApiError("input_invalid", "Choose the source snapshot and current agent revision you reviewed.");
|
|
4768
|
+
try {
|
|
4769
|
+
const entry = await agentWrite(id, () => sources.sync.useSource(id, { revision: body.revision, snapshot: body.snapshot }));
|
|
4770
|
+
return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), source: await sources.status(id) });
|
|
4771
|
+
}
|
|
4772
|
+
catch (error) {
|
|
4773
|
+
if (error instanceof SourcePreparationError || error instanceof SnapshotError)
|
|
4774
|
+
throw new ApiError("agent_not_runnable", error.message);
|
|
4775
|
+
throw error;
|
|
4776
|
+
}
|
|
4777
|
+
}
|
|
4778
|
+
case "bindSourceTool": {
|
|
4779
|
+
const body = await bodyOf(req), record = await sources.sync.get(id);
|
|
4780
|
+
if (Object.keys(body).some(key => !["tool", "server"].includes(key)) || typeof body.tool !== "string" || typeof body.server !== "string")
|
|
4781
|
+
throw new ApiError("input_invalid", "Choose a source tool and its destination connection.");
|
|
4782
|
+
if (!record?.snapshot)
|
|
4783
|
+
throw new ApiError("agent_not_runnable", "Sync the complete setup before choosing its tool connections.");
|
|
4784
|
+
const snapshot = await sources.sync.options.read(id, record.snapshot), requirement = snapshot.configuration.tools.find(tool => tool.name === body.tool);
|
|
4785
|
+
if (!requirement)
|
|
4786
|
+
throw new ApiError("input_invalid", "Choose a tool required by this source setup.");
|
|
4787
|
+
await bindSourceTool(store, id, requirement, body.server);
|
|
4788
|
+
return send(res, 200, await sources.status(id));
|
|
4789
|
+
}
|
|
4322
4790
|
case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
|
|
4323
4791
|
case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
|
|
4324
4792
|
case "revokeRemoteConnector": return send(res, 200, await new RemoteConnectors(store).revoke(id));
|
|
@@ -4329,7 +4797,13 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4329
4797
|
return send(res, 200, await discoverNative({ project: body.project, ...(body.runtime ? { runtime: body.runtime } : {}) }));
|
|
4330
4798
|
}
|
|
4331
4799
|
case "connectNative": {
|
|
4332
|
-
const
|
|
4800
|
+
const { source_sync, ...body } = await bodyOf(req);
|
|
4801
|
+
const entry = await connectNative(store, body);
|
|
4802
|
+
if (source_sync !== undefined) {
|
|
4803
|
+
await localSources.grant(entry.agent.id, source_sync);
|
|
4804
|
+
await sources.sync.grant(entry.agent.id);
|
|
4805
|
+
void sweepLocalSources();
|
|
4806
|
+
}
|
|
4333
4807
|
return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), native: nativeOf(entry.revision?.body) });
|
|
4334
4808
|
}
|
|
4335
4809
|
case "getNative": {
|
|
@@ -4349,6 +4823,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4349
4823
|
const native = nativeOf(entry.revision?.body);
|
|
4350
4824
|
if (!native)
|
|
4351
4825
|
throw new ApiError("not_found", "This agent has no native connection.");
|
|
4826
|
+
await localSources.revoke(id);
|
|
4352
4827
|
const changed = await updateNative(store, entry, { ...native, connected: false });
|
|
4353
4828
|
if (native.remote)
|
|
4354
4829
|
await new RemoteConnectors(store).disconnectTarget(native);
|
|
@@ -4439,6 +4914,32 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4439
4914
|
const page = all.slice(offset, offset + limit).map((row) => revisionView(entry.agent, row));
|
|
4440
4915
|
return send(res, 200, { revisions: page, next_cursor: nextCursor(offset + limit, all.length) });
|
|
4441
4916
|
}
|
|
4917
|
+
case "getAgentPackage": {
|
|
4918
|
+
const entry = await needAgent(id);
|
|
4919
|
+
const { agent, revision } = entry;
|
|
4920
|
+
// An agent whose source is somewhere else has no package here: its project or application holds it.
|
|
4921
|
+
const body = (revision?.body ?? {});
|
|
4922
|
+
const elsewhere = ownedElsewhere(agent) ? "another system's agent, which that system defines" : body.native ? "a native agent, which its project on its own machine defines" : body.cli_learning ? "a CLI learning agent, which its CLI's sessions define" : body.sdk ? "an SDK agent, which its application's code defines" : undefined;
|
|
4923
|
+
if (elsewhere)
|
|
4924
|
+
throw new ApiError("not_exportable", `The agent ${id} is ${elsewhere}: export it from there.`);
|
|
4925
|
+
if (!revision || revision.kind !== "agentic")
|
|
4926
|
+
throw new ApiError("not_exportable", `The agent ${id} ${revision ? "is a workflow, and a template package holds an agent" : "has no revision to export"}.`);
|
|
4927
|
+
// Its triggers: those that start its runs and those that message one of them (each row names the agent it runs as).
|
|
4928
|
+
const own = new Set((await store.triggers.list(id)).map((row) => row.id));
|
|
4929
|
+
const views = (await triggers.list()).triggers.filter((view) => own.has(view.id));
|
|
4930
|
+
const answer = agentPackage({
|
|
4931
|
+
agent: { id, name: agent.name, description: agent.description ?? null },
|
|
4932
|
+
definition: definitionOf(agent, revision, entry.version),
|
|
4933
|
+
skills: (isObject(revision.skills) ? revision.skills : {}),
|
|
4934
|
+
template: entry.template ? { id: entry.template.id, version: entry.template.version, ...(entry.template.secrets ? { secrets: entry.template.secrets } : {}) } : null,
|
|
4935
|
+
origin: entry.template ? registry.get(entry.template.id) : undefined,
|
|
4936
|
+
servers: mcpMeta,
|
|
4937
|
+
triggers: views,
|
|
4938
|
+
signIns: await store.signIns.list(id),
|
|
4939
|
+
now: options.triggerClock?.now() ?? Date.now(),
|
|
4940
|
+
});
|
|
4941
|
+
return send(res, 200, answer);
|
|
4942
|
+
}
|
|
4442
4943
|
case "setCurrent": {
|
|
4443
4944
|
// The body read first, outside the agent's delete turn; the move made in it (agentWrite), as an edit's revision is:
|
|
4444
4945
|
// one whose body arrives while the agent is purged is 410 (the store refuses it too, AgentPurged).
|
|
@@ -4454,6 +4955,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4454
4955
|
const candidate = await agents.revision(id, revision);
|
|
4455
4956
|
if (!candidate)
|
|
4456
4957
|
throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
|
|
4958
|
+
if (sourceSyncOf(candidate.revision.body)?.id !== sourceSyncOf(entry.revision?.body)?.id)
|
|
4959
|
+
throw new ApiError("input_invalid", "A revision restore cannot change this agent’s source ownership. Keep a revision from after Move.");
|
|
4457
4960
|
if (stable(cliLearningOf(candidate.revision.body)) !== stable(cliLearningOf(entry.revision?.body)))
|
|
4458
4961
|
throw new ApiError("input_invalid", "A revision restore cannot change the enrolled CLI learning connection.");
|
|
4459
4962
|
if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
|
|
@@ -4474,16 +4977,23 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4474
4977
|
case "deleteAgent": {
|
|
4475
4978
|
// Another system's agent deleted whole; one made here purged once archived (agent-delete.ts). One delete of an agent
|
|
4476
4979
|
// at a time, the agent read in its turn, so a DELETE after one that finished is 404 (deleted) or 204 (purged).
|
|
4477
|
-
|
|
4478
|
-
|
|
4479
|
-
|
|
4480
|
-
|
|
4481
|
-
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4980
|
+
try {
|
|
4981
|
+
await deleteInTurn(id, async () => {
|
|
4982
|
+
const { agent } = await needAgent(id);
|
|
4983
|
+
if (agent.purgedAt !== null)
|
|
4984
|
+
return;
|
|
4985
|
+
if (ownedElsewhere(agent))
|
|
4986
|
+
return deleteExternalAgent(agentDeleteHost, id);
|
|
4987
|
+
if (agent.archivedAt === null)
|
|
4988
|
+
throw new ApiError("agent_not_archived", `The agent ${id} is not archived: archive it first (POST /v2/agents/${id}/archive), which stops new runs and turns its triggers off, then send the DELETE again. Nothing was purged.`);
|
|
4989
|
+
await purgeAgent(agentDeleteHost, id);
|
|
4990
|
+
});
|
|
4991
|
+
}
|
|
4992
|
+
finally {
|
|
4993
|
+
// An upload its purge took with it is no longer served: also after a purge that committed and then failed, and on
|
|
4994
|
+
// the DELETE sent again. A store that cannot answer leaves it to the next DELETE, or the next start's load.
|
|
4995
|
+
await dropRemovedUploads({ registry, store }).catch(() => undefined);
|
|
4996
|
+
}
|
|
4487
4997
|
res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
4488
4998
|
return void res.end();
|
|
4489
4999
|
}
|
|
@@ -4498,7 +5008,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4498
5008
|
// the archive, each turned on again by PATCH /triggers/{id} {enabled: true}.
|
|
4499
5009
|
// In the agent's delete turn (agentWrite): an unarchive sent while its purge runs waits for it and is 410, so no
|
|
4500
5010
|
// run of it starts between the purge's live check and its tombstone.
|
|
4501
|
-
|
|
5011
|
+
// On an API-only server with the launch hook, which serves no trigger route to turn one on, the unarchive turns its
|
|
5012
|
+
// schedule and feed triggers on again (the ones its apply makes there).
|
|
5013
|
+
const turnOn = options.apiOnly && options.launchHook ? (source) => API_ONLY_HOOKED_KINDS.has(source.kind) : undefined;
|
|
5014
|
+
const triggersOff = await agentWrite(id, () => (found.name === "archiveAgent" ? triggers.agentArchived(id) : triggers.agentUnarchived(id, turnOn)));
|
|
4502
5015
|
// An archived agent's own computer is deleted (an unarchived one gets a new one at its next persistent run).
|
|
4503
5016
|
if (found.name === "archiveAgent")
|
|
4504
5017
|
reconcileComputer(id);
|
|
@@ -4512,7 +5025,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4512
5025
|
const entry = await needAgent(id);
|
|
4513
5026
|
const controller = new AbortController();
|
|
4514
5027
|
req.once("close", () => controller.abort());
|
|
4515
|
-
const agent = { id, archived: entry.agent.archivedAt != null, external: entry.agent
|
|
5028
|
+
const agent = { id, archived: entry.agent.archivedAt != null, external: ownedElsewhere(entry.agent), liveOn: (diskId) => liveRunsOnDisk(store.runs, id, diskId) };
|
|
4516
5029
|
return send(res, 200, await archilRoute(archil, found.name, { agent, signal: controller.signal }), { "cache-control": "no-store" });
|
|
4517
5030
|
}
|
|
4518
5031
|
case "forgetSignIn": {
|
|
@@ -4600,7 +5113,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4600
5113
|
}
|
|
4601
5114
|
case "deleteRun": {
|
|
4602
5115
|
// In its agent's delete turn (an agent's delete or purge, or another purge of one of its runs, finishes first), the
|
|
4603
|
-
// run read in that turn, so a DELETE after one that finished is 204 again (purgeRun: a purged run
|
|
5116
|
+
// run read in that turn, so a DELETE after one that finished is 204 again (purgeRun: a purged run's only work is
|
|
5117
|
+
// its learning folder's scrub, again).
|
|
4604
5118
|
const row = ID.test(id) ? await store.runs.get(id) : undefined;
|
|
4605
5119
|
if (!row)
|
|
4606
5120
|
throw new ApiError("not_found", `no run ${id}`);
|
|
@@ -5100,6 +5614,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5100
5614
|
// Never through `idempotent`: its record keeps the body, and a body may hold a credential.
|
|
5101
5615
|
case "listMcpServers":
|
|
5102
5616
|
return send(res, 200, await mcpServers.list());
|
|
5617
|
+
// Names only: what the API-only profile serves in place of the list.
|
|
5618
|
+
case "listMcpServerNames":
|
|
5619
|
+
return send(res, 200, { names: (await listMcpServers(store)).map((row) => row.name).sort() });
|
|
5103
5620
|
case "getMcpServer":
|
|
5104
5621
|
return send(res, 200, await mcpServers.get(id));
|
|
5105
5622
|
case "previewMcpServer":
|
|
@@ -5187,6 +5704,33 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5187
5704
|
const view = githubConnection();
|
|
5188
5705
|
return send(res, 200, view ? { connected: true, ...view } : { connected: false });
|
|
5189
5706
|
}
|
|
5707
|
+
case "listGitHubRepositories": {
|
|
5708
|
+
// The installations repaired from GitHub's own first, as getGitHubConnection does (at most once a minute): an
|
|
5709
|
+
// installation whose event was missed is listed, not hidden until a restart.
|
|
5710
|
+
await githubConnect.reconcile((detail) => triggers.turnOff("github", detail));
|
|
5711
|
+
const listed = await githubConnect.repositories(stopping.signal);
|
|
5712
|
+
if ("unusable" in listed)
|
|
5713
|
+
throw new ApiError("github_not_connected", listed.unusable);
|
|
5714
|
+
return send(res, 200, listed, { "cache-control": "no-store" });
|
|
5715
|
+
}
|
|
5716
|
+
case "listSuggestions":
|
|
5717
|
+
// The same repair first: the page's Refresh and Check again read installations as GitHub has them.
|
|
5718
|
+
await githubConnect.reconcile((detail) => triggers.turnOff("github", detail));
|
|
5719
|
+
return send(res, 200, await suggestions.list({ ...(url.searchParams.has("repo") ? { repo: url.searchParams.get("repo") } : {}), ...(url.searchParams.has("status") ? { status: url.searchParams.get("status") } : {}) }), { "cache-control": "no-store" });
|
|
5720
|
+
case "scanForSuggestions": {
|
|
5721
|
+
const scanned = await suggestions.scan(await bodyOf(req));
|
|
5722
|
+
return send(res, scanned.status, scanned.body, { location: `/v2/runs/${String(scanned.body.run_id)}` });
|
|
5723
|
+
}
|
|
5724
|
+
case "getSuggestion":
|
|
5725
|
+
return send(res, 200, await suggestions.get(id, stopping.signal, url.searchParams.get("name") ?? undefined), { "cache-control": "no-store" });
|
|
5726
|
+
case "discardSuggestion":
|
|
5727
|
+
return send(res, 200, await suggestions.discard(id));
|
|
5728
|
+
case "restoreSuggestion":
|
|
5729
|
+
return send(res, 200, await suggestions.restore(id));
|
|
5730
|
+
case "createSuggestedAgent": {
|
|
5731
|
+
const created = await suggestions.create(id, await bodyOf(req), stopping.signal);
|
|
5732
|
+
return send(res, created.status, created.body);
|
|
5733
|
+
}
|
|
5190
5734
|
case "disconnectGitHub": {
|
|
5191
5735
|
const view = githubConnection();
|
|
5192
5736
|
if (!view)
|
|
@@ -5255,7 +5799,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5255
5799
|
const costStop = await costStopOverStore(store, id);
|
|
5256
5800
|
const body = entry.revision?.body;
|
|
5257
5801
|
const modelEnv = !body || sdkOf(body) || nativeOf(body) ? env : envAtPlace(env, resolvePlace(body.place, fallbackPlace(entry.revision.kind === "workflow" ? "workflow" : "agentic", body.tools ?? [])));
|
|
5258
|
-
return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop)), learning_model: await learningModelOf(modelEnv, entry.revision) });
|
|
5802
|
+
return send(res, 200, { ...await agentLearning(data, id, await learningShown(id), counts, impact, (workflow) => servingStateOf(records, workflow, costStop), purgedOf), learning_model: await learningModelOf(modelEnv, entry.revision) });
|
|
5259
5803
|
}
|
|
5260
5804
|
case "getLearningCost": {
|
|
5261
5805
|
await needAgent(id);
|
|
@@ -5296,7 +5840,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5296
5840
|
const champion = championOf(records, workflow);
|
|
5297
5841
|
const record = champion?.digest === digest ? champion : undefined;
|
|
5298
5842
|
const commits = records.filter((one) => one.workflow === workflow && one.digest === digest && one.commit).map((one) => one.commit).reverse();
|
|
5299
|
-
const read = await workflowAtDigest(data, id, workflow, digest, commits).catch(() => undefined);
|
|
5843
|
+
const read = await workflowAtDigest(data, id, workflow, digest, commits, store).catch(() => undefined);
|
|
5300
5844
|
let doc;
|
|
5301
5845
|
try {
|
|
5302
5846
|
doc = read ? JSON.parse(read.text) : undefined;
|
|
@@ -5342,7 +5886,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5342
5886
|
}
|
|
5343
5887
|
case "listLearningLog":
|
|
5344
5888
|
await needAgent(id);
|
|
5345
|
-
return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id)));
|
|
5889
|
+
return send(res, 200, await learningLog(data, id, url.searchParams, await learningShown(id), purgedOf));
|
|
5346
5890
|
case "getLearningCorrections": {
|
|
5347
5891
|
await needAgent(id);
|
|
5348
5892
|
// corrections.md whole, as every run of the agent is served it under # Learned, with its ETag in the body and the header.
|
|
@@ -5369,10 +5913,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5369
5913
|
}
|
|
5370
5914
|
case "listLearnedWorkflowRevisions":
|
|
5371
5915
|
await needAgent(id);
|
|
5372
|
-
return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id)));
|
|
5916
|
+
return send(res, 200, await workflowRevisions(data, id, second, url.searchParams, await learningShown(id), purgedOf));
|
|
5373
5917
|
case "readLearningFile":
|
|
5374
5918
|
await needAgent(id);
|
|
5375
|
-
return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id)));
|
|
5919
|
+
return sendText(res, 200, await readLearnedFile(data, id, second, await learningShown(id), store));
|
|
5376
5920
|
case "retireLearningFile":
|
|
5377
5921
|
case "approveLearningFile":
|
|
5378
5922
|
case "restoreLearningFile": {
|
|
@@ -5495,14 +6039,24 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5495
6039
|
return send(res, 200, { templates: listed.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
|
|
5496
6040
|
}
|
|
5497
6041
|
case "importTemplate": {
|
|
5498
|
-
// Read from GitHub and checked; a dry run answers it (200), else it is stored and
|
|
5499
|
-
// package whole, its instructions and every skill file, for a person to read
|
|
5500
|
-
|
|
6042
|
+
// Read from GitHub, or uploaded whole ({files}), and checked; a dry run answers it (200), else it is stored and
|
|
6043
|
+
// served (201). The answer shows the package whole, its instructions and every skill file, for a person to read
|
|
6044
|
+
// before they apply it. An upload's body carries the package's bytes (base64 among them), up to the import's own
|
|
6045
|
+
// limit (TEMPLATE_UPLOAD_BODY).
|
|
6046
|
+
const body = await bodyOf(req, TEMPLATE_UPLOAD_BODY);
|
|
5501
6047
|
const done = new AbortController();
|
|
5502
6048
|
res.once("close", () => done.abort());
|
|
5503
6049
|
const imported = await importTemplate(importDeps, body, done.signal);
|
|
5504
|
-
const
|
|
5505
|
-
return send(res, imported.status, {
|
|
6050
|
+
const uploaded = imported.pkg.id.startsWith(UPLOAD_PREFIX);
|
|
6051
|
+
return send(res, imported.status, { ...packageDetail(imported.pkg, await computerHere([imported.pkg])), publisher_trusted: imported.trusted, stored: imported.status === 201, replaced: imported.replaced, console_url: imported.status === 201 ? templateLink(linkOrigin(req), imported.pkg.id) : uploaded ? templatesLink(linkOrigin(req)) : templateInstallLink(linkOrigin(req), imported.pkg.origin?.source ?? imported.pkg.id) });
|
|
6052
|
+
}
|
|
6053
|
+
case "getTemplate": {
|
|
6054
|
+
// One package whole, a bundled one's too: as the list shows it, with the files an import's answer shows, for a
|
|
6055
|
+
// person (or a coding agent) to read before they apply it.
|
|
6056
|
+
const pkg = registry.get(id);
|
|
6057
|
+
if (!pkg)
|
|
6058
|
+
throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
|
|
6059
|
+
return send(res, 200, { ...packageDetail(pkg, await computerHere([pkg])), console_url: templateLink(linkOrigin(req), pkg.id) });
|
|
5506
6060
|
}
|
|
5507
6061
|
case "deleteTemplate":
|
|
5508
6062
|
await deleteTemplate(importDeps, id);
|
|
@@ -5512,6 +6066,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5512
6066
|
if (!pkg)
|
|
5513
6067
|
throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
|
|
5514
6068
|
const body = await bodyOf(req);
|
|
6069
|
+
// A dry run writes nothing, so it keeps no Idempotency-Key record either: a retry reads the plan again.
|
|
6070
|
+
if (body.dry_run === true)
|
|
6071
|
+
return send(res, 200, await planTemplate(pkg, body));
|
|
5515
6072
|
// The Idempotency-Key's record keeps the agent and triggers, so a retry under the key gets the same apply; it never
|
|
5516
6073
|
// keeps a webhook trigger's secret (below).
|
|
5517
6074
|
let minted = new Map();
|
|
@@ -6145,6 +6702,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
6145
6702
|
// the store closes last.
|
|
6146
6703
|
closing = true;
|
|
6147
6704
|
stopping.abort();
|
|
6705
|
+
clearInterval(localSourceTimer);
|
|
6148
6706
|
// Cancel a pending ChatGPT callback without signing out or changing the saved credential.
|
|
6149
6707
|
plan.close();
|
|
6150
6708
|
const observationStopped = stopObservationRetention();
|
|
@@ -6167,6 +6725,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
6167
6725
|
await schemaSealed;
|
|
6168
6726
|
await installStopped;
|
|
6169
6727
|
await observationStopped;
|
|
6728
|
+
await localSourceSweep;
|
|
6170
6729
|
// The ends' follower stops before the webhooks it feeds and the store it reads.
|
|
6171
6730
|
clearTimeout(endsTimer);
|
|
6172
6731
|
await endsRead;
|
|
@@ -6211,6 +6770,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
6211
6770
|
dial: { ...(options.publicUrl ? { url: options.publicUrl.replace(/\/+$/, "") } : {}), tokens: attach.machineTokens, hub: attachHub },
|
|
6212
6771
|
localInstall,
|
|
6213
6772
|
own: mcpServers.own,
|
|
6773
|
+
...(fauxGitHub ? { fauxGitHub: { api: fauxGitHub.url, ...(fauxGitHub.web ? { web: fauxGitHub.web } : {}) } } : {}),
|
|
6214
6774
|
// Once: a second call, at any time, is the first one's promise, so a close repeated after the next server started
|
|
6215
6775
|
// never writes this data root's record again (the next server's, by then).
|
|
6216
6776
|
close: () => (stopped ??= stop()),
|