@joe-broadhead/opencode-mem 0.6.1 → 0.7.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/README.md +140 -17
- package/SECURITY.md +8 -4
- package/assets/icon.svg +14 -0
- package/package.json +459 -6
- package/src/commands.js +1 -0
- package/src/credentials.js +151 -15
- package/src/index.js +11 -1
- package/src/runtime.js +3 -1
- package/src/tools/status.js +1 -0
- package/src/views/contracts.js +239 -0
- package/src/views/rpc.js +412 -0
- package/views/home.html +184 -0
- package/views/memory.html +487 -0
package/src/views/rpc.js
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import { originOf, PACKAGE_NAME, SOURCES } from "../credentials.js"
|
|
2
|
+
import { oneLine } from "../util.js"
|
|
3
|
+
import {
|
|
4
|
+
ID_PATTERN,
|
|
5
|
+
LIST_MAX,
|
|
6
|
+
MEMORY_TEXT_CHARS,
|
|
7
|
+
PAGE_TEXT_CHARS,
|
|
8
|
+
RECENT_MAX_OFFSET,
|
|
9
|
+
RECENT_PAGE,
|
|
10
|
+
VIEW_ERROR,
|
|
11
|
+
VIEW_METHODS,
|
|
12
|
+
} from "./contracts.js"
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The RPC behind Memory's views in Jelly (`views/*.html`).
|
|
16
|
+
*
|
|
17
|
+
* Each call is a read made the way the tools make it: the space comes from the
|
|
18
|
+
* control plane through the gateway, the bearer from the credential chain
|
|
19
|
+
* (`src/credentials.js`: the token option, then the Jelly token, then a pasted
|
|
20
|
+
* key), and the rows from the data plane, which the gateway scopes to the
|
|
21
|
+
* caller. The plugin names no user and no container; a view can only ever see
|
|
22
|
+
* the memory of the person whose credential the engine holds.
|
|
23
|
+
*
|
|
24
|
+
* **Which agent.** Memory keys L0 turns and L1 atoms by container, user and
|
|
25
|
+
* agent, and a view call carries no agent. Jelly's engines name their main
|
|
26
|
+
* agent themselves (`agent`), and that is the name the tools write under. So a
|
|
27
|
+
* view reads under the engine's own primary agents (`ctx.agent.list()`: mode
|
|
28
|
+
* primary or all, not hidden, at most four), or the `agent` option when it is
|
|
29
|
+
* set. With none, control's default for the person applies, as on the console.
|
|
30
|
+
*
|
|
31
|
+
* Jelly checks each call's input and answer against the declared schemas; the
|
|
32
|
+
* handlers check the input again and clip every answer to them, so a long row
|
|
33
|
+
* is shortened here rather than refused there.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** Primary agents read per call; the rest are left out. */
|
|
37
|
+
const MAX_AGENTS = 4
|
|
38
|
+
/** The engine's agent list is read again after this long. */
|
|
39
|
+
const AGENT_TTL_MS = 60_000
|
|
40
|
+
/** Upstream answers at most this many rows per query. */
|
|
41
|
+
const QUERY_MAX = 100
|
|
42
|
+
/** A page's text is held well under Jelly's 64 KB answer cap. */
|
|
43
|
+
const PAGE_TEXT_BYTES = 56_000
|
|
44
|
+
const ID = new RegExp(ID_PATTERN)
|
|
45
|
+
|
|
46
|
+
/** A refusal in the plugin's own words, which the page shows. */
|
|
47
|
+
class ViewRefusal extends Error {}
|
|
48
|
+
|
|
49
|
+
const refuse = (words) => {
|
|
50
|
+
throw new ViewRefusal(words)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One line, at most `max` characters, never ending in half a surrogate pair. */
|
|
54
|
+
function clip(value, max) {
|
|
55
|
+
const text = oneLine(value, max)
|
|
56
|
+
return /[\uD800-\uDBFF]…$/.test(text) ? `${text.slice(0, -2)}…` : text
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Multi-line text, at most `chars` characters and `bytes` UTF-8 bytes. */
|
|
60
|
+
function clipText(value, chars, bytes) {
|
|
61
|
+
let text = String(value ?? "")
|
|
62
|
+
let clipped = false
|
|
63
|
+
if (text.length > chars) {
|
|
64
|
+
text = text.slice(0, chars)
|
|
65
|
+
clipped = true
|
|
66
|
+
}
|
|
67
|
+
while (Buffer.byteLength(text) > bytes) {
|
|
68
|
+
text = text.slice(0, Math.floor(text.length * 0.9))
|
|
69
|
+
clipped = true
|
|
70
|
+
}
|
|
71
|
+
if (clipped && /[\uD800-\uDBFF]$/.test(text)) text = text.slice(0, -1)
|
|
72
|
+
return { text, clipped }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** An id the schema accepts, or "". */
|
|
76
|
+
function idOf(value) {
|
|
77
|
+
const text = String(value ?? "").trim()
|
|
78
|
+
return ID.test(text) ? text : ""
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const SPACE_KINDS = new Set(["personal", "shared"])
|
|
82
|
+
|
|
83
|
+
function spaceOf(context) {
|
|
84
|
+
if (!context) return { id: "local", name: "Local memory", kind: "personal" }
|
|
85
|
+
return {
|
|
86
|
+
id: idOf(context.space_id) || "unknown",
|
|
87
|
+
name: clip(context.space_name || context.space_id || "Your memory", 200),
|
|
88
|
+
kind: SPACE_KINDS.has(context.space_kind) ? context.space_kind : "unknown",
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const CREDENTIALS = Object.freeze({
|
|
93
|
+
[SOURCES.identity]: "jelly",
|
|
94
|
+
[SOURCES.secret]: "key",
|
|
95
|
+
[SOURCES.option]: "option",
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* @param {{
|
|
100
|
+
* runtime: any,
|
|
101
|
+
* agents?: () => Promise<string[]>,
|
|
102
|
+
* }} input
|
|
103
|
+
*/
|
|
104
|
+
export function createViewReads({ runtime, agents = async () => [] }) {
|
|
105
|
+
const { config, backend, credentials } = runtime
|
|
106
|
+
|
|
107
|
+
/** The agent names a view reads under; [] lets control choose. */
|
|
108
|
+
async function readAgents() {
|
|
109
|
+
if (config.agent && config.agent !== "auto") return [String(config.agent)]
|
|
110
|
+
try {
|
|
111
|
+
return (await agents()).slice(0, MAX_AGENTS)
|
|
112
|
+
} catch {
|
|
113
|
+
return []
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The person's personal space for one agent, or null in local direct mode. */
|
|
118
|
+
async function personalContext(agent) {
|
|
119
|
+
if (!runtime.control) return null
|
|
120
|
+
let context = await runtime.resolveContext({ agent })
|
|
121
|
+
if (!context) refuse("Memory gave no space for you.")
|
|
122
|
+
if (context.space_kind !== "personal") {
|
|
123
|
+
const personal = context.personal_space_id
|
|
124
|
+
if (!personal) refuse("Memory has no personal space for you.")
|
|
125
|
+
context = await runtime.resolveContext({ space: personal, agent })
|
|
126
|
+
if (context?.space_kind !== "personal") refuse("Memory has no personal space for you.")
|
|
127
|
+
}
|
|
128
|
+
return context
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The read scope for each agent, one per agent name: the whole space, not a
|
|
133
|
+
* session (reads describe the space, as `mem_recall`'s do).
|
|
134
|
+
*/
|
|
135
|
+
async function personalScopes() {
|
|
136
|
+
const names = await readAgents()
|
|
137
|
+
const list = names.length > 0 ? names : [undefined]
|
|
138
|
+
const contexts = await Promise.all(list.map((agent) => personalContext(agent)))
|
|
139
|
+
const seen = new Set()
|
|
140
|
+
const scopes = []
|
|
141
|
+
for (const [index, context] of contexts.entries()) {
|
|
142
|
+
const scope = context ? runtime.scopeFor(context, { agent: list[index] }) : runtime.scope({ agent: list[index] })
|
|
143
|
+
delete scope.session_id
|
|
144
|
+
if (seen.has(scope.agent_id)) continue
|
|
145
|
+
seen.add(scope.agent_id)
|
|
146
|
+
scopes.push({ context, scope })
|
|
147
|
+
}
|
|
148
|
+
return scopes
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Refuse before any request while memory is unavailable. */
|
|
152
|
+
function available() {
|
|
153
|
+
const reason = runtime.unavailable?.() ?? ""
|
|
154
|
+
if (reason) refuse(reason)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function credentialState() {
|
|
158
|
+
const described = credentials?.describe?.() ?? { source: config.token ? SOURCES.option : "", refused: "" }
|
|
159
|
+
return {
|
|
160
|
+
credential: CREDENTIALS[described.source] ?? "none",
|
|
161
|
+
...(described.refused ? { refused: clip(described.refused, 40) } : {}),
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function overview() {
|
|
166
|
+
const address = originOf(String(config.controlURL ?? "")) || originOf(String(config.baseURL ?? "").replace(/\/core$/, ""))
|
|
167
|
+
const base = {
|
|
168
|
+
capture: config.capture !== false,
|
|
169
|
+
health: "unknown",
|
|
170
|
+
...(address ? { address: clip(address, 300) } : {}),
|
|
171
|
+
}
|
|
172
|
+
const reason = runtime.unavailable?.() ?? ""
|
|
173
|
+
if (reason) return { connected: false, reason: clip(reason, 400), ...credentialState(), ...base }
|
|
174
|
+
let scopes
|
|
175
|
+
try {
|
|
176
|
+
scopes = await personalScopes()
|
|
177
|
+
} catch (error) {
|
|
178
|
+
runtime.log?.warn?.("view overview failed", error)
|
|
179
|
+
// Asked of the credential after the request, so a refusal it met shows.
|
|
180
|
+
return {
|
|
181
|
+
connected: false,
|
|
182
|
+
reason: clip(failureWords(error), 400),
|
|
183
|
+
...credentialState(),
|
|
184
|
+
...base,
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const count = (read) => read.then((data) => Number(data?.total) || 0).catch(() => 0)
|
|
188
|
+
const [health, perAgent] = await Promise.all([
|
|
189
|
+
backend.probe().catch(() => ({ ok: false })),
|
|
190
|
+
Promise.all(
|
|
191
|
+
scopes.map(({ scope }) =>
|
|
192
|
+
Promise.all([
|
|
193
|
+
count(backend.countAtoms({ scope })),
|
|
194
|
+
count(backend.countConversations({ scope })),
|
|
195
|
+
count(backend.countScenarios({ scope })),
|
|
196
|
+
backend
|
|
197
|
+
.readCore({ scope })
|
|
198
|
+
.then((data) => Boolean(data?.content))
|
|
199
|
+
.catch(() => false),
|
|
200
|
+
]),
|
|
201
|
+
),
|
|
202
|
+
),
|
|
203
|
+
])
|
|
204
|
+
const counts = { memories: 0, conversations: 0, summaries: 0, profile: false }
|
|
205
|
+
for (const [memories, conversations, summaries, profile] of perAgent) {
|
|
206
|
+
counts.memories += memories
|
|
207
|
+
counts.conversations += conversations
|
|
208
|
+
counts.summaries += summaries
|
|
209
|
+
counts.profile ||= profile
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
connected: true,
|
|
213
|
+
...credentialState(),
|
|
214
|
+
...base,
|
|
215
|
+
health: health?.ok ? "ok" : "unreachable",
|
|
216
|
+
space: spaceOf(scopes[0]?.context),
|
|
217
|
+
counts,
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function spacesList() {
|
|
222
|
+
available()
|
|
223
|
+
if (!runtime.control) return { spaces: [{ ...spaceOf(null), role: "owner" }] }
|
|
224
|
+
const spaces = await runtime.control.listSpaces({ userId: config.user })
|
|
225
|
+
return {
|
|
226
|
+
spaces: spaces
|
|
227
|
+
.filter((space) => idOf(space.space_id))
|
|
228
|
+
.slice(0, LIST_MAX)
|
|
229
|
+
.map((space) => ({
|
|
230
|
+
id: idOf(space.space_id),
|
|
231
|
+
name: clip(space.name || space.space_id, 200),
|
|
232
|
+
kind: SPACE_KINDS.has(space.kind) ? space.kind : "unknown",
|
|
233
|
+
role: clip(space.role ?? "", 40),
|
|
234
|
+
})),
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* The newest memories (L1 atoms) of the personal space, newest first, across
|
|
240
|
+
* the agents a view reads under. Each agent's newest `offset + page + 1` are
|
|
241
|
+
* merged, so a page is exact: upstream answers at most 100 rows a query,
|
|
242
|
+
* which is as deep as the screen goes (two pages, `RECENT_MAX_OFFSET`).
|
|
243
|
+
*/
|
|
244
|
+
async function recent(input) {
|
|
245
|
+
available()
|
|
246
|
+
const offset = input?.offset ?? 0
|
|
247
|
+
if (typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > RECENT_MAX_OFFSET || offset % RECENT_PAGE !== 0) {
|
|
248
|
+
refuse(`offset is a multiple of ${RECENT_PAGE} from 0 to ${RECENT_MAX_OFFSET}`)
|
|
249
|
+
}
|
|
250
|
+
const scopes = await personalScopes()
|
|
251
|
+
const want = Math.min(QUERY_MAX, offset + RECENT_PAGE + 1)
|
|
252
|
+
const pages = await Promise.all(
|
|
253
|
+
scopes.map(({ scope }) =>
|
|
254
|
+
backend.queryAtoms({ scope, limit: want, offset: 0 }).then((data) =>
|
|
255
|
+
(data?.items ?? []).map((item) => ({ item })),
|
|
256
|
+
),
|
|
257
|
+
),
|
|
258
|
+
)
|
|
259
|
+
const when = ({ item }) => String(item?.updated_at ?? item?.created_at ?? "")
|
|
260
|
+
const rows = pages
|
|
261
|
+
.flat()
|
|
262
|
+
.filter(({ item }) => idOf(item?.id))
|
|
263
|
+
.sort((a, b) => when(b).localeCompare(when(a)))
|
|
264
|
+
const page = rows.slice(offset, offset + RECENT_PAGE)
|
|
265
|
+
return {
|
|
266
|
+
space: spaceOf(scopes[0]?.context),
|
|
267
|
+
items: page.map(({ item }) => ({
|
|
268
|
+
id: idOf(item.id),
|
|
269
|
+
text: clip(item.content, MEMORY_TEXT_CHARS),
|
|
270
|
+
type: clip(item.type ?? "memory", 40),
|
|
271
|
+
at: clip(item.updated_at ?? item.created_at ?? "", 40),
|
|
272
|
+
})),
|
|
273
|
+
more: offset + RECENT_PAGE <= RECENT_MAX_OFFSET && rows.length > offset + RECENT_PAGE,
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** The knowledge scope: wikis belong to the space, not to an agent. */
|
|
278
|
+
async function knowledgeScope() {
|
|
279
|
+
const [first] = await personalScopes()
|
|
280
|
+
return first.context ? runtime.sharedScope({ context: first.context }) : runtime.sharedScope()
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function wikiList() {
|
|
284
|
+
available()
|
|
285
|
+
const scope = await knowledgeScope()
|
|
286
|
+
const data = await backend.listWiki({ scope })
|
|
287
|
+
return {
|
|
288
|
+
wikis: (data?.items ?? [])
|
|
289
|
+
.filter((item) => idOf(item?.wiki_id))
|
|
290
|
+
.slice(0, LIST_MAX)
|
|
291
|
+
.map((item) => ({
|
|
292
|
+
id: idOf(item.wiki_id),
|
|
293
|
+
name: clip(item.name || item.wiki_id, 200),
|
|
294
|
+
pages: Math.max(0, Math.floor(Number(item.page_count) || 0)),
|
|
295
|
+
})),
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** A wiki the caller can list, or a refusal: a view names only what it was shown. */
|
|
300
|
+
async function visibleWiki(scope, value) {
|
|
301
|
+
const wiki = idOf(value)
|
|
302
|
+
if (!wiki) refuse("That is not a wiki id.")
|
|
303
|
+
const data = await backend.listWiki({ scope })
|
|
304
|
+
if (!(data?.items ?? []).some((item) => item?.wiki_id === wiki)) refuse("That wiki isn't in your memory.")
|
|
305
|
+
return wiki
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async function wikiPages(input) {
|
|
309
|
+
available()
|
|
310
|
+
const scope = await knowledgeScope()
|
|
311
|
+
const wiki = await visibleWiki(scope, input?.wiki)
|
|
312
|
+
const data = await backend.listWikiPages({ scope, wikiID: wiki })
|
|
313
|
+
return {
|
|
314
|
+
pages: (data?.items ?? [])
|
|
315
|
+
.map((item) => ({ ref: idOf(item?.path ?? item?.id), title: clip(item?.title || item?.path || item?.id, 200) }))
|
|
316
|
+
.filter((page) => page.ref)
|
|
317
|
+
.slice(0, LIST_MAX),
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function wikiRead(input) {
|
|
322
|
+
available()
|
|
323
|
+
const scope = await knowledgeScope()
|
|
324
|
+
const wiki = await visibleWiki(scope, input?.wiki)
|
|
325
|
+
const ref = idOf(input?.ref)
|
|
326
|
+
if (!ref) refuse("That is not a page.")
|
|
327
|
+
const data = await backend.readWikiPage({ scope, wikiID: wiki, refs: [ref] })
|
|
328
|
+
const item = (data?.items ?? [])[0]
|
|
329
|
+
const content = item?.content ?? item?.text
|
|
330
|
+
if (!item || item.not_found || typeof content !== "string") refuse("That page isn't in this wiki.")
|
|
331
|
+
const { text, clipped } = clipText(content, PAGE_TEXT_CHARS, PAGE_TEXT_BYTES)
|
|
332
|
+
return { ref, content: text, clipped }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return {
|
|
336
|
+
"memory.overview": overview,
|
|
337
|
+
"spaces.list": spacesList,
|
|
338
|
+
"memories.recent": recent,
|
|
339
|
+
"wiki.list": wikiList,
|
|
340
|
+
"wiki.pages": wikiPages,
|
|
341
|
+
"wiki.read": wikiRead,
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* A failed read in words a person can act on; the detail goes to the log.
|
|
347
|
+
* `status` is the HTTP status, 0 when memory could not be reached and 408 for
|
|
348
|
+
* a timeout (`src/spaces.js`, `src/backend/v3.js`).
|
|
349
|
+
*/
|
|
350
|
+
export function failureWords(error) {
|
|
351
|
+
const status = Number(error?.status) || 0
|
|
352
|
+
if (status === 408) return "Memory didn't answer in time. Try again in a moment."
|
|
353
|
+
if (status === 0) return "Memory can't be reached just now. Try again in a moment."
|
|
354
|
+
if (status === 401) return "Memory didn't accept this agent's sign-in."
|
|
355
|
+
if (status === 403) return "Memory refused this read."
|
|
356
|
+
if (status === 404) return "Memory has no such thing."
|
|
357
|
+
if (status === 409) return "Memory isn't set up for you yet."
|
|
358
|
+
if (status >= 500) return "Memory had a problem. Try again in a moment."
|
|
359
|
+
return `Memory could not answer (${status}).`
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* The engine's own primary agents, read through `ctx.agent.list()` and kept
|
|
364
|
+
* for a minute. A host without the list gives none.
|
|
365
|
+
*/
|
|
366
|
+
export function engineAgents(ctx, now = Date.now) {
|
|
367
|
+
let cached = null
|
|
368
|
+
return async () => {
|
|
369
|
+
if (cached && now() - cached.at < AGENT_TTL_MS) return cached.names
|
|
370
|
+
if (typeof ctx?.agent?.list !== "function") return []
|
|
371
|
+
const answer = await ctx.agent.list()
|
|
372
|
+
const list = Array.isArray(answer) ? answer : Array.isArray(answer?.data) ? answer.data : []
|
|
373
|
+
const names = list
|
|
374
|
+
.filter((agent) => agent && agent.hidden !== true && (agent.mode === "primary" || agent.mode === "all"))
|
|
375
|
+
.map((agent) => String(agent.id ?? "").trim())
|
|
376
|
+
.filter((name) => name && name !== "auto")
|
|
377
|
+
cached = { at: now(), names: [...new Set(names)] }
|
|
378
|
+
return cached.names
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Register the views' RPC with the engine, under the package name: the only id
|
|
384
|
+
* Jelly calls for this package's views. A host without `ctx.rpc` (OpenCode
|
|
385
|
+
* before 2.2.5, or outside Jelly) has nothing to register with, so nothing is.
|
|
386
|
+
*
|
|
387
|
+
* A refusal answers as the declared error, so the page shows the plugin's own
|
|
388
|
+
* words; on the pinned engine a thrown error would reach it only as "RPC call
|
|
389
|
+
* failed".
|
|
390
|
+
*
|
|
391
|
+
* @param {any} ctx
|
|
392
|
+
* @param {any} runtime
|
|
393
|
+
*/
|
|
394
|
+
export async function registerViewRpc(ctx, runtime) {
|
|
395
|
+
if (typeof ctx?.rpc?.register !== "function") return null
|
|
396
|
+
const reads = createViewReads({ runtime, agents: engineAgents(ctx) })
|
|
397
|
+
const methods = {}
|
|
398
|
+
const handlers = {}
|
|
399
|
+
for (const method of VIEW_METHODS) {
|
|
400
|
+
methods[method.name] = { input: method.input, output: method.output, errors: { [VIEW_ERROR]: { type: "object" } } }
|
|
401
|
+
handlers[method.name] = async (input, call) => {
|
|
402
|
+
try {
|
|
403
|
+
return await reads[method.name](input ?? {})
|
|
404
|
+
} catch (error) {
|
|
405
|
+
if (!(error instanceof ViewRefusal)) runtime.log?.warn?.(`view read ${method.name} failed`, error)
|
|
406
|
+
const words = error instanceof ViewRefusal ? error.message : failureWords(error)
|
|
407
|
+
return call.error(VIEW_ERROR, clip(words, 200), {})
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return ctx.rpc.register({ id: PACKAGE_NAME, events: {}, methods }, handlers)
|
|
412
|
+
}
|
package/views/home.html
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en-GB">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<title>Memory</title>
|
|
6
|
+
<style>
|
|
7
|
+
:root {
|
|
8
|
+
color: var(--jelly-text, CanvasText);
|
|
9
|
+
background: var(--jelly-surface, Canvas);
|
|
10
|
+
font: 14px/1.4 var(--jelly-font, system-ui, sans-serif);
|
|
11
|
+
}
|
|
12
|
+
* { box-sizing: border-box; }
|
|
13
|
+
body { margin: 0; padding: 2px; }
|
|
14
|
+
p { margin: 0; }
|
|
15
|
+
.muted { color: var(--jelly-muted, GrayText); font-size: 12px; }
|
|
16
|
+
.state { font-weight: 600; display: flex; align-items: center; gap: 6px; }
|
|
17
|
+
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--jelly-accent, Highlight); flex: none; }
|
|
18
|
+
.dot.off { background: transparent; border: 1.5px solid var(--jelly-muted, GrayText); }
|
|
19
|
+
.dot.danger { background: var(--jelly-danger, CanvasText); }
|
|
20
|
+
.figure { font-size: 26px; font-weight: 600; line-height: 1.15; margin: 6px 0 2px; }
|
|
21
|
+
.button {
|
|
22
|
+
font: inherit; font-size: 12px; color: var(--jelly-text, CanvasText); background: var(--jelly-raised, Canvas);
|
|
23
|
+
border: 1px solid var(--jelly-border, GrayText); border-radius: var(--jelly-radius, 8px); padding: 2px 8px; margin-top: 8px; cursor: pointer;
|
|
24
|
+
}
|
|
25
|
+
.button:focus-visible { outline: 2px solid var(--jelly-accent, Highlight); outline-offset: 2px; }
|
|
26
|
+
</style>
|
|
27
|
+
</head>
|
|
28
|
+
<body>
|
|
29
|
+
<main id="tile" aria-live="polite"><p class="muted">Loading…</p></main>
|
|
30
|
+
<script>
|
|
31
|
+
// jelly-view.js: a client of Jelly's view bridge. Paste it into the page's own <script>:
|
|
32
|
+
// a sealed page loads no script by URL and is given no global. Call jellyView() as the
|
|
33
|
+
// script starts; it resolves with the client when the app says hello.
|
|
34
|
+
function jellyView() {
|
|
35
|
+
return new Promise((resolve) => {
|
|
36
|
+
addEventListener("message", function hello(event) {
|
|
37
|
+
const said = event.data;
|
|
38
|
+
if (event.source !== parent || said?.v !== 1 || said.kind !== "hello" || !event.ports[0])
|
|
39
|
+
return;
|
|
40
|
+
removeEventListener("message", hello);
|
|
41
|
+
const port = event.ports[0];
|
|
42
|
+
const listeners = new Set();
|
|
43
|
+
const latest = new Map();
|
|
44
|
+
const queue = [];
|
|
45
|
+
let sequence = 0;
|
|
46
|
+
let current;
|
|
47
|
+
const theme = (tokens) => {
|
|
48
|
+
const style = document.documentElement.style;
|
|
49
|
+
for (const [name, value] of Object.entries(tokens))
|
|
50
|
+
if (name === "scheme") style.colorScheme = value;
|
|
51
|
+
else style.setProperty(`--jelly-${name}`, value);
|
|
52
|
+
};
|
|
53
|
+
// The app answers one request at a time, so requests go in turn.
|
|
54
|
+
const next = () => {
|
|
55
|
+
if (current !== undefined || queue.length === 0) return;
|
|
56
|
+
current = queue.shift();
|
|
57
|
+
current.timer = setTimeout(
|
|
58
|
+
() => settle({ ok: false, error: "No answer from the app" }),
|
|
59
|
+
15000,
|
|
60
|
+
);
|
|
61
|
+
port.postMessage(current.message);
|
|
62
|
+
};
|
|
63
|
+
const settle = (answer) => {
|
|
64
|
+
const done = current;
|
|
65
|
+
current = undefined;
|
|
66
|
+
clearTimeout(done.timer);
|
|
67
|
+
if (answer.ok) done.resolve(answer.value);
|
|
68
|
+
else done.reject(new Error(answer.error));
|
|
69
|
+
next();
|
|
70
|
+
};
|
|
71
|
+
port.onmessage = ({ data }) => {
|
|
72
|
+
if (data?.v !== 1) return;
|
|
73
|
+
if (typeof data.kind !== "string") {
|
|
74
|
+
if (current !== undefined && data.re === current.message.id) settle(data);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
// A call waiting for the person is answered by `until`, not in 15 s.
|
|
78
|
+
if (data.kind === "rpc.waiting" && data.re === current?.message.id) {
|
|
79
|
+
clearTimeout(current.timer);
|
|
80
|
+
current.timer = setTimeout(
|
|
81
|
+
() => settle({ ok: false, error: "No answer from the app" }),
|
|
82
|
+
Math.max(0, Date.parse(data.until) - Date.now()) + 15000,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
if (data.kind === "theme.changed") theme(data.theme);
|
|
86
|
+
// A wait is news only while it lasts, so a later listener is not told of it.
|
|
87
|
+
if (data.kind !== "rpc.waiting") latest.set(data.kind, data);
|
|
88
|
+
for (const listener of listeners) listener(data);
|
|
89
|
+
};
|
|
90
|
+
port.start();
|
|
91
|
+
theme(said.theme);
|
|
92
|
+
const request = (op, fields = {}) =>
|
|
93
|
+
new Promise((resolve, reject) => {
|
|
94
|
+
queue.push({ resolve, reject, message: { ...fields, v: 1, id: String(++sequence), op } });
|
|
95
|
+
next();
|
|
96
|
+
});
|
|
97
|
+
resolve({
|
|
98
|
+
hello: said,
|
|
99
|
+
// A listener first hears the latest push of each kind that came before it.
|
|
100
|
+
on(listener) {
|
|
101
|
+
for (const push of latest.values()) listener(push);
|
|
102
|
+
listeners.add(listener);
|
|
103
|
+
return () => listeners.delete(listener);
|
|
104
|
+
},
|
|
105
|
+
request,
|
|
106
|
+
data: () => request("data.get"),
|
|
107
|
+
state: () => request("state.get"),
|
|
108
|
+
setState: (revision, data) => request("state.set", { revision, data }),
|
|
109
|
+
call: (method, input = {}) => request("rpc.call", { method, input }),
|
|
110
|
+
openAgent: (prefill) => request("open-agent", prefill === undefined ? {} : { prefill }),
|
|
111
|
+
resize: (height) =>
|
|
112
|
+
request("resize", { height: Math.min(1200, Math.max(1, Math.ceil(height))) }),
|
|
113
|
+
decline: () => request("decline"),
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
</script>
|
|
119
|
+
<script>
|
|
120
|
+
// Memory's Home tile: whether memory is on, and how much it holds. Nothing is
|
|
121
|
+
// fetched; the numbers come from the plugin over the bridge.
|
|
122
|
+
const tile = document.getElementById("tile");
|
|
123
|
+
let view = null;
|
|
124
|
+
|
|
125
|
+
function el(tag, className, text) {
|
|
126
|
+
const node = document.createElement(tag);
|
|
127
|
+
if (className) node.className = className;
|
|
128
|
+
if (text !== undefined) node.textContent = text;
|
|
129
|
+
return node;
|
|
130
|
+
}
|
|
131
|
+
function state(words, dot) {
|
|
132
|
+
const line = el("p", "state");
|
|
133
|
+
const mark = el("span", `dot ${dot}`);
|
|
134
|
+
mark.setAttribute("aria-hidden", "true");
|
|
135
|
+
line.append(mark, words);
|
|
136
|
+
return line;
|
|
137
|
+
}
|
|
138
|
+
function fit() {
|
|
139
|
+
// The body's own height: the document is at least as tall as the frame, so it never shrinks.
|
|
140
|
+
if (view) view.resize(document.body.getBoundingClientRect().height).catch(() => undefined);
|
|
141
|
+
}
|
|
142
|
+
function show(...nodes) {
|
|
143
|
+
tile.replaceChildren(...nodes);
|
|
144
|
+
tile.removeAttribute("aria-busy");
|
|
145
|
+
fit();
|
|
146
|
+
}
|
|
147
|
+
const count = (value, one, many) => `${value.toLocaleString("en-GB")} ${value === 1 ? one : many}`;
|
|
148
|
+
|
|
149
|
+
async function draw() {
|
|
150
|
+
tile.setAttribute("aria-busy", "true");
|
|
151
|
+
let overview;
|
|
152
|
+
try {
|
|
153
|
+
overview = await view.call("memory.overview");
|
|
154
|
+
} catch (error) {
|
|
155
|
+
const retry = el("button", "button", "Try again");
|
|
156
|
+
retry.type = "button";
|
|
157
|
+
retry.addEventListener("click", draw);
|
|
158
|
+
return show(state("Couldn't read memory", "danger"), el("p", "muted", error.message), retry);
|
|
159
|
+
}
|
|
160
|
+
if (!overview.connected)
|
|
161
|
+
return show(
|
|
162
|
+
state("Not connected", "off"),
|
|
163
|
+
el("p", "muted", "Open Settings, then Plugins, then Memory, to connect it."),
|
|
164
|
+
);
|
|
165
|
+
const counts = overview.counts ?? { memories: 0, conversations: 0 };
|
|
166
|
+
const lines = [
|
|
167
|
+
state(overview.capture ? "Remembering" : "Not saving conversations", overview.capture ? "" : "off"),
|
|
168
|
+
el("p", "figure", counts.memories.toLocaleString("en-GB")),
|
|
169
|
+
el("p", "muted", `${counts.memories === 1 ? "memory" : "memories"} kept, from ${count(counts.conversations, "conversation", "conversations")}`),
|
|
170
|
+
];
|
|
171
|
+
if (overview.health !== "ok") lines.push(el("p", "muted", "Memory can't be reached just now."));
|
|
172
|
+
show(...lines);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
jellyView().then((client) => {
|
|
176
|
+
view = client;
|
|
177
|
+
view.on((push) => {
|
|
178
|
+
if (push.kind === "rpc.waiting") show(state("Waiting for you", "off"), el("p", "muted", "Allow this in Jelly to see your memory."));
|
|
179
|
+
});
|
|
180
|
+
draw();
|
|
181
|
+
});
|
|
182
|
+
</script>
|
|
183
|
+
</body>
|
|
184
|
+
</html>
|