@joe-broadhead/opencode-mem 0.6.1 → 0.6.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.
package/README.md CHANGED
@@ -140,34 +140,76 @@ keys plugins and their secrets by, and its `package.json` carries a `jelly`
140
140
  declaration. Inside Jelly the plugin is opt-in: a host has it installed, and a
141
141
  person adds it to an agent.
142
142
 
143
+ **The `memory` resource.** The declaration names `"resources": ["memory"]`.
144
+ Jelly gives an agent's engine the identity accessor for a resource only when
145
+ one of the plugins given to that agent declares it, and its host answers
146
+ `invalid_target` for any other name. `resources` is not in `requires`, on
147
+ purpose: a Jelly that does not know the field ignores it and still loads the
148
+ plugin, which then uses the pasted key.
149
+
143
150
  **Credentials, first match wins** (`src/credentials.js`):
144
151
 
145
152
  1. the `token` option or `MEMORY_TOKEN` (not set inside Jelly; the engine starts
146
153
  with an empty environment);
147
154
  2. Jelly's identity accessor, `globalThis[Symbol.for("jelly.identity")]`, when
148
- the host is signed in to a Jelly account whose Jelly ID offers the `memory`
149
- resource. The plugin asks `token("memory")` for a ten-minute token, keeps it
150
- in memory until 60 s before it expires, and asks again once when the gateway
151
- answers `401`;
155
+ its `resources()` lists `memory`: the host is signed in to a Jelly account
156
+ whose Jelly ID offers `memory`, and the agent was given this plugin. The
157
+ plugin asks `token("memory")` for a ten-minute token, keeps it in memory
158
+ until 60 s before it expires, and asks again once when the gateway answers
159
+ `401`;
152
160
  3. the **Memory key** setting: the key pasted from the memory site's `/account`
153
161
  page, read with
154
162
  `globalThis[Symbol.for("jelly.plugin-secrets")].get("@joe-broadhead/opencode-mem", "token")`.
155
163
 
164
+ **When Jelly refuses the token.** `token("memory")` rejects with a code. Jelly's
165
+ host maps Jelly ID's `400` to `invalid_target`, `401` to `not_enrolled`, `403`
166
+ to `access_denied`, and everything else, a `503` included, to `unavailable`, so
167
+ the plugin cannot tell an outage from Jelly ID turning memory off. The host
168
+ holds each refusal for 30 s, and so does the plugin: Jelly is not asked again
169
+ until the 30 s pass.
170
+
171
+ | Code | What the request does |
172
+ |---|---|
173
+ | `invalid_target`, `not_enrolled`, `unavailable` | Uses the pasted key, when one is saved. With no key, it fails with "this agent's Jelly sign-in can't be used for memory: … (`<code>`), and no memory key is saved in the plugin's settings"; a finished turn is spooled for later |
174
+ | `access_denied` | Fails: "the Jelly account is disabled or marked for deletion (access_denied); a saved memory key is not used in its place". No fallback |
175
+
176
+ Why no fallback on `access_denied`: Jelly says the account behind this agent is
177
+ disabled or about to be deleted. Writing on with a pasted key would get round
178
+ the switch that stops that account, so the plugin stops instead. A `401` from
179
+ the gateway never switches sources: a refused Jelly token is replaced by a new
180
+ Jelly token or not at all, and a refused pasted key is not retried.
181
+
182
+ `mem_status` and `/mem-status` show the credential in use, for example
183
+ `credential: plugin-secret (Jelly refused a memory token: unavailable; Jelly is
184
+ asked again within 30 s)`, and the log has one warning per refusal (its code,
185
+ never a token).
186
+
187
+ **Accepted risk.** If a person's Jelly sign-in and pasted key belong to two
188
+ different memory users, a request that falls back writes as the key's user,
189
+ into that user's memory, until Jelly answers again. Paste a key from the same
190
+ account you sign in to Jelly with.
191
+
156
192
  **Gateway origin:** the **Memory address** setting (`controlURL`), else the
