@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
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// The attach binding's own conformance cases (spec/computer/attach.md), run against any driver that dials in: Computerd
|
|
2
|
+
// on a Mac, a driver on Android, Windows or Linux next, or the fake driver of serve's tests. It starts the binding's
|
|
3
|
+
// server half (createAttachRoutes over a store of its own in a scratch directory and an AttachHub, on a port), makes a
|
|
4
|
+
// pairing code, and waits for the driver to pair with it and dial. Then it acts on the socket as the server may (a ping, a
|
|
5
|
+
// quiet minute, a close with each code a driver must redial after, a drop, a binary frame, a frame over the limit, a
|
|
6
|
+
// second socket with the same token, a revoke) and checks what the driver does. Nothing here knows an OS: a driver passes
|
|
7
|
+
// by what it does on the wire. The next OS's driver passes these cases; the server is not tested again for it.
|
|
8
|
+
//
|
|
9
|
+
// node dist/attach-conformance-cli.js [--port N] [--listen ADDR]
|
|
10
|
+
//
|
|
11
|
+
// prints the server address and a code to type into the driver, runs the cases once the driver has paired, prints a
|
|
12
|
+
// PASS or FAIL line for each, and exits 0 when every case passed. It takes about five minutes with a real driver (a
|
|
13
|
+
// minute of quiet, and the redials' waits as the protocol doubles them). serve's own test runs it on a shorter clock
|
|
14
|
+
// against the fake driver (test/attach-conformance.test.mjs).
|
|
15
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
16
|
+
import { createServer } from "node:http";
|
|
17
|
+
import { tmpdir } from "node:os";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
import { ATTACH_CLOSE, ATTACH_HEARTBEAT_MS, ATTACH_IDLE_MS, ATTACH_PATH, ATTACH_REDIAL_MAX_MS, ATTACH_SUBPROTOCOL, AttachHub, MAX_LINE_BYTES, PROTOCOL_VERSION } from "@parcha/agentrun-computer";
|
|
20
|
+
import WebSocket from "ws";
|
|
21
|
+
import { createAttachRoutes } from "./computer-attach.js";
|
|
22
|
+
import { ApiError } from "./errors.js";
|
|
23
|
+
import { openSqliteStore } from "./store/index.js";
|
|
24
|
+
/** The most of a pairing request's body this server keeps (a code and a hello): a larger one is refused 413. */
|
|
25
|
+
export const PAIR_BODY_MAX = 1 << 20;
|
|
26
|
+
/** The cases, in the order they run: each later one needs the driver attached, and revoke ends it. */
|
|
27
|
+
export const ATTACH_CASES = [
|
|
28
|
+
"pair",
|
|
29
|
+
"wrong-or-used-code",
|
|
30
|
+
"ping",
|
|
31
|
+
"quiet",
|
|
32
|
+
"redial-after-close",
|
|
33
|
+
"redial-after-drop",
|
|
34
|
+
"binary-frame",
|
|
35
|
+
"oversize-frame",
|
|
36
|
+
"same-token",
|
|
37
|
+
"revoke",
|
|
38
|
+
];
|
|
39
|
+
/** `ms` in seconds, to a tenth where it is under ten. */
|
|
40
|
+
const seconds = (ms) => (ms < 10_000 ? (ms / 1000).toFixed(1) : String(Math.round(ms / 1000)));
|
|
41
|
+
class Failed extends Error {
|
|
42
|
+
}
|
|
43
|
+
const fail = (why) => {
|
|
44
|
+
throw new Failed(why);
|
|
45
|
+
};
|
|
46
|
+
/** Runs every case against the driver that pairs with the printed code; answers each case's result. */
|
|
47
|
+
export async function runAttachConformance(options) {
|
|
48
|
+
const scale = options.scale ?? 1;
|
|
49
|
+
const say = options.say ?? (() => { });
|
|
50
|
+
const ms = (protocolMs) => Math.max(1, Math.round(protocolMs * scale));
|
|
51
|
+
/** How long a driver may take to dial back: the protocol's longest redial, and slack for a dial and its hello. */
|
|
52
|
+
const redialWithin = ms(ATTACH_REDIAL_MAX_MS + 5_000) + 2_000;
|
|
53
|
+
const dir = mkdtempSync(join(tmpdir(), "attach-conformance-"));
|
|
54
|
+
const store = await openSqliteStore({ dataDir: dir });
|
|
55
|
+
const hub = new AttachHub();
|
|
56
|
+
const dials = [];
|
|
57
|
+
/** Every dial at the attach path, a refused one too (a revoked token is refused before any socket). */
|
|
58
|
+
let attempts = 0;
|
|
59
|
+
const waiters = new Set();
|
|
60
|
+
const changed = () => {
|
|
61
|
+
for (const wake of [...waiters])
|
|
62
|
+
wake();
|
|
63
|
+
};
|
|
64
|
+
let paired;
|
|
65
|
+
const ourCloses = new WeakSet();
|
|
66
|
+
const routes = createAttachRoutes({
|
|
67
|
+
store,
|
|
68
|
+
hub,
|
|
69
|
+
timing: { heartbeatMs: ms(ATTACH_HEARTBEAT_MS), idleMs: ms(ATTACH_IDLE_MS) },
|
|
70
|
+
log: (event, fields) => {
|
|
71
|
+
if (event !== "computer_attached")
|
|
72
|
+
return;
|
|
73
|
+
const dial = [...dials].reverse().find((one) => one.closed === undefined);
|
|
74
|
+
const hello = hub.hello(fields.computer ?? "");
|
|
75
|
+
if (dial && hello)
|
|
76
|
+
dial.hello = hello;
|
|
77
|
+
changed();
|
|
78
|
+
},
|
|
79
|
+
onSocket: (_computer, ws) => {
|
|
80
|
+
const dial = { ws, at: Date.now(), pings: 0 };
|
|
81
|
+
dials.push(dial);
|
|
82
|
+
ws.on("ping", () => void (dial.pings++, changed()));
|
|
83
|
+
ws.on("close", (code, reason) => {
|
|
84
|
+
dial.closed = { code, reason: reason.toString("utf8"), byUs: ourCloses.has(ws) };
|
|
85
|
+
changed();
|
|
86
|
+
});
|
|
87
|
+
changed();
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
const server = createServer((req, res) => void answer(req, res));
|
|
91
|
+
async function answer(req, res) {
|
|
92
|
+
const send = (status, body) => {
|
|
93
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
|
94
|
+
res.end(JSON.stringify(body));
|
|
95
|
+
};
|
|
96
|
+
if (req.method !== "POST" || req.url !== "/v2/computers/pair")
|
|
97
|
+
return send(404, { error: { code: "not_found", message: "the conformance server answers POST /v2/computers/pair and the attach socket only" } });
|
|
98
|
+
try {
|
|
99
|
+
// Only up to PAIR_BODY_MAX bytes are kept (a code and a hello are small), the rest is read through and refused, so the
|
|
100
|
+
// client gets the answer and a body of any size cannot grow this process.
|
|
101
|
+
const chunks = [];
|
|
102
|
+
let size = 0;
|
|
103
|
+
for await (const chunk of req) {
|
|
104
|
+
size += chunk.length;
|
|
105
|
+
if (size <= PAIR_BODY_MAX)
|
|
106
|
+
chunks.push(chunk);
|
|
107
|
+
}
|
|
108
|
+
if (size > PAIR_BODY_MAX)
|
|
109
|
+
throw new ApiError("payload_too_large", `the pairing body is over ${PAIR_BODY_MAX} bytes`);
|
|
110
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8") || "null");
|
|
111
|
+
const made = await routes.pair(body, req.socket.remoteAddress ?? "unknown");
|
|
112
|
+
paired = { ...made, hello: body.hello };
|
|
113
|
+
changed();
|
|
114
|
+
send(201, made);
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
if (error instanceof ApiError)
|
|
118
|
+
return send(error.status, { error: { code: error.code, message: error.message, ...error.extra } });
|
|
119
|
+
send(400, { error: { code: "bad_request", message: error instanceof Error ? error.message : String(error) } });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
server.on("upgrade", (req, socket, head) => {
|
|
123
|
+
if (new URL(req.url ?? "/", "http://x").pathname !== ATTACH_PATH)
|
|
124
|
+
return socket.destroy();
|
|
125
|
+
attempts++;
|
|
126
|
+
changed();
|
|
127
|
+
routes.upgrade(req, socket, head, (status, words, headers = {}) => {
|
|
128
|
+
if (!socket.writable)
|
|
129
|
+
return void socket.destroy();
|
|
130
|
+
const text = words ?? status;
|
|
131
|
+
socket.end(`HTTP/1.1 ${status}\r\n${Object.entries({ ...headers, "content-type": "text/plain; charset=utf-8", "content-length": String(Buffer.byteLength(text)), connection: "close" }).map(([key, value]) => `${key}: ${value}\r\n`).join("")}\r\n${text}`);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
// A port already in use (or an address this host lacks) is an error event with no listener otherwise, which would crash
|
|
135
|
+
// the CLI and leave the scratch store behind: it rejects here, and the scratch is cleaned before the error goes on.
|
|
136
|
+
try {
|
|
137
|
+
await new Promise((done, fail) => {
|
|
138
|
+
server.once("error", fail);
|
|
139
|
+
server.listen(options.port ?? 0, options.host ?? "127.0.0.1", () => {
|
|
140
|
+
server.off("error", fail);
|
|
141
|
+
done();
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
await routes.close();
|
|
147
|
+
await store.close();
|
|
148
|
+
rmSync(dir, { recursive: true, force: true });
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
const { port } = server.address();
|
|
152
|
+
const host = options.host ?? "127.0.0.1";
|
|
153
|
+
// An IPv6 address goes in brackets in a URL ("http://[::1]:7392").
|
|
154
|
+
const address = `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
|
|
155
|
+
/** Resolves once `ready` answers something, or fails after `within` ms saying `what`. */
|
|
156
|
+
const until = (ready, within, what) => new Promise((resolve, reject) => {
|
|
157
|
+
const check = () => {
|
|
158
|
+
const value = ready();
|
|
159
|
+
if (value === undefined || value === false)
|
|
160
|
+
return false;
|
|
161
|
+
finish();
|
|
162
|
+
resolve(value);
|
|
163
|
+
return true;
|
|
164
|
+
};
|
|
165
|
+
const timer = setTimeout(() => {
|
|
166
|
+
finish();
|
|
167
|
+
reject(new Failed(`${what}, within ${(within / 1000).toFixed(1)} s`));
|
|
168
|
+
}, within);
|
|
169
|
+
const finish = () => {
|
|
170
|
+
clearTimeout(timer);
|
|
171
|
+
waiters.delete(wake);
|
|
172
|
+
};
|
|
173
|
+
const wake = () => void check();
|
|
174
|
+
waiters.add(wake);
|
|
175
|
+
check();
|
|
176
|
+
});
|
|
177
|
+
/** No `happened` for `within` ms; fails saying `what` as soon as it does. */
|
|
178
|
+
const never = (happened, within, what) => new Promise((resolve, reject) => {
|
|
179
|
+
const timer = setTimeout(() => {
|
|
180
|
+
waiters.delete(wake);
|
|
181
|
+
resolve();
|
|
182
|
+
}, within);
|
|
183
|
+
const wake = () => {
|
|
184
|
+
if (!happened())
|
|
185
|
+
return;
|
|
186
|
+
clearTimeout(timer);
|
|
187
|
+
waiters.delete(wake);
|
|
188
|
+
reject(new Failed(what()));
|
|
189
|
+
};
|
|
190
|
+
waiters.add(wake);
|
|
191
|
+
wake();
|
|
192
|
+
});
|
|
193
|
+
const live = () => {
|
|
194
|
+
const last = dials.at(-1);
|
|
195
|
+
return last && last.closed === undefined && last.hello ? last : undefined;
|
|
196
|
+
};
|
|
197
|
+
/** The next socket after `before` (a count of dials) whose hello was kept. */
|
|
198
|
+
const redialed = (before, what) => until(() => dials.slice(before).find((dial) => dial.hello && dial.closed === undefined), redialWithin, what);
|
|
199
|
+
const closeOurs = (dial, code, reason) => {
|
|
200
|
+
ourCloses.add(dial.ws);
|
|
201
|
+
dial.ws.close(code, reason);
|
|
202
|
+
};
|
|
203
|
+
const results = [];
|
|
204
|
+
async function run(name, body) {
|
|
205
|
+
const prior = results.find((result) => !result.ok && result.name === "pair");
|
|
206
|
+
if (prior && name !== "wrong-or-used-code") {
|
|
207
|
+
results.push({ name, ok: false, detail: "not run: the driver never paired and attached" });
|
|
208
|
+
return say(`FAIL ${name}: not run: the driver never paired and attached`);
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
const detail = await body();
|
|
212
|
+
results.push({ name, ok: true, detail });
|
|
213
|
+
say(`PASS ${name}: ${detail}`);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
217
|
+
results.push({ name, ok: false, detail });
|
|
218
|
+
say(`FAIL ${name}: ${detail}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
try {
|
|
222
|
+
const pairing = await routes.createPairing();
|
|
223
|
+
say(`Server address ${address}, code ${pairing.code}: type both into the driver (it has ${seconds(options.pairMs ?? 600_000)} s).`);
|
|
224
|
+
await options.pair(address, pairing.code);
|
|
225
|
+
await run("pair", async () => {
|
|
226
|
+
await until(() => paired, options.pairMs ?? 600_000, "the driver did not pair with the code");
|
|
227
|
+
const dial = await until(() => live(), ms(30_000) + 2_000, "the driver paired but did not dial the attach socket and answer hello");
|
|
228
|
+
const hello = dial.hello;
|
|
229
|
+
if (dial.ws.protocol !== ATTACH_SUBPROTOCOL)
|
|
230
|
+
fail(`it asked for ${dial.ws.protocol || "no subprotocol"}, not ${ATTACH_SUBPROTOCOL}`);
|
|
231
|
+
if (hello.protocol !== PROTOCOL_VERSION)
|
|
232
|
+
fail(`its hello says protocol ${hello.protocol}, not ${PROTOCOL_VERSION}`);
|
|
233
|
+
if (hello.kind !== paired.hello.kind || hello.os !== paired.hello.os)
|
|
234
|
+
fail(`it paired as ${paired.hello.os} ${paired.hello.kind} and its hello says ${hello.os} ${hello.kind}`);
|
|
235
|
+
if (!Array.isArray(hello.groups) || hello.groups.length === 0)
|
|
236
|
+
fail("its hello offers no groups");
|
|
237
|
+
return `paired and attached as ${hello.os} ${hello.kind} (driver ${hello.version}), offering ${hello.groups.join(", ")}`;
|
|
238
|
+
});
|
|
239
|
+
await run("wrong-or-used-code", async () => {
|
|
240
|
+
const tries = [{ what: "a wrong code", code: "ZZZZ-ZZZZ" }, { what: "the used code", code: pairing.code }];
|
|
241
|
+
for (const { what, code } of tries) {
|
|
242
|
+
const res = await fetch(`${address}/v2/computers/pair`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code, name: "another", hello: paired?.hello ?? {} }) });
|
|
243
|
+
if (res.status !== 404)
|
|
244
|
+
fail(`${what} answered ${res.status}, not 404`);
|
|
245
|
+
}
|
|
246
|
+
return "a wrong code and a used code are each refused 404, with nothing said of which";
|
|
247
|
+
});
|
|
248
|
+
await run("ping", async () => {
|
|
249
|
+
const dial = live() ?? fail("no live socket");
|
|
250
|
+
const pong = new Promise((done) => dial.ws.once("pong", () => done()));
|
|
251
|
+
dial.ws.ping();
|
|
252
|
+
await Promise.race([pong, new Promise((_, reject) => setTimeout(() => reject(new Failed("it did not answer a ping")), ms(5_000) + 1_000))]);
|
|
253
|
+
const before = dial.pings;
|
|
254
|
+
await until(() => dial.pings > before || dial.closed !== undefined, ms(ATTACH_HEARTBEAT_MS + 5_000) + 1_000, `it sent no ping of its own in ${ATTACH_HEARTBEAT_MS / 1000} s`);
|
|
255
|
+
if (dial.closed)
|
|
256
|
+
fail(`its socket closed (${dial.closed.code}) while waiting for its ping`);
|
|
257
|
+
return "it answers a ping, and pings every heartbeat itself";
|
|
258
|
+
});
|
|
259
|
+
await run("quiet", async () => {
|
|
260
|
+
const dial = live() ?? fail("no live socket");
|
|
261
|
+
await never(() => dial.closed !== undefined, ms(ATTACH_IDLE_MS + 10_000), () => `its socket closed with ${dial.closed?.code} during a quiet spell`);
|
|
262
|
+
return `with no calls for ${seconds(ms(ATTACH_IDLE_MS + 10_000))} s its socket stays up: its pongs and pings keep it`;
|
|
263
|
+
});
|
|
264
|
+
await run("redial-after-close", async () => {
|
|
265
|
+
const codes = [ATTACH_CLOSE.idle, ATTACH_CLOSE.normal, ATTACH_CLOSE.going, ATTACH_CLOSE.replaced];
|
|
266
|
+
for (const code of codes) {
|
|
267
|
+
const dial = live() ?? fail("no live socket");
|
|
268
|
+
const before = dials.length;
|
|
269
|
+
closeOurs(dial, code, `conformance: a close with ${code}`);
|
|
270
|
+
await redialed(before, `it did not dial back after a close with ${code}`);
|
|
271
|
+
}
|
|
272
|
+
return `it dials back after a close with ${codes.join(", ")}`;
|
|
273
|
+
});
|
|
274
|
+
await run("redial-after-drop", async () => {
|
|
275
|
+
const dial = live() ?? fail("no live socket");
|
|
276
|
+
const before = dials.length;
|
|
277
|
+
ourCloses.add(dial.ws);
|
|
278
|
+
dial.ws.terminate();
|
|
279
|
+
await redialed(before, "it did not dial back after a drop with no close frame");
|
|
280
|
+
return "it dials back after a drop";
|
|
281
|
+
});
|
|
282
|
+
for (const [name, frame, code] of [["binary-frame", Buffer.from([0x7b, 0x7d]), ATTACH_CLOSE.binary], ["oversize-frame", "x".repeat(MAX_LINE_BYTES + 1), ATTACH_CLOSE.tooBig]]) {
|
|
283
|
+
await run(name, async () => {
|
|
284
|
+
const dial = live() ?? fail("no live socket");
|
|
285
|
+
const before = dials.length;
|
|
286
|
+
dial.ws.send(frame, { binary: typeof frame !== "string" });
|
|
287
|
+
await until(() => dial.closed, ms(5_000) + 2_000, `it did not close its socket on ${name === "binary-frame" ? "a binary frame" : "a frame over the limit"}`);
|
|
288
|
+
if (dial.closed.code !== code)
|
|
289
|
+
fail(`it closed with ${dial.closed.code}, not ${code}`);
|
|
290
|
+
await redialed(before, `it did not dial back after closing with ${code}`);
|
|
291
|
+
return `it closes with ${code}, then dials back`;
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
await run("same-token", async () => {
|
|
295
|
+
const dial = live() ?? fail("no live socket");
|
|
296
|
+
const hello = dial.hello;
|
|
297
|
+
const before = dials.length;
|
|
298
|
+
// This run dials as a second driver with the same token and answers hello as the driver did.
|
|
299
|
+
const twin = new WebSocket(`${address.replace(/^http/, "ws")}${ATTACH_PATH}`, ATTACH_SUBPROTOCOL, { headers: { authorization: `Bearer ${paired.token}` } });
|
|
300
|
+
twin.on("error", () => undefined);
|
|
301
|
+
let twinClosed;
|
|
302
|
+
twin.on("close", (code) => void ((twinClosed = code), changed()));
|
|
303
|
+
twin.on("message", (data) => {
|
|
304
|
+
const message = JSON.parse(String(data));
|
|
305
|
+
if (message.method === "hello" && message.id !== undefined)
|
|
306
|
+
twin.send(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: hello }));
|
|
307
|
+
});
|
|
308
|
+
await until(() => dial.closed, redialWithin, "the driver's socket was not closed when a second socket with its token went live");
|
|
309
|
+
if (dial.closed.code !== ATTACH_CLOSE.replaced)
|
|
310
|
+
fail(`the driver's socket closed with ${dial.closed.code}, not ${ATTACH_CLOSE.replaced}`);
|
|
311
|
+
// The driver dials back (4409 is redialed) and its new socket replaces the twin's.
|
|
312
|
+
await until(() => dials.slice(before + 1).find((one) => one.hello && one.closed === undefined), redialWithin, "the driver did not dial back after 4409");
|
|
313
|
+
await until(() => twinClosed, ms(5_000) + 2_000, "the second socket was not closed when the driver dialed back");
|
|
314
|
+
if (twinClosed !== ATTACH_CLOSE.replaced)
|
|
315
|
+
fail(`the second socket closed with ${twinClosed}, not ${ATTACH_CLOSE.replaced}`);
|
|
316
|
+
return "a second socket with its token closes its socket with 4409; it dials back, and its new socket replaces the second";
|
|
317
|
+
});
|
|
318
|
+
await run("revoke", async () => {
|
|
319
|
+
const dial = live() ?? fail("no live socket");
|
|
320
|
+
await routes.remove(paired.computer);
|
|
321
|
+
await until(() => dial.closed, ms(5_000) + 2_000, "its socket was not closed when it was removed");
|
|
322
|
+
if (dial.closed.code !== ATTACH_CLOSE.unauthorized)
|
|
323
|
+
fail(`its socket closed with ${dial.closed.code}, not ${ATTACH_CLOSE.unauthorized}`);
|
|
324
|
+
const before = attempts;
|
|
325
|
+
// As long as a redial may wait: a driver that wrongly dials after 4401 does so within it, however far the cases
|
|
326
|
+
// before this one drove its delay.
|
|
327
|
+
const quiet = redialWithin;
|
|
328
|
+
await never(() => attempts > before, quiet, () => "it dialed again after 4401, which needs the person to pair it again");
|
|
329
|
+
return `removed, its socket closes with 4401 and it does not dial again in ${seconds(quiet)} s`;
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
finally {
|
|
333
|
+
await routes.close();
|
|
334
|
+
// closeAllConnections right after close starts: a pairing request left unfinished would hold the close callback.
|
|
335
|
+
await new Promise((done) => {
|
|
336
|
+
server.close(() => done());
|
|
337
|
+
server.closeAllConnections();
|
|
338
|
+
});
|
|
339
|
+
await store.close();
|
|
340
|
+
rmSync(dir, { recursive: true, force: true });
|
|
341
|
+
}
|
|
342
|
+
return results;
|
|
343
|
+
}
|
package/dist/browser-cost.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Context } from "@earendil-works/chord";
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
2
|
import type { Refusal } from "@parcha/agentrun-kernel";
|
|
3
3
|
import { type Harness, type Conversation, type Session, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
|
|
4
4
|
import type { SessionCharge } from "@parcha/pi-browser";
|
package/dist/browser-live.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
2
|
import type { Duplex } from "node:stream";
|
|
3
|
+
import { type LiveReach } from "./live-reach.js";
|
|
3
4
|
import type { Claim, Store, ViewerKind } from "./store/store.js";
|
|
4
5
|
/** What the run's process hands the server for one session's viewer; `at`, when (the newest is the one shown). `kind`, the
|
|
5
6
|
* computer it views, as the store's row says it. */
|
|
@@ -10,10 +11,11 @@ export type LiveHandover = {
|
|
|
10
11
|
tag: string;
|
|
11
12
|
at?: number;
|
|
12
13
|
kind?: ViewerKind;
|
|
14
|
+
host?: string;
|
|
13
15
|
};
|
|
14
16
|
/** The viewer `fullscreen` URL pi-browser's live view gives (an http URL on the loopback address, /v/<id>#t=<token>) for session `tag`, as
|
|
15
17
|
* a hand-over; undefined for any other shape (a vendor's own URL never is one). */
|
|
16
|
-
export declare function handoverOf(fullscreen: string, tag: string): LiveHandover | undefined;
|
|
18
|
+
export declare function handoverOf(fullscreen: string, tag: string, liveHost?: string): LiveHandover | undefined;
|
|
17
19
|
/** The store's live viewers (store.liveViewers: put and drop under the runner's claim, of() for the server) carry the
|
|
18
20
|
* hand-over across processes, once serve and the runner share only the store. The token is never plaintext there: the
|
|
19
21
|
* runner seals it under the seal key it holds, and the server opens it for the owner's answer alone. */
|
|
@@ -41,8 +43,14 @@ export declare const familyReaches: (family: LiveFamily, handover: LiveHandover)
|
|
|
41
43
|
* the fragment. */
|
|
42
44
|
export declare const viewerLink: (runId: string, handover: LiveHandover, family?: LiveFamily) => string;
|
|
43
45
|
/** The run's viewer answers at its port for this session: its page is there (200), not released (404). Bounded: a dead
|
|
44
|
-
* process's port answers nothing, or another listener's 404.
|
|
45
|
-
|
|
46
|
+
* process's port answers nothing, or another listener's 404. A viewer on a runner on another host (its row's host) is
|
|
47
|
+
* asked only when `reach` counts that host among this server's runners', with the proxy's proof; else it does not
|
|
48
|
+
* answer, and nothing is dialled (live-reach.ts). */
|
|
49
|
+
export declare function viewerAnswers(handover: LiveHandover, reach?: LiveReach, ms?: number): Promise<boolean>;
|
|
50
|
+
/** The newest viewer of run `runId` its runner put over the store whose port answers (`answers`, viewerAnswers), among the
|
|
51
|
+
* kinds `family`'s address reaches (familyReaches: every kind under the computer family, a browser's alone under the
|
|
52
|
+
* browser's); undefined when none does. */
|
|
53
|
+
export declare function answeringViewer(store: LiveViewerStore, sealKey: Buffer, runId: string, answers: (handover: LiveHandover) => Promise<boolean>, family?: LiveFamily): Promise<LiveHandover | undefined>;
|
|
46
54
|
/** The owner's link to run `runId`'s viewer as the server reads it over the store, under the browser's own address
|
|
47
55
|
* (/browser/live): the newest its runner put whose port answers (`answers`, viewerAnswers), as `{ viewer }`; undefined
|
|
48
56
|
* when none does. What run-reads-over-store's runBrowserState takes as its `liveViewer` dep. */
|
|
@@ -65,8 +73,8 @@ export type ViewerSeam = {
|
|
|
65
73
|
* else: with no seam no viewer is handed over, and nothing is written (never a file in the run's folder, the agent's
|
|
66
74
|
* workspace). `changed`: a session launched (its viewer put) or released (its own hand-over dropped, never another's);
|
|
67
75
|
* `reopened`: a kept session's viewer opened again after a restart; `released`: the run let its sessions go, every
|
|
68
|
-
* hand-over of it dropped. */
|
|
69
|
-
export declare function sessionHandovers(seam: ViewerSeam | undefined): {
|
|
76
|
+
* hand-over of it dropped. `liveHost`: the runner's live host, when it is on another host than its server. */
|
|
77
|
+
export declare function sessionHandovers(seam: ViewerSeam | undefined, liveHost?: string): {
|
|
70
78
|
changed: (row: {
|
|
71
79
|
session: {
|
|
72
80
|
tag: string;
|
|
@@ -87,7 +95,9 @@ export declare const liveRest: (rest: string) => boolean;
|
|
|
87
95
|
* id, the viewer's files while the run has one open (its newest); undefined at any other address, or with none open (the
|
|
88
96
|
* route's 404). The WebSocket's upgrade reads liveViewerById with the id in its path. */
|
|
89
97
|
export declare function liveViewerFor(store: LiveViewerStore, sealKey: Buffer, runId: string, rest: string): Promise<LiveHandover | undefined>;
|
|
90
|
-
|
|
98
|
+
/** `page`: whose page a viewer's path ("/v/<id>") serves, the browser's (pi-browser's viewer) or a desktop's or phone's
|
|
99
|
+
* (computer-viewer.ts); each page's two files are under names of their own. */
|
|
100
|
+
export declare function serveViewerFile(req: IncomingMessage, res: ServerResponse, rest: string, page?: "browser" | "computer"): Promise<void>;
|
|
91
101
|
/** How often an open viewer's session is checked again. A reset-password run in another process and a cookie past its end
|
|
92
102
|
* are seen by no call in this one, so a viewer they end closes within this. */
|
|
93
103
|
export declare const LIVE_RECHECK_MS = 2000;
|
|
@@ -107,5 +117,7 @@ export declare class OpenViewers {
|
|
|
107
117
|
/** The viewer's WebSocket to the run's port: the request line and the handshake's own headers, the Host and Origin the
|
|
108
118
|
* run's viewer takes (its own), and nothing else of the owner's (no cookie); then both ways, unread. */
|
|
109
119
|
/** Once piping starts, the viewer's socket carries the run's WebSocket stream: nothing is ever written into it after that,
|
|
110
|
-
* an error only ends it. `onPiping` hears when that starts (the server's own failure handling then destroys, never writes).
|
|
111
|
-
|
|
120
|
+
* an error only ends it. `onPiping` hears when that starts (the server's own failure handling then destroys, never writes).
|
|
121
|
+
* A viewer on a runner on another host is dialled only when `reach` counts that host among this server's runners', with
|
|
122
|
+
* the proxy's proof; else the answer is 404 and nothing is dialled (live-reach.ts). */
|
|
123
|
+
export declare function proxyLiveUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer, handover: LiveHandover, rest: string, onPiping?: () => void, reach?: LiveReach): void;
|
package/dist/browser-live.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
// context, a home, an export or an archive: only its sealed row and the owner's answer hold it.
|
|
17
17
|
import { request as httpRequest } from "node:http";
|
|
18
18
|
import { connect } from "node:net";
|
|
19
|
+
import { dialHost, isLiveHost, LIVE_PROOF_HEADER, liveProof } from "./live-reach.js";
|
|
19
20
|
import { sealColumn, sealedAt, unsealColumn } from "./store/seal.js";
|
|
20
21
|
/** The computer kinds a store row may name. */
|
|
21
22
|
const VIEWER_KINDS = ["browser", "desktop", "phone"];
|
|
@@ -27,7 +28,7 @@ const TOKEN = /^[A-Za-z0-9_-]{43}$/;
|
|
|
27
28
|
const TAG = /^[A-Za-z0-9._:-]{1,200}$/;
|
|
28
29
|
/** The viewer `fullscreen` URL pi-browser's live view gives (an http URL on the loopback address, /v/<id>#t=<token>) for session `tag`, as
|
|
29
30
|
* a hand-over; undefined for any other shape (a vendor's own URL never is one). */
|
|
30
|
-
export function handoverOf(fullscreen, tag) {
|
|
31
|
+
export function handoverOf(fullscreen, tag, liveHost) {
|
|
31
32
|
let url;
|
|
32
33
|
try {
|
|
33
34
|
url = new URL(fullscreen);
|
|
@@ -38,19 +39,21 @@ export function handoverOf(fullscreen, tag) {
|
|
|
38
39
|
const id = /^\/v\/([^/]+)$/.exec(url.pathname)?.[1];
|
|
39
40
|
const token = new URLSearchParams(url.hash.slice(1)).get("t") ?? "";
|
|
40
41
|
const port = Number(url.port);
|
|
41
|
-
|
|
42
|
+
// Loopback, or the runner's own live host when it is on another host than its server (live-reach.ts): no other.
|
|
43
|
+
const remote = liveHost !== undefined && url.hostname === liveHost;
|
|
44
|
+
if (url.protocol !== "http:" || (url.hostname !== LOOPBACK && !remote) || !Number.isInteger(port) || port < 1 || port > 65_535 || !id || !VIEWER_ID.test(id) || !TOKEN.test(token) || !TAG.test(tag))
|
|
42
45
|
return undefined;
|
|
43
|
-
return { port, id, token, tag };
|
|
46
|
+
return { port, id, token, tag, ...(remote ? { host: liveHost } : {}) };
|
|
44
47
|
}
|
|
45
48
|
/** The runner hands session `handover.tag`'s viewer over, under `claim`, its token sealed under `sealKey`: false when the
|
|
46
49
|
* claim is stale and nothing was written. The time is the store's. */
|
|
47
50
|
export async function putLiveViewer(store, sealKey, claim, handover) {
|
|
48
51
|
if (!TAG.test(handover.tag))
|
|
49
52
|
throw new Error("a hand-over's tag is not a session's tag");
|
|
50
|
-
const { tag, port, id, token } = handover;
|
|
53
|
+
const { tag, port, id, token, host } = handover;
|
|
51
54
|
// Every viewer this file hands over is the browser kind: pi-browser's own viewer. Other computer kinds (desktop, phone)
|
|
52
55
|
// get their own hand-over; the store's viewer table carries the kind so the kinds never collide on a shared tag.
|
|
53
|
-
return store.liveViewers.put(claim, { kind: "browser", tag, port, id, sealed: sealColumn(sealKey, sealedAt.liveViewer(claim.runId, "browser", tag), token) });
|
|
56
|
+
return store.liveViewers.put(claim, { kind: "browser", tag, ...(host !== undefined ? { host } : {}), port, id, sealed: sealColumn(sealKey, sealedAt.liveViewer(claim.runId, "browser", tag), token) });
|
|
54
57
|
}
|
|
55
58
|
/** Session `tag`'s hand-over goes, and no other's; with no tag, every one of the run's (its runner let its sessions go). A
|
|
56
59
|
* tag that is not a session's names no row. */
|
|
@@ -65,6 +68,9 @@ export async function dropLiveViewer(store, claim, tag) {
|
|
|
65
68
|
function handoverOfRow(sealKey, runId, row) {
|
|
66
69
|
if (!(typeof row.kind === "string" && VIEWER_KINDS.includes(row.kind) && Number.isInteger(row.port) && row.port > 0 && row.port < 65_536 && VIEWER_ID.test(String(row.id)) && typeof row.tag === "string" && TAG.test(row.tag) && Number.isFinite(row.at) && row.sealed instanceof Uint8Array))
|
|
67
70
|
return undefined;
|
|
71
|
+
// A host that is no host name or address names no viewer.
|
|
72
|
+
if (row.host !== undefined && !isLiveHost(row.host))
|
|
73
|
+
return undefined;
|
|
68
74
|
let token;
|
|
69
75
|
try {
|
|
70
76
|
token = unsealColumn(sealKey, sealedAt.liveViewer(runId, row.kind, row.tag), row.sealed).toString("utf8");
|
|
@@ -72,7 +78,7 @@ function handoverOfRow(sealKey, runId, row) {
|
|
|
72
78
|
catch {
|
|
73
79
|
return undefined;
|
|
74
80
|
}
|
|
75
|
-
return TOKEN.test(token) ? { kind: row.kind, port: row.port, id: row.id, token, tag: row.tag, at: row.at } : undefined;
|
|
81
|
+
return TOKEN.test(token) ? { kind: row.kind, port: row.port, id: row.id, token, tag: row.tag, at: row.at, ...(row.host !== undefined ? { host: row.host } : {}) } : undefined;
|
|
76
82
|
}
|
|
77
83
|
/** Run `runId`'s viewers, of every computer kind, as its live claim handed them over, newest first, each with its kind and
|
|
78
84
|
* its token opened with `sealKey` under that kind; a row that is not a hand-over is left out. */
|
|
@@ -92,10 +98,16 @@ export const familyReaches = (family, handover) => family === "computer" || (han
|
|
|
92
98
|
* the fragment. */
|
|
93
99
|
export const viewerLink = (runId, handover, family = "browser") => `/v2/runs/${encodeURIComponent(runId)}/${family}/live/v/${handover.id}#t=${handover.token}`;
|
|
94
100
|
/** The run's viewer answers at its port for this session: its page is there (200), not released (404). Bounded: a dead
|
|
95
|
-
* process's port answers nothing, or another listener's 404.
|
|
96
|
-
|
|
101
|
+
* process's port answers nothing, or another listener's 404. A viewer on a runner on another host (its row's host) is
|
|
102
|
+
* asked only when `reach` counts that host among this server's runners', with the proxy's proof; else it does not
|
|
103
|
+
* answer, and nothing is dialled (live-reach.ts). */
|
|
104
|
+
export function viewerAnswers(handover, reach, ms = 1_000) {
|
|
105
|
+
const host = dialHost(handover.host, reach);
|
|
106
|
+
if (host === undefined)
|
|
107
|
+
return Promise.resolve(false);
|
|
97
108
|
return new Promise((resolve) => {
|
|
98
|
-
const
|
|
109
|
+
const headers = reach ? { [LIVE_PROOF_HEADER]: liveProof(reach, handover.id) } : {};
|
|
110
|
+
const req = httpRequest({ host, port: handover.port, method: "HEAD", path: `/v/${handover.id}`, timeout: ms, headers }, (res) => {
|
|
99
111
|
res.resume();
|
|
100
112
|
resolve(res.statusCode === 200);
|
|
101
113
|
});
|
|
@@ -104,11 +116,12 @@ export function viewerAnswers(handover, ms = 1_000) {
|
|
|
104
116
|
req.end();
|
|
105
117
|
});
|
|
106
118
|
}
|
|
107
|
-
/** The newest viewer of run `runId` its runner put over the store whose port answers (`answers`, viewerAnswers),
|
|
108
|
-
*
|
|
109
|
-
|
|
119
|
+
/** The newest viewer of run `runId` its runner put over the store whose port answers (`answers`, viewerAnswers), among the
|
|
120
|
+
* kinds `family`'s address reaches (familyReaches: every kind under the computer family, a browser's alone under the
|
|
121
|
+
* browser's); undefined when none does. */
|
|
122
|
+
export async function answeringViewer(store, sealKey, runId, answers, family = "computer") {
|
|
110
123
|
for (const handover of await readLiveViewers(store, sealKey, runId))
|
|
111
|
-
if (await answers(handover))
|
|
124
|
+
if (familyReaches(family, handover) && (await answers(handover)))
|
|
112
125
|
return handover;
|
|
113
126
|
return undefined;
|
|
114
127
|
}
|
|
@@ -116,7 +129,7 @@ async function answeringViewer(store, sealKey, runId, answers) {
|
|
|
116
129
|
* (/browser/live): the newest its runner put whose port answers (`answers`, viewerAnswers), as `{ viewer }`; undefined
|
|
117
130
|
* when none does. What run-reads-over-store's runBrowserState takes as its `liveViewer` dep. */
|
|
118
131
|
export async function liveViewerLink(store, sealKey, runId, answers = viewerAnswers) {
|
|
119
|
-
const handover = await answeringViewer(store, sealKey, runId, answers);
|
|
132
|
+
const handover = await answeringViewer(store, sealKey, runId, answers, "browser");
|
|
120
133
|
return handover && { viewer: viewerLink(runId, handover, "browser") };
|
|
121
134
|
}
|
|
122
135
|
/** The same viewer for GET /computer: its link under the computer family's address (/computer/live), with its computer's
|
|
@@ -129,20 +142,20 @@ export async function computerViewerLink(store, sealKey, runId, answers = viewer
|
|
|
129
142
|
* else: with no seam no viewer is handed over, and nothing is written (never a file in the run's folder, the agent's
|
|
130
143
|
* workspace). `changed`: a session launched (its viewer put) or released (its own hand-over dropped, never another's);
|
|
131
144
|
* `reopened`: a kept session's viewer opened again after a restart; `released`: the run let its sessions go, every
|
|
132
|
-
* hand-over of it dropped. */
|
|
133
|
-
export function sessionHandovers(seam) {
|
|
145
|
+
* hand-over of it dropped. `liveHost`: the runner's live host, when it is on another host than its server. */
|
|
146
|
+
export function sessionHandovers(seam, liveHost) {
|
|
134
147
|
const put = async (handover) => seam?.put(handover);
|
|
135
148
|
const drop = async (tag) => seam?.drop(tag);
|
|
136
149
|
return {
|
|
137
150
|
changed: async (row, change) => {
|
|
138
151
|
if (change === "released")
|
|
139
152
|
return drop(row.session.tag);
|
|
140
|
-
const handover = row.liveView ? handoverOf(row.liveView.fullscreen, row.session.tag) : undefined;
|
|
153
|
+
const handover = row.liveView ? handoverOf(row.liveView.fullscreen, row.session.tag, liveHost) : undefined;
|
|
141
154
|
if (handover)
|
|
142
155
|
await put(handover);
|
|
143
156
|
},
|
|
144
157
|
reopened: async (tag, fullscreen) => {
|
|
145
|
-
const handover = fullscreen ? handoverOf(fullscreen, tag) : undefined;
|
|
158
|
+
const handover = fullscreen ? handoverOf(fullscreen, tag, liveHost) : undefined;
|
|
146
159
|
if (handover)
|
|
147
160
|
await put(handover);
|
|
148
161
|
},
|
|
@@ -153,7 +166,7 @@ export function sessionHandovers(seam) {
|
|
|
153
166
|
* pi-browser's viewer, never the run's port's answer, under this route's own CSP, framed by this server's own origin alone.
|
|
154
167
|
* The page reads the viewer's id from its path and its token from the fragment, as pi-browser's own does. */
|
|
155
168
|
export const LIVE_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'";
|
|
156
|
-
const LIVE_REST = /^\/(v\/[A-Za-z0-9_-]{22}|viewer\.js|viewer\.css)$/;
|
|
169
|
+
const LIVE_REST = /^\/(v\/[A-Za-z0-9_-]{22}|viewer\.js|viewer\.css|computer-viewer\.js|computer-viewer\.css)$/;
|
|
157
170
|
export const liveRest = (rest) => LIVE_REST.test(rest);
|
|
158
171
|
/** The viewer run `runId`'s live route serves at `rest`, read over the store: a viewer's page ("/v/<id>") by its own path
|
|
159
172
|
* id, the viewer's files while the run has one open (its newest); undefined at any other address, or with none open (the
|
|
@@ -164,9 +177,13 @@ export async function liveViewerFor(store, sealKey, runId, rest) {
|
|
|
164
177
|
const viewer = /^\/v\/([A-Za-z0-9_-]{22})$/.exec(rest)?.[1];
|
|
165
178
|
return viewer ? liveViewerById(store, sealKey, runId, viewer) : liveViewer(store, sealKey, runId);
|
|
166
179
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
180
|
+
/** `page`: whose page a viewer's path ("/v/<id>") serves, the browser's (pi-browser's viewer) or a desktop's or phone's
|
|
181
|
+
* (computer-viewer.ts); each page's two files are under names of their own. */
|
|
182
|
+
export async function serveViewerFile(req, res, rest, page = "browser") {
|
|
183
|
+
const { viewerAssets: browser } = await import("@parcha/pi-browser/live-view");
|
|
184
|
+
const { computerViewerAssets: computer } = await import("./computer-viewer.js");
|
|
185
|
+
const assets = rest.startsWith("/computer-viewer.") || (rest.startsWith("/v/") && page === "computer") ? computer : browser;
|
|
186
|
+
const [type, body] = rest.endsWith(".js") ? ["text/javascript; charset=utf-8", assets.js] : rest.endsWith(".css") ? ["text/css; charset=utf-8", assets.css] : ["text/html; charset=utf-8", assets.html];
|
|
170
187
|
res.writeHead(200, { "content-type": type, "content-length": Buffer.byteLength(body), "content-security-policy": LIVE_CSP, "referrer-policy": "no-referrer", "cache-control": "no-store", "x-content-type-options": "nosniff" });
|
|
171
188
|
res.end(req.method === "HEAD" ? undefined : body);
|
|
172
189
|
}
|
|
@@ -207,21 +224,27 @@ export class OpenViewers {
|
|
|
207
224
|
/** The viewer's WebSocket to the run's port: the request line and the handshake's own headers, the Host and Origin the
|
|
208
225
|
* run's viewer takes (its own), and nothing else of the owner's (no cookie); then both ways, unread. */
|
|
209
226
|
/** Once piping starts, the viewer's socket carries the run's WebSocket stream: nothing is ever written into it after that,
|
|
210
|
-
* an error only ends it. `onPiping` hears when that starts (the server's own failure handling then destroys, never writes).
|
|
211
|
-
|
|
227
|
+
* an error only ends it. `onPiping` hears when that starts (the server's own failure handling then destroys, never writes).
|
|
228
|
+
* A viewer on a runner on another host is dialled only when `reach` counts that host among this server's runners', with
|
|
229
|
+
* the proxy's proof; else the answer is 404 and nothing is dialled (live-reach.ts). */
|
|
230
|
+
export function proxyLiveUpgrade(req, socket, head, handover, rest, onPiping, reach) {
|
|
212
231
|
const key = String(req.headers["sec-websocket-key"] ?? "");
|
|
213
232
|
const version = String(req.headers["sec-websocket-version"] ?? "");
|
|
214
233
|
if (!/^[A-Za-z0-9+/]{22}==$/.test(key) || version !== "13")
|
|
215
234
|
return void socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
216
|
-
const
|
|
235
|
+
const host = dialHost(handover.host, reach);
|
|
236
|
+
if (host === undefined)
|
|
237
|
+
return void socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
|
|
238
|
+
const proof = reach ? `${LIVE_PROOF_HEADER}: ${liveProof(reach, handover.id)}\r\n` : "";
|
|
239
|
+
const upstream = connect({ host, port: handover.port });
|
|
217
240
|
let piping = false;
|
|
218
241
|
const end = () => {
|
|
219
242
|
socket.destroy();
|
|
220
243
|
upstream.destroy();
|
|
221
244
|
};
|
|
222
245
|
upstream.once("connect", () => {
|
|
223
|
-
const own = `${
|
|
224
|
-
upstream.write(`GET ${rest} HTTP/1.1\r\nHost: ${own}\r\nOrigin: http://${own}\r\
|
|
246
|
+
const own = `${host}:${handover.port}`;
|
|
247
|
+
upstream.write(`GET ${rest} HTTP/1.1\r\nHost: ${own}\r\nOrigin: http://${own}\r\n${proof}Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`);
|
|
225
248
|
if (head.length)
|
|
226
249
|
upstream.write(head);
|
|
227
250
|
piping = true;
|
package/dist/cap.d.ts
CHANGED
|
@@ -201,23 +201,6 @@ export declare const costOf: (entry: EntryLike) => number;
|
|
|
201
201
|
* figure its start mark holds (openFigures), each the worst case the cap held for it; without that figure either stays
|
|
202
202
|
* cut, at an unknown cost. This cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. */
|
|
203
203
|
export declare function spentFrom(rows: readonly EntryLike[]): number | null;
|
|
204
|
-
/** A workflow decision's charge as the cap counted it (decision-cap.ts): `call` names the request, `usd` what it charged,
|
|
205
|
-
* or its hold when it said none. The run's shown cost reads its decisions from their receipts; this is the cap's own
|
|
206
|
-
* reading, kept so a later process counts each decision as this one did. costOf counts none, so nothing counts twice. */
|
|
207
|
-
export declare const DECISION_COST = "agentrun.decision_cost";
|
|
208
|
-
/** A decision request's hold, kept before it is sent (decision-cap.ts): with no DECISION_COST after it, its process died
|
|
209
|
-
* while it was out, and it counts at this figure. */
|
|
210
|
-
export declare const DECISION_HOLD = "agentrun.decision_hold";
|
|
211
|
-
/** What a workflow run's decisions cost, in its store: what the next process adds to spentFrom's reading. Per decision
|
|
212
|
-
* (its id):
|
|
213
|
-
* - booked (DECISION_COST entries, at its charge, its hold, or $0 for nothing charged): the larger of what was booked,
|
|
214
|
-
* with any hold no booking ended, and what its receipts say it cost (the costs the timeline's decision rows sum);
|
|
215
|
-
* - else, with a receipt that names its charge: that charge (its booking lost after the receipt);
|
|
216
|
-
* - else, with a hold (DECISION_HOLD, kept once the driver admitted the request, right before its send): that hold, the
|
|
217
|
-
* figure the live process held, since the request may have been out when its process died; never $0;
|
|
218
|
-
* - else nothing: no hold is kept before the admission, so a request never sent is never counted.
|
|
219
|
-
* A booking with no decision id is counted as it is. */
|
|
220
|
-
export declare function decisionSpentIn(storeFile: string): number;
|
|
221
204
|
/** /usage's meters for a run that ended, from its store: `tools`, each TOOL_COST's `usd`, unknown (null) when one is,
|
|
222
205
|
* or when a call was cut (marked, never settled: what it charged no one knows); and `tokens`, the rest of its root
|
|
223
206
|
* conversation as its settled timeline prices it; `browser`, the part of `tools` that is browser session time
|