@joe-broadhead/opencode-mem 0.8.1 → 0.8.2

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.
@@ -5,31 +5,76 @@
5
5
  *
6
6
  * 1. the `token` option or `MEMORY_TOKEN` (a memory key);
7
7
  * 2. Jelly's identity accessor, `globalThis[Symbol.for("jelly.identity")]`,
8
- * when it advertises the `memory` resource: `token("memory")` mints a
9
- * ten-minute resource token, cached here until 60 s before it expires,
10
- * one request in flight at a time, and asked for again once when the
11
- * gateway answers 401;
8
+ * when it advertises the `memory` resource: a ten-minute resource token,
9
+ * asked for **per OpenCode session and again at each user turn** (below),
10
+ * cached until 60 s before it expires, one request in flight per session,
11
+ * and asked for again once when the gateway answers 401;
12
12
  * 3. Jelly's plugin-secrets accessor,
13
13
  * `globalThis[Symbol.for("jelly.plugin-secrets")].get(PACKAGE_NAME, "token")`:
14
14
  * the key a person pasted into the plugin's settings.
15
15
  *
16
+ * **A token per session (0.8.2, contract v1.3 §6).** On a Jelly host with
17
+ * members, several people can talk to one agent, and a token names one
18
+ * person. So work done for a session (a captured turn, a tool call, the pinned
19
+ * block, a spooled entry's replay) asks `token("memory", { session })` with
20
+ * that session's id and uses that session's token only. The session comes
21
+ * from `asSession(sessionID, fn)`, which the hooks, the tools, the commands,
22
+ * the capture and the spool wrap their work in; `fn` and everything it awaits
23
+ * see that session. The tokens are kept per session, for at most
24
+ * `SESSION_CACHE_MAX` sessions (the least recently used goes first), and a
25
+ * session is dropped when OpenCode deletes it (`forget`).
26
+ *
27
+ * **Asked again at each user turn.** On a shared agent a second person can
28
+ * speak in a session someone else started. So at each new user message (the
29
+ * `prompt` hook and the admission event, `userTurn`) the session's token and
30
+ * its refusal hold are dropped, and the turn's first memory call asks again;
31
+ * the host keeps tokens per person, so this is cheap. The previous turn's
32
+ * capture still uses the previous turn's token (`asSession`'s `turn`). A turn
33
+ * with no user message (a wake, a routine) keeps the cached token: the host
34
+ * decides who it speaks for, and the token is replaced 60 s before it expires.
35
+ * A spooled entry records the account its token named and is not replayed
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.
40
+ *
41
+ * A host older than members (Jelly 0.3.2) refuses `{ session }` as options it
42
+ * does not know (`invalid_target`, detail `invalid_cnf_jwk`; the plugin sends
43
+ * no `cnf`). The plugin then stops sending `session` in this engine and asks
44
+ * as before: one token for the engine, which on such a host is its owner's.
45
+ * An accessor that ignores `session` answers as before too.
46
+ *
16
47
  * **When Jelly refuses the token.** `token("memory")` rejects with one of four
