@joe-broadhead/opencode-mem 0.9.12 → 0.11.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.
Files changed (144) hide show
  1. package/CHANGELOG.md +1934 -2
  2. package/README.md +29 -17
  3. package/SECURITY.md +3 -1
  4. package/docs/agent-instructions.md +17 -0
  5. package/docs/agent-protocol.md +8 -8
  6. package/docs/permissions.md +22 -4
  7. package/package.json +7923 -217
  8. package/shared/page-paths.js +44 -0
  9. package/skills/mem.pages/SKILL.md +8 -1
  10. package/skills/mem.usage/SKILL.md +15 -15
  11. package/src/action-grant-keys.js +159 -0
  12. package/src/action-grant.js +439 -0
  13. package/src/actions.js +1690 -0
  14. package/src/backend/records.js +25 -2
  15. package/src/backend/v3.js +76 -22
  16. package/src/call-shapes.js +17 -16
  17. package/src/collector-lock.js +533 -62
  18. package/src/collector-service.js +153 -26
  19. package/src/collector.js +627 -33
  20. package/src/config.js +79 -6
  21. package/src/connect.js +106 -8
  22. package/src/credentials.js +123 -25
  23. package/src/events.js +174 -3
  24. package/src/forget-turn.js +141 -0
  25. package/src/host-refusal.js +78 -0
  26. package/src/index.js +209 -22
  27. package/src/jobs/host.js +557 -0
  28. package/src/ops/codes.js +110 -0
  29. package/src/ops/copy-lineage.js +42 -0
  30. package/src/ops/index.js +28 -0
  31. package/src/ops/space-ops.js +1936 -0
  32. package/src/outlinks.js +103 -0
  33. package/src/p2-reservation.js +151 -0
  34. package/src/permissions.js +30 -0
  35. package/src/plugins/descriptor.js +62 -0
  36. package/src/plugins/discovery.js +318 -0
  37. package/src/plugins/grants.js +178 -0
  38. package/src/plugins/locate.js +319 -0
  39. package/src/plugins/manifest.js +1162 -0
  40. package/src/plugins/source-contract/index.js +34 -0
  41. package/src/plugins/source-contract/policy.js +102 -0
  42. package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
  43. package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
  44. package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
  45. package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
  46. package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
  47. package/src/plugins/source-contract/vendor/broker-client.js +93 -0
  48. package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
  49. package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
  50. package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
  51. package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
  52. package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
  53. package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
  54. package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
  55. package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
  56. package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
  57. package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
  58. package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
  59. package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
  60. package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
  61. package/src/plugins/source-contract/vendor/cursor.js +26 -0
  62. package/src/plugins/source-contract/vendor/descriptor.js +34 -0
  63. package/src/plugins/source-contract/vendor/events.js +257 -0
  64. package/src/plugins/source-contract/vendor/index.js +10 -0
  65. package/src/plugins/source-contract/vendor/params.js +22 -0
  66. package/src/plugins/source-contract/vendor/permission.js +28 -0
  67. package/src/plugins/source-contract/vendor/pick.js +22 -0
  68. package/src/plugins/source-contract/vendor/read.js +29 -0
  69. package/src/plugins/source-contract/vendor/registry.js +23 -0
  70. package/src/plugins/source-contract/vendor/schema.js +17 -0
  71. package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
  72. package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
  73. package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
  74. package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
  75. package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
  76. package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
  77. package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
  78. package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
  79. package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
  80. package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
  81. package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
  82. package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
  83. package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
  84. package/src/plugins/source-contract/vendor/schemas.js +19 -0
  85. package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
  86. package/src/plugins/verify.js +56 -0
  87. package/src/protocol.js +21 -5
  88. package/src/recall.js +104 -5
  89. package/src/records.js +61 -2
  90. package/src/requests.js +216 -0
  91. package/src/runtime.js +89 -7
  92. package/src/setup-time.js +68 -0
  93. package/src/skills.js +230 -8
  94. package/src/source-ids.js +25 -0
  95. package/src/sources/declaration.js +365 -0
  96. package/src/sources/reads.js +772 -0
  97. package/src/sources/rpc.js +151 -0
  98. package/src/sources.js +409 -90
  99. package/src/spaces.js +283 -11
  100. package/src/spool.js +61 -4
  101. package/src/stated.js +10 -5
  102. package/src/storable.js +139 -0
  103. package/src/tools/commitments.js +47 -5
  104. package/src/tools/held-write.js +36 -13
  105. package/src/tools/index.js +27 -0
  106. package/src/tools/ingest.js +27 -2
  107. package/src/tools/memory.js +52 -14
  108. package/src/tools/page.js +95 -9
  109. package/src/tools/recall.js +208 -4
  110. package/src/tools/records-kit.js +2 -1
  111. package/src/tools/share.js +42 -3
  112. package/src/tools/shared.js +44 -4
  113. package/src/tools/space-lifecycle.js +278 -0
  114. package/src/tools/spaces.js +373 -29
  115. package/src/tools/status.js +9 -2
  116. package/src/tools/wiki.js +34 -4
  117. package/src/util.js +110 -6
  118. package/src/vendor/source-contract/README.md +24 -0
  119. package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
  120. package/src/vendor/source-contract/VENDOR.json +81 -0
  121. package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
  122. package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
  123. package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
  124. package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
  125. package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
  126. package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
  127. package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
  128. package/src/vendor/source-contract/cursor.js +26 -0
  129. package/src/vendor/source-contract/events.js +257 -0
  130. package/src/vendor/source-contract/registry.js +23 -0
  131. package/src/vendor/source-contract/tools-rpc.js +42 -0
  132. package/src/views/access-reads.js +256 -0
  133. package/src/views/communities.js +77 -0
  134. package/src/views/contracts.js +1183 -36
  135. package/src/views/inbox-bytes.js +103 -0
  136. package/src/views/overdue.js +1 -1
  137. package/src/views/profile.js +31 -0
  138. package/src/views/receipt.js +81 -0
  139. package/src/views/records-reads.js +869 -37
  140. package/src/views/rpc.js +159 -11
  141. package/src/views/shape.js +8 -5
  142. package/views/memory.html +16 -3
  143. package/views/pages.html +2 -2
  144. package/views/remembered.html +130 -0
