@joe-broadhead/opencode-mem 0.8.5 → 0.9.1

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +512 -0
  2. package/README.md +127 -61
  3. package/docs/agent-protocol.md +67 -177
  4. package/package.json +1453 -100
  5. package/skills/mem.pages/SKILL.md +146 -0
  6. package/skills/mem.sharing/SKILL.md +91 -0
  7. package/skills/mem.sources/SKILL.md +94 -0
  8. package/skills/mem.usage/SKILL.md +129 -492
  9. package/src/backend/records.js +285 -0
  10. package/src/backend/v3.js +3 -0
  11. package/src/bootstrap.js +49 -45
  12. package/src/call-shapes.js +41 -10
  13. package/src/collector-lock.js +162 -0
  14. package/src/collector-service.js +441 -0
  15. package/src/collector.js +381 -0
  16. package/src/commands.js +3 -3
  17. package/src/config.js +15 -1
  18. package/src/credentials.js +26 -1
  19. package/src/curation.js +1 -1
  20. package/src/permissions.js +87 -10
  21. package/src/protocol.js +29 -20
  22. package/src/recall.js +104 -27
  23. package/src/records-store.js +267 -121
  24. package/src/records.js +63 -11
  25. package/src/runtime.js +23 -14
  26. package/src/skills.js +44 -18
  27. package/src/sources.js +58 -0
  28. package/src/spaces.js +93 -10
  29. package/src/tools/aliases.js +164 -0
  30. package/src/tools/commitments.js +12 -9
  31. package/src/tools/held-write.js +82 -0
  32. package/src/tools/index.js +100 -23
  33. package/src/tools/ingest.js +277 -0
  34. package/src/tools/knowledge.js +6 -1
  35. package/src/tools/memory.js +722 -229
  36. package/src/tools/page.js +423 -0
  37. package/src/tools/recall.js +371 -113
  38. package/src/tools/records-kit.js +142 -0
  39. package/src/tools/share.js +1042 -0
  40. package/src/tools/shared.js +16 -2
  41. package/src/tools/spaces.js +431 -143
  42. package/src/tools/status.js +87 -58
  43. package/src/tools/wiki.js +8 -4
  44. package/src/views/contracts.js +293 -3
  45. package/src/views/inbox-decision.js +59 -0
  46. package/src/views/recall-result.js +12 -0
  47. package/src/views/records-reads.js +675 -0
  48. package/src/views/rpc.js +58 -99
  49. package/src/views/shape.js +61 -0
  50. package/views/commitments.html +4 -0
  51. package/views/graph.html +753 -0
  52. package/views/home.html +11 -5
  53. package/views/journal.html +621 -0
  54. package/views/memory.html +7 -1
  55. package/views/pages.html +636 -0
  56. package/views/recall.html +123 -0
  57. package/views/review.html +406 -0
  58. package/views/today.html +309 -0
package/views/home.html CHANGED
@@ -2,6 +2,7 @@
2
2
  <html lang="en-GB">
3
3
  <head>
4
4
  <meta charset="utf-8">
5
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-5dtPKkjegOPG8bawdSzGBjixnIaSCLYcZOUAwbRWFAc=' 'sha256-vhQuH/EWSlGque8dkQL2uHtrgUCB4sWo+YfdgAuixMI='; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
5
6
  <title>Memory</title>
6
7
  <style>