157
- `url` of the identity accessor's `memory` resource. `baseURL` and
158
- `knowledgeURL` default to `<origin>/core` and `<origin>/knowledge`.
193
+ `url` of the identity accessor's `memory` resource, during a fallback too.
194
+ `baseURL` and `knowledgeURL` default to `<origin>/core` and `<origin>/knowledge`.
159
195
 
160
196
  A token is never logged, spooled, or written to a file. With no credential the
161
197
  plugin still loads and registers its nine tools; each answers one sentence
162
198
  saying why memory is unavailable, and nothing is captured, spooled, or sent.
163
199
 
200
+ **Icon.** The declaration's `icon` is `assets/icon.svg`, shipped in the
201
+ package: a flat brain mark on a square `viewBox`, made only of the elements
202
+ and attributes Jelly's `cleanPluginIcon` keeps. Jelly drops an icon that does
203
+ not clean, without an error, and draws a monogram instead, so
204
+ `npm run check:jelly` runs the file through Jelly's own cleaner.
205
+
164
206
  **Settings** (`jelly.contributes.settings`):
165
207
 
166
208
  | Key | Type | Meaning |
167
209
  |---|---|---|
168
210
  | `controlURL` | string | Memory address. Empty: the Jelly account's memory origin |
169
211
  | `capture` | boolean | On by default. Off: the tools still work and nothing is captured, the compaction checkpoint included |
170
- | `token` | secret | Memory key, for a host without a Jelly sign-in that offers memory. A saved key reaches the plugin at the engine's next start |
212
+ | `token` | secret | Memory key, for a host without a Jelly sign-in that offers memory, and the fallback when Jelly refuses a token (not after `access_denied`). A saved key reaches the plugin at the engine's next start |
171
213
 
172
214
  **Tools and permissions.** Each tool is declared as `name: "mem.<tool>"`,
173
215
  `permission: "mem_<tool>"`, `effect: "allow"`:
@@ -195,16 +237,30 @@ Why this mapping:
195
237
  write. Jelly denies them to the read-only helpers (researcher, reviewer).
196
238
  `mem_wiki` reads too, but it is one tool, so the helpers lose its reads.
197
239
 
198
- **Known limit: team writes do not ask inside Jelly.** A team-visible write
199
- asserts the plugin's own approval actions (`memory.remember`, `memory.forget`,
200
- `memory.promote`, `memory.promote.revoke`, `wiki.write`). Jelly's default rules
201
- name none of them, and the engine allows what no rule names, so inside Jelly
202
- they run without a prompt. Private writes, the default, never ask anywhere.
240
+ **Team writes ask inside Jelly.** A team-visible write asserts the plugin's own
241
+ approval actions, with the space as the resource: `memory.remember`,
242
+ `memory.forget`, `memory.promote`, `memory.promote.revoke`, `wiki.write`.
243
+ Jelly's default rules (`agents/default/opencode.jsonc`) set all five to `ask`,
244
+ so a person approves each write to a shared space. Private writes, the default,
245
+ assert nothing and never ask. These five action names are a contract with
246
+ Jelly: do not rename one, or add one, without telling Jelly, or a team write
247
+ runs without a prompt there.
248
+
249
+ **`asks`.** The declaration lists the same five actions in `"asks"`, so Jelly
250
+ can read from the plugin, not only from its own default rules, which run-time
251
+ actions to ask a person about. Like `resources`, it is additive and not in
252
+ `requires`: a Jelly that does not know the field leaves it out and still loads
253
+ the plugin. `test/jelly-declaration.test.js` and `npm run check:jelly` both
254
+ compare `asks` with the actions the tools really assert
255
+ (`scripts/approval-actions.mjs`), so the two cannot drift apart.
203
256
 
204
257
  The declaration has no sign-ins: the Jelly account is the host's sign-in, and
205
258
  the pasted key is a secret setting. `npm run check:jelly -- <Jelly checkout>`
206
- parses the declaration with Jelly's own `PluginDeclarationSchema`;
207
- `test/jelly-declaration.test.js` checks its shape in CI.
259
+ parses the declaration with Jelly's own `PluginDeclarationSchema`, checks that
260
+ `resources` is kept and not required, that `asks` is not required and is kept
261
+ when that Jelly knows it, and runs the icon through Jelly's
262
+ `cleanPluginIcon`; `test/jelly-declaration.test.js` checks the same in CI,
263
+ with the schema and the cleaner restated.
208
264
 
