@parcha/agentrun-serve 0.1.0-beta.48 → 0.1.0-beta.49
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 +20 -0
- package/README.md +144 -16
- package/dist/agent-delete.d.ts +33 -10
- package/dist/agent-delete.js +184 -26
- package/dist/agents-store.d.ts +6 -2
- package/dist/agents-store.js +18 -5
- package/dist/agents.d.ts +8 -1
- package/dist/agents.js +14 -4
- package/dist/answer-json.d.ts +2 -2
- package/dist/answer-json.js +3 -4
- package/dist/archil-routes.d.ts +1 -1
- package/dist/archil-routes.js +4 -3
- package/dist/browser-sessions.d.ts +56 -0
- package/dist/browser-sessions.js +117 -0
- package/dist/computer-routes.d.ts +4 -15
- package/dist/computer-routes.js +6 -10
- package/dist/console/assets/index-Bzn4eUYF.js +715 -0
- package/dist/console/assets/index-CR2ZGei1.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +15 -5
- package/dist/import.js +4 -3
- package/dist/learn/check.d.ts +11 -2
- package/dist/learn/check.js +12 -9
- package/dist/learn/promote.d.ts +7 -1
- package/dist/learn/promote.js +47 -0
- package/dist/learn/repick.d.ts +34 -0
- package/dist/learn/repick.js +201 -0
- package/dist/learned-workflow.d.ts +2 -0
- package/dist/learned-workflow.js +18 -1
- package/dist/learning-setting.d.ts +13 -0
- package/dist/learning-setting.js +23 -1
- package/dist/llms.txt +1 -1
- package/dist/openapi.js +170 -12
- package/dist/paid-calls.d.ts +4 -1
- package/dist/paid-calls.js +1 -1
- package/dist/run-learning-served.d.ts +1 -1
- package/dist/run-usage.d.ts +110 -0
- package/dist/run-usage.js +312 -0
- package/dist/runner/adapter-loop.js +51 -20
- package/dist/runner/conformance/harness.d.ts +2 -0
- package/dist/runner/conformance/harness.js +18 -4
- package/dist/runner/feedback-round.d.ts +29 -1
- package/dist/runner/feedback-round.js +54 -3
- package/dist/runner/journal-kinds.d.ts +3 -1
- package/dist/runner/learning-end.js +49 -18
- package/dist/runner/loop-contract.d.ts +3 -0
- package/dist/runner/monid-run.js +2 -2
- package/dist/runner/promotion.js +8 -2
- package/dist/runner/reflect-hook.js +3 -2
- package/dist/runs-over-store.d.ts +3 -2
- package/dist/runs-over-store.js +9 -7
- package/dist/server.d.ts +3 -3
- package/dist/server.js +221 -98
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/journal/storage.js +1 -1
- package/dist/store/open.d.ts +1 -1
- package/dist/store/open.js +1 -1
- package/dist/store/postgres/migrations/0021_purged.sql +13 -0
- package/dist/store/postgres/migrations/0022_computer_intervals.sql +27 -0
- package/dist/store/schema.d.ts +15 -1
- package/dist/store/schema.js +50 -5
- package/dist/store/sqlite/connection.d.ts +4 -1
- package/dist/store/sqlite/connection.js +5 -0
- package/dist/store/sqlite/run-patch.d.ts +8 -3
- package/dist/store/sqlite/run-patch.js +15 -7
- package/dist/store/sqlite/store.d.ts +5 -2
- package/dist/store/sqlite/store.js +249 -48
- package/dist/store/sqlite/worker.d.ts +9 -0
- package/dist/store/sqlite/worker.js +18 -1
- package/dist/store/store.d.ts +142 -9
- package/dist/store/store.js +63 -0
- package/dist/store-reads/analytics.js +2 -1
- package/dist/store-reads/cap.d.ts +8 -2
- package/dist/store-reads/cap.js +27 -3
- package/dist/store-reads/learning.d.ts +1 -1
- package/dist/store-reads/learning.js +5 -2
- package/dist/store-reads/runs.js +2 -0
- package/dist/store-reads/stats.js +4 -2
- package/dist/store-view.d.ts +7 -0
- package/dist/store-view.js +61 -20
- package/dist/tools.js +9 -0
- package/dist/trigger-targets.d.ts +7 -4
- package/dist/trigger-targets.js +6 -6
- package/dist/triggers.d.ts +2 -1
- package/dist/triggers.js +5 -2
- package/dist/validate.d.ts +4 -2
- package/dist/validate.js +13 -3
- package/dist/viewer-credential.d.ts +3 -4
- package/dist/viewer-credential.js +6 -4
- package/dist/workspace/computer-for-claim.d.ts +5 -1
- package/dist/workspace/computer-for-claim.js +47 -18
- package/dist/workspace/computer-intervals.d.ts +20 -0
- package/dist/workspace/computer-intervals.js +49 -0
- package/dist/workspace/computer-janitor.d.ts +7 -3
- package/dist/workspace/computer-janitor.js +14 -6
- package/dist/workspace/computer-kept.d.ts +7 -2
- package/dist/workspace/computer-kept.js +9 -2
- package/dist/workspace/resolve-computer.d.ts +7 -4
- package/dist/workspace/resolve-computer.js +21 -32
- package/dist/workspace/run-end-computers.d.ts +1 -0
- package/dist/workspace/run-end-computers.js +4 -1
- package/package.json +10 -10
- package/dist/console/assets/index-CTGegcKt.css +0 -1
- package/dist/console/assets/index-D1Se6mgG.js +0 -715
package/dist/agent-delete.js
CHANGED
|
@@ -1,7 +1,31 @@
|
|
|
1
1
|
// DELETE /v2/agents/{agent_id}: an agent another system owns (made by an inline run, POST /runs with `external`) deleted
|
|
2
|
-
// whole, for a host that must delete what it sent. An agent made here is
|
|
2
|
+
// whole, for a host that must delete what it sent (deleteExternalAgent). An agent made here is purged once it is archived
|
|
3
|
+
// (purgeAgent; 409 agent_not_archived before). DELETE /v2/runs/{run_id}: one run purged (purgeRun), with the runs made
|
|
4
|
+
// from it. An owner must be able to delete what a run read; what it cost stays in every total. So a purge keeps each
|
|
5
|
+
// run's row, and an agent's, as a tombstone, and removes everything else of it.
|
|
3
6
|
//
|
|
4
|
-
//
|
|
7
|
+
// A run's purge (purgeRun), only once it is not live (409 run_not_final otherwise, nothing purged: live is not final, or
|
|
8
|
+
// held by a runner; a run that ended and can take a follow-up is not live), nor any run made from it: first each run made
|
|
9
|
+
// from it (the replay runs of its input, its audit's shadow run, a learning run its kept learning names; each one's own
|
|
10
|
+
// such runs before it), then the grades its agent keeps of it and the content its promotion records copied from it (each
|
|
11
|
+
// disagreement's input and answers, learn/promote.ts forgetRunCopies), then the run, each by purgeOne: the figures its spend's
|
|
12
|
+
// readers read from its journal (kept on the tombstone, PurgeKept), its folders (its own folder on the agent's Archil disk
|
|
13
|
+
// it resolved to, and on a disk its launch named), settings and kept answers, then its rows (store runs.purge, which sets
|
|
14
|
+
// its purge time last). A replay of its input or an audit's shadow made by a claim (in a runner, maybe another process)
|
|
15
|
+
// after the DELETE read the runs made from it is found by the store's purge, under the run's row lock: 409 run_not_final
|
|
16
|
+
// naming it, the run kept for the next DELETE, which purges it first (RunsMadeFromLeft); one made once the run is purged
|
|
17
|
+
// is refused at its create, nothing written (RunPurged). A DELETE stopped part way finds the run not purged yet and the
|
|
18
|
+
// next DELETE finishes it; a DELETE of a purged run is 204 again, and every other route of it is 410 purged with its
|
|
19
|
+
// tombstone.
|
|
20
|
+
//
|
|
21
|
+
// An archived agent made here (purgeAgent), by the same rule: 409 run_not_final while a run of it is live. Then its
|
|
22
|
+
// learning, its things (triggers, sign-ins, its own computer, its disk), each of its runs by purgeOne (the runs made from
|
|
23
|
+
// it first, as a run's purge does them), its folders, settings and kept answers, and its rows (store agents.purge: its
|
|
24
|
+
// revisions' content, its name and description blanked, its purge time last). Each step is idempotent, so a DELETE stopped part way is finished by the next. Archived, the agent
|
|
25
|
+
// takes no new run and no trigger fires it; a run that reached it anyway keeps it unpurged (the store refuses), for the
|
|
26
|
+
// next DELETE.
|
|
27
|
+
//
|
|
28
|
+
// Another system's agent (deleteExternalAgent), in order, each step finished before the next:
|
|
5
29
|
// 1. The agent refuses new runs, as a mark in the store that outlives a restart: its archive time, which only this
|
|
6
30
|
// delete writes on an agent another system owns (its archive route is refused), set by the trigger engine with its
|
|
7
31
|
// triggers off in the same commit. From that commit a person's run, an inline run, a trigger's firing, an SDK run and
|
|
@@ -27,7 +51,7 @@
|
|
|
27
51
|
// same 503, and the next DELETE removes that trigger as it removes the others.
|
|
28
52
|
import { ApiError } from "./errors.js";
|
|
29
53
|
import { LearningInFlight } from "./learn/delete.js";
|
|
30
|
-
import { FINAL_STATES, TriggersLeft } from "./store/index.js";
|
|
54
|
+
import { FINAL_STATES, RunsMadeFromLeft, StoreConstraint, TriggersLeft } from "./store/index.js";
|
|
31
55
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
32
56
|
const isFinal = (state) => FINAL_STATES.includes(state);
|
|
33
57
|
/** Deletes agent `agentId` (another system's, as the route checked) in the three steps above. Throws ApiError
|
|
@@ -37,7 +61,151 @@ export async function deleteExternalAgent(host, agentId) {
|
|
|
37
61
|
await host.refuse(agentId);
|
|
38
62
|
await stopRuns(host, agentId);
|
|
39
63
|
await host.at?.("after_step_1", agentId);
|
|
40
|
-
// 2. Its learning.
|
|
64
|
+
// 2. Its learning.
|
|
65
|
+
await learningGone(host, agentId);
|
|
66
|
+
await host.at?.("after_step_2", agentId);
|
|
67
|
+
// 3. Its things, then its rows; the agent's row last.
|
|
68
|
+
await thingsGone(host, agentId);
|
|
69
|
+
let first = true;
|
|
70
|
+
for (const run of await host.store.runs.every(agentId)) {
|
|
71
|
+
await host.forgetRun(agentId, run.id, false);
|
|
72
|
+
await host.store.runs.remove(run.id);
|
|
73
|
+
if (first)
|
|
74
|
+
await host.at?.("in_step_3", agentId);
|
|
75
|
+
first = false;
|
|
76
|
+
}
|
|
77
|
+
await host.forgetAgent(agentId);
|
|
78
|
+
try {
|
|
79
|
+
await host.store.agents.remove(agentId);
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
throw triggersLeft(error, agentId);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Purges archived agent `agentId`, made here (as the route checked), as the header says: 409 run_not_final, nothing
|
|
86
|
+
* purged, while a run of it is live; learning_busy while its learning refuses. */
|
|
87
|
+
export async function purgeAgent(host, agentId) {
|
|
88
|
+
const live = await liveOf(host, (await host.store.runs.every(agentId)).filter((run) => run.purgedAt === null));
|
|
89
|
+
if (live.length)
|
|
90
|
+
throw liveRuns(`The agent ${agentId} has ${live.length === 1 ? "a run" : "runs"} that ${live.length === 1 ? "has" : "have"} not ended (${live.join(", ")}): cancel ${live.length === 1 ? "it" : "them"} (POST /v2/runs/{run_id}/cancel), then send the DELETE again. Nothing was purged.`, live);
|
|
91
|
+
// Marked before anything goes, and kept until its tombstone is written: a purge stopped part way leaves the agent
|
|
92
|
+
// refusing an unarchive and every write (server.ts agentWrite) until a DELETE finishes it.
|
|
93
|
+
await host.store.settings.put(purgingKey(agentId), true);
|
|
94
|
+
await learningGone(host, agentId);
|
|
95
|
+
await host.at?.("after_step_2", agentId);
|
|
96
|
+
await thingsGone(host, agentId);
|
|
97
|
+
let first = true;
|
|
98
|
+
for (const run of await host.store.runs.every(agentId)) {
|
|
99
|
+
if (run.purgedAt !== null)
|
|
100
|
+
continue;
|
|
101
|
+
// The runs made from it first, each one's own before it, as purgeRun does: the store refuses a run's purge while one
|
|
102
|
+
// made from it (an audit's shadow, a replay, each started after it) is not purged. Its disk went whole above, each
|
|
103
|
+
// of its runs' folders there with it; a run of another agent keeps that agent's disk.
|
|
104
|
+
for (const one of await madeFromAll(host, run.id))
|
|
105
|
+
await purgeOneOrRefuse(host, one.agentId, one.id, agentId, one.agentId !== agentId);
|
|
106
|
+
// A later run of the list may be gone as one made from an earlier.
|
|
107
|
+
if ((await host.store.runs.get(run.id))?.purgedAt !== null)
|
|
108
|
+
continue;
|
|
109
|
+
await purgeOneOrRefuse(host, agentId, run.id, agentId, false);
|
|
110
|
+
if (first)
|
|
111
|
+
await host.at?.("in_step_3", agentId);
|
|
112
|
+
first = false;
|
|
113
|
+
}
|
|
114
|
+
await host.forgetAgent(agentId);
|
|
115
|
+
try {
|
|
116
|
+
await host.store.agents.purge(agentId);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (error instanceof StoreConstraint)
|
|
120
|
+
throw liveRuns(`The agent ${agentId} has a run started while it was being purged (${error.message}): send the DELETE again once it has ended. Its runs purged so far stay purged.`, []);
|
|
121
|
+
throw triggersLeft(error, agentId);
|
|
122
|
+
}
|
|
123
|
+
// Its tombstone refuses every write from here (410 purged).
|
|
124
|
+
await host.store.settings.remove(purgingKey(agentId));
|
|
125
|
+
}
|
|
126
|
+
/** The setting that marks agent `agentId`'s purge begun and not finished (purgeAgent). */
|
|
127
|
+
export const purgingKey = (agentId) => `agent.purging.${agentId}`;
|
|
128
|
+
/** Purges run `runId` with every run made from it, as the header says. 404 not_found when it is not there; 409
|
|
129
|
+
* run_not_final, nothing purged, while it or a run made from it is live. A purged run is no work. */
|
|
130
|
+
export async function purgeRun(host, runId) {
|
|
131
|
+
const run = await host.store.runs.get(runId);
|
|
132
|
+
if (!run)
|
|
133
|
+
throw new ApiError("not_found", `no run ${runId}`);
|
|
134
|
+
if (run.purgedAt !== null)
|
|
135
|
+
return;
|
|
136
|
+
const made = await madeFromAll(host, runId);
|
|
137
|
+
const live = await liveOf(host, [run, ...made]);
|
|
138
|
+
if (live.length)
|
|
139
|
+
throw notFinal(runId, live);
|
|
140
|
+
for (const one of made)
|
|
141
|
+
await purgeOneOrRefuse(host, one.agentId, one.id, runId, true);
|
|
142
|
+
await host.at?.("run_made_from_gone", runId);
|
|
143
|
+
await host.forgetCopies(run.agentId, runId);
|
|
144
|
+
await purgeOneOrRefuse(host, run.agentId, runId, runId, true);
|
|
145
|
+
}
|
|
146
|
+
/** The one per-run step of both purges: the figures its spend's readers read from its journal, its things outside its
|
|
147
|
+
* rows, then its rows (a tombstone). Its store's refusal of a run gone live again since it was read (a follow-up opened
|
|
148
|
+
* it) is 409 run_not_final, as a run read live is (`purged`: the run or agent the DELETE names; `alone`: its agent's disk
|
|
149
|
+
* stays, AgentDeleteHost.forgetRun). */
|
|
150
|
+
async function purgeOneOrRefuse(host, agentId, runId, purged, alone) {
|
|
151
|
+
const kept = await host.kept(runId);
|
|
152
|
+
await host.forgetRun(agentId, runId, alone);
|
|
153
|
+
await host.at?.("run_forgotten", runId);
|
|
154
|
+
try {
|
|
155
|
+
await host.store.runs.purge(runId, kept);
|
|
156
|
+
}
|
|
157
|
+
catch (error) {
|
|
158
|
+
// A replay or shadow made from it after the runs made from it were read: named, for the next DELETE to purge first.
|
|
159
|
+
if (error instanceof RunsMadeFromLeft)
|
|
160
|
+
throw notFinal(purged, error.runs);
|
|
161
|
+
if (error instanceof StoreConstraint)
|
|
162
|
+
throw notFinal(purged, [runId]);
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** Every run made from run `runId` that is there and not purged, each one's own before it (deepest first), never `runId`. */
|
|
167
|
+
async function madeFromAll(host, runId, seen = new Set([runId])) {
|
|
168
|
+
const out = [];
|
|
169
|
+
for (const id of await host.madeFrom(runId)) {
|
|
170
|
+
if (seen.has(id))
|
|
171
|
+
continue;
|
|
172
|
+
seen.add(id);
|
|
173
|
+
const row = await host.store.runs.get(id);
|
|
174
|
+
if (!row || row.purgedAt !== null)
|
|
175
|
+
continue;
|
|
176
|
+
out.push(...(await madeFromAll(host, id, seen)), { id, agentId: row.agentId, state: row.state, runner: row.runner });
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
|
180
|
+
/** Live: not final, or held by a runner. A run that ended and can take a follow-up (it reads idle) is not. */
|
|
181
|
+
const isLive = (run) => !isFinal(run.state) || run.runner !== null;
|
|
182
|
+
/** Of `runs`, the ids of the live ones. A run whose turn is over (it reads idle: a person's stop, or its turn's end) is
|
|
183
|
+
* written final by its runner a moment after it reads so, so while every live run is such a one, each is read again
|
|
184
|
+
* every host.pollMs, for host.waitMs at most, until it is final and let go. A live run whose turn is not over makes the
|
|
185
|
+
* answer at once, and so does one still live at the end. */
|
|
186
|
+
async function liveOf(host, runs) {
|
|
187
|
+
const deadline = Date.now() + host.waitMs;
|
|
188
|
+
let live = runs.filter(isLive).map((run) => run.id);
|
|
189
|
+
for (;;) {
|
|
190
|
+
if (!live.length)
|
|
191
|
+
return live;
|
|
192
|
+
for (const id of live)
|
|
193
|
+
if (!(await host.turnOver(id)))
|
|
194
|
+
return live;
|
|
195
|
+
if (Date.now() >= deadline)
|
|
196
|
+
return live;
|
|
197
|
+
await sleep(host.pollMs);
|
|
198
|
+
const rows = await Promise.all(live.map((id) => host.store.runs.get(id)));
|
|
199
|
+
live = rows.filter((row) => row !== undefined && row.purgedAt === null && isLive(row)).map((row) => row.id);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const liveRuns = (message, runs) => new ApiError("run_not_final", message, { details: { runs: [...runs] } });
|
|
203
|
+
const notFinal = (runId, live) => liveRuns(live.length === 1 && live[0] === runId
|
|
204
|
+
? `The run ${runId} has not ended: cancel it first (POST /v2/runs/${runId}/cancel), then send the DELETE again. Nothing was purged.`
|
|
205
|
+
: `${runId} has ${live.length === 1 ? "a run" : "runs"} that ${live.length === 1 ? "has" : "have"} not ended (${live.join(", ")}): send the DELETE again once ${live.length === 1 ? "it has" : "they have"} ended. Runs purged so far stay purged.`, live);
|
|
206
|
+
/** An agent's learning deleted (step 2 of a delete, the first of a purge). Its refusal while learning work is in flight is
|
|
207
|
+
* learning_busy; any other failure is the server's own. */
|
|
208
|
+
async function learningGone(host, agentId) {
|
|
41
209
|
try {
|
|
42
210
|
await host.deleteLearning(host.store, agentId);
|
|
43
211
|
}
|
|
@@ -46,10 +214,12 @@ export async function deleteExternalAgent(host, agentId) {
|
|
|
46
214
|
throw error;
|
|
47
215
|
throw new ApiError("learning_busy", `The agent ${agentId}'s learning could not be deleted yet (${error.message}). The agent starts no run meanwhile: send the DELETE again later to finish it.`, { details: { runs: [...error.runs] }, retry_after_ms: 5_000 });
|
|
48
216
|
}
|
|
49
|
-
|
|
50
|
-
|
|
217
|
+
}
|
|
218
|
+
/** An agent's things outside the store's rows: its triggers through the trigger engine (each one's registration upstream
|
|
219
|
+
* first, then its settings, then its row: the row names what is left to remove until each is gone), its saved sign-ins,
|
|
220
|
+
* its own computer, its Archil disk. */
|
|
221
|
+
async function thingsGone(host, agentId) {
|
|
51
222
|
for (const trigger of await host.store.triggers.list(agentId)) {
|
|
52
|
-
// Upstream first, then its settings, then its row: the row names what is left to remove until each is gone.
|
|
53
223
|
await host.removeTriggerThere(trigger.id);
|
|
54
224
|
await host.at?.("in_step_3_trigger", agentId);
|
|
55
225
|
await host.removeTriggerSettings(trigger.id);
|
|
@@ -59,25 +229,13 @@ export async function deleteExternalAgent(host, agentId) {
|
|
|
59
229
|
await host.forgetSignIns(agentId);
|
|
60
230
|
await host.removeOwnComputer(agentId);
|
|
61
231
|
await host.removeDisk(agentId);
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
await host.forgetAgent(agentId);
|
|
71
|
-
try {
|
|
72
|
-
await host.store.agents.remove(agentId);
|
|
73
|
-
}
|
|
74
|
-
catch (error) {
|
|
75
|
-
// A trigger that reached the agent after the listing above (the store refuses one once the agent is marked; this is
|
|
76
|
-
// its backstop): the agent is kept, refusing, for the next DELETE to remove it upstream, its settings, then its row.
|
|
77
|
-
if (!(error instanceof TriggersLeft))
|
|
78
|
-
throw error;
|
|
79
|
-
throw new ApiError("unavailable", `The agent ${agentId} has ${error.triggerIds.length === 1 ? "a trigger" : "triggers"} made while it was being deleted (${error.triggerIds.join(", ")}), not removed yet. It starts no run meanwhile: send the DELETE again to finish it.`, { details: { triggers: error.triggerIds }, retry_after_ms: 5_000 });
|
|
80
|
-
}
|
|
232
|
+
}
|
|
233
|
+
/** A trigger that reached the agent after its delete listed them (the store refuses one once the agent is marked; this is
|
|
234
|
+
* its backstop): the agent is kept for the next DELETE to remove it upstream, its settings, then its row. */
|
|
235
|
+
function triggersLeft(error, agentId) {
|
|
236
|
+
if (!(error instanceof TriggersLeft))
|
|
237
|
+
return error;
|
|
238
|
+
return new ApiError("unavailable", `The agent ${agentId} has ${error.triggerIds.length === 1 ? "a trigger" : "triggers"} made while it was being deleted (${error.triggerIds.join(", ")}), not removed yet. It starts no run meanwhile: send the DELETE again to finish it.`, { details: { triggers: error.triggerIds }, retry_after_ms: 5_000 });
|
|
81
239
|
}
|
|
82
240
|
/** Step 1's second half: each run of the agent not final cancelled once, then read again until every one is final. A run's
|
|
83
241
|
* end may queue its learning run, so the runs are listed again on each read. A run this server cannot end, or one still
|
package/dist/agents-store.d.ts
CHANGED
|
@@ -70,6 +70,8 @@ export declare function createAgent(store: AgentsStore, { definition, skills, no
|
|
|
70
70
|
export declare function makeRevision(definition: Json, files: Record<string, string>, note: string | undefined): NewRevision & {
|
|
71
71
|
note?: string;
|
|
72
72
|
};
|
|
73
|
+
/** Runs a write's last read and its commit in the agent's delete turn (server.ts agentWrite). */
|
|
74
|
+
export type InTurn = <T>(work: () => Promise<T>) => Promise<T>;
|
|
73
75
|
/** An edit: a new revision of the agent, made current. Without `skills` the current revision's skill files carry over. An
|
|
74
76
|
* edit that is the current revision writes nothing, so a PUT sent twice makes one revision. The agent keeps its id and name
|
|
75
77
|
* from its creation (a changed one is input_invalid). Its description is a label: an edit that names a new one makes a
|
|
@@ -83,13 +85,15 @@ export declare function makeRevision(definition: Json, files: Record<string, str
|
|
|
83
85
|
* revision it does not follow. `contract`: an edit that always makes a new revision, even one equal to the current.
|
|
84
86
|
* `template`: the package an apply with agent_id wrote it from, kept on the revision (getAgent's `template`).
|
|
85
87
|
* `fromPackage`: the definition is a whole package's (an apply with agent_id), so what it leaves out is not carried over
|
|
86
|
-
* (editOn).
|
|
87
|
-
|
|
88
|
+
* (editOn). `inTurn`: where the agent is read again and the revision written (the server's agentWrite, which refuses a
|
|
89
|
+
* purged agent, or one whose purge stopped part way); the check runs outside it. */
|
|
90
|
+
export declare function commitAgent(store: AgentsStore, read: AgentEntry, { definition, skills, note }: DefinitionBody, { ifCurrent, check, contract, template, fromPackage, inTurn }?: {
|
|
88
91
|
ifCurrent?: string | null;
|
|
89
92
|
check?: SaveCheck;
|
|
90
93
|
contract?: boolean;
|
|
91
94
|
template?: TemplatePackage;
|
|
92
95
|
fromPackage?: boolean;
|
|
96
|
+
inTurn?: InTurn;
|
|
93
97
|
}): Promise<AgentEntry>;
|
|
94
98
|
/** Makes `revisionId`, one of the agent's own, its current one (POST /agents/{id}/current). */
|
|
95
99
|
export declare function setCurrentRevision(store: AgentsStore, entry: AgentEntry, revisionId: string): Promise<AgentEntry>;
|
package/dist/agents-store.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
//
|
|
7
7
|
// The run counts an agent view shows (runs.count, runs.live) are E3's run reads, not this module's; agentView takes them.
|
|
8
8
|
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { purgedAgent } from "./agents.js";
|
|
9
10
|
import { agentLink } from "./console-links.js";
|
|
10
11
|
import { approvalsOf } from "./approvals.js";
|
|
11
12
|
import { ApiError, invalid } from "./errors.js";
|
|
@@ -241,8 +242,9 @@ const EDIT_TRIES = 5;
|
|
|
241
242
|
* revision it does not follow. `contract`: an edit that always makes a new revision, even one equal to the current.
|
|
242
243
|
* `template`: the package an apply with agent_id wrote it from, kept on the revision (getAgent's `template`).
|
|
243
244
|
* `fromPackage`: the definition is a whole package's (an apply with agent_id), so what it leaves out is not carried over
|
|
244
|
-
* (editOn).
|
|
245
|
-
|
|
245
|
+
* (editOn). `inTurn`: where the agent is read again and the revision written (the server's agentWrite, which refuses a
|
|
246
|
+
* purged agent, or one whose purge stopped part way); the check runs outside it. */
|
|
247
|
+
export async function commitAgent(store, read, { definition, skills, note }, { ifCurrent, check, contract = false, template, fromPackage = false, inTurn } = {}) {
|
|
246
248
|
const stale = () => new ApiError("precondition_failed", "the agent's current revision moved since the If-Match it was read at: read the agent again");
|
|
247
249
|
const held = (entry) => {
|
|
248
250
|
if (ifCurrent !== undefined && (entry.revision?.id ?? null) !== ifCurrent)
|
|
@@ -250,6 +252,9 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
|
|
|
250
252
|
return entry;
|
|
251
253
|
};
|
|
252
254
|
let entry = (await getAgent(store, read.agent.id)) ?? read;
|
|
255
|
+
// Purged since the request read it: 410 before anything is checked (the commit's turn and the store refuse it too).
|
|
256
|
+
if (entry.agent.purgedAt !== null)
|
|
257
|
+
throw purgedAgent(entry.agent);
|
|
253
258
|
refuseExternal(entry.agent);
|
|
254
259
|
held(entry);
|
|
255
260
|
const { agent } = entry;
|
|
@@ -270,8 +275,13 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
|
|
|
270
275
|
const edit = template ? { ...made, package: template } : made;
|
|
271
276
|
const revision = stamped(edit, await check?.(edit, entry.revision));
|
|
272
277
|
const base = entry.revision?.id ?? null;
|
|
273
|
-
|
|
274
|
-
|
|
278
|
+
// The agent read again and the revision written in `inTurn` (the server's agent delete turn): the check above, which
|
|
279
|
+
// may wait on a server's listing, runs outside it, so edits of one agent are checked at once and a DELETE never waits
|
|
280
|
+
// on a check.
|
|
281
|
+
const landed = await (inTurn ?? ((work) => work()))(async () => {
|
|
282
|
+
const now = held((await getAgent(store, agent.id)) ?? entry);
|
|
283
|
+
if ((now.revision?.id ?? null) !== base)
|
|
284
|
+
return undefined;
|
|
275
285
|
// A new description is a real edit: a revision, even with the body unchanged. The same one again writes nothing.
|
|
276
286
|
const described = description !== undefined && description !== now.agent.description;
|
|
277
287
|
if (!contract && !described && now.revision && sameRevision(now.revision, revision)) {
|
|
@@ -291,8 +301,11 @@ export async function commitAgent(store, read, { definition, skills, note }, { i
|
|
|
291
301
|
catch (error) {
|
|
292
302
|
if (!(error instanceof RevisionMoved))
|
|
293
303
|
storeError(error);
|
|
304
|
+
return undefined;
|
|
294
305
|
}
|
|
295
|
-
}
|
|
306
|
+
});
|
|
307
|
+
if (landed)
|
|
308
|
+
return landed;
|
|
296
309
|
// Moved while it was checked or written: with If-Match that is stale; without, built and checked again on it.
|
|
297
310
|
if (ifCurrent !== undefined)
|
|
298
311
|
throw stale();
|
package/dist/agents.d.ts
CHANGED
|
@@ -16,9 +16,16 @@ export declare const homeBusy: () => ApiError;
|
|
|
16
16
|
/** The answer to a run, a trigger or a write refused because its agent is being deleted (the store's AgentDeleting, read
|
|
17
17
|
* in the transaction that would start or reopen the run or write the trigger; the server's own check for a write). */
|
|
18
18
|
export declare const agentDeleting: (agentId: string) => ApiError;
|
|
19
|
+
/** 410 purged for a route of a purged agent (Agents.purge), or a write the store refused because it is (AgentPurged):
|
|
20
|
+
* its tombstone in the details. */
|
|
21
|
+
export declare const purgedAgent: (agent: {
|
|
22
|
+
id: string;
|
|
23
|
+
archivedAt: number | null;
|
|
24
|
+
purgedAt: number | null;
|
|
25
|
+
}) => ApiError;
|
|
19
26
|
/** What a request's error answers, over HTTP and through an MCP tool alike (server.ts, mcp.ts dispatch): an ApiError as
|
|
20
27
|
* it is; a busy store home_busy (409, retryable), never 500; a run of an agent being deleted agent_not_runnable (409);
|
|
21
|
-
* anything else internal, its message kept. */
|
|
28
|
+
* a write to a purged agent purged (410); anything else internal, its message kept. */
|
|
22
29
|
export declare const answerOf: (error: unknown) => ApiError;
|
|
23
30
|
/** Whether a request's error goes to the server's log: every fault the server did not answer on purpose. A busy wait
|
|
24
31
|
* is not one; a transaction past its deadline is (something held the store that long). */
|
package/dist/agents.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// (whenFree), then answered home_busy. The agents themselves are over the one store (agents-store.ts).
|
|
3
3
|
import { ApiError } from "./errors.js";
|
|
4
4
|
import { isObject } from "./validate.js";
|
|
5
|
-
import { AgentDeleting, StoreBusy, StoreDeadline } from "./store/index.js";
|
|
5
|
+
import { AgentDeleting, AgentPurged, StoreBusy, StoreDeadline } from "./store/index.js";
|
|
6
6
|
/** SQLITE_BUSY or SQLITE_LOCKED: another connection holds the database. */
|
|
7
7
|
export const sqliteBusy = (error) => isObject(error) && error.code === "ERR_SQLITE_ERROR" && typeof error.errcode === "number" && [5, 6].includes(error.errcode & 0xff);
|
|
8
8
|
/** How long a request waits for a busy agent store, step by step: short first, so a reader's overlap costs
|
|
@@ -36,10 +36,20 @@ export const homeBusy = () => new ApiError("home_busy", "the agent store is busy
|
|
|
36
36
|
/** The answer to a run, a trigger or a write refused because its agent is being deleted (the store's AgentDeleting, read
|
|
37
37
|
* in the transaction that would start or reopen the run or write the trigger; the server's own check for a write). */
|
|
38
38
|
export const agentDeleting = (agentId) => new ApiError("agent_not_runnable", `The agent ${agentId} is being deleted (DELETE /v2/agents/${agentId}): it starts no run, opens none again and takes no new trigger or write. Send the DELETE again to finish it.`);
|
|
39
|
+
const isoOrNull = (ms) => (ms === null ? null : new Date(ms).toISOString());
|
|
40
|
+
/** 410 purged for a route of a purged agent (Agents.purge), or a write the store refused because it is (AgentPurged):
|
|
41
|
+
* its tombstone in the details. */
|
|
42
|
+
export const purgedAgent = (agent) => new ApiError("purged", `The agent ${agent.id} was purged: its definition, learning and runs' content are gone, and its runs' cost stays in every total.`, {
|
|
43
|
+
details: { agent_id: agent.id, archived_at: isoOrNull(agent.archivedAt), purged_at: isoOrNull(agent.purgedAt) },
|
|
44
|
+
});
|
|
39
45
|
/** What a request's error answers, over HTTP and through an MCP tool alike (server.ts, mcp.ts dispatch): an ApiError as
|
|
40
46
|
* it is; a busy store home_busy (409, retryable), never 500; a run of an agent being deleted agent_not_runnable (409);
|
|
41
|
-
* anything else internal, its message kept. */
|
|
42
|
-
export const answerOf = (error) => error instanceof ApiError ? error
|
|
47
|
+
* a write to a purged agent purged (410); anything else internal, its message kept. */
|
|
48
|
+
export const answerOf = (error) => error instanceof ApiError ? error
|
|
49
|
+
: storeBusy(error) ? homeBusy()
|
|
50
|
+
: error instanceof AgentDeleting ? agentDeleting(error.agentId)
|
|
51
|
+
: error instanceof AgentPurged ? purgedAgent({ id: error.agentId, archivedAt: error.archivedAt, purgedAt: error.purgedAt })
|
|
52
|
+
: new ApiError("internal", error?.message ?? String(error));
|
|
43
53
|
/** Whether a request's error goes to the server's log: every fault the server did not answer on purpose. A busy wait
|
|
44
54
|
* is not one; a transaction past its deadline is (something held the store that long). */
|
|
45
|
-
export const logged = (error) => !(error instanceof ApiError) && !(error instanceof AgentDeleting) && (!storeBusy(error) || error instanceof StoreDeadline);
|
|
55
|
+
export const logged = (error) => !(error instanceof ApiError) && !(error instanceof AgentDeleting) && !(error instanceof AgentPurged) && (!storeBusy(error) || error instanceof StoreDeadline);
|
package/dist/answer-json.d.ts
CHANGED
|
@@ -60,7 +60,7 @@ export declare function answerAsServed(output: string, schema: unknown): {
|
|
|
60
60
|
export declare const X_CARRIED = "x-carried";
|
|
61
61
|
/** Why `schema`'s `x-carried` is not a list of unique names of the root's `properties`; undefined when it is, or absent. */
|
|
62
62
|
export declare function carriedProblem(schema: Record<string, unknown>): string | undefined;
|
|
63
|
-
/** The fields `schema` names in `x-carried`,
|
|
64
|
-
*
|
|
63
|
+
/** The fields `schema` names in `x-carried`, read by the save's rule (carriedProblem): undefined for none, or for one the
|
|
64
|
+
* save would refuse, so its run gets the too-large line. */
|
|
65
65
|
export declare function carriedFields(schema: unknown): readonly string[] | undefined;
|
|
66
66
|
export {};
|
package/dist/answer-json.js
CHANGED
|
@@ -156,9 +156,8 @@ export function carriedProblem(schema) {
|
|
|
156
156
|
const unknown = carried.filter((name) => !Object.hasOwn(properties, name));
|
|
157
157
|
return unknown.length ? `names ${unknown.map((name) => JSON.stringify(name)).join(", ")}, which the root's properties have no field for` : undefined;
|
|
158
158
|
}
|
|
159
|
-
/** The fields `schema` names in `x-carried`,
|
|
160
|
-
*
|
|
159
|
+
/** The fields `schema` names in `x-carried`, read by the save's rule (carriedProblem): undefined for none, or for one the
|
|
160
|
+
* save would refuse, so its run gets the too-large line. */
|
|
161
161
|
export function carriedFields(schema) {
|
|
162
|
-
|
|
163
|
-
return Array.isArray(carried) && carried.length > 0 && carried.every((name) => typeof name === "string") ? carried : undefined;
|
|
162
|
+
return isObject(schema) && !carriedProblem(schema) ? schema[X_CARRIED] : undefined;
|
|
164
163
|
}
|
package/dist/archil-routes.d.ts
CHANGED
|
@@ -70,7 +70,7 @@ export declare function createArchilRoutes(options: ArchilRoutesOptions): {
|
|
|
70
70
|
} | null;
|
|
71
71
|
}>;
|
|
72
72
|
checkLaunchDisk: (diskId: string, signal?: AbortSignal) => Promise<void>;
|
|
73
|
-
removeRunFolder: (agentId: string, runId: string, diskId: string) => Promise<void>;
|
|
73
|
+
removeRunFolder: (agentId: string, runId: string, diskId: string, whose?: "launch" | "agent") => Promise<void>;
|
|
74
74
|
};
|
|
75
75
|
export type ArchilRoutes = ReturnType<typeof createArchilRoutes>;
|
|
76
76
|
/** One of the owner's Archil routes at its handler: its answer (sent 200), or an ApiError (sent with its status). An
|
package/dist/archil-routes.js
CHANGED
|
@@ -253,9 +253,10 @@ export function createArchilRoutes(options) {
|
|
|
253
253
|
* so is the folder of a disk Archil says is gone, which has nothing left to delete (one the caller deleted, or the
|
|
254
254
|
* agent's own disk named in the launch, which the agent's delete removed whole before its runs' folders).
|
|
255
255
|
* Archil off, or no account key, is 503 unavailable; a delete Archil refuses (a computer that still holds the folder,
|
|
256
|
-
* Archil not reached) is 424 upstream_failed, what was not deleted left for the next call.
|
|
257
|
-
|
|
258
|
-
|
|
256
|
+
* Archil not reached) is 424 upstream_failed, what was not deleted left for the next call. `whose` "agent": the run is
|
|
257
|
+
* deleted alone (DELETE /runs/{id}), its folder on its agent's own disk, which stays. */
|
|
258
|
+
async function removeRunFolder(agentId, runId, diskId, whose = "launch") {
|
|
259
|
+
const what = `The run ${runId}'s folder on the Archil disk ${diskId}, ${whose === "launch" ? "which its launch named" : "its agent's own"},`;
|
|
259
260
|
const settings = await loadArchilSettings(store, env);
|
|
260
261
|
if (settings === undefined)
|
|
261
262
|
throw new ApiError("unavailable", `${what} is not deleted yet: Archil is off on this server, so it can't be reached. Turn Archil on again (PUT /v2/workspace/archil)`);
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type Tx } from "@earendil-works/pi-durable";
|
|
2
|
+
import type { BrowserSessionUsage } from "@parcha/agentrun-computer";
|
|
3
|
+
import type { EntryLike } from "./timeline/index.js";
|
|
4
|
+
/** The run journal's record of a browser session let go (on the root): see the file's head. */
|
|
5
|
+
export declare const BROWSER_SESSION_ENDED = "agentrun.browser_session_ended";
|
|
6
|
+
/** How long the provider's record is waited for at a release before the session's end is written without it. */
|
|
7
|
+
export declare const PROVIDER_RECORD_TIMEOUT_MS = 5000;
|
|
8
|
+
/** What came of reading the provider's own record: `read`, it answered; `not_offered`, the provider keeps none this
|
|
9
|
+
* server reads; `not_found`, it does not know the session; `failed`, the read failed or timed out; `no_session`, no
|
|
10
|
+
* session was made (its create failed), so there was nothing to read. */
|
|
11
|
+
export type ProviderRecordStatus = "read" | "not_offered" | "not_found" | "failed" | "no_session";
|
|
12
|
+
/** The provider's record as this server keeps it: each field null where the provider does not say it. */
|
|
13
|
+
export type ProviderRecord = {
|
|
14
|
+
started_at: string | null;
|
|
15
|
+
ended_at: string | null;
|
|
16
|
+
proxy_bytes: number | null;
|
|
17
|
+
};
|
|
18
|
+
/** A browser session as the usage read gives it. */
|
|
19
|
+
export type BrowserSessionLine = {
|
|
20
|
+
provider: string;
|
|
21
|
+
/** pi-browser's tag for the session: the run's own name for it, which its charges name too. */
|
|
22
|
+
tag: string;
|
|
23
|
+
/** The provider's id for the session; null when none was made, or its end is not recorded. */
|
|
24
|
+
provider_session_id: string | null;
|
|
25
|
+
/** When this server began opening the session, and when it let it go (null: no end recorded). */
|
|
26
|
+
started_at: string | null;
|
|
27
|
+
ended_at: string | null;
|
|
28
|
+
release_reason: string | null;
|
|
29
|
+
/** The seconds this server charged for the session's time (its BROWSER_CHARGED records), unrounded; null when none
|
|
30
|
+
* was charged (a free provider's, or a session with no charge yet). */
|
|
31
|
+
charged_seconds: number | null;
|
|
32
|
+
provider_record: ProviderRecord | null;
|
|
33
|
+
provider_record_status: ProviderRecordStatus | null;
|
|
34
|
+
};
|
|
35
|
+
/** A session as pi-browser's release tells it (its SessionRecord), only what is recorded. */
|
|
36
|
+
type Released = {
|
|
37
|
+
tag: string;
|
|
38
|
+
resourceId: string | null;
|
|
39
|
+
createdAt: string;
|
|
40
|
+
endedAt: string | null;
|
|
41
|
+
releaseReason: string | null;
|
|
42
|
+
provider: string;
|
|
43
|
+
};
|
|
44
|
+
/** The writer of each session's end, once per session in this process (pi-browser tells a release at least once):
|
|
45
|
+
* the provider's record read first (`usage`, bounded), then the end written on the root (`commit`). It never throws: a
|
|
46
|
+
* session whose end cannot be written is said in `log`, and reads as not ended. */
|
|
47
|
+
export declare function sessionEnds(options: {
|
|
48
|
+
usage: ((id: string, signal?: AbortSignal) => Promise<BrowserSessionUsage | undefined>) | undefined;
|
|
49
|
+
commit: ((change: (tx: Tx) => Promise<void>) => Promise<unknown>) | undefined;
|
|
50
|
+
log?: (line: string) => void;
|
|
51
|
+
timeoutMs?: number;
|
|
52
|
+
}): (session: Released, conversation: number) => Promise<void>;
|
|
53
|
+
/** A run's browser sessions from its journal `entries`, in the order they were opened: one per tag its root names in an
|
|
54
|
+
* open, an end or a charge. The first end recorded for a tag is its end. */
|
|
55
|
+
export declare function browserSessionsOf(entries: readonly EntryLike[]): BrowserSessionLine[];
|
|
56
|
+
export {};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// A run's browser sessions, one record each (GET /runs/{run_id}/usage `browser_sessions`): how long each ran, how it
|
|
2
|
+
// ended, and its provider's id, by which the provider's own dashboard and invoice find it. Two records on the run's root say a session: its open
|
|
3
|
+
// (BROWSER_SESSION_OPEN, written before the provider is asked to create it, browser-cost.ts) and its end
|
|
4
|
+
// (BROWSER_SESSION_ENDED, below, written once pi-browser lets it go). The end carries the provider's session id, when
|
|
5
|
+
// this server saw the session start and end, why it ended, and the provider's own record of it where the provider keeps
|
|
6
|
+
// one (BrowserComputerProvider.sessionUsage: its start, its end, its proxy bytes), read once at that release. The
|
|
7
|
+
// seconds this server charged for it are its BROWSER_CHARGED records', the provider's minimum included where the
|
|
8
|
+
// release topped the session up to it; nothing is priced here. How long it ran is its end less its start.
|
|
9
|
+
//
|
|
10
|
+
// Unknown is never 0. A session with no end record yet (its run's process lost before the release was told) says
|
|
11
|
+
// `ended_at` null; a provider that keeps no record, or one whose read failed, says so (`provider_record_status`) with
|
|
12
|
+
// `provider_record` null; a field the provider's record does not hold is null in it.
|
|
13
|
+
import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
14
|
+
import { BROWSER_CHARGED, BROWSER_SESSION_OPEN } from "./browser-cost.js";
|
|
15
|
+
/** The run journal's record of a browser session let go (on the root): see the file's head. */
|
|
16
|
+
export const BROWSER_SESSION_ENDED = "agentrun.browser_session_ended";
|
|
17
|
+
/** How long the provider's record is waited for at a release before the session's end is written without it. */
|
|
18
|
+
export const PROVIDER_RECORD_TIMEOUT_MS = 5_000;
|
|
19
|
+
/** The writer of each session's end, once per session in this process (pi-browser tells a release at least once):
|
|
20
|
+
* the provider's record read first (`usage`, bounded), then the end written on the root (`commit`). It never throws: a
|
|
21
|
+
* session whose end cannot be written is said in `log`, and reads as not ended. */
|
|
22
|
+
export function sessionEnds(options) {
|
|
23
|
+
const written = new Set();
|
|
24
|
+
const log = options.log ?? ((line) => void process.stderr.write(`agentrun-serve: ${line}\n`));
|
|
25
|
+
return async (session, conversation) => {
|
|
26
|
+
if (written.has(session.tag) || !options.commit)
|
|
27
|
+
return;
|
|
28
|
+
written.add(session.tag);
|
|
29
|
+
const { record, status } = await providerRecord(session.resourceId, options.usage, options.timeoutMs ?? PROVIDER_RECORD_TIMEOUT_MS);
|
|
30
|
+
const data = {
|
|
31
|
+
tag: session.tag,
|
|
32
|
+
conversation,
|
|
33
|
+
provider: session.provider,
|
|
34
|
+
provider_session_id: session.resourceId,
|
|
35
|
+
started_at: session.createdAt,
|
|
36
|
+
ended_at: session.endedAt ?? new Date().toISOString(),
|
|
37
|
+
release_reason: session.releaseReason,
|
|
38
|
+
provider_record: record,
|
|
39
|
+
provider_record_status: status,
|
|
40
|
+
};
|
|
41
|
+
try {
|
|
42
|
+
await options.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: BROWSER_SESSION_ENDED, data })));
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
written.delete(session.tag);
|
|
46
|
+
log(`the end of browser session ${session.tag} was not recorded (${String(error?.message ?? error).slice(0, 200)}): its usage reads it as not ended`);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async function providerRecord(id, usage, timeoutMs) {
|
|
51
|
+
if (id === null)
|
|
52
|
+
return { record: null, status: "no_session" };
|
|
53
|
+
if (!usage)
|
|
54
|
+
return { record: null, status: "not_offered" };
|
|
55
|
+
let timer;
|
|
56
|
+
try {
|
|
57
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
58
|
+
const read = await Promise.race([usage(id, signal), new Promise((resolve) => { timer = setTimeout(() => resolve("late"), timeoutMs); })]);
|
|
59
|
+
if (read === "late")
|
|
60
|
+
return { record: null, status: "failed" };
|
|
61
|
+
if (read === undefined)
|
|
62
|
+
return { record: null, status: "not_found" };
|
|
63
|
+
return { record: { started_at: read.startedAt, ended_at: read.endedAt, proxy_bytes: read.proxyBytes }, status: "read" };
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return { record: null, status: "failed" };
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const text = (value) => (typeof value === "string" ? value : null);
|
|
73
|
+
const count = (value) => (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null);
|
|
74
|
+
const STATUSES = ["read", "not_offered", "not_found", "failed", "no_session"];
|
|
75
|
+
/** A run's browser sessions from its journal `entries`, in the order they were opened: one per tag its root names in an
|
|
76
|
+
* open, an end or a charge. The first end recorded for a tag is its end. */
|
|
77
|
+
export function browserSessionsOf(entries) {
|
|
78
|
+
const sessions = new Map();
|
|
79
|
+
const of = (tag, provider) => {
|
|
80
|
+
let line = sessions.get(tag);
|
|
81
|
+
if (!line) {
|
|
82
|
+
line = { provider, tag, provider_session_id: null, started_at: null, ended_at: null, release_reason: null, charged_seconds: null, provider_record: null, provider_record_status: null };
|
|
83
|
+
sessions.set(tag, line);
|
|
84
|
+
}
|
|
85
|
+
return line;
|
|
86
|
+
};
|
|
87
|
+
const ended = new Set();
|
|
88
|
+
for (const e of entries) {
|
|
89
|
+
const d = (e.data ?? {});
|
|
90
|
+
const tag = text(d.tag);
|
|
91
|
+
if (tag === null)
|
|
92
|
+
continue;
|
|
93
|
+
if (e.kind === BROWSER_SESSION_OPEN)
|
|
94
|
+
of(tag, text(d.provider) ?? "");
|
|
95
|
+
else if (e.kind === BROWSER_CHARGED && d.tool === "browser" && typeof d.seconds === "number" && Number.isFinite(d.seconds)) {
|
|
96
|
+
const line = of(tag, text(d.charged_by) ?? "");
|
|
97
|
+
line.charged_seconds = Math.round(((line.charged_seconds ?? 0) + d.seconds) * 1e6) / 1e6;
|
|
98
|
+
}
|
|
99
|
+
else if (e.kind === BROWSER_SESSION_ENDED && !ended.has(tag)) {
|
|
100
|
+
ended.add(tag);
|
|
101
|
+
const line = of(tag, text(d.provider) ?? "");
|
|
102
|
+
if (line.provider === "")
|
|
103
|
+
line.provider = text(d.provider) ?? "";
|
|
104
|
+
const record = d.provider_record;
|
|
105
|
+
const status = STATUSES.find((one) => one === d.provider_record_status) ?? null;
|
|
106
|
+
Object.assign(line, {
|
|
107
|
+
provider_session_id: text(d.provider_session_id),
|
|
108
|
+
started_at: text(d.started_at),
|
|
109
|
+
ended_at: text(d.ended_at),
|
|
110
|
+
release_reason: text(d.release_reason),
|
|
111
|
+
provider_record: record && typeof record === "object" ? { started_at: text(record.started_at), ended_at: text(record.ended_at), proxy_bytes: count(record.proxy_bytes) } : null,
|
|
112
|
+
provider_record_status: status,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return [...sessions.values()];
|
|
117
|
+
}
|