@tenonai/yew 0.0.0-stage → 1.4.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 +296 -0
- package/LICENSE +21 -0
- package/README.md +55 -2
- package/THIRD-PARTY-NOTICES.md +122 -0
- package/bin/yew.js +9 -0
- package/dist/cli/app.js +198 -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 +44 -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 +126 -0
- package/dist/cli/serve.js +301 -0
- package/dist/cli/service.js +241 -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 +119 -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 +143 -0
- package/dist/server/db/database.js +49 -0
- package/dist/server/db/migrations.js +347 -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 +468 -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 +51 -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 +179 -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 +34 -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 +80 -0
- package/dist/server/skills.js +262 -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-B9oWPSod.css +1 -0
- package/web/dist/assets/index-C5qBMzFX.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,468 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { RELAY_URL } from "../../remote/protocol.js";
|
|
3
|
+
import { DEFAULT_RELAY_URL, PERMISSION_MODES, RECEIVE_POLICIES, SESSION_KINDS, THINKING_LEVELS, } from "../../shared/types.js";
|
|
4
|
+
import { isBudget, isDay, lastDays, localDay } from "../budget.js";
|
|
5
|
+
import { invalid } from "../errors.js";
|
|
6
|
+
import { exportFileName, sessionMarkdown } from "../export.js";
|
|
7
|
+
import { pickFolder } from "../folder-picker.js";
|
|
8
|
+
import { resolveWorkingFolder } from "../paths.js";
|
|
9
|
+
import { NOTIFY_KINDS, readSettings, resolveLogFile, } from "../settings.js";
|
|
10
|
+
import { resolveMemoryDir } from "../skills.js";
|
|
11
|
+
import { idempotent } from "./idempotency.js";
|
|
12
|
+
import { optArray, optBoolean, optEnum, optIntQuery, optNullableString, optNumber, optObject, optString, pageParams, readJson, reqString, } from "./input.js";
|
|
13
|
+
const RULE_EFFECTS = ["allow", "ask", "deny"];
|
|
14
|
+
export function parseRules(value) {
|
|
15
|
+
return value.map((item, index) => {
|
|
16
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
17
|
+
throw invalid(`Rule ${index + 1} must be an object.`, "rules");
|
|
18
|
+
}
|
|
19
|
+
const fields = item;
|
|
20
|
+
const effect = optEnum(fields, "effect", RULE_EFFECTS);
|
|
21
|
+
const tool = optString(fields, "tool", 64);
|
|
22
|
+
const pattern = optString(fields, "pattern", 1000);
|
|
23
|
+
if (!effect || !tool)
|
|
24
|
+
throw invalid(`Rule ${index + 1} needs an effect and a tool.`, "rules");
|
|
25
|
+
return pattern ? { effect, tool, pattern } : { effect, tool };
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
const MAX_WORKSPACES = 50;
|
|
29
|
+
/** How far back the usage page can look. */
|
|
30
|
+
const MAX_USAGE_DAYS = 90;
|
|
31
|
+
/**
|
|
32
|
+
* Checks the saved workspaces. A new or moved one must point at an existing folder; one already saved
|
|
33
|
+
* with the same path is kept as it is, so a folder that has since gone away can still be renamed or
|
|
34
|
+
* removed.
|
|
35
|
+
*/
|
|
36
|
+
export function parseWorkspaces(value, saved) {
|
|
37
|
+
if (value.length > MAX_WORKSPACES) {
|
|
38
|
+
throw invalid(`Up to ${MAX_WORKSPACES} workspaces can be saved.`, "workspaces");
|
|
39
|
+
}
|
|
40
|
+
const known = new Map(saved.map((workspace) => [workspace.id, workspace]));
|
|
41
|
+
const paths = new Set();
|
|
42
|
+
return value.map((item, index) => {
|
|
43
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) {
|
|
44
|
+
throw invalid(`Workspace ${index + 1} must be an object.`, "workspaces");
|
|
45
|
+
}
|
|
46
|
+
const fields = item;
|
|
47
|
+
const id = reqString(fields, "id", 64);
|
|
48
|
+
if (!/^[\w-]+$/.test(id))
|
|
49
|
+
throw invalid(`Workspace ${index + 1} has an invalid id.`, "workspaces");
|
|
50
|
+
const name = reqString(fields, "name", 60).trim();
|
|
51
|
+
if (!name || /\p{Cc}/u.test(name)) {
|
|
52
|
+
throw invalid(`Workspace ${index + 1} needs a name without control characters.`, "workspaces");
|
|
53
|
+
}
|
|
54
|
+
const requested = reqString(fields, "path", 4096);
|
|
55
|
+
const previous = known.get(id);
|
|
56
|
+
let path;
|
|
57
|
+
if (previous && previous.path === requested) {
|
|
58
|
+
path = previous.path;
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
try {
|
|
62
|
+
path = resolveWorkingFolder(requested);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
throw invalid(error.message, "workspaces");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (paths.has(path))
|
|
69
|
+
throw invalid(`${requested} is already a workspace.`, "workspaces");
|
|
70
|
+
paths.add(path);
|
|
71
|
+
return { id, name, path };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** `filename` for old clients, `filename*` for the real name (RFC 6266 and 5987). */
|
|
75
|
+
function contentDisposition(filename) {
|
|
76
|
+
const ascii = filename
|
|
77
|
+
.replace(/[^\x20-\x7e]/g, "")
|
|
78
|
+
.replace(/["\\]/g, "_")
|
|
79
|
+
.trim();
|
|
80
|
+
const fallback = ascii || "yew-session.md";
|
|
81
|
+
const encoded = encodeURIComponent(filename).replace(/['()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
82
|
+
return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
|
83
|
+
}
|
|
84
|
+
export function api(deps) {
|
|
85
|
+
const { store } = deps;
|
|
86
|
+
const app = new Hono();
|
|
87
|
+
const once = idempotent(store.db);
|
|
88
|
+
// --- groups ---
|
|
89
|
+
app.get("/groups", (c) => c.json({ items: store.listGroups(), nextCursor: null }));
|
|
90
|
+
// The system folder picker, for choosing a workspace's folder (macOS; elsewhere a typed path).
|
|
91
|
+
app.post("/folders/pick", async (c) => {
|
|
92
|
+
const path = await (deps.pickFolder ?? (() => pickFolder()))();
|
|
93
|
+
return c.json({ path });
|
|
94
|
+
});
|
|
95
|
+
app.post("/groups", once, async (c) => {
|
|
96
|
+
const fields = await readJson(c);
|
|
97
|
+
return c.json(store.createGroup(reqString(fields, "name", 200)), 201);
|
|
98
|
+
});
|
|
99
|
+
app.patch("/groups/:id", async (c) => {
|
|
100
|
+
const fields = await readJson(c);
|
|
101
|
+
const name = optString(fields, "name", 200);
|
|
102
|
+
const position = optNumber(fields, "position");
|
|
103
|
+
return c.json(store.updateGroup(c.req.param("id"), {
|
|
104
|
+
...(name !== undefined ? { name } : {}),
|
|
105
|
+
...(position !== undefined ? { position } : {}),
|
|
106
|
+
}));
|
|
107
|
+
});
|
|
108
|
+
app.delete("/groups/:id", (c) => {
|
|
109
|
+
store.deleteGroup(c.req.param("id"));
|
|
110
|
+
return c.body(null, 204);
|
|
111
|
+
});
|
|
112
|
+
// --- sessions ---
|
|
113
|
+
app.get("/sessions", (c) => {
|
|
114
|
+
const { limit, cursor } = pageParams(c);
|
|
115
|
+
const archived = c.req.query("archived") === "true";
|
|
116
|
+
return c.json(store.listSessions({ archived, cursor, limit }));
|
|
117
|
+
});
|
|
118
|
+
app.post("/sessions", once, async (c) => {
|
|
119
|
+
const fields = await readJson(c);
|
|
120
|
+
const settings = readSettings(store);
|
|
121
|
+
const provider = optString(fields, "provider", 100) ?? settings.defaultModel.provider;
|
|
122
|
+
const model = optString(fields, "model", 200) ?? settings.defaultModel.model;
|
|
123
|
+
deps.checkModel?.(provider, model);
|
|
124
|
+
const cwd = optNullableString(fields, "cwd", 4096);
|
|
125
|
+
const session = store.createSession({
|
|
126
|
+
name: reqString(fields, "name", 200),
|
|
127
|
+
kind: optEnum(fields, "kind", SESSION_KINDS) ?? "task",
|
|
128
|
+
groupId: optNullableString(fields, "groupId", 100) ?? null,
|
|
129
|
+
responsibility: optString(fields, "responsibility", 20_000) ?? "",
|
|
130
|
+
cwd: cwd ? resolveWorkingFolder(cwd) : null,
|
|
131
|
+
provider,
|
|
132
|
+
model,
|
|
133
|
+
thinking: optEnum(fields, "thinking", THINKING_LEVELS) ?? settings.defaultModel.thinking,
|
|
134
|
+
// New sessions start with no remembered approvals; "always allow" adds them.
|
|
135
|
+
rules: [],
|
|
136
|
+
// Named after the first message (the home page): Yew gives it a short name after one turn.
|
|
137
|
+
options: optBoolean(fields, "autoName")
|
|
138
|
+
? { permissionMode: settings.defaultPermissionMode, autoName: true }
|
|
139
|
+
: { permissionMode: settings.defaultPermissionMode },
|
|
140
|
+
});
|
|
141
|
+
return c.json(session, 201);
|
|
142
|
+
});
|
|
143
|
+
app.get("/sessions/:id", (c) => c.json(store.getSession(c.req.param("id"))));
|
|
144
|
+
// A copy of the session, with its conversation, under a free name ("名称 副本", "名称 副本 2"…).
|
|
145
|
+
app.post("/sessions/:id/duplicate", once, (c) => {
|
|
146
|
+
const source = store.getSession(c.req.param("id"));
|
|
147
|
+
const english = readSettings(store).language === "en";
|
|
148
|
+
const base = `${[...source.name].slice(0, 52).join("")}${english ? " copy" : " 副本"}`;
|
|
149
|
+
let name = base;
|
|
150
|
+
for (let n = 2; store.findSessionByName(name); n++)
|
|
151
|
+
name = `${base} ${n}`;
|
|
152
|
+
return c.json(store.duplicateSession(source.id, name), 201);
|
|
153
|
+
});
|
|
154
|
+
// A new session that goes on from one reply of this one ("名称 分叉", "名称 分叉 2"…).
|
|
155
|
+
app.post("/sessions/:id/fork", once, async (c) => {
|
|
156
|
+
const source = store.getSession(c.req.param("id"));
|
|
157
|
+
const entryId = reqString(await readJson(c), "entryId", 100);
|
|
158
|
+
const english = readSettings(store).language === "en";
|
|
159
|
+
const base = `${[...source.name].slice(0, 52).join("")}${english ? " fork" : " 分叉"}`;
|
|
160
|
+
let name = base;
|
|
161
|
+
for (let n = 2; store.findSessionByName(name); n++)
|
|
162
|
+
name = `${base} ${n}`;
|
|
163
|
+
return c.json(store.forkSession(source.id, entryId, name), 201);
|
|
164
|
+
});
|
|
165
|
+
app.patch("/sessions/:id", async (c) => {
|
|
166
|
+
const id = c.req.param("id");
|
|
167
|
+
const fields = await readJson(c);
|
|
168
|
+
const patch = {};
|
|
169
|
+
const name = optString(fields, "name", 200);
|
|
170
|
+
if (name !== undefined)
|
|
171
|
+
patch.name = name;
|
|
172
|
+
const groupId = optNullableString(fields, "groupId", 100);
|
|
173
|
+
if (groupId !== undefined)
|
|
174
|
+
patch.groupId = groupId;
|
|
175
|
+
const cwd = optNullableString(fields, "cwd", 4096);
|
|
176
|
+
if (cwd !== undefined)
|
|
177
|
+
patch.cwd = cwd ? resolveWorkingFolder(cwd) : null;
|
|
178
|
+
const responsibility = optString(fields, "responsibility", 20_000);
|
|
179
|
+
if (responsibility !== undefined)
|
|
180
|
+
patch.responsibility = responsibility;
|
|
181
|
+
const provider = optString(fields, "provider", 100);
|
|
182
|
+
const model = optString(fields, "model", 200);
|
|
183
|
+
if (provider !== undefined || model !== undefined) {
|
|
184
|
+
const current = store.getSession(id);
|
|
185
|
+
deps.checkModel?.(provider ?? current.provider, model ?? current.model);
|
|
186
|
+
if (provider !== undefined)
|
|
187
|
+
patch.provider = provider;
|
|
188
|
+
if (model !== undefined)
|
|
189
|
+
patch.model = model;
|
|
190
|
+
}
|
|
191
|
+
const thinking = optEnum(fields, "thinking", THINKING_LEVELS);
|
|
192
|
+
if (thinking !== undefined)
|
|
193
|
+
patch.thinking = thinking;
|
|
194
|
+
const rules = optArray(fields, "rules");
|
|
195
|
+
if (rules !== undefined)
|
|
196
|
+
patch.rules = parseRules(rules);
|
|
197
|
+
const options = optObject(fields, "options");
|
|
198
|
+
if (options !== undefined) {
|
|
199
|
+
const compactAt = options.compactAt;
|
|
200
|
+
if (compactAt !== undefined &&
|
|
201
|
+
compactAt !== null &&
|
|
202
|
+
(typeof compactAt !== "number" || !Number.isInteger(compactAt) || compactAt < 10_000)) {
|
|
203
|
+
throw invalid("compactAt must be a whole number of at least 10000, or null.", "options");
|
|
204
|
+
}
|
|
205
|
+
const permissionMode = optEnum(options, "permissionMode", PERMISSION_MODES);
|
|
206
|
+
const receive = optEnum(options, "receive", RECEIVE_POLICIES);
|
|
207
|
+
const letterQuota = options.letterQuota;
|
|
208
|
+
if (letterQuota !== undefined &&
|
|
209
|
+
letterQuota !== null &&
|
|
210
|
+
(typeof letterQuota !== "number" ||
|
|
211
|
+
!Number.isInteger(letterQuota) ||
|
|
212
|
+
letterQuota < 1 ||
|
|
213
|
+
letterQuota > 100)) {
|
|
214
|
+
throw invalid("letterQuota must be a whole number from 1 to 100, or null.", "options");
|
|
215
|
+
}
|
|
216
|
+
const canPostCards = optBoolean(options, "canPostCards");
|
|
217
|
+
const canOrganize = optBoolean(options, "canOrganize");
|
|
218
|
+
const dailyBudget = options.dailyBudget;
|
|
219
|
+
if (dailyBudget !== undefined && !isBudget(dailyBudget)) {
|
|
220
|
+
throw invalid("dailyBudget must be an amount in US dollars above 0, or null.", "options");
|
|
221
|
+
}
|
|
222
|
+
const next = {};
|
|
223
|
+
if (compactAt !== undefined)
|
|
224
|
+
next.compactAt = compactAt;
|
|
225
|
+
if (permissionMode !== undefined)
|
|
226
|
+
next.permissionMode = permissionMode;
|
|
227
|
+
if (receive !== undefined)
|
|
228
|
+
next.receive = receive;
|
|
229
|
+
if (letterQuota !== undefined)
|
|
230
|
+
next.letterQuota = letterQuota;
|
|
231
|
+
if (canPostCards !== undefined)
|
|
232
|
+
next.canPostCards = canPostCards;
|
|
233
|
+
if (canOrganize !== undefined)
|
|
234
|
+
next.canOrganize = canOrganize;
|
|
235
|
+
// A new limit starts without the room given by continuing under the old one.
|
|
236
|
+
if (dailyBudget !== undefined) {
|
|
237
|
+
next.dailyBudget = dailyBudget;
|
|
238
|
+
next.budgetExtra = null;
|
|
239
|
+
}
|
|
240
|
+
patch.options = next;
|
|
241
|
+
}
|
|
242
|
+
// A name the person chose is not replaced by Yew's automatic one.
|
|
243
|
+
if (patch.name !== undefined)
|
|
244
|
+
patch.options = { ...patch.options, autoName: false };
|
|
245
|
+
const pinned = optBoolean(fields, "pinned");
|
|
246
|
+
if (pinned !== undefined)
|
|
247
|
+
patch.pinned = pinned;
|
|
248
|
+
const archived = optBoolean(fields, "archived");
|
|
249
|
+
if (archived !== undefined)
|
|
250
|
+
patch.archived = archived;
|
|
251
|
+
if (optBoolean(fields, "read") === true)
|
|
252
|
+
patch.read = true;
|
|
253
|
+
const before = store.getSession(id);
|
|
254
|
+
const updated = store.updateSession(id, patch);
|
|
255
|
+
if (before.archivedAt === null && updated.archivedAt !== null)
|
|
256
|
+
deps.onArchived?.(id);
|
|
257
|
+
if (updated.provider !== before.provider || updated.model !== before.model) {
|
|
258
|
+
store.appendEntry(id, {
|
|
259
|
+
role: "notice",
|
|
260
|
+
notice: {
|
|
261
|
+
kind: "model_changed",
|
|
262
|
+
text: `${before.provider}/${before.model} → ${updated.provider}/${updated.model}`,
|
|
263
|
+
timestamp: Date.now(),
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
return c.json(store.getSession(id));
|
|
267
|
+
}
|
|
268
|
+
return c.json(updated);
|
|
269
|
+
});
|
|
270
|
+
app.get("/sessions/:id/transcript", (c) => {
|
|
271
|
+
const session = store.getSession(c.req.param("id"));
|
|
272
|
+
const limit = optIntQuery(c, "limit") ?? 100;
|
|
273
|
+
if (limit < 1 || limit > 500)
|
|
274
|
+
throw invalid("limit must be from 1 to 500.", "limit");
|
|
275
|
+
const before = optIntQuery(c, "before") ?? null;
|
|
276
|
+
// Read everything at one point in time, so the client can resume the event stream from session.eventSeq.
|
|
277
|
+
const transcript = store.tx(() => {
|
|
278
|
+
const page = store.listEntries(session.id, { before, limit });
|
|
279
|
+
const toolCalls = store.toolCallsForMessages(page.entries.map((entry) => entry.id));
|
|
280
|
+
const approvals = store.approvalsForToolCalls(toolCalls.map((call) => call.id));
|
|
281
|
+
const pending = store
|
|
282
|
+
.pendingApprovals(session.id)
|
|
283
|
+
.filter((approval) => !approvals.some((known) => known.id === approval.id));
|
|
284
|
+
return {
|
|
285
|
+
session: store.getSession(session.id),
|
|
286
|
+
entries: page.entries,
|
|
287
|
+
toolCalls,
|
|
288
|
+
approvals: [...approvals, ...pending],
|
|
289
|
+
queue: store.listQueue(session.id),
|
|
290
|
+
olderCursor: page.olderCursor,
|
|
291
|
+
};
|
|
292
|
+
});
|
|
293
|
+
return c.json(transcript);
|
|
294
|
+
});
|
|
295
|
+
// The whole session as one Markdown file. The language comes from the interface; without it the
|
|
296
|
+
// saved interface language is used, and a system setting falls back to Chinese.
|
|
297
|
+
app.get("/sessions/:id/export.md", (c) => {
|
|
298
|
+
const session = store.getSession(c.req.param("id"));
|
|
299
|
+
const requested = c.req.query("lang");
|
|
300
|
+
if (requested !== undefined && requested !== "zh" && requested !== "en") {
|
|
301
|
+
throw invalid("lang must be zh or en.", "lang");
|
|
302
|
+
}
|
|
303
|
+
const saved = readSettings(store).language;
|
|
304
|
+
const language = requested ?? (saved === "en" ? "en" : "zh");
|
|
305
|
+
const groupName = session.groupId ? store.getGroup(session.groupId).name : null;
|
|
306
|
+
const markdown = sessionMarkdown({
|
|
307
|
+
session,
|
|
308
|
+
groupName,
|
|
309
|
+
entries: store.allEntries(session.id),
|
|
310
|
+
toolCalls: store.toolCallsForSession(session.id),
|
|
311
|
+
language,
|
|
312
|
+
});
|
|
313
|
+
c.header("Content-Type", "text/markdown; charset=utf-8");
|
|
314
|
+
c.header("Content-Disposition", contentDisposition(exportFileName(session.name)));
|
|
315
|
+
return c.body(markdown);
|
|
316
|
+
});
|
|
317
|
+
app.get("/sessions/:id/queue", (c) => {
|
|
318
|
+
const id = c.req.param("id");
|
|
319
|
+
store.getSession(id);
|
|
320
|
+
return c.json({ items: store.listQueue(id), nextCursor: null });
|
|
321
|
+
});
|
|
322
|
+
app.patch("/sessions/:id/queue/:queuedId", async (c) => {
|
|
323
|
+
const fields = await readJson(c);
|
|
324
|
+
const text = reqString(fields, "text", 100_000);
|
|
325
|
+
if (text.trim().length === 0)
|
|
326
|
+
throw invalid("The message cannot be empty.", "text");
|
|
327
|
+
return c.json(store.updateQueued(c.req.param("id"), c.req.param("queuedId"), text));
|
|
328
|
+
});
|
|
329
|
+
app.delete("/sessions/:id/queue/:queuedId", (c) => {
|
|
330
|
+
store.removeQueued(c.req.param("id"), c.req.param("queuedId"));
|
|
331
|
+
return c.body(null, 204);
|
|
332
|
+
});
|
|
333
|
+
// --- search and settings ---
|
|
334
|
+
app.get("/search", (c) => {
|
|
335
|
+
const q = c.req.query("q") ?? "";
|
|
336
|
+
if (q.length > 200)
|
|
337
|
+
throw invalid("The search text can be at most 200 characters.", "q");
|
|
338
|
+
const limit = optIntQuery(c, "limit") ?? 20;
|
|
339
|
+
if (limit < 1 || limit > 100)
|
|
340
|
+
throw invalid("limit must be from 1 to 100.", "limit");
|
|
341
|
+
return c.json(store.search(q, limit));
|
|
342
|
+
});
|
|
343
|
+
app.get("/settings", (c) => c.json(readSettings(store)));
|
|
344
|
+
app.patch("/settings", async (c) => {
|
|
345
|
+
const fields = await readJson(c);
|
|
346
|
+
const defaultModel = optObject(fields, "defaultModel");
|
|
347
|
+
if (defaultModel) {
|
|
348
|
+
const value = {
|
|
349
|
+
provider: reqString(defaultModel, "provider", 100),
|
|
350
|
+
model: reqString(defaultModel, "model", 200),
|
|
351
|
+
thinking: optEnum(defaultModel, "thinking", THINKING_LEVELS) ?? "medium",
|
|
352
|
+
};
|
|
353
|
+
deps.checkModel?.(value.provider, value.model);
|
|
354
|
+
store.setSetting("defaultModel", value);
|
|
355
|
+
}
|
|
356
|
+
const theme = optEnum(fields, "theme", ["system", "light", "dark"]);
|
|
357
|
+
if (theme)
|
|
358
|
+
store.setSetting("theme", theme);
|
|
359
|
+
const language = optEnum(fields, "language", ["system", "zh", "en"]);
|
|
360
|
+
if (language)
|
|
361
|
+
store.setSetting("language", language);
|
|
362
|
+
const mascot = optBoolean(fields, "mascot");
|
|
363
|
+
if (mascot !== undefined)
|
|
364
|
+
store.setSetting("mascot", mascot);
|
|
365
|
+
const workspaces = optArray(fields, "workspaces");
|
|
366
|
+
if (workspaces) {
|
|
367
|
+
store.setSetting("workspaces", parseWorkspaces(workspaces, readSettings(store).workspaces));
|
|
368
|
+
}
|
|
369
|
+
const main = optNullableString(fields, "mainSessionId", 100);
|
|
370
|
+
if (main !== undefined) {
|
|
371
|
+
if (main !== null && store.getSession(main).archivedAt !== null) {
|
|
372
|
+
throw invalid("An archived session cannot be the main conversation.", "mainSessionId");
|
|
373
|
+
}
|
|
374
|
+
store.setSetting("mainSessionId", main);
|
|
375
|
+
}
|
|
376
|
+
const log = optNullableString(fields, "decisionLog", 4096);
|
|
377
|
+
if (log !== undefined)
|
|
378
|
+
store.setSetting("decisionLog", log ? resolveLogFile(log) : null);
|
|
379
|
+
const remote = optObject(fields, "remote");
|
|
380
|
+
if (remote) {
|
|
381
|
+
// Remote access is changed on the Mac only (M3 plan, section 4).
|
|
382
|
+
if (c.env?.device)
|
|
383
|
+
throw invalid("Phone access can only be changed on the Mac.", "remote");
|
|
384
|
+
const enabled = optBoolean(remote, "enabled");
|
|
385
|
+
// null goes back to the relay Yew comes with.
|
|
386
|
+
const asked = optNullableString(remote, "relayUrl", 500);
|
|
387
|
+
const relayUrl = asked === null ? DEFAULT_RELAY_URL : asked?.trim();
|
|
388
|
+
if (relayUrl !== undefined && !RELAY_URL.test(relayUrl)) {
|
|
389
|
+
throw invalid("The relay must be a wss:// address (ws:// only inside this network).", "remote");
|
|
390
|
+
}
|
|
391
|
+
const current = readSettings(store).remote;
|
|
392
|
+
store.setSetting("remote", {
|
|
393
|
+
enabled: enabled ?? current.enabled,
|
|
394
|
+
relayUrl: relayUrl ?? current.relayUrl,
|
|
395
|
+
});
|
|
396
|
+
deps.onRemoteChanged?.();
|
|
397
|
+
}
|
|
398
|
+
const mode = optEnum(fields, "defaultPermissionMode", PERMISSION_MODES);
|
|
399
|
+
if (mode)
|
|
400
|
+
store.setSetting("defaultPermissionMode", mode);
|
|
401
|
+
const defaultWorkspace = optNullableString(fields, "defaultWorkspaceId", 64);
|
|
402
|
+
if (defaultWorkspace !== undefined) {
|
|
403
|
+
const saved = readSettings(store).workspaces;
|
|
404
|
+
if (defaultWorkspace !== null && !saved.some((item) => item.id === defaultWorkspace)) {
|
|
405
|
+
throw invalid("The default workspace must be one of the saved ones.", "defaultWorkspaceId");
|
|
406
|
+
}
|
|
407
|
+
store.setSetting("defaultWorkspaceId", defaultWorkspace);
|
|
408
|
+
}
|
|
409
|
+
const notify = optObject(fields, "notify");
|
|
410
|
+
if (notify) {
|
|
411
|
+
const next = { ...readSettings(store).notify };
|
|
412
|
+
for (const kind of NOTIFY_KINDS)
|
|
413
|
+
next[kind] = optBoolean(notify, kind) ?? next[kind];
|
|
414
|
+
store.setSetting("notify", next);
|
|
415
|
+
}
|
|
416
|
+
const memoryDirs = optArray(fields, "memoryDirs");
|
|
417
|
+
if (memoryDirs) {
|
|
418
|
+
if (memoryDirs.length > 10 || memoryDirs.some((dir) => typeof dir !== "string")) {
|
|
419
|
+
throw invalid("memoryDirs is a list of up to 10 folders.", "memoryDirs");
|
|
420
|
+
}
|
|
421
|
+
store.setSetting("memoryDirs", [
|
|
422
|
+
...new Set(memoryDirs.map((dir) => resolveMemoryDir(dir))),
|
|
423
|
+
]);
|
|
424
|
+
}
|
|
425
|
+
if (fields.dailyBudget !== undefined) {
|
|
426
|
+
if (!isBudget(fields.dailyBudget)) {
|
|
427
|
+
throw invalid("dailyBudget must be an amount in US dollars above 0, or null.", "dailyBudget");
|
|
428
|
+
}
|
|
429
|
+
store.setSetting("dailyBudget", fields.dailyBudget);
|
|
430
|
+
store.setSetting("budgetExtra", null);
|
|
431
|
+
}
|
|
432
|
+
return c.json(readSettings(store));
|
|
433
|
+
});
|
|
434
|
+
// What was spent today (this computer's calendar day), in all and by session, for the limits.
|
|
435
|
+
app.get("/usage/today", (c) => {
|
|
436
|
+
const day = localDay(Date.now());
|
|
437
|
+
return c.json({ day, total: store.spentOn(day), sessions: store.spentBySession(day) });
|
|
438
|
+
});
|
|
439
|
+
// The usage page: each of the last days with what all sessions used, days without use as zeros.
|
|
440
|
+
app.get("/usage", (c) => {
|
|
441
|
+
const count = optIntQuery(c, "days") ?? 30;
|
|
442
|
+
if (count < 1 || count > MAX_USAGE_DAYS) {
|
|
443
|
+
throw invalid(`days must be a whole number from 1 to ${MAX_USAGE_DAYS}.`, "days");
|
|
444
|
+
}
|
|
445
|
+
const days = lastDays(Date.now(), count);
|
|
446
|
+
const today = days[days.length - 1];
|
|
447
|
+
const used = new Map(store.usageByDay(days[0], today).map((row) => [row.day, row]));
|
|
448
|
+
const overview = {
|
|
449
|
+
today,
|
|
450
|
+
budget: store.getSetting("dailyBudget", null),
|
|
451
|
+
days: days.map((day) => used.get(day) ?? { day, cost: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }),
|
|
452
|
+
};
|
|
453
|
+
return c.json(overview);
|
|
454
|
+
});
|
|
455
|
+
// One day on the usage page: what each session used, the one that cost most first.
|
|
456
|
+
app.get("/usage/:day", (c) => {
|
|
457
|
+
const day = c.req.param("day");
|
|
458
|
+
if (!isDay(day))
|
|
459
|
+
throw invalid("day must be a calendar day written as YYYY-MM-DD.", "day");
|
|
460
|
+
const detail = {
|
|
461
|
+
day,
|
|
462
|
+
total: store.spentOn(day),
|
|
463
|
+
sessions: store.usageBySession(day),
|
|
464
|
+
};
|
|
465
|
+
return c.json(detail);
|
|
466
|
+
});
|
|
467
|
+
return app;
|
|
468
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { serveStatic } from "@hono/node-server/serve-static";
|
|
4
|
+
import { Hono } from "hono";
|
|
5
|
+
import { VERSION } from "../../shared/version.js";
|
|
6
|
+
import { PostOffice } from "../mail/post.js";
|
|
7
|
+
import { agentRoutes } from "./agents.js";
|
|
8
|
+
import { api } from "./api.js";
|
|
9
|
+
import { artifactRoutes } from "./artifacts.js";
|
|
10
|
+
import { dataRoutes } from "./data.js";
|
|
11
|
+
import { deviceRoutes } from "./devices.js";
|
|
12
|
+
import { DraftCache, eventRoutes } from "./events.js";
|
|
13
|
+
import { mailRoutes } from "./mail.js";
|
|
14
|
+
import { mcpRoutes, oauthCallbackRoute } from "./mcp.js";
|
|
15
|
+
import { noteRoutes } from "./notes.js";
|
|
16
|
+
import { errorHandler, problemResponse, requestId, titleFor } from "./problem.js";
|
|
17
|
+
import { providerRoutes } from "./providers.js";
|
|
18
|
+
import { scheduleRoutes } from "./schedules.js";
|
|
19
|
+
import { searchRoutes } from "./search.js";
|
|
20
|
+
import { authRoutes, deviceLimits, localOnly, requireBrowser, securityHeaders, } from "./security.js";
|
|
21
|
+
import { skillRoutes } from "./skills.js";
|
|
22
|
+
import { systemRoutes } from "./system.js";
|
|
23
|
+
const NOT_BUILT = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>Yew</title>
|
|
24
|
+
<meta name="color-scheme" content="light dark"></head><body>
|
|
25
|
+
<p>网页界面还没有构建。在 Yew 的目录运行 npm run build:web,然后刷新这个页面。</p>
|
|
26
|
+
<p lang="en">The web interface has not been built yet. In the Yew folder, run npm run build:web, then reload this page.</p>
|
|
27
|
+
</body></html>`;
|
|
28
|
+
export function createApp(options) {
|
|
29
|
+
const log = options.log ?? ((line) => process.stderr.write(`${line}\n`));
|
|
30
|
+
const { store, gateway, agents, bus } = options;
|
|
31
|
+
const app = new Hono();
|
|
32
|
+
app.use("*", requestId());
|
|
33
|
+
app.use("*", securityHeaders());
|
|
34
|
+
app.onError(errorHandler(log));
|
|
35
|
+
app.notFound((c) => problemResponse(c, 404, "not-found", titleFor(404), "No such endpoint."));
|
|
36
|
+
if (options.security) {
|
|
37
|
+
app.use("*", localOnly(options.security.port));
|
|
38
|
+
app.use("*", requireBrowser(store, options.security.port));
|
|
39
|
+
app.route("/api", authRoutes(store, options.security.port));
|
|
40
|
+
}
|
|
41
|
+
app.use("*", deviceLimits());
|
|
42
|
+
app.get("/api/health", (c) => c.json({ ok: true, version: VERSION, build: options.build ?? null }));
|
|
43
|
+
app.route("/api", api({
|
|
44
|
+
store,
|
|
45
|
+
...(gateway ? { checkModel: (p, m) => gateway.check(p, m) } : {}),
|
|
46
|
+
...(options.pickFolder ? { pickFolder: options.pickFolder } : {}),
|
|
47
|
+
...(agents ? { onArchived: (id) => agents.archived(id) } : {}),
|
|
48
|
+
...(options.remote
|
|
49
|
+
? { onRemoteChanged: () => void options.remote?.sync().catch((e) => log(e.message)) }
|
|
50
|
+
: {}),
|
|
51
|
+
}));
|
|
52
|
+
app.route("/api", deviceRoutes(store, options.remote));
|
|
53
|
+
// The page on the Mac says it is in front and in use; a phone's use does not count.
|
|
54
|
+
app.post("/api/presence", (c) => {
|
|
55
|
+
if (!c.env?.device)
|
|
56
|
+
options.onPresence?.();
|
|
57
|
+
return c.body(null, 204);
|
|
58
|
+
});
|
|
59
|
+
if (gateway)
|
|
60
|
+
app.route("/api", providerRoutes(store, gateway));
|
|
61
|
+
if (agents)
|
|
62
|
+
app.route("/api", agentRoutes(store, agents, log));
|
|
63
|
+
// The runner's post office, so a released letter or a decision wakes its recipient.
|
|
64
|
+
app.route("/api", mailRoutes(agents?.post ?? new PostOffice(store, log)));
|
|
65
|
+
if (bus)
|
|
66
|
+
app.route("/api", eventRoutes(store, bus, new DraftCache(bus)));
|
|
67
|
+
if (options.scheduler)
|
|
68
|
+
app.route("/api", scheduleRoutes(store, options.scheduler));
|
|
69
|
+
if (options.notes)
|
|
70
|
+
app.route("/api", noteRoutes(options.notes));
|
|
71
|
+
if (options.mcp) {
|
|
72
|
+
app.route("/api", mcpRoutes(store, { log, ...options.mcp }));
|
|
73
|
+
app.route("/", oauthCallbackRoute(options.mcp.hub, log));
|
|
74
|
+
}
|
|
75
|
+
if (options.skills)
|
|
76
|
+
app.route("/api", skillRoutes(store, options.skills));
|
|
77
|
+
if (options.data) {
|
|
78
|
+
// A session's output files are left alone while one of its commands may still write to them.
|
|
79
|
+
const inUse = agents ? (id) => agents.hasLiveCommands(id) : undefined;
|
|
80
|
+
app.route("/api", dataRoutes(store, { ...(inUse ? { inUse } : {}), ...options.data }));
|
|
81
|
+
}
|
|
82
|
+
if (options.search)
|
|
83
|
+
app.route("/api", searchRoutes(options.search));
|
|
84
|
+
if (options.system)
|
|
85
|
+
app.route("/api", systemRoutes(options.system));
|
|
86
|
+
if (options.artifacts)
|
|
87
|
+
app.route("/", artifactRoutes(options.artifacts));
|
|
88
|
+
const root = options.webRoot;
|
|
89
|
+
if (root && existsSync(join(root, "index.html"))) {
|
|
90
|
+
// Read per request, so a rebuilt interface (npm run watch:web) is served without a restart.
|
|
91
|
+
const index = () => readFileSync(join(root, "index.html"), "utf8");
|
|
92
|
+
app.use("/assets/*", async (c, next) => {
|
|
93
|
+
await next();
|
|
94
|
+
// Built assets have content hashes in their names, so they can be cached for good.
|
|
95
|
+
if (c.res.status === 200) {
|
|
96
|
+
c.res.headers.set("Cache-Control", "public, max-age=31536000, immutable");
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
app.use("*", serveStatic({ root }));
|
|
100
|
+
app.get("*", (c) => {
|
|
101
|
+
if (c.req.path.startsWith("/api/"))
|
|
102
|
+
return c.notFound();
|
|
103
|
+
c.header("Cache-Control", "no-cache");
|
|
104
|
+
return c.html(index());
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
app.get("/", (c) => c.html(NOT_BUILT));
|
|
109
|
+
}
|
|
110
|
+
return app;
|
|
111
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { invalid } from "../errors.js";
|
|
3
|
+
import { optIntQuery } from "./input.js";
|
|
4
|
+
/**
|
|
5
|
+
* What an HTML artifact is served with (blueprint 6.6, item 19). `sandbox` without
|
|
6
|
+
* allow-same-origin makes the page its own origin: it has no cookie for Yew and cannot read Yew's
|
|
7
|
+
* pages. `default-src 'none'` stops every request, so it cannot reach Yew's interface or anything
|
|
8
|
+
* else; only its own inline scripts and styles run.
|
|
9
|
+
*/
|
|
10
|
+
export const ARTIFACT_CSP = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; frame-ancestors 'self'";
|
|
11
|
+
const versionOf = (text) => {
|
|
12
|
+
if (!/^\d{1,6}$/.test(text))
|
|
13
|
+
throw invalid("The version is a whole number.", "version");
|
|
14
|
+
return Number(text);
|
|
15
|
+
};
|
|
16
|
+
export function artifactRoutes(artifacts) {
|
|
17
|
+
const app = new Hono();
|
|
18
|
+
app.get("/api/artifacts", (c) => {
|
|
19
|
+
const limit = optIntQuery(c, "limit") ?? 100;
|
|
20
|
+
if (limit < 1 || limit > 500)
|
|
21
|
+
throw invalid("limit must be from 1 to 500.", "limit");
|
|
22
|
+
return c.json({
|
|
23
|
+
items: artifacts.list({ sessionId: c.req.query("session") ?? null, limit }),
|
|
24
|
+
nextCursor: null,
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
app.get("/api/artifacts/:id", (c) => {
|
|
28
|
+
const id = c.req.param("id");
|
|
29
|
+
return c.json({ artifact: artifacts.get(id), versions: artifacts.versions(id) });
|
|
30
|
+
});
|
|
31
|
+
// The version's text as it was saved, for Yew's own viewers and for downloading.
|
|
32
|
+
app.get("/api/artifacts/:id/versions/:version", (c) => {
|
|
33
|
+
const { content } = artifacts.content(c.req.param("id"), versionOf(c.req.param("version")));
|
|
34
|
+
c.header("Content-Type", "text/plain; charset=utf-8");
|
|
35
|
+
c.header("X-Content-Type-Options", "nosniff");
|
|
36
|
+
return c.body(content);
|
|
37
|
+
});
|
|
38
|
+
app.delete("/api/artifacts/:id", (c) => {
|
|
39
|
+
artifacts.delete(c.req.param("id"));
|
|
40
|
+
return c.body(null, 204);
|
|
41
|
+
});
|
|
42
|
+
// An HTML artifact as a page, shut in. Other kinds are drawn by Yew and have no page here.
|
|
43
|
+
app.get("/artifact-view/:id/:version", (c) => {
|
|
44
|
+
const { artifact, content } = artifacts.content(c.req.param("id"), versionOf(c.req.param("version")));
|
|
45
|
+
if (artifact.kind !== "html")
|
|
46
|
+
throw invalid("Only HTML artifacts have a page.", "id");
|
|
47
|
+
c.header("Content-Type", "text/html; charset=utf-8");
|
|
48
|
+
c.header("Content-Security-Policy", ARTIFACT_CSP);
|
|
49
|
+
c.header("Cache-Control", "no-store");
|
|
50
|
+
return c.body(content);
|
|
51
|
+
});
|
|
52
|
+
return app;
|
|
53
|
+
}
|