@joe-broadhead/opencode-mem 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,58 @@
3
3
  The format follows Keep a Changelog 1.1.0: one `## [x.y.z] - date` section per
4
4
  release.
5
5
 
6
+ ## [0.8.3] - 2026-11-07
7
+
8
+ Memory's views ask for the person who opened them (Jelly's resource-token
9
+ contract v1.5 §6.1, Jelly 0.3.3). Not published yet: it is published from its
10
+ own `v0.8.3` tag by `.github/workflows/release.yml`.
11
+
12
+ ### Changed
13
+
14
+ - **A view call asks as its person.** Every method Memory's views call
15
+ (`memory.overview`, `spaces.list`, `memories.recent`, `wiki.list`,
16
+ `wiki.pages`, `wiki.read`, `commitments.list`) declares an optional string
17
+ `jellySpeaker` in its input, in `package.json`'s `jelly.rpc` and in the
18
+ schema the plugin registers with the engine (`src/views/contracts.js`). A
19
+ Jelly host of v1.5 or later fills it with a speaker id naming the person
20
+ whose device made the call. The handler strips it from the input
21
+ (`splitSpeaker` in `src/views/rpc.js`) and runs the read in `asView(id)`
22
+ (`src/credentials.js`): every request of that call carries
23
+ `token("memory", { session: id })`, asked once per call. On a shared agent a
24
+ member's view now shows the member's own memory, and the owner's view works
25
+ after a plugin's turn.
26
+ - **Kept for the call only.** A view call's token and refusal live in the
27
+ call's scope and go with it: never in the 64-session cache or its refusal
28
+ hold, never reused by a later call, the skill mirror, background work or a
29
+ spool replay. The id is never sent to the gateway, logged (a view call's
30
+ refusal is logged as `view: true`), stored or spooled; a write spooled inside
31
+ a view call would record the account its token named and replay under the
32
+ session rules, never with the id.
33
+ - **An unlinked person.** When Jelly refuses a view call with `not_enrolled`
34
+ and the detail `not_signed_in`, Jelly is asked before any request, the call
35
+ uses no credential (not the pasted key, not the owner's or another session's
36
+ token) and sends nothing, and the view answers "Memory is unavailable: you
37
+ have not linked a Jelly account on this host." Other refusals fall back as
38
+ for a session; `access_denied` does not.
39
+ - **Unchanged without the id:** a Jelly before 0.3.3 and stock OpenCode send no
40
+ `jellySpeaker`, and a view asks `token("memory")` with no options, exactly as
41
+ in 0.8.2. A malformed id runs the call the same way.
42
+ - **The declaration grows by one optional input property per method** and asks
43
+ for nothing more: no tool, permission, resource, sign-in, view or grant
44
+ changes, and a method's `permission` and `label` are unchanged, so Jelly's
45
+ declaration refresh (DECL-REFRESH) applies it at once and puts nothing under
46
+ Changes to review.
47
+
48
+ ### Added
49
+
50
+ - `test/view-speaker.test.js`: the eight Memory tests of the VIEW-SPEAKER
51
+ spec, against the real control plane and gateway: a view call asks with its
52
+ id once; without one it asks as 0.8.2; Sam's and Ana's concurrent calls keep
53
+ their own tokens; no view token outlives its call; an unlinked person's call
54
+ sends nothing; the id never reaches a request, the log or a stored record;
55
+ actions (none declared) and the spool; and the declaration's optional
56
+ `jellySpeaker` on every method, never required.
57
+
6
58
  ## [0.8.2] - 2026-11-06
7
59
 
8
60
  A Jelly token per chat, and no fallback for a speaker with no linked account
package/README.md CHANGED
@@ -193,9 +193,9 @@ is still captured with its own speaker's token; a spooled turn is replayed only
193
193
  while the chat's token names the person who spoke it. A turn with no user
194
194
  message (a wake, a routine) keeps the cached token. Tokens are kept per session, for at most 64 sessions (the least
195
195
  recently used goes first), and a session's is dropped when the session is
