@joe-broadhead/opencode-mem 0.8.0 → 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,8 @@
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"
88
+ import { codedMessage, credentialFailure } from "./errors.js"
42
89
 
43
90
  export const PACKAGE_NAME = "@joe-broadhead/opencode-mem"
44
91
  export const IDENTITY_SYMBOL = Symbol.for("jelly.identity")
@@ -55,6 +102,73 @@ export const REFRESH_MARGIN_MS = 60_000
55
102
  * Jelly's `backend/host/src/auth/resource-tokens.ts`).
56
103
  */
57
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
+ }
58
172
  /** The longest value Jelly lets a setting carry (`PLUGIN_SETTING_MAX_LENGTH`). */
59
173
  const MAX_TOKEN_CHARS = 8192
60
174
  /** Visible ASCII only: a bearer goes into an HTTP header. */
@@ -87,11 +201,41 @@ export class CredentialError extends Error {
87
201
  * @param {string} code
88
202
  */
89
203
  constructor(message, code) {
90
- super(message)
204
+ const failure = credentialFailure(code)
205
+ super(codedMessage(failure.code, message, failure.next))
91
206
  this.name = "CredentialError"
92
207
  this.code = code
93
208
  this.status = code === "unavailable" ? 503 : 401
209
+ this.errorCode = failure.code
210
+ this.what = message
211
+ this.next = failure.next
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
94
237
  }
238
+ return false
95
239
  }
96
240
 
97
241
  /** Read one global; a getter that throws or a non-object counts as absent. */
@@ -152,12 +296,116 @@ export function createCredentials(input = {}) {
152
296
  const holder = input.holder ?? globalThis
153
297
  const now = typeof input.now === "function" ? input.now : Date.now
154
298
  const log = input.log ?? null
155
- /** The last Jelly token: `{ accessToken, expiresAt }`. Memory only. */
156
- let cached = null
157
- /** One `token("memory")` call at a time. */
158
- let minting = null
159
- /** The last refusal from `token("memory")`: `{ code, until }`, believed until `until`. */
160
- 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
+ }
161
409
 
162
410
  function identity() {
163
411
  const accessor = readGlobal(holder, IDENTITY_SYMBOL)
@@ -202,26 +450,34 @@ export function createCredentials(input = {}) {
202
450
  }
203
451
  }
204
452
 
205
- /** The refusal Jelly gave within the hold, or null. */
206
- function held() {
207
- if (refusal && refusal.until > now()) return refusal
208
- 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
209
457
  return null
210
458
  }
211
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
+
212
465
  /**
213
- * 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.
214
468
  *
215
469
  * During a hold after a refusal that falls back, that is the pasted key when
216
- * one is saved. With no key, or after `access_denied`, it stays the Jelly
217
- * sign-in: the only candidate, whose requests fail with the reason, so a
218
- * 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.
219
473
  */
220
474
  function source() {
221
475
  if (optionToken) return SOURCES.option
222
476
  if (memoryResource()) {
223
- const refused = held()
224
- 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
+ }
225
481
  return SOURCES.identity
226
482
  }
227
483
  if (secretToken()) return SOURCES.secret
@@ -230,12 +486,36 @@ export function createCredentials(input = {}) {
230
486
 
231
487
  /**
232
488
  * The source in use and, during a hold, the code Jelly refused with ("" when
233
- * none), for `mem_status`.
489
+ * none; `not_signed_in` for an unlinked speaker), for `mem_status`.
234
490
  */
235
491
  function describe() {
236
- const current = source()
237
- const refused = current === SOURCES.option ? null : memoryResource() ? held() : null
238
- 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()
239
519
  }
240
520
 
241
521
  /** Jelly's core plugin has published at least one accessor in this engine. */
@@ -253,68 +533,110 @@ export function createCredentials(input = {}) {
253
533
  }
254
534
 
255
535
  /**
256
- * Hold a refusal for `REFUSAL_HOLD_MS` and log it: the code only, never a
257
- * 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.
258
538
  *
539
+ * @param {{ refusal: any }} state
540
+ * @param {string} session "" for work with no session
259
541
  * @param {string} code
542
+ * @param {string} [detail]
260
543
  * @param {string} [reason] why, in the plugin's words; the code's own by default
261
544
  */
262
- function hold(code, reason = TOKEN_ERRORS[code]) {
263
- refusal = { code, reason, until: now() + REFUSAL_HOLD_MS }
264
- const message = FALLBACK_CODES.includes(code)
265
- ? "Jelly refused a memory token; the saved memory key, if any, is used until Jelly is asked again"
266
- : "Jelly refused a memory token; the saved memory key is not used in its place"
267
- log?.warn?.(message, { code, holdMs: REFUSAL_HOLD_MS, keySaved: Boolean(secretToken()) })
268
- 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)
269
565
  }
270
566
 
271
567
  /** The error for a refusal: the contract's code and the plugin's words, never the accessor's own. */
272
- 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
+ }
273
575
  if (code === "access_denied") {
274
576
  return new CredentialError(`${reason} (${code}); a saved memory key is not used in its place`, code)
275
577
  }
276
578
  return new CredentialError(`${reason} (${code})`, code)
277
579
  }
278
580
 
279
- async function mint() {
280
- if (minting) return minting
281
- 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 () => {
282
593
  const accessor = identity()
283
594
  if (!accessor) throw new CredentialError("the Jelly sign-in is no longer available", "unavailable")
284
595
  let answer
285
596
  try {
286
- 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)
287
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
+ }
288
610
  const code = typeof member(error, "code") === "string" && TOKEN_ERRORS[error.code] ? error.code : "unavailable"
289
- throw hold(code)
611
+ const detail = typeof member(error, "detail") === "string" ? error.detail : ""
612
+ throw hold(state, session, code, detail)
290
613
  }