209
265
  **One memory per person.** Every Jelly engine runs the OpenCode agent `agent`,
210
266
  so a person's Jelly agents read and write one personal memory, under agent
@@ -257,7 +313,9 @@ The auth service serves the console at `/console/` and its API at
257
313
  force-directed wiki graph, code indexes, pipeline state, the crew manifest, and
258
314
  spaces, collections, resources, grants, and members.
259
315
  Grant and member mutations go through the control plane. The browser holds only
260
- a Better Auth session or API key; service keys stay server-side. See [docs/mission-control.md](docs/mission-control.md).
316
+ a Better Auth session or API key; service keys stay server-side. A gateway
317
+ with Jelly ID as its only way in has no sign-in page: the console and `/login`
318
+ say that people use Memory from Jelly. See [docs/mission-control.md](docs/mission-control.md).
261
319
 
262
320
  ## Operations
263
321
 
package/SECURITY.md CHANGED
@@ -44,15 +44,17 @@ This is the summary.
44
44
  `secret_ref` are server-side routing data.
45
45
  - The browser holds a Better Auth session (console and `/account` only); the
46
46
  plugin and CLI hold a Better Auth API key, or inside a Jelly host a
47
- ten-minute Jelly ID resource token for the memory resource. None of them
48
- ever holds a gateway, knowledge, admin, or per-cell key.
47
+ ten-minute Jelly ID resource token for the memory resource, and the API key
48
+ a person pasted, used while Jelly refuses a token (never after
49
+ `access_denied`). None of them ever holds a gateway, knowledge, admin, or
50
+ per-cell key.
49
51
 
50
52
  ### Credentials
51
53
 
52
54
  | Credential | Lives in | Purpose |
53
55
  |---|---|---|
54
56
  | Better Auth API key | Client | Authenticates one user to the gateway; expires after `AUTH_KEY_TTL_DAYS` (90); revocable on `/account` or with `deploy/auth/scripts/revoke-user-keys.mjs` |
55
- | Jelly ID resource token | Client (a Jelly host, in memory only) | Authenticates the host's owner to the gateway for ten minutes; verified with the issuer's Ed25519 keys, audience-bound, never a fallback to another credential kind ([docs/design/adr-personal-containers.md](docs/design/adr-personal-containers.md)) |
57
+ | Jelly ID resource token | Client (a Jelly host, in memory only) | Authenticates the host's owner to the gateway for ten minutes; verified with the issuer's Ed25519 keys, audience-bound; at the gateway a refused one never falls back to another credential kind ([docs/design/adr-personal-containers.md](docs/design/adr-personal-containers.md)). The plugin's own fallback to a pasted key is a separate request with that key ([README](README.md#running-inside-jelly)) |
56
58
  | `CONTROL_TOKEN` | Gateway | Authenticates the gateway to control; must equal `CONTROL_SERVICE_TOKEN` |
57
59
  | `CONTROL_SERVICE_TOKEN` | Control service | Verifies the gateway's `x-control-user` assertion; never grants admin |
58
60
  | `CONTROL_ADMIN_TOKEN` | Operator/infrastructure, the exporter, the `cell-health` job | Cell and placement administration; separate from the service token |
@@ -91,7 +93,9 @@ equal, and a service token never sets `admin`.
91
93
  verifications per address; Better Auth's limiter is on. The shipped
92
94
  Caddyfiles cap bodies at the edge as well.
93
95
  - With Google sign-in, `GOOGLE_HD` is required (or an explicit `*`); the dev
94
- password refuses to start on an https origin.
96
+ password refuses to start on an https origin. The gateway refuses to start
97
+ with no way in at all; Jelly ID alone is enough, and then `/login` offers no
98
+ sign-in.
95
99
 
96
100
  ### No links-file path
97
101
 