196
- deleted. Work that belongs to no chat (the skill mirror, Memory's views) asks
197
- `token("memory")` as before, which Jelly answers with the agent owner's token
198
- while the agent is private. A Jelly older than members (0.3.2) refuses the
196
+ deleted. Work that belongs to no chat (the skill mirror, and Memory's views on
197
+ a Jelly before 0.3.3) asks `token("memory")` as before, which Jelly answers
198
+ with the agent owner's token while the agent is private. A Jelly older than members (0.3.2) refuses the
199
199
  `session` option; the plugin then asks as before, one token for the agent,
200
200
  which on such a host is its owner's.
201
201
 
@@ -349,6 +349,30 @@ sees it:
349
349
  | `wiki.list`, `wiki.pages`, `wiki.read` | `mem_wiki` | The personal space's wikis, a wiki's pages, one page (at most 48,000 characters); never the reserved "Memory records" wiki |
350
350
  | `commitments.list` | `mem_commitments` | The personal space's commitments (the records wiki's `commitments.json`): open ones overdue first, or those closed recently |
351
351
 
352
+ **Views ask for the person who opened them (Jelly 0.3.3 and later; 0.8.3).**
353
+ A view is opened by a person on a device, not in a chat, so a view call has no
354
+ session of its own. Every method's input therefore names an optional string,
355
+ `jellySpeaker` (contract v1.5 §6.1). A Jelly of 0.3.3 or later sees it in the
356
+ declared schema and fills it with a short-lived speaker id, `view_…`, naming
357
+ the person whose device made that one call: the owner, a member with a linked
358
+ Jelly account, or a person with none. The handler takes it out of the input
359
+ before the read sees it and asks `token("memory", { session: <id> })` for that
360
+ call, so on a shared agent a member's view shows the member's own memory, and
361
+ a view still works after another plugin's turn. That token is kept for the
362
+ call only: never in the per-chat cache, never for a later call, the skill
363
+ mirror or the spool, and the id never reaches the gateway, the log or a stored
364
+ record. When Jelly answers `not_enrolled` with the detail `not_signed_in`, the
365
+ person who opened the view has not linked a Jelly account on this host: that
366
+ call uses no credential at all (not the pasted key, not the owner's or another
367
+ chat's token), sends nothing, and the view says "Memory is unavailable: you
368
+ have not linked a Jelly account on this host." Other refusals fall back as
369
+ for a chat. A Jelly before 0.3.3, or stock OpenCode, sends no `jellySpeaker`,
370
+ and a view then asks exactly as in 0.8.2. The id is optional and is never in
371
+ `required`; the schemas keep `additionalProperties: false`. Adding it asks for
372
+ nothing more: no tool, permission, resource or sign-in changes, so Jelly's
373
+ declaration refresh applies it with the release and puts nothing under
374
+ Changes to review.
375
+
352
376
  Every call is a read the tools already make, through the gateway with the
353
377
  credential chain above, so no gateway route is added for the views and the
354
378
  gateway scopes each one to the caller. A view never names a user, a space or
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joe-broadhead/opencode-mem",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "type": "module",
5
5
  "description": "Durable private and shared-space memory for OpenCode agents",
6
6
  "license": "MIT",
@@ -89,7 +89,11 @@
89
89
  "input": {
90
90
  "type": "object",
91
91
  "additionalProperties": false,
92
- "properties": {}
92
+ "properties": {
93
+ "jellySpeaker": {
94
+ "type": "string"
95
+ }
96
+ }
93
97
  },
94
98
  "output": {
95
99
  "type": "object",
@@ -201,7 +205,11 @@
201
205
  "input": {
202
206
  "type": "object",
203
207
  "additionalProperties": false,
204
- "properties": {}
208
+ "properties": {
209
+ "jellySpeaker": {
210
+ "type": "string"
211
+ }
212
+ }
205
213
  },
206
214
  "output": {
207
215
  "type": "object",
@@ -263,6 +271,9 @@
263
271
  "minimum": 0,
264
272
  "maximum": 50,
265
273
  "multipleOf": 50
274
+ },
275
+ "jellySpeaker": {
276
+ "type": "string"
266
277
  }
267
278
  }
268
279
  },
@@ -348,7 +359,11 @@
348
359
  "input": {
349
360
  "type": "object",
350
361
  "additionalProperties": false,
351
- "properties": {}
362
+ "properties": {
363
+ "jellySpeaker": {
364
+ "type": "string"
365
+ }
366
+ }
352
367
  },
353
368
  "output": {
354
369
  "type": "object",
@@ -402,6 +417,9 @@
402
417
  "wiki": {
403
418
  "type": "string",
404
419
  "maxLength": 200
420
+ },
421
+ "jellySpeaker": {
422
+ "type": "string"
405
423
  }
406
424
  }
407
425
  },
