@joe-broadhead/opencode-mem 0.9.14 → 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.
- package/CHANGELOG.md +1805 -0
- package/README.md +14 -7
- package/SECURITY.md +3 -1
- package/docs/agent-instructions.md +1 -1
- package/docs/agent-protocol.md +7 -7
- package/docs/permissions.md +16 -0
- package/package.json +7688 -339
- package/shared/page-paths.js +44 -0
- package/skills/mem.pages/SKILL.md +3 -1
- package/skills/mem.usage/SKILL.md +15 -15
- package/src/action-grant-keys.js +159 -0
- package/src/action-grant.js +439 -0
- package/src/actions.js +1690 -0
- package/src/backend/records.js +25 -2
- package/src/backend/v3.js +76 -22
- package/src/call-shapes.js +17 -16
- package/src/collector-lock.js +533 -62
- package/src/collector-service.js +153 -26
- package/src/collector.js +623 -30
- package/src/config.js +79 -6
- package/src/connect.js +106 -8
- package/src/credentials.js +123 -25
- package/src/events.js +174 -3
- package/src/forget-turn.js +141 -0
- package/src/host-refusal.js +78 -0
- package/src/index.js +209 -22
- package/src/jobs/host.js +557 -0
- package/src/ops/codes.js +110 -0
- package/src/ops/copy-lineage.js +42 -0
- package/src/ops/index.js +28 -0
- package/src/ops/space-ops.js +1936 -0
- package/src/outlinks.js +103 -0
- package/src/p2-reservation.js +151 -0
- package/src/permissions.js +30 -0
- package/src/plugins/descriptor.js +62 -0
- package/src/plugins/discovery.js +318 -0
- package/src/plugins/grants.js +178 -0
- package/src/plugins/locate.js +319 -0
- package/src/plugins/manifest.js +1162 -0
- package/src/plugins/source-contract/index.js +34 -0
- package/src/plugins/source-contract/policy.js +102 -0
- package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
- package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
- package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
- package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
- package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
- package/src/plugins/source-contract/vendor/broker-client.js +93 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/plugins/source-contract/vendor/cursor.js +26 -0
- package/src/plugins/source-contract/vendor/descriptor.js +34 -0
- package/src/plugins/source-contract/vendor/events.js +257 -0
- package/src/plugins/source-contract/vendor/index.js +10 -0
- package/src/plugins/source-contract/vendor/params.js +22 -0
- package/src/plugins/source-contract/vendor/permission.js +28 -0
- package/src/plugins/source-contract/vendor/pick.js +22 -0
- package/src/plugins/source-contract/vendor/read.js +29 -0
- package/src/plugins/source-contract/vendor/registry.js +23 -0
- package/src/plugins/source-contract/vendor/schema.js +17 -0
- package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
- package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
- package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
- package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
- package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
- package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
- package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
- package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
- package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
- package/src/plugins/source-contract/vendor/schemas.js +19 -0
- package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
- package/src/plugins/verify.js +56 -0
- package/src/protocol.js +11 -6
- package/src/recall.js +92 -5
- package/src/records.js +61 -2
- package/src/requests.js +216 -0
- package/src/runtime.js +89 -7
- package/src/setup-time.js +68 -0
- package/src/skills.js +230 -8
- package/src/source-ids.js +25 -0
- package/src/sources/declaration.js +365 -0
- package/src/sources/reads.js +772 -0
- package/src/sources/rpc.js +151 -0
- package/src/sources.js +389 -92
- package/src/spaces.js +283 -11
- package/src/spool.js +61 -4
- package/src/stated.js +10 -5
- package/src/storable.js +139 -0
- package/src/tools/commitments.js +37 -4
- package/src/tools/held-write.js +31 -12
- package/src/tools/index.js +27 -0
- package/src/tools/ingest.js +27 -2
- package/src/tools/memory.js +30 -7
- package/src/tools/page.js +95 -9
- package/src/tools/recall.js +208 -4
- package/src/tools/share.js +42 -3
- package/src/tools/shared.js +44 -4
- package/src/tools/space-lifecycle.js +278 -0
- package/src/tools/spaces.js +373 -29
- package/src/tools/status.js +9 -2
- package/src/tools/wiki.js +34 -4
- package/src/util.js +110 -6
- package/src/vendor/source-contract/README.md +24 -0
- package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
- package/src/vendor/source-contract/VENDOR.json +81 -0
- package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/vendor/source-contract/cursor.js +26 -0
- package/src/vendor/source-contract/events.js +257 -0
- package/src/vendor/source-contract/registry.js +23 -0
- package/src/vendor/source-contract/tools-rpc.js +42 -0
- package/src/views/access-reads.js +256 -0
- package/src/views/communities.js +77 -0
- package/src/views/contracts.js +930 -21
- package/src/views/inbox-bytes.js +103 -0
- package/src/views/profile.js +31 -0
- package/src/views/records-reads.js +355 -38
- package/src/views/rpc.js +118 -8
- package/src/views/shape.js +8 -5
- package/views/pages.html +2 -2
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Discovery of plugin-declared Memory (DESIGN-PLUGIN-MEMORY §2.3), read-only:
|
|
3
|
+
*
|
|
4
|
+
* 1. **List** `ctx.plugin.list()`: active `package` and `local` plugins, not
|
|
5
|
+
* `builtin`, `sdk` or Memory itself.
|
|
6
|
+
* 2. **Find** each one's installed package (src/plugins/locate.js).
|
|
7
|
+
* 3. **Read** `name`, `version` and `memory` from that `package.json`. No
|
|
8
|
+
* `memory` key: not a Memory plugin, and nothing is said about it.
|
|
9
|
+
* 4. **Validate** the declaration (src/plugins/manifest.js) and digest it.
|
|
10
|
+
* 5. **The optional RPC** `<plugin id>.memory/manifest`: no answer is fine;
|
|
11
|
+
* an answer that differs from the file (canonical JSON) refuses the plugin.
|
|
12
|
+
* It proves nothing about who answers.
|
|
13
|
+
* 6. **Conflicts:** a namespace claimed by two installed packages refuses
|
|
14
|
+
* both; an active plugin whose id a `failed: Duplicate plugin ID` entry
|
|
15
|
+
* shares is marked conflict.
|
|
16
|
+
* 7. **Report** to the records service (`plugins.report`, personal space),
|
|
17
|
+
* which validates again. The report is full (`full: true`): a plugin it no
|
|
18
|
+
* longer names is marked missing there.
|
|
19
|
+
*
|
|
20
|
+
* Fail closed: a plugin whose package can't be found is `unverified`; when no
|
|
21
|
+
* package plugin can be found at all, the cause is the store's layout, and
|
|
22
|
+
* the report says `LAYOUT_CHANGED`.
|
|
23
|
+
*
|
|
24
|
+
* This slice changes nothing about collection: the collector and the source
|
|
25
|
+
* registry are as they were. Plugin text is data: it goes to the records
|
|
26
|
+
* service only, never into a prompt, a tool description, a skill, a command
|
|
27
|
+
* or the protocol.
|
|
28
|
+
*/
|
|
29
|
+
import { LAYOUT_CHANGED, cacheRoot, locate } from "./locate.js"
|
|
30
|
+
import { canonicalJSON, validateManifest } from "./manifest.js"
|
|
31
|
+
import { CONTRACT_LABELS, readDeclared } from "./descriptor.js"
|
|
32
|
+
import { setDeclaredSources, setInstalledVersions, sourceEntriesOf } from "../sources.js"
|
|
33
|
+
import { errorMessage, oneLine } from "../util.js"
|
|
34
|
+
import { recordsOf } from "../tools/share.js"
|
|
35
|
+
|
|
36
|
+
export const DIFFERS_FROM_RPC = "the running plugin's declaration differs from its installed package"
|
|
37
|
+
export const DUPLICATE_ID = "another installed package claims the same plugin id"
|
|
38
|
+
export const NAMESPACE_CLAIMED = (namespace) => `another installed package claims the namespace ${namespace}`
|
|
39
|
+
export const RPC_TIMEOUT_MS = 2_000
|
|
40
|
+
/** `plugin.updated` fires twice per install, with no payload: one scan after this quiet period. */
|
|
41
|
+
export const DEBOUNCE_MS = 3_000
|
|
42
|
+
export const STARTUP_MS = 15_000
|
|
43
|
+
export const SCAN_EVERY_MS = 30 * 60_000
|
|
44
|
+
/** The plugin ids Memory never reads a declaration from: its own. */
|
|
45
|
+
const SELF = new Set(["mem"])
|
|
46
|
+
|
|
47
|
+
const REAL_CLOCK = Object.freeze({
|
|
48
|
+
now: () => Date.now(),
|
|
49
|
+
setTimeout: (fn, ms) => {
|
|
50
|
+
const handle = setTimeout(fn, ms)
|
|
51
|
+
handle?.unref?.()
|
|
52
|
+
return handle
|
|
53
|
+
},
|
|
54
|
+
clearTimeout: (handle) => clearTimeout(handle),
|
|
55
|
+
setInterval: (fn, ms) => {
|
|
56
|
+
const handle = setInterval(fn, ms)
|
|
57
|
+
handle?.unref?.()
|
|
58
|
+
return handle
|
|
59
|
+
},
|
|
60
|
+
clearInterval: (handle) => clearInterval(handle),
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
function sourceOf(info) {
|
|
64
|
+
const source = info?.source ?? {}
|
|
65
|
+
return source.type === "local" ? { kind: "local", path: String(source.path ?? "") } : { kind: "package", target: String(source.target ?? "") }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** An answer within `ms`, else undefined: the RPC is optional, and silence is "none". */
|
|
69
|
+
async function within(promise, ms, clock) {
|
|
70
|
+
let timer
|
|
71
|
+
try {
|
|
72
|
+
return await Promise.race([
|
|
73
|
+
promise,
|
|
74
|
+
new Promise((resolve) => {
|
|
75
|
+
timer = clock.setTimeout(() => resolve(undefined), ms)
|
|
76
|
+
}),
|
|
77
|
+
])
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined
|
|
80
|
+
} finally {
|
|
81
|
+
clock.clearTimeout(timer)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The host's reader for the optional `<plugin id>.memory/manifest` RPC; null when the host has no RPC client. */
|
|
86
|
+
export function hostManifestReader(ctx) {
|
|
87
|
+
if (typeof ctx?.rpc !== "function") return null
|
|
88
|
+
return async (id) => {
|
|
89
|
+
const client = ctx.rpc({ id: `${id}.memory`, events: {}, methods: { manifest: { input: { type: "object" }, output: { type: "object" } } } })
|
|
90
|
+
if (typeof client?.manifest !== "function") return undefined
|
|
91
|
+
return client.manifest({})
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* One discovery pass over a plugin list. Never throws for a plugin's sake:
|
|
97
|
+
* each problem is that plugin's state.
|
|
98
|
+
*
|
|
99
|
+
* @param {{ plugins: any[], root: string, readRpc?: ((id: string) => Promise<unknown>) | null, rpcTimeoutMs?: number, clock?: typeof REAL_CLOCK }} input
|
|
100
|
+
* @returns {Promise<{ layout: boolean, plugins: Array<{ id: string, package: string | null, source: { kind: "package", target: string } | { kind: "local", path: string }, version: string | null, digest: string | null, state: "available" | "invalid" | "unverified" | "conflict", reason: string | null, namespace?: string, rpc?: "none" | "same" | "differs", declares?: null | true, manifest?: unknown }> }>}
|
|
101
|
+
*/
|
|
102
|
+
export async function discover({ plugins, root, readRpc = null, rpcTimeoutMs = RPC_TIMEOUT_MS, clock = REAL_CLOCK }) {
|
|
103
|
+
const all = Array.isArray(plugins) ? plugins : []
|
|
104
|
+
const duplicates = new Set(all.filter((info) => info?.state?.status === "failed" && /^Duplicate plugin ID\b/.test(String(info.state.error ?? ""))).map((info) => String(info.id ?? "")))
|
|
105
|
+
const running = all.filter((info) => info?.state?.status === "active" && typeof info.id === "string" && info.id !== "" && !SELF.has(info.id) && (info.source?.type === "package" || info.source?.type === "local"))
|
|
106
|
+
|
|
107
|
+
const out = []
|
|
108
|
+
let packages = 0
|
|
109
|
+
let located = 0
|
|
110
|
+
for (const info of running) {
|
|
111
|
+
const version = info.source.type === "package" ? (typeof info.source.version === "string" ? info.source.version : null) : null
|
|
112
|
+
const found = locate(info, { root })
|
|
113
|
+
if (info.source.type === "package") {
|
|
114
|
+
packages += 1
|
|
115
|
+
if (found.ok || found.cause !== "missing") located += 1
|
|
116
|
+
}
|
|
117
|
+
if (!found.ok) {
|
|
118
|
+
// Unknown whether it declares, except when matching installs differ and one of them does.
|
|
119
|
+
out.push({ id: info.id, package: null, source: sourceOf(info), version, digest: null, state: "unverified", reason: oneLine(found.reason, 300), cause: found.cause, declares: found.cause === "differ" ? true : null })
|
|
120
|
+
continue
|
|
121
|
+
}
|
|
122
|
+
// `sources` wins: a package that declares them is read under the current
|
|
123
|
+
// contract, and its `memory` key (the previous one) is never read.
|
|
124
|
+
if (found.sources === undefined && found.memory === undefined) continue
|
|
125
|
+
const entry = { id: info.id, package: found.packageName, source: sourceOf(info), version: version ?? found.packageVersion, digest: found.digest, state: "available", reason: null }
|
|
126
|
+
if (found.sources !== undefined) {
|
|
127
|
+
const declared = readDeclared(found.dir)
|
|
128
|
+
entry.contract = "sources"
|
|
129
|
+
entry.contractLabel = CONTRACT_LABELS.sources
|
|
130
|
+
if (!declared.ok) {
|
|
131
|
+
out.push({ ...entry, state: "invalid", reason: declared.problems.join("; ").slice(0, 300) })
|
|
132
|
+
continue
|
|
133
|
+
}
|
|
134
|
+
entry.descriptor = declared.descriptor
|
|
135
|
+
entry.descriptorHash = declared.hash
|
|
136
|
+
entry.sourceIds = declared.descriptor.items.map((item) => item.id)
|
|
137
|
+
entry.digest = declared.hash
|
|
138
|
+
if (duplicates.has(info.id)) {
|
|
139
|
+
out.push({ ...entry, state: "conflict", reason: DUPLICATE_ID })
|
|
140
|
+
continue
|
|
141
|
+
}
|
|
142
|
+
out.push(entry)
|
|
143
|
+
continue
|
|
144
|
+
}
|
|
145
|
+
entry.contract = "memory"
|
|
146
|
+
entry.contractLabel = CONTRACT_LABELS.memory
|
|
147
|
+
const checked = validateManifest(found.memory)
|
|
148
|
+
if (!checked.ok) {
|
|
149
|
+
out.push({ ...entry, state: "invalid", reason: checked.reason })
|
|
150
|
+
continue
|
|
151
|
+
}
|
|
152
|
+
entry.namespace = checked.namespace
|
|
153
|
+
entry.rpc = "none"
|
|
154
|
+
if (readRpc) {
|
|
155
|
+
const answer = await within(Promise.resolve().then(() => readRpc(info.id)), rpcTimeoutMs, clock)
|
|
156
|
+
if (answer !== undefined && answer !== null) {
|
|
157
|
+
let same = false
|
|
158
|
+
try {
|
|
159
|
+
same = canonicalJSON(answer) === canonicalJSON(found.memory)
|
|
160
|
+
} catch {
|
|
161
|
+
same = false
|
|
162
|
+
}
|
|
163
|
+
entry.rpc = same ? "same" : "differs"
|
|
164
|
+
if (!same) {
|
|
165
|
+
out.push({ ...entry, state: "invalid", reason: DIFFERS_FROM_RPC })
|
|
166
|
+
continue
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (duplicates.has(info.id)) {
|
|
171
|
+
out.push({ ...entry, state: "conflict", reason: DUPLICATE_ID, manifest: found.memory })
|
|
172
|
+
continue
|
|
173
|
+
}
|
|
174
|
+
out.push({ ...entry, manifest: found.memory })
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// A namespace claimed by two installed packages: both are refused.
|
|
178
|
+
const claims = new Map()
|
|
179
|
+
for (const entry of out) if (entry.namespace && (entry.state === "available" || entry.state === "conflict")) claims.set(entry.namespace, (claims.get(entry.namespace) ?? 0) + 1)
|
|
180
|
+
for (const entry of out) {
|
|
181
|
+
if (entry.namespace && claims.get(entry.namespace) > 1 && entry.state === "available") Object.assign(entry, { state: "conflict", reason: NAMESPACE_CLAIMED(entry.namespace) })
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// A source id two installed packages declare: neither is trusted, or the last
|
|
185
|
+
// one to be listed would silently serve the other's consented binding.
|
|
186
|
+
const sourceClaims = new Map()
|
|
187
|
+
for (const entry of out) {
|
|
188
|
+
if (entry.contract !== "sources" || entry.state !== "available" || !entry.descriptor) continue
|
|
189
|
+
for (const item of entry.descriptor.items ?? []) {
|
|
190
|
+
if (!sourceClaims.has(item.id)) sourceClaims.set(item.id, [])
|
|
191
|
+
sourceClaims.get(item.id).push(entry)
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
for (const [id, holders] of sourceClaims) {
|
|
195
|
+
const packages = [...new Set(holders.map((entry) => entry.package ?? entry.id))]
|
|
196
|
+
if (packages.length < 2) continue
|
|
197
|
+
for (const entry of holders) {
|
|
198
|
+
if (entry.state === "available") {
|
|
199
|
+
Object.assign(entry, {
|
|
200
|
+
state: "invalid",
|
|
201
|
+
reason: `declares the source ${id} that another package also declares (${packages.join(", ")}); neither is trusted until one of them changes its id`.slice(0, 300),
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// No package plugin found at all: the store's layout changed under Memory.
|
|
208
|
+
const layout = packages > 0 && located === 0
|
|
209
|
+
if (layout) for (const entry of out) if (entry.state === "unverified" && entry.source.kind === "package") entry.reason = LAYOUT_CHANGED
|
|
210
|
+
return { layout, plugins: out.map(({ cause: _cause, ...entry }) => entry) }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* The discovery service: a scan at startup, on every tick, and after a
|
|
215
|
+
* debounced `plugin.updated` or `config.updated` (src/events.js passes them
|
|
216
|
+
* on). Each scan reports to the records service. Nothing here throws into the
|
|
217
|
+
* host, and nothing here changes what the collector does.
|
|
218
|
+
*
|
|
219
|
+
* @param {{ ctx: any, runtime: any, toolkit: any, clock?: typeof REAL_CLOCK, root?: () => Promise<string>, readRpc?: ((id: string) => Promise<unknown>) | null, debounceMs?: number, everyMs?: number, startupMs?: number }} input
|
|
220
|
+
*/
|
|
221
|
+
export function createPluginDiscovery({ ctx, runtime, toolkit, clock = REAL_CLOCK, root = () => cacheRoot(), readRpc, debounceMs = DEBOUNCE_MS, everyMs = SCAN_EVERY_MS, startupMs = STARTUP_MS }) {
|
|
222
|
+
const log = runtime?.log
|
|
223
|
+
const reader = readRpc === undefined ? hostManifestReader(ctx) : readRpc
|
|
224
|
+
const timers = { startup: null, interval: null, debounce: null }
|
|
225
|
+
let running = null
|
|
226
|
+
let again = false
|
|
227
|
+
let stopped = false
|
|
228
|
+
let last = null
|
|
229
|
+
|
|
230
|
+
async function unavailable() {
|
|
231
|
+
return (runtime?.availability ? await runtime.availability() : runtime?.unavailable?.()) ?? ""
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function run(trigger) {
|
|
235
|
+
const reason = await unavailable()
|
|
236
|
+
if (reason) return { skipped: reason }
|
|
237
|
+
if (typeof ctx?.plugin?.list !== "function") return { skipped: "this host gives plugins no plugin list" }
|
|
238
|
+
const records = recordsOf(toolkit)
|
|
239
|
+
if (!records) return { skipped: "this plugin build has no records client" }
|
|
240
|
+
try {
|
|
241
|
+
// The person's personal space, as the collector resolves it (src/collector-service.js); a report anywhere else is refused.
|
|
242
|
+
let where = {}
|
|
243
|
+
if (toolkit?.control) {
|
|
244
|
+
const resolved = await toolkit.resolvePrivateSpace({}, {})
|
|
245
|
+
if (resolved.invalid || resolved.error) throw new Error(resolved.invalid || resolved.error)
|
|
246
|
+
where = { space: resolved.context.space_id }
|
|
247
|
+
}
|
|
248
|
+
const result = await discover({ plugins: await ctx.plugin.list(), root: await root(), readRpc: reader, clock })
|
|
249
|
+
// A full report: every plugin this machine has; the records service marks the ones it no longer names as missing.
|
|
250
|
+
await records.call("plugins.report", { layout: result.layout, full: true, plugins: result.plugins }, where)
|
|
251
|
+
// The declarations the collector reads under are published **only after**
|
|
252
|
+
// the report and its re-ask state are stored: a changed descriptor is
|
|
253
|
+
// never read before the person is asked again.
|
|
254
|
+
// The installed version of every plugin this machine has, not only the declaring
|
|
255
|
+
// ones: a previous-contract entry names the release it needs, and the row shows
|
|
256
|
+
// the installed one beside it (G3).
|
|
257
|
+
setInstalledVersions(result.plugins)
|
|
258
|
+
setDeclaredSources(sourceEntriesOf(result.plugins))
|
|
259
|
+
last = { trigger, at: new Date(clock.now()).toISOString(), layout: result.layout, plugins: result.plugins.map(({ id, state }) => ({ id, state })) }
|
|
260
|
+
log?.debug?.("plugin discovery", { trigger, plugins: result.plugins.length, layout: result.layout })
|
|
261
|
+
return { reported: result.plugins.length, layout: result.layout }
|
|
262
|
+
} catch (error) {
|
|
263
|
+
log?.warn?.("plugin discovery failed", { trigger, error: errorMessage(error) })
|
|
264
|
+
return { error: oneLine(errorMessage(error), 300) }
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** One scan now, or after the running one when a scan is under way. */
|
|
269
|
+
async function scan(trigger = "request") {
|
|
270
|
+
if (running) {
|
|
271
|
+
again = true
|
|
272
|
+
return running
|
|
273
|
+
}
|
|
274
|
+
running = run(trigger).finally(() => {
|
|
275
|
+
running = null
|
|
276
|
+
if (again && !stopped) {
|
|
277
|
+
again = false
|
|
278
|
+
void scan("again")
|
|
279
|
+
}
|
|
280
|
+
})
|
|
281
|
+
return running
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function safely(trigger) {
|
|
285
|
+
return scan(trigger).catch((error) => log?.warn?.("plugin discovery failed", { error: errorMessage(error) }))
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** `plugin.updated` (no payload, twice per install) or `config.updated`: re-list everything once things are quiet. */
|
|
289
|
+
function changed(_type) {
|
|
290
|
+
if (stopped) return
|
|
291
|
+
clock.clearTimeout(timers.debounce)
|
|
292
|
+
timers.debounce = clock.setTimeout(() => safely("changed"), debounceMs)
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function start() {
|
|
296
|
+
stopped = false
|
|
297
|
+
timers.startup = clock.setTimeout(() => safely("startup"), startupMs)
|
|
298
|
+
timers.interval = clock.setInterval(() => safely("timer"), everyMs)
|
|
299
|
+
return true
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function stop() {
|
|
303
|
+
stopped = true
|
|
304
|
+
clock.clearTimeout(timers.startup)
|
|
305
|
+
clock.clearTimeout(timers.debounce)
|
|
306
|
+
clock.clearInterval(timers.interval)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
return {
|
|
310
|
+
scan,
|
|
311
|
+
changed,
|
|
312
|
+
start,
|
|
313
|
+
stop,
|
|
314
|
+
get last() {
|
|
315
|
+
return last
|
|
316
|
+
},
|
|
317
|
+
}
|
|
318
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Least privilege for plugin-declared sources (DESIGN-PLUGIN-MEMORY §3.4).
|
|
3
|
+
*
|
|
4
|
+
* ```
|
|
5
|
+
* rules(binding) = deny "*" · allow execute · allow (consented.grants ∩ live.grants), with {account} bound
|
|
6
|
+
* input(binding) = { cursor, limit, account, ...consented.input, scope: consented.scope }
|
|
7
|
+
* accept(answer) = answer.source == binding.source ∧ answer.account == binding.account
|
|
8
|
+
* ∧ answer.owner.id == the confirmed owner ∧ answer.scope ⊆ consented.scope
|
|
9
|
+
* ∧ every event.kind ∈ consented.kinds
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* `consented` is the snapshot the person confirmed (the records service's
|
|
13
|
+
* consent row); `live` is the declaration the collector just re-read from
|
|
14
|
+
* disk (src/plugins/verify.js). Nothing here reads the server's plugins row.
|
|
15
|
+
* OpenCode checks every inner action `events_list` asserts against the
|
|
16
|
+
* binding's session (S0 Q1), so a grant the declaration lists but the person
|
|
17
|
+
* did not confirm is never allowed, and one missing from the declaration is
|
|
18
|
+
* an outage, not a leak.
|
|
19
|
+
*/
|
|
20
|
+
import { canonicalJSON } from "./manifest.js"
|
|
21
|
+
import { errorMessage, isPlainObject, oneLine } from "../util.js"
|
|
22
|
+
|
|
23
|
+
export const BASE_RULES = Object.freeze([
|
|
24
|
+
Object.freeze({ action: "*", resource: "*", effect: "deny" }),
|
|
25
|
+
Object.freeze({ action: "execute", resource: "*", effect: "allow" }),
|
|
26
|
+
])
|
|
27
|
+
/** A binding's account name: no wildcard, separator or space, never empty. */
|
|
28
|
+
export const ACCOUNT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.@+-]{0,127}$/
|
|
29
|
+
export const PAGE_LIMIT = 200
|
|
30
|
+
export const PAGES_PER_RUN = 5
|
|
31
|
+
export const BILLED_PAGES_PER_RUN = 2
|
|
32
|
+
export const MIN_EVERY_MINUTES = 15
|
|
33
|
+
export const BILLED_MIN_EVERY_MINUTES = 120
|
|
34
|
+
const DEFAULT_EVERY_MINUTES = 30
|
|
35
|
+
|
|
36
|
+
const grantKey = (grant) => `${grant.action}\u0000${grant.resource}`
|
|
37
|
+
|
|
38
|
+
function intersect(consented = [], live = []) {
|
|
39
|
+
const keys = new Set(live.map(grantKey))
|
|
40
|
+
return consented.filter((grant) => keys.has(grantKey(grant))).map((grant) => ({ action: grant.action, resource: grant.resource }))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* What a binding may do this run: the consented source declaration narrowed
|
|
45
|
+
* by the one on disk. Grants, probe grants and kinds are intersections; the
|
|
46
|
+
* input and billing are the consent's (a change waits for the person); the
|
|
47
|
+
* cadence is the slower of the two, clamped (at least 15 minutes, 120 when
|
|
48
|
+
* billed), and a billed source reads at most 2 pages a run.
|
|
49
|
+
*/
|
|
50
|
+
export function effectiveSource(consented, live) {
|
|
51
|
+
const billed = Boolean(consented.billing) || Boolean(live.billing)
|
|
52
|
+
const every = Math.max(consented.cadence?.everyMinutes ?? DEFAULT_EVERY_MINUTES, live.cadence?.everyMinutes ?? DEFAULT_EVERY_MINUTES, billed ? BILLED_MIN_EVERY_MINUTES : MIN_EVERY_MINUTES)
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
source: consented.id,
|
|
55
|
+
grants: Object.freeze(intersect(consented.grants, live.grants)),
|
|
56
|
+
probeGrants: Object.freeze(intersect(consented.probe?.grants, live.probe?.grants)),
|
|
57
|
+
kinds: Object.freeze(consented.kinds.filter((kind) => live.kinds.includes(kind))),
|
|
58
|
+
input: Object.freeze({ ...(consented.input ?? {}) }),
|
|
59
|
+
scopeKeys: Object.freeze((consented.scope ?? []).map((entry) => entry.key)),
|
|
60
|
+
everyMinutes: every,
|
|
61
|
+
billed,
|
|
62
|
+
pages: billed ? BILLED_PAGES_PER_RUN : PAGES_PER_RUN,
|
|
63
|
+
})
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The allow rules of a list of grants with `{account}` bound to the binding's account. */
|
|
67
|
+
function bind(grants, account) {
|
|
68
|
+
if (typeof account !== "string" || !ACCOUNT_NAME.test(account)) throw new TypeError(`"${String(account).slice(0, 60)}" is not an account name`)
|
|
69
|
+
return grants.map((grant) => ({ action: grant.action, resource: grant.resource.replaceAll("{account}", account), effect: "allow" }))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A binding's collection session: deny everything, allow Code Mode and exactly its effective grants. */
|
|
73
|
+
export function sessionRules(effective, account) {
|
|
74
|
+
return Object.freeze([...BASE_RULES, ...bind(effective.grants, account)].map((rule) => Object.freeze({ ...rule })))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* A **job's** session (DESIGN-MEMORY-JOBS §5.3): deny everything, then exactly
|
|
79
|
+
* the job's grants. Unlike a collection session it does **not** allow
|
|
80
|
+
* `execute`: a job calls the tools RPC directly, and S0 showed the RPC needs no
|
|
81
|
+
* Code Mode to make the call. The inner reads `events_list` asserts are in the
|
|
82
|
+
* grants, so OpenCode's own check on them is least privilege, not an outage.
|
|
83
|
+
*/
|
|
84
|
+
export function jobSessionRules(grants, account) {
|
|
85
|
+
return Object.freeze([BASE_RULES[0], ...bind(grants, account)].map((rule) => Object.freeze({ ...rule })))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The owner-only call's session: the effective grants and probe grants. Only `limit: 0` runs in it. */
|
|
89
|
+
export function probeRules(effective, account) {
|
|
90
|
+
const seen = new Set()
|
|
91
|
+
const grants = [...effective.grants, ...effective.probeGrants].filter((grant) => !seen.has(grantKey(grant)) && seen.add(grantKey(grant)))
|
|
92
|
+
return Object.freeze([...BASE_RULES, ...bind(grants, account)].map((rule) => Object.freeze({ ...rule })))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The owner-only call (contract 2): `limit: 0`, always naming the account. */
|
|
96
|
+
export function probeInput(effective, { account }) {
|
|
97
|
+
return { limit: 0, account, ...effective.input }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** One page: the cursor, the limit, the account (always named, "default" too) and the confirmed scope. */
|
|
101
|
+
export function listInput(effective, { account, cursor, scope }) {
|
|
102
|
+
return { ...(cursor ? { cursor } : {}), limit: PAGE_LIMIT, account, ...effective.input, scope: { ...(scope ?? {}) } }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export class AnswerRefused extends Error {
|
|
106
|
+
constructor(message, { accountChanged = false } = {}) {
|
|
107
|
+
super(message)
|
|
108
|
+
this.name = "AnswerRefused"
|
|
109
|
+
this.code = accountChanged ? "account_changed" : "answer_refused"
|
|
110
|
+
this.accountChanged = accountChanged
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** An answer as an RPC result's output, as JSON text, or bare. */
|
|
115
|
+
function unwrap(value) {
|
|
116
|
+
let answer = value
|
|
117
|
+
if (isPlainObject(answer) && !Array.isArray(answer.events) && isPlainObject(answer.output)) answer = answer.output
|
|
118
|
+
if (isPlainObject(answer) && !Array.isArray(answer.events) && typeof (answer.content ?? answer.text) === "string") answer = answer.content ?? answer.text
|
|
119
|
+
if (typeof answer === "string") {
|
|
120
|
+
try {
|
|
121
|
+
answer = JSON.parse(answer)
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw new AnswerRefused(`the answer is not JSON (${oneLine(errorMessage(error), 80)})`)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return answer
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function scopeWithin(echo, confirmed, keys) {
|
|
130
|
+
// A job with no confirmed scope key confirmed the whole source (contract 2's
|
|
131
|
+
// `{}`), so whatever the source echoes it read is inside it: the source's own
|
|
132
|
+
// option is what bounds the read, not the echo. A job that names a key is
|
|
133
|
+
// still held to it, id by id.
|
|
134
|
+
if (keys.length === 0) return true
|
|
135
|
+
if (!isPlainObject(echo)) return false
|
|
136
|
+
return Object.entries(echo).every(([key, ids]) => Array.isArray(confirmed?.[key]) && Array.isArray(ids) && ids.every((id) => confirmed[key].includes(id)))
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Check an `events_list` answer against the binding. Throws AnswerRefused
|
|
141
|
+
* (with `accountChanged` when the owner or the account differs from the
|
|
142
|
+
* confirmed one); returns the page otherwise. For the owner-only call
|
|
143
|
+
* (`probe: true`) the scope is not checked and every event is dropped.
|
|
144
|
+
*
|
|
145
|
+
* @param {unknown} value
|
|
146
|
+
* @param {{ source: string, account: string, owner: { id: string } | null, scope: object, kinds: readonly string[], probe?: boolean }} binding
|
|
147
|
+
*/
|
|
148
|
+
export function acceptAnswer(value, binding) {
|
|
149
|
+
const answer = unwrap(value)
|
|
150
|
+
if (!isPlainObject(answer)) throw new AnswerRefused("the answer is not an object")
|
|
151
|
+
if (!Array.isArray(answer.events)) throw new AnswerRefused("the answer has no events list")
|
|
152
|
+
if (answer.source !== binding.source) throw new AnswerRefused(`the answer is for source "${oneLine(String(answer.source ?? ""), 40)}", not ${binding.source}`)
|
|
153
|
+
if (answer.account !== binding.account) throw new AnswerRefused(`account changed: the plugin answered for account "${oneLine(String(answer.account ?? ""), 60)}", not ${binding.account}`, { accountChanged: true })
|
|
154
|
+
const owner = isPlainObject(answer.owner) && typeof answer.owner.id === "string" && answer.owner.id ? { id: oneLine(answer.owner.id, 300), label: oneLine(answer.owner.label ?? answer.owner.id, 300) } : null
|
|
155
|
+
if (binding.owner && owner?.id !== binding.owner.id) throw new AnswerRefused(`account changed: the plugin now reports ${owner ? oneLine(owner.label, 80) : "no account"}, not the confirmed ${oneLine(binding.owner.label ?? binding.owner.id, 80)}`, { accountChanged: true })
|
|
156
|
+
const keys = Object.keys(binding.scope ?? {})
|
|
157
|
+
if (!binding.probe && !scopeWithin(answer.scope, binding.scope, keys)) throw new AnswerRefused("the answer names a scope outside the one the person confirmed")
|
|
158
|
+
if (!binding.probe) {
|
|
159
|
+
const kind = answer.events.find((event) => !isPlainObject(event) || !binding.kinds.includes(event.kind))
|
|
160
|
+
if (kind !== undefined) throw new AnswerRefused(`the answer holds an event of a kind the person did not confirm (${oneLine(String(kind?.kind ?? "?"), 20)})`)
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
source: answer.source,
|
|
164
|
+
account: answer.account,
|
|
165
|
+
owner,
|
|
166
|
+
events: binding.probe ? [] : answer.events,
|
|
167
|
+
cursor: typeof answer.cursor === "string" ? answer.cursor : "",
|
|
168
|
+
more: answer.more === true,
|
|
169
|
+
scope: binding.probe ? null : answer.scope ?? null,
|
|
170
|
+
scopeOptions: binding.probe && isPlainObject(answer.scopeOptions) ? answer.scopeOptions : null,
|
|
171
|
+
setup: typeof answer.setup === "string" && answer.setup.trim() ? oneLine(answer.setup, 400) : null,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A short hash of rules for the session's metadata (unchanged rules, unchanged session). */
|
|
176
|
+
export function rulesKey(rules) {
|
|
177
|
+
return canonicalJSON(rules.map(({ action, resource, effect }) => [action, resource, effect]))
|
|
178
|
+
}
|