@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,603 @@
|
|
|
1
|
+
import { appendFileSync, existsSync } from "node:fs";
|
|
2
|
+
import { letterQuotaOf, permissionModeOf, } from "../../shared/types.js";
|
|
3
|
+
import { conflict, invalid, YewError } from "../errors.js";
|
|
4
|
+
import { readSettings } from "../settings.js";
|
|
5
|
+
import { MailStore } from "./store.js";
|
|
6
|
+
export const SUMMARY_MAX = 200;
|
|
7
|
+
export const BODY_MAX = 20_000;
|
|
8
|
+
const MINUTE = 60_000;
|
|
9
|
+
/** Letters one session may send the same session per minute; more should go in one letter. */
|
|
10
|
+
const PAIR_RATE = 3;
|
|
11
|
+
/**
|
|
12
|
+
* Letters one session may send per minute in all. High enough for the main conversation to write to
|
|
13
|
+
* each session once; the quota bounds the total anyway.
|
|
14
|
+
*/
|
|
15
|
+
const TOTAL_RATE = 20;
|
|
16
|
+
/** The same letter twice within this time is dropped. */
|
|
17
|
+
const DUPLICATE_WINDOW = 10 * MINUTE;
|
|
18
|
+
/** Letters one session may send another within DUPLICATE_WINDOW. */
|
|
19
|
+
const PAIR_LIMIT = 10;
|
|
20
|
+
/** Letters in one chain of hand-offs. */
|
|
21
|
+
const MAX_HOPS = 8;
|
|
22
|
+
/** A session that already sent this many letters in a chain is not written to again in it. */
|
|
23
|
+
const MAX_VISITS = 3;
|
|
24
|
+
const OPTIONS_MAX = 6;
|
|
25
|
+
export function reasonText(reason) {
|
|
26
|
+
switch (reason) {
|
|
27
|
+
case "quota":
|
|
28
|
+
return "you have used up your letters until the person writes to you again";
|
|
29
|
+
case "rate":
|
|
30
|
+
return "you sent this session several letters in the last minute; put what you have to say in one letter";
|
|
31
|
+
case "burst":
|
|
32
|
+
return `you sent ${TOTAL_RATE} letters in the last minute; wait a moment before sending more`;
|
|
33
|
+
case "duplicate":
|
|
34
|
+
return "the same letter was already sent a moment ago";
|
|
35
|
+
case "pair-limit":
|
|
36
|
+
return "you sent this session too many letters in the last ten minutes";
|
|
37
|
+
case "hops":
|
|
38
|
+
return `this chain of hand-offs is already ${MAX_HOPS} letters long; stop and report to whoever started it`;
|
|
39
|
+
case "loop":
|
|
40
|
+
return "this chain keeps coming back to the same session; stop and report instead of sending it on";
|
|
41
|
+
case "refuse-policy":
|
|
42
|
+
return "the session does not accept letters";
|
|
43
|
+
case "hold-policy":
|
|
44
|
+
return "the session holds letters until the person releases them";
|
|
45
|
+
case "lower-rank":
|
|
46
|
+
return "the session has more permissions than you, so the person releases your letters to it first";
|
|
47
|
+
case "person-refused":
|
|
48
|
+
return "the person refused it";
|
|
49
|
+
case "archived":
|
|
50
|
+
return "the session was archived before it read the letter";
|
|
51
|
+
default:
|
|
52
|
+
return reason ?? "";
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Permission level for the hold rule: a chat, then manual, automatic and skip approval (blueprint 7.1). */
|
|
56
|
+
function rank(session) {
|
|
57
|
+
if (!session.cwd)
|
|
58
|
+
return 0;
|
|
59
|
+
return { manual: 1, auto: 2, skip: 3 }[permissionModeOf(session.options)];
|
|
60
|
+
}
|
|
61
|
+
const oneLine = (text) => text.replace(/\s+/g, " ").trim();
|
|
62
|
+
/**
|
|
63
|
+
* Whether a letter from `from` answers a request `to` sent it and is still waiting on: it replies to that
|
|
64
|
+
* request and is not a request itself (a question back is not the answer). Only the first answer counts,
|
|
65
|
+
* because it closes the request.
|
|
66
|
+
*/
|
|
67
|
+
function answersOpenRequest(from, to, repliedTo, kind) {
|
|
68
|
+
return (repliedTo !== null &&
|
|
69
|
+
kind !== "request" &&
|
|
70
|
+
repliedTo.kind === "request" &&
|
|
71
|
+
repliedTo.fromSession === to.id &&
|
|
72
|
+
repliedTo.toSession === from.id &&
|
|
73
|
+
repliedTo.status === "delivered");
|
|
74
|
+
}
|
|
75
|
+
function limited(value, field, max, required) {
|
|
76
|
+
if (value === undefined || value === null) {
|
|
77
|
+
if (required)
|
|
78
|
+
throw invalid(`${field} is required.`, field);
|
|
79
|
+
return "";
|
|
80
|
+
}
|
|
81
|
+
if (typeof value !== "string")
|
|
82
|
+
throw invalid(`${field} must be text.`, field);
|
|
83
|
+
const text = value.trim();
|
|
84
|
+
if (required && !text)
|
|
85
|
+
throw invalid(`${field} cannot be empty.`, field);
|
|
86
|
+
if ([...text].length > max)
|
|
87
|
+
throw invalid(`${field} can be at most ${max} characters.`, field);
|
|
88
|
+
return text;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Letters between sessions and decision cards for the person (blueprint sections 6.3, 6.4 and 7). Every
|
|
92
|
+
* check a letter passes lives here: the address, the recipient's policy, the quota, rate limits,
|
|
93
|
+
* duplicates and the length of a chain of hand-offs. The agent runner delivers what is queued.
|
|
94
|
+
*/
|
|
95
|
+
export class PostOffice {
|
|
96
|
+
mail;
|
|
97
|
+
#store;
|
|
98
|
+
#log;
|
|
99
|
+
#hooks = { queued: () => { } };
|
|
100
|
+
/** Each session's letters in the last minute, and to whom, for the per-minute limits. */
|
|
101
|
+
#sent = new Map();
|
|
102
|
+
/** The chain each working session is in: senders so far, oldest first. */
|
|
103
|
+
#chains = new Map();
|
|
104
|
+
constructor(store, log = () => { }) {
|
|
105
|
+
this.#store = store;
|
|
106
|
+
this.mail = new MailStore(store);
|
|
107
|
+
this.#log = log;
|
|
108
|
+
}
|
|
109
|
+
setHooks(hooks) {
|
|
110
|
+
this.#hooks = hooks;
|
|
111
|
+
}
|
|
112
|
+
/** The main conversation, if one is set and still there. */
|
|
113
|
+
/** Yew's settings, for what list_sessions shows. */
|
|
114
|
+
settings() {
|
|
115
|
+
return readSettings(this.#store);
|
|
116
|
+
}
|
|
117
|
+
mainSessionId() {
|
|
118
|
+
const id = this.#store.getSetting("mainSessionId", null);
|
|
119
|
+
if (!id)
|
|
120
|
+
return null;
|
|
121
|
+
try {
|
|
122
|
+
return this.#store.getSession(id).archivedAt === null ? id : null;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Sessions that may put cards in the approval center: the main conversation and those allowed to. */
|
|
129
|
+
canPostCards(session) {
|
|
130
|
+
return session.id === this.mainSessionId() || session.options.canPostCards === true;
|
|
131
|
+
}
|
|
132
|
+
/** Sessions that may rename sessions and teams and move sessions between teams. */
|
|
133
|
+
canOrganize(session) {
|
|
134
|
+
return session.id === this.mainSessionId() || session.options.canOrganize === true;
|
|
135
|
+
}
|
|
136
|
+
letterQuota(session) {
|
|
137
|
+
return letterQuotaOf(session.options, session.id === this.mainSessionId());
|
|
138
|
+
}
|
|
139
|
+
/** Sessions that can receive letters, with their groups' names (list_sessions). */
|
|
140
|
+
directory() {
|
|
141
|
+
return {
|
|
142
|
+
sessions: this.#store.activeSessions(),
|
|
143
|
+
groups: new Map(this.#store.listGroups().map((group) => [group.id, group.name])),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
sessionName(id) {
|
|
147
|
+
return this.#nameOf(id);
|
|
148
|
+
}
|
|
149
|
+
// --- chains of hand-offs ---
|
|
150
|
+
/** Letters reached the session; letters it now sends continue the longest chain among them. */
|
|
151
|
+
enterChain(sessionId, letters) {
|
|
152
|
+
let longest = this.#chains.get(sessionId) ?? [];
|
|
153
|
+
for (const letter of letters)
|
|
154
|
+
if (letter.path.length > longest.length)
|
|
155
|
+
longest = letter.path;
|
|
156
|
+
this.#chains.set(sessionId, longest);
|
|
157
|
+
}
|
|
158
|
+
/** The person wrote or decided, or the turn ended: what the session sends next starts a new chain. */
|
|
159
|
+
resetChain(sessionId) {
|
|
160
|
+
this.#chains.delete(sessionId);
|
|
161
|
+
}
|
|
162
|
+
// --- letters ---
|
|
163
|
+
send(sender, out) {
|
|
164
|
+
const summary = oneLine(limited(out.summary, "summary", SUMMARY_MAX * 4, true));
|
|
165
|
+
if ([...summary].length > SUMMARY_MAX) {
|
|
166
|
+
throw invalid(`The summary can be at most ${SUMMARY_MAX} characters.`, "summary");
|
|
167
|
+
}
|
|
168
|
+
const body = limited(out.body, "body", BODY_MAX, false);
|
|
169
|
+
const to = this.#find(out.to);
|
|
170
|
+
if (!to)
|
|
171
|
+
throw invalid(`There is no session "${out.to}".`, "to");
|
|
172
|
+
const from = sender.kind === "session" ? sender.session.id : null;
|
|
173
|
+
if (from === to.id)
|
|
174
|
+
throw invalid("A session cannot send a letter to itself.", "to");
|
|
175
|
+
if (to.archivedAt !== null) {
|
|
176
|
+
throw conflict(`${to.name} is archived and cannot receive letters.`, undefined, "session-archived");
|
|
177
|
+
}
|
|
178
|
+
if (out.kind === "decision")
|
|
179
|
+
this.#checkRelay(sender, out.decision);
|
|
180
|
+
let threadId = null;
|
|
181
|
+
let repliedTo = null;
|
|
182
|
+
// A report to a session whose request is open with the sender answers it: Yew links them, so the
|
|
183
|
+
// session need not carry letter ids (blueprint principle 8).
|
|
184
|
+
const answering = !out.replyTo && out.kind === "report" && from !== null
|
|
185
|
+
? this.mail
|
|
186
|
+
.openRequests(from)
|
|
187
|
+
.filter((request) => request.fromSession === to.id)
|
|
188
|
+
.at(-1)
|
|
189
|
+
: undefined;
|
|
190
|
+
if (answering) {
|
|
191
|
+
repliedTo = answering;
|
|
192
|
+
threadId = answering.threadId;
|
|
193
|
+
}
|
|
194
|
+
if (out.replyTo) {
|
|
195
|
+
try {
|
|
196
|
+
repliedTo = this.mail.getLetter(out.replyTo);
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
throw invalid(`There is no letter ${out.replyTo}.`, "replyTo");
|
|
200
|
+
}
|
|
201
|
+
if (from !== null && repliedTo.toSession !== from && repliedTo.fromSession !== from) {
|
|
202
|
+
throw invalid("You can only reply to a letter you sent or received.", "replyTo");
|
|
203
|
+
}
|
|
204
|
+
threadId = repliedTo.threadId;
|
|
205
|
+
}
|
|
206
|
+
const path = from ? [...(this.#chains.get(from) ?? []), from] : [];
|
|
207
|
+
const base = {
|
|
208
|
+
threadId,
|
|
209
|
+
replyTo: repliedTo?.id ?? null,
|
|
210
|
+
fromKind: sender.kind === "schedule" ? "yew" : sender.kind,
|
|
211
|
+
fromSession: from,
|
|
212
|
+
fromName: sender.kind === "session"
|
|
213
|
+
? sender.session.name
|
|
214
|
+
: sender.kind === "schedule"
|
|
215
|
+
? sender.schedule.name
|
|
216
|
+
: sender.kind === "cli"
|
|
217
|
+
? "yew send"
|
|
218
|
+
: "person",
|
|
219
|
+
toSession: to.id,
|
|
220
|
+
kind: out.kind,
|
|
221
|
+
summary,
|
|
222
|
+
body,
|
|
223
|
+
path,
|
|
224
|
+
auto: out.auto ?? false,
|
|
225
|
+
decision: out.decision ?? null,
|
|
226
|
+
scheduleId: sender.kind === "schedule" ? sender.schedule.id : (out.schedule ?? null),
|
|
227
|
+
};
|
|
228
|
+
// Yew's automatic letters answer one request each, so they skip the limits (and cannot loop).
|
|
229
|
+
if (sender.kind === "session" && !out.auto) {
|
|
230
|
+
const current = this.#store.getSession(sender.session.id);
|
|
231
|
+
const stop = this.#limits(current, to, path, summary, body, repliedTo?.id ?? null);
|
|
232
|
+
if (stop) {
|
|
233
|
+
return this.mail.addLetter({ ...base, status: stop.status, statusReason: stop.reason });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
// The first answer to a request the recipient is still waiting on closes that request.
|
|
237
|
+
const answers = sender.kind === "session" &&
|
|
238
|
+
!out.auto &&
|
|
239
|
+
answersOpenRequest(sender.session, to, repliedTo, out.kind);
|
|
240
|
+
const policy = this.#policy(sender, to, out.auto ?? false, answers);
|
|
241
|
+
const letter = this.#store.tx(() => {
|
|
242
|
+
const letter = this.mail.addLetter({
|
|
243
|
+
...base,
|
|
244
|
+
status: policy.status,
|
|
245
|
+
statusReason: policy.reason ?? null,
|
|
246
|
+
});
|
|
247
|
+
if (sender.kind === "session" && !out.auto && policy.status !== "refused") {
|
|
248
|
+
this.#store.countLetterSent(sender.session.id);
|
|
249
|
+
}
|
|
250
|
+
if (answers && repliedTo)
|
|
251
|
+
this.mail.closeRequest(repliedTo.id);
|
|
252
|
+
return letter;
|
|
253
|
+
});
|
|
254
|
+
if (sender.kind === "session" && !out.auto && policy.status !== "refused") {
|
|
255
|
+
this.#recordSend(sender.session.id, to.id);
|
|
256
|
+
}
|
|
257
|
+
if (letter.status === "queued")
|
|
258
|
+
this.#hooks.queued(letter);
|
|
259
|
+
return this.mail.getLetter(letter.id);
|
|
260
|
+
}
|
|
261
|
+
/** The person lets a held letter through. */
|
|
262
|
+
release(letterId) {
|
|
263
|
+
const letter = this.mail.getLetter(letterId);
|
|
264
|
+
if (letter.status !== "held") {
|
|
265
|
+
throw conflict("This letter is not waiting for you.", undefined, "already-answered");
|
|
266
|
+
}
|
|
267
|
+
const to = this.#store.getSession(letter.toSession);
|
|
268
|
+
if (to.archivedAt !== null) {
|
|
269
|
+
throw conflict(`${to.name} is archived and cannot receive letters. Restore it first.`, undefined, "session-archived");
|
|
270
|
+
}
|
|
271
|
+
const released = this.mail.setLetterStatus(letterId, "queued", { reason: null });
|
|
272
|
+
this.#hooks.queued(released);
|
|
273
|
+
return this.mail.getLetter(letterId);
|
|
274
|
+
}
|
|
275
|
+
/** The person turns a held letter away. */
|
|
276
|
+
refuse(letterId) {
|
|
277
|
+
const letter = this.mail.getLetter(letterId);
|
|
278
|
+
if (letter.status !== "held") {
|
|
279
|
+
throw conflict("This letter is not waiting for you.", undefined, "already-answered");
|
|
280
|
+
}
|
|
281
|
+
return this.mail.setLetterStatus(letterId, "refused", { reason: "person-refused" });
|
|
282
|
+
}
|
|
283
|
+
/** Only a decision the person made can be relayed as a decision letter. */
|
|
284
|
+
#checkRelay(sender, number) {
|
|
285
|
+
if (sender.kind === "person")
|
|
286
|
+
return;
|
|
287
|
+
if (typeof number !== "number") {
|
|
288
|
+
throw invalid("A decision letter must name the decision's number.", "decision");
|
|
289
|
+
}
|
|
290
|
+
let card;
|
|
291
|
+
try {
|
|
292
|
+
card = this.mail.cardByNumber(number);
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
throw invalid(`There is no decision #${number}.`, "decision");
|
|
296
|
+
}
|
|
297
|
+
if (card.status !== "decided") {
|
|
298
|
+
throw invalid(`#${number} has not been decided by the person.`, "decision");
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Why a letter from `from` to a session that does not exist yet would not go out, or null.
|
|
303
|
+
* open_session asks before it opens one, so a refused brief leaves no session behind.
|
|
304
|
+
*/
|
|
305
|
+
blockedNew(from) {
|
|
306
|
+
const current = this.#store.getSession(from.id);
|
|
307
|
+
if (current.lettersSent >= this.letterQuota(current))
|
|
308
|
+
return "quota";
|
|
309
|
+
if (this.#recent(from.id).length >= TOTAL_RATE)
|
|
310
|
+
return "burst";
|
|
311
|
+
if ((this.#chains.get(from.id) ?? []).length + 1 > MAX_HOPS)
|
|
312
|
+
return "hops";
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
/** The anti-runaway rules (blueprint 7.1 and 7.2), in the order a person would want to hear them. */
|
|
316
|
+
#limits(from, to, path, summary, body, replyTo) {
|
|
317
|
+
if (from.lettersSent >= this.letterQuota(from))
|
|
318
|
+
return { status: "refused", reason: "quota" };
|
|
319
|
+
const between = this.mail.recentBetween(from.id, to.id, Date.now() - DUPLICATE_WINDOW);
|
|
320
|
+
// The same words answering a different letter are not a duplicate.
|
|
321
|
+
const same = (letter) => letter.summary === summary && letter.body === body && letter.replyTo === replyTo;
|
|
322
|
+
if (between.some(same))
|
|
323
|
+
return { status: "dropped", reason: "duplicate" };
|
|
324
|
+
const recent = this.#recent(from.id);
|
|
325
|
+
if (recent.filter((sent) => sent.to === to.id).length >= PAIR_RATE) {
|
|
326
|
+
return { status: "refused", reason: "rate" };
|
|
327
|
+
}
|
|
328
|
+
if (recent.length >= TOTAL_RATE)
|
|
329
|
+
return { status: "refused", reason: "burst" };
|
|
330
|
+
if (path.length > MAX_HOPS)
|
|
331
|
+
return { status: "refused", reason: "hops" };
|
|
332
|
+
if (path.filter((id) => id === to.id).length >= MAX_VISITS) {
|
|
333
|
+
return { status: "refused", reason: "loop" };
|
|
334
|
+
}
|
|
335
|
+
if (between.length >= PAIR_LIMIT)
|
|
336
|
+
return { status: "dropped", reason: "pair-limit" };
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
/** The session's letters in the last minute, and to whom. */
|
|
340
|
+
#recent(sessionId) {
|
|
341
|
+
const since = Date.now() - MINUTE;
|
|
342
|
+
return (this.#sent.get(sessionId) ?? []).filter((sent) => sent.time > since);
|
|
343
|
+
}
|
|
344
|
+
#recordSend(sessionId, to) {
|
|
345
|
+
const recent = this.#recent(sessionId);
|
|
346
|
+
recent.push({ to, time: Date.now() });
|
|
347
|
+
this.#sent.set(sessionId, recent);
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* The recipient's receive policy, and the hold for letters from sessions with fewer permissions. Both
|
|
351
|
+
* are for letters the recipient did not ask for: Yew's automatic letters and the first answer to a
|
|
352
|
+
* request it is still waiting on go straight through.
|
|
353
|
+
*/
|
|
354
|
+
#policy(sender, to, auto, answers) {
|
|
355
|
+
// The person's decisions and the tasks they scheduled are theirs: no policy holds them back.
|
|
356
|
+
if (sender.kind === "person" || sender.kind === "schedule")
|
|
357
|
+
return { status: "queued" };
|
|
358
|
+
if (sender.kind === "session" && (auto || answers))
|
|
359
|
+
return { status: "queued" };
|
|
360
|
+
const policy = to.options.receive ?? "accept";
|
|
361
|
+
if (policy === "refuse")
|
|
362
|
+
return { status: "refused", reason: "refuse-policy" };
|
|
363
|
+
if (policy === "hold")
|
|
364
|
+
return { status: "held", reason: "hold-policy" };
|
|
365
|
+
if (sender.kind !== "session")
|
|
366
|
+
return { status: "queued" };
|
|
367
|
+
const from = sender.session;
|
|
368
|
+
const exempt = from.id === this.mainSessionId() || from.parentId === to.id || to.parentId === from.id;
|
|
369
|
+
if (!exempt && rank(from) < rank(to))
|
|
370
|
+
return { status: "held", reason: "lower-rank" };
|
|
371
|
+
return { status: "queued" };
|
|
372
|
+
}
|
|
373
|
+
// --- the approval center ---
|
|
374
|
+
/** Everything waiting for the person: approvals and questions, decision cards and held letters. */
|
|
375
|
+
center() {
|
|
376
|
+
return {
|
|
377
|
+
approvals: this.#store.allPendingApprovals(),
|
|
378
|
+
cards: this.mail.pendingCards(),
|
|
379
|
+
held: this.mail.heldLetters(),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
postCard(session, input) {
|
|
383
|
+
this.#requireMaintainer(session);
|
|
384
|
+
const fields = this.#cardFields(input, null);
|
|
385
|
+
const requestedBy = input.requestedBy
|
|
386
|
+
? this.#sessionId(input.requestedBy)
|
|
387
|
+
: (this.#asker(session) ?? session.id);
|
|
388
|
+
return this.#store.tx(() => {
|
|
389
|
+
const card = this.mail.addCard(session.id, requestedBy, fields);
|
|
390
|
+
for (const number of input.replaces ?? []) {
|
|
391
|
+
const old = this.#card(number);
|
|
392
|
+
if (old.status === "pending")
|
|
393
|
+
this.mail.withdrawCard(old.id, `Merged into #${card.number}.`);
|
|
394
|
+
}
|
|
395
|
+
return this.mail.getCard(card.id);
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
updateCard(session, number, input) {
|
|
399
|
+
this.#requireMaintainer(session);
|
|
400
|
+
const card = this.#pending(number);
|
|
401
|
+
return this.mail.updateCardFields(card.id, this.#cardFields(input, card));
|
|
402
|
+
}
|
|
403
|
+
withdrawCard(session, number, reason) {
|
|
404
|
+
this.#requireMaintainer(session);
|
|
405
|
+
const card = this.#pending(number);
|
|
406
|
+
return this.mail.withdrawCard(card.id, limited(reason, "reason", 500, true));
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* The person decides. The decision is recorded as theirs, goes to the session whose request it was and
|
|
410
|
+
* to the session that put up the card, and is added to the decision log file if one is set.
|
|
411
|
+
*/
|
|
412
|
+
decide(cardId, choice, note) {
|
|
413
|
+
const card = this.mail.getCard(cardId);
|
|
414
|
+
if (card.status !== "pending") {
|
|
415
|
+
throw conflict("This card was already decided or withdrawn.", undefined, "already-answered");
|
|
416
|
+
}
|
|
417
|
+
if (choice !== null &&
|
|
418
|
+
(!Number.isInteger(choice) || choice < 0 || choice >= card.options.length)) {
|
|
419
|
+
throw invalid("Choose one of the card's options.", "choice");
|
|
420
|
+
}
|
|
421
|
+
const text = note?.trim() ? limited(note, "note", 4000, false) : null;
|
|
422
|
+
if (choice === null && !text)
|
|
423
|
+
throw invalid("Choose an option or write a note.", "note");
|
|
424
|
+
const decided = this.mail.decideCard(card.id, choice, text);
|
|
425
|
+
const chosen = choice === null ? null : (card.options[choice]?.label ?? null);
|
|
426
|
+
const body = [
|
|
427
|
+
`The person decided #${card.number}: ${card.title}`,
|
|
428
|
+
chosen ? `Chosen: ${chosen}` : "No option chosen; see the note.",
|
|
429
|
+
text ? `Note: ${text}` : null,
|
|
430
|
+
]
|
|
431
|
+
.filter(Boolean)
|
|
432
|
+
.join("\n");
|
|
433
|
+
const recipients = [...new Set([card.requestedBy, card.createdBy])].filter((id) => id !== null);
|
|
434
|
+
for (const id of recipients) {
|
|
435
|
+
try {
|
|
436
|
+
const session = this.#store.getSession(id);
|
|
437
|
+
if (session.archivedAt !== null)
|
|
438
|
+
continue;
|
|
439
|
+
this.#store.resetLettersSent(id);
|
|
440
|
+
this.resetChain(id);
|
|
441
|
+
this.send({ kind: "person" }, {
|
|
442
|
+
to: id,
|
|
443
|
+
kind: "decision",
|
|
444
|
+
summary: `#${card.number} ${oneLine(card.title)}`.slice(0, SUMMARY_MAX),
|
|
445
|
+
body,
|
|
446
|
+
decision: card.number,
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
if (!(error instanceof YewError))
|
|
451
|
+
throw error;
|
|
452
|
+
this.#log(`decision #${card.number}: could not reach ${id}: ${error.message}`);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
this.#appendLog(decided);
|
|
456
|
+
return decided;
|
|
457
|
+
}
|
|
458
|
+
#appendLog(card) {
|
|
459
|
+
const path = this.#store.getSetting("decisionLog", null);
|
|
460
|
+
if (!path)
|
|
461
|
+
return;
|
|
462
|
+
const english = this.#store.getSetting("language", "system") === "en";
|
|
463
|
+
const requester = card.requestedBy ? this.#nameOf(card.requestedBy) : null;
|
|
464
|
+
const chosen = card.choice === null ? null : (card.options[card.choice]?.label ?? null);
|
|
465
|
+
const time = new Date(card.decidedAt ?? Date.now());
|
|
466
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
467
|
+
const stamp = `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())} ${pad(time.getHours())}:${pad(time.getMinutes())}`;
|
|
468
|
+
const parts = english
|
|
469
|
+
? [
|
|
470
|
+
stamp,
|
|
471
|
+
`#${card.number}`,
|
|
472
|
+
oneLine(card.title),
|
|
473
|
+
`Chosen: ${chosen ?? "(note only)"}`,
|
|
474
|
+
...(card.note ? [`Note: ${oneLine(card.note)}`] : []),
|
|
475
|
+
...(requester ? [`Requested by: ${requester}`] : []),
|
|
476
|
+
"Decided by the person in Yew",
|
|
477
|
+
]
|
|
478
|
+
: [
|
|
479
|
+
stamp,
|
|
480
|
+
`#${card.number}`,
|
|
481
|
+
oneLine(card.title),
|
|
482
|
+
`选择:${chosen ?? "(只写了备注)"}`,
|
|
483
|
+
...(card.note ? [`备注:${oneLine(card.note)}`] : []),
|
|
484
|
+
...(requester ? [`提出:${requester}`] : []),
|
|
485
|
+
"本人在 Yew 里决定",
|
|
486
|
+
];
|
|
487
|
+
try {
|
|
488
|
+
const header = existsSync(path) ? "" : english ? "# Approval log\n\n" : "# 审批记录\n\n";
|
|
489
|
+
appendFileSync(path, `${header}- ${parts.join(" · ")}\n`, { mode: 0o600 });
|
|
490
|
+
}
|
|
491
|
+
catch (error) {
|
|
492
|
+
this.#log(`decision log ${path}: ${error.message}`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
#nameOf(sessionId) {
|
|
496
|
+
try {
|
|
497
|
+
return this.#store.getSession(sessionId).name;
|
|
498
|
+
}
|
|
499
|
+
catch {
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
#requireMaintainer(session) {
|
|
504
|
+
if (!this.canPostCards(session)) {
|
|
505
|
+
throw conflict("Only the main conversation, or a session the person allowed, can put cards in the approval center.", undefined, "not-allowed");
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
#card(number) {
|
|
509
|
+
try {
|
|
510
|
+
return this.mail.cardByNumber(number);
|
|
511
|
+
}
|
|
512
|
+
catch {
|
|
513
|
+
throw invalid(`There is no card #${number}.`, "number");
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
#pending(number) {
|
|
517
|
+
const card = this.#card(number);
|
|
518
|
+
if (card.status !== "pending") {
|
|
519
|
+
throw conflict(`#${number} was already decided or withdrawn.`, undefined, "already-answered");
|
|
520
|
+
}
|
|
521
|
+
return card;
|
|
522
|
+
}
|
|
523
|
+
#sessionId(id) {
|
|
524
|
+
if (typeof id !== "string")
|
|
525
|
+
throw invalid("A session must be named by name or id.", "sessions");
|
|
526
|
+
const found = this.#find(id);
|
|
527
|
+
if (!found)
|
|
528
|
+
throw invalid(`There is no session "${id}".`, "sessions");
|
|
529
|
+
return found.id;
|
|
530
|
+
}
|
|
531
|
+
/** A session by id or by its name (names are unique). */
|
|
532
|
+
#find(ref) {
|
|
533
|
+
try {
|
|
534
|
+
return this.#store.getSession(ref);
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
return this.#store.findSessionByName(ref);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* The session whose open request a card most likely answers: the only other session with a request
|
|
542
|
+
* open with the poster. With none or several, the card is the poster's own question.
|
|
543
|
+
*/
|
|
544
|
+
#asker(session) {
|
|
545
|
+
const askers = new Set(this.mail
|
|
546
|
+
.openRequests(session.id)
|
|
547
|
+
.map((request) => request.fromSession)
|
|
548
|
+
.filter((id) => id !== null && id !== session.id));
|
|
549
|
+
return askers.size === 1 ? [...askers][0] : null;
|
|
550
|
+
}
|
|
551
|
+
/** Checks a card's six points; on update, missing fields keep the card's current values. */
|
|
552
|
+
#cardFields(input, current) {
|
|
553
|
+
const options = input.options === undefined
|
|
554
|
+
? (current?.options ?? [])
|
|
555
|
+
: (() => {
|
|
556
|
+
if (!Array.isArray(input.options) || input.options.length > OPTIONS_MAX) {
|
|
557
|
+
throw invalid(`Give at most ${OPTIONS_MAX} options.`, "options");
|
|
558
|
+
}
|
|
559
|
+
return input.options.map((option, index) => {
|
|
560
|
+
const label = limited(option?.label, `options[${index}].label`, 200, true);
|
|
561
|
+
const detail = limited(option?.detail, `options[${index}].detail`, 1000, false);
|
|
562
|
+
return detail ? { label, detail } : { label };
|
|
563
|
+
});
|
|
564
|
+
})();
|
|
565
|
+
const recommended = input.recommended === undefined ? (current?.recommended ?? null) : input.recommended;
|
|
566
|
+
if (recommended !== null &&
|
|
567
|
+
(!Number.isInteger(recommended) || recommended < 0 || recommended >= options.length)) {
|
|
568
|
+
throw invalid("recommended must be the index of one of the options.", "recommended");
|
|
569
|
+
}
|
|
570
|
+
const sessions = input.sessions === undefined
|
|
571
|
+
? (current?.sessions ?? [])
|
|
572
|
+
: [...new Set(input.sessions.map((id) => this.#sessionId(id)))];
|
|
573
|
+
const deadline = input.deadline === undefined
|
|
574
|
+
? (current?.deadline ?? null)
|
|
575
|
+
: limited(input.deadline, "deadline", 100, false) || null;
|
|
576
|
+
if (input.undoable !== undefined && typeof input.undoable !== "boolean") {
|
|
577
|
+
throw invalid("undoable must be true or false.", "undoable");
|
|
578
|
+
}
|
|
579
|
+
const undoable = input.undoable ?? current?.undoable ?? null;
|
|
580
|
+
if (undoable === null) {
|
|
581
|
+
throw invalid("Say whether the decision can be undone (undoable).", "undoable");
|
|
582
|
+
}
|
|
583
|
+
return {
|
|
584
|
+
title: input.title === undefined && current
|
|
585
|
+
? current.title
|
|
586
|
+
: limited(input.title, "title", 300, true),
|
|
587
|
+
context: input.context === undefined
|
|
588
|
+
? (current?.context ?? "")
|
|
589
|
+
: limited(input.context, "context", 10_000, false),
|
|
590
|
+
options,
|
|
591
|
+
recommended,
|
|
592
|
+
deadline,
|
|
593
|
+
sessions,
|
|
594
|
+
undoable,
|
|
595
|
+
reversible: input.reversible === undefined
|
|
596
|
+
? (current?.reversible ?? "")
|
|
597
|
+
: limited(input.reversible, "reversible", 500, false),
|
|
598
|
+
after: input.after === undefined
|
|
599
|
+
? (current?.after ?? "")
|
|
600
|
+
: limited(input.after, "after", 2000, false),
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
}
|