7
8
  :root {
@@ -145,6 +146,8 @@ function show(...nodes) {
145
146
  tile.removeAttribute("aria-busy");
146
147
  fit();
147
148
  }
149
+ // What every view says when the server has no records service (src/views/contracts.js).
150
+ const RECORDS_OFF = "This Memory server has no records service yet, so memories, journals, pages and review can't be shown. Ask whoever runs it to turn it on.";
148
151
  const count = (value, one, many) => `${value.toLocaleString("en-GB")} ${value === 1 ? one : many}`;
149
152
 
150
153
  async function draw() {
@@ -164,11 +167,14 @@ async function draw() {
164
167
  el("p", "muted", "Open Settings, then Plugins, then Memory, to connect it."),
165
168
  );
166
169
  const counts = overview.counts ?? { memories: 0, conversations: 0 };
167
- const lines = [
168
- state(overview.capture ? "Remembering" : "Not saving conversations", overview.capture ? "" : "off"),
169
- el("p", "figure", counts.memories.toLocaleString("en-GB")),
170
- el("p", "muted", `${counts.memories === 1 ? "memory" : "memories"} kept, from ${count(counts.conversations, "conversation", "conversations")}`),
171
- ];
170
+ const lines = [state(overview.capture ? "Remembering" : "Not saving conversations", overview.capture ? "" : "off")];
171
+ // Memories are records from 0.9: a server without the records service says so in one line.
172
+ if (overview.records === "unavailable") lines.push(el("p", "muted", RECORDS_OFF));
173
+ else
174
+ lines.push(
175
+ el("p", "figure", counts.memories.toLocaleString("en-GB")),
176
+ el("p", "muted", `${counts.memories === 1 ? "memory" : "memories"} kept, from ${count(counts.conversations, "conversation", "conversations")}`),
177
+ );
172
178
  if (overview.health !== "ok") lines.push(el("p", "muted", "Memory can't be reached just now."));
173
179
  // The notice: memory is on for every Jelly user, so the tile says plainly what
174
180
  // it saves and where to turn it off. A view cannot open Settings, so it names
@@ -0,0 +1,621 @@
1
+ <!doctype html>
2
+ <html lang="en-GB">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-5dtPKkjegOPG8bawdSzGBjixnIaSCLYcZOUAwbRWFAc=' 'sha256-/0aqZ5aL9ON4+6IAVSSwbjH6b/AakzUoE2N5RwMn9BM=' 'sha256-cJAdoHVR2zEuXSHkrzcA1aINmwH3l1wBqc1+Y7u8V6g='; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
6
+ <title>Journal</title>
7
+ <style>
8
+ :root {
9
+ color: var(--jelly-text, CanvasText);
10
+ background: var(--jelly-surface, Canvas);
11
+ font: 14px/1.45 var(--jelly-font, system-ui, sans-serif);
12
+ }
13
+ * { box-sizing: border-box; }
14
+ body { margin: 0; padding: 2px; }
15
+ p { margin: 0; }
16
+ h1 { font-size: 16px; margin: 0 0 4px; overflow-wrap: anywhere; }
17
+ .muted { color: var(--jelly-muted, GrayText); font-size: 12px; }
18
+ .state { font-weight: 600; display: flex; align-items: center; gap: 6px; }
19
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--jelly-accent, Highlight); flex: none; }
20
+ .dot.off { background: transparent; border: 1.5px solid var(--jelly-muted, GrayText); }
21
+ .dot.danger { background: var(--jelly-danger, CanvasText); }
22
+ .bar { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin: 0 0 8px; }
23
+ .bar.flat { margin: 0; }
24
+ .grow { flex: 1; min-width: 0; overflow-wrap: anywhere; }
25
+ .button, .chip, select, textarea, input {
26
+ font: inherit; font-size: 12px; color: var(--jelly-text, CanvasText); background: var(--jelly-raised, Canvas);
27
+ border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px);
28
+ }
29
+ .button { padding: 2px 8px; cursor: pointer; white-space: nowrap; }
30
+ .button[aria-pressed="true"] { color: var(--jelly-on-accent, HighlightText); background: var(--jelly-accent, Highlight); border-color: var(--jelly-accent, Highlight); }
31
+ .button.quiet { border-color: transparent; background: transparent; padding-left: 0; }
32
+ select { padding: 2px 4px; }
33
+ textarea { width: 100%; padding: 4px 6px; resize: vertical; }
34
+ .button:focus-visible, .chip:focus-visible, .row:focus-visible, select:focus-visible, textarea:focus-visible, input:focus-visible, summary:focus-visible {
35
+ outline: 2px solid var(--jelly-accent, Highlight); outline-offset: 2px;
36
+ }
37
+ .chip {
38
+ display: inline-block; max-width: 22em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
39
+ vertical-align: bottom; padding: 0 7px; margin: 0 2px; border-radius: 999px; cursor: pointer;
40
+ }
41
+ .chip.event, .chip.turn { border-style: dashed; }
42
+ .badge { display: inline-block; font-size: 11px; font-weight: 600; border: 1px solid var(--jelly-border, GrayText); border-radius: 999px; padding: 0 6px; margin-left: 4px; }
43
+ .badge.warn { border-color: var(--jelly-danger, CanvasText); color: var(--jelly-danger, CanvasText); }
44
+ ul.rows { list-style: none; margin: 0; padding: 0; }
45
+ ul.rows > li { border-top: 1px solid var(--jelly-border, GrayText); }
46
+ ul.rows > li:first-child { border-top: 0; }
47
+ .row {
48
+ display: block; width: 100%; text-align: left; font: inherit; color: var(--jelly-text, CanvasText); background: transparent;
49
+ border: 0; padding: 6px 2px; cursor: pointer; overflow-wrap: anywhere;
50
+ }
51
+ .row > span { display: block; }
52
+ .row .title { font-weight: 600; }
53
+ .md { overflow-wrap: anywhere; }
54
+ .md h2 { font-size: 15px; margin: 12px 0 4px; }
55
+ .md h3 { font-size: 14px; margin: 10px 0 4px; }
56
+ .md h4, .md h5 { font-size: 13px; margin: 8px 0 2px; }
57
+ .md p, .md ul, .md ol, .md pre, .md blockquote { margin: 4px 0; }
58
+ .md ul, .md ol { padding-left: 20px; }
59
+ .md li.nested { margin-left: 16px; }
60
+ .md hr { border: 0; border-top: 1px solid var(--jelly-border, GrayText); margin: 10px 0; }
61
+ .md blockquote, blockquote.quote { margin: 4px 0; padding-left: 8px; border-left: 3px solid var(--jelly-border, GrayText); }
62
+ .md pre { overflow: auto; padding: 6px 8px; background: var(--jelly-raised, Canvas); border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px); }
63
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
64
+ .link { text-decoration: underline; }
65
+ .address { color: var(--jelly-muted, GrayText); overflow-wrap: anywhere; }
66
+ .panel { margin: 8px 0; padding: 8px; border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px); background: var(--jelly-raised, Canvas); }
67
+ .panel:empty { display: none; }
68
+ .panel h2 { font-size: 14px; margin: 0 0 4px; }
69
+ dl.fields { display: grid; grid-template-columns: max-content 1fr; gap: 2px 10px; margin: 6px 0; font-size: 12px; }
70
+ dl.fields dt { color: var(--jelly-muted, GrayText); }
71
+ dl.fields dd { margin: 0; overflow-wrap: anywhere; }
72
+ footer, .section { margin-top: 12px; padding-top: 8px; border-top: 1px solid var(--jelly-border, GrayText); }
73
+ details > summary { cursor: pointer; font-size: 12px; }
74
+ .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
75
+ .proposal { padding: 8px 0; }
76
+ .proposal > * + * { margin-top: 4px; }
77
+ .title { font-weight: 600; }
78
+ </style>
79
+ </head>
80
+ <body>
81
+ <main id="root" aria-live="polite"><p class="muted">Loading…</p></main>
82
+ <script>
83
+ // jelly-view.js: a client of Jelly's view bridge. Paste it into the page's own <script>:
84
+ // a sealed page loads no script by URL and is given no global. Call jellyView() as the
85
+ // script starts; it resolves with the client when the app says hello.
86
+ function jellyView() {
87
+ return new Promise((resolve) => {
88
+ addEventListener("message", function hello(event) {
89
+ const said = event.data;
90
+ if (event.source !== parent || said?.v !== 1 || said.kind !== "hello" || !event.ports[0])
91
+ return;
92
+ removeEventListener("message", hello);
93
+ const port = event.ports[0];
94
+ const listeners = new Set();
95
+ const latest = new Map();
96
+ const queue = [];
97
+ let sequence = 0;
98
+ let current;
99
+ const theme = (tokens) => {
100
+ const style = document.documentElement.style;
101
+ for (const [name, value] of Object.entries(tokens))
102
+ if (name === "scheme") style.colorScheme = value;
103
+ else style.setProperty(`--jelly-${name}`, value);
104
+ };
105
+ // The app answers one request at a time, so requests go in turn.
106
+ const next = () => {
107
+ if (current !== undefined || queue.length === 0) return;
108
+ current = queue.shift();
109
+ current.timer = setTimeout(
110
+ () => settle({ ok: false, error: "No answer from the app" }),
111
+ 15000,
112
+ );
113
+ port.postMessage(current.message);
114
+ };
115
+ const settle = (answer) => {
116
+ const done = current;
117
+ current = undefined;
118
+ clearTimeout(done.timer);
119
+ if (answer.ok) done.resolve(answer.value);
120
+ else done.reject(new Error(answer.error));
121
+ next();
122
+ };
123
+ port.onmessage = ({ data }) => {
124
+ if (data?.v !== 1) return;
125
+ if (typeof data.kind !== "string") {
126
+ if (current !== undefined && data.re === current.message.id) settle(data);
127
+ return;
128
+ }
129
+ // A call waiting for the person is answered by `until`, not in 15 s.
130
+ if (data.kind === "rpc.waiting" && data.re === current?.message.id) {
131
+ clearTimeout(current.timer);
132
+ current.timer = setTimeout(
133
+ () => settle({ ok: false, error: "No answer from the app" }),
134
+ Math.max(0, Date.parse(data.until) - Date.now()) + 15000,
135
+ );
136
+ }
137
+ if (data.kind === "theme.changed") theme(data.theme);
138
+ // A wait is news only while it lasts, so a later listener is not told of it.
139
+ if (data.kind !== "rpc.waiting") latest.set(data.kind, data);
140
+ for (const listener of listeners) listener(data);
141
+ };
142
+ port.start();
143
+ theme(said.theme);
144
+ const request = (op, fields = {}) =>
145
+ new Promise((resolve, reject) => {
146
+ queue.push({ resolve, reject, message: { ...fields, v: 1, id: String(++sequence), op } });
147
+ next();
148
+ });
149
+ resolve({
150
+ hello: said,
151
+ // A listener first hears the latest push of each kind that came before it.
152
+ on(listener) {
153
+ for (const push of latest.values()) listener(push);
154
+ listeners.add(listener);
155
+ return () => listeners.delete(listener);
156
+ },
157
+ request,
158
+ data: () => request("data.get"),
159
+ state: () => request("state.get"),
160
+ setState: (revision, data) => request("state.set", { revision, data }),
161
+ call: (method, input = {}) => request("rpc.call", { method, input }),
162
+ openAgent: (prefill) => request("open-agent", prefill === undefined ? {} : { prefill }),
163
+ resize: (height) =>
164
+ request("resize", { height: Math.min(1200, Math.max(1, Math.ceil(height))) }),
165
+ decline: () => request("decline"),
166
+ });
167
+ });
168
+ });
169
+ }
170
+ </script>
171
+ <script>
172
+ // markdown.js: Memory's safe Markdown subset for its view pages. Paste it into the page's own
173
+ // <script>, as jelly-view.js is. It builds elements one by one and sets every word with
174
+ // textContent: no markup is ever parsed, so text from a record, a mail or a page can't run.
175
+ // Headings, paragraphs, lists, quotes, rules, code, bold, italic and links; a link shows its
176
+ // words and its address as text (a sealed page cannot open it). [[target]] and [[target|label]]
177
+ // and the citations [turn msg-…] and [event evt_…] become chips that the page's own hooks make.
178
+ function markdown(source, hooks) {
179
+ const SAFE_SCHEMES = ["http", "https", "mailto"];
180
+ const make = (tag, className, text) => {
181
+ const node = document.createElement(tag);
182
+ if (className) node.className = className;
183
+ if (text !== undefined) node.textContent = text;
184
+ return node;
185
+ };
186
+ const chip = (kind, ref, label) =>
187
+ hooks && typeof hooks.chip === "function" ? hooks.chip(kind, ref, label) : make("span", "chip", label || ref);
188
+ // One token at a time, leftmost first: a link, a citation, code, bold, a Markdown link, an
189
+ // address in angle brackets, italic.
190
+ const INLINE = /\[\[([^\]\n|]{1,300})(?:\|([^\]\n]{1,200}))?\]\]|\[(turn|event) ([^\]\s]{1,200})\]|`([^`\n]{1,500})`|\*\*([^*\n]{1,500})\*\*|\[([^\]\n]{1,300})\]\(((?:[^()\s]|\([^()\s]{0,100}\)){0,500})\)|<([a-z][a-z0-9+.-]{0,20}:[^>\s]{1,500})>|(?:^|(?<=[\s(]))[*_]([^*_\n]{1,500})[*_](?=$|[\s).,;:!?])/g;
191
+ const address = (value) => {
192
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(value);
193
+ return scheme && SAFE_SCHEMES.includes(scheme[1].toLowerCase()) ? value : "";
194
+ };
195
+ function inline(text, depth) {
196
+ const out = [];
197
+ let at = 0;
198
+ INLINE.lastIndex = 0;
199
+ for (let match = INLINE.exec(text); match; match = INLINE.exec(text)) {
200
+ if (match.index > at) out.push(document.createTextNode(text.slice(at, match.index)));
201
+ at = INLINE.lastIndex;
202
+ if (match[1] !== undefined) out.push(chip("record", match[1].trim(), (match[2] || "").trim()));
203
+ else if (match[3] !== undefined) out.push(chip(match[3], match[4], ""));
204
+ else if (match[5] !== undefined) out.push(make("code", "", match[5]));
205
+ else if (match[6] !== undefined) {
206
+ const strong = make("strong");
207
+ strong.append(...(depth < 2 ? inline(match[6], depth + 1) : [document.createTextNode(match[6])]));
208
+ out.push(strong);
209
+ } else if (match[7] !== undefined) {
210
+ const link = make("span", "link", match[7]);
211
+ const safe = address(match[8]);
212
+ out.push(link);
213
+ if (safe && safe !== match[7]) out.push(make("span", "address", ` (${safe})`));
214
+ } else if (match[9] !== undefined) {
215
+ const safe = address(match[9]);
216
+ out.push(make("span", safe ? "address" : "", safe || match[9]));
217
+ } else {
218
+ const em = make("em");
219
+ em.append(...(depth < 2 ? inline(match[10], depth + 1) : [document.createTextNode(match[10])]));
220
+ out.push(em);
221
+ }
222
+ // A nested call moved the shared cursor: put it back.
223
+ INLINE.lastIndex = at;
224
+ }
225
+ if (at < text.length) out.push(document.createTextNode(text.slice(at)));
226
+ return out;
227
+ }
228
+ const blocks = [];
229
+ const lines = String(source ?? "").replace(/\r\n?/g, "\n").split("\n");
230
+ let paragraph = [];
231
+ let list = null;
232
+ const flush = () => {
233
+ if (paragraph.length > 0) {
234
+ const node = make("p");
235
+ node.append(...inline(paragraph.join(" "), 0));
236
+ blocks.push(node);
237
+ paragraph = [];
238
+ }
239
+ };
240
+ const close = () => {
241
+ flush();
242
+ list = null;
243
+ };
244
+ for (let index = 0; index < lines.length; index += 1) {
245
+ const line = lines[index];
246
+ const trimmed = line.trim();
247
+ if (/^(```|~~~)/.test(trimmed)) {
248
+ close();
249
+ const fence = trimmed.slice(0, 3);
250
+ const code = [];
251
+ for (index += 1; index < lines.length && !lines[index].trim().startsWith(fence); index += 1) code.push(lines[index]);
252
+ const pre = make("pre");
253
+ pre.append(make("code", "", code.join("\n")));
254
+ blocks.push(pre);
255
+ continue;
256
+ }
257
+ if (!trimmed) {
258
+ close();
259
+ continue;
260
+ }
261
+ const heading = /^(#{1,6})\s+(.*)$/.exec(trimmed);
262
+ if (heading) {
263
+ close();
264
+ const node = make(`h${Math.min(heading[1].length + 1, 5)}`);
265
+ node.append(...inline(heading[2].replace(/\s+#+$/, ""), 0));
266
+ blocks.push(node);
267
+ continue;
268
+ }
269
+ if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
270
+ close();
271
+ blocks.push(make("hr"));
272
+ continue;
273
+ }
274
+ const item = /^(\s*)(?:([-*+])|(\d{1,9})[.)])\s+(.*)$/.exec(line);
275
+ if (item) {
276
+ flush();
277
+ const tag = item[2] ? "ul" : "ol";
278
+ if (!list || list.tagName.toLowerCase() !== tag) {
279
+ list = make(tag);
280
+ blocks.push(list);
281
+ }
282
+ const entry = make("li", item[1].length >= 2 ? "nested" : "");
283
+ entry.append(...inline(item[4], 0));
284
+ list.append(entry);
285
+ continue;
286
+ }
287
+ if (trimmed.startsWith(">")) {
288
+ close();
289
+ const quote = make("blockquote");
290
+ quote.append(...inline(trimmed.replace(/^>\s?/, ""), 0));
291
+ blocks.push(quote);
292
+ continue;
293
+ }
294
+ if (list && /^\s{2,}/.test(line)) {
295
+ list.lastChild.append(document.createTextNode(" "), ...inline(trimmed, 0));
296
+ continue;
297
+ }
298
+ list = null;
299
+ paragraph.push(trimmed);
300
+ }
301
+ close();
302
+ return blocks;
303
+ }
304
+ </script>
305
+ <script>
306
+ const root = document.getElementById("root");
307
+ let view = null;
308
+ // The space a read goes to: a shared space's id, or undefined for the person's own.
309
+ let space;
310
+ let spaceKind = "personal";
311
+
312
+ function el(tag, className, text) {
313
+ const node = document.createElement(tag);
314
+ if (className) node.className = className;
315
+ if (text !== undefined) node.textContent = text;
316
+ return node;
317
+ }
318
+ function button(label, onClick, className = "button") {
319
+ const node = el("button", className, label);
320
+ node.type = "button";
321
+ node.addEventListener("click", onClick);
322
+ return node;
323
+ }
324
+ function state(words, dot) {
325
+ const line = el("p", "state");
326
+ const mark = el("span", `dot ${dot}`);
327
+ mark.setAttribute("aria-hidden", "true");
328
+ line.append(mark, words);
329
+ return line;
330
+ }
331
+ function fit() {
332
+ // The body's own height: the document is at least as tall as the frame, so it never shrinks.
333
+ if (view) view.resize(document.body.getBoundingClientRect().height).catch(() => undefined);
334
+ }
335
+ function show(...nodes) {
336
+ root.replaceChildren(...nodes);
337
+ root.removeAttribute("aria-busy");
338
+ fit();
339
+ }
340
+ function busy() {
341
+ root.setAttribute("aria-busy", "true");
342
+ }
343
+ // A read's input: the page's own fields and the chosen space.
344
+ function input(fields = {}) {
345
+ return space ? { ...fields, space } : fields;
346
+ }
347
+ // What every view says when the server has no records service (src/views/contracts.js).
348
+ const RECORDS_OFF = "This Memory server has no records service yet, so memories, journals, pages and review can't be shown. Ask whoever runs it to turn it on.";
349
+ function failed(what, error, retry) {
350
+ if (error.message === RECORDS_OFF) return show(el("p", "muted", RECORDS_OFF));
351
+ return show(state(what, "danger"), el("p", "muted", error.message), button("Try again", retry));
352
+ }
353
+ function number(value) {
354
+ return Number(value || 0).toLocaleString("en-GB");
355
+ }
356
+ // "Sun 8 Nov" for a day, from YYYY-MM-DD or an ISO time.
357
+ function dayWords(value) {
358
+ const date = new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value);
359
+ if (Number.isNaN(date.getTime())) return value || "";
360
+ return date.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short", timeZone: "UTC" });
361
+ }
362
+ function waiting(push, what) {
363
+ if (push.kind === "rpc.waiting") show(state("Waiting for you", "off"), el("p", "muted", `Allow this in Jelly to see ${what}.`));
364
+ }
365
+
366
+ // The space picker, when the person has more than one space; null otherwise.
367
+ let spaceList = null;
368
+ async function spacePicker(redraw) {
369
+ if (spaceList === null) {
370
+ try {
371
+ spaceList = (await view.call("spaces.list")).spaces;
372
+ } catch {
373
+ spaceList = [];
374
+ }
375
+ }
376
+ if (spaceList.length < 2) return null;
377
+ const label = el("label", "muted", "Space ");
378
+ const select = el("select");
379
+ for (const entry of spaceList) {
380
+ const option = el("option", "", entry.kind === "personal" ? `${entry.name} (yours)` : entry.name);
381
+ option.value = entry.kind === "personal" ? "" : entry.id;
382
+ if ((space ?? "") === option.value) option.selected = true;
383
+ select.append(option);
384
+ }
385
+ select.addEventListener("change", () => {
386
+ space = select.value || undefined;
387
+ spaceKind = space ? spaceList.find((entry) => entry.id === space)?.kind ?? "shared" : "personal";
388
+ redraw();
389
+ });
390
+ label.append(select);
391
+ return label;
392
+ }
393
+
394
+ const RECORD_ID = /^rec_[0-9A-Za-z]{1,64}$/;
395
+ const PAGE_PATH = /^[a-z0-9][a-z0-9-]{0,63}(\/[a-z0-9][a-z0-9-]{0,63}){0,3}$/;
396
+ // The read that names a link's target, or null when it names nothing Memory keeps.
397
+ function recordInput(ref) {
398
+ if (RECORD_ID.test(ref)) return { id: ref };
399
+ if (PAGE_PATH.test(ref)) return { path: ref };
400
+ return null;
401
+ }
402
+ const TYPE_WORDS = {
403
+ person: "Person", project: "Project", team: "Team", topic: "Topic", runbook: "Runbook", glossary: "Glossary",
404
+ journal: "Journal", index: "Dashboard", decision: "Decision", fact: "Fact", preference: "Preference",
405
+ constraint: "Constraint", procedure: "Procedure", commitment: "Commitment",
406
+ };
407
+ // A link chip's words: its label, "record" for a bare record id, else the page's last part.
408
+ function linkWords(ref, label) {
409
+ if (label) return label;
410
+ return RECORD_ID.test(ref) ? "record" : ref.split("/").pop();
411
+ }
412
+ function linkName(ref, label) {
413
+ return RECORD_ID.test(ref) && !label ? `Open the cited record ${ref}` : `Open ${linkWords(ref, label)}`;
414
+ }
415
+ function typeWords(kind, type) {
416
+ const word = TYPE_WORDS[type] || (type ? type.charAt(0).toUpperCase() + type.slice(1) : "Record");
417
+ if (kind === "page" && type !== "journal" && type !== "index") return `${word} page`;
418
+ if (kind === "proposal") return "Proposal";
419
+ return word;
420
+ }
421
+ // A status that is not plain current, in words.
422
+ function statusBadge(status) {
423
+ if (!status || status === "current") return null;
424
+ const words = { superseded: "Replaced", retired: "Retired", contested: "Contested", proposed: "Waiting for review" }[status] || status;
425
+ return el("span", status === "contested" ? "badge warn" : "badge", words);
426
+ }
427
+ function fieldList(fields) {
428
+ if (!fields.length) return null;
429
+ const list = el("dl", "fields");
430
+ for (const field of fields) list.append(el("dt", "", field.name), el("dd", "", field.value));
431
+ return list;
432
+ }
433
+ // A cited source, as the page knows it: an event's source, title and address; a turn's.
434
+ function sourceNote(kind, ref, source) {
435
+ const nodes = [el("h2", "", kind === "event" ? "Cited message" : "Cited conversation")];
436
+ const list = el("dl", "fields");
437
+ const add = (name, value, className) => {
438
+ if (!value) return;
439
+ list.append(el("dt", "", name), el("dd", className || "", value));
440
+ };
441
+ add("From", source ? source.source : "");
442
+ add("Title", source ? source.title : "");
443
+ add("Address", source ? source.url : "", "address");
444
+ add("Id", ref);
445
+ nodes.push(list);
446
+ if (kind === "event") nodes.push(el("p", "muted", "Memory keeps the messages it collects for 30 days, then only the quote and the address."));
447
+ return nodes;
448
+ }
449
+
450
+ // Memory's Journal: the pages the evening routine writes (journal/YYYY-MM-DD, weekly and
451
+ // monthly), newest first, and one page read as Markdown. Nothing is loaded from anywhere:
452
+ // the pages come from the plugin over the bridge, and every word is set as text. Citations
453
+ // are chips: a record opens beside the page; a message shows its title and address.
454
+ let period = "";
455
+ const PERIODS = [["", "All"], ["day", "Days"], ["week", "Weeks"], ["month", "Months"]];
456
+
457
+ function when(entry) {
458
+ if (entry.period === "month") {
459
+ const date = new Date(`${entry.date}T00:00:00Z`);
460
+ return Number.isNaN(date.getTime()) ? entry.date : date.toLocaleDateString("en-GB", { month: "long", year: "numeric", timeZone: "UTC" });
461
+ }
462
+ return entry.period === "week" ? `Week of ${dayWords(entry.date)}` : dayWords(entry.date);
463
+ }
464
+
465
+ async function toolbar() {
466
+ const bar = el("div", "bar");
467
+ const group = el("div", "bar flat");
468
+ group.setAttribute("role", "group");
469
+ group.setAttribute("aria-label", "Show");
470
+ for (const [value, words] of PERIODS) {
471
+ const choice = button(words, () => {
472
+ period = value;
473
+ drawList();
474
+ });
475
+ choice.setAttribute("aria-pressed", String(period === value));
476
+ group.append(choice);
477
+ }
478
+ bar.append(group);
479
+ const picker = await spacePicker(drawList);
480
+ if (picker) bar.append(picker);
481
+ return bar;
482
+ }
483
+
484
+ async function drawList() {
485
+ busy();
486
+ let answer;
487
+ try {
488
+ answer = await view.call("journal.list", input(period ? { period } : {}));
489
+ } catch (error) {
490
+ return failed("Couldn't read your journal", error, drawList);
491
+ }
492
+ const bar = await toolbar();
493
+ if (answer.items.length === 0) {
494
+ return show(bar, el("p", "muted", period
495
+ ? "No pages of this kind yet."
496
+ : "No journal yet. Memory writes one each evening from the day's conversations and the sources you connected."));
497
+ }
498
+ const list = el("ul", "rows");
499
+ list.setAttribute("aria-label", "Journal pages, newest first");
500
+ for (const entry of answer.items) {
501
+ const item = el("li");
502
+ const open = button("", () => drawPage(entry.path), "row");
503
+ const head = el("span", "title", when(entry));
504
+ if (entry.edited) head.append(el("span", "badge", "Edited by you"));
505
+ open.append(head);
506
+ if (entry.summary) open.append(el("span", "muted", entry.summary));
507
+ item.append(open);
508
+ list.append(item);
509
+ }
510
+ show(bar, list, ...(answer.more ? [el("p", "muted", "Older pages aren't listed here: ask your agent for them.")] : []));
511
+ }
512
+
513
+ // A chip for a citation or a link in the page.
514
+ function chipFor(kind, ref, label, sources, panel) {
515
+ const source = sources.get(ref);
516
+ let words;
517
+ if (kind === "record") words = linkWords(ref, label);
518
+ else if (kind === "event") words = source ? `${source.source}: ${source.title || "message"}` : "message";
519
+ else words = source && source.title ? `conversation: ${source.title}` : "conversation";
520
+ const chip = button(words, () => (kind === "record" ? openRecord(ref, sources, panel) : openSource(kind, ref, source, panel)), `chip ${kind}`);
521
+ chip.setAttribute("aria-label", kind === "record" ? linkName(ref, label) : `Show the cited ${kind === "event" ? "message" : "conversation"}: ${words}`);
522
+ return chip;
523
+ }
524
+
525
+ function closer(panel) {
526
+ return button("Close", () => {
527
+ panel.replaceChildren();
528
+ fit();
529
+ });
530
+ }
531
+
532
+ function openSource(kind, ref, source, panel) {
533
+ const close = closer(panel);
534
+ panel.replaceChildren(...sourceNote(kind, ref, source), close);
535
+ close.focus();
536
+ fit();
537
+ }
538
+
539
+ async function openRecord(ref, sources, panel) {
540
+ const read = recordInput(ref);
541
+ if (!read) {
542
+ panel.replaceChildren(el("p", "muted", "That link names nothing Memory keeps."), closer(panel));
543
+ return fit();
544
+ }
545
+ panel.replaceChildren(el("p", "muted", "Opening…"));
546
+ let record;
547
+ try {
548
+ record = await view.call("pages.read", input(read));
549
+ } catch (error) {
550
+ panel.replaceChildren(el("p", "muted", read.path ? `No page at ${read.path} yet. (${error.message})` : error.message), closer(panel));
551
+ return fit();
552
+ }
553
+ const title = el("h2", "", record.title);
554
+ const badge = statusBadge(record.status);
555
+ if (badge) title.append(badge);
556
+ const body = el("div", "md");
557
+ body.append(...markdown(record.body, { chip: (kind, inner, label) => chipFor(kind, inner, label, sources, panel) }));
558
+ const close = closer(panel);
559
+ panel.replaceChildren(title, el("p", "muted", [typeWords(record.kind, record.type), record.path].filter(Boolean).join(" · ")), ...[fieldList(record.fields)].filter(Boolean), body, close);
560
+ close.focus();
561
+ fit();
562
+ }
563
+
564
+ function footerOf(page) {
565
+ const footer = el("footer");
566
+ const parts = [];
567
+ if (page.footer.counts.length > 0) parts.push(`From ${page.footer.counts.map((count) => `${number(count.count)} ${count.source}`).join(", ")}`);
568
+ if (page.footer.tokens !== undefined) parts.push(`${number(page.footer.tokens)} of ${number(page.footer.budget)} model tokens`);
569
+ if (page.footer.routine) parts.push(`written by ${page.footer.routine}`);
570
+ footer.append(el("p", "muted", parts.length ? parts.join(" · ") : "Written by hand."));
571
+ if (page.edited) footer.append(el("p", "muted", "Edited by you, so the evening routine leaves this page as it is."));
572
+ if (page.footer.line) {
573
+ const details = el("details");
574
+ details.append(el("summary", "", "Run details"), el("p", "muted", page.footer.line));
575
+ footer.append(details);
576
+ }
577
+ return footer;
578
+ }
579
+
580
+ async function drawPage(path) {
581
+ busy();
582
+ let page;
583
+ try {
584
+ page = await view.call("journal.read", input({ path }));
585
+ } catch (error) {
586
+ return failed("Couldn't read this journal page", error, () => drawPage(path));
587
+ }
588
+ const sources = new Map(page.sources.map((source) => [source.ref, source]));
589
+ const panel = el("section", "panel");
590
+ panel.setAttribute("aria-label", "Opened from the page");
591
+ panel.setAttribute("aria-live", "polite");
592
+ const head = el("h1", "", page.title);
593
+ if (page.edited) head.append(el("span", "badge", "Edited by you"));
594
+ const body = el("article", "md");
595
+ body.append(...markdown(page.body, { chip: (kind, ref, label) => chipFor(kind, ref, label, sources, panel) }));
596
+ const nodes = [button("← All journal pages", drawList, "button quiet"), head, el("p", "muted", when(page)), panel, body];
597
+ if (page.clipped) nodes.push(el("p", "muted", "This page is longer than a view shows: ask your agent to read the rest."));
598
+ if (page.sources.length > 0) {
599
+ const list = el("details", "section");
600
+ list.append(el("summary", "", `Sources (${page.sources.length})`));
601
+ const items = el("ul", "rows");
602
+ for (const source of page.sources) {
603
+ const item = el("li");
604
+ item.append(chipFor(source.kind, source.ref, "", sources, panel));
605
+ items.append(item);
606
+ }
607
+ list.append(items);
608
+ nodes.push(list);
609
+ }
610
+ nodes.push(footerOf(page));
611
+ show(...nodes);
612
+ }
613
+
614
+ jellyView().then((client) => {
615
+ view = client;
616
+ view.on((push) => waiting(push, "your journal"));
617
+ drawList();
618
+ });
619
+ </script>
620
+ </body>
621
+ </html>