agent-recall-mcp 3.5.2 → 3.5.4
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/README.md +254 -143
- package/dist/build-server.d.ts +28 -0
- package/dist/build-server.d.ts.map +1 -0
- package/dist/build-server.js +55 -0
- package/dist/build-server.js.map +1 -0
- package/dist/http/activity.d.ts +60 -0
- package/dist/http/activity.d.ts.map +1 -0
- package/dist/http/activity.js +254 -0
- package/dist/http/activity.js.map +1 -0
- package/dist/http/alerts.d.ts +84 -0
- package/dist/http/alerts.d.ts.map +1 -0
- package/dist/http/alerts.js +213 -0
- package/dist/http/alerts.js.map +1 -0
- package/dist/http/cli.d.ts +3 -0
- package/dist/http/cli.d.ts.map +1 -0
- package/dist/http/cli.js +515 -0
- package/dist/http/cli.js.map +1 -0
- package/dist/http/export-tar.d.ts +23 -0
- package/dist/http/export-tar.d.ts.map +1 -0
- package/dist/http/export-tar.js +264 -0
- package/dist/http/export-tar.js.map +1 -0
- package/dist/http/federation.d.ts +45 -0
- package/dist/http/federation.d.ts.map +1 -0
- package/dist/http/federation.js +185 -0
- package/dist/http/federation.js.map +1 -0
- package/dist/http/film/film.css +80 -0
- package/dist/http/film/film.js +446 -0
- package/dist/http/film/human.jpg +0 -0
- package/dist/http/film/m0.jpg +0 -0
- package/dist/http/film/m2.jpg +0 -0
- package/dist/http/film/m3.jpg +0 -0
- package/dist/http/film/wrong.jpg +0 -0
- package/dist/http/film.d.ts +16 -0
- package/dist/http/film.d.ts.map +1 -0
- package/dist/http/film.js +119 -0
- package/dist/http/film.js.map +1 -0
- package/dist/http/home/cabinet.svg +1 -0
- package/dist/http/home/drawer-project.svg +1 -0
- package/dist/http/home/drawer-rules.svg +1 -0
- package/dist/http/home/drawer-you.svg +1 -0
- package/dist/http/home/fig1.svg +242 -0
- package/dist/http/home/fig2-1.svg +61 -0
- package/dist/http/home/fig2-2.svg +92 -0
- package/dist/http/home/fig3.svg +1 -0
- package/dist/http/home/home.css +509 -0
- package/dist/http/home/home.html +517 -0
- package/dist/http/home/icons.svg +15 -0
- package/dist/http/home.d.ts +23 -0
- package/dist/http/home.d.ts.map +1 -0
- package/dist/http/home.js +295 -0
- package/dist/http/home.js.map +1 -0
- package/dist/http/identities.d.ts +29 -0
- package/dist/http/identities.d.ts.map +1 -0
- package/dist/http/identities.js +91 -0
- package/dist/http/identities.js.map +1 -0
- package/dist/http/import-memory.d.ts +161 -0
- package/dist/http/import-memory.d.ts.map +1 -0
- package/dist/http/import-memory.js +718 -0
- package/dist/http/import-memory.js.map +1 -0
- package/dist/http/jsonfile.d.ts +6 -0
- package/dist/http/jsonfile.d.ts.map +1 -0
- package/dist/http/jsonfile.js +60 -0
- package/dist/http/jsonfile.js.map +1 -0
- package/dist/http/legal/PRIVACY.md +70 -0
- package/dist/http/legal.d.ts +10 -0
- package/dist/http/legal.d.ts.map +1 -0
- package/dist/http/legal.js +35 -0
- package/dist/http/legal.js.map +1 -0
- package/dist/http/limits.d.ts +59 -0
- package/dist/http/limits.d.ts.map +1 -0
- package/dist/http/limits.js +163 -0
- package/dist/http/limits.js.map +1 -0
- package/dist/http/markdown-lite.d.ts +2 -0
- package/dist/http/markdown-lite.d.ts.map +1 -0
- package/dist/http/markdown-lite.js +86 -0
- package/dist/http/markdown-lite.js.map +1 -0
- package/dist/http/multipart.d.ts +43 -0
- package/dist/http/multipart.d.ts.map +1 -0
- package/dist/http/multipart.js +152 -0
- package/dist/http/multipart.js.map +1 -0
- package/dist/http/oauth-app.d.ts +75 -0
- package/dist/http/oauth-app.d.ts.map +1 -0
- package/dist/http/oauth-app.js +259 -0
- package/dist/http/oauth-app.js.map +1 -0
- package/dist/http/oauth-config.d.ts +46 -0
- package/dist/http/oauth-config.d.ts.map +1 -0
- package/dist/http/oauth-config.js +122 -0
- package/dist/http/oauth-config.js.map +1 -0
- package/dist/http/oauth-pages.d.ts +40 -0
- package/dist/http/oauth-pages.d.ts.map +1 -0
- package/dist/http/oauth-pages.js +97 -0
- package/dist/http/oauth-pages.js.map +1 -0
- package/dist/http/oauth-provider.d.ts +124 -0
- package/dist/http/oauth-provider.d.ts.map +1 -0
- package/dist/http/oauth-provider.js +486 -0
- package/dist/http/oauth-provider.js.map +1 -0
- package/dist/http/oauth-store.d.ts +128 -0
- package/dist/http/oauth-store.d.ts.map +1 -0
- package/dist/http/oauth-store.js +317 -0
- package/dist/http/oauth-store.js.map +1 -0
- package/dist/http/redirect-policy.d.ts +16 -0
- package/dist/http/redirect-policy.d.ts.map +1 -0
- package/dist/http/redirect-policy.js +83 -0
- package/dist/http/redirect-policy.js.map +1 -0
- package/dist/http/review-pages.d.ts +39 -0
- package/dist/http/review-pages.d.ts.map +1 -0
- package/dist/http/review-pages.js +78 -0
- package/dist/http/review-pages.js.map +1 -0
- package/dist/http/review.d.ts +36 -0
- package/dist/http/review.d.ts.map +1 -0
- package/dist/http/review.js +220 -0
- package/dist/http/review.js.map +1 -0
- package/dist/http/serve.d.ts +58 -0
- package/dist/http/serve.d.ts.map +1 -0
- package/dist/http/serve.js +324 -0
- package/dist/http/serve.js.map +1 -0
- package/dist/http/site-pages.d.ts +110 -0
- package/dist/http/site-pages.d.ts.map +1 -0
- package/dist/http/site-pages.js +630 -0
- package/dist/http/site-pages.js.map +1 -0
- package/dist/http/site-theme.d.ts +13 -0
- package/dist/http/site-theme.d.ts.map +1 -0
- package/dist/http/site-theme.js +22 -0
- package/dist/http/site-theme.js.map +1 -0
- package/dist/http/site.d.ts +52 -0
- package/dist/http/site.d.ts.map +1 -0
- package/dist/http/site.js +353 -0
- package/dist/http/site.js.map +1 -0
- package/dist/http/stats.d.ts +139 -0
- package/dist/http/stats.d.ts.map +1 -0
- package/dist/http/stats.js +599 -0
- package/dist/http/stats.js.map +1 -0
- package/dist/http/tar-import.d.ts +69 -0
- package/dist/http/tar-import.d.ts.map +1 -0
- package/dist/http/tar-import.js +234 -0
- package/dist/http/tar-import.js.map +1 -0
- package/dist/http/tenant-paths.d.ts +14 -0
- package/dist/http/tenant-paths.d.ts.map +1 -0
- package/dist/http/tenant-paths.js +42 -0
- package/dist/http/tenant-paths.js.map +1 -0
- package/dist/http/tokens.d.ts +32 -0
- package/dist/http/tokens.d.ts.map +1 -0
- package/dist/http/tokens.js +137 -0
- package/dist/http/tokens.js.map +1 -0
- package/dist/http/trial.d.ts +55 -0
- package/dist/http/trial.d.ts.map +1 -0
- package/dist/http/trial.js +218 -0
- package/dist/http/trial.js.map +1 -0
- package/dist/http/web-session.d.ts +108 -0
- package/dist/http/web-session.d.ts.map +1 -0
- package/dist/http/web-session.js +267 -0
- package/dist/http/web-session.js.map +1 -0
- package/dist/index.js +12 -65
- package/dist/index.js.map +1 -1
- package/dist/lib/ambient-capture.d.ts.map +1 -1
- package/dist/lib/ambient-capture.js +4 -1
- package/dist/lib/ambient-capture.js.map +1 -1
- package/dist/lib/bookkeeping.d.ts +26 -0
- package/dist/lib/bookkeeping.d.ts.map +1 -0
- package/dist/lib/bookkeeping.js +31 -0
- package/dist/lib/bookkeeping.js.map +1 -0
- package/dist/lib/hosted-redact.d.ts +17 -0
- package/dist/lib/hosted-redact.d.ts.map +1 -0
- package/dist/lib/hosted-redact.js +57 -0
- package/dist/lib/hosted-redact.js.map +1 -0
- package/dist/lib/lifecycle-exit.d.ts +5 -13
- package/dist/lib/lifecycle-exit.d.ts.map +1 -1
- package/dist/lib/lifecycle-exit.js +38 -16
- package/dist/lib/lifecycle-exit.js.map +1 -1
- package/dist/server.d.ts +3 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +6 -3
- package/dist/server.js.map +1 -1
- package/dist/tools/annotations.d.ts +65 -0
- package/dist/tools/annotations.d.ts.map +1 -0
- package/dist/tools/annotations.js +4 -0
- package/dist/tools/annotations.js.map +1 -0
- package/dist/tools/check-action.d.ts.map +1 -1
- package/dist/tools/check-action.js +2 -0
- package/dist/tools/check-action.js.map +1 -1
- package/dist/tools/check.d.ts.map +1 -1
- package/dist/tools/check.js +6 -2
- package/dist/tools/check.js.map +1 -1
- package/dist/tools/digest.d.ts.map +1 -1
- package/dist/tools/digest.js +2 -0
- package/dist/tools/digest.js.map +1 -1
- package/dist/tools/pipeline-close.d.ts.map +1 -1
- package/dist/tools/pipeline-close.js +2 -0
- package/dist/tools/pipeline-close.js.map +1 -1
- package/dist/tools/pipeline-current.d.ts.map +1 -1
- package/dist/tools/pipeline-current.js +2 -0
- package/dist/tools/pipeline-current.js.map +1 -1
- package/dist/tools/pipeline-list.d.ts.map +1 -1
- package/dist/tools/pipeline-list.js +2 -0
- package/dist/tools/pipeline-list.js.map +1 -1
- package/dist/tools/pipeline-open.d.ts.map +1 -1
- package/dist/tools/pipeline-open.js +2 -0
- package/dist/tools/pipeline-open.js.map +1 -1
- package/dist/tools/pipeline-show.d.ts.map +1 -1
- package/dist/tools/pipeline-show.js +2 -0
- package/dist/tools/pipeline-show.js.map +1 -1
- package/dist/tools/recall.d.ts.map +1 -1
- package/dist/tools/recall.js +4 -1
- package/dist/tools/recall.js.map +1 -1
- package/dist/tools/register-rule.d.ts.map +1 -1
- package/dist/tools/register-rule.js +2 -0
- package/dist/tools/register-rule.js.map +1 -1
- package/dist/tools/remember.d.ts.map +1 -1
- package/dist/tools/remember.js +10 -1
- package/dist/tools/remember.js.map +1 -1
- package/dist/tools/session-end.d.ts +15 -0
- package/dist/tools/session-end.d.ts.map +1 -1
- package/dist/tools/session-end.js +13 -1
- package/dist/tools/session-end.js.map +1 -1
- package/dist/tools/session-start.d.ts +6 -1
- package/dist/tools/session-start.d.ts.map +1 -1
- package/dist/tools/session-start.js +24 -212
- package/dist/tools/session-start.js.map +1 -1
- package/package.json +11 -8
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"review.d.ts","sourceRoot":"","sources":["../../src/http/review.ts"],"names":[],"mappings":"AA4BA,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGrD,OAAO,EA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AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,QAAQ,EAAE,CAAC,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,IAAI,CAU9F;AAED,8EAA8E;AAC9E,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,EAAE,eAAe,GAAG,IAAI,CAqG1E"}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* review.ts — the owner's self-service review page for staged corrections.
|
|
3
|
+
*
|
|
4
|
+
* GET /review signed out: provider buttons; signed in: this account's staged proposals
|
|
5
|
+
* POST /review/start → GitHub / Google (same callback URL as the MCP sign-in, told apart by state)
|
|
6
|
+
* POST /review/approve {id, project, csrf} → confirmPendingCorrection, as the owner
|
|
7
|
+
* POST /review/reject {id, project, csrf} → resolvePendingCorrection(reject), as the owner
|
|
8
|
+
* POST /review/logout {csrf}
|
|
9
|
+
*
|
|
10
|
+
* Why a separate browser session and not an MCP token: since the owner gate (#51)
|
|
11
|
+
* whoever holds a tenant's ar_/aro_ token is treated as an AGENT, and an agent must
|
|
12
|
+
* never activate a rule. Here the owner proves who they are with a GitHub/Google
|
|
13
|
+
* sign-in in a browser (re-authentication is not forced: GitHub skips its prompt for
|
|
14
|
+
* an app the user already authorized, so whoever drives the user's signed-in browser
|
|
15
|
+
* can get in, as the user could). The session cookie is HttpOnly, scoped to /review
|
|
16
|
+
* and only ever set by that sign-in. Any request carrying an Authorization header is
|
|
17
|
+
* refused, so a token holder never gets in.
|
|
18
|
+
*
|
|
19
|
+
* CSRF: SameSite=Lax session cookie + a per-session synchronizer token in every form
|
|
20
|
+
* + Sec-Fetch-Site must be same-origin when the browser sends it + Origin (when it is
|
|
21
|
+
* a real origin) must be ours. `Origin: null` is let through on purpose: these pages
|
|
22
|
+
* send Referrer-Policy no-referrer, and browsers then send `null` on same-origin form
|
|
23
|
+
* posts (Fetch spec); the CSRF token still gates every state change. Sign-in: state is 32 random bytes, single use, 10 min,
|
|
24
|
+
* bound to a cookie of the browser that started it; PKCE (S256) and, for Google, a nonce.
|
|
25
|
+
*
|
|
26
|
+
* In memory only: a restart signs everyone out (they sign in again).
|
|
27
|
+
*/
|
|
28
|
+
import * as fs from "node:fs";
|
|
29
|
+
import express from "express";
|
|
30
|
+
import { listPendingCorrections, confirmPendingCorrection, resolvePendingCorrection, readStagedProposal } from "agent-recall-core";
|
|
31
|
+
import { pageHeaders } from "./oauth-pages.js";
|
|
32
|
+
import { siteHeaders } from "./site-pages.js";
|
|
33
|
+
import { reviewListPage, noticeKey } from "./review-pages.js";
|
|
34
|
+
import { asOwner, tenantProjects, tenantRoot, PROJECT_RE } from "./tenant-paths.js";
|
|
35
|
+
import { REVIEW_SESSION_COOKIE, REVIEW_SESSION_TTL_MS, REVIEW_LOGIN_TTL_MS, str, page } from "./web-session.js";
|
|
36
|
+
export { REVIEW_SESSION_COOKIE, REVIEW_SESSION_TTL_MS, REVIEW_LOGIN_TTL_MS };
|
|
37
|
+
export const REVIEW_PATHS = new Set(["/review", "/review/start", "/review/approve", "/review/reject", "/review/logout"]);
|
|
38
|
+
/** Ready proposals shown at once (a project holds at most 200 staged rows). */
|
|
39
|
+
const MAX_SHOWN = 100;
|
|
40
|
+
const MAX_ID_CHARS = 300;
|
|
41
|
+
const MSG_READ_FAILED = "Your proposals could not be read just now. Nothing was changed; please reload in a moment.";
|
|
42
|
+
const MSG_BAD_INPUT = "That request was not valid. Reload the review page and try again.";
|
|
43
|
+
const MSG_SIGNED_OUT = "You are not signed in, or your review session has ended. Sign in again.";
|
|
44
|
+
const MSG_TOKEN = "This page does not accept API tokens. Open it in your browser and sign in with GitHub or Google; agents cannot approve corrections.";
|
|
45
|
+
const MSG_CROSS_SITE = "This request did not come from the review page itself, so it was refused. Reload the review page and try again.";
|
|
46
|
+
const MSG_CSRF = "This form has expired or did not come from your review page. Reload the review page and try again.";
|
|
47
|
+
const MSG_TOO_MANY = "Too many requests. Please wait a few minutes and try again.";
|
|
48
|
+
/** Every staged correction of `uid`, as the owner. Ready proposals are what approving activates, verbatim. */
|
|
49
|
+
export async function listTenantProposals(dataDir, uid) {
|
|
50
|
+
const root = tenantRoot(dataDir, uid);
|
|
51
|
+
if (!fs.existsSync(root))
|
|
52
|
+
return { items: [], incomplete: 0, hidden: 0 }; // never create a tenant by looking
|
|
53
|
+
return asOwner(dataDir, uid, async () => {
|
|
54
|
+
const ready = [];
|
|
55
|
+
let incomplete = 0;
|
|
56
|
+
for (const project of tenantProjects(root)) {
|
|
57
|
+
for (const row of await listPendingCorrections(project, { strict: true })) {
|
|
58
|
+
if (row.kind !== "correction")
|
|
59
|
+
continue;
|
|
60
|
+
const p = readStagedProposal(row);
|
|
61
|
+
if (!p) {
|
|
62
|
+
incomplete++;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
ready.push({
|
|
66
|
+
id: row.id, project, severity: row.severity, seenCount: row.seen_count, firstSeen: row.ts, lastSeen: row.last_seen,
|
|
67
|
+
rule: p.rule, why: p.why, appliesWhen: p.applies_when,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Oldest first, by when it was first staged: a re-submission bumps last_seen and must not jump the queue.
|
|
72
|
+
ready.sort((a, b) => (Date.parse(a.firstSeen) || 0) - (Date.parse(b.firstSeen) || 0));
|
|
73
|
+
return { items: ready.slice(0, MAX_SHOWN), incomplete, hidden: Math.max(0, ready.length - MAX_SHOWN) };
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Approve or reject one staged proposal of `uid`, as the owner. Only a row that
|
|
78
|
+
* readStagedProposal accepts is acted on: its id ends in the digest of exactly the
|
|
79
|
+
* text the page showed, so a tampered id or an altered row is simply "gone".
|
|
80
|
+
*/
|
|
81
|
+
export async function decideProposal(dataDir, uid, project, id, action) {
|
|
82
|
+
return asOwner(dataDir, uid, async () => {
|
|
83
|
+
let rows;
|
|
84
|
+
try {
|
|
85
|
+
rows = await listPendingCorrections(project, { strict: true });
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return "unavailable"; // nothing has been decided yet, so "nothing was changed" is true
|
|
89
|
+
}
|
|
90
|
+
const row = rows.find((r) => r.id === id);
|
|
91
|
+
if (!row || !readStagedProposal(row))
|
|
92
|
+
return "gone";
|
|
93
|
+
if (action === "approve") {
|
|
94
|
+
const out = await confirmPendingCorrection(project, id);
|
|
95
|
+
// A second click (or a parallel tab) finds the row already retired: that is "gone", not a failure.
|
|
96
|
+
if (!out.ok)
|
|
97
|
+
return out.reason?.startsWith("pending correction not found") ? "gone" : "failed";
|
|
98
|
+
return out.merged ? "merged" : "approved";
|
|
99
|
+
}
|
|
100
|
+
const out = await resolvePendingCorrection(project, id, "reject", {
|
|
101
|
+
reason: "rejected by the owner (review page)",
|
|
102
|
+
refuse: (r) => (readStagedProposal(r) ? undefined : "not a proposal awaiting the owner"),
|
|
103
|
+
});
|
|
104
|
+
return out.success ? "rejected" : "gone";
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
export function sendReview(res, r, formOrigins) {
|
|
108
|
+
if (r.cookies.length > 0)
|
|
109
|
+
res.append("set-cookie", r.cookies);
|
|
110
|
+
if (r.kind === "redirect") {
|
|
111
|
+
res.set({ "cache-control": "no-store", "referrer-policy": "no-referrer" });
|
|
112
|
+
res.redirect(r.status, r.location);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
// The site's own pages carry a stricter CSP (hashed style and script); the review page keeps its own.
|
|
116
|
+
const headers = r.surface === "connect" ? siteHeaders({ formOrigins: r.signIn ? formOrigins : [] }) : pageHeaders(r.signIn ? formOrigins : []);
|
|
117
|
+
res.status(r.status).set(headers).send(r.html);
|
|
118
|
+
}
|
|
119
|
+
/** Mounts /review* on the OAuth app. Only called when OAuth is configured. */
|
|
120
|
+
export function mountReview(app, d) {
|
|
121
|
+
const { flow } = d;
|
|
122
|
+
const ownOrigin = d.config.publicUrl.origin;
|
|
123
|
+
const send = (res, r) => sendReview(res, r, d.formOrigins);
|
|
124
|
+
const message = (res, status, title, msg, cookies = []) => send(res, flow.message("review", status, title, msg, cookies));
|
|
125
|
+
const body = express.urlencoded({ extended: false, limit: "8kb" });
|
|
126
|
+
const field = (req, k) => (req.body ?? {})[k];
|
|
127
|
+
// Owner only: an agent's bearer token never gets in, whatever else the request carries.
|
|
128
|
+
app.use("/review", (req, res, next) => {
|
|
129
|
+
if (req.headers.authorization !== undefined)
|
|
130
|
+
return void message(res, 403, "Not here", MSG_TOKEN);
|
|
131
|
+
next();
|
|
132
|
+
});
|
|
133
|
+
/** A state-changing post must come from our own page. */
|
|
134
|
+
const sameOrigin = (req, res, next) => {
|
|
135
|
+
const site = req.headers["sec-fetch-site"];
|
|
136
|
+
const origin = req.headers.origin;
|
|
137
|
+
if ((site !== undefined && site !== "same-origin") || (origin !== undefined && origin !== "null" && origin !== ownOrigin)) {
|
|
138
|
+
return void message(res, 403, "Refused", MSG_CROSS_SITE);
|
|
139
|
+
}
|
|
140
|
+
next();
|
|
141
|
+
};
|
|
142
|
+
app.get("/review", async (req, res, next) => {
|
|
143
|
+
try {
|
|
144
|
+
const found = flow.session(req.headers.cookie);
|
|
145
|
+
if (!found) {
|
|
146
|
+
// A dead cookie is cleared so the browser stops sending it.
|
|
147
|
+
return void send(res, flow.signInPage("review", 200, undefined, flow.hasSessionCookie(req.headers.cookie) ? flow.sessionCookies(null) : []));
|
|
148
|
+
}
|
|
149
|
+
const { s } = found;
|
|
150
|
+
const notice = noticeKey(s.flash);
|
|
151
|
+
let data;
|
|
152
|
+
try {
|
|
153
|
+
data = await listTenantProposals(d.dataDir, s.uid);
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
// Never "nothing is waiting" when we could not look.
|
|
157
|
+
d.log(`[review] list failed uid=${s.uid} kind=${err?.name ?? "unknown"}`);
|
|
158
|
+
return void message(res, 503, "Try again", MSG_READ_FAILED);
|
|
159
|
+
}
|
|
160
|
+
s.flash = undefined; // shown once, and only once it is actually shown
|
|
161
|
+
send(res, page(200, reviewListPage({ account: flow.accountLabel(s), uid: s.uid, csrf: s.csrf, notice, ...data })));
|
|
162
|
+
}
|
|
163
|
+
catch (err) {
|
|
164
|
+
next(err);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
app.post("/review/start", (req, res, next) => {
|
|
168
|
+
const wait = d.limitStart(req);
|
|
169
|
+
if (wait > 0) {
|
|
170
|
+
res.set("retry-after", String(wait));
|
|
171
|
+
return void message(res, 429, "Slow down", MSG_TOO_MANY);
|
|
172
|
+
}
|
|
173
|
+
next();
|
|
174
|
+
}, sameOrigin, body, (req, res) => {
|
|
175
|
+
send(res, flow.start(field(req, "provider"), "review"));
|
|
176
|
+
});
|
|
177
|
+
/** Session + CSRF + budget; on success hands the session to `fn`. */
|
|
178
|
+
const signedPost = (fn) => [
|
|
179
|
+
sameOrigin, body,
|
|
180
|
+
async (req, res, next) => {
|
|
181
|
+
try {
|
|
182
|
+
const found = flow.session(req.headers.cookie);
|
|
183
|
+
if (!found)
|
|
184
|
+
return void message(res, 401, "Signed out", MSG_SIGNED_OUT, flow.hasSessionCookie(req.headers.cookie) ? flow.sessionCookies(null) : []);
|
|
185
|
+
if (!flow.csrfOk(found.s, field(req, "csrf")))
|
|
186
|
+
return void message(res, 403, "Refused", MSG_CSRF);
|
|
187
|
+
if (!flow.spendAction(found.s)) {
|
|
188
|
+
res.set("retry-after", "60");
|
|
189
|
+
return void message(res, 429, "Slow down", MSG_TOO_MANY);
|
|
190
|
+
}
|
|
191
|
+
await fn(req, res, found);
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
next(err);
|
|
195
|
+
}
|
|
196
|
+
},
|
|
197
|
+
];
|
|
198
|
+
for (const action of ["approve", "reject"]) {
|
|
199
|
+
app.post(`/review/${action}`, ...signedPost(async (req, res, { s }) => {
|
|
200
|
+
const id = str(field(req, "id"), MAX_ID_CHARS);
|
|
201
|
+
const project = str(field(req, "project"), 64);
|
|
202
|
+
// eslint-disable-next-line no-control-regex
|
|
203
|
+
if (id === null || /[\u0000-\u001f\u007f]/.test(id) || project === null || !PROJECT_RE.test(project) ||
|
|
204
|
+
!tenantProjects(tenantRoot(d.dataDir, s.uid)).includes(project)) {
|
|
205
|
+
return void message(res, 400, "Not valid", MSG_BAD_INPUT);
|
|
206
|
+
}
|
|
207
|
+
// A throw after the read (rare: confirm/resolve report their own failures) goes to the error handler,
|
|
208
|
+
// never to an "unavailable / nothing was changed" notice that might be untrue.
|
|
209
|
+
const outcome = await decideProposal(d.dataDir, s.uid, project, id, action);
|
|
210
|
+
d.log(`[review] ${action} uid=${s.uid} project=${project} result=${outcome}`);
|
|
211
|
+
s.flash = outcome;
|
|
212
|
+
send(res, { kind: "redirect", status: 303, location: "/review", cookies: [] });
|
|
213
|
+
}));
|
|
214
|
+
}
|
|
215
|
+
app.post("/review/logout", ...signedPost(async (_req, res, { key }) => {
|
|
216
|
+
flow.end(key);
|
|
217
|
+
send(res, { kind: "redirect", status: 303, location: "/review", cookies: flow.sessionCookies(null) });
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
//# sourceMappingURL=review.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"review.js","sourceRoot":"","sources":["../../src/http/review.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEnI,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,SAAS,EAAmB,MAAM,mBAAmB,CAAC;A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AE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACxG,CAAC,CAAC,CAAC,CAAC;AACN,CAAC"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import * as http from "node:http";
|
|
2
|
+
import { type ActivityOptions } from "./activity.js";
|
|
3
|
+
import { type LoginLimits } from "./oauth-app.js";
|
|
4
|
+
import type { OAuthConfig } from "./oauth-config.js";
|
|
5
|
+
import type { ProviderUrls } from "./federation.js";
|
|
6
|
+
import { type StatsOptions } from "./stats.js";
|
|
7
|
+
import { type AlertConfig, type AlerterOptions } from "./alerts.js";
|
|
8
|
+
export interface ServeOptions {
|
|
9
|
+
/** Absolute data directory: tenants/ and _server/ live here. */
|
|
10
|
+
dataDir: string;
|
|
11
|
+
port: number;
|
|
12
|
+
host: string;
|
|
13
|
+
/** Register --full tools (check_action). */
|
|
14
|
+
full: boolean;
|
|
15
|
+
/** Request body cap; default 4 MiB. */
|
|
16
|
+
maxBodyBytes?: number;
|
|
17
|
+
/** Max concurrent in-flight MCP requests across all tenants; beyond it → 503. Default 64. */
|
|
18
|
+
maxInFlight?: number;
|
|
19
|
+
/** Storage quota per user in bytes; undefined → DEFAULT_QUOTA_BYTES, 0 → off. */
|
|
20
|
+
quotaBytes?: number;
|
|
21
|
+
/** Requests per minute per user; undefined → DEFAULT_RATE_PER_MIN, 0 → off. */
|
|
22
|
+
ratePerMinute?: number;
|
|
23
|
+
/** Request log sink; default stderr. Never receives tokens or bodies. */
|
|
24
|
+
log?: (line: string) => void;
|
|
25
|
+
/** OAuth 2.1 sign-in with GitHub / Google. null/undefined → OAuth off, behaviour identical to v1. */
|
|
26
|
+
oauth?: OAuthConfig | null;
|
|
27
|
+
/** Test seams for the per-agent activity log: clock, flush interval, file writer. */
|
|
28
|
+
activityTesting?: ActivityOptions;
|
|
29
|
+
/** Telegram error alerts (see alerts.ts); null/undefined → off. */
|
|
30
|
+
alerts?: AlertConfig | null;
|
|
31
|
+
/** Test seams for alerts: Bot API origin, fetch, clock, window, timeout. */
|
|
32
|
+
alertsTesting?: Omit<AlerterOptions, "config">;
|
|
33
|
+
/** Test seams for the usage statistics: clock, flush interval, file writer. */
|
|
34
|
+
statsTesting?: StatsOptions;
|
|
35
|
+
/** Test seams for OAuth only: clock, login rate limits, provider endpoints, fetch and its timeout. */
|
|
36
|
+
oauthTesting?: {
|
|
37
|
+
now?: () => number;
|
|
38
|
+
loginLimits?: LoginLimits;
|
|
39
|
+
providerUrls?: ProviderUrls;
|
|
40
|
+
fetchImpl?: typeof fetch;
|
|
41
|
+
providerTimeoutMs?: number;
|
|
42
|
+
maxPending?: number;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export declare const DEFAULT_QUOTA_BYTES: number;
|
|
46
|
+
export declare const DEFAULT_RATE_PER_MIN = 120;
|
|
47
|
+
export declare function formatMb(bytes: number): string;
|
|
48
|
+
export type RequestHandler = ((req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>) & {
|
|
49
|
+
/** Write buffered per-agent activity and today's usage statistics to disk now (shutdown path). Never throws. */
|
|
50
|
+
flushActivity(): void;
|
|
51
|
+
};
|
|
52
|
+
export declare function createRequestHandler(opts: ServeOptions): RequestHandler;
|
|
53
|
+
/** The HTTP server plus a way to write buffered activity and usage statistics now (cli.ts uses it before a forced exit). */
|
|
54
|
+
export type HostedServer = http.Server & {
|
|
55
|
+
flushActivity(): void;
|
|
56
|
+
};
|
|
57
|
+
export declare function startHttpServer(opts: ServeOptions): Promise<HostedServer>;
|
|
58
|
+
//# sourceMappingURL=serve.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../../src/http/serve.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAOlC,OAAO,EAA0B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AC,YAAY,CAAC,EAAE,YAAY,CAAC;QAAC,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;QAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC1K;AAID,eAAO,MAAM,mBAAmB,QAAoB,CAAC;AACrD,eAAO,MAAM,oBAAoB,MAAM,CAAC;AAExC,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE9C;AA8ED,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE,IAAI,CAAC,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG;IACtG,gHAAgH;IAChH,aAAa,IAAI,IAAI,CAAC;CACvB,CAAC;AAEF,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,GAAG,cAAc,CAkLvE;AAYD,4HAA4H;AAC5H,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,GAAG;IAAE,aAAa,IAAI,IAAI,CAAA;CAAE,CAAC;AAEnE,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CAUzE"}
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serve.ts — hosted AgentRecall: one process, many tenants, any MCP client.
|
|
3
|
+
*
|
|
4
|
+
* POST /mcp MCP Streamable HTTP (stateless, JSON responses), bearer auth
|
|
5
|
+
* GET /healthz liveness
|
|
6
|
+
* OAuth routes only when OAuth is configured (see oauth-app.ts)
|
|
7
|
+
*
|
|
8
|
+
* Every finished response is counted in the daily usage statistics (stats.ts,
|
|
9
|
+
* counts only) and internal failures raise a rate-limited Telegram alert when
|
|
10
|
+
* configured (alerts.ts).
|
|
11
|
+
*
|
|
12
|
+
* Per request: bearer token → uid → withTenant({root: DATA/tenants/<uid>, …}) →
|
|
13
|
+
* a FRESH McpServer + transport. Nothing MCP-level is shared between requests,
|
|
14
|
+
* and strict tenant mode makes any code path that loses the tenant context
|
|
15
|
+
* throw instead of touching another store.
|
|
16
|
+
*/
|
|
17
|
+
import * as fs from "node:fs";
|
|
18
|
+
import * as http from "node:http";
|
|
19
|
+
import * as path from "node:path";
|
|
20
|
+
import { randomUUID } from "node:crypto";
|
|
21
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
22
|
+
import { VERSION, withTenant, enableStrictTenantMode } from "agent-recall-core";
|
|
23
|
+
import { buildServer } from "../build-server.js";
|
|
24
|
+
import { resolveTokenRecord, TokenStoreUnavailableError } from "./tokens.js";
|
|
25
|
+
import { ActivityStore, observe } from "./activity.js";
|
|
26
|
+
import { tenantRoot, HOSTED_DEFAULT_PROJECT } from "./tenant-paths.js";
|
|
27
|
+
import { RateLimiter, UsageTracker, isWriteCall, quotaExceededResponse } from "./limits.js";
|
|
28
|
+
import { createOAuth } from "./oauth-app.js";
|
|
29
|
+
import { isStaticPath, renderStatic, fallbackBase } from "./site.js";
|
|
30
|
+
import { DEFAULT_PRIVACY_URL } from "./site-pages.js";
|
|
31
|
+
import { UsageStats, routeClass, toolNamesOf } from "./stats.js";
|
|
32
|
+
import { Alerter } from "./alerts.js";
|
|
33
|
+
const DEFAULT_MAX_BODY = 4 * 1024 * 1024;
|
|
34
|
+
const DEFAULT_MAX_IN_FLIGHT = 64;
|
|
35
|
+
export const DEFAULT_QUOTA_BYTES = 100 * 1024 * 1024;
|
|
36
|
+
export const DEFAULT_RATE_PER_MIN = 120;
|
|
37
|
+
export function formatMb(bytes) {
|
|
38
|
+
return `${Math.round((bytes / (1024 * 1024)) * 100) / 100} MB`;
|
|
39
|
+
}
|
|
40
|
+
const TOO_LARGE_INSTRUCTION = "Send a smaller request; split large memories into several remember calls.";
|
|
41
|
+
/** Oversized bodies up to limit × this are drained (so the 413 is delivered); beyond it the socket is dropped. */
|
|
42
|
+
const DRAIN_FACTOR = 4;
|
|
43
|
+
function drain(req) {
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
if (req.readableEnded)
|
|
46
|
+
return resolve();
|
|
47
|
+
req.on("end", resolve);
|
|
48
|
+
req.on("close", resolve);
|
|
49
|
+
req.on("error", () => resolve());
|
|
50
|
+
req.resume();
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
class HttpError extends Error {
|
|
54
|
+
status;
|
|
55
|
+
code;
|
|
56
|
+
agentInstruction;
|
|
57
|
+
constructor(status, code, message, agentInstruction) {
|
|
58
|
+
super(message);
|
|
59
|
+
this.status = status;
|
|
60
|
+
this.code = code;
|
|
61
|
+
this.agentInstruction = agentInstruction;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function sendJson(res, status, body, headers = {}) {
|
|
65
|
+
if (res.headersSent)
|
|
66
|
+
return;
|
|
67
|
+
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", ...headers });
|
|
68
|
+
res.end(JSON.stringify(body));
|
|
69
|
+
}
|
|
70
|
+
function readBody(req, limit) {
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
let size = 0;
|
|
73
|
+
let over = false;
|
|
74
|
+
const chunks = [];
|
|
75
|
+
const tooLarge = () => new HttpError(413, "payload_too_large", `body exceeds ${limit} bytes`, TOO_LARGE_INSTRUCTION);
|
|
76
|
+
req.on("data", (c) => {
|
|
77
|
+
size += c.length;
|
|
78
|
+
if (size > limit * DRAIN_FACTOR) {
|
|
79
|
+
// Abusive upload: stop reading. The client may see a reset; that's acceptable here.
|
|
80
|
+
req.destroy();
|
|
81
|
+
reject(tooLarge());
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (size > limit) {
|
|
85
|
+
over = true;
|
|
86
|
+
chunks.length = 0;
|
|
87
|
+
return; // keep draining: replying mid-upload makes clients see ECONNRESET instead of the 413
|
|
88
|
+
}
|
|
89
|
+
chunks.push(c);
|
|
90
|
+
});
|
|
91
|
+
req.on("end", () => (over ? reject(tooLarge()) : resolve(Buffer.concat(chunks).toString("utf-8"))));
|
|
92
|
+
req.on("error", reject);
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
const V1_401_INSTRUCTION = "Send header 'Authorization: Bearer <your AgentRecall token>'. Tokens start with 'ar_'. Ask the server operator for a token if you do not have one.";
|
|
96
|
+
const OAUTH_401_INSTRUCTION = "Send header 'Authorization: Bearer <token>'. Use a static token starting with 'ar_' from the server operator, or sign in with OAuth: " +
|
|
97
|
+
"an OAuth-capable MCP client finds the sign-in page via the WWW-Authenticate resource_metadata URL and opens it in the user's browser.";
|
|
98
|
+
/** Who is calling: the tenant, and which credential (activity key "token:<id>" / "grant:<id>"). */
|
|
99
|
+
function authenticate(req, dataDir, oauth) {
|
|
100
|
+
const header = req.headers["authorization"];
|
|
101
|
+
const m = typeof header === "string" ? /^Bearer\s+(\S+)\s*$/i.exec(header) : null;
|
|
102
|
+
// Static ar_ tokens first (unchanged), then OAuth-issued aro_ tokens when OAuth is on.
|
|
103
|
+
const tok = m ? resolveTokenRecord(dataDir, m[1]) : null;
|
|
104
|
+
let who = tok ? { uid: tok.uid, key: `token:${tok.id}` } : null;
|
|
105
|
+
if (!who && m && oauth && m[1].startsWith("aro_")) {
|
|
106
|
+
const g = oauth.resolveAccessGrant(m[1]);
|
|
107
|
+
if (g)
|
|
108
|
+
who = { uid: g.uid, key: `grant:${g.grantId}` };
|
|
109
|
+
}
|
|
110
|
+
if (!who) {
|
|
111
|
+
throw new HttpError(401, "unauthorized", "missing, malformed, unknown or revoked token", oauth ? OAUTH_401_INSTRUCTION : V1_401_INSTRUCTION);
|
|
112
|
+
}
|
|
113
|
+
return who;
|
|
114
|
+
}
|
|
115
|
+
export function createRequestHandler(opts) {
|
|
116
|
+
const dataDir = path.resolve(opts.dataDir);
|
|
117
|
+
const maxBody = opts.maxBodyBytes ?? DEFAULT_MAX_BODY;
|
|
118
|
+
const maxInFlight = opts.maxInFlight ?? DEFAULT_MAX_IN_FLIGHT;
|
|
119
|
+
let inFlight = 0;
|
|
120
|
+
const quotaBytes = opts.quotaBytes ?? DEFAULT_QUOTA_BYTES;
|
|
121
|
+
const ratePerMinute = opts.ratePerMinute ?? DEFAULT_RATE_PER_MIN;
|
|
122
|
+
const limiter = ratePerMinute > 0 ? new RateLimiter(ratePerMinute) : null;
|
|
123
|
+
const usage = quotaBytes > 0 ? new UsageTracker({ quotaBytes }) : null;
|
|
124
|
+
const quotaMessage = `AgentRecall storage quota reached (${formatMb(quotaBytes)} per user): this memory was NOT saved. ` +
|
|
125
|
+
"Reading still works (recall, session_start). Tell the user their hosted memory is full and that the server operator can raise the limit.";
|
|
126
|
+
const log = opts.log ?? ((line) => process.stderr.write(line + "\n"));
|
|
127
|
+
let alerts = null;
|
|
128
|
+
try {
|
|
129
|
+
alerts = opts.alerts ? new Alerter({ config: opts.alerts, version: VERSION, log, ...opts.alertsTesting }) : null;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
log("[agent-recall-server] alerts off: invalid Telegram configuration");
|
|
133
|
+
}
|
|
134
|
+
/** Responses whose 5xx was already reported with its own kind (so the generic http_5xx alert does not repeat it). */
|
|
135
|
+
const reported = new WeakSet();
|
|
136
|
+
// A write error is only reported from a flush, which never runs inside the constructor.
|
|
137
|
+
const counts = new UsageStats(dataDir, { log, onWriteError: (err) => internal("stats_write", undefined, err), ...opts.statsTesting });
|
|
138
|
+
/** An internal failure: counted, and alerted (rate-limited) when alerts are on. Never throws. */
|
|
139
|
+
function internal(kind, route, err) {
|
|
140
|
+
counts.internalError(kind);
|
|
141
|
+
alerts?.raise(kind, { route, err });
|
|
142
|
+
}
|
|
143
|
+
const activity = new ActivityStore(dataDir, { log, onWriteError: (err) => internal("activity_write", undefined, err), ...opts.activityTesting });
|
|
144
|
+
/** A federated sign-in. An account's memory space is created on its first one, and that is a sign-up. */
|
|
145
|
+
const onSignIn = (uid) => {
|
|
146
|
+
try {
|
|
147
|
+
if (fs.mkdirSync(tenantRoot(dataDir, uid), { recursive: true, mode: 0o700 }) !== undefined)
|
|
148
|
+
counts.signup();
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
// the first MCP request creates it (and fails visibly) if the disk refuses now
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
const oauth = opts.oauth ? createOAuth({
|
|
155
|
+
config: opts.oauth, dataDir, log, quotaBytes, activity, onTenantChanged: (u) => usage?.invalidate(u), onSignIn,
|
|
156
|
+
onInternalError: (res, err) => { reported.add(res); internal("oauth_internal", "oauth", err); },
|
|
157
|
+
...opts.oauthTesting,
|
|
158
|
+
}) : null;
|
|
159
|
+
const ownHost = oauth ? new URL(oauth.site.base).hostname : undefined;
|
|
160
|
+
const unauthorizedHeader = oauth
|
|
161
|
+
? `Bearer realm="agent-recall", resource_metadata="${oauth.resourceMetadataUrl}"`
|
|
162
|
+
: 'Bearer realm="agent-recall"';
|
|
163
|
+
const handler = async (req, res) => {
|
|
164
|
+
const started = Date.now();
|
|
165
|
+
const url = new URL(req.url ?? "/", "http://localhost");
|
|
166
|
+
let uid = "-";
|
|
167
|
+
res.once("finish", () => {
|
|
168
|
+
const ms = Date.now() - started;
|
|
169
|
+
log(`${new Date().toISOString()} ${req.method} ${url.pathname} uid=${uid} ${res.statusCode} ${ms}ms`);
|
|
170
|
+
const route = routeClass(url.pathname);
|
|
171
|
+
counts.request({ route, method: req.method, path: url.pathname, status: res.statusCode, ms, referer: req.headers.referer, ownHost: ownHost ?? hostOf(req.headers.host) });
|
|
172
|
+
if (res.statusCode >= 500 && !reported.has(res))
|
|
173
|
+
internal("http_5xx", route);
|
|
174
|
+
});
|
|
175
|
+
try {
|
|
176
|
+
if (url.pathname === "/healthz" && req.method === "GET") {
|
|
177
|
+
sendJson(res, 200, { ok: true, version: VERSION });
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
if (isStaticPath(url.pathname, oauth !== null)) {
|
|
181
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
182
|
+
res.setHeader("allow", "GET, HEAD");
|
|
183
|
+
throw new HttpError(405, "method_not_allowed", `${req.method} not supported`, "This is a web page: read it with GET.");
|
|
184
|
+
}
|
|
185
|
+
const site = renderStatic(url.pathname, oauth ? oauth.site : { base: fallbackBase(req), privacyUrl: DEFAULT_PRIVACY_URL, hosted: false, baseFromHost: true });
|
|
186
|
+
if (site) {
|
|
187
|
+
res.writeHead(site.status, site.headers);
|
|
188
|
+
res.end(req.method === "HEAD" ? undefined : site.body);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (oauth && oauth.owns(url.pathname)) {
|
|
193
|
+
oauth.handle(req, res);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (url.pathname !== "/mcp") {
|
|
197
|
+
throw new HttpError(404, "not_found", `no route ${url.pathname}`, "The MCP endpoint is POST /mcp.");
|
|
198
|
+
}
|
|
199
|
+
if (req.method !== "POST") {
|
|
200
|
+
// Stateless server: no server-initiated SSE stream (GET) and no session to delete (DELETE).
|
|
201
|
+
res.setHeader("allow", "POST");
|
|
202
|
+
throw new HttpError(405, "method_not_allowed", `${req.method} not supported`, "This server is stateless: send every MCP message as POST /mcp.");
|
|
203
|
+
}
|
|
204
|
+
// Declared-oversized bodies are rejected before authenticating; the body is
|
|
205
|
+
// drained (bounded) first so the client actually receives the 413.
|
|
206
|
+
const declared = Number(req.headers["content-length"] ?? 0);
|
|
207
|
+
if (declared > maxBody) {
|
|
208
|
+
res.setHeader("connection", "close");
|
|
209
|
+
if (declared <= maxBody * DRAIN_FACTOR)
|
|
210
|
+
await drain(req);
|
|
211
|
+
else
|
|
212
|
+
req.destroy();
|
|
213
|
+
throw new HttpError(413, "payload_too_large", `body exceeds ${maxBody} bytes`, TOO_LARGE_INSTRUCTION);
|
|
214
|
+
}
|
|
215
|
+
const who = authenticate(req, dataDir, oauth);
|
|
216
|
+
uid = who.uid;
|
|
217
|
+
// Capacity before rate: a request refused as "busy" must not cost the user a token.
|
|
218
|
+
if (inFlight >= maxInFlight) {
|
|
219
|
+
res.setHeader("retry-after", "1");
|
|
220
|
+
throw new HttpError(503, "busy", "server at capacity", "The AgentRecall server is busy; retry in a second.");
|
|
221
|
+
}
|
|
222
|
+
const rate = limiter?.take(uid);
|
|
223
|
+
if (rate && !rate.ok) {
|
|
224
|
+
res.setHeader("retry-after", String(rate.retryAfterSec));
|
|
225
|
+
throw new HttpError(429, "rate_limited", `more than ${ratePerMinute} requests per minute`, `Too many AgentRecall requests. Retry after ${rate.retryAfterSec} s; batch memory into fewer calls.`);
|
|
226
|
+
}
|
|
227
|
+
inFlight++;
|
|
228
|
+
res.once("close", () => { inFlight--; });
|
|
229
|
+
const raw = await readBody(req, maxBody);
|
|
230
|
+
let body;
|
|
231
|
+
try {
|
|
232
|
+
body = JSON.parse(raw);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
sendJson(res, 400, { jsonrpc: "2.0", error: { code: -32700, message: "Parse error" }, id: null });
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
// memory only; flushed in the background
|
|
239
|
+
if (activity.record(uid, who.key, observe(body)))
|
|
240
|
+
counts.newAgent();
|
|
241
|
+
counts.activeUser(uid);
|
|
242
|
+
counts.toolCalls(toolNamesOf(body));
|
|
243
|
+
const root = tenantRoot(dataDir, uid);
|
|
244
|
+
fs.mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
245
|
+
const writes = usage !== null && isWriteCall(body);
|
|
246
|
+
if (usage && writes && (await usage.isOver(uid, root))) {
|
|
247
|
+
const answer = quotaExceededResponse(body, quotaMessage);
|
|
248
|
+
if (answer === null) {
|
|
249
|
+
res.writeHead(202).end();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
sendJson(res, 200, answer);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (usage && writes)
|
|
256
|
+
usage.add(uid, raw.length);
|
|
257
|
+
// stageAgentCorrections: a token holder can propose a correction but never activate one (owner gate).
|
|
258
|
+
// reviewUrl: where the owner approves them (the /review page exists only with OAuth on).
|
|
259
|
+
const reviewUrl = oauth ? `${oauth.site.base}/review` : undefined;
|
|
260
|
+
await withTenant({ root, sid: randomUUID(), defaultProject: HOSTED_DEFAULT_PROJECT, stageAgentCorrections: true, reviewUrl, credential: who.key }, async () => {
|
|
261
|
+
const server = buildServer({ tier: "B", full: opts.full, extras: false, ambientCapture: false, redactPaths: true });
|
|
262
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
263
|
+
res.on("close", () => {
|
|
264
|
+
transport.close().catch(() => { });
|
|
265
|
+
server.close().catch(() => { });
|
|
266
|
+
});
|
|
267
|
+
await server.connect(transport);
|
|
268
|
+
await transport.handleRequest(req, res, body);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
catch (err) {
|
|
272
|
+
if (err instanceof HttpError) {
|
|
273
|
+
const headers = err.status === 401 ? { "www-authenticate": unauthorizedHeader } : {};
|
|
274
|
+
sendJson(res, err.status, { error: err.code, message: err.message, agent_instruction: err.agentInstruction }, headers);
|
|
275
|
+
}
|
|
276
|
+
else if (err instanceof TokenStoreUnavailableError) {
|
|
277
|
+
log(`[agent-recall-server] token store unavailable: ${err.message}`);
|
|
278
|
+
reported.add(res);
|
|
279
|
+
internal("token_store", routeClass(url.pathname), err);
|
|
280
|
+
sendJson(res, 503, { error: "auth_unavailable", message: "authentication temporarily unavailable", agent_instruction: "Retry shortly; the server operator must fix the token store." }, { "retry-after": "5" });
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
log(`[agent-recall-server] internal error uid=${uid}: ${err?.stack ?? String(err)}`);
|
|
284
|
+
reported.add(res);
|
|
285
|
+
internal("mcp_internal", routeClass(url.pathname), err);
|
|
286
|
+
sendJson(res, 500, { error: "internal_error", message: "internal server error", agent_instruction: "Retry once; if it persists, continue without memory and tell the user the AgentRecall server failed." });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
const flushAll = () => {
|
|
291
|
+
try {
|
|
292
|
+
activity.flush();
|
|
293
|
+
}
|
|
294
|
+
finally {
|
|
295
|
+
// Called on shutdown: a failure here has no retry left, so say so (the retry log line says "quietly").
|
|
296
|
+
if (!counts.flush())
|
|
297
|
+
log("[agent-recall-server] usage stats NOT saved at shutdown (disk full or not writable?); today's counts are lost");
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
return Object.assign(handler, { flushActivity: flushAll });
|
|
301
|
+
}
|
|
302
|
+
/** Host name of a Host header (no port), or undefined. Used only to tell internal navigation from a referrer. */
|
|
303
|
+
function hostOf(header) {
|
|
304
|
+
if (typeof header !== "string" || header.length > 300)
|
|
305
|
+
return undefined;
|
|
306
|
+
try {
|
|
307
|
+
return new URL(`http://${header}`).hostname || undefined;
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
export function startHttpServer(opts) {
|
|
314
|
+
enableStrictTenantMode();
|
|
315
|
+
const handler = createRequestHandler(opts);
|
|
316
|
+
const server = Object.assign(http.createServer((req, res) => void handler(req, res)), { flushActivity: () => handler.flushActivity() });
|
|
317
|
+
// Graceful shutdown (cli.ts calls server.close on SIGTERM/SIGINT): write buffered activity and stats before exit.
|
|
318
|
+
server.once("close", () => handler.flushActivity());
|
|
319
|
+
return new Promise((resolve, reject) => {
|
|
320
|
+
server.once("error", reject);
|
|
321
|
+
server.listen(opts.port, opts.host, () => resolve(server));
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
//# sourceMappingURL=serve.js.map
|