@joe-broadhead/opencode-mem 0.8.1 → 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 +117 -0
- package/README.md +55 -8
- package/SECURITY.md +1 -1
- package/package.json +28 -4
- package/src/commands.js +8 -5
- package/src/credentials.js +490 -76
- package/src/errors.js +3 -0
- package/src/events.js +63 -20
- package/src/hooks.js +29 -17
- package/src/index.js +6 -3
- package/src/runtime.js +66 -7
- package/src/spool.js +91 -4
- package/src/tools/index.js +10 -5
- package/src/views/contracts.js +36 -26
- package/src/views/rpc.js +78 -17
package/src/credentials.js
CHANGED
|
@@ -5,31 +5,91 @@
|
|
|
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:
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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, 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.
|
|
55
|
+
*
|
|
56
|
+
* A host older than members (Jelly 0.3.2) refuses `{ session }` as options it
|
|
57
|
+
* does not know (`invalid_target`, detail `invalid_cnf_jwk`; the plugin sends
|
|
58
|
+
* no `cnf`). The plugin then stops sending `session` in this engine and asks
|
|
59
|
+
* as before: one token for the engine, which on such a host is its owner's.
|
|
60
|
+
* An accessor that ignores `session` answers as before too.
|
|
61
|
+
*
|
|
16
62
|
* **When Jelly refuses the token.** `token("memory")` rejects with one of four
|
|
17
63
|
* codes (Jelly's host maps Jelly ID's 400 to `invalid_target`, 401 to
|
|
18
64
|
* `not_enrolled`, 403 to `access_denied`, and anything else, a 503 included,
|
|
19
|
-
* to `unavailable`, and holds each answer for 30 s)
|
|
65
|
+
* to `unavailable`, and holds each answer for 30 s). Each refusal is held here
|
|
66
|
+
* for `REFUSAL_HOLD_MS` (the host's own hold), per session, so Jelly is not
|
|
67
|
+
* asked on every request; after it, Jelly is asked again.
|
|
20
68
|
*
|
|
21
|
-
* - `
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
69
|
+
* - `not_enrolled` with the detail `not_signed_in`: the person speaking in the
|
|
70
|
+
* session has not linked a Jelly account on this host. That session uses
|
|
71
|
+
* **no** credential: not the pasted key, which belongs to whoever pasted it,
|
|
72
|
+
* and not another session's token. Nothing is captured for it, and each tool
|
|
73
|
+
* answers `UNLINKED_SENTENCE`. Other sessions are not affected.
|
|
74
|
+
* - `invalid_target`, `not_enrolled` (with no such detail), `unavailable`: the
|
|
75
|
+
* request uses the pasted key instead, when one is saved. With no key saved,
|
|
76
|
+
* the request fails with one sentence saying the agent's Jelly sign-in
|
|
77
|
+
* cannot be used for memory and no memory key is saved.
|
|
27
78
|
* - `access_denied`: no fallback. Jelly says the account behind this agent is
|
|
28
79
|
* disabled or marked for deletion; writing on with a pasted key would get
|
|
29
80
|
* round the switch that stops that account, so the request fails instead.
|
|
30
81
|
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
82
|
+
* An accessor that throws something with no known `code` counts as
|
|
83
|
+
* `unavailable`, as before.
|
|
84
|
+
*
|
|
85
|
+
* Accepted risk: when Jelly refuses a session's token with a code that falls
|
|
86
|
+
* back (`invalid_target`, `unavailable`, or `not_enrolled` without
|
|
87
|
+
* `not_signed_in`), that session writes as the pasted key's memory user while
|
|
88
|
+
* the hold lasts, whoever is speaking in it. The key is the person's who
|
|
89
|
+
* pasted it. `not_signed_in`, the refusal that says the speaker is someone
|
|
90
|
+
* with no linked account, never falls back. The plugin relies on the accessor
|
|
91
|
+
* passing the host's `detail` through: an accessor that drops it makes an
|
|
92
|
+
* unlinked speaker's refusal look like a plain `not_enrolled`, which falls back.
|
|
33
93
|
*
|
|
34
94
|
* The gateway origin is the `controlURL` option, else the identity accessor's
|
|
35
95
|
* `memory` resource `url` (see `followOrigin`).
|
|
@@ -39,6 +99,7 @@
|
|
|
39
99
|
* has the wrong shape counts as absent. A token is held in memory only: it is
|
|
40
100
|
* never logged, spooled, or written to a file.
|
|
41
101
|
*/
|
|
102
|
+
import { AsyncLocalStorage } from "node:async_hooks"
|
|
42
103
|
import { codedMessage, credentialFailure } from "./errors.js"
|
|
43
104
|
|
|
44
105
|
export const PACKAGE_NAME = "@joe-broadhead/opencode-mem"
|
|
@@ -56,6 +117,106 @@ export const REFRESH_MARGIN_MS = 60_000
|
|
|
56
117
|
* Jelly's `backend/host/src/auth/resource-tokens.ts`).
|
|
57
118
|
*/
|
|
58
119
|
export const REFUSAL_HOLD_MS = 30_000
|
|
120
|
+
/** Sessions whose tokens and refusals are kept; the least recently used goes first. */
|
|
121
|
+
export const SESSION_CACHE_MAX = 64
|
|
122
|
+
/** The `detail` Jelly gives `not_enrolled` when the person speaking has no Jelly account linked on the host. */
|
|
123
|
+
export const NOT_SIGNED_IN = "not_signed_in"
|
|
124
|
+
/** The `detail` a host older than members gives options it does not know, `session` included. */
|
|
125
|
+
const INVALID_CNF_JWK = "invalid_cnf_jwk"
|
|
126
|
+
/** An engine session's id as the accessor carries it (contract v1.3 §6). */
|
|
127
|
+
const SESSION_PATTERN = /^[A-Za-z0-9_-]{1,128}$/
|
|
128
|
+
/** What a tool, a command and `mem_status` answer in a session whose speaker has not linked a Jelly account. */
|
|
129
|
+
export const UNLINKED_SENTENCE =
|
|
130
|
+
"Memory isn't available in this chat because the person speaking hasn't linked their Jelly account on this host."
|
|
131
|
+
|
|
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
|
+
*/
|
|
138
|
+
const sessionScope = new AsyncLocalStorage()
|
|
139
|
+
|
|
140
|
+
/** A session id the accessor accepts, or "" (work with no session). */
|
|
141
|
+
function sessionKey(value) {
|
|
142
|
+
return typeof value === "string" && SESSION_PATTERN.test(value) ? value : ""
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Run `fn` for one OpenCode session: every credential it and what it awaits
|
|
147
|
+
* ask for is that session's. A missing or malformed id runs `fn` as work with
|
|
148
|
+
* no session, which also stops an outer session from leaking in.
|
|
149
|
+
*
|
|
150
|
+
* `turn`, the id of the user message that opened a turn, is given by work
|
|
151
|
+
* that belongs to one turn whatever came after it: the capture of that turn.
|
|
152
|
+
* It then uses that turn's token even when a newer user message has arrived
|
|
153
|
+
* (see `userTurn`).
|
|
154
|
+
*
|
|
155
|
+
* @template T
|
|
156
|
+
* @param {unknown} sessionID
|
|
157
|
+
* @param {() => T} fn
|
|
158
|
+
* @param {unknown} [turn]
|
|
159
|
+
* @returns {T}
|
|
160
|
+
*/
|
|
161
|
+
export function asSession(sessionID, fn, turn) {
|
|
162
|
+
return sessionScope.run({ session: sessionKey(sessionID), turn: typeof turn === "string" ? turn : "" }, fn)
|
|
163
|
+
}
|
|
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
|
+
|
|
193
|
+
/** The session the current work is done for, or "" for none. */
|
|
194
|
+
export function currentSession() {
|
|
195
|
+
return sessionScope.getStore()?.session ?? ""
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The turn the current work belongs to, or "" when it is the session's latest. */
|
|
199
|
+
function currentTurn() {
|
|
200
|
+
return sessionScope.getStore()?.turn ?? ""
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* The account a Jelly token names (`sub`, contract §4), read without verifying
|
|
205
|
+
* it: for the plugin's own bookkeeping only, never for a decision the gateway
|
|
206
|
+
* makes. "" for anything that is not a Jelly token.
|
|
207
|
+
*
|
|
208
|
+
* @param {string} token
|
|
209
|
+
*/
|
|
210
|
+
export function tokenSubject(token) {
|
|
211
|
+
const parts = typeof token === "string" ? token.split(".") : []
|
|
212
|
+
if (parts.length !== 3) return ""
|
|
213
|
+
try {
|
|
214
|
+
const sub = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"))?.sub
|
|
215
|
+
return typeof sub === "string" && /^acc_[A-Za-z0-9._:-]{1,123}$/.test(sub) ? sub : ""
|
|
216
|
+
} catch {
|
|
217
|
+
return ""
|
|
218
|
+
}
|
|
219
|
+
}
|
|
59
220
|
/** The longest value Jelly lets a setting carry (`PLUGIN_SETTING_MAX_LENGTH`). */
|
|
60
221
|
const MAX_TOKEN_CHARS = 8192
|
|
61
222
|
/** Visible ASCII only: a bearer goes into an HTTP header. */
|
|
@@ -97,6 +258,32 @@ export class CredentialError extends Error {
|
|
|
97
258
|
this.what = message
|
|
98
259
|
this.next = failure.next
|
|
99
260
|
}
|
|
261
|
+
|
|
262
|
+
/** The person speaking has not linked a Jelly account on this host: nothing for this session is sent or kept. */
|
|
263
|
+
get unlinked() {
|
|
264
|
+
return this.code === NOT_SIGNED_IN
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The code a request carries when its session's speaker has no Jelly account linked on this host. */
|
|
269
|
+
const UNLINKED_CODE = credentialFailure(NOT_SIGNED_IN).code
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* True when an error says the person speaking has not linked a Jelly account
|
|
273
|
+
* on this host: the CredentialError itself, or a gateway or control error
|
|
274
|
+
* that wrapped it (`BackendError` and `ControlError` keep the credential's
|
|
275
|
+
* code, `MEMORY_NOT_LINKED`), or one with it as its `cause`.
|
|
276
|
+
*
|
|
277
|
+
* @param {unknown} error
|
|
278
|
+
*/
|
|
279
|
+
export function isUnlinked(error) {
|
|
280
|
+
let current = /** @type {any} */ (error)
|
|
281
|
+
for (let depth = 0; depth < 5 && current && typeof current === "object"; depth += 1) {
|
|
282
|
+
if (current instanceof CredentialError) return current.unlinked
|
|
283
|
+
if (current.errorCode === UNLINKED_CODE) return true
|
|
284
|
+
current = current.cause
|
|
285
|
+
}
|
|
286
|
+
return false
|
|
100
287
|
}
|
|
101
288
|
|
|
102
289
|
/** Read one global; a getter that throws or a non-object counts as absent. */
|
|
@@ -157,12 +344,141 @@ export function createCredentials(input = {}) {
|
|
|
157
344
|
const holder = input.holder ?? globalThis
|
|
158
345
|
const now = typeof input.now === "function" ? input.now : Date.now
|
|
159
346
|
const log = input.log ?? null
|
|
160
|
-
/**
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
347
|
+
/**
|
|
348
|
+
* What Jelly last answered for one asker: `cached` the last token
|
|
349
|
+
* (`{ accessToken, expiresAt }`, memory only), `minting` the one
|
|
350
|
+
* `token("memory")` call in flight, `refusal` the last refusal
|
|
351
|
+
* (`{ code, detail, reason, until }`, believed until `until`).
|
|
352
|
+
*/
|
|
353
|
+
const newState = () => ({ cached: null, minting: null, refusal: null })
|
|
354
|
+
/** Work with no session: today's single ask. Never evicted. */
|
|
355
|
+
const engine = newState()
|
|
356
|
+
/**
|
|
357
|
+
* Session id -> `{ turn, state, pending, previous }`, least recently used
|
|
358
|
+
* first. `state` belongs to the user message `turn`; `pending` is a newer
|
|
359
|
+
* user message not yet rotated in (see `userTurn`); `previous` is the turn
|
|
360
|
+
* before, `{ turn, state }`, kept for that turn's capture.
|
|
361
|
+
*/
|
|
362
|
+
const sessions = new Map()
|
|
363
|
+
/** Ids for user messages that came without one. */
|
|
364
|
+
let anonymousTurns = 0
|
|
365
|
+
/**
|
|
366
|
+
* False once the accessor refused `{ session }` as options it does not know
|
|
367
|
+
* (a host older than members): from then on every session asks as `engine`.
|
|
368
|
+
*/
|
|
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
|
+
}
|
|
386
|
+
|
|
387
|
+
function newEntry() {
|
|
388
|
+
return { turn: "", state: newState(), pending: null, previous: null }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Take the session's entry, newest in the LRU order, creating it. */
|
|
392
|
+
function entryOf(session) {
|
|
393
|
+
let entry = sessions.get(session)
|
|
394
|
+
if (entry) sessions.delete(session)
|
|
395
|
+
else entry = newEntry()
|
|
396
|
+
sessions.set(session, entry)
|
|
397
|
+
while (sessions.size > SESSION_CACHE_MAX) sessions.delete(sessions.keys().next().value)
|
|
398
|
+
return entry
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* The state for work of `turn` ("" for the session's latest). A pending
|
|
403
|
+
* newer user message is rotated in here, lazily, by work that is not tied to
|
|
404
|
+
* an older turn; `rotate: false` only reads, as rotating would.
|
|
405
|
+
*/
|
|
406
|
+
function stateIn(entry, turn, rotate) {
|
|
407
|
+
if (turn && turn === entry.turn) return entry.state
|
|
408
|
+
if (turn && entry.previous && turn === entry.previous.turn) return entry.previous.state
|
|
409
|
+
if (entry.pending === null) return entry.state
|
|
410
|
+
if (!rotate) return newState()
|
|
411
|
+
entry.previous = { turn: entry.turn, state: entry.state }
|
|
412
|
+
entry.state = newState()
|
|
413
|
+
entry.turn = entry.pending
|
|
414
|
+
entry.pending = null
|
|
415
|
+
return entry.state
|
|
416
|
+
}
|
|
417
|
+
|
|
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
|
+
*/
|
|
424
|
+
function current() {
|
|
425
|
+
const view = sessionAsks ? currentView() : null
|
|
426
|
+
if (view) return { state: viewState(view), session: view.id, view: true }
|
|
427
|
+
const session = sessionAsks ? currentSession() : ""
|
|
428
|
+
if (!session) return { state: engine, session: "", view: false }
|
|
429
|
+
return { state: stateIn(entryOf(session), currentTurn(), true), session, view: false }
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** The current work's state without creating, reordering or rotating one: for reads such as `source()`. */
|
|
433
|
+
function peek() {
|
|
434
|
+
const view = sessionAsks ? currentView() : null
|
|
435
|
+
if (view) return viewState(view)
|
|
436
|
+
const session = sessionAsks ? currentSession() : ""
|
|
437
|
+
if (!session) return engine
|
|
438
|
+
const entry = sessions.get(session)
|
|
439
|
+
return entry ? stateIn(entry, currentTurn(), false) : newState()
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* A new user message in a session: the person speaking may have changed,
|
|
444
|
+
* so the session's token and its refusal hold are dropped, and the turn's
|
|
445
|
+
* first memory call asks Jelly again (the host keeps tokens per person, so
|
|
446
|
+
* this is cheap). The drop is lazy: the previous turn's capture, which may
|
|
447
|
+
* run after this message arrived, still uses the previous turn's token, and
|
|
448
|
+
* every other use rotates to the new turn. The same message reported twice
|
|
449
|
+
* (by the prompt hook and the admission event) drops once.
|
|
450
|
+
*
|
|
451
|
+
* A turn with no user message (a wake or a routine) keeps the cached token:
|
|
452
|
+
* the host decides who it speaks for, the token is replaced 60 s before it
|
|
453
|
+
* expires at the latest, and a new user message drops it at once.
|
|
454
|
+
*
|
|
455
|
+
* @param {unknown} sessionID
|
|
456
|
+
* @param {unknown} [messageID]
|
|
457
|
+
*/
|
|
458
|
+
function userTurn(sessionID, messageID) {
|
|
459
|
+
const session = sessionKey(sessionID)
|
|
460
|
+
if (!session) return
|
|
461
|
+
const id = typeof messageID === "string" && messageID ? messageID : `anonymous-${(anonymousTurns += 1)}`
|
|
462
|
+
const entry = entryOf(session)
|
|
463
|
+
if (id === entry.turn || id === entry.pending) return
|
|
464
|
+
entry.pending = id
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Drop what is kept for a session: OpenCode deleted it. */
|
|
468
|
+
function forget(sessionID) {
|
|
469
|
+
const session = sessionKey(sessionID)
|
|
470
|
+
if (session) sessions.delete(session)
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* The account the current work's cached Jelly token names, or "" (none
|
|
475
|
+
* cached, a pasted key, or the option). Spooled entries record it.
|
|
476
|
+
*/
|
|
477
|
+
function subject() {
|
|
478
|
+
if (optionToken || !memoryResource()) return ""
|
|
479
|
+
const cached = peek().cached
|
|
480
|
+
return cached && fresh(cached) ? tokenSubject(cached.accessToken) : ""
|
|
481
|
+
}
|
|
166
482
|
|
|
167
483
|
function identity() {
|
|
168
484
|
const accessor = readGlobal(holder, IDENTITY_SYMBOL)
|
|
@@ -207,26 +523,34 @@ export function createCredentials(input = {}) {
|
|
|
207
523
|
}
|
|
208
524
|
}
|
|
209
525
|
|
|
210
|
-
/** The refusal Jelly gave within the hold, or null. */
|
|
211
|
-
function held() {
|
|
212
|
-
if (refusal && refusal.until > now()) return refusal
|
|
213
|
-
refusal = null
|
|
526
|
+
/** The refusal Jelly gave this state within the hold, or null. */
|
|
527
|
+
function held(state) {
|
|
528
|
+
if (state.refusal && state.refusal.until > now()) return state.refusal
|
|
529
|
+
state.refusal = null
|
|
214
530
|
return null
|
|
215
531
|
}
|
|
216
532
|
|
|
533
|
+
/** The refusal says the person speaking has no Jelly account linked on this host. */
|
|
534
|
+
function unlinkedRefusal(refused) {
|
|
535
|
+
return Boolean(refused && refused.code === "not_enrolled" && refused.detail === NOT_SIGNED_IN)
|
|
536
|
+
}
|
|
537
|
+
|
|
217
538
|
/**
|
|
218
|
-
* Which source supplies the bearer now, or "" when
|
|
539
|
+
* Which source supplies the bearer now, for the current session, or "" when
|
|
540
|
+
* none does.
|
|
219
541
|
*
|
|
220
542
|
* During a hold after a refusal that falls back, that is the pasted key when
|
|
221
|
-
* one is saved. With no key,
|
|
222
|
-
* sign-in: the only candidate, whose
|
|
223
|
-
*
|
|
543
|
+
* one is saved. With no key, after `access_denied`, or after
|
|
544
|
+
* `not_signed_in`, it stays the Jelly sign-in: the only candidate, whose
|
|
545
|
+
* requests fail with the reason.
|
|
224
546
|
*/
|
|
225
547
|
function source() {
|
|
226
548
|
if (optionToken) return SOURCES.option
|
|
227
549
|
if (memoryResource()) {
|
|
228
|
-
const refused = held()
|
|
229
|
-
if (refused && FALLBACK_CODES.includes(refused.code) && secretToken())
|
|
550
|
+
const refused = held(peek())
|
|
551
|
+
if (refused && FALLBACK_CODES.includes(refused.code) && !unlinkedRefusal(refused) && secretToken()) {
|
|
552
|
+
return SOURCES.secret
|
|
553
|
+
}
|
|
230
554
|
return SOURCES.identity
|
|
231
555
|
}
|
|
232
556
|
if (secretToken()) return SOURCES.secret
|
|
@@ -235,12 +559,36 @@ export function createCredentials(input = {}) {
|
|
|
235
559
|
|
|
236
560
|
/**
|
|
237
561
|
* The source in use and, during a hold, the code Jelly refused with ("" when
|
|
238
|
-
* none), for `mem_status`.
|
|
562
|
+
* none; `not_signed_in` for an unlinked speaker), for `mem_status`.
|
|
239
563
|
*/
|
|
240
564
|
function describe() {
|
|
241
|
-
const
|
|
242
|
-
const refused =
|
|
243
|
-
return { source:
|
|
565
|
+
const source_ = source()
|
|
566
|
+
const refused = source_ === SOURCES.option ? null : memoryResource() ? held(peek()) : null
|
|
567
|
+
return { source: source_, refused: unlinkedRefusal(refused) ? NOT_SIGNED_IN : (refused?.code ?? "") }
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* True while Jelly's last answer for the current session, within the hold,
|
|
572
|
+
* is that the person speaking has no Jelly account linked on this host.
|
|
573
|
+
*/
|
|
574
|
+
function unlinked() {
|
|
575
|
+
if (optionToken || !memoryResource()) return false
|
|
576
|
+
return unlinkedRefusal(held(peek()))
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Learn whether the current session's speaker can have a token, asking Jelly
|
|
581
|
+
* when nothing is cached or held for the session. Never throws; the answer
|
|
582
|
+
* is `unlinked()`. Without a Jelly sign-in in use this asks nothing.
|
|
583
|
+
*/
|
|
584
|
+
async function check() {
|
|
585
|
+
if (source() !== SOURCES.identity) return false
|
|
586
|
+
try {
|
|
587
|
+
await bearer()
|
|
588
|
+
} catch {
|
|
589
|
+
/* the refusal, if any, is held */
|
|
590
|
+
}
|
|
591
|
+
return unlinked()
|
|
244
592
|
}
|
|
245
593
|
|
|
246
594
|
/** Jelly's core plugin has published at least one accessor in this engine. */
|
|
@@ -258,68 +606,121 @@ export function createCredentials(input = {}) {
|
|
|
258
606
|
}
|
|
259
607
|
|
|
260
608
|
/**
|
|
261
|
-
* Hold a refusal for `REFUSAL_HOLD_MS` and log it: the code only,
|
|
262
|
-
* token or the accessor's words. Returns the error for this request.
|
|
609
|
+
* Hold a refusal for `REFUSAL_HOLD_MS` and log it: the code and detail only,
|
|
610
|
+
* never a token or the accessor's words. Returns the error for this request.
|
|
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.
|
|
263
614
|
*
|
|
615
|
+
* @param {{ refusal: any }} state
|
|
616
|
+
* @param {{ session: string, view: boolean }} asker `session` "" for work with no session
|
|
264
617
|
* @param {string} code
|
|
618
|
+
* @param {string} [detail]
|
|
265
619
|
* @param {string} [reason] why, in the plugin's words; the code's own by default
|
|
266
620
|
*/
|
|
267
|
-
function hold(code, reason = TOKEN_ERRORS[code]) {
|
|
268
|
-
refusal = { code, reason, until: now() + REFUSAL_HOLD_MS }
|
|
269
|
-
const
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
621
|
+
function hold(state, asker, code, detail = "", reason = TOKEN_ERRORS[code]) {
|
|
622
|
+
state.refusal = { code, detail, reason, until: now() + 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 }
|
|
625
|
+
if (unlinkedRefusal(state.refusal)) {
|
|
626
|
+
log?.warn?.(
|
|
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",
|
|
630
|
+
fields,
|
|
631
|
+
)
|
|
632
|
+
} else if (FALLBACK_CODES.includes(code)) {
|
|
633
|
+
log?.warn?.("Jelly refused a memory token; the saved memory key, if any, is used until Jelly is asked again", {
|
|
634
|
+
...fields,
|
|
635
|
+
keySaved: Boolean(secretToken()),
|
|
636
|
+
})
|
|
637
|
+
} else {
|
|
638
|
+
log?.warn?.("Jelly refused a memory token; the saved memory key is not used in its place", {
|
|
639
|
+
...fields,
|
|
640
|
+
keySaved: Boolean(secretToken()),
|
|
641
|
+
})
|
|
642
|
+
}
|
|
643
|
+
return refusalError(state.refusal)
|
|
274
644
|
}
|
|
275
645
|
|
|
276
646
|
/** The error for a refusal: the contract's code and the plugin's words, never the accessor's own. */
|
|
277
|
-
function refusalError({ code, reason }) {
|
|
647
|
+
function refusalError({ code, detail, reason }) {
|
|
648
|
+
if (code === "not_enrolled" && detail === NOT_SIGNED_IN) {
|
|
649
|
+
return new CredentialError(
|
|
650
|
+
"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",
|
|
651
|
+
NOT_SIGNED_IN,
|
|
652
|
+
)
|
|
653
|
+
}
|
|
278
654
|
if (code === "access_denied") {
|
|
279
655
|
return new CredentialError(`${reason} (${code}); a saved memory key is not used in its place`, code)
|
|
280
656
|
}
|
|
281
657
|
return new CredentialError(`${reason} (${code})`, code)
|
|
282
658
|
}
|
|
283
659
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
660
|
+
/** The accessor did not know the `session` option: a host older than members. */
|
|
661
|
+
function sessionUnknown(error) {
|
|
662
|
+
return member(error, "code") === "invalid_target" && member(error, "detail") === INVALID_CNF_JWK
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
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
|
|
673
|
+
*/
|
|
674
|
+
function mint(state, session, view = false) {
|
|
675
|
+
if (state.minting) return state.minting
|
|
676
|
+
const flight = (async () => {
|
|
287
677
|
const accessor = identity()
|
|
288
678
|
if (!accessor) throw new CredentialError("the Jelly sign-in is no longer available", "unavailable")
|
|
289
679
|
let answer
|
|
290
680
|
try {
|
|
291
|
-
|
|
681
|
+
// No second argument without a session: exactly the ask of 0.8.1.
|
|
682
|
+
answer = session ? await accessor.token(MEMORY_RESOURCE, { session }) : await accessor.token(MEMORY_RESOURCE)
|
|
292
683
|
} catch (error) {
|
|
684
|
+
if (session && sessionUnknown(error)) {
|
|
685
|
+
// A host older than members: it has one person to name, its owner.
|
|
686
|
+
// Ask as before, for the whole engine, from now on.
|
|
687
|
+
if (sessionAsks) {
|
|
688
|
+
sessionAsks = false
|
|
689
|
+
sessions.clear()
|
|
690
|
+
log?.info?.("this Jelly host does not take a session with a memory token; one token is used for the engine, as before")
|
|
691
|
+
}
|
|
692
|
+
return mint(engine, "")
|
|
693
|
+
}
|
|
293
694
|
const code = typeof member(error, "code") === "string" && TOKEN_ERRORS[error.code] ? error.code : "unavailable"
|
|
294
|
-
|
|
695
|
+
const detail = typeof member(error, "detail") === "string" ? error.detail : ""
|
|
696
|
+
throw hold(state, { session, view }, code, detail)
|
|
295
697
|
}
|
|
296
698
|
const accessToken = usableToken(member(answer, "accessToken"))
|
|
297
699
|
const expiresAt = Number(member(answer, "expiresAt"))
|
|
298
700
|
if (!accessToken || !Number.isFinite(expiresAt)) {
|
|
299
|
-
throw hold("unavailable", "Jelly returned a malformed memory token")
|
|
701
|
+
throw hold(state, { session, view }, "unavailable", "", "Jelly returned a malformed memory token")
|
|
300
702
|
}
|
|
301
703
|
const entry = { accessToken, expiresAt }
|
|
302
|
-
refusal = null
|
|
704
|
+
state.refusal = null
|
|
303
705
|
// A token already inside the refresh margin is used for this request
|
|
304
706
|
// but not kept: the next request asks again.
|
|
305
|
-
cached = fresh(entry) ? entry : null
|
|
707
|
+
state.cached = fresh(entry) ? entry : null
|
|
306
708
|
return entry
|
|
307
709
|
})()
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
}
|
|
710
|
+
state.minting = flight
|
|
711
|
+
return flight.finally(() => {
|
|
712
|
+
if (state.minting === flight) state.minting = null
|
|
713
|
+
})
|
|
313
714
|
}
|
|
314
715
|
|
|
315
716
|
/**
|
|
316
717
|
* The pasted key for a request Jelly refused with a code that falls back, or
|
|
317
718
|
* a CredentialError saying what is missing. `status` follows the code (503
|
|
318
719
|
* for `unavailable`, else 401), so the spool and the bootstrap classify it as
|
|
319
|
-
* before.
|
|
720
|
+
* before. An unlinked speaker never falls back.
|
|
320
721
|
*/
|
|
321
722
|
function fallback(refused) {
|
|
322
|
-
if (!FALLBACK_CODES.includes(refused.code)) throw refusalError(refused)
|
|
723
|
+
if (unlinkedRefusal(refused) || !FALLBACK_CODES.includes(refused.code)) throw refusalError(refused)
|
|
323
724
|
const key = secretToken()
|
|
324
725
|
if (key) return key
|
|
325
726
|
throw new CredentialError(
|
|
@@ -329,22 +730,24 @@ export function createCredentials(input = {}) {
|
|
|
329
730
|
}
|
|
330
731
|
|
|
331
732
|
/**
|
|
332
|
-
* The bearer for one request, or "" when no source
|
|
333
|
-
* that cannot be had falls back to the pasted key
|
|
334
|
-
* or rejects with a CredentialError.
|
|
733
|
+
* The bearer for one request of the current session, or "" when no source
|
|
734
|
+
* has one. A Jelly token that cannot be had falls back to the pasted key
|
|
735
|
+
* (see the module comment), or rejects with a CredentialError.
|
|
335
736
|
*
|
|
336
737
|
* @returns {Promise<string>}
|
|
337
738
|
*/
|
|
338
739
|
async function bearer() {
|
|
339
740
|
if (optionToken) return optionToken
|
|
340
741
|
if (!memoryResource()) return secretToken()
|
|
341
|
-
|
|
742
|
+
const asked = current()
|
|
743
|
+
let refused = held(asked.state)
|
|
342
744
|
if (!refused) {
|
|
343
|
-
if (fresh(cached)) return cached.accessToken
|
|
745
|
+
if (fresh(asked.state.cached)) return asked.state.cached.accessToken
|
|
344
746
|
try {
|
|
345
|
-
return (await mint()).accessToken
|
|
747
|
+
return (await mint(asked.state, asked.session, asked.view)).accessToken
|
|
346
748
|
} catch (error) {
|
|
347
|
-
|
|
749
|
+
// The ask may have moved to the engine's state (a host older than members).
|
|
750
|
+
refused = held(current().state)
|
|
348
751
|
// Only a refusal is held; an accessor gone since `memoryResource()` read it is not.
|
|
349
752
|
if (!refused) throw error
|
|
350
753
|
}
|
|
@@ -353,12 +756,14 @@ export function createCredentials(input = {}) {
|
|
|
353
756
|
}
|
|
354
757
|
|
|
355
758
|
/**
|
|
356
|
-
* After a 401: drop the refused Jelly token and ask for
|
|
357
|
-
* new bearer, or "" when there is nothing different to
|
|
358
|
-
* option or the settings, a host that hands back the
|
|
359
|
-
* refusing within its hold. A 401 never switches
|
|
360
|
-
* never passed back and forth between a Jelly
|
|
361
|
-
* refusal here is held, and the next request
|
|
759
|
+
* After a 401: drop the current session's refused Jelly token and ask for
|
|
760
|
+
* another. Returns the new bearer, or "" when there is nothing different to
|
|
761
|
+
* try: a key from the option or the settings, a host that hands back the
|
|
762
|
+
* same token, or Jelly refusing within its hold. A 401 never switches
|
|
763
|
+
* sources, so a request is never passed back and forth between a Jelly
|
|
764
|
+
* token and the pasted key; a refusal here is held, and the next request
|
|
765
|
+
* falls back (or, for an unlinked speaker, does not). Other sessions'
|
|
766
|
+
* tokens are not touched.
|
|
362
767
|
*
|
|
363
768
|
* @param {string} rejected the bearer the gateway refused
|
|
364
769
|
* @returns {Promise<string>}
|
|
@@ -366,19 +771,25 @@ export function createCredentials(input = {}) {
|
|
|
366
771
|
async function refresh(rejected) {
|
|
367
772
|
if (optionToken || !memoryResource()) return ""
|
|
368
773
|
if (!rejected || rejected === secretToken()) return ""
|
|
369
|
-
|
|
370
|
-
if (
|
|
371
|
-
if (
|
|
774
|
+
const { state, session, view } = current()
|
|
775
|
+
if (held(state)) return ""
|
|
776
|
+
if (state.cached?.accessToken === rejected) state.cached = null
|
|
777
|
+
if (fresh(state.cached)) return state.cached.accessToken
|
|
372
778
|
let next
|
|
373
779
|
try {
|
|
374
|
-
next = (await mint()).accessToken
|
|
780
|
+
next = (await mint(state, session, view)).accessToken
|
|
375
781
|
} catch {
|
|
376
782
|
return ""
|
|
377
783
|
}
|
|
378
784
|
return next === rejected ? "" : next
|
|
379
785
|
}
|
|
380
786
|
|
|
381
|
-
|
|
787
|
+
/** How many sessions have state kept, for tests and diagnostics. */
|
|
788
|
+
function sessionCount() {
|
|
789
|
+
return sessions.size
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
return { source, describe, unlinked, check, inJelly, origin, bearer, refresh, userTurn, forget, subject, sessionCount, memoryResource }
|
|
382
793
|
}
|
|
383
794
|
|
|
384
795
|
/**
|
|
@@ -390,6 +801,9 @@ export function createCredentials(input = {}) {
|
|
|
390
801
|
export function credentialLine({ source, refused }) {
|
|
391
802
|
const name = source || "none"
|
|
392
803
|
if (!refused) return name
|
|
804
|
+
if (refused === NOT_SIGNED_IN) {
|
|
805
|
+
return `none (the person speaking in this chat hasn't linked their Jelly account on this host: ${NOT_SIGNED_IN})`
|
|
806
|
+
}
|
|
393
807
|
if (source === SOURCES.secret) {
|
|
394
808
|
return `${name} (Jelly refused a memory token: ${refused}; Jelly is asked again within ${REFUSAL_HOLD_MS / 1000} s)`
|
|
395
809
|
}
|