@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/sources.js CHANGED
@@ -1,76 +1,77 @@
1
1
  /**
2
- * The source registry (docs/design/memory-v1-contracts.md §4.4): every source
3
- * Memory can collect from, with the plugin that serves it. A source is added
4
- * here and nowhere else.
2
+ * Memory's source catalog (DESIGN-MEMORY-JOBS §8.3.2): every source Memory may
3
+ * collect from, and how it reads it.
5
4
  *
6
- * - `rpc`: the source plugin's tools-RPC id; the in-plugin collector and a
7
- * bind call `events_list` through it (`ctx.rpc`).
8
- * - `namespace` and `tool`: the Code Mode path a host schedule's check calls,
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.
28
- * - `input`: what every `events_list` call to this source adds; a plugin that
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.
39
- * - `package` and `minVersion`: who to update when the plugin's `events_list`
40
- * does not keep the source contract (§4.5). `minVersion` is the first release
41
- * whose `events_list` answers `source`, `account` and `owner`.
5
+ * **`SOURCE_REGISTRY` is gone.** A source is not listed in Memory any more; it
6
+ * is read from the installed package on disk, in one of three ways, and
7
+ * **`sources` wins**:
8
+ *
9
+ * | What the installed `package.json` holds | Contract | Label | Read with |
10
+ * |---|---|---|---|
11
+ * | a top-level `sources` object (`contractVersion`, `items[]`) | current, version 1 | `sources (contract version 1)` | the library: `events_list`, `probe`, `snapshot_read`, detail reads |
12
+ * | a `memory` key (the plugin kit's schema v2) | previous | `memory (previous)` | its declared sources' `events_list` |
13
+ * | neither, and the package is one of the nine `events_list` plugins | previous | `events_list (previous)` | `events_list`, with the permissions below |
14
+ *
15
+ * **How they are told apart:** the presence of the `sources` key is the
16
+ * current contract; the `memory` key is the previous one; and the nine family
17
+ * plugins, which ship `events_list` and no declaration, keep working through
18
+ * `PREVIOUS_CONTRACT_SOURCES` until their wave. A plugin that declares
19
+ * `sources` never has its `memory` key read: `sources` wins, in the catalog and
20
+ * in discovery alike.
21
+ *
22
+ * Everything a declared source needs comes from its descriptor: the RPC method,
23
+ * its fixed input, its permissions (`permission.sessionRules`), its scope keys,
24
+ * its detail reads, its price, and its `maxBytes`. Nothing here is hand-kept
25
+ * for a declared source.
42
26
  */
27
+ import { decodeBoundCursor, encodeBoundCursor, canonicalScope } from "./plugins/source-contract/vendor/cursor.js"
28
+ import { probeRules, sessionRules } from "./plugins/source-contract/vendor/permission.js"
29
+ import { maxBytesOf } from "./plugins/source-contract/vendor/descriptor.js"
30
+
43
31
  /** A binding's account name: no wildcard (`*`, `?`), separator (`:`, `/`) or space, and never empty. */
44
32
  export const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.@+-]{0,127}$/
45
33
 
46
- function freezePermission(permission) {
47
- return Object.freeze({ ...permission, actions: Object.freeze([...permission.actions]), reads: Object.freeze([...permission.reads]) })
48
- }
49
-
50
34
  /** The timer's default cadence per source, in minutes. */
51
35
  export const DEFAULT_EVERY_MINUTES = 30
52
36
 
