@parcha/agentrun-serve 0.1.0-beta.53 → 0.1.0-beta.55
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 +138 -3
- package/README.md +346 -99
- package/dist/adapters.d.ts +10 -0
- package/dist/adapters.js +46 -0
- package/dist/agent-package.d.ts +3 -3
- package/dist/agent-package.js +7 -14
- package/dist/agent-rows.d.ts +1 -1
- package/dist/agents-store.js +7 -6
- package/dist/api-only.d.ts +17 -6
- package/dist/api-only.js +22 -9
- package/dist/cli.js +11 -4
- package/dist/composio-made.d.ts +26 -1
- package/dist/composio-made.js +39 -2
- package/dist/composio-preset.d.ts +6 -4
- package/dist/composio-preset.js +50 -17
- package/dist/computer-held-routes.js +2 -3
- package/dist/computer-needs.d.ts +1 -1
- package/dist/computer-needs.js +1 -1
- package/dist/computer-setting.d.ts +8 -4
- package/dist/computer-setting.js +0 -2
- package/dist/computers-running.d.ts +8 -0
- package/dist/computers-running.js +27 -0
- package/dist/computers.d.ts +0 -2
- package/dist/computers.js +1 -1
- package/dist/console/assets/backend-D5EmB4N3.js +166 -0
- package/dist/console/assets/index-DUYLaqiR.js +746 -0
- package/dist/console/assets/index-DYhU4adm.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/docker-host-addresses.d.ts +23 -3
- package/dist/docker-host-addresses.js +90 -18
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +7 -0
- package/dist/exa-keyless.d.ts +2 -3
- package/dist/exa-keyless.js +43 -127
- package/dist/firecrawl-keyless.d.ts +41 -0
- package/dist/firecrawl-keyless.js +152 -0
- package/dist/github-connection.d.ts +50 -1
- package/dist/github-connection.js +96 -3
- package/dist/github-faux.d.ts +11 -2
- package/dist/github-faux.js +138 -7
- package/dist/github-pull-request.d.ts +37 -0
- package/dist/github-pull-request.js +110 -0
- package/dist/handed-secret.d.ts +3 -1
- package/dist/handed-secret.js +4 -2
- package/dist/harness-keys.d.ts +98 -0
- package/dist/harness-keys.js +247 -0
- package/dist/harness-recipe-entry.d.ts +14 -9
- package/dist/harness-recipe-entry.js +25 -14
- package/dist/harness-table.d.ts +16 -1
- package/dist/harness-table.js +19 -7
- package/dist/harness.d.ts +4 -0
- package/dist/harness.js +12 -1
- package/dist/host-check.d.ts +2 -0
- package/dist/host-check.js +6 -0
- package/dist/import-summary.d.ts +1 -1
- package/dist/import-summary.js +1 -1
- package/dist/import.d.ts +5 -5
- package/dist/import.js +54 -67
- package/dist/keyless-mcp.d.ts +36 -0
- package/dist/keyless-mcp.js +127 -0
- package/dist/learn/audit.d.ts +3 -3
- package/dist/learn/audit.js +3 -3
- package/dist/learn/commit.d.ts +8 -7
- package/dist/learn/commit.js +60 -20
- package/dist/learn/compile.d.ts +4 -3
- package/dist/learn/compile.js +7 -5
- package/dist/learn/folder.d.ts +16 -3
- package/dist/learn/folder.js +46 -13
- package/dist/learn/promote.d.ts +37 -13
- package/dist/learn/promote.js +112 -40
- package/dist/learn/secrets.js +10 -2
- package/dist/learning-routes.d.ts +22 -17
- package/dist/learning-routes.js +40 -39
- package/dist/learning.js +2 -2
- package/dist/live-reach.d.ts +34 -7
- package/dist/live-reach.js +76 -11
- package/dist/manifest.d.ts +10 -0
- package/dist/manifest.js +30 -0
- package/dist/mcp-pin-first.d.ts +4 -2
- package/dist/mcp-pin-first.js +5 -2
- package/dist/mcp-probe.js +2 -2
- package/dist/mcp-secret-writes.d.ts +16 -7
- package/dist/mcp-secret-writes.js +35 -27
- package/dist/mcp-servers-store.d.ts +30 -6
- package/dist/mcp-servers-store.js +112 -28
- package/dist/mcp-sources.d.ts +10 -2
- package/dist/mcp-sources.js +9 -2
- package/dist/mcp-store.d.ts +13 -7
- package/dist/mcp-store.js +12 -9
- package/dist/model-form.d.ts +3 -2
- package/dist/model-form.js +11 -7
- package/dist/model.d.ts +20 -4
- package/dist/model.js +68 -9
- package/dist/native/history.d.ts +1 -1
- package/dist/native/history.js +2 -2
- package/dist/ollama-provider.d.ts +92 -0
- package/dist/ollama-provider.js +495 -0
- package/dist/openapi/agentrun-v2.openapi.json +2 -2
- package/dist/openapi.js +235 -41
- package/dist/page.d.ts +11 -3
- package/dist/page.js +22 -7
- package/dist/place-offers.d.ts +17 -1
- package/dist/place-offers.js +46 -5
- package/dist/print.js +1 -1
- package/dist/purged-workflow.d.ts +35 -7
- package/dist/purged-workflow.js +73 -26
- package/dist/run-computer.d.ts +2 -0
- package/dist/run-computer.js +2 -0
- package/dist/run-files.d.ts +4 -0
- package/dist/run-files.js +4 -0
- package/dist/run-keys.d.ts +2 -4
- package/dist/run-keys.js +6 -7
- package/dist/run-launch.d.ts +4 -0
- package/dist/run-launch.js +4 -0
- package/dist/run-reads-over-store.d.ts +3 -2
- package/dist/run-reads-over-store.js +66 -2
- package/dist/run-secrets.js +5 -2
- package/dist/runner/adapter-loop.d.ts +6 -3
- package/dist/runner/adapter-loop.js +34 -15
- package/dist/runner/adapter-run-spec.d.ts +3 -0
- package/dist/runner/adapter-run-spec.js +6 -4
- package/dist/runner/audit.js +8 -4
- package/dist/runner/beside.d.ts +2 -1
- package/dist/runner/beside.js +6 -2
- package/dist/runner/claim-secrets.d.ts +5 -8
- package/dist/runner/claim-secrets.js +6 -0
- package/dist/runner/cli-run-spec.d.ts +1 -1
- package/dist/runner/cli-run-spec.js +39 -7
- package/dist/runner/harness-loops.d.ts +22 -9
- package/dist/runner/harness-loops.js +21 -11
- package/dist/runner/held.d.ts +3 -0
- package/dist/runner/learning-end.d.ts +1 -1
- package/dist/runner/learning-end.js +8 -3
- package/dist/runner/loop-contract.d.ts +5 -4
- package/dist/runner/main.js +4 -2
- package/dist/runner/mcp-claim.d.ts +3 -0
- package/dist/runner/mcp-claim.js +26 -2
- package/dist/runner/mcp-run.d.ts +3 -0
- package/dist/runner/mcp-run.js +2 -1
- package/dist/runner/metrics.d.ts +10 -8
- package/dist/runner/metrics.js +20 -27
- package/dist/runner/model-route.d.ts +3 -0
- package/dist/runner/model-route.js +6 -2
- package/dist/runner/pr-checkout.d.ts +21 -4
- package/dist/runner/pr-checkout.js +103 -4
- package/dist/runner/promotion.d.ts +15 -9
- package/dist/runner/promotion.js +25 -15
- package/dist/runner/run-child-host.js +24 -11
- package/dist/runner/run-child.js +3 -1
- package/dist/runner/runner-check.d.ts +3 -0
- package/dist/runner/runner-check.js +23 -0
- package/dist/runner/sdk-loop.js +2 -0
- package/dist/runner/workflow-loop.d.ts +2 -2
- package/dist/runner/workflow-loop.js +1 -2
- package/dist/runner/workflow-spec.d.ts +1 -1
- package/dist/runner/workflow-spec.js +6 -6
- package/dist/sdk/check.d.ts +4 -1
- package/dist/sdk/check.js +2 -1
- package/dist/sdk/runs.d.ts +2 -2
- package/dist/sdk/runs.js +8 -6
- package/dist/secret-cut.js +2 -1
- package/dist/secret-writes.d.ts +3 -2
- package/dist/secret-writes.js +1 -1
- package/dist/server.d.ts +55 -8
- package/dist/server.js +363 -118
- package/dist/standard-webhooks.d.ts +11 -0
- package/dist/standard-webhooks.js +20 -2
- package/dist/store/agent-body.d.ts +2 -2
- package/dist/store/agent-body.js +2 -2
- package/dist/store/index.d.ts +1 -1
- package/dist/store/schema.js +5 -2
- package/dist/store/sqlite/store.js +90 -34
- package/dist/store/store.d.ts +54 -14
- package/dist/store-reads/journal.d.ts +7 -2
- package/dist/store-reads/journal.js +9 -6
- package/dist/store-reads/learning.d.ts +12 -9
- package/dist/store-reads/learning.js +18 -24
- package/dist/store-view.d.ts +0 -5
- package/dist/store-view.js +9 -8
- package/dist/suggestions.d.ts +282 -0
- package/dist/suggestions.js +919 -0
- package/dist/telemetry.d.ts +8 -1
- package/dist/telemetry.js +12 -4
- package/dist/template-eval.d.ts +49 -4
- package/dist/template-eval.js +168 -45
- package/dist/template-import.d.ts +17 -0
- package/dist/template-import.js +36 -2
- package/dist/templates.d.ts +83 -76
- package/dist/templates.js +29 -48
- package/dist/timeline/labels.d.ts +2 -2
- package/dist/timeline/labels.js +2 -2
- package/dist/timeline/timeline.d.ts +2 -2
- package/dist/timeline/timeline.js +1 -1
- package/dist/tool-plane.d.ts +17 -9
- package/dist/tool-plane.js +38 -17
- package/dist/tools.js +2 -2
- package/dist/trigger-launch-hook.d.ts +19 -9
- package/dist/trigger-launch-hook.js +35 -25
- package/dist/trigger-targets.d.ts +18 -8
- package/dist/trigger-targets.js +42 -19
- package/dist/triggers.d.ts +85 -23
- package/dist/triggers.js +303 -96
- package/dist/validate.d.ts +1 -1
- package/dist/validate.js +2 -2
- package/dist/web-fake.js +3 -3
- package/dist/web-fetch-direct.d.ts +4 -0
- package/dist/web-fetch-direct.js +8 -1
- package/dist/web-fetch.d.ts +12 -3
- package/dist/web-fetch.js +47 -14
- package/dist/web-search.d.ts +33 -4
- package/dist/web-search.js +100 -41
- package/dist/webhooks.js +4 -5
- package/dist/workspace/synced-folder.d.ts +1 -1
- package/dist/workspace/synced-folder.js +11 -14
- package/launcher/agentrun-serve +5 -1
- package/package.json +17 -13
- package/templates/README.md +5 -4
- package/templates/agent-scout/agent.md +46 -0
- package/templates/agent-scout/skills/scout/SKILL.md +88 -0
- package/templates/agent-scout/skills/scout/suggestions.schema.json +112 -0
- package/dist/console/assets/index-BFgyZzF_.js +0 -734
- package/dist/console/assets/index-DbilxljH.css +0 -1
- package/dist/import-sources.d.ts +0 -116
- package/dist/import-sources.js +0 -693
package/dist/exa-keyless.js
CHANGED
|
@@ -1,39 +1,33 @@
|
|
|
1
|
-
// web_search's keyless fallback
|
|
2
|
-
// which answers its `web_search_exa` tool
|
|
3
|
-
//
|
|
4
|
-
// `tools/call` of web_search_exa with `{query, numResults}`, at most 8. Exa answers one text block, a result per section
|
|
5
|
-
// `---` lines, each `Title:`, `URL:`, `Published:`, `Author:`, then `Highlights:` (or `Text:`) and its lines; a
|
|
6
|
-
// line may lead it. That text is read into the same Search every web_search answers
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
1
|
+
// web_search's keyless fallback, behind keyless Firecrawl (firecrawl-keyless.ts) or alone where it is picked: Exa's
|
|
2
|
+
// public MCP endpoint (https://mcp.exa.ai/mcp, docs.exa.ai/reference/exa-mcp), which answers its `web_search_exa` tool
|
|
3
|
+
// with no key at a free rate limit. One search is one MCP exchange through the shared client (keyless-mcp.ts callTool):
|
|
4
|
+
// `tools/call` of web_search_exa with `{query, numResults}`, at most 8. Exa answers one text block, a result per section
|
|
5
|
+
// split by `---` lines, each `Title:`, `URL:`, `Published:`, `Author:`, then `Highlights:` (or `Text:`) and its lines; a
|
|
6
|
+
// `Note:` line may lead it. That text is read into the same Search every web_search answers. Past its free limit Exa
|
|
7
|
+
// answers a 429 with Retry-After, or (when its search API refuses the keyless call) a 200 whose tool result is marked
|
|
8
|
+
// isError and `ai.exa/rateLimited`, its text telling the user to put an API key in their MCP URL. Either is tried once
|
|
9
|
+
// more, a new exchange after a jittered 1 to 3 s or the Retry-After Exa names when it is 5 s or less (past that, as with
|
|
10
|
+
// its daily limit, the limit does not lift within a search, and it is not tried again); still limited, the search
|
|
11
|
+
// answers RATE_LIMITED, in our words, never Exa's. Any other failure Exa answers is ours too, quoting only the first
|
|
12
|
+
// sentence of Exa's (exaSaid). A 403 is a connection keyless use refuses (Exa takes it over IPv4, straight to the
|
|
13
|
+
// endpoint), never tried again. Both say which limit they met (ExaLimited), for the caller's breaker. A search ends at
|
|
14
|
+
// 60 s, its retry and wait included. No key is sent, ever. Exa is dialled over IPv4 alone (ipv4Fetch): its name looked
|
|
15
|
+
// up for family 4 and the connection made to that address, so a host whose default route is IPv6 reaches it the one way
|
|
16
|
+
// keyless use is taken.
|
|
17
17
|
import { lookup as dnsLookup } from "node:dns";
|
|
18
|
+
import { callTool, RATE_LIMITED, sleep, textBlocks } from "./keyless-mcp.js";
|
|
18
19
|
import { clip, TITLE_CAP } from "./web-fetch-direct.js";
|
|
19
20
|
import { snippetOf } from "./web-search.js";
|
|
21
|
+
export { RATE_LIMITED };
|
|
20
22
|
export const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
|
|
21
23
|
export const EXA_SEARCH_TOOL = "web_search_exa";
|
|
22
24
|
/** Under `--faux` only: a module whose default export is the fetch Exa's MCP exchange goes through (the tests' fake
|
|
23
25
|
* MCP server), in place of Exa's endpoint. */
|
|
24
26
|
export const FAUX_EXA_ENV = "AGENTRUN_SERVE_FAUX_EXA";
|
|
25
|
-
/** The MCP revision this client speaks; the server answers the one it takes. */
|
|
26
|
-
const PROTOCOL = "2025-06-18";
|
|
27
27
|
const TIMEOUT_MS = 60_000;
|
|
28
28
|
/** The most results Exa's free endpoint is asked for (its default is 10). Its own cap on purpose, not web search's
|
|
29
29
|
* RESULTS_MAX: the hosted providers take more, and Exa's keyless limit is per request. */
|
|
30
30
|
const RESULTS_MAX = 8;
|
|
31
|
-
const ACCEPT = "application/json, text/event-stream";
|
|
32
|
-
/** The most of an answer read: a search's text is a few kilobytes; past this the rest is never read. */
|
|
33
|
-
const MAX_BYTES = 1 << 20;
|
|
34
|
-
/** What a search answers when Exa's free limit holds after the one retry. Exa's own words name a fix (an API key in
|
|
35
|
-
* its MCP URL) that means nothing to a person here, so they are never passed on. */
|
|
36
|
-
export const RATE_LIMITED = "Free web search is rate-limited right now. Try again in a minute; add the free Parallel Search server in Settings → MCP servers and grant the agent its web_search; or add a Parallel key in Settings → API Keys to search with a key.";
|
|
37
31
|
/** The most of Exa's own words a failure quotes: the first sentence of its first line, cut on a word. */
|
|
38
32
|
const SAID_MAX = 120;
|
|
39
33
|
/** A failure Exa answered, in our words: the first sentence of its text, short and quoted. Its later lines (a fix for its
|
|
@@ -48,33 +42,9 @@ function exaSaid(text) {
|
|
|
48
42
|
const RATE_LIMITED_META = "ai.exa/rateLimited";
|
|
49
43
|
/** The longest Retry-After waited out before the one retry. */
|
|
50
44
|
const RETRY_AFTER_MAX_S = 5;
|
|
51
|
-
/** The seconds a Retry-After names, as seconds or a date; undefined when it names none. */
|
|
52
|
-
function retryAfterOf(response) {
|
|
53
|
-
const said = response.headers.get("retry-after")?.trim();
|
|
54
|
-
if (!said)
|
|
55
|
-
return undefined;
|
|
56
|
-
if (/^\d+$/.test(said))
|
|
57
|
-
return Number(said);
|
|
58
|
-
const at = Date.parse(said);
|
|
59
|
-
return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - Date.now()) / 1000));
|
|
60
|
-
}
|
|
61
45
|
/** The wait before the one retry: the Retry-After Exa named, else 1 to 3 s, each with jitter so runs limited together
|
|
62
46
|
* do not all ask again at once. */
|
|
63
47
|
const waitOf = (retryAfterS) => (retryAfterS === undefined ? 1_000 + Math.random() * 2_000 : retryAfterS * 1_000 + Math.random() * 500);
|
|
64
|
-
/** `ms` of waiting that `signal` ends, rejecting with its reason. */
|
|
65
|
-
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
66
|
-
if (signal.aborted)
|
|
67
|
-
return reject(signal.reason);
|
|
68
|
-
const stop = () => {
|
|
69
|
-
clearTimeout(timer);
|
|
70
|
-
reject(signal.reason);
|
|
71
|
-
};
|
|
72
|
-
const timer = setTimeout(() => {
|
|
73
|
-
signal.removeEventListener("abort", stop);
|
|
74
|
-
resolve();
|
|
75
|
-
}, ms);
|
|
76
|
-
signal.addEventListener("abort", stop, { once: true });
|
|
77
|
-
});
|
|
78
48
|
/** A fetch that reaches hosts over IPv4 alone: each name looked up for family 4 (through `lookup`, default the system
|
|
79
49
|
* resolver) and the connection dialled at the address found, never an IPv6 one. undici loads at the first request, so
|
|
80
50
|
* a run that never searches never loads it; `close` ends the connections. */
|
|
@@ -88,36 +58,6 @@ export function ipv4Fetch(lookup = dnsLookup) {
|
|
|
88
58
|
};
|
|
89
59
|
return { send: send, close: async () => void (opened && (await (await opened).dispatcher.close())) };
|
|
90
60
|
}
|
|
91
|
-
/** At most MAX_BYTES of a body, as text; the rest is not read. */
|
|
92
|
-
async function boundedText(response) {
|
|
93
|
-
const reader = response.body?.getReader();
|
|
94
|
-
const chunks = [];
|
|
95
|
-
for (let size = 0; reader && size < MAX_BYTES;) {
|
|
96
|
-
const { done, value } = await reader.read();
|
|
97
|
-
if (done)
|
|
98
|
-
break;
|
|
99
|
-
chunks.push(value);
|
|
100
|
-
size += value.byteLength;
|
|
101
|
-
}
|
|
102
|
-
await reader?.cancel().catch(() => undefined);
|
|
103
|
-
return Buffer.concat(chunks).subarray(0, MAX_BYTES).toString("utf8");
|
|
104
|
-
}
|
|
105
|
-
/** A JSON-RPC answer's body: JSON, or the `data:` lines of an event stream, the one answering `id`. */
|
|
106
|
-
async function answerOf(response, id) {
|
|
107
|
-
const text = await boundedText(response);
|
|
108
|
-
const messages = /event-stream/i.test(response.headers.get("content-type") ?? "")
|
|
109
|
-
? text.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim())
|
|
110
|
-
: [text];
|
|
111
|
-
for (const message of messages) {
|
|
112
|
-
try {
|
|
113
|
-
const parsed = JSON.parse(message);
|
|
114
|
-
if (parsed.id === id)
|
|
115
|
-
return parsed;
|
|
116
|
-
}
|
|
117
|
-
catch { }
|
|
118
|
-
}
|
|
119
|
-
return undefined;
|
|
120
|
-
}
|
|
121
61
|
/** Exa's text for one result as a Hit, or undefined when it names no URL. */
|
|
122
62
|
function hitOf(section) {
|
|
123
63
|
const lines = section.split("\n");
|
|
@@ -131,6 +71,28 @@ function hitOf(section) {
|
|
|
131
71
|
const published = known(field("Published"));
|
|
132
72
|
return { url, title: clip(known(field("Title")) ?? "", TITLE_CAP), snippet: snippetOf(snippet), ...(published ? { published } : {}) };
|
|
133
73
|
}
|
|
74
|
+
/** One exchange's outcome as Exa's answer to a search for `query`, at most `n` results: its refusals and failures in our
|
|
75
|
+
* words, else its hits. */
|
|
76
|
+
function searchOf(called, query, n) {
|
|
77
|
+
if ("status" in called) {
|
|
78
|
+
if (called.status === 429)
|
|
79
|
+
return { error: RATE_LIMITED, limit: "rate_limited", ...(called.retryAfterS === undefined ? {} : { retryAfterS: called.retryAfterS }) };
|
|
80
|
+
if (called.status === 403)
|
|
81
|
+
return { error: "Exa refused keyless use from this connection (403): it takes keyless searches only over IPv4, straight to its endpoint, not over IPv6 or through a proxy", limit: "connection_refused" };
|
|
82
|
+
return { error: `Exa's MCP endpoint answered ${called.status} to ${called.step === "initialize" ? "initialize" : "the search"}` };
|
|
83
|
+
}
|
|
84
|
+
if ("error" in called)
|
|
85
|
+
return { error: called.rpc ? exaSaid(called.error) : "Exa's MCP endpoint did not answer initialize" };
|
|
86
|
+
const { result } = called;
|
|
87
|
+
const meta = result?._meta;
|
|
88
|
+
if (result?.isError === true && typeof meta === "object" && meta !== null && meta[RATE_LIMITED_META] === true)
|
|
89
|
+
return { error: RATE_LIMITED, limit: "rate_limited" };
|
|
90
|
+
const said = textBlocks(result);
|
|
91
|
+
if (!Array.isArray(result?.content) || result.isError === true)
|
|
92
|
+
return { error: exaSaid(said) };
|
|
93
|
+
const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
|
|
94
|
+
return { provider: "exa-keyless", query, results: hits.slice(0, n) };
|
|
95
|
+
}
|
|
134
96
|
/** `query` searched on Exa's keyless MCP endpoint through `send` (a test's fake; default a fetch over IPv4 alone,
|
|
135
97
|
* ipv4Fetch, closed when the search ends), at most `n` results: once, and once more past Exa's free limit after
|
|
136
98
|
* `pause` (default a wait the search's signal ends; a test's records it). */
|
|
@@ -138,12 +100,13 @@ export async function exaSearch(query, n, { send, signal, pause = sleep } = {})
|
|
|
138
100
|
const deadline = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), ...(signal ? [signal] : [])]);
|
|
139
101
|
const own = send ? undefined : ipv4Fetch();
|
|
140
102
|
const dial = send ?? own.send;
|
|
103
|
+
const once = async () => searchOf(await callTool(EXA_MCP_URL, dial, deadline, EXA_SEARCH_TOOL, { query, numResults: Math.min(n, RESULTS_MAX) }), query, n);
|
|
141
104
|
try {
|
|
142
|
-
const first = await
|
|
105
|
+
const first = await once();
|
|
143
106
|
if (!("limit" in first) || first.limit !== "rate_limited" || (first.retryAfterS ?? 0) > RETRY_AFTER_MAX_S)
|
|
144
107
|
return first;
|
|
145
108
|
await pause(waitOf(first.retryAfterS), deadline);
|
|
146
|
-
return await
|
|
109
|
+
return await once();
|
|
147
110
|
}
|
|
148
111
|
catch (error) {
|
|
149
112
|
const name = error?.name;
|
|
@@ -153,50 +116,3 @@ export async function exaSearch(query, n, { send, signal, pause = sleep } = {})
|
|
|
153
116
|
await own?.close().catch(() => undefined);
|
|
154
117
|
}
|
|
155
118
|
}
|
|
156
|
-
/** One MCP exchange searching `query` through `dial`, each request ended by `deadline`; a failure to reach Exa throws. */
|
|
157
|
-
async function exchange(query, n, dial, deadline) {
|
|
158
|
-
let session;
|
|
159
|
-
const post = (body) => dial(EXA_MCP_URL, {
|
|
160
|
-
method: "POST",
|
|
161
|
-
headers: { "content-type": "application/json", accept: ACCEPT, "mcp-protocol-version": PROTOCOL, ...(session ? { "mcp-session-id": session } : {}) },
|
|
162
|
-
body: JSON.stringify({ jsonrpc: "2.0", ...body }),
|
|
163
|
-
signal: deadline,
|
|
164
|
-
});
|
|
165
|
-
const refused = async (response, step) => {
|
|
166
|
-
if (response.ok)
|
|
167
|
-
return undefined;
|
|
168
|
-
await response.body?.cancel().catch(() => undefined);
|
|
169
|
-
if (response.status === 429) {
|
|
170
|
-
const retryAfterS = retryAfterOf(response);
|
|
171
|
-
return { error: RATE_LIMITED, limit: "rate_limited", ...(retryAfterS === undefined ? {} : { retryAfterS }) };
|
|
172
|
-
}
|
|
173
|
-
if (response.status === 403)
|
|
174
|
-
return { error: "Exa refused keyless use from this connection (403): it takes keyless searches only over IPv4, straight to its endpoint, not over IPv6 or through a proxy", limit: "connection_refused" };
|
|
175
|
-
return { error: `Exa's MCP endpoint answered ${response.status} to ${step}` };
|
|
176
|
-
};
|
|
177
|
-
const opened = await post({ id: 1, method: "initialize", params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "agentrun-serve", version: "1" } } });
|
|
178
|
-
const failed = await refused(opened, "initialize");
|
|
179
|
-
if (failed)
|
|
180
|
-
return failed;
|
|
181
|
-
session = opened.headers.get("mcp-session-id") ?? undefined;
|
|
182
|
-
if (!(await answerOf(opened, 1))?.result)
|
|
183
|
-
return { error: "Exa's MCP endpoint did not answer initialize" };
|
|
184
|
-
const ready = await post({ method: "notifications/initialized" });
|
|
185
|
-
await ready.body?.cancel().catch(() => undefined);
|
|
186
|
-
const called = await post({ id: 2, method: "tools/call", params: { name: EXA_SEARCH_TOOL, arguments: { query, numResults: Math.min(n, RESULTS_MAX) } } });
|
|
187
|
-
const late = await refused(called, "the search");
|
|
188
|
-
if (late)
|
|
189
|
-
return late;
|
|
190
|
-
const answer = await answerOf(called, 2);
|
|
191
|
-
if (answer?.error)
|
|
192
|
-
return { error: exaSaid(typeof answer.error.message === "string" ? answer.error.message : "") };
|
|
193
|
-
const meta = answer?.result?._meta;
|
|
194
|
-
if (answer?.result?.isError === true && typeof meta === "object" && meta !== null && meta[RATE_LIMITED_META] === true)
|
|
195
|
-
return { error: RATE_LIMITED, limit: "rate_limited" };
|
|
196
|
-
const content = Array.isArray(answer?.result?.content) ? answer.result.content : undefined;
|
|
197
|
-
const said = content?.flatMap((part) => (part.type === "text" && typeof part.text === "string" ? [part.text] : [])).join("\n") ?? "";
|
|
198
|
-
if (!content || answer?.result?.isError === true)
|
|
199
|
-
return { error: exaSaid(said) };
|
|
200
|
-
const hits = said.split(/\n-{3,}\n/).flatMap((section) => hitOf(section) ?? []);
|
|
201
|
-
return { provider: "exa-keyless", query, results: hits.slice(0, n) };
|
|
202
|
-
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Read } from "./web-fetch-direct.js";
|
|
2
|
+
import { type Limit, type Search } from "./web-search.js";
|
|
3
|
+
export declare const FIRECRAWL_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
|
|
4
|
+
export declare const FIRECRAWL_SEARCH_TOOL = "firecrawl_search";
|
|
5
|
+
export declare const FIRECRAWL_SCRAPE_TOOL = "firecrawl_scrape";
|
|
6
|
+
/** Under `--faux` only: the URL of a fake MCP server (a test's, on loopback) asked in place of Firecrawl's endpoint.
|
|
7
|
+
* Under --faux with none named, Firecrawl is never asked. */
|
|
8
|
+
export declare const FAUX_FIRECRAWL_ENV = "AGENTRUN_SERVE_FAUX_FIRECRAWL";
|
|
9
|
+
/** The most one call to Firecrawl takes: half a search's one deadline (web-search.ts KEYLESS_SEARCH_MS). */
|
|
10
|
+
export declare const FIRECRAWL_MS = 30000;
|
|
11
|
+
/** A call Firecrawl refused or failed, in our words, and the limit it met, if any (for the run's breaker). */
|
|
12
|
+
export type FirecrawlFailed = {
|
|
13
|
+
error: string;
|
|
14
|
+
limit?: Limit;
|
|
15
|
+
};
|
|
16
|
+
/** Where a call goes: `endpoint` (default Firecrawl's), through `send` (default fetch), ended at `timeoutMs` (default
|
|
17
|
+
* FIRECRAWL_MS) or by `signal`, whichever is first. */
|
|
18
|
+
export type FirecrawlOptions = {
|
|
19
|
+
endpoint?: string;
|
|
20
|
+
send?: typeof fetch;
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
};
|
|
24
|
+
/** The limit a refusal's `code` names (QUOTA_CODES, RATE_CODES), with the wait its payload names; undefined for any
|
|
25
|
+
* other code. */
|
|
26
|
+
export declare function firecrawlLimitOf(payload: Record<string, unknown> | undefined): Limit | undefined;
|
|
27
|
+
/** `query` searched on Firecrawl's keyless endpoint, at most `n` results, its answer at most MAX_BYTES. */
|
|
28
|
+
export declare function firecrawlSearch(query: string, n: number, options?: FirecrawlOptions): Promise<Search | FirecrawlFailed>;
|
|
29
|
+
/** The page at `url` scraped by Firecrawl's keyless endpoint, as markdown, its answer at most the direct fetch's bound
|
|
30
|
+
* (pi-browser's PUBLIC_MAX_BYTES). Firecrawl names no cut, so the text is read as the whole page's. A page whose status
|
|
31
|
+
* is not 2xx is no read: the caller fetches directly, as for a refusal. */
|
|
32
|
+
export declare function firecrawlScrape(url: string, options?: FirecrawlOptions): Promise<Read | FirecrawlFailed>;
|
|
33
|
+
/** keyless Firecrawl's scrape for one run's web_fetch, with the run's breaker on it: `live` is false once a quota answer
|
|
34
|
+
* came (for the rest of the run) and while a rate limit's wait holds (waitOf: the wait Firecrawl named, else 60 s, at
|
|
35
|
+
* most 15 minutes); `read` is one scrape, the page or, for any failure, why there is none (the caller then fetches
|
|
36
|
+
* directly). `now` is the breaker's clock (a test's). */
|
|
37
|
+
export type KeylessFetch = {
|
|
38
|
+
live(): boolean;
|
|
39
|
+
read(url: string, signal?: AbortSignal): Promise<Read | string>;
|
|
40
|
+
};
|
|
41
|
+
export declare function firecrawlFetch(options?: Omit<FirecrawlOptions, "signal">, now?: () => number): KeylessFetch;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// Keyless Firecrawl: Firecrawl's public MCP endpoint (https://mcp.firecrawl.dev/v2/mcp, the console's preset too), which
|
|
2
|
+
// answers its keyless tools with no key, under a free daily limit. The default backend of web_search (keyless Exa behind
|
|
3
|
+
// it, web-search.ts) and of web_fetch (the guarded direct fetch behind it, web-fetch.ts). Each call is one MCP exchange
|
|
4
|
+
// through the shared client (keyless-mcp.ts callTool), with no key, no Authorization and no header of our own:
|
|
5
|
+
// `firecrawl_search` with `{query, limit}`, whose text block is JSON, `{success, data: {web: [{url, title, description,
|
|
6
|
+
// position}]}}`; or `firecrawl_scrape` with `{url, formats: ["markdown"]}`, whose text block is JSON, `{markdown,
|
|
7
|
+
// metadata: {title, sourceURL, statusCode, ...}}`. Those are read into the same Search every web_search answers, or the
|
|
8
|
+
// same Read every web_fetch answers. web_fetch sends each URL it reads this way to Firecrawl, a third party; a URL the
|
|
9
|
+
// public-host guard refuses (a private, loopback, link-local or intranet address) never goes (web-fetch.ts).
|
|
10
|
+
//
|
|
11
|
+
// Firecrawl refuses a keyless call it will not serve with a tool result marked isError whose payload (its
|
|
12
|
+
// recoveryPayload: `{code, request_id, auth_mode: "keyless", message, signup_url?, retry_after_seconds?}`) comes as the
|
|
13
|
+
// result's structuredContent or as JSON in its text: both are read, and only `code` is, never the message's words.
|
|
14
|
+
// KEYLESS_QUOTA_EXHAUSTED (its daily limit), KEYLESS_ACCESS_NOT_AVAILABLE and KEYLESS_TOOL_NOT_AVAILABLE are a quota
|
|
15
|
+
// answer: the run's breaker turns Firecrawl off for the rest of the run. KEYLESS_LIMIT_REACHED and an HTTP 429 are a
|
|
16
|
+
// rate limit, with the wait it names (retry_after_seconds, Retry-After), which the breaker holds Firecrawl for. Firecrawl's
|
|
17
|
+
// own words (a link to sign up) are never passed on: a call answers ours. A call is not retried here (the backend behind
|
|
18
|
+
// Firecrawl answers it in its place), and ends at FIRECRAWL_MS (30 s), inside any deadline its caller holds, so a
|
|
19
|
+
// Firecrawl that hangs leaves the backend behind it the rest of a search's 60 s, or a fetch's direct read its own time.
|
|
20
|
+
import { callTool, MAX_BYTES, RATE_LIMITED, textBlocks } from "./keyless-mcp.js";
|
|
21
|
+
import { clip, markdownRead, TITLE_CAP } from "./web-fetch-direct.js";
|
|
22
|
+
import { snippetOf, waitOf } from "./web-search.js";
|
|
23
|
+
export const FIRECRAWL_MCP_URL = "https://mcp.firecrawl.dev/v2/mcp";
|
|
24
|
+
export const FIRECRAWL_SEARCH_TOOL = "firecrawl_search";
|
|
25
|
+
export const FIRECRAWL_SCRAPE_TOOL = "firecrawl_scrape";
|
|
26
|
+
/** Under `--faux` only: the URL of a fake MCP server (a test's, on loopback) asked in place of Firecrawl's endpoint.
|
|
27
|
+
* Under --faux with none named, Firecrawl is never asked. */
|
|
28
|
+
export const FAUX_FIRECRAWL_ENV = "AGENTRUN_SERVE_FAUX_FIRECRAWL";
|
|
29
|
+
/** The most one call to Firecrawl takes: half a search's one deadline (web-search.ts KEYLESS_SEARCH_MS). */
|
|
30
|
+
export const FIRECRAWL_MS = 30_000;
|
|
31
|
+
/** Firecrawl's keyless refusal codes, by what the run's breaker makes of each. */
|
|
32
|
+
const QUOTA_CODES = new Set(["KEYLESS_QUOTA_EXHAUSTED", "KEYLESS_ACCESS_NOT_AVAILABLE", "KEYLESS_TOOL_NOT_AVAILABLE"]);
|
|
33
|
+
const RATE_CODES = new Set(["KEYLESS_LIMIT_REACHED"]);
|
|
34
|
+
/** A refusal's payload: the result's structuredContent, else its text read as JSON; undefined when neither is an object. */
|
|
35
|
+
function payloadOf(result) {
|
|
36
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
37
|
+
if (isObject(result?.structuredContent) && typeof result.structuredContent.code === "string")
|
|
38
|
+
return result.structuredContent;
|
|
39
|
+
try {
|
|
40
|
+
const parsed = JSON.parse(textBlocks(result));
|
|
41
|
+
return isObject(parsed) ? parsed : undefined;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** The limit a refusal's `code` names (QUOTA_CODES, RATE_CODES), with the wait its payload names; undefined for any
|
|
48
|
+
* other code. */
|
|
49
|
+
export function firecrawlLimitOf(payload) {
|
|
50
|
+
const code = payload?.code;
|
|
51
|
+
if (typeof code !== "string")
|
|
52
|
+
return undefined;
|
|
53
|
+
if (QUOTA_CODES.has(code))
|
|
54
|
+
return { kind: "quota" };
|
|
55
|
+
if (!RATE_CODES.has(code))
|
|
56
|
+
return undefined;
|
|
57
|
+
const seconds = payload.retry_after_seconds;
|
|
58
|
+
if (typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0)
|
|
59
|
+
return { kind: "rate", retryAfter: seconds };
|
|
60
|
+
return { kind: "rate" };
|
|
61
|
+
}
|
|
62
|
+
/** What a call answers for a limit Firecrawl met. */
|
|
63
|
+
const limitWords = (limit, what) => (limit.kind === "rate" ? RATE_LIMITED : `Keyless Firecrawl will not serve this server's ${what}es now (its free limit is spent, or keyless use is not open to it): it is not asked again in this run`);
|
|
64
|
+
/** One call's outcome as Firecrawl's answer to `what`: its refusals and failures in our words, else `read` of the result's
|
|
65
|
+
* JSON text. */
|
|
66
|
+
function readCalled(called, what, read) {
|
|
67
|
+
if ("status" in called) {
|
|
68
|
+
if (called.status === 429) {
|
|
69
|
+
const limit = { kind: "rate", ...(called.retryAfterS === undefined ? {} : { retryAfter: called.retryAfterS }) };
|
|
70
|
+
return { error: limitWords(limit, what), limit };
|
|
71
|
+
}
|
|
72
|
+
return { error: `Firecrawl's MCP endpoint answered ${called.status} to ${called.step === "initialize" ? "initialize" : `the ${what}`}` };
|
|
73
|
+
}
|
|
74
|
+
if ("over" in called)
|
|
75
|
+
return { error: `Firecrawl's ${what} answered more than ${called.over / MAX_BYTES} MiB: not read` };
|
|
76
|
+
if ("error" in called)
|
|
77
|
+
return { error: called.rpc ? `Firecrawl's ${what} failed: its MCP endpoint answered an error` : "Firecrawl's MCP endpoint did not answer initialize" };
|
|
78
|
+
const { result } = called;
|
|
79
|
+
if (result?.isError === true) {
|
|
80
|
+
const payload = payloadOf(result);
|
|
81
|
+
const limit = firecrawlLimitOf(payload);
|
|
82
|
+
if (limit)
|
|
83
|
+
return { error: limitWords(limit, what), limit };
|
|
84
|
+
return { error: typeof payload?.code === "string" ? `Firecrawl's ${what} failed (${clip(payload.code, 60)})` : `Firecrawl's ${what} failed` };
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(textBlocks(result));
|
|
88
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
|
|
89
|
+
return read(parsed);
|
|
90
|
+
}
|
|
91
|
+
catch { }
|
|
92
|
+
return { error: `Firecrawl's ${what} answered no result this server reads` };
|
|
93
|
+
}
|
|
94
|
+
/** The tool `name` with `args` on Firecrawl's keyless endpoint, its answer bounded at `maxBytes`, read by `read`: once. */
|
|
95
|
+
async function firecrawlCall(name, args, what, maxBytes, read, { endpoint = FIRECRAWL_MCP_URL, send = fetch, signal, timeoutMs = FIRECRAWL_MS }) {
|
|
96
|
+
const own = AbortSignal.timeout(timeoutMs);
|
|
97
|
+
const deadline = AbortSignal.any([own, ...(signal ? [signal] : [])]);
|
|
98
|
+
try {
|
|
99
|
+
return readCalled(await callTool(endpoint, send, deadline, name, args, maxBytes), what, read);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
// Firecrawl's own bound, or the caller's: its deadline (a search's, spent) or its stop.
|
|
103
|
+
if (own.aborted)
|
|
104
|
+
return { error: `Firecrawl's ${what} did not answer within ${timeoutMs / 1000} s` };
|
|
105
|
+
const reason = signal?.aborted ? signal.reason?.name : error?.name;
|
|
106
|
+
return { error: reason === "TimeoutError" ? `Firecrawl's ${what} did not answer before the ${what}'s time ran out` : reason === "AbortError" ? `the ${what} was stopped` : `Firecrawl's ${what} failed: ${String(error?.message ?? error).slice(0, 300)}` };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** `query` searched on Firecrawl's keyless endpoint, at most `n` results, its answer at most MAX_BYTES. */
|
|
110
|
+
export async function firecrawlSearch(query, n, options = {}) {
|
|
111
|
+
return firecrawlCall(FIRECRAWL_SEARCH_TOOL, { query, limit: n }, "search", MAX_BYTES, (json) => {
|
|
112
|
+
const data = json.data;
|
|
113
|
+
const rows = Array.isArray(data) ? data : Array.isArray(data?.web) ? data.web : undefined;
|
|
114
|
+
if (!rows)
|
|
115
|
+
return { error: "Firecrawl's search answered no results this server reads" };
|
|
116
|
+
const hits = rows.flatMap((row) => (typeof row?.url === "string" && URL.canParse(row.url) ? [{ url: row.url, title: typeof row.title === "string" ? clip(row.title, TITLE_CAP) : "", snippet: snippetOf(typeof row.description === "string" ? row.description : "") }] : []));
|
|
117
|
+
return { provider: "firecrawl-keyless", query, results: hits.slice(0, n) };
|
|
118
|
+
}, options);
|
|
119
|
+
}
|
|
120
|
+
/** The page at `url` scraped by Firecrawl's keyless endpoint, as markdown, its answer at most the direct fetch's bound
|
|
121
|
+
* (pi-browser's PUBLIC_MAX_BYTES). Firecrawl names no cut, so the text is read as the whole page's. A page whose status
|
|
122
|
+
* is not 2xx is no read: the caller fetches directly, as for a refusal. */
|
|
123
|
+
export async function firecrawlScrape(url, options = {}) {
|
|
124
|
+
const { PUBLIC_MAX_BYTES } = await import("@parcha/pi-browser");
|
|
125
|
+
return firecrawlCall(FIRECRAWL_SCRAPE_TOOL, { url, formats: ["markdown"] }, "fetch", PUBLIC_MAX_BYTES, (json) => {
|
|
126
|
+
if (typeof json.markdown !== "string" || json.markdown.trim() === "")
|
|
127
|
+
return { error: "Firecrawl's fetch answered no page text" };
|
|
128
|
+
const meta = (typeof json.metadata === "object" && json.metadata !== null ? json.metadata : {});
|
|
129
|
+
const final = [meta.url, meta.sourceURL].find((one) => typeof one === "string" && URL.canParse(one)) ?? url;
|
|
130
|
+
const status = typeof meta.statusCode === "number" && Number.isInteger(meta.statusCode) ? meta.statusCode : 200;
|
|
131
|
+
if (status < 200 || status > 299)
|
|
132
|
+
return { error: `Firecrawl's fetch: the page answered ${status}` };
|
|
133
|
+
return markdownRead(final, typeof meta.title === "string" ? meta.title : "", json.markdown, true, status);
|
|
134
|
+
}, options);
|
|
135
|
+
}
|
|
136
|
+
export function firecrawlFetch(options = {}, now = Date.now) {
|
|
137
|
+
let off = false;
|
|
138
|
+
let until = 0;
|
|
139
|
+
return {
|
|
140
|
+
live: () => !off && now() >= until,
|
|
141
|
+
async read(url, signal) {
|
|
142
|
+
const read = await firecrawlScrape(url, { ...options, ...(signal ? { signal } : {}) });
|
|
143
|
+
if ("ok" in read)
|
|
144
|
+
return read;
|
|
145
|
+
if (read.limit?.kind === "quota")
|
|
146
|
+
off = true;
|
|
147
|
+
else if (read.limit)
|
|
148
|
+
until = Math.max(until, now() + waitOf(read.limit.retryAfter, now()));
|
|
149
|
+
return read.error;
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
@@ -5,7 +5,8 @@ import type { Held } from "./template-github-permissions.js";
|
|
|
5
5
|
import { type Json } from "./validate.js";
|
|
6
6
|
/** What every GitHub App Connect GitHub makes asks of the repositories it is installed on (its manifest's
|
|
7
7
|
* default_permissions): the least its templates need. Applying a template warns from each installation's real permissions
|
|
8
|
-
* (installationPermissions, template-github-permissions.ts), never from this.
|
|
8
|
+
* (installationPermissions, template-github-permissions.ts), never from this. A Connect that asks for `contents: write`
|
|
9
|
+
* (suggested agents' pull requests, which add files) gets that one widened; nothing else ever is. */
|
|
9
10
|
export declare const APP_PERMISSIONS: {
|
|
10
11
|
readonly pull_requests: "write";
|
|
11
12
|
readonly contents: "read";
|
|
@@ -36,6 +37,22 @@ export type Installation = {
|
|
|
36
37
|
id: number;
|
|
37
38
|
account: string;
|
|
38
39
|
};
|
|
40
|
+
/** The installation that covers one repository, and what it holds there (suggestions.ts reads it before a pull request). */
|
|
41
|
+
export type RepoInstallation = {
|
|
42
|
+
id: number;
|
|
43
|
+
account: string;
|
|
44
|
+
organization: boolean;
|
|
45
|
+
permissions: Record<string, "read" | "write">;
|
|
46
|
+
};
|
|
47
|
+
/** One repository an installation covers, as GET /v2/integrations/github/repositories lists it. */
|
|
48
|
+
export type ListedRepository = {
|
|
49
|
+
full_name: string;
|
|
50
|
+
private: boolean;
|
|
51
|
+
default_branch?: string;
|
|
52
|
+
description?: string;
|
|
53
|
+
account: string;
|
|
54
|
+
installation: number;
|
|
55
|
+
};
|
|
39
56
|
/** What a caller (a GitHub template, the console) may read of the connection: never a secret. */
|
|
40
57
|
export type GitHubConnectionView = {
|
|
41
58
|
app_id: string;
|
|
@@ -206,6 +223,38 @@ export declare class GitHubConnect {
|
|
|
206
223
|
* server (only GitHub's API sees it), revoked at once, whatever the answer. A read GitHub did not answer (a 429, a
|
|
207
224
|
* 5xx, nothing) is UNANSWERED, never "none". */
|
|
208
225
|
private firstRepository;
|
|
226
|
+
/** GitHub's API this connection calls (GitHub's own, or a fake's). */
|
|
227
|
+
get api(): string;
|
|
228
|
+
/** The App's installation that covers `repo` (GET /repos/{owner}/{repo}/installation, with the App's JWT), with the
|
|
229
|
+
* account it is on and what it holds (`admin` read as `write`), or why there is none: no App here, not installed there,
|
|
230
|
+
* or GitHub that did not answer. Suggested agents read it before a pull request, to say what is missing first. */
|
|
231
|
+
repoInstallation(repo: string, signal?: AbortSignal): Promise<RepoInstallation | {
|
|
232
|
+
unusable: string;
|
|
233
|
+
reason: "not_connected" | "not_installed" | "github_failed";
|
|
234
|
+
}>;
|
|
235
|
+
/** An installation token of installation `id` for `repo` alone with `permissions` (each at most what it holds), kept
|
|
236
|
+
* among the live tokens; or why GitHub gave none. Revoke it (revokeToken) once its one job is done. */
|
|
237
|
+
tokenWith(id: number, repo: string, permissions: Record<string, "read" | "write">, signal?: AbortSignal): Promise<{
|
|
238
|
+
token: string;
|
|
239
|
+
expiresAt: number;
|
|
240
|
+
} | {
|
|
241
|
+
unusable: string;
|
|
242
|
+
}>;
|
|
243
|
+
/** An installation token revoked at GitHub (DELETE /installation/token, the token its own credential): best effort. */
|
|
244
|
+
revokeToken(token: string): Promise<void>;
|
|
245
|
+
/** Every repository the App's installations cover, as GitHub lists them (GET /installation/repositories with a
|
|
246
|
+
* metadata-read token per installation, revoked at once), at most `limit` in all; `truncated` when there were more.
|
|
247
|
+
* An installation GitHub did not list is said in `unread`, never left out silently. */
|
|
248
|
+
repositories(signal?: AbortSignal, limit?: number): Promise<{
|
|
249
|
+
repositories: ListedRepository[];
|
|
250
|
+
truncated: boolean;
|
|
251
|
+
unread: {
|
|
252
|
+
account: string;
|
|
253
|
+
why: string;
|
|
254
|
+
}[];
|
|
255
|
+
} | {
|
|
256
|
+
unusable: string;
|
|
257
|
+
}>;
|
|
209
258
|
private mint;
|
|
210
259
|
}
|
|
211
260
|
/** GitHub that did not answer a listing token's call: a 429, a 5xx, a rate limit's 403, or no answer at all. Nothing is
|
|
@@ -15,7 +15,8 @@ registerSecretWrite("disconnectGitHub", () => true);
|
|
|
15
15
|
registerSecretPage(["connectGitHub", "disconnectGitHub"], "/#/settings/github");
|
|
16
16
|
/** What every GitHub App Connect GitHub makes asks of the repositories it is installed on (its manifest's
|
|
17
17
|
* default_permissions): the least its templates need. Applying a template warns from each installation's real permissions
|
|
18
|
-
* (installationPermissions, template-github-permissions.ts), never from this.
|
|
18
|
+
* (installationPermissions, template-github-permissions.ts), never from this. A Connect that asks for `contents: write`
|
|
19
|
+
* (suggested agents' pull requests, which add files) gets that one widened; nothing else ever is. */
|
|
19
20
|
export const APP_PERMISSIONS = { pull_requests: "write", contents: "read", metadata: "read", issues: "read" };
|
|
20
21
|
/** How long a Connect's state is good for, and the most kept at once. */
|
|
21
22
|
export const STATE_MS = 60 * 60 * 1000;
|
|
@@ -186,9 +187,11 @@ export class GitHubConnect {
|
|
|
186
187
|
/** POST /integrations/github/connect: the form the console posts to GitHub (its action, with the state, and the
|
|
187
188
|
* manifest), refused while GitHub could not reach this server, nothing could be kept, or an App is connected. */
|
|
188
189
|
start(body, origin) {
|
|
189
|
-
const issues = Object.keys(body).filter((key) => key !== "org").map((key) => ({ field: key, reason: "not_allowed", message: `The body keeps no field ${key}.` }));
|
|
190
|
+
const issues = Object.keys(body).filter((key) => key !== "org" && key !== "contents").map((key) => ({ field: key, reason: "not_allowed", message: `The body keeps no field ${key}.` }));
|
|
190
191
|
if (body.org !== undefined && !(typeof body.org === "string" && LOGIN.test(body.org)))
|
|
191
192
|
issues.push({ field: "org", reason: "invalid", message: "org is a GitHub organization's login: the App is made under it (absent: under the signed-in GitHub user)" });
|
|
193
|
+
if (body.contents !== undefined && body.contents !== "read" && body.contents !== "write")
|
|
194
|
+
issues.push({ field: "contents", reason: "not_an_option", message: "contents is read (the default) or write: write lets suggested agents open pull requests that add files" });
|
|
192
195
|
if (issues.length)
|
|
193
196
|
throw invalid(issues);
|
|
194
197
|
const base = this.options.publicUrl;
|
|
@@ -213,7 +216,8 @@ export class GitHubConnect {
|
|
|
213
216
|
setup_url: `${base}${INSTALLED_PATH}`,
|
|
214
217
|
setup_on_update: true,
|
|
215
218
|
public: false,
|
|
216
|
-
|
|
219
|
+
// Contents write only when the owner asked for it (suggested agents' pull requests add files): never by default.
|
|
220
|
+
default_permissions: { ...APP_PERMISSIONS, ...(body.contents === "write" ? { contents: "write" } : {}) },
|
|
217
221
|
// The events the templates' github triggers take: code-review's pull requests and comments, release-notes'
|
|
218
222
|
// published releases. A trigger takes only what the App is subscribed to.
|
|
219
223
|
default_events: ["pull_request", "issue_comment", "release"],
|
|
@@ -656,6 +660,95 @@ export class GitHubConnect {
|
|
|
656
660
|
await githubCall(this.options.api, "/installation/token", { method: "DELETE", jwt: scout.token }).catch(() => undefined);
|
|
657
661
|
}
|
|
658
662
|
}
|
|
663
|
+
/** GitHub's API this connection calls (GitHub's own, or a fake's). */
|
|
664
|
+
get api() {
|
|
665
|
+
return this.options.api;
|
|
666
|
+
}
|
|
667
|
+
/** The App's installation that covers `repo` (GET /repos/{owner}/{repo}/installation, with the App's JWT), with the
|
|
668
|
+
* account it is on and what it holds (`admin` read as `write`), or why there is none: no App here, not installed there,
|
|
669
|
+
* or GitHub that did not answer. Suggested agents read it before a pull request, to say what is missing first. */
|
|
670
|
+
async repoInstallation(repo, signal) {
|
|
671
|
+
const credentials = this.connection.credentials();
|
|
672
|
+
if (!credentials || !this.connection.view())
|
|
673
|
+
return { unusable: "This server has no GitHub App: connect GitHub in Settings → GitHub.", reason: "not_connected" };
|
|
674
|
+
const jwt = appJwt(credentials.appId, credentials.pem, this.options.now?.() ?? Date.now());
|
|
675
|
+
const answer = await githubCall(this.options.api, `/repos/${repo}/installation`, { jwt, ...(signal ? { signal } : {}) }).catch((error) => ({ status: 0, json: null, headers: new Headers(), error }));
|
|
676
|
+
if (answer.status === 404)
|
|
677
|
+
return { unusable: `The GitHub App isn't installed on ${repo}: add the repository to its installation on GitHub.`, reason: "not_installed" };
|
|
678
|
+
const id = isObject(answer.json) ? answer.json.id : undefined;
|
|
679
|
+
const account = isObject(answer.json) && isObject(answer.json.account) ? answer.json.account : {};
|
|
680
|
+
const map = isObject(answer.json) && isObject(answer.json.permissions) ? answer.json.permissions : undefined;
|
|
681
|
+
if (answer.status !== 200 || !Number.isSafeInteger(id) || !map)
|
|
682
|
+
return { unusable: `GitHub did not say which installation covers ${repo}${answer.status ? ` (HTTP ${answer.status})` : ""}: try again.`, reason: "github_failed" };
|
|
683
|
+
const permissions = {};
|
|
684
|
+
for (const [name, level] of Object.entries(map))
|
|
685
|
+
if (level === "read" || level === "write" || level === "admin")
|
|
686
|
+
permissions[name] = level === "read" ? "read" : "write";
|
|
687
|
+
return { id: id, account: typeof account.login === "string" ? account.login : "", organization: account.type === "Organization", permissions };
|
|
688
|
+
}
|
|
689
|
+
/** An installation token of installation `id` for `repo` alone with `permissions` (each at most what it holds), kept
|
|
690
|
+
* among the live tokens; or why GitHub gave none. Revoke it (revokeToken) once its one job is done. */
|
|
691
|
+
async tokenWith(id, repo, permissions, signal) {
|
|
692
|
+
const credentials = this.connection.credentials();
|
|
693
|
+
if (!credentials)
|
|
694
|
+
return { unusable: "This server has no GitHub App: connect GitHub in Settings → GitHub." };
|
|
695
|
+
const jwt = appJwt(credentials.appId, credentials.pem, this.options.now?.() ?? Date.now());
|
|
696
|
+
const minted = await this.mint(id, jwt, [repo.split("/")[1]], { unusable: `GitHub gave no token for ${repo} with ${Object.entries(permissions).map(([name, level]) => `${name}: ${level}`).join(", ")}.` }, signal, permissions);
|
|
697
|
+
return "failed" in minted ? { unusable: minted.failed } : minted;
|
|
698
|
+
}
|
|
699
|
+
/** An installation token revoked at GitHub (DELETE /installation/token, the token its own credential): best effort. */
|
|
700
|
+
async revokeToken(token) {
|
|
701
|
+
await githubCall(this.options.api, "/installation/token", { method: "DELETE", jwt: token }).catch(() => undefined);
|
|
702
|
+
this.live.delete(token);
|
|
703
|
+
}
|
|
704
|
+
/** Every repository the App's installations cover, as GitHub lists them (GET /installation/repositories with a
|
|
705
|
+
* metadata-read token per installation, revoked at once), at most `limit` in all; `truncated` when there were more.
|
|
706
|
+
* An installation GitHub did not list is said in `unread`, never left out silently. */
|
|
707
|
+
async repositories(signal, limit = 500) {
|
|
708
|
+
const credentials = this.connection.credentials();
|
|
709
|
+
const view = this.connection.view();
|
|
710
|
+
if (!credentials || !view)
|
|
711
|
+
return { unusable: "This server has no GitHub App: connect GitHub in Settings → GitHub." };
|
|
712
|
+
const jwt = appJwt(credentials.appId, credentials.pem, this.options.now?.() ?? Date.now());
|
|
713
|
+
const repositories = [];
|
|
714
|
+
const unread = [];
|
|
715
|
+
let truncated = false;
|
|
716
|
+
for (const installation of view.installations) {
|
|
717
|
+
const refused = { unusable: `GitHub gave no token to list the repositories of the installation on ${installation.account}.` };
|
|
718
|
+
const minted = await this.mint(installation.id, jwt, undefined, refused, signal, { metadata: "read" });
|
|
719
|
+
if (!("token" in minted)) {
|
|
720
|
+
unread.push({ account: installation.account, why: "failed" in minted ? minted.failed : minted.unusable });
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
try {
|
|
724
|
+
for (let page = 1; page <= 10; page++) {
|
|
725
|
+
const listed = await githubCall(this.options.api, `/installation/repositories?per_page=100&page=${page}`, { jwt: minted.token, ...(signal ? { signal } : {}) }).catch(() => undefined);
|
|
726
|
+
const list = listed && listed.status === 200 && isObject(listed.json) && Array.isArray(listed.json.repositories) ? listed.json.repositories : undefined;
|
|
727
|
+
if (!list) {
|
|
728
|
+
unread.push({ account: installation.account, why: `GitHub did not list its repositories${listed ? ` (HTTP ${listed.status})` : ""}` });
|
|
729
|
+
break;
|
|
730
|
+
}
|
|
731
|
+
for (const repo of list) {
|
|
732
|
+
if (!isObject(repo) || typeof repo.full_name !== "string")
|
|
733
|
+
continue;
|
|
734
|
+
if (repositories.length >= limit) {
|
|
735
|
+
truncated = true;
|
|
736
|
+
break;
|
|
737
|
+
}
|
|
738
|
+
repositories.push({ full_name: repo.full_name, private: repo.private === true, ...(typeof repo.default_branch === "string" ? { default_branch: repo.default_branch } : {}), ...(typeof repo.description === "string" && repo.description ? { description: repo.description.slice(0, 300) } : {}), account: installation.account, installation: installation.id });
|
|
739
|
+
}
|
|
740
|
+
const total = isObject(listed.json) && typeof listed.json.total_count === "number" ? listed.json.total_count : 0;
|
|
741
|
+
if (truncated || list.length < 100 || page * 100 >= total)
|
|
742
|
+
break;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
finally {
|
|
746
|
+
await this.revokeToken(minted.token);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
repositories.sort((a, b) => a.full_name.localeCompare(b.full_name));
|
|
750
|
+
return { repositories, truncated, unread };
|
|
751
|
+
}
|
|
659
752
|
async mint(installation, jwt, repositories, refused, signal, permissions) {
|
|
660
753
|
const body = { ...(repositories ? { repositories } : {}), ...(permissions ? { permissions } : {}) };
|
|
661
754
|
const answer = await githubCall(this.options.api, `/app/installations/${installation}/access_tokens`, { method: "POST", jwt, ...(Object.keys(body).length ? { body } : {}), ...(signal ? { signal } : {}) }).catch(() => undefined);
|