@parcha/agentrun-serve 0.1.0-beta.36 → 0.1.0-beta.37
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 +170 -0
- package/README.md +158 -52
- package/dist/attach-conformance-cli.d.ts +1 -0
- package/dist/attach-conformance-cli.js +18 -0
- package/dist/attach-conformance.d.ts +25 -0
- package/dist/attach-conformance.js +343 -0
- package/dist/browser-cost.d.ts +1 -1
- package/dist/browser-live.d.ts +20 -8
- package/dist/browser-live.js +50 -27
- package/dist/cap.d.ts +0 -17
- package/dist/cap.js +0 -91
- package/dist/catalog.d.ts +1 -12
- package/dist/catalog.js +3 -33
- package/dist/cli.js +13 -4
- package/dist/composio-preset.d.ts +36 -0
- package/dist/composio-preset.js +179 -0
- package/dist/computer-attach.d.ts +125 -0
- package/dist/computer-attach.js +330 -0
- package/dist/computer-calls.d.ts +48 -0
- package/dist/computer-calls.js +126 -0
- package/dist/computer-channel.d.ts +57 -0
- package/dist/computer-channel.js +115 -0
- package/dist/computer-commands.d.ts +1 -1
- package/dist/computer-held-routes.d.ts +35 -0
- package/dist/computer-held-routes.js +106 -0
- package/dist/computer-held.d.ts +48 -0
- package/dist/computer-held.js +87 -0
- package/dist/computer-keys.d.ts +21 -1
- package/dist/computer-keys.js +53 -11
- package/dist/computer-live.d.ts +160 -0
- package/dist/computer-live.js +643 -0
- package/dist/computer-view.d.ts +13 -0
- package/dist/computer-view.js +50 -3
- package/dist/computer-viewer.d.ts +6 -0
- package/dist/computer-viewer.js +297 -0
- package/dist/computers.d.ts +33 -7
- package/dist/computers.js +50 -8
- package/dist/console/assets/index-Cn6JX1uH.js +563 -0
- package/dist/console/assets/index-DRN62V5v.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/faux-computers.d.ts +9 -20
- package/dist/faux-computers.js +53 -25
- package/dist/github-connection.d.ts +10 -2
- package/dist/github-connection.js +65 -2
- package/dist/github-faux.js +1 -1
- package/dist/graph-view.d.ts +1 -1
- package/dist/harness.d.ts +1 -0
- package/dist/harness.js +35 -1
- package/dist/host-tools.d.ts +1 -1
- package/dist/hosted-search.d.ts +5 -4
- package/dist/hosted-search.js +2 -7
- package/dist/import-sources.d.ts +10 -0
- package/dist/import-sources.js +44 -2
- package/dist/import.d.ts +3 -3
- package/dist/import.js +37 -6
- package/dist/learn/check.d.ts +4 -1
- package/dist/learn/check.js +1 -1
- package/dist/learn/commit.d.ts +4 -2
- package/dist/learn/commit.js +5 -5
- package/dist/learn/folder.d.ts +6 -0
- package/dist/learn/folder.js +4 -1
- package/dist/learn/general.d.ts +66 -0
- package/dist/learn/general.js +73 -0
- package/dist/learn/grade.d.ts +4 -0
- package/dist/learn/grade.js +22 -1
- package/dist/learn/reflect.d.ts +10 -1
- package/dist/learn/reflect.js +14 -4
- package/dist/learn/skills.d.ts +33 -5
- package/dist/learn/skills.js +53 -7
- package/dist/learned-workflow.d.ts +24 -0
- package/dist/learned-workflow.js +66 -3
- package/dist/learning-batch.d.ts +283 -0
- package/dist/learning-batch.js +574 -0
- package/dist/learning-evals.d.ts +33 -0
- package/dist/learning-evals.js +98 -0
- package/dist/learning-routes.d.ts +25 -2
- package/dist/learning-routes.js +39 -6
- package/dist/learning-words.d.ts +6 -0
- package/dist/learning-words.js +6 -0
- package/dist/learning.d.ts +28 -15
- package/dist/learning.js +84 -44
- package/dist/live/stream.js +6 -3
- package/dist/live/translate.d.ts +4 -3
- package/dist/live/translate.js +8 -4
- package/dist/live-reach.d.ts +37 -0
- package/dist/live-reach.js +62 -0
- package/dist/mcp-gateway.d.ts +9 -0
- package/dist/mcp-gateway.js +60 -11
- package/dist/mcp-oauth.d.ts +57 -7
- package/dist/mcp-oauth.js +133 -18
- package/dist/mcp-private-hosts.d.ts +4 -4
- package/dist/mcp-private-hosts.js +20 -12
- package/dist/mcp-probe.d.ts +19 -2
- package/dist/mcp-probe.js +44 -9
- package/dist/mcp-secret-writes.js +4 -0
- package/dist/mcp-servers-store.d.ts +38 -15
- package/dist/mcp-servers-store.js +112 -20
- package/dist/mcp-store.d.ts +10 -4
- package/dist/mcp-store.js +17 -6
- package/dist/model-form.d.ts +26 -0
- package/dist/model-form.js +80 -0
- package/dist/model.js +23 -10
- package/dist/openapi.js +386 -21
- package/dist/page.d.ts +18 -0
- package/dist/page.js +48 -20
- package/dist/paid-calls.d.ts +1 -1
- package/dist/place-offers.d.ts +2 -3
- package/dist/place-offers.js +3 -7
- package/dist/place.js +1 -2
- package/dist/print.d.ts +15 -1
- package/dist/print.js +14 -3
- package/dist/propose.d.ts +3 -0
- package/dist/propose.js +13 -5
- package/dist/provider.js +3 -2
- package/dist/reflect-range.d.ts +8 -1
- package/dist/reflect-range.js +1 -1
- package/dist/run-launch.d.ts +14 -2
- package/dist/run-launch.js +9 -4
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-reads-over-store.d.ts +1 -1
- package/dist/run-repo.d.ts +20 -0
- package/dist/run-repo.js +63 -0
- package/dist/run-timeline-served.d.ts +1 -1
- package/dist/run-view.d.ts +3 -3
- package/dist/run-view.js +14 -7
- package/dist/runner/adapter-loop.d.ts +23 -7
- package/dist/runner/adapter-loop.js +648 -62
- package/dist/runner/adapter-run-spec.d.ts +11 -3
- package/dist/runner/adapter-run-spec.js +77 -22
- package/dist/runner/adapters/pi-computer.d.ts +7 -0
- package/dist/runner/adapters/pi-computer.js +43 -0
- package/dist/runner/adapters/pi.d.ts +9 -4
- package/dist/runner/adapters/pi.js +76 -14
- package/dist/runner/beside.d.ts +7 -3
- package/dist/runner/beside.js +21 -11
- package/dist/runner/claim-secrets.d.ts +4 -0
- package/dist/runner/claim-secrets.js +6 -1
- package/dist/runner/cli-run-spec.d.ts +20 -3
- package/dist/runner/cli-run-spec.js +113 -43
- package/dist/runner/commands.d.ts +3 -1
- package/dist/runner/commands.js +28 -3
- package/dist/runner/computer-channel.d.ts +34 -0
- package/dist/runner/computer-channel.js +61 -0
- package/dist/runner/conformance/harness.js +80 -14
- package/dist/runner/conformance/subject.d.ts +1 -1
- package/dist/runner/dispatch.js +3 -0
- package/dist/runner/end-of-run.d.ts +22 -12
- package/dist/runner/end-of-run.js +38 -16
- package/dist/runner/github-app.d.ts +2 -1
- package/dist/runner/github-app.js +4 -2
- package/dist/runner/harness-loops.js +15 -1
- package/dist/runner/held-run.d.ts +65 -0
- package/dist/runner/held-run.js +158 -0
- package/dist/runner/journal-kinds.d.ts +20 -1
- package/dist/runner/journal-kinds.js +14 -0
- package/dist/runner/journal-reader.d.ts +5 -4
- package/dist/runner/journal-reader.js +12 -10
- package/dist/runner/learning-ask.d.ts +7 -1
- package/dist/runner/learning-ask.js +21 -6
- package/dist/runner/learning-dispatch.d.ts +22 -0
- package/dist/runner/learning-dispatch.js +77 -10
- package/dist/runner/learning-end.d.ts +22 -1
- package/dist/runner/learning-end.js +92 -12
- package/dist/runner/learning-factory.d.ts +1 -1
- package/dist/runner/learning-factory.js +11 -5
- package/dist/runner/learning-loop.d.ts +67 -7
- package/dist/runner/learning-loop.js +173 -21
- package/dist/runner/learning-seed.d.ts +7 -0
- package/dist/runner/learning-seed.js +13 -0
- package/dist/runner/live-ticker.js +1 -0
- package/dist/runner/loop-contract.d.ts +8 -1
- package/dist/runner/loop.d.ts +5 -1
- package/dist/runner/loop.js +2 -1
- package/dist/runner/main.d.ts +13 -1
- package/dist/runner/main.js +27 -5
- package/dist/runner/mcp-claim.d.ts +10 -7
- package/dist/runner/mcp-claim.js +113 -24
- package/dist/runner/mcp-github.js +1 -1
- package/dist/runner/mcp-run.d.ts +5 -5
- package/dist/runner/mcp-run.js +15 -3
- package/dist/runner/metrics.d.ts +11 -2
- package/dist/runner/metrics.js +12 -2
- package/dist/runner/pr-checkout.d.ts +1 -0
- package/dist/runner/pr-checkout.js +1 -1
- package/dist/runner/reflect-hook.d.ts +18 -0
- package/dist/runner/reflect-hook.js +20 -8
- package/dist/runner/runner.d.ts +26 -0
- package/dist/runner/runner.js +184 -15
- package/dist/runner/scratch-sweep.d.ts +13 -0
- package/dist/runner/scratch-sweep.js +62 -0
- package/dist/runner/sessions.d.ts +1 -1
- package/dist/runner/store-port.d.ts +4 -2
- package/dist/runner/store-secrets.js +4 -3
- package/dist/runner/subagent.js +3 -1
- package/dist/runner/workflow-host.d.ts +6 -1
- package/dist/runner/workflow-host.js +1 -1
- package/dist/runner/workflow-loop.d.ts +1 -1
- package/dist/runner/workflow-spec.d.ts +14 -2
- package/dist/runner/workflow-spec.js +56 -20
- package/dist/runs-over-store.d.ts +6 -1
- package/dist/runs-over-store.js +38 -9
- package/dist/seal-key.js +3 -3
- package/dist/sealed-settings-store.d.ts +5 -2
- package/dist/sealed-settings-store.js +10 -4
- package/dist/secret-writes.d.ts +5 -4
- package/dist/secret-writes.js +5 -4
- package/dist/server-secrets-store.d.ts +4 -3
- package/dist/server-secrets-store.js +15 -9
- package/dist/server-secrets.js +3 -2
- package/dist/server.d.ts +43 -14
- package/dist/server.js +472 -126
- package/dist/settings-wake.d.ts +21 -0
- package/dist/settings-wake.js +59 -0
- package/dist/standard-webhooks.d.ts +4 -1
- package/dist/standard-webhooks.js +8 -4
- package/dist/store/command-wake.d.ts +12 -0
- package/dist/store/command-wake.js +37 -0
- package/dist/store/dialect.d.ts +6 -0
- package/dist/store/dialect.js +5 -0
- package/dist/store/index.d.ts +1 -1
- package/dist/store/journal/storage.d.ts +3 -2
- package/dist/store/journal/storage.js +13 -5
- package/dist/store/postgres/dialect.js +4 -0
- package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
- package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
- package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
- package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
- package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
- package/dist/store/schema.d.ts +1 -1
- package/dist/store/schema.js +77 -8
- package/dist/store/sqlite/run-patch.d.ts +7 -5
- package/dist/store/sqlite/run-patch.js +28 -13
- package/dist/store/sqlite/store.js +272 -54
- package/dist/store/store.d.ts +268 -9
- package/dist/store/store.js +12 -1
- package/dist/store-reads/cap.d.ts +1 -1
- package/dist/store-reads/cap.js +8 -1
- package/dist/store-reads/decisions.d.ts +2 -2
- package/dist/store-reads/decisions.js +1 -1
- package/dist/store-reads/import-summary.d.ts +1 -1
- package/dist/store-reads/journal.d.ts +5 -4
- package/dist/store-reads/journal.js +73 -15
- package/dist/store-reads/learning.d.ts +20 -4
- package/dist/store-reads/learning.js +74 -18
- package/dist/store-reads/runs.d.ts +1 -1
- package/dist/store-reads/workflow.d.ts +1 -1
- package/dist/store-view.d.ts +5 -0
- package/dist/store-view.js +26 -11
- package/dist/template-eval.js +6 -4
- package/dist/template-github-permissions.d.ts +22 -8
- package/dist/template-github-permissions.js +35 -15
- package/dist/timeline/timeline.d.ts +27 -0
- package/dist/timeline/timeline.js +10 -9
- package/dist/timeline/util.d.ts +4 -0
- package/dist/timeline/util.js +14 -0
- package/dist/tool-budget.d.ts +19 -7
- package/dist/tool-budget.js +14 -8
- package/dist/tool-gate.d.ts +16 -9
- package/dist/tool-gate.js +53 -42
- package/dist/tool-plane.d.ts +16 -12
- package/dist/tool-plane.js +9 -4
- package/dist/tools.d.ts +13 -4
- package/dist/tools.js +13 -4
- package/dist/trigger-adapter.d.ts +4 -0
- package/dist/trigger-secrets-shown.d.ts +2 -2
- package/dist/trigger-secrets-shown.js +1 -1
- package/dist/trigger-signatures.d.ts +25 -6
- package/dist/trigger-signatures.js +41 -7
- package/dist/trigger-targets.d.ts +2 -0
- package/dist/trigger-targets.js +1 -0
- package/dist/trigger-webhook.js +5 -2
- package/dist/triggers.d.ts +7 -3
- package/dist/triggers.js +35 -5
- package/dist/turns.js +16 -1
- package/dist/validate.js +11 -1
- package/dist/web-fetch.d.ts +1 -1
- package/dist/web-search.d.ts +10 -5
- package/dist/web-search.js +7 -6
- package/dist/webhooks.d.ts +145 -102
- package/dist/webhooks.js +559 -322
- package/dist/workflow/decisions.d.ts +1 -1
- package/dist/workflow/node-runner.d.ts +2 -1
- package/dist/workflow/node.d.ts +2 -1
- package/dist/workflow/node.js +3 -1
- package/dist/workflow/pi-versions.d.ts +23 -0
- package/dist/workflow/pi-versions.js +57 -0
- package/dist/workflow/record-tool.d.ts +2 -1
- package/dist/workflow/store.d.ts +1 -1
- package/dist/workflow/task.js +3 -2
- package/dist/workflow-run.d.ts +1 -1
- package/dist/workspace/attached-computers.d.ts +41 -0
- package/dist/workspace/attached-computers.js +114 -0
- package/dist/workspace/computer-deps.d.ts +16 -9
- package/dist/workspace/computer-deps.js +19 -7
- package/dist/workspace/computer-for-claim.d.ts +17 -8
- package/dist/workspace/computer-for-claim.js +62 -21
- package/dist/workspace/computer-hold.d.ts +11 -27
- package/dist/workspace/computer-hold.js +36 -56
- package/dist/workspace/computer-ledger.d.ts +3 -1
- package/dist/workspace/computer-ledger.js +4 -0
- package/dist/workspace/computer-mcp.d.ts +25 -0
- package/dist/workspace/computer-mcp.js +41 -0
- package/dist/workspace/computer-ports.d.ts +4 -13
- package/dist/workspace/computer-ports.js +4 -107
- package/dist/workspace/computer-script.d.ts +37 -0
- package/dist/workspace/computer-script.js +138 -0
- package/dist/workspace/executors.d.ts +1 -1
- package/dist/workspace/index.d.ts +4 -2
- package/dist/workspace/index.js +3 -1
- package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
- package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
- package/dist/workspace/resolve-computer.d.ts +3 -0
- package/dist/workspace/resolve-computer.js +8 -2
- package/dist/workspace/run-tools.d.ts +32 -15
- package/dist/workspace/run-tools.js +23 -30
- package/package.json +19 -16
- package/templates/market-monitor/agent.md +1 -1
- package/dist/console/assets/index-BI4Byidu.js +0 -550
- package/dist/console/assets/index-C19gUF2n.css +0 -1
- package/dist/run-db.d.ts +0 -53
- package/dist/run-db.js +0 -116
- package/dist/workflow/readers.d.ts +0 -36
- package/dist/workflow/readers.js +0 -145
- package/dist/workflow/wal.d.ts +0 -11
- package/dist/workflow/wal.js +0 -106
package/dist/learning.js
CHANGED
|
@@ -57,7 +57,8 @@ export function learningOf(env, given) {
|
|
|
57
57
|
return value;
|
|
58
58
|
}
|
|
59
59
|
/** How much of what a run learned its instructions hold under `# Learned` by default, in UTF-8 bytes (learnedParts): its
|
|
60
|
-
* notes whole while they fit, else the
|
|
60
|
+
* notes whole while they fit, else the notes that bear most on the run whole while they fit, then a line for each of
|
|
61
|
+
* the next while they fit; the rest are left out, and the run's log names them. */
|
|
61
62
|
export const LEARNING_BUDGET = 8000;
|
|
62
63
|
export const LEARNING_BUDGET_ENV = "AGENTRUN_SERVE_LEARNING_BUDGET";
|
|
63
64
|
/** The learning budget: `given` (`--learning-budget`), else AGENTRUN_SERVE_LEARNING_BUDGET, else LEARNING_BUDGET. Any
|
|
@@ -74,7 +75,11 @@ export function learningBudgetOf(env, given) {
|
|
|
74
75
|
* checks and is kept (propose.ts), `merged` once it is on main (runner/learning-loop.ts), or `dropped` with a
|
|
75
76
|
* reason from the closed list. A learning fault never refuses a run: it starts with nothing learned, `seed_failed`. */
|
|
76
77
|
export const LEARNING_STATES = ["seeded", "reflecting", "proposed", "merged", "dropped"];
|
|
77
|
-
export const LEARNING_REASONS = ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_timeout", "reflect_failed", "empty", "unparsed", "propose_failed", "checker", "grader", "grade_failed"];
|
|
78
|
+
export const LEARNING_REASONS = ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_timeout", "reflect_failed", "empty", "unparsed", "propose_failed", "checker", "grader", "grade_failed", "use"];
|
|
79
|
+
/** A run's own `learning` on its start (POST /agents/{agent_id}/runs): it starts from what its agent learned, as a run that
|
|
80
|
+
* learns does, and keeps nothing (no end-of-run turn, no proposal, no grade, no merge, at any end), so runs of one agent
|
|
81
|
+
* read one learned state however many run at once. Its learning ends `dropped`, reason `use`. */
|
|
82
|
+
export const RUN_LEARNING_USE = "use";
|
|
78
83
|
/** The variable that names the grader's model, as `--grade-model` does. */
|
|
79
84
|
export const GRADE_MODEL_ENV = "AGENTRUN_SERVE_GRADE_MODEL";
|
|
80
85
|
/** The model this server grades on, by name: `given` (`--grade-model`), else GRADE_MODEL_ENV, else its strong tier
|
|
@@ -407,23 +412,55 @@ export async function layLearned(work, seed, shown) {
|
|
|
407
412
|
}
|
|
408
413
|
/** All of `candidates` fit whole: every note within the budget, and an index that names no note main does not hold. */
|
|
409
414
|
const allFit = ({ notes, indexComplete, budget }) => indexComplete && notes.reduce((sum, { bytes }) => sum + bytes, 0) <= budget;
|
|
415
|
+
/** Past the budget: the first `bearing` notes in `ranked`'s order (those that bear on the run), each whole while it fits
|
|
416
|
+
* what is left of the budget (one that does not is passed over for the next), then one rule line for each of the rest,
|
|
417
|
+
* in the same order, while it fits what the whole notes leave and no more than a run reads of the index (INDEX_LINES,
|
|
418
|
+
* INDEX_BYTES), the section's own lines counted. Whole notes come first: lines never take the room a whole note fits in, so past ~50 notes a run still
|
|
419
|
+
* reads the ones that bear on it whole (Run B, 11-12: past 8 KB of lines every run got lines alone). The rest are left
|
|
420
|
+
* out, and learnedParts names them. */
|
|
421
|
+
const withinBudget = (ranked, budget, read = true, bearing = ranked.length) => {
|
|
422
|
+
const whole = [];
|
|
423
|
+
// The section's own lines (its intro, the read-tool line when the run has the read tool, the blank lines around the
|
|
424
|
+
// rule lines) come first.
|
|
425
|
+
let room = budget - FRAME_BYTES(read);
|
|
426
|
+
for (const { note, bytes } of ranked.slice(0, bearing))
|
|
427
|
+
if (bytes <= room)
|
|
428
|
+
(room -= bytes), whole.push(note);
|
|
429
|
+
if (whole.length === ranked.length)
|
|
430
|
+
return { whole, index: false };
|
|
431
|
+
const taken = new Set(whole);
|
|
432
|
+
const lines = [];
|
|
433
|
+
let lineBytes = 0;
|
|
434
|
+
for (const { note, lineBytes: bytes } of ranked) {
|
|
435
|
+
if (taken.has(note) || lines.length >= INDEX_LINES || bytes > room || lineBytes + bytes > INDEX_BYTES)
|
|
436
|
+
continue;
|
|
437
|
+
room -= bytes;
|
|
438
|
+
lineBytes += bytes;
|
|
439
|
+
lines.push(note);
|
|
440
|
+
}
|
|
441
|
+
return { whole, index: false, lines };
|
|
442
|
+
};
|
|
410
443
|
/** The selector by recency: every note whole while all fit the budget and the index names no note main does not hold
|
|
411
|
-
* whole;
|
|
444
|
+
* whole; notes that fit with an index that names one it lacks, the index, then the newest notes that fit what it
|
|
445
|
+
* leaves, each whole; past the budget, the newest notes whole while they fit, then a line for each of the next while
|
|
446
|
+
* they fit (withinBudget). */
|
|
412
447
|
export const byRecency = (candidates) => {
|
|
413
448
|
const { notes, indexBytes, budget } = candidates;
|
|
414
449
|
if (allFit(candidates))
|
|
415
450
|
return { whole: notes.map(({ note }) => note), index: false };
|
|
451
|
+
if (notes.reduce((sum, { bytes }) => sum + bytes, 0) > budget)
|
|
452
|
+
return withinBudget(notes, budget, candidates.read);
|
|
416
453
|
let left = budget - indexBytes;
|
|
417
454
|
return { whole: notes.filter(({ bytes }) => bytes <= left && ((left -= bytes), true)).map(({ note }) => note), index: true };
|
|
418
455
|
};
|
|
419
456
|
/** The default selector, by relevance, past the budget: while the notes fit it, recency's choice (byRecency). Else each
|
|
420
457
|
* note is scored against the run's input (learn/relevance.ts: BM25 over its name, description and body, a code
|
|
421
458
|
* review's changed paths' words weighed PATH_WEIGHT; no model call), and the run reads the notes that bear on it most
|
|
422
|
-
* whole,
|
|
423
|
-
*
|
|
424
|
-
*
|
|
459
|
+
* whole, best first, while they fit the budget, then one rule line for each of the next while they fit what is left
|
|
460
|
+
* (withinBudget), a note that bears on it in no word a line at most; the rest are left out. An input with no word any
|
|
461
|
+
* note holds reads by recency. */
|
|
425
462
|
export const byRelevance = (candidates, run) => {
|
|
426
|
-
// Within the budget, nothing changes: recency's choice (every note whole
|
|
463
|
+
// Within the budget, nothing changes: recency's choice (every note whole).
|
|
427
464
|
if (candidates.notes.reduce((sum, { bytes }) => sum + bytes, 0) <= candidates.budget)
|
|
428
465
|
return byRecency(candidates, run);
|
|
429
466
|
const { notes, budget } = candidates;
|
|
@@ -432,26 +469,8 @@ export const byRelevance = (candidates, run) => {
|
|
|
432
469
|
return byRecency(candidates, run);
|
|
433
470
|
// Best first; a tie keeps recency (the candidates' order).
|
|
434
471
|
const ranked = notes.map((candidate, i) => ({ ...candidate, score: scores[i], at: i })).sort((a, b) => b.score - a.score || a.at - b.at);
|
|
435
|
-
//
|
|
436
|
-
|
|
437
|
-
let bytes = 0;
|
|
438
|
-
return ranked.filter(({ note }) => !whole.has(note)).slice(0, INDEX_LINES).filter(({ lineBytes }) => (bytes += lineBytes) <= INDEX_BYTES);
|
|
439
|
-
};
|
|
440
|
-
const lineBytesOf = (whole) => linesOf(whole).reduce((sum, { lineBytes }) => sum + lineBytes, 0);
|
|
441
|
-
// Promoted whole, best first, while the whole notes and the lines served of the rest fit: the room kept for lines is
|
|
442
|
-
// only what is served of them (past INDEX_LINES or INDEX_BYTES a line is never served), never every note's.
|
|
443
|
-
const whole = new Set();
|
|
444
|
-
let wholeBytes = 0;
|
|
445
|
-
for (const { note, bytes, score } of ranked) {
|
|
446
|
-
if (score <= 0)
|
|
447
|
-
break;
|
|
448
|
-
whole.add(note);
|
|
449
|
-
if (wholeBytes + bytes + lineBytesOf(whole) <= budget)
|
|
450
|
-
wholeBytes += bytes;
|
|
451
|
-
else
|
|
452
|
-
whole.delete(note);
|
|
453
|
-
}
|
|
454
|
-
return { whole: ranked.filter(({ note }) => whole.has(note)).map(({ note }) => note), index: false, lines: linesOf(whole).map(({ note }) => note) };
|
|
472
|
+
// Only a note that bears on the run is read whole; one that shares no word with it is a line at most.
|
|
473
|
+
return withinBudget(ranked, budget, candidates.read, ranked.filter(({ score }) => score > 0).length);
|
|
455
474
|
};
|
|
456
475
|
/** The lines before what a run learned, under `# Learned` after LEARNS, and the one that names `.learning/` to an agent
|
|
457
476
|
* that can read it. */
|
|
@@ -459,9 +478,18 @@ const KEPT = "Follow a note when it applies to what you are doing.";
|
|
|
459
478
|
const WHOLE_INTRO = `What you learned in earlier runs: each note whole, newest first. ${KEPT}`;
|
|
460
479
|
const SOME_INTRO = `What you learned in earlier runs: the index, one line per note, then the newest notes whole. ${KEPT}`;
|
|
461
480
|
const INDEX_INTRO = `What you learned in earlier runs, one line per note. ${KEPT}`;
|
|
462
|
-
const LINES_INTRO = `What you learned in earlier runs: the notes that bear most on this run whole, then one line for
|
|
481
|
+
const LINES_INTRO = `What you learned in earlier runs: the notes that bear most on this run whole, then one line each for more of them. ${KEPT}`;
|
|
482
|
+
const BEST_INTRO = `What you learned in earlier runs: the notes that bear most on this run, each whole. ${KEPT}`;
|
|
483
|
+
const LINES_ONLY_INTRO = `What you learned in earlier runs: one line each for the notes that bear most on this run. ${KEPT}`;
|
|
463
484
|
const READ_LINE = `The notes not given whole here are files in \`${LEARNED_DIR}/\` in your working directory: open one with the read tool when it applies.`;
|
|
464
485
|
const oneLine = (text) => text.replace(/\s+/g, " ").trim();
|
|
486
|
+
/** What a run whose notes are all past a budget that holds none of them reads in place of them: that they are there, and,
|
|
487
|
+
* with the read tool, where. Never "Nothing learned yet." while it has notes. */
|
|
488
|
+
const NONE_FIT = "You learned notes in earlier runs, but none fit this run's learning budget, so none is given here.";
|
|
489
|
+
const NONE_FIT_READ = `You learned notes in earlier runs, but none fit this run's learning budget. They are files in \`${LEARNED_DIR}/\` in your working directory: open one with the read tool when it applies.`;
|
|
490
|
+
/** The most a section past the budget takes beside its notes and lines: its longest intro, the read-tool line when the run
|
|
491
|
+
* has the read tool (`read`), and the blank lines between its parts (withinBudget). */
|
|
492
|
+
const FRAME_BYTES = (read) => Math.max(...[LINES_INTRO, BEST_INTRO, LINES_ONLY_INTRO].map((intro) => Buffer.byteLength(intro))) + (read ? Buffer.byteLength(READ_LINE) + 2 : 0) + 4;
|
|
465
493
|
/** A note as one rule line: its name and file, then its description, cut of the host's secrets. */
|
|
466
494
|
const ruleLine = (note, shown) => `- ${shown.text(oneLine(note.name))} (${shown.name(note.file)}): ${shown.text(oneLine(note.description))}`;
|
|
467
495
|
/** A note as a run reads it whole: its name and file, its description, then its body, each cut of the host's secrets. */
|
|
@@ -472,8 +500,10 @@ const wholeNote = (note, shown) => [`## ${shown.text(oneLine(note.name))} (${sho
|
|
|
472
500
|
* the index, nor counted toward the budget (readSeed reads active notes alone, and servedIndex drops their lines). Its
|
|
473
501
|
* active notes, newest first (`seed.recent`, else by name), each whole while all fit `budget`; past it, the selector's
|
|
474
502
|
* choice (byRelevance by default). An agent with the read tool is told the rest are in `.learning/`, one without is not.
|
|
503
|
+
* Notes past a budget that holds none of them (0 among them) are said to be there (NONE_FIT), never "Nothing learned yet.".
|
|
475
504
|
* Every text is cut of the host's secrets. A run "was given" `given`; of them, it "read" those whose file it opened
|
|
476
|
-
* (store-reads/learning.ts notesReadOf). Whether it applied one given whole is not measured.
|
|
505
|
+
* (store-reads/learning.ts notesReadOf). Whether it applied one given whole is not measured. `left`: the active notes
|
|
506
|
+
* the section names in no way, over the budget, which the run's log names (runner/learning-seed.ts). */
|
|
477
507
|
export function learnedParts(seed, options) {
|
|
478
508
|
const { budget, read, shown, select = byRelevance, run = {} } = options;
|
|
479
509
|
const active = new Map(activeOf(seed).map((note) => [note.file, note]));
|
|
@@ -481,7 +511,7 @@ export function learnedParts(seed, options) {
|
|
|
481
511
|
const index = servedIndex(seed);
|
|
482
512
|
const lines = index === undefined ? [] : loadedIndex(index).split("\n").filter((entry) => entry.trim() !== "");
|
|
483
513
|
if (!notes.length && !lines.length)
|
|
484
|
-
return { section: undefined, given: [] };
|
|
514
|
+
return { section: undefined, given: [], left: [] };
|
|
485
515
|
const blocks = new Map(notes.map((note) => [note, wholeNote(note, shown)]));
|
|
486
516
|
// Each part's bytes, and the blank line before it.
|
|
487
517
|
const size = (text) => Buffer.byteLength(text) + 2;
|
|
@@ -493,38 +523,45 @@ export function learnedParts(seed, options) {
|
|
|
493
523
|
indexBytes: shownIndex ? size(shownIndex) : 0,
|
|
494
524
|
indexComplete: lines.every((entry) => active.has(linkedFiles(entry)[0] ?? "")),
|
|
495
525
|
budget,
|
|
526
|
+
read,
|
|
496
527
|
}, run);
|
|
497
528
|
const chosen = new Set(choice.whole);
|
|
498
529
|
const whole = choice.whole.filter((note) => blocks.has(note)).map((note) => blocks.get(note));
|
|
499
530
|
// Rule lines in place of the index: the whole notes first, then a line for each of the rest the selector names.
|
|
500
531
|
if (choice.lines) {
|
|
501
532
|
// The whole section fits the budget, its intro, blank lines and read-tool line counted: while it does not, the last
|
|
502
|
-
//
|
|
503
|
-
//
|
|
533
|
+
// line goes, then the last whole note (whole notes are what a run reads past the budget, so they go last). The lines
|
|
534
|
+
// are capped as the index is read.
|
|
504
535
|
const wholeNotes = choice.whole.filter((note) => blocks.has(note));
|
|
505
536
|
// The lines as the index is read (learn/notes.ts loadedIndex): the first INDEX_LINES, within INDEX_BYTES, each line
|
|
506
|
-
// and its newline counted.
|
|
537
|
+
// and its newline counted.
|
|
507
538
|
const capped = (list) => {
|
|
508
539
|
let bytes = 0;
|
|
509
540
|
return list.slice(0, INDEX_LINES).filter((note) => (bytes += Buffer.byteLength(ruleLine(note, shown)) + 1) <= INDEX_BYTES);
|
|
510
541
|
};
|
|
511
|
-
|
|
512
|
-
const render = () => [LINES_INTRO, ...wholeNotes.map((note) => blocks.get(note)), lined.map((note) => ruleLine(note, shown)).join("\n"), ...(read &&
|
|
542
|
+
const lined = capped(choice.lines.filter((note) => blocks.has(note) && !chosen.has(note)));
|
|
543
|
+
const render = () => [!wholeNotes.length ? LINES_ONLY_INTRO : lined.length ? LINES_INTRO : BEST_INTRO, ...wholeNotes.map((note) => blocks.get(note)), lined.map((note) => ruleLine(note, shown)).join("\n"), ...(read && wholeNotes.length < notes.length ? [READ_LINE] : [])].filter(Boolean).join("\n\n");
|
|
513
544
|
let section = render();
|
|
514
|
-
while (Buffer.byteLength(section) > budget && wholeNotes.length) {
|
|
515
|
-
|
|
545
|
+
while (Buffer.byteLength(section) > budget && (lined.length || wholeNotes.length)) {
|
|
546
|
+
if (lined.length)
|
|
547
|
+
lined.pop();
|
|
548
|
+
else
|
|
549
|
+
wholeNotes.pop();
|
|
516
550
|
section = render();
|
|
517
551
|
}
|
|
518
552
|
const served = new Set([...wholeNotes, ...lined]);
|
|
519
|
-
|
|
553
|
+
// Notes, none of which fit the budget (0 among them): the run is told they are there, never that it learned nothing.
|
|
554
|
+
if (!served.size)
|
|
555
|
+
return { section: notes.length ? (read ? NONE_FIT_READ : NONE_FIT) : undefined, given: [], left: notes };
|
|
556
|
+
return { section, given: notes.filter((note) => served.has(note)), left: notes.filter((note) => !served.has(note)) };
|
|
520
557
|
}
|
|
521
558
|
if (!choice.index)
|
|
522
|
-
return { section: [WHOLE_INTRO, ...whole].join("\n\n"), given: notes.filter((note) => chosen.has(note)) };
|
|
559
|
+
return { section: [WHOLE_INTRO, ...whole].join("\n\n"), given: notes.filter((note) => chosen.has(note)), left: notes.filter((note) => !chosen.has(note)) };
|
|
523
560
|
// Given: each note whole here, and each the index names by its file, by any of a line's links (a hand-edited line may
|
|
524
561
|
// name more than one; linkedFiles, as servedIndex reads them).
|
|
525
562
|
const indexed = new Set(lines.flatMap((entry) => linkedFiles(entry).filter((file) => active.has(file))));
|
|
526
563
|
const given = notes.filter((note) => indexed.has(note.file) || chosen.has(note));
|
|
527
|
-
return { section: [whole.length ? SOME_INTRO : INDEX_INTRO, shownIndex, ...(read && whole.length < notes.length ? [READ_LINE] : []), ...whole].filter(Boolean).join("\n\n"), given };
|
|
564
|
+
return { section: [whole.length ? SOME_INTRO : INDEX_INTRO, shownIndex, ...(read && whole.length < notes.length ? [READ_LINE] : []), ...whole].filter(Boolean).join("\n\n"), given, left: notes.filter((note) => !given.includes(note)) };
|
|
528
565
|
}
|
|
529
566
|
/** The run's skills folder, `.agents/skills`, as its Workspace names it. */
|
|
530
567
|
const SKILLS_PATH = RUN_SKILLS.join("/");
|
|
@@ -729,16 +766,19 @@ export async function readPin(runDir) {
|
|
|
729
766
|
}
|
|
730
767
|
/** The heading of what a run learned, in its instructions. */
|
|
731
768
|
export const LEARNED_HEADING = "# Learned";
|
|
769
|
+
/** What a run that only uses what its agent learned (RUN_LEARNING_USE) is told first under it, in place of LEARNS: it is
|
|
770
|
+
* never asked what to keep. */
|
|
771
|
+
const USES = "You learned from earlier runs, below. This run keeps nothing new: when the person asks you to remember something, tell them in one short sentence that this run can't keep it.";
|
|
732
772
|
/** What every run that learns is told first under it, notes or none: a run not told it learns saves what the person
|
|
733
773
|
* asks it to remember in a file, or says it cannot, and that is never kept. */
|
|
734
774
|
const LEARNS = "You learn from your runs. When this run ends you are asked what to keep for later runs, anything the person asked you to remember included, and only your answer then is kept: a file you write is not. So when the person asks you to remember something, don't put it in a file or say you can't: tell them in one short sentence at the start of your reply that you will keep it for later runs. When what they asked sets how your reply starts or ends, follow it from your reply's first line to its last and leave that sentence out. A secret (a password, key or token) is never kept, so say so instead.";
|
|
735
775
|
/** What a run that starts with no note is told in place of what it learned. */
|
|
736
776
|
const NOTHING_YET = "Nothing learned yet.";
|
|
737
777
|
/** A run's instructions with its # Learned section laid in main's position: the revision's instructions, then the heading,
|
|
738
|
-
* LEARNS, and the section text — "Nothing learned yet." when the
|
|
739
|
-
* seed that could not be read). Shared so the runner (laying
|
|
740
|
-
* (withLearned) lay the same bytes. */
|
|
741
|
-
export const laidLearned = (instructions, section) => `${instructions.trim()}\n\n${LEARNED_HEADING}\n\n${LEARNS}\n\n${section || NOTHING_YET}`;
|
|
778
|
+
* LEARNS (USES for a run that only `use`s what its agent learned), and the section text — "Nothing learned yet." when the
|
|
779
|
+
* run learns but its section is empty (no notes yet, or a seed that could not be read). Shared so the runner (laying
|
|
780
|
+
* launch.learning.section, read with no folder) and app.ts (withLearned) lay the same bytes. */
|
|
781
|
+
export const laidLearned = (instructions, section, use = false) => `${instructions.trim()}\n\n${LEARNED_HEADING}\n\n${use ? USES : LEARNS}\n\n${section || NOTHING_YET}`;
|
|
742
782
|
/** A run's instructions, with `# Learned` after them when its pin in `runDir` says it learns: that it learns, then what
|
|
743
783
|
* the pin says it learned, or that it has learned nothing yet. A run with no pin (its agent does not learn, its seed
|
|
744
784
|
* failed, a workflow's run) is never asked what to keep, so it is told nothing. And its skill files: the revision's
|
package/dist/live/stream.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// stored commit (live/translate.ts), in commit order, each batch naming its commit's seq so a reader that comes back
|
|
4
4
|
// resumes from it; and beside them, never inside a commit's batch, what the runner holds before pi stores it (the run's
|
|
5
5
|
// run_live row: a running tool, a partial answer), in the same vocabulary.
|
|
6
|
-
import { RUN_RESUMED } from "../timeline/index.js";
|
|
6
|
+
import { REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
|
|
7
7
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
8
8
|
import { FINAL_STATES } from "../store/store.js";
|
|
9
9
|
import { emptyState, snapshotOf, translate } from "./translate.js";
|
|
@@ -12,8 +12,11 @@ import { emptyState, snapshotOf, translate } from "./translate.js";
|
|
|
12
12
|
* row — but it is not a live stream event: a takeover ends the door's watch, so a reader meets the note only in a
|
|
13
13
|
* reconnect's snapshot, never as a commit on the open stream. The live view polls across a takeover, so without this it
|
|
14
14
|
* would stream the note's entry_appended; dropping it keeps a run taken over mid-turn streaming the same events as one
|
|
15
|
-
* that was not. The note stays in state.entries (translate pushed it before returning), so the next snapshot carries it.
|
|
16
|
-
|
|
15
|
+
* that was not. The note stays in state.entries (translate pushed it before returning), so the next snapshot carries it.
|
|
16
|
+
* A request's start and end marks (REQUEST_STARTED, REQUEST_ENDED) are the same: bookkeeping the timeline reads for a
|
|
17
|
+
* request's cost, no event a watcher is shown. */
|
|
18
|
+
const NOT_STREAMED = new Set([RUN_RESUMED, REQUEST_STARTED, REQUEST_ENDED]);
|
|
19
|
+
const delivered = (events) => events.filter((event) => !(event.type === "entry_appended" && NOT_STREAMED.has(event.entry?.kind)));
|
|
17
20
|
const PAGE = 500;
|
|
18
21
|
/** The journals each store's watches read, by (run, epoch), with how many watches hold each. store.journal hands out one
|
|
19
22
|
* journal per (run, epoch) and keeps it until it is closed: two watches of one run share it, and the last one to end
|
package/dist/live/translate.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { JsonValue } from "@earendil-works/chord";
|
|
1
|
+
import type { JsonValue } from "@earendil-works/chord/json";
|
|
2
2
|
import { type EntryRecord, type SubmissionRecord } from "@earendil-works/pi-durable";
|
|
3
3
|
import type { JournalCommit } from "../store/journal/storage.js";
|
|
4
4
|
export type LiveEvent = {
|
|
@@ -36,8 +36,9 @@ export interface LiveState {
|
|
|
36
36
|
}>;
|
|
37
37
|
/** An answer streamed as a partial (held): its stored message is only its end. */
|
|
38
38
|
partial: boolean;
|
|
39
|
-
/** Where the run's end-of-run turn began (end-of-run.ts
|
|
40
|
-
* on carry the learning label, a tag the reader puts on (the run writes
|
|
39
|
+
/** Where the run's end-of-run turn under way began (end-of-run.ts reflectRanges), once its input is placed, until the
|
|
40
|
+
* run's end closes it: its messages from there on carry the learning label, a tag the reader puts on (the run writes
|
|
41
|
+
* nothing for it). A follow-up's messages, after that end, carry none; its next end's turn begins anew. */
|
|
41
42
|
reflectFrom?: number;
|
|
42
43
|
}
|
|
43
44
|
export declare function emptyState(): LiveState;
|
package/dist/live/translate.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AgentDoc, UsageDoc } from "@earendil-works/pi-durable";
|
|
2
2
|
import { HOST_PHASE, RUN_RESUMED } from "../timeline/index.js";
|
|
3
|
-
import { REFLECT_LABEL,
|
|
3
|
+
import { inReflect, REFLECT_LABEL, reflectRanges } from "../runner/end-of-run.js";
|
|
4
4
|
import { KINDS } from "../runner/journal-kinds.js";
|
|
5
5
|
import { PI_STOP } from "../runner/pi-stop.js";
|
|
6
6
|
export function emptyState() {
|
|
@@ -106,9 +106,13 @@ export function translate(state, commit) {
|
|
|
106
106
|
const entries = commit.entries.filter(mine);
|
|
107
107
|
const tasks = commit.tasks.filter(mine);
|
|
108
108
|
const submissions = commit.submissions.filter(mine);
|
|
109
|
-
// The end-of-run turn
|
|
110
|
-
|
|
111
|
-
const
|
|
109
|
+
// The end-of-run turn under way, and any whose input was placed in this commit: their messages, up to the run's end that
|
|
110
|
+
// closes each, are the turn's. One still open after this commit carries on to the next.
|
|
111
|
+
const endAt = (from) => entries.find((entry) => entry.kind === KINDS.end && Number(entry.id) >= from);
|
|
112
|
+
const carried = state.reflectFrom === undefined ? [] : [{ from: state.reflectFrom, ...(endAt(state.reflectFrom) ? { until: Number(endAt(state.reflectFrom).id) } : {}) }];
|
|
113
|
+
const ranges = [...carried, ...reflectRanges(submissions, entries)];
|
|
114
|
+
state.reflectFrom = ranges.filter((range) => range.until === undefined).at(-1)?.from;
|
|
115
|
+
const tag = (entry) => (inReflect(ranges, Number(entry.id)) ? { agent_label: REFLECT_LABEL } : {});
|
|
112
116
|
for (const entry of entries) {
|
|
113
117
|
const message = modelOf(entry);
|
|
114
118
|
if (message?.role === "assistant" && Array.isArray(message.content)) {
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
/** The header the proxy's proof travels in. */
|
|
3
|
+
export declare const LIVE_PROOF_HEADER = "x-agentrun-live";
|
|
4
|
+
/** How far a proof's time may be from the endpoint's clock. */
|
|
5
|
+
export declare const LIVE_PROOF_MS = 60000;
|
|
6
|
+
/** Where every viewer answers when its runner is on the server's own machine. */
|
|
7
|
+
export declare const LOOPBACK = "127.0.0.1";
|
|
8
|
+
export declare const isLiveHost: (host: unknown) => host is string;
|
|
9
|
+
/** What the server needs to reach a runner's viewer: the hosts it dials (its runners'), and the proof's key. */
|
|
10
|
+
export type LiveReach = {
|
|
11
|
+
readonly hosts: ReadonlySet<string>;
|
|
12
|
+
readonly key: Buffer;
|
|
13
|
+
};
|
|
14
|
+
/** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
|
|
15
|
+
* out. */
|
|
16
|
+
export declare function liveReachOf(env: {
|
|
17
|
+
readonly AGENTRUN_RUNNER_HOSTS?: string | undefined;
|
|
18
|
+
}, sealKey: Buffer): LiveReach;
|
|
19
|
+
/** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
|
|
20
|
+
export declare function dialHost(host: string | undefined, reach: LiveReach | undefined): string | undefined;
|
|
21
|
+
/** The proxy's proof for viewer `viewerId`, at `at` (ms). */
|
|
22
|
+
export declare const liveProof: (reach: Pick<LiveReach, "key">, viewerId: string, at?: number) => string;
|
|
23
|
+
/** Where a runner's viewers answer: the host the server reaches it at (put in each row), the address they listen on,
|
|
24
|
+
* and the proof's key. */
|
|
25
|
+
export type RunnerLive = {
|
|
26
|
+
readonly host: string;
|
|
27
|
+
readonly bind: string;
|
|
28
|
+
readonly key: Buffer;
|
|
29
|
+
};
|
|
30
|
+
/** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
|
|
31
|
+
* undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
|
|
32
|
+
export declare function runnerLiveOf(env: {
|
|
33
|
+
readonly AGENTRUN_RUNNER_LIVE_HOST?: string | undefined;
|
|
34
|
+
readonly AGENTRUN_RUNNER_LIVE_BIND?: string | undefined;
|
|
35
|
+
}, sealKey: Buffer): RunnerLive | undefined;
|
|
36
|
+
/** Whether `req` carries a good, fresh proof for viewer `viewerId` under `live`'s key. */
|
|
37
|
+
export declare function provenFor(req: Pick<IncomingMessage, "headers">, live: Pick<RunnerLive, "key">, viewerId: string, now?: number): boolean;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// A live viewer on a runner on another host than its server (one image, a server and its runners apart). The runner says
|
|
2
|
+
// where it answers (AGENTRUN_RUNNER_LIVE_HOST: a host name or IPv4 address the server reaches it at; the viewers listen
|
|
3
|
+
// on AGENTRUN_RUNNER_LIVE_BIND, that host by default) and puts that host in each viewer's row. The server dials a row's
|
|
4
|
+
// host only when it is one of its runners' (AGENTRUN_RUNNER_HOSTS, a comma list), else the row reads as no viewer: a
|
|
5
|
+
// store writer that is no runner can't aim the server's socket elsewhere. Each request the server makes of a runner's
|
|
6
|
+
// viewer (the HEAD that asks whether it answers, and the proxied WebSocket) carries the proxy's proof: an HMAC of the
|
|
7
|
+
// viewer's id and the time, under a key derived from the seal key the server and its runners already share. A runner's
|
|
8
|
+
// endpoint off loopback takes no request without a good, fresh proof for its own viewer. The proof is not the viewer's:
|
|
9
|
+
// the hello's token still decides who watches. The hop is plain HTTP, for a private network (the server and its
|
|
10
|
+
// runners' own); TLS on it is a later step.
|
|
11
|
+
import { createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
|
|
12
|
+
/** The header the proxy's proof travels in. */
|
|
13
|
+
export const LIVE_PROOF_HEADER = "x-agentrun-live";
|
|
14
|
+
/** How far a proof's time may be from the endpoint's clock. */
|
|
15
|
+
export const LIVE_PROOF_MS = 60_000;
|
|
16
|
+
/** A host a row may name: a DNS name or an IPv4 address, nothing with a port, a path or a scheme. */
|
|
17
|
+
const HOST = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
|
|
18
|
+
/** Where every viewer answers when its runner is on the server's own machine. */
|
|
19
|
+
export const LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule where a viewer on the same machine as its server answers
|
|
20
|
+
/** The derived key's label: the seal key itself is never a MAC key. */
|
|
21
|
+
const LABEL = "agentrun live proxy v1";
|
|
22
|
+
export const isLiveHost = (host) => typeof host === "string" && HOST.test(host);
|
|
23
|
+
const proofKey = (sealKey) => Buffer.from(hkdfSync("sha256", sealKey, Buffer.alloc(0), LABEL, 32));
|
|
24
|
+
const mac = (key, viewerId, at) => createHmac("sha256", key).update(`${viewerId}\n${at}`).digest("hex");
|
|
25
|
+
/** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
|
|
26
|
+
* out. */
|
|
27
|
+
export function liveReachOf(env, sealKey) {
|
|
28
|
+
const hosts = new Set((env.AGENTRUN_RUNNER_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(isLiveHost));
|
|
29
|
+
return { hosts, key: proofKey(sealKey) };
|
|
30
|
+
}
|
|
31
|
+
/** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
|
|
32
|
+
export function dialHost(host, reach) {
|
|
33
|
+
if (host === undefined || host === LOOPBACK)
|
|
34
|
+
return LOOPBACK;
|
|
35
|
+
return reach?.hosts.has(host.toLowerCase()) ? host : undefined;
|
|
36
|
+
}
|
|
37
|
+
/** The proxy's proof for viewer `viewerId`, at `at` (ms). */
|
|
38
|
+
export const liveProof = (reach, viewerId, at = Date.now()) => `${at}.${mac(reach.key, viewerId, at)}`;
|
|
39
|
+
/** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
|
|
40
|
+
* undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
|
|
41
|
+
export function runnerLiveOf(env, sealKey) {
|
|
42
|
+
// Lower case, as a URL's hostname reads a DNS name and the server's runners' hosts are read (liveReachOf): one form for
|
|
43
|
+
// the links, the origins and the rows.
|
|
44
|
+
const host = env.AGENTRUN_RUNNER_LIVE_HOST?.trim().toLowerCase();
|
|
45
|
+
if (!isLiveHost(host) || host === LOOPBACK)
|
|
46
|
+
return undefined;
|
|
47
|
+
const bind = env.AGENTRUN_RUNNER_LIVE_BIND?.trim().toLowerCase();
|
|
48
|
+
return { host, bind: bind && (isLiveHost(bind) || bind === "0.0.0.0") ? bind : host, key: proofKey(sealKey) };
|
|
49
|
+
}
|
|
50
|
+
/** Whether `req` carries a good, fresh proof for viewer `viewerId` under `live`'s key. */
|
|
51
|
+
export function provenFor(req, live, viewerId, now = Date.now()) {
|
|
52
|
+
const said = req.headers[LIVE_PROOF_HEADER];
|
|
53
|
+
const match = typeof said === "string" ? /^(\d{1,16})\.([0-9a-f]{64})$/.exec(said) : null;
|
|
54
|
+
if (!match)
|
|
55
|
+
return false;
|
|
56
|
+
const at = Number(match[1]);
|
|
57
|
+
if (!Number.isSafeInteger(at) || Math.abs(now - at) > LIVE_PROOF_MS)
|
|
58
|
+
return false;
|
|
59
|
+
const want = Buffer.from(mac(live.key, viewerId, at), "hex");
|
|
60
|
+
const got = Buffer.from(match[2], "hex");
|
|
61
|
+
return got.length === want.length && timingSafeEqual(got, want);
|
|
62
|
+
}
|
package/dist/mcp-gateway.d.ts
CHANGED
|
@@ -69,6 +69,15 @@ export interface McpGatewayOptions {
|
|
|
69
69
|
};
|
|
70
70
|
/** The run's commit to its store: an unpriced call's "not metered" is written on its root. */
|
|
71
71
|
commit?: () => McpCommit | undefined;
|
|
72
|
+
/** Where each request to a server may go, asked before anything is sent to it: the runner's MCP claim passes the
|
|
73
|
+
* address rule (mcp-oauth.ts mcpServerAt) with the owner's private-network hosts read now, and a fetch dialled at the
|
|
74
|
+
* address it checked (`send`; none, `fetch` as it is). A refusal is said to the model, nothing sent. None: every
|
|
75
|
+
* request goes as `fetch` sends it. */
|
|
76
|
+
reach?: (url: string, signal: AbortSignal) => Promise<{
|
|
77
|
+
refused: string;
|
|
78
|
+
} | {
|
|
79
|
+
send?: typeof fetch;
|
|
80
|
+
}>;
|
|
72
81
|
/** The claim's per-call check of a server's credential (its custody stamp): awaited before each call is checked for
|
|
73
82
|
* sending, it may drop the credential (`credentials[server].unopened`), which the call then refuses unsent; one that
|
|
74
83
|
* throws (a store read failed, the call was stopped) refuses the call unsent too, in words, and the run goes on. Only
|
package/dist/mcp-gateway.js
CHANGED
|
@@ -142,6 +142,26 @@ export function mcpPinOf(names, source) {
|
|
|
142
142
|
}
|
|
143
143
|
return pin;
|
|
144
144
|
}
|
|
145
|
+
/** A request's address refused by the guarded fetch below, before anything left: thrown only there, and told apart by
|
|
146
|
+
* its class, never by its words. A server's error answer can carry the same words after it ran the call (the SDK puts
|
|
147
|
+
* the body of a failed POST in its error's message), and reading them as this refusal would say a call that may have
|
|
148
|
+
* run was never sent. */
|
|
149
|
+
class AddressRefused extends Error {
|
|
150
|
+
reason;
|
|
151
|
+
constructor(reason) {
|
|
152
|
+
super(`its address is refused here: ${reason}`);
|
|
153
|
+
this.reason = reason;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** The reason of the address refusal an error is, or a cause the SDK wrapped it in: the one request's own, so a
|
|
157
|
+
* refusal of one call is never read as another's. */
|
|
158
|
+
function addressRefusal(error) {
|
|
159
|
+
for (let e = error, depth = 0; e && depth < 8; e = e.cause, depth++) {
|
|
160
|
+
if (e instanceof AddressRefused)
|
|
161
|
+
return e.reason;
|
|
162
|
+
}
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
145
165
|
/** Why a connection failed, in a few words: the network's own code, read down the error's causes (the SDK wraps fetch's
|
|
146
166
|
* error, which wraps the socket's), else the deepest message, cut short. */
|
|
147
167
|
function unreachable(error) {
|
|
@@ -181,7 +201,8 @@ export function mcpGateway(options) {
|
|
|
181
201
|
const clients = new Map();
|
|
182
202
|
const pins = new Map(Object.entries(options.pin));
|
|
183
203
|
const credentials = { get: (server) => (Object.hasOwn(options.credentials, server) ? options.credentials[server] : undefined) };
|
|
184
|
-
/** Each server's last HTTP status, which tells a refused credential from another failure.
|
|
204
|
+
/** Each server's last HTTP status, which tells a refused credential from another failure. (An address refusal is never
|
|
205
|
+
* kept here: it is read from each call's own error, since calls to one server run at once.) */
|
|
185
206
|
const statuses = new Map();
|
|
186
207
|
const send = options.fetch ?? fetch;
|
|
187
208
|
/** The credential values each call in flight took or its server's requests sent while it was out, one set per call, by
|
|
@@ -216,11 +237,22 @@ export function mcpGateway(options) {
|
|
|
216
237
|
const scrubberOf = (server, headers, values) => (text) => scrub(text, [...Object.values(headers), ...values, ...Object.values(credentials.get(server)?.headers ?? {})]);
|
|
217
238
|
/** The fetch one server's client sends with: its credential added, no redirect followed, at most MAX_RESPONSE read. */
|
|
218
239
|
const guarded = (server, headers, status) => async (input, init = {}) => {
|
|
240
|
+
// Its address checked first, every request: a name that resolves somewhere private now is refused before anything
|
|
241
|
+
// (its credential among it) leaves, and the request is dialled at the address checked.
|
|
242
|
+
let through = send;
|
|
243
|
+
if (options.reach) {
|
|
244
|
+
const at = await options.reach(input instanceof Request ? input.url : String(input), init.signal ?? AbortSignal.timeout(options.bounds?.connectMs ?? CONNECT_MS));
|
|
245
|
+
if ("refused" in at) {
|
|
246
|
+
throw new AddressRefused(at.refused);
|
|
247
|
+
}
|
|
248
|
+
if (at.send)
|
|
249
|
+
through = at.send;
|
|
250
|
+
}
|
|
219
251
|
const sent = new Headers(init.headers);
|
|
220
252
|
// Live credentials: the server's headers as they are at this request, held for the scrub before they leave.
|
|
221
253
|
for (const [name, value] of Object.entries(hold(server, typeof headers === "function" ? headers() : headers)))
|
|
222
254
|
sent.set(name, value);
|
|
223
|
-
const response = await
|
|
255
|
+
const response = await through(input, { ...init, headers: sent, redirect: "manual" });
|
|
224
256
|
status.last = response.status;
|
|
225
257
|
if (response.status >= 300 && response.status < 400)
|
|
226
258
|
throw new Error(`it answered a redirect (HTTP ${response.status}), which is never followed`);
|
|
@@ -296,7 +328,7 @@ export function mcpGateway(options) {
|
|
|
296
328
|
* it, in `call` below: the one place every harness's call passes before anything is sent. */
|
|
297
329
|
/** `sending`, when given, runs once the server is connected and right before the call leaves: its refusal (a text)
|
|
298
330
|
* keeps the call from leaving. A call that never got that far (a failed connect, a stop) never ran it. */
|
|
299
|
-
const forward = async (server, url, headers, tool, args, signal, sending) => {
|
|
331
|
+
const forward = async (server, url, headers, tool, args, signal, sending, outcome = {}) => {
|
|
300
332
|
let connected = false;
|
|
301
333
|
// Read at each use: a token refreshed while the call is out, and sent, is scrubbed with the one it took.
|
|
302
334
|
const held = callSet(server);
|
|
@@ -319,6 +351,15 @@ export function mcpGateway(options) {
|
|
|
319
351
|
return said(`The call to the MCP server ${server} was stopped.`, true);
|
|
320
352
|
// The next call connects again (a server that dropped its session, say); this one is never sent again.
|
|
321
353
|
clients.delete(server);
|
|
354
|
+
// Its address refused before the request left (reach): nothing reached it. Read from this call's own error, never
|
|
355
|
+
// from the server's shared state: another call's refusal says nothing of whether this one was sent.
|
|
356
|
+
const refused = addressRefusal(error);
|
|
357
|
+
if (refused !== undefined) {
|
|
358
|
+
// `sending` may have run already (the connection was open): the request's own address check refused it, so the call
|
|
359
|
+
// never left and `outcome` says so, for the caller that books a price only for a call that went.
|
|
360
|
+
outcome.unsent = true;
|
|
361
|
+
return said(`The MCP server ${server}'s address is refused here: ${refused}. Nothing was sent.`, true);
|
|
362
|
+
}
|
|
322
363
|
const status = statuses.get(server)?.last;
|
|
323
364
|
// An OAuth token that expired mid-run is not refreshed here (no channel to serve for it): the next launch does.
|
|
324
365
|
if (status === 401 || status === 403)
|
|
@@ -376,11 +417,18 @@ export function mcpGateway(options) {
|
|
|
376
417
|
const listed = pinnedTools.find((t) => t.name === tool);
|
|
377
418
|
// Whether the call left for the server: only then is it booked, at its price or as not metered.
|
|
378
419
|
let went = false;
|
|
379
|
-
const call = (mark = async () => undefined) =>
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
420
|
+
const call = async (mark = async () => undefined) => {
|
|
421
|
+
const outcome = {};
|
|
422
|
+
const result = await forward(server, url, credentials.get(server)?.headers ?? {}, listed, args, signal, async () => {
|
|
423
|
+
const refused = await mark();
|
|
424
|
+
went = refused === undefined;
|
|
425
|
+
return refused;
|
|
426
|
+
}, outcome);
|
|
427
|
+
// The request's own address check refused it after the mark: it never left, so nothing is booked.
|
|
428
|
+
if (outcome.unsent)
|
|
429
|
+
went = false;
|
|
430
|
+
return result;
|
|
431
|
+
};
|
|
384
432
|
const name = mcpToolName(server, tool);
|
|
385
433
|
const label = { tool: name, charged_by: server, call: callId };
|
|
386
434
|
const commit = options.commit?.();
|
|
@@ -404,9 +452,10 @@ export function mcpGateway(options) {
|
|
|
404
452
|
servers: [...pins].map(([name, pinned]) => ({ name, tools: pinned.tools })),
|
|
405
453
|
heldValues: () => [...new Set([...inFlight.values()].flatMap((calls) => [...calls].flatMap((values) => [...values])))],
|
|
406
454
|
async call(server, tool, args, { signal, callId }) {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
455
|
+
// Only what no sign-in can change is refused here: the rest (a credential that did not open, a server since removed)
|
|
456
|
+
// is read by sent() after beforeCall, which opens the row again, so a call after the owner signs in again goes.
|
|
457
|
+
if (!pins.get(server)?.tools.some((t) => t.name === tool))
|
|
458
|
+
return said(`${tool} is not a tool of the MCP server ${server} in this run.`, true);
|
|
410
459
|
return sent(server, tool, args, callId ?? `mcp_${randomUUID()}`, signal);
|
|
411
460
|
},
|
|
412
461
|
};
|