53
- export const SOURCE_REGISTRY = Object.freeze(
37
+ function freezePermission(permission) {
38
+ return Object.freeze({
39
+ ...permission,
40
+ actions: Object.freeze([...permission.actions]),
41
+ reads: Object.freeze([...permission.reads]),
42
+ apiReads: permission.apiReads ? Object.freeze({ ...permission.apiReads, resources: Object.freeze([...permission.apiReads.resources]) }) : null,
43
+ })
44
+ }
45
+
46
+ /**
47
+ * The previous contract version: the nine plugins that implement `events_list`
48
+ * and declare no sources yet. Their permissions are what their events_list
49
+ * asserts; a source is bound with this data until its plugin declares `sources`
50
+ * in a Wave 1/4 release, and the entry is then dropped. Nothing adds to this
51
+ * list: a new source declares itself.
52
+ *
53
+ * `minVersion` is the released tag that declares `sources`, and it is **prose,
54
+ * never a gate** (review S1): a git-pinned install reports a commit rather than
55
+ * a version, Jelly's curated pins report `0.0.0`, and nine of nine still collect
56
+ * through `events_list`. It names the release a person would install, and a
57
+ * build below it is told so — not refused.
58
+ */
59
+ export const PREVIOUS_CONTRACT_SOURCES = Object.freeze(
54
60
  [
55
61
  // 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" },
62
+ { source: "history", rpc: "history.sessions.tools", namespace: "history", package: "@joe-broadhead/opencode-history", minVersion: "0.0.4" },
57
63
  {
58
64
  source: "gmail",
59
65
  rpc: "google-workspace.gws.tools",
60
66
  namespace: "gws",
61
67
  input: { source: "gmail" },
62
68
  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.
69
+ minVersion: "0.0.5",
68
70
  permission: {
69
71
  events: "gws.events_list",
70
72
  readAction: "gws.read",
71
73
  reads: ["gmail.users.getProfile", "gmail.users.history.list", "gmail.users.messages.list", "gmail.users.messages.get"],
72
74
  },
73
- // gws scopes the reads by account, so the account is always named: "default" too.
74
75
  namesAccount: true,
75
76
  },
76
77
  {
@@ -78,9 +79,7 @@ export const SOURCE_REGISTRY = Object.freeze(
78
79
  rpc: "slack.workspace.tools",
79
80
  namespace: "slack",
80
81
  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).
82
+ minVersion: "0.0.3",
84
83
  permission: { actions: ["slack_slack_read_user_profile", "slack_slack_read_channel"] },
85
84
  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
85
  },
@@ -89,11 +88,8 @@ export const SOURCE_REGISTRY = Object.freeze(
89
88
  rpc: "x.posts.tools",
90
89
  namespace: "x",
91
90
  package: "@joe-broadhead/opencode-x",
92
- minVersion: "0.0.1",
93
- // Every X read is billed to the developer account that owns the app.
91
+ minVersion: "0.0.4",
94
92
  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
93
  permission: { actions: ["x_get_users_me", "x_get_users_mentions", "x_get_users_bookmarks", "x_get_users_timeline"] },
98
94
  setupOptions:
99
95
  '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.',
@@ -103,8 +99,7 @@ export const SOURCE_REGISTRY = Object.freeze(
103
99
  rpc: "granola.meetings.tools",
104
100
  namespace: "granola",
105
101
  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.
102
+ minVersion: "0.0.3",
108
103
  permission: { actions: ["granola_get_account_info", "granola_search_meetings", "granola_get_meetings"] },
109
104
  },
110
105
  {
@@ -112,9 +107,7 @@ export const SOURCE_REGISTRY = Object.freeze(
112
107
  rpc: "plaud.recordings.tools",
113
108
  namespace: "plaud",
114
109
  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.
110
+ minVersion: "0.0.3",
118
111
  permission: { actions: ["plaud_list_files", "plaud_get_current_user"], accountServer: "plaud-{account}" },
119
112
  },
120
113
  {
@@ -123,7 +116,6 @@ export const SOURCE_REGISTRY = Object.freeze(
123
116
  namespace: "wisprflow",
124
117
  package: "@joe-broadhead/opencode-wisprflow",
125
118
  minVersion: "0.0.3",
126
- // The owner comes from the sign-in itself; the meetings from search_meetings, in its READ_TOOLS.
127
119
  permission: { actions: ["wisprflow_search_meetings"] },
128
120
  },
129
121
  {
@@ -131,17 +123,21 @@ export const SOURCE_REGISTRY = Object.freeze(
131
123
  rpc: "github.platform.tools",
132
124
  namespace: "github",
133
125
  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"] },
126
+ minVersion: "0.0.3",
127
+ // The owner from get_me (the context toolset's read); then events_list's own API reads, which the release
128
+ // after v0.0.0 asserts on github_api unattended (before it, only writes were gated). listEvents makes
129
+ // exactly these four GETs (opencode-github src/source-events.ts), so exactly these four are granted.
130
+ permission: {
131
+ actions: ["github_get_me"],
132
+ apiReads: { action: "github_api", resources: ["GET /user", "GET /search/issues", "GET /search/commits", "GET /notifications"] },
133
+ },
137
134
  },
138
135
  {
139
136
  source: "linear",
140
137
  rpc: "linear.workspace.tools",
141
138
  namespace: "linear",
142
139
  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.
140
+ minVersion: "0.0.3",
145
141
  permission: { actions: ["linear_list_issues", "linear_get_notifications", "linear_get_workspace", "linear_get_user"] },
146
142
  },
147
143
  ].map((entry) =>
@@ -153,77 +149,400 @@ export const SOURCE_REGISTRY = Object.freeze(
153
149
  ownerProbe: "limit1",
154
150
  setupOptions: null,
155
151
  namesAccount: false,
152
+ contract: "events_list",
153
+ contractLabel: "events_list (previous)",
154
+ kind: "events",
156
155
  ...entry,
157
156
  input: Object.freeze({ ...(entry.input ?? {}) }),
158
- // The plugins' convention: <namespace>_events_list; each source lists its own inner actions.
159
157
  permission: freezePermission({
160
158
  events: `${entry.namespace}_events_list`,
161
159
  actions: [],
162
160
  accountServer: null,
163
161
  readAction: null,
164
162
  reads: [],
163
+ apiReads: null,
165
164
  ...(entry.permission ?? {}),
166
165
  }),
167
166
  }),
168
167
  ),
169
168
  )
170
169
 
171
- const BY_SOURCE = new Map(SOURCE_REGISTRY.map((entry) => [entry.source, entry]))
170
+ const BY_SOURCE = new Map(PREVIOUS_CONTRACT_SOURCES.map((entry) => [entry.source, entry]))
171
+
172
+ /** Declared sources, by binding id, published by discovery (`setDeclaredSources`). */
173
+ let declared = new Map()
174
+
175
+ /** The packages that declared a source under the contract: their legacy aliases are retired. */
176
+ let declaredPackages = new Set()
177
+
178
+ /** The version of each installed plugin the last discovery pass saw, by package name. */
179
+ let installedVersions = new Map()
180
+
181
+ /**
182
+ * Publish the declarations one discovery pass resolved. Only `available`
183
+ * plugins' descriptors arrive here; an invalid or unverified one is absent, and
184
+ * its source is then not collectable. A plugin that declares `sources` never
185
+ * contributes a `memory`-key entry: `sources` wins.
186
+ *
187
+ * @param {object[]} entries entries from `sourceEntriesOf`
188
+ */
189
+ export function setDeclaredSources(entries) {
190
+ const next = new Map()
191
+ const packages = new Set()
192
+ for (const entry of Array.isArray(entries) ? entries : []) {
193
+ if (!entry?.source) continue
194
+ next.set(entry.source, Object.freeze(entry))
195
+ if (entry.contract === "sources" && typeof entry.package === "string" && entry.package !== "") packages.add(entry.package)
196
+ }
197
+ declared = next
198
+ declaredPackages = packages
199
+ }
200
+
201
+ /** Every declared source entry, in binding order. */
202
+ export function declaredSources() {
203
+ return [...declared.values()]
204
+ }
205
+
206
+ /**
207
+ * Publish the versions one discovery pass saw, for every installed plugin — the
208
+ * declaration's or not. A previous-contract entry names the released tag that
209
+ * declares `sources`, and the installed version is the other half of a Sources
210
+ * row that informs: "0.0.0 is installed; v0.0.5 declares its sources" (G3).
211
+ * **Nothing here refuses or stops a read** (review S1): a build below the tag
212
+ * still collects through `events_list`, which is what the tag replaces.
213
+ *
214
+ * @param {Array<{ id?: string, package?: string | null, version?: string | null, state?: string }>} report
215
+ */
216
+ export function setInstalledVersions(report) {
217
+ const next = new Map()
218
+ for (const plugin of Array.isArray(report) ? report : []) {
219
+ if (!plugin || typeof plugin.package !== "string" || plugin.package === "") continue
220
+ if (typeof plugin.version !== "string" || plugin.version === "") continue
221
+ if (plugin.state !== undefined && plugin.state !== "available" && plugin.state !== "conflict" && plugin.state !== "unverified") continue
222
+ next.set(plugin.package, Object.freeze({ version: plugin.version, pluginId: typeof plugin.id === "string" ? plugin.id : null }))
223
+ }
224
+ installedVersions = next
225
+ }
226
+
227
+ /** The installed version of the package a source comes from, as the last discovery pass saw it, or null. */
228
+ export function installedVersionOf(source) {
229
+ const entry = sourceEntry(source)
230
+ return entry ? (installedVersions.get(entry.package)?.version ?? null) : null
231
+ }
232
+
233
+ /** `major.minor.patch` of a version, or null when it is not one. */
234
+ function versionParts(value) {
235
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value ?? ""))
236
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null
237
+ }
238
+
239
+ /** -1, 0 or 1: two `major.minor.patch` versions, or null when either is not one. */
240
+ export function compareVersions(left, right) {
241
+ const a = versionParts(left)
242
+ const b = versionParts(right)
243
+ if (!a || !b) return null
244
+ for (let index = 0; index < 3; index += 1) {
245
+ if (a[index] !== b[index]) return a[index] < b[index] ? -1 : 1
246
+ }
247
+ return 0
248
+ }
249
+
250
+ /**
251
+ * What a Sources row says about the installed release, or null when there is
252
+ * nothing to say. **Informational, never a refusal** (review S1): the legacy
253
+ * floors name the released tag that declares `sources`, and a build below it is
254
+ * told so in words — it still collects through `events_list`, and the audit's
255
+ * live runs proved it.
256
+ *
257
+ * - a versioned install: "@joe-broadhead/opencode-gws 0.0.0 is installed; v0.0.5
258
+ * declares its sources."
259
+ * - a git pin (a commit, which is not a version): the tag alone, so a SHA is
260
+ * never compared with a version.
261
+ * - an install that declares (the declared entry won): nothing — its row is the
262
+ * declaration's own.
263
+ *
264
+ * @returns {{ source: string, package: string, installed: string | null, declares: string, message: string } | null}
265
+ */
266
+ export function releaseNote(source) {
267
+ const entry = sourceEntry(source)
268
+ if (!entry || entry.contract !== "events_list" || !entry.minVersion) return null
269
+ const raw = installedVersions.get(entry.package)?.version ?? null
270
+ const installed = raw !== null && versionParts(raw) !== null ? raw : null
271
+ const declares = `v${entry.minVersion}`
272
+ return {
273
+ source: entry.source,
274
+ package: entry.package,
275
+ installed,
276
+ declares,
277
+ message: installed
278
+ ? `${entry.package} ${installed} is installed; ${declares} declares its sources.`
279
+ : `This build of ${entry.package} predates the source contract; ${declares} declares its sources, and Memory reads it through events_list until then.`,
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Why a declared source of another kind is not offered in this release, or
285
+ * null. This release collects events sources only: a snapshot source is
286
+ * declared, bindable in the contract's terms, and read by nothing
287
+ * (`collector.js` collects `kind: "events"`), so offering it would bind a
288
+ * person to a source that never answers (G1, audit §1).
289
+ *
290
+ * @returns {{ source: string, kind: string, message: string, next: string } | null}
291
+ */
292
+ export function kindProblem(source) {
293
+ const entry = declared.get(String(source ?? ""))
294
+ if (!entry || entry.kind === "events") return null
295
+ const kind = String(entry.kind ?? "unknown")
296
+ return {
297
+ source: entry.source,
298
+ kind,
299
+ message: `${entry.source} is a ${kind} source, and this release collects events sources only.`,
300
+ next: "Nothing was collected, and nothing was changed. Its plugin is still installed; it is not offered until Memory reads this kind of source.",
301
+ }
302
+ }
172
303
 
173
- /** The registry entry for a source name, or null. */
304
+ /** The entry for a source name, or null: a declaration first, then the previous contract. */
174
305
  export function sourceEntry(source) {
175
- return BY_SOURCE.get(String(source ?? "")) ?? null
306
+ const name = String(source ?? "")
307
+ return declared.get(name) ?? BY_SOURCE.get(name) ?? null
308
+ }
309
+
310
+ /** True when a package declares a source under the contract, so its legacy alias is retired (audit 1.3). */
311
+ export function legacyRetired(source) {
312
+ const entry = BY_SOURCE.get(String(source ?? ""))
313
+ return entry !== undefined && declaredPackages.has(entry.package)
314
+ }
315
+
316
+ /**
317
+ * True when a source is offered for binding: a declared **events** source, or a
318
+ * legacy alias whose package has not declared yet. A retired alias is not
319
+ * offered, but `sourceEntry` still resolves it so a binding made before its
320
+ * package declared keeps collecting (never silently stops, and never
321
+ * duplicated). A snapshot source is declared and not offered: this release reads
322
+ * no snapshot (G1). A legacy alias is never withheld for its installed release
323
+ * (review S1): the row informs, and the read still works.
324
+ */
325
+ export function bindableSource(source) {
326
+ const name = String(source ?? "")
327
+ if (declared.has(name)) return declared.get(name).kind === "events"
328
+ return BY_SOURCE.has(name) && !legacyRetired(name)
176
329
  }
177
330
 
178
- /** Every source Memory knows, in the registry's order. */
331
+ /*
332
+ * One-binding rule: no copy lives here. Which names are the same account (a
333
+ * legacy alias and the declared sources it stands for) is the records service's
334
+ * rule (`records/src/plugins/legacy-sources.js`), because every bind path
335
+ * converges there: this plugin's `mem_spaces` asks `sources.request` and shows
336
+ * the records service's refusal, and the console asks it too.
337
+ */
338
+
339
+ /**
340
+ * Every source Memory can bind, declared first, then the previous contract's
341
+ * unretired aliases: a declared source of a kind this release collects (G1), and
342
+ * every legacy alias whose package has not declared (G3 informs, never hides).
343
+ */
179
344
  export function knownSources() {
180
- return SOURCE_REGISTRY.map((entry) => entry.source)
345
+ return [
346
+ ...[...declared.entries()].filter(([, entry]) => entry.kind === "events").map(([name]) => name),
347
+ ...[...BY_SOURCE.keys()].filter((source) => !declared.has(source) && !legacyRetired(source)),
348
+ ]
349
+ }
350
+
351
+ /** The contract a source is read under: `"sources"`, `"memory"` or `"events_list"`. */
352
+ export function contractOf(source) {
353
+ return sourceEntry(source)?.contract ?? null
354
+ }
355
+
356
+ /**
357
+ * The catalog entries a discovery report resolves: every plugin that declares
358
+ * `sources` (current), every plugin that declares `memory` and no `sources`
359
+ * (previous), each source with its plugin, package, RPC id and descriptor.
360
+ *
361
+ * @param {Array<{ id: string, package: string | null, state: string, version?: string | null, contract?: "sources" | "memory", contractLabel?: string, descriptor?: object, descriptorHash?: string | null, manifest?: any }>} report
362
+ */
363
+ export function sourceEntriesOf(report) {
364
+ const entries = []
365
+ for (const plugin of Array.isArray(report) ? report : []) {
366
+ if (plugin?.state !== "available") continue
367
+ if (plugin.contract === "sources" && plugin.descriptor) {
368
+ for (const item of plugin.descriptor.items ?? []) entries.push(declaredEntry(plugin, item))
369
+ continue
370
+ }
371
+ if (plugin.contract === "memory" && plugin.manifest) {
372
+ for (const entry of memoryEntries(plugin)) entries.push(entry)
373
+ }
374
+ }
375
+ return entries
376
+ }
377
+
378
+ /** A source's short name in a page (`gmail` for `gws.gmail`): what its `input` names, else its id's last part. */
379
+ export function pageSourceOf(item) {
380
+ const named = item?.input?.source
381
+ if (typeof named === "string" && /^[a-z][a-z0-9-]*$/.test(named)) return named
382
+ const last = String(item?.id ?? "").split(".").pop()
383
+ return /^[a-z][a-z0-9-]*$/.test(last) ? last : String(item?.id ?? "")
384
+ }
385
+
386
+ /** One declared source as the catalog holds it. */
387
+ function declaredEntry(plugin, item) {
388
+ const named = item.accounts?.named === true
389
+ const stated = Number(item.cadence?.providerMinMinutes)
390
+ const floor = Number.isInteger(stated) && stated >= 1 ? stated : null
391
+ return Object.freeze({
392
+ source: item.id,
393
+ pluginId: plugin.id,
394
+ package: plugin.package,
395
+ version: plugin.version ?? null,
396
+ rpc: `${plugin.id}.tools`,
397
+ namespace: String(item.id).split(".")[0],
398
+ tool: item.tool,
399
+ kind: item.kind,
400
+ reads: item.reads ?? null,
401
+ output: item.output ?? null,
402
+ input: Object.freeze({ ...(item.input ?? {}) }),
403
+ pageSource: pageSourceOf(item),
404
+ // A declared source's account handling comes from its descriptor: "named"
405
+ // means a read names one, and Memory names "default" too so the session's
406
+ // rules and the plugin's account always agree.
407
+ namesAccount: named,
408
+ ownerProbe: "probe",
409
+ everyMinutes: Math.max(DEFAULT_EVERY_MINUTES, floor ?? 0),
410
+ minVersion: null,
411
+ setupOptions: null,
412
+ contract: "sources",
413
+ contractLabel: "sources (contract version 1)",
414
+ descriptor: plugin.descriptor,
415
+ descriptorHash: plugin.descriptorHash ?? null,
416
+ item: Object.freeze({ ...item }),
417
+ permission: Object.freeze({ events: item.permission?.events ?? null, tool: item.permission?.tool ?? null, operations: Object.freeze([...(item.permission?.operations ?? [])]), actions: Object.freeze([]), readAction: null, reads: Object.freeze([]), accountServer: null }),
418
+ private: item.private === true,
419
+ cost: Object.freeze({ ...(item.cost ?? { class: "free" }) }),
420
+ scopeKeys: Object.freeze([...(item.scope?.keys ?? [])]),
421
+ scopeDescribe: item.scope?.describe ?? null,
422
+ suggest: item.scope?.suggest ?? null,
423
+ details: Object.freeze([...(item.details ?? [])]),
424
+ urlHosts: Object.freeze([...(item.urlHosts ?? [])]),
425
+ maxBytes: maxBytesOf(item),
426
+ retentionDays: Number(item.retentionDays) || null,
427
+ cadenceMinMinutes: floor,
428
+ })
181
429
  }
182
430
 
183
- /** The account a binding without one names. */
184
- const DEFAULT_ACCOUNT = "default"
431
+ /**
432
+ * The sources a previous-contract `memory` declaration holds. Its `sources[]`
433
+ * carry an `id`, its grants and its identity; only what the collector needs is
434
+ * kept, and the grants are derived the same way `permission.sessionRules`
435
+ * derives a descriptor's (`operationRule`: a dotted operation as `<ns>.read` on
436
+ * `<account>:<operation>`, a bare one as `<ns>_<operation>`).
437
+ */
438
+ function memoryEntries(plugin) {
439
+ return (plugin.manifest?.sources ?? []).map((source) =>
440
+ Object.freeze({
441
+ source: source.id,
442
+ pluginId: plugin.id,
443
+ package: plugin.package,
444
+ version: plugin.version ?? null,
445
+ rpc: `${plugin.id}.tools`,
446
+ namespace: String(source.id).split(".")[0],
447
+ tool: "events_list",
448
+ kind: "events",
449
+ reads: Array.isArray(source.kinds) ? source.kinds[0] : null,
450
+ input: Object.freeze({ ...(source.input ?? {}) }),
451
+ pageSource: pageSourceOf({ id: source.id, input: source.input }),
452
+ namesAccount: source.accounts === "multi",
453
+ ownerProbe: "limit0",
454
+ everyMinutes: Math.max(DEFAULT_EVERY_MINUTES, Number(source.cadence?.everyMinutes) || 0),
455
+ minVersion: null,
456
+ setupOptions: null,
457
+ contract: "memory",
458
+ contractLabel: "memory (previous)",
459
+ manifest: source,
460
+ permission: Object.freeze({ events: null, tool: null, operations: Object.freeze([]), actions: Object.freeze([]), readAction: null, reads: Object.freeze([]), accountServer: null }),
461
+ // A schema-v2 source declares `grants` as a list of `{action, resource}`:
462
+ // its `events_list` action and each inner read it asserts.
463
+ grants: Object.freeze((Array.isArray(source.grants) ? source.grants : []).map((grant) => Object.freeze({ action: String(grant.action), resource: String(grant.resource ?? "*") }))),
464
+ private: source.private === true,
465
+ cost: Object.freeze({ ...(source.billing ?? { class: "free" }) }),
466
+ scopeKeys: Object.freeze((source.scope ?? []).map((entry) => entry.key ?? entry)),
467
+ scopeDescribe: null,
468
+ suggest: null,
469
+ details: Object.freeze([]),
470
+ urlHosts: Object.freeze([...(source.urlHosts ?? [])]),
471
+ maxBytes: Number(source.maxBytes) || 65536,
472
+ retentionDays: null,
473
+ cadenceMinMinutes: null,
474
+ }),
475
+ )
476
+ }
185
477
 
186
478
  /**
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.
479
+ * The allow rules a source's read needs in one binding's session.
480
+ *
481
+ * - **declared:** `permission.sessionRules` from the descriptor, which is the
482
+ * contract's own derivation (deny all, the method's action, each operation);
483
+ * - **memory:** the grants it declares, with `{account}` bound;
484
+ * - **events_list (previous):** its events action, its inner actions and its
485
+ * exact read operations, as the plugin asserts them.
486
+ *
487
+ * An account that is not an account name is refused: it would widen the rules.
192
488
  *
193
489
  * @param {string | null} [account] the binding's account; null for the default binding, "default"
194
490
  * @returns {{ action: string, resource: string, effect: "allow" }[]}
195
491
  */
196
492
  export function sourceAllowRules(entry, account = null) {
197
- const permission = entry.permission
198
493
  if (account !== null && account !== undefined && (typeof account !== "string" || !ACCOUNT_NAME.test(account))) {
199
494
  throw new TypeError(`sourceAllowRules: "${String(account).slice(0, 60)}" is not an account name`)
200
495
  }
201
- const bound = account ?? DEFAULT_ACCOUNT
202
- const named = bound !== DEFAULT_ACCOUNT ? bound : null
496
+ const bound = account ?? "default"
497
+ if (entry.contract === "sources") {
498
+ const derived = sessionRules(entry.item, { source: entry.item.id, account: bound })
499
+ if (!derived.ok) throw new TypeError(`sourceAllowRules: ${entry.source}: ${derived.problems?.join("; ") ?? "the descriptor cannot be fenced"}`)
500
+ const rules = derived.value.filter((rule) => rule.effect === "allow")
501
+ // The bootstrap probe runs in this same session (D11), so its action and identity operations are allowed
502
+ // too: the plugin's declared `sources.probe.action`, or the source's own when it declares none, and the
503
+ // source's identity operations (Memory's own sources declare the bare `probe`).
504
+ const identity = Array.isArray(entry.item.permission?.identity) && entry.item.permission.identity.length > 0 ? entry.item.permission.identity : ["probe"]
505
+ const probing = probeRules(entry.item, bound, identity, entry.descriptor?.probe?.action)
506
+ if (probing.ok) {
507
+ for (const rule of probing.value) {
508
+ if (rule.effect === "allow" && !rules.some((known) => known.action === rule.action && known.resource === rule.resource)) rules.push({ ...rule })
509
+ }
510
+ }
511
+ return rules
512
+ }
513
+ if (entry.contract === "memory") return entry.grants.map((grant) => ({ action: grant.action, resource: String(grant.resource ?? "*").replaceAll("{account}", bound), effect: "allow" }))
514
+ const permission = entry.permission
515
+ const named = bound !== "default" ? bound : null
203
516
  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>".
517
+ // A declared API read is one read, whole: a pattern (GET *) would grant every path, so it is refused here
518
+ // rather than silently widening a collector's session.
519
+ for (const resource of permission.apiReads?.resources ?? []) {
520
+ if (typeof resource !== "string" || /[?*]/.test(resource)) throw new TypeError(`sourceAllowRules: apiReads resource "${String(resource).slice(0, 60)}" is not an exact resource`)
521
+ }
205
522
  const server = named && permission.accountServer ? permission.accountServer.replace("{account}", named) : null
206
523
  const inner = (action) => (server && action.startsWith(`${entry.namespace}_`) ? `${server}${action.slice(entry.namespace.length)}` : action)
207
524
  return [
208
525
  allow(permission.events),
209
526
  ...permission.actions.map((action) => allow(inner(action))),
527
+ ...(permission.apiReads?.resources ?? []).map((resource) => allow(permission.apiReads.action, resource)),
210
528
  ...permission.reads.map((operation) => allow(permission.readAction, `${bound}:${operation}`)),
211
529
  ]
212
530
  }
213
531
 
214
- /** The source contract version a plugin's `events_list` must keep. */
532
+ /** The source contract version a previous-contract plugin's `events_list` must keep. */
215
533
  export const SOURCE_CONTRACT = "the memory source contract v1 (events_list answers source and account)"
216
534
 
217
535
  /**
218
- * The one sentence for a plugin whose `events_list` answered without `source`
219
- * and `account` (§4.5): it names the package and the release it needs.
536
+ * The one sentence for a previous-contract plugin whose `events_list` answered
537
+ * without `source` and `account`: it names the package and the release it needs.
220
538
  */
221
539
  export function contractRefusal(entry) {
222
540
  const release = entry.minVersion ? `${entry.package} ${entry.minVersion} or newer` : `a release of ${entry.package} that keeps ${SOURCE_CONTRACT}`
223
541
  return `${entry.package}'s events_list answered without source and account, so Memory refused it: update to ${release}.`
224
542
  }
225
543
 
226
- /** The RPC definition `ctx.rpc` takes for a source's `events_list`. */
544
+ /** The RPC definition `ctx.rpc` takes for a source's read. */
227
545
  export function rpcDefinition(entry) {
228
546
  return { id: entry.rpc, events: {}, methods: { [entry.tool]: { input: { type: "object" }, output: { type: "object" } } } }
229
547
  }
548
+