@tenonai/yew 0.0.0-stage → 1.3.0
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 +273 -0
- package/LICENSE +21 -0
- package/README.md +64 -2
- package/THIRD-PARTY-NOTICES.md +122 -0
- package/bin/yew.js +9 -0
- package/dist/cli/app.js +211 -0
- package/dist/cli/export.js +57 -0
- package/dist/cli/io.js +65 -0
- package/dist/cli/key.js +113 -0
- package/dist/cli/main.js +58 -0
- package/dist/cli/mcp.js +76 -0
- package/dist/cli/remote.js +116 -0
- package/dist/cli/run.js +72 -0
- package/dist/cli/schedule.js +123 -0
- package/dist/cli/send.js +127 -0
- package/dist/cli/serve.js +301 -0
- package/dist/cli/service.js +268 -0
- package/dist/cli/system.js +44 -0
- package/dist/remote/access.js +107 -0
- package/dist/remote/connector.js +278 -0
- package/dist/remote/identity.js +71 -0
- package/dist/remote/noise.js +287 -0
- package/dist/remote/protocol.js +51 -0
- package/dist/remote/push.js +37 -0
- package/dist/server/agent/compaction.js +242 -0
- package/dist/server/agent/context.js +120 -0
- package/dist/server/agent/held.js +48 -0
- package/dist/server/agent/helper.js +122 -0
- package/dist/server/agent/mailroom.js +510 -0
- package/dist/server/agent/prompt.js +268 -0
- package/dist/server/agent/runner.js +1159 -0
- package/dist/server/artifacts.js +216 -0
- package/dist/server/budget.js +88 -0
- package/dist/server/data-export.js +105 -0
- package/dist/server/data-usage.js +144 -0
- package/dist/server/db/database.js +49 -0
- package/dist/server/db/migrations.js +343 -0
- package/dist/server/errors.js +16 -0
- package/dist/server/events.js +17 -0
- package/dist/server/export.js +378 -0
- package/dist/server/folder-picker.js +32 -0
- package/dist/server/from-jig.js +98 -0
- package/dist/server/http/agents.js +78 -0
- package/dist/server/http/api.js +465 -0
- package/dist/server/http/app.js +111 -0
- package/dist/server/http/artifacts.js +53 -0
- package/dist/server/http/data.js +54 -0
- package/dist/server/http/devices.js +47 -0
- package/dist/server/http/events.js +134 -0
- package/dist/server/http/idempotency.js +53 -0
- package/dist/server/http/input.js +106 -0
- package/dist/server/http/mail.js +52 -0
- package/dist/server/http/mcp.js +134 -0
- package/dist/server/http/notes.js +91 -0
- package/dist/server/http/problem.js +55 -0
- package/dist/server/http/providers.js +131 -0
- package/dist/server/http/schedules.js +58 -0
- package/dist/server/http/search.js +42 -0
- package/dist/server/http/security.js +168 -0
- package/dist/server/http/skills.js +53 -0
- package/dist/server/http/system.js +26 -0
- package/dist/server/ids.js +30 -0
- package/dist/server/keys.js +70 -0
- package/dist/server/mail/envelope.js +152 -0
- package/dist/server/mail/post.js +603 -0
- package/dist/server/mail/store.js +279 -0
- package/dist/server/manage.js +601 -0
- package/dist/server/mcp-builtin.js +180 -0
- package/dist/server/mcp-config.js +305 -0
- package/dist/server/mcp-oauth.js +448 -0
- package/dist/server/mcp.js +668 -0
- package/dist/server/model/gateway.js +410 -0
- package/dist/server/paths.js +43 -0
- package/dist/server/permissions/engine.js +249 -0
- package/dist/server/permissions/paths.js +93 -0
- package/dist/server/permissions/shell.js +635 -0
- package/dist/server/push.js +345 -0
- package/dist/server/reveal.js +36 -0
- package/dist/server/runtime.js +17 -0
- package/dist/server/schedules.js +356 -0
- package/dist/server/settings.js +77 -0
- package/dist/server/skills.js +263 -0
- package/dist/server/store.js +1077 -0
- package/dist/server/tools/files.js +318 -0
- package/dist/server/tools/html.js +221 -0
- package/dist/server/tools/jobs.js +38 -0
- package/dist/server/tools/mail.js +680 -0
- package/dist/server/tools/match.js +81 -0
- package/dist/server/tools/misc.js +253 -0
- package/dist/server/tools/process.js +128 -0
- package/dist/server/tools/read-state.js +40 -0
- package/dist/server/tools/registry.js +43 -0
- package/dist/server/tools/search.js +175 -0
- package/dist/server/tools/shell.js +124 -0
- package/dist/server/tools/types.js +43 -0
- package/dist/server/tools/web-search.js +198 -0
- package/dist/server/tools/web.js +240 -0
- package/dist/shared/cron.js +105 -0
- package/dist/shared/mcp-presets.js +170 -0
- package/dist/shared/messages.js +45 -0
- package/dist/shared/policy.js +42 -0
- package/dist/shared/types.js +34 -0
- package/dist/shared/version.js +8 -0
- package/mcp-builtin/package-lock.json +3398 -0
- package/mcp-builtin/package.json +14 -0
- package/mcp-builtin/presets/gitee/package-lock.json +105 -0
- package/mcp-builtin/presets/gitee/package.json +10 -0
- package/mcp-builtin/presets/notion/package-lock.json +2243 -0
- package/mcp-builtin/presets/notion/package.json +10 -0
- package/mcp-builtin/presets/sentry/package-lock.json +28 -0
- package/mcp-builtin/presets/sentry/package.json +10 -0
- package/package.json +75 -5
- package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
- package/web/dist/assets/index-BtK_SzpF.css +1 -0
- package/web/dist/assets/index-C0rnUFI-.js +68 -0
- package/web/dist/icons/app-icon.png +0 -0
- package/web/dist/icons/apple-touch-icon.png +0 -0
- package/web/dist/icons/favicon-16.png +0 -0
- package/web/dist/icons/favicon-32.png +0 -0
- package/web/dist/icons/favicon-64.png +0 -0
- package/web/dist/icons/tenon-mark.svg +1 -0
- package/web/dist/icons/yew-mark.svg +1 -0
- package/web/dist/index.html +18 -0
- package/web/dist/mascot/gift.webp +0 -0
- package/web/dist/mascot/greeting.webp +0 -0
- package/web/dist/mascot/happy.webp +0 -0
- package/web/dist/mascot/lost.webp +0 -0
- package/web/dist/mascot/shush.webp +0 -0
- package/web/dist/mascot/sleepy.webp +0 -0
- package/web/dist/mascot/sorry.webp +0 -0
- package/web/dist/mascot/thinking.webp +0 -0
- package/web/dist/mascot/waking.webp +0 -0
- package/web/dist/mascot/writing.webp +0 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { exportAll } from "../data-export.js";
|
|
3
|
+
import { cleanTemp, dataUsage } from "../data-usage.js";
|
|
4
|
+
import { conflict, invalid, YewError } from "../errors.js";
|
|
5
|
+
import { resolveWorkingFolder } from "../paths.js";
|
|
6
|
+
import { revealKind, showInFileManager } from "../reveal.js";
|
|
7
|
+
import { idempotent } from "./idempotency.js";
|
|
8
|
+
import { readJson, reqString } from "./input.js";
|
|
9
|
+
/**
|
|
10
|
+
* Data in the settings (blueprint 6.10, item 36): what the data folder takes, exporting everything
|
|
11
|
+
* as `yew export` does, and deleting the over-long command output. Computer-only: these are this
|
|
12
|
+
* computer's folders. The only folders shown in the file manager are the data folder and the one
|
|
13
|
+
* this process last exported to; a request never supplies a path to show.
|
|
14
|
+
*/
|
|
15
|
+
export function dataRoutes(store, options) {
|
|
16
|
+
const app = new Hono();
|
|
17
|
+
const once = idempotent(store.db);
|
|
18
|
+
const platform = options.platform ?? process.platform;
|
|
19
|
+
const inUse = options.inUse ?? (() => false);
|
|
20
|
+
let exported = null;
|
|
21
|
+
app.get("/data", (c) => c.json({ ...dataUsage(options.home, inUse), reveal: revealKind(platform) }));
|
|
22
|
+
app.post("/data/export", once, async (c) => {
|
|
23
|
+
const fields = await readJson(c);
|
|
24
|
+
const requested = reqString(fields, "folder", 4096);
|
|
25
|
+
let folder;
|
|
26
|
+
try {
|
|
27
|
+
folder = resolveWorkingFolder(requested);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error instanceof YewError)
|
|
31
|
+
throw invalid(error.message, "folder");
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
// The same call as `yew export`: it refuses a folder that is not empty.
|
|
35
|
+
const counts = exportAll(store, folder, Date.now(), options.home);
|
|
36
|
+
exported = folder;
|
|
37
|
+
return c.json({ folder, ...counts }, 201);
|
|
38
|
+
});
|
|
39
|
+
app.post("/data/cleanup", once, (c) => c.json(cleanTemp(options.home, inUse)));
|
|
40
|
+
app.post("/data/reveal", async (c) => {
|
|
41
|
+
const target = reqString(await readJson(c), "target", 20);
|
|
42
|
+
if (target !== "home" && target !== "export") {
|
|
43
|
+
throw invalid("target must be home or export.", "target");
|
|
44
|
+
}
|
|
45
|
+
const dir = target === "home" ? options.home : exported;
|
|
46
|
+
if (dir === null) {
|
|
47
|
+
throw conflict("Nothing was exported since Yew started.", { field: "target" }, "no-export");
|
|
48
|
+
}
|
|
49
|
+
// The folder itself is opened, so its contents are what the person sees.
|
|
50
|
+
await showInFileManager(dir, { platform, run: options.run, inside: true, field: "target" });
|
|
51
|
+
return c.body(null, 204);
|
|
52
|
+
});
|
|
53
|
+
return app;
|
|
54
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { renderSVG } from "uqr";
|
|
3
|
+
import { PUSH_TOKEN } from "../../remote/push.js";
|
|
4
|
+
import { conflict, invalid } from "../errors.js";
|
|
5
|
+
import { optBoolean, optNullableString, optString, readJson } from "./input.js";
|
|
6
|
+
/** Paired phones and pairing (M3 plan, section 4). Pairing and revoking stay on the Mac. */
|
|
7
|
+
export function deviceRoutes(store, remote) {
|
|
8
|
+
const app = new Hono();
|
|
9
|
+
app.get("/devices", (c) => c.json({ devices: store.listDevices(), remote: remote?.status() ?? null }));
|
|
10
|
+
app.patch("/devices/:id", async (c) => {
|
|
11
|
+
const id = c.req.param("id");
|
|
12
|
+
const fields = await readJson(c);
|
|
13
|
+
const name = optString(fields, "name", 60)?.trim();
|
|
14
|
+
if (name !== undefined && !name)
|
|
15
|
+
throw invalid("The name cannot be empty.", "name");
|
|
16
|
+
const push = optBoolean(fields, "push");
|
|
17
|
+
// Only the phone itself hands over its notification token.
|
|
18
|
+
const pushToken = optNullableString(fields, "pushToken", 200);
|
|
19
|
+
if (pushToken !== undefined && c.env?.device !== id) {
|
|
20
|
+
throw invalid("Only the device itself can set its notification token.", "pushToken");
|
|
21
|
+
}
|
|
22
|
+
if (pushToken && !PUSH_TOKEN.test(pushToken)) {
|
|
23
|
+
throw invalid("The notification token is not one Apple gives out.", "pushToken");
|
|
24
|
+
}
|
|
25
|
+
return c.json(store.updateDevice(id, {
|
|
26
|
+
...(name !== undefined ? { name } : {}),
|
|
27
|
+
...(push !== undefined ? { push } : {}),
|
|
28
|
+
...(pushToken !== undefined ? { pushToken } : {}),
|
|
29
|
+
}));
|
|
30
|
+
});
|
|
31
|
+
app.delete("/devices/:id", (c) => {
|
|
32
|
+
const id = c.req.param("id");
|
|
33
|
+
store.deleteDevice(id);
|
|
34
|
+
remote?.disconnect(id);
|
|
35
|
+
return c.body(null, 204);
|
|
36
|
+
});
|
|
37
|
+
app.post("/devices/pairing", async (c) => {
|
|
38
|
+
if (!remote)
|
|
39
|
+
throw conflict("Remote access is not available here.", undefined, "remote-off");
|
|
40
|
+
if (!remote.status().enabled) {
|
|
41
|
+
throw conflict("Turn on phone access first.", undefined, "remote-off");
|
|
42
|
+
}
|
|
43
|
+
const { link, expiresAt } = await remote.pairing();
|
|
44
|
+
return c.json({ link, expiresAt, svg: renderSVG(link) });
|
|
45
|
+
});
|
|
46
|
+
return app;
|
|
47
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { streamSSE } from "hono/streaming";
|
|
3
|
+
const KEEPALIVE_MS = 15_000;
|
|
4
|
+
const MAX_QUEUE = 2000;
|
|
5
|
+
/**
|
|
6
|
+
* A session event as the stream sends it. A conversation taken back changes entries already shown,
|
|
7
|
+
* so clients load it again: every client, phones included, already does that on "reset".
|
|
8
|
+
*/
|
|
9
|
+
function sessionMessage(seq, event) {
|
|
10
|
+
if (event.type === "rewound")
|
|
11
|
+
return { event: "reset", id: String(seq), data: "{}" };
|
|
12
|
+
return { event: "session", id: String(seq), data: JSON.stringify(event) };
|
|
13
|
+
}
|
|
14
|
+
/** Remembers each session's in-flight draft, so a client that connects mid-answer sees it at once. */
|
|
15
|
+
export class DraftCache {
|
|
16
|
+
#drafts = new Map();
|
|
17
|
+
constructor(bus) {
|
|
18
|
+
bus.subscribe((event) => {
|
|
19
|
+
if (event.scope !== "live")
|
|
20
|
+
return;
|
|
21
|
+
if (event.event.type === "draft")
|
|
22
|
+
this.#drafts.set(event.sessionId, event.event.draft);
|
|
23
|
+
else if (event.event.type === "draftCleared")
|
|
24
|
+
this.#drafts.delete(event.sessionId);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
get(sessionId) {
|
|
28
|
+
return this.#drafts.get(sessionId);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* One event stream per browser tab (HTTP/1.1 allows six connections per host). It carries the
|
|
33
|
+
* sidebar's events for every session, and the open session's transcript events. Transcript events
|
|
34
|
+
* have the session's sequence number as their SSE id, so after a reconnect the browser's
|
|
35
|
+
* `Last-Event-ID` resumes from the database; drafts and sidebar updates are not replayed, and the
|
|
36
|
+
* client reloads instead (prior-art 5.1). A client that cannot keep up is disconnected.
|
|
37
|
+
*/
|
|
38
|
+
export function eventRoutes(store, bus, drafts) {
|
|
39
|
+
const app = new Hono();
|
|
40
|
+
app.get("/events", (c) => {
|
|
41
|
+
const sessionId = c.req.query("session") ?? null;
|
|
42
|
+
const lastId = c.req.header("Last-Event-ID") ?? c.req.query("after");
|
|
43
|
+
const after = lastId !== undefined && /^\d+$/.test(lastId) ? Number(lastId) : null;
|
|
44
|
+
if (sessionId)
|
|
45
|
+
store.getSession(sessionId);
|
|
46
|
+
return streamSSE(c, async (stream) => {
|
|
47
|
+
const queue = [];
|
|
48
|
+
let wake = null;
|
|
49
|
+
let overflow = false;
|
|
50
|
+
let replayedUpTo = after ?? 0;
|
|
51
|
+
let replaying = true;
|
|
52
|
+
const buffered = [];
|
|
53
|
+
const push = (item) => {
|
|
54
|
+
if (queue.length >= MAX_QUEUE) {
|
|
55
|
+
overflow = true;
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
queue.push(item);
|
|
59
|
+
}
|
|
60
|
+
wake?.();
|
|
61
|
+
};
|
|
62
|
+
const forward = (event) => {
|
|
63
|
+
if (event.scope === "global") {
|
|
64
|
+
push({ event: "global", data: JSON.stringify(event.event) });
|
|
65
|
+
}
|
|
66
|
+
else if (event.sessionId === sessionId) {
|
|
67
|
+
if (event.scope === "live")
|
|
68
|
+
push({ event: "live", data: JSON.stringify(event.event) });
|
|
69
|
+
else if (event.seq > replayedUpTo) {
|
|
70
|
+
replayedUpTo = event.seq;
|
|
71
|
+
push(sessionMessage(event.seq, event.event));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
// Subscribe before reading the database, so nothing falls between replay and live events.
|
|
76
|
+
const unsubscribe = bus.subscribe((event) => {
|
|
77
|
+
if (replaying)
|
|
78
|
+
buffered.push(event);
|
|
79
|
+
else
|
|
80
|
+
forward(event);
|
|
81
|
+
});
|
|
82
|
+
stream.onAbort(() => {
|
|
83
|
+
unsubscribe();
|
|
84
|
+
wake?.();
|
|
85
|
+
});
|
|
86
|
+
push({ event: "hello", data: JSON.stringify({ time: Date.now() }) });
|
|
87
|
+
if (sessionId && after !== null) {
|
|
88
|
+
const { events, complete } = store.eventsAfter(sessionId, after, MAX_QUEUE);
|
|
89
|
+
if (!complete || events.length >= MAX_QUEUE) {
|
|
90
|
+
push({ event: "reset", data: "{}" });
|
|
91
|
+
replayedUpTo = store.getSession(sessionId).eventSeq;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
for (const { seq, event } of events) {
|
|
95
|
+
replayedUpTo = seq;
|
|
96
|
+
push(sessionMessage(seq, event));
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
else if (sessionId) {
|
|
101
|
+
replayedUpTo = store.getSession(sessionId).eventSeq;
|
|
102
|
+
}
|
|
103
|
+
const draft = sessionId ? drafts.get(sessionId) : undefined;
|
|
104
|
+
if (draft)
|
|
105
|
+
push({ event: "live", data: JSON.stringify({ type: "draft", draft }) });
|
|
106
|
+
replaying = false;
|
|
107
|
+
for (const event of buffered.splice(0))
|
|
108
|
+
forward(event);
|
|
109
|
+
const keepalive = setInterval(() => {
|
|
110
|
+
void stream.write(": keepalive\n\n");
|
|
111
|
+
}, KEEPALIVE_MS);
|
|
112
|
+
try {
|
|
113
|
+
while (!stream.aborted && !overflow) {
|
|
114
|
+
const item = queue.shift();
|
|
115
|
+
if (item) {
|
|
116
|
+
await stream.writeSSE(item);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
await new Promise((resolve) => {
|
|
120
|
+
wake = resolve;
|
|
121
|
+
});
|
|
122
|
+
wake = null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
clearInterval(keepalive);
|
|
127
|
+
unsubscribe();
|
|
128
|
+
if (overflow && !stream.aborted)
|
|
129
|
+
await stream.writeSSE({ event: "reset", data: "{}" });
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
return app;
|
|
134
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { YewError } from "../errors.js";
|
|
3
|
+
const KEEP_MS = 24 * 60 * 60 * 1000;
|
|
4
|
+
const KEY_PATTERN = /^[\x21-\x7e]{1,255}$/;
|
|
5
|
+
/**
|
|
6
|
+
* `Idempotency-Key` for create requests (spec 20.2, IETF draft): a repeat with the same key and body
|
|
7
|
+
* returns the first response without running the handler again; the same key with a different body is
|
|
8
|
+
* rejected, and so is a repeat that arrives while the first is still running.
|
|
9
|
+
*/
|
|
10
|
+
export function idempotent(db) {
|
|
11
|
+
const inFlight = new Set();
|
|
12
|
+
const find = db.prepare("SELECT fingerprint, status, body FROM idempotency_keys WHERE scope = ? AND key = ?");
|
|
13
|
+
const save = db.prepare(`INSERT INTO idempotency_keys (scope, key, fingerprint, status, body, created_at)
|
|
14
|
+
VALUES (?, ?, ?, ?, ?, ?)`);
|
|
15
|
+
const expire = db.prepare("DELETE FROM idempotency_keys WHERE created_at < ?");
|
|
16
|
+
return async (c, next) => {
|
|
17
|
+
const key = c.req.header("Idempotency-Key");
|
|
18
|
+
if (key === undefined)
|
|
19
|
+
return next();
|
|
20
|
+
if (!KEY_PATTERN.test(key)) {
|
|
21
|
+
throw new YewError("invalid-request", 400, "Idempotency-Key must be 1–255 visible characters.");
|
|
22
|
+
}
|
|
23
|
+
const scope = `${c.req.method} ${c.req.path}`;
|
|
24
|
+
const fingerprint = createHash("sha256")
|
|
25
|
+
.update(await c.req.text())
|
|
26
|
+
.digest("hex");
|
|
27
|
+
const saved = find.get(scope, key);
|
|
28
|
+
if (saved) {
|
|
29
|
+
if (saved.fingerprint !== fingerprint) {
|
|
30
|
+
throw new YewError("idempotency-key-reused", 422, "This Idempotency-Key was already used with a different request body.");
|
|
31
|
+
}
|
|
32
|
+
return c.newResponse(saved.body, saved.status, {
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
"Idempotent-Replayed": "true",
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
const slot = `${scope} ${key}`;
|
|
38
|
+
if (inFlight.has(slot)) {
|
|
39
|
+
throw new YewError("idempotency-key-in-use", 409, "A request with this Idempotency-Key is still being processed.");
|
|
40
|
+
}
|
|
41
|
+
inFlight.add(slot);
|
|
42
|
+
try {
|
|
43
|
+
await next();
|
|
44
|
+
if (c.res.status < 500) {
|
|
45
|
+
expire.run(Date.now() - KEEP_MS);
|
|
46
|
+
save.run(scope, key, fingerprint, c.res.status, await c.res.clone().text(), Date.now());
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
inFlight.delete(slot);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { invalid, YewError } from "../errors.js";
|
|
2
|
+
/** Reads a JSON object body. Requiring application/json also keeps out cross-site "simple" form posts. */
|
|
3
|
+
export async function readJson(c) {
|
|
4
|
+
const type = c.req.header("Content-Type") ?? "";
|
|
5
|
+
if (!/^application\/json\b/i.test(type)) {
|
|
6
|
+
throw new YewError("unsupported-media-type", 415, "Send the body as application/json.");
|
|
7
|
+
}
|
|
8
|
+
let value;
|
|
9
|
+
try {
|
|
10
|
+
value = await c.req.json();
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw invalid("The body is not valid JSON.");
|
|
14
|
+
}
|
|
15
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
16
|
+
throw invalid("The body must be a JSON object.");
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
export function optString(fields, key, max = 10_000) {
|
|
21
|
+
const value = fields[key];
|
|
22
|
+
if (value === undefined)
|
|
23
|
+
return undefined;
|
|
24
|
+
if (typeof value !== "string")
|
|
25
|
+
throw invalid(`${key} must be text.`, key);
|
|
26
|
+
if (value.length > max)
|
|
27
|
+
throw invalid(`${key} can be at most ${max} characters.`, key);
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
export function reqString(fields, key, max = 10_000) {
|
|
31
|
+
const value = optString(fields, key, max);
|
|
32
|
+
if (value === undefined)
|
|
33
|
+
throw invalid(`${key} is required.`, key);
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
export function optNullableString(fields, key, max = 10_000) {
|
|
37
|
+
if (fields[key] === null)
|
|
38
|
+
return null;
|
|
39
|
+
return optString(fields, key, max);
|
|
40
|
+
}
|
|
41
|
+
export function optBoolean(fields, key) {
|
|
42
|
+
const value = fields[key];
|
|
43
|
+
if (value === undefined)
|
|
44
|
+
return undefined;
|
|
45
|
+
if (typeof value !== "boolean")
|
|
46
|
+
throw invalid(`${key} must be true or false.`, key);
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
export function optNumber(fields, key) {
|
|
50
|
+
const value = fields[key];
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
return undefined;
|
|
53
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
54
|
+
throw invalid(`${key} must be a number.`, key);
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
export function optEnum(fields, key, values) {
|
|
59
|
+
const value = fields[key];
|
|
60
|
+
if (value === undefined)
|
|
61
|
+
return undefined;
|
|
62
|
+
if (typeof value !== "string" || !values.includes(value)) {
|
|
63
|
+
throw invalid(`${key} must be one of: ${values.join(", ")}.`, key);
|
|
64
|
+
}
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
export function optObject(fields, key) {
|
|
68
|
+
const value = fields[key];
|
|
69
|
+
if (value === undefined)
|
|
70
|
+
return undefined;
|
|
71
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
72
|
+
throw invalid(`${key} must be an object.`, key);
|
|
73
|
+
}
|
|
74
|
+
return value;
|
|
75
|
+
}
|
|
76
|
+
export function optArray(fields, key) {
|
|
77
|
+
const value = fields[key];
|
|
78
|
+
if (value === undefined)
|
|
79
|
+
return undefined;
|
|
80
|
+
if (!Array.isArray(value))
|
|
81
|
+
throw invalid(`${key} must be a list.`, key);
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
84
|
+
export const DEFAULT_PAGE = 50;
|
|
85
|
+
export const MAX_PAGE = 200;
|
|
86
|
+
/** `limit` and `cursor` query parameters (spec 20.3: every list is paginated and capped). */
|
|
87
|
+
export function pageParams(c, max = MAX_PAGE) {
|
|
88
|
+
const raw = c.req.query("limit");
|
|
89
|
+
let limit = DEFAULT_PAGE;
|
|
90
|
+
if (raw !== undefined) {
|
|
91
|
+
limit = Number(raw);
|
|
92
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > max) {
|
|
93
|
+
throw invalid(`limit must be a whole number from 1 to ${max}.`, "limit");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return { limit, cursor: c.req.query("cursor") ?? null };
|
|
97
|
+
}
|
|
98
|
+
export function optIntQuery(c, key) {
|
|
99
|
+
const raw = c.req.query(key);
|
|
100
|
+
if (raw === undefined)
|
|
101
|
+
return undefined;
|
|
102
|
+
const value = Number(raw);
|
|
103
|
+
if (!Number.isSafeInteger(value))
|
|
104
|
+
throw invalid(`${key} must be a whole number.`, key);
|
|
105
|
+
return value;
|
|
106
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { invalid } from "../errors.js";
|
|
3
|
+
import { idempotent } from "./idempotency.js";
|
|
4
|
+
import { optEnum, optString, pageParams, readJson } from "./input.js";
|
|
5
|
+
/** How far back the sessions map looks for letters. */
|
|
6
|
+
const MAP_WINDOW_MS = 24 * 3600 * 1000;
|
|
7
|
+
/** The approval center, decisions and letters (M2 plan, section 8). */
|
|
8
|
+
export function mailRoutes(post) {
|
|
9
|
+
const app = new Hono();
|
|
10
|
+
const once = idempotent(post.mail.db);
|
|
11
|
+
// Everything waiting for the person, across sessions.
|
|
12
|
+
app.get("/center", (c) => c.json(post.center()));
|
|
13
|
+
app.get("/cards", (c) => {
|
|
14
|
+
const { limit, cursor } = pageParams(c);
|
|
15
|
+
const status = optEnum({ status: c.req.query("status") }, "status", [
|
|
16
|
+
"pending",
|
|
17
|
+
"decided",
|
|
18
|
+
"withdrawn",
|
|
19
|
+
]);
|
|
20
|
+
if (cursor !== null && !/^\d+$/.test(cursor))
|
|
21
|
+
throw invalid("cursor is not valid.", "cursor");
|
|
22
|
+
return c.json(post.mail.listCards({
|
|
23
|
+
status: status ?? null,
|
|
24
|
+
cursor: cursor ? Number(cursor) : null,
|
|
25
|
+
limit,
|
|
26
|
+
}));
|
|
27
|
+
});
|
|
28
|
+
// The person decides: an option, a note, or both. Only the person can reach this, from Yew's page.
|
|
29
|
+
app.post("/cards/:id/decide", once, async (c) => {
|
|
30
|
+
const fields = await readJson(c);
|
|
31
|
+
const choice = fields.choice;
|
|
32
|
+
if (choice !== undefined && choice !== null && typeof choice !== "number") {
|
|
33
|
+
throw invalid("choice must be the index of an option, or null.", "choice");
|
|
34
|
+
}
|
|
35
|
+
const note = optString(fields, "note", 4000) ?? null;
|
|
36
|
+
return c.json(post.decide(c.req.param("id"), choice ?? null, note));
|
|
37
|
+
});
|
|
38
|
+
app.get("/letters", (c) => {
|
|
39
|
+
const { limit, cursor } = pageParams(c);
|
|
40
|
+
const session = c.req.query("session") ?? null;
|
|
41
|
+
return c.json(post.mail.listLetters({ sessionId: session, cursor, limit }));
|
|
42
|
+
});
|
|
43
|
+
// The sessions map: letters of the last 24 hours added up per sender and receiver. The sessions
|
|
44
|
+
// themselves come from /sessions; a phone that may read those and the letters may read this.
|
|
45
|
+
app.get("/map", (c) => {
|
|
46
|
+
const since = Date.now() - MAP_WINDOW_MS;
|
|
47
|
+
return c.json({ since, letters: post.mail.letterFlows(since) });
|
|
48
|
+
});
|
|
49
|
+
app.post("/letters/:id/release", (c) => c.json(post.release(c.req.param("id"))));
|
|
50
|
+
app.post("/letters/:id/refuse", (c) => c.json(post.refuse(c.req.param("id"))));
|
|
51
|
+
return app;
|
|
52
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { conflict, invalid } from "../errors.js";
|
|
3
|
+
import { addMcpEntry, listMcpEntries, patchMcpEntry, removeMcpEntry, } from "../mcp-config.js";
|
|
4
|
+
import { idempotent } from "./idempotency.js";
|
|
5
|
+
import { optArray, optBoolean, optObject, optString, readJson, reqString, } from "./input.js";
|
|
6
|
+
/** Names with text values (null allowed where a value can be removed); anything else is refused. */
|
|
7
|
+
function values(fields, key, nullable) {
|
|
8
|
+
const object = optObject(fields, key);
|
|
9
|
+
if (!object)
|
|
10
|
+
return undefined;
|
|
11
|
+
for (const [name, value] of Object.entries(object)) {
|
|
12
|
+
if (typeof value !== "string" && !(nullable && value === null)) {
|
|
13
|
+
throw invalid(`The value of ${name} must be text.`, key);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return object;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The MCP servers in mcp.json (blueprint 6.10, item 29): list them with their connection and tools,
|
|
20
|
+
* add one, turn one off or on, remove one. Each change is written to the file and the running hub
|
|
21
|
+
* reads it again at once. Computer-only: a server is a program this computer starts.
|
|
22
|
+
*/
|
|
23
|
+
export function mcpRoutes(store, options) {
|
|
24
|
+
const app = new Hono();
|
|
25
|
+
const once = idempotent(store.db);
|
|
26
|
+
const { home, hub } = options;
|
|
27
|
+
const shown = (entry) => {
|
|
28
|
+
const status = hub.status().find((server) => server.name === entry.name);
|
|
29
|
+
return {
|
|
30
|
+
...entry,
|
|
31
|
+
// In the file but not read by the hub yet: it is about to be started.
|
|
32
|
+
state: entry.disabled ? "disabled" : (status?.state ?? "connecting"),
|
|
33
|
+
error: entry.disabled ? null : (status?.error ?? null),
|
|
34
|
+
tools: entry.disabled ? [] : (status?.tools ?? []),
|
|
35
|
+
signedIn: status?.signedIn ?? false,
|
|
36
|
+
...(status?.signInAt && !entry.disabled ? { signInAt: status.signInAt } : {}),
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const reload = () => {
|
|
40
|
+
void hub.reload().catch((error) => options.log?.(`mcp: ${error.message}`));
|
|
41
|
+
};
|
|
42
|
+
app.get("/mcp", (c) => c.json({ items: listMcpEntries(home, hub.builtin).map(shown), nextCursor: null }));
|
|
43
|
+
app.post("/mcp", once, async (c) => {
|
|
44
|
+
const fields = await readJson(c);
|
|
45
|
+
const args = optArray(fields, "args");
|
|
46
|
+
if (args?.some((arg) => typeof arg !== "string")) {
|
|
47
|
+
throw invalid("args is a list of text values.", "args");
|
|
48
|
+
}
|
|
49
|
+
const command = optString(fields, "command", 4096);
|
|
50
|
+
const preset = optString(fields, "preset", 100);
|
|
51
|
+
const url = optString(fields, "url", 2000);
|
|
52
|
+
const env = values(fields, "env", false);
|
|
53
|
+
const headers = values(fields, "headers", false);
|
|
54
|
+
const oauth = optObject(fields, "oauth");
|
|
55
|
+
const entry = addMcpEntry(home, {
|
|
56
|
+
name: reqString(fields, "name", 100),
|
|
57
|
+
...(preset !== undefined ? { preset } : {}),
|
|
58
|
+
...(command !== undefined ? { command } : {}),
|
|
59
|
+
...(args ? { args: args } : {}),
|
|
60
|
+
...(env ? { env } : {}),
|
|
61
|
+
...(url !== undefined ? { url } : {}),
|
|
62
|
+
...(headers ? { headers } : {}),
|
|
63
|
+
...(oauth ? { oauth } : {}),
|
|
64
|
+
});
|
|
65
|
+
reload();
|
|
66
|
+
return c.json(shown(entry), 201);
|
|
67
|
+
});
|
|
68
|
+
app.patch("/mcp/:name", async (c) => {
|
|
69
|
+
const fields = await readJson(c);
|
|
70
|
+
const disabled = optBoolean(fields, "disabled");
|
|
71
|
+
const env = values(fields, "env", true);
|
|
72
|
+
const headers = values(fields, "headers", true);
|
|
73
|
+
const entry = patchMcpEntry(home, c.req.param("name"), {
|
|
74
|
+
...(disabled !== undefined ? { disabled } : {}),
|
|
75
|
+
...(env ? { env } : {}),
|
|
76
|
+
...(headers ? { headers } : {}),
|
|
77
|
+
}, hub.builtin);
|
|
78
|
+
reload();
|
|
79
|
+
return c.json(shown(entry));
|
|
80
|
+
});
|
|
81
|
+
// Signing in to a server in the browser (blueprint 6.11, item 40): the page opens the address.
|
|
82
|
+
app.post("/mcp/:name/sign-in", async (c) => {
|
|
83
|
+
try {
|
|
84
|
+
return c.json({ url: await hub.signInUrl(c.req.param("name")) });
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
throw conflict(error.message, undefined, "mcp-sign-in");
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
// The same from a link on Yew's page, which opens the sign-in in a new tab: no pop-up to block.
|
|
91
|
+
app.get("/mcp/:name/sign-in", async (c) => {
|
|
92
|
+
try {
|
|
93
|
+
return c.redirect(await hub.signInUrl(c.req.param("name")), 302);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
const text = error.message.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
|
97
|
+
return c.html(`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>没有登录 · Not signed in</title><body><h1>没有登录 · Not signed in</h1><p>${text}</p></body></html>`, 409);
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
app.post("/mcp/:name/sign-out", async (c) => {
|
|
101
|
+
await hub.signOut(c.req.param("name"));
|
|
102
|
+
return c.body(null, 204);
|
|
103
|
+
});
|
|
104
|
+
app.delete("/mcp/:name", (c) => {
|
|
105
|
+
removeMcpEntry(home, c.req.param("name"), hub.builtin);
|
|
106
|
+
reload();
|
|
107
|
+
return c.body(null, 204);
|
|
108
|
+
});
|
|
109
|
+
return app;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Where the browser comes back after signing in to an MCP server. It is a plain page outside /api: the
|
|
113
|
+
* provider's redirect is a navigation from another site, which carries neither Yew's cookie nor its
|
|
114
|
+
* origin, so the one-time `state` Yew made when the sign-in started is what proves it.
|
|
115
|
+
*/
|
|
116
|
+
export function oauthCallbackRoute(hub, log) {
|
|
117
|
+
const app = new Hono();
|
|
118
|
+
const page = (title, text) => `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${title}</title><body><h1>${title}</h1><p>${text}</p></body></html>`;
|
|
119
|
+
const html = (text) => text.replace(/[&<>"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
|
120
|
+
app.get("/oauth/callback", async (c) => {
|
|
121
|
+
const state = c.req.query("state") ?? "";
|
|
122
|
+
// The address held a one-time code: nothing keeps a copy of the page.
|
|
123
|
+
c.header("Cache-Control", "no-store");
|
|
124
|
+
try {
|
|
125
|
+
const name = await hub.completeSignIn(state, c.req.query("code") ?? null, c.req.query("error") ?? null, c.req.query("iss") ?? null);
|
|
126
|
+
return c.html(page("已登录 · Signed in", `已登录 ${html(name)},可以关掉这个页面回到 Yew。<br>Signed in to ${html(name)}. You can close this page and go back to Yew.`));
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
log?.(`mcp: sign-in did not finish: ${error.message}`);
|
|
130
|
+
return c.html(page("没有登录 · Not signed in", `${html(error.message)}<br>回到 Yew 的「MCP 服务」再试一次。Go back to MCP servers in Yew and try again.`), 400);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
return app;
|
|
134
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { streamSSE } from "hono/streaming";
|
|
3
|
+
import { invalid } from "../errors.js";
|
|
4
|
+
const KEEPALIVE_MS = 15_000;
|
|
5
|
+
const MAX_QUEUE = 200;
|
|
6
|
+
/**
|
|
7
|
+
* Notifications for phones that keep their own connection instead of a push service (the Android
|
|
8
|
+
* app; blueprint 0.34). What the notifier decides to tell the phone is written to every paired
|
|
9
|
+
* phone that has this stream open and takes notifications, as plain JSON: the channel it travels
|
|
10
|
+
* in is already end-to-end encrypted. A phone that was away reads the approval center when it is
|
|
11
|
+
* back; nothing is kept for it here.
|
|
12
|
+
*/
|
|
13
|
+
export class NoteStreams {
|
|
14
|
+
#listeners = new Map();
|
|
15
|
+
#store;
|
|
16
|
+
constructor(store) {
|
|
17
|
+
this.#store = store;
|
|
18
|
+
}
|
|
19
|
+
/** Writes to the phones listening now; returns how many took it. */
|
|
20
|
+
send(note) {
|
|
21
|
+
const takes = new Set(this.#store
|
|
22
|
+
.listDevices()
|
|
23
|
+
.filter((device) => device.push)
|
|
24
|
+
.map((device) => device.id));
|
|
25
|
+
let sent = 0;
|
|
26
|
+
for (const [device, listeners] of this.#listeners) {
|
|
27
|
+
if (!takes.has(device) || listeners.size === 0)
|
|
28
|
+
continue;
|
|
29
|
+
for (const listener of listeners)
|
|
30
|
+
listener(note);
|
|
31
|
+
sent += 1;
|
|
32
|
+
}
|
|
33
|
+
return sent;
|
|
34
|
+
}
|
|
35
|
+
listen(device, listener) {
|
|
36
|
+
const listeners = this.#listeners.get(device) ?? new Set();
|
|
37
|
+
this.#listeners.set(device, listeners);
|
|
38
|
+
listeners.add(listener);
|
|
39
|
+
return () => {
|
|
40
|
+
listeners.delete(listener);
|
|
41
|
+
if (listeners.size === 0)
|
|
42
|
+
this.#listeners.delete(device);
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** `GET /api/notes`: `hello`, then one `note` event per notification. Paired phones only. */
|
|
47
|
+
export function noteRoutes(streams) {
|
|
48
|
+
const app = new Hono();
|
|
49
|
+
app.get("/notes", (c) => {
|
|
50
|
+
const device = c.env?.device;
|
|
51
|
+
if (!device)
|
|
52
|
+
throw invalid("Only a paired phone listens for notifications.", "device");
|
|
53
|
+
return streamSSE(c, async (stream) => {
|
|
54
|
+
const queue = [];
|
|
55
|
+
let wake = null;
|
|
56
|
+
const stop = streams.listen(device, (note) => {
|
|
57
|
+
// A phone that does not keep up loses the oldest; it reads the approval center anyway.
|
|
58
|
+
if (queue.length >= MAX_QUEUE)
|
|
59
|
+
queue.shift();
|
|
60
|
+
queue.push(JSON.stringify(note));
|
|
61
|
+
wake?.();
|
|
62
|
+
});
|
|
63
|
+
stream.onAbort(() => {
|
|
64
|
+
stop();
|
|
65
|
+
wake?.();
|
|
66
|
+
});
|
|
67
|
+
await stream.writeSSE({ event: "hello", data: "{}" });
|
|
68
|
+
const keepalive = setInterval(() => {
|
|
69
|
+
void stream.write(": keepalive\n\n");
|
|
70
|
+
}, KEEPALIVE_MS);
|
|
71
|
+
try {
|
|
72
|
+
while (!stream.aborted) {
|
|
73
|
+
const data = queue.shift();
|
|
74
|
+
if (data !== undefined) {
|
|
75
|
+
await stream.writeSSE({ event: "note", data });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
await new Promise((resolve) => {
|
|
79
|
+
wake = resolve;
|
|
80
|
+
});
|
|
81
|
+
wake = null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
clearInterval(keepalive);
|
|
86
|
+
stop();
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
return app;
|
|
91
|
+
}
|