package/src/config.js CHANGED
@@ -2,7 +2,7 @@ import fs from "node:fs"
2
2
  import os from "node:os"
3
3
  import path from "node:path"
4
4
  import { isPlainObject, toPositiveInt } from "./util.js"
5
- import { ASK_ACTIONS } from "./permissions.js"
5
+ import { NEVER_SKIPPED, SKIPPABLE_ASK_ACTIONS } from "./permissions.js"
6
6
 
7
7
  /** The bundled simulator: the core URL of local direct mode. */
8
8
  export const LOCAL_BASE_URL = "http://127.0.0.1:8420"
@@ -10,6 +10,15 @@ export const LOCAL_BASE_URL = "http://127.0.0.1:8420"
10
10
  const DEFAULTS = Object.freeze({
11
11
  /** Memory core base URL. Unset: `<controlURL>/core`, else the local simulator. */
12
12
  baseURL: "",
13
+ /**
14
+ * Jelly's "Use my own Memory service" switch (settings `ownService`). The
15
+ * plugin follows exactly what Jelly's sheet shows, which is the saved value
16
+ * or the declared default (`false`): off is the service the person's Jelly
17
+ * account offers, and no address or key of their own is read at all. Outside
18
+ * Jelly, unset still means "an address set means one", as every install
19
+ * before 0.11 meant it.
20
+ */
21
+ ownService: undefined,
13
22
  /**
14
23
  * Public gateway origin. When empty (and not inside Jelly), the plugin runs
15
24
  * against one fixed local scope.
@@ -47,6 +56,27 @@ const DEFAULTS = Object.freeze({
47
56
  tools: true,
48
57
  /** Opt-in only for hosts that expose the held-write Inbox decisions. */
49
58
  heldTeamWrites: false,
59
+ /**
60
+ * The actions a person's own page in a host may change, as the person, under a
61
+ * host-signed action grant (#58 section A). Off by default: every act answers
62
+ * ACTIONS_OFF and nothing is sent to records, which has its own switch
63
+ * (`RECORDS_ACTIONS_ENABLED`, empty by default). Both are off until Jelly
64
+ * settles the eight confirmations on opencode-mem#49.
65
+ */
66
+ actions: false,
67
+ /**
68
+ * Where a host's public action key is read, for a host that publishes a file
69
+ * rather than handing it to the engine (Jelly publishes it in the engine).
70
+ * Unset: only the published key verifies, so no file means no act.
71
+ */
72
+ actionKeysFile: "",
73
+ /**
74
+ * How old the action key file may be and still verify a grant: the same
75
+ * limit records applies (MEMORY_ACTION_KEYS_MAX_AGE_HOURS, default 24;
76
+ * 0 disables it). A file older than this, or stamped over five minutes in
77
+ * the future, is refused.
78
+ */
79
+ actionKeysMaxAgeHours: 24,
50
80
  /**
51
81
  * Default asks the person turned off: approval action names (ASK_ACTIONS in
52
82
  * src/permissions.js), as a list or one comma-separated string, such as
@@ -121,9 +151,13 @@ const ENV_MAP = {
121
151
  recordsWriteTimeoutMs: "MEMORY_RECORDS_WRITE_TIMEOUT_MS",
122
152
  captureTimeoutMs: "MEMORY_CAPTURE_TIMEOUT_MS",
123
153
  recordsWriteRetries: "MEMORY_RECORDS_WRITE_RETRIES",
154
+ actions: "MEM_ACTIONS",
155
+ actionKeysFile: "MEMORY_ACTION_KEYS_FILE",
156
+ actionKeysMaxAgeHours: "MEMORY_ACTION_KEYS_MAX_AGE_HOURS",
124
157
  }
125
158
 
126
159
  const BOOLEAN_KEYS = [
160
+ "ownService",
127
161
  "capture",
128
162
  "captureSubagents",
129
163
  "captureScenarios",
@@ -131,6 +165,7 @@ const BOOLEAN_KEYS = [
131
165
  "compactionCheckpoint",
132
166
  "tools",
133
167
  "heldTeamWrites",
168
+ "actions",
134
169
  "skills",
135
170
  "commands",
136
171
  "spool",
@@ -183,7 +218,7 @@ function parseAskList(value) {
183
218
  /** The known action names of a `skipAsks` value, and the others. */
184
219
  function splitAsks(value) {
185
220
  const named = parseAskList(value)
186
- return { names: Object.freeze(named.filter((name) => ASK_ACTIONS.includes(name))), unknown: Object.freeze(named.filter((name) => !ASK_ACTIONS.includes(name))) }
221
+ return { names: Object.freeze(named.filter((name) => SKIPPABLE_ASK_ACTIONS.includes(name))), unknown: Object.freeze(named.filter((name) => !SKIPPABLE_ASK_ACTIONS.includes(name))) }
187
222
  }
188
223
 
189
224
  /** JSON with comments and trailing commas (opencode.jsonc), parsed; strings keep their slashes. */
@@ -271,14 +306,14 @@ function userLevelOptions({ env = process.env, home = os.homedir(), packageName
271
306
  * accessors may appear after setup.
272
307
  *
273
308
  * @param {any} config resolveConfig's answer
274
- * @param {{ inJelly: () => boolean, user?: { names: readonly string[], unknown: readonly string[] } }} source
309
+ * @param {{ memoryResourceOffered: () => boolean, user?: { names: readonly string[], unknown: readonly string[] } }} source
275
310
  */
276
- export function applySkipAsksSource(config, { inJelly, user = userLevelSkipAsks() }) {
311
+ export function applySkipAsksSource(config, { memoryResourceOffered, user = userLevelSkipAsks() }) {
277
312
  const fromOptions = config.optionSkipAsks ?? Object.freeze([])
278
313
  const optionUnknown = config.unknownSkipAsks ?? Object.freeze([])
279
314
  const jelly = () => {
280
315
  try {
281
- return Boolean(inJelly?.())
316
+ return Boolean(memoryResourceOffered?.())
282
317
  } catch {
283
318
  return false
284
319
  }
@@ -329,6 +364,10 @@ export function resolveConfig(options = {}, env = process.env) {
329
364
  merged.recordsWriteRetries = Number.isInteger(value) && value >= 0 ? Math.min(value, 5) : DEFAULTS.recordsWriteRetries
330
365
  }
331
366
  merged.collectEveryMinutes = Math.min(Math.max(merged.collectEveryMinutes, 5), 1440)
367
+ {
368
+ const value = Number(merged.actionKeysMaxAgeHours)
369
+ merged.actionKeysMaxAgeHours = Number.isInteger(value) && value >= 0 ? Math.min(value, 8760) : DEFAULTS.actionKeysMaxAgeHours
370
+ }
332
371
  {
333
372
  // What the plugin options say. Outside Jelly the plugin uses the
334
373
  // user-level config's value instead (applySkipAsksSource), because a
@@ -339,6 +378,40 @@ export function resolveConfig(options = {}, env = process.env) {
339
378
  Object.defineProperty(merged, "unknownSkipAsks", { value: split.unknown, enumerable: false, writable: true, configurable: true })
340
379
  }
341
380
 
381
+ // The switch, exactly as Jelly's sheet shows it: the saved value, else the
382
+ // declared default (`false`). Off means the service the person's Jelly
383
+ // account offers, so nothing of their own is read — no address, no key, and
384
+ // no explicit core or knowledge URL either (a key of one's own must never
385
+ // reach Jelly's Memory). Outside Jelly an unset switch keeps the rule every
386
+ // install before 0.11 used: an address set means one.
387
+ const memoryResourceOffered = input.memoryResourceOffered === true
388
+ const savedAddress = Boolean(merged.controlURL)
389
+ if (merged.ownService === undefined) merged.ownService = memoryResourceOffered ? false : savedAddress
390
+ let ownServiceNote = ""
391
+ if (!merged.ownService) {
392
+ // Inside Jelly with an address saved before 0.11, the sheet shows the
393
+ // switch off: the address is not used, and the person is told so rather
394
+ // than switched to another server silently.
395
+ if (savedAddress && memoryResourceOffered) ownServiceNote = "paused"
396
+ merged.controlURL = ""
397
+ if (memoryResourceOffered) {
398
+ // Nothing of the person's own is read inside Jelly: an explicit core or
399
+ // knowledge URL is an address of one's own too, and their key must never
400
+ // reach the service Jelly offers, which is another operator's server.
401
+ merged.baseURL = ""
402
+ merged.knowledgeURL = ""
403
+ merged.token = ""
404
+ merged.keyAllowed = false
405
+ }
406
+ } else if (!merged.controlURL) {
407
+ // On with no address: load normally and answer "unconfigured", never throw
408
+ // (Jelly saves the switch the moment it changes, so every person passes
409
+ // through this state before typing the address).
410
+ ownServiceNote = "incomplete"
411
+ }
412
+ merged.ownServiceNote = ownServiceNote
413
+ merged.memoryResourceOffered = memoryResourceOffered
414
+
342
415
  for (const key of ["baseURL", "controlURL", "knowledgeURL"]) {
343
416
  if (!merged[key]) continue
344
417
  let parsed
@@ -404,6 +477,6 @@ export function configWarnings(config, { credentialSource = config.token ? "opti
404
477
  warnings.push("captureSubagents=true; subagent sessions are captured and pinned like primary sessions")
405
478
  if (config.skipAsks?.length) warnings.push(`skipAsks=${config.skipAsks.join(",")}; these run without asking (a held team write still waits in the Inbox)`)
406
479
  if (config.ignoredSkipAsks?.length) warnings.push(`skipAsks ${config.ignoredSkipAsks.join(", ")} ignored: outside Jelly it is read only from the user-level config (~/.config/opencode/opencode.json), never from a project's`)
407
- if (config.unknownSkipAsks?.length) warnings.push(`skipAsks ignores ${config.unknownSkipAsks.join(", ")}: not one of ${ASK_ACTIONS.join(", ")}`)
480
+ if (config.unknownSkipAsks?.length) warnings.push(`skipAsks ignores ${config.unknownSkipAsks.join(", ")}: not one of ${SKIPPABLE_ASK_ACTIONS.join(", ")}${config.unknownSkipAsks.some((name) => NEVER_SKIPPED.includes(name)) ? ` (${NEVER_SKIPPED.join(", ")} always ask)` : ""}`)
408
481
  return warnings
409
482
  }
package/src/connect.js CHANGED
@@ -29,6 +29,20 @@ export const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
29
29
  export const ACCESS_MARGIN_MS = 60_000
30
30
  /** While not connected, OpenCode is asked again at most this often. */
31
31
  export const PROBE_EVERY_MS = 5_000
32
+ /**
33
+ * The longest a read of OpenCode's credential store may take before it is
34
+ * answered as unavailable. OpenCode's own renewal has a 30-second timeout
35
+ * (`docs/design/plugin-sign-in.md`), and this plugin's token POST has its own
36
+ * (`REQUEST_TIMEOUT_MS`), so a read is bounded already; this is the bound for
37
+ * everything else between them, so nothing a start or a tool waits for can hang.
38
+ */
39
+ export const READ_DEADLINE_MS = 10_000
40
+ /**
41
+ * The longest `stored()` may take. It reads the host's own store and makes no
42
+ * request, so this is only a guard: a host that somehow blocks there costs the
43
+ * start this much and no more, and the probe still answers afterwards.
44
+ */
45
+ export const STORED_DEADLINE_MS = 250
32
46
  const REQUEST_TIMEOUT_MS = 15_000
33
47
  /** Consecutive network failures while polling before the sign-in gives up. */
34
48
  const POLL_FAILURES_MAX = 5
@@ -235,9 +249,31 @@ export async function registerConnect(ctx, options) {
235
249
  return registration ?? null
236
250
  }
237
251
 
252
+ /**
253
+ * `promise`, or a rejection once `ms` has passed: the bound on a host call, so
254
+ * nothing a start or a tool waits for can hang. The host call itself keeps
255
+ * running (a renewal must finish for OpenCode to store it); its result is
256
+ * simply not waited for.
257
+ */
258
+ function withinDeadline(promise, ms, what) {
259
+ let timer
260
+ return Promise.race([
261
+ promise,
262
+ new Promise((_, reject) => {
263
+ timer = setTimeout(() => reject(new CredentialError(`${what} did not answer within ${ms} ms`, "unavailable")), ms)
264
+ timer.unref?.()
265
+ }),
266
+ ]).finally(() => clearTimeout(timer))
267
+ }
268
+
238
269
  /**
239
270
  * The bearer from OpenCode's stored Memory sign-in, for `src/credentials.js`.
240
271
  *
272
+ * At a start, the host's own store is read and nothing else: setup asks
273
+ * `stored()`, then starts `warm()` and awaits neither a renewal nor the probe
274
+ * (jelly's ask, opencode-mem#58). Whatever needs the answer joins the one read
275
+ * in flight at first use (`probe`), and every host call is bounded.
276
+ *
241
277
  * @param {{ integration?: any, origin: () => string, log?: any, now?: () => number }} input
242
278
  */
243
279
  export function createConnectSource(input) {
@@ -250,6 +286,8 @@ export function createConnectSource(input) {
250
286
  let connected = false
251
287
  let probedAt = -Infinity
252
288
  let reading = null
289
+ /** `warm()`'s promise: the probe a start made in the background, or null. */
290
+ let warming = null
253
291
  /** The access token reported as refused, while the connection shows Sign in required. */
254
292
  let refused = ""
255
293
  let mismatchLogged = false
@@ -270,8 +308,16 @@ export function createConnectSource(input) {
270
308
  let connection
271
309
  let credential
272
310
  try {
273
- connection = await integration.connection.active(INTEGRATION_ID)
274
- credential = connection ? await integration.connection.resolve(connection) : undefined
311
+ const answer = await withinDeadline(
312
+ (async () => {
313
+ const found = await integration.connection.active(INTEGRATION_ID)
314
+ return { connection: found, credential: found ? await integration.connection.resolve(found) : undefined }
315
+ })(),
316
+ READ_DEADLINE_MS,
317
+ "OpenCode",
318
+ )
319
+ connection = answer.connection
320
+ credential = answer.credential
275
321
  } catch (error) {
276
322
  cached = null
277
323
  throw new CredentialError(`OpenCode could not read Memory's sign-in: ${error instanceof Error ? error.message.slice(0, 200) : "unknown error"}`, "unavailable")
@@ -302,22 +348,74 @@ export function createConnectSource(input) {
302
348
  return reading
303
349
  }
304
350
 
351
+ /** Learn whether a sign-in exists now; asks OpenCode at most every few seconds while there is none. */
352
+ async function probe({ report = false } = {}) {
353
+ if (!supported) return false
354
+ // A read already in flight is the answer a first use is waiting for: join
355
+ // it, rather than answering "no sign-in" from the throttle below, which
356
+ // only exists to spare a host that has already said there is none.
357
+ if (reading) {
358
+ try {
359
+ await reading
360
+ } catch {
361
+ /* reported by the read's own caller, or by `warm` when nothing waits */
362
+ }
363
+ return connected
364
+ }
365
+ if (!connected && now() - probedAt < PROBE_EVERY_MS) return false
366
+ try {
367
+ await read()
368
+ } catch (error) {
369
+ // Nobody awaits a start's probe, so it names its own failure once. The
370
+ // first use asks again: the throttle is `PROBE_EVERY_MS`, never a stop.
371
+ if (report) {
372
+ log?.warn?.("Memory's sign-in could not be read; it is asked again on first use", {
373
+ error: error instanceof Error ? error.message.slice(0, 200) : "unknown error",
374
+ })
375
+ }
376
+ }
377
+ return connected
378
+ }
379
+
305
380
  return {
306
381
  /** The host can hold a Memory sign-in. */
307
382
  supported,
308
383
  /** OpenCode held a usable Memory sign-in at the last read. Synchronous. */
309
384
  connected: () => supported && connected,
310
- /** Learn whether a sign-in exists now; asks OpenCode at most every few seconds while there is none. */
311
- async probe() {
385
+ /**
386
+ * Whether OpenCode holds a Memory sign-in on this machine, from its own
387
+ * credential store alone: no renewal and no request.
388
+ *
389
+ * This is the start's own answer — its log line and its warnings — because
390
+ * it is local, and a start may not wait for the network. It says a sign-in
391
+ * is stored, not that it is this address's: only a read checks the origin,
392
+ * and `probe` replaces this answer with that one. Nothing about the tool
393
+ * list or a tool's words depends on it: a tool asks `probeSignIn` at its
394
+ * first use (`src/credentials.js`).
395
+ */
396
+ async stored() {
312
397
  if (!supported) return false
313
- if (!connected && now() - probedAt < PROBE_EVERY_MS) return false
314
398
  try {
315
- await read()
399
+ const connection = await withinDeadline(integration.connection.active(INTEGRATION_ID), STORED_DEADLINE_MS, "OpenCode's credential store")
400
+ return Boolean(connection)
316
401
  } catch {
317
- /* reported on use */
402
+ return false
318
403
  }
319
- return connected
320
404
  },
405
+ /**
406
+ * Probe now, in the background: the start's half of the same answer.
407
+ *
408
+ * Setup calls this and awaits nothing (`src/index.js`). The promise never
409
+ * rejects — a failure is logged, once — so nothing it starts can become an
410
+ * unhandled rejection, and a first use that arrives meanwhile joins its read
411
+ * (`probe`).
412
+ */
413
+ warm() {
414
+ if (!supported) return Promise.resolve(false)
415
+ warming ??= probe({ report: true })
416
+ return warming
417
+ },
418
+ probe,
321
419
  /** The access token for one request, or "" with no sign-in. */
322
420
  async bearer() {
323
421
  if (!supported) return ""
@@ -364,7 +364,20 @@ export function originOf(value) {
364
364
  * }} [input]
365
365
  */
366
366
  export function createCredentials(input = {}) {
367
- const optionToken = typeof input.token === "string" ? input.token : ""
367
+ /**
368
+ * Whether a key of the person's own may be read at all (jelly's `ownService`).
369
+ * Off, neither the `token` option nor the key in the plugin's settings is
370
+ * read, so no request can carry one to the service the Jelly account offers.
371
+ */
372
+ const keyAllowed = input.keyAllowed !== false
373
+ /**
374
+ * Whether Jelly's identity token may be used at all. Inside Jelly with the
375
+ * switch **on**, it may not: that token is minted for Jelly's Memory (it has
376
+ * no `cnf`, so another operator could replay it there) and must never be sent
377
+ * to an address of one's own. Only the key or `/connect` is used then.
378
+ */
379
+ const identityAllowed = input.identityAllowed !== false
380
+ const optionToken = keyAllowed && typeof input.token === "string" ? input.token : ""
368
381
  /** OpenCode's `/connect` sign-in (src/connect.js), or null. */
369
382
  const connect = input.connect ?? null
370
383
  const holder = input.holder ?? globalThis
@@ -540,6 +553,7 @@ export function createCredentials(input = {}) {
540
553
 
541
554
  /** The key saved in the plugin's settings, or "". */
542
555
  function secretToken() {
556
+ if (!keyAllowed) return ""
543
557
  const accessor = secrets()
544
558
  if (!accessor) return ""
545
559
  try {
@@ -570,9 +584,9 @@ export function createCredentials(input = {}) {
570
584
  * `not_signed_in`, it stays the Jelly sign-in: the only candidate, whose
571
585
  * requests fail with the reason.
572
586
  */
573
- function source() {
587
+ function source(target = undefined) {
574
588
  if (optionToken) return SOURCES.option
575
- if (memoryResource()) {
589
+ if (identityResource(target)) {
576
590
  const refused = held(peek())
577
591
  if (refused && FALLBACK_CODES.includes(refused.code) && !unlinkedRefusal(refused) && secretToken()) {
578
592
  return SOURCES.secret
@@ -588,9 +602,9 @@ export function createCredentials(input = {}) {
588
602
  * The source in use and, during a hold, the code Jelly refused with ("" when
589
603
  * none; `not_signed_in` for an unlinked speaker), for `mem_status`.
590
604
  */
591
- function describe() {
592
- const source_ = source()
593
- const refused = source_ === SOURCES.option ? null : memoryResource() ? held(peek()) : null
605
+ function describe(target = undefined) {
606
+ const source_ = source(target)
607
+ const refused = source_ === SOURCES.option ? null : identityResource(target) ? held(peek()) : null
594
608
  return { source: source_, refused: unlinkedRefusal(refused) ? NOT_SIGNED_IN : (refused?.code ?? "") }
595
609
  }
596
610
 
@@ -630,11 +644,6 @@ export function createCredentials(input = {}) {
630
644
  return source() === SOURCES.connect
631
645
  }
632
646
 
633
- /** Jelly's core plugin has published at least one accessor in this engine. */
634
- function inJelly() {
635
- return Boolean(identity() || secrets())
636
- }
637
-
638
647
  /** The gateway origin the identity accessor advertises, or "". */
639
648
  function origin() {
640
649
  return memoryResource()?.url ?? ""
@@ -769,18 +778,45 @@ export function createCredentials(input = {}) {
769
778
  )
770
779
  }
771
780
 
781
+ /**
782
+ * The identity resource a request to `target` may carry, or null. The
783
+ * resource-token contract (§1, `url`) is the rule: the host's token names one
784
+ * service, so it is sent only to that resource's origin — never to any other
785
+ * origin, in any mode, whether the resource arrived at setup or later.
786
+ * `target` undefined is an internal caller with no network destination.
787
+ */
788
+ function identityResource(target) {
789
+ if (!identityAllowed) return null
790
+ const resource = memoryResource()
791
+ if (!resource) return null
792
+ if (target === undefined) return resource
793
+ let wanted = ""
794
+ try {
795
+ const url = new URL(String(target))
796
+ wanted = /^https?:$/.test(url.protocol) ? url.origin : ""
797
+ } catch {
798
+ wanted = ""
799
+ }
800
+ return wanted && wanted === resource.url ? resource : null
801
+ }
802
+
772
803
  /**
773
804
  * The bearer for one request of the current session, or "" when no source
774
- * has one. A Jelly token that cannot be had falls back to the pasted key
775
- * (see the module comment), or rejects with a CredentialError.
805
+ * has one. `target` is that request's URL; the identity token is used only
806
+ * for the resource's own origin. A Jelly token that cannot be had falls back
807
+ * to the pasted key (see the module comment), or rejects with a
808
+ * CredentialError.
776
809
  *
810
+ * @param {string} [target] the URL the request is sent to; the identity token
811
+ * is used only for the resource's own origin
777
812
  * @returns {Promise<string>}
778
813
  */
779
- async function bearer() {
814
+ async function bearer(target = undefined) {
815
+ const resource = identityResource(target)
780
816
  const strict = strictIdentity()
781
- if (strict && (optionToken || !memoryResource() || !sessionAsks)) throw new CredentialError("a caller-specific Jelly memory token is required", "not_enrolled")
817
+ if (strict && (optionToken || !resource || !sessionAsks)) throw new CredentialError("a caller-specific Jelly memory token is required", "not_enrolled")
782
818
  if (optionToken) return optionToken
783
- if (!memoryResource()) {
819
+ if (!resource) {
784
820
  const signedIn = connect ? await connect.bearer() : ""
785
821
  return signedIn || secretToken()
786
822
  }
@@ -814,12 +850,15 @@ export function createCredentials(input = {}) {
814
850
  * tokens are not touched.
815
851
  *
816
852
  * @param {string} rejected the bearer the gateway refused
853
+ * @param {string} [target] the URL the request was sent to
817
854
  * @returns {Promise<string>}
818
855
  */
819
- async function refresh(rejected) {
856
+ async function refresh(rejected, target = undefined) {
820
857
  if (optionToken) return ""
821
- if (!memoryResource()) {
822
- // OpenCode is asked again for its sign-in; a pasted key is not retried.
858
+ if (!identityResource(target)) {
859
+ // A resource that is not this request's origin is never asked; OpenCode
860
+ // is asked again for its sign-in, and a pasted key is not retried.
861
+ if (memoryResource()) return ""
823
862
  return connect && rejected && connect.owns(rejected) ? connect.refresh(rejected) : ""
824
863
  }
825
864
  if (!rejected || rejected === secretToken()) return ""
@@ -842,7 +881,7 @@ export function createCredentials(input = {}) {
842
881
  return sessions.size
843
882
  }
844
883
 
845
- return { source, describe, unlinked, check, probeSignIn, inJelly, origin, bearer, refresh, userTurn, forget, subject, sessionCount, memoryResource }
884
+ return { source, describe, unlinked, check, probeSignIn, origin, bearer, refresh, userTurn, forget, subject, sessionCount, memoryResource }
846
885
  }
847
886
 
848
887
  /**
@@ -868,17 +907,26 @@ export function credentialLine({ source, refused }) {
868
907
  * gateway deployment needs a credential: local direct mode (no gateway, not in
869
908
  * Jelly) runs without one, as before.
870
909
  *
871
- * @param {{ source: string, controlURL: string, inJelly: boolean }} state
910
+ * @param {{ source: string, controlURL: string, memoryResourceOffered: boolean }} state
872
911
  */
873
- export function unavailableReason({ source, controlURL, inJelly }) {
912
+ export function unavailableReason({ source, controlURL, memoryResourceOffered, ownServiceNote = "" }) {
913
+ // The switch's own two states, in words that name a field the sheet shows:
914
+ // on with no address, and an address saved before 0.11 that the sheet's
915
+ // switch-off does not use.
916
+ if (ownServiceNote === "incomplete") {
917
+ return "Memory is unavailable: \"Use my own Memory service\" is on and the address is empty; set the Memory address in Memory's settings."
918
+ }
919
+ if (ownServiceNote === "paused") {
920
+ return "Memory is unavailable: the saved Memory address is not in use until \"Use my own Memory service\" is turned on in Memory's settings."
921
+ }
874
922
  if (!source) {
875
- return inJelly
923
+ return memoryResourceOffered
876
924
  ? "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."
877
925
  : "Memory is unavailable: no memory key is set; run /connect and choose Memory, or set the token option or MEMORY_TOKEN to a key from Memory's /account page."
878
926
  }
879
927
  if (!controlURL) {
880
- return inJelly
881
- ? "Memory is unavailable: no memory address is known; set controlURL in the plugin's settings."
928
+ return memoryResourceOffered
929
+ ? "Memory is unavailable: no memory address is known; turn on \"Use my own Memory service\" and set the address in Memory's settings."
882
930
  : "Memory is unavailable: no memory address is known; set the controlURL option or MEMORY_CONTROL_URL."
883
931
  }
884
932
  return ""
@@ -893,6 +941,56 @@ export function unavailableReason({ source, controlURL, inJelly }) {
893
941
  * @param {Record<string, any>} config the resolved configuration
894
942
  * @param {() => string} origin
895
943
  */
944
+ /**
945
+ * Whether this engine was handed a resource token for the resource named
946
+ * `memory`: the identity accessor advertises it in `resources()`
947
+ * (`~/hey-jelly/docs/architecture/resource-token-contract.md` §1 and §6).
948
+ *
949
+ * This is a contract fact, never a host's name. An accessor that advertises
950
+ * other resources, or none, is not this plugin's; a plugin-secrets accessor is
951
+ * a different channel and says nothing about a resource.
952
+ */
953
+ export function memoryResourceAvailable(holder = globalThis) {
954
+ const accessor = readGlobal(holder, IDENTITY_SYMBOL)
955
+ if (!accessor || typeof member(accessor, "resources") !== "function") return false
956
+ let list
957
+ try {
958
+ list = accessor.resources()
959
+ } catch {
960
+ return false
961
+ }
962
+ return Array.isArray(list) && list.some((entry) => member(entry, "name") === MEMORY_RESOURCE)
963
+ }
964
+
965
+ /**
966
+ * Whether this engine was handed the host's plugin secret store
967
+ * (`~/hey-jelly/backend/plugins/runtime/src/handoff.ts`: installed in every
968
+ * engine, so on its own it says nothing about a `memory` resource).
969
+ */
970
+ export function secretStoreAvailable(holder = globalThis) {
971
+ const accessor = readGlobal(holder, PLUGIN_SECRETS_SYMBOL)
972
+ return Boolean(accessor && typeof member(accessor, "get") === "function")
973
+ }
974
+
975
+ /** The `memory` resource's origin, or "": what `followOrigin` follows (resource-token contract §1). */
976
+ export function memoryResourceOrigin(holder = globalThis) {
977
+ const accessor = readGlobal(holder, IDENTITY_SYMBOL)
978
+ if (!accessor || typeof member(accessor, "resources") !== "function") return ""
979
+ let list
980
+ try {
981
+ list = accessor.resources()
982
+ } catch {
983
+ return ""
984
+ }
985
+ if (!Array.isArray(list)) return ""
986
+ for (const entry of list) {
987
+ if (member(entry, "name") !== MEMORY_RESOURCE) continue
988
+ const url = originOf(member(entry, "url"))
989
+ if (url) return url
990
+ }
991
+ return ""
992
+ }
993
+
896
994
  export function followOrigin(config, origin) {
897
995
  const explicit = config.explicitURLs ?? {}
898
996
  const define = (key, get) => Object.defineProperty(config, key, { get, enumerable: true, configurable: true })