291
614
  const accessToken = usableToken(member(answer, "accessToken"))
292
615
  const expiresAt = Number(member(answer, "expiresAt"))
293
616
  if (!accessToken || !Number.isFinite(expiresAt)) {
294
- throw hold("unavailable", "Jelly returned a malformed memory token")
617
+ throw hold(state, session, "unavailable", "", "Jelly returned a malformed memory token")
295
618
  }
296
619
  const entry = { accessToken, expiresAt }
297
- refusal = null
620
+ state.refusal = null
298
621
  // A token already inside the refresh margin is used for this request
299
622
  // but not kept: the next request asks again.
300
- cached = fresh(entry) ? entry : null
623
+ state.cached = fresh(entry) ? entry : null
301
624
  return entry
302
625
  })()
303
- try {
304
- return await minting
305
- } finally {
306
- minting = null
307
- }
626
+ state.minting = flight
627
+ return flight.finally(() => {
628
+ if (state.minting === flight) state.minting = null
629
+ })
308
630
  }
309
631
 
310
632
  /**
311
633
  * The pasted key for a request Jelly refused with a code that falls back, or
312
634
  * a CredentialError saying what is missing. `status` follows the code (503
313
635
  * for `unavailable`, else 401), so the spool and the bootstrap classify it as
314
- * before.
636
+ * before. An unlinked speaker never falls back.
315
637
  */
316
638
  function fallback(refused) {
317
- if (!FALLBACK_CODES.includes(refused.code)) throw refusalError(refused)
639
+ if (unlinkedRefusal(refused) || !FALLBACK_CODES.includes(refused.code)) throw refusalError(refused)
318
640
  const key = secretToken()
319
641
  if (key) return key
320
642
  throw new CredentialError(
@@ -324,22 +646,24 @@ export function createCredentials(input = {}) {
324
646
  }
325
647
 
326
648
  /**
327
- * The bearer for one request, or "" when no source has one. A Jelly token
328
- * that cannot be had falls back to the pasted key (see the module comment),
329
- * 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.
330
652
  *
331
653
  * @returns {Promise<string>}
332
654
  */
333
655
  async function bearer() {
334
656
  if (optionToken) return optionToken
335
657
  if (!memoryResource()) return secretToken()
336
- let refused = held()
658
+ const asked = current()
659
+ let refused = held(asked.state)
337
660
  if (!refused) {
338
- if (fresh(cached)) return cached.accessToken
661
+ if (fresh(asked.state.cached)) return asked.state.cached.accessToken
339
662
  try {
340
- return (await mint()).accessToken
663
+ return (await mint(asked.state, asked.session)).accessToken
341
664
  } catch (error) {
342
- refused = held()
665
+ // The ask may have moved to the engine's state (a host older than members).
666
+ refused = held(current().state)
343
667
  // Only a refusal is held; an accessor gone since `memoryResource()` read it is not.
344
668
  if (!refused) throw error
345
669
  }
@@ -348,12 +672,14 @@ export function createCredentials(input = {}) {
348
672
  }
349
673
 
350
674
  /**
351
- * After a 401: drop the refused Jelly token and ask for another. Returns the
352
- * new bearer, or "" when there is nothing different to try: a key from the
353
- * option or the settings, a host that hands back the same token, or Jelly
354
- * refusing within its hold. A 401 never switches sources, so a request is
355
- * never passed back and forth between a Jelly token and the pasted key; a
356
- * 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.
357
683
  *
358
684
  * @param {string} rejected the bearer the gateway refused
359
685
  * @returns {Promise<string>}
@@ -361,19 +687,25 @@ export function createCredentials(input = {}) {
361
687
  async function refresh(rejected) {
362
688
  if (optionToken || !memoryResource()) return ""
363
689
  if (!rejected || rejected === secretToken()) return ""
364
- if (held()) return ""
365
- if (cached?.accessToken === rejected) cached = null
366
- 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
367
694
  let next
368
695
  try {
369
- next = (await mint()).accessToken
696
+ next = (await mint(state, session)).accessToken
370
697
  } catch {
371
698
  return ""
372
699
  }
373
700
  return next === rejected ? "" : next
374
701
  }
375
702
 
376
- 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 }
377
709
  }
378
710
 
379
711
  /**
@@ -385,6 +717,9 @@ export function createCredentials(input = {}) {
385
717
  export function credentialLine({ source, refused }) {
386
718
  const name = source || "none"
387
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
+ }
388
723
  if (source === SOURCES.secret) {
389
724
  return `${name} (Jelly refused a memory token: ${refused}; Jelly is asked again within ${REFUSAL_HOLD_MS / 1000} s)`
390
725
  }
@@ -402,7 +737,7 @@ export function unavailableReason({ source, controlURL, inJelly }) {
402
737
  if (!source) {
403
738
  return inJelly
404
739
  ? "Memory is unavailable: this agent's Jelly sign-in can't be used for memory, and no memory key is saved in the plugin's settings."
405
- : "Memory is unavailable: no memory key is set; set the token option or MEMORY_TOKEN to the key from the memory site's /account page."
740
+ : "Memory is unavailable: no memory key is set; set the token option or MEMORY_TOKEN to the key from Memory's /account page."
406
741
  }
407
742
  if (!controlURL) {
408
743
  return inJelly