@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30
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 +748 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +2190 -2
- package/dist/adapters.d.ts +234 -0
- package/dist/adapters.js +585 -0
- package/dist/agents.d.ts +130 -0
- package/dist/agents.js +308 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +384 -0
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +285 -0
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +45 -0
- package/dist/box-relay.js +227 -0
- package/dist/boxes.d.ts +72 -0
- package/dist/boxes.js +189 -0
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +332 -0
- package/dist/cap.js +992 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +35 -0
- package/dist/coding-tools.js +87 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +19 -0
- package/dist/decision-rows.js +123 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +74 -0
- package/dist/errors.js +69 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +65 -0
- package/dist/files.js +158 -0
- package/dist/grade.d.ts +93 -0
- package/dist/grade.js +328 -0
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +102 -0
- package/dist/graph-view.js +219 -0
- package/dist/harness-app.d.ts +40 -0
- package/dist/harness-app.js +708 -0
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +56 -0
- package/dist/harness.js +77 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +30 -0
- package/dist/host-tools.js +154 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +85 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +133 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1222 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +37 -0
- package/dist/key-check.js +112 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +191 -0
- package/dist/learn/check.d.ts +108 -0
- package/dist/learn/check.js +277 -0
- package/dist/learn/grade.d.ts +80 -0
- package/dist/learn/grade.js +445 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +147 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +213 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +131 -0
- package/dist/learn/skills.d.ts +97 -0
- package/dist/learn/skills.js +271 -0
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +306 -0
- package/dist/learning-run.js +819 -0
- package/dist/learning-words.d.ts +76 -0
- package/dist/learning-words.js +174 -0
- package/dist/learning.d.ts +418 -0
- package/dist/learning.js +946 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +118 -0
- package/dist/mcp-servers.js +450 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +186 -0
- package/dist/model.js +485 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4806 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1727 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +50 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +70 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +69 -0
- package/dist/place.js +137 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +40 -0
- package/dist/propose.js +112 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +22 -0
- package/dist/request-start.js +350 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +186 -0
- package/dist/run-box.js +590 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +83 -0
- package/dist/runnable.js +170 -0
- package/dist/runs.d.ts +1062 -0
- package/dist/runs.js +3020 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +62 -0
- package/dist/secrets.js +158 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +722 -0
- package/dist/server.js +2118 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +43 -0
- package/dist/skills.js +96 -0
- package/dist/stats.d.ts +106 -0
- package/dist/stats.js +103 -0
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +187 -0
- package/dist/tool-keys.js +315 -0
- package/dist/tool-plane.d.ts +228 -0
- package/dist/tool-plane.js +400 -0
- package/dist/tools.d.ts +202 -0
- package/dist/tools.js +372 -0
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +24 -0
- package/dist/turn-end.js +15 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +57 -0
- package/dist/validate.js +184 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +189 -0
- package/dist/webhooks.js +503 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +100 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// A pi run's model request is marked on the run's root before it leaves (REQUEST_STARTED), and again if its stream
|
|
2
|
+
// ends aborted (REQUEST_ENDED). pi writes a request's entry when it answers or fails, and when it is aborted only if
|
|
3
|
+
// content had streamed, so one cut before that (a stop, a crash) would leave nothing to count; with the marks, the
|
|
4
|
+
// timeline counts it and reads the run's cost unknown, while a request still in flight reads as the sum so far.
|
|
5
|
+
//
|
|
6
|
+
// pi's compaction summary is a paid request too (`completeSimple`), and pi books its usage in its own usage document,
|
|
7
|
+
// never as an entry the run's timeline sums. So it is marked the same way (`request: "compaction"`), and its answer's
|
|
8
|
+
// cost is written as REQUEST_COST: the run's total, and /usage with it, include it, and one cut before its answer reads
|
|
9
|
+
// unknown. Both are wrapped here: `streamSimple` for the generation's requests, `completeSimple` for the summary. A
|
|
10
|
+
// tool's own request on the run's models (web_search's, hosted-search.ts) is a side request the same way, under its own
|
|
11
|
+
// label (sideRequests), and its cost is its tokens' plus the fee its tool names.
|
|
12
|
+
//
|
|
13
|
+
// Under a cap (cap.ts), each request comes with the worst case the cap held for it, and its start mark carries that
|
|
14
|
+
// figure (`heldUsd`), as does the end mark of a summary that failed: the cap counts a request a crash cut at it, in a
|
|
15
|
+
// later process too. The end mark of one stopped before its end carries what the cap counts it at given what it streamed
|
|
16
|
+
// (cap.ts stoppedFigure: what it streamed and an allowance, never more than its worst case). The timeline does not read it, so the run's shown cost
|
|
17
|
+
// is unknown as before. A request the cap refused gets a start mark of its own (`capRefused`), written before pi writes
|
|
18
|
+
// its error entry, so that entry answers its own mark and never stands for an earlier request a stop or a crash cut.
|
|
19
|
+
import { existsSync } from "node:fs";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
22
|
+
import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
23
|
+
import { REQUEST_COST, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED } from "@parcha/pi-durable-agent/timeline";
|
|
24
|
+
import { anyAttemptLost, ATTEMPTS, attemptLost, CAP_REFUSED_FIELD, END_NOT_WRITTEN, CLAMP, HELD_FIELD, HELD_USD, MARK_NOT_WRITTEN, markResponseBegan, piEnded, sideRequests, STOPPED_USD } from "./cap.js";
|
|
25
|
+
import { RUN_CANCELLED } from "./files.js";
|
|
26
|
+
import { isConnectCode, isGatewayTimeout } from "@parcha/agentrun-kernel";
|
|
27
|
+
/** Whether the run in `root` (its directory) was cancelled: the mark serve's cancel writes there first. */
|
|
28
|
+
export const cancelledIn = (root) => () => existsSync(join(root, RUN_CANCELLED));
|
|
29
|
+
/** How long a mark that carries a hold (a lost or failed request's end, an unreadable cost's) may take to reach the store
|
|
30
|
+
* before the request fails loudly (END_NOT_WRITTEN): 15 s. A lost mark is waited for before the retry is sent, so a
|
|
31
|
+
* commit queued behind a large entry on a slow disk (seconds) past 1 s let the retry leave, and its answer reach pi,
|
|
32
|
+
* with no mark in the store: a crash then read the request at the answer's own usage. Such a mark is written only on a
|
|
33
|
+
* path already lost or failed, so the wait costs latency there and nowhere else; 15 s holds such a commit with room to
|
|
34
|
+
* spare, and still fails a store that has stopped within a turn's patience, never a turn held without bound. */
|
|
35
|
+
export const END_MARK_WAIT_MS = 15_000;
|
|
36
|
+
/** How long a stop's mark is waited for before pi has the stopped result: a stop's mark needs no fatal wait (without it
|
|
37
|
+
* the request reads as cut, at its hold, never less), so a slow store costs a stop at most this. */
|
|
38
|
+
const STOP_MARK_WAIT_MS = 1_000;
|
|
39
|
+
/** `models` with each generation request marked before it leaves, once `open` hands over the run (its Harness). Once
|
|
40
|
+
* `cancelled` says the run was cancelled, no request is sent: each is refused here, before it is marked, or after its
|
|
41
|
+
* mark when the cancel came while the mark waited, and then its start is withdrawn (an end mark, `unsent`). */
|
|
42
|
+
export async function markRequests(models, cancelled = () => false, { holdMarkWaitMs = END_MARK_WAIT_MS } = {}) {
|
|
43
|
+
const { createAssistantMessageEventStream } = await import("@earendil-works/pi-ai");
|
|
44
|
+
let open;
|
|
45
|
+
// A request a resumed turn sends before the app's open waits for it: the mark needs the run's store.
|
|
46
|
+
const opened = new Promise((resolve) => (open = resolve));
|
|
47
|
+
const mark = async (kind, data = {}) => {
|
|
48
|
+
const run = await opened;
|
|
49
|
+
await run.harness.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind, data })), BACKGROUND_CONTEXT);
|
|
50
|
+
};
|
|
51
|
+
const failed = (model, why) => ({
|
|
52
|
+
role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
|
|
53
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
|
|
54
|
+
errorMessage: why,
|
|
55
|
+
});
|
|
56
|
+
const reason = (error) => String(error?.message ?? error).slice(0, 200);
|
|
57
|
+
/** Whether `work` (a mark's write) is in the store within `holdMarkWaitMs` (END_MARK_WAIT_MS, a test's own when it
|
|
58
|
+
* gives one): undefined when it is, else why not (its refusal, or the wait run out). */
|
|
59
|
+
const landed = (work) => new Promise((resolve) => {
|
|
60
|
+
const timer = setTimeout(() => resolve(new Error(`the store had not taken it in ${holdMarkWaitMs} ms`)), holdMarkWaitMs);
|
|
61
|
+
work.then(() => (clearTimeout(timer), resolve(undefined)), (error) => (clearTimeout(timer), resolve(error ?? new Error("refused"))));
|
|
62
|
+
});
|
|
63
|
+
/** Until `work` settles, or `ms` pass. */
|
|
64
|
+
const within = (work, ms) => new Promise((resolve) => {
|
|
65
|
+
const timer = setTimeout(resolve, ms);
|
|
66
|
+
void work.finally(() => (clearTimeout(timer), resolve()));
|
|
67
|
+
});
|
|
68
|
+
/** What the run's cap held for a request (its options' HELD_USD), as an end mark's field; none without a cap. */
|
|
69
|
+
const heldOf = (options) => {
|
|
70
|
+
const held = options?.[HELD_USD];
|
|
71
|
+
return typeof held === "number" && Number.isFinite(held) ? { [HELD_FIELD]: held } : {};
|
|
72
|
+
};
|
|
73
|
+
/** Whether a request the cap watched is lost (piEnded, from the attempts its cap recorded): an error before any event
|
|
74
|
+
* that left, or an answer after an attempt that was lost. It can have been billed, so it counts at its hold. Only a
|
|
75
|
+
* request the cap watched (a hold, and its attempts, or null on an API it cannot watch): another is read as before. */
|
|
76
|
+
const lostOf = (options, message) => {
|
|
77
|
+
const record = options;
|
|
78
|
+
if (typeof record?.[HELD_USD] !== "number" || !record || !(ATTEMPTS in record))
|
|
79
|
+
return false;
|
|
80
|
+
return piEnded(message, false, record[ATTEMPTS] ?? undefined).end === "lost";
|
|
81
|
+
};
|
|
82
|
+
/** `options` whose fetch writes the request's end mark at its hold (`lost`), once, the moment an attempt is known lost:
|
|
83
|
+
* a rejection once it could have left (any code but a connect one, and not the run's own stop) or a gateway's timeout
|
|
84
|
+
* (504, 524), as that attempt's fetch ends; an answer pi-ai then tries again (a 2xx that was not the last), before the
|
|
85
|
+
* next attempt is sent, since only the retry says so. Whatever follows (a retry's answer, a stop while pi-ai waits to
|
|
86
|
+
* retry, an error), the provider can have billed the lost attempt, and the mark is in the store before pi's entry for
|
|
87
|
+
* the request can be, so a later process reads the hold this one books, with no window between them. `options` as
|
|
88
|
+
* given on a request the cap does not watch. */
|
|
89
|
+
const watchingLost = (options, markLost) => {
|
|
90
|
+
const record = options;
|
|
91
|
+
const attempts = record && ATTEMPTS in record ? record[ATTEMPTS] : null;
|
|
92
|
+
if (!attempts || typeof record?.[HELD_USD] !== "number" || typeof record.fetch !== "function")
|
|
93
|
+
return options;
|
|
94
|
+
const inner = record.fetch;
|
|
95
|
+
let marked = false;
|
|
96
|
+
const markOnce = async () => {
|
|
97
|
+
if (marked)
|
|
98
|
+
return;
|
|
99
|
+
marked = true;
|
|
100
|
+
await markLost().catch(() => undefined);
|
|
101
|
+
};
|
|
102
|
+
/** Whether the attempt the fetch just recorded is lost as it ends, whatever comes after it. */
|
|
103
|
+
const lostNow = () => {
|
|
104
|
+
const last = attempts.at(-1);
|
|
105
|
+
return last !== undefined && ("code" in last ? !last.aborted && !isConnectCode(last.code) : isGatewayTimeout(last.status));
|
|
106
|
+
};
|
|
107
|
+
return { ...record, fetch: (async (input, init) => {
|
|
108
|
+
// An answer pi-ai tries again: lost, as the retry shows.
|
|
109
|
+
if (attempts.some((attempt) => attemptLost(attempt, false)))
|
|
110
|
+
await markOnce();
|
|
111
|
+
let response;
|
|
112
|
+
try {
|
|
113
|
+
response = await inner(input, init);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (lostNow())
|
|
117
|
+
await markOnce();
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
if (lostNow())
|
|
121
|
+
await markOnce();
|
|
122
|
+
return response;
|
|
123
|
+
}) };
|
|
124
|
+
};
|
|
125
|
+
/** What the run's cap counts a request stopped before its end at, given the answer it had streamed (its options'
|
|
126
|
+
* STOPPED_USD), as an end mark's field; its worst case when the cap gave no such figure, or when an attempt before the
|
|
127
|
+
* stop was lost (anyAttemptLost: it can have been billed, and the cap counts it at its hold in this process too); none
|
|
128
|
+
* without a cap. The one figure every stop's end mark carries, a generation's and a summary's. */
|
|
129
|
+
const stoppedOf = (options, message) => {
|
|
130
|
+
const attempts = options?.[ATTEMPTS];
|
|
131
|
+
if (anyAttemptLost(attempts ?? undefined))
|
|
132
|
+
return heldOf(options);
|
|
133
|
+
const stopped = options?.[STOPPED_USD];
|
|
134
|
+
const figure = typeof stopped === "function" ? stopped(message) : undefined;
|
|
135
|
+
return typeof figure === "number" && Number.isFinite(figure) ? { [HELD_FIELD]: figure } : heldOf(options);
|
|
136
|
+
};
|
|
137
|
+
/** A start mark's figures: its worst case, and what the cap limited its output to when it did (CLAMP), so a reply cut
|
|
138
|
+
* short there says so on the run's timeline. */
|
|
139
|
+
const startOf = (options) => {
|
|
140
|
+
const clamp = options?.[CLAMP];
|
|
141
|
+
const kept = clamp && typeof clamp.tokens === "number" && typeof clamp.leftUsd === "number" && typeof clamp.capUsd === "number" ? { clamp: { tokens: clamp.tokens, leftUsd: clamp.leftUsd, capUsd: clamp.capUsd } } : {};
|
|
142
|
+
return { ...heldOf(options), ...kept };
|
|
143
|
+
};
|
|
144
|
+
/** A cancelled run's request, never sent. It waits for the cancel to reach the run (the request's abort), and then ends
|
|
145
|
+
* as aborted, as a request the cancel cut does: the turn, or a workflow's node, stops, never failing on the refusal.
|
|
146
|
+
* serve's cancel aborts a live run's turn and then stops its process, so the wait is short. Its bound, a minute, is a
|
|
147
|
+
* backstop for a process the cancel never reaches (an orphan of a server that died in between): it then ends as an
|
|
148
|
+
* error, and `markRefusal` lets the timeline skip pi's entry for it. */
|
|
149
|
+
const refuse = async (model, what, signal, markRefusal) => {
|
|
150
|
+
if (signal && !signal.aborted) {
|
|
151
|
+
await new Promise((resolve) => {
|
|
152
|
+
const timer = setTimeout(resolve, 60_000);
|
|
153
|
+
signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
if (signal?.aborted)
|
|
157
|
+
return { ...failed(model, ""), stopReason: "aborted", errorMessage: undefined };
|
|
158
|
+
if (markRefusal)
|
|
159
|
+
await mark(REQUEST_REFUSED).catch(() => undefined);
|
|
160
|
+
return failed(model, `the run was cancelled: the ${what} was not sent`);
|
|
161
|
+
};
|
|
162
|
+
const streamSimple = (model, context, options) => {
|
|
163
|
+
const outer = createAssistantMessageEventStream();
|
|
164
|
+
const refused = async () => {
|
|
165
|
+
const message = await refuse(model, "model request", options?.signal, true);
|
|
166
|
+
outer.push({ type: "error", reason: message.stopReason === "aborted" ? "aborted" : "error", error: message });
|
|
167
|
+
outer.end(message);
|
|
168
|
+
};
|
|
169
|
+
void (async () => {
|
|
170
|
+
if (cancelled())
|
|
171
|
+
return refused();
|
|
172
|
+
try {
|
|
173
|
+
await mark(REQUEST_STARTED, startOf(options));
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
const message = failed(model, `${MARK_NOT_WRITTEN} (${reason(error)})`);
|
|
177
|
+
outer.push({ type: "error", reason: "error", error: message });
|
|
178
|
+
outer.end(message);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (cancelled()) {
|
|
182
|
+
await mark(REQUEST_ENDED, { unsent: true }).catch(() => undefined);
|
|
183
|
+
return refused();
|
|
184
|
+
}
|
|
185
|
+
let result;
|
|
186
|
+
// Whether the provider's response had begun (an event came in) by the time the request ended.
|
|
187
|
+
let began = false;
|
|
188
|
+
// The stream's error event, passed on once the request's end is marked (below): the outer stream's result, which
|
|
189
|
+
// pi writes as the entry and the cap counts, settles on that event.
|
|
190
|
+
let failure;
|
|
191
|
+
// Its done event, held the same way: the stream's result settles on it too, so pi has an answer only once its mark
|
|
192
|
+
// that carries a hold (a lost or unpriced request's) is in the store, and its entry always comes after that mark.
|
|
193
|
+
let done;
|
|
194
|
+
// Marked lost before pi-ai tries again (watchingLost): its end mark is in the store before its answer can be.
|
|
195
|
+
let lostMarked = false;
|
|
196
|
+
// Its write refused: the request's end is not recorded, and the request fails saying so (END_NOT_WRITTEN).
|
|
197
|
+
let lostRefused;
|
|
198
|
+
const sent = watchingLost(options, async () => {
|
|
199
|
+
lostMarked = true;
|
|
200
|
+
lostRefused = await landed(mark(REQUEST_ENDED, { lost: true, ...heldOf(options) }));
|
|
201
|
+
});
|
|
202
|
+
try {
|
|
203
|
+
const inner = models.streamSimple(model, context, sent);
|
|
204
|
+
for await (const event of inner) {
|
|
205
|
+
if (event.type === "error") {
|
|
206
|
+
failure = event;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
began = true;
|
|
210
|
+
if (event.type === "done") {
|
|
211
|
+
done = event;
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
outer.push(event);
|
|
215
|
+
}
|
|
216
|
+
result = await inner.result();
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
// A stream that throws instead of ending on an error event still ends the request, as an error, never a hang.
|
|
220
|
+
result = failed(model, `the model request failed: ${reason(error)}`);
|
|
221
|
+
failure = { type: "error", reason: "error", error: result };
|
|
222
|
+
}
|
|
223
|
+
// An answer or a failure gets pi's own entry; an abort may get none, so its end is marked, with the provider's id
|
|
224
|
+
// for the request when it named one before the cut (the request joins its record by it). A store that cannot
|
|
225
|
+
// take the mark leaves the request unended, which the timeline also reads as cut, at an unknown cost: the
|
|
226
|
+
// conservative reading, so the failure is swallowed here.
|
|
227
|
+
let ending;
|
|
228
|
+
// Whether `ending` carries the hold a later process must read (an error's or a lost request's): it is in the store
|
|
229
|
+
// before pi has the result, however long the store takes, and a refused one fails the request loudly. A stop's
|
|
230
|
+
// mark keeps its bound: without it the request stays open, read at its hold, which is never less.
|
|
231
|
+
let holding = false;
|
|
232
|
+
// An answer whose cost cannot be read counts at its hold (the booking rule), in this process and in a later one: its
|
|
233
|
+
// end mark carries the hold (`unpriced`), in the store before pi has the answer, as a lost request's does.
|
|
234
|
+
const total = result.usage?.cost?.total;
|
|
235
|
+
const unpriced = result.stopReason !== "error" && result.stopReason !== "aborted" && !(typeof total === "number" && Number.isFinite(total)) && Object.keys(heldOf(options)).length > 0;
|
|
236
|
+
// A request marked lost before its retry was sent has its end in the store already, at its hold: nothing more.
|
|
237
|
+
if (lostMarked) {
|
|
238
|
+
if (result.stopReason === "error" && failure?.type === "error")
|
|
239
|
+
markResponseBegan(failure.error);
|
|
240
|
+
}
|
|
241
|
+
else if (result.stopReason === "aborted") {
|
|
242
|
+
// Reached only with no lost attempt: watchingLost sets `lostMarked` synchronously, before it awaits the mark, the
|
|
243
|
+
// moment an attempt is lost, and that mark lands before pi-ai's retry sleep, so a stop in the sleep finds it set.
|
|
244
|
+
const responseId = result.responseId;
|
|
245
|
+
ending = mark(REQUEST_ENDED, { ...(typeof responseId === "string" ? { responseId } : {}), ...stoppedOf(options, result) });
|
|
246
|
+
}
|
|
247
|
+
else if (result.stopReason === "error" && (began || lostOf(options, result))) {
|
|
248
|
+
// An error after its response began (an overload part way, a reset): its usage is what had streamed, not what the
|
|
249
|
+
// provider can have billed. Its message is recorded (markResponseBegan), which the cap counts at its hold in this
|
|
250
|
+
// process, and its end is marked with the hold (`error`), which the spend read back counts. One before any event
|
|
251
|
+
// (a 429, a 5xx) is refused unbilled, and counts at its own usage.
|
|
252
|
+
markResponseBegan(result);
|
|
253
|
+
if (failure?.type === "error")
|
|
254
|
+
markResponseBegan(failure.error);
|
|
255
|
+
ending = mark(REQUEST_ENDED, { error: true, ...heldOf(options) });
|
|
256
|
+
holding = true;
|
|
257
|
+
}
|
|
258
|
+
else if (unpriced) {
|
|
259
|
+
ending = mark(REQUEST_ENDED, { unpriced: true, ...heldOf(options) });
|
|
260
|
+
holding = true;
|
|
261
|
+
}
|
|
262
|
+
// The end mark goes in before pi has the result, so the store holds it before pi's entry; a store that has not taken
|
|
263
|
+
// it in END_MARK_WAIT_MS does not hold the turn. One that carries a hold and is not in the store by then (refused, or
|
|
264
|
+
// still being written) fails the request loudly (END_NOT_WRITTEN): pi's entry for it then leaves its start open, read
|
|
265
|
+
// at its hold (spentIn), so no store's pace stands between a crash and a request read at less than it can have cost.
|
|
266
|
+
// A stop's mark needs none of that: without it the request reads as cut, at its hold, which is never less.
|
|
267
|
+
let unrecorded = lostRefused;
|
|
268
|
+
if (ending && holding)
|
|
269
|
+
unrecorded = await landed(ending);
|
|
270
|
+
else if (ending)
|
|
271
|
+
await within(ending.catch(() => undefined), STOP_MARK_WAIT_MS);
|
|
272
|
+
if (unrecorded !== undefined && result.stopReason !== "aborted") {
|
|
273
|
+
result = failed(model, `${END_NOT_WRITTEN} (${reason(unrecorded)})`);
|
|
274
|
+
failure = { type: "error", reason: "error", error: result };
|
|
275
|
+
}
|
|
276
|
+
// A request whose end could not be recorded fails loudly (failure, above) in place of its answer.
|
|
277
|
+
if (failure)
|
|
278
|
+
outer.push(failure);
|
|
279
|
+
else if (done)
|
|
280
|
+
outer.push(done);
|
|
281
|
+
outer.end(result);
|
|
282
|
+
})();
|
|
283
|
+
return outer;
|
|
284
|
+
};
|
|
285
|
+
const completeSimple = async (model, context, options) => {
|
|
286
|
+
const side = sideRequests.get(context);
|
|
287
|
+
const COMPACTION = { request: side?.label ?? "compaction" };
|
|
288
|
+
const what = side ? `${side.label} request` : "summary request";
|
|
289
|
+
// A cancelled run sends no summary either; pi writes no entry for a failed summary, so nothing needs marking.
|
|
290
|
+
if (cancelled())
|
|
291
|
+
return refuse(model, what, options?.signal, false);
|
|
292
|
+
try {
|
|
293
|
+
await mark(REQUEST_STARTED, { ...COMPACTION, ...heldOf(options) });
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
return failed(model, `${MARK_NOT_WRITTEN} (${reason(error)})`);
|
|
297
|
+
}
|
|
298
|
+
if (cancelled()) {
|
|
299
|
+
await mark(REQUEST_ENDED, { ...COMPACTION, unsent: true }).catch(() => undefined);
|
|
300
|
+
return refuse(model, what, options?.signal, false);
|
|
301
|
+
}
|
|
302
|
+
let result;
|
|
303
|
+
try {
|
|
304
|
+
result = await models.completeSimple(model, context, options);
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
await mark(REQUEST_ENDED, { ...COMPACTION, ...heldOf(options) }).catch(() => undefined);
|
|
308
|
+
throw error;
|
|
309
|
+
}
|
|
310
|
+
// Its cost closes it; an abort, as for a generation's request, closes it unpriced. A store that cannot take either
|
|
311
|
+
// leaves it open, which reads as cut, at an unknown cost.
|
|
312
|
+
if (result.stopReason === "aborted")
|
|
313
|
+
await mark(REQUEST_ENDED, { ...COMPACTION, ...stoppedOf(options, result) }).catch(() => undefined);
|
|
314
|
+
else {
|
|
315
|
+
const total = result.usage?.cost?.total;
|
|
316
|
+
// A side request's fee is its cost too, on the answer as well: the cap counts the answer's total (cap.ts).
|
|
317
|
+
const usd = typeof total === "number" ? total + (side?.feeUsd() ?? 0) : null;
|
|
318
|
+
if (side && usd !== null)
|
|
319
|
+
result.usage.cost.total = usd;
|
|
320
|
+
// Its tokens, in pi's shape, when pi counted any: zeros are no count.
|
|
321
|
+
const u = result.usage;
|
|
322
|
+
const usage = u && u.input + u.output + u.cacheRead + u.cacheWrite > 0 ? { input: u.input, output: u.output, cacheRead: u.cacheRead, cacheWrite: u.cacheWrite } : undefined;
|
|
323
|
+
// One that ended on an error after its response began (it holds content or a token count; a summary has no events
|
|
324
|
+
// to read) counts at its hold: it says so, and carries it. One before any of that counts at its own usage.
|
|
325
|
+
const began = result.stopReason === "error" && (usage !== undefined || result.content.length > 0);
|
|
326
|
+
if (began)
|
|
327
|
+
markResponseBegan(result);
|
|
328
|
+
// Failed before any response, it counts at its hold too unless it provably never left (piEnded): the same figure the
|
|
329
|
+
// cap books in this process, which a later process reads from this mark.
|
|
330
|
+
// An answer whose cost cannot be read counts at its hold too (the booking rule), which its mark carries.
|
|
331
|
+
const failure = began || lostOf(options, result) ? { failed: true, ...heldOf(options) } : result.stopReason !== "error" && !(typeof usd === "number" && Number.isFinite(usd)) && Object.keys(heldOf(options)).length > 0 ? { unpriced: true, ...heldOf(options) } : {};
|
|
332
|
+
await mark(REQUEST_COST, usage ? { ...COMPACTION, usd, usage: usage, ...failure } : { ...COMPACTION, usd, ...failure }).catch(() => undefined);
|
|
333
|
+
}
|
|
334
|
+
return result;
|
|
335
|
+
};
|
|
336
|
+
const proxy = new Proxy(models, {
|
|
337
|
+
get: (target, key) => {
|
|
338
|
+
if (key === "streamSimple")
|
|
339
|
+
return streamSimple;
|
|
340
|
+
if (key === "completeSimple")
|
|
341
|
+
return completeSimple;
|
|
342
|
+
const value = Reflect.get(target, key, target);
|
|
343
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
// The start mark of a generation request the cap refused (capModels), which never left: pi's error entry answers it. A
|
|
347
|
+
// refusal for room keeps its figures on it (what the cap counted as taken, and the least the request needed).
|
|
348
|
+
const refused = (figures) => mark(REQUEST_STARTED, { [CAP_REFUSED_FIELD]: true, ...(figures ? { spentUsd: figures.spentUsd, needsUsd: figures.needsUsd } : {}) });
|
|
349
|
+
return { models: proxy, open, refused };
|
|
350
|
+
}
|
package/dist/result.d.ts
ADDED
package/dist/result.js
ADDED
package/dist/rows.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { TimelineEvent } from "@parcha/pi-durable-agent/timeline";
|
|
2
|
+
export type Row = TimelineEvent & {
|
|
3
|
+
seq: number;
|
|
4
|
+
};
|
|
5
|
+
/** One server's change numbers: they start at its start time in microseconds, so a cursor from before a restart is below
|
|
6
|
+
* every number it hands out, and increase strictly across its runs. */
|
|
7
|
+
export declare class ChangeClock {
|
|
8
|
+
readonly base: number;
|
|
9
|
+
private counter;
|
|
10
|
+
next(): number;
|
|
11
|
+
get current(): number;
|
|
12
|
+
}
|
|
13
|
+
export type Page = {
|
|
14
|
+
reset: boolean;
|
|
15
|
+
rows: Row[];
|
|
16
|
+
drop: string[];
|
|
17
|
+
next_after: number;
|
|
18
|
+
unchanged: boolean;
|
|
19
|
+
has_more: boolean;
|
|
20
|
+
};
|
|
21
|
+
export declare class RowLog {
|
|
22
|
+
private readonly clock;
|
|
23
|
+
private readonly slots;
|
|
24
|
+
private readonly uses;
|
|
25
|
+
private seq;
|
|
26
|
+
/** The last change of this run: rows, drops and its status. */
|
|
27
|
+
last: number;
|
|
28
|
+
private stateChange;
|
|
29
|
+
private state;
|
|
30
|
+
private readonly waiters;
|
|
31
|
+
constructor(clock: ChangeClock);
|
|
32
|
+
private next;
|
|
33
|
+
/** Make the served rows equal `rows`: new ids are added after every row served so far, changed ones keep their seq,
|
|
34
|
+
* and ids no longer there are dropped, except those `keep` says stay (a row a committed entry made: the timeline only
|
|
35
|
+
* grows). Returns whether anything changed. */
|
|
36
|
+
sync(rows: readonly TimelineEvent[], keep?: (id: string) => boolean): boolean;
|
|
37
|
+
/** The run's status and state, as one more change when they move. */
|
|
38
|
+
setState(value: string): boolean;
|
|
39
|
+
rows(): Row[];
|
|
40
|
+
/** The changes after `after`, at most `limit` rows. A cursor from before this process, ahead of this run, or 0
|
|
41
|
+
* answers every row with `reset`. */
|
|
42
|
+
page(after: number, limit: number): Page;
|
|
43
|
+
/** Resolves on the next change, or after `ms`. */
|
|
44
|
+
changed(ms: number): Promise<void>;
|
|
45
|
+
private touch;
|
|
46
|
+
}
|
package/dist/rows.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
let latest = 0;
|
|
2
|
+
/** One server's change numbers: they start at its start time in microseconds, so a cursor from before a restart is below
|
|
3
|
+
* every number it hands out, and increase strictly across its runs. */
|
|
4
|
+
export class ChangeClock {
|
|
5
|
+
base = Math.max(Date.now() * 1000, latest + 1);
|
|
6
|
+
counter = this.base;
|
|
7
|
+
next() {
|
|
8
|
+
latest = Math.max(latest, ++this.counter);
|
|
9
|
+
return this.counter;
|
|
10
|
+
}
|
|
11
|
+
get current() {
|
|
12
|
+
return this.counter;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const SEQ_FREE = (row) => JSON.stringify({ ...row, seq: undefined, id: undefined });
|
|
16
|
+
export class RowLog {
|
|
17
|
+
clock;
|
|
18
|
+
slots = new Map();
|
|
19
|
+
uses = new Map();
|
|
20
|
+
seq = 0;
|
|
21
|
+
/** The last change of this run: rows, drops and its status. */
|
|
22
|
+
last;
|
|
23
|
+
stateChange;
|
|
24
|
+
state = "";
|
|
25
|
+
waiters = new Set();
|
|
26
|
+
constructor(clock) {
|
|
27
|
+
this.clock = clock;
|
|
28
|
+
this.last = clock.base;
|
|
29
|
+
this.stateChange = clock.base;
|
|
30
|
+
}
|
|
31
|
+
next() {
|
|
32
|
+
return this.clock.next();
|
|
33
|
+
}
|
|
34
|
+
/** Make the served rows equal `rows`: new ids are added after every row served so far, changed ones keep their seq,
|
|
35
|
+
* and ids no longer there are dropped, except those `keep` says stay (a row a committed entry made: the timeline only
|
|
36
|
+
* grows). Returns whether anything changed. */
|
|
37
|
+
sync(rows, keep) {
|
|
38
|
+
let changed = false;
|
|
39
|
+
const present = new Set();
|
|
40
|
+
for (const row of rows) {
|
|
41
|
+
present.add(row.id);
|
|
42
|
+
const text = SEQ_FREE(row);
|
|
43
|
+
const slot = this.slots.get(row.id);
|
|
44
|
+
if (slot && !slot.dropped) {
|
|
45
|
+
if (slot.text === text)
|
|
46
|
+
continue;
|
|
47
|
+
slot.text = text;
|
|
48
|
+
slot.row = { ...row, id: slot.id, seq: slot.seq };
|
|
49
|
+
slot.change = this.next();
|
|
50
|
+
changed = true;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const use = (this.uses.get(row.id) ?? 0) + 1;
|
|
54
|
+
this.uses.set(row.id, use);
|
|
55
|
+
const id = use === 1 ? row.id : `${row.id}~${use}`;
|
|
56
|
+
if (slot)
|
|
57
|
+
this.slots.set(`${row.id}\0${slot.change}`, slot);
|
|
58
|
+
const seq = this.seq++;
|
|
59
|
+
this.slots.set(row.id, { id, source: row.id, seq, row: { ...row, id, seq }, change: this.next(), dropped: false, text });
|
|
60
|
+
changed = true;
|
|
61
|
+
}
|
|
62
|
+
for (const [key, slot] of this.slots) {
|
|
63
|
+
if (slot.dropped || key !== slot.source || present.has(slot.source) || keep?.(slot.source))
|
|
64
|
+
continue;
|
|
65
|
+
slot.dropped = true;
|
|
66
|
+
slot.change = this.next();
|
|
67
|
+
changed = true;
|
|
68
|
+
}
|
|
69
|
+
// The usage row stays last: one served after it moves it to the end.
|
|
70
|
+
const shown = [...this.slots.values()].filter((s) => !s.dropped);
|
|
71
|
+
const usage = shown.find((s) => s.row.kind === "usage");
|
|
72
|
+
if (usage && shown.some((s) => s.seq > usage.seq)) {
|
|
73
|
+
usage.seq = this.seq++;
|
|
74
|
+
usage.row = { ...usage.row, seq: usage.seq };
|
|
75
|
+
usage.change = this.next();
|
|
76
|
+
changed = true;
|
|
77
|
+
}
|
|
78
|
+
if (changed)
|
|
79
|
+
this.touch();
|
|
80
|
+
return changed;
|
|
81
|
+
}
|
|
82
|
+
/** The run's status and state, as one more change when they move. */
|
|
83
|
+
setState(value) {
|
|
84
|
+
if (value === this.state)
|
|
85
|
+
return false;
|
|
86
|
+
this.state = value;
|
|
87
|
+
this.stateChange = this.next();
|
|
88
|
+
this.touch();
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
rows() {
|
|
92
|
+
return [...this.slots.values()].filter((s) => !s.dropped).map((s) => s.row).sort((a, b) => a.seq - b.seq);
|
|
93
|
+
}
|
|
94
|
+
/** The changes after `after`, at most `limit` rows. A cursor from before this process, ahead of this run, or 0
|
|
95
|
+
* answers every row with `reset`. */
|
|
96
|
+
page(after, limit) {
|
|
97
|
+
const reset = after <= 0 || after < this.clock.base || after > this.last;
|
|
98
|
+
const slots = [...this.slots.values()];
|
|
99
|
+
const changed = slots.filter((s) => !s.dropped && (reset || s.change > after)).sort((a, b) => a.change - b.change);
|
|
100
|
+
const has_more = changed.length > limit;
|
|
101
|
+
const taken = changed.slice(0, limit);
|
|
102
|
+
const upto = has_more ? taken.at(-1).change : this.last;
|
|
103
|
+
const drop = reset ? [] : slots.filter((s) => s.dropped && s.change > after && s.change <= upto).map((s) => s.id);
|
|
104
|
+
const rows = taken.map((s) => s.row).sort((a, b) => a.seq - b.seq);
|
|
105
|
+
const unchanged = !reset && rows.length === 0 && drop.length === 0 && this.stateChange <= after;
|
|
106
|
+
return { reset, rows, drop, next_after: upto, unchanged, has_more };
|
|
107
|
+
}
|
|
108
|
+
/** Resolves on the next change, or after `ms`. */
|
|
109
|
+
changed(ms) {
|
|
110
|
+
return new Promise((resolve) => {
|
|
111
|
+
const done = () => (clearTimeout(timer), this.waiters.delete(done), resolve());
|
|
112
|
+
const timer = setTimeout(done, ms);
|
|
113
|
+
this.waiters.add(done);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
touch() {
|
|
117
|
+
this.last = this.clock.current;
|
|
118
|
+
for (const wake of [...this.waiters])
|
|
119
|
+
wake();
|
|
120
|
+
}
|
|
121
|
+
}
|