@ouro.bot/cli 0.1.0-alpha.1517 → 0.1.0-alpha.1518
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.json +6 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/actions/generated/mailbox/actions.json +558 -7
- package/dist/actions/generated/mailbox/commands.json +168 -2
- package/dist/actions/generated/mailbox/mcp.json +413 -5
- package/dist/actions/generated/mailbox-tools/tools.json +487 -6
- package/dist/heart/daemon/cli-exec.js +19 -3
- package/dist/heart/daemon/cli-parse.js +21 -9
- package/dist/heart/daemon/daemon.js +9 -0
- package/dist/heart/letters/doors-tools.js +33 -1
- package/dist/heart/letters/doors.js +229 -19
- package/dist/heart/letters/letter-index.js +89 -0
- package/dist/heart/letters/letter.js +247 -0
- package/dist/heart/letters/store.js +210 -0
- package/dist/heart/letters/writer.js +298 -0
- package/dist/heart/mcp/mcp-server.js +37 -8
- package/dist/repertoire/in-turn-tools-door.js +1 -0
- package/dist/repertoire/tools.js +9 -3
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_OPTIONS = exports.LETTER_LIMITS = exports.LETTER_KINDS = void 0;
|
|
4
|
+
exports.fold = fold;
|
|
5
|
+
exports.storedText = storedText;
|
|
6
|
+
exports.hasLetterCode = hasLetterCode;
|
|
7
|
+
exports.checkLetterInput = checkLetterInput;
|
|
8
|
+
exports.checkWithdrawReason = checkWithdrawReason;
|
|
9
|
+
exports.letterState = letterState;
|
|
10
|
+
exports.newLetterId = newLetterId;
|
|
11
|
+
// A letter: a request from an agent to its person that only that person can answer (design §3.1). This module holds
|
|
12
|
+
// the types, the checks a sender's letter must pass and the folding those checks use. It reads and writes nothing.
|
|
13
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
14
|
+
exports.LETTER_KINDS = ["decide", "do", "accept", "know"];
|
|
15
|
+
const URGENCIES = ["now", "today", "whenever"];
|
|
16
|
+
exports.LETTER_LIMITS = {
|
|
17
|
+
subject: 80,
|
|
18
|
+
whyOnlyYou: 200,
|
|
19
|
+
body: 4000,
|
|
20
|
+
label: 40,
|
|
21
|
+
effect: 160,
|
|
22
|
+
linkLabel: 80,
|
|
23
|
+
url: 500,
|
|
24
|
+
dedupeKey: 120,
|
|
25
|
+
lane: 120,
|
|
26
|
+
reason: 200,
|
|
27
|
+
};
|
|
28
|
+
/** Every letter has options, so "answered" means the same for every kind (review B3). Only decide letters bring their own. */
|
|
29
|
+
exports.DEFAULT_OPTIONS = {
|
|
30
|
+
do: [{ id: "1", label: "done", effect: "It is done." }, { id: "2", label: "can't", effect: "It can't be done; the sender is told." }],
|
|
31
|
+
accept: [{ id: "1", label: "accept", effect: "The work is accepted." }, { id: "2", label: "send back", effect: "The work goes back to the sender." }],
|
|
32
|
+
know: [{ id: "1", label: "got it", effect: "The sender knows you have read it." }],
|
|
33
|
+
};
|
|
34
|
+
/** Fields Ouro sets from who calls, never the caller (R4-M4). */
|
|
35
|
+
const SET_BY_OURO = new Set(["to", "from", "session", "id", "code", "createdAt", "answeringHandle", "v"]);
|
|
36
|
+
const SENDER_FIELDS = new Set(["kind", "subject", "whyOnlyYou", "body", "options", "links", "dedupeKey", "urgency", "holdUntil", "expiresAt", "lane"]);
|
|
37
|
+
/**
|
|
38
|
+
* Letters from other scripts that look like Latin ones. Only letters are folded, never digits, so a code written with
|
|
39
|
+
* look-alikes still reads as a code while text in another script's digits stays as it is.
|
|
40
|
+
*/
|
|
41
|
+
const LOOK_ALIKES = {
|
|
42
|
+
"а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "у": "y", "х": "x", "і": "i",
|
|
43
|
+
"ј": "j", "ӏ": "l", "Ӏ": "l", "ѕ": "s", "ԁ": "d", "ԛ": "q", "ԝ": "w",
|
|
44
|
+
"А": "A", "В": "B", "Е": "E", "К": "K", "М": "M", "Н": "H", "О": "O", "Р": "P",
|
|
45
|
+
"С": "C", "Т": "T", "Х": "X", "Ѕ": "S", "І": "I", "Ј": "J",
|
|
46
|
+
"Α": "A", "Β": "B", "Ε": "E", "Ζ": "Z", "Η": "H", "Ι": "I", "Κ": "K", "Μ": "M",
|
|
47
|
+
"Ν": "N", "Ο": "O", "Ρ": "P", "Τ": "T", "Υ": "Y", "Χ": "X", "ο": "o", "ι": "i",
|
|
48
|
+
"ν": "v", "ρ": "p", "ı": "i", "ʟ": "L",
|
|
49
|
+
};
|
|
50
|
+
const HIDDEN = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
|
|
51
|
+
const HIDDEN_RUNS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu;
|
|
52
|
+
/** The copy sender text is checked on: NFKC, then look-alike letters folded, then hidden characters removed. */
|
|
53
|
+
function fold(text) {
|
|
54
|
+
return [...text.normalize("NFKC")].map((char) => LOOK_ALIKES[char] ?? char).join("").replace(HIDDEN, "");
|
|
55
|
+
}
|
|
56
|
+
/** Text as it is stored: each run of control, format and line or paragraph separators becomes one space. */
|
|
57
|
+
function storedText(text) {
|
|
58
|
+
return text.replace(HIDDEN_RUNS, " ");
|
|
59
|
+
}
|
|
60
|
+
// An L that doesn't follow a letter or digit, up to three characters that are neither, then a digit: L8, L 8, L-8, L·8.
|
|
61
|
+
const CODE_TOKEN = /(?<![\p{L}\p{N}])[Ll][^\p{L}\p{N}]{0,3}\p{Nd}/u;
|
|
62
|
+
const LETTER_NUMBER = /(?<![\p{L}\p{N}])letter[^\p{L}\p{N}]{0,3}\p{Nd}/iu;
|
|
63
|
+
const OPTIONS_LINE = /options\s*\(\s*from\s+ouro\s*\)\s*:/iu;
|
|
64
|
+
/** Whether text could pass for a letter code or Ouro's own answer block once folded (design §3.4, R8-M1). */
|
|
65
|
+
function hasLetterCode(text) {
|
|
66
|
+
const folded = fold(text);
|
|
67
|
+
return CODE_TOKEN.test(folded) || LETTER_NUMBER.test(folded) || OPTIONS_LINE.test(folded);
|
|
68
|
+
}
|
|
69
|
+
class Refusal extends Error {
|
|
70
|
+
}
|
|
71
|
+
function refuse(problem) {
|
|
72
|
+
throw new Refusal(problem);
|
|
73
|
+
}
|
|
74
|
+
function isObject(value) {
|
|
75
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
76
|
+
}
|
|
77
|
+
/** Sender text: required or not, at most `limit` characters (counted as the schemas count them, by code point). */
|
|
78
|
+
function plain(name, value, limit, required) {
|
|
79
|
+
if (value === undefined || (typeof value === "string" && value.trim() === "")) {
|
|
80
|
+
if (required)
|
|
81
|
+
refuse(`${name} is required.`);
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
if (typeof value !== "string")
|
|
85
|
+
refuse(`${name} must be text.`);
|
|
86
|
+
if ([...value].length > limit)
|
|
87
|
+
refuse(`${name} is longer than ${limit} characters.`);
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
/** Sender text the person reads: plain, with no letter code or answer form, and hidden characters collapsed. */
|
|
91
|
+
function text(name, input, limit, required) {
|
|
92
|
+
const value = plain(name, input, limit, required);
|
|
93
|
+
if (value === undefined)
|
|
94
|
+
return undefined;
|
|
95
|
+
if (hasLetterCode(value))
|
|
96
|
+
refuse(`${name} contains a letter code or Ouro's answer form, which only Ouro writes. Fix: say it without a code such as L8.`);
|
|
97
|
+
return storedText(value);
|
|
98
|
+
}
|
|
99
|
+
function options(kind, value) {
|
|
100
|
+
if (kind !== "decide") {
|
|
101
|
+
if (value !== undefined)
|
|
102
|
+
refuse("only a decide letter takes options; the others have Ouro's own.");
|
|
103
|
+
return exports.DEFAULT_OPTIONS[kind].map((option) => ({ ...option }));
|
|
104
|
+
}
|
|
105
|
+
if (!Array.isArray(value) || value.length < 2 || value.length > 5)
|
|
106
|
+
refuse("a decide letter needs 2 to 5 options.");
|
|
107
|
+
const seen = new Set();
|
|
108
|
+
return value.map((entry, index) => {
|
|
109
|
+
const at = `option ${index + 1}`;
|
|
110
|
+
if (!isObject(entry))
|
|
111
|
+
refuse(`${at} must be { label, effect }.`);
|
|
112
|
+
const label = text(`${at}'s label`, entry.label, exports.LETTER_LIMITS.label, true);
|
|
113
|
+
const folded = fold(label).trim();
|
|
114
|
+
if (/^\p{Nd}+$/u.test(folded))
|
|
115
|
+
refuse(`${at}'s label is only digits, which would read as an answer. Fix: name the choice in words.`);
|
|
116
|
+
if (/[\p{Pd}\u2212]/u.test(folded))
|
|
117
|
+
refuse(`${at}'s label contains a dash, which Ouro uses between a label and its effect. Fix: drop the dash.`);
|
|
118
|
+
const key = folded.toLowerCase();
|
|
119
|
+
if (seen.has(key))
|
|
120
|
+
refuse(`${at}'s label repeats another label. Fix: give each option its own label.`);
|
|
121
|
+
seen.add(key);
|
|
122
|
+
const effect = text(`${at}'s effect`, entry.effect, exports.LETTER_LIMITS.effect, true);
|
|
123
|
+
return { id: String(index + 1), label, effect };
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
function links(value) {
|
|
127
|
+
if (value === undefined)
|
|
128
|
+
return [];
|
|
129
|
+
if (!Array.isArray(value))
|
|
130
|
+
refuse("links must be a list of { label, url }.");
|
|
131
|
+
return value.map((entry, index) => {
|
|
132
|
+
const at = `link ${index + 1}`;
|
|
133
|
+
if (!isObject(entry))
|
|
134
|
+
refuse(`${at} must be { label, url }.`);
|
|
135
|
+
const label = text(`${at}'s label`, entry.label, exports.LETTER_LIMITS.linkLabel, true);
|
|
136
|
+
const url = text(`${at}'s url`, entry.url, exports.LETTER_LIMITS.url, true);
|
|
137
|
+
if (!/^https?:\/\//.test(url))
|
|
138
|
+
refuse(`${at}'s url must start with https:// or http://.`);
|
|
139
|
+
return { label, url };
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
function isoTime(value) {
|
|
143
|
+
return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/.test(value) && !Number.isNaN(Date.parse(value));
|
|
144
|
+
}
|
|
145
|
+
function draft(input) {
|
|
146
|
+
if (!isObject(input))
|
|
147
|
+
refuse("a letter must be an object.");
|
|
148
|
+
for (const key of Object.keys(input)) {
|
|
149
|
+
if (SET_BY_OURO.has(key))
|
|
150
|
+
refuse(`${key} is set by Ouro from who calls, never by the caller. Fix: leave ${key} out.`);
|
|
151
|
+
if (!SENDER_FIELDS.has(key))
|
|
152
|
+
refuse(`${key} is not a letter field.`);
|
|
153
|
+
}
|
|
154
|
+
const kind = input.kind;
|
|
155
|
+
if (!exports.LETTER_KINDS.includes(kind))
|
|
156
|
+
refuse(`kind must be one of ${exports.LETTER_KINDS.join(", ")}.`);
|
|
157
|
+
const subject = text("subject", input.subject, exports.LETTER_LIMITS.subject, true);
|
|
158
|
+
const whyOnlyYou = text("whyOnlyYou", input.whyOnlyYou, exports.LETTER_LIMITS.whyOnlyYou, false);
|
|
159
|
+
if (!whyOnlyYou && kind !== "know")
|
|
160
|
+
refuse(`whyOnlyYou is required for a ${kind} letter. Fix: say in one line why only the person can answer.`);
|
|
161
|
+
const body = text("body", input.body, exports.LETTER_LIMITS.body, false) ?? "";
|
|
162
|
+
const letterOptions = options(kind, input.options);
|
|
163
|
+
const letterLinks = links(input.links);
|
|
164
|
+
const urgency = (input.urgency ?? "whenever");
|
|
165
|
+
if (!URGENCIES.includes(urgency))
|
|
166
|
+
refuse(`urgency must be one of ${URGENCIES.join(", ")}.`);
|
|
167
|
+
const holdUntil = input.holdUntil;
|
|
168
|
+
if (holdUntil !== undefined && (typeof holdUntil !== "string" || (holdUntil !== "interactive" && !isoTime(holdUntil))))
|
|
169
|
+
refuse('holdUntil must be "interactive" or an ISO time.');
|
|
170
|
+
const expiresAt = input.expiresAt;
|
|
171
|
+
if (expiresAt !== undefined && (typeof expiresAt !== "string" || !isoTime(expiresAt)))
|
|
172
|
+
refuse("expiresAt must be an ISO time.");
|
|
173
|
+
// The person never sees the dedupe key, so it may hold anything, a code such as L2 included.
|
|
174
|
+
const dedupeKey = input.dedupeKey === undefined ? undefined : plain("dedupeKey", input.dedupeKey, exports.LETTER_LIMITS.dedupeKey, true);
|
|
175
|
+
const lane = text("lane", input.lane, exports.LETTER_LIMITS.lane, false);
|
|
176
|
+
return {
|
|
177
|
+
kind,
|
|
178
|
+
subject,
|
|
179
|
+
...(whyOnlyYou ? { whyOnlyYou } : {}),
|
|
180
|
+
body,
|
|
181
|
+
options: letterOptions,
|
|
182
|
+
links: letterLinks,
|
|
183
|
+
...(dedupeKey ? { dedupeKey } : {}),
|
|
184
|
+
urgency,
|
|
185
|
+
...(holdUntil ? { holdUntil: holdUntil } : {}),
|
|
186
|
+
...(expiresAt ? { expiresAt: expiresAt } : {}),
|
|
187
|
+
...(lane ? { lane } : {}),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
/** Checks a sender's letter. A refusal names the field and, where it helps, the fix. */
|
|
191
|
+
function checkLetterInput(input) {
|
|
192
|
+
let result;
|
|
193
|
+
try {
|
|
194
|
+
result = { ok: true, letter: draft(input) };
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (!(error instanceof Refusal))
|
|
198
|
+
throw error;
|
|
199
|
+
result = { ok: false, problem: error.message };
|
|
200
|
+
}
|
|
201
|
+
(0, runtime_1.emitNervesEvent)({
|
|
202
|
+
component: "daemon",
|
|
203
|
+
event: "letters.letter_checked",
|
|
204
|
+
message: result.ok ? "letter accepted" : "letter refused",
|
|
205
|
+
meta: { ok: result.ok, ...(result.ok ? { kind: result.letter.kind } : {}) },
|
|
206
|
+
});
|
|
207
|
+
return result;
|
|
208
|
+
}
|
|
209
|
+
/** Checks a withdraw's reason, which the person reads like any sender text. */
|
|
210
|
+
function checkWithdrawReason(input) {
|
|
211
|
+
try {
|
|
212
|
+
return { ok: true, reason: text("reason", input, exports.LETTER_LIMITS.reason, true) };
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
// text() throws only a Refusal.
|
|
216
|
+
return { ok: false, problem: error.message };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/** A letter's state, derived from its events and never stored: the first closing event decides it. */
|
|
220
|
+
function letterState(events) {
|
|
221
|
+
for (const event of events) {
|
|
222
|
+
if (event.t === "answered")
|
|
223
|
+
return "answered";
|
|
224
|
+
if (event.t === "withdrawn")
|
|
225
|
+
return "withdrawn";
|
|
226
|
+
if (event.t === "expired")
|
|
227
|
+
return "expired";
|
|
228
|
+
}
|
|
229
|
+
return "waiting";
|
|
230
|
+
}
|
|
231
|
+
const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
232
|
+
/**
|
|
233
|
+
* A new letter id: `ltr_` and a ULID, 10 characters of milliseconds then 16 random ones, so ids sort by when they were
|
|
234
|
+
* filed. `random` returns a value in [0, 1); tests pass their own.
|
|
235
|
+
*/
|
|
236
|
+
function newLetterId(now, random = Math.random) {
|
|
237
|
+
let time = "";
|
|
238
|
+
let rest = now;
|
|
239
|
+
for (let i = 0; i < 10; i++) {
|
|
240
|
+
time = CROCKFORD[rest % 32] + time;
|
|
241
|
+
rest = Math.floor(rest / 32);
|
|
242
|
+
}
|
|
243
|
+
let tail = "";
|
|
244
|
+
for (let i = 0; i < 16; i++)
|
|
245
|
+
tail += CROCKFORD[Math.floor(random() * 32)];
|
|
246
|
+
return `ltr_${time}${tail}`;
|
|
247
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.LetterStore = void 0;
|
|
37
|
+
// The letters on disk (design §3.2): one append-only JSONL file per letter in <bundle>/state/letters/, the letter on
|
|
38
|
+
// the first line and an event on each line after it. Only the daemon's writer (writer.ts) uses this, one call at a
|
|
39
|
+
// time, so nothing here locks. Every append is fsynced, and a torn last line from a crash is cut off before the next
|
|
40
|
+
// append so it never fuses with a new event.
|
|
41
|
+
const fs = __importStar(require("fs"));
|
|
42
|
+
const path = __importStar(require("path"));
|
|
43
|
+
const runtime_1 = require("../../nerves/runtime");
|
|
44
|
+
const LETTER_ID = /^ltr_[0-9A-Za-z]+$/;
|
|
45
|
+
const NEXT_CODE = "next-code";
|
|
46
|
+
class LetterStore {
|
|
47
|
+
dir;
|
|
48
|
+
io;
|
|
49
|
+
constructor(dir, io = fs) {
|
|
50
|
+
this.dir = dir;
|
|
51
|
+
this.io = io;
|
|
52
|
+
(0, runtime_1.emitNervesEvent)({ level: "debug", component: "daemon", event: "letters.store_opened", message: "letters store opened", meta: {} });
|
|
53
|
+
}
|
|
54
|
+
/** Writes a new letter's file, then syncs the file and the folder, so the letter survives a crash once this returns. */
|
|
55
|
+
create(letter) {
|
|
56
|
+
const file = this.openFile(letter.id);
|
|
57
|
+
this.io.mkdirSync(this.dir, { recursive: true });
|
|
58
|
+
const fd = this.io.openSync(file, "wx", 0o600);
|
|
59
|
+
try {
|
|
60
|
+
this.io.writeSync(fd, `${JSON.stringify(letter)}\n`);
|
|
61
|
+
this.io.fsyncSync(fd);
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
this.io.closeSync(fd);
|
|
65
|
+
}
|
|
66
|
+
this.syncDir(this.dir);
|
|
67
|
+
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.letter_created", message: "letter file created", meta: { kind: letter.kind } });
|
|
68
|
+
}
|
|
69
|
+
/** Appends one event to an open letter, after cutting any torn last line back to the last newline. */
|
|
70
|
+
append(id, event) {
|
|
71
|
+
const fd = this.io.openSync(this.openFile(id), "r+");
|
|
72
|
+
try {
|
|
73
|
+
const end = this.lastNewlineEnd(fd);
|
|
74
|
+
this.io.ftruncateSync(fd, end);
|
|
75
|
+
this.io.writeSync(fd, `${JSON.stringify(event)}\n`, end);
|
|
76
|
+
this.io.fsyncSync(fd);
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
this.io.closeSync(fd);
|
|
80
|
+
}
|
|
81
|
+
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.event_appended", message: "letter event appended", meta: { t: event.t } });
|
|
82
|
+
}
|
|
83
|
+
/** One letter, open or closed; null when there is none or its first line is torn. */
|
|
84
|
+
read(id) {
|
|
85
|
+
const open = this.openFile(id);
|
|
86
|
+
if (this.io.existsSync(open))
|
|
87
|
+
return this.parse(open, false);
|
|
88
|
+
const closed = this.closedFiles().find((file) => path.basename(file, ".jsonl") === id);
|
|
89
|
+
return closed ? this.parse(closed, true) : null;
|
|
90
|
+
}
|
|
91
|
+
/** Moves a closed letter into closed/YYYY-MM/ with a rename, then syncs both folders. */
|
|
92
|
+
roll(id, at) {
|
|
93
|
+
const month = at.toISOString().slice(0, 7);
|
|
94
|
+
const target = path.join(this.dir, "closed", month);
|
|
95
|
+
this.io.mkdirSync(target, { recursive: true });
|
|
96
|
+
this.io.renameSync(this.openFile(id), path.join(target, `${id}.jsonl`));
|
|
97
|
+
this.syncDir(target);
|
|
98
|
+
this.syncDir(this.dir);
|
|
99
|
+
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.letter_rolled", message: "closed letter rolled", meta: { month } });
|
|
100
|
+
}
|
|
101
|
+
/** Every readable letter, open and closed, for rebuilding the index when the daemon starts. */
|
|
102
|
+
loadAll() {
|
|
103
|
+
const loaded = [];
|
|
104
|
+
for (const file of this.letterFiles(this.dir)) {
|
|
105
|
+
const letter = this.parse(file, false);
|
|
106
|
+
if (letter)
|
|
107
|
+
loaded.push(letter);
|
|
108
|
+
}
|
|
109
|
+
for (const file of this.closedFiles()) {
|
|
110
|
+
const letter = this.parse(file, true);
|
|
111
|
+
if (letter)
|
|
112
|
+
loaded.push(letter);
|
|
113
|
+
}
|
|
114
|
+
(0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.store_loaded", message: "letters loaded from disk", meta: { letters: loaded.length } });
|
|
115
|
+
return loaded;
|
|
116
|
+
}
|
|
117
|
+
/** The next code number on record; 1 when none is, or the record can't be read. */
|
|
118
|
+
readNextCode() {
|
|
119
|
+
const file = path.join(this.dir, NEXT_CODE);
|
|
120
|
+
if (!this.io.existsSync(file))
|
|
121
|
+
return 1;
|
|
122
|
+
const value = Number(this.io.readFileSync(file, "utf8"));
|
|
123
|
+
return Number.isInteger(value) && value > 0 ? value : 1;
|
|
124
|
+
}
|
|
125
|
+
/** Records the next code number: a temporary file, synced, renamed over the record, then the folder synced. */
|
|
126
|
+
writeNextCode(next) {
|
|
127
|
+
this.io.mkdirSync(this.dir, { recursive: true });
|
|
128
|
+
const temp = path.join(this.dir, `${NEXT_CODE}.tmp`);
|
|
129
|
+
const fd = this.io.openSync(temp, "w", 0o600);
|
|
130
|
+
try {
|
|
131
|
+
this.io.writeSync(fd, String(next));
|
|
132
|
+
this.io.fsyncSync(fd);
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
this.io.closeSync(fd);
|
|
136
|
+
}
|
|
137
|
+
this.io.renameSync(temp, path.join(this.dir, NEXT_CODE));
|
|
138
|
+
this.syncDir(this.dir);
|
|
139
|
+
}
|
|
140
|
+
openFile(id) {
|
|
141
|
+
if (!LETTER_ID.test(id))
|
|
142
|
+
throw new Error(`${id} is not a letter id.`);
|
|
143
|
+
return path.join(this.dir, `${id}.jsonl`);
|
|
144
|
+
}
|
|
145
|
+
syncDir(dir) {
|
|
146
|
+
const fd = this.io.openSync(dir, "r");
|
|
147
|
+
try {
|
|
148
|
+
this.io.fsyncSync(fd);
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
this.io.closeSync(fd);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** The length of the file up to and including its last newline. */
|
|
155
|
+
lastNewlineEnd(fd) {
|
|
156
|
+
const size = this.io.fstatSync(fd).size;
|
|
157
|
+
const buffer = Buffer.alloc(size);
|
|
158
|
+
this.io.readSync(fd, buffer, 0, size, 0);
|
|
159
|
+
return buffer.lastIndexOf(0x0a) + 1;
|
|
160
|
+
}
|
|
161
|
+
letterFiles(dir) {
|
|
162
|
+
if (!this.io.existsSync(dir))
|
|
163
|
+
return [];
|
|
164
|
+
return this.io.readdirSync(dir).filter((name) => name.startsWith("ltr_") && name.endsWith(".jsonl")).map((name) => path.join(dir, name));
|
|
165
|
+
}
|
|
166
|
+
closedFiles() {
|
|
167
|
+
const closed = path.join(this.dir, "closed");
|
|
168
|
+
if (!this.io.existsSync(closed))
|
|
169
|
+
return [];
|
|
170
|
+
// Only the month folders the roll writes; anything else under closed/ is left alone.
|
|
171
|
+
return this.io.readdirSync(closed).filter((month) => /^\d{4}-\d{2}$/.test(month)).flatMap((month) => this.letterFiles(path.join(closed, month)));
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Complete lines only: a torn last line is left for the next append to cut. A first line that isn't a letter makes
|
|
175
|
+
* the file unreadable; a later line that isn't JSON is skipped.
|
|
176
|
+
*/
|
|
177
|
+
parse(file, closed) {
|
|
178
|
+
const [first, ...rest] = this.io.readFileSync(file, "utf8").split("\n").slice(0, -1).map(parseLine);
|
|
179
|
+
if (!isStoredLetter(first, path.basename(file, ".jsonl"))) {
|
|
180
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.file_unreadable", message: "a letter file without a letter on its first line was skipped", meta: { file: path.basename(file) } });
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
const events = rest.filter(isStoredEvent);
|
|
184
|
+
if (events.length < rest.length) {
|
|
185
|
+
(0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.line_unreadable", message: "letter lines that aren't events were skipped", meta: { skipped: rest.length - events.length } });
|
|
186
|
+
}
|
|
187
|
+
return { letter: first, events, closed };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
exports.LetterStore = LetterStore;
|
|
191
|
+
function isRecord(value) {
|
|
192
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
193
|
+
}
|
|
194
|
+
/** The fields the index and the doors read from a stored letter, with its id matching its file's name. */
|
|
195
|
+
function isStoredLetter(value, id) {
|
|
196
|
+
return isRecord(value) && value.v === 1 && value.id === id && typeof value.code === "string" && /^L\d+$/.test(value.code)
|
|
197
|
+
&& typeof value.kind === "string" && typeof value.subject === "string" && typeof value.createdAt === "string"
|
|
198
|
+
&& Array.isArray(value.options) && isRecord(value.from) && typeof value.from.agent === "string";
|
|
199
|
+
}
|
|
200
|
+
function isStoredEvent(value) {
|
|
201
|
+
return isRecord(value) && typeof value.t === "string" && typeof value.at === "string";
|
|
202
|
+
}
|
|
203
|
+
function parseLine(line) {
|
|
204
|
+
try {
|
|
205
|
+
return JSON.parse(line);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
}
|