@@ -0,0 +1,14 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
2
+ <rect width="64" height="64" rx="14" fill="#3B3486"/>
3
+ <g fill="none" stroke="#F4F1FF" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round">
4
+ <path d="M32 15C28.5 11 21.5 11.5 19.5 17C14.5 17.5 11.5 22.5 14 27C10 30 10.5 36 15 38C13.5 43.5 18 48 23 47C25 51 30 51.5 32 48"/>
5
+ <path d="M32 15C35.5 11 42.5 11.5 44.5 17C49.5 17.5 52.5 22.5 50 27C54 30 53.5 36 49 38C50.5 43.5 46 48 41 47C39 51 34 51.5 32 48"/>
6
+ <path d="M32 15V48"/>
7
+ <path d="M19.5 17C20.5 20.5 23.5 22 26.5 21"/>
8
+ <path d="M14 27C17.5 28.5 21 27.5 22.5 25"/>
9
+ <path d="M15 38C18 36.5 21.5 37 24 39.5"/>
10
+ <path d="M44.5 17C43.5 20.5 40.5 22 37.5 21"/>
11
+ <path d="M50 27C46.5 28.5 43 27.5 41.5 25"/>
12
+ <path d="M49 38C46 36.5 42.5 37 40 39.5"/>
13
+ </g>
14
+ </svg>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joe-broadhead/opencode-mem",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
4
4
  "type": "module",
5
5
  "description": "Durable private and shared-space memory for OpenCode agents",
6
6
  "license": "MIT",
@@ -14,6 +14,7 @@
14
14
  "jelly": {
15
15
  "title": "Memory",
16
16
  "summary": "Remembers your decisions, preferences and notes across conversations and agents.",
17
+ "icon": "assets/icon.svg",
17
18
  "tools": [
18
19
  {
19
20
  "name": "mem.recall",
@@ -100,12 +101,23 @@
100
101
  "description": "Only needed when your Jelly account does not sign you in to memory: paste the key from the memory site's /account page."
101
102
  }
102
103
  ]
103
- }
104
+ },
105
+ "resources": [
106
+ "memory"
107
+ ],
108
+ "asks": [
109
+ "memory.remember",
110
+ "memory.forget",
111
+ "memory.promote",
112
+ "memory.promote.revoke",
113
+ "wiki.write"
114
+ ]
104
115
  },
