@joe-broadhead/opencode-mem 0.9.5 → 0.9.12

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 (53) hide show
  1. package/CHANGELOG.md +1281 -0
  2. package/README.md +105 -31
  3. package/docs/agent-protocol.md +28 -27
  4. package/docs/permissions.md +148 -0
  5. package/package.json +24 -12
  6. package/skills/mem.pages/SKILL.md +35 -16
  7. package/skills/mem.sharing/SKILL.md +39 -6
  8. package/skills/mem.sources/SKILL.md +41 -10
  9. package/skills/mem.usage/SKILL.md +37 -16
  10. package/src/backend/records.js +8 -0
  11. package/src/backend/v3.js +15 -10
  12. package/src/call-shapes.js +18 -25
  13. package/src/capture-pause.js +136 -0
  14. package/src/capture.js +7 -5
  15. package/src/collector-service.js +212 -35
  16. package/src/collector.js +186 -47
  17. package/src/commands.js +37 -0
  18. package/src/compaction.js +4 -2
  19. package/src/config.js +151 -1
  20. package/src/curation.js +6 -10
  21. package/src/events.js +144 -36
  22. package/src/forget-purge.js +377 -0
  23. package/src/forgotten.js +152 -0
  24. package/src/hooks.js +9 -4
  25. package/src/index.js +5 -3
  26. package/src/permissions.js +116 -38
  27. package/src/protocol.js +21 -11
  28. package/src/records.js +4 -1
  29. package/src/runtime.js +202 -15
  30. package/src/shapes.js +63 -0
  31. package/src/sources.js +183 -12
  32. package/src/spaces.js +58 -1
  33. package/src/spool.js +442 -64
  34. package/src/stated.js +334 -0
  35. package/src/storable.js +477 -0
  36. package/src/tools/aliases.js +36 -147
  37. package/src/tools/commitments.js +69 -12
  38. package/src/tools/index.js +25 -43
  39. package/src/tools/ingest.js +33 -128
  40. package/src/tools/memory.js +503 -904
  41. package/src/tools/page-sections.js +147 -0
  42. package/src/tools/page.js +314 -82
  43. package/src/tools/recall-browse.js +173 -0
  44. package/src/tools/recall.js +36 -8
  45. package/src/tools/share.js +494 -131
  46. package/src/tools/shared.js +97 -19
  47. package/src/tools/spaces.js +194 -101
  48. package/src/tools/status.js +31 -3
  49. package/src/tools/wiki.js +5 -13
  50. package/src/util.js +10 -59
  51. package/src/views/profile.js +2 -3
  52. package/src/views/records-reads.js +6 -1
  53. package/src/erase.js +0 -36
package/src/runtime.js CHANGED
@@ -9,6 +9,9 @@ import { UNLINKED_SENTENCE, asSession, credentialLine, unavailableReason } from
9
9
  import { createControlClient } from "./spaces.js"
10
10
  import { createSkillContexts } from "./skill-contexts.js"
11
11
  import { createSpool } from "./spool.js"
12
+ import { createForgetPurge } from "./forget-purge.js"
13
+ import { createCapturePause } from "./capture-pause.js"
14
+ import { createStatedText } from "./stated.js"
12
15
  import { errorMessage, oneLine, rememberBounded, shortHash } from "./util.js"
13
16
 
14
17
  /** A session bind uses a shorter bound so prompt construction never waits long. */
