Repository navigation
Expand file tree
/
Copy pathhosted-sandbox.ts
More file actions
205 lines (190 loc) · 9.18 KB
/
Copy pathhosted-sandbox.ts
File metadata and controls
205 lines (190 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
* The keyless hosted demo: one process that runs the whole system on a real
* local NEAR chain and resets itself every hour.
*
* pnpm hosted # API on :8080 (INDEXER_PORT), worker admin on loopback
* HOSTED_RESET_MINUTES=60 HOSTED_SEED=1 pnpm hosted
*
* Each cycle:
* 1. boots a fresh NEAR sandbox, deploys the council DAO + contract, seeds
* the cast (same code as `pnpm demo`);
* 2. runs the seven scenarios so the site opens with history: a slash, a
* rejected claim, an appeal, a market (HOSTED_SEED=0 skips this);
* 3. starts every service live, in-process, each signing as its own
* account: the worker (with the sabotage switch), the arbiter, the
* keeper, three underwriter personas — plus the indexer API as a child;
* 4. after HOSTED_RESET_MINUTES, stops it all and starts again.
*
* Models: the seeded scenarios replay the genuine NEAR AI Cloud recordings
* (demo/fixtures/near-ai). New hires from the web UI are answered by the
* deterministic dev model (scripts/lib/dev-answer.ts), signed with the
* allow-listed sandbox key; those receipts say "dev-fixture" (no TEE), because
* a public keyless demo cannot spend a NEAR AI key. Every transaction is real
* on the local chain and every receipt is checked by the contract. The
* testnet deployment (docs/hosting.md) runs live NEAR AI Cloud.
*
* Run everything from the browser: the status of each scenario is written to
* .data/sandbox-run.json as it runs (GET /demo/run), and POST /demo/run asks
* this loop to start a fresh chain and replay all seven (the Demo page).
*
* Linux x64 / macOS arm64 (nearcore sandbox builds). Use Docker elsewhere.
*/
import { spawn, type ChildProcess } from "node:child_process";
import { randomBytes } from "node:crypto";
import { existsSync } from "node:fs";
import { SCENARIOS, setupNetwork, runScenarios, printReport } from "../demo/run-demo.js";
import { selectBackend } from "../packages/adapters/src/index.js";
import { RUN_REQUEST_FILE, RUN_STATUS_FILE, removeFile, writeJson, type RunStatus } from "../services/indexer/src/run-status.js";
import { DEV_MODEL } from "../demo/fixtures/plan.js";
import { adminServer, listenLocal } from "../services/worker-agent/src/admin.js";
import { KeeperService } from "../services/keeper/src/service.js";
import { SdkKeeperChain } from "../services/keeper/src/sdk-chain.js";
import { KeeperLogger } from "../services/keeper/src/logger.js";
import { Bidder } from "../services/underwriters/src/bidder.js";
import { PERSONAS, personaStrategy } from "../services/underwriters/src/personas.js";
import { JsonlRationaleSink, rationaleWriterFor } from "../services/underwriters/src/rationale.js";
import { SdkUnderwriterChain } from "../services/underwriters/src/sdk-chain.js";
import { MemoryBidStore } from "../services/underwriters/src/state.js";
import { devLiveBackend } from "./lib/dev-answer.js";
import { DATA_DIR } from "./lib/near.js";
import { cast } from "./lib/scenario.js";
import { artifactDir, services } from "./lib/services.js";
const RESET_MIN = Number(process.env.HOSTED_RESET_MINUTES ?? 60);
const SEED = process.env.HOSTED_SEED !== "0";
const TICK_MS = Number(process.env.HOSTED_TICK_MS ?? 2000);
const ADMIN_PORT = Number(process.env.WORKER_ADMIN_PORT ?? 8787);
function log(msg: string, fields: Record<string, unknown> = {}) {
console.log(JSON.stringify({ t: new Date().toISOString(), service: "hosted", msg, ...fields }));
}
async function cycle(n: number): Promise<void> {
log("cycle starting", { cycle: n, resetMinutes: RESET_MIN });
removeFile(RUN_REQUEST_FILE);
const status: RunStatus = {
cycle: n,
phase: "starting",
started_at: new Date().toISOString(),
finished_at: null,
reset_at: null,
model_source: selectBackend("sandbox").source,
scenarios: SEED ? SCENARIOS.map((x) => ({ id: x.id, name: x.name, expected: x.expected, state: "pending" as const })) : [],
passed: 0,
total: SEED ? SCENARIOS.length : 0,
solvency_ok: null,
};
const publish = () => writeJson(RUN_STATUS_FILE, status);
publish();
const net = await setupNetwork("sandbox", (s) => log(s));
const stops: (() => Promise<void> | void)[] = [net.stop];
let indexer: ChildProcess | undefined;
try {
const token = process.env.WORKER_ADMIN_TOKEN ?? randomBytes(32).toString("hex");
const rpcUrl = process.env.RECOURSE_RPC_URL!;
// Indexer API first (it configures itself from .data), so the site shows
// the scenarios' events as they happen. The sandbox keeps every block, so
// it could also catch up later; starting now just makes the page live.
indexer = spawn(process.execPath, ["--import", "tsx", "services/indexer/src/main.ts", "--mode", "sandbox"], {
stdio: "inherit",
env: { ...process.env, RECOURSE_RPC_URL: rpcUrl, WORKER_ADMIN_TOKEN: token, WORKER_ADMIN_PORT: String(ADMIN_PORT), INDEXER_HOST: process.env.INDEXER_HOST ?? "0.0.0.0", INDEXER_PORT: process.env.INDEXER_PORT ?? "8085" },
});
stops.push(() => {
indexer?.kill("SIGTERM");
});
if (SEED) {
status.phase = "seeding";
publish();
const report = await runScenarios(undefined, () => {}, {
onStart: (x) => {
const row = status.scenarios.find((r) => r.id === x.id);
if (row) row.state = "running";
publish();
},
onResult: (r) => {
const row = status.scenarios.find((x) => x.id === r.id);
if (row) Object.assign(row, { state: r.pass ? "pass" : "fail", actual: r.actual, txs: r.txs, ms: r.ms });
status.passed = status.scenarios.filter((x) => x.state === "pass").length;
publish();
},
});
printReport(report);
status.solvency_ok = report.solvencyOk;
log("seeded with the seven scenarios", { passed: report.passed, total: report.total, solvency: report.solvencyOk });
}
const c = cast();
// Worker + arbiter, live, on the dev model.
const s = services(c, artifactDir(), "none", devLiveBackend(DEV_MODEL), { worker: DEV_MODEL, arbiter: DEV_MODEL });
const admin = adminServer({ token, sabotage: s.sabotage, log: { log: (level, msg, f) => log(`worker ${level}: ${msg}`, f ?? {}) } });
await listenLocal(admin, ADMIN_PORT);
stops.push(() => new Promise<void>((r) => admin.close(() => r())));
// Keeper (Direct payouts on NEAR).
const keeper = new KeeperService(
{ mode: "sandbox", rpcUrl, contractId: c.contractId, keeperAccountId: c.accounts.keeper.accountId, keeperKey: c.accounts.keeper.privateKey, oneClickUrl: "", pollMs: TICK_MS, stateFile: `${DATA_DIR}/sandbox-keeper-state.json`, dryQuote: true, models: [], signerRegistrationIntervalMs: 3_600_000 },
new SdkKeeperChain({ rpcUrl, contractId: c.contractId, keeperAccountId: c.accounts.keeper.accountId, keeperKey: c.accounts.keeper.privateKey }),
null,
new KeeperLogger("keeper"),
);
await keeper.init();
// Three underwriter personas.
const sink = new JsonlRationaleSink(`${DATA_DIR}/sandbox-rationales.jsonl`);
const bidders = (
[
[PERSONAS.cautious, "underwriter"],
[PERSONAS.balanced, "underwriter2"],
[PERSONAS.aggressive, "underwriter3"],
] as const
).map(
([p, role]) =>
new Bidder({
chain: new SdkUnderwriterChain({ rpcUrl, contractId: c.contractId, accountId: c.accounts[role].accountId, key: c.accounts[role].privateKey }),
strategy: personaStrategy(p),
store: new MemoryBidStore(),
persona: p.name,
explain: rationaleWriterFor(p, {}),
publish: (r) => sink.publish(r),
}),
);
const until = Date.now() + RESET_MIN * 60_000;
status.phase = "live";
status.finished_at = new Date().toISOString();
status.reset_at = new Date(until).toISOString();
publish();
log("stack live", { contract: c.contractId, api: `http://${process.env.INDEXER_HOST ?? "0.0.0.0"}:${process.env.INDEXER_PORT ?? 8080}`, resetAt: new Date(Date.now() + RESET_MIN * 60_000).toISOString() });
while (Date.now() < until) {
if (existsSync(RUN_REQUEST_FILE)) {
log("fresh run requested from the web UI; resetting the chain");
status.phase = "resetting";
publish();
break;
}
for (const [name, tick] of [
["worker", () => s.worker.tick()],
["arbiter", () => s.arbiter.tick()],
["keeper", () => keeper.tick()],
...bidders.map((b, i) => [`underwriter-${i + 1}`, () => b.tick()] as const),
] as const) {
await (tick as () => Promise<unknown>)().catch((e: unknown) => log(`${name} tick failed`, { error: String(e).slice(0, 200) }));
}
await new Promise((r) => setTimeout(r, TICK_MS));
}
} finally {
for (const stop of stops.reverse()) await Promise.resolve(stop()).catch(() => {});
log("cycle stopped", { cycle: n });
}
}
async function main() {
let stopping = false;
const quit = () => {
stopping = true;
process.exit(0);
};
process.on("SIGINT", quit);
process.on("SIGTERM", quit);
for (let n = 1; !stopping; n++) {
try {
await cycle(n);
} catch (e) {
log("cycle failed; restarting in 10s", { error: e instanceof Error ? e.message : String(e) });
await new Promise((r) => setTimeout(r, 10_000));
}
}
}
void main();