@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.51
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 +147 -0
- package/README.md +142 -17
- package/dist/agents-store.js +7 -3
- package/dist/api-only.d.ts +2 -1
- package/dist/api-only.js +3 -2
- package/dist/capacity.d.ts +50 -0
- package/dist/capacity.js +49 -0
- package/dist/cli-learning/claude-wire.d.ts +41 -0
- package/dist/cli-learning/claude-wire.js +258 -0
- package/dist/cli-learning/cli.d.ts +11 -0
- package/dist/cli-learning/cli.js +241 -0
- package/dist/cli-learning/codex-worktree.d.ts +10 -0
- package/dist/cli-learning/codex-worktree.js +119 -0
- package/dist/cli-learning/connections.d.ts +62 -0
- package/dist/cli-learning/connections.js +87 -0
- package/dist/cli-learning/entry.d.ts +1 -0
- package/dist/cli-learning/entry.js +4 -0
- package/dist/cli-learning/evidence.d.ts +78 -0
- package/dist/cli-learning/evidence.js +492 -0
- package/dist/cli-learning/hook.d.ts +33 -0
- package/dist/cli-learning/hook.js +544 -0
- package/dist/cli-learning/install.d.ts +33 -0
- package/dist/cli-learning/install.js +335 -0
- package/dist/cli-learning/observation-proof.d.ts +14 -0
- package/dist/cli-learning/observation-proof.js +10 -0
- package/dist/cli-learning/policy.d.ts +48 -0
- package/dist/cli-learning/policy.js +363 -0
- package/dist/cli-learning/schema.d.ts +16 -0
- package/dist/cli-learning/schema.js +27 -0
- package/dist/cli-learning/state.d.ts +23 -0
- package/dist/cli-learning/state.js +61 -0
- package/dist/cli.js +24 -2
- package/dist/console/assets/index-Bt1B51b7.js +733 -0
- package/dist/console/assets/index-sVftE9Ht.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/email/email-faux.d.ts +3 -1
- package/dist/email/email-faux.js +3 -2
- package/dist/email/routes.js +22 -12
- package/dist/harness-install.d.ts +6 -2
- package/dist/harness-install.js +40 -8
- package/dist/harness.d.ts +1 -1
- package/dist/harness.js +2 -2
- package/dist/learn/secrets.js +14 -3
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +1 -1
- package/dist/mcp-pin-first.js +2 -1
- package/dist/mcp-private-hosts.d.ts +24 -3
- package/dist/mcp-private-hosts.js +53 -3
- package/dist/model-gateway.d.ts +2 -0
- package/dist/model-gateway.js +3 -1
- package/dist/native/runtimes.d.ts +2 -0
- package/dist/native/runtimes.js +2 -0
- package/dist/observation/learning.d.ts +32 -0
- package/dist/observation/learning.js +66 -0
- package/dist/observation/observer.d.ts +8 -1
- package/dist/observation/observer.js +89 -9
- package/dist/observation/schema.js +12 -4
- package/dist/observation/usage-identity.d.ts +9 -0
- package/dist/observation/usage-identity.js +11 -0
- package/dist/openapi.js +89 -13
- package/dist/run-launch.d.ts +14 -0
- package/dist/run-launch.js +4 -0
- package/dist/run-view.d.ts +2 -0
- package/dist/run-view.js +12 -7
- package/dist/runner/adapter-loop.js +29 -26
- package/dist/runner/adapter-run-spec.js +2 -2
- package/dist/runner/beside.d.ts +13 -0
- package/dist/runner/beside.js +27 -8
- package/dist/runner/cli-run-spec.js +2 -2
- package/dist/runner/disk-free.d.ts +44 -0
- package/dist/runner/disk-free.js +96 -0
- package/dist/runner/feedback-round.d.ts +12 -8
- package/dist/runner/feedback-round.js +16 -30
- package/dist/runner/harness-loops.js +3 -1
- package/dist/runner/journal-kinds.d.ts +1 -1
- package/dist/runner/learning-end.js +4 -0
- package/dist/runner/main.d.ts +17 -6
- package/dist/runner/main.js +187 -45
- package/dist/runner/presence.d.ts +11 -2
- package/dist/runner/presence.js +31 -3
- package/dist/runner/run-child-host.d.ts +12 -15
- package/dist/runner/run-child-host.js +46 -108
- package/dist/runner/run-errors.js +2 -0
- package/dist/runner/runner-check.d.ts +51 -0
- package/dist/runner/runner-check.js +206 -0
- package/dist/runner/runner-metrics.d.ts +19 -0
- package/dist/runner/runner-metrics.js +49 -0
- package/dist/runner/runner.d.ts +37 -0
- package/dist/runner/runner.js +43 -3
- package/dist/runner/sdk-loop.js +34 -22
- package/dist/runs-over-store.d.ts +8 -1
- package/dist/runs-over-store.js +57 -9
- package/dist/sdk/runs.d.ts +22 -2
- package/dist/sdk/runs.js +103 -34
- package/dist/server.d.ts +3 -0
- package/dist/server.js +149 -26
- package/dist/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/start-switches.js +2 -0
- package/dist/stats.d.ts +4 -0
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.d.ts +12 -0
- package/dist/store/agent-body.js +16 -2
- package/dist/store/dialect.d.ts +2 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/postgres/connection.d.ts +5 -2
- package/dist/store/postgres/connection.js +19 -7
- package/dist/store/postgres/dialect.js +1 -0
- package/dist/store/postgres/migrate.d.ts +30 -0
- package/dist/store/postgres/migrate.js +72 -5
- package/dist/store/postgres/migration-lint.d.ts +8 -0
- package/dist/store/postgres/migration-lint.js +119 -0
- package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
- package/dist/store/postgres/store.d.ts +8 -3
- package/dist/store/postgres/store.js +31 -11
- package/dist/store/schema.d.ts +18 -1
- package/dist/store/schema.js +33 -2
- package/dist/store/sqlite/run-launch.d.ts +9 -1
- package/dist/store/sqlite/run-launch.js +44 -0
- package/dist/store/sqlite/store.d.ts +17 -0
- package/dist/store/sqlite/store.js +87 -10
- package/dist/store/store-schema.d.ts +34 -0
- package/dist/store/store-schema.js +125 -0
- package/dist/store/store.d.ts +53 -1
- package/dist/store/store.js +13 -0
- package/dist/store-reads/analytics.d.ts +3 -2
- package/dist/store-reads/analytics.js +20 -8
- package/dist/store-view.d.ts +4 -3
- package/dist/store-view.js +11 -7
- package/dist/templates.d.ts +3 -2
- package/dist/tool-gate.d.ts +4 -2
- package/dist/unified-usage.d.ts +24 -0
- package/dist/unified-usage.js +400 -0
- package/dist/uploads-archil.d.ts +100 -0
- package/dist/uploads-archil.js +430 -0
- package/dist/uploads.d.ts +55 -1
- package/dist/uploads.js +185 -98
- package/dist/validate.js +1 -1
- package/dist/workspace/archil-disk.d.ts +6 -5
- package/dist/workspace/archil-disk.js +27 -12
- package/dist/workspace/archil.js +3 -2
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/console/assets/index-D0mr9wfZ.css +0 -1
- package/dist/console/assets/index-D7G6o-1E.js +0 -720
package/dist/server.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { CliLearningConnections } from "./cli-learning/connections.js";
|
|
2
|
+
import { ObservationLearning } from "./observation/learning.js";
|
|
3
|
+
import { cliLearningOf } from "./store/agent-body.js";
|
|
1
4
|
import { maintainObservations, Observations } from './observation/observer.js';
|
|
2
5
|
import { isObservationRoute, observationHttp } from './observation/http.js';
|
|
3
6
|
import { SdkRuns, sdkOf, sdkRunSecret } from "./sdk/runs.js";
|
|
@@ -7,7 +10,7 @@ import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './
|
|
|
7
10
|
import { REMOTE_HISTORY_BODY_BYTES } from './native/history.js';
|
|
8
11
|
import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED, NATIVE_CAP_UNSUPPORTED } from "./native/binding.js";
|
|
9
12
|
import { discoverNative } from "./native/discovery.js";
|
|
10
|
-
import { isNativeRuntime } from "./native/runtimes.js";
|
|
13
|
+
import { isNativeRuntime, NATIVE_RUNTIME_FACTS } from "./native/runtimes.js";
|
|
11
14
|
import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
|
|
12
15
|
// The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
|
|
13
16
|
// token.
|
|
@@ -16,6 +19,7 @@ import { chmod, lstat, mkdir, readFile, realpath, rename, stat, writeFile } from
|
|
|
16
19
|
import { createServer } from "node:http";
|
|
17
20
|
import proxyaddr from "proxy-addr";
|
|
18
21
|
import { apiOnlyRefusal, servedApiOnly } from "./api-only.js";
|
|
22
|
+
import { capacityOverStore, capacityWindowOf } from "./capacity.js";
|
|
19
23
|
import { carriedFields } from "./answer-json.js";
|
|
20
24
|
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
21
25
|
import { pathToFileURL } from "node:url";
|
|
@@ -117,9 +121,12 @@ import { modelGatewayRoute, readSavedGateway, withSavedGateway } from "./model-g
|
|
|
117
121
|
import { CLAUDE_LOGIN_ROUTES, ClaudeLoginRefused, claudeLoginOf, claudeLoginRouteOff, claudeLoginSwitchedOff, claudeLoginSetting, claudeLoginView, dropRefusedLogin, envAtPlace, LOGIN_HARNESS, loginOf, startLoginHere, turnOffClaudeLogin, turnOnClaudeLogin, whyNotOneOwner, withClaudeLogin } from "./claude-login.js";
|
|
118
122
|
import { bootSealKey, parametersDigest, withSealKey } from "./seal-key.js";
|
|
119
123
|
import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
|
|
124
|
+
import { recordDataRoot } from "./runner/disk-free.js";
|
|
125
|
+
import { recordRunEnv, runFacingNames } from "./runner/runner-check.js";
|
|
120
126
|
import { DRAIN_TIMEOUT } from "./runner/beside.js";
|
|
121
127
|
import { analyticsFilter, analyticsView, statsView } from "./stats.js";
|
|
122
128
|
import { joinedBasis } from "./runner/metrics.js";
|
|
129
|
+
import { unifiedUsage } from "./unified-usage.js";
|
|
123
130
|
import { agentLoopOverStore } from "./store-reads/loop.js";
|
|
124
131
|
import { printable } from "./learn/index.js";
|
|
125
132
|
import { agentCostOverStore, agentLearningOverStore, costStopOverStore, learningCountsOverStore, learningSpendOverStore, runAllInOverStore, runLearningEnd } from "./store-reads/learning.js";
|
|
@@ -168,6 +175,7 @@ import { wakeAnsweredBySetting } from "./settings-wake.js";
|
|
|
168
175
|
import { toolSettingsOverStore } from "./tool-settings-store.js";
|
|
169
176
|
import { readApprovers, writeApprovers } from "./server-approvers.js";
|
|
170
177
|
import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
|
|
178
|
+
import { archilUploads, runKeepsUploads, UPLOAD_RETENTION_ENV, UPLOAD_SWEEP_EVERY_MS, uploadRetentionMs } from "./uploads-archil.js";
|
|
171
179
|
import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
|
|
172
180
|
import { recordingsOf, recordingsWorkspace } from "./run-recordings.js";
|
|
173
181
|
import { recordingsFolder } from "./workspace/paths.js";
|
|
@@ -292,6 +300,13 @@ export const ROUTES = [
|
|
|
292
300
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
|
|
293
301
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
|
|
294
302
|
{ method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
|
|
303
|
+
{ method: "POST", pattern: /^\/cli-learning\/connections$/, name: "enrollCliLearning" },
|
|
304
|
+
{ method: "GET", pattern: /^\/cli-learning\/connections$/, name: "listCliLearning" },
|
|
305
|
+
{ method: "DELETE", pattern: /^\/cli-learning\/connections\/([^/]+)$/, name: "revokeCliLearning" },
|
|
306
|
+
{ method: "POST", pattern: /^\/cli-learning\/connections\/([^/]+)\/runs$/, name: "startCliLearningRun" },
|
|
307
|
+
{ method: "GET", pattern: /^\/cli-learning\/runs\/([^/]+)$/, name: "getCliLearningRun" },
|
|
308
|
+
{ method: "POST", pattern: /^\/cli-learning\/runs\/([^/]+)\/events$/, name: "cliLearningEvents" },
|
|
309
|
+
{ method: "POST", pattern: /^\/cli-learning\/runs\/([^/]+)\/complete$/, name: "completeCliLearningRun" },
|
|
295
310
|
{ method: "POST", pattern: /^\/agents\/([^/]+)\/sdk-runs$/, name: "startSdkRun" },
|
|
296
311
|
{ method: "GET", pattern: /^\/sdk-runs\/([^/]+)$/, name: "getSdkRun" },
|
|
297
312
|
{ method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/events$/, name: "sdkRunEvents" },
|
|
@@ -391,6 +406,8 @@ export const ROUTES = [
|
|
|
391
406
|
{ method: "POST", pattern: /^\/quotes$/, name: "createQuote", capability: "quotes" },
|
|
392
407
|
{ method: "GET", pattern: /^\/usage$/, name: "getUsage" },
|
|
393
408
|
{ method: "GET", pattern: /^\/stats$/, name: "getStats" },
|
|
409
|
+
// The runs waiting and held, the live runners and their free slots, and the recent hand-backs (capacity.ts).
|
|
410
|
+
{ method: "GET", pattern: /^\/capacity$/, name: "getCapacity" },
|
|
394
411
|
{ method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
|
|
395
412
|
{ method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
|
|
396
413
|
{ method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
|
|
@@ -946,6 +963,11 @@ async function startHolding(options, data, checked, stops) {
|
|
|
946
963
|
// there is no keeping one in the clear.
|
|
947
964
|
const seal = await bootSealKey(store, data);
|
|
948
965
|
stops.push(async () => seal.release());
|
|
966
|
+
// What a runner apart reads to tell its disk from this server's, and its environment's gaps (runner/disk-free.ts,
|
|
967
|
+
// runner/runner-check.ts): this data root's id, and the names (never the values) of the run-facing environment this
|
|
968
|
+
// server holds, each said in the store at every start, replacing the last start's.
|
|
969
|
+
await recordDataRoot(store, data);
|
|
970
|
+
await recordRunEnv(store, runFacingNames((name) => secret(name) ?? base[name], Object.keys(base)));
|
|
949
971
|
// Its runners on other hosts (AGENTRUN_RUNNER_HOSTS): a viewer's row naming one of their hosts is dialled there, with
|
|
950
972
|
// the proxy's proof under the seal key (live-reach.ts); any other host is never dialled. A hosted machine a runner in a
|
|
951
973
|
// process of its own made is relayed to that runner's attach listener the same way (dial-relay.ts).
|
|
@@ -1399,6 +1421,31 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1399
1421
|
if (!row || FINAL_STATES.includes(row.state))
|
|
1400
1422
|
await uploads.release(runId);
|
|
1401
1423
|
}
|
|
1424
|
+
// Mode 2 (uploads-archil.ts): the uploads on this server's own Archil disk, and each run's placed in its folder at its
|
|
1425
|
+
// start, so its runner reads no upload. Mode 1 keeps them in this data directory (uploads above), as before.
|
|
1426
|
+
const archilFiles = archilUploads({ store, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl ? { control: options.archilControl } : {}) });
|
|
1427
|
+
/** Where the files routes find uploads now: the uploads disk in Mode 2, else this data directory. `make`: an upload,
|
|
1428
|
+
* which makes the uploads disk when there is none. */
|
|
1429
|
+
const uploadsHere = async (make = false) => (await archilFiles.here(make)) ?? uploads;
|
|
1430
|
+
const uploadRetention = uploadRetentionMs(options.uploadRetention ?? process.env[UPLOAD_RETENTION_ENV]);
|
|
1431
|
+
if (uploadRetention !== undefined) {
|
|
1432
|
+
// An uploaded file no run names, older than the retention, is deleted from the uploads disk (Mode 2 only): once an
|
|
1433
|
+
// hour, each sweep after the last one ends.
|
|
1434
|
+
let sweeping = Promise.resolve();
|
|
1435
|
+
const sweepUploads = () => {
|
|
1436
|
+
sweeping = sweeping.then(async () => {
|
|
1437
|
+
const removed = await archilFiles.sweep(uploadRetention, runKeepsUploads(store));
|
|
1438
|
+
if (removed.length)
|
|
1439
|
+
log?.(logLine("uploads_expired", { removed: removed.length }));
|
|
1440
|
+
}).catch((error) => void log?.(logLine("uploads_sweep_failed", { why: String(error?.message ?? error).slice(0, 300) })));
|
|
1441
|
+
};
|
|
1442
|
+
const uploadsTimer = setInterval(sweepUploads, UPLOAD_SWEEP_EVERY_MS);
|
|
1443
|
+
uploadsTimer.unref();
|
|
1444
|
+
stops.push(async () => {
|
|
1445
|
+
clearInterval(uploadsTimer);
|
|
1446
|
+
await sweeping;
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1402
1449
|
const documents = options.documents ?? process.env[DOCUMENTS_ENV];
|
|
1403
1450
|
if (documents !== undefined && !(await stat(documents).then((info) => info.isDirectory(), () => false)))
|
|
1404
1451
|
throw new Error(`the documents directory ${documents} is not a directory`);
|
|
@@ -1451,7 +1498,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1451
1498
|
// no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
|
|
1452
1499
|
// needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
|
|
1453
1500
|
// reads launch.model alone).
|
|
1454
|
-
const modelOf = (_entry, revision) => nativeOf(revision.body) ? Promise.resolve(undefined) : runModelRef(env, revision);
|
|
1501
|
+
const modelOf = (_entry, revision) => (nativeOf(revision.body) || cliLearningOf(revision.body)) ? Promise.resolve(undefined) : runModelRef(env, revision);
|
|
1455
1502
|
// Why no runner here can take a run, while every runner there refused to claim (runner/presence.ts): read from the
|
|
1456
1503
|
// store at each start, capabilities and health answer, so a runner in another process (or on another host over one
|
|
1457
1504
|
// Postgres) counts as the one beside this server does, and a runner that can claim, once there, clears it at once.
|
|
@@ -1487,8 +1534,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1487
1534
|
told: (error) => told(error),
|
|
1488
1535
|
runnable,
|
|
1489
1536
|
pinFirst: (revision) => pinFirst(revision),
|
|
1490
|
-
readyFiles: (ids) =>
|
|
1491
|
-
files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
|
|
1537
|
+
readyFiles: async (ids) => (await uploadsHere()).readyFiles(ids),
|
|
1538
|
+
files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId), place: (runId, agentId, launch) => archilFiles.place(runId, agentId, launch) },
|
|
1492
1539
|
fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
|
|
1493
1540
|
// The run's Archil disk for its launch record (run-launch.ts archilDisk): the body's, else its agent's when it has one.
|
|
1494
1541
|
// A disk the body names is read at Archil once, before the run is made (archil-routes.ts checkLaunchDisk): one that is
|
|
@@ -1569,7 +1616,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
1569
1616
|
// (liveViewerLink, the one the runner's browser tool wrote under its claim), opened with the server's seal key. The
|
|
1570
1617
|
// timeline route keeps its own stub (store-reads journal + SSE) until E2c's timeline lands.
|
|
1571
1618
|
const runReadsDeps = {
|
|
1572
|
-
runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own") }),
|
|
1619
|
+
runWorkspace: (_store, runId) => serverRunWorkspace(store, runId, { data, sealKey, env: withSecrets(process.env, "own"), ...(options.archilControl?.makeDisk ? { makeDisk: options.archilControl.makeDisk } : {}) }),
|
|
1573
1620
|
recordings: async (_store, runId) => {
|
|
1574
1621
|
const run = await store.runs.get(runId);
|
|
1575
1622
|
return run ? recordingsWorkspace(recordingsFolder(data, run.agentId, runId)) : null;
|
|
@@ -2482,6 +2529,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2482
2529
|
* does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). `price`:
|
|
2483
2530
|
* what prices an OpenRouter decision model under that cap; a start's reads OpenRouter's catalog (decisionPrice). */
|
|
2484
2531
|
async function runnable(revision, place, { capped = false, price = decisionPrice } = {}) {
|
|
2532
|
+
if (cliLearningOf(revision.body))
|
|
2533
|
+
throw new ApiError("agent_not_runnable", "Continue in the original CLI session; this connection records learning without launching its tools.");
|
|
2485
2534
|
if (sdkOf(revision.body))
|
|
2486
2535
|
throw new ApiError("agent_not_runnable", "This agent runs in its backend SDK. Call its SDK wrapper to start a task; AgentRun does not launch its tools or credentials.");
|
|
2487
2536
|
const native = nativeOf(revision.body);
|
|
@@ -2647,7 +2696,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2647
2696
|
throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
|
|
2648
2697
|
return { warnings: [], stamp: {} };
|
|
2649
2698
|
}
|
|
2650
|
-
if (sdkOf(body))
|
|
2699
|
+
if (cliLearningOf(body) || sdkOf(body))
|
|
2651
2700
|
return { warnings: [], stamp: {} };
|
|
2652
2701
|
// An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
|
|
2653
2702
|
const harnessId = revision.kind === "agentic" ? harnessOfBody(body) : undefined;
|
|
@@ -2980,7 +3029,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
2980
3029
|
// (catchup_window_s and max_active_runs the package leaves out back to their defaults, as a fresh apply makes them); a new name is made; one the package
|
|
2981
3030
|
// marked and no longer lists is removed (`removing`). Each trigger the apply makes or keeps is marked as the package's; each write to one the agent had is made only while it
|
|
2982
3031
|
// is still the agent's: one a PATCH moved away meanwhile is neither changed nor removed, and its name is made anew.
|
|
2983
|
-
|
|
3032
|
+
// Each trigger it made or kept, in the package's order, as it stands after its write: the answer's trigger_ids and
|
|
3033
|
+
// triggers (its name, its kind, and whether it is on).
|
|
3034
|
+
const answered = [];
|
|
3035
|
+
const list = (view) => answered.push({ trigger_id: view.id, name: view.name, kind: view.source.kind, enabled: view.enabled });
|
|
2984
3036
|
// The triggers this apply made (never one it changed in place): what a refusal's undo removes.
|
|
2985
3037
|
const madeNow = [];
|
|
2986
3038
|
// Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
|
|
@@ -3014,8 +3066,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3014
3066
|
// The package's settings whole: one its version leaves out goes back to what a fresh apply makes (POST
|
|
3015
3067
|
// /triggers' default), never kept from the version before. PATCH reads null as no cap.
|
|
3016
3068
|
const patch = { ...sent, catchup_window_s: sent.catchup_window_s ?? CATCHUP_WINDOW_S, max_active_runs: sent.max_active_runs ?? null };
|
|
3017
|
-
|
|
3018
|
-
|
|
3069
|
+
const changed = await triggers.update(was.id, source ? { ...patch, source } : patch, own).catch(movedAway);
|
|
3070
|
+
if (changed) {
|
|
3071
|
+
list(changed);
|
|
3019
3072
|
continue;
|
|
3020
3073
|
}
|
|
3021
3074
|
was = undefined;
|
|
@@ -3030,8 +3083,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3030
3083
|
was = undefined;
|
|
3031
3084
|
else if (isObject(left) && isObject(left.composio) && left.composio.done === false)
|
|
3032
3085
|
throw new ApiError("upstream_failed", `The ${pkg.name} template's trigger ${String(trigger.name).trim()} changed, so its old Composio trigger instance must go before the new one is made, and Composio didn't delete it: the new one was not made, and the old trigger is kept here as it was. ${String(left.composio.note ?? "")} Then apply again.`.trim());
|
|
3033
|
-
const
|
|
3034
|
-
|
|
3086
|
+
const created = await triggers.create(was && !was.enabled ? { ...aimed, enabled: false } : aimed, { templateId: pkg.id });
|
|
3087
|
+
const { id: madeId, secret } = created;
|
|
3088
|
+
list(created);
|
|
3035
3089
|
madeNow.push(madeId);
|
|
3036
3090
|
if (secret)
|
|
3037
3091
|
secrets.push({ trigger_id: madeId, secret });
|
|
@@ -3095,7 +3149,10 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3095
3149
|
const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
|
|
3096
3150
|
// Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
|
|
3097
3151
|
const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
|
|
3098
|
-
|
|
3152
|
+
// What the apply did to the agent: made it, wrote a new revision, or wrote none (an update whose package and
|
|
3153
|
+
// parameters the current revision already holds: commitAgent keeps that revision).
|
|
3154
|
+
const agentChange = !onto ? "made" : entry.revision?.id === onto.revision?.id ? "unchanged" : "updated";
|
|
3155
|
+
const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, revision_version: entry.version, agent_change: agentChange, servers: used, trigger_ids: answered.map((one) => one.trigger_id), triggers: answered, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...composioSkipped, ...feedsSkipped, ...leftThere, ...appShort, ...twins] };
|
|
3099
3156
|
return { applied, minted, updated: onto !== undefined };
|
|
3100
3157
|
}
|
|
3101
3158
|
/** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
|
|
@@ -3264,6 +3321,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3264
3321
|
* (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
|
|
3265
3322
|
async function createInlineRun(req) {
|
|
3266
3323
|
const { body, handed } = handedLaunchSecrets(await bodyOf(req));
|
|
3324
|
+
if (isObject(body.definition) && body.definition.cli_learning !== undefined)
|
|
3325
|
+
throw new ApiError("input_invalid", "CLI learning references are registered only through /cli-learning/connections on the source machine.");
|
|
3267
3326
|
if (isObject(body.definition) && body.definition.native !== undefined)
|
|
3268
3327
|
throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
|
|
3269
3328
|
const { external, definition, skills, note, revision: pinned, ...run } = body;
|
|
@@ -3916,7 +3975,11 @@ async function startHolding(options, data, checked, stops) {
|
|
|
3916
3975
|
// runner_refused: why no runner here can take a run, in their words, while every runner there refused to claim
|
|
3917
3976
|
// (runner/presence.ts); null while one can, or none is there yet.
|
|
3918
3977
|
const runnerRefused = (await refusedNow().catch(() => undefined)) ?? null;
|
|
3919
|
-
|
|
3978
|
+
// store_schema: the store's version and runner floor now, beside this build's (Store.schemaState), for a deploy's
|
|
3979
|
+
// skew check; left out when the store cannot say (a read that failed).
|
|
3980
|
+
const state = await store.schemaState?.().catch(() => undefined);
|
|
3981
|
+
const storeSchema = state ? { store_schema: { version: state.version, runner_floor: state.runnerFloor, known: state.known } } : {};
|
|
3982
|
+
return send(res, 200, { ...answer, ...storeSchema, runner_refused: runnerRefused, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
|
|
3920
3983
|
}
|
|
3921
3984
|
if (found.name === "getOpenapi")
|
|
3922
3985
|
return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
|
|
@@ -4094,6 +4157,48 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4094
4157
|
const commandId = decodeURIComponent(parts[2]);
|
|
4095
4158
|
return send(res, 200, found.name === "remoteCommandEvents" ? await broker.events(connectorId, commandId, body) : await broker.complete(connectorId, commandId, body));
|
|
4096
4159
|
}
|
|
4160
|
+
if (found.name === "startCliLearningRun") {
|
|
4161
|
+
if (options.apiOnly || options.publicUrl || !isLoopback(host) || !isLoopback(req.socket.remoteAddress ?? ""))
|
|
4162
|
+
throw new ApiError("forbidden", "CLI learning runs require the enrolled local source server.");
|
|
4163
|
+
const connectionId = decodeURIComponent(found.pattern.exec(path)[1]);
|
|
4164
|
+
const broker = new CliLearningConnections(store, sdkSecret);
|
|
4165
|
+
const connection = await broker.authenticate(connectionId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
|
|
4166
|
+
if (!req.headers["idempotency-key"])
|
|
4167
|
+
throw new ApiError("bad_request", "A CLI prompt window requires Idempotency-Key.");
|
|
4168
|
+
const body = await bodyOf(req);
|
|
4169
|
+
if (Object.keys(body).some(key => !["session_id", "turn_id", "input", "instructions", "policy_complete", "model"].includes(key)) || typeof body.session_id !== "string" || !body.session_id || body.session_id.length > 256 || typeof body.turn_id !== "string" || !body.turn_id || body.turn_id.length > 256 || typeof body.policy_complete !== "boolean")
|
|
4170
|
+
throw new ApiError("input_invalid", "Supply session_id, turn_id, input, instructions, and explicit policy_complete.");
|
|
4171
|
+
const entry = await needAgent(connection.agent_id);
|
|
4172
|
+
const runtime = NATIVE_RUNTIME_FACTS[connection.runtime].captureRuntime;
|
|
4173
|
+
const sdk = new SdkRuns(store, data, sdkSecret, () => [...serverSecrets(), broker.token(connection)], [], "cli");
|
|
4174
|
+
const input = { runtime, input: body.input, instructions: body.instructions, ...(body.model !== undefined ? { model: body.model } : {}) };
|
|
4175
|
+
const key = `cli-window:${connectionId}:${connection.generation}:${createHash("sha256").update(`${body.session_id}\0${body.turn_id}`).digest("hex")}`;
|
|
4176
|
+
const fingerprint = createHash("sha256").update(stable(body)).digest("hex");
|
|
4177
|
+
const answer = await idempotent(req, `${path}:${connection.generation}`, body, async () => ({ status: 201, body: await sdk.start(entry, input, startDeps, { key, fingerprint }, { check: async () => { } }, linkOrigin(req), { runtime, connection_id: connectionId, connection_generation: connection.generation, session_id: body.session_id, turn_id: body.turn_id, instructions: String(body.instructions ?? ""), policy_complete: body.policy_complete }) }));
|
|
4178
|
+
const receipt = await sdk.receipt(answer.body.run_id, linkOrigin(req));
|
|
4179
|
+
await broker.recordWindow(connectionId, connection.generation, receipt.run_id, body.session_id);
|
|
4180
|
+
return send(res, answer.status, receipt, answer.headers);
|
|
4181
|
+
}
|
|
4182
|
+
if (["getCliLearningRun", "cliLearningEvents", "completeCliLearningRun"].includes(found.name)) {
|
|
4183
|
+
const runId = decodeURIComponent(found.pattern.exec(path)[1]);
|
|
4184
|
+
const authentication = new SdkRuns(store, data, sdkSecret, serverSecrets, [], "cli");
|
|
4185
|
+
await authentication.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
|
|
4186
|
+
const launch = (await store.runs.launch(runId)).body;
|
|
4187
|
+
if (!launch.cli_learning)
|
|
4188
|
+
throw new ApiError("not_found", "This is not a CLI learning prompt window.");
|
|
4189
|
+
const connection = await new CliLearningConnections(store, sdkSecret).get(launch.cli_learning.connection_id);
|
|
4190
|
+
if (!connection.active || connection.generation !== launch.cli_learning.connection_generation)
|
|
4191
|
+
throw new ApiError("unauthenticated", "The CLI learning connection was disconnected.");
|
|
4192
|
+
const sdk = new SdkRuns(store, data, sdkSecret, () => [...serverSecrets(), new CliLearningConnections(store, sdkSecret).token(connection)], [], "cli");
|
|
4193
|
+
if (found.name === "cliLearningEvents")
|
|
4194
|
+
return send(res, 200, await sdk.events(runId, await bodyOf(req)));
|
|
4195
|
+
if (found.name === "completeCliLearningRun") {
|
|
4196
|
+
const result = await sdk.complete(runId, await bodyOf(req));
|
|
4197
|
+
await new CliLearningConnections(store, sdkSecret).recordWindow(connection.connection_id, connection.generation, runId, launch.cli_learning.session_id);
|
|
4198
|
+
return send(res, 200, result);
|
|
4199
|
+
}
|
|
4200
|
+
return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
|
|
4201
|
+
}
|
|
4097
4202
|
if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
|
|
4098
4203
|
const runId = decodeURIComponent(found.pattern.exec(path)[1]);
|
|
4099
4204
|
const sdk = new SdkRuns(store, data, sdkSecret, serverSecrets, tokens.map((entry) => entry.token));
|
|
@@ -4110,7 +4215,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4110
4215
|
}
|
|
4111
4216
|
if (found.capability)
|
|
4112
4217
|
throw unsupported(found.capability, UNSUPPORTED[found.capability]);
|
|
4113
|
-
if (["discoverNative", "connectNative"].includes(found.name) && (options.apiOnly || options.publicUrl || !isLoopback(host)))
|
|
4218
|
+
if (["discoverNative", "connectNative", "enrollCliLearning"].includes(found.name) && (options.apiOnly || options.publicUrl || !isLoopback(host)))
|
|
4114
4219
|
throw new ApiError("forbidden", "Native connections require AgentRun on the source machine, bound to loopback without a public URL. A hosted browser cannot discover your laptop.");
|
|
4115
4220
|
const [, first, second] = found.pattern.exec(path);
|
|
4116
4221
|
const id = first ? decodeURIComponent(first) : "";
|
|
@@ -4129,6 +4234,13 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4129
4234
|
}
|
|
4130
4235
|
}
|
|
4131
4236
|
switch (found.name) {
|
|
4237
|
+
case "enrollCliLearning": {
|
|
4238
|
+
if (!isLoopback(req.socket.remoteAddress ?? ""))
|
|
4239
|
+
throw new ApiError("forbidden", "CLI learning enrollment must come from the local source machine.");
|
|
4240
|
+
return send(res, 201, await new CliLearningConnections(store, sdkSecret).enroll(await bodyOf(req)));
|
|
4241
|
+
}
|
|
4242
|
+
case "listCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).list());
|
|
4243
|
+
case "revokeCliLearning": return send(res, 200, await new CliLearningConnections(store, sdkSecret).revoke(id));
|
|
4132
4244
|
case "startSdkRun": {
|
|
4133
4245
|
if (!req.headers["idempotency-key"])
|
|
4134
4246
|
throw new ApiError("bad_request", "An SDK run requires Idempotency-Key so a retried start never duplicates execution.");
|
|
@@ -4157,7 +4269,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4157
4269
|
const days = Number(url.searchParams.get("days") ?? 30);
|
|
4158
4270
|
if (!Number.isInteger(days) || days < 1 || days > 31)
|
|
4159
4271
|
throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
|
|
4160
|
-
return send(res, 200, await new Observations(store).snapshot(days, url.searchParams.get("session_id") ?? undefined));
|
|
4272
|
+
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));
|
|
4161
4273
|
}
|
|
4162
4274
|
case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
|
|
4163
4275
|
case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
|
|
@@ -4196,6 +4308,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4196
4308
|
}
|
|
4197
4309
|
case "createAgent": {
|
|
4198
4310
|
const body = await bodyOf(req);
|
|
4311
|
+
if (isObject(body.definition) && body.definition.cli_learning !== undefined)
|
|
4312
|
+
throw new ApiError("input_invalid", "CLI learning references are registered only through /cli-learning/connections on the source machine.");
|
|
4199
4313
|
if (isObject(body.definition) && body.definition.native !== undefined)
|
|
4200
4314
|
throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine.");
|
|
4201
4315
|
const answer = await idempotent(req, "/agents", body, async () => {
|
|
@@ -4242,6 +4356,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4242
4356
|
// contract's is the definition itself, and takes the contract's preconditions: If-Match, and a version past the
|
|
4243
4357
|
// current one.
|
|
4244
4358
|
const contract = !("definition" in body);
|
|
4359
|
+
const cliEdit = contract ? body.cli_learning : isObject(body.definition) ? body.definition.cli_learning : undefined;
|
|
4360
|
+
if (cliEdit !== undefined && stable(cliEdit) !== stable(cliLearningOf(entry.revision?.body)))
|
|
4361
|
+
throw new ApiError("input_invalid", "CLI learning bindings are changed only through their enrollment endpoints.");
|
|
4245
4362
|
const nativeEdit = contract ? body.native : isObject(body.definition) ? body.definition.native : undefined;
|
|
4246
4363
|
if (nativeEdit !== undefined && stable(nativeEdit) !== stable(nativeOf(entry.revision?.body)))
|
|
4247
4364
|
throw new ApiError("input_invalid", "Native references are changed only through the native connection endpoints. Normal edits retain the existing reference.");
|
|
@@ -4289,6 +4406,8 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4289
4406
|
const candidate = await agents.revision(id, revision);
|
|
4290
4407
|
if (!candidate)
|
|
4291
4408
|
throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
|
|
4409
|
+
if (stable(cliLearningOf(candidate.revision.body)) !== stable(cliLearningOf(entry.revision?.body)))
|
|
4410
|
+
throw new ApiError("input_invalid", "A revision restore cannot change the enrolled CLI learning connection.");
|
|
4292
4411
|
if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
|
|
4293
4412
|
throw new ApiError("input_invalid", "This revision changes the native connection. Reconnect or verify through the native connection controls; ordinary revision restore cannot change its source or connection state.");
|
|
4294
4413
|
if (nativeOf(candidate.revision.body)) {
|
|
@@ -4487,7 +4606,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4487
4606
|
throw invalid([{ field: "label", reason: "wrong_type", message: `label is a string of at most ${LABEL_MAX} characters: the grade's words` }]);
|
|
4488
4607
|
// A run that reads ended while it still learns from that end (its look-back: store-view.ts lookingBackEnd) is graded
|
|
4489
4608
|
// once that ends: its row is not ended yet, and the round a grade opens reopens only an ended run.
|
|
4490
|
-
if (!FINAL_STATES.includes(row.state) && (await lookingBackEnd(store, row
|
|
4609
|
+
if (!FINAL_STATES.includes(row.state) && (await lookingBackEnd(store, row)))
|
|
4491
4610
|
throw new ApiError("run_learning", "The run is still learning from its answer: grade it once that ends.");
|
|
4492
4611
|
if (!FINAL_STATES.includes(row.state))
|
|
4493
4612
|
throw invalid([{ field: "run_id", reason: "not_allowed", message: "A run is graded once it has ended." }]);
|
|
@@ -4770,8 +4889,9 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4770
4889
|
case "createFile": {
|
|
4771
4890
|
// A `path` in the query, or a body that is not JSON: the file sent in one call, its bytes the body. Else the
|
|
4772
4891
|
// contract's JSON reservation, its bytes sent after with PUT /files/{file_id}.
|
|
4892
|
+
const kept = await uploadsHere(true);
|
|
4773
4893
|
if (url.searchParams.has("path") || !isJson(req)) {
|
|
4774
|
-
const received = await
|
|
4894
|
+
const received = await kept.take(url.searchParams, req.headers["content-type"], req);
|
|
4775
4895
|
try {
|
|
4776
4896
|
const answer = await idempotent(req, "/files", received.fingerprint, async () => ({ status: 201, body: await received.commit() }));
|
|
4777
4897
|
return send(res, answer.status, answer.body, answer.headers);
|
|
@@ -4781,36 +4901,39 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4781
4901
|
}
|
|
4782
4902
|
}
|
|
4783
4903
|
const body = await bodyOf(req);
|
|
4784
|
-
const answer = await idempotent(req, "/files", body, async () => ({ status: 201, body: await
|
|
4904
|
+
const answer = await idempotent(req, "/files", body, async () => ({ status: 201, body: await kept.reserve(body) }));
|
|
4785
4905
|
return send(res, answer.status, answer.body, answer.headers);
|
|
4786
4906
|
}
|
|
4787
4907
|
case "uploadFile":
|
|
4788
|
-
return send(res, 200, await
|
|
4908
|
+
return send(res, 200, await (await uploadsHere()).receive(id, req));
|
|
4789
4909
|
case "listFiles": {
|
|
4910
|
+
const kept = await uploadsHere();
|
|
4790
4911
|
// This server's own: its uploads, newest first, a page at a time, so an id is never lost with the answer that gave it.
|
|
4791
4912
|
const limit = limitOf(url.searchParams.get("limit"));
|
|
4792
4913
|
const offset = cursorOf(url.searchParams.get("cursor"));
|
|
4793
|
-
const ids = await
|
|
4794
|
-
const files = (await Promise.all(ids.slice(offset, offset + limit).map((fileId) =>
|
|
4914
|
+
const ids = await kept.ids();
|
|
4915
|
+
const files = (await Promise.all(ids.slice(offset, offset + limit).map((fileId) => kept.get(fileId)))).filter((file) => file !== null);
|
|
4795
4916
|
return send(res, 200, { files, next_cursor: nextCursor(offset + limit, ids.length) });
|
|
4796
4917
|
}
|
|
4797
4918
|
case "getFile": {
|
|
4798
|
-
const file = await
|
|
4919
|
+
const file = await (await uploadsHere()).get(id);
|
|
4799
4920
|
if (!file)
|
|
4800
4921
|
throw new ApiError("not_found", `no file ${id}: GET /v2/files lists the files this server keeps`);
|
|
4801
4922
|
return send(res, 200, file);
|
|
4802
4923
|
}
|
|
4803
4924
|
case "deleteFile":
|
|
4804
|
-
await
|
|
4925
|
+
await (await uploadsHere()).remove(id);
|
|
4805
4926
|
return void res.writeHead(204, { "cache-control": "no-store" }).end();
|
|
4806
4927
|
case "getUsage":
|
|
4807
4928
|
return send(res, 200, await usage(url));
|
|
4929
|
+
case "getCapacity":
|
|
4930
|
+
return send(res, 200, await capacityOverStore(store.runners, capacityWindowOf(url)));
|
|
4808
4931
|
case "getStats": {
|
|
4809
4932
|
const filter = analyticsFilter(url);
|
|
4810
4933
|
// The store's counts and cost sums (store-reads/stats), the runs' metrics summed (store-reads/analytics), and the
|
|
4811
4934
|
// runs over the store for the learning counts. No in-process pending set and no held Runs: the runner writes a
|
|
4812
4935
|
// run's end to the store before it lets it go.
|
|
4813
|
-
const [s, a] = await Promise.all([statsOverStore(store), analyticsOverStore(store, { ...filter })]);
|
|
4936
|
+
const [s, a, tokens] = await Promise.all([statsOverStore(store), analyticsOverStore(store, { ...filter }), unifiedUsage(store, filter)]);
|
|
4814
4937
|
// Each running row's status over the store (viewOverStore), for the active/needs_input/unknown buckets.
|
|
4815
4938
|
const vd = viewDepsFor(ownOriginOf());
|
|
4816
4939
|
const runningStatus = new Map();
|
|
@@ -4819,7 +4942,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
4819
4942
|
// How the runs that tried to learn fared, over the store (learning-1's learningCountsOverStore): the same figures the
|
|
4820
4943
|
// ledger gave, run for run; no held run's learning from memory.
|
|
4821
4944
|
const learning = await learningCountsOverStore(store, filter);
|
|
4822
|
-
return send(res, 200, { ...statsView(s, (id) => runningStatus.get(id)), analytics: analyticsView(a, filter), learning });
|
|
4945
|
+
return send(res, 200, { ...statsView(s, (id) => runningStatus.get(id)), analytics: { ...analyticsView(a, filter), usage: tokens }, learning });
|
|
4823
4946
|
}
|
|
4824
4947
|
case "listToolKeys":
|
|
4825
4948
|
// The offers the server holds, not capabilities': a model key's row names the harnesses its key would run too.
|
|
@@ -5525,7 +5648,7 @@ async function startHolding(options, data, checked, stops) {
|
|
|
5525
5648
|
if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
|
|
5526
5649
|
return;
|
|
5527
5650
|
if (isObservationRoute(raw))
|
|
5528
|
-
return void observationHttp(req, res, url, new Observations(store), (header) => bearer(header, req)).catch(fail);
|
|
5651
|
+
return void observationHttp(req, res, url, new Observations(store, Date.now, new ObservationLearning(store, new CliLearningConnections(store, sdkSecret), learning !== "off")), (header) => bearer(header, req)).catch(fail);
|
|
5529
5652
|
if (!raw.startsWith("/v2/"))
|
|
5530
5653
|
return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
|
|
5531
5654
|
// A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
|
|
@@ -30,7 +30,7 @@ Inspect configured models before asking for a key. For an existing setup, follow
|
|
|
30
30
|
and history import need no destination model key. Live jobs use the source runtime's existing sign-in.
|
|
31
31
|
|
|
32
32
|
Finish with the first requested run's result and console link, or imported history and counts. Offer optional
|
|
33
|
-
self-improvement separately, and verify
|
|
33
|
+
self-improvement separately, and verify owner corrections in a fresh later run when requested.
|
|
34
34
|
|
|
35
35
|
## Connect agent
|
|
36
36
|
|
|
@@ -108,11 +108,56 @@ reported model/harness and activity/usage. CLI `configured` or `delivery_state:
|
|
|
108
108
|
delivery. Observed sessions are read-only: idle is not proof of completion, and missing telemetry is not proof of
|
|
109
109
|
an agent failure. No prompts, transcripts or tool contents are uploaded through this metadata path.
|
|
110
110
|
|
|
111
|
-
|
|
111
|
+
For independently started **Codex CLI or Claude Code** sessions, use the existing CLI learning path below.
|
|
112
|
+
For SDK application-owned jobs, follow the supported backend SDK learning
|
|
112
113
|
integration and verify accepted-revision delivery in a fresh run. Observation alone cannot enable it. The current
|
|
113
114
|
Claude Agent SDK and Codex SDK wrappers are TypeScript integrations; do not claim a Python SDK backend is wrapped
|
|
114
115
|
by setting OTEL variables. Do not fabricate a runnable native agent or use a copied prompt as proof.
|
|
115
116
|
|
|
117
|
+
### Learning in existing CLI sessions
|
|
118
|
+
|
|
119
|
+
For a connected-session card handoff, read its exact `GET /v2/observations?session_id=...` record.
|
|
120
|
+
On the source machine, resolve `external_session_id` through the collector's private identity map to the
|
|
121
|
+
native session, then inspect that session's actual project through its harness. Never print the identity
|
|
122
|
+
map or credentials, and never select a project from a display name or basename. A verified
|
|
123
|
+
`learning.agent_id` links to the existing shared project/runtime learning profile; reuse it. If the
|
|
124
|
+
source is unavailable, ask the user to open the original session. Run and Edit continue or change that
|
|
125
|
+
original setup, not a managed run or a replacement definition. Delegated children cannot enable independent
|
|
126
|
+
hook learning. Only offer enrollment for the selected root session's project, with its shared scope clear.
|
|
127
|
+
|
|
128
|
+
When requested, use the matching build's `learning connect` on the source machine. This path keeps the
|
|
129
|
+
original CLI in control of task execution and does not require an SDK wrapper. The initial integration
|
|
130
|
+
requires AgentRun on that same machine; identify its loopback port and actual data directory. Do not
|
|
131
|
+
silently replace a remote destination with a new local server. Enrollment uses the local owner credential
|
|
132
|
+
privately and leaves a scoped connection credential for hooks, never an owner key in project files.
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
agentrun-serve learning connect --project /absolute/project --runtime codex \
|
|
136
|
+
--url http://127.0.0.1:7340 --data /absolute/server-data
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Use `claude-code` for Claude Code. Scope enrollment to the selected project/runtime. Installation merges
|
|
140
|
+
source hooks without replacing other hooks or changing tools, permissions, instructions or sign-in.
|
|
141
|
+
Codex linked worktrees append exact project-scoped hooks to the corresponding main-checkout
|
|
142
|
+
`.codex/hooks.json`, following native discovery. They keep separate local receipts and a local `.codex`
|
|
143
|
+
directory; disconnect preserves surviving native hook positions. If `learning status` reports `migration-required`,
|
|
144
|
+
rerun the same connect command to migrate unchanged owned hooks without replacing the connection.
|
|
145
|
+
Verify `/hooks`; Codex must trust the current declaration. Project configuration does not hot reload:
|
|
146
|
+
open a new session or close and resume it after the current task finishes. Reloading user settings alone
|
|
147
|
+
does not reload these project hooks. Do not interrupt the user's running task to activate them.
|
|
148
|
+
Do not claim merely writing a configuration file activated a running session. Begin on the next complete
|
|
149
|
+
prompt after activation, without importing earlier conversations or learning from an in-flight turn.
|
|
150
|
+
|
|
151
|
+
The prompt hook supplies pinned owner corrections; completion hooks record bounded role-preserving evidence
|
|
152
|
+
and reported usage. Source dialogue never becomes a standing correction automatically. Source hooks do not
|
|
153
|
+
provide a workflow execution bridge or make extra native reflection calls. Missing policy, truncated evidence
|
|
154
|
+
and cancellation stay explicit. This is not metadata-only observation.
|
|
155
|
+
|
|
156
|
+
Use `learning status` with the same project/runtime/data arguments and open the returned agent's Learning
|
|
157
|
+
tab. Save a correction explicitly, then verify an actual completed source run and its delivery and use
|
|
158
|
+
on a later prompt. Report incomplete evidence accurately. Learning Off controls guidance for future prompts;
|
|
159
|
+
`learning disconnect` revokes enrollment and removes only its installed hooks, retaining prior history.
|
|
160
|
+
|
|
116
161
|
### Live connection on this server
|
|
117
162
|
|
|
118
163
|
Verify that the coding agent, source project and AgentRun server are on the same machine. A browser's loopback
|
|
@@ -210,11 +255,11 @@ target; duplicates are skipped. The worker does not continuously upload historic
|
|
|
210
255
|
|
|
211
256
|
### Optional self-improvement
|
|
212
257
|
|
|
213
|
-
When requested, verify the imported agent and enable its existing **Self-improving** control.
|
|
214
|
-
additive, pinned to a learning revision for each run.
|
|
215
|
-
the
|
|
216
|
-
|
|
217
|
-
|
|
258
|
+
When requested, verify the imported agent and enable its existing **Self-improving** control. Owner corrections
|
|
259
|
+
are additive, pinned to a learning revision for each run. Eligible jobs compile into workflow drafts by resuming
|
|
260
|
+
the exact task session with tools disabled; checks and a dry run decide whether to keep a draft. Compilation
|
|
261
|
+
adds model usage. Learned workflows do not serve native runs in this release. Off means later runs receive
|
|
262
|
+
and create no AgentRun learning. Do not start a paid run unless authorized, and do not promise enforcement
|
|
218
263
|
of native dollar caps, interactive approvals, learned workflows or unsupported desktop tools.
|
|
219
264
|
|
|
220
265
|
### Historical import into a local store
|
package/dist/start-switches.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// caller of the API can widen what the server reaches. GET /v2/capabilities lists them (`switches`), and a refusal one of
|
|
3
3
|
// them causes names it, the value that allows it and the restart it takes (restartWith).
|
|
4
4
|
import { BOX_ALLOW_ENV, boxAllowOf, boxAllowSetIn } from "./box-settings.js";
|
|
5
|
+
import { PRIVATE_HOSTS_ENV, privateHostsSwitchValue } from "./mcp-private-hosts.js";
|
|
5
6
|
/** The env that says this server is a local install (cli.ts), the one kind an MCP server may be on loopback for. */
|
|
6
7
|
export const MCP_ALLOW_LOOPBACK_ENV = "AGENTRUN_MCP_ALLOW_LOOPBACK";
|
|
7
8
|
/** The env that lets the outbound webhook send to a private network or this machine. */
|
|
@@ -29,6 +30,7 @@ export function startSwitches(env, { mcpLoopback, webhookPrivateTargets }) {
|
|
|
29
30
|
return {
|
|
30
31
|
[MCP_ALLOW_LOOPBACK_ENV]: flag(mcpLoopback, `An MCP server on this machine's loopback (127.0.0.1, localhost), for every caller of this server's API: ${ALONE_WORDS}.`),
|
|
31
32
|
[WEBHOOK_PRIVATE_TARGETS_ENV]: flag(webhookPrivateTargets, `The outbound webhook (Settings → Webhook) sending to a private network or this machine, which any caller who may set it then reaches: ${ALONE_WORDS}.`),
|
|
33
|
+
[PRIVATE_HOSTS_ENV]: ((value) => ({ on: value !== null, value, allows: "The private-network hosts an owner may allow an MCP server or a calendar on (Settings → MCP servers): unset, the owner's list; none, no private host at all (set it on a server or runner many customers share); or a comma list of address ranges every listed host's address must also fall in. Set it on the server and on each runner: each process holds to its own." }))(privateHostsSwitchValue(env)),
|
|
32
34
|
[BOX_ALLOW_ENV]: { on: boxAllowSetIn(env), value: boxAllowSetIn(env) ? (allow === "none" ? "none" : allow.join(",")) : null, allows: "The hosts a run's computer may reach: a comma list of host names, or none for no network. Unset, the package registries and GitHub (capabilities' places.allow)." },
|
|
33
35
|
[BOX_CPUS_ENV]: size(BOX_CPUS_ENV, "A Docker computer's CPUs, such as 2 or 1.5. Unset, the Docker provider's default."),
|
|
34
36
|
[BOX_MEMORY_ENV]: size(BOX_MEMORY_ENV, "A Docker computer's memory, swap included, such as 512m or 4g. Unset, the Docker provider's default."),
|
package/dist/stats.d.ts
CHANGED
|
@@ -50,6 +50,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
|
|
|
50
50
|
needs_review: number;
|
|
51
51
|
failed: number;
|
|
52
52
|
runs_with_metrics: number;
|
|
53
|
+
runs_with_token_metrics: number;
|
|
53
54
|
tokens: number | null;
|
|
54
55
|
cost_usd: number | null;
|
|
55
56
|
unknown_cost_runs: number;
|
|
@@ -66,6 +67,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
|
|
|
66
67
|
needs_review: number;
|
|
67
68
|
failed: number;
|
|
68
69
|
runs_with_metrics: number;
|
|
70
|
+
runs_with_token_metrics: number;
|
|
69
71
|
tokens: number | null;
|
|
70
72
|
cost_usd: number | null;
|
|
71
73
|
unknown_cost_runs: number;
|
|
@@ -78,6 +80,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
|
|
|
78
80
|
needs_review: number;
|
|
79
81
|
failed: number;
|
|
80
82
|
runs_with_metrics: number;
|
|
83
|
+
runs_with_token_metrics: number;
|
|
81
84
|
tokens: number | null;
|
|
82
85
|
cost_usd: number | null;
|
|
83
86
|
unknown_cost_runs: number;
|
|
@@ -89,6 +92,7 @@ export declare function analyticsView(a: StoreAnalytics, filter: AnalyticsFilter
|
|
|
89
92
|
needs_review: number;
|
|
90
93
|
failed: number;
|
|
91
94
|
runs_with_metrics: number;
|
|
95
|
+
runs_with_token_metrics: number;
|
|
92
96
|
tokens: number | null;
|
|
93
97
|
cost_usd: number | null;
|
|
94
98
|
unknown_cost_runs: number;
|
package/dist/stats.js
CHANGED
|
@@ -70,7 +70,7 @@ export function analyticsFilter(url) {
|
|
|
70
70
|
return filter;
|
|
71
71
|
}
|
|
72
72
|
/** A group's counts: an escalated run is completed, and needs review; never failed. */
|
|
73
|
-
const group = (g) => ({ runs: g.runs, completed: g.completed, needs_review: g.needsReview, failed: g.failed, runs_with_metrics: g.runsWithMetrics, tokens: g.tokens, cost_usd: round(g.costUsd), unknown_cost_runs: g.unknownCostRuns });
|
|
73
|
+
const group = (g) => ({ runs: g.runs, completed: g.completed, needs_review: g.needsReview, failed: g.failed, runs_with_metrics: g.runsWithMetrics, runs_with_token_metrics: g.runsWithTokenMetrics, tokens: g.tokens, cost_usd: round(g.costUsd), unknown_cost_runs: g.unknownCostRuns });
|
|
74
74
|
export function analyticsView(a, filter) {
|
|
75
75
|
const t = a.totals;
|
|
76
76
|
return {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type SdkBinding } from "../sdk/runtimes.js";
|
|
2
2
|
import type { NativeBinding } from "../native/types.js";
|
|
3
|
+
import { type NativeRuntime } from "../native/runtimes.js";
|
|
3
4
|
import { type LearningSetting } from "../learning-setting.js";
|
|
4
5
|
/** A revision's body the store refuses: its content is not one the store keeps. The server maps it to an input refusal. */
|
|
5
6
|
export declare class AgentBodyInvalid extends Error {
|
|
@@ -60,8 +61,18 @@ export type MonidPinBody = Readonly<Record<string, {
|
|
|
60
61
|
readonly input: Record<string, unknown>;
|
|
61
62
|
readonly usd: number | null;
|
|
62
63
|
}>>;
|
|
64
|
+
export type CliLearningBinding = {
|
|
65
|
+
runtime: NativeRuntime;
|
|
66
|
+
connection_id: string;
|
|
67
|
+
project: string;
|
|
68
|
+
};
|
|
69
|
+
export declare const cliLearningOf: (body: unknown) => CliLearningBinding | undefined;
|
|
70
|
+
/** Read old CLI enrollment settings through the current model without rewriting its revision or learned files.
|
|
71
|
+
* New definitions still reject "notes"; existing CLI profiles use owner corrections and no workflow bridge. */
|
|
72
|
+
export declare function learningSettingForBody(body: unknown): LearningSetting | undefined;
|
|
63
73
|
export type { SdkBinding } from "../sdk/runtimes.js";
|
|
64
74
|
export type AgenticBody = {
|
|
75
|
+
cli_learning?: CliLearningBinding;
|
|
65
76
|
sdk?: SdkBinding;
|
|
66
77
|
native?: NativeBinding;
|
|
67
78
|
instructions: string;
|
|
@@ -97,6 +108,7 @@ export type WorkflowBody = {
|
|
|
97
108
|
* checked and canonical (agents-store.ts via tool-plane's one copy); this validator keeps it as given. */
|
|
98
109
|
export type RevisionBodyInput = {
|
|
99
110
|
kind: "agentic";
|
|
111
|
+
cli_learning?: CliLearningBinding;
|
|
100
112
|
sdk?: SdkBinding;
|
|
101
113
|
native?: NativeBinding;
|
|
102
114
|
instructions: string;
|