@@ -457,6 +475,9 @@
457
475
  "ref": {
458
476
  "type": "string",
459
477
  "maxLength": 200
478
+ },
479
+ "jellySpeaker": {
480
+ "type": "string"
460
481
  }
461
482
  }
462
483
  },
@@ -498,6 +519,9 @@
498
519
  "open",
499
520
  "closed"
500
521
  ]
522
+ },
523
+ "jellySpeaker": {
524
+ "type": "string"
501
525
  }
502
526
  }
503
527
  },
@@ -34,9 +34,24 @@
34
34
  * decides who it speaks for, and the token is replaced 60 s before it expires.
35
35
  * A spooled entry records the account its token named and is not replayed
36
36
  * while its session's token names someone else. Work with no session
37
- * (the skill mirror, Memory's views, start-up) asks `token("memory")` as
38
- * before: the contract gives the agent owner's token while the agent is
39
- * private, and refuses it otherwise.
37
+ * (the skill mirror, start-up, and Memory's views on a host before contract
38
+ * v1.5) asks `token("memory")` as before: the contract gives the agent owner's
39
+ * token while the agent is private, and refuses it otherwise.
40
+ *
41
+ * **A view asks for the person who opened it (0.8.3, contract v1.5 §6.1).** A
42
+ * view's call carries no engine session, but a host of v1.5 or later (Jelly
43
+ * 0.3.3) fills the call's `jellySpeaker` input with a speaker id, `view_…`,
44
+ * naming the person whose device made that one call. The view's handler runs
45
+ * the call in `asView(id, fn)`: every credential `fn` asks for is asked
46
+ * `token("memory", { session: id })`, held in that call's scope only and
47
+ * dropped with it. A speaker id is never put in the session cache or its
48
+ * refusal hold, never logged, and never reused by a later call, the skill
49
+ * mirror or background work: each call has a fresh id, and the host keeps
50
+ * the token per person, so asking again costs one round trip, not a mint.
51
+ * The refusals are a session's: `not_signed_in` gives that call no
52
+ * credential (never the pasted key, never another session's or the owner's
53
+ * token); the others fall back as for a session. Without an id (a host
54
+ * before v1.5, stock OpenCode) a view asks as before, with no session.
40
55
  *
41
56
  * A host older than members (Jelly 0.3.2) refuses `{ session }` as options it
