@joe-broadhead/opencode-mem 0.6.2 → 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.
@@ -0,0 +1,239 @@
1
+ /**
2
+ * The read-only RPC methods Memory's views call in Jelly, and their schemas.
3
+ *
4
+ * This module is the one source of the method list: `package.json`'s
5
+ * `jelly.rpc` must equal `declaredMethods()` (test/views-contract.test.js), and
6
+ * `src/views/rpc.js` registers exactly these, under the package name, with the
7
+ * engine's RPC (`ctx.rpc.register`).
8
+ *
9
+ * Jelly holds each call to the agent's rules for the method's `permission`
10
+ * before the plugin sees it, so every method reads under the permission of the
11
+ * tool that makes the same read: the overview under `mem_status`, the space
12
+ * list under `mem_spaces`, recent memories under `mem_recall`, the wiki under
13
+ * `mem_wiki`. None of them writes: a write starts as a message the person sends
14
+ * (`open-agent`), and the agent's tool runs under the person's rules.
15
+ *
16
+ * The schemas are JSON Schema documents Jelly reads as data, checked on every
17
+ * call both ways (input and answer), each at most 16 KB. They use no
18
+ * `pattern`: the pinned engine's RPC (OpenCode 2.2.5, through Effect's
19
+ * `fromJsonSchemaDocument`) refuses to register a schema that has one ("Patterns
20
+ * may block validation and are disabled"). The handlers check ids themselves
21
+ * (`ID_PATTERN`) and refuse a bad one in words.
22
+ */
23
+
24
+ /** A memory, space, wiki or page id as the views pass it back: visible ASCII, bounded. */
25
+ export const ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$"
26
+ /**
27
+ * Recent memories per page, and the most the page may skip: two pages, the
28
+ * newest 100, as deep as one upstream query reads (`src/views/rpc.js`).
29
+ */
30
+ export const RECENT_PAGE = 50
31
+ export const RECENT_MAX_OFFSET = 50
32
+ /** Characters of one memory a view is given; the tool reads the rest. */
33
+ export const MEMORY_TEXT_CHARS = 600
34
+ /** Characters of one wiki page a view is given. */
35
+ export const PAGE_TEXT_CHARS = 48_000
36
+ /** The most wikis, pages and spaces one answer lists. */
37
+ export const LIST_MAX = 100
38
+
39
+ const empty = { type: "object", additionalProperties: false, properties: {} }
40
+ const id = { type: "string", maxLength: 200 }
41
+ const line = (max) => ({ type: "string", maxLength: max })
42
+ const space = {
43
+ type: "object",
44
+ additionalProperties: false,
45
+ required: ["id", "name", "kind"],
46
+ properties: {
47
+ id,
48
+ name: line(200),
49
+ kind: { type: "string", enum: ["personal", "shared", "unknown"] },
50
+ },
51
+ }
52
+
53
+ const overviewOutput = {
54
+ type: "object",
55
+ additionalProperties: false,
56
+ required: ["connected", "credential", "capture", "health"],
57
+ properties: {
58
+ /** Whether memory can be used at all; `reason` says why not. */
59
+ connected: { type: "boolean" },
60
+ reason: line(400),
61
+ /** Where the bearer comes from: Jelly, a pasted key, the token option, or nothing. */
62
+ credential: { type: "string", enum: ["jelly", "key", "option", "none"] },
63
+ /** Jelly's refusal code while the plugin falls back to a pasted key. */
64
+ refused: line(40),
65
+ /** The memory service's origin. */
66
+ address: line(300),
67
+ /** Capture as this engine runs it now: the declared setting, read at start. */
68
+ capture: { type: "boolean" },
69
+ health: { type: "string", enum: ["ok", "unreachable", "unknown"] },
70
+ space,
71
+ counts: {
72
+ type: "object",
73
+ additionalProperties: false,
74
+ required: ["memories", "conversations", "summaries", "profile"],
75
+ properties: {
76
+ memories: { type: "integer", minimum: 0 },
77
+ conversations: { type: "integer", minimum: 0 },
78
+ summaries: { type: "integer", minimum: 0 },
79
+ profile: { type: "boolean" },
80
+ },
81
+ },
82
+ },
83
+ }
84
+
85
+ const spacesOutput = {
86
+ type: "object",
87
+ additionalProperties: false,
88
+ required: ["spaces"],
89
+ properties: {
90
+ spaces: {
91
+ type: "array",
92
+ maxItems: LIST_MAX,
93
+ items: {
94
+ type: "object",
95
+ additionalProperties: false,
96
+ required: ["id", "name", "kind", "role"],
97
+ properties: { ...space.properties, role: line(40) },
98
+ },
99
+ },
100
+ },
101
+ }
102
+
103
+ const recentInput = {
104
+ type: "object",
105
+ additionalProperties: false,
106
+ properties: { offset: { type: "integer", minimum: 0, maximum: RECENT_MAX_OFFSET, multipleOf: RECENT_PAGE } },
107
+ }
108
+
109
+ const recentOutput = {
110
+ type: "object",
111
+ additionalProperties: false,
112
+ required: ["space", "items", "more"],
113
+ properties: {
114
+ space,
115
+ items: {
116
+ type: "array",
117
+ maxItems: RECENT_PAGE,
118
+ items: {
119
+ type: "object",
120
+ additionalProperties: false,
121
+ required: ["id", "text", "type", "at"],
122
+ properties: {
123
+ id,
124
+ text: line(MEMORY_TEXT_CHARS),
125
+ type: line(40),
126
+ /** ISO time it was written or last changed; "" when the store gave none. */
127
+ at: line(40),
128
+ },
129
+ },
130
+ },
131
+ /** Whether a later page has more. */
132
+ more: { type: "boolean" },
133
+ },
134
+ }
135
+
136
+ const wikiListOutput = {
137
+ type: "object",
138
+ additionalProperties: false,
139
+ required: ["wikis"],
140
+ properties: {
141
+ wikis: {
142
+ type: "array",
143
+ maxItems: LIST_MAX,
144
+ items: {
145
+ type: "object",
146
+ additionalProperties: false,
147
+ required: ["id", "name", "pages"],
148
+ properties: { id, name: line(200), pages: { type: "integer", minimum: 0 } },
149
+ },
150
+ },
151
+ },
152
+ }
153
+
154
+ const wikiPagesOutput = {
155
+ type: "object",
156
+ additionalProperties: false,
157
+ required: ["pages"],
158
+ properties: {
159
+ pages: {
160
+ type: "array",
161
+ maxItems: LIST_MAX,
162
+ items: {
163
+ type: "object",
164
+ additionalProperties: false,
165
+ required: ["ref", "title"],
166
+ properties: { ref: id, title: line(200) },
167
+ },
168
+ },
169
+ },
170
+ }
171
+
172
+ const wikiReadOutput = {
173
+ type: "object",
174
+ additionalProperties: false,
175
+ required: ["ref", "content", "clipped"],
176
+ properties: { ref: id, content: line(PAGE_TEXT_CHARS), clipped: { type: "boolean" } },
177
+ }
178
+
179
+ /**
180
+ * The methods, in the order `package.json` declares them.
181
+ * @type {ReadonlyArray<{ name: string, label: string, permission: string, input: object, output: object }>}
182
+ */
183
+ export const VIEW_METHODS = Object.freeze([
184
+ {
185
+ name: "memory.overview",
186
+ label: "say whether memory is connected and how much it holds",
187
+ permission: "mem_status",
188
+ input: empty,
189
+ output: overviewOutput,
190
+ },
191
+ { name: "spaces.list", label: "list your memory spaces", permission: "mem_spaces", input: empty, output: spacesOutput },
192
+ {
193
+ name: "memories.recent",
194
+ label: "list your newest memories",
195
+ permission: "mem_recall",
196
+ input: recentInput,
197
+ output: recentOutput,
198
+ },
199
+ { name: "wiki.list", label: "list your wikis", permission: "mem_wiki", input: empty, output: wikiListOutput },
200
+ {
201
+ name: "wiki.pages",
202
+ label: "list a wiki's pages",
203
+ permission: "mem_wiki",
204
+ input: {
205
+ type: "object",
206
+ additionalProperties: false,
207
+ required: ["wiki"],
208
+ properties: { wiki: id },
209
+ },
210
+ output: wikiPagesOutput,
211
+ },
212
+ {
213
+ name: "wiki.read",
214
+ label: "read a wiki page",
215
+ permission: "mem_wiki",
216
+ input: {
217
+ type: "object",
218
+ additionalProperties: false,
219
+ required: ["wiki", "ref"],
220
+ properties: { wiki: id, ref: id },
221
+ },
222
+ output: wikiReadOutput,
223
+ },
224
+ ])
225
+
226
+ /** The refusal a page can show in the plugin's own words (`call.error`). */
227
+ export const VIEW_ERROR = "memory.refused"
228
+
229
+ /** `jelly.rpc` as package.json declares it. */
230
+ export function declaredMethods() {
231
+ return VIEW_METHODS.map(({ name, label, permission, input, output }) => ({
232
+ name,
233
+ label,
234
+ permission,
235
+ readOnly: true,
236
+ input,
237
+ output,
238
+ }))
239
+ }
@@ -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
+ }