17
48
  * codes (Jelly's host maps Jelly ID's 400 to `invalid_target`, 401 to
18
49
  * `not_enrolled`, 403 to `access_denied`, and anything else, a 503 included,
19
- * to `unavailable`, and holds each answer for 30 s):
50
+ * to `unavailable`, and holds each answer for 30 s). Each refusal is held here
51
+ * for `REFUSAL_HOLD_MS` (the host's own hold), per session, so Jelly is not
52
+ * asked on every request; after it, Jelly is asked again.
20
53
  *
21
- * - `invalid_target`, `not_enrolled`, `unavailable`: the request uses the
22
- * pasted key instead, when one is saved. The refusal is held here for
23
- * `REFUSAL_HOLD_MS` (the host's own hold), so Jelly is not asked on every
24
- * request; after it, Jelly is asked again. With no key saved, the request
25
- * fails with one sentence saying the agent's Jelly sign-in cannot be used for
26
- * memory and no memory key is saved.
54
+ * - `not_enrolled` with the detail `not_signed_in`: the person speaking in the
55
+ * session has not linked a Jelly account on this host. That session uses
56
+ * **no** credential: not the pasted key, which belongs to whoever pasted it,
57
+ * and not another session's token. Nothing is captured for it, and each tool
58
+ * answers `UNLINKED_SENTENCE`. Other sessions are not affected.
59
+ * - `invalid_target`, `not_enrolled` (with no such detail), `unavailable`: the
60
+ * request uses the pasted key instead, when one is saved. With no key saved,
61
+ * the request fails with one sentence saying the agent's Jelly sign-in
62
+ * cannot be used for memory and no memory key is saved.
27
63
  * - `access_denied`: no fallback. Jelly says the account behind this agent is
28
64
  * disabled or marked for deletion; writing on with a pasted key would get
29
65
  * round the switch that stops that account, so the request fails instead.
30
66
  *
31
- * Accepted risk: a person whose Jelly sign-in and pasted key belong to two
32
- * different memory users writes as the key's user while a fallback lasts.
67
+ * An accessor that throws something with no known `code` counts as
68
+ * `unavailable`, as before.
69
+ *
70
+ * Accepted risk: when Jelly refuses a session's token with a code that falls
71
+ * back (`invalid_target`, `unavailable`, or `not_enrolled` without
72
+ * `not_signed_in`), that session writes as the pasted key's memory user while
73
+ * the hold lasts, whoever is speaking in it. The key is the person's who
74
+ * pasted it. `not_signed_in`, the refusal that says the speaker is someone
75
+ * with no linked account, never falls back. The plugin relies on the accessor
76
+ * passing the host's `detail` through: an accessor that drops it makes an
77
+ * unlinked speaker's refusal look like a plain `not_enrolled`, which falls back.
33
78
  *
34
79
  * The gateway origin is the `controlURL` option, else the identity accessor's
35
80
  * `memory` resource `url` (see `followOrigin`).
@@ -39,6 +84,7 @@
39
84
  * has the wrong shape counts as absent. A token is held in memory only: it is
40
85
  * never logged, spooled, or written to a file.
41
86
  */
87
+ import { AsyncLocalStorage } from "node:async_hooks"
42
88
  import { codedMessage, credentialFailure } from "./errors.js"
43
89
 
44
90
  export const PACKAGE_NAME = "@joe-broadhead/opencode-mem"
@@ -56,6 +102,73 @@ export const REFRESH_MARGIN_MS = 60_000
56
102
  * Jelly's `backend/host/src/auth/resource-tokens.ts`).
57
103
  */
58
104
  export const REFUSAL_HOLD_MS = 30_000
105
+ /** Sessions whose tokens and refusals are kept; the least recently used goes first. */
106
+ export const SESSION_CACHE_MAX = 64
107
+ /** The `detail` Jelly gives `not_enrolled` when the person speaking has no Jelly account linked on the host. */
108
+ export const NOT_SIGNED_IN = "not_signed_in"
109
+ /** The `detail` a host older than members gives options it does not know, `session` included. */
110
+ const INVALID_CNF_JWK = "invalid_cnf_jwk"
111
+ /** An engine session's id as the accessor carries it (contract v1.3 §6). */
112
+ const SESSION_PATTERN = /^[A-Za-z0-9_-]{1,128}$/
113
+ /** What a tool, a command and `mem_status` answer in a session whose speaker has not linked a Jelly account. */
114
+ export const UNLINKED_SENTENCE =
115
+ "Memory isn't available in this chat because the person speaking hasn't linked their Jelly account on this host."
116
+
117
+ /** The session the current work is done for, and the turn when the work belongs to one: `{ session, turn }`. */
118
+ const sessionScope = new AsyncLocalStorage()
119
+
120
+ /** A session id the accessor accepts, or "" (work with no session). */
121
+ function sessionKey(value) {
122
+ return typeof value === "string" && SESSION_PATTERN.test(value) ? value : ""
123
+ }
124
+
125
+ /**
126
+ * Run `fn` for one OpenCode session: every credential it and what it awaits
127
+ * ask for is that session's. A missing or malformed id runs `fn` as work with
128
+ * no session, which also stops an outer session from leaking in.
129
+ *
130
+ * `turn`, the id of the user message that opened a turn, is given by work
131
+ * that belongs to one turn whatever came after it: the capture of that turn.
132
+ * It then uses that turn's token even when a newer user message has arrived
133
+ * (see `userTurn`).
134
+ *
135
+ * @template T
136
+ * @param {unknown} sessionID
137
+ * @param {() => T} fn
138
+ * @param {unknown} [turn]
139
+ * @returns {T}
140
+ */
141
+ export function asSession(sessionID, fn, turn) {
142
+ return sessionScope.run({ session: sessionKey(sessionID), turn: typeof turn === "string" ? turn : "" }, fn)
143
+ }
144
+
145
+ /** The session the current work is done for, or "" for none. */
146
+ export function currentSession() {
147
+ return sessionScope.getStore()?.session ?? ""
148
+ }
149
+
150
+ /** The turn the current work belongs to, or "" when it is the session's latest. */
151
+ function currentTurn() {
152
+ return sessionScope.getStore()?.turn ?? ""
153
+ }
154
+
155
+ /**
156
+ * The account a Jelly token names (`sub`, contract §4), read without verifying
157
+ * it: for the plugin's own bookkeeping only, never for a decision the gateway
158
+ * makes. "" for anything that is not a Jelly token.
159
+ *
160
+ * @param {string} token
161
+ */
162
+ export function tokenSubject(token) {
163
+ const parts = typeof token === "string" ? token.split(".") : []
164
+ if (parts.length !== 3) return ""
165
+ try {
166
+ const sub = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"))?.sub
167
+ return typeof sub === "string" && /^acc_[A-Za-z0-9._:-]{1,123}$/.test(sub) ? sub : ""
168
+ } catch {
169
+ return ""
170
+ }
171
+ }
59
172
  /** The longest value Jelly lets a setting carry (`PLUGIN_SETTING_MAX_LENGTH`). */
60
173
  const MAX_TOKEN_CHARS = 8192
61
174
  /** Visible ASCII only: a bearer goes into an HTTP header. */
@@ -97,6 +210,32 @@ export class CredentialError extends Error {
97
210
  this.what = message
98
211
  this.next = failure.next
99
212
  }
213
+
214
+ /** The person speaking has not linked a Jelly account on this host: nothing for this session is sent or kept. */
215
+ get unlinked() {
216
+ return this.code === NOT_SIGNED_IN
217
+ }
218
+ }
219
+
220
+ /** The code a request carries when its session's speaker has no Jelly account linked on this host. */
221
+ const UNLINKED_CODE = credentialFailure(NOT_SIGNED_IN).code
222
+
223
+ /**
224
+ * True when an error says the person speaking has not linked a Jelly account
225
+ * on this host: the CredentialError itself, or a gateway or control error
226
+ * that wrapped it (`BackendError` and `ControlError` keep the credential's
227
+ * code, `MEMORY_NOT_LINKED`), or one with it as its `cause`.
228
+ *
229
+ * @param {unknown} error
230
+ */
231
+ export function isUnlinked(error) {
232
+ let current = /** @type {any} */ (error)
233
+ for (let depth = 0; depth < 5 && current && typeof current === "object"; depth += 1) {
234
+ if (current instanceof CredentialError) return current.unlinked
235
+ if (current.errorCode === UNLINKED_CODE) return true
236
+ current = current.cause
237
+ }
238
+ return false
100
239
  }
101
240
 
102
241
  /** Read one global; a getter that throws or a non-object counts as absent. */
@@ -157,12 +296,116 @@ export function createCredentials(input = {}) {
157
296
  const holder = input.holder ?? globalThis
158
297
  const now = typeof input.now === "function" ? input.now : Date.now
159
298
  const log = input.log ?? null
160
- /** The last Jelly token: `{ accessToken, expiresAt }`. Memory only. */
161
- let cached = null
162
- /** One `token("memory")` call at a time. */
163
- let minting = null
164
- /** The last refusal from `token("memory")`: `{ code, until }`, believed until `until`. */
165
- let refusal = null
299
+ /**
300
+ * What Jelly last answered for one asker: `cached` the last token
301
+ * (`{ accessToken, expiresAt }`, memory only), `minting` the one
302
+ * `token("memory")` call in flight, `refusal` the last refusal
303
+ * (`{ code, detail, reason, until }`, believed until `until`).
304
+ */
305
+ const newState = () => ({ cached: null, minting: null, refusal: null })
306
+ /** Work with no session: today's single ask. Never evicted. */
307
+ const engine = newState()
308
+ /**
309
+ * Session id -> `{ turn, state, pending, previous }`, least recently used
310
+ * first. `state` belongs to the user message `turn`; `pending` is a newer
311
+ * user message not yet rotated in (see `userTurn`); `previous` is the turn
312
+ * before, `{ turn, state }`, kept for that turn's capture.
313
+ */
314
+ const sessions = new Map()
315
+ /** Ids for user messages that came without one. */
316
+ let anonymousTurns = 0
317
+ /**
318
+ * False once the accessor refused `{ session }` as options it does not know
319
+ * (a host older than members): from then on every session asks as `engine`.
320
+ */
321
+ let sessionAsks = true
322
+
323
+ function newEntry() {
324
+ return { turn: "", state: newState(), pending: null, previous: null }
325
+ }
326
+
327
+ /** Take the session's entry, newest in the LRU order, creating it. */
328
+ function entryOf(session) {
329
+ let entry = sessions.get(session)
330
+ if (entry) sessions.delete(session)
331
+ else entry = newEntry()
332
+ sessions.set(session, entry)
333
+ while (sessions.size > SESSION_CACHE_MAX) sessions.delete(sessions.keys().next().value)
334
+ return entry
335
+ }
336
+
337
+ /**
338
+ * The state for work of `turn` ("" for the session's latest). A pending
339
+ * newer user message is rotated in here, lazily, by work that is not tied to
340
+ * an older turn; `rotate: false` only reads, as rotating would.
341
+ */
342
+ function stateIn(entry, turn, rotate) {
343
+ if (turn && turn === entry.turn) return entry.state
344
+ if (turn && entry.previous && turn === entry.previous.turn) return entry.previous.state
345
+ if (entry.pending === null) return entry.state
346
+ if (!rotate) return newState()
347
+ entry.previous = { turn: entry.turn, state: entry.state }
348
+ entry.state = newState()
349
+ entry.turn = entry.pending
350
+ entry.pending = null
351
+ return entry.state
352
+ }
353
+
354
+ /** The state the current work uses, and the session it asks for ("" for none). */
355
+ function current() {
356
+ const session = sessionAsks ? currentSession() : ""
357
+ if (!session) return { state: engine, session: "" }
358
+ return { state: stateIn(entryOf(session), currentTurn(), true), session }
359
+ }
360
+
361
+ /** The current work's state without creating, reordering or rotating one: for reads such as `source()`. */
362
+ function peek() {
363
+ const session = sessionAsks ? currentSession() : ""
364
+ if (!session) return engine
365
+ const entry = sessions.get(session)
366
+ return entry ? stateIn(entry, currentTurn(), false) : newState()
367
+ }
368
+
369
+ /**
370
+ * A new user message in a session: the person speaking may have changed,
371
+ * so the session's token and its refusal hold are dropped, and the turn's
372
+ * first memory call asks Jelly again (the host keeps tokens per person, so
373
+ * this is cheap). The drop is lazy: the previous turn's capture, which may
374
+ * run after this message arrived, still uses the previous turn's token, and
375
+ * every other use rotates to the new turn. The same message reported twice
376
+ * (by the prompt hook and the admission event) drops once.
377
+ *
378
+ * A turn with no user message (a wake or a routine) keeps the cached token:
379
+ * the host decides who it speaks for, the token is replaced 60 s before it
380
+ * expires at the latest, and a new user message drops it at once.
381
+ *
382
+ * @param {unknown} sessionID
383
+ * @param {unknown} [messageID]
384
+ */
385
+ function userTurn(sessionID, messageID) {
386
+ const session = sessionKey(sessionID)
387
+ if (!session) return
388
+ const id = typeof messageID === "string" && messageID ? messageID : `anonymous-${(anonymousTurns += 1)}`
389
+ const entry = entryOf(session)
390
+ if (id === entry.turn || id === entry.pending) return
391
+ entry.pending = id
392
+ }
393
+
394
+ /** Drop what is kept for a session: OpenCode deleted it. */
395
+ function forget(sessionID) {
396
+ const session = sessionKey(sessionID)
397
+ if (session) sessions.delete(session)
398
+ }
399
+
400
+ /**
401
+ * The account the current work's cached Jelly token names, or "" (none
402
+ * cached, a pasted key, or the option). Spooled entries record it.
403
+ */
404
+ function subject() {
405
+ if (optionToken || !memoryResource()) return ""
406
+ const cached = peek().cached
407
+ return cached && fresh(cached) ? tokenSubject(cached.accessToken) : ""
408
+ }
166
409
 
167
410
  function identity() {
168
411
  const accessor = readGlobal(holder, IDENTITY_SYMBOL)
@@ -207,26 +450,34 @@ export function createCredentials(input = {}) {
207
450
  }
208
451
  }
209
452
 
210
- /** The refusal Jelly gave within the hold, or null. */
211
- function held() {
212
- if (refusal && refusal.until > now()) return refusal
213
- refusal = null
453
+ /** The refusal Jelly gave this state within the hold, or null. */
454
+ function held(state) {
455
+ if (state.refusal && state.refusal.until > now()) return state.refusal
456
+ state.refusal = null
214
457
  return null
215
458
  }
216
459
 
460
+ /** The refusal says the person speaking has no Jelly account linked on this host. */
461
+ function unlinkedRefusal(refused) {
462
+ return Boolean(refused && refused.code === "not_enrolled" && refused.detail === NOT_SIGNED_IN)
463
+ }
464
+
217
465
  /**
218
- * Which source supplies the bearer now, or "" when none does.
466
+ * Which source supplies the bearer now, for the current session, or "" when
467
+ * none does.
219
468
  *
220
469
  * During a hold after a refusal that falls back, that is the pasted key when
221
- * one is saved. With no key, or after `access_denied`, it stays the Jelly
222
- * sign-in: the only candidate, whose requests fail with the reason, so a
223
- * finished turn is spooled for later rather than dropped as unavailable.
470
+ * one is saved. With no key, after `access_denied`, or after
471
+ * `not_signed_in`, it stays the Jelly sign-in: the only candidate, whose
472
+ * requests fail with the reason.
224
473
  */
225
474
  function source() {
226
475
  if (optionToken) return SOURCES.option
227
476
  if (memoryResource()) {
228
- const refused = held()
229
- if (refused && FALLBACK_CODES.includes(refused.code) && secretToken()) return SOURCES.secret
477
+ const refused = held(peek())
478
+ if (refused && FALLBACK_CODES.includes(refused.code) && !unlinkedRefusal(refused) && secretToken()) {
479
+ return SOURCES.secret
480
+ }
230
481
  return SOURCES.identity
231
482
  }
232
483
  if (secretToken()) return SOURCES.secret
@@ -235,12 +486,36 @@ export function createCredentials(input = {}) {
235
486
 
236
487
  /**
237
488
  * The source in use and, during a hold, the code Jelly refused with ("" when
238
- * none), for `mem_status`.
489
+ * none; `not_signed_in` for an unlinked speaker), for `mem_status`.
239
490
  */
240
491
  function describe() {
241
- const current = source()
242
- const refused = current === SOURCES.option ? null : memoryResource() ? held() : null
243
- return { source: current, refused: refused?.code ?? "" }
492
+ const source_ = source()
493
+ const refused = source_ === SOURCES.option ? null : memoryResource() ? held(peek()) : null
494
+ return { source: source_, refused: unlinkedRefusal(refused) ? NOT_SIGNED_IN : (refused?.code ?? "") }
495
+ }
496
+
497
+ /**
498
+ * True while Jelly's last answer for the current session, within the hold,
499
+ * is that the person speaking has no Jelly account linked on this host.
500
+ */
501
+ function unlinked() {
502
+ if (optionToken || !memoryResource()) return false
503
+ return unlinkedRefusal(held(peek()))
504
+ }
505
+
506
+ /**
507
+ * Learn whether the current session's speaker can have a token, asking Jelly
508
+ * when nothing is cached or held for the session. Never throws; the answer
509
+ * is `unlinked()`. Without a Jelly sign-in in use this asks nothing.
510
+ */
511
+ async function check() {
512
+ if (source() !== SOURCES.identity) return false
513
+ try {
514
+ await bearer()
515
+ } catch {
516
+ /* the refusal, if any, is held */
517
+ }
518
+ return unlinked()
244
519
  }
245
520
 
246
521
  /** Jelly's core plugin has published at least one accessor in this engine. */
@@ -258,68 +533,110 @@ export function createCredentials(input = {}) {
258
533
  }
259
534
 
260
535
  /**
261
- * Hold a refusal for `REFUSAL_HOLD_MS` and log it: the code only, never a
262
- * token or the accessor's words. Returns the error for this request.
536
+ * Hold a refusal for `REFUSAL_HOLD_MS` and log it: the code and detail only,
537
+ * never a token or the accessor's words. Returns the error for this request.
263
538
  *
539
+ * @param {{ refusal: any }} state
540
+ * @param {string} session "" for work with no session
264
541
  * @param {string} code
542
+ * @param {string} [detail]
265
543
  * @param {string} [reason] why, in the plugin's words; the code's own by default
266
544
  */
267
- function hold(code, reason = TOKEN_ERRORS[code]) {
268
- refusal = { code, reason, until: now() + REFUSAL_HOLD_MS }
269
- const message = FALLBACK_CODES.includes(code)
270
- ? "Jelly refused a memory token; the saved memory key, if any, is used until Jelly is asked again"
271
- : "Jelly refused a memory token; the saved memory key is not used in its place"
272
- log?.warn?.(message, { code, holdMs: REFUSAL_HOLD_MS, keySaved: Boolean(secretToken()) })
273
- return refusalError(refusal)
545
+ function hold(state, session, code, detail = "", reason = TOKEN_ERRORS[code]) {
546
+ state.refusal = { code, detail, reason, until: now() + REFUSAL_HOLD_MS }
547
+ const fields = { code, ...(detail ? { detail } : {}), ...(session ? { sessionID: session } : {}), holdMs: REFUSAL_HOLD_MS }
548
+ if (unlinkedRefusal(state.refusal)) {
549
+ 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",
551
+ fields,
552
+ )
553
+ } else if (FALLBACK_CODES.includes(code)) {
554
+ log?.warn?.("Jelly refused a memory token; the saved memory key, if any, is used until Jelly is asked again", {
555
+ ...fields,
556
+ keySaved: Boolean(secretToken()),
557
+ })
558
+ } else {
559
+ log?.warn?.("Jelly refused a memory token; the saved memory key is not used in its place", {
560
+ ...fields,
561
+ keySaved: Boolean(secretToken()),
562
+ })
563
+ }
564
+ return refusalError(state.refusal)
274
565
  }
275
566
 
276
567
  /** The error for a refusal: the contract's code and the plugin's words, never the accessor's own. */
277
- function refusalError({ code, reason }) {
568
+ function refusalError({ code, detail, reason }) {
569
+ if (code === "not_enrolled" && detail === NOT_SIGNED_IN) {
570
+ return new CredentialError(
571
+ "the person speaking in this chat hasn't linked their Jelly account on this host (not_signed_in); a saved memory key is not used in its place",
572
+ NOT_SIGNED_IN,
573
+ )
574
+ }
278
575
  if (code === "access_denied") {
279
576
  return new CredentialError(`${reason} (${code}); a saved memory key is not used in its place`, code)
280
577
  }
281
578
  return new CredentialError(`${reason} (${code})`, code)
282
579
  }
283
580
 
284
- async function mint() {
285
- if (minting) return minting
286
- minting = (async () => {
581
+ /** The accessor did not know the `session` option: a host older than members. */
582
+ function sessionUnknown(error) {
583
+ return member(error, "code") === "invalid_target" && member(error, "detail") === INVALID_CNF_JWK
584
+ }
585
+
586
+ /**
587
+ * Ask Jelly for a token for `state`: with `session` when there is one, else
588
+ * as before. One call per state in flight.
589
+ */
590
+ function mint(state, session) {
591
+ if (state.minting) return state.minting
592
+ const flight = (async () => {
287
593
  const accessor = identity()
288
594
  if (!accessor) throw new CredentialError("the Jelly sign-in is no longer available", "unavailable")
289
595
  let answer
290
596
  try {
291
- answer = await accessor.token(MEMORY_RESOURCE)
597
+ // No second argument without a session: exactly the ask of 0.8.1.
598
+ answer = session ? await accessor.token(MEMORY_RESOURCE, { session }) : await accessor.token(MEMORY_RESOURCE)
292
599
  } catch (error) {
600
+ if (session && sessionUnknown(error)) {
601
+ // A host older than members: it has one person to name, its owner.
602
+ // Ask as before, for the whole engine, from now on.
603
+ if (sessionAsks) {
604
+ sessionAsks = false
605
+ sessions.clear()
606
+ log?.info?.("this Jelly host does not take a session with a memory token; one token is used for the engine, as before")
607
+ }
608
+ return mint(engine, "")
609
+ }
293
610
  const code = typeof member(error, "code") === "string" && TOKEN_ERRORS[error.code] ? error.code : "unavailable"
294
- throw hold(code)
611
+ const detail = typeof member(error, "detail") === "string" ? error.detail : ""
612
+ throw hold(state, session, code, detail)
295
613
  }
296
614
  const accessToken = usableToken(member(answer, "accessToken"))
297
615
  const expiresAt = Number(member(answer, "expiresAt"))
298
616
  if (!accessToken || !Number.isFinite(expiresAt)) {
299
- throw hold("unavailable", "Jelly returned a malformed memory token")
617
+ throw hold(state, session, "unavailable", "", "Jelly returned a malformed memory token")
300
618
  }
301
619
  const entry = { accessToken, expiresAt }
302
- refusal = null
620
+ state.refusal = null
303
621
  // A token already inside the refresh margin is used for this request
304
622
  // but not kept: the next request asks again.
305
- cached = fresh(entry) ? entry : null
623
+ state.cached = fresh(entry) ? entry : null
306
624
  return entry
307
625
  })()
308
- try {
309
- return await minting
310
- } finally {
311
- minting = null
312
- }
626
+ state.minting = flight
627
+ return flight.finally(() => {
628
+ if (state.minting === flight) state.minting = null
629
+ })
313
630
  }
314
631
 
315
632
  /**
316
633
  * The pasted key for a request Jelly refused with a code that falls back, or
317
634
  * a CredentialError saying what is missing. `status` follows the code (503
318
635
  * for `unavailable`, else 401), so the spool and the bootstrap classify it as
319
- * before.
636
+ * before. An unlinked speaker never falls back.
320
637
  */
321
638
  function fallback(refused) {
322
- if (!FALLBACK_CODES.includes(refused.code)) throw refusalError(refused)
639
+ if (unlinkedRefusal(refused) || !FALLBACK_CODES.includes(refused.code)) throw refusalError(refused)
323
640
  const key = secretToken()
324
641
  if (key) return key
325
642
  throw new CredentialError(
@@ -329,22 +646,24 @@ export function createCredentials(input = {}) {
329
646
  }
330
647
 
331
648
  /**
332
- * The bearer for one request, or "" when no source has one. A Jelly token
333
- * that cannot be had falls back to the pasted key (see the module comment),
334
- * or rejects with a CredentialError.
649
+ * The bearer for one request of the current session, or "" when no source
650
+ * has one. A Jelly token that cannot be had falls back to the pasted key
651
+ * (see the module comment), or rejects with a CredentialError.
335
652
  *
336
653
  * @returns {Promise<string>}
337
654
  */
338
655
  async function bearer() {
339
656
  if (optionToken) return optionToken
340
657
  if (!memoryResource()) return secretToken()
341
- let refused = held()
658
+ const asked = current()
659
+ let refused = held(asked.state)
342
660
  if (!refused) {
343
- if (fresh(cached)) return cached.accessToken
661
+ if (fresh(asked.state.cached)) return asked.state.cached.accessToken
344
662
  try {
345
- return (await mint()).accessToken
663
+ return (await mint(asked.state, asked.session)).accessToken
346
664
  } catch (error) {
347
- refused = held()
665
+ // The ask may have moved to the engine's state (a host older than members).
666
+ refused = held(current().state)
348
667
  // Only a refusal is held; an accessor gone since `memoryResource()` read it is not.
349
668
  if (!refused) throw error
350
669
  }
@@ -353,12 +672,14 @@ export function createCredentials(input = {}) {
353
672
  }
354
673
 
355
674
  /**
356
- * After a 401: drop the refused Jelly token and ask for another. Returns the
357
- * new bearer, or "" when there is nothing different to try: a key from the
358
- * option or the settings, a host that hands back the same token, or Jelly
359
- * refusing within its hold. A 401 never switches sources, so a request is
360
- * never passed back and forth between a Jelly token and the pasted key; a
361
- * refusal here is held, and the next request falls back.
675
+ * After a 401: drop the current session's refused Jelly token and ask for
676
+ * another. Returns the new bearer, or "" when there is nothing different to
677
+ * try: a key from the option or the settings, a host that hands back the
678
+ * same token, or Jelly refusing within its hold. A 401 never switches
679
+ * sources, so a request is never passed back and forth between a Jelly
680
+ * token and the pasted key; a refusal here is held, and the next request
681
+ * falls back (or, for an unlinked speaker, does not). Other sessions'
682
+ * tokens are not touched.
362
683
  *
363
684
  * @param {string} rejected the bearer the gateway refused
364
685
  * @returns {Promise<string>}
@@ -366,19 +687,25 @@ export function createCredentials(input = {}) {
366
687
  async function refresh(rejected) {
367
688
  if (optionToken || !memoryResource()) return ""
368
689
  if (!rejected || rejected === secretToken()) return ""
369
- if (held()) return ""
370
- if (cached?.accessToken === rejected) cached = null
371
- if (fresh(cached)) return cached.accessToken
690
+ const { state, session } = current()
691
+ if (held(state)) return ""
692
+ if (state.cached?.accessToken === rejected) state.cached = null
693
+ if (fresh(state.cached)) return state.cached.accessToken
372
694
  let next
373
695
  try {
374
- next = (await mint()).accessToken
696
+ next = (await mint(state, session)).accessToken
375
697
  } catch {
376
698
  return ""
377
699
  }
378
700
  return next === rejected ? "" : next
379
701
  }
380
702
 
381
- return { source, describe, inJelly, origin, bearer, refresh, memoryResource }
703
+ /** How many sessions have state kept, for tests and diagnostics. */
704
+ function sessionCount() {
705
+ return sessions.size
706
+ }
707
+
708
+ return { source, describe, unlinked, check, inJelly, origin, bearer, refresh, userTurn, forget, subject, sessionCount, memoryResource }
382
709
  }
383
710
 
384
711
  /**
@@ -390,6 +717,9 @@ export function createCredentials(input = {}) {
390
717
  export function credentialLine({ source, refused }) {
391
718
  const name = source || "none"
392
719
  if (!refused) return name
720
+ if (refused === NOT_SIGNED_IN) {
721
+ return `none (the person speaking in this chat hasn't linked their Jelly account on this host: ${NOT_SIGNED_IN})`
722
+ }
393
723
  if (source === SOURCES.secret) {
394
724
  return `${name} (Jelly refused a memory token: ${refused}; Jelly is asked again within ${REFUSAL_HOLD_MS / 1000} s)`
395
725
  }
package/src/errors.js CHANGED
@@ -66,6 +66,9 @@ export function credentialFailure(code) {
66
66
  return { code: "MEMORY_ACCESS_DENIED", next: "ask the Jelly account's owner to restore the account" }
67
67
  case "invalid_target":
68
68
  return { code: "MEMORY_NOT_OFFERED", next: `ask the Jelly account's owner to offer Memory to this agent, or ${KEY_STEP}` }
69
+ case "not_signed_in":
70
+ // A saved key is the person's who pasted it, never the speaker's: no key step.
71
+ return { code: "MEMORY_NOT_LINKED", next: "link your Jelly account on this host in Jelly, then try again" }
69
72
  default:
70
73
  return { code: "MEMORY_SIGN_IN_FAILED", next: KEY_STEP }
71
74
  }