@@ -57,6 +60,8 @@ export function createRuntime(input) {
57
60
  const credentials = input.credentials ?? null
58
61
  /** Wall clock for cache expiry and spool scheduling; injectable for tests. Deadlines use real time. */
59
62
  const now = typeof input.now === "function" ? input.now : Date.now
63
+ /** The per-session capture pause (/mem-pause, /mem-resume): no turn, summary or checkpoint while set. */
64
+ const capturePause = createCapturePause({ stateDir: config.stateDir, log, now: () => new Date(now()) })
60
65
  /** `${sessionID}::${agent}` -> the pinned block and its refresh state. */
61
66
  const pins = new Map()
62
67
  /** `${sessionID}::${agent}` -> { context, expires }: the session context, cached for the TTL. */
@@ -87,6 +92,8 @@ export function createRuntime(input) {
87
92
  const clock = createClock(config)
88
93
  /** Today's date in the agent's zone: part of the pinned block's cache key. */
89
94
  const today = () => dayIn(clock.now(), clock.zone)
95
+ /** The person's recent messages per session, for the writes that keep only what they said (src/stated.js). */
96
+ const stated = createStatedText({ now: clock.now })
90
97
  const gatewayMode = input.gateway ?? Boolean(config.controlURL)
91
98
  const control =
92
99
  input.control ??
@@ -145,8 +152,14 @@ export function createRuntime(input) {
145
152
  * container, user, and agent; without one the fixed local scope applies.
146
153
  */
147
154
  function scopeFor(context, overrides = {}) {
155
+ // A data-plane call with a space and a session lets the gateway's context
156
+ // lookup bind the session to that space (control before 0.9.7). The
157
+ // session goes only with the space the session is bound to; a space a call
158
+ // names, or the personal space read for a shared-bound session, goes alone.
159
+ const foreign = Boolean(context?.space_id) && context.session_space_id !== context.space_id
148
160
  return resolveScope(config, {
149
161
  ...overrides,
162
+ ...(foreign ? { sessionID: undefined } : {}),
150
163
  spaceID: context?.space_id,
151
164
  containerID: context?.container_id,
152
165
  user: overrides.user || context?.user_id,
@@ -168,7 +181,7 @@ export function createRuntime(input) {
168
181
 
169
182
  /**
170
183
  * The task a session declared most recently through mem_recall, mem_remember,
171
- * or mem_forget. Captured turns and the compaction checkpoint of that session
184
+ * or revise forget. Captured turns and the compaction checkpoint of that session
172
185
  * carry it as `x-tdai-task-id`. Returns the stored key, or "" when the value
173
186
  * clears the task or has no usable characters.
174
187
  */
@@ -194,17 +207,21 @@ export function createRuntime(input) {
194
207
  if (!control) return null
195
208
  const space = String(overrides.space ?? "").trim()
196
209
  const agent = overrides.agent && overrides.agent !== "auto" ? String(overrides.agent) : undefined
210
+ // Only an explicit bind (mem_spaces current with bind) changes the
211
+ // session's binding. A space named for one call is resolved without the
212
+ // session: control before 0.9.7 binds any session sent with a space.
213
+ const bind = overrides.bind === true && Boolean(overrides.sessionID)
197
214
  const context = await control.resolveContext({
198
215
  userId: overrides.userId || config.user,
199
216
  spaceId: space || undefined,
200
- sessionId: overrides.sessionID,
217
+ sessionId: space && !bind ? undefined : overrides.sessionID,
201
218
  agent,
219
+ ...(bind ? { bind: true } : {}),
202
220
  })
203
- // An explicit space together with a session binds the session to that
204
- // space. When that changes the session's space, the cached session context
221
+ // A bind that changes the session's space makes the cached session context
205
222
  // and the pinned block belong to the previous binding: the next model call
206
223
  // starts a new epoch. Re-binding to the same space changes nothing.
207
- if (space && overrides.sessionID && cachedSpaceOf(overrides.sessionID) !== context?.space_id) {
224
+ if (bind && cachedSpaceOf(overrides.sessionID) !== context?.space_id) {
208
225
  invalidate(overrides.sessionID)
209
226
  }
210
227
  return context
@@ -245,6 +262,55 @@ export function createRuntime(input) {
245
262
  return context
246
263
  }
247
264
 
265
+ /**
266
+ * Run a data-plane call that must carry a session with a space that may not
267
+ * be the session's own (deleting turns needs the session they were written
268
+ * under). Control before 0.9.7 binds a session sent with a space, so for a
269
+ * session this process has resolved, the binding is read before the call
270
+ * and put back with an explicit bind if the call moved it. Other sessions,
271
+ * and a control that only binds on request, take the call as it is.
272
+ *
273
+ * @template T
274
+ * @param {{ space_id?: string, session_id?: string, agent_id?: string } | null | undefined} scope
275
+ * @param {() => Promise<T>} run
276
+ * @param {string[]} [notes] receives a sentence when the binding could not be
277
+ * put back, so the caller's answer can tell the person
278
+ * @returns {Promise<T>}
279
+ */
280
+ async function keepBinding(scope, run, notes = []) {
281
+ const sessionID = scope?.session_id
282
+ const space = scope?.space_id
283
+ if (!control || !sessionID || !space || cachedSpaceOf(sessionID) === undefined) return run()
284
+ // No agent hint: the session keeps the agent it runs as.
285
+ const agent = undefined
286
+ let prior = ""
287
+ try {
288
+ prior = (await resolveContext({ sessionID, agent }))?.session_space_id || ""
289
+ } catch {
290
+ prior = ""
291
+ }
292
+ if (!prior || prior === space) return run()
293
+ try {
294
+ return await run()
295
+ } finally {
296
+ let after = ""
297
+ try {
298
+ after = (await resolveContext({ sessionID, agent }))?.session_space_id || ""
299
+ if (after !== prior) {
300
+ await resolveContext({ space: prior, sessionID, agent, bind: true })
301
+ log.info("restored a session binding an older control moved", { sessionID })
302
+ }
303
+ } catch (error) {
304
+ log.warn("could not restore the session binding after a delete", { sessionID, error: errorMessage(error) })
305
+ const now = after && after !== prior ? after : space
306
+ notes.push(
307
+ `The session may now be bound to ${oneLine(now, 80)}, not ${oneLine(prior, 80)}: an older Memory control binds a session sent with a space, and putting the binding back failed (${oneLine(errorMessage(error), 160)}). ` +
308
+ `Rebind with mem_spaces({"action": "current", "bind": {"space": "personal"}}) or mem_spaces({"action": "current", "bind": {"space": "${oneLine(prior, 80)}"}}); check it with mem_spaces({"action": "current"}).`,
309
+ )
310
+ }
311
+ }
312
+ }
313
+
248
314
  /** The space of any context cached for a session, whatever the agent. */
249
315
  function cachedSpaceOf(sessionID) {
250
316
  const prefix = `${sessionID}::`
@@ -254,6 +320,24 @@ export function createRuntime(input) {
254
320
  return undefined
255
321
  }
256
322
 
323
+ /**
324
+ * The space a captured turn will most likely land in, as far as this
325
+ * machine knows without a request ("" when not known). Recorded with a
326
+ * spooled turn so a pending forget holds back that space's turns only
327
+ * (src/forget-purge.js); never used to place the turn.
328
+ */
329
+ function spaceHint(sessionID, visibility = config.captureVisibility) {
330
+ if (!control) return scope({ sessionID }).space_id ?? ""
331
+ if (visibility === "team") {
332
+ for (const [key, cached] of sessionContexts) {
333
+ if (key.startsWith(`${sessionID}::`) && cached.context?.space_kind === "shared") return cached.context.space_id ?? ""
334
+ }
335
+ return ""
336
+ }
337
+ for (const cached of sessionContexts.values()) if (cached.context?.personal_space_id) return cached.context.personal_space_id
338
+ return ""
339
+ }
340
+
257
341
  /** The session context cached by the last fresh resolution, if still within the TTL. */
258
342
  function cachedSessionContext(sessionID, agent) {
259
343
  if (!sessionID) return null
@@ -328,12 +412,15 @@ export function createRuntime(input) {
328
412
  * fallback to the data plane: that would put the container choice back in
329
413
  * the plugin.
330
414
  *
331
- * @param {{ sessionID: string, agent?: string, visibility?: string, task?: string, payload: object }} input
415
+ * `key` is the turn's idempotency key (`turnKey`): the gateway answers a
416
+ * repeat from its receipt instead of storing the turn twice.
417
+ *
418
+ * @param {{ sessionID: string, agent?: string, visibility?: string, task?: string, payload: object, key?: string }} input
332
419
  */
333
- async function captureTurn({ sessionID, agent, visibility, task, payload }) {
420
+ async function captureTurn({ sessionID, agent, visibility, task, payload, key }) {
334
421
  const requested = visibility === "team" ? "team" : "private"
335
422
  const hint = agent && agent !== "auto" ? String(agent) : undefined
336
- const send = (as) => backend.captureTurn({ sessionID, agent: hint, visibility: as, task, payload })
423
+ const send = (as) => backend.captureTurn({ sessionID, agent: hint, visibility: as, task, payload, ...(key ? { key } : {}) })
337
424
  try {
338
425
  return await send(requested)
339
426
  } catch (error) {
@@ -720,7 +807,7 @@ export function createRuntime(input) {
720
807
  *
721
808
  * @param {{ sessionID?: string, agent?: string, messages?: any[], timeoutMs?: number, model?: any, directory?: string }} input
722
809
  * @returns {Promise<{ ok: boolean, chars: number, sessionID: string, reason?: string }>}
723
- * `reason` says why nothing was written: no-session, disabled, unavailable, subagent,
810
+ * `reason` says why nothing was written: no-session, disabled, paused, unavailable, subagent,
724
811
  * context-unresolved, no-context, empty, duplicate, or write-failed.
725
812
  */
726
813
  function writeCompactionCheckpoint(input = {}) {
@@ -735,6 +822,9 @@ export function createRuntime(input) {
735
822
  const skipped = (reason) => ({ ok: false, chars: 0, sessionID, reason })
736
823
  if (!sessionID) return skipped("no-session")
737
824
  if (config.compactionCheckpoint === false) return skipped("disabled")
825
+ // The person paused capture in this session (/mem-pause): the checkpoint
826
+ // summarises the whole transcript, so it stays off even after a resume.
827
+ if (capturePause.everPaused(sessionID)) return skipped("paused")
738
828
  // As the session compacting: its token, or nothing when its speaker has
739
829
  // no Jelly account linked on this host.
740
830
  if (await availability()) return skipped("unavailable")
@@ -771,7 +861,7 @@ export function createRuntime(input) {
771
861
  }
772
862
 
773
863
  const label = context ? contextScopeLabel(context, scoped) : scopeLabel(scoped)
774
- const checkpoint = buildCheckpoint({
864
+ const built = buildCheckpoint({
775
865
  sessionID,
776
866
  agent: input.agent,
777
867
  messages,
@@ -779,10 +869,16 @@ export function createRuntime(input) {
779
869
  now: new Date(),
780
870
  directory: typeof input.directory === "string" ? input.directory : undefined,
781
871
  })
782
- if (!checkpoint) {
872
+ if (!built) {
783
873
  log.debug("compaction checkpoint skipped: nothing to checkpoint", { sessionID })
784
874
  return skipped("empty")
785
875
  }
876
+ // The transcript may still hold text the person asked to forget (the
877
+ // asking turn restates it): each run of it is masked before upload
878
+ // (src/forget-purge.js).
879
+ const masked = forgetPurge.mask(built.text)
880
+ if (masked.hits.length > 0) log.info("compaction checkpoint: forgotten text masked", { sessionID, purge: masked.hits })
881
+ const checkpoint = masked.hits.length > 0 ? { ...built, text: masked.value } : built
786
882
 
787
883
  // The timestamp changes on every fire; exclude it so a repeated compaction
788
884
  // event for the same transcript is recognized as a duplicate.
@@ -845,17 +941,82 @@ export function createRuntime(input) {
845
941
  await credentials.check()
846
942
  return credentials.subject()
847
943
  },
944
+ // An entry that holds text the person forgot after it was queued is
945
+ // deleted, never replayed (src/forget-purge.js).
946
+ sendable: (entry) => forgetPurge.sendable(entry),
947
+ })
948
+
949
+ /** Forget, end to end on the client: purge the spool, mask captures (src/forget-purge.js). */
950
+ const forgetPurge = createForgetPurge({
951
+ config,
952
+ log,
953
+ records: recordsClient,
954
+ spool,
955
+ now,
956
+ scope: () => scope({}),
957
+ hasEntries: () => {
958
+ const stats = spool.spoolStats()
959
+ return stats.pending + stats.inflight + stats.quarantined > 0
960
+ },
848
961
  })
849
962
 
963
+ /**
964
+ * Replay the spool, after the forget purge: new purge entries are fetched
965
+ * (startup, a drain, /mem-sync) and matching entries deleted first. While a
966
+ * forget is pending and its entries cannot be read, nothing is replayed.
967
+ */
968
+ async function flushSpool(options = {}) {
969
+ let gate = { ok: true }
970
+ try {
971
+ gate = await forgetPurge.beforeFlush({ force: options?.force === true })
972
+ } catch (error) {
973
+ log.warn("forget purge before replay failed", errorMessage(error))
974
+ }
975
+ if (!gate.ok) return { flushed: 0, failed: 0, quarantined: 0, deferred: spool.spoolStats().pending, held: "forget-pending" }
976
+ return spool.flushSpool(options)
977
+ }
978
+
850
979
  /** A new user message in a session: its Jelly token is asked for again (src/credentials.js `userTurn`). */
851
980
  function userTurn(sessionID, messageID) {
852
981
  credentials?.userTurn?.(sessionID, messageID)
853
982
  }
854
983
 
984
+ /** Keep a user message as the person's words in this session (the `prompt` hook and the admission events). */
985
+ function notePrompt(sessionID, text) {
986
+ stated.note(sessionID, text)
987
+ }
988
+
989
+ /**
990
+ * The person's recent messages for a tool call in `sessionID`, oldest first.
991
+ * A known subagent's prompt is its parent agent's brief, so the root
992
+ * session's messages are read instead. An empty list: none was seen.
993
+ */
994
+ function personSaid(sessionID) {
995
+ return stated.of(rootSession(sessionID))
996
+ }
997
+
998
+ /** The due dates the commitments check dropped in this session's root, with the words they were tied to. */
999
+ function personDrops(sessionID) {
1000
+ return stated.drops(rootSession(sessionID))
1001
+ }
1002
+
1003
+ /** A session's root: itself, or the first ancestor with no recorded parent. */
1004
+ function rootSession(sessionID) {
1005
+ let id = sessionID ? String(sessionID) : ""
1006
+ for (let hops = 0; id && hops < 8; hops += 1) {
1007
+ const parent = parentOf(id)
1008
+ if (!parent) break
1009
+ id = parent
1010
+ }
1011
+ return id
1012
+ }
1013
+
855
1014
  /** Drop what is kept for a session OpenCode deleted: its credential, pinned block and context. */
856
1015
  function forgetSession(sessionID) {
857
1016
  if (!sessionID) return
858
1017
  credentials?.forget?.(sessionID)
1018
+ stated.drop(sessionID)
1019
+ capturePause.drop(sessionID)
859
1020
  invalidate(sessionID)
860
1021
  }
861
1022
  let lastDrain = 0
@@ -871,11 +1032,22 @@ export function createRuntime(input) {
871
1032
  if (started - lastDrain < SPOOL_DRAIN_INTERVAL_MS) return
872
1033
  lastDrain = started
873
1034
  if (spool.spoolStats().pending === 0) return
874
- void spool.flushSpool().catch((error) => log.warn("background spool flush failed", errorMessage(error)))
1035
+ void flushSpool().catch((error) => log.warn("background spool flush failed", errorMessage(error)))
1036
+ }
1037
+
1038
+ /** What capture does for a session: off, paused since when, or on with its visibility. */
1039
+ function describeCapture(sessionID) {
1040
+ if (!config.capture) return "off"
1041
+ const since = sessionID ? capturePause.pausedSince(sessionID) : ""
1042
+ if (since) return `paused for this session since ${since} (/mem-resume turns it back on)`
1043
+ if (sessionID && capturePause.everPaused(sessionID)) return `${config.captureVisibility}; no checkpoint or compaction summary for this session, which was paused`
1044
+ return config.captureVisibility
875
1045
  }
876
1046
 
877
1047
  async function status(overrides = {}) {
878
- const { context, ...rest } = overrides
1048
+ // `captureSession`: the session whose capture state to show, also when the
1049
+ // counts are for another space (mem_spaces health with a space).
1050
+ const { context, captureSession, ...rest } = overrides
879
1051
  const scoped = scope({ ...rest, context, visibility: rest.visibility ?? config.captureVisibility })
880
1052
  const shared = sharedScope({ context })
881
1053
  // Counts describe the whole scope, not the current session.
@@ -901,7 +1073,8 @@ export function createRuntime(input) {
901
1073
  spaceName: context?.space_name ?? null,
902
1074
  spaceKind: context?.space_kind ?? null,
903
1075
  collection: context?.collection_id ?? null,
904
- capture: config.captureVisibility,
1076
+ capture: describeCapture(captureSession ?? rest.sessionID),
1077
+ capturePaused: (captureSession ?? rest.sessionID) ? capturePause.pausedSince(captureSession ?? rest.sessionID) : "",
905
1078
  layers: {
906
1079
  l0: conversations?.total ?? null,
907
1080
  l1: atoms?.total ?? null,
@@ -931,21 +1104,31 @@ export function createRuntime(input) {
931
1104
  unavailable,
932
1105
  availability,
933
1106
  userTurn,
1107
+ notePrompt,
1108
+ personSaid,
1109
+ personDrops,
934
1110
  forgetSession,
935
1111
  scope,
936
1112
  scopeFor,
937
1113
  sharedScope,
938
1114
  resolveContext,
939
1115
  isSessionBound,
1116
+ keepBinding,
940
1117
  sessionContext,
941
1118
  captureContext,
942
1119
  gatewayCapture,
943
1120
  captureTurn,
1121
+ spaceHint,
944
1122
  noteSession,
945
1123
  noteAgent,
946
1124
  agentFor: lastAgent,
947
1125
  parentOf,
948
1126
  skipsSubagent,
1127
+ pauseCapture: (sessionID) => capturePause.pause(sessionID),
1128
+ resumeCapture: (sessionID) => capturePause.resume(sessionID),
1129
+ capturePausedSince: (sessionID) => capturePause.pausedSince(sessionID),
1130
+ captureEverPaused: (sessionID) => capturePause.everPaused(sessionID),
1131
+ describeCapture,
949
1132
  setSessionTask,
950
1133
  taskFor,
951
1134
  skillContexts,
@@ -969,8 +1152,12 @@ export function createRuntime(input) {
969
1152
  recentCheckpoint: spool.recentCheckpoint,
970
1153
  pruneClaims: spool.pruneClaims,
971
1154
  enqueueSpool: spool.enqueueSpool,
972
- flushSpool: spool.flushSpool,
1155
+ flushSpool,
973
1156
  spoolStats: spool.spoolStats,
1157
+ // The forget purge's hook (slice 6b): delete spooled entries a predicate matches.
1158
+ purgeSpool: spool.purgeMatching,
1159
+ forgetPurge,
1160
+ maskForgotten: forgetPurge.mask,
974
1161
  drainSpool,
975
1162
  status,
976
1163
  }
package/src/shapes.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The unsafe shapes of a text: instruction, permission, share
3
+ * (memory-funnel-v1.md §7, §10). One module, two copies kept identical by
4
+ * scripts/check-copies.mjs: records/src/shapes.js for the routines and the
5
+ * store, src/shapes.js for the plugin's pinned block. The patterns are
6
+ * anchored on the phrasing of an injected command, not on single words, so an
7
+ * ordinary "I'll share the deck on Monday" survives.
8
+ */
9
+
10
+ const INSTRUCTION = [
11
+ /\b(?:ignore|disregard|forget|override) (?:(?:all|any|the|your|of|my) )*(?:(?:previous|prior|above|earlier|other|existing) )?(?:instructions|rules|directions|guidelines|prompts?)\b/i,
12
+ /\b(?:you are|you're) now\b/i,
13
+ /\breveal (?:the |your )?(?:secret|token|password|api key|credentials|system prompt)\b/i,
14
+ /\b(?:print|show|repeat|override|replace|ignore|disregard) (?:the |your )?system prompt\b/i,
15
+ /\b(?:new|updated) system prompt\b/i,
16
+ /\b(?:do not|don't|never) (?:tell|mention|inform|alert) the (?:user|person|owner)\b/i,
17
+ /\b(?:when|if|once|after) you (?:read|see|recall|retrieve|load|process|summari[sz]e) (?:this|these)\b/i,
18
+ /\b(?:note|message|instructions?) (?:to|for) (?:the |any )?(?:ai|assistant|agent|llm|model|bot)s?\b/i,
19
+ /\b(?:ai|llm|assistant|agent|model)s?(?: (?:reading|processing|summari[sz]ing))? (?:this|these)[^.]{0,40}\b(?:must|should|shall|will)\b/i,
20
+ /\bfrom now on\b[^.]{0,60}\b(?:you|always|never|the assistant)\b/i,
21
+ /\b(?:add|store|save|remember|record|write|create) (?:a |an |the )?(?:new )?(?:memory|preference|rule|constraint|instruction|decision)s? (?:that|saying|stating)\b/i,
22
+ /\b(?:system|assistant)\s*:\s*\S/i,
23
+ /<\s*\/?\s*(?:system|instructions?|assistant|im_start|im_end)\b/i,
24
+ /\b(?:run|execute|eval) (?:the following|this) (?:command|code|script)\b/i,
25
+ ]
26
+
27
+ const PERMISSION = [
28
+ /\b(?:grant|give|assign|add)\b[^.]{0,40}\b(?:access|permissions?|admin|owner(?:ship)?|editor|write rights?)\b/i,
29
+ /\b(?:make|set|promote)\b[^.]{0,30}\b(?:an? )?(?:admin|owner|editor)\b/i,
30
+ /\ballow\b[^.]{0,40}\bto (?:read|write|access|edit|delete|see)\b/i,
31
+ /\b(?:auto-?approve|approve (?:all|every|everything|any))\b/i,
32
+ /\b(?:disable|turn off|bypass|skip)\b[^.]{0,20}\b(?:review|safety|filters?|guards?|checks?|approval|2fa|mfa)\b/i,
33
+ /\b(?:transfer|hand over)\b[^.]{0,30}\b(?:ownership|the (?:space|vault|account))\b/i,
34
+ // Standing approvals (FABLE records #4): "always approve shares from …",
35
+ // "accept invites … without asking".
36
+ /\b(?:always|automatically|auto-)\s*(?:approve|accept|grant|trust|allow)\b/i,
37
+ /\b(?:approve|accept|allow|grant|share|forward|send)\b[^.]{0,60}\bwithout (?:asking|confirm(?:ing|ation)|review(?:ing)?|approval|checking|permission)\b/i,
38
+ /\bapprove\b[^.]{0,40}\b(?:shares?|share requests?|access requests?|invites?|invitations?|permissions?|grants?)\b/i,
39
+ /\b(?:ignore|disregard|bypass|override)\b[^.]{0,30}\b(?:rules?|polic(?:y|ies)|protocol|permissions?)\b/i,
40
+ ]
41
+
42
+ const SHARE = [
43
+ /\b(?:share|send|forward|export|upload|post|leak|email|copy|dump)\b[^.]{0,40}\b(?:all|every|entire|whole|everything|your)\b[^.]{0,30}\b(?:memor(?:y|ies)|notes|records|journals?|vault|pages|data|contacts|inbox|mail|files|credentials|passwords?|secrets?|tokens?|keys)\b/i,
44
+ /\b(?:share|send|forward|export|copy)\b[^.]{0,30}\b(?:memor(?:y|ies)|vault|journals?|records)\b[^.]{0,40}\b(?:to|with)\b/i,
45
+ /\bmake\b[^.]{0,40}\bpublic\b/i,
46
+ /\b(?:publish|expose)\b[^.]{0,30}\b(?:memor(?:y|ies)|notes|vault|journals?|pages)\b/i,
47
+ /\bshare everything\b/i,
48
+ /\b(?:all|every|everything)\b[^.]{0,30}\b(?:memor(?:y|ies)|notes|records|journals?|vault|pages|data)\b[^.]{0,20}\b(?:shared|sent|forwarded|exported|published|public(?:ly)?)\b/i,
49
+ /\bshared? (?:it |them |this |these |everything )?(?:publicly|with (?:everyone|anyone|the public))\b/i,
50
+ ]
51
+
52
+ /**
53
+ * Which unsafe shapes a text has.
54
+ * @param {string} text
55
+ * @returns {{instruction: boolean, permission: boolean, share: boolean, any: boolean}}
56
+ */
57
+ export function shapes(text) {
58
+ const value = String(text ?? "")
59
+ const instruction = INSTRUCTION.some((p) => p.test(value))
60
+ const permission = PERMISSION.some((p) => p.test(value))
61
+ const share = SHARE.some((p) => p.test(value))
62
+ return { instruction, permission, share, any: instruction || permission || share }
63
+ }
package/src/sources.js CHANGED
@@ -7,25 +7,165 @@
7
7
  * bind call `events_list` through it (`ctx.rpc`).
8
8
  * - `namespace` and `tool`: the Code Mode path a host schedule's check calls,
9
9
  * `tools.<namespace>.<tool>`.
10
+ * - `permission`: exactly what the source plugin asserts when Memory calls its
11
+ * `events_list`, so the collector's session allows that and nothing more
12
+ * (`collectSessionRules` in src/collector.js). OpenCode checks each inner
13
+ * action against that session (S0, 0.9.11), so a missing one is an outage.
14
+ * - `events`: its events action, allowed on `"*"`: the plugin's tools RPC
15
+ * checks it on `"*"` before it runs (gws included).
16
+ * - `actions`: the exact inner actions it then asserts, on `"*"`: the MCP
17
+ * tools it reads through OpenCode's executors, `<server>_<tool>`. When
18
+ * `accountServer` is set (Plaud), a named account's tools are on their own
19
+ * server, so `<server>_` becomes that server's name.
20
+ * - `reads` with `readAction`: the operations it asserts `readAction` on,
21
+ * named `<account>:<operation>` (gws: `work:gmail.users.messages.get`),
22
+ * always on the binding's own account, never `*:`. Such a source sets
23
+ * `namesAccount`, so Memory always sends that account in `events_list`,
24
+ * "default" included (gws's own default alias). A confirmed binding's
25
+ * account is the alias its bind probe reported, so its session is pinned
26
+ * to the account the person confirmed.
27
+ * No source gets a generic `<ns>_*`, `.read` or any write.
10
28
  * - `input`: what every `events_list` call to this source adds; a plugin that
11
29
  * serves several sources (gws: gmail, later calendar and drive) is told which.
30
+ * - `everyMinutes`: how often the timer collects this source (default 30). A
31
+ * billed source (X) runs less often; "collect now" ignores it.
32
+ * - `ownerProbe`: how a bind request learns the signed-in account. `"limit0"`
33
+ * is the contract's owner-only call (`limit: 0`, §4.5): no events. `"limit1"`
34
+ * is the fallback for releases that refuse 0: one event is read and dropped,
35
+ * never stored, as the plugin's own bind does.
36
+ * - `setupOptions`: the plugin options this source needs or should have before
37
+ * it is bound, said in the bind answer and the docs. Memory never sets them:
38
+ * they are the source plugin's.
12
39
  * - `package` and `minVersion`: who to update when the plugin's `events_list`
13
40
  * does not keep the source contract (§4.5). `minVersion` is the first release
14
- * whose `events_list` answers `source` and `account`; null until lane SRC
15
- * publishes it, and the error then names the contract instead.
41
+ * whose `events_list` answers `source`, `account` and `owner`.
16
42
  */
43
+ /** A binding's account name: no wildcard (`*`, `?`), separator (`:`, `/`) or space, and never empty. */
44
+ export const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.@+-]{0,127}$/
45
+
46
+ function freezePermission(permission) {
47
+ return Object.freeze({ ...permission, actions: Object.freeze([...permission.actions]), reads: Object.freeze([...permission.reads]) })
48
+ }
49
+
50
+ /** The timer's default cadence per source, in minutes. */
51
+ export const DEFAULT_EVERY_MINUTES = 30
52
+
17
53
  export const SOURCE_REGISTRY = Object.freeze(
18
54
  [
19
- { source: "history", rpc: "history.sessions.tools", namespace: "history", package: "@joe-broadhead/opencode-history" },
20
- { source: "gmail", rpc: "google-workspace.gws.tools", namespace: "gws", input: { source: "gmail" }, package: "@joe-broadhead/opencode-gws" },
21
- { source: "slack", rpc: "slack.workspace.tools", namespace: "slack", package: "@joe-broadhead/opencode-slack" },
22
- { source: "x", rpc: "x.posts.tools", namespace: "x", package: "@joe-broadhead/opencode-x" },
23
- { source: "granola", rpc: "granola.meetings.tools", namespace: "granola", package: "@joe-broadhead/opencode-granola" },
24
- { source: "plaud", rpc: "plaud.recordings.tools", namespace: "plaud", package: "@joe-broadhead/opencode-plaud" },
25
- { source: "wisprflow", rpc: "wisprflow.meetings.tools", namespace: "wisprflow", package: "@joe-broadhead/opencode-wisprflow" },
26
- { source: "github", rpc: "github.platform.tools", namespace: "github", package: "@joe-broadhead/opencode-github" },
27
- { source: "linear", rpc: "linear.workspace.tools", namespace: "linear", package: "@joe-broadhead/opencode-linear" },
28
- ].map((entry) => Object.freeze({ tool: "events_list", input: {}, minVersion: null, ...entry, input: Object.freeze({ ...(entry.input ?? {}) }) })),
55
+ // history reads its own local index: no inner action.
56
+ { source: "history", rpc: "history.sessions.tools", namespace: "history", package: "@joe-broadhead/opencode-history", minVersion: "0.0.6" },
57
+ {
58
+ source: "gmail",
59
+ rpc: "google-workspace.gws.tools",
60
+ namespace: "gws",
61
+ input: { source: "gmail" },
62
+ package: "@joe-broadhead/opencode-gws",
63
+ minVersion: "0.0.10",
64
+ // gws (dist src/host/tools-rpc.ts) first checks gws.events_list with the rules whose resource
65
+ // matches "*", so it must be allowed on "*"; then events_list asserts gws.events_list on
66
+ // <account>:gmail.users.history.list and gws.read ("Run a read-only operation") on
67
+ // <account>:<operation> for each of its EVENT_READS, all Gmail list and get calls.
68
+ permission: {
69
+ events: "gws.events_list",
70
+ readAction: "gws.read",
71
+ reads: ["gmail.users.getProfile", "gmail.users.history.list", "gmail.users.messages.list", "gmail.users.messages.get"],
72
+ },
73
+ // gws scopes the reads by account, so the account is always named: "default" too.
74
+ namesAccount: true,
75
+ },
76
+ {
77
+ source: "slack",
78
+ rpc: "slack.workspace.tools",
79
+ namespace: "slack",
80
+ package: "@joe-broadhead/opencode-slack",
81
+ minVersion: "0.0.8",
82
+ // events_list reads the owner, then each enabled channel, through the MCP executors of the server
83
+ // "slack", whose tools are named slack_*: both are "read" in its class table (S0 Q1.4 proved this pair).
84
+ permission: { actions: ["slack_slack_read_user_profile", "slack_slack_read_channel"] },
85
+ setupOptions: 'Slack collects only the channels and direct messages listed in the slack plugin\'s option "events": {"channels": ["C…", "D…"]} (at most 16); set it, then restart OpenCode.',
86
+ },
87
+ {
88
+ source: "x",
89
+ rpc: "x.posts.tools",
90
+ namespace: "x",
91
+ package: "@joe-broadhead/opencode-x",
92
+ minVersion: "0.0.1",
93
+ // Every X read is billed to the developer account that owns the app.
94
+ everyMinutes: 120,
95
+ // The owner, then each feed in the plugin's events.feeds (mentions, bookmarks, and the home
96
+ // timeline only when named), all in its READ_TOOLS.
97
+ permission: { actions: ["x_get_users_me", "x_get_users_mentions", "x_get_users_bookmarks", "x_get_users_timeline"] },
98
+ setupOptions:
99
+ 'X reads are billed. Set the x plugin\'s options "events": {"feeds": ["mentions", "bookmarks"], "maxCalls": 2}, and "ownsXApp": true only if the signed-in account owns the developer app (it lowers the price X charges); then restart OpenCode.',
100
+ },
101
+ {
102
+ source: "granola",
103
+ rpc: "granola.meetings.tools",
104
+ namespace: "granola",
105
+ package: "@joe-broadhead/opencode-granola",
106
+ minVersion: "0.0.9",
107
+ // The owner, the week windows, then each meeting's details: all in its READ_TOOLS.
108
+ permission: { actions: ["granola_get_account_info", "granola_search_meetings", "granola_get_meetings"] },
109
+ },
110
+ {
111
+ source: "plaud",
112
+ rpc: "plaud.recordings.tools",
113
+ namespace: "plaud",
114
+ package: "@joe-broadhead/opencode-plaud",
115
+ minVersion: "0.0.8",
116
+ // The owner, then the recordings, both in its KNOWN_READS, on the account's server:
117
+ // "plaud" for the default account, "plaud-<account>" for another.
118
+ permission: { actions: ["plaud_list_files", "plaud_get_current_user"], accountServer: "plaud-{account}" },
119
+ },
120
+ {
121
+ source: "wisprflow",
122
+ rpc: "wisprflow.meetings.tools",
123
+ namespace: "wisprflow",
124
+ package: "@joe-broadhead/opencode-wisprflow",
125
+ minVersion: "0.0.3",
126
+ // The owner comes from the sign-in itself; the meetings from search_meetings, in its READ_TOOLS.
127
+ permission: { actions: ["wisprflow_search_meetings"] },
128
+ },
129
+ {
130
+ source: "github",
131
+ rpc: "github.platform.tools",
132
+ namespace: "github",
133
+ package: "@joe-broadhead/opencode-github",
134
+ minVersion: "0.0.9",
135
+ // The owner from get_me (the context toolset's read); the rest are REST GETs, which assert nothing.
136
+ permission: { actions: ["github_get_me"] },
137
+ },
138
+ {
139
+ source: "linear",
140
+ rpc: "linear.workspace.tools",
141
+ namespace: "linear",
142
+ package: "@joe-broadhead/opencode-linear",
143
+ minVersion: "0.0.9",
144
+ // Assigned issues, the inbox, then the workspace and the owner: all in its READ_TOOLS.
145
+ permission: { actions: ["linear_list_issues", "linear_get_notifications", "linear_get_workspace", "linear_get_user"] },
146
+ },
147
+ ].map((entry) =>
148
+ Object.freeze({
149
+ tool: "events_list",
150
+ input: {},
151
+ minVersion: null,
152
+ everyMinutes: DEFAULT_EVERY_MINUTES,
153
+ ownerProbe: "limit1",
154
+ setupOptions: null,
155
+ namesAccount: false,
156
+ ...entry,
157
+ input: Object.freeze({ ...(entry.input ?? {}) }),
158
+ // The plugins' convention: <namespace>_events_list; each source lists its own inner actions.
159
+ permission: freezePermission({
160
+ events: `${entry.namespace}_events_list`,
161
+ actions: [],
162
+ accountServer: null,
163
+ readAction: null,
164
+ reads: [],
165
+ ...(entry.permission ?? {}),
166
+ }),
167
+ }),
168
+ ),
29
169
  )
30
170
 
31
171
  const BY_SOURCE = new Map(SOURCE_REGISTRY.map((entry) => [entry.source, entry]))
@@ -40,6 +180,37 @@ export function knownSources() {
40
180
  return SOURCE_REGISTRY.map((entry) => entry.source)
41
181
  }
42
182
 
183
+ /** The account a binding without one names. */
184
+ const DEFAULT_ACCOUNT = "default"
185
+
186
+ /**
187
+ * The allow rules a source's `events_list` needs in one binding's collector
188
+ * session: its events action, its exact inner actions, and its exact read
189
+ * operations, always on the binding's account. Never a generic `<ns>_*` or
190
+ * `.read`, and never a write. An account that is not an account name (a
191
+ * wildcard, a separator, empty) is refused: it would widen the rules.
192
+ *
193
+ * @param {string | null} [account] the binding's account; null for the default binding, "default"
194
+ * @returns {{ action: string, resource: string, effect: "allow" }[]}
195
+ */
196
+ export function sourceAllowRules(entry, account = null) {
197
+ const permission = entry.permission
198
+ if (account !== null && account !== undefined && (typeof account !== "string" || !ACCOUNT_NAME.test(account))) {
199
+ throw new TypeError(`sourceAllowRules: "${String(account).slice(0, 60)}" is not an account name`)
200
+ }
201
+ const bound = account ?? DEFAULT_ACCOUNT
202
+ const named = bound !== DEFAULT_ACCOUNT ? bound : null
203
+ const allow = (action, resource = "*") => ({ action, resource, effect: "allow" })
204
+ // A named account's MCP tools on its own server (Plaud): "<namespace>_<tool>" becomes "<server>_<tool>".
205
+ const server = named && permission.accountServer ? permission.accountServer.replace("{account}", named) : null
206
+ const inner = (action) => (server && action.startsWith(`${entry.namespace}_`) ? `${server}${action.slice(entry.namespace.length)}` : action)
207
+ return [
208
+ allow(permission.events),
209
+ ...permission.actions.map((action) => allow(inner(action))),
210
+ ...permission.reads.map((operation) => allow(permission.readAction, `${bound}:${operation}`)),
211
+ ]
212
+ }
213
+
43
214
  /** The source contract version a plugin's `events_list` must keep. */
44
215
  export const SOURCE_CONTRACT = "the memory source contract v1 (events_list answers source and account)"
45
216