42
57
  * does not know (`invalid_target`, detail `invalid_cnf_jwk`; the plugin sends
@@ -114,7 +129,12 @@ const SESSION_PATTERN = /^[A-Za-z0-9_-]{1,128}$/
114
129
  export const UNLINKED_SENTENCE =
115
130
  "Memory isn't available in this chat because the person speaking hasn't linked their Jelly account on this host."
116
131
 
117
- /** The session the current work is done for, and the turn when the work belongs to one: `{ session, turn }`. */
132
+ /**
133
+ * The session the current work is done for, and the turn when the work
134
+ * belongs to one: `{ session, turn }`; for one view call, `view` instead
135
+ * (`asView`): `{ id }`, the call's speaker id, an object that lives as long as
136
+ * the call.
137
+ */
118
138
  const sessionScope = new AsyncLocalStorage()
119
139
 
120
140
  /** A session id the accessor accepts, or "" (work with no session). */
@@ -142,6 +162,34 @@ export function asSession(sessionID, fn, turn) {
142
162
  return sessionScope.run({ session: sessionKey(sessionID), turn: typeof turn === "string" ? turn : "" }, fn)
143
163
  }
144
164
 
165
+ /**
166
+ * Run `fn` as one view call made by the person the speaker id `speaker` names
167
+ * (contract v1.5 §6.1, `jellySpeaker`): every credential it and what it awaits
168
+ * ask for is that person's, asked for this call and kept for it only. A value
169
+ * that is not a string the accessor accepts runs `fn` as work with no session,
170
+ * exactly as a view did before the id existed.
171
+ *
172
+ * @template T
173
+ * @param {unknown} speaker
174
+ * @param {() => T} fn
175
+ * @returns {T}
176
+ */
177
+ export function asView(speaker, fn) {
178
+ const id = sessionKey(speaker)
179
+ if (!id) return asSession("", fn)
180
+ return sessionScope.run({ session: "", turn: "", view: { id } }, fn)
181
+ }
182
+
183
+ /** True inside a view call that carries a speaker id (`asView`). */
184
+ export function inView() {
185
+ return Boolean(sessionScope.getStore()?.view)
186
+ }
187
+
188
+ /** The current view call, `{ id }`, or null. */
189
+ function currentView() {
190
+ return sessionScope.getStore()?.view ?? null
191
+ }
192
+
145
193
  /** The session the current work is done for, or "" for none. */
146
194
  export function currentSession() {
147
195
  return sessionScope.getStore()?.session ?? ""
@@ -319,6 +367,22 @@ export function createCredentials(input = {}) {
319
367
  * (a host older than members): from then on every session asks as `engine`.
320
368
  */
321
369
  let sessionAsks = true
370
+ /**
371
+ * One view call -> its state, for as long as the call's scope object lives:
372
+ * a speaker id is never a key of `sessions`, so it never reaches the LRU,
373
+ * a session's refusal hold, or any later call.
374
+ */
375
+ const views = new WeakMap()
376
+
377
+ /** The state of one view call, created on its first ask. */
378
+ function viewState(view) {
379
+ let state = views.get(view)
380
+ if (!state) {
381
+ state = newState()
382
+ views.set(view, state)
383
+ }
384
+ return state
385
+ }
322
386
 
323
387
  function newEntry() {
324
388
  return { turn: "", state: newState(), pending: null, previous: null }
@@ -351,15 +415,24 @@ export function createCredentials(input = {}) {
351
415
  return entry.state
352
416
  }
353
417
 
354
- /** The state the current work uses, and the session it asks for ("" for none). */
418
+ /**
419
+ * The state the current work uses, the session it asks for ("" for none),
420
+ * and whether that is a view call's speaker id (`view`). On a host that
421
+ * refused `session` (older than members) a view asks as the engine, as it
422
+ * did before.
423
+ */
355
424
  function current() {
425
+ const view = sessionAsks ? currentView() : null
426
+ if (view) return { state: viewState(view), session: view.id, view: true }
356
427
  const session = sessionAsks ? currentSession() : ""
357
- if (!session) return { state: engine, session: "" }
358
- return { state: stateIn(entryOf(session), currentTurn(), true), session }
428
+ if (!session) return { state: engine, session: "", view: false }
429
+ return { state: stateIn(entryOf(session), currentTurn(), true), session, view: false }
359
430
  }
360
431
 
361
432
  /** The current work's state without creating, reordering or rotating one: for reads such as `source()`. */
362
433
  function peek() {
434
+ const view = sessionAsks ? currentView() : null
435
+ if (view) return viewState(view)
363
436
  const session = sessionAsks ? currentSession() : ""
364
437
  if (!session) return engine
365
438
  const entry = sessions.get(session)
@@ -536,18 +609,24 @@ export function createCredentials(input = {}) {
536
609
  * Hold a refusal for `REFUSAL_HOLD_MS` and log it: the code and detail only,
537
610
  * never a token or the accessor's words. Returns the error for this request.
538
611
  *
612
+ * A view call's refusal is logged as `view: true`, never with its speaker
613
+ * id, which is a credential handle; it is held for that call only.
614
+ *
539
615
  * @param {{ refusal: any }} state
540
- * @param {string} session "" for work with no session
616
+ * @param {{ session: string, view: boolean }} asker `session` "" for work with no session
541
617
  * @param {string} code
542
618
  * @param {string} [detail]
543
619
  * @param {string} [reason] why, in the plugin's words; the code's own by default
544
620
  */
545
- function hold(state, session, code, detail = "", reason = TOKEN_ERRORS[code]) {
621
+ function hold(state, asker, code, detail = "", reason = TOKEN_ERRORS[code]) {
546
622
  state.refusal = { code, detail, reason, until: now() + REFUSAL_HOLD_MS }
547
- const fields = { code, ...(detail ? { detail } : {}), ...(session ? { sessionID: session } : {}), holdMs: REFUSAL_HOLD_MS }
623
+ const who = asker.view ? { view: true } : asker.session ? { sessionID: asker.session } : {}
624
+ const fields = { code, ...(detail ? { detail } : {}), ...who, holdMs: REFUSAL_HOLD_MS }
548
625
  if (unlinkedRefusal(state.refusal)) {
549
626
  log?.warn?.(
550
- "Jelly has no memory token for the person speaking: they have not linked a Jelly account on this host; memory is off for this session, and the saved memory key is not used in its place",
627
+ asker.view
628
+ ? "Jelly has no memory token for the person who opened this view: they have not linked a Jelly account on this host; this call gets no credential, and the saved memory key is not used in its place"
629
+ : "Jelly has no memory token for the person speaking: they have not linked a Jelly account on this host; memory is off for this session, and the saved memory key is not used in its place",
551
630
  fields,
552
631
  )
553
632
  } else if (FALLBACK_CODES.includes(code)) {
@@ -584,10 +663,15 @@ export function createCredentials(input = {}) {
584
663
  }
585
664
 
586
665
  /**
587
- * Ask Jelly for a token for `state`: with `session` when there is one, else
588
- * as before. One call per state in flight.
666
+ * Ask Jelly for a token for `state`: with `session` when there is one (an
667
+ * engine session or a view call's speaker id), else as before. One call per
668
+ * state in flight.
669
+ *
670
+ * @param {any} state
671
+ * @param {string} session
672
+ * @param {boolean} [view] `session` is a view call's speaker id
589
673
  */
590
- function mint(state, session) {
674
+ function mint(state, session, view = false) {
591
675
  if (state.minting) return state.minting
592
676
  const flight = (async () => {
593
677
  const accessor = identity()
@@ -609,12 +693,12 @@ export function createCredentials(input = {}) {
609
693
  }
610
694
  const code = typeof member(error, "code") === "string" && TOKEN_ERRORS[error.code] ? error.code : "unavailable"
611
695
  const detail = typeof member(error, "detail") === "string" ? error.detail : ""
612
- throw hold(state, session, code, detail)
696
+ throw hold(state, { session, view }, code, detail)
613
697
  }
614
698
  const accessToken = usableToken(member(answer, "accessToken"))
615
699
  const expiresAt = Number(member(answer, "expiresAt"))
616
700
  if (!accessToken || !Number.isFinite(expiresAt)) {
617
- throw hold(state, session, "unavailable", "", "Jelly returned a malformed memory token")
701
+ throw hold(state, { session, view }, "unavailable", "", "Jelly returned a malformed memory token")
618
702
  }
619
703
  const entry = { accessToken, expiresAt }
620
704
  state.refusal = null
@@ -660,7 +744,7 @@ export function createCredentials(input = {}) {
660
744
  if (!refused) {
661
745
  if (fresh(asked.state.cached)) return asked.state.cached.accessToken
662
746
  try {
663
- return (await mint(asked.state, asked.session)).accessToken
747
+ return (await mint(asked.state, asked.session, asked.view)).accessToken
664
748
  } catch (error) {
665
749
  // The ask may have moved to the engine's state (a host older than members).
666
750
  refused = held(current().state)
@@ -687,13 +771,13 @@ export function createCredentials(input = {}) {
687
771
  async function refresh(rejected) {
688
772
  if (optionToken || !memoryResource()) return ""
689
773
  if (!rejected || rejected === secretToken()) return ""
690
- const { state, session } = current()
774
+ const { state, session, view } = current()
691
775
  if (held(state)) return ""
692
776
  if (state.cached?.accessToken === rejected) state.cached = null
693
777
  if (fresh(state.cached)) return state.cached.accessToken
694
778
  let next
695
779
  try {
696
- next = (await mint(state, session)).accessToken
780
+ next = (await mint(state, session, view)).accessToken
697
781
  } catch {
698
782
  return ""
699
783
  }
@@ -19,6 +19,15 @@
19
19
  * `fromJsonSchemaDocument`) refuses to register a schema that has one ("Patterns
20
20
  * may block validation and are disabled"). The handlers check ids themselves
21
21
  * (`ID_PATTERN`) and refuse a bad one in words.
22
+ *
23
+ * **Who asked (contract v1.5 §6.1).** Every method's input names the optional
24
+ * string `jellySpeaker`. A Jelly host of v1.5 or later (Jelly 0.3.3) sees it in
25
+ * the declared schema and fills it, per call, with a speaker id naming the
26
+ * person whose device made the call; the handler asks for that person's token
27
+ * with it and strips it before anything else reads the input
28
+ * (`src/views/rpc.js`). It is never `required`: a host before v1.5 sends
29
+ * nothing there, and the call is answered as before. A page cannot set it: the
30
+ * host refuses a page's input that carries it.
22
31
  */
23
32
 
24
33
  /** A memory, space, wiki or page id as the views pass it back: visible ASCII, bounded. */
@@ -38,7 +47,24 @@ export const LIST_MAX = 100
38
47
  /** The most commitments one answer lists (the Home card shows fewer). */
39
48
  export const COMMITMENTS_MAX = 100
40
49
 
41
- const empty = { type: "object", additionalProperties: false, properties: {} }
50
+ /** The input property a Jelly host of contract v1.5 or later fills with the caller's speaker id. */
51
+ export const SPEAKER_FIELD = "jellySpeaker"
52
+
53
+ /**
54
+ * A method's input: its own properties and the optional `jellySpeaker`, which
55
+ * is never required.
56
+ *
57
+ * @param {Record<string, object>} [properties]
58
+ * @param {string[]} [required]
59
+ */
60
+ const viewInput = (properties = {}, required = []) => ({
61
+ type: "object",
62
+ additionalProperties: false,
63
+ ...(required.length > 0 ? { required } : {}),
64
+ properties: { ...properties, [SPEAKER_FIELD]: { type: "string" } },
65
+ })
66
+
67
+ const empty = viewInput()
42
68
  const id = { type: "string", maxLength: 200 }
43
69
  const line = (max) => ({ type: "string", maxLength: max })
44
70
  const space = {
@@ -102,11 +128,9 @@ const spacesOutput = {
102
128
  },
103
129
  }
104
130
 
105
- const recentInput = {
106
- type: "object",
107
- additionalProperties: false,
108
- properties: { offset: { type: "integer", minimum: 0, maximum: RECENT_MAX_OFFSET, multipleOf: RECENT_PAGE } },
109
- }
131
+ const recentInput = viewInput({
132
+ offset: { type: "integer", minimum: 0, maximum: RECENT_MAX_OFFSET, multipleOf: RECENT_PAGE },
133
+ })
110
134
 
111
135
  const recentOutput = {
112
136
  type: "object",
@@ -178,14 +202,10 @@ const wikiReadOutput = {
178
202
  properties: { ref: id, content: line(PAGE_TEXT_CHARS), clipped: { type: "boolean" } },
179
203
  }
180
204
 
181
- const commitmentsInput = {
182
- type: "object",
183
- additionalProperties: false,
184
- properties: {
185
- /** open (default): what is still to do; closed: done or cancelled, newest first. */
186
- state: { type: "string", enum: ["open", "closed"] },
187
- },
188
- }
205
+ const commitmentsInput = viewInput({
206
+ /** open (default): what is still to do; closed: done or cancelled, newest first. */
207
+ state: { type: "string", enum: ["open", "closed"] },
208
+ })
189
209
 
190
210
  const commitmentsOutput = {
191
211
  type: "object",
@@ -247,24 +267,14 @@ export const VIEW_METHODS = Object.freeze([
247
267
  name: "wiki.pages",
248
268
  label: "list a wiki's pages",
249
269
  permission: "mem_wiki",
250
- input: {
251
- type: "object",
252
- additionalProperties: false,
253
- required: ["wiki"],
254
- properties: { wiki: id },
255
- },
270
+ input: viewInput({ wiki: id }, ["wiki"]),
256
271
  output: wikiPagesOutput,
257
272
  },
258
273
  {
259
274
  name: "wiki.read",
260
275
  label: "read a wiki page",
261
276
  permission: "mem_wiki",
262
- input: {
263
- type: "object",
264
- additionalProperties: false,
265
- required: ["wiki", "ref"],
266
- properties: { wiki: id, ref: id },
267
- },
277
+ input: viewInput({ wiki: id, ref: id }, ["wiki", "ref"]),
268
278
  output: wikiReadOutput,
269
279
  },
270
280
  {
package/src/views/rpc.js CHANGED
@@ -1,4 +1,4 @@
1
- import { originOf, PACKAGE_NAME, SOURCES } from "../credentials.js"
1
+ import { UNLINKED_SENTENCE, asView, inView, isUnlinked, originOf, PACKAGE_NAME, SOURCES } from "../credentials.js"
2
2
  import { dayIn, dueDay, filterItems, formatDay, formatDue } from "../records.js"
3
3
  import { isRecordsWikiName } from "../tools/knowledge.js"
4
4
  import { oneLine } from "../util.js"
@@ -10,6 +10,7 @@ import {
10
10
  PAGE_TEXT_CHARS,
11
11
  RECENT_MAX_OFFSET,
12
12
  RECENT_PAGE,
13
+ SPEAKER_FIELD,
13
14
  VIEW_ERROR,
14
15
  VIEW_METHODS,
15
16
  } from "./contracts.js"
@@ -34,8 +35,20 @@ import {
34
35
  * Jelly checks each call's input and answer against the declared schemas; the
35
36
  * handlers check the input again and clip every answer to them, so a long row
36
37
  * is shortened here rather than refused there.
38
+ *
39
+ * **Whose memory (0.8.3, contract v1.5 §6.1).** A Jelly host of v1.5 or later
40
+ * sends each call a speaker id in `jellySpeaker`, naming the person whose
41
+ * device made it. The handler takes it out of the input before the read sees
42
+ * the input, and runs the read in `asView(id)`: every request of that call
43
+ * carries that person's own token, asked for the call and dropped with it
44
+ * (`src/credentials.js`). A person who has not linked a Jelly account on this
45
+ * host gets `VIEW_UNLINKED_SENTENCE` and the call sends nothing. With no id (a
46
+ * host before v1.5) the call reads as it did in 0.8.2.
37
47
  */
38
48
 
49
+ /** What a view says to a person who opened it without a Jelly account linked on this host. */
50
+ export const VIEW_UNLINKED_SENTENCE = "Memory is unavailable: you have not linked a Jelly account on this host."
51
+
39
52
  /** Primary agents read per call; the rest are left out. */
40
53
  const MAX_AGENTS = 4
41
54
  /** The engine's agent list is read again after this long. */
@@ -151,9 +164,21 @@ export function createViewReads({ runtime, agents = async () => [] }) {
151
164
  return scopes
152
165
  }
153
166
 
167
+ /**
168
+ * Why memory is unavailable for this call, or "". In a view call that names
169
+ * its speaker, Jelly is asked for that person's token first (`availability`),
170
+ * so an unlinked person is known before any request is sent; without one
171
+ * this knows only what Jelly already answered, as in 0.8.2.
172
+ */
173
+ async function unavailableNow() {
174
+ let reason = runtime.unavailable?.() ?? ""
175
+ if (!reason && inView() && typeof runtime.availability === "function") reason = await runtime.availability()
176
+ return viewWords(reason)
177
+ }
178
+
154
179
  /** Refuse before any request while memory is unavailable. */
155
- function available() {
156
- const reason = runtime.unavailable?.() ?? ""
180
+ async function available() {
181
+ const reason = await unavailableNow()
157
182
  if (reason) refuse(reason)
158
183
  }
159
184
 
@@ -172,7 +197,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
172
197
  health: "unknown",
173
198
  ...(address ? { address: clip(address, 300) } : {}),
174
199
  }
175
- const reason = runtime.unavailable?.() ?? ""
200
+ const reason = await unavailableNow()
176
201
  if (reason) return { connected: false, reason: clip(reason, 400), ...credentialState(), ...base }
177
202
  let scopes
178
203
  try {
@@ -182,7 +207,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
182
207
  // Asked of the credential after the request, so a refusal it met shows.
183
208
  return {
184
209
  connected: false,
185
- reason: clip(failureWords(error), 400),
210
+ reason: clip(viewFailureWords(error), 400),
186
211
  ...credentialState(),
187
212
  ...base,
188
213
  }
@@ -222,7 +247,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
222
247
  }
223
248
 
224
249
  async function spacesList() {
225
- available()
250
+ await available()
226
251
  if (!runtime.control) return { spaces: [{ ...spaceOf(null), role: "owner" }] }
227
252
  const spaces = await runtime.control.listSpaces({ userId: config.user })
228
253
  return {
@@ -245,7 +270,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
245
270
  * which is as deep as the screen goes (two pages, `RECENT_MAX_OFFSET`).
246
271
  */
247
272
  async function recent(input) {
248
- available()
273
+ await available()
249
274
  const offset = input?.offset ?? 0
250
275
  if (typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > RECENT_MAX_OFFSET || offset % RECENT_PAGE !== 0) {
251
276
  refuse(`offset is a multiple of ${RECENT_PAGE} from 0 to ${RECENT_MAX_OFFSET}`)
@@ -284,7 +309,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
284
309
  }
285
310
 
286
311
  async function wikiList() {
287
- available()
312
+ await available()
288
313
  const scope = await knowledgeScope()
289
314
  const data = await backend.listWiki({ scope })
290
315
  return {
@@ -312,7 +337,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
312
337
  }
313
338
 
314
339
  async function wikiPages(input) {
315
- available()
340
+ await available()
316
341
  const scope = await knowledgeScope()
317
342
  const wiki = await visibleWiki(scope, input?.wiki)
318
343
  const data = await backend.listWikiPages({ scope, wikiID: wiki })
@@ -325,7 +350,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
325
350
  }
326
351
 
327
352
  async function wikiRead(input) {
328
- available()
353
+ await available()
329
354
  const scope = await knowledgeScope()
330
355
  const wiki = await visibleWiki(scope, input?.wiki)
331
356
  const ref = idOf(input?.ref)
@@ -344,7 +369,7 @@ export function createViewReads({ runtime, agents = async () => [] }) {
344
369
  * space is read; a view can change nothing (closing one opens the agent).
345
370
  */
346
371
  async function commitmentsList(input) {
347
- available()
372
+ await available()
348
373
  const state = input?.state === "closed" ? "closed" : "open"
349
374
  const [first] = await personalScopes()
350
375
  const records = (await runtime.records.read(first.scope)).records
@@ -388,6 +413,21 @@ export function createViewReads({ runtime, agents = async () => [] }) {
388
413
  }
389
414
  }
390
415
 
416
+ /**
417
+ * The unlinked speaker's sentence in a view's own words when the call names
418
+ * its speaker; any other reason unchanged.
419
+ *
420
+ * @param {string} reason
421
+ */
422
+ function viewWords(reason) {
423
+ return reason === UNLINKED_SENTENCE && inView() ? VIEW_UNLINKED_SENTENCE : reason
424
+ }
425
+
426
+ /** A failed read in words; a view call's unlinked speaker in the view's words. */
427
+ function viewFailureWords(error) {
428
+ return isUnlinked(error) && inView() ? VIEW_UNLINKED_SENTENCE : failureWords(error)
429
+ }
430
+
391
431
  /**
392
432
  * A failed read in words a person can act on; the detail goes to the log.
393
433
  * `status` is the HTTP status, 0 when memory could not be reached and 408 for
@@ -425,6 +465,19 @@ export function engineAgents(ctx, now = Date.now) {
425
465
  }
426
466
  }
427
467
 
468
+ /**
469
+ * A view call's input split into the speaker id the host put in `jellySpeaker`
470
+ * (`undefined` when there is none) and the page's own input without it: the
471
+ * only input a read, a request or a log ever sees.
472
+ *
473
+ * @param {unknown} input
474
+ * @returns {{ speaker: unknown, rest: Record<string, unknown> }}
475
+ */
476
+ export function splitSpeaker(input) {
477
+ const { [SPEAKER_FIELD]: speaker, ...rest } = input && typeof input === "object" && !Array.isArray(input) ? input : {}
478
+ return { speaker, rest }
479
+ }
480
+
428
481
  /**
429
482
  * Register the views' RPC with the engine, under the package name: the only id
430
483
  * Jelly calls for this package's views. A host without `ctx.rpc` (OpenCode
@@ -434,6 +487,10 @@ export function engineAgents(ctx, now = Date.now) {
434
487
  * words; on the pinned engine a thrown error would reach it only as "RPC call
435
488
  * failed".
436
489
  *
490
+ * `jellySpeaker` is taken out of the input here, before the read, the log or a
491
+ * request can see it, and the read runs as that speaker (`asView`); a call
492
+ * without it runs exactly as before.
493
+ *
437
494
  * @param {any} ctx
438
495
  * @param {any} runtime
439
496
  */
@@ -445,13 +502,17 @@ export async function registerViewRpc(ctx, runtime) {
445
502
  for (const method of VIEW_METHODS) {
446
503
  methods[method.name] = { input: method.input, output: method.output, errors: { [VIEW_ERROR]: { type: "object" } } }
447
504
  handlers[method.name] = async (input, call) => {
448
- try {
449
- return await reads[method.name](input ?? {})
450
- } catch (error) {
451
- if (!(error instanceof ViewRefusal)) runtime.log?.warn?.(`view read ${method.name} failed`, error)
452
- const words = error instanceof ViewRefusal ? error.message : failureWords(error)
453
- return call.error(VIEW_ERROR, clip(words, 200), {})
505
+ const { speaker, rest } = splitSpeaker(input)
506
+ const read = async () => {
507
+ try {
508
+ return await reads[method.name](rest)
509
+ } catch (error) {
510
+ if (!(error instanceof ViewRefusal)) runtime.log?.warn?.(`view read ${method.name} failed`, error)
511
+ const words = error instanceof ViewRefusal ? error.message : viewFailureWords(error)
512
+ return call.error(VIEW_ERROR, clip(words, 200), {})
513
+ }
454
514
  }
515
+ return typeof speaker === "string" ? asView(speaker, read) : read()
455
516
  }
456
517
  }
457
518
  return ctx.rpc.register({ id: PACKAGE_NAME, events: {}, methods }, handlers)