105
116
  "files": [
106
117
  "index.js",
107
118
  "src",
108
119
  "skills",
120
+ "assets/icon.svg",
109
121
  "docs/agent-protocol.md",
110
122
  "!docs/README.md",
111
123
  "README.md",
package/src/commands.js CHANGED
@@ -92,6 +92,7 @@ export async function registerCommands(ctx, runtime) {
92
92
  }
93
93
  if (status.collection) lines.push(`- collection: ${oneLine(status.collection, 120)}`)
94
94
  lines.push(
95
+ `- credential: ${status.credential}`,
95
96
  `- L0 conversations: ${status.layers?.l0 ?? "?"}`,
96
97
  `- L1 atoms: ${status.layers?.l1 ?? "?"}`,
97
98
  `- L2 scenarios: ${status.layers?.l2 ?? "?"}`,
@@ -13,6 +13,24 @@
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
+ * **When Jelly refuses the token.** `token("memory")` rejects with one of four
17
+ * codes (Jelly's host maps Jelly ID's 400 to `invalid_target`, 401 to
18
+ * `not_enrolled`, 403 to `access_denied`, and anything else, a 503 included,
19
+ * to `unavailable`, and holds each answer for 30 s):
20
+ *
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.
27
+ * - `access_denied`: no fallback. Jelly says the account behind this agent is
28
+ * disabled or marked for deletion; writing on with a pasted key would get
29
+ * round the switch that stops that account, so the request fails instead.
30
+ *
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.
33
+ *
16
34
  * The gateway origin is the `controlURL` option, else the identity accessor's
17
35
  * `memory` resource `url` (see `followOrigin`).
18
36
  *
@@ -31,6 +49,12 @@ export const MEMORY_RESOURCE = "memory"
31
49
  export const SECRET_KEY = "token"
32
50
  /** A Jelly token is replaced this long before it expires. */
33
51
  export const REFRESH_MARGIN_MS = 60_000
52
+ /**
53
+ * How long a refusal from `token("memory")` is believed before Jelly is asked
54
+ * again: the host holds each refusal this long too (`REFUSAL_HOLD_MS` in
55
+ * Jelly's `backend/host/src/auth/resource-tokens.ts`).
56
+ */
57
+ export const REFUSAL_HOLD_MS = 30_000
34
58
  /** The longest value Jelly lets a setting carry (`PLUGIN_SETTING_MAX_LENGTH`). */
35
59
  const MAX_TOKEN_CHARS = 8192
36
60
  /** Visible ASCII only: a bearer goes into an HTTP header. */
@@ -44,9 +68,15 @@ const TOKEN_ERRORS = Object.freeze({
44
68
  unavailable: "Jelly could not issue a memory token just now",
45
69
  not_enrolled: "this Jelly host is not enrolled at a Jelly account",
46
70
  access_denied: "the Jelly account is disabled or marked for deletion",
47
- invalid_target: "the Jelly account does not offer memory",
71
+ invalid_target: "the Jelly account does not offer memory to this agent",
48
72
  })
49
73
 
74
+ /**
75
+ * The refusals after which a request uses the pasted key instead. Not
76
+ * `access_denied`: see the module comment.
77
+ */
78
+ export const FALLBACK_CODES = Object.freeze(["invalid_target", "not_enrolled", "unavailable"])
79
+
50
80
  /**
51
81
  * A memory token could not be had. `status` lets the spool and the bootstrap
52
82
  * classify it: 503 when Jelly cannot answer now, 401 otherwise.
@@ -114,16 +144,20 @@ export function originOf(value) {
114
144
  * token?: string,
115
145
  * holder?: Record<symbol, unknown>,
116
146
  * now?: () => number,
147
+ * log?: { info?: Function, warn?: Function },
117
148
  * }} [input]
118
149
  */
119
150
  export function createCredentials(input = {}) {
120
151
  const optionToken = typeof input.token === "string" ? input.token : ""
121
152
  const holder = input.holder ?? globalThis
122
153
  const now = typeof input.now === "function" ? input.now : Date.now
154
+ const log = input.log ?? null
123
155
  /** The last Jelly token: `{ accessToken, expiresAt }`. Memory only. */
124
156
  let cached = null
125
157
  /** One `token("memory")` call at a time. */
126
158
  let minting = null
159
+ /** The last refusal from `token("memory")`: `{ code, until }`, believed until `until`. */
160
+ let refusal = null
127
161
 
128
162
  function identity() {
129
163
  const accessor = readGlobal(holder, IDENTITY_SYMBOL)
@@ -168,14 +202,42 @@ export function createCredentials(input = {}) {
168
202
  }
169
203
  }
170
204
 
171
- /** Which source supplies the bearer now, or "" when none does. */
205
+ /** The refusal Jelly gave within the hold, or null. */
206
+ function held() {
207
+ if (refusal && refusal.until > now()) return refusal
208
+ refusal = null
209
+ return null
210
+ }
211
+
212
+ /**
213
+ * Which source supplies the bearer now, or "" when none does.
214
+ *
215
+ * 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.
219
+ */
172
220
  function source() {
173
221
  if (optionToken) return SOURCES.option
174
- if (memoryResource()) return SOURCES.identity
222
+ if (memoryResource()) {
223
+ const refused = held()
224
+ if (refused && FALLBACK_CODES.includes(refused.code) && secretToken()) return SOURCES.secret
225
+ return SOURCES.identity
226
+ }
175
227
  if (secretToken()) return SOURCES.secret
176
228
  return ""
177
229
  }
178
230
 
231
+ /**
232
+ * The source in use and, during a hold, the code Jelly refused with ("" when
233
+ * none), for `mem_status`.
234
+ */
235
+ function describe() {
236
+ const current = source()
237
+ const refused = current === SOURCES.option ? null : memoryResource() ? held() : null
238
+ return { source: current, refused: refused?.code ?? "" }
239
+ }
240
+
179
241
  /** Jelly's core plugin has published at least one accessor in this engine. */
180
242
  function inJelly() {
181
243
  return Boolean(identity() || secrets())
@@ -190,6 +252,30 @@ export function createCredentials(input = {}) {
190
252
  return Boolean(entry && entry.expiresAt - REFRESH_MARGIN_MS > now())
191
253
  }
192
254
 
255
+ /**
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.
258
+ *
259
+ * @param {string} code
260
+ * @param {string} [reason] why, in the plugin's words; the code's own by default
261
+ */
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)
269
+ }
270
+
271
+ /** The error for a refusal: the contract's code and the plugin's words, never the accessor's own. */
272
+ function refusalError({ code, reason }) {
273
+ if (code === "access_denied") {
274
+ return new CredentialError(`${reason} (${code}); a saved memory key is not used in its place`, code)
275
+ }
276
+ return new CredentialError(`${reason} (${code})`, code)
277
+ }
278
+
193
279
  async function mint() {
194
280
  if (minting) return minting
195
281
  minting = (async () => {
@@ -200,15 +286,15 @@ export function createCredentials(input = {}) {
200
286
  answer = await accessor.token(MEMORY_RESOURCE)
201
287
  } catch (error) {
202
288
  const code = typeof member(error, "code") === "string" && TOKEN_ERRORS[error.code] ? error.code : "unavailable"
203
- // The accessor's own words are not repeated: only the contract's codes are.
204
- throw new CredentialError(`${TOKEN_ERRORS[code]} (${code})`, code)
289
+ throw hold(code)
205
290
  }
206
291
  const accessToken = usableToken(member(answer, "accessToken"))
207
292
  const expiresAt = Number(member(answer, "expiresAt"))
208
293
  if (!accessToken || !Number.isFinite(expiresAt)) {
209
- throw new CredentialError("Jelly returned a malformed memory token", "unavailable")
294
+ throw hold("unavailable", "Jelly returned a malformed memory token")
210
295
  }
211
296
  const entry = { accessToken, expiresAt }
297
+ refusal = null
212
298
  // A token already inside the refresh margin is used for this request
213
299
  // but not kept: the next request asks again.
214
300
  cached = fresh(entry) ? entry : null
@@ -221,38 +307,88 @@ export function createCredentials(input = {}) {
221
307
  }
222
308
  }
223
309
 
310
+ /**
311
+ * The pasted key for a request Jelly refused with a code that falls back, or
312
+ * a CredentialError saying what is missing. `status` follows the code (503
313
+ * for `unavailable`, else 401), so the spool and the bootstrap classify it as
314
+ * before.
315
+ */
316
+ function fallback(refused) {
317
+ if (!FALLBACK_CODES.includes(refused.code)) throw refusalError(refused)
318
+ const key = secretToken()
319
+ if (key) return key
320
+ throw new CredentialError(
321
+ `this agent's Jelly sign-in can't be used for memory: ${refused.reason} (${refused.code}), and no memory key is saved in the plugin's settings`,
322
+ refused.code,
323
+ )
324
+ }
325
+
224
326
  /**
225
327
  * The bearer for one request, or "" when no source has one. A Jelly token
226
- * that is failing to mint rejects with a CredentialError.
328
+ * that cannot be had falls back to the pasted key (see the module comment),
329
+ * or rejects with a CredentialError.
227
330
  *
228
331
  * @returns {Promise<string>}
229
332
  */
230
333
  async function bearer() {
231
334
  if (optionToken) return optionToken
232
- if (memoryResource()) {
335
+ if (!memoryResource()) return secretToken()
336
+ let refused = held()
337
+ if (!refused) {
233
338
  if (fresh(cached)) return cached.accessToken
234
- return (await mint()).accessToken
339
+ try {
340
+ return (await mint()).accessToken
341
+ } catch (error) {
342
+ refused = held()
343
+ // Only a refusal is held; an accessor gone since `memoryResource()` read it is not.
344
+ if (!refused) throw error
345
+ }
235
346
  }
236
- return secretToken()
347
+ return fallback(refused)
237
348
  }
238
349
 
239
350
  /**
240
351
  * After a 401: drop the refused Jelly token and ask for another. Returns the
241
- * new bearer, or "" when there is nothing different to try (a key from the
242
- * option or the settings, or a host that hands back the same token).
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.
243
357
  *
244
358
  * @param {string} rejected the bearer the gateway refused
245
359
  * @returns {Promise<string>}
246
360
  */
247
361
  async function refresh(rejected) {
248
362
  if (optionToken || !memoryResource()) return ""
363
+ if (!rejected || rejected === secretToken()) return ""
364
+ if (held()) return ""
249
365
  if (cached?.accessToken === rejected) cached = null
250
366
  if (fresh(cached)) return cached.accessToken
251
- const next = (await mint()).accessToken
367
+ let next
368
+ try {
369
+ next = (await mint()).accessToken
370
+ } catch {
371
+ return ""
372
+ }
252
373
  return next === rejected ? "" : next
253
374
  }
254
375
 
255
- return { source, inJelly, origin, bearer, refresh, memoryResource }
376
+ return { source, describe, inJelly, origin, bearer, refresh, memoryResource }
377
+ }
378
+
379
+ /**
380
+ * The `credential` line of `mem_status` and `/mem-status`, from `describe()`:
381
+ * the source in use, and during a hold the code Jelly refused with.
382
+ *
383
+ * @param {{ source: string, refused: string }} state
384
+ */
385
+ export function credentialLine({ source, refused }) {
386
+ const name = source || "none"
387
+ if (!refused) return name
388
+ if (source === SOURCES.secret) {
389
+ return `${name} (Jelly refused a memory token: ${refused}; Jelly is asked again within ${REFUSAL_HOLD_MS / 1000} s)`
390
+ }
391
+ return `${name} (Jelly refused a memory token: ${refused})`
256
392
  }
257
393
 
258
394
  /**
@@ -265,7 +401,7 @@ export function createCredentials(input = {}) {
265
401
  export function unavailableReason({ source, controlURL, inJelly }) {
266
402
  if (!source) {
267
403
  return inJelly
268
- ? "Memory is unavailable: this Jelly is not signed in to a Jelly account that offers memory, and no memory key is saved in the plugin's settings."
404
+ ? "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."
269
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."
270
406
  }
271
407
  if (!controlURL) {
package/src/index.js CHANGED
@@ -57,7 +57,7 @@ export default {
57
57
 
58
58
  // Credentials and, inside Jelly, the gateway origin are read on use: the
59
59
  // accessors Jelly's core plugin publishes may appear after this setup.
60
- const credentials = createCredentials({ token: config.token })
60
+ const credentials = createCredentials({ token: config.token, log })
61
61
  const jelly = !config.controlURL && credentials.inJelly()
62
62
  if (jelly) followOrigin(config, () => credentials.origin())
63
63
  const gateway = Boolean(config.controlURL) || jelly
package/src/runtime.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { contextScopeLabel, placementSignature, resolveScope, scopeLabel, taskKey } from "./scope.js"
2
2
  import { buildBootstrap } from "./bootstrap.js"
3
3
  import { buildCheckpoint, checkpointFingerprint } from "./compaction.js"
4
- import { unavailableReason } from "./credentials.js"
4
+ import { credentialLine, unavailableReason } from "./credentials.js"
5
5
  import { createControlClient } from "./spaces.js"
6
6
  import { createSkillContexts } from "./skill-contexts.js"
7
7
  import { createSpool } from "./spool.js"
@@ -793,6 +793,8 @@ export function createRuntime(input) {
793
793
  ])
794
794
  return {
795
795
  health: health.ok ? "ok" : `unavailable (${health.error})`,
796
+ // Read after the requests above, so a refusal they met is reported.
797
+ credential: credentials ? credentialLine(credentials.describe()) : config.token ? "option" : "none",
796
798
  scope: context ? contextScopeLabel(context, scoped) : scopeLabel(scoped),
797
799
  space: context?.space_id ?? null,
798
800
  spaceName: context?.space_name ?? null,
@@ -35,6 +35,7 @@ export function registerStatus(editor, toolkit) {
35
35
  `backend: ${status.health}`,
36
36
  `scope: ${status.scope}`,
37
37
  `capture: ${status.capture}`,
38
+ `credential: ${status.credential}`,
38
39
  ]
39
40
  if (status.space) {
40
41
  const kind = status.spaceKind && status.spaceKind !== "unknown" ? ` [${status.spaceKind}]` : ""