@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.29
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 +560 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +1723 -2
- package/dist/adapters.d.ts +205 -0
- package/dist/adapters.js +459 -0
- package/dist/agents.d.ts +124 -0
- package/dist/agents.js +302 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +324 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +283 -0
- package/dist/box-relay.d.ts +42 -0
- package/dist/box-relay.js +222 -0
- package/dist/boxes.d.ts +54 -0
- package/dist/boxes.js +182 -0
- package/dist/cap.d.ts +224 -0
- package/dist/cap.js +721 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +31 -0
- package/dist/coding-tools.js +81 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
- package/dist/console/assets/index-BN7oVcO4.js +445 -0
- package/dist/console/assets/index-By-jkqki.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +11 -0
- package/dist/decision-rows.js +116 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +72 -0
- package/dist/errors.js +66 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +60 -0
- package/dist/files.js +153 -0
- package/dist/grade.d.ts +96 -0
- package/dist/grade.js +348 -0
- package/dist/graph-view.d.ts +100 -0
- package/dist/graph-view.js +212 -0
- package/dist/harness-app.d.ts +38 -0
- package/dist/harness-app.js +626 -0
- package/dist/harness.d.ts +53 -0
- package/dist/harness.js +74 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +20 -0
- package/dist/host-tools.js +140 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +81 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +129 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1221 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +36 -0
- package/dist/key-check.js +108 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +187 -0
- package/dist/learn/check.d.ts +99 -0
- package/dist/learn/check.js +259 -0
- package/dist/learn/grade.d.ts +79 -0
- package/dist/learn/grade.js +433 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +146 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +167 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +111 -0
- package/dist/learn/skills.d.ts +84 -0
- package/dist/learn/skills.js +198 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +304 -0
- package/dist/learning-run.js +797 -0
- package/dist/learning-words.d.ts +73 -0
- package/dist/learning-words.js +171 -0
- package/dist/learning.d.ts +377 -0
- package/dist/learning.js +801 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +115 -0
- package/dist/mcp-servers.js +445 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +184 -0
- package/dist/model.js +484 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4805 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1417 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +46 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +68 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +46 -0
- package/dist/place.js +105 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +38 -0
- package/dist/propose.js +82 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +14 -0
- package/dist/request-start.js +226 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +134 -0
- package/dist/run-box.js +440 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +80 -0
- package/dist/runnable.js +162 -0
- package/dist/runs.d.ts +840 -0
- package/dist/runs.js +2279 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +50 -0
- package/dist/secrets.js +140 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +626 -0
- package/dist/server.js +1756 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/skills.d.ts +31 -0
- package/dist/skills.js +68 -0
- package/dist/stats.d.ts +101 -0
- package/dist/stats.js +82 -0
- package/dist/tool-keys.d.ts +151 -0
- package/dist/tool-keys.js +273 -0
- package/dist/tool-plane.d.ts +143 -0
- package/dist/tool-plane.js +242 -0
- package/dist/tools.d.ts +147 -0
- package/dist/tools.js +253 -0
- package/dist/turn-end.d.ts +23 -0
- package/dist/turn-end.js +14 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +55 -0
- package/dist/validate.js +175 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +182 -0
- package/dist/webhooks.js +487 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +94 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { TSchema } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { PublicFetchOptions } from "@parcha/pi-browser";
|
|
3
|
+
/** On a page that was read, `chars`: the length of `text`, the part of the page's text this answer holds. `truncated`
|
|
4
|
+
* while more of it follows this part, and `next_offset` where that begins; `offset` where this part begins, when not 0;
|
|
5
|
+
* `original_chars` the whole text's length in characters, when it is known and this part is not all of it;
|
|
6
|
+
* `beyond_read` on the last part a read reaches of a page that goes on past PAGE_READ_MAX_CHARS; `links_omitted`, with the
|
|
7
|
+
* first part, how many of the page's links its caps left out. `html_chars`, on every part of a page whose HTML readPage
|
|
8
|
+
* cut before it was read: the page's whole length in characters. Its text, all its parts together, is then the start of
|
|
9
|
+
* the page's, so no part gives original_chars, and the last part (no truncated: no part follows) still says the page was
|
|
10
|
+
* cut. `converted: "text"` when the text is the page's plain text, its conversion to markdown having run out of time. */
|
|
11
|
+
export type Page = {
|
|
12
|
+
ok: boolean;
|
|
13
|
+
url: string;
|
|
14
|
+
status: number;
|
|
15
|
+
title: string;
|
|
16
|
+
text: string;
|
|
17
|
+
chars?: number;
|
|
18
|
+
truncated?: true;
|
|
19
|
+
original_chars?: number;
|
|
20
|
+
beyond_read?: true;
|
|
21
|
+
offset?: number;
|
|
22
|
+
next_offset?: number;
|
|
23
|
+
html_chars?: number;
|
|
24
|
+
converted?: "text";
|
|
25
|
+
links: string[];
|
|
26
|
+
links_omitted?: number;
|
|
27
|
+
refused?: string;
|
|
28
|
+
error?: string;
|
|
29
|
+
};
|
|
30
|
+
/** web_fetch's legacy name: a revision or a call node naming it runs web_fetch under it (tools.ts). */
|
|
31
|
+
export declare const FETCH_PAGE_TOOL = "fetch_page";
|
|
32
|
+
/** Under `--faux` only: a module whose default export gives `{ lookup, fetchImpl }` for the fetch (the tests' fake
|
|
33
|
+
* network), in place of the system's resolver and undici. */
|
|
34
|
+
export declare const FAUX_WEB_ENV = "AGENTRUN_SERVE_FAUX_WEB";
|
|
35
|
+
/** The most of a page's text one answer holds (max_chars at most), what it holds when max_chars is not given, and the
|
|
36
|
+
* least max_chars a tool's call may ask for (a smaller one is refused, saying so). */
|
|
37
|
+
export declare const TEXT_CAP = 50000;
|
|
38
|
+
export declare const PAGE_CHARS = 20000;
|
|
39
|
+
export declare const MAX_CHARS_MIN = 200;
|
|
40
|
+
/** The most of a page's TEXT web_fetch reads, from either provider: its first million characters (not HTML_READ_CHARS,
|
|
41
|
+
* readPage's cut of the HTML before any text is read). A part reads within it, Parallel is never asked for more of a
|
|
42
|
+
* page than that and one character (web-fetch.ts), and an offset at or past it is refused. */
|
|
43
|
+
export declare const PAGE_READ_MAX_CHARS = 1000000;
|
|
44
|
+
/** A page's links, with its first part only: at most LINKS_CAP of them, in at most LINKS_CHARS characters of the answer. */
|
|
45
|
+
export declare const LINKS_CAP = 200;
|
|
46
|
+
export declare const LINKS_CHARS = 20000;
|
|
47
|
+
export declare const TITLE_CAP = 500;
|
|
48
|
+
/** The longest URL fetched: a longer one is refused before anything is sent. */
|
|
49
|
+
export declare const URL_MAX = 4096;
|
|
50
|
+
export declare const TIMEOUT_MS = 30000;
|
|
51
|
+
/** Where readPage cuts a page's HTML before it reads it, scripts and styles aside (not PAGE_READ_MAX_CHARS, the most of
|
|
52
|
+
* the text read): pi-browser's READ_MAX_CHARS, held here so the tool's words name it without loading pi-browser where
|
|
53
|
+
* nothing is fetched (fetch-page-cut.test holds the two equal). */
|
|
54
|
+
export declare const HTML_READ_CHARS = 1000000;
|
|
55
|
+
export declare const clip: (text: string, max: number) => string;
|
|
56
|
+
/** Which part of a page's text an answer holds: from `offset` (0 by default), about `maxChars` characters (PAGE_CHARS by
|
|
57
|
+
* default, at most TEXT_CAP). */
|
|
58
|
+
export type Part = {
|
|
59
|
+
offset?: number;
|
|
60
|
+
maxChars?: number;
|
|
61
|
+
};
|
|
62
|
+
/** Why a tool's call may not read `part`, or undefined: an offset that is not a whole number of 0 or more, a maxChars that
|
|
63
|
+
* is not a number of MAX_CHARS_MIN or more (one past TEXT_CAP reads TEXT_CAP). */
|
|
64
|
+
export declare function partProblem({ offset, maxChars }: Part): string | undefined;
|
|
65
|
+
/** `part` in range: a whole offset of 0 or more, a whole maxChars of 1 to TEXT_CAP. */
|
|
66
|
+
export declare const partOf: (part?: Part) => Required<Part>;
|
|
67
|
+
/** Where the longest run of `text` from `start` ends whose JSON string takes at most `budget` characters (less its
|
|
68
|
+
* quotes): a character takes one, a quote, a backslash or a control character JSON writes short (\n, \t) two, any other
|
|
69
|
+
* control character or a lone surrogate six. A surrogate pair is never split. While a character is left the run holds
|
|
70
|
+
* one at least, whatever it takes, so a part always advances (only a budget under six can be passed, by that one). */
|
|
71
|
+
export declare function partEnd(text: string, start: number, budget: number): number;
|
|
72
|
+
/** A page's text as it is read once: its first PAGE_READ_MAX_CHARS characters (`text`), whether the page's text goes on
|
|
73
|
+
* past them (`beyond`), and its whole length where it is known (`length`). */
|
|
74
|
+
export type Text = {
|
|
75
|
+
text: string;
|
|
76
|
+
beyond: boolean;
|
|
77
|
+
length?: number;
|
|
78
|
+
};
|
|
79
|
+
/** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
|
|
80
|
+
* it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
|
|
81
|
+
* it would, it is one unit short. */
|
|
82
|
+
export declare function textOf(text: string, whole: boolean): Text;
|
|
83
|
+
/** The part of a page's text an answer holds, and what it says of the rest. */
|
|
84
|
+
export declare function pageText({ text, beyond, length }: Text, part?: Part): Pick<Page, "text" | "chars" | "truncated" | "original_chars" | "beyond_read" | "offset" | "next_offset">;
|
|
85
|
+
/** A page's links as its first part holds them: in page order, at most LINKS_CAP of them, each one that fits in what is
|
|
86
|
+
* left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
|
|
87
|
+
export declare function linksWithin(links: Iterable<string>): Pick<Page, "links" | "links_omitted">;
|
|
88
|
+
/** A page read once, before any part of it is taken: its final url, status and title, its Text, the links its first part
|
|
89
|
+
* holds (linksWithin), and readPage's `html_chars` and `converted` where it gave them. */
|
|
90
|
+
export type Read = {
|
|
91
|
+
ok: true;
|
|
92
|
+
url: string;
|
|
93
|
+
status: number;
|
|
94
|
+
title: string;
|
|
95
|
+
links: string[];
|
|
96
|
+
links_omitted?: number;
|
|
97
|
+
html_chars?: number;
|
|
98
|
+
converted?: "text";
|
|
99
|
+
} & Text;
|
|
100
|
+
/** A Page that was not read, saying why. */
|
|
101
|
+
export type Unread = Page & {
|
|
102
|
+
ok: false;
|
|
103
|
+
};
|
|
104
|
+
/** The part `part` names of a page read once, as a Page: the links with its first part only. */
|
|
105
|
+
export declare function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }: Read, part?: Part): Page;
|
|
106
|
+
/** The page at `url`, read once through the guarded direct fetch, or why it was not. The rest of `options` are the
|
|
107
|
+
* guard's resolver and fetch, for a test; a signal ends it early. */
|
|
108
|
+
export declare function readDirect(url: unknown, options?: Omit<PublicFetchOptions, "maxBytes">): Promise<Read | Unread>;
|
|
109
|
+
/** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
|
|
110
|
+
export declare function fetchPage(url: unknown, { offset, maxChars, ...options }?: Omit<PublicFetchOptions, "maxBytes"> & Part): Promise<Page>;
|
|
111
|
+
/** The fetch's resolver and fetch in the run's process: the faux module's under `--faux` with one named, else none. */
|
|
112
|
+
export declare function fetchOptions(env: NodeJS.ProcessEnv, fauxEnv: string): Promise<Omit<PublicFetchOptions, "maxBytes" | "signal">>;
|
|
113
|
+
/** A page tool's arguments: `url`, and the part of its text to read (`offset`, `max_chars`). */
|
|
114
|
+
export declare const URL_PARAMETERS: TSchema;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// The guarded direct fetch: one web page from a public host, as a Page: { ok, url, status, title, text, chars, links,
|
|
2
|
+
// refused?, error? }. web_fetch reads a page through it (web-fetch.ts); fetch_page, its legacy name, runs web_fetch. The
|
|
3
|
+
// fetch is pi-browser's public-host guard (publicFetch): every redirect hop resolved, checked and dialled at the address
|
|
4
|
+
// checked, http(s) only, a byte cap and a timeout. Before it, a URL on a port other than 80 or 443, or longer than
|
|
5
|
+
// URL_MAX, is refused here as well. A refusal or a failure is a Page with ok false, never a throw, so an agent reads why
|
|
6
|
+
// and a workflow can branch on it.
|
|
7
|
+
//
|
|
8
|
+
// A page is read once (a Read: its first PAGE_READ_MAX_CHARS characters of text, and what is known of the rest), and its
|
|
9
|
+
// text comes in parts of that: about max_chars characters from offset (a Part), counted as the answer holds them, so a
|
|
10
|
+
// part is within its bound whatever the page holds (web_fetch keeps a run's reads, web-fetch.ts). A part that is not the whole page says so: truncated while more
|
|
11
|
+
// follows, with the offset that reads on (next_offset), and the page's whole length (original_chars) where it is known.
|
|
12
|
+
// Every field of a Page is held to a cap (its text, its title, its URL, its links), so one answer is too: serve's
|
|
13
|
+
// host-bounds test holds it to the host's result bound.
|
|
14
|
+
import { pathToFileURL } from "node:url";
|
|
15
|
+
/** web_fetch's legacy name: a revision or a call node naming it runs web_fetch under it (tools.ts). */
|
|
16
|
+
export const FETCH_PAGE_TOOL = "fetch_page";
|
|
17
|
+
/** Under `--faux` only: a module whose default export gives `{ lookup, fetchImpl }` for the fetch (the tests' fake
|
|
18
|
+
* network), in place of the system's resolver and undici. */
|
|
19
|
+
export const FAUX_WEB_ENV = "AGENTRUN_SERVE_FAUX_WEB";
|
|
20
|
+
/** The most of a page's text one answer holds (max_chars at most), what it holds when max_chars is not given, and the
|
|
21
|
+
* least max_chars a tool's call may ask for (a smaller one is refused, saying so). */
|
|
22
|
+
export const TEXT_CAP = 50_000;
|
|
23
|
+
export const PAGE_CHARS = 20_000;
|
|
24
|
+
export const MAX_CHARS_MIN = 200;
|
|
25
|
+
/** The most of a page's TEXT web_fetch reads, from either provider: its first million characters (not HTML_READ_CHARS,
|
|
26
|
+
* readPage's cut of the HTML before any text is read). A part reads within it, Parallel is never asked for more of a
|
|
27
|
+
* page than that and one character (web-fetch.ts), and an offset at or past it is refused. */
|
|
28
|
+
export const PAGE_READ_MAX_CHARS = 1_000_000;
|
|
29
|
+
/** A page's links, with its first part only: at most LINKS_CAP of them, in at most LINKS_CHARS characters of the answer. */
|
|
30
|
+
export const LINKS_CAP = 200;
|
|
31
|
+
export const LINKS_CHARS = 20_000;
|
|
32
|
+
export const TITLE_CAP = 500;
|
|
33
|
+
/** The longest URL fetched: a longer one is refused before anything is sent. */
|
|
34
|
+
export const URL_MAX = 4_096;
|
|
35
|
+
export const TIMEOUT_MS = 30_000;
|
|
36
|
+
/** Where readPage cuts a page's HTML before it reads it, scripts and styles aside (not PAGE_READ_MAX_CHARS, the most of
|
|
37
|
+
* the text read): pi-browser's READ_MAX_CHARS, held here so the tool's words name it without loading pi-browser where
|
|
38
|
+
* nothing is fetched (fetch-page-cut.test holds the two equal). */
|
|
39
|
+
export const HTML_READ_CHARS = 1_000_000;
|
|
40
|
+
export const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
|
|
41
|
+
/** Why a tool's call may not read `part`, or undefined: an offset that is not a whole number of 0 or more, a maxChars that
|
|
42
|
+
* is not a number of MAX_CHARS_MIN or more (one past TEXT_CAP reads TEXT_CAP). */
|
|
43
|
+
export function partProblem({ offset, maxChars }) {
|
|
44
|
+
const shown = (value) => (typeof value === "number" ? String(value) : String(JSON.stringify(value)).slice(0, 40));
|
|
45
|
+
if (offset !== undefined && !(Number.isInteger(offset) && offset >= 0))
|
|
46
|
+
return `offset must be a whole number, 0 or more (it was ${shown(offset)})`;
|
|
47
|
+
if (offset !== undefined && offset >= PAGE_READ_MAX_CHARS)
|
|
48
|
+
return `offset must be under ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")}: web_fetch reads a page's first ${PAGE_READ_MAX_CHARS.toLocaleString("en-US")} characters (it was ${shown(offset)})`;
|
|
49
|
+
if (maxChars !== undefined && !(typeof maxChars === "number" && maxChars >= MAX_CHARS_MIN))
|
|
50
|
+
return `max_chars must be ${typeof maxChars === "number" ? "" : "a number, "}at least ${MAX_CHARS_MIN} (it was ${shown(maxChars)})`;
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
/** `part` in range: a whole offset of 0 or more, a whole maxChars of 1 to TEXT_CAP. */
|
|
54
|
+
export const partOf = (part = {}) => ({
|
|
55
|
+
offset: Math.max(0, Math.floor(Number(part.offset) || 0)),
|
|
56
|
+
maxChars: Math.max(1, Math.min(TEXT_CAP, Math.floor(Number(part.maxChars) || PAGE_CHARS))),
|
|
57
|
+
});
|
|
58
|
+
/** Where the longest run of `text` from `start` ends whose JSON string takes at most `budget` characters (less its
|
|
59
|
+
* quotes): a character takes one, a quote, a backslash or a control character JSON writes short (\n, \t) two, any other
|
|
60
|
+
* control character or a lone surrogate six. A surrogate pair is never split. While a character is left the run holds
|
|
61
|
+
* one at least, whatever it takes, so a part always advances (only a budget under six can be passed, by that one). */
|
|
62
|
+
export function partEnd(text, start, budget) {
|
|
63
|
+
let at = start;
|
|
64
|
+
for (let used = 0; at < text.length;) {
|
|
65
|
+
const unit = text.charCodeAt(at);
|
|
66
|
+
let width = 1;
|
|
67
|
+
let cost = 1;
|
|
68
|
+
if (unit >= 0xd800 && unit <= 0xdbff && at + 1 < text.length && (text.charCodeAt(at + 1) & 0xfc00) === 0xdc00)
|
|
69
|
+
[width, cost] = [2, 2];
|
|
70
|
+
else if ((unit & 0xf800) === 0xd800)
|
|
71
|
+
cost = 6;
|
|
72
|
+
else if (unit === 0x22 || unit === 0x5c || unit === 0x08 || unit === 0x09 || unit === 0x0a || unit === 0x0c || unit === 0x0d)
|
|
73
|
+
cost = 2;
|
|
74
|
+
else if (unit < 0x20)
|
|
75
|
+
cost = 6;
|
|
76
|
+
if (used + cost > budget && at > start)
|
|
77
|
+
break;
|
|
78
|
+
used += cost;
|
|
79
|
+
at += width;
|
|
80
|
+
}
|
|
81
|
+
return at;
|
|
82
|
+
}
|
|
83
|
+
/** `text` as read: `whole` says whether it is all of the page's text, so its length is the page's (a provider that cut
|
|
84
|
+
* it, or readPage's cut of its HTML, gives none). The cut at PAGE_READ_MAX_CHARS never splits a surrogate pair: where
|
|
85
|
+
* it would, it is one unit short. */
|
|
86
|
+
export function textOf(text, whole) {
|
|
87
|
+
const beyond = text.length > PAGE_READ_MAX_CHARS;
|
|
88
|
+
const split = (text.charCodeAt(PAGE_READ_MAX_CHARS - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(PAGE_READ_MAX_CHARS) & 0xfc00) === 0xdc00;
|
|
89
|
+
return { text: beyond ? text.slice(0, PAGE_READ_MAX_CHARS - (split ? 1 : 0)) : text, beyond, ...(whole ? { length: text.length } : {}) };
|
|
90
|
+
}
|
|
91
|
+
/** The part of a page's text an answer holds, and what it says of the rest. */
|
|
92
|
+
export function pageText({ text, beyond, length }, part = {}) {
|
|
93
|
+
const { offset, maxChars } = partOf(part);
|
|
94
|
+
const start = Math.min(offset, text.length);
|
|
95
|
+
const end = partEnd(text, start, maxChars);
|
|
96
|
+
const held = text.slice(start, end);
|
|
97
|
+
const more = end < text.length;
|
|
98
|
+
// The last part a read reaches of a page that goes on past it.
|
|
99
|
+
const last = !more && beyond;
|
|
100
|
+
return {
|
|
101
|
+
text: held,
|
|
102
|
+
chars: held.length,
|
|
103
|
+
...(more ? { truncated: true } : {}),
|
|
104
|
+
...(length !== undefined && (offset > 0 || more || last) ? { original_chars: length } : {}),
|
|
105
|
+
...(last ? { beyond_read: true } : {}),
|
|
106
|
+
...(offset > 0 ? { offset } : {}),
|
|
107
|
+
...(more ? { next_offset: end } : {}),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** A page's links as its first part holds them: in page order, at most LINKS_CAP of them, each one that fits in what is
|
|
111
|
+
* left of LINKS_CHARS (as JSON, with its comma); and how many of them that left out, when any. */
|
|
112
|
+
export function linksWithin(links) {
|
|
113
|
+
const kept = [];
|
|
114
|
+
let used = 0;
|
|
115
|
+
let omitted = 0;
|
|
116
|
+
for (const link of links) {
|
|
117
|
+
const cost = JSON.stringify(link).length + 1;
|
|
118
|
+
if (kept.length === LINKS_CAP || used + cost > LINKS_CHARS) {
|
|
119
|
+
omitted += 1;
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
kept.push(link);
|
|
123
|
+
used += cost;
|
|
124
|
+
}
|
|
125
|
+
return { links: kept, ...(omitted ? { links_omitted: omitted } : {}) };
|
|
126
|
+
}
|
|
127
|
+
/** The part `part` names of a page read once, as a Page: the links with its first part only. */
|
|
128
|
+
export function partOfRead({ text, beyond, length, links, links_omitted, html_chars, converted, ...page }, part = {}) {
|
|
129
|
+
const first = partOf(part).offset === 0;
|
|
130
|
+
return { ...page, ...pageText({ text, beyond, length }, part), ...(html_chars === undefined ? {} : { html_chars }), ...(converted ? { converted } : {}), links: first ? links : [], ...(first && links_omitted ? { links_omitted } : {}) };
|
|
131
|
+
}
|
|
132
|
+
/** The page at `url`, read once through the guarded direct fetch, or why it was not. The rest of `options` are the
|
|
133
|
+
* guard's resolver and fetch, for a test; a signal ends it early. */
|
|
134
|
+
export async function readDirect(url, options = {}) {
|
|
135
|
+
const failed = (fields) => ({ ok: false, url: typeof url === "string" ? clip(url, URL_MAX) : "", status: 0, title: "", text: "", links: [], ...fields });
|
|
136
|
+
if (typeof url !== "string" || !URL.canParse(url))
|
|
137
|
+
return failed({ error: "url is not an absolute URL" });
|
|
138
|
+
if (url.length > URL_MAX)
|
|
139
|
+
return failed({ error: `url is longer than ${URL_MAX.toLocaleString("en-US")} characters` });
|
|
140
|
+
const { port } = new URL(url);
|
|
141
|
+
if (port && port !== "80" && port !== "443")
|
|
142
|
+
return failed({ refused: `refused: port ${port} is not 80 or 443` });
|
|
143
|
+
const { BrowserFailureError, publicFetch, readPage } = await import("@parcha/pi-browser");
|
|
144
|
+
try {
|
|
145
|
+
const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(options.signal ? [options.signal] : [])]);
|
|
146
|
+
const answer = await publicFetch(url, { ...options, signal });
|
|
147
|
+
if (answer.body === null)
|
|
148
|
+
return failed({ url: clip(answer.url, URL_MAX), status: answer.status, error: `the page answered ${answer.status}` });
|
|
149
|
+
// The caller's stop reaches the read too; the timeout is the network's, and readPage keeps its own deadline.
|
|
150
|
+
const read = /html/i.test(answer.contentType) ? await readPage(answer.body, answer.url, options.signal ? { signal: options.signal } : {}) : null;
|
|
151
|
+
const page = read ?? { title: "", text: answer.body, links: [] };
|
|
152
|
+
return { ok: true, url: clip(answer.url, URL_MAX), status: answer.status, title: clip(page.title, TITLE_CAP), ...textOf(page.text, !read?.truncated), ...(read?.truncated ? { html_chars: read.html_chars } : {}), ...(read?.converted === "text" ? { converted: "text" } : {}), ...linksWithin(page.links) };
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
if (error instanceof BrowserFailureError && error.failure.code === "refused")
|
|
156
|
+
return failed({ refused: error.message });
|
|
157
|
+
return failed({ error: error?.message ?? String(error) });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** The part `options` names of the page at `url`, as a Page, read through the guarded direct fetch. */
|
|
161
|
+
export async function fetchPage(url, { offset, maxChars, ...options } = {}) {
|
|
162
|
+
const read = await readDirect(url, options);
|
|
163
|
+
return read.ok ? partOfRead(read, { offset, maxChars }) : read;
|
|
164
|
+
}
|
|
165
|
+
/** The fetch's resolver and fetch in the run's process: the faux module's under `--faux` with one named, else none. */
|
|
166
|
+
export async function fetchOptions(env, fauxEnv) {
|
|
167
|
+
const faux = env[fauxEnv] ? env[FAUX_WEB_ENV] : undefined;
|
|
168
|
+
if (!faux)
|
|
169
|
+
return {};
|
|
170
|
+
return (await import(pathToFileURL(faux).href)).default();
|
|
171
|
+
}
|
|
172
|
+
/** A page tool's arguments: `url`, and the part of its text to read (`offset`, `max_chars`). */
|
|
173
|
+
export const URL_PARAMETERS = {
|
|
174
|
+
type: "object",
|
|
175
|
+
additionalProperties: false,
|
|
176
|
+
properties: {
|
|
177
|
+
url: { type: "string", minLength: 1, description: "An absolute http(s) URL." },
|
|
178
|
+
offset: { type: "integer", minimum: 0, description: "Where in the page's text to start, in characters (default 0). An answer that stops short of the page's end gives the offset that reads on." },
|
|
179
|
+
max_chars: { type: "integer", minimum: MAX_CHARS_MIN, maximum: TEXT_CAP, description: `About how many characters of the page's text to read (default ${PAGE_CHARS.toLocaleString("en-US")}, at least ${MAX_CHARS_MIN}, at most ${TEXT_CAP.toLocaleString("en-US")}).` },
|
|
180
|
+
},
|
|
181
|
+
required: ["url"],
|
|
182
|
+
};
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type Stats } from "node:fs";
|
|
2
|
+
import type { Json } from "./validate.js";
|
|
3
|
+
/** The server's own file in each run's directory: the run's title, input and how it was asked to run. */
|
|
4
|
+
export declare const RUN_META = "serve.json";
|
|
5
|
+
/** A cancelled run's mark in its directory, written before its process is told: the run's process sends no model
|
|
6
|
+
* request once it is there, however the cancel and the process's start interleave. */
|
|
7
|
+
export declare const RUN_CANCELLED = "cancelled";
|
|
8
|
+
/** A run's launch mark in its directory, written before its process is spawned and removed once that process serves
|
|
9
|
+
* or exits: found at a start, the server went down while it launched the run. */
|
|
10
|
+
export declare const RUN_LAUNCHING = "launching";
|
|
11
|
+
/** Set in a run's process environment when the server opens the run for a person's follow-up to a run whose turn had
|
|
12
|
+
* ended (it answered, or the person stopped it): that open resumes no cut work, so it writes no "resumed" row (app.ts). */
|
|
13
|
+
export declare const FOLLOW_UP_OPEN_ENV = "AGENTRUN_FOLLOW_UP_OPEN";
|
|
14
|
+
/** The server's API token (`ar_local_...`), in the data directory, made at its first start when it is given none. */
|
|
15
|
+
export declare const TOKEN_FILE = ".token";
|
|
16
|
+
/** The server-wide door token, in the data directory: the door of a run an older server started takes it. */
|
|
17
|
+
export declare const DOOR_TOKEN_FILE = ".door-token";
|
|
18
|
+
/** A run's own door token, in its directory, made at its first launch and handed to its process alone (its
|
|
19
|
+
* `--serve-token-file`): the server's calls to that run's door carry it, and so do that run's calls to the box relay
|
|
20
|
+
* (box-relay.ts), which takes a call for a run only with that run's token. */
|
|
21
|
+
export declare const RUN_DOOR_TOKEN = "door-token";
|
|
22
|
+
/** Run directory `dir`'s own door token (RUN_DOOR_TOKEN), when it has one. */
|
|
23
|
+
export declare function runDoorToken(dir: string): string | undefined;
|
|
24
|
+
/** Why a run fails whose launch mark a start finds (`error.details.reason`, openapi.ts). */
|
|
25
|
+
export declare const LAUNCH_LOST = "server_lost_at_launch";
|
|
26
|
+
/** The server's data directory when none is given (`--data`): `agentrun/agents` under XDG_DATA_HOME, or ~/.local/share.
|
|
27
|
+
* The server, its import and reset-password default to it. `npx @parcha/agentrun` keeps its own, ~/.agentrun, and
|
|
28
|
+
* passes it as --data. */
|
|
29
|
+
export declare const defaultData: (env?: NodeJS.ProcessEnv) => string;
|
|
30
|
+
/** The server's own data directory, on its reading of the environment (startServe): an npx hint names it (adapters.ts
|
|
31
|
+
* npxLine). */
|
|
32
|
+
export declare const DATA_ENV = "AGENTRUN_SERVE_DATA";
|
|
33
|
+
export declare const HOMES_DIR = "homes";
|
|
34
|
+
/** Paths in an agent's home that only the host writes (another component owns them): read through the API, never written through it. */
|
|
35
|
+
export declare const HOME_HOST_OWNED: string[];
|
|
36
|
+
/** An agent's home directory's name: its id in lower case, then 16 hex digits of the id's SHA-256. Ids that differ only
|
|
37
|
+
* in case get names that differ in any case, so on a disk that folds case (macOS's, by default) they never share one. */
|
|
38
|
+
export declare const homeKey: (agentId: string) => string;
|
|
39
|
+
export declare const homeOf: (data: string, agentId: string) => string;
|
|
40
|
+
/** The file parsed as JSON, or null when it is missing, unreadable, or not whole JSON (a half-written file). */
|
|
41
|
+
export declare const readJson: (path: string) => Promise<Json | null>;
|
|
42
|
+
/** A temporary file beside `path`, this write's own: two writes of one file at once never share one, so neither renames
|
|
43
|
+
* the other's away nor writes into the file the other renamed. */
|
|
44
|
+
export declare const tempOf: (path: string) => string;
|
|
45
|
+
/** Writes `text` to `path` whole: through a temporary file and a rename, so a reader never sees half of it. */
|
|
46
|
+
export declare function writeWhole(path: string, text: string, mode?: number): Promise<void>;
|
|
47
|
+
/** Syncs the directory `path`, so the entries made in it survive a crash of the machine. */
|
|
48
|
+
export declare function syncDir(path: string): Promise<void>;
|
|
49
|
+
/** Writes `text` (or bytes) to `path` whole and durably: the temporary file is synced before the rename, and the
|
|
50
|
+
* directory after it, so once this resolves a crash, even of the machine, leaves the new text in place, never the old or
|
|
51
|
+
* none. `temp` is the temporary file, created only if nothing is there yet: a link planted at it is never written through.
|
|
52
|
+
* Answers the stats of the file it wrote, read before the rename: a write of `path` that lands after it is not them.
|
|
53
|
+
* `exact`: the file gets `mode` itself, whatever this process's umask takes away (set on its handle, never by path). */
|
|
54
|
+
export declare function writeDurable(path: string, text: string | Uint8Array, mode?: number, temp?: string, exact?: boolean): Promise<Stats>;
|
|
55
|
+
/** writeDurable, synchronously: on disk, the file and then its directory synced, when it returns. For a record that
|
|
56
|
+
* must be durable before the next line runs, with nothing between them that could let anything else happen first. */
|
|
57
|
+
export declare function writeDurableSync(path: string, text: string, mode?: number): void;
|
|
58
|
+
/** Runs `work` once every call queued before it under `key` in `queues` has settled: one at a time per key. The queue
|
|
59
|
+
* holds only settled turns, so one that failed never fails the next, and a key is dropped once its last turn settles. */
|
|
60
|
+
export declare function serialBy<T>(queues: Map<string, Promise<unknown>>, key: string, work: () => Promise<T>): Promise<T>;
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// The small JSON files the server reads and writes beside the agent store.
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
|
4
|
+
import { open, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
/** The server's own file in each run's directory: the run's title, input and how it was asked to run. */
|
|
8
|
+
export const RUN_META = "serve.json";
|
|
9
|
+
/** A cancelled run's mark in its directory, written before its process is told: the run's process sends no model
|
|
10
|
+
* request once it is there, however the cancel and the process's start interleave. */
|
|
11
|
+
export const RUN_CANCELLED = "cancelled";
|
|
12
|
+
/** A run's launch mark in its directory, written before its process is spawned and removed once that process serves
|
|
13
|
+
* or exits: found at a start, the server went down while it launched the run. */
|
|
14
|
+
export const RUN_LAUNCHING = "launching";
|
|
15
|
+
/** Set in a run's process environment when the server opens the run for a person's follow-up to a run whose turn had
|
|
16
|
+
* ended (it answered, or the person stopped it): that open resumes no cut work, so it writes no "resumed" row (app.ts). */
|
|
17
|
+
export const FOLLOW_UP_OPEN_ENV = "AGENTRUN_FOLLOW_UP_OPEN";
|
|
18
|
+
/** The server's API token (`ar_local_...`), in the data directory, made at its first start when it is given none. */
|
|
19
|
+
export const TOKEN_FILE = ".token";
|
|
20
|
+
/** The server-wide door token, in the data directory: the door of a run an older server started takes it. */
|
|
21
|
+
export const DOOR_TOKEN_FILE = ".door-token";
|
|
22
|
+
/** A run's own door token, in its directory, made at its first launch and handed to its process alone (its
|
|
23
|
+
* `--serve-token-file`): the server's calls to that run's door carry it, and so do that run's calls to the box relay
|
|
24
|
+
* (box-relay.ts), which takes a call for a run only with that run's token. */
|
|
25
|
+
export const RUN_DOOR_TOKEN = "door-token";
|
|
26
|
+
/** Run directory `dir`'s own door token (RUN_DOOR_TOKEN), when it has one. */
|
|
27
|
+
export function runDoorToken(dir) {
|
|
28
|
+
try {
|
|
29
|
+
const token = readFileSync(join(dir, RUN_DOOR_TOKEN), "utf8").trim();
|
|
30
|
+
return token && !/\s/.test(token) ? token : undefined;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Why a run fails whose launch mark a start finds (`error.details.reason`, openapi.ts). */
|
|
37
|
+
export const LAUNCH_LOST = "server_lost_at_launch";
|
|
38
|
+
/** The server's data directory when none is given (`--data`): `agentrun/agents` under XDG_DATA_HOME, or ~/.local/share.
|
|
39
|
+
* The server, its import and reset-password default to it. `npx @parcha/agentrun` keeps its own, ~/.agentrun, and
|
|
40
|
+
* passes it as --data. */
|
|
41
|
+
export const defaultData = (env = process.env) => join(env.XDG_DATA_HOME || join(env.HOME || homedir(), ".local", "share"), "agentrun", "agents");
|
|
42
|
+
/** The server's own data directory, on its reading of the environment (startServe): an npx hint names it (adapters.ts
|
|
43
|
+
* npxLine). */
|
|
44
|
+
export const DATA_ENV = "AGENTRUN_SERVE_DATA";
|
|
45
|
+
export const HOMES_DIR = "homes";
|
|
46
|
+
/** Paths in an agent's home that only the host writes (another component owns them): read through the API, never written through it. */
|
|
47
|
+
export const HOME_HOST_OWNED = ["learning"];
|
|
48
|
+
/** An agent's home directory's name: its id in lower case, then 16 hex digits of the id's SHA-256. Ids that differ only
|
|
49
|
+
* in case get names that differ in any case, so on a disk that folds case (macOS's, by default) they never share one. */
|
|
50
|
+
export const homeKey = (agentId) => `${agentId.toLowerCase()}-${createHash("sha256").update(agentId, "utf8").digest("hex").slice(0, 16)}`;
|
|
51
|
+
export const homeOf = (data, agentId) => join(data, HOMES_DIR, homeKey(agentId));
|
|
52
|
+
/** The file parsed as JSON, or null when it is missing, unreadable, or not whole JSON (a half-written file). */
|
|
53
|
+
export const readJson = (path) => readFile(path, "utf8")
|
|
54
|
+
.then((text) => JSON.parse(text))
|
|
55
|
+
.catch(() => null);
|
|
56
|
+
/** A temporary file beside `path`, this write's own: two writes of one file at once never share one, so neither renames
|
|
57
|
+
* the other's away nor writes into the file the other renamed. */
|
|
58
|
+
export const tempOf = (path) => `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
59
|
+
/** Writes `text` to `path` whole: through a temporary file and a rename, so a reader never sees half of it. */
|
|
60
|
+
export async function writeWhole(path, text, mode = 0o600) {
|
|
61
|
+
const temp = `${path}.tmp`;
|
|
62
|
+
await writeFile(temp, text, { mode });
|
|
63
|
+
await rename(temp, path);
|
|
64
|
+
}
|
|
65
|
+
/** Syncs the directory `path`, so the entries made in it survive a crash of the machine. */
|
|
66
|
+
export async function syncDir(path) {
|
|
67
|
+
const dir = await open(path, constants.O_RDONLY | constants.O_DIRECTORY);
|
|
68
|
+
try {
|
|
69
|
+
await dir.sync();
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
await dir.close();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Writes `text` (or bytes) to `path` whole and durably: the temporary file is synced before the rename, and the
|
|
76
|
+
* directory after it, so once this resolves a crash, even of the machine, leaves the new text in place, never the old or
|
|
77
|
+
* none. `temp` is the temporary file, created only if nothing is there yet: a link planted at it is never written through.
|
|
78
|
+
* Answers the stats of the file it wrote, read before the rename: a write of `path` that lands after it is not them.
|
|
79
|
+
* `exact`: the file gets `mode` itself, whatever this process's umask takes away (set on its handle, never by path). */
|
|
80
|
+
export async function writeDurable(path, text, mode = 0o600, temp = tempOf(path), exact = false) {
|
|
81
|
+
// Its own temporary file: a box's record can be let go by two settlements at once (a run's archive and its agent's).
|
|
82
|
+
const bytes = typeof text === "string" ? Buffer.from(text) : text;
|
|
83
|
+
const file = await open(temp, "wx", mode);
|
|
84
|
+
let stats;
|
|
85
|
+
try {
|
|
86
|
+
if (exact)
|
|
87
|
+
await file.chmod(mode);
|
|
88
|
+
// Every byte, or an error: a short write (a disk nearly full) is never synced and renamed as if whole.
|
|
89
|
+
for (let at = 0; at < bytes.length;) {
|
|
90
|
+
const { bytesWritten } = await file.write(bytes, at, bytes.length - at);
|
|
91
|
+
if (bytesWritten <= 0)
|
|
92
|
+
throw new Error(`${temp}: wrote ${at} of ${bytes.length} bytes`);
|
|
93
|
+
at += bytesWritten;
|
|
94
|
+
}
|
|
95
|
+
await file.sync();
|
|
96
|
+
stats = await file.stat();
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
await file.close();
|
|
100
|
+
await unlink(temp).catch(() => { });
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
await file.close();
|
|
104
|
+
await rename(temp, path).catch(async (error) => {
|
|
105
|
+
await unlink(temp).catch(() => { });
|
|
106
|
+
throw error;
|
|
107
|
+
});
|
|
108
|
+
await syncDir(dirname(path));
|
|
109
|
+
return stats;
|
|
110
|
+
}
|
|
111
|
+
/** writeDurable, synchronously: on disk, the file and then its directory synced, when it returns. For a record that
|
|
112
|
+
* must be durable before the next line runs, with nothing between them that could let anything else happen first. */
|
|
113
|
+
export function writeDurableSync(path, text, mode = 0o600) {
|
|
114
|
+
const temp = `${path}.tmp`;
|
|
115
|
+
const bytes = Buffer.from(text);
|
|
116
|
+
const file = openSync(temp, "w", mode);
|
|
117
|
+
try {
|
|
118
|
+
// Every byte, or an error: a short write (a disk nearly full) is never synced and renamed as if whole.
|
|
119
|
+
for (let at = 0; at < bytes.length;) {
|
|
120
|
+
const written = writeSync(file, bytes, at, bytes.length - at);
|
|
121
|
+
if (written <= 0)
|
|
122
|
+
throw new Error(`${temp}: wrote ${at} of ${bytes.length} bytes`);
|
|
123
|
+
at += written;
|
|
124
|
+
}
|
|
125
|
+
fsyncSync(file);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
closeSync(file);
|
|
129
|
+
try {
|
|
130
|
+
unlinkSync(temp);
|
|
131
|
+
}
|
|
132
|
+
catch { }
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
closeSync(file);
|
|
136
|
+
renameSync(temp, path);
|
|
137
|
+
const dir = openSync(dirname(path), "r");
|
|
138
|
+
try {
|
|
139
|
+
fsyncSync(dir);
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
closeSync(dir);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Runs `work` once every call queued before it under `key` in `queues` has settled: one at a time per key. The queue
|
|
146
|
+
* holds only settled turns, so one that failed never fails the next, and a key is dropped once its last turn settles. */
|
|
147
|
+
export function serialBy(queues, key, work) {
|
|
148
|
+
const turn = (queues.get(key) ?? Promise.resolve()).then(work);
|
|
149
|
+
const settled = turn.then(() => undefined, () => undefined);
|
|
150
|
+
queues.set(key, settled);
|
|
151
|
+
void settled.then(() => queues.get(key) === settled && queues.delete(key));
|
|
152
|
+
return turn;
|
|
153
|
+
}
|
package/dist/grade.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type IndexEntry, type NoteText, type Problem, type Verdict } from "./learn/index.js";
|
|
2
|
+
import { claudeProvider } from "./adapters.js";
|
|
3
|
+
import { type Proposal, type Tokens } from "./learning.js";
|
|
4
|
+
/** Main as a grade reads it: its commit, every entry at its top, its notes' texts by file (any status), and each
|
|
5
|
+
* entry's object id. */
|
|
6
|
+
export type Main = {
|
|
7
|
+
sha: string;
|
|
8
|
+
files: string[];
|
|
9
|
+
texts: Map<string, string>;
|
|
10
|
+
oids: Map<string, string>;
|
|
11
|
+
};
|
|
12
|
+
/** What a grade spent: the screen's judge and the grader. The dollars, null when any call's are unknown, and the tokens,
|
|
13
|
+
* null when any call's are. */
|
|
14
|
+
export type GradeCost = {
|
|
15
|
+
usd: number | null;
|
|
16
|
+
tokens: Tokens | null;
|
|
17
|
+
};
|
|
18
|
+
export type Judged = {
|
|
19
|
+
cost: GradeCost;
|
|
20
|
+
} & ({
|
|
21
|
+
verdict: Verdict;
|
|
22
|
+
} | {
|
|
23
|
+
reason: "screen" | "screen_down";
|
|
24
|
+
file: string;
|
|
25
|
+
} | {
|
|
26
|
+
reason: "grade_failed";
|
|
27
|
+
error: Error;
|
|
28
|
+
});
|
|
29
|
+
/** The agentic revision the run ran: its standing instructions, and what its model is. */
|
|
30
|
+
export type Agent = {
|
|
31
|
+
instructions: string;
|
|
32
|
+
harness?: string;
|
|
33
|
+
model?: string;
|
|
34
|
+
thinking?: string;
|
|
35
|
+
};
|
|
36
|
+
/** What a grade reads of main: each active note as the index lists it, the whole text of the ones the proposal
|
|
37
|
+
* supersedes, and the blob each of those was on main then (`graded`, by file), which its merge checks. */
|
|
38
|
+
export type GradeMain = {
|
|
39
|
+
active: IndexEntry[];
|
|
40
|
+
superseded: NoteText[];
|
|
41
|
+
graded: Record<string, string>;
|
|
42
|
+
};
|
|
43
|
+
/** Main now, for run `runId`'s grade, in the agent's queue: merged already (a commit names the run), what stops its
|
|
44
|
+
* proposal joining main as it is now, or its active notes' index lines and the notes the proposal supersedes in full. */
|
|
45
|
+
export declare function readForGrade(data: string, agentId: string, runId: string, proposal: Proposal): Promise<{
|
|
46
|
+
merged: string;
|
|
47
|
+
} | {
|
|
48
|
+
problems: Problem[];
|
|
49
|
+
} | GradeMain>;
|
|
50
|
+
/** claude-agent's provider, as claudeProvider returns it. Without `auth`, it takes x-api-key, as the adapter does. */
|
|
51
|
+
export type RunProvider = ReturnType<typeof claudeProvider> & {
|
|
52
|
+
auth?: "x-api-key" | "bearer";
|
|
53
|
+
};
|
|
54
|
+
/** pi-ai's auth context for a grade on `provider`, the run's: its credential under the one variable pi-ai reads for its
|
|
55
|
+
* auth mode, and no other variable of serve's env. */
|
|
56
|
+
export declare function graderAuth(provider: RunProvider): {
|
|
57
|
+
env: (asked: string) => Promise<string | undefined>;
|
|
58
|
+
fileExists: () => Promise<boolean>;
|
|
59
|
+
};
|
|
60
|
+
/** The screen (only with an independent judge), then the grader, on `gradeModel` when the server names one (gradeModelOf),
|
|
61
|
+
* given `asked`, what the user said in the run: the first note the screen refuses or cannot judge, the grader's verdict,
|
|
62
|
+
* or why the grader gave none; with what it spent. Rejects only when `signal` (the server closing) aborts it: nothing
|
|
63
|
+
* is decided then. */
|
|
64
|
+
export declare function judgeProposal(input: {
|
|
65
|
+
runId: string;
|
|
66
|
+
agent: Agent;
|
|
67
|
+
main: GradeMain;
|
|
68
|
+
proposed: NoteText[];
|
|
69
|
+
files?: NoteText[];
|
|
70
|
+
asked?: readonly string[];
|
|
71
|
+
gradeModel?: string;
|
|
72
|
+
env: NodeJS.ProcessEnv;
|
|
73
|
+
signal: AbortSignal;
|
|
74
|
+
gradeTimeoutMs?: number;
|
|
75
|
+
}): Promise<Judged>;
|
|
76
|
+
/** Each skill and draft file as main keeps it: as the run gave it, or, for one the grader held for its owner's OK, with
|
|
77
|
+
* `status: pending` in its SKILL.md or its README.md (learn/skills.ts held). A held workflow.json is as given: its
|
|
78
|
+
* README holds it. */
|
|
79
|
+
export declare function heldFiles(files: readonly NoteText[], verdict?: Verdict): NoteText[];
|
|
80
|
+
/** Merges run `runId`'s proposal into main as main is now, in the agent's queue, as `verdict` judged its notes: one commit
|
|
81
|
+
* on main (its parent main) that adds the new notes, each with its `origin` and a pending one with `status: pending`
|
|
82
|
+
* (in no index, so no run reads it, until a person approves it), marks each note a kept one supersedes (a pending
|
|
83
|
+
* note's wait for its approval), adds or changes the skill's and draft's files (heldFiles: a held one pending) and
|
|
84
|
+
* rebuilds MEMORY.md, its message `learning: <run>: merged`,
|
|
85
|
+
* `reason` and the run's Run-Id; moved onto main only from the commit it was made on, once more on a main that moved
|
|
86
|
+
* meanwhile. Then the checked-out files are main's. A run a commit on main already names is that commit. `problems`
|
|
87
|
+
* when main, as it is now, takes the notes no more (mergeProblems), or when a note the merge marks superseded is not
|
|
88
|
+
* the blob the grade read (`graded`, readForGrade's): a person changed it since, and their text stands. A note held for
|
|
89
|
+
* its owner's OK marks nothing (supersededBy), so what it names is not checked. `checkout` is why the files could not
|
|
90
|
+
* be brought in line, when they could not: main is merged all the same. */
|
|
91
|
+
export declare function mergeProposal(data: string, agentId: string, runId: string, proposal: Proposal, reason: string, graded: Readonly<Record<string, string>>, verdict?: Verdict): Promise<{
|
|
92
|
+
merged: string;
|
|
93
|
+
checkout: Error | undefined;
|
|
94
|
+
} | {
|
|
95
|
+
problems: Problem[];
|
|
96
|
+
}>;
|