@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31
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 +238 -0
- package/README.md +739 -116
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +18 -7
- package/dist/agents.js +19 -10
- package/dist/app.js +101 -26
- package/dist/background.d.ts +29 -0
- package/dist/background.js +397 -0
- package/dist/box-egress-vm.d.ts +125 -0
- package/dist/box-egress-vm.js +350 -0
- package/dist/box-egress.d.ts +99 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +1 -1
- package/dist/box-image.js +9 -7
- package/dist/box-relay-vm.d.ts +84 -0
- package/dist/box-relay-vm.js +410 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +28 -5
- package/dist/boxes.js +44 -18
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +130 -21
- package/dist/cap.js +339 -67
- package/dist/cli.js +30 -4
- package/dist/coding-tools.d.ts +7 -3
- package/dist/coding-tools.js +16 -10
- package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
- package/dist/console/assets/index-CnJBf7Lc.js +486 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-rows.d.ts +11 -3
- package/dist/decision-rows.js +18 -11
- package/dist/decisions.d.ts +3 -3
- package/dist/decisions.js +4 -3
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +9 -1
- package/dist/files.js +10 -2
- package/dist/grade.d.ts +11 -11
- package/dist/grade.js +43 -55
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +7 -5
- package/dist/graph-view.js +10 -3
- package/dist/harness-app.d.ts +4 -2
- package/dist/harness-app.js +110 -19
- 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 +4 -1
- package/dist/harness.js +5 -2
- package/dist/host-check.d.ts +12 -0
- package/dist/host-check.js +34 -0
- package/dist/host-tools.d.ts +12 -2
- package/dist/host-tools.js +26 -12
- package/dist/host.js +6 -2
- package/dist/hosted-search.js +5 -1
- package/dist/import.d.ts +2 -2
- package/dist/import.js +4 -3
- package/dist/key-check.d.ts +3 -2
- package/dist/key-check.js +7 -3
- package/dist/key-refusal.js +8 -4
- package/dist/key-words.d.ts +37 -0
- package/dist/key-words.js +40 -0
- package/dist/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +6 -2
- package/dist/learn/grade.js +28 -14
- package/dist/learn/index.d.ts +3 -3
- package/dist/learn/index.js +3 -3
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +53 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +19 -4
- package/dist/learn/skills.js +95 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +30 -1
- package/dist/learning-routes.js +173 -19
- package/dist/learning-run.d.ts +8 -6
- package/dist/learning-run.js +70 -27
- package/dist/learning-words.d.ts +12 -5
- package/dist/learning-words.js +34 -13
- package/dist/learning.d.ts +52 -3
- package/dist/learning.js +204 -4
- package/dist/mcp-gateway.d.ts +96 -0
- package/dist/mcp-gateway.js +408 -0
- package/dist/mcp-meta.d.ts +17 -0
- package/dist/mcp-meta.js +38 -0
- package/dist/mcp-servers.d.ts +33 -9
- package/dist/mcp-servers.js +58 -10
- package/dist/mcp.js +5 -5
- package/dist/model.d.ts +13 -11
- package/dist/model.js +11 -10
- package/dist/openapi/agentrun-v2.openapi.json +1 -0
- package/dist/openapi.js +407 -54
- package/dist/page.d.ts +2 -0
- package/dist/page.js +3 -0
- package/dist/paid-calls.d.ts +5 -1
- package/dist/paid-calls.js +1 -1
- package/dist/pause.d.ts +2 -0
- package/dist/place.d.ts +29 -5
- package/dist/place.js +51 -11
- package/dist/print.d.ts +7 -0
- package/dist/print.js +13 -0
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +38 -8
- package/dist/request-start.d.ts +12 -4
- package/dist/request-start.js +139 -15
- package/dist/run-box.d.ts +56 -4
- package/dist/run-box.js +183 -23
- package/dist/runnable.d.ts +13 -3
- package/dist/runnable.js +63 -6
- package/dist/runs.d.ts +266 -37
- package/dist/runs.js +884 -90
- package/dist/secrets.d.ts +27 -0
- package/dist/secrets.js +38 -2
- package/dist/server.d.ts +141 -36
- package/dist/server.js +562 -118
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +16 -4
- package/dist/skills.js +35 -7
- package/dist/stats.d.ts +7 -2
- package/dist/stats.js +28 -7
- package/dist/tool-gate.d.ts +281 -0
- package/dist/tool-gate.js +585 -0
- package/dist/tool-keys.d.ts +48 -11
- package/dist/tool-keys.js +46 -8
- package/dist/tool-plane.d.ts +116 -27
- package/dist/tool-plane.js +232 -50
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +148 -26
- 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 +3 -2
- package/dist/turn-end.js +3 -2
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +11 -2
- package/dist/web-fetch.js +3 -3
- package/dist/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +16 -14
- package/dist/console/assets/index-BN7oVcO4.js +0 -445
- package/dist/console/assets/index-By-jkqki.css +0 -1
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
export declare const SIGN_INS_DIR = "sign-ins";
|
|
2
|
+
/** The one saved profile an agent keeps per vendor. */
|
|
3
|
+
export declare const SIGN_IN_KEY = "default";
|
|
4
|
+
/** The file a run's process writes in its run directory when a session that saved to its sign-in let go: when the
|
|
5
|
+
* lease ends, its time is the sign-in's `verified_at`. A time, never a pointer. */
|
|
6
|
+
export declare const SIGN_IN_SAVED = "sign-in-saved";
|
|
7
|
+
export type Vendor = "browserbase" | "kernel";
|
|
8
|
+
/** What a run's process is handed: the vendor, the pointer it opens (a context id, a profile name), and whether it saves. */
|
|
9
|
+
export type HandedSignIn = {
|
|
10
|
+
provider: Vendor;
|
|
11
|
+
ref: string;
|
|
12
|
+
save: boolean;
|
|
13
|
+
};
|
|
14
|
+
/** A sign-in as GET /agents/{id} shows it (the contract's SignIn): never its ref. `unreadable` (this server's own state):
|
|
15
|
+
* its pointer does not open under this server's seal key (none now, or another), so no run starts from it and none is
|
|
16
|
+
* made in its place until it is forgotten (DELETE); `held_by` names a run that still holds its lease. */
|
|
17
|
+
export type SignInView = {
|
|
18
|
+
key: string;
|
|
19
|
+
provider: Vendor;
|
|
20
|
+
state: "ready" | "held" | "unreadable";
|
|
21
|
+
held_by: string | null;
|
|
22
|
+
verified_at: string | null;
|
|
23
|
+
};
|
|
24
|
+
/** The vendor's side: make an agent's object (its pointer), and delete one. */
|
|
25
|
+
export type Vendors = {
|
|
26
|
+
create(vendor: Vendor): Promise<string>;
|
|
27
|
+
remove(vendor: Vendor, ref: string): Promise<void>;
|
|
28
|
+
};
|
|
29
|
+
/** Browserbase writes a saved context back after its session ends (pi-browser waits profileSettleMs, 5 s, for it), so
|
|
30
|
+
* its saver's lease outlasts the run's end by twice that: a run started meanwhile neither saves over it. A bound this
|
|
31
|
+
* server chose; Browserbase publishes none. */
|
|
32
|
+
export declare const BROWSERBASE_SETTLE_MS = 10000;
|
|
33
|
+
/** How long a lease outlives its holder's process: pi-browser's default session timeout (DEFAULT_BROWSER_POLICY's
|
|
34
|
+
* sessionTimeoutS, 1800 s), which every session a run opens is created under, so none it opened before its process
|
|
35
|
+
* went can still write back after it. A holder that comes back (its relaunch) holds the lease again from then on. */
|
|
36
|
+
export declare const GONE_LEASE_MS = 1800000;
|
|
37
|
+
/** The vendor a run's browser resolves to (its plane's `browser`) keeps a sign-in for: Browserbase's and Kernel's; local
|
|
38
|
+
* Chrome is refused by name; an unavailable browser has none. */
|
|
39
|
+
export declare function vendorOf(resolution: string): Vendor | undefined;
|
|
40
|
+
export declare class SignIns {
|
|
41
|
+
private readonly data;
|
|
42
|
+
private readonly key;
|
|
43
|
+
private readonly vendors;
|
|
44
|
+
private readonly holds;
|
|
45
|
+
/** One read-modify-write at a time per agent; an agent's queue goes once it is empty. */
|
|
46
|
+
private readonly chains;
|
|
47
|
+
private readonly now;
|
|
48
|
+
private readonly writeFile;
|
|
49
|
+
private readonly sleep;
|
|
50
|
+
/** `holds(run)`: whether that run has not ended, so a lease it names still holds; `now` and `sleep`, the clock, and
|
|
51
|
+
* `write`, the durable write (writeDurable), the tests'. */
|
|
52
|
+
constructor(data: string, key: Buffer | undefined, vendors: Vendors, holds: (runId: string) => Promise<boolean>, options?: {
|
|
53
|
+
now?: () => number;
|
|
54
|
+
sleep?: (ms: number) => Promise<void>;
|
|
55
|
+
write?: (path: string, text: string) => Promise<unknown>;
|
|
56
|
+
});
|
|
57
|
+
/** Whether sign-ins are kept here: never without a seal key, never in the clear. */
|
|
58
|
+
get available(): boolean;
|
|
59
|
+
private file;
|
|
60
|
+
private read;
|
|
61
|
+
private write;
|
|
62
|
+
private locked;
|
|
63
|
+
/** Whether `entry`'s lease still holds: it names a run that has not ended; or, once its process was found gone, that
|
|
64
|
+
* went less than GONE_LEASE_MS ago, ended or not (a run waiting on its person with no process, or one that crashed and
|
|
65
|
+
* ended, is never let go otherwise, or let go too soon). */
|
|
66
|
+
private held;
|
|
67
|
+
/** `entry`'s pointer, opened under this server's seal key; undefined when it does not open (none now, or another). */
|
|
68
|
+
private open;
|
|
69
|
+
/** The agent's sign-ins, as the contract shows them: never a ref. */
|
|
70
|
+
view(agentId: string): Promise<SignInView[]>;
|
|
71
|
+
/** The sign-in run `runId` of `agentId` starts from on `resolution` (its plane's browser): made at the vendor when the
|
|
72
|
+
* agent has none, then leased to this run to save, unless another run of the agent holds the lease. None for a
|
|
73
|
+
* browser that keeps none, or with no seal key. */
|
|
74
|
+
forRun(agentId: string, runId: string, resolution: string): Promise<HandedSignIn | undefined>;
|
|
75
|
+
/** Run `runId`'s process was found gone: a lease it holds counts from now, while it does not come back (held). */
|
|
76
|
+
markGone(agentId: string, runId: string): Promise<void>;
|
|
77
|
+
/** Ends the lease run `runId` holds, if it holds one: it ended, or let go to wait for its person; one whose process did
|
|
78
|
+
* not let its sessions go (`clean` false) keeps it until the gone rule ends it. A session of it that saved (its
|
|
79
|
+
* run directory's SIGN_IN_SAVED) makes that the sign-in's `verified_at`. */
|
|
80
|
+
release(agentId: string, runId: string, runDir: string, clean?: boolean): Promise<void>;
|
|
81
|
+
/** DELETE /agents/{id}/sign-ins/{key}: each vendor's object deleted (best effort: what failed is said), then the
|
|
82
|
+
* pointer. 404 for a key the agent has none of; 409 while a run holds it. */
|
|
83
|
+
forget(agentId: string, signInKey: string): Promise<{
|
|
84
|
+
key: string;
|
|
85
|
+
removed: Array<{
|
|
86
|
+
provider: Vendor;
|
|
87
|
+
at_vendor: "deleted" | "not_deleted";
|
|
88
|
+
message?: string;
|
|
89
|
+
}>;
|
|
90
|
+
}>;
|
|
91
|
+
}
|
|
92
|
+
/** The vendors over their REST APIs, with the server's keys (`env`, read at each call) through `fetchFor` (the tests'
|
|
93
|
+
* fakes under faux). Browserbase: a context made for the agent (POST /v1/contexts, which opens no session; Browserbase
|
|
94
|
+
* bills a session's browser time and proxy data), deleted with DELETE /v1/contexts/{id}. Kernel: a profile made under a
|
|
95
|
+
* random name (POST /profiles, which starts no browser; Kernel bills a browser's running time), since a profile name
|
|
96
|
+
* is the account's, so one derived from the agent would be any server's on that account; deleted with DELETE
|
|
97
|
+
* /profiles/{name}. The name is the pointer, sealed as a context id is, and well inside pi-browser's 64 characters. A
|
|
98
|
+
* 404 on delete is gone already. */
|
|
99
|
+
export declare function vendorsOver(env: () => NodeJS.ProcessEnv, fetchFor: (vendor: Vendor) => Promise<typeof fetch | undefined>): Vendors;
|
package/dist/sign-ins.js
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// An agent's saved sign-ins: the browser it signed in with stays signed in for its later runs. The cookies stay at the
|
|
2
|
+
// browser's vendor (a Browserbase context, a Kernel profile); this server keeps only a pointer to that object per agent,
|
|
3
|
+
// in DATA/homes/<home key>/sign-ins/sign-ins.json (a host-owned folder: the home API neither reads nor writes it, and no
|
|
4
|
+
// run's tools see it), each pointer sealed under the seal key tool keys are kept under (AGENTRUN_SEAL_KEY), bound to its
|
|
5
|
+
// agent, key and vendor. One saved profile per agent per vendor, keyed `default`; the host picks it, never the model.
|
|
6
|
+
// The server resolves the pointer before a run's launch and hands the run the pointer over its secrets' pipe, never its
|
|
7
|
+
// environment: the run's process never gets the seal key. Local Chrome keeps none (its cookies would sit on this disk).
|
|
8
|
+
//
|
|
9
|
+
// Saving is leased across runs: each run is its own process, so pi-browser's one-saver rule (per process) cannot see
|
|
10
|
+
// two runs of one agent. The first run of the agent to start with the browser holds the lease and its sessions save;
|
|
11
|
+
// a run started while another holds it starts from the same sign-in and saves nothing. The lease ends when its run
|
|
12
|
+
// ends, or lets go cleanly to wait for its person (runs.ts); a relaunch or a restart keeps it, since a session the run
|
|
13
|
+
// opened before its process went may still write back. One whose run has ended since (a server down first) is stale.
|
|
14
|
+
import { randomBytes } from "node:crypto";
|
|
15
|
+
import { lstat, mkdir, readFile, rm } from "node:fs/promises";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { seal, unseal } from "@parcha/pi-durable-agent";
|
|
18
|
+
import { ApiError } from "./errors.js";
|
|
19
|
+
import { homeOf, serialBy, writeDurable } from "./files.js";
|
|
20
|
+
export const SIGN_INS_DIR = "sign-ins";
|
|
21
|
+
const FILE = "sign-ins.json";
|
|
22
|
+
const FORMAT = "sign-ins/1";
|
|
23
|
+
/** The one saved profile an agent keeps per vendor. */
|
|
24
|
+
export const SIGN_IN_KEY = "default";
|
|
25
|
+
/** The file a run's process writes in its run directory when a session that saved to its sign-in let go: when the
|
|
26
|
+
* lease ends, its time is the sign-in's `verified_at`. A time, never a pointer. */
|
|
27
|
+
export const SIGN_IN_SAVED = "sign-in-saved";
|
|
28
|
+
/** Browserbase writes a saved context back after its session ends (pi-browser waits profileSettleMs, 5 s, for it), so
|
|
29
|
+
* its saver's lease outlasts the run's end by twice that: a run started meanwhile neither saves over it. A bound this
|
|
30
|
+
* server chose; Browserbase publishes none. */
|
|
31
|
+
export const BROWSERBASE_SETTLE_MS = 10_000;
|
|
32
|
+
/** How long a lease outlives its holder's process: pi-browser's default session timeout (DEFAULT_BROWSER_POLICY's
|
|
33
|
+
* sessionTimeoutS, 1800 s), which every session a run opens is created under, so none it opened before its process
|
|
34
|
+
* went can still write back after it. A holder that comes back (its relaunch) holds the lease again from then on. */
|
|
35
|
+
export const GONE_LEASE_MS = 1_800_000;
|
|
36
|
+
/** The vendor a run's browser resolves to (its plane's `browser`) keeps a sign-in for: Browserbase's and Kernel's; local
|
|
37
|
+
* Chrome is refused by name; an unavailable browser has none. */
|
|
38
|
+
export function vendorOf(resolution) {
|
|
39
|
+
if (resolution === "browserbase" || resolution === "kernel")
|
|
40
|
+
return resolution;
|
|
41
|
+
if (resolution === "chrome" || resolution === "cdp")
|
|
42
|
+
throw new Error("a local Chrome keeps no saved sign-in: its cookies would sit on this server's disk");
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const aad = (agentId, entry) => `${FORMAT}|${agentId}|${entry.key}|${entry.provider}`;
|
|
46
|
+
export class SignIns {
|
|
47
|
+
data;
|
|
48
|
+
key;
|
|
49
|
+
vendors;
|
|
50
|
+
holds;
|
|
51
|
+
/** One read-modify-write at a time per agent; an agent's queue goes once it is empty. */
|
|
52
|
+
chains = new Map();
|
|
53
|
+
now;
|
|
54
|
+
writeFile;
|
|
55
|
+
sleep;
|
|
56
|
+
/** `holds(run)`: whether that run has not ended, so a lease it names still holds; `now` and `sleep`, the clock, and
|
|
57
|
+
* `write`, the durable write (writeDurable), the tests'. */
|
|
58
|
+
constructor(data, key, vendors, holds, options = {}) {
|
|
59
|
+
this.data = data;
|
|
60
|
+
this.key = key;
|
|
61
|
+
this.vendors = vendors;
|
|
62
|
+
this.holds = holds;
|
|
63
|
+
this.now = options.now ?? Date.now;
|
|
64
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
|
|
65
|
+
this.writeFile = options.write ?? writeDurable;
|
|
66
|
+
}
|
|
67
|
+
/** Whether sign-ins are kept here: never without a seal key, never in the clear. */
|
|
68
|
+
get available() {
|
|
69
|
+
return this.key !== undefined;
|
|
70
|
+
}
|
|
71
|
+
file(agentId) {
|
|
72
|
+
return join(homeOf(this.data, agentId), SIGN_INS_DIR, FILE);
|
|
73
|
+
}
|
|
74
|
+
async read(agentId) {
|
|
75
|
+
const text = await readFile(this.file(agentId), "utf8").catch((error) => (error.code === "ENOENT" ? null : Promise.reject(error)));
|
|
76
|
+
if (text === null)
|
|
77
|
+
return [];
|
|
78
|
+
const stored = JSON.parse(text);
|
|
79
|
+
if (stored?.format !== FORMAT || !Array.isArray(stored.sign_ins))
|
|
80
|
+
throw new Error(`${FILE} is not a ${FORMAT} file, so it was left as it is`);
|
|
81
|
+
return stored.sign_ins;
|
|
82
|
+
}
|
|
83
|
+
async write(agentId, entries) {
|
|
84
|
+
const dir = join(homeOf(this.data, agentId), SIGN_INS_DIR);
|
|
85
|
+
if (!entries.length)
|
|
86
|
+
return void (await rm(this.file(agentId), { force: true }));
|
|
87
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
88
|
+
if ((await lstat(dir)).isSymbolicLink())
|
|
89
|
+
throw new Error(`${SIGN_INS_DIR}/ is a link, which this server never follows`);
|
|
90
|
+
// Synced before it answers: a pointer to a vendor object just made survives a crash of the machine.
|
|
91
|
+
await this.writeFile(this.file(agentId), `${JSON.stringify({ format: FORMAT, sign_ins: entries })}\n`);
|
|
92
|
+
}
|
|
93
|
+
locked(agentId, work) {
|
|
94
|
+
return serialBy(this.chains, agentId, work);
|
|
95
|
+
}
|
|
96
|
+
/** Whether `entry`'s lease still holds: it names a run that has not ended; or, once its process was found gone, that
|
|
97
|
+
* went less than GONE_LEASE_MS ago, ended or not (a run waiting on its person with no process, or one that crashed and
|
|
98
|
+
* ended, is never let go otherwise, or let go too soon). */
|
|
99
|
+
async held(entry) {
|
|
100
|
+
if (entry.held_by === null)
|
|
101
|
+
return false;
|
|
102
|
+
if (entry.held_until)
|
|
103
|
+
return this.now() < Date.parse(entry.held_until);
|
|
104
|
+
// A Browserbase session that lived out the timeout still writes its context back after it ends; Kernel's browser
|
|
105
|
+
// ends at its idle timeout and saves as it ends, so it needs no margin.
|
|
106
|
+
// Once its process is found gone, that alone decides, whether its run has ended since or not: a session it left
|
|
107
|
+
// live may still write back until then.
|
|
108
|
+
if (entry.gone_at)
|
|
109
|
+
return this.now() - Date.parse(entry.gone_at) < GONE_LEASE_MS + (entry.provider === "browserbase" ? BROWSERBASE_SETTLE_MS : 0);
|
|
110
|
+
return this.holds(entry.held_by).catch(() => true);
|
|
111
|
+
}
|
|
112
|
+
/** `entry`'s pointer, opened under this server's seal key; undefined when it does not open (none now, or another). */
|
|
113
|
+
open(agentId, entry) {
|
|
114
|
+
if (!this.key)
|
|
115
|
+
return undefined;
|
|
116
|
+
try {
|
|
117
|
+
return unseal(this.key, Buffer.from(entry.ref, "base64"), aad(agentId, entry)).toString("utf8");
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/** The agent's sign-ins, as the contract shows them: never a ref. */
|
|
124
|
+
async view(agentId) {
|
|
125
|
+
const entries = await this.read(agentId).catch(() => []);
|
|
126
|
+
return Promise.all(entries.map(async (entry) => {
|
|
127
|
+
const held = await this.held(entry);
|
|
128
|
+
// Unreadable or not, a run that holds its lease is named: forget is refused until it ends.
|
|
129
|
+
if (this.open(agentId, entry) === undefined)
|
|
130
|
+
return { key: entry.key, provider: entry.provider, state: "unreadable", held_by: held ? entry.held_by : null, verified_at: entry.verified_at };
|
|
131
|
+
return { key: entry.key, provider: entry.provider, state: held ? "held" : "ready", held_by: held ? entry.held_by : null, verified_at: entry.verified_at };
|
|
132
|
+
}));
|
|
133
|
+
}
|
|
134
|
+
/** The sign-in run `runId` of `agentId` starts from on `resolution` (its plane's browser): made at the vendor when the
|
|
135
|
+
* agent has none, then leased to this run to save, unless another run of the agent holds the lease. None for a
|
|
136
|
+
* browser that keeps none, or with no seal key. */
|
|
137
|
+
async forRun(agentId, runId, resolution) {
|
|
138
|
+
const vendor = vendorOf(resolution);
|
|
139
|
+
if (!vendor || !this.key)
|
|
140
|
+
return undefined;
|
|
141
|
+
const key = this.key;
|
|
142
|
+
// The Browserbase saver itself, resumed while its last save is still being written back (held_until): it waits that
|
|
143
|
+
// out, at most BROWSERBASE_SETTLE_MS, before it is handed save again, so no session of it opens on a context in flux.
|
|
144
|
+
const mine = (await this.read(agentId).catch(() => [])).find((e) => e.key === SIGN_IN_KEY && e.provider === vendor && e.held_by === runId && e.held_until);
|
|
145
|
+
const rest = mine ? Date.parse(mine.held_until) - this.now() : 0;
|
|
146
|
+
if (rest > 0)
|
|
147
|
+
await this.sleep(Math.min(rest, BROWSERBASE_SETTLE_MS));
|
|
148
|
+
return this.locked(agentId, async () => {
|
|
149
|
+
const entries = await this.read(agentId);
|
|
150
|
+
let entry = entries.find((e) => e.key === SIGN_IN_KEY && e.provider === vendor);
|
|
151
|
+
let ref;
|
|
152
|
+
let made = false;
|
|
153
|
+
if (entry) {
|
|
154
|
+
// Never replaced by itself: the vendor's object it points to would be left behind, holding the agent's cookies.
|
|
155
|
+
ref = this.open(agentId, entry);
|
|
156
|
+
if (ref === undefined)
|
|
157
|
+
throw new Error(`its saved sign-in does not open under this server's seal key: forget it (DELETE /v2/agents/${agentId}/sign-ins/${SIGN_IN_KEY}) and its next run signs in afresh`);
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
ref = await this.vendors.create(vendor);
|
|
161
|
+
made = true;
|
|
162
|
+
entry = { key: SIGN_IN_KEY, provider: vendor, ref: "", verified_at: null, held_by: null };
|
|
163
|
+
entry.ref = seal(key, Buffer.from(ref, "utf8"), aad(agentId, entry)).toString("base64");
|
|
164
|
+
entries.push(entry);
|
|
165
|
+
}
|
|
166
|
+
const save = entry.held_by === runId || !(await this.held(entry));
|
|
167
|
+
if (save)
|
|
168
|
+
Object.assign(entry, { held_by: runId, gone_at: null, held_until: null });
|
|
169
|
+
try {
|
|
170
|
+
await this.write(agentId, entries);
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
// Never kept, so never forgotten: the object just made goes at the vendor now, as far as it answers. Unless the
|
|
174
|
+
// write landed and only what follows it failed (the folder's sync): then the pointer is kept, and so is its object.
|
|
175
|
+
const sealed = entry.ref;
|
|
176
|
+
const kept = await this.read(agentId).then((now) => now.some((e) => e.ref === sealed), () => false);
|
|
177
|
+
if (made && !kept)
|
|
178
|
+
await this.vendors.remove(vendor, ref).catch(() => undefined);
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
return { provider: vendor, ref, save };
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/** Run `runId`'s process was found gone: a lease it holds counts from now, while it does not come back (held). */
|
|
185
|
+
markGone(agentId, runId) {
|
|
186
|
+
return this.locked(agentId, async () => {
|
|
187
|
+
const entries = await this.read(agentId);
|
|
188
|
+
const mine = entries.filter((entry) => entry.held_by === runId && !entry.gone_at && !entry.held_until);
|
|
189
|
+
if (!mine.length)
|
|
190
|
+
return;
|
|
191
|
+
for (const entry of mine)
|
|
192
|
+
entry.gone_at = new Date(this.now()).toISOString();
|
|
193
|
+
await this.write(agentId, entries);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/** Ends the lease run `runId` holds, if it holds one: it ended, or let go to wait for its person; one whose process did
|
|
197
|
+
* not let its sessions go (`clean` false) keeps it until the gone rule ends it. A session of it that saved (its
|
|
198
|
+
* run directory's SIGN_IN_SAVED) makes that the sign-in's `verified_at`. */
|
|
199
|
+
release(agentId, runId, runDir, clean = true) {
|
|
200
|
+
return this.locked(agentId, async () => {
|
|
201
|
+
const marker = join(runDir, SIGN_IN_SAVED);
|
|
202
|
+
const saved = await readFile(marker, "utf8").then((text) => text.trim(), () => undefined);
|
|
203
|
+
const entries = await this.read(agentId);
|
|
204
|
+
const mine = entries.filter((entry) => entry.held_by === runId && !entry.held_until);
|
|
205
|
+
if (mine.length) {
|
|
206
|
+
const when = saved && !Number.isNaN(Date.parse(saved)) ? new Date(saved).toISOString() : undefined;
|
|
207
|
+
const now = new Date(this.now()).toISOString();
|
|
208
|
+
// `clean`: its process let its sessions go. One that crashed may have left a session live at the vendor, which
|
|
209
|
+
// writes back when it ends: the lease stays named for it, and the gone rule (held) ends it.
|
|
210
|
+
// A Browserbase session that saved is still being written back: the lease waits that out, named for this run.
|
|
211
|
+
for (const entry of mine)
|
|
212
|
+
Object.assign(entry, !clean ? { gone_at: entry.gone_at ?? now } : { gone_at: null, ...(when && entry.provider === "browserbase" ? { held_until: new Date(this.now() + BROWSERBASE_SETTLE_MS).toISOString() } : { held_by: null, held_until: null }) }, when ? { verified_at: when } : {});
|
|
213
|
+
await this.write(agentId, entries);
|
|
214
|
+
}
|
|
215
|
+
await rm(marker, { force: true });
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
/** DELETE /agents/{id}/sign-ins/{key}: each vendor's object deleted (best effort: what failed is said), then the
|
|
219
|
+
* pointer. 404 for a key the agent has none of; 409 while a run holds it. */
|
|
220
|
+
forget(agentId, signInKey) {
|
|
221
|
+
return this.locked(agentId, async () => {
|
|
222
|
+
const entries = await this.read(agentId);
|
|
223
|
+
const named = entries.filter((entry) => entry.key === signInKey);
|
|
224
|
+
if (!named.length)
|
|
225
|
+
throw new ApiError("not_found", `The agent ${agentId} has no sign-in ${signInKey}.`);
|
|
226
|
+
for (const entry of named)
|
|
227
|
+
if (await this.held(entry))
|
|
228
|
+
throw new ApiError("sign_in_held", `The sign-in ${signInKey} is held by the run ${entry.held_by}, which may still save to it: forget it once that run ends.`, { details: { held_by: entry.held_by } });
|
|
229
|
+
const removed = [];
|
|
230
|
+
for (const entry of named) {
|
|
231
|
+
const ref = this.open(agentId, entry);
|
|
232
|
+
const gone = ref === undefined ? new Error("its pointer does not open under this server's seal key") : await this.vendors.remove(entry.provider, ref).then(() => undefined, (error) => error);
|
|
233
|
+
removed.push({ provider: entry.provider, at_vendor: gone ? "not_deleted" : "deleted", ...(gone ? { message: `Not deleted at ${entry.provider}: ${gone.message}. This server no longer points to it.` } : {}) });
|
|
234
|
+
}
|
|
235
|
+
await this.write(agentId, entries.filter((entry) => entry.key !== signInKey));
|
|
236
|
+
return { key: signInKey, removed };
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const base = (set, fallback) => (set?.trim() || fallback).replace(/\/+$/, "");
|
|
241
|
+
/** The vendors over their REST APIs, with the server's keys (`env`, read at each call) through `fetchFor` (the tests'
|
|
242
|
+
* fakes under faux). Browserbase: a context made for the agent (POST /v1/contexts, which opens no session; Browserbase
|
|
243
|
+
* bills a session's browser time and proxy data), deleted with DELETE /v1/contexts/{id}. Kernel: a profile made under a
|
|
244
|
+
* random name (POST /profiles, which starts no browser; Kernel bills a browser's running time), since a profile name
|
|
245
|
+
* is the account's, so one derived from the agent would be any server's on that account; deleted with DELETE
|
|
246
|
+
* /profiles/{name}. The name is the pointer, sealed as a context id is, and well inside pi-browser's 64 characters. A
|
|
247
|
+
* 404 on delete is gone already. */
|
|
248
|
+
export function vendorsOver(env, fetchFor) {
|
|
249
|
+
const call = async (vendor, method, url, headers, body) => {
|
|
250
|
+
const fetcher = await fetchFor(vendor);
|
|
251
|
+
if (!fetcher)
|
|
252
|
+
throw new Error(`this server has no ${vendor} to call`);
|
|
253
|
+
// Fetch's own words name the URL, which holds the pointer on a delete (a base URL with no scheme fails to parse with
|
|
254
|
+
// it): only the error's kind is said, never its message.
|
|
255
|
+
const res = await fetcher(url, { method, headers: { ...headers, ...(body ? { "content-type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}), redirect: "manual", signal: AbortSignal.timeout(20_000) }).catch((error) => {
|
|
256
|
+
throw new Error(`${vendor} unreachable (${error instanceof Error ? error.name : "Error"})`);
|
|
257
|
+
});
|
|
258
|
+
if (!res.ok && !(method === "DELETE" && res.status === 404))
|
|
259
|
+
throw new Error(`${vendor} answered ${res.status}`);
|
|
260
|
+
return res;
|
|
261
|
+
};
|
|
262
|
+
const bb = (e) => ({ url: base(e.BROWSERBASE_BASE_URL, "https://api.browserbase.com"), headers: { "x-bb-api-key": e.BROWSERBASE_API_KEY ?? "" } });
|
|
263
|
+
const kernel = (e) => ({ url: base(e.KERNEL_BASE_URL, "https://api.onkernel.com"), headers: { authorization: `Bearer ${e.KERNEL_API_KEY ?? ""}` } });
|
|
264
|
+
return {
|
|
265
|
+
async create(vendor) {
|
|
266
|
+
if (vendor === "kernel") {
|
|
267
|
+
const { url, headers } = kernel(env());
|
|
268
|
+
const name = `agentrun-${randomBytes(12).toString("hex")}`;
|
|
269
|
+
const made = (await (await call(vendor, "POST", `${url}/profiles`, headers, { name })).json()).name;
|
|
270
|
+
if (made !== name)
|
|
271
|
+
throw new Error("kernel answered another profile than the one asked for");
|
|
272
|
+
return name;
|
|
273
|
+
}
|
|
274
|
+
const e = env();
|
|
275
|
+
const { url, headers } = bb(e);
|
|
276
|
+
// Behind a proxy (a base URL set) the project is the key's, as pi-browser's provider has it; a direct key names it.
|
|
277
|
+
const project = e.BROWSERBASE_BASE_URL || e.BROWSERBASE_CONNECT_BASE_URL ? {} : { projectId: e.BROWSERBASE_PROJECT_ID };
|
|
278
|
+
const id = (await (await call(vendor, "POST", `${url}/v1/contexts`, headers, project)).json()).id;
|
|
279
|
+
if (typeof id !== "string" || !id)
|
|
280
|
+
throw new Error("browserbase answered no context id");
|
|
281
|
+
return id;
|
|
282
|
+
},
|
|
283
|
+
async remove(vendor, ref) {
|
|
284
|
+
const { url, headers } = vendor === "kernel" ? kernel(env()) : bb(env());
|
|
285
|
+
await call(vendor, "DELETE", `${url}/${vendor === "kernel" ? "profiles" : "v1/contexts"}/${encodeURIComponent(ref)}`, headers);
|
|
286
|
+
},
|
|
287
|
+
};
|
|
288
|
+
}
|
package/dist/skills.d.ts
CHANGED
|
@@ -8,8 +8,17 @@ export type SkillFiles = {
|
|
|
8
8
|
export type SkillCheck = (skills: readonly SkillFiles[]) => string[];
|
|
9
9
|
/** The most skill files read at once, so a run with many skill files stays under a low open-file limit. */
|
|
10
10
|
export declare const READS_AT_ONCE = 16;
|
|
11
|
-
/** The
|
|
12
|
-
export declare
|
|
11
|
+
/** The tools that read a file in the run's work/: a run with one is told where each skill is and reads it when it fits. */
|
|
12
|
+
export declare const READING_TOOLS: readonly string[];
|
|
13
|
+
/** Whether a run with `tools` reads its own files, so its skills can be given on demand. */
|
|
14
|
+
export declare const readsFiles: (tools: readonly string[]) => boolean;
|
|
15
|
+
/** The line before the skills a run reads on demand. */
|
|
16
|
+
export declare const ON_DEMAND = "Your skills follow: each one's name, what it is for and its file. When one fits the step you are on, read its SKILL.md whole before you act, and follow it; the files it names are in its folder.";
|
|
17
|
+
/** The revision's instructions, then each skill's `<name>/SKILL.md` from the run's workspace, by name: whole, or, with
|
|
18
|
+
* `onDemand` (the run reads its files: readsFiles), as a line naming it, what it is for and its path. */
|
|
19
|
+
export declare function promptOf(instructions: string, skillFiles: Iterable<string>, work: string, { onDemand }?: {
|
|
20
|
+
onDemand?: boolean;
|
|
21
|
+
}): Promise<string>;
|
|
13
22
|
/**
|
|
14
23
|
* The revision's skills, by name, each with its files' text from the run's workspace (`work`). A file goes to the nearest
|
|
15
24
|
* skill above it (`team/review/checklist.md` to `team/review` when there is a `team/review/SKILL.md`, else to `team`); a
|
|
@@ -24,8 +33,11 @@ export declare function splitSkills(skills: readonly SkillFiles[], check: SkillC
|
|
|
24
33
|
inlined: SkillFiles[];
|
|
25
34
|
};
|
|
26
35
|
/** A run's system prompt, and the skills its harness loads itself. With the harness's `check`, the skills it takes are
|
|
27
|
-
* its own and leave the prompt; with none,
|
|
28
|
-
|
|
36
|
+
* its own and leave the prompt, and the ones it refuses stay inlined; with none, the skills are as promptOf gives them
|
|
37
|
+
* (on demand, with `onDemand`). */
|
|
38
|
+
export declare function systemOf(instructions: string, skillFiles: Iterable<string>, work: string, check?: SkillCheck, { onDemand }?: {
|
|
39
|
+
onDemand?: boolean;
|
|
40
|
+
}): Promise<{
|
|
29
41
|
system: string;
|
|
30
42
|
native: SkillFiles[];
|
|
31
43
|
}>;
|
package/dist/skills.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
// A revision's skills as a run's harness gets them. pi and codex
|
|
1
|
+
// A revision's skills as a run's harness gets them. pi and codex, when the run can read its files (a `read` or `bash`
|
|
2
|
+
// tool), get each skill's name, what it is for and its SKILL.md's path in the system prompt, and read the SKILL.md when
|
|
3
|
+
// it fits the step they are on (on demand); a run that cannot read files gets every skill's SKILL.md inlined there.
|
|
2
4
|
// claude-agent loads skills itself (its Skill tool, from a local plugin the adapter writes): it gets each skill whole, every
|
|
3
5
|
// file of it, and the prompt keeps only the skills its adapter would refuse. The adapter's own check (its exported
|
|
4
6
|
// skillProblems) says which: serve takes any <name>/SKILL.md, the adapter only a lowercase name, a SKILL.md whose front
|
|
5
7
|
// matter names the skill and describes it, plain file paths, and 1 MiB in all.
|
|
8
|
+
import { learnedFront } from "./learn/skills.js";
|
|
6
9
|
import { skillNames } from "./validate.js";
|
|
7
10
|
import { readWorkText } from "./workspace.js";
|
|
8
11
|
/** The most skill files read at once, so a run with many skill files stays under a low open-file limit. */
|
|
@@ -18,16 +21,40 @@ async function readSkillFiles(work, paths) {
|
|
|
18
21
|
}
|
|
19
22
|
return texts;
|
|
20
23
|
}
|
|
24
|
+
/** The tools that read a file in the run's work/: a run with one is told where each skill is and reads it when it fits. */
|
|
25
|
+
export const READING_TOOLS = ["read", "bash"];
|
|
26
|
+
/** Whether a run with `tools` reads its own files, so its skills can be given on demand. */
|
|
27
|
+
export const readsFiles = (tools) => tools.some((tool) => READING_TOOLS.includes(tool));
|
|
28
|
+
/** The line before the skills a run reads on demand. */
|
|
29
|
+
export const ON_DEMAND = "Your skills follow: each one's name, what it is for and its file. When one fits the step you are on, read its SKILL.md whole before you act, and follow it; the files it names are in its folder.";
|
|
30
|
+
/** The most of a skill's description its line carries. */
|
|
31
|
+
const DESCRIPTION_MAX = 1024;
|
|
32
|
+
/** What a skill is for, as its line says it: its SKILL.md's front matter description, else its first line of text (a
|
|
33
|
+
* heading's words), else its name. One line, at most DESCRIPTION_MAX characters. */
|
|
34
|
+
function describedBy(name, text) {
|
|
35
|
+
const described = learnedFront(text)?.description;
|
|
36
|
+
const body = text.replace(/\r\n/g, "\n").replace(/^---\n[\s\S]*?\n---\n/, "");
|
|
37
|
+
const first = body.split("\n").map((line) => line.replace(/^#+\s*/, "").trim()).find(Boolean);
|
|
38
|
+
return (described || first || name).replace(/\s+/g, " ").trim().slice(0, DESCRIPTION_MAX);
|
|
39
|
+
}
|
|
40
|
+
/** The instructions, then each skill as a line: its name, what it is for and its SKILL.md's path under the run's
|
|
41
|
+
* work/, which the run reads when the skill fits (on demand). */
|
|
42
|
+
function listingWith(instructions, skills) {
|
|
43
|
+
const lines = skills.map(({ name, files }) => `- ${name}: ${describedBy(name, files["SKILL.md"] ?? "")} (${skillPath(`${name}/SKILL.md`)})`);
|
|
44
|
+
return [instructions.trim(), ...(lines.length ? [ON_DEMAND, lines.join("\n")] : [])].join("\n\n");
|
|
45
|
+
}
|
|
21
46
|
/** The instructions, then each skill's SKILL.md, by name. */
|
|
22
47
|
function promptWith(instructions, skills) {
|
|
23
48
|
const blocks = skills.map(({ name, files }) => `<skill name="${name}">\n${(files["SKILL.md"] ?? "").trim()}\n</skill>`);
|
|
24
49
|
return [instructions.trim(), ...(blocks.length ? ["Your skills follow. Use the one that fits the step you are on.", ...blocks] : [])].join("\n\n");
|
|
25
50
|
}
|
|
26
|
-
/** The revision's instructions, then each skill's `<name>/SKILL.md` from the run's workspace, by name
|
|
27
|
-
|
|
51
|
+
/** The revision's instructions, then each skill's `<name>/SKILL.md` from the run's workspace, by name: whole, or, with
|
|
52
|
+
* `onDemand` (the run reads its files: readsFiles), as a line naming it, what it is for and its path. */
|
|
53
|
+
export async function promptOf(instructions, skillFiles, work, { onDemand = false } = {}) {
|
|
28
54
|
const names = skillNames(skillFiles);
|
|
29
55
|
const texts = await readSkillFiles(work, names.map((name) => `${name}/SKILL.md`));
|
|
30
|
-
|
|
56
|
+
const skills = names.map((name, i) => ({ name, files: { "SKILL.md": texts[i] } }));
|
|
57
|
+
return onDemand ? listingWith(instructions, skills) : promptWith(instructions, skills);
|
|
31
58
|
}
|
|
32
59
|
/**
|
|
33
60
|
* The revision's skills, by name, each with its files' text from the run's workspace (`work`). A file goes to the nearest
|
|
@@ -59,10 +86,11 @@ export function splitSkills(skills, check) {
|
|
|
59
86
|
return { native, inlined: skills.filter((skill) => !native.includes(skill)) };
|
|
60
87
|
}
|
|
61
88
|
/** A run's system prompt, and the skills its harness loads itself. With the harness's `check`, the skills it takes are
|
|
62
|
-
* its own and leave the prompt; with none,
|
|
63
|
-
|
|
89
|
+
* its own and leave the prompt, and the ones it refuses stay inlined; with none, the skills are as promptOf gives them
|
|
90
|
+
* (on demand, with `onDemand`). */
|
|
91
|
+
export async function systemOf(instructions, skillFiles, work, check, { onDemand = false } = {}) {
|
|
64
92
|
if (!check)
|
|
65
|
-
return { system: await promptOf(instructions, skillFiles, work), native: [] };
|
|
93
|
+
return { system: await promptOf(instructions, skillFiles, work, { onDemand }), native: [] };
|
|
66
94
|
const { native, inlined } = splitSkills(await skillsOf(skillFiles, work), check);
|
|
67
95
|
return { system: promptWith(instructions, inlined), native };
|
|
68
96
|
}
|
package/dist/stats.d.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
import type { AnalyticsFilter, StoreAnalytics, StoreStats } from "@parcha/pi-durable-agent";
|
|
1
|
+
import type { AnalyticsFilter, PendingEnd, StoreAnalytics, StoreStats } from "@parcha/pi-durable-agent";
|
|
2
2
|
import { type Runs } from "./runs.js";
|
|
3
|
-
|
|
3
|
+
/** The running rows this server holds as ended, by the state their end will have: a run reads ended as soon as its turn
|
|
4
|
+
* ends, and its end and metrics reach the store after its process has let it go. Counted by what the server holds; their
|
|
5
|
+
* metrics, cost and effort are left out until the store has their end (analytics' `pending`), never counted as running
|
|
6
|
+
* or as an unknown cost. */
|
|
7
|
+
export declare function pendingOf(running: readonly string[], runs: Runs): Record<string, PendingEnd>;
|
|
8
|
+
export declare function statsView(stats: StoreStats, runs: Runs, pending?: Readonly<Record<string, PendingEnd>>): {
|
|
4
9
|
agents: number;
|
|
5
10
|
runs: {
|
|
6
11
|
total: number;
|
package/dist/stats.js
CHANGED
|
@@ -2,23 +2,44 @@ import { nameOf } from "@parcha/pi-durable-agent/timeline";
|
|
|
2
2
|
import { ApiError } from "./errors.js";
|
|
3
3
|
import { statusOf } from "./runs.js";
|
|
4
4
|
import { ID } from "./validate.js";
|
|
5
|
-
/** Where a running row this server holds is counted, by its status (a paused workflow run is held, so active). One it
|
|
6
|
-
*
|
|
7
|
-
const BUCKET = { queued: "active", working: "active", paused: "active", input_required: "needs_input"
|
|
5
|
+
/** Where a running row this server holds is counted, by its status (a paused workflow run is held, so active). One it
|
|
6
|
+
* holds as ended is pending (pendingOf), never here. */
|
|
7
|
+
const BUCKET = { queued: "active", working: "active", paused: "active", input_required: "needs_input" };
|
|
8
|
+
/** The state a held run's end will have in the store, by the status it reads (an escalation reads completed until then). */
|
|
9
|
+
const END_OF = { completed: "completed", failed: "failed", cancelled: "stopped" };
|
|
10
|
+
/** The running rows this server holds as ended, by the state their end will have: a run reads ended as soon as its turn
|
|
11
|
+
* ends, and its end and metrics reach the store after its process has let it go. Counted by what the server holds; their
|
|
12
|
+
* metrics, cost and effort are left out until the store has their end (analytics' `pending`), never counted as running
|
|
13
|
+
* or as an unknown cost. */
|
|
14
|
+
export function pendingOf(running, runs) {
|
|
15
|
+
const pending = {};
|
|
16
|
+
for (const id of running) {
|
|
17
|
+
const run = runs.held(id);
|
|
18
|
+
const end = run && END_OF[statusOf(run).status];
|
|
19
|
+
if (end)
|
|
20
|
+
pending[id] = end;
|
|
21
|
+
}
|
|
22
|
+
return pending;
|
|
23
|
+
}
|
|
8
24
|
/** As GET /usage rounds its sums; null stays null. */
|
|
9
25
|
const round = (usd) => (usd === null ? null : Math.round(usd * 1e6) / 1e6);
|
|
10
|
-
export function statsView(stats, runs) {
|
|
26
|
+
export function statsView(stats, runs, pending = pendingOf(stats.running, runs)) {
|
|
11
27
|
const running = { active: 0, needs_input: 0, status_unknown: 0 };
|
|
12
28
|
for (const id of stats.running) {
|
|
29
|
+
if (pending[id])
|
|
30
|
+
continue;
|
|
13
31
|
const run = runs.held(id);
|
|
14
|
-
running[run
|
|
32
|
+
running[(run && BUCKET[statusOf(run).status]) ?? "status_unknown"] += 1;
|
|
15
33
|
}
|
|
34
|
+
// Each pending run is one of the store's running rows, which its cost counts as unknown (stats.running and the cost's
|
|
35
|
+
// sums leave out the same archived runs and agents).
|
|
36
|
+
const ends = Object.values(pending);
|
|
16
37
|
const usd = round(stats.cost.usd);
|
|
17
38
|
return {
|
|
18
39
|
agents: stats.agents,
|
|
19
|
-
runs: { total: stats.runs.total, active: running.active, needs_input: running.needs_input, failed: stats.runs.failed, needs_review: stats.runs.escalated, status_unknown: running.status_unknown },
|
|
40
|
+
runs: { total: stats.runs.total, active: running.active, needs_input: running.needs_input, failed: stats.runs.failed + ends.filter((end) => end === "failed").length, needs_review: stats.runs.escalated, status_unknown: running.status_unknown },
|
|
20
41
|
per_agent: stats.byAgent.map((a) => ({ agent_id: a.id, name: a.name, runs: a.runs })),
|
|
21
|
-
cost: { usd, basis: usd === null ? null : "estimate", unknown_runs: stats.cost.unknown },
|
|
42
|
+
cost: { usd, basis: usd === null ? null : "estimate", unknown_runs: stats.cost.unknown - ends.length },
|
|
22
43
|
archived: { agents: stats.archivedAgents, runs: stats.archivedRuns },
|
|
23
44
|
};
|
|
24
45
|
}
|